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