Skip to content

xtr_http_kernel

Requests turned into responses through events: a request lifecycle for web applications.

A web framework routes a request to the function that answers it. Everything an application wants around that function — a request id on every response, an uncaught exception written to the log with the request that caused it, a header that keeps a page out of a search index — is not the endpoint's business, and does not belong in each of them.

This library puts those between the framework and the endpoint as events: a request announces itself, the response it produced announces itself, and whoever listens contributes. Listeners come from the container, so they are services like any other.

MIDDLEWARE_TAG module-attribute

MIDDLEWARE_TAG: Final = 'http_kernel.middleware'

The tag name bundles and the setup call agree on.

ExceptionEvent

ExceptionEvent(request: ServerRequestInterface, state: MutableMapping[str, object], exception: BaseException)

Bases: Event

Handling request raised, and nothing has been sent.

A listener that only wants to know — one writing the failure to a log, say — reads :attr:exception and leaves the response alone: the exception then carries on out of the lifecycle, to whatever the application put in charge of turning it into a response.

A listener that wants to answer calls :meth:set_response, which stops the event: the exception is swallowed, and that response leaves instead.

:attr:exception is a :class:BaseException, not an :class:Exception: a cancellation or an interrupt is exactly the kind of failure a listener logging what went wrong wants to see.

Announce that handling request raised exception.

Parameters:

  • request (ServerRequestInterface) –

    The request whose handling raised, as a message.

  • state (MutableMapping[str, object]) –

    The per-request state bag — the same one the framework's own request wraps — for whatever a listener kept on it.

  • exception (BaseException) –

    What was raised.

request property

request: ServerRequestInterface

Return the request whose handling raised, as a message.

state property

state: MutableMapping[str, object]

Return the per-request state bag, shared with the framework's own request.

exception property

exception: BaseException

Return what was raised.

response property

response: Response | None

Return the response a listener turned the exception into, if one did.

set_response

set_response(response: Response) -> None

Answer with response, and skip the listeners after this one.

The exception stops here: response is what leaves, and the listeners that have not run never hear about the failure.

FinishRequestEvent

FinishRequestEvent(request: ServerRequestInterface, state: MutableMapping[str, object])

Bases: Event

Handling of request finished — the one event dispatched on every path.

It runs whether the application answered, a listener short-circuited the request, an exception was turned into a response, or an exception is about to leave the lifecycle unhandled. That is what makes it the place to put away anything a request set up: the per-request logging unit, a trace, a scope closed by hand.

When there is a body, it is dispatched before the last chunk leaves, so a listener can still do its work while the request is recognisably the one being answered. It carries no response: by this point the head is gone, and there is nothing left to change — see :class:~xtr_http_kernel.event.terminate_event.TerminateEvent for what was actually sent.

Announce that handling request finished.

Parameters:

  • request (ServerRequestInterface) –

    The request whose handling finished, as a message.

  • state (MutableMapping[str, object]) –

    The per-request state bag — the same one the framework's own request wraps — for whatever a listener kept on it.

request property

request: ServerRequestInterface

Return the request whose handling finished, as a message.

state property

state: MutableMapping[str, object]

Return the per-request state bag, shared with the framework's own request.

RequestEvent

RequestEvent(request: ServerRequestInterface, state: MutableMapping[str, object])

Bases: Event

A request arrived, and nothing has looked at it yet.

This is the one moment a listener can answer instead of the application: :meth:set_response short-circuits routing, so a cache, a maintenance page or a redirect never reaches an endpoint. Answering stops the event, because the listeners after it would be deciding about a request that has already been dealt with.

A listener that only wants to read or annotate the request leaves the response alone; the request then carries on to the router untouched.

Announce request, before anything has handled it.

Parameters:

  • request (ServerRequestInterface) –

    The request that arrived, as a message.

  • state (MutableMapping[str, object]) –

    The per-request state bag — the same one the framework's own request wraps — for whatever a listener keeps on it.

request property

request: ServerRequestInterface

Return the request that arrived, as a message.

state property

state: MutableMapping[str, object]

Return the per-request state bag, shared with the framework's own request.

response property

response: Response | None

Return the response a listener answered with, if one did.

set_response

set_response(response: Response) -> None

Answer the request with response, and skip the listeners after this one.

The application never runs: response is what leaves, after the rest of the lifecycle has had its say about it.

ResponseEvent

ResponseEvent(request: ServerRequestInterface, state: MutableMapping[str, object], status_code: int, headers: MutableHeaders)

Bases: Event

A response is about to start, and its head can still be changed.

Dispatched once the application has decided on a status and a set of headers, and before either has left — a request id, a caching directive or a header keeping the page out of a search index belongs here.

