Embedding¶
The CLI (h2corn module:app) and the serve() function start the server as a top-level process. Use the Server class inside an existing asyncio event loop or test harness. Full signatures are in the API reference.
Inside an asyncio app¶
This self-contained example starts a loopback server on an available port, makes one request, and shuts down:
import asyncio
from urllib.request import urlopen
from h2corn import Config, Server
from h2corn.types import Receive, Scope, Send
async def app(scope: Scope, receive: Receive, send: Send) -> None:
assert scope['type'] == 'http'
await send({'type': 'http.response.start', 'status': 200, 'headers': []})
await send({'type': 'http.response.body', 'body': b'Hello, world!'})
async def main() -> None:
server = Server(
app,
Config(bind=('127.0.0.1:0',), access_log=False, lifespan='off'),
)
serving = asyncio.create_task(server.serve())
try:
await server.wait_started()
url = f'http://{server.addresses[0]}/'
# Keep the event loop free to serve the synchronous client's request.
with await asyncio.to_thread(urlopen, url, timeout=5) as response: # ruff: ignore[suspicious-url-open-usage] - The URL is the local HTTP listener above.
assert response.status == 200
assert response.read() == b'Hello, world!'
print(f'embedded request: {response.status}')
finally:
server.shutdown()
await serving
asyncio.run(main())
Run it with python embedded.py; it prints embedded request: 200.
Server.serve() is an async function that runs until the server is asked to shut down. It runs one worker in the calling process; serve() runs several through the same multi-process supervisor as the CLI.
Server.serve() owns an in-process lifecycle, so it rejects a configuration that combines pidfile with user or group: the pidfile and privilege change need one supervisor to own their ordering. On Unix, use serve() or the CLI for that topology; their supervisor owns the pidfile and manages worker privilege changes.
Readiness, ephemeral ports, and shutdown¶
serve() runs until the server stops, so run it as a task when you need readiness or programmatic control. Bind port 0 to let the kernel choose a free port, await Server.wait_started() to read Server.addresses, and call Server.shutdown() from any thread or coroutine to stop gracefully:
import asyncio
from h2corn import Config, Server
from hello import app
async def main() -> None:
server = Server(app, Config(bind=('127.0.0.1:0',)))
serving = asyncio.create_task(server.serve())
await server.wait_started()
print(server.addresses) # runtime-assigned address; ready for requests
server.shutdown()
await serving
asyncio.run(main())
wait_started() waits for both listener binding and lifespan startup. A failed bind, a failed lifespan startup, or a shutdown before readiness raises to everyone waiting at the time; only success is remembered. Readiness is process-wide, so a Server driven from another thread's loop can still be awaited from yours. When several TCP listeners bind port 0 (for example 0.0.0.0:0 plus [::]:0), they share one kernel-assigned port.
shutdown() returns immediately; serve() owns the wait. Cooperative requests get up to timeout_graceful_shutdown seconds to finish, then cancellation and cleanup get the same budget again. A synchronous Python call that blocks the event-loop thread cannot be preempted by an in-process deadline: if a request outlives both drain periods, serve() raises RuntimeError, lifespan shutdown waits for it, is_draining stays true, and a concurrent serve() call raises RuntimeError: this Server is still releasing a previous serve() call. Use supervised workers when a process-level hard-kill bound is required.
Lifecycle¶
One serve() call at a time, and a Server can be reused once that call has let go of everything it held.
- Sequential reuse works. After
shutdown(), cancellation, or a startup failure — and after any straggling requests and lifespan shutdown have finished — the sameServercanserve()again with fresh state. - Concurrent calls are rejected. A second
serve()while the first is still running, or still winding down, raisesRuntimeError: this Server already has an active serve() callorRuntimeError: this Server is still releasing a previous serve() call.is_drainingdistinguishes these states: it stays true afterserve()returns until reuse is safe. - Cancellation drains gracefully. Cancelling the task running
serve()does not abort in-flight work — it starts the same bounded drain asshutdown(). The difference is what surfaces: cancellation always re-raisesCancelledErroronce the drain finishes or its budget runs out, never the over-budgetRuntimeError.