harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0280harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0280Task: Harder Falcon-like micro-framework
Overview
You must implement a more demanding, Falcon-inspired HTTP micro-framework as a Python package placed under /app/falcon/. The package must be robust, thread-safe, and capable of handling larger inputs and edge cases while still satisfying a comprehensive test suite that exercises routing, request/response plumbing, streaming, and a small testing helper.
What to implement (at minimum)
- Package layout
- /app/falcon/__init__.py
- /app/falcon/request_helpers.py
- /app/falcon/testing.py
- Public API and behavior (harder, more robust)
1) falcon.API class (in __init__.py)
- Purpose: A tiny, Falcon-like WSGI application with thread-safe routing to resource objects.
- API surface:
- __init__(self): initialize internal route map and a small, thread-safe guard for mutations.
- add_route(self, path, obj): register a resource object for the given path. Must be safe for concurrent calls.
- __call__(self, environ, start_response): WSGI entry point. Dispatches to registered resource methods with proper request/response plumbing.
- Routing and dispatch rules (must satisfy tests and be resilient to edge cases):
- Routes:
- '/': handled by a resource with on_get, on_post, on_put (and also support on_head? Tests rely on 405 for HEAD, so HEAD must be considered not implemented by default).
- '/bucket': handled by a resource with on_post.
- Request/Response plumbing:
- Build a request object and a response object and pass them to resource methods.
- Support on_get, on_post, on_put method dispatch based on REQUEST_METHOD (upper-cased).
- If a method is not implemented for a resource (e.g., HEAD for '/'), respond with 405 Method Not Allowed, with an appropriate Allow header listing supported methods for that path.
- If the path is not registered, respond with 404 Not Found.
- Request/Response objects:
- The resource method signature: on_<method>(self, req, resp).
- The resp object must be mutable by the resource (e.g., resp.body, resp.status, resp.headers).
- After the resource method returns, translate resp.body into a bytes object for the WSGI response:
- If resp.body is a str, encode as UTF-8.
- If resp.body is already bytes, use it directly.
- If resp.body is None, treat as empty body (b'').
- Default status should be '200 OK' unless resp.status is explicitly set.
- Request object semantics (must be passed to resource methods):
- req.remote_addr from environ['REMOTE_ADDR'] (tests rely on '127.0.0.1' or similar).
- req.content_length parsed as int from environ.get('CONTENT_LENGTH'), with robust handling:
- If missing or invalid, treat as 0.
- req.stream must be an instance of BoundedStream wrapping environ['wsgi.input'] with a maximum number of bytes equal to content_length (or 0 if no body).
- req.bounded_stream must refer to the exact same BoundedStream instance as req.stream.
- Expose helper methods on req as needed (e.g., req.get_header(name, default=None)) to facilitate tests focusing on headers.
- Response object semantics:
- resp.status defaults to '200 OK' if not set.
- resp.body can be str or bytes (and must be converted to bytes for WSGI output as described above).
- resp.headers is a mapping-like object; provide a simple set_header(name, value) helper.
- For compatibility with tests, you may keep headers minimal, but ensure content-length is emitted when possible.
- Error handling and edge cases:
- Invalid or missing Content-Length should result in an empty body for that request (as tests expect).
- If a path has no registered resource, 404 Not Found.
- If the resource lacks a handler for the given method, 405 Method Not Allowed. Include an Allow header with the supported methods for that resource (best effort, e.g., "GET,POST,PUT" as applicable).
- Performance and correctness constraints:
- The API must be thread-safe for concurrent requests. The route map may be mutated at runtime before requests begin; any runtime dispatch must not require global locks for read-only dispatch.
- Do not read the entire request body into memory unless necessary; utilize BoundedStream to enforce max reads and to support large payloads efficiently.
- Use minimal CPU overhead per request; avoid unnecessary copies and allocations in hot paths.
- WSGI compliance:
- Must be able to run under Python’s wsgiref.simple_server or similar, serving multiple simultaneous requests.
- Properly set content-length when possible (derive from len(resp.body) or compute from bytes).
2) falcon.request_helpers.BoundedStream (in request_helpers.py)
- Purpose: A safe, minimal wrapper around the WSGI input stream enforcing a maximum number of bytes that can be read.
- Class:
- class BoundedStream:
- __init__(self, stream, max_bytes):
- stream: the underlying binary input stream (e.g., environ['wsgi.input'], expected to be a binary file-like object).
- max_bytes: maximum number of bytes that may be read from the stream, as an int.
- read(self, size=-1) -> bytes:
- Reads up to size bytes from the underlying stream, but never beyond the remaining max_bytes.
- If size is -1 or None, read all remaining bytes (up to max_bytes).
- Maintain and update the remaining byte count after each read.
- If no bytes remain, return b''.
- The class must be light-weight and thread-safe for single-request usage; ensure no accidental data races on per-request streams.
- Test expectations (core):
- req.stream is an instance of BoundedStream.
- req.bounded_stream is the same object as req.stream.
- Reading from req.stream yields posted body data (or portions) according to size and content_length semantics.
- In bucket-related tests, the stream must be used via the bounded_stream wrapper to echo payload.
3) falcon.testing (in testing.py)
- Provide a small, deterministic testing helper:
- rand_string(min_len, max_len) -> str
- Parameters: min_len and max_len (ints or values coercible to int).
- Returns a random ASCII string of length between min_len and max_len inclusive.
- Character set: a-zA-Z0-9.
- This module will be imported in tests as falcon.testing; ensure the rand_string function is exposed at falcon.testing.rand_string.
- Wiring and behavior expectations (driven by tests)
- Resource classes used by tests:
- On path '/':
- class Things:
- on_get(self, req, resp): resp.body = req.remote_addr
- on_post(self, req, resp): resp.body = req.stream.read() # read all (bounded)
- on_put(self, req, resp): read from req.stream in a way that exercises reading beyond end without hanging, e.g., req_body = (req.stream.read(1) for _ in range(req.content_length + 1)); resp.body = b''.join(req_body)
- On path '/bucket':
- class Bucket:
- on_post(self, req, resp):
- Verify req.stream is an instance of BoundedStream and req.stream is req.bounded_stream.
- resp.body = req.bounded_stream.read() # read all
- The Request object semantics (passed to handlers):
- req.remote_addr equals environ['REMOTE_ADDR'].
- req.content_length is parsed as int from environ['CONTENT_LENGTH']; if invalid or missing, 0.
- req.stream is a BoundedStream wrapping environ['wsgi.input'] with max_bytes equal to req.content_length (or 0).
- req.bounded_stream is the same object as req.stream.
- Response behavior:
- Resource methods set resp.body (str or bytes) and may set resp.status.
- The framework converts resp.body to bytes for the WSGI response; strings encoded as UTF-8.
- Content-length and headers:
- The server should attempt to set Content-Length when possible. If not known, it may fall back to a chunked-like approach, but tests will assume a straightforward bytes send with a known length when possible.
- Error behavior:
- 404 for unknown route; 405 for unsupported method; 411 or improper content length handling is not required unless tests demand it, but you should gracefully handle invalid Content-Length by treating it as 0.
- How to structure and run
- Implement the package under /app/ so that imports such as:
- import falcon
- from falcon.request_helpers import BoundedStream
- import falcon.testing
work as expected.
- The code should be self-contained, with no external dependencies beyond the Python Standard Library.
- You will be provided with tests that instantiate falcon.API(), register routes with add_route, and exercise WSGI behavior using a small server or test harness. Ensure your implementation is compatible with those tests and that edge cases (empty input, huge input, unicode, etc.) are handled gracefully.
- Acceptance criteria
- All tests pass, including:
- GET on '/': response body equals the remote address (e.g., '127.0.0.1').
- PUT on '/': request body is echoed back via resp.body.
- HEAD on '/': 405 Method Not Allowed.
- POST on '/': posted payload is echoed back.
- POST with invalid Content-Length yields 200 with empty body (per the provided tests' expectations).
- POST on '/bucket' reads the payload via BoundStream and returns that payload.
- POST on '/bucket' with no body yields an empty response.
- BoundedStream is used and req.stream is req.bounded_stream in the bucket handler.
- The falcon package exposes:
- falcon.API class with routing, request/response objects, and WSGI entry points.
- falcon.request_helpers.BoundedStream with the exact behavior described.
- falcon.testing.rand_string as falcon.testing.rand_string(min_len, max_len).
Notes and constraints
- Coding language: Python (no external dependencies beyond the Standard Library).
- The solution should run as a package placed at /app/.
- Strive for clean, readable code with minimal but robust error handling and clear separation of concerns between request, response, routing, and I/O.
- Document any non-obvious behavior with inline comments in code to aid future contributors and reviewers.