The body is not here, and cannot be replaced. A response is streamed: by the time the first chunk is written the head is already gone, and the body may be produced a chunk at a time by something that is still running. This event owns exactly what an application can still change at that point: :attr:status_code, which may be assigned, and :attr:headers, which may be mutated. A listener wanting to answer with a body of its own does so at :class:~xtr_http_kernel.event.request_event.RequestEvent or :class:~xtr_http_kernel.event.exception_event.ExceptionEvent, where nothing has been sent yet.

Announce the response to request, starting with status_code and headers.

Parameters:

  • request (ServerRequestInterface) –

    The request being answered, as a message.

  • state (MutableMapping[str, object]) –

    The per-request state bag — the same one the framework's own request wraps — for whatever a listener kept on it.

  • status_code (int) –

    The status the response will start with.

  • headers (MutableHeaders) –

    The outgoing list itself, not a copy: what a listener writes into it is what leaves.

request property

request: ServerRequestInterface

Return the request being answered, as a message.

state property

state: MutableMapping[str, object]

Return the per-request state bag, shared with the framework's own request.

status_code property writable

status_code: int

Return the status the response will start with.

headers property

headers: MutableHeaders

Return the outgoing headers, to read or to change in place.

TerminateEvent

TerminateEvent(request: ServerRequestInterface, state: MutableMapping[str, object], status_code: int)

Bases: Event

Everything was sent, or the failure went past the lifecycle.

Dispatched after the last chunk of the response left, so nothing a listener does here can reach the client. That is the point: work worth doing once the caller has their answer — a metric, a notification, a write that would otherwise have held the response — belongs here.

:attr:status_code is what was actually sent. When nothing was sent at all, because an exception left the lifecycle before the response started, it is 500: that is what the caller ends up seeing, and a listener counting statuses should count it.

Announce that request was answered with status_code.

Parameters:

  • request (ServerRequestInterface) –

    The request that was answered, as a message.

  • state (MutableMapping[str, object]) –

    The per-request state bag — the same one the framework's own request wraps — for whatever a listener kept on it.

  • status_code (int) –

    The status that was sent, or 500 when nothing was.

request property

request: ServerRequestInterface

Return the request that was answered, as a message.

state property

state: MutableMapping[str, object]

Return the per-request state bag, shared with the framework's own request.

status_code property

status_code: int

Return the status that was sent, or 500 when nothing was.

HttpKernelError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything turning a request into a response can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

InvalidArgumentError

InvalidArgumentError(reason: str)

Bases: HttpKernelError, ValueError

The lifecycle or its configuration was given a value it cannot work with.

Also a :class:ValueError, so code that already guards its configuration with except ValueError keeps working without learning a new exception.

Attributes:

  • reason (str) –

    What is wrong with the value.

Record what is wrong with the value.

InvalidCollectorPriorityError

InvalidCollectorPriorityError(key: ServiceKey, priority: object)

Bases: HttpKernelError, TypeError

A data collector tag's priority is not an integer.

The priority orders the panels of a profile, so a value that cannot be compared with the others fails the build rather than a profile later. Also a :class:TypeError.

Attributes:

  • key (ServiceKey) –

    The tagged definition.

  • priority (object) –

    The value it carried.

Record the definition and the priority it carried.

InvalidCollectorTagError

InvalidCollectorTagError(key: ServiceKey, attribute: str)

Bases: HttpKernelError, ValueError

A data collector tag lacks a name or a template, or one is not a string.

The name is what a profile keeps the collector's data under and the template is what shows it, so neither can be left for later. Also a :class:ValueError.

Attributes:

  • key (ServiceKey) –

    The tagged definition.

  • attribute (str) –

    The attribute that is missing or not a string.

Record the definition and the attribute it lacks.

InvalidCookieError

InvalidCookieError(name: str, reason: str)

Bases: HttpKernelError, ValueError

A cookie of a request message is not one a Cookie header can carry.

The cookies of a message are a plain mapping, which nothing checked on the way in; the header they are written into is read back by splitting it apart again. So a name or a value the cookie grammar refuses would either break the header or come back as something else — a value holding ; reads back as further cookies of its own, one of them possibly replacing a cookie that was really sent. The cookie is refused here instead, where the name is still known.

Also a :class:ValueError, so code that already guards what it builds with except ValueError keeps working without learning a new exception.

Attributes:

  • name (str) –

    The name the cookie was held under.

  • reason (str) –

    What is wrong with the cookie.

Record which cookie was refused and why.

InvalidMiddlewarePriorityError

InvalidMiddlewarePriorityError(key: tuple[type, Hashable | None], priority: object)

