Skip to main content

toolkit/bootstrap/
oop.rs

1//! Out-of-process gear bootstrap library
2//!
3//! This gear provides reusable functionality for bootstrapping `OoP` (out-of-process)
4//! `ToolKit` gears in local (non-k8s) environments.
5//!
6//! ## Features
7//!
8//! - Configuration loading using `toolkit-bootstrap`
9//! - Logging initialization with tracing
10//! - Lazy gRPC client to the `DirectoryService` (connects on first use, so a
11//!   cold `DirectoryService` never blocks or crashes bootstrap —
12//!   `cpt-cf-adr-eventual-readiness`)
13//! - Gear instance registration
14//! - Heartbeat management
15//! - Gear lifecycle execution
16//!
17//! ## Shutdown Model
18//!
19//! Shutdown is driven by a single root `CancellationToken` per process:
20//! - OS signals (SIGTERM, SIGINT, Ctrl+C) are hooked at bootstrap level
21//! - The root token is passed to `RunOptions::Token` for gear runtime shutdown
22//! - Background tasks (like heartbeat) use child tokens derived from the root
23//!
24//! On shutdown, the gear deregisters itself from the `DirectoryService` before exiting.
25//!
26//! ## Example
27//!
28//! ```rust,no_run
29//! use toolkit::bootstrap::oop::{OopRunOptions, run_oop_with_options};
30//!
31//! #[tokio::main]
32//! async fn main() -> anyhow::Result<()> {
33//!     let opts = OopRunOptions {
34//!         gear_name: "my_gear".to_string(),
35//!         config_gear_name: None,
36//!         instance_id: None,
37//!         directory_endpoint: "http://127.0.0.1:50051".to_string(),
38//!         config_path: None,
39//!         verbose: 0,
40//!         print_config: false,
41//!         heartbeat_interval_secs: 5,
42//!         version: None,
43//!     };
44//!
45//!     run_oop_with_options(opts).await
46//! }
47//! ```
48
49use anyhow::{Context, Result};
50use figment::{Figment, providers::Serialized};
51use std::path::{Path, PathBuf};
52use std::sync::Arc;
53use std::time::Duration;
54use tokio::time::sleep;
55use tokio_util::sync::CancellationToken;
56use tracing::{debug, error, info, warn};
57use uuid::Uuid;
58
59use super::config::{
60    AppConfig, LoggingConfig, RenderedDbConfig, RenderedGearConfig, TOOLKIT_MODULE_CONFIG_ENV,
61};
62use crate::bootstrap::host::{init_logging_unified, init_panic_tracing};
63use crate::runtime::{
64    ClientCleanup, ClientCleanupError, ClientRegistration, DbOptions, OopServeOptions, RunOptions,
65    ShutdownOptions, TOOLKIT_DIRECTORY_ENDPOINT_ENV, run, run_oop_serving, shutdown,
66};
67use cf_system_sdks::directory::{DirectoryClient, DirectoryGrpcClient};
68use toolkit_contract::runtime::config::InternalTokenProvider;
69
70/// Supplies process lifetime inputs to a composition factory.
71#[derive(Debug)]
72pub struct OopCompositionContext {
73    /// Cancels process work when shutdown starts.
74    pub cancel: CancellationToken,
75    /// The outbound credential shared with the directory client and gear contexts.
76    pub internal_token_provider: Option<InternalTokenProvider>,
77}
78
79/// Transfers the factory's clients and their cleanup operation to bootstrap.
80pub struct OopComposition {
81    /// The directory registration name for this serving role.
82    pub registration_name: String,
83    /// Registrations installed before gear initialization.
84    pub clients: Vec<ClientRegistration>,
85    /// Completes client shutdown after gears stop. Use a separate abort token so
86    /// process cancellation leaves client workers available during gear shutdown.
87    pub cleanup: ClientCleanup,
88}
89
90impl std::fmt::Debug for OopComposition {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.debug_struct("OopComposition")
93            .field("registration_name", &self.registration_name)
94            .field("client_count", &self.clients.len())
95            .field("cleanup", &self.cleanup)
96            .finish()
97    }
98}
99
100/// Constructs clients from the effective configuration. Finish all fallible work
101/// before starting a factory-owned worker. Once a worker starts, transfer its
102/// cleanup owner through the successful return.
103pub type OopCompositionFactory =
104    fn(&AppConfig, &OopCompositionContext) -> Result<OopComposition, OopCompositionError>;
105
106/// A static failure category safe to report without exposing configuration values.
107#[derive(Debug, PartialEq, Eq, thiserror::Error)]
108pub enum OopCompositionError {
109    /// The named field has an invalid value.
110    #[error("invalid composition configuration field: {field}")]
111    InvalidConfig { field: &'static str },
112    /// Client construction failed in the named component.
113    #[error("client construction failed: {component}")]
114    ClientConstruction { component: &'static str },
115}
116
117/// The outcome of composition, gear execution, or client shutdown.
118#[derive(Debug, thiserror::Error)]
119pub enum OopCompositionRunError {
120    /// Composition failed before client ownership transferred to bootstrap.
121    #[error(transparent)]
122    Composition(#[from] OopCompositionError),
123    /// Bootstrap or the gear runtime failed.
124    #[error("OoP bootstrap failed: {source}")]
125    Bootstrap {
126        source: Box<dyn std::error::Error + Send + Sync>,
127    },
128    /// Client cleanup failed after successful gear execution.
129    #[error(transparent)]
130    Cleanup(#[from] ClientCleanupError),
131    /// Both bootstrap and subsequent client cleanup failed.
132    #[error("OoP bootstrap failed: {source}. Client cleanup failed: {cleanup}")]
133    BootstrapAndCleanup {
134        source: Box<dyn std::error::Error + Send + Sync>,
135        cleanup: ClientCleanupError,
136    },
137}
138
139impl OopCompositionRunError {
140    fn bootstrap(error: anyhow::Error) -> Self {
141        Self::Bootstrap {
142            source: error.reallocate_into_boxed_dyn_error_without_backtrace(),
143        }
144    }
145}
146
147/// Configuration options for `OoP` gear bootstrap
148#[derive(Debug, Clone)]
149pub struct OopRunOptions {
150    /// Directory registration name used by [`run_oop_with_options`].
151    ///
152    /// [`run_oop_with_composition`] uses [`OopComposition::registration_name`] instead.
153    /// This value remains the configuration-key fallback when
154    /// [`Self::config_gear_name`](field@Self::config_gear_name) is `None`.
155    pub gear_name: String,
156
157    /// Key of the `gears.<key>` configuration section.
158    ///
159    /// `None` selects [`Self::gear_name`] in both entrypoints.
160    /// The composition's registration name does not change this key.
161    pub config_gear_name: Option<String>,
162
163    /// Instance ID (defaults to a random UUID if None)
164    pub instance_id: Option<Uuid>,
165
166    /// Directory service gRPC endpoint (e.g., "<http://127.0.0.1:50051>")
167    pub directory_endpoint: String,
168
169    /// Path to configuration file
170    pub config_path: Option<PathBuf>,
171
172    /// Log verbosity level (0=default, 1=debug, 2=trace)
173    pub verbose: u8,
174
175    /// Print configuration and exit before running the gear.
176    ///
177    /// [`run_oop_with_options`] prints the loaded local configuration.
178    /// [`run_oop_with_composition`] prints configuration after merging the rendered gear section
179    /// with local overrides, before client construction. Both apply CLI verbosity overrides.
180    pub print_config: bool,
181
182    /// Heartbeat interval in seconds (default: 5)
183    pub heartbeat_interval_secs: u64,
184
185    /// Gear version (used for `DirectoryService` registration and `OpenAPI` version).
186    /// Defaults to `None`.
187    pub version: Option<String>,
188}
189
190impl OopRunOptions {
191    /// Configuration key from [`Self::config_gear_name`](field@Self::config_gear_name),
192    /// or [`Self::gear_name`] when unset.
193    #[must_use]
194    pub fn config_gear_name(&self) -> &str {
195        self.config_gear_name.as_deref().unwrap_or(&self.gear_name)
196    }
197}
198
199impl Default for OopRunOptions {
200    fn default() -> Self {
201        // Check for config path in environment variable as fallback
202        let config_path = std::env::var("TOOLKIT_CONFIG_PATH").ok().map(PathBuf::from);
203
204        // Check for directory endpoint in environment variable (set by master host)
205        // This is the preferred way to get the endpoint when spawned by master host
206        let directory_endpoint = std::env::var(TOOLKIT_DIRECTORY_ENDPOINT_ENV)
207            .unwrap_or_else(|_| "http://127.0.0.1:50051".to_owned());
208
209        Self {
210            gear_name: String::new(),
211            config_gear_name: None,
212            instance_id: None,
213            directory_endpoint,
214            config_path,
215            verbose: 0,
216            print_config: false,
217            heartbeat_interval_secs: 5,
218            version: None,
219        }
220    }
221}
222
223/// Builds the final configuration and `DbOptions` for an `OoP` gear.
224///
225/// Configuration merge strategy (for each section):
226/// - **Database**: field-by-field merge using `DbManager` (master as base, local as override)
227/// - **Logging**: key-by-key merge (each subsystem key is overridden by local)
228/// - **Config**: local completely replaces master if present
229///
230/// The local config file (--config) can override any settings from master's `TOOLKIT_MODULE_CONFIG`.
231///
232/// For database, the merge happens at 3 levels:
233/// 1. Global database.servers.* from master
234/// 2. Gear's database section from master (gears.<name>.database)
235/// 3. Gear's database section from local --config (overrides master)
236#[tracing::instrument(
237    level = "debug",
238    skip(local_config, rendered_config),
239    fields(
240        has_rendered = rendered_config.is_some(),
241        has_local_db = local_config.database.is_some()
242    )
243)]
244fn build_oop_config_and_db(
245    local_config: &AppConfig,
246    gear_name: &str,
247    rendered_config: Option<&RenderedGearConfig>,
248) -> Result<(AppConfig, LoggingConfig, DbOptions)> {
249    let home_dir = PathBuf::from(&local_config.server.home_dir);
250    let final_config = effective_oop_config(local_config, gear_name, rendered_config);
251
252    // Merge logging: master logging (base) + local logging (override by key)
253    let final_logging = merge_logging_configs(
254        rendered_config.as_ref().and_then(|r| r.logging.as_ref()),
255        &local_config.logging,
256    );
257
258    // Build DbOptions using Figment merge + DbManager
259    // This allows field-by-field merge: master db config (base) -> local db config (override)
260    let db_options = build_merged_db_options(
261        &home_dir,
262        gear_name,
263        rendered_config.as_ref().and_then(|r| r.database.as_ref()),
264        local_config,
265    )?;
266
267    Ok((final_config, final_logging, db_options))
268}
269
270/// Merge the master's rendered gear config with local overrides, without I/O.
271/// Shared by runtime and deployment publication to produce identical manifests.
272fn effective_oop_config(
273    local_config: &AppConfig,
274    gear_name: &str,
275    rendered_config: Option<&RenderedGearConfig>,
276) -> AppConfig {
277    if let Some(rendered) = rendered_config {
278        // TOOLKIT_MODULE_CONFIG exists: use rendered config as BASE, local config as OVERRIDE
279        let mut config = local_config.clone();
280
281        // Get or create the gear entry
282        let gear_entry = config
283            .gears
284            .entry(gear_name.to_owned())
285            .or_insert_with(|| serde_json::json!({}));
286
287        // Merge rendered.config as base, local gear config as override
288        if let Some(obj) = gear_entry.as_object_mut() {
289            // If local doesn't have "config" section, use rendered entirely
290            // If local has "config" section, it takes precedence (local overrides master)
291            if !obj.contains_key("config") || obj["config"].is_null() {
292                obj.insert("config".to_owned(), rendered.config.clone());
293            }
294            // If local has "config", it already overrides - no action needed
295            // `clients` follows the same rule.
296            if !rendered.clients.is_null()
297                && (!obj.contains_key("clients") || obj["clients"].is_null())
298            {
299                obj.insert("clients".to_owned(), rendered.clients.clone());
300            }
301        }
302
303        debug!(
304            gear =  %gear_name,
305            has_rendered_db = %rendered.database.is_some(),
306            has_rendered_logging = %rendered.logging.is_some(),
307            "Using rendered config from master as base, local config as override"
308        );
309
310        config
311    } else {
312        // No TOOLKIT_MODULE_CONFIG: use local config entirely (standalone mode)
313        debug!(
314            gear =  %gear_name,
315            "No rendered config from master, using local config entirely (standalone mode)"
316        );
317        local_config.clone()
318    }
319}
320
321/// Load the `OoP` unit's effective config: local file and CLI overrides merged
322/// with `TOOLKIT_MODULE_CONFIG`, as for runtime startup, without starting gears.
323/// Used by [`run_publish_gts`](super::run_publish_gts).
324///
325/// # Errors
326/// The file cannot be loaded or the rendered configuration is invalid.
327pub fn oop_publication_config(opts: &OopRunOptions) -> Result<AppConfig> {
328    oop_publication_config_from(opts, rendered_config_from_env()?.as_ref())
329}
330
331/// The master's rendered configuration from `TOOLKIT_MODULE_CONFIG`: `None`
332/// when the variable is absent. The `OoP` runtime and the deployment job share
333/// it, so both fail on the same invalid value.
334///
335/// # Errors
336/// The variable is present but not a valid rendered configuration.
337fn rendered_config_from_env() -> Result<Option<RenderedGearConfig>> {
338    parse_rendered_config(std::env::var(TOOLKIT_MODULE_CONFIG_ENV).ok().as_deref())
339}
340
341fn parse_rendered_config(value: Option<&str>) -> Result<Option<RenderedGearConfig>> {
342    value
343        .map(RenderedGearConfig::from_json)
344        .transpose()
345        .with_context(|| format!("{TOOLKIT_MODULE_CONFIG_ENV} is set but invalid"))
346}
347
348fn oop_publication_config_from(
349    opts: &OopRunOptions,
350    rendered: Option<&RenderedGearConfig>,
351) -> Result<AppConfig> {
352    let mut config = AppConfig::load_or_default(opts.config_path.as_ref())?;
353    config.apply_cli_overrides(opts.verbose);
354    Ok(effective_oop_config(
355        &config,
356        opts.config_gear_name(),
357        rendered,
358    ))
359}
360
361/// Merges logging configurations: master as base, local as override (by key).
362///
363/// Each key in the logging `HashMap` (e.g., "default", "calculator", "sqlx")
364/// is overridden by local if present.
365fn merge_logging_configs(master: Option<&LoggingConfig>, local: &LoggingConfig) -> LoggingConfig {
366    master
367        .cloned()
368        .unwrap_or_default()
369        .into_iter()
370        .chain(local.clone())
371        .collect()
372}
373
374/// Builds `DbOptions` by merging rendered config from master with local config.
375///
376/// Uses Figment to merge configurations and `DbManager` to handle the actual
377/// database connection setup with field-by-field merge logic.
378fn build_merged_db_options(
379    home_dir: &Path,
380    gear_name: &str,
381    rendered_db: Option<&RenderedDbConfig>,
382    local_config: &AppConfig,
383) -> Result<DbOptions> {
384    // Check if we have any database configuration
385    let has_rendered_db = rendered_db.is_some_and(|db| db.gear.is_some() || db.global.is_some());
386    let has_local_db = local_config.database.is_some()
387        || local_config
388            .gears
389            .values()
390            .any(|m| m.get("database").is_some());
391
392    if !has_rendered_db && !has_local_db {
393        debug!(
394            gear =  %gear_name,
395            "No database config available"
396        );
397        return Ok(DbOptions::None);
398    }
399
400    // Build a merged configuration for DbManager:
401    // 1. Start with rendered config from master (global servers + gear db)
402    // 2. Overlay local config (local can override any field)
403
404    let mut merged_config = serde_json::Map::new();
405
406    // Step 1: Add rendered database config from master as base
407    if let Some(rendered) = rendered_db {
408        // Add global servers from master
409        if let Some(ref global) = rendered.global {
410            let global_json = serde_json::to_value(global)
411                .context("Failed to serialize rendered global db config")?;
412            merged_config.insert("database".to_owned(), global_json);
413        }
414
415        // Add gear's database config from master
416        if let Some(ref gear_db) = rendered.gear {
417            let gear_db_json = serde_json::to_value(gear_db)
418                .context("Failed to serialize rendered gear db config")?;
419
420            let mut gears = serde_json::Map::new();
421            let mut gear_entry = serde_json::Map::new();
422            gear_entry.insert("database".to_owned(), gear_db_json);
423            gears.insert(gear_name.to_owned(), serde_json::Value::Object(gear_entry));
424            merged_config.insert("gears".to_owned(), serde_json::Value::Object(gears));
425        }
426    }
427
428    // Step 2: Overlay local config (local overrides master)
429    // Local global database config
430    if let Some(ref local_db) = local_config.database {
431        let local_db_json =
432            serde_json::to_value(local_db).context("Failed to serialize local global db config")?;
433
434        // Merge with existing or replace
435        if let Some(existing) = merged_config.get_mut("database") {
436            merge_json_objects(existing, &local_db_json);
437        } else {
438            merged_config.insert("database".to_owned(), local_db_json);
439        }
440    }
441
442    // Local gear database config: the unit's own gear, and every gear it co-hosts
443    // that names a database in the local config (the master renders only its own).
444    for (local_gear_name, local_gear) in &local_config.gears {
445        let Some(local_gear_db) = local_gear.get("database") else {
446            continue;
447        };
448        let gears = merged_config
449            .entry("gears".to_owned())
450            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
451
452        if let Some(gears_obj) = gears.as_object_mut() {
453            let gear_entry = gears_obj
454                .entry(local_gear_name.clone())
455                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
456
457            if let Some(gear_obj) = gear_entry.as_object_mut() {
458                if let Some(existing_db) = gear_obj.get_mut("database") {
459                    merge_json_objects(existing_db, local_gear_db);
460                } else {
461                    gear_obj.insert("database".to_owned(), local_gear_db.clone());
462                }
463            }
464        }
465    }
466
467    debug!(
468        gear =  %gear_name,
469        has_rendered = %rendered_db.is_some(),
470        has_local_global = %local_config.database.is_some(),
471        "Building DbManager with merged config"
472    );
473
474    // Create DbManager from merged Figment
475    let figment = Figment::new().merge(Serialized::defaults(serde_json::Value::Object(
476        merged_config,
477    )));
478    let db_manager = Arc::new(
479        toolkit_db::DbManager::from_figment(figment, home_dir.to_path_buf())
480            .context("Failed to create DbManager from merged config")?,
481    );
482
483    Ok(DbOptions::Manager(db_manager))
484}
485
486/// Recursively merges source JSON object into target.
487/// Source values override target values for matching keys.
488fn merge_json_objects(target: &mut serde_json::Value, source: &serde_json::Value) {
489    if let (Some(target_obj), Some(source_obj)) = (target.as_object_mut(), source.as_object()) {
490        for (key, value) in source_obj {
491            if let Some(target_value) = target_obj.get_mut(key) {
492                // Recursively merge objects, otherwise replace
493                if target_value.is_object() && value.is_object() {
494                    merge_json_objects(target_value, value);
495                } else {
496                    *target_value = value.clone();
497                }
498            } else {
499                target_obj.insert(key.clone(), value.clone());
500            }
501        }
502    } else {
503        // If target is not an object, replace entirely
504        *target = source.clone();
505    }
506}
507
508/// Runs an out-of-process gear under the process signal token.
509///
510/// HTTP-serving gears manage directory presence through the serving lifecycle.
511/// Without HTTP configuration, a heartbeat maintains externally registered instances.
512/// Both modes use a lazy directory connection so a temporarily unavailable directory
513/// does not block startup.
514///
515/// # Example
516///
517/// ```rust,no_run
518/// use toolkit::bootstrap::oop::{OopRunOptions, run_oop_with_options};
519///
520/// #[tokio::main]
521/// async fn main() -> anyhow::Result<()> {
522///     let opts = OopRunOptions {
523///         gear_name: "file-parser".to_string(),
524///         config_gear_name: None,
525///         instance_id: None,
526///         directory_endpoint: "http://127.0.0.1:50051".to_string(),
527///         config_path: None,
528///         verbose: 1,
529///         print_config: false,
530///         heartbeat_interval_secs: 5,
531///         version: None,
532///     };
533///
534///     run_oop_with_options(opts).await
535/// }
536/// ```
537///
538/// # Errors
539///
540/// Returns an error if configuration, setup, or the gear lifecycle fails.
541#[tracing::instrument(
542    level = "info",
543    name = "oop_bootstrap",
544    skip(opts),
545    fields(
546        gear =  %opts.gear_name,
547        directory = %opts.directory_endpoint
548    )
549)]
550pub async fn run_oop_with_options(opts: OopRunOptions) -> Result<()> {
551    let cancel = process_cancellation()?;
552    let _on_exit = cancel.clone().drop_guard();
553    let Some(prepared) = prepare(&opts, &cancel, Invocation::Legacy)? else {
554        return Ok(());
555    };
556    let http = prepared.config.oop_http.clone();
557    let connected = prepared.connect(&opts.directory_endpoint).await?;
558    let result = if let Some(cfg) = http {
559        let (run_options, serve) = connected
560            .prepare_serving(&cfg, &opts.gear_name, &opts)
561            .await?;
562        run_oop_serving(run_options, serve).await
563    } else {
564        info!("Starting gear lifecycle (legacy gRPC-only)");
565        start_legacy_heartbeat(
566            connected.directory,
567            &opts,
568            connected.run_options.instance_id,
569            &cancel,
570        );
571        run(connected.run_options).await
572    };
573    report_runtime_result(&result);
574    #[cfg(feature = "otel")]
575    super::telemetry::tracing_shutdown().await;
576    result
577}
578
579/// Runs an HTTP-serving gear with application-supplied clients and a registration name.
580///
581/// The factory runs once after configuration and directory credentials are ready.
582/// Printing the effective configuration returns before client construction.
583/// After successful composition, bootstrap awaits the host lifecycle, then client cleanup
584/// under the server shutdown deadline, then telemetry shutdown.
585///
586/// # Cancellation safety
587///
588/// Dropping this future during serving preparation, execution, or unfinished client cleanup
589/// requests abort through the cleanup owner's token. A drop or deadline does not join workers.
590///
591/// # Errors
592///
593/// Returns the factory's typed error, a bootstrap failure, a cleanup failure, or both failures.
594pub async fn run_oop_with_composition(
595    options: OopRunOptions,
596    compose: OopCompositionFactory,
597) -> Result<(), OopCompositionRunError> {
598    let cancel = process_cancellation().map_err(OopCompositionRunError::bootstrap)?;
599    let _on_exit = cancel.clone().drop_guard();
600    let Some(prepared) = prepare(&options, &cancel, Invocation::Composed)
601        .map_err(OopCompositionRunError::bootstrap)?
602    else {
603        return Ok(());
604    };
605    let config = prepared.config.clone();
606    let http = config
607        .oop_http
608        .as_ref()
609        .ok_or(OopCompositionError::InvalidConfig { field: "oop_http" })?;
610    let mut connected = prepared
611        .connect(&options.directory_endpoint)
612        .await
613        .map_err(OopCompositionRunError::bootstrap)?;
614    let context = OopCompositionContext {
615        cancel: cancel.clone(),
616        internal_token_provider: connected.run_options.internal_token_provider.clone(),
617    };
618    let OopComposition {
619        registration_name,
620        clients,
621        cleanup,
622    } = compose(&config, &context)?;
623    connected.run_options.clients.extend(clients);
624    let host = async {
625        let (run_options, serve) = connected
626            .prepare_serving(http, &registration_name, &options)
627            .await?;
628        run_oop_serving(run_options, serve).await
629    };
630    let result = Box::pin(finalize_composition(host, cleanup, &cancel, &config.server)).await;
631    report_runtime_result(&result);
632    #[cfg(feature = "otel")]
633    super::telemetry::tracing_shutdown().await;
634    result
635}
636
637async fn finalize_composition(
638    host: impl std::future::Future<Output = Result<()>>,
639    cleanup: ClientCleanup,
640    cancel: &CancellationToken,
641    server: &super::config::ServerConfig,
642) -> Result<(), OopCompositionRunError> {
643    let result = host.await;
644    if result.is_err() {
645        cancel.cancel();
646    }
647    let deadline = server
648        .shutdown_deadline()
649        .unwrap_or(crate::runtime::DEFAULT_SHUTDOWN_DEADLINE);
650    let completion = tokio::time::timeout(deadline, cleanup.finish())
651        .await
652        .unwrap_or(Err(ClientCleanupError::DeadlineExceeded));
653    match (result, completion) {
654        (Ok(()), Ok(())) => Ok(()),
655        (Err(source), Ok(())) => Err(OopCompositionRunError::bootstrap(source)),
656        (Ok(()), Err(cleanup)) => Err(cleanup.into()),
657        (Err(source), Err(cleanup)) => Err(OopCompositionRunError::BootstrapAndCleanup {
658            source: source.reallocate_into_boxed_dyn_error_without_backtrace(),
659            cleanup,
660        }),
661    }
662}
663
664#[derive(Clone, Copy)]
665enum Invocation {
666    Legacy,
667    Composed,
668}
669
670struct Prepared {
671    config: Arc<AppConfig>,
672    db: DbOptions,
673    cancel: CancellationToken,
674    instance_id: Uuid,
675}
676
677struct Connected {
678    run_options: RunOptions,
679    directory: Arc<dyn DirectoryClient>,
680}
681
682impl Prepared {
683    async fn connect(self, endpoint: &str) -> Result<Connected> {
684        let auth = self
685            .config
686            .oop_http
687            .as_ref()
688            .and_then(|cfg| cfg.internal_auth.as_ref());
689        info!("Creating directory service client (lazy connect) for {endpoint}");
690        let (directory, provider) = build_directory_client(endpoint, auth, &self.cancel).await?;
691        info!("Directory service client ready (will connect on first use)");
692        let directory: Arc<dyn DirectoryClient> = Arc::new(directory);
693        let init_deadline = self.config.server.init_deadline();
694        let shutdown_deadline = self.config.server.shutdown_deadline();
695        let run_options = RunOptions::new(
696            self.config,
697            self.db,
698            ShutdownOptions::Token(self.cancel),
699            self.instance_id,
700        )
701        .with_clients(vec![ClientRegistration::new::<dyn DirectoryClient>(
702            directory.clone(),
703        )])
704        .with_internal_token_provider(provider)
705        .with_init_deadline(init_deadline)
706        .with_shutdown_deadline(shutdown_deadline);
707        Ok(Connected {
708            run_options,
709            directory,
710        })
711    }
712}
713
714impl Connected {
715    async fn prepare_serving(
716        self,
717        cfg: &super::config::OopHttpConfig,
718        name: &str,
719        opts: &OopRunOptions,
720    ) -> Result<(RunOptions, OopServeOptions)> {
721        let serve = build_oop_serve_options(
722            cfg,
723            name,
724            self.run_options.instance_id,
725            opts.version.clone(),
726            Duration::from_secs(opts.heartbeat_interval_secs),
727            self.directory,
728        )
729        .await?;
730        Ok((self.run_options, serve))
731    }
732}
733
734fn process_cancellation() -> Result<CancellationToken> {
735    super::init_crypto_provider()?;
736    Ok(arm_shutdown_wait(async {
737        wait_for_shutdown_or_fallback(
738            shutdown::wait_for_shutdown(),
739            tokio::signal::ctrl_c(),
740            std::io::stderr(),
741        )
742        .await;
743        info!("shutdown: signal received in OoP bootstrap");
744    }))
745}
746
747async fn wait_for_shutdown_or_fallback(
748    primary: impl std::future::Future<Output = anyhow::Result<()>>,
749    fallback: impl std::future::Future<Output = std::io::Result<()>>,
750    mut diagnostic: impl std::io::Write,
751) {
752    use futures_util::FutureExt;
753
754    let Err(error) = primary.await else {
755        return;
756    };
757    let mut fallback = std::pin::pin!(fallback);
758    // Arm Ctrl+C before stderr can block. The tracing subscriber may not be installed yet.
759    let fallback_pending = fallback.as_mut().now_or_never().is_none();
760    _ = writeln!(
761        diagnostic,
762        "OoP signal waiter failed, falling back to ctrl_c(): {error}"
763    );
764    drop(diagnostic);
765    if fallback_pending {
766        _ = fallback.await;
767    }
768}
769
770fn arm_shutdown_wait(
771    wait: impl std::future::Future<Output = ()> + Send + 'static,
772) -> CancellationToken {
773    use futures_util::FutureExt;
774
775    let cancel = CancellationToken::new();
776    let mut wait = Box::pin(wait);
777    // Register listeners before clients can start. The same waiter owns them until shutdown.
778    if wait.as_mut().now_or_never().is_some() {
779        cancel.cancel();
780    } else {
781        let process = cancel.clone();
782        tokio::spawn(async move {
783            tokio::select! {
784                () = process.cancelled() => {},
785                () = wait => process.cancel(),
786            }
787        });
788    }
789    cancel
790}
791
792fn prepare(
793    opts: &OopRunOptions,
794    cancel: &CancellationToken,
795    invocation: Invocation,
796) -> Result<Option<Prepared>> {
797    let instance_id = opts.instance_id.unwrap_or_else(Uuid::new_v4);
798    let mut config = AppConfig::load_or_default(opts.config_path.as_ref())?;
799    config.apply_cli_overrides(opts.verbose);
800    let rendered_config = rendered_config_from_env()?;
801
802    if opts.print_config && matches!(invocation, Invocation::Composed) {
803        print_config(&effective_oop_config(
804            &config,
805            opts.config_gear_name(),
806            rendered_config.as_ref(),
807        ));
808        return Ok(None);
809    }
810    let (final_config, merged_logging, db_options) =
811        build_oop_config_and_db(&config, opts.config_gear_name(), rendered_config.as_ref())?;
812    // The master owns telemetry settings for every child process.
813    #[cfg(feature = "otel")]
814    let otel_cfg = rendered_config
815        .as_ref()
816        .and_then(|rc| rc.opentelemetry.as_ref());
817
818    #[cfg(feature = "otel")]
819    let otel_layer = otel_cfg
820        .filter(|cfg| cfg.tracing.enabled)
821        .map(crate::telemetry::init_tracing)
822        .transpose()?;
823    #[cfg(not(feature = "otel"))]
824    let otel_layer = None;
825
826    // Defer the metrics diagnostic until the logging subscriber is installed.
827    #[cfg(feature = "otel")]
828    let metrics_init_error = otel_cfg
829        .filter(|cfg| cfg.metrics.enabled)
830        .and_then(|cfg| crate::telemetry::init::init_metrics_provider(cfg).err());
831
832    // An absent telemetry section enables trace IDs, matching the in-process default.
833    #[cfg(feature = "otel")]
834    let inject_trace_ids =
835        otel_cfg.is_none_or(crate::telemetry::OpenTelemetryConfig::inject_trace_ids_into_logs);
836    #[cfg(not(feature = "otel"))]
837    let inject_trace_ids = false;
838
839    init_logging_unified(
840        &merged_logging,
841        &config.server.home_dir,
842        otel_layer,
843        inject_trace_ids,
844    );
845
846    #[cfg(feature = "otel")]
847    if let Some(e) = metrics_init_error {
848        tracing::error!(error = %e, "OpenTelemetry metrics not initialized (OoP)");
849    }
850
851    init_panic_tracing();
852
853    if let Some(ref rc) = rendered_config {
854        info!(
855            env_var = TOOLKIT_MODULE_CONFIG_ENV,
856            has_database = rc.database.is_some(),
857            has_config = !rc.config.is_null(),
858            has_logging = rc.logging.is_some(),
859            has_opentelemetry = rc.opentelemetry.is_some(),
860            "Received rendered config from master host"
861        );
862    } else {
863        debug!(
864            env_var = TOOLKIT_MODULE_CONFIG_ENV,
865            "No rendered config from master host, using local config only"
866        );
867    }
868
869    info!(
870        gear =  %opts.gear_name,
871        instance_id = %instance_id,
872        directory_endpoint = %opts.directory_endpoint,
873        "OoP gear bootstrap starting"
874    );
875
876    if opts.print_config {
877        print_config(&config);
878        return Ok(None);
879    }
880
881    Ok(Some(Prepared {
882        config: Arc::new(final_config),
883        db: db_options,
884        cancel: cancel.clone(),
885        instance_id,
886    }))
887}
888
889fn start_legacy_heartbeat(
890    directory: Arc<dyn DirectoryClient>,
891    opts: &OopRunOptions,
892    instance_id: Uuid,
893    cancel: &CancellationToken,
894) {
895    let heartbeat_gear = opts.gear_name.clone();
896    let instance = instance_id.to_string();
897    let heartbeat_interval = Duration::from_secs(opts.heartbeat_interval_secs.max(1));
898    let cancel = cancel.child_token();
899    tokio::spawn(async move {
900        info!(interval_secs = ?heartbeat_interval, "Starting legacy heartbeat loop");
901        loop {
902            tokio::select! {
903                () = cancel.cancelled() => {
904                    info!("Heartbeat loop stopping due to cancellation");
905                    break;
906                }
907                () = sleep(heartbeat_interval) => {
908                    if let Err(error) = directory.send_heartbeat(&heartbeat_gear, &instance).await {
909                        warn!(%error, "Failed to send heartbeat, will retry");
910                    }
911                }
912            }
913        }
914    });
915}
916
917fn report_runtime_result<E: std::fmt::Display>(result: &Result<(), E>) {
918    if let Err(error) = result {
919        error!(%error, "Gear runtime failed");
920    } else {
921        info!("Gear runtime completed successfully");
922    }
923}
924
925/// Build [`OopServeOptions`] from configuration.
926///
927/// The tenant-plane `BearerAuthenticator` injection point is left unset here;
928/// the app/gear binary supplies that adapter when it needs the tenant-plane
929/// middleware installed. The platform-plane authenticator is constructed from
930/// `oop_http.internal_auth` when the `k8s-auth` feature is enabled.
931async fn build_oop_serve_options(
932    cfg: &super::config::OopHttpConfig,
933    gear_name: &str,
934    instance_id: Uuid,
935    version: Option<String>,
936    heartbeat_interval: Duration,
937    directory: Arc<dyn DirectoryClient>,
938) -> Result<OopServeOptions> {
939    let listen_addr: std::net::SocketAddr = cfg
940        .listen_addr
941        .parse()
942        .with_context(|| format!("invalid oop_http.listen_addr: {}", cfg.listen_addr))?;
943
944    let probe_bind_addr = cfg
945        .probe_bind_addr
946        .as_deref()
947        .map(|s| {
948            s.parse::<std::net::SocketAddr>()
949                .with_context(|| format!("invalid oop_http.probe_bind_addr: {s}"))
950        })
951        .transpose()?;
952
953    let advertise_uri = cfg
954        .advertise_uri
955        .clone()
956        .unwrap_or_else(|| default_advertise_uri(listen_addr));
957
958    // Fail fast on a malformed or unreachable advertise_uri rather than only
959    // when the directory rejects the registration — the same late-failure the
960    // label validation below avoids.
961    validate_advertise_uri(&advertise_uri, cfg.allow_loopback_advertise)?;
962    log_auth_disabled_when_routable(cfg.auth_disabled, &advertise_uri);
963
964    // Fail fast on a mis-configured label (bad charset, over-long, too many)
965    // at start-up, using the same shared rules the directory enforces. Without
966    // this the process would come up, attempt to register, and only then be
967    // permanently rejected by the directory — a confusing late failure for what
968    // is a static configuration error. Checked before authenticator init so a
969    // static config error is reported without any async backend setup.
970    cf_system_sdks::directory::validate_labels(&cfg.labels).with_context(|| {
971        "invalid oop_http.labels: label keys/values must be <=63 chars, <=64 entries, and use \
972         only ASCII alphanumerics plus '-', '_', '.' (starting and ending alphanumeric)"
973    })?;
974
975    let internal_authenticator = build_internal_authenticator(cfg.internal_auth.as_ref()).await?;
976
977    Ok(OopServeOptions {
978        gear_name: gear_name.to_owned(),
979        instance_id: instance_id.to_string(),
980        version,
981        advertise_uri,
982        listen_addr,
983        probe_bind_addr,
984        drain_timeout: Duration::from_secs(cfg.drain_timeout_secs),
985        heartbeat_interval,
986        healthcheck_timeout: Duration::from_millis(cfg.healthcheck_timeout_ms),
987        request_limits: cfg.request_limits,
988        directory,
989        bearer_authenticator: None,
990        internal_authenticator,
991        auth_disabled: cfg.auth_disabled,
992        labels: cfg.labels.clone(),
993    })
994}
995
996/// Construct the inbound platform-plane authenticator from configuration, via
997/// the shared [`toolkit_security::build_inbound_authenticator`] (also used by
998/// api-gateway and `grpc-hub`). `provider: kube` needs the `k8s-auth` feature;
999/// without it, it is an error rather than a silent enforcement downgrade.
1000/// `Ok(None)` only when no `internal_auth` is configured (Profile 1).
1001async fn build_internal_authenticator(
1002    cfg: Option<&toolkit_security::InternalAuthConfig>,
1003) -> Result<Option<toolkit_security::DynInternalAuthenticator>> {
1004    #[cfg(feature = "k8s-auth")]
1005    let kube = Some(toolkit_k8s_auth::kube_authenticator_builder(
1006        Some(toolkit_security::DEFAULT_TOKEN_REVIEW_CACHE_TTL),
1007        None,
1008    ));
1009    #[cfg(not(feature = "k8s-auth"))]
1010    let kube = None;
1011    toolkit_security::build_inbound_authenticator(cfg, kube)
1012        .await
1013        .map_err(|e| anyhow::anyhow!("oop_http: {e}"))
1014}
1015
1016/// Build the `OoP` gear's `DirectoryService` client on a **lazy** channel, plus
1017/// the outbound
1018/// [`InternalTokenProvider`](toolkit_contract::runtime::config::InternalTokenProvider)
1019/// when a platform-plane credential is configured (`None` => no credential).
1020///
1021/// The lazy channel performs no eager connection, so this succeeds even when
1022/// `directory_endpoint` is unreachable (`cpt-cf-adr-eventual-readiness`).
1023///
1024/// The provider is built by the shared
1025/// [`build_internal_token_provider`](toolkit_contract::runtime::platform_credential::build_internal_token_provider),
1026/// and the directory client's interceptor is a thin adapter over it, so the two
1027/// can't diverge after a rotation and follow the same attach policy. An `OoP`
1028/// gear always registers and heartbeats with `DirectoryService`, so a kube
1029/// config without a `present` block is a startup error here.
1030///
1031/// # Errors
1032/// Only if the endpoint is malformed or a configured credential source fails to
1033/// initialise — never for an unreachable directory. The endpoint is validated
1034/// before any credential work, so a malformed endpoint is reported ahead of a
1035/// credential-source failure.
1036async fn build_directory_client(
1037    directory_endpoint: &str,
1038    internal_auth_cfg: Option<&toolkit_security::InternalAuthConfig>,
1039    cancel: &CancellationToken,
1040) -> Result<(
1041    DirectoryGrpcClient,
1042    Option<toolkit_contract::runtime::config::InternalTokenProvider>,
1043)> {
1044    // Validate the endpoint up front — before any credential-source work — so a
1045    // malformed endpoint is reported ahead of a credential failure. The lazy
1046    // client performs no connection, only URI validation; it is reused as-is on
1047    // the no-credential path.
1048    let client = DirectoryGrpcClient::connect_lazy(directory_endpoint)?;
1049
1050    let Some(cfg) = internal_auth_cfg else {
1051        return Ok((client, None));
1052    };
1053
1054    let provider =
1055        toolkit_contract::runtime::platform_credential::build_internal_token_provider(cfg, cancel)
1056            .await?;
1057    let interceptor = toolkit_contract::runtime::platform_credential::internal_auth_interceptor(
1058        Some(&provider),
1059        "directory",
1060    );
1061    // Rebuild with the interceptor attached (it must be set at construction);
1062    // the endpoint was already validated above.
1063    let client =
1064        DirectoryGrpcClient::connect_lazy_with_interceptor(directory_endpoint, interceptor)?;
1065    Ok((client, Some(provider)))
1066}
1067
1068/// Derive a default advertise URI from the bind address. Unspecified hosts
1069/// (`0.0.0.0` / `[::]`) are rewritten to loopback, and every IPv6 host is
1070/// enclosed in brackets so the resulting URI is valid when registered as a
1071/// REST endpoint.
1072fn default_advertise_uri(listen_addr: std::net::SocketAddr) -> String {
1073    let host = match listen_addr {
1074        std::net::SocketAddr::V4(addr) if addr.ip().is_unspecified() => "127.0.0.1".to_owned(),
1075        std::net::SocketAddr::V4(addr) => addr.ip().to_string(),
1076        std::net::SocketAddr::V6(addr) if addr.ip().is_unspecified() => "[::1]".to_owned(),
1077        std::net::SocketAddr::V6(addr) => format!("[{}]", addr.ip()),
1078    };
1079    format!("http://{host}:{}", listen_addr.port())
1080}
1081
1082/// Reject a malformed or unreachable `advertise_uri` at start-up (fail fast).
1083///
1084/// Checks shape (parseable `http`/`https` URL, non-empty host, no userinfo) and,
1085/// unless `allow_loopback`, rejects a loopback / unspecified host - a
1086/// registered-but-unreachable instance in multi-host Profile 2 / Profile 3
1087/// (`cpt-cf-adr-instance-addressable-discovery` section 5). The default derives
1088/// loopback from an unspecified bind, so this also covers an *unset* value. The
1089/// directory enforces its full endpoint ruleset server-side.
1090fn validate_advertise_uri(uri: &str, allow_loopback: bool) -> Result<()> {
1091    let parsed = url::Url::parse(uri)
1092        .with_context(|| format!("invalid oop_http.advertise_uri: not a valid URL: {uri}"))?;
1093    if !matches!(parsed.scheme(), "http" | "https") {
1094        anyhow::bail!(
1095            "invalid oop_http.advertise_uri: scheme must be http or https (got '{}')",
1096            parsed.scheme()
1097        );
1098    }
1099    if parsed.host_str().is_none_or(str::is_empty) {
1100        anyhow::bail!("invalid oop_http.advertise_uri: missing host: {uri}");
1101    }
1102    if !parsed.username().is_empty() || parsed.password().is_some() {
1103        anyhow::bail!("invalid oop_http.advertise_uri: must not contain userinfo: {uri}");
1104    }
1105    if !allow_loopback && is_loopback_host(&parsed) {
1106        anyhow::bail!(
1107            "invalid oop_http.advertise_uri: '{uri}' is a loopback/unspecified address, which is \
1108             unreachable by other gears in multi-host Profile 2 / Profile 3 (a registered-but-\
1109             unreachable instance). Set oop_http.advertise_uri to a routable host, or set \
1110             oop_http.allow_loopback_advertise = true for single-host / local-dev."
1111        );
1112    }
1113    Ok(())
1114}
1115
1116/// Whether `uri`'s host is loopback / unspecified, i.e. unreachable from other hosts.
1117fn is_loopback_host(uri: &url::Url) -> bool {
1118    match uri.host() {
1119        Some(url::Host::Ipv4(ip)) => ip.is_loopback() || ip.is_unspecified(),
1120        Some(url::Host::Ipv6(ip)) => ip.is_loopback() || ip.is_unspecified(),
1121        Some(url::Host::Domain(d)) => d.trim_end_matches('.').eq_ignore_ascii_case("localhost"),
1122        None => false,
1123    }
1124}
1125
1126/// Log an `error!` when the development-only `auth_disabled` is set on a worker advertised
1127/// at a routable address: other hosts reach it through the directory, and every tenant's
1128/// request then runs as the default tenant.
1129fn log_auth_disabled_when_routable(auth_disabled: bool, advertise_uri: &str) {
1130    if !auth_disabled {
1131        return;
1132    }
1133    let routable = url::Url::parse(advertise_uri).is_ok_and(|uri| !is_loopback_host(&uri));
1134    if routable {
1135        tracing::error!(
1136            advertise_uri,
1137            "oop_http.auth_disabled is set on a worker advertised at a routable address: every \
1138             tenant request reaching it runs as the default tenant. Development only; unset it \
1139             or advertise a loopback address."
1140        );
1141    }
1142}
1143
1144#[allow(unknown_lints, de1301_no_print_macros)] // direct stdout config print before exit
1145fn print_config(config: &AppConfig) {
1146    match config.to_yaml() {
1147        Ok(yaml) => {
1148            println!("{yaml}");
1149        }
1150        Err(e) => {
1151            eprintln!("Failed to render config as YAML: {e}");
1152        }
1153    }
1154}
1155
1156#[cfg(test)]
1157#[cfg_attr(coverage_nightly, coverage(off))]
1158#[path = "oop_tests.rs"]
1159mod tests;