Serving an HttpApi (Effect's HttpApiBuilder).
group(api, Users, build) is the layer of one group's handlers;
layer(api) adds every group's routes to the HttpRouter::
UsersLive = builder.group(
api, Users, lambda handlers: handlers.handle(Users.get_user)(get_user)
)
app = builder.layer(api).pipe(layer.provide(UsersLive))
router.serve(app)A handler gets an HttpApiRequest with the decoded parts and returns
its success value (or any HttpServerResponse); a declared error is
answered with its schema's response. A request part that does not decode
is a 400, a response that does not encode a 500.
Functions#
layer#
layer[G](api, *, openapi_path=None, schema_error_details=False) -> Layer[Never, Never, HttpRouter | G]Adds the routes of every group of api to the router (each
group's layer must be provided), and GET openapi_path answering
with the API's OpenAPI document.
A request whose params, headers, query or payload do not decode gets an
empty 400, as in Effect; schema_error_details=True sends the schema
issue in it ({"_tag": "HttpApiSchemaError", "kind", "message"}).
| Parameter | Type | Description |
|---|---|---|
api | HttpApi[G] | |
openapi_path | str | None = None | |
schema_error_details | bool = False |
Returns Layer[Never, Never, HttpRouter | G]
def layer[G](
api: HttpApi[G], *, openapi_path: str | None = None, schema_error_details: bool = False
) -> Layer[Never, Never, HttpRouter | G]:
"""Adds the routes of every group of ``api`` to the router (each
group's layer must be provided), and ``GET openapi_path`` answering
with the API's OpenAPI document.
A request whose params, headers, query or payload do not decode gets an
empty 400, as in Effect; ``schema_error_details=True`` sends the schema
issue in it (``{"_tag": "HttpApiSchemaError", "kind", "message"}``)."""
def add(router: HttpRouterService) -> Effect[None, Never, Any]:
def with_services(services: Context[Any]) -> Effect[None, Never, Any]:
routes: list[Route[Any, Any]] = []
owners: dict[str, str] = {}
for group in api.groups.values():
found = services.get_option(group.origin)
if found is None:
return die(RuntimeError(_missing_group(group, services)))
service: GroupService = found.value
for entry in service.handlers.values():
clash = _claim_route(owners, group, entry.endpoint)
if clash is not None:
return die(RuntimeError(clash))
routes.extend(service.routes)
if schema_error_details:
detailed = provide_service(_SchemaErrorDetails, True)
routes = [dataclasses.replace(r, handler=detailed(r.handler)) for r in routes]
added = router.add_all(routes)
if openapi_path is None:
return added
path = openapi_path
document = memoize_success(lambda: _openapi_document(api))
return added.flat_map(lambda _: router.add("GET", path, sync(document)))
return context().flat_map(with_services)
return use(add)group#
group[G: HttpApiGroup[Any, Any]](api: ApiWith[G], group: type[G], build: Callable[[GroupHandlers[G]], GroupHandlers[G]], /) -> Layer[G]
group[G: HttpApiGroup[Any, Any], R](api: ApiWith[G], group: type[G], build: Callable[[GroupHandlers[G]], Handlers[Any, Any, R]], /) -> Layer[G, Never, R]
group[G: HttpApiGroup[Any, Any], EX, RR = Never](api: ApiWith[G], group: type[G], build: Callable[[GroupHandlers[G]], Effect[Handlers[Any, Any, RR], EX, RR]], /) -> Layer[G, EX, RR]The layer of group's handlers in api: build gets the
empty handlers and returns them with one for each endpoint (or an
effect making them; it runs when the layer is built). A group with an
endpoint left unhandled is a defect of the layer (a group not in
api is a type error, and a ValueError). The handlers run with
the services of the layer's context.
| Parameter | Type | Description |
|---|---|---|
given | ||
group | ||
build |
@overload
def group[G: HttpApiGroup[Any, Any]](
api: ApiWith[G],
group: type[G],
build: Callable[[GroupHandlers[G]], GroupHandlers[G]],
/,
) -> Layer[G]: ...
@overload
def group[G: HttpApiGroup[Any, Any], R](
api: ApiWith[G],
group: type[G],
build: Callable[[GroupHandlers[G]], Handlers[Any, Any, R]],
/,
) -> Layer[G, Never, R]: ...
@overload
def group[G: HttpApiGroup[Any, Any], EX, RR = Never](
api: ApiWith[G],
group: type[G],
build: Callable[[GroupHandlers[G]], Effect[Handlers[Any, Any, RR], EX, RR]],
/,
) -> Layer[G, EX, RR]: ...
def group(
given: ApiWith[Any],
group: AnyGroup,
build: Callable[[GroupHandlers[Any]], Any],
/,
) -> Layer[Any, Any, Any]:
"""The layer of ``group``'s handlers in ``api``: ``build`` gets the
empty handlers and returns them with one for each endpoint (or an
effect making them; it runs when the layer is built). A group with an
endpoint left unhandled is a defect of the layer (a group not in
``api`` is a type error, and a ``ValueError``). The handlers run with
the services of the layer's context."""
api = api_of(given)
declared = api.groups.get(group.identifier)
if declared is None:
raise ValueError(
f'HttpApiGroup "{group.identifier}" not found in HttpApi "{api.identifier}"'
)
api_group = declared
def make(services: Context[Any]) -> Effect[Context[Any], Any, Any]:
result = build(GroupHandlers(api_group))
made: Effect[Any, Any, Any] = (
cast("Effect[Any, Any, Any]", result) if isinstance(result, Effect) else succeed(result)
)
return made.flat_map(lambda handlers: _group_context(api, api_group, handlers, services))
return layer_effect_context(context().flat_map(lambda services: make(_omit_scope(services))))handler#
handler[P, Q, B, CB, H, S1, CS, E1, R](endpoint: HttpApiEndpoint[P, Q, B, CB, H, S1, CS, E1, Never], f: _Handler[HttpApiRequest[P, Q, B, H], S1, E1, R], /) -> _Handler[HttpApiRequest[P, Q, B, H], S1, E1, R]
handler[P, Q, B, CB, H, S1, CS, E1, MP, ME, MR, MT, R](endpoint: HttpApiEndpoint[P, Q, B, CB, H, S1, CS, E1, HttpApiMiddleware[MP, ME, MR], MT], f: _Handler[HttpApiRequest[P, Q, B, H], S1, E1 | ME, R], /) -> _Handler[HttpApiRequest[P, Q, B, H], S1, E1 | ME, R]f unchanged, typed as endpoint's handler, for a later
handle(endpoint)(f) (Effect's HttpApiBuilder.handler).
| Parameter | Type | Description |
|---|---|---|
endpoint | ||
f |
@overload
def handler[P, Q, B, CB, H, S1, CS, E1, R](
endpoint: HttpApiEndpoint[P, Q, B, CB, H, S1, CS, E1, Never],
f: _Handler[HttpApiRequest[P, Q, B, H], S1, E1, R],
/,
) -> _Handler[HttpApiRequest[P, Q, B, H], S1, E1, R]: ...
@overload
def handler[P, Q, B, CB, H, S1, CS, E1, MP, ME, MR, MT, R](
endpoint: HttpApiEndpoint[P, Q, B, CB, H, S1, CS, E1, HttpApiMiddleware[MP, ME, MR], MT],
f: _Handler[HttpApiRequest[P, Q, B, H], S1, E1 | ME, R],
/,
) -> _Handler[HttpApiRequest[P, Q, B, H], S1, E1 | ME, R]: ...
def handler(endpoint: AnyEndpoint, f: Any, /) -> Any:
"""``f`` unchanged, typed as ``endpoint``'s handler, for a later
``handle(endpoint)(f)`` (Effect's ``HttpApiBuilder.handler``)."""
return fhandler_to_route#
handler_to_route(api, group, entry, services) -> Route[Any, Any]The router route of a handler.
| Parameter | Type | Description |
|---|---|---|
api | AnyApi | |
group | AnyGroup | |
entry | HandlerEntry | |
services | Context[Any] |
Returns Route[Any, Any]
def handler_to_route(
api: AnyApi, group: AnyGroup, entry: HandlerEntry, services: Context[Any]
) -> Route[Any, Any]:
"""The router route of a handler."""
endpoint = entry.endpoint
return route(
endpoint.method,
_path.to_router_path(endpoint.path, endpoint.params),
handler_to_http_effect(api, group, endpoint, services, entry.handler, is_raw=entry.is_raw),
uninterruptible=entry.uninterruptible,
)endpoint#
endpoint(api, group, endpoint, handler) -> Effect[Effect[HttpServerResponse, Never, Any], Never, Any]The HTTP effect of one endpoint's handler, run with the current
services (Effect's HttpApiBuilder.endpoint).
| Parameter | Type | Description |
|---|---|---|
api | AnyApi | |
group | AnyGroup | |
endpoint | AnyEndpoint | |
handler | Callable[[HttpApiRequest[Any, Any, Any, Any]], Effect[Any, Any, Any]] |
Returns Effect[Effect[HttpServerResponse, Never, Any], Never, Any]
def endpoint(
api: AnyApi,
group: AnyGroup,
endpoint: AnyEndpoint,
handler: Callable[[HttpApiRequest[Any, Any, Any, Any]], Effect[Any, Any, Any]],
) -> Effect[Effect[HttpServerResponse, Never, Any], Never, Any]:
"""The HTTP effect of one endpoint's handler, run with the current
services (Effect's ``HttpApiBuilder.endpoint``)."""
api_group = api.groups[group.identifier]
declared = api_group.endpoints[endpoint.identifier]
return context().map(
lambda services: handler_to_http_effect(
api, api_group, declared, _omit_scope(services), handler, is_raw=False
)
)handler_to_http_effect#
handler_to_http_effect(api, group, endpoint, services, handler, *, is_raw) -> Effect[HttpServerResponse, Never, Any]| Parameter | Type | Description |
|---|---|---|
api | AnyApi | |
group | AnyGroup | |
endpoint | AnyEndpoint | |
services | Context[Any] | |
handler | Callable[[HttpApiRequest[Any, Any, Any, Any]], Effect[Any, Any, Any]] | |
is_raw | bool |
Returns Effect[HttpServerResponse, Never, Any]
def handler_to_http_effect(
api: AnyApi,
group: AnyGroup,
endpoint: AnyEndpoint,
services: Context[Any],
handler: Callable[[HttpApiRequest[Any, Any, Any, Any]], Effect[Any, Any, Any]],
*,
is_raw: bool,
) -> Effect[HttpServerResponse, Never, Any]:
annotations = api.annotations.merge(group.annotations).merge(endpoint.annotations)
options = get_slot_parse_options(annotations)
encode_success = S.encode_unknown_effect(
success_schema(endpoint, options.headers), **options.success
)
encode_error = S.encode_unknown_effect(error_schema(endpoint, options.headers), **options.error)
decode_params = _decoder(endpoint.params, options.params)
decode_headers = _decoder(endpoint.headers, options.headers)
decode_query = (
None
if endpoint.query is None
else S.decode_unknown_effect(S.to_codec_array_from_single(endpoint.query), **options.query)
)
encode_stream = stream_encoder(endpoint, options.success)
encode_with_headers = with_headers_encoders(endpoint, options.success, options.headers)
upgrade = next((s for s in endpoint.success if api_schema.is_upgrade(s)), None)
# The handler of a mixed endpoint may decline the upgrade with another success.
upgrade_only = upgrade is not None and len(endpoint.success) == 1
encode_upgrade_headers = (
None
if upgrade is None or upgrade.headers is None
else S.encode_unknown_effect(upgrade.headers, **options.headers)
)
encode_response = _ResponseEncoder(
upgrade_only, encode_success, encode_stream, encode_with_headers, services
)
payload_by = (
payload_decoders(endpoint.payload, options.payload)
if endpoint.payload and not is_raw
else None
)
def respond() -> Any:
request: ServerRequest = yield from HttpServerRequest()
route_info = yield from RouteContext()
query = yield from ParsedSearchParams()
params = headers = query_value = payload = None
if decode_params is not None:
params = yield from HttpApiSchemaError.wrap("Params", decode_params(route_info.params))
if decode_headers is not None:
headers = yield from HttpApiSchemaError.wrap("Headers", decode_headers(request.headers))
if decode_query is not None:
query_value = yield from HttpApiSchemaError.wrap("Query", decode_query(query))
upgrader = None
upgraded: list[bool] = []
if upgrade is not None:
if not _is_upgrade_request(request, upgrade.protocol):
return _upgrade_required(upgrade.protocol)
upgrader = _upgrader(request, encode_upgrade_headers, upgraded)
if payload_by is not None:
decoded = decode_payload(payload_by, request, query)
payload = yield from HttpApiSchemaError.wrap("Payload", decoded)
if isinstance(payload, HttpServerResponse):
return payload
response = yield from handler(
HttpApiRequest(
params, query_value, payload, headers, request, endpoint, group, upgrader
)
)
return (yield from encode_response(response, upgraded=bool(upgraded)))
def on_error(error: object) -> Effect[HttpServerResponse, Never, Any]:
if isinstance(error, HttpApiSchemaError):
schema_error = error
def with_details(details: bool) -> Effect[HttpServerResponse, Never, Any]:
return die(dataclasses.replace(schema_error, details=details))
return _SchemaErrorDetails().flat_map(with_details)
if isinstance(error, HttpApiPayloadTooLarge):
return die(error)
def unencodable(schema_error: object) -> Effect[HttpServerResponse, Never, Any]:
if is_respondable(error):
return to_response(error)
return die(cast("BaseException", schema_error))
encoded = cast("Effect[HttpServerResponse, S.SchemaError, Any]", encode_error(error))
return encoded.catch_all(unencodable)
wrapped = _apply_middleware(group, endpoint, services, gen(respond))
return wrapped.with_error_reporting().catch_all(on_error).pipe(provide_context(services))authorization_credential#
authorization_credential(authorization, scheme) -> str | NoneThe credential of an Authorization header with scheme. RFC
9110, Section 11.1: schemes are case-insensitive and credentials follow
1*SP.
| Parameter | Type | Description |
|---|---|---|
authorization | str | None | |
scheme | str |
Returns str | None
def authorization_credential(authorization: str | None, scheme: str) -> str | None:
"""The credential of an ``Authorization`` header with ``scheme``. RFC
9110, Section 11.1: schemes are case-insensitive and credentials follow
1*SP."""
length = len(scheme)
if (
authorization is None
or len(authorization) <= length
or authorization[length] != " "
or authorization[:length].lower() != scheme.lower()
):
return None
credential = authorization[length:].lstrip(" ")
return credential or Nonesecurity_decode#
security_decode(security: Basic) -> Effect[Credentials, Never, HttpServerRequest | ParsedSearchParams]
security_decode(security: Http | ApiKey) -> Effect[Redacted[str], Never, HttpServerRequest | ParsedSearchParams]The credential security reads from the request; empty when it
is missing or malformed.
| Parameter | Type | Description |
|---|---|---|
security |
@overload
def security_decode(
security: Basic,
) -> Effect[Credentials, Never, HttpServerRequest | ParsedSearchParams]: ...
@overload
def security_decode(
security: Http | ApiKey,
) -> Effect[Redacted[str], Never, HttpServerRequest | ParsedSearchParams]: ...
def security_decode(
security: HttpApiSecurity,
) -> Effect[Redacted[str] | Credentials, Never, HttpServerRequest | ParsedSearchParams]:
"""The credential ``security`` reads from the request; empty when it
is missing or malformed."""
match security:
case Http():
scheme = security.scheme
return HttpServerRequest().map(
lambda request: redacted.make(
authorization_credential(request.headers.get("authorization"), scheme) or ""
)
)
case ApiKey():
return _api_key(security)
case Basic():
return HttpServerRequest().map(_basic)security_set_cookie#
security_set_cookie(security, value, **options) -> Effect[None, Never, HttpServerRequest]Set security's cookie on the response (secure, HTTP-only and
SameSite=Lax unless options say otherwise; Effect sets no
SameSite).
| Parameter | Type | Description |
|---|---|---|
security | ApiKey | |
value | str | Redacted[str] | |
options | Unpack[CookieOptionsInput] = {} |
Returns Effect[None, Never, HttpServerRequest]
def security_set_cookie(
security: ApiKey, value: str | Redacted[str], **options: Unpack[CookieOptionsInput]
) -> Effect[None, Never, HttpServerRequest]:
"""Set ``security``'s cookie on the response (secure, HTTP-only and
``SameSite=Lax`` unless ``options`` say otherwise; Effect sets no
``SameSite``)."""
text = value if isinstance(value, str) else redacted.value(value)
cookie: CookieOptionsInput = {"secure": True, "http_only": True, "same_site": "lax", **options}
def handler(
_request: ServerRequest, response: HttpServerResponse
) -> Effect[HttpServerResponse]:
return response.set_cookie(security.key, text, **cookie).or_die()
return append_pre_response_handler(handler)