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