toolkit/runtime/readiness.rs
1//! Framework-managed readiness state for the `OoP` bootstrap (`cpt-cf-fr-eventual-readiness`).
2//!
3//! An `OoP` gear becomes *live* the moment its HTTP server binds (`/healthz`),
4//! but only becomes *ready* (`/readyz`) once startup is complete, every critical
5//! dependency has been resolved, **and** the gear's registered healthchecks
6//! report it can serve traffic (Spring Boot-style health groups per
7//! `cpt-cf-fr-eventual-readiness`).
8//!
9//! Readiness reuses the framework's standard healthcheck mechanism
10//! ([`crate::healthcheck`]): a gear expresses readiness once, via
11//! [`RestApiCapability::healthcheck`](crate::contracts::RestApiCapability::healthcheck),
12//! and it is honored identically whether the gear is hosted in-process by the
13//! `api-gateway` or run `OoP`. This module layers the three `OoP`-only concerns
14//! the gateway path lacks — startup completion, critical-dependency resolution
15//! gating, and the graceful-drain readiness flip — on top of that shared
16//! healthcheck report.
17//!
18//! The healthcheck report itself is fanned out concurrently, timeout-bounded,
19//! panic-isolated, and cached inside the [`RestHealthcheckRegistry`], so a burst
20//! of probe traffic cannot storm the registered checks. The dependency and
21//! draining state layered on top are cheap live reads.
22
23use std::collections::BTreeMap;
24use std::sync::Arc;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::time::Duration;
27
28use parking_lot::RwLock;
29
30use crate::healthcheck::{HealthcheckReport, HealthcheckStatus, RestHealthcheckRegistry};
31
32/// Sticky, dynamic dependency-resolution tracker shared across serving modes
33/// (in-process host and `OoP`).
34///
35/// **Passive:** the resolution loop / consumer-wiring feeds it
36/// ([`register_dep`](Self::register_dep), [`mark_resolved`](Self::mark_resolved));
37/// it never runs a check itself — unlike the active
38/// [`Healthcheck`](crate::healthcheck::Healthcheck) registry. It answers exactly
39/// one question — *are all declared dependencies resolved?* — and carries the
40/// process-wide draining flag both `/readyz` front-ends consult (the in-process
41/// [`ReadinessHealthcheck`] leaf check and the `OoP` [`ReadinessState`]
42/// aggregator).
43///
44/// Startup-gating and **sticky**: once a dependency is resolved it stays
45/// resolved. A provider vanishing later does NOT revert `/readyz` — that is
46/// runtime churn, handled lazily by the directory-resolving client at call time
47/// (liveness is `/healthz`, not `/readyz`).
48#[derive(Debug, Default)]
49pub struct DependencyChecker {
50 /// Graceful-shutdown flag; when set, `/readyz` reports `503` regardless of deps.
51 draining: AtomicBool,
52 /// `dep_gear` → resolved. Populated by the proxy-wiring / consumer-wiring
53 /// phase from each `#[toolkit::consumes]` registration; flipped `true` once
54 /// the provider endpoint resolves.
55 deps: RwLock<BTreeMap<String, bool>>,
56}
57
58impl DependencyChecker {
59 /// Create an empty checker (no deps → trivially resolved / ready).
60 #[must_use]
61 pub fn new() -> Self {
62 Self::default()
63 }
64
65 /// Declare a consumed dependency that gates readiness (idempotent; keeps an
66 /// already-resolved entry resolved).
67 pub fn register_dep(&self, dep_gear: impl Into<String>) {
68 self.deps.write().entry(dep_gear.into()).or_insert(false);
69 }
70
71 /// Mark a dependency unresolved again, registering it if unknown: a
72 /// consumer wired later needs a target that is not resolved yet.
73 pub fn mark_unresolved(&self, dep_gear: &str) {
74 self.deps.write().insert(dep_gear.to_owned(), false);
75 }
76
77 /// Mark a previously-registered dependency as resolved. Unknown names are
78 /// ignored. Returns `true` only on the `false → true` transition (so callers
79 /// can log the resolution exactly once).
80 pub fn mark_resolved(&self, dep_gear: &str) -> bool {
81 if let Some(resolved) = self.deps.write().get_mut(dep_gear) {
82 let was = *resolved;
83 *resolved = true;
84 !was
85 } else {
86 false
87 }
88 }
89
90 /// Names of consumed dependency gears not yet resolved.
91 #[must_use]
92 pub fn unresolved_deps(&self) -> Vec<String> {
93 self.deps
94 .read()
95 .iter()
96 .filter(|(_, resolved)| !**resolved)
97 .map(|(name, _)| name.clone())
98 .collect()
99 }
100
101 /// Whether every declared dependency has resolved (or none were declared).
102 #[must_use]
103 pub fn all_resolved(&self) -> bool {
104 self.deps.read().values().all(|resolved| *resolved)
105 }
106
107 /// Begin (or clear) draining. Setting it makes `/readyz` report `503`
108 /// regardless of dependency state so upstreams drain the instance.
109 pub fn set_draining(&self, draining: bool) {
110 self.draining.store(draining, Ordering::SeqCst);
111 }
112
113 /// Whether shutdown has begun.
114 #[must_use]
115 pub fn is_draining(&self) -> bool {
116 self.draining.load(Ordering::SeqCst)
117 }
118
119 /// Whether the process is serving traffic: all deps resolved and not draining.
120 #[must_use]
121 pub fn is_ready(&self) -> bool {
122 !self.is_draining() && self.all_resolved()
123 }
124}
125
126/// Bridges a [`DependencyChecker`] into the
127/// [`RestHealthcheckRegistry`](crate::healthcheck::RestHealthcheckRegistry) as a
128/// single leaf check, for the **in-process** (`api-gateway`-hosted) `/readyz`
129/// path where readiness is one check among many in a shared registry.
130///
131/// The gateway `/readyz` reports `503` whenever any registered check is
132/// `Unhealthy`, so mapping draining / unresolved-deps → `Unhealthy` gates the
133/// probe exactly as ADR-0007 intends. `/healthz` (liveness) is a static handler
134/// and is unaffected. The registry caches reports (~2s), so a readiness/drain
135/// transition surfaces on `/readyz` with up to that lag.
136///
137/// The `OoP` path instead uses [`ReadinessState::evaluate`] directly (it owns
138/// its registry), so this leaf adapter is not used there — avoiding the
139/// re-aggregation recursion that owning the same registry would cause.
140pub struct ReadinessHealthcheck {
141 deps: Arc<DependencyChecker>,
142}
143
144impl ReadinessHealthcheck {
145 /// Wrap the shared dependency checker.
146 #[must_use]
147 pub fn new(deps: Arc<DependencyChecker>) -> Self {
148 Self { deps }
149 }
150}
151
152#[async_trait::async_trait]
153impl crate::healthcheck::Healthcheck for ReadinessHealthcheck {
154 fn name(&self) -> &'static str {
155 "readiness"
156 }
157
158 async fn check(&self) -> crate::healthcheck::HealthcheckResult {
159 use crate::healthcheck::HealthcheckResult;
160 if self.deps.is_draining() {
161 return HealthcheckResult::unhealthy("draining").with_code("draining");
162 }
163 let unresolved = self.deps.unresolved_deps();
164 if unresolved.is_empty() {
165 HealthcheckResult::healthy()
166 } else {
167 HealthcheckResult::unhealthy(format!(
168 "unresolved dependencies: {}",
169 unresolved.join(", ")
170 ))
171 .with_code("deps_unresolved")
172 }
173 }
174}
175
176/// Default per-check timeout for readiness healthchecks.
177///
178/// Matches the `api-gateway` `healthcheck_timeout_ms` default so a gear's
179/// healthcheck behaves identically in-process and `OoP`.
180pub const DEFAULT_HEALTHCHECK_TIMEOUT: Duration = Duration::from_millis(500);
181
182/// Lifecycle state reported on `/readyz` (`cpt-cf-adr-eventual-readiness`).
183///
184/// Serialized lowercase; the four variants are a stable wire contract.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
186#[serde(rename_all = "lowercase")]
187pub enum ReadinessLifecycle {
188 /// Not yet able to serve — startup is not complete, critical deps are
189 /// unresolved, or a healthcheck is `Unhealthy`. Maps to `503`.
190 Starting,
191 /// Fully serving traffic. Maps to `200`.
192 Ready,
193 /// Serving with reduced functionality — a healthcheck reported `Degraded`
194 /// (e.g. an optional backend is down but a fallback is acceptable). Kept in
195 /// rotation: maps to `200`.
196 Degraded,
197 /// Graceful shutdown in progress; upstreams should stop routing. Maps to
198 /// `503`.
199 Draining,
200}
201
202/// The aggregate readiness report rendered as the `/readyz` response body.
203///
204/// Readiness still depends on the aggregated [`HealthcheckReport`] internally,
205/// but the detailed per-component report is intentionally not echoed here; it
206/// belongs on the separate `/health` endpoint (see `oop_serve.rs`).
207#[derive(Debug, Clone, serde::Serialize)]
208pub struct ReadinessReport {
209 /// Lifecycle state — the primary readiness signal (`cpt-cf-adr-eventual-readiness`).
210 pub state: ReadinessLifecycle,
211 /// Whether the gear is ready to receive traffic (`true` → `200`, else `503`).
212 /// Convenience mirror of `state ∈ {ready, degraded}` for probes/clients that
213 /// do not want to know the `state → status` mapping.
214 pub ready: bool,
215 /// Critical dependencies not yet resolved via `DirectoryService` / DNS.
216 /// Non-empty only while `starting`. Omitted from the body when empty.
217 #[serde(skip_serializing_if = "Vec::is_empty")]
218 pub unresolved_deps: Vec<String>,
219}
220
221/// Shared, framework-owned readiness state for an `OoP` gear instance.
222///
223/// Created by the `OoP` bootstrap with the gear's critical dependency names and
224/// a shared [`RestHealthcheckRegistry`] (populated from each gear's
225/// [`RestApiCapability::healthcheck`](crate::contracts::RestApiCapability::healthcheck)).
226/// Cloned as an `Arc` into the probe router and the dependency-resolution task.
227pub struct ReadinessState {
228 /// Shared dependency-resolution core (deps + draining). Owned here for the
229 /// `OoP` aggregator; the in-process path shares the same [`DependencyChecker`]
230 /// via [`Self::dependency_checker`].
231 deps: Arc<DependencyChecker>,
232 /// Whether the gear has finished startup and is actually serving traffic.
233 /// Remains `false` until the bootstrap publishes the composed routes.
234 startup_complete: AtomicBool,
235 /// Shared gear healthcheck registry; supplies the "custom checks" dimension
236 /// of readiness (fan-out, timeout, panic isolation, and caching live here).
237 healthchecks: Arc<RestHealthcheckRegistry>,
238 /// Per-check timeout passed to [`RestHealthcheckRegistry::report`].
239 check_timeout: Duration,
240}
241
242impl std::fmt::Debug for ReadinessState {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244 f.debug_struct("ReadinessState")
245 .field("unresolved_deps", &self.deps.unresolved_deps())
246 .field("draining", &self.deps.is_draining())
247 .field(
248 "startup_complete",
249 &self.startup_complete.load(Ordering::Relaxed),
250 )
251 .field("check_timeout", &self.check_timeout)
252 .finish_non_exhaustive()
253 }
254}
255
256impl ReadinessState {
257 /// Create a new readiness state seeded with the gear's critical dependency
258 /// names and the shared healthcheck registry. All listed deps start
259 /// unresolved; the gear is not ready until startup is complete, each dep is
260 /// marked resolved via [`mark_dep_resolved`](Self::mark_dep_resolved), and
261 /// the healthchecks pass. Uses [`DEFAULT_HEALTHCHECK_TIMEOUT`] as the
262 /// per-check timeout.
263 #[must_use]
264 pub fn new<I, S>(critical_deps: I, healthchecks: Arc<RestHealthcheckRegistry>) -> Arc<Self>
265 where
266 I: IntoIterator<Item = S>,
267 S: Into<String>,
268 {
269 Self::with_check_timeout(critical_deps, healthchecks, DEFAULT_HEALTHCHECK_TIMEOUT)
270 }
271
272 /// Like [`new`](Self::new) but with an explicit per-check timeout.
273 #[must_use]
274 pub fn with_check_timeout<I, S>(
275 critical_deps: I,
276 healthchecks: Arc<RestHealthcheckRegistry>,
277 check_timeout: Duration,
278 ) -> Arc<Self>
279 where
280 I: IntoIterator<Item = S>,
281 S: Into<String>,
282 {
283 let deps = Arc::new(DependencyChecker::new());
284 for dep in critical_deps {
285 deps.register_dep(dep);
286 }
287 Self::from_checker(deps, healthchecks, check_timeout)
288 }
289
290 /// Build an aggregator around an **existing** [`DependencyChecker`], so the
291 /// in-process consumer-wiring path and the `OoP` `/readyz` aggregator share
292 /// one dependency-resolution core (the checker is fed once, read by both).
293 #[must_use]
294 pub fn from_checker(
295 deps: Arc<DependencyChecker>,
296 healthchecks: Arc<RestHealthcheckRegistry>,
297 check_timeout: Duration,
298 ) -> Arc<Self> {
299 Arc::new(Self {
300 deps,
301 startup_complete: AtomicBool::new(false),
302 healthchecks,
303 check_timeout,
304 })
305 }
306
307 /// The shared dependency-resolution core, e.g. to feed it from consumer
308 /// wiring or to back an in-process [`ReadinessHealthcheck`] leaf.
309 #[must_use]
310 pub fn dependency_checker(&self) -> Arc<DependencyChecker> {
311 Arc::clone(&self.deps)
312 }
313
314 /// Declare a critical dependency dynamically (idempotent; preserves an
315 /// already-resolved entry). Complements the up-front `critical_deps` seed for
316 /// deps discovered during consumer wiring.
317 pub fn register_dep(&self, dep_gear: impl Into<String>) {
318 self.deps.register_dep(dep_gear);
319 }
320
321 /// Mark startup as complete. Idempotent; subsequent calls are ignored.
322 /// `/readyz` will not report `Ready` or `Degraded` until this is called.
323 pub fn mark_startup_complete(&self) {
324 self.startup_complete.store(true, Ordering::SeqCst);
325 }
326
327 /// Whether startup is complete.
328 #[must_use]
329 pub fn is_startup_complete(&self) -> bool {
330 self.startup_complete.load(Ordering::SeqCst)
331 }
332
333 /// Mark a critical dependency as resolved. Idempotent; unknown names are
334 /// ignored.
335 pub fn mark_dep_resolved(&self, name: &str) {
336 if self.deps.mark_resolved(name) {
337 tracing::info!(dep = %name, "critical dependency resolved");
338 }
339 }
340
341 /// Whether all critical dependencies have been resolved.
342 #[must_use]
343 pub fn all_deps_resolved(&self) -> bool {
344 self.deps.all_resolved()
345 }
346
347 /// Set (or clear) the draining flag. Setting it flips `/readyz` to `503`
348 /// immediately so upstreams pull the instance out of rotation while
349 /// in-flight requests drain.
350 pub fn set_draining(&self, draining: bool) {
351 self.deps.set_draining(draining);
352 }
353
354 /// Whether the gear is currently draining.
355 #[must_use]
356 pub fn is_draining(&self) -> bool {
357 self.deps.is_draining()
358 }
359
360 /// Run the registered healthchecks and return the aggregated report.
361 ///
362 /// Used by `/health` to expose full per-component detail and by
363 /// [`Self::evaluate`] to decide readiness state. The registry caches the
364 /// report, so repeated calls within the cache window do not re-run checks.
365 pub async fn health_report(&self) -> HealthcheckReport {
366 self.healthchecks.report(self.check_timeout).await
367 }
368
369 /// Evaluate the aggregate readiness.
370 ///
371 /// The gear is ready when it is not draining, startup is complete, all
372 /// critical deps are resolved, and the aggregated healthcheck report is not
373 /// `Unhealthy`. `Degraded` healthchecks keep the gear ready (`state =
374 /// degraded`, `ready = true`) but the detailed per-component messages belong
375 /// on `/health`, not `/readyz`. The healthcheck fan-out is cached inside the
376 /// registry, so repeated probe traffic does not re-run checks; dependency and
377 /// draining state are read live so transitions take effect immediately.
378 pub async fn evaluate(&self) -> ReadinessReport {
379 let health = self.health_report().await;
380 let draining = self.deps.is_draining();
381 let startup_complete = self.is_startup_complete();
382 let unresolved_deps: Vec<String> = self.deps.unresolved_deps();
383
384 // Draining wins; then any not-ready condition (startup not complete,
385 // unresolved deps, or an Unhealthy check) is `Starting`; then `Degraded`;
386 // else `Ready`.
387 let state = if draining {
388 ReadinessLifecycle::Draining
389 } else if !startup_complete
390 || !unresolved_deps.is_empty()
391 || health.status == HealthcheckStatus::Unhealthy
392 {
393 ReadinessLifecycle::Starting
394 } else if health.status == HealthcheckStatus::Degraded {
395 ReadinessLifecycle::Degraded
396 } else {
397 ReadinessLifecycle::Ready
398 };
399
400 let ready = matches!(
401 state,
402 ReadinessLifecycle::Ready | ReadinessLifecycle::Degraded
403 );
404
405 ReadinessReport {
406 state,
407 ready,
408 unresolved_deps,
409 }
410 }
411}
412
413#[cfg(test)]
414#[cfg_attr(coverage_nightly, coverage(off))]
415#[path = "readiness_tests.rs"]
416mod tests;
417
418#[cfg(test)]
419#[cfg_attr(coverage_nightly, coverage(off))]
420mod dep_checker_tests {
421 use super::DependencyChecker;
422
423 #[test]
424 fn no_deps_is_ready() {
425 let c = DependencyChecker::new();
426 assert!(c.all_resolved());
427 assert!(c.is_ready());
428 assert!(c.unresolved_deps().is_empty());
429 }
430
431 #[test]
432 fn unresolved_dep_lists_and_blocks() {
433 let c = DependencyChecker::new();
434 c.register_dep("billing");
435 c.register_dep("inventory");
436 assert!(!c.is_ready());
437 assert_eq!(
438 c.unresolved_deps(),
439 vec!["billing".to_owned(), "inventory".to_owned()]
440 );
441 }
442
443 #[test]
444 fn ready_once_all_deps_resolved() {
445 let c = DependencyChecker::new();
446 c.register_dep("billing");
447 c.register_dep("inventory");
448 assert!(c.mark_resolved("billing")); // false -> true
449 assert!(!c.is_ready());
450 assert!(c.mark_resolved("inventory"));
451 assert!(c.is_ready());
452 }
453
454 #[test]
455 fn register_dep_is_idempotent_and_preserves_resolved() {
456 let c = DependencyChecker::new();
457 c.register_dep("billing");
458 assert!(c.mark_resolved("billing"));
459 c.register_dep("billing"); // must NOT reset to unresolved
460 assert!(c.is_ready());
461 assert!(!c.mark_resolved("billing")); // already resolved -> no transition
462 }
463
464 #[test]
465 fn mark_resolved_unknown_dep_is_noop() {
466 let c = DependencyChecker::new();
467 assert!(!c.mark_resolved("nope")); // no panic, no transition, no entry
468 assert!(c.is_ready());
469 }
470
471 #[test]
472 fn draining_overrides_ready() {
473 let c = DependencyChecker::new();
474 assert!(c.is_ready());
475 c.set_draining(true);
476 assert!(c.is_draining());
477 assert!(!c.is_ready());
478 c.set_draining(false);
479 assert!(c.is_ready());
480 }
481
482 #[tokio::test]
483 async fn readiness_healthcheck_maps_state_to_status() {
484 use super::ReadinessHealthcheck;
485 use crate::healthcheck::{Healthcheck, HealthcheckStatus};
486 use std::sync::Arc;
487
488 let checker = Arc::new(DependencyChecker::new());
489 checker.register_dep("billing");
490 let hc = ReadinessHealthcheck::new(checker.clone());
491 assert_eq!(hc.name(), "readiness");
492
493 // Unresolved dep → Unhealthy (503), stable code, dep listed.
494 let starting = hc.check().await;
495 assert_eq!(starting.status, HealthcheckStatus::Unhealthy);
496 assert_eq!(starting.code.as_deref(), Some("deps_unresolved"));
497 assert!(starting.message.unwrap().contains("billing"));
498
499 // Resolved → Healthy (200).
500 checker.mark_resolved("billing");
501 assert_eq!(hc.check().await.status, HealthcheckStatus::Healthy);
502
503 // Draining wins regardless of deps.
504 checker.set_draining(true);
505 let draining = hc.check().await;
506 assert_eq!(draining.status, HealthcheckStatus::Unhealthy);
507 assert_eq!(draining.code.as_deref(), Some("draining"));
508 }
509}