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 auth policy from the same specs.
2209#[cfg(feature = "bootstrap")]
2210type ComposedOopRouter = (Router, String, toolkit_http_middleware::RouteAuthPolicy);
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 auth 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 route_auth =
2285            super::oop_serve::route_auth_policy(composition.registry.operation_specs.iter());
2286
2287        Ok((composition.router.clone(), json, route_auth))
2288    }
2289
2290    /// Run the full `OoP` gear lifecycle: phases (`pre_init` … `start`), then
2291    /// serve the composed router with framework probes, background
2292    /// self-registration, dependency resolution, and graceful drain, then the
2293    /// `stop` phase.
2294    ///
2295    /// The listener binds first. The system group's routes attach as
2296    /// soon as it started — platform-plane calls only, tenant-plane calls get
2297    /// `503` — and the process is present in the directory then if its
2298    /// advertised gear is a system gear. The application group's routes
2299    /// attach on the same listener once it started.
2300    ///
2301    /// # Errors
2302    /// Returns an error if any lifecycle phase or the HTTP server fails.
2303    pub async fn run_oop_serving(
2304        self,
2305        options: crate::runtime::OopServeOptions,
2306    ) -> anyhow::Result<()> {
2307        use crate::runtime::ReadinessState;
2308
2309        tracing::info!("Running OoP serving lifecycle");
2310
2311        // Make the directory client reachable to the proxy-wiring phase, which
2312        // resolves remote `#[toolkit::consumes]` providers through the
2313        // `ClientHub`. The `OoP` presence loop uses `options.directory`
2314        // directly; consumer wiring reads it here.
2315        if self.client_hub.get::<dyn crate::DirectoryClient>().is_err() {
2316            self.client_hub
2317                .register::<dyn crate::DirectoryClient>(Arc::clone(&options.directory));
2318        }
2319
2320        // Shared gear healthcheck registry (same mechanism as the api-gateway
2321        // host path). Seeded with the root cancellation token so in-flight
2322        // checks are aborted on shutdown. Populated during router composition.
2323        let hc_registry = Arc::new(
2324            crate::healthcheck::RestHealthcheckRegistry::with_cancellation(self.cancel.clone()),
2325        );
2326
2327        // Readiness gates on `#[toolkit::consumes]` dependencies only — the same
2328        // policy as the in-process host path — via the shared `DependencyChecker`
2329        // fed by the proxy-wiring phase below. `deps = [...]`-only declarations
2330        // remain for topo-sort ordering but do NOT gate `/readyz`. The
2331        // healthcheck registry supplies the per-gear readiness dimension; both
2332        // feed the `/readyz` aggregate.
2333        let readiness = ReadinessState::from_checker(
2334            Arc::clone(&self.dep_checker),
2335            Arc::clone(&hc_registry),
2336            options.healthcheck_timeout,
2337        );
2338
2339        // Bind the HTTP server and serve probes BEFORE the (possibly slow)
2340        // lifecycle phases, so the kubelet's liveness probe (`/healthz`) passes
2341        // immediately instead of getting connection-refused during `start()`.
2342        // Gear routes reply `503 starting` until attached below.
2343        let mut server = super::oop_serve::OopHttpServer::start(
2344            Arc::clone(&readiness),
2345            options,
2346            self.cancel.clone(),
2347        )
2348        .await?;
2349
2350        // Publish the server's presence manager so every in-process registrar
2351        // that runs during the startup phases below — grpc-hub's registrar,
2352        // event-broker's role registration — renews its lease through one
2353        // manager instead of registering without a renewer.
2354        self.client_hub
2355            .register::<PresenceManager>(server.presence_manager());
2356
2357        self.spawn_drain_watcher();
2358        let mut composition = OopComposition::default();
2359        let outcome = self
2360            .run_oop_startup(&mut server, &hc_registry, &mut composition)
2361            .await;
2362
2363        let serve_result = match outcome {
2364            Ok(outcome) => {
2365                let failed = startup_failure(outcome);
2366                // End failed preparation promptly so the supervisor can restart.
2367                if failed.is_some() {
2368                    self.cancel.cancel();
2369                }
2370                // Serve until cancelled, drain, then deregister.
2371                let joined = server.join().await;
2372                match failed {
2373                    Some(failure) => {
2374                        if let Err(e) = joined {
2375                            tracing::warn!(error = %e, "OoP server after a failed application group reported an error");
2376                        }
2377                        Err(failure.into())
2378                    }
2379                    None => joined,
2380                }
2381            }
2382            Err(e) => {
2383                tracing::error!(error = %e, "OoP startup failed before serving gear routes");
2384                // Tear down the probe server that is already bound.
2385                self.cancel.cancel();
2386                if let Err(join_err) = server.join().await {
2387                    tracing::warn!(error = %join_err, "OoP probe server teardown after startup failure errored");
2388                }
2389                Err(e)
2390            }
2391        };
2392
2393        // Served or failed to start: the runtime's tasks end and gears stop. Errors are
2394        // logged but do not fail the shutdown process (same contract as
2395        // run_stop_phase).
2396        if let Err(e) = self.shut_down().await {
2397            tracing::warn!(error = %e, "OoP stop phase reported an error");
2398        }
2399
2400        serve_result
2401    }
2402
2403    /// The `OoP` phases from the manifests to the attached application routes.
2404    async fn run_oop_startup(
2405        &self,
2406        server: &mut super::oop_serve::OopHttpServer,
2407        hc_registry: &Arc<crate::healthcheck::RestHealthcheckRegistry>,
2408        composition: &mut OopComposition,
2409    ) -> anyhow::Result<AppStartup> {
2410        let system = self.group(true);
2411        let app = self.group(false);
2412        let advertised = server.options().gear_name.clone();
2413        let advertised_is_system = system.iter().any(|e| e.name == advertised.as_str());
2414        let root_is_advertised = || {
2415            self.registry
2416                .gears()
2417                .iter()
2418                .find(|entry| entry.name == advertised.as_str())
2419                .and_then(|entry| entry.caps.query::<RestApiCap>())
2420                .is_none_or(|rest| rest.advertised_in_directory())
2421        };
2422
2423        let manifests = self.build_gts_manifests()?;
2424        let regs = self.consumer_registrations();
2425        self.check_wiring_groups(&manifests, &regs)?;
2426
2427        // System group, complete before the application group.
2428        self.run_pre_init_phase_for(&system).await?;
2429        #[cfg(feature = "db")]
2430        self.run_db_phase_for(&system).await?;
2431        self.run_init_phase_for(&system).await?;
2432        self.wire_system_clients(&regs)?;
2433        self.run_post_init_phase_for(&system).await?;
2434        let mut grpc_seen = HashSet::new();
2435        self.run_grpc_initial_phase(&mut grpc_seen).await?;
2436        self.run_start_phase_for(&system).await?;
2437
2438        // System routes on the bound listener: platform-plane calls
2439        // only until the application group attached its routes.
2440        if system.iter().any(|e| e.caps.has::<RestApiCap>()) {
2441            let (router, openapi, route_auth) = self
2442                .compose_oop_router(server.options(), hc_registry, &system, composition)
2443                .await?;
2444            server.publish_bootstrap_routes(router, openapi, route_auth);
2445            if advertised_is_system && root_is_advertised() {
2446                server.start_presence();
2447            }
2448            // Every co-hosted system provider is discoverable at once,
2449            // whatever the root gear: an external publisher must reach a
2450            // registry the application group here may be waiting for.
2451            for entry in &system {
2452                if entry.name != advertised.as_str()
2453                    && entry
2454                        .caps
2455                        .query::<RestApiCap>()
2456                        .is_some_and(|rest| rest.advertised_in_directory())
2457                {
2458                    server.start_provider_presence(entry.name.to_owned());
2459                }
2460            }
2461        }
2462
2463        // Application group: pre-init, migrations, the registry clients, then
2464        // the GTS barrier.
2465        self.run_pre_init_phase_for(&app).await?;
2466        #[cfg(feature = "db")]
2467        self.run_db_phase_for(&app).await?;
2468        self.wire_registry_clients(&manifests)?;
2469        match self.run_gts_publication_barrier(&manifests).await? {
2470            AppStartup::Started => {}
2471            other => {
2472                self.grpc_installers.close();
2473                return Ok(other);
2474            }
2475        }
2476        self.run_init_phase_for(&app).await?;
2477        // Proxy-wiring before start: a gear resolving a consumed contract
2478        // during `start` finds the client in the hub under both profiles.
2479        self.wire_consumer_registrations(&regs)?;
2480        self.run_legacy_finalization().await?;
2481        self.run_post_init_phase_for(&app).await?;
2482        self.run_grpc_late_phase(&mut grpc_seen).await?;
2483        self.run_start_phase_for(&app).await?;
2484
2485        // The gear lifecycle has populated the ClientHub. If an in-process
2486        // authn stack (e.g. a linked authn-resolver gear) registered a
2487        // DynBearerAuthenticator bridge, install the tenant plane now —
2488        // before the final routes layer security_context_middleware. (The
2489        // platform plane is built eagerly at bootstrap from
2490        // `oop_http.internal_auth`.)
2491        server.resolve_bearer_authenticator(&self.client_hub);
2492        let all: Vec<&GearEntry> = self.registry.gears().iter().collect();
2493        let (router, openapi, route_auth) = self
2494            .compose_oop_router(server.options(), hc_registry, &all, composition)
2495            .await?;
2496        // Publish the full routes (they go live), then start directory
2497        // presence of the advertised gear: the directory never advertises it
2498        // while its routes reply 503.
2499        server.attach(router, openapi, route_auth)?;
2500        // First presence of an application root; a system root's restarts
2501        // with the full `OpenAPI` document.
2502        if root_is_advertised() {
2503            server.start_presence();
2504        }
2505        self.dep_checker.mark_resolved(PREPARATION_GATE);
2506        Ok(AppStartup::Started)
2507    }
2508}
2509
2510/// The transports one gear consumes one dep over, and whether its
2511/// `clients.consumes.<dep>` sets only `endpoint`.
2512#[derive(Default)]
2513struct PairTransports {
2514    rest: bool,
2515    grpc: bool,
2516    only_endpoint: bool,
2517}
2518
2519impl PairTransports {
2520    fn record(&mut self, outcome: crate::discovery::WireOutcome, only_endpoint: bool) {
2521        match outcome {
2522            crate::discovery::WireOutcome::Remote => self.rest = true,
2523            crate::discovery::WireOutcome::RemoteGrpc { .. } => self.grpc = true,
2524            crate::discovery::WireOutcome::Local => {}
2525        }
2526        self.only_endpoint = only_endpoint;
2527    }
2528
2529    /// One `endpoint` cannot serve a gear's REST and gRPC clients of a dep.
2530    fn check(&self, reg: &crate::discovery::ConsumerRegistration) -> Result<(), RegistryError> {
2531        if self.rest && self.grpc && self.only_endpoint {
2532            return Err(RegistryError::ProxyWiring {
2533                gear: reg.owner_gear,
2534                source: anyhow::anyhow!(
2535                    "gear '{}' consumes '{}' over both REST and gRPC, and \
2536                     `clients.consumes.{}` sets only `endpoint`; one address cannot serve \
2537                     both. Add `grpc_endpoint` for the gRPC client.",
2538                    reg.owner_gear,
2539                    reg.dep_gear,
2540                    reg.dep_gear,
2541                ),
2542            });
2543        }
2544        Ok(())
2545    }
2546}
2547
2548/// A gRPC client ignores the REST pool and concurrency knobs and
2549/// `stream_reconnect`; say so.
2550fn warn_grpc_ignored_knobs(
2551    reg: &crate::discovery::ConsumerRegistration,
2552    outcome: crate::discovery::WireOutcome,
2553    knobs: &[&str],
2554) {
2555    if let crate::discovery::WireOutcome::RemoteGrpc { service } = outcome
2556        && !knobs.is_empty()
2557    {
2558        tracing::warn!(
2559            owner = reg.owner_gear,
2560            dep = reg.dep_gear,
2561            service,
2562            knobs = ?knobs,
2563            "proxy-wiring: clients.consumes sets knobs a gRPC client does not apply; \
2564             they have no effect"
2565        );
2566    }
2567}
2568
2569/// What the readiness probe resolves for one consumed dep.
2570#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2571enum Probe {
2572    /// The provider gear's REST endpoint.
2573    Rest,
2574    /// A gRPC service, by fully qualified name.
2575    Grpc(&'static str),
2576}
2577
2578/// Directory targets still unresolved, per consumed dep.
2579type PendingTargets =
2580    Arc<parking_lot::Mutex<std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>>>;
2581
2582/// Where a probe reports: the readiness gate and the targets shared by every
2583/// wiring batch.
2584struct Readiness {
2585    deps: Arc<super::readiness::DependencyChecker>,
2586    pending: PendingTargets,
2587}
2588
2589impl Readiness {
2590    /// `target` of `dep` resolved. The dep is resolved once no batch waits for
2591    /// any other target of it.
2592    fn resolved(&self, dep: &str, target: &Probe) {
2593        let mut pending = self.pending.lock();
2594        let done = match pending.get_mut(dep) {
2595            Some(targets) => {
2596                targets.remove(target);
2597                targets.is_empty()
2598            }
2599            None => true,
2600        };
2601        if done {
2602            pending.remove(dep);
2603            if self.deps.mark_resolved(dep) {
2604                tracing::info!(dep = %dep, "readiness: dependency resolved");
2605            }
2606        }
2607    }
2608}
2609
2610/// Probe rounds after which a gRPC service still missing from the directory
2611/// gets a hint in the log: with backoff this is about a minute.
2612const GRPC_HINT_ROUNDS: u32 = 10;
2613
2614fn unreachable_dep(reg: &crate::discovery::ConsumerRegistration, why: &str) -> RegistryError {
2615    RegistryError::ProxyWiring {
2616        gear: reg.owner_gear,
2617        source: anyhow::anyhow!(
2618            "consumer '{}' depends on in-process gear '{}', which registered no local impl \
2619             and {why}; the provider must register its client in init() \
2620             (#[toolkit::provides] wire_* or ClientHub::register) or serve the contract over \
2621             the transport the consumer uses.",
2622            reg.owner_gear,
2623            reg.dep_gear,
2624        ),
2625    }
2626}
2627
2628/// Upper bound on one directory lookup of the readiness probe. An injected
2629/// `DirectoryClient` need not time out by itself, and a hung lookup would
2630/// block every target after it.
2631const PROBE_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
2632
2633/// Resolve every pending target with backoff, marking a dep ready once all of
2634/// its targets resolve. A lookup that takes longer than
2635/// [`PROBE_LOOKUP_TIMEOUT`] is retried next round. Stops on `cancel`, also
2636/// during a lookup.
2637async fn probe_until_resolved(
2638    resolver: Arc<dyn toolkit_contract::runtime::resolving::EndpointResolver>,
2639    readiness: Readiness,
2640    cancel: CancellationToken,
2641    mut pending: std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>,
2642) {
2643    const BASE: std::time::Duration = std::time::Duration::from_millis(100);
2644    const MAX: std::time::Duration = std::time::Duration::from_secs(30);
2645    let mut backoff = BASE;
2646    let mut rounds = 0u32;
2647    while !pending.is_empty() {
2648        let mut still_pending = std::collections::BTreeMap::new();
2649        for (dep, targets) in pending {
2650            let mut left = std::collections::BTreeSet::new();
2651            for target in targets {
2652                let lookup = async {
2653                    match &target {
2654                        Probe::Rest => resolver.resolve_endpoint(&dep).await,
2655                        Probe::Grpc(service) => resolver.resolve_grpc_endpoint(service).await,
2656                    }
2657                };
2658                let lookup = tokio::select! {
2659                    () = cancel.cancelled() => return,
2660                    lookup = tokio::time::timeout(PROBE_LOOKUP_TIMEOUT, lookup) => lookup,
2661                };
2662                match lookup {
2663                    Ok(Ok(Some(_))) => readiness.resolved(&dep, &target),
2664                    // No live instance yet — expected during startup churn.
2665                    Ok(Ok(None)) => {
2666                        left.insert(target);
2667                    }
2668                    // Genuine directory-backend failure: surface it (a stuck
2669                    // Starting / 503 pod otherwise has no diagnostic trail).
2670                    Ok(Err(e)) => {
2671                        tracing::warn!(dep = %dep, target = ?target, error = %e, "readiness: directory lookup failed");
2672                        left.insert(target);
2673                    }
2674                    Err(_) => {
2675                        tracing::warn!(
2676                            dep = %dep,
2677                            target = ?target,
2678                            timeout = ?PROBE_LOOKUP_TIMEOUT,
2679                            "readiness: directory lookup timed out"
2680                        );
2681                        left.insert(target);
2682                    }
2683                }
2684            }
2685            if !left.is_empty() {
2686                still_pending.insert(dep, left);
2687            }
2688        }
2689        pending = still_pending;
2690        if pending.is_empty() {
2691            break;
2692        }
2693        rounds = rounds.saturating_add(1);
2694        if rounds == GRPC_HINT_ROUNDS {
2695            for (dep, targets) in &pending {
2696                for target in targets {
2697                    if let Probe::Grpc(service) = target {
2698                        tracing::warn!(
2699                            dep = %dep,
2700                            service,
2701                            "readiness: gRPC service still not in the directory; check that the \
2702                             provider's process runs grpc-hub with a listen_addr and an \
2703                             advertise_addr it can register"
2704                        );
2705                    }
2706                }
2707            }
2708        }
2709        tokio::select! {
2710            () = cancel.cancelled() => break,
2711            () = tokio::time::sleep(backoff) => {}
2712        }
2713        backoff = (backoff * 2).min(MAX);
2714    }
2715}
2716
2717/// Read the [`ConsumerWiring`] for `owner`'s client of `dep` from
2718/// `gears.<owner>.clients` ([`crate::clients_config::consumer_wiring`]).
2719///
2720/// `Ok(None)` when absent (the dep keeps discovery). A *present* entry that cannot
2721/// be read is an `Err` that aborts proxy-wiring, as on the provider side.
2722fn read_consumer_wiring(
2723    cfg: &dyn ConfigProvider,
2724    owner_gear: &str,
2725    dep_gear: &str,
2726) -> Result<Option<toolkit_contract::wiring::ConsumerWiring>, anyhow::Error> {
2727    crate::clients_config::consumer_wiring(cfg, owner_gear, dep_gear)
2728}
2729
2730#[cfg(test)]
2731#[cfg(feature = "bootstrap")]
2732#[cfg_attr(coverage_nightly, coverage(off))]
2733#[path = "host_runtime_oop_tests.rs"]
2734mod host_runtime_oop_tests;
2735
2736#[cfg(test)]
2737#[cfg_attr(coverage_nightly, coverage(off))]
2738mod tests {
2739    use super::*;
2740    use crate::context::GearCtx;
2741    use crate::contracts::{Gear, RunnableCapability, SystemCapability};
2742    use crate::registry::RegistryBuilder;
2743    use std::sync::Arc;
2744    use std::sync::atomic::{AtomicUsize, Ordering};
2745    use tokio::sync::Mutex;
2746
2747    #[derive(Default)]
2748    #[allow(dead_code)]
2749    struct DummyCore;
2750    #[async_trait::async_trait]
2751    impl Gear for DummyCore {
2752        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2753            Ok(())
2754        }
2755    }
2756
2757    struct StopOrderTracker {
2758        my_order: usize,
2759        stop_order: Arc<AtomicUsize>,
2760    }
2761
2762    impl StopOrderTracker {
2763        fn new(counter: &Arc<AtomicUsize>, stop_order: Arc<AtomicUsize>) -> Self {
2764            let my_order = counter.fetch_add(1, Ordering::SeqCst);
2765            Self {
2766                my_order,
2767                stop_order,
2768            }
2769        }
2770    }
2771
2772    #[async_trait::async_trait]
2773    impl Gear for StopOrderTracker {
2774        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2775            Ok(())
2776        }
2777    }
2778
2779    #[async_trait::async_trait]
2780    impl RunnableCapability for StopOrderTracker {
2781        async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2782            Ok(())
2783        }
2784        async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2785            let order = self.stop_order.fetch_add(1, Ordering::SeqCst);
2786            tracing::info!(my_order = self.my_order, stop_order = order, "Gear stopped");
2787            Ok(())
2788        }
2789    }
2790
2791    #[tokio::test]
2792    async fn test_stop_phase_reverse_order() {
2793        let counter = Arc::new(AtomicUsize::new(0));
2794        let stop_order = Arc::new(AtomicUsize::new(0));
2795
2796        let gear_a = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2797        let gear_b = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2798        let gear_c = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2799
2800        let mut builder = RegistryBuilder::default();
2801        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2802        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2803        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2804
2805        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2806        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2807        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2808
2809        let registry = builder.build_topo_sorted().unwrap();
2810
2811        // Verify gear order is a -> b -> c
2812        let gear_names: Vec<_> = registry.gears().iter().map(|m| m.name).collect();
2813        assert_eq!(gear_names, vec!["a", "b", "c"]);
2814
2815        let client_hub = Arc::new(ClientHub::new());
2816        let cancel = CancellationToken::new();
2817        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2818
2819        let runtime = HostRuntime::new(
2820            registry,
2821            config_provider,
2822            DbOptions::None,
2823            client_hub,
2824            cancel.clone(),
2825            Uuid::new_v4(),
2826            None,
2827        );
2828
2829        // Run stop phase
2830        runtime.run_start_phase().await.unwrap();
2831        runtime.run_stop_phase().await.unwrap();
2832
2833        // Verify gears stopped in reverse order: c (stop_order=0), b (stop_order=1), a (stop_order=2)
2834        // Gear order is: a=0, b=1, c=2
2835        // Stop order should be: c=0, b=1, a=2
2836        assert_eq!(stop_order.load(Ordering::SeqCst), 3);
2837    }
2838
2839    #[tokio::test]
2840    async fn test_stop_phase_continues_on_error() {
2841        struct FailingGear {
2842            should_fail: bool,
2843            stopped: Arc<AtomicUsize>,
2844        }
2845
2846        #[async_trait::async_trait]
2847        impl Gear for FailingGear {
2848            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2849                Ok(())
2850            }
2851        }
2852
2853        #[async_trait::async_trait]
2854        impl RunnableCapability for FailingGear {
2855            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2856                Ok(())
2857            }
2858            async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2859                self.stopped.fetch_add(1, Ordering::SeqCst);
2860                if self.should_fail {
2861                    anyhow::bail!("Intentional failure")
2862                }
2863                Ok(())
2864            }
2865        }
2866
2867        let stopped = Arc::new(AtomicUsize::new(0));
2868        let gear_a = Arc::new(FailingGear {
2869            should_fail: false,
2870            stopped: stopped.clone(),
2871        });
2872        let gear_b = Arc::new(FailingGear {
2873            should_fail: true,
2874            stopped: stopped.clone(),
2875        });
2876        let gear_c = Arc::new(FailingGear {
2877            should_fail: false,
2878            stopped: stopped.clone(),
2879        });
2880
2881        let mut builder = RegistryBuilder::default();
2882        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2883        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2884        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2885
2886        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2887        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2888        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2889
2890        let registry = builder.build_topo_sorted().unwrap();
2891
2892        let client_hub = Arc::new(ClientHub::new());
2893        let cancel = CancellationToken::new();
2894        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2895
2896        let runtime = HostRuntime::new(
2897            registry,
2898            config_provider,
2899            DbOptions::None,
2900            client_hub,
2901            cancel.clone(),
2902            Uuid::new_v4(),
2903            None,
2904        );
2905
2906        // Run stop phase - should not fail even though gear_b fails
2907        runtime.run_start_phase().await.unwrap();
2908        runtime.run_stop_phase().await.unwrap();
2909
2910        // All gears should have attempted to stop
2911        assert_eq!(stopped.load(Ordering::SeqCst), 3);
2912    }
2913
2914    struct EmptyConfigProvider;
2915    impl ConfigProvider for EmptyConfigProvider {
2916        fn get_gear_config(&self, _gear_name: &str) -> Option<&serde_json::Value> {
2917            None
2918        }
2919    }
2920
2921    /// Serves one config blob for owner gear `orders` (the owner every
2922    /// `read_consumer_wiring` test uses) and nothing for anything else.
2923    struct OrdersCfg(serde_json::Value);
2924    impl ConfigProvider for OrdersCfg {
2925        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2926            (gear == "orders").then_some(&self.0)
2927        }
2928    }
2929
2930    /// Serves config blobs by owner-gear name (for tests wiring several gears).
2931    struct MapCfg(std::collections::HashMap<String, serde_json::Value>);
2932    impl ConfigProvider for MapCfg {
2933        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2934            self.0.get(gear)
2935        }
2936    }
2937
2938    /// Extract just the static-endpoint override from a `clients.consumes` entry.
2939    fn endpoint_override(cfg: &dyn ConfigProvider, owner: &str, dep: &str) -> Option<String> {
2940        super::read_consumer_wiring(cfg, owner, dep)
2941            .expect("clients.consumes must not error for a valid/absent endpoint")
2942            .and_then(|w| w.into_parts().0)
2943    }
2944
2945    #[test]
2946    fn static_endpoint_override_reads_the_clients_consumes_entry() {
2947        let mut map = std::collections::HashMap::new();
2948        map.insert(
2949            "orders".to_owned(),
2950            serde_json::json!({
2951                "clients": {
2952                    "consumes": { "billing": { "endpoint": "http://localhost:8081" } }
2953                }
2954            }),
2955        );
2956        let cfg = MapCfg(map);
2957
2958        // Present override is read from `clients.consumes.<dep>.endpoint`.
2959        assert_eq!(
2960            endpoint_override(&cfg, "orders", "billing").as_deref(),
2961            Some("http://localhost:8081")
2962        );
2963        // Absent dep / owner → None (falls through to directory resolution).
2964        assert_eq!(endpoint_override(&cfg, "orders", "inventory"), None);
2965        assert_eq!(endpoint_override(&cfg, "warehouse", "billing"), None);
2966        assert_eq!(
2967            endpoint_override(&EmptyConfigProvider, "orders", "billing"),
2968            None
2969        );
2970    }
2971
2972    /// The object form yields both the `endpoint` override and the flattened
2973    /// `ClientTuning`.
2974    #[test]
2975    fn consumer_wiring_object_form_yields_endpoint_and_tuning() {
2976        let cfg = OrdersCfg(serde_json::json!({
2977            "clients": {
2978                "consumes": {
2979                    "billing": {
2980                        "endpoint": "http://billing:8080",
2981                        "timeout": "5s",
2982                        "max_concurrent_requests": 256,
2983                        "pool_max_idle_per_host": 256
2984                    }
2985                }
2986            }
2987        }));
2988
2989        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2990            .expect("wiring must parse")
2991            .expect("wiring present")
2992            .into_parts();
2993        assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
2994        assert_eq!(tuning.timeout, Some(std::time::Duration::from_secs(5)));
2995        assert_eq!(tuning.max_concurrent_requests, Some(256));
2996        assert_eq!(tuning.pool_max_idle_per_host, Some(256));
2997    }
2998
2999    /// Omitting `endpoint` keeps discovery while still applying the tuning.
3000    #[test]
3001    fn consumer_wiring_object_without_endpoint_keeps_discovery() {
3002        let cfg = OrdersCfg(serde_json::json!({
3003            "clients": {
3004                "consumes": { "billing": { "max_concurrent_requests": 1 } }
3005            }
3006        }));
3007
3008        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
3009            .expect("wiring must parse")
3010            .expect("wiring present")
3011            .into_parts();
3012        assert_eq!(endpoint, None, "omitted endpoint must keep discovery");
3013        assert_eq!(tuning.max_concurrent_requests, Some(1));
3014    }
3015
3016    /// A present-but-unparseable entry (wrong shape or wrong-typed tuning) is a
3017    /// boot error, matching the provider side's `clients.provides` — not a silent
3018    /// downgrade to discovery.
3019    #[test]
3020    fn consumer_wiring_malformed_entry_is_an_error() {
3021        let malformed = [
3022            // Not a ConsumerWiring object at all.
3023            serde_json::json!([1, 2, 3]),
3024            // A wrong-typed tuning value: a string where a count is expected, and
3025            // a bare number where a humantime duration string is expected.
3026            serde_json::json!({ "max_concurrent_requests": "lots" }),
3027            serde_json::json!({ "timeout": 5 }),
3028            // The same, even alongside an otherwise-valid endpoint override: the
3029            // whole entry fails, so the override is not silently honoured untuned.
3030            serde_json::json!({ "endpoint": "http://billing:8080", "timeout": 5 }),
3031        ];
3032        for entry in malformed {
3033            let cfg = OrdersCfg(serde_json::json!({
3034                "clients": { "consumes": { "billing": entry.clone() } }
3035            }));
3036            assert!(
3037                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
3038                "a malformed entry (`{entry}`) must be a boot error, not silently dropped"
3039            );
3040        }
3041    }
3042
3043    /// A present-but-invalid `endpoint` is surfaced as an error, not downgraded to
3044    /// discovery — the operator asked for a specific endpoint that can't be honoured.
3045    #[test]
3046    fn consumer_wiring_invalid_endpoint_is_an_error() {
3047        for bad in ["", "billing", "/path/only"] {
3048            let cfg = OrdersCfg(serde_json::json!({
3049                "clients": { "consumes": { "billing": { "endpoint": bad } } }
3050            }));
3051            assert!(
3052                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
3053                "a present-but-invalid endpoint (`{bad}`) must be a hard error, not survived"
3054            );
3055        }
3056    }
3057
3058    /// One record of what a test wired the phase with. The phase tests share this
3059    /// collector and run in parallel, so each finds its own entry by a unique
3060    /// tuning value.
3061    #[derive(Clone)]
3062    struct WiredCall {
3063        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3064        max_concurrent_requests: Option<usize>,
3065        /// A dropped credential is otherwise invisible — the only runtime symptom
3066        /// is a missing `X-ToolKit-Internal-Token` on every Profile 2/3 call.
3067        has_credential: bool,
3068    }
3069    static WIRED: std::sync::Mutex<Vec<WiredCall>> = std::sync::Mutex::new(Vec::new());
3070
3071    /// Stands in for the `#[toolkit::consumes]`-generated wire fn: records the
3072    /// resolver and tuning it was handed, then reports a remote binding.
3073    #[allow(
3074        clippy::unnecessary_wraps,
3075        clippy::needless_pass_by_value,
3076        reason = "must match the ConsumerRegistration::wire signature the macro emits"
3077    )]
3078    fn record_wire(
3079        _hub: &ClientHub,
3080        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3081        tuning: toolkit_contract::wiring::ClientTuning,
3082    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3083        WIRED.lock().unwrap().push(WiredCall {
3084            resolver,
3085            max_concurrent_requests: tuning.max_concurrent_requests,
3086            has_credential: tuning.internal_token_provider.is_some(),
3087        });
3088        Ok(crate::discovery::WireOutcome::Remote)
3089    }
3090
3091    /// A consumer registration for the phase tests, wired directly so it never
3092    /// enters the link-time-global `inventory` set (which would leak onto other
3093    /// tests in this binary).
3094    fn test_registration() -> crate::discovery::ConsumerRegistration {
3095        crate::discovery::ConsumerRegistration {
3096            owner_gear: "orders",
3097            dep_gear: "billing",
3098            wire: record_wire,
3099        }
3100    }
3101
3102    /// A gRPC client warns about the knobs it does not apply, among them
3103    /// `stream_reconnect`; a REST client applies them all and stays quiet.
3104    #[test]
3105    #[tracing_test::traced_test]
3106    fn a_grpc_consumer_warns_about_knobs_it_does_not_apply() {
3107        let tuning: toolkit_contract::wiring::ClientTuning = serde_json::from_value(
3108            serde_json::json!({ "stream_reconnect": { "max_attempts": 3 } }),
3109        )
3110        .unwrap();
3111        let knobs = tuning.grpc_ignored_knobs();
3112        let reg = test_registration();
3113
3114        warn_grpc_ignored_knobs(&reg, crate::discovery::WireOutcome::Remote, &knobs);
3115        assert!(!logs_contain("does not apply"));
3116
3117        warn_grpc_ignored_knobs(
3118            &reg,
3119            crate::discovery::WireOutcome::RemoteGrpc {
3120                service: "billing.v1.BillingApi",
3121            },
3122            &knobs,
3123        );
3124        assert!(logs_contain("does not apply"));
3125        assert!(logs_contain("stream_reconnect"));
3126    }
3127
3128    /// Static-endpoint arm: an `endpoint` wires a `StaticEndpointResolver` pinned
3129    /// to it, threads the entry's tuning through, and marks the dep resolved
3130    /// immediately (no probe loop).
3131    #[tokio::test]
3132    async fn proxy_wiring_static_override_uses_static_resolver_and_marks_ready() {
3133        let mut map = std::collections::HashMap::new();
3134        map.insert(
3135            "orders".to_owned(),
3136            serde_json::json!({
3137                "clients": {
3138                    "consumes": {
3139                        "billing": {
3140                            "endpoint": "http://localhost:8081",
3141                            "max_concurrent_requests": 7
3142                        }
3143                    }
3144                }
3145            }),
3146        );
3147
3148        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3149        let runtime = HostRuntime::new(
3150            registry,
3151            Arc::new(MapCfg(map)),
3152            DbOptions::None,
3153            Arc::new(ClientHub::new()),
3154            CancellationToken::new(),
3155            Uuid::new_v4(),
3156            None,
3157        );
3158
3159        let reg = test_registration();
3160        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3161
3162        // Find *the* entry whose resolver yields the configured endpoint and
3163        // assert that same entry's tuning — OR-ing two flags independently across
3164        // every WIRED entry would pass even if the endpoint and the tuning had
3165        // arrived on two different wire calls.
3166        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3167        let mut matched = None;
3168        for call in &calls {
3169            if let Ok(Some(ep)) = call.resolver.resolve_endpoint("billing").await
3170                && ep == "http://localhost:8081"
3171            {
3172                matched = Some(call.clone());
3173                break;
3174            }
3175        }
3176        let matched = matched
3177            .expect("static override must wire a resolver pinned to the configured endpoint");
3178        assert_eq!(
3179            matched.max_concurrent_requests,
3180            Some(7),
3181            "the tuning on the same wire call as the static endpoint must be the configured one"
3182        );
3183
3184        // A static endpoint is resolvable by construction: the dep must be
3185        // resolved immediately rather than left gating /readyz.
3186        assert_eq!(
3187            runtime.dep_checker.unresolved_deps(),
3188            [crate::runtime::PREPARATION_GATE],
3189            "only the not yet started application group gates readiness"
3190        );
3191    }
3192
3193    /// An in-process provider that forgot to register its local impl must fail
3194    /// startup rather than silently wiring a self-pointing proxy: here both the
3195    /// consumer `orders` and provider `billing` are registered gears, but the
3196    /// consumer's wiring reports `Remote`.
3197    #[tokio::test]
3198    async fn proxy_wiring_in_process_provider_wired_remote_is_a_hard_error() {
3199        // Register the consumer `orders` and the provider `billing`, where billing
3200        // never provides its client (no local impl, no REST).
3201        let mut b = crate::registry::RegistryBuilder::default();
3202        b.register_core_with_meta("orders", &[], Arc::new(DummyCore));
3203        b.register_core_with_meta("billing", &[], Arc::new(DummyCore));
3204        let registry = b.build_topo_sorted().unwrap();
3205
3206        let runtime = HostRuntime::new(
3207            registry,
3208            Arc::new(MapCfg(std::collections::HashMap::new())),
3209            DbOptions::None,
3210            Arc::new(ClientHub::new()),
3211            CancellationToken::new(),
3212            Uuid::new_v4(),
3213            None,
3214        );
3215
3216        // `test_registration()` is owner=orders, dep=billing, and `record_wire`
3217        // reports `Remote` without registering a local impl — the bug scenario.
3218        let reg = test_registration();
3219        let err = runtime
3220            .wire_consumer_registrations(&[&reg])
3221            .expect_err("an in-process provider wired Remote must fail startup");
3222        let msg = err.to_string();
3223        assert!(
3224            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
3225            "expected a ProxyWiring error for the consumer gear, got: {msg}"
3226        );
3227        // Display must surface the source, so both the consumer and provider gear
3228        // names appear in the rendered message.
3229        assert!(
3230            msg.contains("orders") && msg.contains("billing"),
3231            "displayed error must name both consumer and provider, got: {msg}"
3232        );
3233    }
3234
3235    /// Tuning-only entry (no `endpoint`, the production shape): keeps the shared
3236    /// discovery resolver and leaves the dep gating readiness — a remote dep with
3237    /// no directory stays unresolved.
3238    #[tokio::test]
3239    async fn proxy_wiring_tuning_only_entry_keeps_discovery_and_gates_readiness() {
3240        let mut map = std::collections::HashMap::new();
3241        // A unique tuning value so this test can find its own WIRED entry among
3242        // the link-time-global registrations.
3243        map.insert(
3244            "orders".to_owned(),
3245            serde_json::json!({
3246                "clients": {
3247                    "consumes": { "billing": { "max_concurrent_requests": 4343 } }
3248                }
3249            }),
3250        );
3251
3252        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3253        let runtime = HostRuntime::new(
3254            registry,
3255            Arc::new(MapCfg(map)),
3256            DbOptions::None,
3257            Arc::new(ClientHub::new()),
3258            CancellationToken::new(),
3259            Uuid::new_v4(),
3260            None,
3261        );
3262
3263        let reg = test_registration();
3264        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3265
3266        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3267        let ours = calls
3268            .iter()
3269            .find(|c| c.max_concurrent_requests == Some(4343))
3270            .expect("our tuning-only wire call must have been recorded");
3271        assert!(
3272            matches!(ours.resolver.resolve_endpoint("billing").await, Ok(None)),
3273            "a tuning-only entry must keep discovery -- the resolver must not be pinned to a \
3274             static endpoint"
3275        );
3276
3277        // No directory + a remote dep → it must stay unresolved and gate /readyz.
3278        assert!(!runtime.dep_checker.all_resolved());
3279        assert!(
3280            runtime
3281                .dep_checker
3282                .unresolved_deps()
3283                .contains(&"billing".to_owned()),
3284            "a discovery-wired dep with no directory must gate readiness"
3285        );
3286    }
3287
3288    /// The process's platform-plane credential must ride on the tuning handed to
3289    /// the wire fn (Profile 2/3), else every inter-gear call ships without
3290    /// `X-ToolKit-Internal-Token`.
3291    #[tokio::test]
3292    async fn proxy_wiring_threads_platform_credential_onto_tuning() {
3293        use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
3294
3295        let mut map = std::collections::HashMap::new();
3296        map.insert(
3297            "orders".to_owned(),
3298            serde_json::json!({
3299                "clients": {
3300                    "consumes": { "billing": { "max_concurrent_requests": 4242 } }
3301                }
3302            }),
3303        );
3304
3305        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3306        let provider = InternalTokenProvider::new(|| CredentialState::NotConfigured);
3307        let runtime = HostRuntime::new(
3308            registry,
3309            Arc::new(MapCfg(map)),
3310            DbOptions::None,
3311            Arc::new(ClientHub::new()),
3312            CancellationToken::new(),
3313            Uuid::new_v4(),
3314            None,
3315        )
3316        .with_internal_token_provider(Some(provider));
3317
3318        let reg = test_registration();
3319        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3320
3321        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
3322        let ours = calls
3323            .iter()
3324            .find(|c| c.max_concurrent_requests == Some(4242))
3325            .expect("our wire call must have been recorded");
3326        assert!(
3327            ours.has_credential,
3328            "the process credential must be threaded onto the tuning handed to the wire fn"
3329        );
3330    }
3331
3332    /// Phase-level: a non-absolute `endpoint` aborts proxy-wiring with
3333    /// `RegistryError::ProxyWiring` rather than silently downgrading to discovery
3334    /// (which would mark the dep resolved while every call fails).
3335    #[tokio::test]
3336    async fn proxy_wiring_invalid_endpoint_is_a_hard_error() {
3337        let mut map = std::collections::HashMap::new();
3338        map.insert(
3339            "orders".to_owned(),
3340            serde_json::json!({
3341                "clients": {
3342                    "consumes": {
3343                        "billing": { "endpoint": "", "max_concurrent_requests": 4444 }
3344                    }
3345                }
3346            }),
3347        );
3348
3349        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3350        let runtime = HostRuntime::new(
3351            registry,
3352            Arc::new(MapCfg(map)),
3353            DbOptions::None,
3354            Arc::new(ClientHub::new()),
3355            CancellationToken::new(),
3356            Uuid::new_v4(),
3357            None,
3358        );
3359
3360        let reg = test_registration();
3361        let err = runtime
3362            .wire_consumer_registrations(&[&reg])
3363            .expect_err("an invalid static endpoint must abort proxy-wiring");
3364        assert!(
3365            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
3366            "expected a ProxyWiring error for the owning gear, got {err:?}"
3367        );
3368    }
3369
3370    /// The override is keyed by the kebab *gear name* (`owner_gear`), not the
3371    /// struct ident. Regression guard: the macro once emitted
3372    /// `stringify!(StructIdent)`, so the lookup could never fire.
3373    #[test]
3374    fn static_endpoint_override_is_keyed_by_kebab_gear_name() {
3375        let mut map = std::collections::HashMap::new();
3376        map.insert(
3377            "api-contracts-consumer".to_owned(),
3378            serde_json::json!({
3379                "clients": {
3380                    "consumes": {
3381                        "api-contracts": { "endpoint": "http://localhost:9099" }
3382                    }
3383                }
3384            }),
3385        );
3386        let cfg = MapCfg(map);
3387
3388        assert_eq!(
3389            endpoint_override(&cfg, "api-contracts-consumer", "api-contracts").as_deref(),
3390            Some("http://localhost:9099"),
3391        );
3392        // The pre-fix value — the Rust struct ident — must NOT resolve.
3393        assert_eq!(
3394            endpoint_override(&cfg, "ApiContractsConsumer", "api-contracts"),
3395            None,
3396        );
3397    }
3398
3399    /// What a consumer's proxy was built from, for the per-consumer tests.
3400    trait ShippingApi: Send + Sync {
3401        fn wiring(&self) -> &ShippingProxy;
3402    }
3403
3404    struct ShippingProxy {
3405        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3406        timeout: Option<std::time::Duration>,
3407        max_attempts: Option<u32>,
3408        require_tls: Option<bool>,
3409    }
3410
3411    impl ShippingApi for ShippingProxy {
3412        fn wiring(&self) -> &ShippingProxy {
3413            self
3414        }
3415    }
3416
3417    /// The body `#[toolkit::consumes]` emits, with a proxy that keeps its
3418    /// resolver and tuning.
3419    fn wire_shipping(
3420        hub: &ClientHub,
3421        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3422        tuning: toolkit_contract::wiring::ClientTuning,
3423    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3424        if hub.try_get_local::<dyn ShippingApi>().is_some() {
3425            return Ok(crate::discovery::WireOutcome::Local);
3426        }
3427        if hub.has_remote_proxy::<dyn ShippingApi>() {
3428            if let Some(owner) = hub.owner() {
3429                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
3430            }
3431            return Ok(crate::discovery::WireOutcome::Remote);
3432        }
3433        hub.register_remote_proxy::<dyn ShippingApi>(Arc::new(ShippingProxy {
3434            resolver,
3435            timeout: tuning.timeout,
3436            max_attempts: tuning.retry.and_then(|r| r.max_attempts),
3437            require_tls: tuning.require_tls,
3438        }));
3439        Ok(crate::discovery::WireOutcome::Remote)
3440    }
3441
3442    fn shipping_registration(owner_gear: &'static str) -> crate::discovery::ConsumerRegistration {
3443        crate::discovery::ConsumerRegistration {
3444            owner_gear,
3445            dep_gear: "shipping",
3446            wire: wire_shipping,
3447        }
3448    }
3449
3450    /// A runtime hosting consumer gears `a` and `b` (shipping is remote).
3451    fn shipping_runtime(config: serde_json::Value) -> HostRuntime {
3452        let mut b = crate::registry::RegistryBuilder::default();
3453        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3454        b.register_core_with_meta("b", &[], Arc::new(DummyCore));
3455        let registry = b.build_topo_sorted().unwrap();
3456        let map = serde_json::from_value(config).unwrap();
3457        HostRuntime::new(
3458            registry,
3459            Arc::new(MapCfg(map)),
3460            DbOptions::None,
3461            Arc::new(ClientHub::new()),
3462            CancellationToken::new(),
3463            Uuid::new_v4(),
3464            None,
3465        )
3466    }
3467
3468    /// Issue #5686: two gears consuming one contract each get a proxy built
3469    /// from their own `clients.consumes` entry, whichever wires first.
3470    #[tokio::test]
3471    async fn each_consumer_gets_a_proxy_with_its_own_wiring() {
3472        let config = serde_json::json!({
3473            "a": { "clients": { "consumes": { "shipping": {
3474                "endpoint": "http://shipping-for-a:8080",
3475                "timeout": "1s",
3476                "retry": { "max_attempts": 2 },
3477                "require_tls": false
3478            } } } },
3479            "b": { "clients": { "consumes": { "shipping": {
3480                "endpoint": "http://shipping-for-b:8080",
3481                "timeout": "10s",
3482                "retry": { "max_attempts": 5 },
3483                "require_tls": true
3484            } } } }
3485        });
3486        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3487
3488        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3489            let runtime = shipping_runtime(config.clone());
3490            runtime.wire_consumer_registrations(&order).unwrap();
3491
3492            let hub = &runtime.client_hub;
3493            let a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3494            let b = hub.for_gear("b").get::<dyn ShippingApi>().unwrap();
3495            assert!(!Arc::ptr_eq(&a, &b));
3496            assert!(
3497                hub.try_get::<dyn ShippingApi>().is_none(),
3498                "a gear's proxy is not process-wide"
3499            );
3500
3501            let (a, b) = (a.wiring(), b.wiring());
3502            assert_eq!(
3503                a.resolver
3504                    .resolve_endpoint("shipping")
3505                    .await
3506                    .unwrap()
3507                    .as_deref(),
3508                Some("http://shipping-for-a:8080")
3509            );
3510            assert_eq!(
3511                b.resolver
3512                    .resolve_endpoint("shipping")
3513                    .await
3514                    .unwrap()
3515                    .as_deref(),
3516                Some("http://shipping-for-b:8080")
3517            );
3518            assert_eq!(a.timeout, Some(std::time::Duration::from_secs(1)));
3519            assert_eq!(b.timeout, Some(std::time::Duration::from_secs(10)));
3520            assert_eq!((a.max_attempts, b.max_attempts), (Some(2), Some(5)));
3521            assert_eq!((a.require_tls, b.require_tls), (Some(false), Some(true)));
3522        }
3523    }
3524
3525    /// An owner that is not a gear in this process (an SDK-level registration)
3526    /// wires a process-wide proxy that every gear's view can read.
3527    #[tokio::test]
3528    async fn an_unknown_owner_wires_a_process_wide_proxy() {
3529        let runtime = shipping_runtime(serde_json::json!({}));
3530        let reg = shipping_registration("shipping-sdk");
3531        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3532
3533        let hub = &runtime.client_hub;
3534        let shared = hub.get::<dyn ShippingApi>().unwrap();
3535        let seen_by_a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3536        assert!(Arc::ptr_eq(&shared, &seen_by_a));
3537    }
3538
3539    /// With one consumer on a static endpoint and another on discovery, the dep
3540    /// stays unresolved: the second consumer's provider is not found yet.
3541    #[tokio::test]
3542    async fn a_static_consumer_does_not_resolve_a_dep_another_consumer_discovers() {
3543        let config = serde_json::json!({
3544            "a": { "clients": { "consumes": { "shipping": {
3545                "endpoint": "http://shipping:8080"
3546            } } } }
3547        });
3548        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3549
3550        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3551            let runtime = shipping_runtime(config.clone());
3552            runtime.wire_consumer_registrations(&order).unwrap();
3553
3554            assert!(
3555                runtime
3556                    .dep_checker
3557                    .unresolved_deps()
3558                    .contains(&"shipping".to_owned()),
3559                "the discovery consumer must keep the dep gating readiness"
3560            );
3561        }
3562    }
3563
3564    /// Same mix with a directory: the dep stays unresolved until the provider
3565    /// is advertised, then the probe resolves it.
3566    #[tokio::test]
3567    async fn a_mixed_dep_resolves_once_the_provider_is_advertised() {
3568        let config = serde_json::json!({
3569            "a": { "clients": { "consumes": { "shipping": {
3570                "endpoint": "http://shipping:8080"
3571            } } } }
3572        });
3573        let runtime = shipping_runtime(config);
3574        let gears = Arc::new(crate::runtime::GearManager::new());
3575        runtime
3576            .client_hub
3577            .register::<dyn crate::DirectoryClient>(Arc::new(
3578                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3579            ));
3580        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3581        runtime
3582            .wire_consumer_registrations(&[&reg_a, &reg_b])
3583            .unwrap();
3584
3585        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3586        assert!(
3587            runtime
3588                .dep_checker
3589                .unresolved_deps()
3590                .contains(&"shipping".to_owned()),
3591            "no provider is advertised yet"
3592        );
3593
3594        gears
3595            .register_instance(Arc::new(
3596                crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3597                    .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3598            ))
3599            .unwrap();
3600        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3601            while runtime
3602                .dep_checker
3603                .unresolved_deps()
3604                .contains(&"shipping".to_owned())
3605            {
3606                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3607            }
3608        })
3609        .await
3610        .expect("the probe must resolve the dep once the provider is advertised");
3611        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3612        runtime.owned.cancel();
3613    }
3614
3615    /// Both consumers on static endpoints: resolved at wiring time.
3616    #[tokio::test]
3617    async fn static_consumers_resolve_the_dep() {
3618        let entry = serde_json::json!({ "clients": { "consumes": { "shipping": {
3619            "endpoint": "http://shipping:8080"
3620        } } } });
3621        let runtime = shipping_runtime(serde_json::json!({ "a": entry, "b": entry }));
3622        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3623        runtime
3624            .wire_consumer_registrations(&[&reg_a, &reg_b])
3625            .unwrap();
3626
3627        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3628    }
3629
3630    /// One gear consuming the same contract twice is a boot error naming it.
3631    #[tokio::test]
3632    async fn a_gear_consuming_a_contract_twice_fails_wiring() {
3633        let runtime = shipping_runtime(serde_json::json!({}));
3634        let reg = shipping_registration("a");
3635        let duplicate = shipping_registration("a");
3636        let err = runtime
3637            .wire_consumer_registrations(&[&reg, &duplicate])
3638            .expect_err("a duplicate consumer must fail wiring");
3639        assert!(
3640            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "a"),
3641            "got {err:?}"
3642        );
3643    }
3644
3645    const SHIPPING_GRPC: &str = "shipping.v1.ShippingApi";
3646
3647    /// `wire_shipping` for a gRPC client: same proxy, readiness on the service.
3648    fn wire_shipping_grpc(
3649        hub: &ClientHub,
3650        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3651        tuning: toolkit_contract::wiring::ClientTuning,
3652    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3653        match wire_shipping(hub, resolver, tuning)? {
3654            crate::discovery::WireOutcome::Remote => {
3655                Ok(crate::discovery::WireOutcome::RemoteGrpc {
3656                    service: SHIPPING_GRPC,
3657                })
3658            }
3659            other => Ok(other),
3660        }
3661    }
3662
3663    fn shipping_grpc_registration(
3664        owner_gear: &'static str,
3665    ) -> crate::discovery::ConsumerRegistration {
3666        crate::discovery::ConsumerRegistration {
3667            owner_gear,
3668            dep_gear: "shipping",
3669            wire: wire_shipping_grpc,
3670        }
3671    }
3672
3673    /// `shipping_runtime` with an in-process directory the test can publish to.
3674    fn shipping_runtime_with_directory(
3675        config: serde_json::Value,
3676    ) -> (HostRuntime, Arc<crate::runtime::GearManager>) {
3677        let runtime = shipping_runtime(config);
3678        let gears = Arc::new(crate::runtime::GearManager::new());
3679        runtime
3680            .client_hub
3681            .register::<dyn crate::DirectoryClient>(Arc::new(
3682                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3683            ));
3684        (runtime, gears)
3685    }
3686
3687    fn publish(gears: &crate::runtime::GearManager, instance: crate::runtime::GearInstance) {
3688        gears.register_instance(Arc::new(instance)).unwrap();
3689    }
3690
3691    /// Every consumed dep resolved; only the startup preparation gate,
3692    /// which these wiring-only tests never lift, is left.
3693    fn deps_resolved(runtime: &HostRuntime) -> bool {
3694        runtime.dep_checker.unresolved_deps() == [PREPARATION_GATE]
3695    }
3696
3697    async fn wait_resolved(runtime: &HostRuntime) -> bool {
3698        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3699            while !deps_resolved(runtime) {
3700                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3701            }
3702        })
3703        .await
3704        .is_ok()
3705    }
3706
3707    /// A gRPC consumer's dep is probed by service name, not by the gear's
3708    /// REST endpoint.
3709    #[tokio::test]
3710    async fn a_grpc_dep_resolves_when_its_service_is_published() {
3711        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3712        let reg = shipping_grpc_registration("a");
3713        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3714
3715        // A REST endpoint for the gear does not satisfy a gRPC consumer.
3716        publish(
3717            &gears,
3718            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3719                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3720        );
3721        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3722        assert!(!deps_resolved(&runtime));
3723
3724        publish(
3725            &gears,
3726            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3727                SHIPPING_GRPC,
3728                crate::runtime::Endpoint::http("shipping", 50051),
3729            ),
3730        );
3731        assert!(
3732            wait_resolved(&runtime).await,
3733            "the published service resolves the dep"
3734        );
3735        runtime.cancel.cancel();
3736    }
3737
3738    /// A REST consumer and a gRPC consumer of one dep: ready only when both
3739    /// targets resolve.
3740    #[tokio::test]
3741    async fn a_dep_consumed_over_both_transports_waits_for_both() {
3742        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3743        let (rest, grpc) = (shipping_registration("a"), shipping_grpc_registration("b"));
3744        runtime
3745            .wire_consumer_registrations(&[&rest, &grpc])
3746            .unwrap();
3747
3748        publish(
3749            &gears,
3750            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3751                SHIPPING_GRPC,
3752                crate::runtime::Endpoint::http("shipping", 50051),
3753            ),
3754        );
3755        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3756        assert!(!deps_resolved(&runtime), "the REST consumer still waits");
3757
3758        publish(
3759            &gears,
3760            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3761                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3762        );
3763        assert!(wait_resolved(&runtime).await);
3764        runtime.cancel.cancel();
3765    }
3766
3767    /// Wiring runs in batches (system gears, then the rest). A static consumer
3768    /// wired in one batch must not resolve a dep that a consumer in another
3769    /// batch discovers, in either order.
3770    #[tokio::test]
3771    async fn a_static_batch_does_not_resolve_a_dep_another_batch_discovers() {
3772        let config = serde_json::json!({
3773            "a": { "clients": { "consumes": { "shipping": {
3774                "endpoint": "http://shipping:8080"
3775            } } } }
3776        });
3777        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3778
3779        for (first, second) in [(&reg_a, &reg_b), (&reg_b, &reg_a)] {
3780            let runtime = shipping_runtime(config.clone());
3781            runtime.wire_consumer_registrations(&[first]).unwrap();
3782            runtime.wire_consumer_registrations(&[second]).unwrap();
3783
3784            assert!(
3785                runtime
3786                    .dep_checker
3787                    .unresolved_deps()
3788                    .contains(&"shipping".to_owned()),
3789                "the discovery consumer must keep the dep gating readiness"
3790            );
3791        }
3792    }
3793
3794    /// Probes started by two batches for one dep: the dep resolves only when
3795    /// the targets of both have.
3796    #[tokio::test]
3797    async fn probes_from_two_batches_resolve_the_dep_together() {
3798        let (runtime, gears) = shipping_runtime_with_directory(serde_json::json!({}));
3799        let (rest, grpc) = (shipping_registration("a"), shipping_grpc_registration("b"));
3800        runtime.wire_consumer_registrations(&[&rest]).unwrap();
3801        runtime.wire_consumer_registrations(&[&grpc]).unwrap();
3802
3803        publish(
3804            &gears,
3805            crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3806                .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3807        );
3808        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3809        assert!(!deps_resolved(&runtime), "the gRPC consumer still waits");
3810
3811        publish(
3812            &gears,
3813            crate::runtime::GearInstance::new("shipping", Uuid::new_v4()).with_grpc_service(
3814                SHIPPING_GRPC,
3815                crate::runtime::Endpoint::http("shipping", 50051),
3816            ),
3817        );
3818        assert!(wait_resolved(&runtime).await);
3819        runtime.cancel.cancel();
3820    }
3821
3822    /// `grpc_endpoint` is a static override for the gRPC client only.
3823    #[tokio::test]
3824    async fn grpc_endpoint_wires_the_grpc_client_statically() {
3825        let config = serde_json::json!({
3826            "a": { "clients": { "consumes": { "shipping": {
3827                "grpc_endpoint": "http://shipping:50051"
3828            } } } }
3829        });
3830        let runtime = shipping_runtime(config);
3831        let reg = shipping_grpc_registration("a");
3832        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3833
3834        assert!(deps_resolved(&runtime));
3835        let proxy = runtime
3836            .client_hub
3837            .for_gear("a")
3838            .get::<dyn ShippingApi>()
3839            .unwrap();
3840        assert_eq!(
3841            proxy
3842                .wiring()
3843                .resolver
3844                .resolve_grpc_endpoint(SHIPPING_GRPC)
3845                .await
3846                .unwrap()
3847                .as_deref(),
3848            Some("http://shipping:50051")
3849        );
3850    }
3851
3852    /// `grpc_endpoint` alone leaves a REST consumer of the dep on discovery.
3853    #[tokio::test]
3854    async fn grpc_endpoint_does_not_pin_the_rest_client() {
3855        let config = serde_json::json!({
3856            "a": { "clients": { "consumes": { "shipping": {
3857                "grpc_endpoint": "http://shipping:50051"
3858            } } } }
3859        });
3860        let runtime = shipping_runtime(config);
3861        let reg = shipping_registration("a");
3862        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3863
3864        assert!(!deps_resolved(&runtime), "REST still waits for discovery");
3865    }
3866
3867    /// One `endpoint` cannot serve one gear's REST and gRPC clients.
3868    #[tokio::test]
3869    async fn one_endpoint_for_both_transports_of_a_gear_is_an_error() {
3870        let runtime = shipping_runtime(serde_json::json!({
3871            "a": { "clients": { "consumes": { "shipping": {
3872                "endpoint": "http://shipping:8080"
3873            } } } }
3874        }));
3875        let rest = shipping_registration("a");
3876        // In real code the two clients are two contracts; the test proxy type
3877        // is shared, so the gRPC one goes into another view to get past the
3878        // duplicate check.
3879        let grpc = crate::discovery::ConsumerRegistration {
3880            owner_gear: "a",
3881            dep_gear: "shipping",
3882            wire: |hub, resolver, tuning| {
3883                wire_shipping_grpc(&hub.for_gear("a-grpc"), resolver, tuning)
3884            },
3885        };
3886        let err = runtime
3887            .wire_consumer_registrations(&[&rest, &grpc])
3888            .expect_err("a single endpoint for both transports must fail");
3889        assert!(err.to_string().contains("grpc_endpoint"), "{err}");
3890    }
3891
3892    struct DummyGrpc;
3893
3894    #[async_trait::async_trait]
3895    impl crate::contracts::GrpcServiceCapability for DummyGrpc {
3896        async fn get_grpc_services(
3897            &self,
3898            _ctx: &GearCtx,
3899        ) -> anyhow::Result<Vec<crate::contracts::RegisterGrpcServiceFn>> {
3900            Ok(Vec::new())
3901        }
3902    }
3903
3904    /// An in-process provider that serves gRPC is a valid gRPC dependency; one
3905    /// that serves neither REST nor gRPC is not.
3906    #[tokio::test]
3907    async fn an_in_process_grpc_dep_must_serve_grpc() {
3908        let build = |grpc: bool| {
3909            let mut b = crate::registry::RegistryBuilder::default();
3910            b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3911            b.register_core_with_meta("shipping", &[], Arc::new(DummyCore));
3912            if grpc {
3913                b.register_grpc_service_with_meta("shipping", Arc::new(DummyGrpc));
3914            }
3915            HostRuntime::new(
3916                b.build_topo_sorted().unwrap(),
3917                Arc::new(MapCfg(std::collections::HashMap::new())),
3918                DbOptions::None,
3919                Arc::new(ClientHub::new()),
3920                CancellationToken::new(),
3921                Uuid::new_v4(),
3922                None,
3923            )
3924        };
3925        let reg = shipping_grpc_registration("a");
3926
3927        build(true).wire_consumer_registrations(&[&reg]).unwrap();
3928        let err = build(false)
3929            .wire_consumer_registrations(&[&reg])
3930            .expect_err("no gRPC service to call");
3931        assert!(err.to_string().contains("serves no gRPC service"), "{err}");
3932    }
3933
3934    #[tokio::test]
3935    async fn test_post_init_runs_after_all_init_for_every_gear_system_group_first() {
3936        #[derive(Clone)]
3937        struct TrackHooks {
3938            name: &'static str,
3939            events: Arc<Mutex<Vec<String>>>,
3940        }
3941
3942        #[async_trait::async_trait]
3943        impl Gear for TrackHooks {
3944            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3945                self.events.lock().await.push(format!("init:{}", self.name));
3946                Ok(())
3947            }
3948
3949            async fn post_init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3950                self.events
3951                    .lock()
3952                    .await
3953                    .push(format!("post_init:{}", self.name));
3954                Ok(())
3955            }
3956        }
3957
3958        impl SystemCapability for TrackHooks {}
3959
3960        let events = Arc::new(Mutex::new(Vec::<String>::new()));
3961        let sys_a = Arc::new(TrackHooks {
3962            name: "sys_a",
3963            events: events.clone(),
3964        });
3965        let user_b = Arc::new(TrackHooks {
3966            name: "user_b",
3967            events: events.clone(),
3968        });
3969        let user_c = Arc::new(TrackHooks {
3970            name: "user_c",
3971            events: events.clone(),
3972        });
3973
3974        let mut builder = RegistryBuilder::default();
3975        builder.register_core_with_meta("sys_a", &[], sys_a.clone() as Arc<dyn Gear>);
3976        builder.register_core_with_meta("user_b", &["sys_a"], user_b.clone() as Arc<dyn Gear>);
3977        builder.register_core_with_meta("user_c", &["user_b"], user_c.clone() as Arc<dyn Gear>);
3978        builder.register_system_with_meta("sys_a", sys_a.clone() as Arc<dyn SystemCapability>);
3979
3980        let registry = builder.build_topo_sorted().unwrap();
3981
3982        let client_hub = Arc::new(ClientHub::new());
3983        let cancel = CancellationToken::new();
3984        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3985
3986        let runtime = HostRuntime::new(
3987            registry,
3988            config_provider,
3989            DbOptions::None,
3990            client_hub,
3991            cancel,
3992            Uuid::new_v4(),
3993            None,
3994        );
3995
3996        // Run init phase for all gears, then post_init as a separate barrier phase.
3997        runtime.run_init_phase().await.unwrap();
3998        runtime.run_post_init_phase().await.unwrap();
3999
4000        let events = events.lock().await.clone();
4001        let first_post_init = events
4002            .iter()
4003            .position(|e| e.starts_with("post_init:"))
4004            .expect("expected post_init events");
4005        assert!(
4006            events[..first_post_init]
4007                .iter()
4008                .all(|e| e.starts_with("init:")),
4009            "expected all init events before post_init, got: {events:?}"
4010        );
4011
4012        // The system group first, each group in topological order.
4013        assert_eq!(
4014            events,
4015            vec![
4016                "init:sys_a",
4017                "init:user_b",
4018                "init:user_c",
4019                "post_init:sys_a",
4020                "post_init:user_b",
4021                "post_init:user_c",
4022            ]
4023        );
4024    }
4025
4026    /// The force-exit watchdog (shared by init and stop) fires only when it is
4027    /// never disarmed within the deadline. The decision is split from
4028    /// `process::exit` into `watchdog_verdict` so it is unit-testable without
4029    /// killing the test process; these cover the hung case and both disarm cases.
4030    #[test]
4031    fn watchdog_times_out_when_not_disarmed() {
4032        let (_tx, rx) = std::sync::mpsc::channel::<()>();
4033        // Hold the sender; never signal → the deadline elapses → TimedOut.
4034        assert_eq!(
4035            watchdog_verdict(&rx, std::time::Duration::from_millis(20)),
4036            WatchdogVerdict::TimedOut
4037        );
4038    }
4039
4040    #[test]
4041    fn init_watchdog_subprocess() {
4042        const CHILD_MODE: &str = "TOOLKIT_INIT_WATCHDOG_TEST_MODE";
4043        struct WatchdogGear(String);
4044
4045        #[async_trait::async_trait]
4046        impl Gear for WatchdogGear {
4047            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4048                match self.0.as_str() {
4049                    "success" => (),
4050                    // Async hang: the async timeout observes it → recoverable error.
4051                    "async-hang" | "cancelled" => {
4052                        std::future::pending::<()>().await;
4053                    }
4054                    // Synchronous block: no async timer can fire; only the
4055                    // OS-thread watchdog catches it → force-exit.
4056                    "blocking" | "blocking-no-tracing" => {
4057                        std::thread::sleep(std::time::Duration::from_secs(3600));
4058                    }
4059                    "error" => anyhow::bail!("init failed"),
4060                    other => panic!("unexpected watchdog test mode: {other}"),
4061                }
4062                Ok(())
4063            }
4064        }
4065
4066        let Ok(mode) = std::env::var(CHILD_MODE) else {
4067            for (mode, expected_code) in [
4068                ("success", 0),
4069                ("async-hang", 0),
4070                ("blocking", 1),
4071                ("blocking-no-tracing", 1),
4072                ("error", 0),
4073                ("cancelled", 0),
4074            ] {
4075                let mut child = std::process::Command::new(std::env::current_exe().unwrap())
4076                    .args([
4077                        "--exact",
4078                        "runtime::host_runtime::tests::init_watchdog_subprocess",
4079                        "--nocapture",
4080                    ])
4081                    .env(CHILD_MODE, mode)
4082                    .stdout(std::process::Stdio::piped())
4083                    .stderr(std::process::Stdio::piped())
4084                    .spawn()
4085                    .unwrap();
4086                let limit = std::time::Instant::now() + std::time::Duration::from_secs(5);
4087                while child.try_wait().unwrap().is_none() {
4088                    if std::time::Instant::now() >= limit {
4089                        child.kill().unwrap();
4090                        let output = child.wait_with_output().unwrap();
4091                        panic!("watchdog subprocess {mode} hung: {output:?}");
4092                    }
4093                    std::thread::sleep(std::time::Duration::from_millis(10));
4094                }
4095                let output = child.wait_with_output().unwrap();
4096                assert_eq!(
4097                    output.status.code(),
4098                    Some(expected_code),
4099                    "{mode}: {output:?}"
4100                );
4101                if mode.starts_with("blocking") {
4102                    // One line must carry ERROR + message + gear name (holds even
4103                    // with tracing OFF, where only the stderr fallback is emitted).
4104                    let logs = String::from_utf8_lossy(&output.stderr);
4105                    assert!(
4106                        logs.lines().any(|line| line.contains("ERROR")
4107                            && line.contains("init timed out")
4108                            && line.contains("watchdog-test")),
4109                        "{logs}"
4110                    );
4111                }
4112            }
4113            return;
4114        };
4115
4116        tracing_subscriber::fmt()
4117            .with_ansi(false)
4118            .with_max_level(if mode == "blocking-no-tracing" {
4119                tracing::level_filters::LevelFilter::OFF
4120            } else {
4121                tracing::level_filters::LevelFilter::INFO
4122            })
4123            .with_writer(std::io::stderr)
4124            .try_init()
4125            .unwrap();
4126        tokio::runtime::Builder::new_current_thread()
4127            .enable_all()
4128            .build()
4129            .unwrap()
4130            .block_on(async {
4131                let mut builder = RegistryBuilder::default();
4132                builder.register_core_with_meta(
4133                    "watchdog-test",
4134                    &[],
4135                    Arc::new(WatchdogGear(mode.clone())) as Arc<dyn Gear>,
4136                );
4137                let runtime = HostRuntime::new(
4138                    builder.build_topo_sorted().unwrap(),
4139                    Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4140                    DbOptions::None,
4141                    Arc::new(ClientHub::new()),
4142                    CancellationToken::new(),
4143                    Uuid::new_v4(),
4144                    None,
4145                )
4146                .with_init_deadline(std::time::Duration::from_millis(200));
4147
4148                #[allow(
4149                    clippy::match_same_arms,
4150                    reason = "`success` returns normally; in `blocking*` the same call never returns and the watchdog force-exits"
4151                )]
4152                match mode.as_str() {
4153                    "cancelled" => {
4154                        // Dropping the phase future disarms the watchdog: no exit.
4155                        assert!(
4156                            tokio::time::timeout(
4157                                std::time::Duration::from_millis(20),
4158                                runtime.run_init_phase(),
4159                            )
4160                            .await
4161                            .is_err()
4162                        );
4163                    }
4164                    "success" => {
4165                        runtime.run_init_phase().await.unwrap();
4166                    }
4167                    "async-hang" => {
4168                        // Recoverable error, not a force-exit.
4169                        let err = runtime.run_init_phase().await.unwrap_err();
4170                        assert!(matches!(
4171                            err,
4172                            RegistryError::InitTimeout {
4173                                gear: "watchdog-test",
4174                                ..
4175                            }
4176                        ));
4177                    }
4178                    "error" => {
4179                        let err = runtime.run_init_phase().await.unwrap_err();
4180                        assert!(matches!(
4181                            err,
4182                            RegistryError::Init {
4183                                gear: "watchdog-test",
4184                                ..
4185                            }
4186                        ));
4187                    }
4188                    // Never returns; the OS-thread watchdog force-exits instead.
4189                    "blocking" | "blocking-no-tracing" => {
4190                        runtime.run_init_phase().await.unwrap();
4191                    }
4192                    other => panic!("unexpected watchdog test mode: {other}"),
4193                }
4194                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
4195            });
4196    }
4197
4198    #[test]
4199    fn watchdog_disarms_when_signalled() {
4200        let (tx, rx) = std::sync::mpsc::channel::<()>();
4201        tx.send(()).unwrap();
4202        // A generous deadline proves we return on the signal, not by timing out.
4203        assert_eq!(
4204            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
4205            WatchdogVerdict::Disarmed
4206        );
4207    }
4208
4209    #[test]
4210    fn watchdog_disarms_when_sender_is_dropped() {
4211        let (tx, rx) = std::sync::mpsc::channel::<()>();
4212        drop(tx); // guarded future dropped before it finished
4213        assert_eq!(
4214            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
4215            WatchdogVerdict::Disarmed
4216        );
4217    }
4218
4219    /// When `GearContextBuilder::for_gear` fails (here: the gear's database
4220    /// config references a global server that does not exist), the init phase
4221    /// must surface it as `RegistryError::Init` naming the gear — not hang or
4222    /// force-exit.
4223    #[cfg(feature = "db")]
4224    #[tokio::test]
4225    async fn init_ctx_failure_surfaces_as_init_error() {
4226        use figment::{Figment, providers::Serialized};
4227
4228        struct NeedsDbGear;
4229
4230        #[async_trait::async_trait]
4231        impl Gear for NeedsDbGear {
4232            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4233                Ok(())
4234            }
4235        }
4236
4237        let mut builder = RegistryBuilder::default();
4238        builder.register_core_with_meta("needsdb", &[], Arc::new(NeedsDbGear) as Arc<dyn Gear>);
4239        let registry = builder.build_topo_sorted().unwrap();
4240
4241        let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
4242            "gears": {
4243                "needsdb": {
4244                    "database": { "server": "does-not-exist" }
4245                }
4246            }
4247        })));
4248        let db_manager =
4249            toolkit_db::DbManager::from_figment(figment, std::path::PathBuf::from("/tmp/test"))
4250                .unwrap();
4251
4252        let runtime = HostRuntime::new(
4253            registry,
4254            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4255            DbOptions::Manager(Arc::new(db_manager)),
4256            Arc::new(ClientHub::new()),
4257            CancellationToken::new(),
4258            Uuid::new_v4(),
4259            None,
4260        );
4261
4262        let err = runtime.run_init_phase().await.unwrap_err();
4263        assert!(
4264            matches!(err, RegistryError::Init { gear, .. } if gear == "needsdb"),
4265            "expected RegistryError::Init for needsdb, got {err:?}"
4266        );
4267    }
4268
4269    /// A REST gear opting out of directory advertisement is served but not
4270    /// advertised (nor deregistered) as a REST provider.
4271    #[test]
4272    fn a_rest_gear_can_opt_out_of_directory_advertisement() {
4273        struct Rest {
4274            advertised: bool,
4275        }
4276        #[async_trait::async_trait]
4277        impl Gear for Rest {
4278            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4279                Ok(())
4280            }
4281        }
4282        impl crate::contracts::RestApiCapability for Rest {
4283            fn register_rest(
4284                &self,
4285                _ctx: &GearCtx,
4286                router: axum::Router,
4287                _openapi: &dyn crate::api::OpenApiRegistry,
4288            ) -> anyhow::Result<axum::Router> {
4289                Ok(router)
4290            }
4291            fn advertised_in_directory(&self) -> bool {
4292                self.advertised
4293            }
4294        }
4295
4296        let mut builder = RegistryBuilder::default();
4297        for (name, advertised) in [("advertised", true), ("hidden", false)] {
4298            let gear = Arc::new(Rest { advertised });
4299            builder.register_core_with_meta(name, &[], gear.clone() as Arc<dyn Gear>);
4300            builder.register_rest_with_meta(
4301                name,
4302                gear as Arc<dyn crate::contracts::RestApiCapability>,
4303            );
4304        }
4305        let runtime = HostRuntime::new(
4306            builder.build_topo_sorted().unwrap(),
4307            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
4308            DbOptions::None,
4309            Arc::new(ClientHub::new()),
4310            CancellationToken::new(),
4311            Uuid::new_v4(),
4312            None,
4313        );
4314
4315        assert_eq!(runtime.rest_provider_gears(), vec!["advertised"]);
4316    }
4317
4318    #[tokio::test]
4319    async fn test_stop_phase_provides_fresh_deadline_token() {
4320        use std::sync::atomic::AtomicBool;
4321
4322        struct TokenCheckGear {
4323            stop_was_called: AtomicBool,
4324            token_was_cancelled_on_entry: AtomicBool,
4325        }
4326
4327        #[async_trait::async_trait]
4328        impl Gear for TokenCheckGear {
4329            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4330                Ok(())
4331            }
4332        }
4333
4334        #[async_trait::async_trait]
4335        impl RunnableCapability for TokenCheckGear {
4336            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4337                Ok(())
4338            }
4339            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4340                // Record that stop() was called
4341                self.stop_was_called.store(true, Ordering::SeqCst);
4342                // Record whether the token was already cancelled when stop() was called
4343                self.token_was_cancelled_on_entry
4344                    .store(deadline_token.is_cancelled(), Ordering::SeqCst);
4345                Ok(())
4346            }
4347        }
4348
4349        let gear = Arc::new(TokenCheckGear {
4350            stop_was_called: AtomicBool::new(false),
4351            // Default to true to detect if stop() was never called
4352            token_was_cancelled_on_entry: AtomicBool::new(true),
4353        });
4354
4355        let mut builder = RegistryBuilder::default();
4356        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4357        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4358
4359        let registry = builder.build_topo_sorted().unwrap();
4360        let client_hub = Arc::new(ClientHub::new());
4361        let cancel = CancellationToken::new();
4362        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4363
4364        let runtime = HostRuntime::new(
4365            registry,
4366            config_provider,
4367            DbOptions::None,
4368            client_hub,
4369            cancel.clone(),
4370            Uuid::new_v4(),
4371            None,
4372        );
4373
4374        // Run stop phase - the deadline token should NOT be cancelled
4375        runtime.run_start_phase().await.unwrap();
4376        runtime.run_stop_phase().await.unwrap();
4377
4378        // First, verify stop() was actually called (guards against silent registration failures)
4379        assert!(
4380            gear.stop_was_called.load(Ordering::SeqCst),
4381            "stop() was never called - gear may not have been registered correctly"
4382        );
4383
4384        // The token should NOT have been cancelled when stop() was called
4385        // This is the key fix: gears get a fresh token, not the already-cancelled root token
4386        assert!(
4387            !gear.token_was_cancelled_on_entry.load(Ordering::SeqCst),
4388            "deadline_token should NOT be cancelled when stop() is called - this enables graceful shutdown"
4389        );
4390    }
4391
4392    #[tokio::test]
4393    async fn test_stop_phase_graceful_shutdown_completes_before_deadline() {
4394        use std::sync::atomic::AtomicBool;
4395        use std::time::Duration;
4396
4397        struct GracefulGear {
4398            graceful_completed: AtomicBool,
4399            deadline_fired: AtomicBool,
4400        }
4401
4402        #[async_trait::async_trait]
4403        impl Gear for GracefulGear {
4404            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4405                Ok(())
4406            }
4407        }
4408
4409        #[async_trait::async_trait]
4410        impl RunnableCapability for GracefulGear {
4411            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4412                Ok(())
4413            }
4414            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4415                // Simulate graceful shutdown that completes quickly (10ms)
4416                tokio::select! {
4417                    () = tokio::time::sleep(Duration::from_millis(10)) => {
4418                        self.graceful_completed.store(true, Ordering::SeqCst);
4419                    }
4420                    () = deadline_token.cancelled() => {
4421                        self.deadline_fired.store(true, Ordering::SeqCst);
4422                    }
4423                }
4424                Ok(())
4425            }
4426        }
4427
4428        let gear = Arc::new(GracefulGear {
4429            graceful_completed: AtomicBool::new(false),
4430            deadline_fired: AtomicBool::new(false),
4431        });
4432
4433        let mut builder = RegistryBuilder::default();
4434        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4435        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4436
4437        let registry = builder.build_topo_sorted().unwrap();
4438        let client_hub = Arc::new(ClientHub::new());
4439        let cancel = CancellationToken::new();
4440        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4441
4442        // Use a long deadline (5s) - gear should complete gracefully before this
4443        let runtime = HostRuntime::new(
4444            registry,
4445            config_provider,
4446            DbOptions::None,
4447            client_hub,
4448            cancel.clone(),
4449            Uuid::new_v4(),
4450            None,
4451        )
4452        .with_shutdown_deadline(Duration::from_secs(5));
4453
4454        runtime.run_start_phase().await.unwrap();
4455        runtime.run_stop_phase().await.unwrap();
4456
4457        // Graceful shutdown should have completed
4458        assert!(
4459            gear.graceful_completed.load(Ordering::SeqCst),
4460            "graceful shutdown should complete"
4461        );
4462        // Deadline should NOT have fired (gear finished before deadline)
4463        assert!(
4464            !gear.deadline_fired.load(Ordering::SeqCst),
4465            "deadline should not fire when graceful shutdown completes quickly"
4466        );
4467    }
4468
4469    #[tokio::test]
4470    async fn test_stop_phase_deadline_fires_for_slow_gear() {
4471        use std::sync::atomic::AtomicBool;
4472        use std::time::Duration;
4473
4474        struct SlowGear {
4475            graceful_completed: AtomicBool,
4476            deadline_fired: AtomicBool,
4477        }
4478
4479        #[async_trait::async_trait]
4480        impl Gear for SlowGear {
4481            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
4482                Ok(())
4483            }
4484        }
4485
4486        #[async_trait::async_trait]
4487        impl RunnableCapability for SlowGear {
4488            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
4489                Ok(())
4490            }
4491            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
4492                // Simulate slow graceful shutdown (would take 10s, but deadline is 100ms)
4493                tokio::select! {
4494                    () = tokio::time::sleep(Duration::from_secs(10)) => {
4495                        self.graceful_completed.store(true, Ordering::SeqCst);
4496                    }
4497                    () = deadline_token.cancelled() => {
4498                        self.deadline_fired.store(true, Ordering::SeqCst);
4499                    }
4500                }
4501                Ok(())
4502            }
4503        }
4504
4505        let gear = Arc::new(SlowGear {
4506            graceful_completed: AtomicBool::new(false),
4507            deadline_fired: AtomicBool::new(false),
4508        });
4509
4510        let mut builder = RegistryBuilder::default();
4511        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
4512        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
4513
4514        let registry = builder.build_topo_sorted().unwrap();
4515        let client_hub = Arc::new(ClientHub::new());
4516        let cancel = CancellationToken::new();
4517        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
4518
4519        // Use a short deadline (100ms) - gear should be interrupted by deadline
4520        let runtime = HostRuntime::new(
4521            registry,
4522            config_provider,
4523            DbOptions::None,
4524            client_hub,
4525            cancel.clone(),
4526            Uuid::new_v4(),
4527            None,
4528        )
4529        .with_shutdown_deadline(Duration::from_millis(100));
4530
4531        runtime.run_start_phase().await.unwrap();
4532        runtime.run_stop_phase().await.unwrap();
4533
4534        // Graceful shutdown should NOT have completed (deadline fired first)
4535        assert!(
4536            !gear.graceful_completed.load(Ordering::SeqCst),
4537            "graceful shutdown should not complete when deadline fires first"
4538        );
4539        // Deadline should have fired
4540        assert!(
4541            gear.deadline_fired.load(Ordering::SeqCst),
4542            "deadline should fire for slow gears"
4543        );
4544    }
4545
4546    /// `billing` never answers; `orders` answers at once.
4547    struct HangingResolver;
4548
4549    #[async_trait::async_trait]
4550    impl toolkit_contract::runtime::resolving::EndpointResolver for HangingResolver {
4551        async fn resolve_endpoint(
4552            &self,
4553            gear: &str,
4554        ) -> Result<Option<String>, toolkit_contract::runtime::resolving::ResolveError> {
4555            if gear == "billing" {
4556                std::future::pending::<()>().await;
4557            }
4558            Ok(Some(format!("http://{gear}")))
4559        }
4560    }
4561
4562    fn probe_fixture(
4563        deps: &[&str],
4564    ) -> (
4565        Readiness,
4566        Arc<crate::runtime::readiness::DependencyChecker>,
4567        std::collections::BTreeMap<String, std::collections::BTreeSet<Probe>>,
4568    ) {
4569        let checker = Arc::new(crate::runtime::readiness::DependencyChecker::new());
4570        let mut pending = std::collections::BTreeMap::new();
4571        for dep in deps {
4572            checker.register_dep(*dep);
4573            pending.insert((*dep).to_owned(), [Probe::Rest].into());
4574        }
4575        let readiness = Readiness {
4576            deps: Arc::clone(&checker),
4577            pending: Arc::new(parking_lot::Mutex::new(pending.clone())),
4578        };
4579        (readiness, checker, pending)
4580    }
4581
4582    #[tokio::test(start_paused = true)]
4583    async fn a_hung_lookup_times_out_and_does_not_block_other_deps() {
4584        let (readiness, checker, pending) = probe_fixture(&["billing", "orders"]);
4585        let cancel = CancellationToken::new();
4586        let probe = tokio::spawn(probe_until_resolved(
4587            Arc::new(HangingResolver),
4588            readiness,
4589            cancel.clone(),
4590            pending,
4591        ));
4592
4593        tokio::time::sleep(PROBE_LOOKUP_TIMEOUT + std::time::Duration::from_secs(1)).await;
4594        assert_eq!(checker.unresolved_deps(), vec!["billing".to_owned()]);
4595
4596        cancel.cancel();
4597        probe.await.unwrap();
4598    }
4599
4600    #[tokio::test(start_paused = true)]
4601    async fn cancel_stops_the_probe_during_a_lookup() {
4602        let (readiness, checker, pending) = probe_fixture(&["billing"]);
4603        let cancel = CancellationToken::new();
4604        let probe = tokio::spawn(probe_until_resolved(
4605            Arc::new(HangingResolver),
4606            readiness,
4607            cancel.clone(),
4608            pending,
4609        ));
4610        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
4611        cancel.cancel();
4612
4613        tokio::time::timeout(std::time::Duration::from_millis(10), probe)
4614            .await
4615            .expect("the probe stops without waiting for the lookup")
4616            .unwrap();
4617        assert_eq!(checker.unresolved_deps(), vec!["billing".to_owned()]);
4618    }
4619}
4620
4621#[cfg(test)]
4622#[cfg_attr(coverage_nightly, coverage(off))]
4623#[path = "host_runtime_preparation_tests.rs"]
4624mod host_runtime_preparation_tests;
4625
4626#[cfg(test)]
4627#[cfg_attr(coverage_nightly, coverage(off))]
4628#[path = "host_runtime_rest_bootstrap_tests.rs"]
4629mod host_runtime_rest_bootstrap_tests;