Bases: HttpKernelError

A http_kernel.middleware tag's priority attribute is not an integer.

Raised while the kernel is built, so a misdeclared bundle fails at startup rather than serving an unordered chain.

Attributes:

  • key (tuple[type, Hashable | None]) –

    The tagged service's (type, qualifier) key.

  • priority (object) –

    What the tag carried instead of an integer.

Record the offending service key and what its tag carried.

InvalidRateLimitError

InvalidRateLimitError(reason: str)

Bases: HttpKernelError, ValueError

A route's rate limit was declared in a way it cannot be applied.

Raised where it is declared — fewer than one token, a router that already has routes, a key that is not a string — rather than silently limiting nothing.

Attributes:

  • reason (str) –

    What is wrong with the declaration.

Record what is wrong with the declaration.

InvalidTokenError

InvalidTokenError(token: str)

Bases: HttpKernelError, ValueError

A profile token holds characters a profile is never stored under.

A token names a file under the profiler's folder, so anything but letters, digits, _ and - is refused before a path is built from it — a .. reaching outside the folder included. Also a :class:ValueError.

Attributes:

  • token (str) –

    The token that was refused.

Record the refused token.

RangedResponseBodyError

RangedResponseBodyError(response: str, content_range: str)

Bases: HttpKernelError

The response being built into a message declares a Content-Range.

The header says the body is one part of the file; which part that is, and the reading of it, belong to where the response is sent. A message built here would carry the whole file under a header saying it carries a part of it — the two halves of the message contradicting each other, which is worse than either alone. Build the message from the range being sent instead.

Attributes:

  • response (str) –

    The kind of response whose body could not be read, as the name of its class.

  • content_range (str) –

    The range the response declares, as the header carries it.

Record the kind of response that was refused and the range it declares.

ResponseAlreadyAMessageError

ResponseAlreadyAMessageError(response: str)

Bases: HttpKernelError

The response being built into a message already is one.

The bridge's own response is both what the framework sends and a message in its own right, so converting it is asking to turn a message into the same message: there is nothing to do but read its body, which is awaited and so cannot be read here. Use the response as the message it already is — await response.get_body().get_contents() for its body — rather than handing it over to be converted.

Attributes:

  • response (str) –

    The kind of response that already is a message, as the name of its class.

Record the kind of response that already is a message.

StreamedResponseBodyError

StreamedResponseBodyError(response: str)

Bases: HttpKernelError

The response being built into a message streams its body.

A streamed body is an iterator the server drains once as it sends it: reading it here would consume it and leave the response with nothing to send, and handing over a message with an empty body instead would pass emptiness off as the answer. Build the message from the content the response was given, and stream that.

Attributes:

  • response (str) –

    The kind of response whose body could not be read, as the name of its class.

Record the kind of response whose body could not be read.

TooManyRequestsError

TooManyRequestsError(rate_limit: RateLimit, limiter: str, key: str, now: float)

Bases: HttpKernelError, HTTPException

A route turned a request away because a rate limit refused it.

Also the framework's own HTTP exception, so the application answers it as it answers any other: 429 Too Many Requests with a Retry-After header, reshaped by an exception handler registered for this class when the application wants another body.

Attributes:

  • rate_limit (RateLimit) –

    The limit that refused the request.

  • limiter (str) –

    The configured limiter's name.

  • key (str) –

    The key the request was counted under.

  • retry_after (int) –

    Whole seconds until the request would be accepted.

Record the refused limit, counting the wait from now.

UnknownCollectorError

UnknownCollectorError(name: str, available: tuple[str, ...])

Bases: HttpKernelError, LookupError

A profile was asked for data no collector of it gathered.

Also a :class:LookupError, as a missing key is.

Attributes:

  • name (str) –

    The collector asked for.

  • available (tuple[str, ...]) –

    The collectors the profile holds.

Record the collector asked for and the ones there are.

UnknownRateLimiterError

UnknownRateLimiterError(limiter: str, available: tuple[str, ...])

Bases: HttpKernelError, LookupError

A route names a rate limiter nobody configured.

Raised when the first request reaches the route, since routes are declared before any kernel is built. A limiter is configured in the rate limiter bundle's configuration, under the name the route uses.

Attributes:

  • limiter (str) –

    The name the route used.

  • available (tuple[str, ...]) –

    The names the application configured.

Record the unknown name and the ones that exist.

UnsupportedConnectionError

UnsupportedConnectionError(connection: str)

Bases: HttpKernelError

Something asked for the request as a message while a socket was served.

An HTTP message describes a request and the response it earns, so it can only be built from an HTTP request. A WebSocket connection has neither a method nor a body to read once, and the frames it exchanges are not messages of this kind; a route serving one takes the framework's own websocket parameter instead.

