ASGI Adapter — Aquilia Documentation
Comprehensive guide and documentation for ASGI Adapter in the Aquilia framework. View API reference, examples, and implementation patterns.
ASGI Adapter aquilia.asgi — Bridging ASGI to Aquilia internals The ASGIAdapter is a high-performance 777-line class designed for maximum throughput and security. It translates raw ASGI connection scopes and event streams into Aquilia's Request and Response abstractions, manages transactional dependency injection scopes, executes the middleware stack, and handles the ASGI lifespan handshake. 1 ASGI Call 2 Ctx Pool 3 Version strip 4 Middleware 5 Action The ASGI Specification ASGI (Asynchronous Server Gateway Interface) defines the standard interface between async-capable Python web servers and web applications. Aquilia is an async-native, pure ASGI application that runs on any compliant server (such as Uvicorn, Hypercorn, or Granian). None: """ scope: Dictionary containing connection metadata (type, path, method, headers, etc.) receive: Async callable to receive incoming ASGI events (HTTP request bodies, WebSocket messages) send: Async callable to push outgoing ASGI events to the client """ ...`} language="python" /> ASGIAdapter Architecture The adapter uses `__slots__` to eliminate per-instance dictionary overhead and caches references to subsystems to avoid expensive attribute lookups during hot paths: Core Adapter Operations 1. Zero-Allocation Context Pooling To prevent garbage collection overhead under high request concurrency, the adapter uses a lock-free RequestCtx object pool (_ctx_pool). Instead of allocating a new context object on every request, the adapter acquires a recycled context, resets its fields in-place, and releases it back to the pool once the response is sent. 2. API Version & Path Prefix Pre-Resolution API versioning can affect the routing table. To resolve this, the adapter calls _resolve_route_inputs() before route matching. It evaluates version headers/queries, strips structural URL prefixes (e.g., stripping /v2 from /v2/users), and passes the cleaned path to the Router , ensuring version middleware can negotiate correctly without route mismatches. 3. RFC-Compliant Auto-HEAD Fallback In compliance with the HTTP/1.1 specification (RFC 7231 §4.3.2), if a client sends a HEAD request but no explicit HEAD handler is registered on the matched path, the adapter automatically matches the route's GET handler, runs the full middleware and validation logic, and then strips the body from the final response before sending headers. 4. Structured 405 Method Not Allowed Responses If a path matches a route but does not support the requested HTTP method, the adapter queries alternative methods, automatically sets a valid Allow header, and generates a structured error (returning styled HTML for browsers or structured JSON for APIs based on the Accept header). Built-in Performance-Optimized Health Endpoint The health endpoint (/_health and /health) is handled directly inside the ASGI adapter, bypassing the entire middleware stack to minimize CPU overhead. • Method Restricting: Bypassed paths are restricted to GET and HEAD requests; other methods immediately return a 405 Method Not Allowed response. • Subsystem Diagnostics: Integrates with the central HealthRegistry to query status details for registered subsystems (database, cache, task workers, mail, and storage). • Security Hardening: To satisfy OWASP compliance, the health endpoint manually applies strict security headers (e.g., cache-control: no-store, x-content-type-options: nosniff, x-frame-options: DENY) since it bypasses normal security middleware. Lifespan Startup Guards & Error Sanitization The ASGI lifespan protocol coordinates application startup and shutdown. Aquilia hardens this phase with two critical behaviors: Database Not Ready Guard (SystemExit) If a module raises DatabaseNotReadyError (which inherits from SystemExit) during startup, the adapter catches the warning, logs it, and sends lifespan.startup.complete anyway. This prevents ASGI servers (like Uvicorn) from logging a fatal crash and disabling lifespan events, allowing the server to boot into a degraded/retry state. OWASP Error Sanitization For standard exceptions raised during startup, the adapter logs the full traceback inside the application logs but returns a sanitized message ("Server startup failed") back to the ASGI server's startup.failed event, preventing stack traces or database connection string secrets from leaking into system logs. Production Deployment Deploy Aquilia using uvicorn or granian workers. Ensure lifespan is explicitly enabled. Uvicorn (Standard Python Worker) Granian (High-Performance Rust-based ASGI Server) → Lifecycle: Startup/shutdown coordination → Request: The Request object in depth → MiddlewareStack: How the chain is built and ordered )
Go to Homepage