seiva_server/lib.rs
1//! Delonix Seiva — the service runtime ("the main a module installs").
2//!
3//! This crate is the runtime that boots a Seiva service. It is the piece a
4//! module's binary installs instead of writing its own `main`; it replaces
5//! DORM's old `dorm-api`. It does four things, each delegated to a focused
6//! framework crate so nothing is re-implemented here:
7//!
8//! - **Mounts the framework HTTP surface** — `/openapi.json` and the
9//! `/health/{live,ready}` endpoints — through [`seiva_http::router`]. It is
10//! **demo-free**: it mounts no example module, so it is publishable. A real
11//! service's `apps/<name>-api` composition root merges its modules' generated
12//! controllers and calls [`serve_router`]; the `accounts` composition is
13//! exercised in this crate's tests. See [`serve`].
14//! - **Runs a background worker host** on the framework's worker runtime
15//! ([`seiva::worker::run_worker`]). See [`run_workers`].
16//! - **Reads 12-factor configuration** from the environment with [`seiva_config`],
17//! validated at startup and guarded against dev shortcuts in production. See
18//! [`ServerConfig`].
19//! - **Shuts down gracefully**: on a shutdown signal it flips the process to
20//! [`HealthState::Draining`](seiva_http::HealthState) — so a load balancer takes
21//! it out of rotation — and drains in-flight requests before exiting.
22//!
23//! It is a LIBRARY (so each piece is testable without a live port or a running
24//! clock) plus a thin binary (`seiva-server`) that wires the pieces together.
25//!
26//! # DORM-free
27//!
28//! This crate depends on no `dorm-*` crate and on none of the excluded,
29//! DORM-git-coupled Seiva crates (`seiva-data-dorm`, `seiva-outbox-relay`,
30//! `seiva-rag-worker`, `seiva-mcp`). It declares no cargo feature that could pull
31//! any of them in. [`run_workers`] therefore ships a no-op demonstration pass
32//! today; the real transactional-outbox relay pass is injected here behind the
33//! framework's `dorm` feature once the CI token for the private DORM repo exists.
34//!
35//! # Example
36//!
37//! ```no_run
38//! use seiva_server::{run_workers, serve, ServerConfig};
39//!
40//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
41//! let config = ServerConfig::from_process_env()?;
42//! // A resolved shutdown future would stop both at once; a real binary feeds a
43//! // Ctrl-C / SIGTERM future to each (see `src/main.rs`).
44//! let (served, _reports) = tokio::join!(serve(config, async {}), run_workers(async {}));
45//! served?;
46//! # Ok(())
47//! # }
48//! ```
49
50#![forbid(unsafe_code)]
51#![deny(missing_docs)]
52
53use std::fmt;
54use std::future::Future;
55use std::net::{Ipv4Addr, SocketAddr};
56use std::time::Duration;
57
58use axum::Router;
59use seiva::ports::PortResult;
60use seiva::worker::{run_worker, WorkerConfig};
61use std::sync::Arc;
62
63use seiva_config::{EnvReader, FromEnv};
64use seiva_http::{
65 router_with_auth, Authenticator, Health, HttpSecurity, JwtAuthenticator, RateLimit,
66};
67use tokio::net::TcpListener;
68
69pub use seiva::worker::WorkerReport;
70pub use seiva_config::{AppEnv, ConfigError};
71
72/// Structured logging for a Seiva service (12-factor: logs are an event stream
73/// written to stdout, for the platform to collect).
74pub mod observability {
75 use tracing_subscriber::{fmt, EnvFilter};
76
77 /// Installs the global JSON tracing subscriber, writing one JSON object per
78 /// event to **stdout**. The level filter comes from `RUST_LOG` (e.g.
79 /// `RUST_LOG=info,seiva_server=debug`), defaulting to `info`.
80 ///
81 /// Idempotent and panic-free: a second call (or a test that already set a
82 /// subscriber) is a no-op, so binaries and tests can both call it.
83 pub fn init() {
84 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
85 let _ = fmt()
86 .json()
87 .with_current_span(false)
88 .with_env_filter(filter)
89 .try_init();
90 }
91}
92
93/// The environment variable holding the full HTTP bind address (`host:port`).
94/// Highest precedence; see [`ServerConfig`].
95pub const HTTP_ADDR_VAR: &str = "SEIVA_HTTP_ADDR";
96
97/// The environment variable holding a bare port, the convention many hosting
98/// platforms (Heroku, Cloud Run, …) set. Used only when [`HTTP_ADDR_VAR`] is
99/// unset; see [`ServerConfig`].
100pub const PORT_VAR: &str = "PORT";
101
102/// The environment variable for the development-only "expose internal error
103/// details to clients" shortcut. Guarded: it must not be enabled in production.
104pub const EXPOSE_ERROR_DETAILS_VAR: &str = "SEIVA_EXPOSE_ERROR_DETAILS";
105
106/// The default HTTP bind address when neither [`HTTP_ADDR_VAR`] nor [`PORT_VAR`]
107/// is set: loopback only, so an unconfigured service is not exposed off-box.
108pub const DEFAULT_HTTP_ADDR: &str = "127.0.0.1:8080";
109
110/// The environment variable holding the Prometheus `/metrics` bind address
111/// (`host:port`) — the **separate** admin scrape surface (ADR 0027), kept off the
112/// public API port. Unset (or empty) means no metrics exporter. Honoured only when
113/// the binary is built with the `metrics` feature; see `Server::with_metrics`.
114pub const METRICS_ADDR_VAR: &str = "SEIVA_METRICS_ADDR";
115
116/// Comma-separated allowlist of cross-origin (CORS) origins, e.g.
117/// `https://app.example.com,https://admin.example.com`. Unset or empty means
118/// same-origin only (no CORS layer). See [`HttpSecurity::cors_allowed_origins`].
119pub const CORS_ALLOWED_ORIGINS_VAR: &str = "SEIVA_CORS_ALLOWED_ORIGINS";
120
121/// Whether the rate limiter keys on the trusted `X-Forwarded-For` client IP
122/// instead of the raw TCP peer. Set to `true` **only** behind a single trusted
123/// reverse proxy; defaults to `false`. See [`HttpSecurity::trust_forwarded_for`].
124pub const TRUST_FORWARDED_FOR_VAR: &str = "SEIVA_TRUST_FORWARDED_FOR";
125
126/// Whether to serve `/openapi.json` and the interactive reference (`/docs`,
127/// `/redoc`, `/scalar`). Defaults to `true` (FastAPI parity); set `false` to stop
128/// publishing the contract to anonymous callers (OWASP API9). See
129/// [`HttpSecurity::expose_docs`].
130pub const EXPOSE_DOCS_VAR: &str = "SEIVA_EXPOSE_DOCS";
131
132/// The per-client rate-limit budget per window. Defaults to
133/// [`RateLimit::DEFAULT_MAX_REQUESTS`]; `0` disables rate limiting entirely.
134pub const RATE_LIMIT_MAX_REQUESTS_VAR: &str = "SEIVA_RATE_LIMIT_MAX_REQUESTS";
135
136/// The rate-limit window length in seconds. Defaults to
137/// [`RateLimit::DEFAULT_WINDOW`] (60s); a `0` is clamped to 1s.
138pub const RATE_LIMIT_WINDOW_SECS_VAR: &str = "SEIVA_RATE_LIMIT_WINDOW_SECS";
139
140/// Path to a JWKS (JSON Web Key Set) file whose keys verify inbound bearer JWTs.
141/// Setting it (with the issuer and audience below) turns on the authentication
142/// layer; leaving all three unset means no authn layer (every caller anonymous).
143pub const OIDC_JWKS_FILE_VAR: &str = "SEIVA_OIDC_JWKS_FILE";
144/// The expected JWT `iss` (issuer). Required when [`OIDC_JWKS_FILE_VAR`] is set.
145pub const OIDC_ISSUER_VAR: &str = "SEIVA_OIDC_ISSUER";
146/// The expected JWT `aud` (audience). Required when [`OIDC_JWKS_FILE_VAR`] is set.
147pub const OIDC_AUDIENCE_VAR: &str = "SEIVA_OIDC_AUDIENCE";
148/// The claim carrying the caller's tenant (default `tenant`). Optional.
149pub const OIDC_TENANT_CLAIM_VAR: &str = "SEIVA_OIDC_TENANT_CLAIM";
150/// The claim carrying the caller's permissions (default `permissions`, `scope`
151/// fallback). Optional.
152pub const OIDC_PERMISSION_CLAIM_VAR: &str = "SEIVA_OIDC_PERMISSION_CLAIM";
153
154/// The runtime configuration of a Seiva service, read from the environment.
155///
156/// It is small but real. Build it with [`from_process_env`](ServerConfig::from_process_env)
157/// (the 12-factor path) or, in tests, with [`seiva_config::load_from`] over an
158/// explicit map (deterministic, never racing on the process-global environment).
159///
160/// # HTTP address precedence
161///
162/// The bind address is resolved in this order, highest first:
163///
164/// 1. [`SEIVA_HTTP_ADDR`](HTTP_ADDR_VAR) — a full `host:port` (e.g.
165/// `0.0.0.0:8080`). Wins whenever it is set.
166/// 2. [`PORT`](PORT_VAR) — a bare port, the convention hosting platforms set.
167/// Bound on `0.0.0.0` (all interfaces), since a platform that sets `PORT`
168/// routes external traffic to the container.
169/// 3. [`DEFAULT_HTTP_ADDR`] — `127.0.0.1:8080`, loopback only.
170///
171/// # Production-safety guard
172///
173/// [`EXPOSE_ERROR_DETAILS_VAR`] is a development convenience. Through
174/// [`AppEnv::reject_dev_shortcut`] it is a *startup error* to enable it when
175/// `APP_ENV=production`, so the mistake fails the boot rather than leaking
176/// internals on the first error in production.
177#[derive(Debug, Clone)]
178pub struct ServerConfig {
179 /// The runtime environment (`APP_ENV`), defaulting to
180 /// [`Development`](AppEnv::Development).
181 pub env: AppEnv,
182 /// The resolved HTTP bind address (see the precedence on [`ServerConfig`]).
183 pub http_addr: SocketAddr,
184 /// Whether internal error details are exposed to clients. A development-only
185 /// shortcut, refused in production by the guard.
186 pub expose_error_details: bool,
187 /// The transport-level security posture ([`HttpSecurity`]) read from the
188 /// environment: the CORS allowlist, the trusted-proxy switch and the rate
189 /// limit. [`Default`](HttpSecurity::default) (same-origin only, rate limiting
190 /// on) when none of the variables are set.
191 pub security: HttpSecurity,
192 /// The OIDC/JWT authentication configuration, or `None` when the
193 /// `SEIVA_OIDC_*` variables are unset (no authn layer — every caller
194 /// anonymous). Built into a `JwtAuthenticator` at [`serve`] time.
195 pub oidc: Option<OidcConfig>,
196}
197
198/// The inbound-JWT verification configuration read from the environment. Present
199/// only when [`OIDC_JWKS_FILE_VAR`], [`OIDC_ISSUER_VAR`] and [`OIDC_AUDIENCE_VAR`]
200/// are all set; a partial set fails the boot.
201#[derive(Debug, Clone)]
202pub struct OidcConfig {
203 /// Path to the JWKS file whose keys verify bearer tokens.
204 pub jwks_file: String,
205 /// The expected `iss`.
206 pub issuer: String,
207 /// The expected `aud`.
208 pub audience: String,
209 /// The claim carrying the tenant (default `tenant`).
210 pub tenant_claim: Option<String>,
211 /// The claim carrying the permissions (default `permissions`, `scope` fallback).
212 pub permission_claim: Option<String>,
213}
214
215/// Reads the OIDC configuration: `None` when the `SEIVA_OIDC_*` trio is unset
216/// (no authn). If any of the three is set, all three are required — a partial
217/// configuration records a problem and fails the boot, so a typo cannot silently
218/// leave the service unauthenticated.
219fn resolve_oidc(reader: &mut EnvReader) -> Option<Option<OidcConfig>> {
220 let present = reader.optional_var(OIDC_JWKS_FILE_VAR).is_some()
221 || reader.optional_var(OIDC_ISSUER_VAR).is_some()
222 || reader.optional_var(OIDC_AUDIENCE_VAR).is_some();
223 if !present {
224 return Some(None);
225 }
226 // require_var records a "missing" problem for any of the three left unset.
227 let jwks_file = reader.require_var(OIDC_JWKS_FILE_VAR);
228 let issuer = reader.require_var(OIDC_ISSUER_VAR);
229 let audience = reader.require_var(OIDC_AUDIENCE_VAR);
230 let tenant_claim = reader.optional_var(OIDC_TENANT_CLAIM_VAR);
231 let permission_claim = reader.optional_var(OIDC_PERMISSION_CLAIM_VAR);
232 Some(Some(OidcConfig {
233 jwks_file: jwks_file?,
234 issuer: issuer?,
235 audience: audience?,
236 tenant_claim,
237 permission_claim,
238 }))
239}
240
241impl ServerConfig {
242 /// Loads and validates the configuration from the live process environment.
243 ///
244 /// This is what a `main` calls: on success it holds a fully typed, fully
245 /// validated configuration; on failure every problem is reported together.
246 ///
247 /// # Errors
248 ///
249 /// Returns a [`ConfigError`] when `APP_ENV` is unrecognised, when an address
250 /// variable fails to parse, or when the production guard rejects a dev
251 /// shortcut.
252 pub fn from_process_env() -> Result<Self, ConfigError> {
253 seiva_config::load::<Self>()
254 }
255
256 /// The [`DEFAULT_HTTP_ADDR`] parsed into a [`SocketAddr`].
257 #[must_use]
258 pub fn default_http_addr() -> SocketAddr {
259 SocketAddr::from((Ipv4Addr::LOCALHOST, 8080))
260 }
261}
262
263/// Resolves the HTTP bind address from the reader, honouring the precedence
264/// documented on [`ServerConfig`]. A present-but-unparseable value records a
265/// problem (and yields `None`) so a typo fails the boot.
266fn resolve_http_addr(reader: &mut EnvReader) -> Option<SocketAddr> {
267 if reader.optional_var(HTTP_ADDR_VAR).is_some() {
268 reader.optional_parsed::<SocketAddr>(HTTP_ADDR_VAR, ServerConfig::default_http_addr())
269 } else if reader.optional_var(PORT_VAR).is_some() {
270 let port = reader.optional_parsed::<u16>(PORT_VAR, 0)?;
271 Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)))
272 } else {
273 Some(ServerConfig::default_http_addr())
274 }
275}
276
277/// Builds the [`HttpSecurity`] posture from the environment, honouring the
278/// secure-by-default baseline: an unset variable leaves [`HttpSecurity::default`]
279/// (same-origin only, rate limiting on). A present-but-unparseable numeric or
280/// boolean records a problem (and yields `None`) so a typo fails the boot.
281fn resolve_security(reader: &mut EnvReader) -> Option<HttpSecurity> {
282 let cors_allowed_origins = reader
283 .optional_var(CORS_ALLOWED_ORIGINS_VAR)
284 .map(|raw| {
285 raw.split(',')
286 .map(str::trim)
287 .filter(|s| !s.is_empty())
288 .map(String::from)
289 .collect()
290 })
291 .unwrap_or_default();
292 let trust_forwarded_for = reader.optional_bool(TRUST_FORWARDED_FOR_VAR, false)?;
293 // Contract-discovery surface on by default (FastAPI parity); a deployment
294 // closes it with `SEIVA_EXPOSE_DOCS=false` (OWASP API9).
295 let expose_docs = reader.optional_bool(EXPOSE_DOCS_VAR, true)?;
296 let max_requests = reader
297 .optional_parsed::<u32>(RATE_LIMIT_MAX_REQUESTS_VAR, RateLimit::DEFAULT_MAX_REQUESTS)?;
298 let window_secs = reader.optional_parsed::<u64>(
299 RATE_LIMIT_WINDOW_SECS_VAR,
300 RateLimit::DEFAULT_WINDOW.as_secs(),
301 )?;
302
303 // `0 requests` is the explicit off switch; otherwise the window is clamped to
304 // at least a second so a `0` can never degenerate into an always-exhausted budget.
305 let rate_limit = (max_requests > 0).then(|| RateLimit {
306 max_requests,
307 window: Duration::from_secs(window_secs.max(1)),
308 });
309
310 Some(HttpSecurity {
311 cors_allowed_origins,
312 rate_limit,
313 trust_forwarded_for,
314 expose_docs,
315 })
316}
317
318impl FromEnv for ServerConfig {
319 fn from_env(reader: &mut EnvReader) -> Option<Self> {
320 // Read every field up front so each problem is collected, not just the
321 // first; the `?`s below only decide whether to assemble.
322 let env = reader.app_env();
323 let http_addr = resolve_http_addr(reader);
324 let expose_error_details = reader.optional_bool(EXPOSE_ERROR_DETAILS_VAR, false);
325 let security = resolve_security(reader);
326 let oidc = resolve_oidc(reader);
327
328 let config = Self {
329 env,
330 http_addr: http_addr?,
331 expose_error_details: expose_error_details?,
332 security: security?,
333 oidc: oidc?,
334 };
335
336 reader.guard(
337 config
338 .env
339 .reject_dev_shortcut(EXPOSE_ERROR_DETAILS_VAR, config.expose_error_details),
340 );
341
342 Some(config)
343 }
344}
345
346/// An error raised while binding or serving the HTTP application.
347///
348/// It wraps the pointer-sized [`std::io::Error`] from the failing stage, so it is
349/// cheap to return by value (it does not trip clippy's `result_large_err`).
350#[derive(Debug)]
351#[non_exhaustive]
352pub enum ServeError {
353 /// Binding the [`TcpListener`] to the configured address failed (the address
354 /// is in use, not permitted, or unavailable).
355 Bind(std::io::Error),
356 /// The server itself failed while accepting or draining connections.
357 Serve(std::io::Error),
358 /// The configured OIDC identity could not be built (the JWKS file is missing
359 /// or is not a valid key set). A startup error — the service refuses to boot
360 /// claiming to authenticate when it cannot.
361 Identity(String),
362 /// Two or more mounted facades pluralise to the same `(version, resource)`
363 /// route prefix, which would panic `Router::merge`. Carries the colliding
364 /// `"<version>/<resource>"` prefixes so the operator can rename a facade.
365 RouteCollision(Vec<String>),
366 /// An opt-in observability exporter (ADR 0027) could not be installed — the
367 /// Prometheus recorder (already installed, or a bad bucket config) or the OTLP
368 /// tracing pipeline. A startup error: a service that asked for metrics/tracing
369 /// refuses to boot silently blind. Only constructed under the `metrics` /
370 /// `tracing-otlp` features.
371 Observability(String),
372 /// The mutual-TLS configuration could not be loaded (a `SEIVA_TLS_*` file is
373 /// unreadable, or rustls refused the certificate, key, CA or CRL). A startup
374 /// error: the service refuses to boot with a half-configured listener. Only
375 /// under the `mtls` feature (ADR 0047).
376 #[cfg(feature = "mtls")]
377 Tls(String),
378}
379
380impl fmt::Display for ServeError {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 match self {
383 ServeError::Bind(e) => write!(f, "failed to bind the HTTP listener: {e}"),
384 ServeError::Serve(e) => write!(f, "the HTTP server failed: {e}"),
385 ServeError::Identity(m) => write!(f, "failed to build the OIDC authenticator: {m}"),
386 ServeError::RouteCollision(prefixes) => write!(
387 f,
388 "two or more facades mount on the same route prefix ({}); \
389 rename a facade so each resolves to a distinct `<version>/<resource>`",
390 prefixes.join(", ")
391 ),
392 ServeError::Observability(m) => {
393 write!(f, "failed to install an observability exporter: {m}")
394 }
395 #[cfg(feature = "mtls")]
396 ServeError::Tls(m) => write!(f, "failed to load the mutual-TLS configuration: {m}"),
397 }
398 }
399}
400
401impl std::error::Error for ServeError {
402 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
403 match self {
404 ServeError::Bind(e) | ServeError::Serve(e) => Some(e),
405 ServeError::Identity(_)
406 | ServeError::RouteCollision(_)
407 | ServeError::Observability(_) => None,
408 #[cfg(feature = "mtls")]
409 ServeError::Tls(_) => None,
410 }
411 }
412}
413
414/// Builds the inbound-JWT authenticator from [`ServerConfig::oidc`], or `None`
415/// when no OIDC configuration is set (every caller then anonymous). The JWKS file
416/// is read once at startup — a missing or malformed key set fails the boot rather
417/// than leaving the service silently unauthenticated.
418fn build_authenticator(
419 config: &ServerConfig,
420) -> Result<Option<Arc<dyn Authenticator>>, ServeError> {
421 let Some(oidc) = &config.oidc else {
422 return Ok(None);
423 };
424 let jwks_json = std::fs::read_to_string(&oidc.jwks_file)
425 .map_err(|e| ServeError::Identity(format!("reading JWKS file {}: {e}", oidc.jwks_file)))?;
426 let mut auth = JwtAuthenticator::from_jwks_json(&jwks_json, &oidc.issuer, &oidc.audience)
427 .map_err(|e| ServeError::Identity(format!("parsing JWKS {}: {e}", oidc.jwks_file)))?;
428 if let Some(claim) = &oidc.tenant_claim {
429 auth = auth.with_tenant_claim(claim);
430 }
431 if let Some(claim) = &oidc.permission_claim {
432 auth = auth.with_permission_claim(claim);
433 }
434 Ok(Some(Arc::new(auth)))
435}
436
437/// Serves the framework HTTP surface until `shutdown` resolves, then drains.
438///
439/// It serves the module-free framework router (health, `/openapi.json`, `/docs`)
440/// under the [`HttpSecurity`] posture read from the environment into
441/// [`ServerConfig::security`] (CORS allowlist, trusted-proxy switch, rate limit),
442/// and — when [`ServerConfig::oidc`] is set — the OIDC/JWT authentication layer.
443/// A real service does not call this — its `apps/<name>-api` composition root
444/// builds its own router (merging its modules' generated controllers) and calls
445/// [`serve_router`] directly. This entrypoint is the module-free skeleton the
446/// binary runs; the example composition (`accounts`) lives in this crate's tests.
447///
448/// The lifecycle, in order:
449///
450/// 1. A fresh [`Health`] in [`Starting`](seiva_http::HealthState::Starting), so
451/// `/health/ready` answers `503` until the socket is live.
452/// 2. Binds a [`TcpListener`] to [`ServerConfig::http_addr`]; a bind failure is
453/// [`ServeError::Bind`].
454/// 3. Flips `Health` [`Starting -> Ready`](seiva_http::Health::set_ready) once the
455/// socket is listening.
456/// 4. Serves with a graceful-shutdown future that, once `shutdown` resolves, flips
457/// `Health` to [`Draining`](seiva_http::Health::set_draining) *before* the
458/// server stops accepting, so the process leaves rotation while in-flight
459/// requests finish.
460///
461/// # Errors
462///
463/// Returns [`ServeError::Bind`] if the listener cannot bind, or
464/// [`ServeError::Serve`] if serving fails.
465pub async fn serve(
466 config: ServerConfig,
467 // `'static` is required by `axum::serve(..).with_graceful_shutdown(..)`: the
468 // graceful-shutdown future is held by the server task for its whole life.
469 shutdown: impl Future<Output = ()> + Send + 'static,
470) -> Result<(), ServeError> {
471 // Apply the validated error-detail policy process-wide before serving, so a
472 // `500` honours `SEIVA_EXPOSE_ERROR_DETAILS` (off in production — the config
473 // guard above enforces it). Fail-closed by default: a composition root that
474 // drives `serve_router` directly and forgets this still hides internal errors.
475 seiva_http::problem::set_expose_error_details(config.expose_error_details);
476 let health = Health::starting();
477 let authenticator = build_authenticator(&config)?;
478 let app = router_with_auth(health.clone(), &config.security, authenticator);
479 serve_router(config.http_addr, app, health, shutdown).await
480}
481
482/// Serves an arbitrary application `router` on `addr` with the framework's
483/// lifecycle: bind, flip `health` [`Starting -> Ready`](seiva_http::Health::set_ready)
484/// once the socket is live, and on `shutdown` flip to
485/// [`Draining`](seiva_http::Health::set_draining) *before* the server stops
486/// accepting so `/health/ready` goes `503` while in-flight requests finish.
487///
488/// This is the loop a generated project's `apps/<name>-api` composition root
489/// calls: it builds its own router (`seiva_http::router(health.clone())` merged
490/// with its modules' routers) and hands it here, instead of writing its own
491/// `main`. The demo [`serve`] is exactly this over the built-in application.
492///
493/// The peer `SocketAddr` is installed as a request extension
494/// (`into_make_service_with_connect_info`), so `seiva_http`'s rate limiter keys
495/// on the real client IP.
496///
497/// # Errors
498///
499/// Returns [`ServeError::Bind`] if the listener cannot bind, or
500/// [`ServeError::Serve`] if serving fails.
501pub async fn serve_router(
502 addr: SocketAddr,
503 router: Router,
504 health: Health,
505 shutdown: impl Future<Output = ()> + Send + 'static,
506) -> Result<(), ServeError> {
507 // Fail fast on a route-prefix collision (two facades pluralising to the same
508 // `(version, resource)`): a clear startup error beats the bare `Router::merge`
509 // panic that would otherwise fire while mounting the modules.
510 let collisions = seiva_http::route_collisions();
511 if !collisions.is_empty() {
512 return Err(ServeError::RouteCollision(collisions));
513 }
514
515 let listener = TcpListener::bind(addr).await.map_err(ServeError::Bind)?;
516
517 // The socket is live: Starting -> Ready, so /health/ready passes.
518 health.set_ready();
519
520 let draining = {
521 let health = health.clone();
522 async move {
523 shutdown.await;
524 health.set_draining();
525 }
526 };
527
528 axum::serve(
529 listener,
530 router.into_make_service_with_connect_info::<SocketAddr>(),
531 )
532 .with_graceful_shutdown(draining)
533 .await
534 .map_err(ServeError::Serve)?;
535
536 Ok(())
537}
538
539#[cfg(feature = "mtls")]
540pub mod mtls;
541#[cfg(feature = "mtls")]
542pub use mtls::{serve_router_mtls, MtlsFiles};
543
544/// A Seiva service with **opt-in observability** (ADR 0027).
545///
546/// [`serve`] is the zero-config path; this builder adds the exporters a service
547/// opts into, wired **only here at the composition root** so the default build
548/// links none. A `Server` with neither hook set behaves exactly like [`serve`]:
549/// today's JSON logs, no exporter.
550///
551/// - `with_metrics` (feature `metrics`) serves a Prometheus `/metrics` scrape
552/// surface on a **separate** bind — an admin port, off the public API surface
553/// and exempt from auth/rate-limiting like the health probes. The library crates
554/// already record against the `metrics` facade (`seiva_http::track_metrics`);
555/// this installs the recorder that gives those records a backend.
556/// - `with_tracing` (feature `tracing-otlp`) installs the OpenTelemetry OTLP span
557/// exporter and the W3C trace-context propagator.
558///
559/// # Example
560///
561/// ```no_run
562/// # #[cfg(feature = "metrics")]
563/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
564/// use seiva_server::{Server, ServerConfig};
565///
566/// let config = ServerConfig::from_process_env()?;
567/// Server::new(config)
568/// .with_metrics("127.0.0.1:9090".parse()?)
569/// .serve(async {})
570/// .await?;
571/// # Ok(())
572/// # }
573/// ```
574#[derive(Debug)]
575pub struct Server {
576 config: ServerConfig,
577 /// The Prometheus `/metrics` bind, when metrics are opted in.
578 #[cfg(feature = "metrics")]
579 metrics_addr: Option<SocketAddr>,
580 /// The OTLP tracing configuration, when tracing is opted in.
581 #[cfg(feature = "tracing-otlp")]
582 tracing: Option<seiva_observability::tracing::TracingConfig>,
583}
584
585impl Server {
586 /// A server over `config` with no observability exporter opted in (equivalent
587 /// to [`serve`] until a hook is added).
588 #[must_use]
589 pub fn new(config: ServerConfig) -> Self {
590 Self {
591 config,
592 #[cfg(feature = "metrics")]
593 metrics_addr: None,
594 #[cfg(feature = "tracing-otlp")]
595 tracing: None,
596 }
597 }
598
599 /// Opt in to the Prometheus `/metrics` exporter, served on `addr` — a
600 /// **separate** bind from the public API (ADR 0027). Installs the process-wide
601 /// recorder at [`serve`](Server::serve) time.
602 #[cfg(feature = "metrics")]
603 #[must_use]
604 pub fn with_metrics(mut self, addr: SocketAddr) -> Self {
605 self.metrics_addr = Some(addr);
606 self
607 }
608
609 /// Opt in to OpenTelemetry OTLP tracing (ADR 0027). The exporter endpoint,
610 /// protocol and sampling come from the standard `OTEL_*` environment; `config`
611 /// carries only the in-code overrides (the service name).
612 ///
613 /// When tracing is opted in, the OTLP subscriber is installed at
614 /// [`serve`](Server::serve) time, so the binary must **not** also call
615 /// [`observability::init`] (the first global subscriber wins).
616 #[cfg(feature = "tracing-otlp")]
617 #[must_use]
618 pub fn with_tracing(mut self, config: seiva_observability::tracing::TracingConfig) -> Self {
619 self.tracing = Some(config);
620 self
621 }
622
623 /// Serves the framework HTTP surface until `shutdown` resolves, alongside the
624 /// opted-in exporters, then drains.
625 ///
626 /// The one `shutdown` is fanned out to the main server and the (optional)
627 /// metrics server, so a single signal stops both. The main server is exactly
628 /// [`serve`]; the metrics server runs on its own task and bind.
629 ///
630 /// # Errors
631 ///
632 /// Returns [`ServeError::Observability`] if an opted-in exporter cannot be
633 /// installed, or the same errors as [`serve`] for the main server.
634 pub async fn serve(
635 self,
636 shutdown: impl Future<Output = ()> + Send + 'static,
637 ) -> Result<(), ServeError> {
638 // Fan one shutdown out to every server. `watch` holds the latch; a task
639 // flips it when `shutdown` resolves.
640 let (tx, rx) = tokio::sync::watch::channel(false);
641 tokio::spawn(async move {
642 shutdown.await;
643 let _ = tx.send(true);
644 });
645
646 // Install the OTLP tracing pipeline before serving, replacing the default
647 // JSON-only subscriber. Held until after serving so its batch exporter can
648 // flush the span tail on shutdown.
649 #[cfg(feature = "tracing-otlp")]
650 let tracing_provider = match self.tracing {
651 Some(config) => Some(
652 seiva_observability::tracing::init(config)
653 .map_err(|e| ServeError::Observability(e.to_string()))?,
654 ),
655 None => None,
656 };
657
658 // The Prometheus exporter on its own bind, sharing the shutdown latch. The
659 // recorder is process-global and install-once; a failure (already present,
660 // or a bad bucket config) fails the boot rather than serving blind.
661 #[cfg(feature = "metrics")]
662 if let Some(metrics_addr) = self.metrics_addr {
663 let handle = seiva_observability::metrics::install_recorder().map_err(|e| {
664 ServeError::Observability(format!("installing the Prometheus recorder: {e}"))
665 })?;
666 let mut metrics_rx = rx.clone();
667 let metrics_shutdown = async move {
668 let _ = metrics_rx.wait_for(|stop| *stop).await;
669 };
670 tokio::spawn(async move {
671 if let Err(error) = seiva_observability::metrics::serve_metrics(
672 metrics_addr,
673 handle,
674 metrics_shutdown,
675 )
676 .await
677 {
678 tracing::error!(%error, "the Prometheus /metrics exporter failed");
679 }
680 });
681 tracing::info!(addr = %metrics_addr, "serving Prometheus /metrics on a separate bind");
682 }
683
684 // The main server derives its shutdown from the same latch.
685 let mut main_rx = rx;
686 let main_shutdown = async move {
687 let _ = main_rx.wait_for(|stop| *stop).await;
688 };
689 let result = serve(self.config, main_shutdown).await;
690
691 // Flush and shut the span exporter down so the trailing spans are exported.
692 #[cfg(feature = "tracing-otlp")]
693 if let Some(provider) = tracing_provider {
694 let _ = provider.shutdown();
695 }
696
697 result
698 }
699}
700
701/// Resolves once the process is asked to shut down: Ctrl-C (SIGINT) on every
702/// platform, or `SIGTERM` on unix (the signal an orchestrator sends to stop a
703/// container). A generated `apps/<name>-api` feeds this to
704/// [`serve_router`] so its service drains gracefully on `delonix`/Kubernetes
705/// termination without reimplementing signal handling.
706pub async fn shutdown_signal() {
707 #[cfg(unix)]
708 {
709 use tokio::signal::unix::{signal, SignalKind};
710
711 let mut term = signal(SignalKind::terminate()).expect("install a SIGTERM handler");
712 tokio::select! {
713 _ = tokio::signal::ctrl_c() => {}
714 _ = term.recv() => {}
715 }
716 }
717
718 #[cfg(not(unix))]
719 {
720 let _ = tokio::signal::ctrl_c().await;
721 }
722}
723
724/// The default interval between background worker passes. A pass that drains a
725/// backlog could poll faster; the demonstration pass has no backlog, so it idles
726/// at this cadence until shutdown.
727pub const DEFAULT_WORKER_INTERVAL: Duration = Duration::from_secs(30);
728
729/// The demonstration worker pass: a no-op that processes nothing and never fails.
730///
731/// It exists so the worker host has a real pass to drive today, DORM-free. The
732/// real transactional-outbox relay pass (`seiva-outbox-relay`, DORM-git-coupled)
733/// is injected in its place behind the framework's `dorm` feature once the
734/// private-repo CI token exists — this crate does not wire DORM now.
735///
736/// # Errors
737///
738/// Never errors; the [`PortResult`] return type matches the shape
739/// [`run_worker`] drives.
740pub async fn demo_pass() -> PortResult<u64> {
741 Ok(0)
742}
743
744/// Runs the background worker host until `shutdown` resolves, returning one
745/// [`WorkerReport`] per worker.
746///
747/// Today it drives a single worker over [`demo_pass`] through
748/// [`seiva::worker::run_worker`], which owns the loop, the interval, the
749/// shutdown check and the metrics. A resolved `shutdown` ends the host within one
750/// pass.
751///
752/// To add real passes (e.g. the DORM outbox relay once the `dorm` feature is
753/// wired), fan a single shutdown out to each worker over a `watch` channel and
754/// collect their reports — the host shape is otherwise unchanged.
755pub async fn run_workers(shutdown: impl Future<Output = ()> + Send) -> Vec<WorkerReport> {
756 let config = WorkerConfig::new("demo-noop", DEFAULT_WORKER_INTERVAL);
757 let report = run_worker(config, shutdown, demo_pass).await;
758 vec![report]
759}
760
761/// Runs a background worker that purges expired idempotency records (ADR 0011) on
762/// `config.interval` until `shutdown` resolves. Each pass runs
763/// [`IdempotencyStore::purge_expired`](seiva::ports::IdempotencyStore::purge_expired)
764/// inside a [`UnitOfWork`](seiva::ports::UnitOfWork) transaction — the
765/// DORM store's purge needs an open session — and reports how many it removed.
766///
767/// The composition root wires it next to [`serve`]; both share one `shutdown`.
768/// The `store` and `uow` are shared (`Arc`) so each pass owns its own clones and
769/// the loop never borrows across awaits.
770pub async fn run_idempotency_purge<U, St, Sh>(
771 uow: std::sync::Arc<U>,
772 store: std::sync::Arc<St>,
773 config: WorkerConfig,
774 shutdown: Sh,
775) -> WorkerReport
776where
777 U: seiva::ports::UnitOfWork + 'static,
778 St: seiva::ports::IdempotencyStore + 'static,
779 Sh: Future<Output = ()>,
780{
781 run_worker(config, shutdown, move || {
782 let uow = std::sync::Arc::clone(&uow);
783 let store = std::sync::Arc::clone(&store);
784 async move {
785 uow.transaction(seiva::ports::Scope::Global, move || async move {
786 store.purge_expired().await
787 })
788 .await
789 }
790 })
791 .await
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797 use axum::body::Body;
798 use axum::http::{Request, StatusCode};
799 use seiva_config::load_from;
800 use std::collections::HashMap;
801 use tower::ServiceExt; // for `oneshot`
802
803 /// The composition a real `apps/<name>-api` performs, exercised here with the
804 /// `accounts` example (a dev-dependency, so it never enters a release build or
805 /// blocks publishing): the framework router merged with the module's generated
806 /// controller router wired to the in-memory repository.
807 fn application(health: Health) -> Router {
808 let accounts =
809 accounts_interface::accounts_router(accounts_interface::AccountsController::new(
810 accounts_infrastructure::InMemoryCredentialRepository::new(),
811 ));
812 seiva_http::router(health).merge(accounts)
813 }
814
815 fn map(pairs: &[(&str, &str)]) -> HashMap<String, String> {
816 pairs
817 .iter()
818 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
819 .collect()
820 }
821
822 // --- Config: parsing from an explicit map (no env races) ----------------
823
824 #[test]
825 fn config_defaults_to_loopback_8080_and_development() {
826 let cfg: ServerConfig = load_from(map(&[])).expect("empty env is a valid dev config");
827 assert_eq!(cfg.http_addr, ServerConfig::default_http_addr());
828 assert_eq!(cfg.http_addr.to_string(), "127.0.0.1:8080");
829 assert!(cfg.env.is_development());
830 assert!(!cfg.expose_error_details);
831 }
832
833 #[test]
834 fn config_http_addr_var_wins_over_port() {
835 // Both set: SEIVA_HTTP_ADDR takes precedence.
836 let cfg: ServerConfig =
837 load_from(map(&[(HTTP_ADDR_VAR, "0.0.0.0:9000"), (PORT_VAR, "1234")]))
838 .expect("valid address");
839 assert_eq!(cfg.http_addr.to_string(), "0.0.0.0:9000");
840 }
841
842 #[test]
843 fn config_port_fallback_binds_all_interfaces() {
844 let cfg: ServerConfig = load_from(map(&[(PORT_VAR, "8081")])).expect("valid port fallback");
845 assert_eq!(cfg.http_addr.to_string(), "0.0.0.0:8081");
846 }
847
848 #[test]
849 fn config_rejects_unparseable_address() {
850 let err = load_from::<ServerConfig>(map(&[(HTTP_ADDR_VAR, "not-an-addr")])).unwrap_err();
851 assert!(err.problems()[0].contains(HTTP_ADDR_VAR));
852 }
853
854 #[test]
855 fn config_production_guard_rejects_expose_error_details() {
856 let err = load_from::<ServerConfig>(map(&[
857 ("APP_ENV", "production"),
858 (EXPOSE_ERROR_DETAILS_VAR, "true"),
859 ]))
860 .unwrap_err();
861 assert_eq!(err.problems().len(), 1);
862 assert!(err.problems()[0].contains(EXPOSE_ERROR_DETAILS_VAR));
863 assert!(err.problems()[0].contains("production"));
864 }
865
866 #[test]
867 fn config_development_allows_the_same_shortcut() {
868 let cfg: ServerConfig = load_from(map(&[
869 ("APP_ENV", "development"),
870 (EXPOSE_ERROR_DETAILS_VAR, "true"),
871 ]))
872 .expect("dev permits the shortcut");
873 assert!(cfg.expose_error_details);
874 assert!(cfg.env.is_development());
875 }
876
877 #[test]
878 fn security_defaults_to_the_secure_baseline() {
879 let cfg: ServerConfig = load_from(map(&[])).expect("empty env is valid");
880 assert!(cfg.security.cors_allowed_origins.is_empty());
881 assert!(!cfg.security.trust_forwarded_for);
882 assert_eq!(cfg.security.rate_limit, Some(RateLimit::default()));
883 }
884
885 #[test]
886 fn security_reads_cors_trust_proxy_and_rate_limit_from_env() {
887 let cfg: ServerConfig = load_from(map(&[
888 (
889 CORS_ALLOWED_ORIGINS_VAR,
890 " https://app.example.com , https://admin.example.com ,",
891 ),
892 (TRUST_FORWARDED_FOR_VAR, "true"),
893 (RATE_LIMIT_MAX_REQUESTS_VAR, "100"),
894 (RATE_LIMIT_WINDOW_SECS_VAR, "30"),
895 ]))
896 .expect("valid security config");
897
898 // Trimmed, and the trailing empty segment dropped.
899 assert_eq!(
900 cfg.security.cors_allowed_origins,
901 vec![
902 "https://app.example.com".to_string(),
903 "https://admin.example.com".to_string()
904 ]
905 );
906 assert!(cfg.security.trust_forwarded_for);
907 assert_eq!(
908 cfg.security.rate_limit,
909 Some(RateLimit {
910 max_requests: 100,
911 window: Duration::from_secs(30)
912 })
913 );
914 }
915
916 #[test]
917 fn oidc_is_absent_by_default_and_parsed_when_fully_set() {
918 let none: ServerConfig = load_from(map(&[])).expect("empty env");
919 assert!(none.oidc.is_none());
920
921 let cfg: ServerConfig = load_from(map(&[
922 (OIDC_JWKS_FILE_VAR, "/etc/seiva/jwks.json"),
923 (OIDC_ISSUER_VAR, "https://id.example.com/"),
924 (OIDC_AUDIENCE_VAR, "seiva-api"),
925 (OIDC_TENANT_CLAIM_VAR, "org_id"),
926 ]))
927 .expect("full oidc config");
928 let oidc = cfg.oidc.expect("present");
929 assert_eq!(oidc.jwks_file, "/etc/seiva/jwks.json");
930 assert_eq!(oidc.issuer, "https://id.example.com/");
931 assert_eq!(oidc.audience, "seiva-api");
932 assert_eq!(oidc.tenant_claim.as_deref(), Some("org_id"));
933 assert!(oidc.permission_claim.is_none());
934 }
935
936 #[test]
937 fn a_partial_oidc_config_fails_the_boot() {
938 // Only the issuer set: the service must not boot half-authenticated.
939 let err = load_from::<ServerConfig>(map(&[(OIDC_ISSUER_VAR, "https://id.example.com/")]))
940 .unwrap_err();
941 let problems = err.problems().join(" ");
942 assert!(problems.contains(OIDC_JWKS_FILE_VAR));
943 assert!(problems.contains(OIDC_AUDIENCE_VAR));
944 }
945
946 #[test]
947 fn rate_limit_is_disabled_by_a_zero_budget() {
948 let cfg: ServerConfig =
949 load_from(map(&[(RATE_LIMIT_MAX_REQUESTS_VAR, "0")])).expect("zero disables");
950 assert_eq!(cfg.security.rate_limit, None);
951 }
952
953 #[test]
954 fn config_rejects_unparseable_rate_limit() {
955 let err =
956 load_from::<ServerConfig>(map(&[(RATE_LIMIT_MAX_REQUESTS_VAR, "lots")])).unwrap_err();
957 assert!(err.problems()[0].contains(RATE_LIMIT_MAX_REQUESTS_VAR));
958 }
959
960 // --- HTTP surface: driven via the router, no live port -----------------
961
962 #[tokio::test]
963 async fn health_live_is_ok_and_ready_tracks_the_lifecycle() {
964 let health = Health::starting();
965 let app = seiva_http::router(health.clone());
966
967 // /health/live is 200 in every state.
968 let res = app
969 .clone()
970 .oneshot(
971 Request::builder()
972 .uri("/health/live")
973 .body(Body::empty())
974 .unwrap(),
975 )
976 .await
977 .unwrap();
978 assert_eq!(res.status(), StatusCode::OK);
979
980 // /health/ready is 503 while Starting...
981 let res = app
982 .clone()
983 .oneshot(
984 Request::builder()
985 .uri("/health/ready")
986 .body(Body::empty())
987 .unwrap(),
988 )
989 .await
990 .unwrap();
991 assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
992
993 // ...and 200 once Ready (the clone shares the atomic serve() flips).
994 health.set_ready();
995 let res = app
996 .oneshot(
997 Request::builder()
998 .uri("/health/ready")
999 .body(Body::empty())
1000 .unwrap(),
1001 )
1002 .await
1003 .unwrap();
1004 assert_eq!(res.status(), StatusCode::OK);
1005 }
1006
1007 // --- accounts module: the merged app serves the real use case ----------
1008
1009 /// The merged application serves the `accounts` create route: an anonymous
1010 /// caller is denied with an RFC 9457 `403`, and a tenanted caller holding
1011 /// `accounts.create` with a valid body succeeds (`200`, the generic write
1012 /// branch) with a secret-free user. The caller carries a tenant so the
1013 /// use case can derive its `Scope` (SG1 fail-closed). This proves `serve`
1014 /// mounts the real module, not just the demo.
1015 #[tokio::test]
1016 async fn merged_app_serves_the_accounts_create_route() {
1017 let app = application(Health::starting());
1018
1019 // Without the permission: 403 problem.
1020 let denied = app
1021 .clone()
1022 .oneshot(
1023 Request::builder()
1024 .method("POST")
1025 .uri("/v1/accounts/create_user")
1026 .header("content-type", "application/json")
1027 .body(Body::from(r#"{"username":"alice","password":"hunter2"}"#))
1028 .unwrap(),
1029 )
1030 .await
1031 .unwrap();
1032 assert_eq!(denied.status(), StatusCode::FORBIDDEN);
1033
1034 // With the permission and a valid body: 200 and a secret-free user.
1035 let ok = app
1036 .oneshot(
1037 Request::builder()
1038 .method("POST")
1039 .uri("/v1/accounts/create_user")
1040 .header("content-type", "application/json")
1041 .extension(std::sync::Arc::new(seiva_http::Principal::in_tenant(
1042 "user",
1043 "acme",
1044 ["accounts.create"],
1045 )))
1046 .body(Body::from(r#"{"username":"alice","password":"hunter2"}"#))
1047 .unwrap(),
1048 )
1049 .await
1050 .unwrap();
1051 assert_eq!(ok.status(), StatusCode::OK);
1052 let bytes = axum::body::to_bytes(ok.into_body(), usize::MAX)
1053 .await
1054 .unwrap();
1055 let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1056 assert_eq!(body["username"], "alice");
1057 let rendered = body.to_string();
1058 assert!(
1059 !rendered.contains("hunter2") && !rendered.contains("$argon2id$"),
1060 "no secret must appear in the response: {rendered}"
1061 );
1062 }
1063
1064 // --- facade discovery: /openapi.json lists every mounted module ---------
1065
1066 /// The served `/openapi.json` documents the mounted `accounts` module,
1067 /// proving link-time discovery (`registered_facades`) picks up every
1068 /// `#[seiva::facade]` linked into the binary with no hand-maintained list
1069 /// (OWASP API9). The runtime itself is demo-free, so `accounts` is the only
1070 /// facade here (it comes from the test's dev-dependency composition).
1071 #[tokio::test]
1072 async fn openapi_discovers_the_mounted_facade() {
1073 let app = application(Health::starting());
1074 let res = app
1075 .oneshot(
1076 Request::builder()
1077 .uri("/openapi.json")
1078 .body(Body::empty())
1079 .unwrap(),
1080 )
1081 .await
1082 .unwrap();
1083 assert_eq!(res.status(), StatusCode::OK);
1084 let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
1085 .await
1086 .unwrap();
1087 let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1088 let paths = doc["paths"].as_object().expect("paths object");
1089 assert!(
1090 paths.keys().any(|p| p.contains("/accounts")),
1091 "the mounted accounts module must be discovered and documented: {:?}",
1092 paths.keys().collect::<Vec<_>>()
1093 );
1094 }
1095
1096 // --- serve: binds an ephemeral port, drains on a resolved shutdown ------
1097
1098 #[tokio::test]
1099 async fn serve_binds_ephemeral_and_returns_on_resolved_shutdown() {
1100 let config = ServerConfig {
1101 env: AppEnv::Development,
1102 // Port 0: the OS assigns a free ephemeral port, so the test never
1103 // races another on a fixed port.
1104 http_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
1105 expose_error_details: false,
1106 security: HttpSecurity::default(),
1107 oidc: None,
1108 };
1109 // An already-resolved shutdown: serve binds, flips Ready, immediately
1110 // drains and returns Ok — no fixed port, no running clock.
1111 serve(config, async {})
1112 .await
1113 .expect("serve binds and drains cleanly");
1114 }
1115
1116 // --- worker host: stops on a resolved shutdown, reports zero processed --
1117
1118 #[tokio::test]
1119 async fn run_workers_stops_and_reports_the_demo_pass() {
1120 let reports = run_workers(async {}).await;
1121 assert_eq!(reports.len(), 1);
1122 let report = &reports[0];
1123 assert!(report.passes >= 1, "at least one pass runs before shutdown");
1124 assert_eq!(report.processed, 0, "the demo pass processes nothing");
1125 assert_eq!(report.errors, 0, "the demo pass never fails");
1126 }
1127
1128 #[tokio::test]
1129 async fn idempotency_purge_worker_runs_passes_and_never_fails() {
1130 use seiva_testing::{InMemoryIdempotencyStore, InMemoryUnitOfWork};
1131 use std::sync::Arc;
1132
1133 let uow = Arc::new(InMemoryUnitOfWork::new());
1134 let store = Arc::new(InMemoryIdempotencyStore::new());
1135 // Zero interval + immediate shutdown: it runs a pass, then stops.
1136 let config = WorkerConfig::new("idempotency-purge", std::time::Duration::ZERO);
1137 let report = run_idempotency_purge(uow, store, config, async {}).await;
1138 assert!(report.passes >= 1, "the purge worker ran at least one pass");
1139 assert_eq!(report.errors, 0, "purge must not fail");
1140 }
1141}