harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0205harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0205Harder task: robust, concurrency-safe uvicorn stub with edge-case handling
Goal
Create a minimal, dependency-free Python module at /app/uvicorn.py that provides a safe, non-blocking, and test-friendly stub of uvicorn. The implementation should be designed for robustness under concurrent test scenarios, handle diverse inputs, and illustrate a lightweight, multi-file-analog organization within a single file.
Public API (stable interface)
- def run(app, host: str = "127.0.0.1", port: int | str = 8000, log_level: str = "info", reload: bool = False, workers: int = 1) -> "ServerStub"
- Behavior and constraints:
- Input validation (light but strict enough for tests):
- host must be a non-empty string (strip whitespace; reject None/empty after trim).
- port must be an integer in 1..65535. If port is a string that looks like a number, coerce to int; otherwise raise ValueError.
- log_level should be one of a small white-listed set (case-insensitive), e.g., {"debug","info","warning","error","critical"}.
- workers must be an int >= 1.
- reload must be a boolean (coerce from truthy/falsy values if necessary); warn if reload is True and workers > 1 (non-blocking, non-fatal).
- app can be any object; do not try to introspect it (no reliance on FastAPI internals).
- No real network server started. Create and return a lightweight ServerStub instance after a tiny, deterministic startup sequence.
- The function must return promptly (non-blocking). Do not perform real I/O or block on synchronization primitives for extended time.
- Optional: print a tiny startup message to stdout for visibility, but avoid side effects that would break tests; make prints easily disableable via an environment flag if desired.
- Return value:
- A ServerStub instance containing metadata about the “started” session, with attributes:
- app, host, port, log_level, reload, workers
- started: bool (should be True immediately after run returns)
- id: a small, deterministic session identifier (e.g., integer counter)
- created_at: timestamp (optional; for debugging)
- The ServerStub must expose:
- def start(self) -> None: marks the session as started (thread-safe)
- def stop(self) -> None: marks the session as stopped
- def status(self) -> dict: returns a snapshot (including started)
- def __repr__/__str__ for readable debugging
ServerStub class (internal type, exposed via run return)
- class ServerStub:
- __init__(self, app, host: str, port: int, log_level: str, reload: bool, workers: int)
- Initialize with provided metadata; do not start blocking I/O here.
- Use a small thread-safe mechanism to guard state changes (threading.Lock).
- start(self) -> None
- Thread-safely set started = True; record a timestamp if desired.
- stop(self) -> None
- Thread-safely set started = False.
- status(self) -> dict
- Return a shallow, serializable snapshot, e.g., {"id": ..., "host": ..., "port": ..., "started": bool, "workers": int, "reload": bool}
- Properties/attributes to support tests:
- host, port, app, started, id
Design, architecture, and constraints
- No external dependencies; import-safe module.
- Non-blocking and fast: run must not await or perform real I/O; aim for O(1) time and O(1) additional memory per call (aside from the returned object and a tiny internal registry).
- Thread-safety:
- If run is called concurrently from multiple threads, each ServerStub should be independently started, with a small global registry to assign unique IDs and track active sessions.
- Use a threading.Lock to guard the global registry and ID counter.
- Edge-case handling and input fuzzing:
- Empty or whitespace-only host strings should raise ValueError.
- port provided as non-integer non-coercible value should raise ValueError.
- Large port values beyond 65535 raise ValueError.
- Unicode or special characters in host should be accepted if non-empty; tests may exercise unicode hostnames.
- log_level case-insensitivity should be accepted and normalized (e.g., lowercased).
- reload and workers interplay:
- workers must be >= 1.
- If reload is True and workers > 1, emit a non-blocking informational note (e.g., via print or logging) but do not affect behavior.
- Performance and design constraints:
- Time complexity of run: O(1) with respect to inputs (only simple validation and object creation).
- Space complexity: O(1) per ServerStub; global registry grows with number of runs but should be kept minimal; provide a method to prune stale entries if needed (not required by tests, but design with future cleanup in mind).
- Optional multi-file architecture (within a single file):
- The code should be structured to resemble a small modular boundary within one file:
- A private _core-like section that coordinates lifecycle (_server_registry, _generate_id, etc.).
- A public API surface (run, ServerStub) that remains importable as a single module.
- This design should make it straightforward to split into multiple files/modules later (uvicorn.core, uvicorn.config, etc.) without altering the top-level API.
Documentation and comments
- Top-level module docstring explaining:
- Purpose, usage, and caveats (no real server started; safe for tests).
- Design choices (thread-safety, zero I/O, etc.).
- Inline comments explaining non-obvious decisions (e.g., input coercion, ID generation, race-condition considerations).
File placement
- Implement the code in /app/uvicorn.py
- The solution must be importable as a module named uvicorn from the /app directory (e.g., tests import uvicorn).
Acceptance criteria (test-oriented)
- Importing uvicorn succeeds without ImportError.
- Calling uvicorn.run(app, host="127.0.0.1", port=9000) returns a ServerStub object with:
- host == "127.0.0.1"
- port == 9000
- app is the same object passed in
- started == True immediately after the call
- attributes like id, created_at present
- Repeated or concurrent calls to run behave deterministically and do not block or start real servers.
- No real network I/O, no event loop requirements, and no external dependencies.
- The module remains import-safe in test environments and does not produce side effects on import.
Example usage
- Simple one-liner:
- server = uvicorn.run(app, host="127.0.0.1", port=9000)
- assert server.started is True
- assert server.host == "127.0.0.1" and server.port == 9000
Notes for testers
- The tests may simulate various edge cases (invalid inputs, unicode hostnames, string port, etc.). Ensure the function raises clear exceptions (ValueError) with helpful messages for invalid inputs.
- The __main__ guard in the consuming code should not cause real network activity; demonstrate that the stub remains inert in that path as well.
- Keep the module as small, deterministic, and dependency-free as possible while satisfying the extended constraints.