2.9 KiB
2.9 KiB
Runtime Lifecycle Subsystem
The nx9-auth runtime lifecycle subsystem provides an enterprise-grade, lock-free, deterministic architecture for application startup, dependency assembly, operational observability, background worker coordination, prioritized shutdown hooks, and graceful HTTP server termination.
Architecture Overview
CLI Commands / binary entrypoint (main.rs)
│
▼
ApplicationBuilder
│
├── Database Initialization (SQLite / PostgreSQL)
├── Repository Provider Assembly
├── AppState Construction
└── Router Construction (Axum API + SPA UI)
│
▼
Application Container (Lifecycle)
│
├── AtomicRuntimeState Machine
├── SignalManager (SIGINT / SIGTERM)
├── ShutdownCoordinator (CancellationToken Hierarchy)
├── WorkerManager (Task Groups)
├── HookRegistry (Prioritized Shutdown Hooks)
└── RuntimeMetrics
│
▼
axum::serve (HTTP Server)
Lifecycle States (RuntimeState)
The state machine is lock-free and driven by AtomicU8 with compare_exchange transitions.
| State | Value | Description |
|---|---|---|
Initializing |
0 | Runtime configuration loading and dependency assembly. |
Starting |
1 | Database connection pool init, migrations, router assembly. |
Running |
2 | HTTP server bound and actively serving requests. |
Draining |
3 | Shutdown signal received; server stops accepting new connections, draining existing HTTP requests. |
StoppingWorkers |
4 | Cancelling and joining active background worker tasks. |
ExecutingHooks |
5 | Executing registered shutdown hooks in priority order (First -> Normal -> Last). |
ClosingResources |
6 | Closing database connection pools and flushing logs. |
Stopped |
7 | All resources released cleanly; runtime process exits with status 0. |
Startup Sequence
main()parses CLI flags and loads configuration viaConfig::find_and_load().run_server()invokesApplication::builder(config).build().await.ApplicationBuildercreatesApplicationand executesinitialize().initialize()transitions state toStarting, connects database pool, executes migrations, and buildsRouter.app.start().awaittransitions state toRunning, bindsTcpListener, printsListening on <addr>, and awaitsaxum::serve.
Graceful Shutdown Sequence
SIGINT(Ctrl+C) orSIGTERMsignal received bySignalManagerorShutdownCoordinator.axum::servecompletes its graceful shutdown loop, stopping the TCP listener.- State transitions to
Draining. - State transitions to
StoppingWorkers;WorkerManagercancels and joins task groups. - State transitions to
ExecutingHooks;HookRegistryexecutes registered hooks. - State transitions to
ClosingResources;PoolHandlecloses the database pool. - State transitions to
Stopped; application returnsOk(())with exit status 0.