Skip to main content

toolkit/runtime/
host_runtime.rs

1//! Host runtime lifecycle, shared by in-process and `OoP` execution.
2//!
3//! Startup order:
4//! 1. Build manifests and policies; check GTS ownership and wiring groups
5//!    before any gear runs or writes to the registry.
6//! 2. System group: runtime wiring, `pre_init`, migrations, `init`, client
7//!    wiring, `post_init`, initial gRPC services, `start`.
8//! 3. Application preparation: `pre_init`, migrations, registry-client wiring,
9//!    then concurrent GTS publication. All manifests must be admitted before
10//!    any application `init`; failed admission stops the process for restart.
11//! 4. Application `init`, remaining client wiring, legacy registry finalization,
12//!    `post_init`, REST composition, late gRPC installation, `start`.
13//! 5. In-process host: advertise REST providers, then spawn configured children
14//!    without waiting for readiness. Parent publication cannot depend on them.
15//!
16//! Hooks run once per gear, in topological order within each group. Migration-only
17//! mode runs runtime wiring, `pre_init` and migrations for all gears, system first.
18//! Shutdown stops applications before system gears, reversing each group's order.
19//! `oop_serve` owns HTTP serving, directory presence and drain in the `OoP` path;
20//! that path has no REST host, directory-register or child-spawn phases.
21//!
22//! # `deps` and `#[toolkit::consumes]`
23//!
24//! - `deps` orders same-process `init`s and requires linked gears; an unknown
25//!   dependency fails registry construction. It cannot order remote providers.
26//! - `#[toolkit::consumes(contract, from)]` wires a local client or a resolving
27//!   proxy and gates `/readyz`, without adding an ordering edge. Wiring precedes
28//!   `post_init` and `start` in both profiles.
29//!
30//! Prefer `consumes` for inter-gear calls; use `deps` for local init ordering.
31
32#[path = "host_runtime_rest.rs"]
33mod rest_bootstrap;
34
35#[path = "rest_advertiser.rs"]
36mod rest_advertiser;
37use rest_advertiser::RestAdvertiser;
38
39use axum::Router;
40use std::collections::HashSet;
41use std::sync::Arc;
42
43use tokio_util::sync::CancellationToken;
44use uuid::Uuid;
45
46use crate::backends::OopSpawnConfig;
47use crate::client_hub::ClientHub;
48use crate::config::ConfigProvider;
49use crate::context::{GearContextBuilder, GtsAdmittedManifests};
50use crate::gts_publication::{
51    GtsManifest, GtsPublicationDescriptor, GtsPublicationOptions, PreparedGtsPublication,
52};
53
54/// A publishing gear's manifest and policy, read once from the configuration before
55/// any gear runs.
56type GtsPublicationPlan = (
57    &'static GtsPublicationDescriptor,
58    Arc<GtsManifest>,
59    GtsPublicationOptions,
60);
61use crate::registry::{
62    ApiGatewayCap, GearEntry, GearRegistry, GrpcHubCap, GtsPublicationCap, RegistryError,
63    RestApiCap, RunnableCap, SystemCap,
64};
65use crate::runtime::{
66    GearManager, GrpcInstallerStore, OopSpawnOptions, PREPARATION_GATE, SystemContext,
67};
68
69#[cfg(feature = "db")]
70use crate::registry::DatabaseCap;
71
72/// How the runtime should provide DBs to gears.
73#[derive(Clone)]
74pub enum DbOptions {
75    /// No database integration. `GearCtx::db()` will be `None`, `db_required()` will error.
76    None,
77    /// Use a `DbManager` to handle database connections with Figment-based configuration.
78    #[cfg(feature = "db")]
79    Manager(Arc<toolkit_db::DbManager>),
80}
81
82/// Runtime execution mode that determines which phases to run.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum RunMode {
85    /// Run all phases and wait for shutdown signal (normal application mode).
86    Full,
87    /// Run only pre-init and DB migration phases, then exit (for cloud deployments).
88    MigrateOnly,
89}
90
91/// Environment variable name for passing directory endpoint to `OoP` gears.
92pub const TOOLKIT_DIRECTORY_ENDPOINT_ENV: &str = "TOOLKIT_DIRECTORY_ENDPOINT";
93
94/// Environment variable name for passing rendered gear config to `OoP` gears.
95pub const TOOLKIT_MODULE_CONFIG_ENV: &str = "TOOLKIT_MODULE_CONFIG";
96
97/// Default shutdown deadline for graceful gear stop (35 seconds).
98///
99/// This is intentionally 5 seconds longer than `WithLifecycle::stop_timeout` (30s default)
100/// to ensure deterministic behavior: the lifecycle's internal timeout fires first,
101/// and the runtime deadline acts as a hard backstop.
102pub const DEFAULT_SHUTDOWN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(35);
103
104/// How long the runtime waits for the gRPC hub to install the late services
105/// of the application group on its running listener.
106const LATE_GRPC_INSTALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
107
108/// How the startup of the application group ended.
109#[derive(Debug)]
110enum AppStartup {
111    /// Every application gear initialized and started.
112    Started,
113    /// Publication failed before application init; cleanup precedes the error return.
114    Failed(RegistryError),
115    /// Shutdown came first.
116    Cancelled,
117}
118
119/// Log the preparation failure before cleanup and error return.
120fn startup_failure(outcome: AppStartup) -> Option<RegistryError> {
121    match outcome {
122        AppStartup::Failed(failure) => {
123            tracing::error!(
124                error = %failure,
125                "the application group did not start; stopping the process"
126            );
127            Some(failure)
128        }
129        AppStartup::Started | AppStartup::Cancelled => None,
130    }
131}
132
133/// Default per-gear init deadline (10 minutes); see [`HostRuntime::with_init_deadline`].
134pub const DEFAULT_INIT_DEADLINE: std::time::Duration = std::time::Duration::from_secs(600);
135
136/// Verdict of a force-exit watchdog's wait, kept free of `process::exit` so the
137/// decision is unit-testable.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139enum WatchdogVerdict {
140    /// Disarmed in time: the guarded work finished or its future was dropped.
141    Disarmed,
142    /// The deadline elapsed first; the caller must force-exit.
143    TimedOut,
144}
145
146/// Block until the watchdog is disarmed (`disarm_rx` signalled or dropped) or
147/// `deadline` elapses. Runs on an OS thread (see [`arm_force_exit_watchdog`]) so
148/// the bound holds even when the guarded code blocks a runtime worker
149/// synchronously, which an async timer cannot observe.
150fn watchdog_verdict(
151    disarm_rx: &std::sync::mpsc::Receiver<()>,
152    deadline: std::time::Duration,
153) -> WatchdogVerdict {
154    match disarm_rx.recv_timeout(deadline) {
155        Ok(()) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => WatchdogVerdict::Disarmed,
156        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => WatchdogVerdict::TimedOut,
157    }
158}
159
160/// Grace the force-exit diagnostic gets before the process exits regardless.
161const FORCE_EXIT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
162
163/// Log a force-exit diagnostic and terminate the process with code 1.
164///
165/// A backstop timer is armed *first* so a wedged writer (e.g. a full `stderr`
166/// pipe) can delay the message but not the exit. `message` is mirrored to
167/// `stderr` so it survives tracing being off or unflushed.
168fn force_exit(message: &str) -> ! {
169    std::thread::spawn(|| {
170        std::thread::sleep(FORCE_EXIT_GRACE);
171        std::process::exit(1);
172    });
173
174    tracing::error!("{message}");
175    {
176        use std::io::Write as _;
177        _ = writeln!(std::io::stderr().lock(), "ERROR {message}");
178    }
179
180    std::process::exit(1);
181}
182
183/// Arm a thread that [`force_exit`]s unless the returned sender is dropped within
184/// `deadline`. Dropping it (normal completion *or* the guarded future being
185/// cancelled) disarms the watchdog, so a cancelled phase never force-exits.
186/// Shared by the init and stop phases.
187#[must_use = "bind the returned sender for the guarded region; dropping it disarms the watchdog"]
188fn arm_force_exit_watchdog(
189    deadline: std::time::Duration,
190    message: String,
191) -> std::sync::mpsc::Sender<()> {
192    let (disarm_tx, disarm_rx) = std::sync::mpsc::channel::<()>();
193    std::thread::spawn(move || {
194        if watchdog_verdict(&disarm_rx, deadline) == WatchdogVerdict::TimedOut {
195            force_exit(&message);
196        }
197    });
198    disarm_tx
199}
200
201/// Owns the lifecycle orchestration for `ToolKit`: encapsulates all runtime
202/// state and drives gears through the full lifecycle (see gear docs).
203pub struct HostRuntime {
204    registry: GearRegistry,
205    ctx_builder: GearContextBuilder,
206    instance_id: Uuid,
207    gear_manager: Arc<GearManager>,
208    grpc_installers: Arc<GrpcInstallerStore>,
209    client_hub: Arc<ClientHub>,
210    /// Per-gear config, retained for the proxy-wiring phase to read a consumer's
211    /// static-endpoint override (dev/test escape hatch, ADR-0004).
212    gears_cfg: Arc<dyn ConfigProvider>,
213    /// Process-level dependency-resolution + draining signal, published in
214    /// `client_hub` for the `/readyz` probe and updated by the proxy-wiring
215    /// readiness loop + draining watcher. In-process, an
216    /// [`ReadinessHealthcheck`](super::readiness::ReadinessHealthcheck) leaf
217    /// bridges it into the gateway's healthcheck registry.
218    dep_checker: Arc<super::readiness::DependencyChecker>,
219    /// Admitted manifests, read by the contexts of application gears.
220    gts_admitted: GtsAdmittedManifests,
221    /// In-process REST provider advertisement. In `OoP` serving, presence +
222    /// deregister is owned by `oop_serve`, so it stays unused.
223    advertiser: Arc<RestAdvertiser>,
224    /// Gears whose `start` the runtime called: the ones the stop phase stops,
225    /// on shutdown and after a failed startup alike.
226    start_called: parking_lot::Mutex<HashSet<&'static str>>,
227    /// Consumer registrations already wired, by address: the registry
228    /// clients are wired early, the rest after application `init`, each once.
229    wired: parking_lot::Mutex<HashSet<usize>>,
230    /// Directory targets each consumed dep still waits for, across all wiring
231    /// batches and their probes. A dep is resolved only when its entry is gone.
232    pending_targets: PendingTargets,
233    /// Replaces the link-time `inventory` registrations in a test: a test
234    /// binary links none, and submitting one would wire it in every test.
235    #[cfg(test)]
236    consumer_registrations: Option<Vec<&'static crate::discovery::ConsumerRegistration>>,
237    cancel: CancellationToken,
238    /// Ends the runtime's own background tasks (readiness probes, the drain
239    /// watcher) when startup fails or the runtime is dropped, without
240    /// cancelling `cancel`, which the caller may share. A child of `cancel`.
241    owned: CancellationToken,
242    /// Cancels `owned` when the runtime is dropped — the lifecycle future
243    /// abandoned.
244    _owned_on_drop: tokio_util::sync::DropGuard,
245    #[allow(dead_code)]
246    db_options: DbOptions,
247    /// `OoP` gear spawn configuration and backend
248    oop_options: Option<OopSpawnOptions>,
249    /// Maximum time allowed for graceful shutdown before hard-stop signal is sent.
250    shutdown_deadline: std::time::Duration,
251    /// Per-gear deadline for context construction and [`Gear::init`](crate::contracts::Gear::init).
252    /// Expiry force-exits the process (see [`DEFAULT_INIT_DEADLINE`]).
253    init_deadline: std::time::Duration,
254}
255
256impl HostRuntime {
257    /// Create a new `HostRuntime` instance.
258    ///
259    /// This prepares all runtime components but does not start any lifecycle phases.
260    pub fn new(
261        registry: GearRegistry,
262        gears_cfg: Arc<dyn ConfigProvider>,
263        db_options: DbOptions,
264        client_hub: Arc<ClientHub>,
265        cancel: CancellationToken,
266        instance_id: Uuid,
267        oop_options: Option<OopSpawnOptions>,
268    ) -> Self {
269        // Create runtime-owned components for system gears
270        let gear_manager = Arc::new(GearManager::new());
271        let grpc_installers = Arc::new(GrpcInstallerStore::new());
272
273        // Process-level dependency/draining signal, published so the gateway's
274        // /readyz handler can fetch it (concrete-type key). Created before any
275        // phase runs.
276        let dep_checker = Arc::new(super::readiness::DependencyChecker::new());
277        client_hub.register::<super::readiness::DependencyChecker>(dep_checker.clone());
278
279        let owned = cancel.child_token();
280        let owned_on_drop = owned.clone().drop_guard();
281        dep_checker.register_dep(PREPARATION_GATE);
282
283        // Build the context builder that will resolve per-gear DbHandles
284        let ctx_builder = GearContextBuilder::new(
285            instance_id,
286            gears_cfg.clone(),
287            client_hub.clone(),
288            cancel.clone(),
289        );
290        let gts_admitted = ctx_builder.gts_admitted_manifests();
291        #[cfg(feature = "db")]
292        let ctx_builder = match &db_options {
293            DbOptions::Manager(mgr) => ctx_builder.with_db_manager(mgr.clone()),
294            DbOptions::None => ctx_builder,
295        };
296
297        Self {
298            registry,
299            ctx_builder,
300            instance_id,
301            gear_manager,
302            grpc_installers,
303            client_hub,
304            gears_cfg,
305            dep_checker,
306            gts_admitted,
307            advertiser: Arc::new(RestAdvertiser::new(instance_id, &owned)),
308            start_called: parking_lot::Mutex::new(HashSet::new()),
309            wired: parking_lot::Mutex::new(HashSet::new()),
310            pending_targets: PendingTargets::default(),
311            #[cfg(test)]
312            consumer_registrations: None,
313            owned,
314            _owned_on_drop: owned_on_drop,
315            cancel,
316            db_options,
317            oop_options,
318            shutdown_deadline: DEFAULT_SHUTDOWN_DEADLINE,
319            init_deadline: DEFAULT_INIT_DEADLINE,
320        }
321    }
322
323    /// Set the per-gear deadline for context construction and [`Gear::init`](crate::contracts::Gear::init).
324    ///
325    /// A stuck `.await` returns [`RegistryError::InitTimeout`]; a synchronous
326    /// block force-exits the process. Defaults to [`DEFAULT_INIT_DEADLINE`].
327    #[must_use]
328    pub fn with_init_deadline(mut self, deadline: std::time::Duration) -> Self {
329        self.init_deadline = deadline;
330        self
331    }
332
333    #[cfg(test)]
334    pub(crate) fn init_deadline(&self) -> std::time::Duration {
335        self.init_deadline
336    }
337
338    /// Set a custom shutdown deadline for graceful gear stop.
339    ///
340    /// This is the maximum time the runtime will wait for each gear to stop gracefully
341    /// before sending the hard-stop signal (cancelling the deadline token).
342    ///
343    /// # Relationship with `WithLifecycle::stop_timeout`
344    ///
345    /// When using `WithLifecycle`, its `stop_timeout` (default 30s) races against this
346    /// `shutdown_deadline` (default [`DEFAULT_SHUTDOWN_DEADLINE`], 35s). To ensure
347    /// deterministic behavior:
348    ///
349    /// - `WithLifecycle::stop_timeout` should be **less than** `shutdown_deadline`
350    /// - This allows the lifecycle's internal timeout to trigger first for graceful cleanup
351    /// - The runtime's `deadline_token` then acts as a hard backstop
352    ///
353    /// Example: `stop_timeout = 30s`, `shutdown_deadline = 35s`
354    #[must_use]
355    pub fn with_shutdown_deadline(mut self, deadline: std::time::Duration) -> Self {
356        self.shutdown_deadline = deadline;
357        self
358    }
359
360    /// Set the process-wide platform-plane credential source, applied to every
361    /// [`GearCtx`](crate::context::GearCtx) this runtime builds so
362    /// `#[toolkit::provides]`-generated clients attach `X-ToolKit-Internal-Token`
363    /// on platform-plane methods. `None` (Profile 1 / in-process, or no
364    /// credential configured) attaches nothing.
365    #[must_use]
366    pub fn with_internal_token_provider(
367        mut self,
368        provider: Option<toolkit_contract::runtime::config::InternalTokenProvider>,
369    ) -> Self {
370        self.ctx_builder = self.ctx_builder.with_internal_token_provider(provider);
371        self
372    }
373
374    /// The system group (`system = true`) or the application group, in
375    /// topological order.
376    fn group(&self, system: bool) -> Vec<&GearEntry> {
377        self.registry
378            .gears()
379            .iter()
380            .filter(|entry| entry.is_system() == system)
381            .collect()
382    }
383
384    /// Every gear, the system group first, each group in topological order.
385    fn by_group(&self) -> Vec<&GearEntry> {
386        let mut gears = self.group(true);
387        gears.extend(self.group(false));
388        gears
389    }
390
391    /// The runtime internals handed to the system gears.
392    fn system_context(&self) -> SystemContext {
393        SystemContext::new(
394            self.instance_id,
395            Arc::clone(&self.gear_manager),
396            Arc::clone(&self.grpc_installers),
397        )
398    }
399
400    /// `PRE_INIT` phase over every gear, the system group first
401    /// (migration-only mode).
402    ///
403    /// # Errors
404    /// Returns `RegistryError` if runtime wiring or a `pre_init` fails.
405    pub async fn run_pre_init_phase(&self) -> Result<(), RegistryError> {
406        self.run_pre_init_phase_for(&self.by_group()).await
407    }
408
409    /// Wire system runtime internals, then run `entries`' `pre_init`s in order,
410    /// before their migrations. Contexts have no DB handle or admitted manifest.
411    async fn run_pre_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
412        tracing::info!(gears = entries.len(), "Phase: pre_init");
413
414        let sys_ctx = self.system_context();
415        for entry in entries {
416            if self.cancel.is_cancelled() {
417                tracing::warn!("Pre-init phase cancelled by signal");
418                return Err(RegistryError::Cancelled);
419            }
420            if let Some(system) = entry.caps.query::<SystemCap>() {
421                tracing::debug!(gear = entry.name, "Wiring runtime internals");
422                system
423                    .wire_runtime(&sys_ctx)
424                    .map_err(|e| RegistryError::PreInit {
425                        gear: entry.name,
426                        source: e.context("runtime wiring"),
427                    })?;
428            }
429        }
430
431        for entry in entries {
432            // Check for cancellation before processing each gear
433            if self.cancel.is_cancelled() {
434                tracing::warn!("Pre-init phase cancelled by signal");
435                return Err(RegistryError::Cancelled);
436            }
437            let ctx = self.ctx_builder.for_gear_before_migrations(entry.name);
438            entry
439                .core
440                .pre_init(&ctx)
441                .await
442                .map_err(|e| RegistryError::PreInit {
443                    gear: entry.name,
444                    source: e,
445                })?;
446        }
447
448        Ok(())
449    }
450
451    /// Helper: resolve context for a gear with error mapping.
452    #[cfg(feature = "db")]
453    async fn gear_context(
454        &self,
455        gear_name: &'static str,
456    ) -> Result<crate::context::GearCtx, RegistryError> {
457        self.ctx_builder
458            .for_gear(gear_name)
459            .await
460            .map_err(|e| RegistryError::DbMigrate {
461                gear: gear_name,
462                source: e,
463            })
464    }
465
466    /// Helper: extract DB handle and gear if both exist.
467    #[cfg(feature = "db")]
468    async fn db_migration_target(
469        &self,
470        gear_name: &'static str,
471        ctx: &crate::context::GearCtx,
472        db_gear: Option<Arc<dyn crate::contracts::DatabaseCapability>>,
473    ) -> Result<
474        Option<(
475            toolkit_db::Db,
476            Arc<dyn crate::contracts::DatabaseCapability>,
477        )>,
478        RegistryError,
479    > {
480        let Some(dbm) = db_gear else {
481            return Ok(None);
482        };
483
484        // Important: DB migrations require access to the underlying `Db`, not just `DBProvider`.
485        // `GearCtx` intentionally exposes only `DBProvider` for better DX and to reduce mistakes.
486        // So the runtime resolves the `Db` directly from its `DbManager`.
487        let db = match &self.db_options {
488            DbOptions::None => None,
489            #[cfg(feature = "db")]
490            DbOptions::Manager(mgr) => {
491                mgr.get(gear_name)
492                    .await
493                    .map_err(|e| RegistryError::DbMigrate {
494                        gear: gear_name,
495                        source: e.into(),
496                    })?
497            }
498        };
499
500        _ = ctx; // ctx is kept for parity/error context; DB is resolved from manager above.
501        Ok(db.map(|db| (db, dbm)))
502    }
503
504    /// Helper: run migrations for a single gear using the new migration runner.
505    ///
506    /// This collects migrations from the gear and executes them via the
507    /// runtime's privileged connection. Gears never see the raw connection.
508    #[cfg(feature = "db")]
509    async fn migrate_gear(
510        gear_name: &'static str,
511        db: &toolkit_db::Db,
512        db_gear: Arc<dyn crate::contracts::DatabaseCapability>,
513    ) -> Result<(), RegistryError> {
514        // Collect migrations from the gear
515        let migrations = db_gear.migrations();
516
517        if migrations.is_empty() {
518            tracing::debug!(gear = gear_name, "No migrations to run");
519            return Ok(());
520        }
521
522        tracing::debug!(
523            gear = gear_name,
524            count = migrations.len(),
525            "Running DB migrations"
526        );
527
528        // Execute migrations using the migration runner
529        let result =
530            toolkit_db::migration_runner::run_migrations_for_gear(db, gear_name, migrations)
531                .await
532                .map_err(|e| RegistryError::DbMigrate {
533                    gear: gear_name,
534                    source: anyhow::Error::new(e),
535                })?;
536
537        tracing::info!(
538            gear = gear_name,
539            applied = result.applied,
540            skipped = result.skipped,
541            "DB migrations completed"
542        );
543
544        Ok(())
545    }
546
547    /// DB MIGRATION phase over every gear, the system group first
548    /// (migration-only mode).
549    #[cfg(feature = "db")]
550    async fn run_db_phase(&self) -> Result<(), RegistryError> {
551        self.run_db_phase_for(&self.by_group()).await
552    }
553
554    /// DB MIGRATION phase: run migrations for `entries` with DB capability,
555    /// in the given order.
556    ///
557    /// Gears provide migrations via `DatabaseCapability::migrations()`.
558    /// The runtime executes them with a privileged connection that gears
559    /// never receive directly. Each gear gets a separate migration history
560    /// table, preventing cross-gear interference.
561    #[cfg(feature = "db")]
562    async fn run_db_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
563        tracing::info!(gears = entries.len(), "Phase: db (before init)");
564
565        for entry in entries {
566            // Check for cancellation before processing each gear
567            if self.cancel.is_cancelled() {
568                tracing::warn!("DB migration phase cancelled by signal");
569                return Err(RegistryError::Cancelled);
570            }
571
572            let ctx = self.gear_context(entry.name).await?;
573            let db_gear = entry.caps.query::<DatabaseCap>();
574
575            match self
576                .db_migration_target(entry.name, &ctx, db_gear.clone())
577                .await?
578            {
579                Some((db, dbm)) => {
580                    Self::migrate_gear(entry.name, &db, dbm).await?;
581                }
582                None if db_gear.is_some() => {
583                    tracing::debug!(
584                        gear = entry.name,
585                        "Gear has DbGear trait but no DB handle (no config)"
586                    );
587                }
588                None => {}
589            }
590        }
591
592        Ok(())
593    }
594
595    /// INIT phase over every gear, the system group first.
596    #[cfg(test)]
597    async fn run_init_phase(&self) -> Result<(), RegistryError> {
598        self.run_init_phase_for(&self.by_group()).await
599    }
600
601    /// INIT phase: initialize `entries` in the given order.
602    ///
603    /// Each gear's context construction and [`Gear::init`] share a force-exit
604    /// watchdog bounded by [`Self::init_deadline`] (see [`Self::init_gear`]).
605    async fn run_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
606        tracing::info!(gears = entries.len(), "Phase: init");
607
608        for entry in entries {
609            if self.cancel.is_cancelled() {
610                tracing::warn!("Init phase cancelled by signal");
611                return Err(RegistryError::Cancelled);
612            }
613            tracing::info!(gear = entry.name, "Initializing a gear...");
614            self.init_gear(entry).await?;
615            tracing::info!(gear = entry.name, "Initialized a gear.");
616        }
617
618        Ok(())
619    }
620
621    /// Run a single gear's context construction and `init()` under a two-tier
622    /// bound on [`Self::init_deadline`]:
623    ///
624    /// - An async `tokio::time::timeout` catches the common case (a stuck
625    ///   `.await`) and returns a recoverable [`RegistryError::InitTimeout`].
626    /// - An OS-thread force-exit watchdog, armed at a *longer* deadline, is the
627    ///   only thing that can catch init blocking a worker *synchronously* (where
628    ///   the async timer can never fire); it disarms when init finishes or this
629    ///   future is dropped.
630    async fn init_gear(&self, entry: &GearEntry) -> Result<(), RegistryError> {
631        let gear_name = entry.name;
632        let deadline = self.init_deadline;
633        // Longer than the async bound so the recoverable path wins when the timer
634        // can actually fire.
635        let backstop = deadline.saturating_mul(2);
636        let _watchdog = arm_force_exit_watchdog(
637            backstop,
638            format!(
639                "init timed out; the gear appears hung, force exiting gear={gear_name} timeout_secs={}",
640                backstop.as_secs()
641            ),
642        );
643
644        let init =
645            async {
646                let ctx = self.ctx_builder.for_gear(entry.name).await.map_err(|e| {
647                    RegistryError::Init {
648                        gear: entry.name,
649                        source: e,
650                    }
651                })?;
652
653                entry
654                    .core
655                    .init(&ctx)
656                    .await
657                    .map_err(|e| RegistryError::Init {
658                        gear: entry.name,
659                        source: e,
660                    })
661            };
662
663        match tokio::time::timeout(deadline, init).await {
664            Ok(result) => result,
665            Err(_elapsed) => {
666                tracing::error!(
667                    gear = gear_name,
668                    timeout_secs = deadline.as_secs(),
669                    "init timed out waiting on the gear; returning an error"
670                );
671                Err(RegistryError::InitTimeout {
672                    gear: gear_name,
673                    timeout: deadline,
674                })
675            }
676        }
677    }
678
679    /// Consumer proxy-wiring phase (eventual readiness).
680    ///
681    /// Runs after init (compile-time / local registrations) and before
682    /// post-init. Replays each `ConsumerRegistration` emitted by
683    /// `#[toolkit::consumes]`: if a compile-time impl is already in the
684    /// `ClientHub` it wins (the wiring closure short-circuits); otherwise a
685    /// directory-resolving REST client is registered under the contract trait.
686    ///
687    /// Non-blocking: endpoint discovery is lazy/per-call inside the resolving
688    /// client, so this phase never waits on provider availability (ADR-0007).
689    /// A no-op when no consumer is registered, preserving the phase-order
690    /// invariants relied on by existing tests.
691    #[cfg_attr(
692        not(test),
693        expect(clippy::unused_self, reason = "reads the test override in test builds")
694    )]
695    fn consumer_registrations(&self) -> Vec<&'static crate::discovery::ConsumerRegistration> {
696        #[cfg(test)]
697        if let Some(regs) = &self.consumer_registrations {
698            return regs.clone();
699        }
700        inventory::iter::<crate::discovery::ConsumerRegistration>
701            .into_iter()
702            .collect()
703    }
704
705    /// Wire `regs` instead of the linked registrations.
706    #[cfg(test)]
707    fn with_consumer_registrations(
708        mut self,
709        regs: Vec<&'static crate::discovery::ConsumerRegistration>,
710    ) -> Self {
711        self.consumer_registrations = Some(regs);
712        self
713    }
714
715    /// Wire registrations once, deduplicated by address so contracts sharing a
716    /// provider remain distinct. Registry clients may already be wired early.
717    /// Explicit `regs` let tests avoid process-wide inventory registrations.
718    /// Readiness probes are spawned, not awaited.
719    fn wire_consumer_registrations(
720        &self,
721        regs: &[&crate::discovery::ConsumerRegistration],
722    ) -> Result<Vec<crate::discovery::WireOutcome>, RegistryError> {
723        let regs = self.unwired_consumer_registrations(regs);
724        self.wire_untracked(&regs)
725    }
726
727    fn unwired_consumer_registrations<'a>(
728        &self,
729        regs: &[&'a crate::discovery::ConsumerRegistration],
730    ) -> Vec<&'a crate::discovery::ConsumerRegistration> {
731        let mut wired = self.wired.lock();
732        regs.iter()
733            .copied()
734            .filter(|reg| wired.insert(std::ptr::from_ref(*reg) as usize))
735            .collect()
736    }
737
738    /// Wire `regs` without deduplication; callers manage which registrations run.
739    fn wire_untracked(
740        &self,
741        regs: &[&crate::discovery::ConsumerRegistration],
742    ) -> Result<Vec<crate::discovery::WireOutcome>, RegistryError> {
743        use crate::discovery::{DirectoryEndpointResolver, NullEndpointResolver};
744        use toolkit_contract::runtime::resolving::EndpointResolver;
745
746        if regs.is_empty() {
747            return Ok(Vec::new());
748        }
749        tracing::info!(
750            count = regs.len(),
751            "Phase: proxy-wiring (consumer discovery)"
752        );
753
754        // Without a DirectoryClient we cannot resolve *remote* providers, but we
755        // must NOT silently skip wiring: co-located consumers still short-circuit
756        // to their local impl, and remote consumers must register as unresolved
757        // readiness gates so `/readyz` stays 503 (a misconfigured consumer must
758        // not report Ready). A null resolver makes every remote lookup `Ok(None)`
759        // so the loop below classifies deps correctly without a directory.
760        let (resolver, have_directory): (Arc<dyn EndpointResolver>, bool) =
761            if let Ok(dir) = self.client_hub.get::<dyn crate::DirectoryClient>() {
762                (Arc::new(DirectoryEndpointResolver::new(dir)), true)
763            } else {
764                tracing::error!(
765                    consumers = regs.len(),
766                    "proxy-wiring: no DirectoryClient in ClientHub; remote consumer \
767                     dependencies cannot be resolved and will gate /readyz (503). \
768                     Co-located (local) dependencies are unaffected."
769                );
770                (Arc::new(NullEndpointResolver), false)
771            };
772
773        // Wire each consumer contract. The outcome distinguishes a co-located
774        // local impl (hub short-circuit) from a directory-resolving REST client.
775        // Every dep is registered as a readiness gate; local ones are marked
776        // resolved once wiring is done, and only remote ones gate readiness + get
777        // the background directory-resolve loop (ADR-0007: startup-gating + sticky).
778        // `owner_gear` is set by `#[toolkit::consumes]` to the gear's declared
779        // `#[toolkit::gear(name = ...)]`, falling back to the kebab-case of the
780        // struct ident when that attribute is absent. It is used as the config key
781        // `gears.<owner_gear>.clients.consumes.<dep>` and as the owner of the
782        // hub view the proxy is wired into. If it does not match any registered
783        // gear name, the proxy is wired process-wide and that config key silently
784        // resolves to nothing, so warn.
785        let known_gears: std::collections::HashSet<&str> =
786            self.registry.gears().iter().map(GearEntry::name).collect();
787        // In-process gears with no REST API: a `Remote` outcome for
788        // one of these is a self-pointing dead proxy (see the hard error below).
789        // Directory advertisement is a separate choice: a partial REST provider
790        // can opt out so other contracts resolve to a provider in another process.
791        let unreachable_in_process: std::collections::HashSet<&str> = self
792            .registry
793            .gears()
794            .iter()
795            .filter(|gear| !gear.caps.has::<RestApiCap>())
796            .map(GearEntry::name)
797            .collect();
798        for reg in regs {
799            if !known_gears.contains(reg.owner_gear) {
800                tracing::warn!(
801                    owner = reg.owner_gear,
802                    dep = reg.dep_gear,
803                    "proxy-wiring: consumer's owner gear name does not match any registered gear; \
804                     the `gears.{}.clients.consumes.{}` static override will never resolve. \
805                     Ensure the consumer's `#[toolkit::gear(name = ...)]` matches its registered name.",
806                    reg.owner_gear,
807                    reg.dep_gear,
808                );
809            }
810        }
811
812        let mut outcomes = Vec::with_capacity(regs.len());
813        // In-process gears that serve no gRPC: a `RemoteGrpc` outcome for one of
814        // these can never resolve.
815        let grpc_providers: std::collections::HashSet<&str> = self
816            .registry
817            .grpc_services
818            .iter()
819            .map(|(name, _)| name.as_str())
820            .collect();
821        let no_grpc_in_process: std::collections::HashSet<&str> = known_gears
822            .iter()
823            .copied()
824            .filter(|g| !grpc_providers.contains(g))
825            .collect();
826
827        // A dep is resolved at wiring time only if no consumer of it needs the
828        // directory: with one consumer on a static endpoint and another on
829        // discovery, the dep waits for the probe. One dep can be probed for
830        // several targets (a REST consumer and a gRPC consumer); it is
831        // resolved when all of them are.
832        let mut resolved_now: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
833        let mut probes: std::collections::BTreeMap<&str, std::collections::BTreeSet<Probe>> =
834            std::collections::BTreeMap::new();
835        let mut transports_by_pair: std::collections::HashMap<(&str, &str), PairTransports> =
836            std::collections::HashMap::new();
837        for reg in regs {
838            // Read the consumer's `clients.consumes.<dep>` entry (if any) and
839            // split it into the optional static-endpoint overrides and the
840            // per-deployment `ClientTuning` (timeout/retry/pool/breaker).
841            let (rest_override, grpc_override, mut tuning) =
842                match read_consumer_wiring(self.gears_cfg.as_ref(), reg.owner_gear, reg.dep_gear)
843                    .map_err(|source| RegistryError::ProxyWiring {
844                        gear: reg.owner_gear,
845                        source,
846                    })? {
847                    Some(wiring) => {
848                        let grpc = wiring.grpc_endpoint.clone();
849                        let (endpoint, tuning) = wiring.into_parts();
850                        (endpoint, grpc, tuning)
851                    }
852                    None => (
853                        None,
854                        None,
855                        toolkit_contract::wiring::ClientTuning::default(),
856                    ),
857                };
858            let grpc_ignored_knobs = tuning.grpc_ignored_knobs();
859
860            // Thread the process's platform-plane credential onto the tuning so
861            // the wired (directory-resolving) client's platform-plane methods
862            // attach `X-ToolKit-Internal-Token` (`cpt-cf-adr-two-plane-auth`).
863            // This is the genuine remote inter-gear path (Profile 2/3); a
864            // co-located local impl short-circuits before the credential is used.
865            tuning = tuning
866                .with_internal_token_provider(self.ctx_builder.internal_token_provider().cloned());
867
868            // ADR-0004 static-endpoint override: a configured `endpoint` (and,
869            // for gRPC clients, `grpc_endpoint`) wires the dep directly,
870            // bypassing discovery for that transport. Validated as absolute URIs
871            // at parse time, so no probe loop is needed for it.
872            let grpc_static = grpc_override.clone().or_else(|| rest_override.clone());
873            let reg_resolver: Arc<dyn EndpointResolver> =
874                if rest_override.is_some() || grpc_override.is_some() {
875                    tracing::warn!(
876                        owner = reg.owner_gear,
877                        dep = reg.dep_gear,
878                        endpoint = ?rest_override,
879                        grpc_endpoint = ?grpc_override,
880                        "proxy-wiring: STATIC endpoint override in use (ADR-0004) - bypasses \
881                         service discovery"
882                    );
883                    Arc::new(crate::discovery::OverrideResolver {
884                        rest: rest_override.clone(),
885                        grpc: grpc_static.clone(),
886                        fallback: Arc::clone(&resolver),
887                    })
888                } else {
889                    Arc::clone(&resolver)
890                };
891
892            // Each registered consumer wires into its own view, so its proxy carries
893            // its own settings. An owner that is not a gear here (an SDK-level
894            // registration such as cluster-sdk's, or a stray consumer) wires
895            // process-wide.
896            let hub = if known_gears.contains(reg.owner_gear) {
897                self.client_hub.for_gear(reg.owner_gear)
898            } else {
899                Arc::clone(&self.client_hub)
900            };
901            let outcome = (reg.wire)(&hub, reg_resolver, tuning).map_err(|source| {
902                RegistryError::ProxyWiring {
903                    gear: reg.owner_gear,
904                    source,
905                }
906            })?;
907            self.dep_checker.register_dep(reg.dep_gear.to_owned());
908            let in_process_owner = known_gears.contains(reg.owner_gear);
909            match outcome {
910                // Local impl won the hub short-circuit — resolved.
911                crate::discovery::WireOutcome::Local => {
912                    resolved_now.insert(reg.dep_gear);
913                }
914                // Static override → fixed endpoint, always resolvable — no probe.
915                crate::discovery::WireOutcome::Remote if rest_override.is_some() => {
916                    resolved_now.insert(reg.dep_gear);
917                }
918                crate::discovery::WireOutcome::RemoteGrpc { .. } if grpc_static.is_some() => {
919                    resolved_now.insert(reg.dep_gear);
920                }
921                // A registered consumer depends on an in-process dep with no local
922                // impl and no API on the transport the client uses: wiring fell to
923                // a self-pointing proxy that would gate `/readyz` forever. Gated on
924                // the owner being registered too, so a stray/unused consumer
925                // (owner not in this process) falls through to the normal remote
926                // path below instead of aborting.
927                crate::discovery::WireOutcome::Remote
928                    if in_process_owner && unreachable_in_process.contains(reg.dep_gear) =>
929                {
930                    return Err(unreachable_dep(reg, "serves no REST API"));
931                }
932                crate::discovery::WireOutcome::RemoteGrpc { .. }
933                    if in_process_owner && no_grpc_in_process.contains(reg.dep_gear) =>
934                {
935                    return Err(unreachable_dep(reg, "serves no gRPC service"));
936                }
937                // Directory-resolved remote → gate readiness + background probe.
938                crate::discovery::WireOutcome::Remote => {
939                    probes.entry(reg.dep_gear).or_default().insert(Probe::Rest);
940                }
941                crate::discovery::WireOutcome::RemoteGrpc { service } => {
942                    probes
943                        .entry(reg.dep_gear)
944                        .or_default()
945                        .insert(Probe::Grpc(service));
946                }
947            }
948            warn_grpc_ignored_knobs(reg, outcome, &grpc_ignored_knobs);
949            let seen = transports_by_pair
950                .entry((reg.owner_gear, reg.dep_gear))
951                .or_default();
952            seen.record(outcome, rest_override.is_some() && grpc_override.is_none());
953            seen.check(reg)?;
954            tracing::debug!(
955                owner = reg.owner_gear,
956                dep = reg.dep_gear,
957                outcome = ?outcome,
958                "wired consumer contract"
959            );
960            outcomes.push(outcome);
961        }
962
963        // Wiring runs in batches (registry clients, system gears, the rest),
964        // and one dep can be consumed in several. Record this batch's targets
965        // first: a static or local outcome resolves a dep only when no batch
966        // still waits for a directory target of it, and a target added now
967        // reopens a dep an earlier batch resolved. Startup holds the
968        // preparation gate until the last batch, so a reopened dep is never
969        // seen as ready in between.
970        {
971            let mut pending = self.pending_targets.lock();
972            for (dep, targets) in &probes {
973                let entry = pending.entry((*dep).to_owned()).or_default();
974                let added = targets.iter().any(|t| !entry.contains(t));
975                entry.extend(targets.iter().cloned());
976                if added {
977                    self.dep_checker.mark_unresolved(dep);
978                }
979            }
980            for dep in &resolved_now {
981                if !pending.contains_key(*dep) {
982                    self.dep_checker.mark_resolved(dep);
983                }
984            }
985        }
986
987        // Only directory-resolved deps need probing; local and static ones are
988        // already resolved above. Without a directory the null resolver can
989        // never resolve them, so skip the probe entirely and leave those deps
990        // gating /readyz.
991        if !have_directory || probes.is_empty() {
992            return Ok(outcomes);
993        }
994        let pending: std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>> = probes
995            .into_iter()
996            .map(|(dep, targets)| (dep.to_owned(), targets))
997            .collect();
998
999        let readiness = Readiness {
1000            deps: Arc::clone(&self.dep_checker),
1001            pending: Arc::clone(&self.pending_targets),
1002        };
1003        let cancel = self.owned.clone();
1004        tokio::spawn(probe_until_resolved(resolver, readiness, cancel, pending));
1005
1006        Ok(outcomes)
1007    }
1008
1009    /// Build manifests and policies once, checking ownership before any gear runs.
1010    /// Application `init` reads the admitted manifest without rebuilding it.
1011    fn build_gts_manifests(&self) -> Result<Vec<GtsPublicationPlan>, RegistryError> {
1012        let mut manifests = Vec::new();
1013        for entry in self.registry.gears() {
1014            entry
1015                .validate_gts_publication_config(self.gears_cfg.as_ref())
1016                .map_err(|source| RegistryError::Publication {
1017                    gear: entry.name,
1018                    source,
1019                })?;
1020            let Some(publication) = entry.caps.query::<GtsPublicationCap>() else {
1021                continue;
1022            };
1023            let descriptor = publication.descriptor();
1024            let manifest = descriptor
1025                .build_gts_manifest(self.gears_cfg.as_ref())
1026                .map_err(|source| RegistryError::Publication {
1027                    gear: entry.name,
1028                    source,
1029                })?;
1030            let options = GtsPublicationOptions::from_config(entry.name, self.gears_cfg.as_ref())
1031                .map_err(|source| RegistryError::Publication {
1032                gear: entry.name,
1033                source: crate::gts_publication::GtsPublicationError::Options {
1034                    gear: descriptor.gear,
1035                    source,
1036                }
1037                .into(),
1038            })?;
1039            manifests.push((descriptor, Arc::new(manifest), options));
1040        }
1041        crate::gts_publication::check_ownership(manifests.iter().map(|(_, m, _)| m.as_ref()))
1042            .map_err(|source| RegistryError::GtsOwnership { source })?;
1043        Ok(manifests)
1044    }
1045
1046    /// Before the GTS barrier, wire non-empty manifests' registry clients and
1047    /// consumed contracts of those providers. Prefer local clients; otherwise use
1048    /// resolving proxies with platform credentials. Other consumers wait for
1049    /// application `init` so proxies cannot shadow local application providers.
1050    /// Empty manifests need no publisher client or readiness dependency.
1051    ///
1052    /// Refuse a local advertised provider missing the contract: discovery would
1053    /// route publication back to itself (e.g. an embedded registry without a DB).
1054    fn wire_registry_clients(&self, manifests: &[GtsPublicationPlan]) -> Result<(), RegistryError> {
1055        self.wire_registry_clients_over(manifests, &self.consumer_registrations())
1056    }
1057
1058    /// [`Self::wire_registry_clients`] over the given consumer registrations.
1059    fn wire_registry_clients_over(
1060        &self,
1061        manifests: &[GtsPublicationPlan],
1062        all: &[&'static crate::discovery::ConsumerRegistration],
1063    ) -> Result<(), RegistryError> {
1064        let publications: Vec<crate::discovery::ConsumerRegistration> = manifests
1065            .iter()
1066            .filter(|(_, manifest, _)| !manifest.is_empty())
1067            .map(
1068                |(descriptor, _, _)| crate::discovery::ConsumerRegistration {
1069                    owner_gear: descriptor.gear,
1070                    dep_gear: descriptor.provider,
1071                    wire: descriptor.wire,
1072                },
1073            )
1074            .collect();
1075        if publications.is_empty() {
1076            return Ok(());
1077        }
1078        let providers: HashSet<&str> = publications.iter().map(|p| p.dep_gear).collect();
1079        let consumers: Vec<&crate::discovery::ConsumerRegistration> = all
1080            .iter()
1081            .copied()
1082            .filter(|reg| providers.contains(reg.dep_gear))
1083            .collect();
1084        // Explicit consumers reject duplicate contracts. Wire them first, then
1085        // let publication adapters reuse their proxies in the same gear view.
1086        // One batch keeps a static endpoint from resolving a dependency that
1087        // another consumer still needs to discover.
1088        let mut regs = self.unwired_consumer_registrations(&consumers);
1089        let consumer_count = regs.len();
1090        regs.extend(publications.iter());
1091        let outcomes = self.wire_untracked(&regs)?;
1092        for (publisher, outcome) in publications
1093            .iter()
1094            .zip(outcomes.into_iter().skip(consumer_count))
1095        {
1096            if outcome != crate::discovery::WireOutcome::Remote {
1097                continue;
1098            }
1099            self.check_child_registry_dependency(publisher.owner_gear, publisher.dep_gear)?;
1100            let advertised_here = self.registry.gears().iter().any(|entry| {
1101                entry.name == publisher.dep_gear
1102                    && entry
1103                        .caps
1104                        .query::<RestApiCap>()
1105                        .is_some_and(|rest| rest.advertised_in_directory())
1106            });
1107            if advertised_here {
1108                return Err(RegistryError::Publication {
1109                    gear: publisher.owner_gear,
1110                    source: anyhow::anyhow!(
1111                        "'{}' runs in this process and advertises itself, but does not provide \
1112                         the contract the publication needs here: publishing would call this \
1113                         process forever. Give it what it needs to provide the contract (an \
1114                         embedded types registry needs its database), or run it elsewhere",
1115                        publisher.dep_gear
1116                    ),
1117                });
1118            }
1119        }
1120        Ok(())
1121    }
1122
1123    /// Whether `gear` runs in this process, and in the system group.
1124    fn local_group(&self, gear: &str) -> Option<bool> {
1125        self.registry
1126            .gears()
1127            .iter()
1128            .find(|e| e.name == gear)
1129            .map(GearEntry::is_system)
1130    }
1131
1132    /// A remote publisher cannot discover its own unstarted child. An explicit
1133    /// endpoint may name an already-running external registry instead.
1134    fn check_child_registry_dependency(
1135        &self,
1136        publisher: &'static str,
1137        provider: &str,
1138    ) -> Result<(), RegistryError> {
1139        let child = self.oop_options.as_ref().is_some_and(|options| {
1140            options
1141                .gears
1142                .iter()
1143                .any(|child| child.gear_name == provider)
1144        });
1145        if !child {
1146            return Ok(());
1147        }
1148        let wiring = read_consumer_wiring(self.gears_cfg.as_ref(), publisher, provider).map_err(
1149            |source| RegistryError::Publication {
1150                gear: publisher,
1151                source,
1152            },
1153        )?;
1154        if wiring.is_some_and(|wiring| wiring.endpoint.is_some()) {
1155            return Ok(());
1156        }
1157        Err(RegistryError::Publication {
1158            gear: publisher,
1159            source: anyhow::anyhow!(
1160                "'{publisher}' publishes to child '{provider}', which starts only after parent \
1161                 preparation; use an in-process registry or an already-running external registry"
1162            ),
1163        })
1164    }
1165
1166    /// Reject early wiring to a local application provider before any gear runs:
1167    /// a system consumer or non-empty publication would cache a proxy before the
1168    /// provider registers its local client.
1169    fn check_wiring_groups(
1170        &self,
1171        manifests: &[GtsPublicationPlan],
1172        regs: &[&'static crate::discovery::ConsumerRegistration],
1173    ) -> Result<(), RegistryError> {
1174        let application = |gear: &str| self.local_group(gear) == Some(false);
1175        for reg in regs {
1176            if self.local_group(reg.owner_gear) == Some(true) && application(reg.dep_gear) {
1177                return Err(RegistryError::ProxyWiring {
1178                    gear: reg.owner_gear,
1179                    source: anyhow::anyhow!(
1180                        "system gear '{}' consumes '{}', an application gear of this \
1181                         process: its client is needed before that gear initializes",
1182                        reg.owner_gear,
1183                        reg.dep_gear
1184                    ),
1185                });
1186            }
1187        }
1188        for (descriptor, manifest, _) in manifests {
1189            if !manifest.is_empty() && application(descriptor.provider) {
1190                return Err(RegistryError::Publication {
1191                    gear: descriptor.gear,
1192                    source: anyhow::anyhow!(
1193                        "'{}' publishes to '{}', an application gear of this process: the \
1194                         publication precedes every application `init`",
1195                        descriptor.gear,
1196                        descriptor.provider
1197                    ),
1198                });
1199            }
1200            if !manifest.is_empty() && self.local_group(descriptor.provider).is_none() {
1201                self.check_child_registry_dependency(descriptor.gear, descriptor.provider)?;
1202            }
1203        }
1204        Ok(())
1205    }
1206
1207    /// After system `init`, wire registrations owned or provided by system gears.
1208    /// Local system clients now win over proxies and are ready for `post_init`.
1209    /// Others wait for application `init` to avoid shadowing its local providers.
1210    fn wire_system_clients(
1211        &self,
1212        all: &[&'static crate::discovery::ConsumerRegistration],
1213    ) -> Result<(), RegistryError> {
1214        let system = |gear: &str| self.local_group(gear) == Some(true);
1215        let regs: Vec<&crate::discovery::ConsumerRegistration> = all
1216            .iter()
1217            .copied()
1218            .filter(|reg| system(reg.owner_gear) || system(reg.dep_gear))
1219            .collect();
1220        self.wire_consumer_registrations(&regs).map(drop)
1221    }
1222
1223    /// `POST_INIT` phase over every gear, the system group first.
1224    #[cfg(test)]
1225    async fn run_post_init_phase(&self) -> Result<(), RegistryError> {
1226        self.run_post_init_phase_for(&self.by_group()).await
1227    }
1228
1229    /// `POST_INIT` phase: every gear's `post_init` of `entries`, after their
1230    /// group's `init` and proxy wiring, in the given order.
1231    async fn run_post_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
1232        tracing::info!(gears = entries.len(), "Phase: post_init");
1233
1234        for entry in entries {
1235            if self.cancel.is_cancelled() {
1236                tracing::warn!("Post-init phase cancelled by signal");
1237                return Err(RegistryError::Cancelled);
1238            }
1239            let ctx = self.ctx_builder.for_gear(entry.name).await.map_err(|e| {
1240                RegistryError::PostInit {
1241                    gear: entry.name,
1242                    source: e,
1243                }
1244            })?;
1245            entry
1246                .core
1247                .post_init(&ctx)
1248                .await
1249                .map_err(|e| RegistryError::PostInit {
1250                    gear: entry.name,
1251                    source: e,
1252                })?;
1253        }
1254
1255        Ok(())
1256    }
1257
1258    /// Finalize legacy in-memory registrations once, after all application `init`s
1259    /// and proxy wiring, before application `post_init`. Removed with ready mode.
1260    async fn run_legacy_finalization(&self) -> Result<(), RegistryError> {
1261        let sys_ctx = self.system_context();
1262        for entry in self.registry.gears() {
1263            if let Some(sys_mod) = entry.caps.query::<SystemCap>() {
1264                sys_mod
1265                    .legacy_finalize_after_application_init(&sys_ctx)
1266                    .await
1267                    .map_err(|e| RegistryError::PostInit {
1268                        gear: entry.name,
1269                        source: e.context("legacy finalization after application init"),
1270                    })?;
1271            }
1272        }
1273        Ok(())
1274    }
1275
1276    /// Await all manifests' admission concurrently, then store them for application contexts.
1277    /// Backend binding errors fail startup. Refusal or expiry returns
1278    /// [`AppStartup::Failed`] without application `init` or a startup retry.
1279    async fn run_gts_publication_barrier(
1280        &self,
1281        manifests: &[GtsPublicationPlan],
1282    ) -> Result<AppStartup, RegistryError> {
1283        let mut prepared = Vec::with_capacity(manifests.len());
1284        for (descriptor, manifest, options) in manifests {
1285            prepared.push(
1286                PreparedGtsPublication::bind(
1287                    descriptor,
1288                    Arc::clone(manifest),
1289                    *options,
1290                    &self.client_hub.for_gear(descriptor.gear),
1291                )
1292                .map_err(|e| RegistryError::Publication {
1293                    gear: descriptor.gear,
1294                    source: e.into(),
1295                })?,
1296            );
1297        }
1298        if prepared.iter().any(|p| !p.gts_manifest().is_empty()) {
1299            tracing::info!(
1300                publishers = prepared.len(),
1301                "Phase: GTS publication (application group waits for admission)"
1302            );
1303        }
1304        let results = crate::gts_publication::publish_all(
1305            &prepared,
1306            &self.cancel,
1307            Arc::new(|gear, detail: &str| {
1308                tracing::debug!(gear, detail, "GTS publication pending");
1309            }),
1310            true,
1311        )
1312        .await;
1313
1314        let failures: Vec<_> = results
1315            .into_iter()
1316            .filter_map(|(_, result)| match result {
1317                Ok(()) | Err(crate::gts_publication::GtsPublicationError::Cancelled { .. }) => None,
1318                Err(e) => Some(e),
1319            })
1320            .collect();
1321        if !failures.is_empty() {
1322            return Ok(AppStartup::Failed(
1323                RegistryError::ApplicationGroupNotStarted { failures },
1324            ));
1325        }
1326        if self.cancel.is_cancelled() {
1327            return Ok(AppStartup::Cancelled);
1328        }
1329        for publication in &prepared {
1330            self.gts_admitted.insert(publication.shared_gts_manifest());
1331        }
1332        Ok(AppStartup::Started)
1333    }
1334
1335    /// The host gear and its REST host capability, if any.
1336    fn rest_host(&self) -> Option<(&GearEntry, Arc<dyn crate::contracts::ApiGatewayCapability>)> {
1337        self.registry
1338            .gears()
1339            .iter()
1340            .find_map(|e| e.caps.query::<ApiGatewayCap>().map(|host| (e, host)))
1341    }
1342
1343    /// REST phase: compose the full router against the REST host.
1344    ///
1345    /// Prepares the host, registers every gear's routes, then finalizes with
1346    /// `OpenAPI` endpoints before the application group's REST host starts.
1347    async fn run_rest_phase(&self) -> Result<Router, RegistryError> {
1348        tracing::info!("Phase: rest (sync)");
1349
1350        // Find host(s) and whether any rest gears exist
1351        let host_count = self
1352            .registry
1353            .gears()
1354            .iter()
1355            .filter(|e| e.caps.has::<ApiGatewayCap>())
1356            .count();
1357
1358        match host_count {
1359            0 => {
1360                return if self
1361                    .registry
1362                    .gears()
1363                    .iter()
1364                    .any(|e| e.caps.has::<RestApiCap>())
1365                {
1366                    Err(RegistryError::RestRequiresHost)
1367                } else {
1368                    Ok(Router::new())
1369                };
1370            }
1371            1 => { /* proceed */ }
1372            _ => return Err(RegistryError::MultipleRestHosts),
1373        }
1374
1375        let (host_entry, host) = self
1376            .rest_host()
1377            .ok_or(RegistryError::RestHostNotFoundAfterValidation)?;
1378        let host_ctx = self
1379            .ctx_builder
1380            .for_gear(host_entry.name)
1381            .await
1382            .map_err(|e| RegistryError::RestPrepare {
1383                gear: host_entry.name,
1384                source: e,
1385            })?;
1386        let hc_registry = self.rest_health_registry();
1387        let router = host
1388            .rest_prepare(&host_ctx, Router::new(), Arc::clone(&hc_registry))
1389            .map_err(|source| RegistryError::RestPrepare {
1390                gear: host_entry.name,
1391                source,
1392            })?;
1393
1394        let all: Vec<_> = self.registry.gears().iter().collect();
1395        let router = self
1396            .add_rest_routes(router, &hc_registry, &all, host.as_registry())
1397            .await?;
1398
1399        // Host finalize: attach /openapi.json and /docs, persist Router if needed (no server start)
1400        host.rest_finalize(&host_ctx, router, hc_registry)
1401            .map_err(|source| RegistryError::RestFinalize {
1402                gear: host_entry.name,
1403                source,
1404            })
1405    }
1406
1407    /// Collect the gRPC installers of the service gears of the system group
1408    /// (`system = true`) or the application group, reject duplicate service
1409    /// names, and pin their owners.
1410    async fn collect_grpc_installers(
1411        &self,
1412        system: bool,
1413        seen: &mut HashSet<&'static str>,
1414    ) -> Result<Vec<crate::runtime::GearInstallers>, RegistryError> {
1415        let mut gears_data = Vec::new();
1416        // Compiled-in service_name -> owning-gear map, installed as
1417        // authoritative ownership below (see
1418        // `GearManager::merge_authoritative_grpc_service_owners`).
1419        let mut owners: std::collections::HashMap<String, String> =
1420            std::collections::HashMap::new();
1421        for (gear_name, service_gear) in &self.registry.grpc_services {
1422            let in_group = self
1423                .registry
1424                .gears()
1425                .iter()
1426                .any(|e| e.name == gear_name.as_str() && e.is_system() == system);
1427            if !in_group {
1428                continue;
1429            }
1430            let ctx = self.ctx_builder.for_gear(gear_name).await.map_err(|err| {
1431                RegistryError::GrpcRegister {
1432                    gear: gear_name.clone(),
1433                    source: err,
1434                }
1435            })?;
1436
1437            let installers = service_gear
1438                .get_grpc_services(&ctx)
1439                .await
1440                .map_err(|source| RegistryError::GrpcRegister {
1441                    gear: gear_name.clone(),
1442                    source,
1443                })?;
1444
1445            for reg in &installers {
1446                if !seen.insert(reg.service_name) {
1447                    return Err(RegistryError::GrpcRegister {
1448                        gear: gear_name.clone(),
1449                        source: anyhow::anyhow!(
1450                            "Duplicate gRPC service name: {}",
1451                            reg.service_name
1452                        ),
1453                    });
1454                }
1455                owners.insert(reg.service_name.to_owned(), gear_name.clone());
1456            }
1457
1458            gears_data.push(crate::runtime::GearInstallers {
1459                gear_name: gear_name.clone(),
1460                installers,
1461            });
1462        }
1463        if !owners.is_empty() {
1464            self.gear_manager
1465                .merge_authoritative_grpc_service_owners(owners);
1466        }
1467        Ok(gears_data)
1468    }
1469
1470    /// Whether gRPC is in play at all; an error when services exist without a hub.
1471    fn grpc_in_use(&self) -> Result<bool, RegistryError> {
1472        match (
1473            &self.registry.grpc_hub,
1474            self.registry.grpc_services.is_empty(),
1475        ) {
1476            (None, true) => Ok(false),
1477            (None, false) => Err(RegistryError::GrpcRequiresHub),
1478            (Some(_), _) => Ok(true),
1479        }
1480    }
1481
1482    /// Initial gRPC batch: the services of the system gears, for the
1483    /// hub to serve when it starts. Says whether application services follow.
1484    async fn run_grpc_initial_phase(
1485        &self,
1486        seen: &mut HashSet<&'static str>,
1487    ) -> Result<(), RegistryError> {
1488        if !self.grpc_in_use()? {
1489            return Ok(());
1490        }
1491        tracing::info!("Phase: grpc (initial services)");
1492        let gears = self.collect_grpc_installers(true, seen).await?;
1493        let more_batches = self.registry.grpc_services.iter().any(|(gear, _)| {
1494            self.registry
1495                .gears()
1496                .iter()
1497                .any(|e| e.name == gear.as_str() && !e.is_system())
1498        });
1499        let hub_name = self.registry.grpc_hub.clone().unwrap_or_default();
1500        self.grpc_installers
1501            .set(crate::runtime::GrpcInstallerData {
1502                gears,
1503                more_batches,
1504            })
1505            .map_err(|source| RegistryError::GrpcRegister {
1506                gear: hub_name,
1507                source,
1508            })
1509    }
1510
1511    /// Late gRPC batch: the application group's services, installed by the
1512    /// running hub on its listener. Returns once the hub acknowledged them.
1513    async fn run_grpc_late_phase(
1514        &self,
1515        seen: &mut HashSet<&'static str>,
1516    ) -> Result<(), RegistryError> {
1517        if !self.grpc_in_use()? {
1518            return Ok(());
1519        }
1520        let hub_name = self.registry.grpc_hub.clone().unwrap_or_default();
1521        let gears = self.collect_grpc_installers(false, seen).await?;
1522        if gears.is_empty() {
1523            self.grpc_installers.close();
1524            return Ok(());
1525        }
1526        tracing::info!(gears = gears.len(), "Phase: grpc (late services)");
1527        let hub_runs = self.start_called.lock().contains(hub_name.as_str());
1528        let installed = self.grpc_installers.publish_late(gears).map_err(|source| {
1529            RegistryError::GrpcRegister {
1530                gear: hub_name.clone(),
1531                source,
1532            }
1533        })?;
1534        self.grpc_installers.close();
1535        if !hub_runs {
1536            // The hub runs in the application group: it takes the late batch
1537            // when it starts.
1538            return Ok(());
1539        }
1540        let ack = tokio::select! {
1541            () = self.cancel.cancelled() => return Err(RegistryError::Cancelled),
1542            ack = tokio::time::timeout(LATE_GRPC_INSTALL_TIMEOUT, installed) => ack,
1543        };
1544        match ack {
1545            Ok(Ok(Ok(()))) => Ok(()),
1546            Ok(Ok(Err(source))) => Err(RegistryError::GrpcRegister {
1547                gear: hub_name,
1548                source,
1549            }),
1550            Ok(Err(_)) => Err(RegistryError::GrpcRegister {
1551                gear: hub_name,
1552                source: anyhow::anyhow!("the gRPC hub dropped the late services uninstalled"),
1553            }),
1554            Err(_) => Err(RegistryError::GrpcRegister {
1555                gear: hub_name,
1556                source: anyhow::anyhow!(
1557                    "the gRPC hub did not install the late services within {}s",
1558                    LATE_GRPC_INSTALL_TIMEOUT.as_secs()
1559                ),
1560            }),
1561        }
1562    }
1563
1564    /// START phase over every gear, the system group first.
1565    #[cfg(test)]
1566    async fn run_start_phase(&self) -> Result<(), RegistryError> {
1567        self.run_start_phase_for(&self.by_group()).await
1568    }
1569
1570    /// START phase: start the stateful gears of `entries` in order.
1571    async fn run_start_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
1572        tracing::info!(gears = entries.len(), "Phase: start");
1573
1574        for e in entries {
1575            if let Some(s) = e.caps.query::<RunnableCap>() {
1576                tracing::debug!(
1577                    gear = e.name,
1578                    is_system = e.is_system(),
1579                    "Starting stateful gear"
1580                );
1581                self.start_called.lock().insert(e.name);
1582                s.start(self.cancel.clone())
1583                    .await
1584                    .map_err(|source| RegistryError::Start {
1585                        gear: e.name,
1586                        source,
1587                    })?;
1588                tracing::info!(gear = e.name, "Started gear");
1589            }
1590        }
1591
1592        Ok(())
1593    }
1594
1595    /// Stop a single gear, logging errors but continuing execution.
1596    async fn stop_one_gear(entry: &GearEntry, cancel: CancellationToken) {
1597        if let Some(s) = entry.caps.query::<RunnableCap>() {
1598            match s.stop(cancel).await {
1599                Err(err) => {
1600                    tracing::warn!(gear =  entry.name, error = %err, "Failed to stop gear");
1601                }
1602                _ => {
1603                    tracing::info!(gear = entry.name, "Stopped gear");
1604                }
1605            }
1606        }
1607    }
1608
1609    /// STOP phase: stop all started gears: the application group, then the
1610    /// system group, each in reverse order.
1611    ///
1612    /// # Two-Phase Shutdown Contract
1613    ///
1614    /// This phase implements a proper two-phase shutdown for **each gear**:
1615    ///
1616    /// 1. **Graceful stop request**: Each gear's `stop(deadline_token)` is called with a
1617    ///    *fresh* cancellation token (not the already-cancelled root token). Gears should
1618    ///    interpret this as "please stop gracefully".
1619    ///
1620    /// 2. **Hard-stop deadline**: After `shutdown_deadline` expires **for that gear**,
1621    ///    its `deadline_token` is cancelled. Gears should interpret this as "abort immediately".
1622    ///
1623    /// Each gear gets its own independent deadline — if gear A takes 25s to stop,
1624    /// gear B still gets the full `shutdown_deadline` for its graceful shutdown.
1625    ///
1626    /// This allows gears to implement real graceful shutdown:
1627    /// - Request cooperative shutdown of child tasks
1628    /// - Wait for them to finish gracefully
1629    /// - If `deadline_token` fires, switch to hard-abort mode
1630    ///
1631    /// Errors are logged but do not fail the shutdown process.
1632    /// Note: `OoP` gears are stopped automatically by the backend when the
1633    /// cancellation token is triggered.
1634    async fn run_stop_phase(&self) -> Result<(), RegistryError> {
1635        tracing::info!("Phase: stop");
1636
1637        // Drop our REST providers from the directory first, so consumers stop
1638        // resolving an endpoint that is about to disappear.
1639        self.deregister_rest_providers().await;
1640
1641        let deadline = self.shutdown_deadline;
1642
1643        // The application group first: it may still use the system group.
1644        let in_reverse = self
1645            .registry
1646            .gears()
1647            .iter()
1648            .rev()
1649            .filter(|e| !e.is_system())
1650            .chain(self.registry.gears().iter().rev().filter(|e| e.is_system()));
1651        for e in in_reverse {
1652            let gear_name = e.name;
1653            // Only a gear whose `start` was called has anything to stop.
1654            if !self.start_called.lock().contains(gear_name) {
1655                continue;
1656            }
1657
1658            // Create a fresh deadline token for THIS gear
1659            // Each gear gets the full shutdown_deadline independently
1660            let deadline_token = CancellationToken::new();
1661            let deadline_token_for_timeout = deadline_token.clone();
1662
1663            // Spawn a task to cancel this gear's deadline token after shutdown_deadline
1664            let deadline_task = tokio::spawn(async move {
1665                tokio::time::sleep(deadline).await;
1666                tracing::warn!(
1667                    gear = gear_name,
1668                    deadline_secs = deadline.as_secs(),
1669                    "Gear shutdown deadline reached, sending hard-stop signal"
1670                );
1671                deadline_token_for_timeout.cancel();
1672            });
1673
1674            // Stop this gear with its own deadline token
1675            // The gear can observe the token transition from uncancelled→cancelled
1676            Self::stop_one_gear(e, deadline_token).await;
1677
1678            // Cancel the deadline task and await it to ensure full cleanup
1679            deadline_task.abort();
1680            #[allow(clippy::let_underscore_must_use)]
1681            let _ = deadline_task.await;
1682        }
1683
1684        Ok(())
1685    }
1686
1687    /// Run the stop phase under a force-exit watchdog so a stop that hangs on a
1688    /// blocking syscall cannot wedge shutdown. The watchdog disarms when the
1689    /// phase returns (success or failure) or if this future is dropped.
1690    async fn run_stop_phase_guarded(&self) -> Result<(), RegistryError> {
1691        let gear_count = u32::try_from(self.registry.gears().len().max(1)).unwrap_or(1);
1692        let stop_timeout = self
1693            .shutdown_deadline
1694            .checked_mul(gear_count)
1695            .and_then(|d| d.checked_add(std::time::Duration::from_secs(5)))
1696            .unwrap_or(self.shutdown_deadline);
1697
1698        let _watchdog = arm_force_exit_watchdog(
1699            stop_timeout,
1700            format!(
1701                "shutdown: stop phase timed out, force exiting timeout_secs={}",
1702                stop_timeout.as_secs()
1703            ),
1704        );
1705
1706        self.run_stop_phase().await
1707    }
1708
1709    /// End a pending preparation, the runtime's own tasks and the gRPC
1710    /// batches, stop and join the spawned children, then
1711    /// stop every started gear. Runs after a failed startup as at shutdown;
1712    /// it never cancels the caller's token.
1713    async fn shut_down(&self) -> Result<(), RegistryError> {
1714        self.dep_checker.set_draining(true);
1715        self.owned.cancel();
1716        // Stop discovery traffic before joining a potentially slow HTTP drain.
1717        if tokio::time::timeout(self.shutdown_deadline, self.deregister_rest_providers())
1718            .await
1719            .is_err()
1720        {
1721            tracing::warn!("REST provider deregistration timed out");
1722        }
1723        if let Some((entry, host)) = self.rest_host() {
1724            match tokio::time::timeout(self.shutdown_deadline, host.rest_shutdown_bootstrap()).await
1725            {
1726                Ok(Ok(())) => {}
1727                Ok(Err(error)) => {
1728                    tracing::warn!(gear = entry.name, %error, "REST bootstrap shutdown failed");
1729                }
1730                Err(_) => tracing::warn!(gear = entry.name, "REST bootstrap shutdown timed out"),
1731            }
1732        }
1733        self.grpc_installers.close();
1734        if let Some(oop) = &self.oop_options {
1735            // Bound child shutdown so in-process gears still stop if reaping hangs.
1736            // A timeout drops this wait; LocalProcessBackend's own shutdown task continues.
1737            // Other backends must also tolerate a dropped shutdown future.
1738            if tokio::time::timeout(self.shutdown_deadline, oop.backend.shutdown_all())
1739                .await
1740                .is_err()
1741            {
1742                tracing::warn!(
1743                    timeout_secs = self.shutdown_deadline.as_secs(),
1744                    "shutdown: OoP children did not stop in time; stopping the in-process gears"
1745                );
1746            }
1747        }
1748        self.run_stop_phase_guarded().await
1749    }
1750
1751    /// `OoP` SPAWN phase: spawn configured children after parent preparation,
1752    /// application start and REST provider registration. Children can use the
1753    /// parent's full API; parent publication must not depend on its children.
1754    /// Child readiness is not awaited.
1755    async fn run_oop_spawn_phase(&self) -> Result<(), RegistryError> {
1756        let oop_opts = match &self.oop_options {
1757            Some(opts) if !opts.gears.is_empty() => opts,
1758            _ => return Ok(()),
1759        };
1760
1761        tracing::info!("Phase: oop_spawn");
1762
1763        // Wait for grpc_hub to publish its endpoint (it runs async in start phase)
1764        let directory_endpoint = self.wait_for_grpc_hub_endpoint().await;
1765
1766        for gear_cfg in &oop_opts.gears {
1767            // Build environment with directory endpoint and rendered config
1768            // Note: User controls --config via execution.args in master config
1769            let mut env = gear_cfg.env.clone();
1770            env.insert(
1771                TOOLKIT_MODULE_CONFIG_ENV.to_owned(),
1772                gear_cfg.rendered_config_json.clone(),
1773            );
1774            if let Some(ref endpoint) = directory_endpoint {
1775                env.insert(TOOLKIT_DIRECTORY_ENDPOINT_ENV.to_owned(), endpoint.clone());
1776            }
1777
1778            // Use args from execution config as-is (user controls --config via args)
1779            let args = gear_cfg.args.clone();
1780
1781            let spawn_config = OopSpawnConfig {
1782                gear_name: gear_cfg.gear_name.clone(),
1783                binary: gear_cfg.binary.clone(),
1784                args,
1785                env,
1786                working_directory: gear_cfg.working_directory.clone(),
1787            };
1788
1789            oop_opts
1790                .backend
1791                .spawn(spawn_config)
1792                .await
1793                .map_err(|e| RegistryError::OopSpawn {
1794                    gear: gear_cfg.gear_name.clone(),
1795                    source: e,
1796                })?;
1797
1798            tracing::info!(
1799                gear =  %gear_cfg.gear_name,
1800                directory_endpoint = ?directory_endpoint,
1801                "Spawned OoP gear via backend"
1802            );
1803        }
1804
1805        Ok(())
1806    }
1807
1808    /// Wait for `grpc-hub` to publish its bound endpoint.
1809    ///
1810    /// Polls the `GrpcHubGear::bound_endpoint()` with a short interval until available or timeout.
1811    /// Returns None if no `grpc-hub` is running or if it times out.
1812    async fn wait_for_grpc_hub_endpoint(&self) -> Option<String> {
1813        const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
1814        const MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
1815
1816        // Find grpc_hub in registry
1817        let grpc_hub = self
1818            .registry
1819            .gears()
1820            .iter()
1821            .find_map(|e| e.caps.query::<GrpcHubCap>());
1822
1823        let Some(hub) = grpc_hub else {
1824            return None; // No grpc_hub registered
1825        };
1826
1827        let start = std::time::Instant::now();
1828
1829        loop {
1830            if let Some(endpoint) = hub.bound_endpoint() {
1831                tracing::debug!(
1832                    endpoint = %endpoint,
1833                    elapsed_ms = start.elapsed().as_millis(),
1834                    "gRPC hub endpoint available"
1835                );
1836                return Some(endpoint);
1837            }
1838
1839            if hub.serves_no_endpoint() {
1840                tracing::debug!("gRPC hub binds no endpoint");
1841                return None;
1842            }
1843            if start.elapsed() > MAX_WAIT {
1844                tracing::warn!("Timed out waiting for gRPC hub to bind");
1845                return None;
1846            }
1847
1848            tokio::time::sleep(POLL_INTERVAL).await;
1849        }
1850    }
1851
1852    /// Wait for the REST host gateway to publish its bound endpoint.
1853    ///
1854    /// The gateway binds its listener asynchronously in the start phase, so the
1855    /// bound endpoint may not be set the instant the start phase returns; poll
1856    /// with a short interval until available or timeout.
1857    async fn wait_for_rest_endpoint(
1858        &self,
1859        host: &Arc<dyn crate::contracts::ApiGatewayCapability>,
1860    ) -> Option<String> {
1861        const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
1862        const MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
1863
1864        let start = std::time::Instant::now();
1865        loop {
1866            if let Some(endpoint) = host.bound_endpoint() {
1867                return Some(endpoint);
1868            }
1869            if start.elapsed() > MAX_WAIT {
1870                tracing::warn!("Timed out waiting for REST host to bind");
1871                return None;
1872            }
1873            tokio::time::sleep(POLL_INTERVAL).await;
1874        }
1875    }
1876
1877    /// Advertise `entries`' REST providers by gear name at the shared gateway URL,
1878    /// after application/REST-host startup and before child spawning. Covers both
1879    /// groups, through the local or remote `DirectoryClient` in `ClientHub`.
1880    /// No-op without a REST host or REST providers.
1881    async fn run_directory_register_phase(
1882        &self,
1883        entries: &[&GearEntry],
1884    ) -> Result<(), RegistryError> {
1885        let rest_gears: Vec<&'static str> = self
1886            .rest_provider_gears()
1887            .into_iter()
1888            .filter(|gear| entries.iter().any(|e| e.name == *gear))
1889            .collect();
1890        if rest_gears.is_empty() {
1891            return Ok(());
1892        }
1893
1894        let Some((_, host)) = self.rest_host() else {
1895            return Ok(()); // no REST host serving the routes
1896        };
1897
1898        if !self.advertiser.is_enabled() {
1899            let Some(endpoint) = self.wait_for_rest_endpoint(&host).await else {
1900                tracing::warn!(
1901                    "directory-register: REST host endpoint unavailable; skipping REST provider registration"
1902                );
1903                return Ok(());
1904            };
1905
1906            let Ok(dir) = self.client_hub.get::<dyn crate::DirectoryClient>() else {
1907                tracing::debug!(
1908                    "directory-register: no DirectoryClient in ClientHub; skipping REST provider registration"
1909                );
1910                return Ok(());
1911            };
1912
1913            self.advertiser.enable(dir, endpoint);
1914        }
1915        for gear in rest_gears {
1916            self.advertiser.advertise(gear).await;
1917        }
1918        Ok(())
1919    }
1920
1921    /// Names of all gears that provide a REST API (have `RestApiCap`), excluding
1922    /// the REST host gateway itself (`ApiGatewayCap`) — the gateway is the
1923    /// transport, not a contract provider, so it must not be advertised in the
1924    /// directory under its own gear name.
1925    fn rest_provider_gears(&self) -> Vec<&'static str> {
1926        self.registry
1927            .gears()
1928            .iter()
1929            .filter(|e| {
1930                e.caps
1931                    .query::<RestApiCap>()
1932                    .is_some_and(|rest| rest.advertised_in_directory())
1933                    && !e.caps.has::<ApiGatewayCap>()
1934            })
1935            .map(|e| e.name)
1936            .collect()
1937    }
1938
1939    /// Deregister this process's REST providers from the directory on shutdown,
1940    /// so consumers stop resolving an endpoint that is going away. Best-effort.
1941    async fn deregister_rest_providers(&self) {
1942        self.advertiser.deregister_all().await;
1943    }
1944
1945    /// Run the full gear lifecycle (all phases).
1946    ///
1947    /// This is the standard entry point for normal application execution.
1948    /// It runs all phases from pre-init through shutdown.
1949    ///
1950    /// # Errors
1951    ///
1952    /// Returns an error if any gear phase fails during execution.
1953    pub async fn run_gear_phases(self) -> anyhow::Result<()> {
1954        self.run_phases_internal(RunMode::Full).await
1955    }
1956
1957    /// Run only the migration phases (pre-init + DB migration).
1958    ///
1959    /// This is designed for cloud deployment workflows where database migrations
1960    /// need to run as a separate step before starting the application.
1961    /// The process exits after migrations complete.
1962    ///
1963    /// # Errors
1964    ///
1965    /// Returns an error if pre-init or migration phases fail.
1966    pub async fn run_migration_phases(self) -> anyhow::Result<()> {
1967        self.run_phases_internal(RunMode::MigrateOnly).await
1968    }
1969
1970    /// Run full startup and wait for shutdown, or run only `pre_init` and migrations
1971    /// for every gear in migration-only mode. Shared by both public phase runners.
1972    async fn run_phases_internal(self, mode: RunMode) -> anyhow::Result<()> {
1973        // Log execution mode
1974        match mode {
1975            RunMode::Full => {
1976                tracing::info!("Running full lifecycle (all phases)");
1977            }
1978            RunMode::MigrateOnly => {
1979                tracing::info!("Running in migration mode (pre-init + db phases only)");
1980            }
1981        }
1982
1983        // Migration-only: pre-init and migrations of every gear, then exit.
1984        if mode == RunMode::MigrateOnly {
1985            self.run_pre_init_phase().await?;
1986            // DB migration phase (the system group first)
1987            #[cfg(feature = "db")]
1988            self.run_db_phase().await?;
1989            tracing::info!("Migration phases completed successfully");
1990            return Ok(());
1991        }
1992
1993        // A startup that fails leaves no started gear running:
1994        // gears started so far are stopped before the error returns.
1995        let outcome = match self.run_startup_phases().await {
1996            Ok(outcome) => outcome,
1997            Err(e) => {
1998                if let Err(stop) = self.shut_down().await {
1999                    tracing::warn!(error = %stop, "stop after a failed startup reported an error");
2000                }
2001                return Err(e);
2002            }
2003        };
2004        let failed = startup_failure(outcome);
2005
2006        // Return failed preparation to the supervisor after cleanup.
2007        if failed.is_none() {
2008            self.cancel.cancelled().await;
2009        }
2010
2011        // Stop phase with hard timeout. Blocking stop implementations are
2012        // guarded by a watchdog thread so a hang cannot block shutdown,
2013        // whether in the in-process or OoP path.
2014        let stopped = self.shut_down().await;
2015        match failed {
2016            Some(failure) => {
2017                if let Err(stop) = stopped {
2018                    tracing::warn!(error = %stop, "stop after a failed application group reported an error");
2019                }
2020                Err(failure.into())
2021            }
2022            None => Ok(stopped?),
2023        }
2024    }
2025
2026    /// Mark readiness Draining as soon as shutdown begins, before requests finish.
2027    /// Started first in both profiles; ends with the runtime's owned tasks.
2028    fn spawn_drain_watcher(&self) {
2029        let readiness = Arc::clone(&self.dep_checker);
2030        let cancel = self.cancel.clone();
2031        let owned = self.owned.clone();
2032        tokio::spawn(async move {
2033            tokio::select! {
2034                biased;
2035                () = cancel.cancelled() => {
2036                    readiness.set_draining(true);
2037                }
2038                () = owned.cancelled() => {}
2039            }
2040        });
2041    }
2042
2043    /// Everything from the manifests to the started application group.
2044    async fn run_startup_phases(&self) -> anyhow::Result<AppStartup> {
2045        let system = self.group(true);
2046        let app = self.group(false);
2047        self.spawn_drain_watcher();
2048
2049        // Local configuration first: a manifest that does not build, or a
2050        // client that would be wired before its provider, fails before any
2051        // gear runs or anything is written.
2052        let manifests = self.build_gts_manifests()?;
2053        let regs = self.consumer_registrations();
2054        self.check_wiring_groups(&manifests, &regs)?;
2055        let mut rest = self.bind_rest_bootstrap().await?;
2056
2057        // System group, complete: pre-init, migrations, init, its clients,
2058        // post-init.
2059        self.run_pre_init_phase_for(&system).await?;
2060        #[cfg(feature = "db")]
2061        self.run_db_phase_for(&system).await?;
2062        self.run_init_phase_for(&system).await?;
2063        self.wire_system_clients(&regs)?;
2064        self.run_post_init_phase_for(&system).await?;
2065
2066        // Serve system routes on the listener already hosting probes.
2067        let mut grpc_seen = HashSet::new();
2068        self.run_grpc_initial_phase(&mut grpc_seen).await?;
2069        self.run_start_phase_for(&system).await?;
2070        if let Some(composition) = &mut rest {
2071            self.publish_system_rest(composition, &system).await?;
2072        }
2073
2074        // Application group: pre-init, migrations, the registry clients, then
2075        // the GTS barrier.
2076        self.run_pre_init_phase_for(&app).await?;
2077        #[cfg(feature = "db")]
2078        self.run_db_phase_for(&app).await?;
2079        self.wire_registry_clients(&manifests)?;
2080        match self.run_gts_publication_barrier(&manifests).await? {
2081            AppStartup::Started => {}
2082            other => {
2083                self.grpc_installers.close();
2084                return Ok(other);
2085            }
2086        }
2087
2088        self.run_init_phase_for(&app).await?;
2089        self.wire_consumer_registrations(&regs)?;
2090        self.run_legacy_finalization().await?;
2091        self.run_post_init_phase_for(&app).await?;
2092
2093        // Attach the full REST/gRPC surface before starting applications.
2094        if let Some(composition) = rest {
2095            self.finish_rest_bootstrap(composition, &app).await?;
2096        } else {
2097            let _router = self.run_rest_phase().await?;
2098        }
2099        self.run_grpc_late_phase(&mut grpc_seen).await?;
2100        self.run_start_phase_for(&app).await?;
2101        let all: Vec<&GearEntry> = self.registry.gears().iter().collect();
2102        self.run_directory_register_phase(&all).await?;
2103        self.dep_checker.mark_resolved(PREPARATION_GATE);
2104
2105        // Children only start once the parent can serve them. Neither the
2106        // registry nor GTS prerequisites of this process may rely on a child.
2107        self.run_oop_spawn_phase().await?;
2108        Ok(AppStartup::Started)
2109    }
2110}
2111
2112#[cfg(test)]
2113#[cfg_attr(coverage_nightly, coverage(off))]
2114#[path = "rest_advertiser_tests.rs"]
2115mod rest_advertiser_tests;
2116
2117/// Composed `OoP` router, serialized `OpenAPI`, and auth policy from the same specs.
2118#[cfg(feature = "bootstrap")]
2119type ComposedOopRouter = (Router, String, toolkit_http_middleware::RouteAuthPolicy);
2120
2121/// The host-less `OoP` router composed so far: each gear's routes are
2122/// registered once, the system gears' before the application group.
2123#[cfg(feature = "bootstrap")]
2124#[derive(Default)]
2125struct OopComposition {
2126    registry: crate::api::OpenApiRegistryImpl,
2127    router: Router,
2128    composed: HashSet<&'static str>,
2129}
2130
2131/// Out-of-process HTTP serving lifecycle (`cpt-cf-component-oop-bootstrap`).
2132#[cfg(feature = "bootstrap")]
2133impl HostRuntime {
2134    /// Register the routes of the `RestApiCap` gears among `entries` not
2135    /// registered yet into the **host-less** `composition`, and return the
2136    /// router so far with its generated `OpenAPI` document (serialized JSON)
2137    /// and auth policy.
2138    ///
2139    /// Unlike [`run_rest_phase`](Self::run_rest_phase), this does not require an
2140    /// `ApiGatewayCap` host: `OoP` gears serve their own routes directly.
2141    async fn compose_oop_router(
2142        &self,
2143        options: &crate::runtime::OopServeOptions,
2144        hc_registry: &Arc<crate::healthcheck::RestHealthcheckRegistry>,
2145        entries: &[&GearEntry],
2146        composition: &mut OopComposition,
2147    ) -> anyhow::Result<ComposedOopRouter> {
2148        use crate::api::OpenApiInfo;
2149        use anyhow::Context as _;
2150
2151        for entry in self.registry.gears() {
2152            if !entries.iter().any(|e| e.name == entry.name) {
2153                continue;
2154            }
2155            let Some(rest) = entry.caps.query::<RestApiCap>() else {
2156                continue;
2157            };
2158            if !composition.composed.insert(entry.name) {
2159                continue;
2160            }
2161            let ctx = self
2162                .ctx_builder
2163                .for_gear(entry.name)
2164                .await
2165                .with_context(|| format!("OoP router: build context for '{}'", entry.name))?;
2166            let router = std::mem::take(&mut composition.router);
2167            composition.router = rest
2168                .register_rest(&ctx, router, &composition.registry)
2169                .with_context(|| format!("OoP router: register_rest for '{}'", entry.name))?;
2170
2171            // Register the gear's readiness healthcheck (the same mechanism
2172            // the api-gateway host uses), so /readyz reflects it identically
2173            // whether the gear runs in-process or OoP.
2174            if let Some(hc) = rest.healthcheck(&ctx) {
2175                hc_registry.register(entry.name, hc);
2176            }
2177        }
2178
2179        let info = OpenApiInfo {
2180            title: options.gear_name.clone(),
2181            version: options
2182                .version
2183                .clone()
2184                .unwrap_or_else(|| "0.0.0".to_owned()),
2185            description: None,
2186            servers: vec![],
2187        };
2188        let openapi = composition
2189            .registry
2190            .build_openapi(&info)
2191            .context("OoP router: build OpenAPI document")?;
2192        let json = serde_json::to_string(&openapi).context("OoP router: serialize OpenAPI")?;
2193        let route_auth =
2194            super::oop_serve::route_auth_policy(composition.registry.operation_specs.iter());
2195
2196        Ok((composition.router.clone(), json, route_auth))
2197    }
2198
2199    /// Run the full `OoP` gear lifecycle: phases (`pre_init` … `start`), then
2200    /// serve the composed router with framework probes, background
2201    /// self-registration, dependency resolution, and graceful drain, then the
2202    /// `stop` phase.
2203    ///
2204    /// The listener binds first. The system group's routes attach as
2205    /// soon as it started — platform-plane calls only, tenant-plane calls get
2206    /// `503` — and the process is present in the directory then if its
2207    /// advertised gear is a system gear. The application group's routes
2208    /// attach on the same listener once it started.
2209    ///
2210    /// # Errors
2211    /// Returns an error if any lifecycle phase or the HTTP server fails.
2212    pub async fn run_oop_serving(
2213        self,
2214        options: crate::runtime::OopServeOptions,
2215    ) -> anyhow::Result<()> {
2216        use crate::runtime::ReadinessState;
2217
2218        tracing::info!("Running OoP serving lifecycle");
2219
2220        // Make the directory client reachable to the proxy-wiring phase, which
2221        // resolves remote `#[toolkit::consumes]` providers through the
2222        // `ClientHub`. The `OoP` presence loop uses `options.directory`
2223        // directly; consumer wiring reads it here.
2224        if self.client_hub.get::<dyn crate::DirectoryClient>().is_err() {
2225            self.client_hub
2226                .register::<dyn crate::DirectoryClient>(Arc::clone(&options.directory));
2227        }
2228
2229        // Shared gear healthcheck registry (same mechanism as the api-gateway
2230        // host path). Seeded with the root cancellation token so in-flight
2231        // checks are aborted on shutdown. Populated during router composition.
2232        let hc_registry = Arc::new(
2233            crate::healthcheck::RestHealthcheckRegistry::with_cancellation(self.cancel.clone()),
2234        );
2235
2236        // Readiness gates on `#[toolkit::consumes]` dependencies only — the same
2237        // policy as the in-process host path — via the shared `DependencyChecker`
2238        // fed by the proxy-wiring phase below. `deps = [...]`-only declarations
2239        // remain for topo-sort ordering but do NOT gate `/readyz`. The
2240        // healthcheck registry supplies the per-gear readiness dimension; both
2241        // feed the `/readyz` aggregate.
2242        let readiness = ReadinessState::from_checker(
2243            Arc::clone(&self.dep_checker),
2244            Arc::clone(&hc_registry),
2245            options.healthcheck_timeout,
2246        );
2247
2248        // Bind the HTTP server and serve probes BEFORE the (possibly slow)
2249        // lifecycle phases, so the kubelet's liveness probe (`/healthz`) passes
2250        // immediately instead of getting connection-refused during `start()`.
2251        // Gear routes reply `503 starting` until attached below.
2252        let mut server = super::oop_serve::OopHttpServer::start(
2253            Arc::clone(&readiness),
2254            options,
2255            self.cancel.clone(),
2256        )
2257        .await?;
2258
2259        self.spawn_drain_watcher();
2260        let mut composition = OopComposition::default();
2261        let outcome = self
2262            .run_oop_startup(&mut server, &hc_registry, &mut composition)
2263            .await;
2264
2265        let serve_result = match outcome {
2266            Ok(outcome) => {
2267                let failed = startup_failure(outcome);
2268                // End failed preparation promptly so the supervisor can restart.
2269                if failed.is_some() {
2270                    self.cancel.cancel();
2271                }
2272                // Serve until cancelled, drain, then deregister.
2273                let joined = server.join().await;
2274                match failed {
2275                    Some(failure) => {
2276                        if let Err(e) = joined {
2277                            tracing::warn!(error = %e, "OoP server after a failed application group reported an error");
2278                        }
2279                        Err(failure.into())
2280                    }
2281                    None => joined,
2282                }
2283            }
2284            Err(e) => {
2285                tracing::error!(error = %e, "OoP startup failed before serving gear routes");
2286                // Tear down the probe server that is already bound.
2287                self.cancel.cancel();
2288                if let Err(join_err) = server.join().await {
2289                    tracing::warn!(error = %join_err, "OoP probe server teardown after startup failure errored");
2290                }
2291                Err(e)
2292            }
2293        };
2294
2295        // Served or failed to start: the runtime's tasks end and gears stop. Errors are
2296        // logged but do not fail the shutdown process (same contract as
2297        // run_stop_phase).
2298        if let Err(e) = self.shut_down().await {
2299            tracing::warn!(error = %e, "OoP stop phase reported an error");
2300        }
2301
2302        serve_result
2303    }
2304
2305    /// The `OoP` phases from the manifests to the attached application routes.
2306    async fn run_oop_startup(
2307        &self,
2308        server: &mut super::oop_serve::OopHttpServer,
2309        hc_registry: &Arc<crate::healthcheck::RestHealthcheckRegistry>,
2310        composition: &mut OopComposition,
2311    ) -> anyhow::Result<AppStartup> {
2312        let system = self.group(true);
2313        let app = self.group(false);
2314        let advertised = server.options().gear_name.clone();
2315        let advertised_is_system = system.iter().any(|e| e.name == advertised.as_str());
2316        let root_is_advertised = || {
2317            self.registry
2318                .gears()
2319                .iter()
2320                .find(|entry| entry.name == advertised.as_str())
2321                .and_then(|entry| entry.caps.query::<RestApiCap>())
2322                .is_none_or(|rest| rest.advertised_in_directory())
2323        };
2324
2325        let manifests = self.build_gts_manifests()?;
2326        let regs = self.consumer_registrations();
2327        self.check_wiring_groups(&manifests, &regs)?;
2328
2329        // System group, complete before the application group.
2330        self.run_pre_init_phase_for(&system).await?;
2331        #[cfg(feature = "db")]
2332        self.run_db_phase_for(&system).await?;
2333        self.run_init_phase_for(&system).await?;
2334        self.wire_system_clients(&regs)?;
2335        self.run_post_init_phase_for(&system).await?;
2336        let mut grpc_seen = HashSet::new();
2337        self.run_grpc_initial_phase(&mut grpc_seen).await?;
2338        self.run_start_phase_for(&system).await?;
2339
2340        // System routes on the bound listener: platform-plane calls
2341        // only until the application group attached its routes.
2342        if system.iter().any(|e| e.caps.has::<RestApiCap>()) {
2343            let (router, openapi, route_auth) = self
2344                .compose_oop_router(server.options(), hc_registry, &system, composition)
2345                .await?;
2346            server.publish_bootstrap_routes(router, openapi, route_auth);
2347            if advertised_is_system && root_is_advertised() {
2348                server.start_presence();
2349            }
2350            // Every co-hosted system provider is discoverable at once,
2351            // whatever the root gear: an external publisher must reach a
2352            // registry the application group here may be waiting for.
2353            for entry in &system {
2354                if entry.name != advertised.as_str()
2355                    && entry
2356                        .caps
2357                        .query::<RestApiCap>()
2358                        .is_some_and(|rest| rest.advertised_in_directory())
2359                {
2360                    server.start_provider_presence(entry.name.to_owned());
2361                }
2362            }
2363        }
2364
2365        // Application group: pre-init, migrations, the registry clients, then
2366        // the GTS barrier.
2367        self.run_pre_init_phase_for(&app).await?;
2368        #[cfg(feature = "db")]
2369        self.run_db_phase_for(&app).await?;
2370        self.wire_registry_clients(&manifests)?;
2371        match self.run_gts_publication_barrier(&manifests).await? {
2372            AppStartup::Started => {}
2373            other => {
2374                self.grpc_installers.close();
2375                return Ok(other);
2376            }
2377        }
2378        self.run_init_phase_for(&app).await?;
2379        // Proxy-wiring before start: a gear resolving a consumed contract
2380        // during `start` finds the client in the hub under both profiles.
2381        self.wire_consumer_registrations(&regs)?;
2382        self.run_legacy_finalization().await?;
2383        self.run_post_init_phase_for(&app).await?;
2384        self.run_grpc_late_phase(&mut grpc_seen).await?;
2385        self.run_start_phase_for(&app).await?;
2386
2387        // The gear lifecycle has populated the ClientHub. If an in-process
2388        // authn stack (e.g. a linked authn-resolver gear) registered a
2389        // DynBearerAuthenticator bridge, install the tenant plane now —
2390        // before the final routes layer security_context_middleware. (The
2391        // platform plane is built eagerly at bootstrap from
2392        // `oop_http.internal_auth`.)
2393        server.resolve_bearer_authenticator(&self.client_hub);
2394        let all: Vec<&GearEntry> = self.registry.gears().iter().collect();
2395        let (router, openapi, route_auth) = self
2396            .compose_oop_router(server.options(), hc_registry, &all, composition)
2397            .await?;
2398        // Publish the full routes (they go live), then start directory
2399        // presence of the advertised gear: the directory never advertises it
2400        // while its routes reply 503.
2401        server.attach(router, openapi, route_auth)?;
2402        // First presence of an application root; a system root's restarts
2403        // with the full `OpenAPI` document.
2404        if root_is_advertised() {
2405            server.start_presence();
2406        }
2407        self.dep_checker.mark_resolved(PREPARATION_GATE);
2408        Ok(AppStartup::Started)
2409    }
2410}
2411
2412/// The transports one gear consumes one dep over, and whether its
2413/// `clients.consumes.<dep>` sets only `endpoint`.
2414#[derive(Default)]
2415struct PairTransports {
2416    rest: bool,
2417    grpc: bool,
2418    only_endpoint: bool,
2419}
2420
2421impl PairTransports {
2422    fn record(&mut self, outcome: crate::discovery::WireOutcome, only_endpoint: bool) {
2423        match outcome {
2424            crate::discovery::WireOutcome::Remote => self.rest = true,
2425            crate::discovery::WireOutcome::RemoteGrpc { .. } => self.grpc = true,
2426            crate::discovery::WireOutcome::Local => {}
2427        }
2428        self.only_endpoint = only_endpoint;
2429    }
2430
2431    /// One `endpoint` cannot serve a gear's REST and gRPC clients of a dep.
2432    fn check(&self, reg: &crate::discovery::ConsumerRegistration) -> Result<(), RegistryError> {
2433        if self.rest && self.grpc && self.only_endpoint {
2434            return Err(RegistryError::ProxyWiring {
2435                gear: reg.owner_gear,
2436                source: anyhow::anyhow!(
2437                    "gear '{}' consumes '{}' over both REST and gRPC, and \
2438                     `clients.consumes.{}` sets only `endpoint`; one address cannot serve \
2439                     both. Add `grpc_endpoint` for the gRPC client.",
2440                    reg.owner_gear,
2441                    reg.dep_gear,
2442                    reg.dep_gear,
2443                ),
2444            });
2445        }
2446        Ok(())
2447    }
2448}
2449
2450/// A gRPC client ignores the REST pool and concurrency knobs and
2451/// `stream_reconnect`; say so.
2452fn warn_grpc_ignored_knobs(
2453    reg: &crate::discovery::ConsumerRegistration,
2454    outcome: crate::discovery::WireOutcome,
2455    knobs: &[&str],
2456) {
2457    if let crate::discovery::WireOutcome::RemoteGrpc { service } = outcome
2458        && !knobs.is_empty()
2459    {
2460        tracing::warn!(
2461            owner = reg.owner_gear,
2462            dep = reg.dep_gear,
2463            service,
2464            knobs = ?knobs,
2465            "proxy-wiring: clients.consumes sets knobs a gRPC client does not apply; \
2466             they have no effect"
2467        );
2468    }
2469}
2470
2471/// What the readiness probe resolves for one consumed dep.
2472#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2473enum Probe {
2474    /// The provider gear's REST endpoint.
2475    Rest,
2476    /// A gRPC service, by fully qualified name.
2477    Grpc(&'static str),
2478}
2479
2480/// Directory targets still unresolved, per consumed dep.
2481type PendingTargets =
2482    Arc<parking_lot::Mutex<std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>>>;
2483
2484/// Where a probe reports: the readiness gate and the targets shared by every
2485/// wiring batch.
2486struct Readiness {
2487    deps: Arc<super::readiness::DependencyChecker>,
2488    pending: PendingTargets,
2489}
2490
2491impl Readiness {
2492    /// `target` of `dep` resolved. The dep is resolved once no batch waits for
2493    /// any other target of it.
2494    fn resolved(&self, dep: &str, target: &Probe) {
2495        let mut pending = self.pending.lock();
2496        let done = match pending.get_mut(dep) {
2497            Some(targets) => {
2498                targets.remove(target);
2499                targets.is_empty()
2500            }
2501            None => true,
2502        };
2503        if done {
2504            pending.remove(dep);
2505            if self.deps.mark_resolved(dep) {
2506                tracing::info!(dep = %dep, "readiness: dependency resolved");
2507            }
2508        }
2509    }
2510}
2511
2512/// Probe rounds after which a gRPC service still missing from the directory
2513/// gets a hint in the log: with backoff this is about a minute.
2514const GRPC_HINT_ROUNDS: u32 = 10;
2515
2516fn unreachable_dep(reg: &crate::discovery::ConsumerRegistration, why: &str) -> RegistryError {
2517    RegistryError::ProxyWiring {
2518        gear: reg.owner_gear,
2519        source: anyhow::anyhow!(
2520            "consumer '{}' depends on in-process gear '{}', which registered no local impl \
2521             and {why}; the provider must register its client in init() \
2522             (#[toolkit::provides] wire_* or ClientHub::register) or serve the contract over \
2523             the transport the consumer uses.",
2524            reg.owner_gear,
2525            reg.dep_gear,
2526        ),
2527    }
2528}
2529
2530/// Upper bound on one directory lookup of the readiness probe. An injected
2531/// `DirectoryClient` need not time out by itself, and a hung lookup would
2532/// block every target after it.
2533const PROBE_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
2534
2535/// Resolve every pending target with backoff, marking a dep ready once all of
2536/// its targets resolve. A lookup that takes longer than
2537/// [`PROBE_LOOKUP_TIMEOUT`] is retried next round. Stops on `cancel`, also
2538/// during a lookup.
2539async fn probe_until_resolved(
2540    resolver: Arc<dyn toolkit_contract::runtime::resolving::EndpointResolver>,
2541    readiness: Readiness,
2542    cancel: CancellationToken,
2543    mut pending: std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>,
2544) {
2545    const BASE: std::time::Duration = std::time::Duration::from_millis(100);
2546    const MAX: std::time::Duration = std::time::Duration::from_secs(30);
2547    let mut backoff = BASE;
2548    let mut rounds = 0u32;
2549    while !pending.is_empty() {
2550        let mut still_pending = std::collections::BTreeMap::new();
2551        for (dep, targets) in pending {
2552            let mut left = std::collections::BTreeSet::new();
2553            for target in targets {
2554                let lookup = async {
2555                    match &target {
2556                        Probe::Rest => resolver.resolve_endpoint(&dep).await,
2557                        Probe::Grpc(service) => resolver.resolve_grpc_endpoint(service).await,
2558                    }
2559                };
2560                let lookup = tokio::select! {
2561                    () = cancel.cancelled() => return,
2562                    lookup = tokio::time::timeout(PROBE_LOOKUP_TIMEOUT, lookup) => lookup,
2563                };
2564                match lookup {
2565                    Ok(Ok(Some(_))) => readiness.resolved(&dep, &target),
2566                    // No live instance yet — expected during startup churn.
2567                    Ok(Ok(None)) => {
2568                        left.insert(target);
2569                    }
2570                    // Genuine directory-backend failure: surface it (a stuck
2571                    // Starting / 503 pod otherwise has no diagnostic trail).
2572                    Ok(Err(e)) => {
2573                        tracing::warn!(dep = %dep, target = ?target, error = %e, "readiness: directory lookup failed");
2574                        left.insert(target);
2575                    }
2576                    Err(_) => {
2577                        tracing::warn!(
2578                            dep = %dep,
2579                            target = ?target,
2580                            timeout = ?PROBE_LOOKUP_TIMEOUT,
2581                            "readiness: directory lookup timed out"
2582                        );
2583                        left.insert(target);
2584                    }
2585                }
2586            }
2587            if !left.is_empty() {
2588                still_pending.insert(dep, left);
2589            }
2590        }
2591        pending = still_pending;
2592        if pending.is_empty() {
2593            break;
2594        }
2595        rounds = rounds.saturating_add(1);
2596        if rounds == GRPC_HINT_ROUNDS {
2597            for (dep, targets) in &pending {
2598                for target in targets {
2599                    if let Probe::Grpc(service) = target {
2600                        tracing::warn!(
2601                            dep = %dep,
2602                            service,
2603                            "readiness: gRPC service still not in the directory; check that the \
2604                             provider's process runs grpc-hub with a listen_addr and an \
2605                             advertise_addr it can register"
2606                        );
2607                    }
2608                }
2609            }
2610        }
2611        tokio::select! {
2612            () = cancel.cancelled() => break,
2613            () = tokio::time::sleep(backoff) => {}
2614        }
2615        backoff = (backoff * 2).min(MAX);
2616    }
2617}
2618
2619/// Read the [`ConsumerWiring`] for `owner`'s client of `dep` from
2620/// `gears.<owner>.clients` ([`crate::clients_config::consumer_wiring`]).
2621///
2622/// `Ok(None)` when absent (the dep keeps discovery). A *present* entry that cannot
2623/// be read is an `Err` that aborts proxy-wiring, as on the provider side.
2624fn read_consumer_wiring(
2625    cfg: &dyn ConfigProvider,
2626    owner_gear: &str,
2627    dep_gear: &str,
2628) -> Result<Option<toolkit_contract::wiring::ConsumerWiring>, anyhow::Error> {
2629    crate::clients_config::consumer_wiring(cfg, owner_gear, dep_gear)
2630}
2631
2632#[cfg(test)]
2633#[cfg(feature = "bootstrap")]
2634#[cfg_attr(coverage_nightly, coverage(off))]
2635#[path = "host_runtime_oop_tests.rs"]
2636mod host_runtime_oop_tests;
2637
2638#[cfg(test)]
2639#[cfg_attr(coverage_nightly, coverage(off))]
2640mod tests {
2641    use super::*;
2642    use crate::context::GearCtx;
2643    use crate::contracts::{Gear, RunnableCapability, SystemCapability};
2644    use crate::registry::RegistryBuilder;
2645    use std::sync::Arc;
2646    use std::sync::atomic::{AtomicUsize, Ordering};
2647    use tokio::sync::Mutex;
2648
2649    #[derive(Default)]
2650    #[allow(dead_code)]
2651    struct DummyCore;
2652    #[async_trait::async_trait]
2653    impl Gear for DummyCore {
2654        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2655            Ok(())
2656        }
2657    }
2658
2659    struct StopOrderTracker {
2660        my_order: usize,
2661        stop_order: Arc<AtomicUsize>,
2662    }
2663
2664    impl StopOrderTracker {
2665        fn new(counter: &Arc<AtomicUsize>, stop_order: Arc<AtomicUsize>) -> Self {
2666            let my_order = counter.fetch_add(1, Ordering::SeqCst);
2667            Self {
2668                my_order,
2669                stop_order,
2670            }
2671        }
2672    }
2673
2674    #[async_trait::async_trait]
2675    impl Gear for StopOrderTracker {
2676        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2677            Ok(())
2678        }
2679    }
2680
2681    #[async_trait::async_trait]
2682    impl RunnableCapability for StopOrderTracker {
2683        async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2684            Ok(())
2685        }
2686        async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2687            let order = self.stop_order.fetch_add(1, Ordering::SeqCst);
2688            tracing::info!(my_order = self.my_order, stop_order = order, "Gear stopped");
2689            Ok(())
2690        }
2691    }
2692
2693    #[tokio::test]
2694    async fn test_stop_phase_reverse_order() {
2695        let counter = Arc::new(AtomicUsize::new(0));
2696        let stop_order = Arc::new(AtomicUsize::new(0));
2697
2698        let gear_a = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2699        let gear_b = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2700        let gear_c = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2701
2702        let mut builder = RegistryBuilder::default();
2703        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2704        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2705        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2706
2707        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2708        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2709        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2710
2711        let registry = builder.build_topo_sorted().unwrap();
2712
2713        // Verify gear order is a -> b -> c
2714        let gear_names: Vec<_> = registry.gears().iter().map(|m| m.name).collect();
2715        assert_eq!(gear_names, vec!["a", "b", "c"]);
2716
2717        let client_hub = Arc::new(ClientHub::new());
2718        let cancel = CancellationToken::new();
2719        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2720
2721        let runtime = HostRuntime::new(
2722            registry,
2723            config_provider,
2724            DbOptions::None,
2725            client_hub,
2726            cancel.clone(),
2727            Uuid::new_v4(),
2728            None,
2729        );
2730
2731        // Run stop phase
2732        runtime.run_start_phase().await.unwrap();
2733        runtime.run_stop_phase().await.unwrap();
2734
2735        // Verify gears stopped in reverse order: c (stop_order=0), b (stop_order=1), a (stop_order=2)
2736        // Gear order is: a=0, b=1, c=2
2737        // Stop order should be: c=0, b=1, a=2
2738        assert_eq!(stop_order.load(Ordering::SeqCst), 3);
2739    }
2740
2741    #[tokio::test]
2742    async fn test_stop_phase_continues_on_error() {
2743        struct FailingGear {
2744            should_fail: bool,
2745            stopped: Arc<AtomicUsize>,
2746        }
2747
2748        #[async_trait::async_trait]
2749        impl Gear for FailingGear {
2750            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2751                Ok(())
2752            }
2753        }
2754
2755        #[async_trait::async_trait]
2756        impl RunnableCapability for FailingGear {
2757            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2758                Ok(())
2759            }
2760            async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2761                self.stopped.fetch_add(1, Ordering::SeqCst);
2762                if self.should_fail {
2763                    anyhow::bail!("Intentional failure")
2764                }
2765                Ok(())
2766            }
2767        }
2768
2769        let stopped = Arc::new(AtomicUsize::new(0));
2770        let gear_a = Arc::new(FailingGear {
2771            should_fail: false,
2772            stopped: stopped.clone(),
2773        });
2774        let gear_b = Arc::new(FailingGear {
2775            should_fail: true,
2776            stopped: stopped.clone(),
2777        });
2778        let gear_c = Arc::new(FailingGear {
2779            should_fail: false,
2780            stopped: stopped.clone(),
2781        });
2782
2783        let mut builder = RegistryBuilder::default();
2784        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2785        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2786        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2787
2788        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2789        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2790        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2791
2792        let registry = builder.build_topo_sorted().unwrap();
2793
2794        let client_hub = Arc::new(ClientHub::new());
2795        let cancel = CancellationToken::new();
2796        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2797
2798        let runtime = HostRuntime::new(
2799            registry,
2800            config_provider,
2801            DbOptions::None,
2802            client_hub,
2803            cancel.clone(),
2804            Uuid::new_v4(),
2805            None,
2806        );
2807
2808        // Run stop phase - should not fail even though gear_b fails
2809        runtime.run_start_phase().await.unwrap();
2810        runtime.run_stop_phase().await.unwrap();
2811
2812        // All gears should have attempted to stop
2813        assert_eq!(stopped.load(Ordering::SeqCst), 3);
2814    }
2815
2816    struct EmptyConfigProvider;
2817    impl ConfigProvider for EmptyConfigProvider {
2818        fn get_gear_config(&self, _gear_name: &str) -> Option<&serde_json::Value> {
2819            None
2820        }
2821    }
2822
2823    /// Serves one config blob for owner gear `orders` (the owner every
2824    /// `read_consumer_wiring` test uses) and nothing for anything else.
2825    struct OrdersCfg(serde_json::Value);
2826    impl ConfigProvider for OrdersCfg {
2827        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2828            (gear == "orders").then_some(&self.0)
2829        }
2830    }
2831
2832    /// Serves config blobs by owner-gear name (for tests wiring several gears).
2833    struct MapCfg(std::collections::HashMap<String, serde_json::Value>);
2834    impl ConfigProvider for MapCfg {
2835        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2836            self.0.get(gear)
2837        }
2838    }
2839
2840    /// Extract just the static-endpoint override from a `clients.consumes` entry.
2841    fn endpoint_override(cfg: &dyn ConfigProvider, owner: &str, dep: &str) -> Option<String> {
2842        super::read_consumer_wiring(cfg, owner, dep)
2843            .expect("clients.consumes must not error for a valid/absent endpoint")
2844            .and_then(|w| w.into_parts().0)
2845    }
2846
2847    #[test]
2848    fn static_endpoint_override_reads_the_clients_consumes_entry() {
2849        let mut map = std::collections::HashMap::new();
2850        map.insert(
2851            "orders".to_owned(),
2852            serde_json::json!({
2853                "clients": {
2854                    "consumes": { "billing": { "endpoint": "http://localhost:8081" } }
2855                }
2856            }),
2857        );
2858        let cfg = MapCfg(map);
2859
2860        // Present override is read from `clients.consumes.<dep>.endpoint`.
2861        assert_eq!(
2862            endpoint_override(&cfg, "orders", "billing").as_deref(),
2863            Some("http://localhost:8081")
2864        );
2865        // Absent dep / owner → None (falls through to directory resolution).
2866        assert_eq!(endpoint_override(&cfg, "orders", "inventory"), None);
2867        assert_eq!(endpoint_override(&cfg, "warehouse", "billing"), None);
2868        assert_eq!(
2869            endpoint_override(&EmptyConfigProvider, "orders", "billing"),
2870            None
2871        );
2872    }
2873
2874    /// The object form yields both the `endpoint` override and the flattened
2875    /// `ClientTuning`.
2876    #[test]
2877    fn consumer_wiring_object_form_yields_endpoint_and_tuning() {
2878        let cfg = OrdersCfg(serde_json::json!({
2879            "clients": {
2880                "consumes": {
2881                    "billing": {
2882                        "endpoint": "http://billing:8080",
2883                        "timeout": "5s",
2884                        "max_concurrent_requests": 256,
2885                        "pool_max_idle_per_host": 256
2886                    }
2887                }
2888            }
2889        }));
2890
2891        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2892            .expect("wiring must parse")
2893            .expect("wiring present")
2894            .into_parts();
2895        assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
2896        assert_eq!(tuning.timeout, Some(std::time::Duration::from_secs(5)));
2897        assert_eq!(tuning.max_concurrent_requests, Some(256));
2898        assert_eq!(tuning.pool_max_idle_per_host, Some(256));
2899    }
2900
2901    /// Omitting `endpoint` keeps discovery while still applying the tuning.
2902    #[test]
2903    fn consumer_wiring_object_without_endpoint_keeps_discovery() {
2904        let cfg = OrdersCfg(serde_json::json!({
2905            "clients": {
2906                "consumes": { "billing": { "max_concurrent_requests": 1 } }
2907            }
2908        }));
2909
2910        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2911            .expect("wiring must parse")
2912            .expect("wiring present")
2913            .into_parts();
2914        assert_eq!(endpoint, None, "omitted endpoint must keep discovery");
2915        assert_eq!(tuning.max_concurrent_requests, Some(1));
2916    }
2917
2918    /// A present-but-unparseable entry (wrong shape or wrong-typed tuning) is a
2919    /// boot error, matching the provider side's `clients.provides` — not a silent
2920    /// downgrade to discovery.
2921    #[test]
2922    fn consumer_wiring_malformed_entry_is_an_error() {
2923        let malformed = [
2924            // Not a ConsumerWiring object at all.
2925            serde_json::json!([1, 2, 3]),
2926            // A wrong-typed tuning value: a string where a count is expected, and
2927            // a bare number where a humantime duration string is expected.
2928            serde_json::json!({ "max_concurrent_requests": "lots" }),
2929            serde_json::json!({ "timeout": 5 }),
2930            // The same, even alongside an otherwise-valid endpoint override: the
2931            // whole entry fails, so the override is not silently honoured untuned.
2932            serde_json::json!({ "endpoint": "http://billing:8080", "timeout": 5 }),
2933        ];
2934        for entry in malformed {
2935            let cfg = OrdersCfg(serde_json::json!({
2936                "clients": { "consumes": { "billing": entry.clone() } }
2937            }));
2938            assert!(
2939                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2940                "a malformed entry (`{entry}`) must be a boot error, not silently dropped"
2941            );
2942        }
2943    }
2944
2945    /// A present-but-invalid `endpoint` is surfaced as an error, not downgraded to
2946    /// discovery — the operator asked for a specific endpoint that can't be honoured.
2947    #[test]
2948    fn consumer_wiring_invalid_endpoint_is_an_error() {
2949        for bad in ["", "billing", "/path/only"] {
2950            let cfg = OrdersCfg(serde_json::json!({
2951                "clients": { "consumes": { "billing": { "endpoint": bad } } }
2952            }));
2953            assert!(
2954                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2955                "a present-but-invalid endpoint (`{bad}`) must be a hard error, not survived"
2956            );
2957        }
2958    }
2959
2960    /// One record of what a test wired the phase with. The phase tests share this
2961    /// collector and run in parallel, so each finds its own entry by a unique
2962    /// tuning value.
2963    #[derive(Clone)]
2964    struct WiredCall {
2965        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2966        max_concurrent_requests: Option<usize>,
2967        /// A dropped credential is otherwise invisible — the only runtime symptom
2968        /// is a missing `X-ToolKit-Internal-Token` on every Profile 2/3 call.
2969        has_credential: bool,
2970    }
2971    static WIRED: std::sync::Mutex<Vec<WiredCall>> = std::sync::Mutex::new(Vec::new());
2972
2973    /// Stands in for the `#[toolkit::consumes]`-generated wire fn: records the
2974    /// resolver and tuning it was handed, then reports a remote binding.
2975    #[allow(
2976        clippy::unnecessary_wraps,
2977        clippy::needless_pass_by_value,
2978        reason = "must match the ConsumerRegistration::wire signature the macro emits"
2979    )]
2980    fn record_wire(
2981        _hub: &ClientHub,
2982        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2983        tuning: toolkit_contract::wiring::ClientTuning,
2984    ) -> anyhow::Result<crate::discovery::WireOutcome> {
2985        WIRED.lock().unwrap().push(WiredCall {
2986            resolver,
2987            max_concurrent_requests: tuning.max_concurrent_requests,
2988            has_credential: tuning.internal_token_provider.is_some(),
2989        });
2990        Ok(crate::discovery::WireOutcome::Remote)
2991    }
2992
2993    /// A consumer registration for the phase tests, wired directly so it never
2994    /// enters the link-time-global `inventory` set (which would leak onto other
2995    /// tests in this binary).
2996    fn test_registration() -> crate::discovery::ConsumerRegistration {
2997        crate::discovery::ConsumerRegistration {
2998            owner_gear: "orders",
2999            dep_gear: "billing",
3000            wire: record_wire,
3001        }
3002    }
3003
3004    /// A gRPC client warns about the knobs it does not apply, among them
3005    /// `stream_reconnect`; a REST client applies them all and stays quiet.
3006    #[test]
3007    #[tracing_test::traced_test]
3008    fn a_grpc_consumer_warns_about_knobs_it_does_not_apply() {
3009        let tuning: toolkit_contract::wiring::ClientTuning = serde_json::from_value(
3010            serde_json::json!({ "stream_reconnect": { "max_attempts": 3 } }),
3011        )
3012        .unwrap();
3013        let knobs = tuning.grpc_ignored_knobs();
3014        let reg = test_registration();
3015
3016        warn_grpc_ignored_knobs(&reg, crate::discovery::WireOutcome::Remote, &knobs);
3017        assert!(!logs_contain("does not apply"));
3018
3019        warn_grpc_ignored_knobs(
3020            &reg,
3021            crate::discovery::WireOutcome::RemoteGrpc {
3022                service: "billing.v1.BillingApi",
3023            },
3024            &knobs,
3025        );
3026        assert!(logs_contain("does not apply"));
3027        assert!(logs_contain("stream_reconnect"));
3028    }
3029
3030    /// Static-endpoint arm: an `endpoint` wires a `StaticEndpointResolver` pinned
3031    /// to it, threads the entry's tuning through, and marks the dep resolved
3032    /// immediately (no probe loop).
3033    #[tokio::test]
3034    async fn proxy_wiring_static_override_uses_static_resolver_and_marks_ready() {
3035        let mut map = std::collections::HashMap::new();
3036        map.insert(
3037            "orders".to_owned(),
3038            serde_json::json!({
3039                "clients": {
3040                    "consumes": {
3041                        "billing": {
3042                            "endpoint": "http://localhost:8081",
3043                            "max_concurrent_requests": 7
3044                        }
3045                    }
3046                }
3047            }),
3048        );
3049
3050        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3051        let runtime = HostRuntime::new(
3052            registry,
3053            Arc::new(MapCfg(map)),
3054            DbOptions::None,
3055            Arc::new(ClientHub::new()),
3056            CancellationToken::new(),
3057            Uuid::new_v4(),
3058            None,
3059        );
3060
3061        let reg = test_registration();
3062        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3063
3064        // Find *the* entry whose resolver yields the configured endpoint and
3065        // assert that same entry's tuning — OR-ing two flags independently across
3066        // every WIRED entry would pass even if the endpoint and the tuning had
3067        // arrived on two different wire calls.
3068        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3069        let mut matched = None;
3070        for call in &calls {
3071            if let Ok(Some(ep)) = call.resolver.resolve_endpoint("billing").await
3072                && ep == "http://localhost:8081"
3073            {
3074                matched = Some(call.clone());
3075                break;
3076            }
3077        }
3078        let matched = matched
3079            .expect("static override must wire a resolver pinned to the configured endpoint");
3080        assert_eq!(
3081            matched.max_concurrent_requests,
3082            Some(7),
3083            "the tuning on the same wire call as the static endpoint must be the configured one"
3084        );
3085
3086        // A static endpoint is resolvable by construction: the dep must be
3087        // resolved immediately rather than left gating /readyz.
3088        assert_eq!(
3089            runtime.dep_checker.unresolved_deps(),
3090            [crate::runtime::PREPARATION_GATE],
3091            "only the not yet started application group gates readiness"
3092        );
3093    }
3094
3095    /// An in-process provider that forgot to register its local impl must fail
3096    /// startup rather than silently wiring a self-pointing proxy: here both the
3097    /// consumer `orders` and provider `billing` are registered gears, but the
3098    /// consumer's wiring reports `Remote`.
3099    #[tokio::test]
3100    async fn proxy_wiring_in_process_provider_wired_remote_is_a_hard_error() {
3101        // Register the consumer `orders` and the provider `billing`, where billing
3102        // never provides its client (no local impl, no REST).
3103        let mut b = crate::registry::RegistryBuilder::default();
3104        b.register_core_with_meta("orders", &[], Arc::new(DummyCore));
3105        b.register_core_with_meta("billing", &[], Arc::new(DummyCore));
3106        let registry = b.build_topo_sorted().unwrap();
3107
3108        let runtime = HostRuntime::new(
3109            registry,
3110            Arc::new(MapCfg(std::collections::HashMap::new())),
3111            DbOptions::None,
3112            Arc::new(ClientHub::new()),
3113            CancellationToken::new(),
3114            Uuid::new_v4(),
3115            None,
3116        );
3117
3118        // `test_registration()` is owner=orders, dep=billing, and `record_wire`
3119        // reports `Remote` without registering a local impl — the bug scenario.
3120        let reg = test_registration();
3121        let err = runtime
3122            .wire_consumer_registrations(&[&reg])
3123            .expect_err("an in-process provider wired Remote must fail startup");
3124        let msg = err.to_string();
3125        assert!(
3126            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
3127            "expected a ProxyWiring error for the consumer gear, got: {msg}"
3128        );
3129        // Display must surface the source, so both the consumer and provider gear
3130        // names appear in the rendered message.
3131        assert!(
3132            msg.contains("orders") && msg.contains("billing"),
3133            "displayed error must name both consumer and provider, got: {msg}"
3134        );
3135    }
3136
3137    /// Tuning-only entry (no `endpoint`, the production shape): keeps the shared
3138    /// discovery resolver and leaves the dep gating readiness — a remote dep with
3139    /// no directory stays unresolved.
3140    #[tokio::test]
3141    async fn proxy_wiring_tuning_only_entry_keeps_discovery_and_gates_readiness() {
3142        let mut map = std::collections::HashMap::new();
3143        // A unique tuning value so this test can find its own WIRED entry among
3144        // the link-time-global registrations.
3145        map.insert(
3146            "orders".to_owned(),
3147            serde_json::json!({
3148                "clients": {
3149                    "consumes": { "billing": { "max_concurrent_requests": 4343 } }
3150                }
3151            }),
3152        );
3153
3154        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3155        let runtime = HostRuntime::new(
3156            registry,
3157            Arc::new(MapCfg(map)),
3158            DbOptions::None,
3159            Arc::new(ClientHub::new()),
3160            CancellationToken::new(),
3161            Uuid::new_v4(),
3162            None,
3163        );
3164
3165        let reg = test_registration();
3166        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3167
3168        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3169        let ours = calls
3170            .iter()
3171            .find(|c| c.max_concurrent_requests == Some(4343))
3172            .expect("our tuning-only wire call must have been recorded");
3173        assert!(
3174            matches!(ours.resolver.resolve_endpoint("billing").await, Ok(None)),
3175            "a tuning-only entry must keep discovery -- the resolver must not be pinned to a \
3176             static endpoint"
3177        );
3178
3179        // No directory + a remote dep → it must stay unresolved and gate /readyz.
3180        assert!(!runtime.dep_checker.all_resolved());
3181        assert!(
3182            runtime
3183                .dep_checker
3184                .unresolved_deps()
3185                .contains(&"billing".to_owned()),
3186            "a discovery-wired dep with no directory must gate readiness"
3187        );
3188    }
3189
3190    /// The process's platform-plane credential must ride on the tuning handed to
3191    /// the wire fn (Profile 2/3), else every inter-gear call ships without
3192    /// `X-ToolKit-Internal-Token`.
3193    #[tokio::test]
3194    async fn proxy_wiring_threads_platform_credential_onto_tuning() {
3195        use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
3196
3197        let mut map = std::collections::HashMap::new();
3198        map.insert(
3199            "orders".to_owned(),
3200            serde_json::json!({
3201                "clients": {
3202                    "consumes": { "billing": { "max_concurrent_requests": 4242 } }
3203                }
3204            }),
3205        );
3206
3207        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3208        let provider = InternalTokenProvider::new(|| CredentialState::NotConfigured);
3209        let runtime = HostRuntime::new(
3210            registry,
3211            Arc::new(MapCfg(map)),
3212            DbOptions::None,
3213            Arc::new(ClientHub::new()),
3214            CancellationToken::new(),
3215            Uuid::new_v4(),
3216            None,
3217        )
3218        .with_internal_token_provider(Some(provider));
3219
3220        let reg = test_registration();
3221        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3222
3223        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3224        let ours = calls
3225            .iter()
3226            .find(|c| c.max_concurrent_requests == Some(4242))
3227            .expect("our wire call must have been recorded");
3228        assert!(
3229            ours.has_credential,
3230            "the process credential must be threaded onto the tuning handed to the wire fn"
3231        );
3232    }
3233
3234    /// Phase-level: a non-absolute `endpoint` aborts proxy-wiring with
3235    /// `RegistryError::ProxyWiring` rather than silently downgrading to discovery
3236    /// (which would mark the dep resolved while every call fails).
3237    #[tokio::test]
3238    async fn proxy_wiring_invalid_endpoint_is_a_hard_error() {
3239        let mut map = std::collections::HashMap::new();
3240        map.insert(
3241            "orders".to_owned(),
3242            serde_json::json!({
3243                "clients": {
3244                    "consumes": {
3245                        "billing": { "endpoint": "", "max_concurrent_requests": 4444 }
3246                    }
3247                }
3248            }),
3249        );
3250
3251        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3252        let runtime = HostRuntime::new(
3253            registry,
3254            Arc::new(MapCfg(map)),
3255            DbOptions::None,
3256            Arc::new(ClientHub::new()),
3257            CancellationToken::new(),
3258            Uuid::new_v4(),
3259            None,
3260        );
3261
3262        let reg = test_registration();
3263        let err = runtime
3264            .wire_consumer_registrations(&[&reg])
3265            .expect_err("an invalid static endpoint must abort proxy-wiring");
3266        assert!(
3267            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
3268            "expected a ProxyWiring error for the owning gear, got {err:?}"
3269        );
3270    }
3271
3272    /// The override is keyed by the kebab *gear name* (`owner_gear`), not the
3273    /// struct ident. Regression guard: the macro once emitted
3274    /// `stringify!(StructIdent)`, so the lookup could never fire.
3275    #[test]
3276    fn static_endpoint_override_is_keyed_by_kebab_gear_name() {
3277        let mut map = std::collections::HashMap::new();
3278        map.insert(
3279            "api-contracts-consumer".to_owned(),
3280            serde_json::json!({
3281                "clients": {
3282                    "consumes": {
3283                        "api-contracts": { "endpoint": "http://localhost:9099" }
3284                    }
3285                }
3286            }),
3287        );
3288        let cfg = MapCfg(map);
3289
3290        assert_eq!(
3291            endpoint_override(&cfg, "api-contracts-consumer", "api-contracts").as_deref(),
3292            Some("http://localhost:9099"),
3293        );
3294        // The pre-fix value — the Rust struct ident — must NOT resolve.
3295        assert_eq!(
3296            endpoint_override(&cfg, "ApiContractsConsumer", "api-contracts"),
3297            None,
3298        );
3299    }
3300
3301    /// What a consumer's proxy was built from, for the per-consumer tests.
3302    trait ShippingApi: Send + Sync {
3303        fn wiring(&self) -> &ShippingProxy;
3304    }
3305
3306    struct ShippingProxy {
3307        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3308        timeout: Option<std::time::Duration>,
3309        max_attempts: Option<u32>,
3310        require_tls: Option<bool>,
3311    }
3312
3313    impl ShippingApi for ShippingProxy {
3314        fn wiring(&self) -> &ShippingProxy {
3315            self
3316        }
3317    }
3318
3319    /// The body `#[toolkit::consumes]` emits, with a proxy that keeps its
3320    /// resolver and tuning.
3321    fn wire_shipping(
3322        hub: &ClientHub,
3323        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3324        tuning: toolkit_contract::wiring::ClientTuning,
3325    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3326        if hub.try_get_local::<dyn ShippingApi>().is_some() {
3327            return Ok(crate::discovery::WireOutcome::Local);
3328        }
3329        if hub.has_remote_proxy::<dyn ShippingApi>() {
3330            if let Some(owner) = hub.owner() {
3331                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
3332            }
3333            return Ok(crate::discovery::WireOutcome::Remote);
3334        }
3335        hub.register_remote_proxy::<dyn ShippingApi>(Arc::new(ShippingProxy {
3336            resolver,
3337            timeout: tuning.timeout,
3338            max_attempts: tuning.retry.and_then(|r| r.max_attempts),
3339            require_tls: tuning.require_tls,
3340        }));
3341        Ok(crate::discovery::WireOutcome::Remote)
3342    }
3343
3344    fn shipping_registration(owner_gear: &'static str) -> crate::discovery::ConsumerRegistration {
3345        crate::discovery::ConsumerRegistration {
3346            owner_gear,
3347            dep_gear: "shipping",
3348            wire: wire_shipping,
3349        }
3350    }
3351
3352    /// A runtime hosting consumer gears `a` and `b` (shipping is remote).
3353    fn shipping_runtime(config: serde_json::Value) -> HostRuntime {
3354        let mut b = crate::registry::RegistryBuilder::default();
3355        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3356        b.register_core_with_meta("b", &[], Arc::new(DummyCore));
3357        let registry = b.build_topo_sorted().unwrap();
3358        let map = serde_json::from_value(config).unwrap();
3359        HostRuntime::new(
3360            registry,
3361            Arc::new(MapCfg(map)),
3362            DbOptions::None,
3363            Arc::new(ClientHub::new()),
3364            CancellationToken::new(),
3365            Uuid::new_v4(),
3366            None,
3367        )
3368    }
3369
3370    /// Issue #5686: two gears consuming one contract each get a proxy built
3371    /// from their own `clients.consumes` entry, whichever wires first.
3372    #[tokio::test]
3373    async fn each_consumer_gets_a_proxy_with_its_own_wiring() {
3374        let config = serde_json::json!({
3375            "a": { "clients": { "consumes": { "shipping": {
3376                "endpoint": "http://shipping-for-a:8080",
3377                "timeout": "1s",
3378                "retry": { "max_attempts": 2 },
3379                "require_tls": false
3380            } } } },
3381            "b": { "clients": { "consumes": { "shipping": {
3382                "endpoint": "http://shipping-for-b:8080",
3383                "timeout": "10s",
3384                "retry": { "max_attempts": 5 },
3385                "require_tls": true
3386            } } } }
3387        });
3388        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3389
3390        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3391            let runtime = shipping_runtime(config.clone());
3392            runtime.wire_consumer_registrations(&order).unwrap();
3393
3394            let hub = &runtime.client_hub;
3395            let a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3396            let b = hub.for_gear("b").get::<dyn ShippingApi>().unwrap();
3397            assert!(!Arc::ptr_eq(&a, &b));
3398            assert!(
3399                hub.try_get::<dyn ShippingApi>().is_none(),
3400                "a gear's proxy is not process-wide"
3401            );
3402
3403            let (a, b) = (a.wiring(), b.wiring());
3404            assert_eq!(
3405                a.resolver
3406                    .resolve_endpoint("shipping")
3407                    .await
3408                    .unwrap()
3409                    .as_deref(),
3410                Some("http://shipping-for-a:8080")
3411            );
3412            assert_eq!(
3413                b.resolver
3414                    .resolve_endpoint("shipping")
3415                    .await
3416                    .unwrap()
3417                    .as_deref(),
3418                Some("http://shipping-for-b:8080")
3419            );
3420            assert_eq!(a.timeout, Some(std::time::Duration::from_secs(1)));
3421            assert_eq!(b.timeout, Some(std::time::Duration::from_secs(10)));
3422            assert_eq!((a.max_attempts, b.max_attempts), (Some(2), Some(5)));
3423            assert_eq!((a.require_tls, b.require_tls), (Some(false), Some(true)));
3424        }
3425    }
3426
3427    /// An owner that is not a gear in this process (an SDK-level registration)
3428    /// wires a process-wide proxy that every gear's view can read.
3429    #[tokio::test]
3430    async fn an_unknown_owner_wires_a_process_wide_proxy() {
3431        let runtime = shipping_runtime(serde_json::json!({}));
3432        let reg = shipping_registration("shipping-sdk");
3433        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3434
3435        let hub = &runtime.client_hub;
3436        let shared = hub.get::<dyn ShippingApi>().unwrap();
3437        let seen_by_a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3438        assert!(Arc::ptr_eq(&shared, &seen_by_a));
3439    }
3440
3441    /// With one consumer on a static endpoint and another on discovery, the dep
3442    /// stays unresolved: the second consumer's provider is not found yet.
3443    #[tokio::test]
3444    async fn a_static_consumer_does_not_resolve_a_dep_another_consumer_discovers() {
3445        let config = serde_json::json!({
3446            "a": { "clients": { "consumes": { "shipping": {
3447                "endpoint": "http://shipping:8080"
3448            } } } }
3449        });
3450        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3451
3452        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3453            let runtime = shipping_runtime(config.clone());
3454            runtime.wire_consumer_registrations(&order).unwrap();
3455
3456            assert!(
3457                runtime
3458                    .dep_checker
3459                    .unresolved_deps()
3460                    .contains(&"shipping".to_owned()),
3461                "the discovery consumer must keep the dep gating readiness"
3462            );
3463        }
3464    }
3465
3466    /// Same mix with a directory: the dep stays unresolved until the provider
3467    /// is advertised, then the probe resolves it.
3468    #[tokio::test]
3469    async fn a_mixed_dep_resolves_once_the_provider_is_advertised() {
3470        let config = serde_json::json!({
3471            "a": { "clients": { "consumes": { "shipping": {
3472                "endpoint": "http://shipping:8080"
3473            } } } }
3474        });
3475        let runtime = shipping_runtime(config);
3476        let gears = Arc::new(crate::runtime::GearManager::new());
3477        runtime
3478            .client_hub
3479            .register::<dyn crate::DirectoryClient>(Arc::new(
3480                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3481            ));
3482        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3483        runtime
3484            .wire_consumer_registrations(&[&reg_a, &reg_b])
3485            .unwrap();
3486
3487        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3488        assert!(
3489            runtime
3490                .dep_checker
3491                .unresolved_deps()
3492                .contains(&"shipping".to_owned()),
3493            "no provider is advertised yet"
3494        );
3495
3496        gears
3497            .register_instance(Arc::new(
3498                crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3499                    .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3500            ))
3501            .unwrap();
3502        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3503            while runtime
3504                .dep_checker
3505                .unresolved_deps()
3506                .contains(&"shipping".to_owned())
3507            {
3508                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3509            }
3510        })
3511        .await
3512        .expect("the probe must resolve the dep once the provider is advertised");
3513        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3514        runtime.owned.cancel();
3515    }
3516
3517    /// Both consumers on static endpoints: resolved at wiring time.
3518    #[tokio::test]
3519    async fn static_consumers_resolve_the_dep() {
3520        let entry = serde_json::json!({ "clients": { "consumes": { "shipping": {
3521            "endpoint": "http://shipping:8080"
3522        } } } });
3523        let runtime = shipping_runtime(serde_json::json!({ "a": entry, "b": entry }));
3524        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3525        runtime
3526            .wire_consumer_registrations(&[&reg_a, &reg_b])
3527            .unwrap();
3528
3529        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3530    }
3531
3532    /// One gear consuming the same contract twice is a boot error naming it.
3533    #[tokio::test]
3534    async fn a_gear_consuming_a_contract_twice_fails_wiring() {
3535        let runtime = shipping_runtime(serde_json::json!({}));
3536        let reg = shipping_registration("a");
3537        let duplicate = shipping_registration("a");
3538        let err = runtime
3539            .wire_consumer_registrations(&[&reg, &duplicate])
3540            .expect_err("a duplicate consumer must fail wiring");
3541        assert!(
3542            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "a"),
3543            "got {err:?}"
3544        );
3545    }
3546
3547    const SHIPPING_GRPC: &str = "shipping.v1.ShippingApi";
3548
3549    /// `wire_shipping` for a gRPC client: same proxy, readiness on the service.
3550    fn wire_shipping_grpc(
3551        hub: &ClientHub,
3552        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3553        tuning: toolkit_contract::wiring::ClientTuning,
3554    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3555        match wire_shipping(hub, resolver, tuning)? {
3556            crate::discovery::WireOutcome::Remote => {
3557                Ok(crate::discovery::WireOutcome::RemoteGrpc {
3558                    service: SHIPPING_GRPC,
3559                })
3560            }
3561            other => Ok(other),
3562        }
3563    }
3564
3565    fn shipping_grpc_registration(
3566        owner_gear: &'static str,
3567    ) -> crate::discovery::ConsumerRegistration {
3568        crate::discovery::ConsumerRegistration {
3569            owner_gear,
3570            dep_gear: "shipping",
3571            wire: wire_shipping_grpc,
3572        }
3573    }
3574
3575    /// `shipping_runtime` with an in-process directory the test can publish to.
3576    fn shipping_runtime_with_directory(
3577        config: serde_json::Value,
3578    ) -> (HostRuntime, Arc<crate::runtime::GearManager>) {
3579        let runtime = shipping_runtime(config);
3580        let gears = Arc::new(crate::runtime::GearManager::new());
3581        runtime
3582            .client_hub
3583            .register::<dyn crate::DirectoryClient>(Arc::new(
3584                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3585            ));
3586        (runtime, gears)
3587    }
3588
3589    fn publish(gears: &crate::runtime::GearManager, instance: crate::runtime::GearInstance) {
3590        gears.register_instance(Arc::new(instance)).unwrap();
3591    }
3592
3593    /// Every consumed dep resolved; only the startup preparation gate,
3594    /// which these wiring-only tests never lift, is left.
3595    fn deps_resolved(runtime: &HostRuntime) -> bool {
3596        runtime.dep_checker.unresolved_deps() == [PREPARATION_GATE]
3597    }
3598
3599    async fn wait_resolved(runtime: &HostRuntime) -> bool {
3600        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3601            while !deps_resolved(runtime) {
3602                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3603            }
3604        })
3605        .await
3606        .is_ok()
3607    }
3608
3609    /// A gRPC consumer's dep is probed by service name, not by the gear's
3610    /// REST endpoint.
3611    #[tokio::test]
3612    async fn a_grpc_dep_resolves_when_its_service_is_published() {
3613        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3614        let reg = shipping_grpc_registration("a");
3615        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3616
3617        // A REST endpoint for the gear does not satisfy a gRPC consumer.
3618        publish(
3619            &gears,
3620            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3621                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3622        );
3623        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3624        assert!(!deps_resolved(&runtime));
3625
3626        publish(
3627            &gears,
3628            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3629                SHIPPING_GRPC,
3630                crate::runtime::Endpoint::http("shipping", 50051),
3631            ),
3632        );
3633        assert!(
3634            wait_resolved(&runtime).await,
3635            "the published service resolves the dep"
3636        );
3637        runtime.cancel.cancel();
3638    }
3639
3640    /// A REST consumer and a gRPC consumer of one dep: ready only when both
3641    /// targets resolve.
3642    #[tokio::test]
3643    async fn a_dep_consumed_over_both_transports_waits_for_both() {
3644        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3645        let (rest, grpc) = (shipping_registration("a"), shipping_grpc_registration("b"));
3646        runtime
3647            .wire_consumer_registrations(&[&rest, &grpc])
3648            .unwrap();
3649
3650        publish(
3651            &gears,
3652            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3653                SHIPPING_GRPC,
3654                crate::runtime::Endpoint::http("shipping", 50051),
3655            ),
3656        );
3657        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3658        assert!(!deps_resolved(&runtime), "the REST consumer still waits");
3659
3660        publish(
3661            &gears,
3662            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3663                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3664        );
3665        assert!(wait_resolved(&runtime).await);
3666        runtime.cancel.cancel();
3667    }
3668
3669    /// Wiring runs in batches (system gears, then the rest). A static consumer
3670    /// wired in one batch must not resolve a dep that a consumer in another
3671    /// batch discovers, in either order.
3672    #[tokio::test]
3673    async fn a_static_batch_does_not_resolve_a_dep_another_batch_discovers() {
3674        let config = serde_json::json!({
3675            "a": { "clients": { "consumes": { "shipping": {
3676                "endpoint": "http://shipping:8080"
3677            } } } }
3678        });
3679        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3680
3681        for (first, second) in [(&reg_a, &reg_b), (&reg_b, &reg_a)] {
3682            let runtime = shipping_runtime(config.clone());
3683            runtime.wire_consumer_registrations(&[first]).unwrap();
3684            runtime.wire_consumer_registrations(&[second]).unwrap();
3685
3686            assert!(
3687                runtime
3688                    .dep_checker
3689                    .unresolved_deps()
3690                    .contains(&"shipping".to_owned()),
3691                "the discovery consumer must keep the dep gating readiness"
3692            );
3693        }
3694    }
3695
3696    /// Probes started by two batches for one dep: the dep resolves only when
3697    /// the targets of both have.
3698    #[tokio::test]
3699    async fn probes_from_two_batches_resolve_the_dep_together() {
3700        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3701        let (rest, grpc) = (shipping_registration("a"), shipping_grpc_registration("b"));
3702        runtime.wire_consumer_registrations(&[&rest]).unwrap();
3703        runtime.wire_consumer_registrations(&[&grpc]).unwrap();
3704
3705        publish(
3706            &gears,
3707            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3708                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3709        );
3710        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3711        assert!(!deps_resolved(&runtime), "the gRPC consumer still waits");
3712
3713        publish(
3714            &gears,
3715            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3716                SHIPPING_GRPC,
3717                crate::runtime::Endpoint::http("shipping", 50051),
3718            ),
3719        );
3720        assert!(wait_resolved(&runtime).await);
3721        runtime.cancel.cancel();
3722    }
3723
3724    /// `grpc_endpoint` is a static override for the gRPC client only.
3725    #[tokio::test]
3726    async fn grpc_endpoint_wires_the_grpc_client_statically() {
3727        let config = serde_json::json!({
3728            "a": { "clients": { "consumes": { "shipping": {
3729                "grpc_endpoint": "http://shipping:50051"
3730            } } } }
3731        });
3732        let runtime = shipping_runtime(config);
3733        let reg = shipping_grpc_registration("a");
3734        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3735
3736        assert!(deps_resolved(&runtime));
3737        let proxy = runtime
3738            .client_hub
3739            .for_gear("a")
3740            .get::<dyn ShippingApi>()
3741            .unwrap();
3742        assert_eq!(
3743            proxy
3744                .wiring()
3745                .resolver
3746                .resolve_grpc_endpoint(SHIPPING_GRPC)
3747                .await
3748                .unwrap()
3749                .as_deref(),
3750            Some("http://shipping:50051")
3751        );
3752    }
3753
3754    /// `grpc_endpoint` alone leaves a REST consumer of the dep on discovery.
3755    #[tokio::test]
3756    async fn grpc_endpoint_does_not_pin_the_rest_client() {
3757        let config = serde_json::json!({
3758            "a": { "clients": { "consumes": { "shipping": {
3759                "grpc_endpoint": "http://shipping:50051"
3760            } } } }
3761        });
3762        let runtime = shipping_runtime(config);
3763        let reg = shipping_registration("a");
3764        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3765
3766        assert!(!deps_resolved(&runtime), "REST still waits for discovery");
3767    }
3768
3769    /// One `endpoint` cannot serve one gear's REST and gRPC clients.
3770    #[tokio::test]
3771    async fn one_endpoint_for_both_transports_of_a_gear_is_an_error() {
3772        let runtime = shipping_runtime(serde_json::json!({
3773            "a": { "clients": { "consumes": { "shipping": {
3774                "endpoint": "http://shipping:8080"
3775            } } } }
3776        }));
3777        let rest = shipping_registration("a");
3778        // In real code the two clients are two contracts; the test proxy type
3779        // is shared, so the gRPC one goes into another view to get past the
3780        // duplicate check.
3781        let grpc = crate::discovery::ConsumerRegistration {
3782            owner_gear: "a",
3783            dep_gear: "shipping",
3784            wire: |hub, resolver, tuning| {
3785                wire_shipping_grpc(&hub.for_gear("a-grpc"), resolver, tuning)
3786            },
3787        };
3788        let err = runtime
3789            .wire_consumer_registrations(&[&rest, &grpc])
3790            .expect_err("a single endpoint for both transports must fail");
3791        assert!(err.to_string().contains("grpc_endpoint"), "{err}");
3792    }
3793
3794    struct DummyGrpc;
3795
3796    #[async_trait::async_trait]
3797    impl crate::contracts::GrpcServiceCapability for DummyGrpc {
3798        async fn get_grpc_services(
3799            &self,
3800            _ctx: &GearCtx,
3801        ) -> anyhow::Result<Vec<crate::contracts::RegisterGrpcServiceFn>> {
3802            Ok(Vec::new())
3803        }
3804    }
3805
3806    /// An in-process provider that serves gRPC is a valid gRPC dependency; one
3807    /// that serves neither REST nor gRPC is not.
3808    #[tokio::test]
3809    async fn an_in_process_grpc_dep_must_serve_grpc() {
3810        let build = |grpc: bool| {
3811            let mut b = crate::registry::RegistryBuilder::default();
3812            b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3813            b.register_core_with_meta("shipping", &[], Arc::new(DummyCore));
3814            if grpc {
3815                b.register_grpc_service_with_meta("shipping", Arc::new(DummyGrpc));
3816            }
3817            HostRuntime::new(
3818                b.build_topo_sorted().unwrap(),
3819                Arc::new(MapCfg(std::collections::HashMap::new())),
3820                DbOptions::None,
3821                Arc::new(ClientHub::new()),
3822                CancellationToken::new(),
3823                Uuid::new_v4(),
3824                None,
3825            )
3826        };
3827        let reg = shipping_grpc_registration("a");
3828
3829        build(true).wire_consumer_registrations(&[&reg]).unwrap();
3830        let err = build(false)
3831            .wire_consumer_registrations(&[&reg])
3832            .expect_err("no gRPC service to call");
3833        assert!(err.to_string().contains("serves no gRPC service"), "{err}");
3834    }
3835
3836    #[tokio::test]
3837    async fn test_post_init_runs_after_all_init_for_every_gear_system_group_first() {
3838        #[derive(Clone)]
3839        struct TrackHooks {
3840            name: &'static str,
3841            events: Arc<Mutex<Vec<String>>>,
3842        }
3843
3844        #[async_trait::async_trait]
3845        impl Gear for TrackHooks {
3846            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3847                self.events.lock().await.push(format!("init:{}", self.name));
3848                Ok(())
3849            }
3850
3851            async fn post_init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3852                self.events
3853                    .lock()
3854                    .await
3855                    .push(format!("post_init:{}", self.name));
3856                Ok(())
3857            }
3858        }
3859
3860        impl SystemCapability for TrackHooks {}
3861
3862        let events = Arc::new(Mutex::new(Vec::<String>::new()));
3863        let sys_a = Arc::new(TrackHooks {
3864            name: "sys_a",
3865            events: events.clone(),
3866        });
3867        let user_b = Arc::new(TrackHooks {
3868            name: "user_b",
3869            events: events.clone(),
3870        });
3871        let user_c = Arc::new(TrackHooks {
3872            name: "user_c",
3873            events: events.clone(),
3874        });
3875
3876        let mut builder = RegistryBuilder::default();
3877        builder.register_core_with_meta("sys_a", &[], sys_a.clone() as Arc<dyn Gear>);
3878        builder.register_core_with_meta("user_b", &["sys_a"], user_b.clone() as Arc<dyn Gear>);
3879        builder.register_core_with_meta("user_c", &["user_b"], user_c.clone() as Arc<dyn Gear>);
3880        builder.register_system_with_meta("sys_a", sys_a.clone() as Arc<dyn SystemCapability>);
3881
3882        let registry = builder.build_topo_sorted().unwrap();
3883
3884        let client_hub = Arc::new(ClientHub::new());
3885        let cancel = CancellationToken::new();
3886        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3887
3888        let runtime = HostRuntime::new(
3889            registry,
3890            config_provider,
3891            DbOptions::None,
3892            client_hub,
3893            cancel,
3894            Uuid::new_v4(),
3895            None,
3896        );
3897
3898        // Run init phase for all gears, then post_init as a separate barrier phase.
3899        runtime.run_init_phase().await.unwrap();
3900        runtime.run_post_init_phase().await.unwrap();
3901
3902        let events = events.lock().await.clone();
3903        let first_post_init = events
3904            .iter()
3905            .position(|e| e.starts_with("post_init:"))
3906            .expect("expected post_init events");
3907        assert!(
3908            events[..first_post_init]
3909                .iter()
3910                .all(|e| e.starts_with("init:")),
3911            "expected all init events before post_init, got: {events:?}"
3912        );
3913
3914        // The system group first, each group in topological order.
3915        assert_eq!(
3916            events,
3917            vec![
3918                "init:sys_a",
3919                "init:user_b",
3920                "init:user_c",
3921                "post_init:sys_a",
3922                "post_init:user_b",
3923                "post_init:user_c",
3924            ]
3925        );
3926    }
3927
3928    /// The force-exit watchdog (shared by init and stop) fires only when it is
3929    /// never disarmed within the deadline. The decision is split from
3930    /// `process::exit` into `watchdog_verdict` so it is unit-testable without
3931    /// killing the test process; these cover the hung case and both disarm cases.
3932    #[test]
3933    fn watchdog_times_out_when_not_disarmed() {
3934        let (_tx, rx) = std::sync::mpsc::channel::<()>();
3935        // Hold the sender; never signal → the deadline elapses → TimedOut.
3936        assert_eq!(
3937            watchdog_verdict(&rx, std::time::Duration::from_millis(20)),
3938            WatchdogVerdict::TimedOut
3939        );
3940    }
3941
3942    #[test]
3943    fn init_watchdog_subprocess() {
3944        const CHILD_MODE: &str = "TOOLKIT_INIT_WATCHDOG_TEST_MODE";
3945        struct WatchdogGear(String);
3946
3947        #[async_trait::async_trait]
3948        impl Gear for WatchdogGear {
3949            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3950                match self.0.as_str() {
3951                    "success" => (),
3952                    // Async hang: the async timeout observes it → recoverable error.
3953                    "async-hang" | "cancelled" => {
3954                        std::future::pending::<()>().await;
3955                    }
3956                    // Synchronous block: no async timer can fire; only the
3957                    // OS-thread watchdog catches it → force-exit.
3958                    "blocking" | "blocking-no-tracing" => {
3959                        std::thread::sleep(std::time::Duration::from_secs(3600));
3960                    }
3961                    "error" => anyhow::bail!("init failed"),
3962                    other => panic!("unexpected watchdog test mode: {other}"),
3963                }
3964                Ok(())
3965            }
3966        }
3967
3968        let Ok(mode) = std::env::var(CHILD_MODE) else {
3969            for (mode, expected_code) in [
3970                ("success", 0),
3971                ("async-hang", 0),
3972                ("blocking", 1),
3973                ("blocking-no-tracing", 1),
3974                ("error", 0),
3975                ("cancelled", 0),
3976            ] {
3977                let mut child = std::process::Command::new(std::env::current_exe().unwrap())
3978                    .args([
3979                        "--exact",
3980                        "runtime::host_runtime::tests::init_watchdog_subprocess",
3981                        "--nocapture",
3982                    ])
3983                    .env(CHILD_MODE, mode)
3984                    .stdout(std::process::Stdio::piped())
3985                    .stderr(std::process::Stdio::piped())
3986                    .spawn()
3987                    .unwrap();
3988                let limit = std::time::Instant::now() + std::time::Duration::from_secs(5);
3989                while child.try_wait().unwrap().is_none() {
3990                    if std::time::Instant::now() >= limit {
3991                        child.kill().unwrap();
3992                        let output = child.wait_with_output().unwrap();
3993                        panic!("watchdog subprocess {mode} hung: {output:?}");
3994                    }
3995                    std::thread::sleep(std::time::Duration::from_millis(10));
3996                }
3997                let output = child.wait_with_output().unwrap();
3998                assert_eq!(
3999                    output.status.code(),
4000                    Some(expected_code),
4001                    "{mode}: {output:?}"
4002                );
4003                if mode.starts_with("blocking") {
4004                    // One line must carry ERROR + message + gear name (holds even
4005                    // with tracing OFF, where only the stderr fallback is emitted).
4006                    let logs = String::from_utf8_lossy(&output.stderr);
4007                    assert!(
4008                        logs.lines().any(|line| line.contains("ERROR")
4009                            && line.contains("init timed out")
4010                            && line.contains("watchdog-test")),
4011                        "{logs}"
4012                    );
4013                }
4014            }
4015            return;
4016        };
4017
4018        tracing_subscriber::fmt()
4019            .with_ansi(false)
4020            .with_max_level(if mode == "blocking-no-tracing" {
4021                tracing::level_filters::LevelFilter::OFF
4022            } else {
4023                tracing::level_filters::LevelFilter::INFO
4024            })
4025            .with_writer(std::io::stderr)
4026            .try_init()
4027            .unwrap();
4028        tokio::runtime::Builder::new_current_thread()
4029            .enable_all()
4030            .build()
4031            .unwrap()
4032            .block_on(async {
4033                let mut builder = RegistryBuilder::default();
4034                builder.register_core_with_meta(
4035                    "watchdog-test",
4036                    &[],
4037                    Arc::new(WatchdogGear(mode.clone())) as Arc<dyn Gear>,
4038                );
4039                let runtime = HostRuntime::new(
4040                    builder.build_topo_sorted().unwrap(),
4041                    Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4042                    DbOptions::None,
4043                    Arc::new(ClientHub::new()),
4044                    CancellationToken::new(),
4045                    Uuid::new_v4(),
4046                    None,
4047                )
4048                .with_init_deadline(std::time::Duration::from_millis(200));
4049
4050                #[allow(
4051                    clippy::match_same_arms,
4052                    reason = "`success` returns normally; in `blocking*` the same call never returns and the watchdog force-exits"
4053                )]
4054                match mode.as_str() {
4055                    "cancelled" => {
4056                        // Dropping the phase future disarms the watchdog: no exit.
4057                        assert!(
4058                            tokio::time::timeout(
4059                                std::time::Duration::from_millis(20),
4060                                runtime.run_init_phase(),
4061                            )
4062                            .await
4063                            .is_err()
4064                        );
4065                    }
4066                    "success" => {
4067                        runtime.run_init_phase().await.unwrap();
4068                    }
4069                    "async-hang" => {
4070                        // Recoverable error, not a force-exit.
4071                        let err = runtime.run_init_phase().await.unwrap_err();
4072                        assert!(matches!(
4073                            err,
4074                            RegistryError::InitTimeout {
4075                                gear: "watchdog-test",
4076                                ..
4077                            }
4078                        ));
4079                    }
4080                    "error" => {
4081                        let err = runtime.run_init_phase().await.unwrap_err();
4082                        assert!(matches!(
4083                            err,
4084                            RegistryError::Init {
4085                                gear: "watchdog-test",
4086                                ..
4087                            }
4088                        ));
4089                    }
4090                    // Never returns; the OS-thread watchdog force-exits instead.
4091                    "blocking" | "blocking-no-tracing" => {
4092                        runtime.run_init_phase().await.unwrap();
4093                    }
4094                    other => panic!("unexpected watchdog test mode: {other}"),
4095                }
4096                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
4097            });
4098    }
4099
4100    #[test]
4101    fn watchdog_disarms_when_signalled() {
4102        let (tx, rx) = std::sync::mpsc::channel::<()>();
4103        tx.send(()).unwrap();
4104        // A generous deadline proves we return on the signal, not by timing out.
4105        assert_eq!(
4106            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
4107            WatchdogVerdict::Disarmed
4108        );
4109    }
4110
4111    #[test]
4112    fn watchdog_disarms_when_sender_is_dropped() {
4113        let (tx, rx) = std::sync::mpsc::channel::<()>();
4114        drop(tx); // guarded future dropped before it finished
4115        assert_eq!(
4116            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
4117            WatchdogVerdict::Disarmed
4118        );
4119    }
4120
4121    /// When `GearContextBuilder::for_gear` fails (here: the gear's database
4122    /// config references a global server that does not exist), the init phase
4123    /// must surface it as `RegistryError::Init` naming the gear — not hang or
4124    /// force-exit.
4125    #[cfg(feature = "db")]
4126    #[tokio::test]
4127    async fn init_ctx_failure_surfaces_as_init_error() {
4128        use figment::{Figment, providers::Serialized};
4129
4130        struct NeedsDbGear;
4131
4132        #[async_trait::async_trait]
4133        impl Gear for NeedsDbGear {
4134            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4135                Ok(())
4136            }
4137        }
4138
4139        let mut builder = RegistryBuilder::default();
4140        builder.register_core_with_meta("needsdb", &[], Arc::new(NeedsDbGear) as Arc<dyn Gear>);
4141        let registry = builder.build_topo_sorted().unwrap();
4142
4143        let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
4144            "gears": {
4145                "needsdb": {
4146                    "database": { "server": "does-not-exist" }
4147                }
4148            }
4149        })));
4150        let db_manager =
4151            toolkit_db::DbManager::from_figment(figment, std::path::PathBuf::from("/tmp/test"))
4152                .unwrap();
4153
4154        let runtime = HostRuntime::new(
4155            registry,
4156            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4157            DbOptions::Manager(Arc::new(db_manager)),
4158            Arc::new(ClientHub::new()),
4159            CancellationToken::new(),
4160            Uuid::new_v4(),
4161            None,
4162        );
4163
4164        let err = runtime.run_init_phase().await.unwrap_err();
4165        assert!(
4166            matches!(err, RegistryError::Init { gear, .. } if gear == "needsdb"),
4167            "expected RegistryError::Init for needsdb, got {err:?}"
4168        );
4169    }
4170
4171    /// A REST gear opting out of directory advertisement is served but not
4172    /// advertised (nor deregistered) as a REST provider.
4173    #[test]
4174    fn a_rest_gear_can_opt_out_of_directory_advertisement() {
4175        struct Rest {
4176            advertised: bool,
4177        }
4178        #[async_trait::async_trait]
4179        impl Gear for Rest {
4180            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4181                Ok(())
4182            }
4183        }
4184        impl crate::contracts::RestApiCapability for Rest {
4185            fn register_rest(
4186                &self,
4187                _ctx: &GearCtx,
4188                router: axum::Router,
4189                _openapi: &dyn crate::api::OpenApiRegistry,
4190            ) -> anyhow::Result<axum::Router> {
4191                Ok(router)
4192            }
4193            fn advertised_in_directory(&self) -> bool {
4194                self.advertised
4195            }
4196        }
4197
4198        let mut builder = RegistryBuilder::default();
4199        for (name, advertised) in [("advertised", true), ("hidden", false)] {
4200            let gear = Arc::new(Rest { advertised });
4201            builder.register_core_with_meta(name, &[], gear.clone() as Arc<dyn Gear>);
4202            builder.register_rest_with_meta(
4203                name,
4204                gear as Arc<dyn crate::contracts::RestApiCapability>,
4205            );
4206        }
4207        let runtime = HostRuntime::new(
4208            builder.build_topo_sorted().unwrap(),
4209            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4210            DbOptions::None,
4211            Arc::new(ClientHub::new()),
4212            CancellationToken::new(),
4213            Uuid::new_v4(),
4214            None,
4215        );
4216
4217        assert_eq!(runtime.rest_provider_gears(), vec!["advertised"]);
4218    }
4219
4220    #[tokio::test]
4221    async fn test_stop_phase_provides_fresh_deadline_token() {
4222        use std::sync::atomic::AtomicBool;
4223
4224        struct TokenCheckGear {
4225            stop_was_called: AtomicBool,
4226            token_was_cancelled_on_entry: AtomicBool,
4227        }
4228
4229        #[async_trait::async_trait]
4230        impl Gear for TokenCheckGear {
4231            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4232                Ok(())
4233            }
4234        }
4235
4236        #[async_trait::async_trait]
4237        impl RunnableCapability for TokenCheckGear {
4238            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4239                Ok(())
4240            }
4241            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4242                // Record that stop() was called
4243                self.stop_was_called.store(true, Ordering::SeqCst);
4244                // Record whether the token was already cancelled when stop() was called
4245                self.token_was_cancelled_on_entry
4246                    .store(deadline_token.is_cancelled(), Ordering::SeqCst);
4247                Ok(())
4248            }
4249        }
4250
4251        let gear = Arc::new(TokenCheckGear {
4252            stop_was_called: AtomicBool::new(false),
4253            // Default to true to detect if stop() was never called
4254            token_was_cancelled_on_entry: AtomicBool::new(true),
4255        });
4256
4257        let mut builder = RegistryBuilder::default();
4258        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4259        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4260
4261        let registry = builder.build_topo_sorted().unwrap();
4262        let client_hub = Arc::new(ClientHub::new());
4263        let cancel = CancellationToken::new();
4264        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4265
4266        let runtime = HostRuntime::new(
4267            registry,
4268            config_provider,
4269            DbOptions::None,
4270            client_hub,
4271            cancel.clone(),
4272            Uuid::new_v4(),
4273            None,
4274        );
4275
4276        // Run stop phase - the deadline token should NOT be cancelled
4277        runtime.run_start_phase().await.unwrap();
4278        runtime.run_stop_phase().await.unwrap();
4279
4280        // First, verify stop() was actually called (guards against silent registration failures)
4281        assert!(
4282            gear.stop_was_called.load(Ordering::SeqCst),
4283            "stop() was never called - gear may not have been registered correctly"
4284        );
4285
4286        // The token should NOT have been cancelled when stop() was called
4287        // This is the key fix: gears get a fresh token, not the already-cancelled root token
4288        assert!(
4289            !gear.token_was_cancelled_on_entry.load(Ordering::SeqCst),
4290            "deadline_token should NOT be cancelled when stop() is called - this enables graceful shutdown"
4291        );
4292    }
4293
4294    #[tokio::test]
4295    async fn test_stop_phase_graceful_shutdown_completes_before_deadline() {
4296        use std::sync::atomic::AtomicBool;
4297        use std::time::Duration;
4298
4299        struct GracefulGear {
4300            graceful_completed: AtomicBool,
4301            deadline_fired: AtomicBool,
4302        }
4303
4304        #[async_trait::async_trait]
4305        impl Gear for GracefulGear {
4306            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4307                Ok(())
4308            }
4309        }
4310
4311        #[async_trait::async_trait]
4312        impl RunnableCapability for GracefulGear {
4313            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4314                Ok(())
4315            }
4316            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4317                // Simulate graceful shutdown that completes quickly (10ms)
4318                tokio::select! {
4319                    () = tokio::time::sleep(Duration::from_millis(10)) => {
4320                        self.graceful_completed.store(true, Ordering::SeqCst);
4321                    }
4322                    () = deadline_token.cancelled() => {
4323                        self.deadline_fired.store(true, Ordering::SeqCst);
4324                    }
4325                }
4326                Ok(())
4327            }
4328        }
4329
4330        let gear = Arc::new(GracefulGear {
4331            graceful_completed: AtomicBool::new(false),
4332            deadline_fired: AtomicBool::new(false),
4333        });
4334
4335        let mut builder = RegistryBuilder::default();
4336        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4337        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4338
4339        let registry = builder.build_topo_sorted().unwrap();
4340        let client_hub = Arc::new(ClientHub::new());
4341        let cancel = CancellationToken::new();
4342        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4343
4344        // Use a long deadline (5s) - gear should complete gracefully before this
4345        let runtime = HostRuntime::new(
4346            registry,
4347            config_provider,
4348            DbOptions::None,
4349            client_hub,
4350            cancel.clone(),
4351            Uuid::new_v4(),
4352            None,
4353        )
4354        .with_shutdown_deadline(Duration::from_secs(5));
4355
4356        runtime.run_start_phase().await.unwrap();
4357        runtime.run_stop_phase().await.unwrap();
4358
4359        // Graceful shutdown should have completed
4360        assert!(
4361            gear.graceful_completed.load(Ordering::SeqCst),
4362            "graceful shutdown should complete"
4363        );
4364        // Deadline should NOT have fired (gear finished before deadline)
4365        assert!(
4366            !gear.deadline_fired.load(Ordering::SeqCst),
4367            "deadline should not fire when graceful shutdown completes quickly"
4368        );
4369    }
4370
4371    #[tokio::test]
4372    async fn test_stop_phase_deadline_fires_for_slow_gear() {
4373        use std::sync::atomic::AtomicBool;
4374        use std::time::Duration;
4375
4376        struct SlowGear {
4377            graceful_completed: AtomicBool,
4378            deadline_fired: AtomicBool,
4379        }
4380
4381        #[async_trait::async_trait]
4382        impl Gear for SlowGear {
4383            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4384                Ok(())
4385            }
4386        }
4387
4388        #[async_trait::async_trait]
4389        impl RunnableCapability for SlowGear {
4390            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4391                Ok(())
4392            }
4393            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4394                // Simulate slow graceful shutdown (would take 10s, but deadline is 100ms)
4395                tokio::select! {
4396                    () = tokio::time::sleep(Duration::from_secs(10)) => {
4397                        self.graceful_completed.store(true, Ordering::SeqCst);
4398                    }
4399                    () = deadline_token.cancelled() => {
4400                        self.deadline_fired.store(true, Ordering::SeqCst);
4401                    }
4402                }
4403                Ok(())
4404            }
4405        }
4406
4407        let gear = Arc::new(SlowGear {
4408            graceful_completed: AtomicBool::new(false),
4409            deadline_fired: AtomicBool::new(false),
4410        });
4411
4412        let mut builder = RegistryBuilder::default();
4413        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4414        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4415
4416        let registry = builder.build_topo_sorted().unwrap();
4417        let client_hub = Arc::new(ClientHub::new());
4418        let cancel = CancellationToken::new();
4419        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4420
4421        // Use a short deadline (100ms) - gear should be interrupted by deadline
4422        let runtime = HostRuntime::new(
4423            registry,
4424            config_provider,
4425            DbOptions::None,
4426            client_hub,
4427            cancel.clone(),
4428            Uuid::new_v4(),
4429            None,
4430        )
4431        .with_shutdown_deadline(Duration::from_millis(100));
4432
4433        runtime.run_start_phase().await.unwrap();
4434        runtime.run_stop_phase().await.unwrap();
4435
4436        // Graceful shutdown should NOT have completed (deadline fired first)
4437        assert!(
4438            !gear.graceful_completed.load(Ordering::SeqCst),
4439            "graceful shutdown should not complete when deadline fires first"
4440        );
4441        // Deadline should have fired
4442        assert!(
4443            gear.deadline_fired.load(Ordering::SeqCst),
4444            "deadline should fire for slow gears"
4445        );
4446    }
4447
4448    /// `billing` never answers; `orders` answers at once.
4449    struct HangingResolver;
4450
4451    #[async_trait::async_trait]
4452    impl toolkit_contract::runtime::resolving::EndpointResolver for HangingResolver {
4453        async fn resolve_endpoint(
4454            &self,
4455            gear: &str,
4456        ) -> Result<Option<String>, toolkit_contract::runtime::resolving::ResolveError> {
4457            if gear == "billing" {
4458                std::future::pending::<()>().await;
4459            }
4460            Ok(Some(format!("http://{gear}")))
4461        }
4462    }
4463
4464    fn probe_fixture(
4465        deps: &[&str],
4466    ) -> (
4467        Readiness,
4468        Arc<crate::runtime::readiness::DependencyChecker>,
4469        std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>,
4470    ) {
4471        let checker = Arc::new(crate::runtime::readiness::DependencyChecker::new());
4472        let mut pending = std::collections::BTreeMap::new();
4473        for dep in deps {
4474            checker.register_dep(*dep);
4475            pending.insert((*dep).to_owned(), [Probe::Rest].into());
4476        }
4477        let readiness = Readiness {
4478            deps: Arc::clone(&checker),
4479            pending: Arc::new(parking_lot::Mutex::new(pending.clone())),
4480        };
4481        (readiness, checker, pending)
4482    }
4483
4484    #[tokio::test(start_paused = true)]
4485    async fn a_hung_lookup_times_out_and_does_not_block_other_deps() {
4486        let (readiness, checker, pending) = probe_fixture(&["billing", "orders"]);
4487        let cancel = CancellationToken::new();
4488        let probe = tokio::spawn(probe_until_resolved(
4489            Arc::new(HangingResolver),
4490            readiness,
4491            cancel.clone(),
4492            pending,
4493        ));
4494
4495        tokio::time::sleep(PROBE_LOOKUP_TIMEOUT + std::time::Duration::from_secs(1)).await;
4496        assert_eq!(checker.unresolved_deps(), vec!["billing".to_owned()]);
4497
4498        cancel.cancel();
4499        probe.await.unwrap();
4500    }
4501
4502    #[tokio::test(start_paused = true)]
4503    async fn cancel_stops_the_probe_during_a_lookup() {
4504        let (readiness, checker, pending) = probe_fixture(&["billing"]);
4505        let cancel = CancellationToken::new();
4506        let probe = tokio::spawn(probe_until_resolved(
4507            Arc::new(HangingResolver),
4508            readiness,
4509            cancel.clone(),
4510            pending,
4511        ));
4512        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
4513        cancel.cancel();
4514
4515        tokio::time::timeout(std::time::Duration::from_millis(10), probe)
4516            .await
4517            .expect("the probe stops without waiting for the lookup")
4518            .unwrap();
4519        assert_eq!(checker.unresolved_deps(), vec!["billing".to_owned()]);
4520    }
4521}
4522
4523#[cfg(test)]
4524#[cfg_attr(coverage_nightly, coverage(off))]
4525#[path = "host_runtime_preparation_tests.rs"]
4526mod host_runtime_preparation_tests;
4527
4528#[cfg(test)]
4529#[cfg_attr(coverage_nightly, coverage(off))]
4530#[path = "host_runtime_rest_bootstrap_tests.rs"]
4531mod host_runtime_rest_bootstrap_tests;