API reference¶
Generated from the source docstrings.
Resources¶
asgimachine.resource.Resource
¶
Base class for graph-lane endpoints. Override only what you care about.
Generic over its context type C: subclass Ctx for typed per-request
state and declare it via context_class (and Resource[MyCtx] for the
checker). Plain Resource uses base Ctx.
Source code in src/asgimachine/resource.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
lifespan
async
¶
Per-request setup/teardown, wrapping the whole graph walk.
Override as a plain async generator — acquire in the setup half,
yield exactly once, release after. No decorator: the core wraps
this in an async context manager itself, so a forgotten
@asynccontextmanager can't bite. (Forgetting the yield instead is
a type error, since the declared return is AsyncIterator[None].)
The core opens this before B13 and closes it on the way out, guaranteed
across every exit — a normal response, a halt (404/401/…), a raised
error, or a client disconnect. The teardown is cancellation-shielded, so
a disconnect cannot interrupt resource release; and for a streaming
response it is deferred until the body is fully drained, so a connection
stashed on ctx stays alive for the life of the stream. An in-flight
exception is fed into the generator (so async with conn.transaction()
rolls back), but the lifespan must not suppress it::
async def lifespan(self, ctx: MyCtx) -> AsyncIterator[None]:
async with self._pool.acquire() as conn: # released on any exit
ctx.conn = conn
yield
Source code in src/asgimachine/resource.py
asgimachine.resource.Ctx
dataclass
¶
webmachine's ReqData: the framework's per-request state.
Deliberately minimal and domain-agnostic — it holds the request, the trace,
negotiation result, and codec registry, plus an untyped extra bag. Domain
state (a principal, the loaded entity) is not the framework's business: a
resource that wants typed per-request state subclasses Ctx and declares
it (see Resource.context_class and PLAN.md §2.7).
Source code in src/asgimachine/resource.py
The core walk¶
asgimachine.core.run
async
¶
Walk the graph for one request and return an HttpResponse value object.
In debug mode the ordered node path is attached as the
X-Asgimachine-Trace response header on every exit path (§9). codecs
is the media-type -> Codec registry (defaults to JSON only). on_exception
is the app-level catch-all for an unexpected Exception (a resource may
override it); it defaults to re-raising, so the exception propagates to the
substrate's outer handler unless a handler opts to own the 500. event_sink,
when given, receives one wide event per request (ctx.event), emitted once at
the boundary — after lifespan teardown, or at stream-close for a streamed body.
Source code in src/asgimachine/core.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
asgimachine.http.HttpRequest
¶
Bases: Protocol
The read-only view of a request the core depends on.
Case-insensitive header access is required of headers (per RFC 9110);
the Starlette adapter satisfies this. Kept minimal on purpose — the core
only reads what the v0 graph needs.
Source code in src/asgimachine/http.py
query_params
property
¶
The parsed query string (?limit=20 -> {"limit": "20"}).
A repeated key (?tag=a&tag=b) yields its last value through this
mapping; the substrate's concrete type may offer getlist for all of
them. Empty when there is no query string.
route
property
¶
The matched route template (e.g. /notes/{id}), or None if unrouted.
The low-cardinality grouping key for the wide event (http.route), as
distinct from path (the concrete /notes/42).
body
async
¶
The buffered request body.
May raise :class:BodyTooLarge (the substrate bounds the read at the
resource's limit → 413) or :class:BodyMalformed (the bytes read
disagree with Content-Length → 400). The graph and command lanes map
these to their statuses.
Source code in src/asgimachine/http.py
asgimachine.http.HttpResponse
dataclass
¶
What the core walk returns; the substrate turns it into a wire response.
Source code in src/asgimachine/http.py
asgimachine.http.Status
¶
Bases: IntEnum
HTTP status codes the v0 graph can select. Extended in later phases.
Source code in src/asgimachine/http.py
asgimachine.http.HaltResponse
¶
Bases: Exception
Short-circuit the walk with an explicit response (PLAN.md §6).
Any callback or node may raise this to terminate the graph immediately.
Source code in src/asgimachine/http.py
Commands¶
asgimachine.command.Command
¶
asgimachine.command.json_response
¶
Build a JSON :class:HttpResponse — the ergonomic return for a command.
Source code in src/asgimachine/command.py
Authorization header parsing¶
asgimachine.auth.parse_authorization
¶
Split an Authorization value into (scheme, credentials).
The scheme must be a valid token (a non-token is rejected) and is lowercased
(it is case-insensitive, RFC 9110 §11.1). The credentials are everything after
the first run of whitespace, verbatim (a scheme-only header yields "") —
their grammar is scheme-specific, so they are not validated here; that is the
job of the scheme helpers below. Returns None for a missing/blank header or a
malformed scheme.
Source code in src/asgimachine/auth.py
asgimachine.auth.bearer_token
¶
The token from an Authorization: Bearer <token> header, or None when
the header is absent, uses a different scheme, or the token is not a valid
token68 (RFC 6750).
Source code in src/asgimachine/auth.py
asgimachine.auth.basic_credentials
¶
The (user_id, password) from an Authorization: Basic … header (RFC
7617), or None when the header is absent, uses a different scheme, or is
malformed. The password may contain colons; the user id may not (the split is on
the first colon).
Source code in src/asgimachine/auth.py
Authorization policy¶
asgimachine.policy.RuleEngine
¶
Ordered Allow/Deny rule engine; first matching rule wins (§7).
Generic over the resource's context type C so rules see typed
ctx. default decides when no rule fires (deny-by-default is safe).
Source code in src/asgimachine/policy.py
asgimachine.policy.NamedRule
dataclass
¶
asgimachine.policy.Effect
¶
asgimachine.policy.Decision
dataclass
¶
Codecs¶
asgimachine.codec.Codec
¶
Bases: Protocol
Encodes a representation value to bytes and decodes a body to structure.
Source code in src/asgimachine/codec.py
asgimachine.codec.JsonCodec
¶
application/json codec. Encode reuses :func:http.serialize (Pydantic
model_dump_json or json.dumps); decode is a syntactic parse.
Source code in src/asgimachine/codec.py
Schema generation¶
asgimachine.schema.generate_openapi
¶
Emit an OpenAPI 3.1 document for the resources that declare a describe().
security_schemes populates components.securitySchemes; security is
the document-level default requirement (scheme names), overridable per
operation via Operation.security.
Source code in src/asgimachine/schema.py
asgimachine.schema.Operation
dataclass
¶
One HTTP method's declared surface. Errors are auto-derived; declare the
success bodies. security: None inherits the document default, []
marks the operation public, ["name"] requires those schemes.
Source code in src/asgimachine/schema.py
asgimachine.schema.ResourceDescription
dataclass
¶
A resource's per-method declarations (bodies + summaries). Methods absent
here but present in ALLOWED_METHODS are still documented (auto-errors
only).
Source code in src/asgimachine/schema.py
Decision trace¶
asgimachine.trace.Trace
dataclass
¶
Source code in src/asgimachine/trace.py
asgimachine.trace.TraceEntry
dataclass
¶
Wide events¶
asgimachine.event.EventSink
¶
Bases: Protocol
Where a completed wide event goes. One synchronous method — sync so it is
safe to call from the request's exit path even under cancellation (a
disconnect); hand off to an async queue inside emit if you must.
Source code in src/asgimachine/event.py
asgimachine.event.LoggingEventSink
¶
Reference :class:EventSink over the stdlib logging module.
The full event rides on the log record as record.event (via extra), so
a structured/JSON handler can render every field; the formatted message is a
terse METHOD path -> status summary for plain handlers. Swap in a structlog
or OpenTelemetry sink at the composition root when you want those backends.
Source code in src/asgimachine/event.py
Streaming¶
asgimachine.streaming.sse_event
¶
Format one Server-Sent Events frame as bytes.
data is emitted verbatim if it is a str, otherwise JSON-encoded.
Multi-line data becomes multiple data: lines, per the SSE spec.
Source code in src/asgimachine/streaming.py
asgimachine.streaming.sse_error
¶
Format an SSE frame carrying an error (the post-commit failure channel).
asgimachine.streaming.guard_sse
async
¶
Yield from source; on a post-commit exception, emit an SSE error frame.
Wrap a producer's event generator with this so a failure after the response
has committed surfaces as an event: error frame instead of tearing down
the connection. format_error maps the exception to the error payload.
Source code in src/asgimachine/streaming.py
Starlette substrate¶
asgimachine.substrate.starlette.build_app
¶
Assemble the composition root into an ASGI application.
middleware is passed straight to Starlette, so cross-cutting concerns are
rented rather than baked into the graph (PLAN.md §2.1). CORS in particular is
its own decision machine — mount Starlette's CORSMiddleware here and true
preflights are answered before a request ever reaches the graph, while actual
responses get their Access-Control-* headers on the way out::
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
build_app(
routes,
middleware=[Middleware(CORSMiddleware, allow_origins=["https://app.example"])],
)
on_exception is the app-wide catch-all for an unexpected Exception raised
during a resource's walk (a resource may override its own). It defaults to
re-raising — so a bug propagates to Starlette's ServerErrorMiddleware (or an
ASGI error reporter) as before — but a handler may report the error, enrich the
request context, and return to have the graph own a negotiated 500 instead.
event_sink, when given, receives one wide event per request (ctx.event)
— the canonical-log-line seam. None by default (nothing is emitted);
:class:asgimachine.event.LoggingEventSink is the reference sink.
Source code in src/asgimachine/substrate/starlette.py
asgimachine.substrate.starlette.resource_route
¶
Build a Starlette Route that runs resource through the graph.
codecs injects a media-type -> Codec registry (default: JSON only).
Source code in src/asgimachine/substrate/starlette.py
asgimachine.substrate.starlette.command_route
¶
Build a Route for a command (plain-handler lane, §2.5).
Unlike a resource, a command does not walk the graph, so the router owns
method restriction here (405 for an unlisted method) — that's fine for a
command-shaped endpoint. max_body_bytes bounds the request body (the graph
lane gets this from the resource's MAX_BODY_BYTES; a command has no
resource, so it is set here) — an over-cap body is 413, a Content-Length
mismatch 400.