Attributes:

  • connection (str) –

    What the connection being served is, as the server named it — "websocket" where a socket was served.

Record what was being served instead of an HTTP request.

KernelEvents

One name per lifecycle event, for listeners registered by name.

An event is keyed by the qualified name of its class, so a listener declared on a typed parameter and one registered under the matching constant here are registered for the same event. The constants exist for the places a class cannot be written — a listener whose event is chosen at runtime, a configuration file, a subscriber mapping names to methods:

dispatcher.add_listener(KernelEvents.RESPONSE, stamp_request_id, priority=100)

Keeping them in one place also means the set of moments a request goes through can be read at a glance, in the order it goes through them.

REQUEST class-attribute instance-attribute

REQUEST: Final[str] = event_name_of(RequestEvent)

The request arrived and nothing has handled it.

RESPONSE class-attribute instance-attribute

RESPONSE: Final[str] = event_name_of(ResponseEvent)

A response is about to start, and its head can still be changed.

EXCEPTION class-attribute instance-attribute

EXCEPTION: Final[str] = event_name_of(ExceptionEvent)

Handling raised, and nothing has been sent.

FINISH_REQUEST class-attribute instance-attribute

FINISH_REQUEST: Final[str] = event_name_of(FinishRequestEvent)

Handling finished — dispatched on every path.

TERMINATE class-attribute instance-attribute

TERMINATE: Final[str] = event_name_of(TerminateEvent)

Everything has been sent, or the failure went past the lifecycle.

MiddlewareStack

MiddlewareStack(factories: Iterable[MiddlewareFactory] = ())

The middleware factories a kernel contributed, the outermost first.

Immutable: built once when the kernel is compiled, composed as many times as the serving code asks.

Hold factories in the given order — the outermost first.

wrap

wrap(app: ASGIApp) -> ASGIApp

Return app wrapped in every factory, the first one outermost.

RequestLifecycleMiddleware

RequestLifecycleMiddleware(app: ASGIApp, *, dispatcher: EventDispatcherInterface, message_factory: HttpMessageFactoryInterface)

Announces each moment of a request's life to whoever listens.

Sits between the server and the application as plain middleware — built from an application, a dispatcher and the bridge's message factory, nothing else — so a framework registers it the way it registers any other:

app.add_middleware(
    RequestLifecycleMiddleware,
    dispatcher=dispatcher,
    message_factory=HttpMessageFactory(...),
)

Every request then goes through the same sequence, whatever becomes of it: :class:~xtr_http_kernel.event.request_event.RequestEvent before the application sees it (a listener answering there skips the application), :class:~xtr_http_kernel.event.response_event.ResponseEvent before the response start leaves, :class:~xtr_http_kernel.event.exception_event.ExceptionEvent when handling raised (a listener answering there swallows the failure, unless the response already started), :class:~xtr_http_kernel.event.finish_request_event.FinishRequestEvent before the last body chunk leaves — or once handling ended any other way: a file sent whole, a client gone mid-stream, an unanswered failure — and :class:~xtr_http_kernel.event.terminate_event.TerminateEvent last, with the status that was sent. Each event at most once per request, and every one of them carries the request as a message — the served request, born connected to its connection, its body read only if a listener asks to read it — plus the per-request state bag the framework's own request wraps.

A listener that does read the body drains the wire, so the application is handed a receive that replays the buffered bytes; a request no listener reads passes through untouched. A form the served request parsed is closed as the request leaves.

A failure nobody answered propagates as it arrived: turning it into a response is the application's business, not this middleware's. A failure the server's send raised — a layer outside answering in the application's place, as a body limit answers 413, or a socket gone — is no failure of handling: it is announced to no exception listener, and propagates once the request finished. Only the lifespan of the application and its websockets pass through untouched — they are not requests.

The finish and terminate listeners, and closing what the request opened, run to their end whatever cancels the request — each in a task of its own, in a copy of the request's context, so a listener cannot reset a context variable set earlier in the request — within :data:_CLEANUP_TIMEOUT seconds each; one still running then is cancelled with a TimeoutError.

When the dispatcher records per unit of work — it offers callable begin_unit and end_unit — each request is framed as one unit, so overlapping requests each trace only their own events.

Wrap app, announcing every request to dispatcher's listeners.

Parameters:

  • app (ASGIApp) –

    The application whose requests are announced.

  • dispatcher (EventDispatcherInterface) –

    Where the lifecycle's events go.

  • message_factory (HttpMessageFactoryInterface) –

    Builds each request's served request message — the bridge's own factory when the container builds this, built by hand when nothing does.