Lifecycle — Aquilia Documentation
Comprehensive guide and documentation for Lifecycle in the Aquilia framework. View API reference, examples, and implementation patterns.
Lifecycle aquilia.lifecycle — Dependency-ordered startup and shutdown The LifecycleCoordinator manages application startup and shutdown phases in strict dependency order. It ensures that service containers are prepared, global and module-level hooks are executed sequentially, and resources are rolled back or cleaned up safely in reverse order on boot failures. INIT 1. Wire Config GLOB 2. Global Startup TOPO 3. Dependency Sort DI 4. DI Container Startup 5. READY Lifecycle Phases The application transitions through distinct states defined in the LifecyclePhase enum: return ( ) })} LifecycleCoordinator The coordinator is instantiated during AquiliaServer.__init__(). It retrieves module dependency configurations, tracks started applications, and fires events to registered observers: Lifecycle Hook Execution Flow 1. Startup Sequence (Topological Order) When startup() is called, the coordinator: Fires the global workspace-level on_startup hook (if defined in self.config), passing the base DI container. Iterates through module application contexts (runtime.meta.app_contexts), which are pre-sorted in topological dependency order. For each module: starts its DI container (executes DI provider startup events) and resolves and executes the module's on_startup(config_ns, container) hook. Appends the booted module to started_apps for rollback tracking. 2. Shutdown Sequence (Reverse Dependency Order) teardown is executed in reverse order of startup. If App A boots before App B, then App B's on_shutdown runs before App A's. This ensures dependent resources remain active while their consumers tear down. Graceful Error Handling: Unlike startup, exceptions raised during shutdown do not halt the process. The coordinator catches the error, logs it as a warning, and continues running the remaining teardown hooks to ensure best-effort resource cleanup. 3. Automatic Startup Rollback If any module fails to startup, the coordinator flags the phase as LifecyclePhase.ERROR, logs the traceback, and initiates an automatic rollback. It executes the shutdown sequence for all modules listed in started_apps in reverse order, ensuring no orphaned resources remain active before propagating a LifecycleError. Controller Lifecycle Hooks Controllers with instantiation_mode = "singleton" can hook into startup and shutdown events directly. All controllers, regardless of mode, support per-request hooks: None: """Called once when the server boots.""" self.client = await self.init_client() async def on_shutdown(self, ctx: RequestCtx) -> None: """Called once during server shutdown.""" await self.client.close() async def on_request(self, ctx: RequestCtx) -> None: """Called before EVERY incoming request routed to this controller.""" ctx.state["req_start"] = time.monotonic() async def on_response(self, ctx: RequestCtx, response: Response) -> Response: """Called after EVERY request. Allows altering response headers/body.""" duration = time.monotonic() - ctx.state["req_start"] response.headers["X-Process-Time"] = f" s" return response`} language="python" /> Hook Method Trigger Frequency Supported Modes ))} The LifecycleManager Context Manager For script execution, testing, or server wrappers, the LifecycleManager class exposes an async context manager. This enforces startup on entry and guarantees cleanup on block exit, even if unhandled exceptions are raised: Central Observability Observers The AquiliaServer registers two default observers on the coordinator: • Fault Observer ( _lifecycle_fault_observer): Intercepts error events and records them in the structured FaultEngine database. • Trace Observer ( _lifecycle_trace_observer): Records all successful transitions and phase changes directly to the .aquilia/lifecycle.log journal. → AquiliaServer: Full server orchestration → DI Lifecycle: Container-level lifecycle management )
Go to Homepage