GitHub

middleware

API reference for middleware.

HTTP API middleware (Effect's HttpApiMiddleware): a service that wraps the handlers of the endpoints it is added to.

Declare one as a tag class over what it provides, the errors it may fail with and the services it needs, and give the error schemas::

class Authorization(
    HttpApiMiddleware[CurrentUser, Unauthorized], security={"bearer": security.bearer}
):
    error = Unauthorized

AuthorizationLive = layer.succeed(Authorization, {"bearer": check_token})

Without security the service is a MiddlewareFn: it gets the handler's effect, which needs what the middleware provides. With it, the service maps each security name to a SecurityMiddlewareFn, which also gets the decoded credential; they are tried in order. Add a middleware to an endpoint with endpoint.middleware(Authorization) or to a whole group with class Users(HttpApiGroup[Authorization], ...).

Types

TypeDefinitionDescription
MiddlewareFntype MiddlewareFn[P, E, R] = Callable[[Effect[HttpServerResponse, Unhandled, P], MiddlewareOptions], Effect[HttpServerResponse, Unhandled | E, R | Provided]]
SecurityMiddlewareFntype SecurityMiddlewareFn[P, E, R] = Callable[[Effect[HttpServerResponse, Unhandled, P], SecurityOptions], Effect[HttpServerResponse, Unhandled | E, R | Provided]]
MiddlewareServicetype MiddlewareService[P, E, R] = MiddlewareFn[P, E, R] | Mapping[str, SecurityMiddlewareFn[P, E, R]]
AnyMiddlewaretype AnyMiddleware = type[HttpApiMiddleware[Any, Any, Any]]
ClientMiddlewareFntype ClientMiddlewareFn[E, R] = Callable[[ClientMiddlewareOptions], Effect[HttpClientResponse, E | HttpClientError, R]]

Classes

Functions

layer_schema_error_transform

layer_schema_error_transform[E, R](middleware, transform) -> Layer[HttpApiMiddleware[Never, E, R]]

A layer of middleware answering the schema errors of requests with transform (a 422 instead of the 400, say).

ParameterTypeDescription
middlewaretype[HttpApiMiddleware[Never, E, R]]
transformCallable[[HttpApiSchemaError, MiddlewareOptions], Effect[HttpServerResponse, E | HttpApiSchemaError, R | Provided]]

Returns Layer[HttpApiMiddleware[Never, E, R]]

def layer_schema_error_transform[E, R](
    middleware: type[HttpApiMiddleware[Never, E, R]],
    transform: Callable[
        [HttpApiSchemaError, MiddlewareOptions],
        Effect[HttpServerResponse, E | HttpApiSchemaError, R | Provided],
    ],
) -> Layer[HttpApiMiddleware[Never, E, R]]:
    """A layer of ``middleware`` answering the schema errors of requests
    with ``transform`` (a 422 instead of the 400, say)."""

    def service(
        effect: Effect[HttpServerResponse, Unhandled, Never], options: MiddlewareOptions
    ) -> Effect[HttpServerResponse, Any, Any]:
        def on_error(error: object) -> Effect[HttpServerResponse, Any, Any]:
            if isinstance(error, HttpApiSchemaError):
                return transform(error, options)
            return fail(error)

        return effect.catch_all(on_error)

    return layer_succeed(middleware, service)

layer_problem_details

layer_problem_details(*, include_details=False) -> Layer[ProblemDetails]

The ProblemDetails middleware (Effect's layerProblemDetails): a request that does not decode fails with a BadRequestProblem whose detail is generic; include_details=True adds errors, one entry per issue, its path prefixed by the request slot. A response that does not encode is reported to the error reporters, as without the middleware, and answered with an InternalServerErrorProblem.

ParameterTypeDescription
include_detailsbool = False

Returns Layer[ProblemDetails]

def layer_problem_details(*, include_details: bool = False) -> Layer[ProblemDetails]:
    """The ``ProblemDetails`` middleware (Effect's ``layerProblemDetails``): a
    request that does not decode fails with a ``BadRequestProblem`` whose
    ``detail`` is generic; ``include_details=True`` adds ``errors``, one
    entry per issue, its path prefixed by the request slot. A response that
    does not encode is reported to the error reporters, as without the
    middleware, and answered with an ``InternalServerErrorProblem``."""

    def transform(
        error: HttpApiSchemaError, _options: MiddlewareOptions
    ) -> Effect[HttpServerResponse, BadRequestProblem]:
        if error.kind in ("Body", "ResponseHeaders"):
            reported = error_reporter.report(_cause.fail(error))
            return reported.flat_map(lambda _: to_response(InternalServerErrorProblem()))
        if include_details:
            return fail(
                BadRequestProblem(
                    detail=_REQUEST_VALIDATION_FAILED,
                    errors=_problem_issues(error),  # pyright: ignore[reportArgumentType]
                )
            )
        return fail(BadRequestProblem(detail=_REQUEST_VALIDATION_FAILED))

    return layer_schema_error_transform(ProblemDetails, transform)

client_key

client_key(middleware) -> str
ParameterTypeDescription
middlewareAnyMiddleware

Returns str

def client_key(middleware: AnyMiddleware) -> str:
    return f"{middleware.key}/Client"

layer_client

layer_client[M: HttpApiMiddleware[Any, Any, Any], E, R](middleware, service) -> Layer[ForClient[M], Never, R]

The client side of middleware: runs around each request a client of its endpoints sends (Effect's layerClient).

ParameterTypeDescription
middlewaretype[M]
serviceClientMiddlewareFn[E, R]

Returns Layer[ForClient[M], Never, R]

def layer_client[M: HttpApiMiddleware[Any, Any, Any], E, R](
    middleware: type[M], service: ClientMiddlewareFn[E, R]
) -> Layer[ForClient[M], Never, R]:
    """The client side of ``middleware``: runs around each request a
    client of its endpoints sends (Effect's ``layerClient``)."""
    return layer_client_effect(middleware, succeed(service))

layer_client_effect

layer_client_effect[M: HttpApiMiddleware[Any, Any, Any], E, R, EX, RX](middleware, made) -> Layer[ForClient[M], EX, R | RX]

layer_client with the client middleware made by an effect.

ParameterTypeDescription
middlewaretype[M]
madeEffect[ClientMiddlewareFn[E, R], EX, RX]

Returns Layer[ForClient[M], EX, R | RX]

def layer_client_effect[M: HttpApiMiddleware[Any, Any, Any], E, R, EX, RX](
    middleware: type[M], made: Effect[ClientMiddlewareFn[E, R], EX, RX]
) -> Layer[ForClient[M], EX, R | RX]:
    """``layer_client`` with the client middleware made by an effect."""
    require_effect(made, "made")

    def build(fn: ClientMiddlewareFn[E, R]) -> Effect[Context[Any], Never, Any]:
        def with_services(services: Context[Any]) -> Context[Any]:
            def run(options: ClientMiddlewareOptions) -> Effect[HttpClientResponse, Any, Any]:
                return fn(options).pipe(provide_context(services))

            return Context({client_tag(middleware): run})

        return context().map(with_services)

    return layer_effect_context(made.flat_map(build))

client_tag

client_tag(middleware) -> type[Tag[Any]]

The tag holding middleware's client function: one per middleware, keyed <key>/Client (Effect's ForClient key).

ParameterTypeDescription
middlewareAnyMiddleware

Returns type[Tag[Any]]

def client_tag(middleware: AnyMiddleware) -> type[Tag[Any]]:
    """The tag holding ``middleware``'s client function: one per middleware,
    keyed ``<key>/Client`` (Effect's ``ForClient`` key)."""
    key = client_key(middleware)
    found = _client_tags.get(key)
    if found is None:
        found = type(f"{middleware.__name__}Client", (Tag,), {}, key=key)
        _client_tags[key] = found
    return found