Running an HTTP app: an Effect[HttpServerResponse, E, R] that
reads the current HttpServerRequest (Effect's HttpEffect).
to_handled is what servers run per request: the app in a request scope
(closed when the response is sent, or when a streamed body ends), its
failure turned into a response (server_error.cause_response) and
reported, pre-response handlers applied, then handle_response writing
it. The app runs uninterruptibly unless it opts in (routes do), so a client
abort only interrupts an app that allows it.
Values#
| Attribute | Type | Description |
|---|---|---|
append_pre_response_handler_unsafe | (context: Context[Any], handler: (ServerRequest, HttpServerResponse) -> Effect[HttpServerResponse, HttpServerError, Never]) -> None |
Types#
| Type | Definition | Description |
|---|---|---|
HttpApp | type HttpApp[E = Never, R = Never] = Effect[HttpServerResponse, E, R] | An app: the response to the current request. |
HttpMiddleware | type HttpMiddleware = Callable[[HttpApp[Any, Any]], HttpApp[Any, Any]] | Wraps an app ( |
ResponseHandler | type ResponseHandler[EH, RH] = Callable[[ServerRequest, HttpServerResponse], Effect[object, EH, RH]] | Writes a response; succeeding with a response says what was sent. |
PreResponseHandler | type PreResponseHandler = Callable[[ServerRequest, HttpServerResponse], Effect[HttpServerResponse, HttpServerError]] | Runs on a response before it is sent, and may replace it. |
Functions#
to_handled#
to_handled[E, R, EH = Never, RH = Never](app, handle_response, middleware=None) -> Effect[None, Never, R | RH | HttpServerRequest]Handle the current request with app and write the response with
handle_response. A failure becomes its response and is reported;
the request's Scope closes with the handler's exit.
| Parameter | Type | Description |
|---|---|---|
app | Effect[HttpServerResponse, E, R | Scope] | |
handle_response | ResponseHandler[EH, RH] | |
middleware | HttpMiddleware | None = None |
Returns Effect[None, Never, R | RH | HttpServerRequest]
def to_handled[E, R, EH = Never, RH = Never](
app: Effect[HttpServerResponse, E, R | Scope],
handle_response: ResponseHandler[EH, RH],
middleware: HttpMiddleware | None = None,
) -> Effect[None, Never, R | RH | HttpServerRequest]:
"""Handle the current request with ``app`` and write the response with
``handle_response``. A failure becomes its response and is reported;
the request's ``Scope`` closes with the handler's exit."""
require_effect(app, "app")
def body(fiber: Fiber[Any, Any]) -> Effect[None, Never, Any]:
previous = fiber._context
request = previous.get_unsafe(HttpServerRequest)
scope = CloseableScope()
request_scope = RequestScope(scope)
state = RequestState(request_scope)
failed: list[Cause[Any]] = []
def on_failure(cause: Cause[Any]) -> Effect[HttpServerResponse, Any, Any]:
failed.append(cause)
def respond(pair: tuple[HttpServerResponse, Cause[Any]]) -> Effect[Any, Any, Any]:
response, reported = pair
report_unsafe(fiber, reported)
rest = succeed(response) if not reported.reasons else fail_cause(reported)
return _send(state, request, response, handle_response).flat_map(lambda _: rest)
return cause_response(cause).flat_map(respond)
responded: Effect[HttpServerResponse, Any, Any] = app.match_cause_effect(
on_success=lambda response: _send(state, request, response, handle_response),
on_failure=on_failure,
)
handled: Effect[object, Any, Any]
if middleware is None:
skip_tracer = uses_native_tracer(fiber) or is_tracer_disabled_unsafe(fiber, request)
handled = responded if skip_tracer else tracer(responded)
else:
def middleware_failed(cause: Cause[Any]) -> Effect[None, Any, Any]:
report_unsafe(fiber, cause)
if state.handled:
return void
def write(pair: tuple[HttpServerResponse, Cause[Any]]) -> Effect[None, Any, Any]:
return handle_response(request, pair[0]).as_void()
return cause_response(cause).match_cause_effect(
on_failure=lambda _: handle_response(request, empty(status=500)).as_void(),
on_success=write,
)
def middleware_succeeded(response: HttpServerResponse) -> Effect[None, Any, Any]:
if state.handled:
return void
return handle_response(request, response).as_void()
handled = tracer(middleware(responded)).match_cause_effect(
on_failure=middleware_failed, on_success=middleware_succeeded
)
def close(exit: Exit[Any, Any]) -> Effect[None]:
closed_with = Failure(failed[0]) if failed else exit
return request_scope.finish(closed_with, state.scope_ejected)
in_request: Effect[object, Any, Any] = _Locally(
handled, lambda ctx: ctx.add(Scope, scope).add(CurrentRequestState, state)
)
# The cause is reported where it happens; the handled request ends.
return in_request.on_exit(close).catch_cause(lambda _: void).as_void()
return _WithFiber(body).uninterruptible()scope_disable_close#
scope_disable_close(target) -> NoneKeep the request's scope open when the request finishes: the host closes it, with
the exit it chooses (Effect's scopeDisableClose). Takes the request's Scope, as
Effect's does, or its state. A body transferred with scope_transfer_to_stream still
closes the scope when it exits; without one, the host must close it on every path,
failures and interruption included, or the request's resources leak.
| Parameter | Type | Description |
|---|---|---|
target | RequestState | CloseableScope |
def scope_disable_close(target: RequestState | CloseableScope) -> None:
"""Keep the request's scope open when the request finishes: the host closes it, with
the exit it chooses (Effect's ``scopeDisableClose``). Takes the request's ``Scope``, as
Effect's does, or its state. A body transferred with ``scope_transfer_to_stream`` still
closes the scope when it exits; without one, the host must close it on every path,
failures and interruption included, or the request's resources leak."""
if isinstance(target, RequestState):
target.scope_ejected = True
return
fiber = Fiber.get_current()
state = None if fiber is None else _request_state.get(fiber._context)
request_scope = None if state is None else state.request_scope
if state is not None and request_scope is not None and request_scope.scope is target:
state.scope_ejected = Truescope_transfer_to_stream#
scope_transfer_to_stream(response) -> HttpServerResponseA streamed response whose body closes the request's scope with the body's exit (call
while handling the request). The scope to_handled made closes once both the body has
exited and the request has finished, middleware and tracing included; any other scope
closes as soon as the body exits. A response without a streamed body is returned as is,
and its scope keeps its usual close.
| Parameter | Type | Description |
|---|---|---|
response | HttpServerResponse |
Returns HttpServerResponse
def scope_transfer_to_stream(response: HttpServerResponse) -> HttpServerResponse:
"""A streamed response whose body closes the request's scope with the body's exit (call
while handling the request). The scope ``to_handled`` made closes once both the body has
exited and the request has finished, middleware and tracing included; any other scope
closes as soon as the body exits. A response without a streamed body is returned as is,
and its scope keeps its usual close."""
return _transfer_to_stream(response)[0]append_pre_response_handler#
append_pre_response_handler(handler) -> Effect[None, Never, HttpServerRequest]Run handler on the response before it is sent, after the ones
already added.
| Parameter | Type | Description |
|---|---|---|
handler | PreResponseHandler |
Returns Effect[None, Never, HttpServerRequest]
def append_pre_response_handler(
handler: PreResponseHandler,
) -> Effect[None, Never, HttpServerRequest]:
"""Run ``handler`` on the response before it is sent, after the ones
already added."""
def body(fiber: Fiber[Any, Any]) -> Effect[None]:
_request_state.append_pre_response_handler_unsafe(fiber._context, handler)
return void
return _WithFiber(body)with_pre_response_handler#
with_pre_response_handler[A, E, R](eff, handler) -> Effect[A, E, R | HttpServerRequest]eff, after adding handler (append_pre_response_handler).
| Parameter | Type | Description |
|---|---|---|
eff | Effect[A, E, R] | |
handler | PreResponseHandler |
Returns Effect[A, E, R | HttpServerRequest]
def with_pre_response_handler[A, E, R](
eff: Effect[A, E, R], handler: PreResponseHandler
) -> Effect[A, E, R | HttpServerRequest]:
"""``eff``, after adding ``handler`` (``append_pre_response_handler``)."""
require_effect(eff, "eff")
return append_pre_response_handler(handler).and_then(eff)