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, CliArgs, LoggingConfig, RenderedDbConfig, RenderedGearConfig,
61 TOOLKIT_MODULE_CONFIG_ENV,
62};
63use crate::bootstrap::host::{init_logging_unified, init_panic_tracing};
64use crate::runtime::{
65 ClientRegistration, DbOptions, OopServeOptions, RunOptions, ShutdownOptions,
66 TOOLKIT_DIRECTORY_ENDPOINT_ENV, run, run_oop_serving, shutdown,
67};
68use cf_system_sdks::directory::{DirectoryClient, DirectoryGrpcClient};
69
70/// Configuration options for `OoP` gear bootstrap
71#[derive(Debug, Clone)]
72pub struct OopRunOptions {
73 /// Logical gear name (e.g., "`file-parser`")
74 ///
75 /// **This is the directory registration name, and since roles it is not
76 /// always the gear's own id.** A role-split gear registers under its role's
77 /// directory name -- `event-broker-ingest` for the `cluster_ingest` mode --
78 /// while its configuration still lives under the gear id the
79 /// `#[toolkit::gear(name = ...)]` attribute declares, because that is the
80 /// key `GearCtx::config()` looks up. See [`Self::config_gear_name`].
81 pub gear_name: String,
82
83 /// The `gears.<key>` section this process's configuration lives under.
84 ///
85 /// `None` means the same as [`Self::gear_name`], which is the answer for
86 /// every gear that runs in one undifferentiated shape -- so no existing
87 /// caller changes behaviour.
88 ///
89 /// **It exists because `gear_name` was doing two jobs that used to be one
90 /// string.** The registry names a gear by its attribute, and
91 /// `GearCtx::config()` reads `gears.<that name>.config`; a role changes the
92 /// name the instance *registers* under and not the name it *reads* under.
93 /// With the two conflated, a worker started as a role filed the master's
94 /// rendered blob under `gears["event-broker-ingest"]` while the gear read
95 /// `gears["event-broker"]`, so `TOOLKIT_MODULE_CONFIG` was inert under any
96 /// role and only the local `--config` file had any effect. Nothing failed;
97 /// the override simply did not arrive.
98 pub config_gear_name: Option<String>,
99
100 /// Instance ID (defaults to a random UUID if None)
101 pub instance_id: Option<Uuid>,
102
103 /// Directory service gRPC endpoint (e.g., "<http://127.0.0.1:50051>")
104 pub directory_endpoint: String,
105
106 /// Path to configuration file
107 pub config_path: Option<PathBuf>,
108
109 /// Log verbosity level (0=default, 1=debug, 2=trace)
110 pub verbose: u8,
111
112 /// Print effective configuration and exit
113 pub print_config: bool,
114
115 /// Heartbeat interval in seconds (default: 5)
116 pub heartbeat_interval_secs: u64,
117
118 /// Gear version (used for `DirectoryService` registration and `OpenAPI` version).
119 /// Defaults to `None`.
120 pub version: Option<String>,
121}
122
123impl OopRunOptions {
124 /// The `gears.<key>` section to read configuration from.
125 ///
126 /// [`Self::config_gear_name`] when set, and [`Self::gear_name`] otherwise --
127 /// so a caller that does not know about roles keeps exactly the behaviour it
128 /// had.
129 #[must_use]
130 pub fn config_gear_name(&self) -> &str {
131 self.config_gear_name.as_deref().unwrap_or(&self.gear_name)
132 }
133}
134
135impl Default for OopRunOptions {
136 fn default() -> Self {
137 // Check for config path in environment variable as fallback
138 let config_path = std::env::var("TOOLKIT_CONFIG_PATH").ok().map(PathBuf::from);
139
140 // Check for directory endpoint in environment variable (set by master host)
141 // This is the preferred way to get the endpoint when spawned by master host
142 let directory_endpoint = std::env::var(TOOLKIT_DIRECTORY_ENDPOINT_ENV)
143 .unwrap_or_else(|_| "http://127.0.0.1:50051".to_owned());
144
145 Self {
146 gear_name: String::new(),
147 config_gear_name: None,
148 instance_id: None,
149 directory_endpoint,
150 config_path,
151 verbose: 0,
152 print_config: false,
153 heartbeat_interval_secs: 5,
154 version: None,
155 }
156 }
157}
158
159/// Builds the final configuration and `DbOptions` for an `OoP` gear.
160///
161/// Configuration merge strategy (for each section):
162/// - **Database**: field-by-field merge using `DbManager` (master as base, local as override)
163/// - **Logging**: key-by-key merge (each subsystem key is overridden by local)
164/// - **Config**: local completely replaces master if present
165///
166/// The local config file (--config) can override any settings from master's `TOOLKIT_MODULE_CONFIG`.
167///
168/// For database, the merge happens at 3 levels:
169/// 1. Global database.servers.* from master
170/// 2. Gear's database section from master (gears.<name>.database)
171/// 3. Gear's database section from local --config (overrides master)
172#[tracing::instrument(
173 level = "debug",
174 skip(local_config, rendered_config),
175 fields(
176 has_rendered = rendered_config.is_some(),
177 has_local_db = local_config.database.is_some()
178 )
179)]
180fn build_oop_config_and_db(
181 local_config: &AppConfig,
182 gear_name: &str,
183 rendered_config: Option<&RenderedGearConfig>,
184) -> Result<(AppConfig, LoggingConfig, DbOptions)> {
185 let home_dir = PathBuf::from(&local_config.server.home_dir);
186 let final_config = effective_oop_config(local_config, gear_name, rendered_config);
187
188 // Merge logging: master logging (base) + local logging (override by key)
189 let final_logging = merge_logging_configs(
190 rendered_config.as_ref().and_then(|r| r.logging.as_ref()),
191 &local_config.logging,
192 );
193
194 // Build DbOptions using Figment merge + DbManager
195 // This allows field-by-field merge: master db config (base) -> local db config (override)
196 let db_options = build_merged_db_options(
197 &home_dir,
198 gear_name,
199 rendered_config.as_ref().and_then(|r| r.database.as_ref()),
200 local_config,
201 )?;
202
203 Ok((final_config, final_logging, db_options))
204}
205
206/// Merge the master's rendered gear config with local overrides, without I/O.
207/// Shared by runtime and deployment publication to produce identical manifests.
208fn effective_oop_config(
209 local_config: &AppConfig,
210 gear_name: &str,
211 rendered_config: Option<&RenderedGearConfig>,
212) -> AppConfig {
213 if let Some(rendered) = rendered_config {
214 // TOOLKIT_MODULE_CONFIG exists: use rendered config as BASE, local config as OVERRIDE
215 let mut config = local_config.clone();
216
217 // Get or create the gear entry
218 let gear_entry = config
219 .gears
220 .entry(gear_name.to_owned())
221 .or_insert_with(|| serde_json::json!({}));
222
223 // Merge rendered.config as base, local gear config as override
224 if let Some(obj) = gear_entry.as_object_mut() {
225 // If local doesn't have "config" section, use rendered entirely
226 // If local has "config" section, it takes precedence (local overrides master)
227 if !obj.contains_key("config") || obj["config"].is_null() {
228 obj.insert("config".to_owned(), rendered.config.clone());
229 }
230 // If local has "config", it already overrides - no action needed
231 // `clients` follows the same rule.
232 if !rendered.clients.is_null()
233 && (!obj.contains_key("clients") || obj["clients"].is_null())
234 {
235 obj.insert("clients".to_owned(), rendered.clients.clone());
236 }
237 }
238
239 debug!(
240 gear = %gear_name,
241 has_rendered_db = %rendered.database.is_some(),
242 has_rendered_logging = %rendered.logging.is_some(),
243 "Using rendered config from master as base, local config as override"
244 );
245
246 config
247 } else {
248 // No TOOLKIT_MODULE_CONFIG: use local config entirely (standalone mode)
249 debug!(
250 gear = %gear_name,
251 "No rendered config from master, using local config entirely (standalone mode)"
252 );
253 local_config.clone()
254 }
255}
256
257/// Load the `OoP` unit's effective config: local file and CLI overrides merged
258/// with `TOOLKIT_MODULE_CONFIG`, as for runtime startup, without starting gears.
259/// Used by [`run_publish_gts`](super::run_publish_gts).
260///
261/// # Errors
262/// The file cannot be loaded or the rendered configuration is invalid.
263pub fn oop_publication_config(opts: &OopRunOptions) -> Result<AppConfig> {
264 oop_publication_config_from(opts, rendered_config_from_env()?.as_ref())
265}
266
267/// The master's rendered configuration from `TOOLKIT_MODULE_CONFIG`: `None`
268/// when the variable is absent. The `OoP` runtime and the deployment job share
269/// it, so both fail on the same invalid value.
270///
271/// # Errors
272/// The variable is present but not a valid rendered configuration.
273fn rendered_config_from_env() -> Result<Option<RenderedGearConfig>> {
274 parse_rendered_config(std::env::var(TOOLKIT_MODULE_CONFIG_ENV).ok().as_deref())
275}
276
277fn parse_rendered_config(value: Option<&str>) -> Result<Option<RenderedGearConfig>> {
278 value
279 .map(RenderedGearConfig::from_json)
280 .transpose()
281 .with_context(|| format!("{TOOLKIT_MODULE_CONFIG_ENV} is set but invalid"))
282}
283
284fn oop_publication_config_from(
285 opts: &OopRunOptions,
286 rendered: Option<&RenderedGearConfig>,
287) -> Result<AppConfig> {
288 let mut config = AppConfig::load_or_default(opts.config_path.as_ref())?;
289 config.apply_cli_overrides(opts.verbose);
290 Ok(effective_oop_config(
291 &config,
292 opts.config_gear_name(),
293 rendered,
294 ))
295}
296
297/// Merges logging configurations: master as base, local as override (by key).
298///
299/// Each key in the logging `HashMap` (e.g., "default", "calculator", "sqlx")
300/// is overridden by local if present.
301fn merge_logging_configs(master: Option<&LoggingConfig>, local: &LoggingConfig) -> LoggingConfig {
302 master
303 .cloned()
304 .unwrap_or_default()
305 .into_iter()
306 .chain(local.clone())
307 .collect()
308}
309
310/// Builds `DbOptions` by merging rendered config from master with local config.
311///
312/// Uses Figment to merge configurations and `DbManager` to handle the actual
313/// database connection setup with field-by-field merge logic.
314fn build_merged_db_options(
315 home_dir: &Path,
316 gear_name: &str,
317 rendered_db: Option<&RenderedDbConfig>,
318 local_config: &AppConfig,
319) -> Result<DbOptions> {
320 // Check if we have any database configuration
321 let has_rendered_db = rendered_db.is_some_and(|db| db.gear.is_some() || db.global.is_some());
322 let has_local_db = local_config.database.is_some()
323 || local_config
324 .gears
325 .values()
326 .any(|m| m.get("database").is_some());
327
328 if !has_rendered_db && !has_local_db {
329 debug!(
330 gear = %gear_name,
331 "No database config available"
332 );
333 return Ok(DbOptions::None);
334 }
335
336 // Build a merged configuration for DbManager:
337 // 1. Start with rendered config from master (global servers + gear db)
338 // 2. Overlay local config (local can override any field)
339
340 let mut merged_config = serde_json::Map::new();
341
342 // Step 1: Add rendered database config from master as base
343 if let Some(rendered) = rendered_db {
344 // Add global servers from master
345 if let Some(ref global) = rendered.global {
346 let global_json = serde_json::to_value(global)
347 .context("Failed to serialize rendered global db config")?;
348 merged_config.insert("database".to_owned(), global_json);
349 }
350
351 // Add gear's database config from master
352 if let Some(ref gear_db) = rendered.gear {
353 let gear_db_json = serde_json::to_value(gear_db)
354 .context("Failed to serialize rendered gear db config")?;
355
356 let mut gears = serde_json::Map::new();
357 let mut gear_entry = serde_json::Map::new();
358 gear_entry.insert("database".to_owned(), gear_db_json);
359 gears.insert(gear_name.to_owned(), serde_json::Value::Object(gear_entry));
360 merged_config.insert("gears".to_owned(), serde_json::Value::Object(gears));
361 }
362 }
363
364 // Step 2: Overlay local config (local overrides master)
365 // Local global database config
366 if let Some(ref local_db) = local_config.database {
367 let local_db_json =
368 serde_json::to_value(local_db).context("Failed to serialize local global db config")?;
369
370 // Merge with existing or replace
371 if let Some(existing) = merged_config.get_mut("database") {
372 merge_json_objects(existing, &local_db_json);
373 } else {
374 merged_config.insert("database".to_owned(), local_db_json);
375 }
376 }
377
378 // Local gear database config: the unit's own gear, and every gear it co-hosts
379 // that names a database in the local config (the master renders only its own).
380 for (local_gear_name, local_gear) in &local_config.gears {
381 let Some(local_gear_db) = local_gear.get("database") else {
382 continue;
383 };
384 let gears = merged_config
385 .entry("gears".to_owned())
386 .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
387
388 if let Some(gears_obj) = gears.as_object_mut() {
389 let gear_entry = gears_obj
390 .entry(local_gear_name.clone())
391 .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
392
393 if let Some(gear_obj) = gear_entry.as_object_mut() {
394 if let Some(existing_db) = gear_obj.get_mut("database") {
395 merge_json_objects(existing_db, local_gear_db);
396 } else {
397 gear_obj.insert("database".to_owned(), local_gear_db.clone());
398 }
399 }
400 }
401 }
402
403 debug!(
404 gear = %gear_name,
405 has_rendered = %rendered_db.is_some(),
406 has_local_global = %local_config.database.is_some(),
407 "Building DbManager with merged config"
408 );
409
410 // Create DbManager from merged Figment
411 let figment = Figment::new().merge(Serialized::defaults(serde_json::Value::Object(
412 merged_config,
413 )));
414 let db_manager = Arc::new(
415 toolkit_db::DbManager::from_figment(figment, home_dir.to_path_buf())
416 .context("Failed to create DbManager from merged config")?,
417 );
418
419 Ok(DbOptions::Manager(db_manager))
420}
421
422/// Recursively merges source JSON object into target.
423/// Source values override target values for matching keys.
424fn merge_json_objects(target: &mut serde_json::Value, source: &serde_json::Value) {
425 if let (Some(target_obj), Some(source_obj)) = (target.as_object_mut(), source.as_object()) {
426 for (key, value) in source_obj {
427 if let Some(target_value) = target_obj.get_mut(key) {
428 // Recursively merge objects, otherwise replace
429 if target_value.is_object() && value.is_object() {
430 merge_json_objects(target_value, value);
431 } else {
432 *target_value = value.clone();
433 }
434 } else {
435 target_obj.insert(key.clone(), value.clone());
436 }
437 }
438 } else {
439 // If target is not an object, replace entirely
440 *target = source.clone();
441 }
442}
443
444/// Run an out-of-process gear with the given options
445///
446/// This function:
447/// 1. Creates a root `CancellationToken` for the process
448/// 2. Hooks OS signals (SIGTERM, SIGINT, Ctrl+C) to trigger cancellation
449/// 3. Loads configuration and initializes logging
450/// 4. Creates a lazy `DirectoryService` client (connects on first use, not at
451/// bootstrap — `cpt-cf-adr-eventual-readiness`)
452/// 5. Registers the gear instance (background presence loop, with backoff)
453/// 6. Starts a background heartbeat loop (using a child token)
454/// 7. Runs the gear lifecycle with `ShutdownOptions::Token`
455/// 8. Deregisters from `DirectoryService` on shutdown
456///
457/// ## Shutdown Model
458///
459/// A single root cancellation token drives shutdown for the entire process.
460/// OS signals are hooked at this bootstrap level (not via `ShutdownOptions::Signals`).
461/// The heartbeat loop and gear runtime both observe this token tree.
462///
463/// # Arguments
464///
465/// * `opts` - Bootstrap configuration options
466///
467/// # Returns
468///
469/// * `Ok(())` - If the gear lifecycle completed successfully
470/// * `Err(e)` - If any step failed
471///
472/// # Example
473///
474/// ```rust,no_run
475/// use toolkit::bootstrap::oop::{OopRunOptions, run_oop_with_options};
476///
477/// #[tokio::main]
478/// async fn main() -> anyhow::Result<()> {
479/// let opts = OopRunOptions {
480/// gear_name: "file-parser".to_string(),
481/// config_gear_name: None,
482/// instance_id: None,
483/// directory_endpoint: "http://127.0.0.1:50051".to_string(),
484/// config_path: None,
485/// verbose: 1,
486/// print_config: false,
487/// heartbeat_interval_secs: 5,
488/// version: None,
489/// };
490///
491/// run_oop_with_options(opts).await
492/// }
493/// ```
494///
495/// # Errors
496/// Returns an error if the `OoP` gear fails to start or run.
497#[tracing::instrument(
498 level = "info",
499 name = "oop_bootstrap",
500 skip(opts),
501 fields(
502 gear = %opts.gear_name,
503 directory = %opts.directory_endpoint
504 )
505)]
506pub async fn run_oop_with_options(opts: OopRunOptions) -> Result<()> {
507 // Install the rustls crypto provider FIRST — before any TLS/network setup,
508 // mirroring `init_procedure` so OoP gears run the same crypto startup
509 // checks. Process-wide and idempotent.
510 super::init_crypto_provider()?;
511
512 // Generate instance ID if not provided
513 let instance_id = opts.instance_id.unwrap_or_else(Uuid::new_v4);
514
515 // Create root cancellation token for the entire process.
516 // This token drives shutdown for the gear runtime and all background tasks.
517 let cancel = CancellationToken::new();
518
519 // Hook OS signals to the root token at bootstrap level.
520 // This replaces the use of ShutdownOptions::Signals inside the runtime.
521 let cancel_for_signals = cancel.clone();
522 tokio::spawn(async move {
523 match shutdown::wait_for_shutdown().await {
524 Ok(()) => {
525 info!(target: "", "------------------");
526 info!("shutdown: signal received in OoP bootstrap");
527 }
528 Err(e) => {
529 warn!(
530 error = %e,
531 "shutdown: primary waiter failed in OoP bootstrap, falling back to ctrl_c()"
532 );
533 _ = tokio::signal::ctrl_c().await;
534 }
535 }
536 cancel_for_signals.cancel();
537 });
538
539 // Prepare CLI args for AppConfig loading
540 let args = CliArgs {
541 config: opts
542 .config_path
543 .as_ref()
544 .map(|p| p.to_string_lossy().to_string()),
545 print_config: opts.print_config,
546 verbose: opts.verbose,
547 mock: false,
548 };
549
550 // Load configuration
551 let mut config = AppConfig::load_or_default(opts.config_path.as_ref())?;
552 config.apply_cli_overrides(args.verbose);
553
554 // Read rendered gear config from master host via env var BEFORE logging init
555 // so we can use the tracing config from master for OTEL. Present but invalid
556 // fails startup, as it fails the deployment publication job.
557 let rendered_config = rendered_config_from_env()?;
558
559 // Build final config by merging:
560 // 1. Rendered config from master host (base)
561 // 2. Local config file (override)
562 // This also merges logging configuration for proper initialization
563 let (final_config, merged_logging, db_options) =
564 // The *config* key, not the registration name: a role changes what this
565 // process registers as and not what section it reads. Conflating them
566 // filed the master's rendered blob under a key the gear never looks up.
567 build_oop_config_and_db(&config, opts.config_gear_name(), rendered_config.as_ref())?;
568
569 // Use OpenTelemetry config from rendered (master) config only.
570 // OoP gears do not fall back to local config for telemetry — if the master
571 // does not provide an opentelemetry section, telemetry is skipped entirely.
572 #[cfg(feature = "otel")]
573 let otel_cfg = rendered_config
574 .as_ref()
575 .and_then(|rc| rc.opentelemetry.as_ref());
576
577 // Initialize OTEL tracing layer (if tracing is enabled)
578 #[cfg(feature = "otel")]
579 let otel_layer = otel_cfg
580 .filter(|cfg| cfg.tracing.enabled)
581 .map(crate::telemetry::init_tracing)
582 .transpose()?;
583 #[cfg(not(feature = "otel"))]
584 let otel_layer = None;
585
586 // Initialize OpenTelemetry metrics provider (if configured and enabled).
587 // Store error to log after logging is initialized.
588 #[cfg(feature = "otel")]
589 let metrics_init_error = otel_cfg
590 .filter(|cfg| cfg.metrics.enabled)
591 .and_then(|cfg| crate::telemetry::init::init_metrics_provider(cfg).err());
592
593 // Initialize logging with MERGED config (master base + local override)
594 // Trace-id injection follows the same rule as the other telemetry
595 // settings: it comes from the master's rendered config, never the local one.
596 //
597 // `is_none_or`, not `is_some_and`: an absent `opentelemetry` section resolves
598 // the splice ON, matching the in-process default (`bootstrap::run` over
599 // `OpenTelemetryConfig::default()` -> `unwrap_or(true)`). `is_some_and` would
600 // silently disable it for every OoP gear with no section.
601 #[cfg(feature = "otel")]
602 let inject_trace_ids =
603 otel_cfg.is_none_or(crate::telemetry::OpenTelemetryConfig::inject_trace_ids_into_logs);
604 #[cfg(not(feature = "otel"))]
605 let inject_trace_ids = false;
606
607 init_logging_unified(
608 &merged_logging,
609 &config.server.home_dir,
610 otel_layer,
611 inject_trace_ids,
612 );
613
614 // Now that logging is available, report deferred metrics init error
615 #[cfg(feature = "otel")]
616 if let Some(e) = metrics_init_error {
617 tracing::error!(error = %e, "OpenTelemetry metrics not initialized (OoP)");
618 }
619
620 // Register custom panic hook to reroute panic backtrace into tracing.
621 init_panic_tracing();
622
623 // Now we can log - report what we received from master
624 if let Some(ref rc) = rendered_config {
625 info!(
626 env_var = TOOLKIT_MODULE_CONFIG_ENV,
627 has_database = rc.database.is_some(),
628 has_config = !rc.config.is_null(),
629 has_logging = rc.logging.is_some(),
630 has_opentelemetry = rc.opentelemetry.is_some(),
631 "Received rendered config from master host"
632 );
633 } else {
634 debug!(
635 env_var = TOOLKIT_MODULE_CONFIG_ENV,
636 "No rendered config from master host, using local config only"
637 );
638 }
639
640 info!(
641 gear = %opts.gear_name,
642 instance_id = %instance_id,
643 directory_endpoint = %opts.directory_endpoint,
644 "OoP gear bootstrap starting"
645 );
646
647 // Print config and exit if requested
648 if opts.print_config {
649 print_config(&config);
650 return Ok(());
651 }
652
653 // Create the DirectoryService client on a LAZY channel. Per
654 // `cpt-cf-adr-eventual-readiness`, an OoP gear must start even when the
655 // DirectoryService is not yet reachable; blocking or crashing on it at
656 // bootstrap would make it a hard startup dependency (the SPOF the ADR
657 // rejects). A lazy channel performs no eager connection: it fails fast only
658 // on a malformed endpoint and defers the connect to the first RPC.
659 //
660 // Recovery from a cold directory differs by lifecycle:
661 // - `oop_http` configured: the presence loop retries registration with
662 // exponential backoff (100ms -> 30s, forever).
663 // - Legacy path (no `oop_http`): only a fixed-interval heartbeat runs, with
664 // no registration retry — it relies on an external orchestrator.
665 //
666 // When a platform-plane credential is configured, it is attached (as
667 // `x-toolkit-internal-token`) to outbound system calls via an
668 // InternalAuthInterceptor (`cpt-cf-adr-two-plane-auth`).
669 info!(
670 "Creating directory service client (lazy connect) for {}",
671 opts.directory_endpoint
672 );
673 let internal_auth_cfg = final_config
674 .oop_http
675 .as_ref()
676 .and_then(|h| h.internal_auth.as_ref());
677 let (directory_client, internal_token_provider) =
678 build_directory_client(&opts.directory_endpoint, internal_auth_cfg, &cancel).await?;
679 let directory_api: Arc<dyn DirectoryClient> = Arc::new(directory_client);
680
681 info!("Directory service client ready (will connect on first use)");
682
683 // Capture OoP HTTP config (if any) before moving the config into the provider.
684 let oop_http = final_config.oop_http.clone();
685
686 // Apply configured lifecycle deadlines (absent fields keep framework defaults).
687 let init_deadline = final_config.server.init_deadline();
688 let shutdown_deadline = final_config.server.shutdown_deadline();
689
690 // Build config provider for gears
691 let config_provider = Arc::new(final_config);
692
693 // The DirectoryClient (gRPC client) is injected into the ClientHub so gears can access it.
694 // `oop` is left unset: OoP gears don't spawn other OoP gears.
695 let run_options = RunOptions::new(
696 config_provider,
697 db_options,
698 ShutdownOptions::Token(cancel.clone()),
699 instance_id,
700 )
701 .with_clients(vec![ClientRegistration::new::<dyn DirectoryClient>(
702 Arc::clone(&directory_api),
703 )])
704 .with_internal_token_provider(internal_token_provider)
705 .with_init_deadline(init_deadline)
706 .with_shutdown_deadline(shutdown_deadline);
707
708 // When `oop_http` is configured, run the HTTP-serving lifecycle:
709 // Axum server + probes + directory presence (registration + heartbeat +
710 // self-heal, owned by `presence_loop`) + dependency resolution + drain.
711 // Otherwise fall back to the legacy gRPC-only lifecycle.
712 let result = if let Some(http_cfg) = oop_http {
713 info!("Starting OoP HTTP-serving lifecycle");
714 let serve = build_oop_serve_options(
715 &http_cfg,
716 &opts.gear_name,
717 instance_id,
718 opts.version.clone(),
719 Duration::from_secs(opts.heartbeat_interval_secs),
720 Arc::clone(&directory_api),
721 )
722 .await?;
723 run_oop_serving(run_options, serve).await
724 } else {
725 info!("Starting gear lifecycle (legacy gRPC-only)");
726 // Legacy path: presence is not self-managed by an HTTP serve lifecycle,
727 // so run a standalone heartbeat on a child token. (A no-op unless the
728 // instance is registered by an external orchestrator.)
729 let heartbeat_directory = Arc::clone(&directory_api);
730 let heartbeat_gear = opts.gear_name.clone();
731 let heartbeat_instance_id_str = instance_id.to_string();
732 let heartbeat_interval = Duration::from_secs(opts.heartbeat_interval_secs.max(1));
733 let heartbeat_cancel = cancel.child_token();
734 tokio::spawn(async move {
735 info!(interval_secs = ?heartbeat_interval, "Starting legacy heartbeat loop");
736 loop {
737 tokio::select! {
738 () = heartbeat_cancel.cancelled() => {
739 info!("Heartbeat loop stopping due to cancellation");
740 break;
741 }
742 () = sleep(heartbeat_interval) => {
743 if let Err(e) = heartbeat_directory
744 .send_heartbeat(&heartbeat_gear, &heartbeat_instance_id_str)
745 .await
746 {
747 warn!(error = %e, "Failed to send heartbeat, will retry");
748 }
749 }
750 }
751 }
752 });
753 run(run_options).await
754 };
755
756 if let Err(ref e) = result {
757 error!(error = %e, "Gear runtime failed");
758 } else {
759 info!("Gear runtime completed successfully");
760 }
761
762 // Graceful shutdown - flush remaining telemetry. An OoP gear is a separate
763 // OS process owning its own global providers, so the in-process host's
764 // flush in `bootstrap::run` does not cover it.
765 #[cfg(feature = "otel")]
766 super::telemetry::tracing_shutdown().await;
767
768 result
769}
770
771/// Build [`OopServeOptions`] from configuration.
772///
773/// The tenant-plane `BearerAuthenticator` injection point is left unset here;
774/// the app/gear binary supplies that adapter when it needs the tenant-plane
775/// middleware installed. The platform-plane authenticator is constructed from
776/// `oop_http.internal_auth` when the `k8s-auth` feature is enabled.
777async fn build_oop_serve_options(
778 cfg: &super::config::OopHttpConfig,
779 gear_name: &str,
780 instance_id: Uuid,
781 version: Option<String>,
782 heartbeat_interval: Duration,
783 directory: Arc<dyn DirectoryClient>,
784) -> Result<OopServeOptions> {
785 let listen_addr: std::net::SocketAddr = cfg
786 .listen_addr
787 .parse()
788 .with_context(|| format!("invalid oop_http.listen_addr: {}", cfg.listen_addr))?;
789
790 let probe_bind_addr = cfg
791 .probe_bind_addr
792 .as_deref()
793 .map(|s| {
794 s.parse::<std::net::SocketAddr>()
795 .with_context(|| format!("invalid oop_http.probe_bind_addr: {s}"))
796 })
797 .transpose()?;
798
799 let advertise_uri = cfg
800 .advertise_uri
801 .clone()
802 .unwrap_or_else(|| default_advertise_uri(listen_addr));
803
804 // Fail fast on a malformed or unreachable advertise_uri rather than only
805 // when the directory rejects the registration — the same late-failure the
806 // label validation below avoids.
807 validate_advertise_uri(&advertise_uri, cfg.allow_loopback_advertise)?;
808 log_auth_disabled_when_routable(cfg.auth_disabled, &advertise_uri);
809
810 // Fail fast on a mis-configured label (bad charset, over-long, too many)
811 // at start-up, using the same shared rules the directory enforces. Without
812 // this the process would come up, attempt to register, and only then be
813 // permanently rejected by the directory — a confusing late failure for what
814 // is a static configuration error. Checked before authenticator init so a
815 // static config error is reported without any async backend setup.
816 cf_system_sdks::directory::validate_labels(&cfg.labels).with_context(|| {
817 "invalid oop_http.labels: label keys/values must be <=63 chars, <=64 entries, and use \
818 only ASCII alphanumerics plus '-', '_', '.' (starting and ending alphanumeric)"
819 })?;
820
821 let internal_authenticator = build_internal_authenticator(cfg.internal_auth.as_ref()).await?;
822
823 Ok(OopServeOptions {
824 gear_name: gear_name.to_owned(),
825 instance_id: instance_id.to_string(),
826 version,
827 advertise_uri,
828 listen_addr,
829 probe_bind_addr,
830 drain_timeout: Duration::from_secs(cfg.drain_timeout_secs),
831 heartbeat_interval,
832 healthcheck_timeout: Duration::from_millis(cfg.healthcheck_timeout_ms),
833 directory,
834 bearer_authenticator: None,
835 internal_authenticator,
836 auth_disabled: cfg.auth_disabled,
837 labels: cfg.labels.clone(),
838 })
839}
840
841/// Construct the inbound platform-plane authenticator from configuration.
842///
843/// The `shared_secret` provider is built here directly (no external backend).
844/// The `kube` provider is built (with the default positive/negative
845/// validation cache) by the single shared
846/// `toolkit_k8s_auth::build_cached_k8s_authenticator` helper also used by
847/// `grpc-hub`, so the two never drift on what `provider: kube` means or how
848/// it is cached. The `kube` provider requires the `k8s-auth` feature; without
849/// it, `provider: kube` is an error rather than a silent enforcement
850/// downgrade, as is any other unrecognized provider value. `Ok(None)` is
851/// returned only when no `internal_auth` is configured at all (Profile 1).
852#[cfg_attr(not(feature = "k8s-auth"), allow(clippy::unused_async))]
853async fn build_internal_authenticator(
854 cfg: Option<&toolkit_security::InternalAuthConfig>,
855) -> Result<Option<toolkit_security::DynInternalAuthenticator>> {
856 let Some(cfg) = cfg else {
857 return Ok(None);
858 };
859
860 // Dependency-light providers (shared-secret) build directly here. An
861 // unusable secret is an error rather than a fallthrough: dropping to the
862 // kube branch below would report the wrong problem entirely.
863 match cfg.build_authenticator()? {
864 toolkit_security::BuiltAuthenticator::Built(authenticator) => {
865 info!("Initializing shared-secret platform-plane authenticator");
866 return Ok(Some(authenticator));
867 }
868 toolkit_security::BuiltAuthenticator::RequiresExternalBackend => {}
869 }
870
871 #[cfg(feature = "k8s-auth")]
872 {
873 if cfg.is_kube() {
874 info!("Initializing Kubernetes TokenReview platform-plane authenticator");
875 let audiences = cfg.kube_audiences().unwrap_or_default().to_vec();
876 let authenticator = toolkit_k8s_auth::build_cached_k8s_authenticator(
877 audiences,
878 Some(toolkit_security::DEFAULT_TOKEN_REVIEW_CACHE_TTL),
879 None,
880 )
881 .await
882 .context("failed to initialize Kubernetes TokenReview authenticator")?;
883 return Ok(Some(authenticator));
884 }
885 }
886 #[cfg(not(feature = "k8s-auth"))]
887 {
888 if cfg.is_kube() {
889 anyhow::bail!("oop_http.internal_auth provider=kube requires the `k8s-auth` feature");
890 }
891 }
892
893 anyhow::bail!(
894 "internal_auth is configured but no authenticator could be built for the selected provider"
895 )
896}
897
898/// Build the `OoP` gear's `DirectoryService` client on a **lazy** channel, plus
899/// the outbound
900/// [`InternalTokenProvider`](toolkit_contract::runtime::config::InternalTokenProvider)
901/// when a platform-plane credential is configured (`None` => no credential).
902///
903/// The lazy channel performs no eager connection, so this succeeds even when
904/// `directory_endpoint` is unreachable (`cpt-cf-adr-eventual-readiness`).
905/// Interceptor and provider come from one credential source (see
906/// [`build_platform_credentials`]) so they can't diverge after a rotation.
907///
908/// # Errors
909/// Only if the endpoint is malformed or a configured credential source fails to
910/// initialise — never for an unreachable directory. The endpoint is validated
911/// before any credential work, so a malformed endpoint is reported ahead of a
912/// credential-source failure.
913async fn build_directory_client(
914 directory_endpoint: &str,
915 internal_auth_cfg: Option<&toolkit_security::InternalAuthConfig>,
916 cancel: &CancellationToken,
917) -> Result<(
918 DirectoryGrpcClient,
919 Option<toolkit_contract::runtime::config::InternalTokenProvider>,
920)> {
921 // Validate the endpoint up front — before any credential-source work — so a
922 // malformed endpoint is reported ahead of a credential failure. The lazy
923 // client performs no connection, only URI validation; it is reused as-is on
924 // the no-credential path.
925 let client = DirectoryGrpcClient::connect_lazy(directory_endpoint)?;
926
927 let Some(cfg) = internal_auth_cfg else {
928 return Ok((client, None));
929 };
930
931 let (interceptor, provider) = build_platform_credentials(cfg, cancel).await?;
932 // Rebuild with the interceptor attached (it must be set at construction);
933 // the endpoint was already validated above.
934 let client =
935 DirectoryGrpcClient::connect_lazy_with_interceptor(directory_endpoint, interceptor)?;
936 Ok((client, provider))
937}
938
939/// Build the platform-plane credential material from config: the **outbound**
940/// gRPC [`InternalAuthInterceptor`] (for `DirectoryService` calls) and the
941/// transport-agnostic
942/// [`InternalTokenProvider`](toolkit_contract::runtime::config::InternalTokenProvider)
943/// that `#[toolkit::provides]` clients attach as `X-ToolKit-Internal-Token` on
944/// platform-plane methods (`cpt-cf-adr-two-plane-auth`).
945///
946/// Both derive from ONE credential source so they never disagree after a
947/// rotation:
948/// - `shared_secret` → a static token for both.
949/// - `kube` with `token_path` → one [`ServiceAccountTokenReader`] drives both;
950/// its "no token yet" maps to [`CredentialState::Unavailable`] so an attach
951/// site warns rather than silently sending nothing.
952/// - `kube` without `token_path` → inbound-only: disabled interceptor + `None`
953/// provider (warned).
954///
955/// The `match` is exhaustive so a future variant fails to compile here rather
956/// than silently downgrading to no outbound credential.
957pub(super) async fn build_platform_credentials(
958 cfg: &toolkit_security::InternalAuthConfig,
959 cancel: &CancellationToken,
960) -> Result<(
961 toolkit_transport_grpc::InternalAuthInterceptor,
962 Option<toolkit_contract::runtime::config::InternalTokenProvider>,
963)> {
964 use secrecy::SecretString;
965 use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
966 use toolkit_security::InternalAuthConfig;
967 use toolkit_transport_grpc::{
968 DEFAULT_REFRESH_INTERVAL, InternalAuthInterceptor, ServiceAccountTokenReader,
969 };
970
971 match cfg {
972 InternalAuthConfig::SharedSecret { secret, .. } => {
973 let token = SecretString::from(secret.clone());
974 Ok((
975 InternalAuthInterceptor::from_token(token.clone()),
976 Some(InternalTokenProvider::from_token(token)),
977 ))
978 }
979 InternalAuthConfig::Kube {
980 token_path: Some(path),
981 ..
982 } => {
983 let reader = ServiceAccountTokenReader::with_cancellation(
984 path,
985 DEFAULT_REFRESH_INTERVAL,
986 cancel.child_token(),
987 )
988 .await
989 .context("failed to read projected service-account token for outbound credential")?;
990 let interceptor = reader.interceptor();
991 // The reader yields `None` while the projected file is empty or the
992 // refresh has not populated it; surface that as `Unavailable` (warn)
993 // rather than `NotConfigured` (silent).
994 let token_fn = reader.token_provider();
995 let provider = InternalTokenProvider::new(move || match token_fn() {
996 Some(token) => CredentialState::Available(token),
997 None => CredentialState::Unavailable(
998 "projected service-account token is currently unavailable \
999 (file empty or not yet read)"
1000 .into(),
1001 ),
1002 });
1003 Ok((interceptor, Some(provider)))
1004 }
1005 InternalAuthConfig::Kube {
1006 token_path: None, ..
1007 } => {
1008 warn!(
1009 "oop_http.internal_auth: provider=kube without token_path - this participant \
1010 validates inbound platform tokens but will attach NO outbound credential"
1011 );
1012 Ok((InternalAuthInterceptor::disabled(), None))
1013 }
1014 }
1015}
1016
1017/// Derive a default advertise URI from the bind address. Unspecified hosts
1018/// (`0.0.0.0` / `[::]`) are rewritten to loopback, and every IPv6 host is
1019/// enclosed in brackets so the resulting URI is valid when registered as a
1020/// REST endpoint.
1021fn default_advertise_uri(listen_addr: std::net::SocketAddr) -> String {
1022 let host = match listen_addr {
1023 std::net::SocketAddr::V4(addr) if addr.ip().is_unspecified() => "127.0.0.1".to_owned(),
1024 std::net::SocketAddr::V4(addr) => addr.ip().to_string(),
1025 std::net::SocketAddr::V6(addr) if addr.ip().is_unspecified() => "[::1]".to_owned(),
1026 std::net::SocketAddr::V6(addr) => format!("[{}]", addr.ip()),
1027 };
1028 format!("http://{host}:{}", listen_addr.port())
1029}
1030
1031/// Reject a malformed or unreachable `advertise_uri` at start-up (fail fast).
1032///
1033/// Checks shape (parseable `http`/`https` URL, non-empty host, no userinfo) and,
1034/// unless `allow_loopback`, rejects a loopback / unspecified host - a
1035/// registered-but-unreachable instance in multi-host Profile 2 / Profile 3
1036/// (`cpt-cf-adr-instance-addressable-discovery` section 5). The default derives
1037/// loopback from an unspecified bind, so this also covers an *unset* value. The
1038/// directory enforces its full endpoint ruleset server-side.
1039fn validate_advertise_uri(uri: &str, allow_loopback: bool) -> Result<()> {
1040 let parsed = url::Url::parse(uri)
1041 .with_context(|| format!("invalid oop_http.advertise_uri: not a valid URL: {uri}"))?;
1042 if !matches!(parsed.scheme(), "http" | "https") {
1043 anyhow::bail!(
1044 "invalid oop_http.advertise_uri: scheme must be http or https (got '{}')",
1045 parsed.scheme()
1046 );
1047 }
1048 if parsed.host_str().is_none_or(str::is_empty) {
1049 anyhow::bail!("invalid oop_http.advertise_uri: missing host: {uri}");
1050 }
1051 if !parsed.username().is_empty() || parsed.password().is_some() {
1052 anyhow::bail!("invalid oop_http.advertise_uri: must not contain userinfo: {uri}");
1053 }
1054 if !allow_loopback && is_loopback_host(&parsed) {
1055 anyhow::bail!(
1056 "invalid oop_http.advertise_uri: '{uri}' is a loopback/unspecified address, which is \
1057 unreachable by other gears in multi-host Profile 2 / Profile 3 (a registered-but-\
1058 unreachable instance). Set oop_http.advertise_uri to a routable host, or set \
1059 oop_http.allow_loopback_advertise = true for single-host / local-dev."
1060 );
1061 }
1062 Ok(())
1063}
1064
1065/// Whether `uri`'s host is loopback / unspecified, i.e. unreachable from other hosts.
1066fn is_loopback_host(uri: &url::Url) -> bool {
1067 match uri.host() {
1068 Some(url::Host::Ipv4(ip)) => ip.is_loopback() || ip.is_unspecified(),
1069 Some(url::Host::Ipv6(ip)) => ip.is_loopback() || ip.is_unspecified(),
1070 Some(url::Host::Domain(d)) => d.trim_end_matches('.').eq_ignore_ascii_case("localhost"),
1071 None => false,
1072 }
1073}
1074
1075/// Log an `error!` when the development-only `auth_disabled` is set on a worker advertised
1076/// at a routable address: other hosts reach it through the directory, and every tenant's
1077/// request then runs as the default tenant.
1078fn log_auth_disabled_when_routable(auth_disabled: bool, advertise_uri: &str) {
1079 if !auth_disabled {
1080 return;
1081 }
1082 let routable = url::Url::parse(advertise_uri).is_ok_and(|uri| !is_loopback_host(&uri));
1083 if routable {
1084 tracing::error!(
1085 advertise_uri,
1086 "oop_http.auth_disabled is set on a worker advertised at a routable address: every \
1087 tenant request reaching it runs as the default tenant. Development only; unset it \
1088 or advertise a loopback address."
1089 );
1090 }
1091}
1092
1093#[allow(unknown_lints, de1301_no_print_macros)] // direct stdout config print before exit
1094fn print_config(config: &AppConfig) {
1095 match config.to_yaml() {
1096 Ok(yaml) => {
1097 println!("{yaml}");
1098 }
1099 Err(e) => {
1100 eprintln!("Failed to render config as YAML: {e}");
1101 }
1102 }
1103}
1104
1105#[cfg(test)]
1106#[cfg_attr(coverage_nightly, coverage(off))]
1107#[path = "oop_tests.rs"]
1108mod tests;