Skip to main content

toolkit/bootstrap/
run.rs

1use super::config::{get_gear_runtime_config, render_gear_config_for_oop};
2use super::host::{init_logging_unified, init_panic_tracing, normalize_path};
3#[cfg(feature = "otel")]
4use super::telemetry::tracing_shutdown;
5use super::{AppConfig, RuntimeKind};
6use crate::backends::LocalProcessBackend;
7use crate::runtime::{
8    DbOptions, OopGearSpawnConfig, OopSpawnOptions, RunOptions, ShutdownOptions, run, shutdown,
9};
10use anyhow::Result;
11use figment::Figment;
12use figment::providers::Serialized;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tokio_util::sync::CancellationToken;
16
17/// Spawn a signal handler task that cancels the provided token on SIGTERM/SIGINT.
18///
19/// This helper consolidates signal handling logic used by both `run_server` and `run_migrate`.
20/// The `context` parameter customizes log messages for better diagnostics.
21fn spawn_signal_handler(cancel: CancellationToken, context: &str) {
22    let context_owned = context.to_owned();
23    tokio::spawn(async move {
24        match shutdown::wait_for_shutdown().await {
25            Ok(()) => {
26                tracing::info!(target: "", "------------------");
27                tracing::info!("{}: shutdown signal received", context_owned);
28            }
29            Err(e) => {
30                tracing::warn!(
31                    error = %e,
32                    "{}: signal handler failed, falling back to ctrl_c()",
33                    context_owned
34                );
35                _ = tokio::signal::ctrl_c().await;
36            }
37        }
38        cancel.cancel();
39    });
40}
41
42/// # Errors
43///
44/// Returns an error if:
45/// - There was a critical error during initialization of the gears
46/// - Problems with the database or third-party services
47/// - An issue during runtime or shutdown
48///
49/// The TLS crypto provider is installed automatically as the first step of
50/// [`init_procedure`] (idempotent), so callers do not need to invoke
51/// [`super::init_crypto_provider`] explicitly.
52pub async fn run_server(config: AppConfig) -> Result<()> {
53    init_procedure(&config).map_err(|e| {
54        tracing::error!(error = %e, "Initialization failed");
55        e
56    })?;
57    tracing::info!("Initializing gears...");
58
59    // Generate process-level instance ID once at startup.
60    // This is shared by all gears in this process.
61    let instance_id = uuid::Uuid::new_v4();
62    tracing::info!(instance_id = %instance_id, "Generated process instance ID");
63
64    // Create root cancellation token for the entire process.
65    // This token drives shutdown for the gear runtime and all lifecycle/stateful gears.
66    let cancel = CancellationToken::new();
67
68    // Hook OS signals to the root token at the host level.
69    // This replaces the use of ShutdownOptions::Signals inside the runtime.
70    spawn_signal_handler(cancel.clone(), "server");
71
72    // Build config provider and resolve database options
73    let db_options = resolve_db_options(&config)?;
74
75    // Create OoP backend with cancellation token - it will auto-shutdown all processes on cancel
76    let oop_backend = LocalProcessBackend::new(cancel.clone());
77
78    // Build OoP spawn configuration
79    let oop_options = build_oop_spawn_options(&config, oop_backend)?;
80
81    // Remote platform-plane calls carry `X-ToolKit-Internal-Token` from
82    // `oop_http.internal_auth` (cpt-cf-adr-two-plane-auth); without it they fail.
83    // Co-hosted dependencies use local ClientHub objects and need no credential.
84    let internal_token_provider = match config
85        .oop_http
86        .as_ref()
87        .and_then(|http| http.internal_auth.as_ref())
88    {
89        Some(internal_auth) => {
90            super::oop::build_platform_credentials(internal_auth, &cancel)
91                .await?
92                .1
93        }
94        None => None,
95    };
96
97    // Apply configured lifecycle deadlines (absent fields keep framework defaults).
98    let init_deadline = config.server.init_deadline();
99    let shutdown_deadline = config.server.shutdown_deadline();
100
101    // Run the ToolKit runtime with the root cancellation token.
102    // Shutdown is driven by the signal handler spawned above, not by ShutdownOptions::Signals.
103    // OoP gears are spawned after parent publication, application startup and
104    // REST provider registration, so the parent's complete API is available.
105    let run_options = RunOptions::new(
106        Arc::new(config),
107        db_options,
108        ShutdownOptions::Token(cancel.clone()),
109        instance_id,
110    )
111    .with_oop(oop_options)
112    .with_internal_token_provider(internal_token_provider)
113    .with_init_deadline(init_deadline)
114    .with_shutdown_deadline(shutdown_deadline);
115
116    let result = run(run_options).await;
117
118    // Graceful shutdown - flush remaining telemetry
119    #[cfg(feature = "otel")]
120    tracing_shutdown().await;
121
122    result
123}
124
125/// Run database migrations and exit.
126///
127/// This mode is designed for cloud deployment workflows where database
128/// migrations need to run as a separate step before starting the application.
129///
130/// Phases executed:
131/// - Pre-init (wire runtime internals)
132/// - DB migration (run all pending migrations)
133///
134/// The process exits after migrations complete. Any errors are reported
135/// and propagated as non-zero exit codes.
136///
137/// # Errors
138///
139/// Returns an error if:
140/// - No database configuration is found
141/// - Gear discovery fails
142/// - Pre-init phase fails
143/// - Migration phase fails
144///
145/// The TLS crypto provider is installed automatically as the first step of
146/// [`init_procedure`] (idempotent), so callers do not need to invoke
147/// [`super::init_crypto_provider`] explicitly.
148pub async fn run_migrate(config: AppConfig) -> Result<()> {
149    init_procedure(&config).map_err(|e| {
150        tracing::error!(error = %e, "Initialization failed");
151        e
152    })?;
153    tracing::info!("Starting migration mode...");
154
155    // Generate process-level instance ID for this migration run
156    let instance_id = uuid::Uuid::new_v4();
157    tracing::info!(instance_id = %instance_id, "Generated migration instance ID");
158
159    // Create cancellation token and wire it to OS signals
160    let cancel = CancellationToken::new();
161
162    // Hook OS signals to enable graceful cancellation of migrations
163    spawn_signal_handler(cancel.clone(), "migration");
164
165    // Build database options from configuration
166    let db_options = resolve_db_options(&config)?;
167
168    // Verify we have database configuration
169    if matches!(db_options, DbOptions::None) {
170        anyhow::bail!("Cannot run migrations: no database configuration found");
171    }
172
173    // Discover and build the gear registry
174    let registry = crate::registry::GearRegistry::discover_and_build()?;
175    tracing::info!(
176        gear_count = registry.gears().len(),
177        "Discovered gears for migration"
178    );
179
180    // Create the host runtime
181    let host = crate::runtime::HostRuntime::new(
182        registry,
183        Arc::new(config),
184        db_options,
185        Arc::new(crate::client_hub::ClientHub::new()),
186        cancel,
187        instance_id,
188        None, // No OoP spawning during migration
189    );
190
191    // Run only the migration phases (pre-init + DB migration)
192    let result = host.run_migration_phases().await;
193
194    // Graceful shutdown - flush remaining telemetry
195    #[cfg(feature = "otel")]
196    tracing_shutdown().await;
197
198    result?;
199
200    tracing::info!("All migrations completed successfully");
201    Ok(())
202}
203
204/// Options of [`run_publish_gts`].
205#[derive(Debug, Clone)]
206pub struct PublishGtsOptions {
207    /// Base URI of the remote registry, e.g. `https://registry:8443`.
208    pub registry_endpoint: String,
209    /// The overall deadline for every publication; at most
210    /// [`MAX_PUBLICATION_BUDGET`](crate::gts_publication::MAX_PUBLICATION_BUDGET) (10 minutes).
211    pub deadline: std::time::Duration,
212}
213
214/// Publish the GTS manifests of every linked gear to a remote registry and exit:
215/// a deployment step.
216///
217/// No gear runs: no `init`, database, bootstrap or plugin binding. Manifests
218/// come from the effective configuration (file, environment overrides,
219/// defaults), as at application startup. Requests carry the platform
220/// credential of `oop_http.internal_auth`. All publications run concurrently;
221/// see [`crate::gts_publication::deployment`].
222///
223/// # Errors
224/// No platform credential is configured, setup fails (manifest, ownership,
225/// wiring), or any publisher is refused or misses the deadline: the report is
226/// in the error, naming each publisher and its GTS ids.
227pub async fn run_publish_gts(config: AppConfig, options: PublishGtsOptions) -> Result<()> {
228    init_procedure(&config).map_err(|e| {
229        tracing::error!(error = %e, "Initialization failed");
230        e
231    })?;
232    // SIGTERM/SIGINT end the job, reported as cancelled. Dropping this future
233    // cancels too: the guard also ends the credential watcher.
234    let cancel = CancellationToken::new();
235    spawn_signal_handler(cancel.clone(), "publish-gts");
236    let _cancel_on_drop = cancel.clone().drop_guard();
237    let result = publish_gts(&config, &options, &cancel).await;
238
239    // The outcome is logged before the telemetry flush, on every path.
240    match &result {
241        Ok(()) => tracing::info!("GTS publication complete"),
242        Err(e) => tracing::error!(error = format!("{e:#}"), "GTS publication failed"),
243    }
244    #[cfg(feature = "otel")]
245    tracing_shutdown().await;
246    result
247}
248
249/// [`run_publish_gts`] after initialization.
250async fn publish_gts(
251    config: &AppConfig,
252    options: &PublishGtsOptions,
253    cancel: &CancellationToken,
254) -> Result<()> {
255    // Reject an over-long deadline before touching the registry or the credential.
256    crate::gts_publication::check_publication_budget("--timeout", options.deadline)?;
257    // Match startup validation without running gear lifecycle hooks.
258    let registry = crate::registry::GearRegistry::discover_and_build()?;
259    validate_deployment_configuration(&registry, config)?;
260    let internal_auth = platform_credential(config)?;
261    let (_, provider) = super::oop::build_platform_credentials(internal_auth, cancel).await?;
262    let provider = provider.ok_or_else(|| {
263        anyhow::anyhow!("oop_http.internal_auth gives no outbound platform credential")
264    })?;
265    let tuning = toolkit_contract::wiring::ClientTuning::default()
266        .with_internal_token_provider(Some(provider));
267    let descriptors = crate::gts_publication::linked_descriptors();
268    tracing::info!(
269        publishers = descriptors.len(),
270        registry = %options.registry_endpoint,
271        "publishing GTS manifests"
272    );
273    let report = crate::gts_publication::deployment::publish(
274        &descriptors,
275        config,
276        &options.registry_endpoint,
277        &tuning,
278        options.deadline,
279        cancel,
280    )
281    .await?;
282    publication_result(&report)
283}
284
285fn validate_deployment_configuration(
286    registry: &crate::registry::GearRegistry,
287    config: &dyn crate::config::ConfigProvider,
288) -> Result<()> {
289    for entry in registry.gears() {
290        entry.validate_gts_publication_config(config)?;
291    }
292    Ok(())
293}
294
295/// The platform credential `publish-gts` sends: `oop_http.internal_auth`.
296fn platform_credential(config: &AppConfig) -> Result<&toolkit_security::InternalAuthConfig> {
297    config
298        .oop_http
299        .as_ref()
300        .and_then(|http| http.internal_auth.as_ref())
301        .ok_or_else(|| {
302            anyhow::anyhow!(
303                "publish-gts needs a platform credential: configure oop_http.internal_auth"
304            )
305        })
306}
307
308/// The job's result: an error carrying the report unless every publisher succeeded.
309fn publication_result(
310    report: &crate::gts_publication::deployment::GtsDeploymentReport,
311) -> Result<()> {
312    if report.succeeded() {
313        tracing::info!("GTS publication report:\n{report}");
314        Ok(())
315    } else {
316        anyhow::bail!("GTS publication failed:\n{report}")
317    }
318}
319
320fn resolve_db_options(config: &AppConfig) -> Result<DbOptions> {
321    if config.database.is_none() {
322        tracing::warn!("No global database section found; running without databases");
323        return Ok(DbOptions::None);
324    }
325
326    tracing::info!("Using DbManager with Figment-based configuration");
327    let figment = Figment::new().merge(Serialized::defaults(config));
328    let db_manager = Arc::new(toolkit_db::DbManager::from_figment(
329        figment,
330        config.server.home_dir.clone(),
331    )?);
332    Ok(DbOptions::Manager(db_manager))
333}
334
335/// Build `OoP` spawn configuration from `AppConfig`.
336///
337/// This collects all gears with `type=oop` and prepares their spawn configuration.
338/// The actual spawning happens in the `HostRuntime` after parent startup.
339fn build_oop_spawn_options(
340    config: &AppConfig,
341    backend: LocalProcessBackend,
342) -> Result<Option<OopSpawnOptions>> {
343    let home_dir = PathBuf::from(&config.server.home_dir);
344    let mut gears = Vec::new();
345
346    for gear_name in config.gears.keys() {
347        if let Some(spawn_config) = try_build_oop_gear_config(config, gear_name, &home_dir)? {
348            gears.push(spawn_config);
349        }
350    }
351
352    if gears.is_empty() {
353        Ok(None)
354    } else {
355        tracing::info!(count = gears.len(), "Prepared OoP gears for spawning");
356        Ok(Some(OopSpawnOptions {
357            gears,
358            backend: Box::new(backend),
359        }))
360    }
361}
362
363/// Try to build `OoP` gear spawn config if gear is of type `OoP`
364fn try_build_oop_gear_config(
365    config: &AppConfig,
366    gear_name: &str,
367    home_dir: &Path,
368) -> Result<Option<OopGearSpawnConfig>> {
369    let Some(runtime_cfg) = get_gear_runtime_config(config, gear_name)? else {
370        return Ok(None);
371    };
372
373    if !matches!(runtime_cfg.mod_type, RuntimeKind::Oop) {
374        return Ok(None);
375    }
376
377    let exec_cfg = runtime_cfg.execution.as_ref().ok_or_else(|| {
378        anyhow::anyhow!("gear '{gear_name}' is type=oop but execution config is missing")
379    })?;
380
381    let binary = normalize_path(&exec_cfg.executable_path)?;
382    let spawn_args = exec_cfg.args.clone();
383    let env = exec_cfg.environment.clone();
384
385    // Render the complete gear config (with resolved DB)
386    let rendered_config = render_gear_config_for_oop(config, gear_name, home_dir)?;
387    let rendered_json = rendered_config.to_json()?;
388
389    tracing::debug!(
390        gear =  %gear_name,
391        "Prepared OoP gear config: db={}",
392        rendered_config.database.is_some()
393    );
394
395    Ok(Some(OopGearSpawnConfig {
396        gear_name: gear_name.to_owned(),
397        binary,
398        args: spawn_args,
399        env,
400        working_directory: exec_cfg.working_directory.clone(),
401        rendered_config_json: rendered_json,
402    }))
403}
404
405/// Initialize process-wide bootstrap state from a provided `&AppConfig`.
406///
407/// This helper performs the common startup sequence shared by server and migration modes.
408/// It does **not** load configuration; the caller is responsible for building and passing
409/// a valid `AppConfig`.
410///
411/// Steps performed:
412///
413/// - initializes tracing/logging (once, guarded by a process-wide `Once`) and metrics
414///   when OpenTelemetry is enabled
415/// - registers the panic hook used to route panics through tracing
416/// - emits a small startup span and version metadata for diagnostics
417///
418/// The rustls crypto provider is installed inside this function (idempotent
419/// `OnceLock`), so callers do not need to invoke
420/// [`super::init_crypto_provider`] separately. Direct callers of
421/// [`super::init_crypto_provider`] outside the bootstrap path (e.g. ad-hoc
422/// probe binaries that do not call `run_server` / `run_migrate`) are still
423/// supported.
424///
425/// # Errors
426///
427/// Returns an error if OpenTelemetry tracing initialization fails while
428/// tracing is enabled, or if the crypto provider installation fails.
429#[cfg_attr(not(feature = "otel"), allow(clippy::unnecessary_wraps))]
430pub fn init_procedure(config: &AppConfig) -> Result<()> {
431    // Install the rustls crypto provider FIRST — before anything that may
432    // touch TLS (OTLP exporter over HTTPS, DB connections, etc.). The call
433    // is process-wide and idempotent; calling it twice is safe.
434    super::init_crypto_provider()?;
435
436    // Build OpenTelemetry layer before logging
437    #[cfg(feature = "otel")]
438    let otel_layer = if config.opentelemetry.tracing.enabled {
439        Some(crate::telemetry::init::init_tracing(&config.opentelemetry)?)
440    } else {
441        None
442    };
443    #[cfg(not(feature = "otel"))]
444    let otel_layer = None;
445
446    // Initialize logging + otel in one Registry
447    init_logging_unified(
448        &config.logging,
449        &config.server.home_dir,
450        otel_layer,
451        config.opentelemetry.inject_trace_ids_into_logs(),
452    );
453
454    // Register custom panic hook to reroute panic backtrace into tracing.
455    init_panic_tracing();
456
457    // Initialize OpenTelemetry metrics (or confirm noop when disabled)
458    #[cfg(feature = "otel")]
459    if let Err(e) = crate::telemetry::init::init_metrics_provider(&config.opentelemetry) {
460        tracing::error!(error = %e, "OpenTelemetry metrics not initialized");
461    }
462
463    // One-time connectivity probe
464    #[cfg(feature = "otel")]
465    if config.opentelemetry.tracing.enabled
466        && let Err(e) = crate::telemetry::init::otel_connectivity_probe(&config.opentelemetry)
467    {
468        tracing::error!(error = %e, "OTLP connectivity probe failed");
469    }
470
471    // Smoke test span to confirm traces flow to Jaeger
472    tracing::info_span!("startup_check", app = config.server.name).in_scope(|| {
473        tracing::info!("startup span alive - traces should be visible in Jaeger");
474    });
475
476    tracing::info!(
477        version = env!("CARGO_PKG_VERSION"),
478        rust_version = env!("CARGO_PKG_RUST_VERSION"),
479        "{} Server starting",
480        config.server.name,
481    );
482
483    Ok(())
484}
485
486#[cfg(test)]
487#[cfg_attr(coverage_nightly, coverage(off))]
488mod publish_gts_tests {
489    use super::*;
490    use crate::gts_publication::deployment::{GtsDeploymentOutcome, GtsDeploymentReport};
491
492    #[test]
493    fn deployment_rejects_publication_options_on_a_nonpublishing_gear() {
494        struct PlainGear;
495        #[async_trait::async_trait]
496        impl crate::Gear for PlainGear {
497            async fn init(&self, _ctx: &crate::GearCtx) -> Result<()> {
498                panic!("deployment validation must not initialize gears")
499            }
500        }
501
502        let mut builder = crate::registry::RegistryBuilder::default();
503        builder.register_core_with_meta("plain-gear", &[], Arc::new(PlainGear));
504        let registry = builder.build_topo_sorted().unwrap();
505        let mut config = AppConfig::default();
506        validate_deployment_configuration(&registry, &config).unwrap();
507        config.gears.insert(
508            "plain-gear".to_owned(),
509            serde_json::json!({"config": {"gts_publication": {"timeout": "1s"}}}),
510        );
511        let error = validate_deployment_configuration(&registry, &config).unwrap_err();
512        assert!(error.to_string().contains("plain-gear"), "{error}");
513        assert!(error.to_string().contains("gts_publication"), "{error}");
514    }
515
516    /// `publish-gts --timeout` above 10 minutes is refused first, before the
517    /// registry, the credential or the network; no clamping.
518    #[tokio::test]
519    async fn publish_gts_rejects_a_deadline_above_ten_minutes_first() {
520        let over =
521            crate::gts_publication::MAX_PUBLICATION_BUDGET + std::time::Duration::from_secs(1);
522        let err = publish_gts(
523            &AppConfig::default(),
524            &PublishGtsOptions {
525                registry_endpoint: "https://registry.example:8443".to_owned(),
526                deadline: over,
527            },
528            &CancellationToken::new(),
529        )
530        .await
531        .unwrap_err();
532        let message = format!("{err:#}");
533        assert!(
534            message.contains("--timeout")
535                && message.contains("too large to be a publication budget"),
536            "{message}"
537        );
538    }
539
540    #[test]
541    fn publish_gts_needs_the_platform_credential() {
542        let err = platform_credential(&AppConfig::default()).unwrap_err();
543        assert!(err.to_string().contains("oop_http.internal_auth"), "{err}");
544    }
545
546    #[test]
547    fn a_failed_publisher_fails_the_job_with_the_report() {
548        let failed = GtsDeploymentReport {
549            publishers: vec![
550                ("ok", GtsDeploymentOutcome::Published { documents: 1 }),
551                (
552                    "late",
553                    GtsDeploymentOutcome::DeadlineExceeded {
554                        unconfirmed: vec![
555                            toolkit_gts::gts_id!("cf.test.publication.late.v1~").to_owned(),
556                        ],
557                    },
558                ),
559            ],
560        };
561        let err = publication_result(&failed).unwrap_err();
562        let message = format!("{err:#}");
563        assert!(
564            message.contains("late: deadline exceeded")
565                && message.contains(toolkit_gts::gts_id!("cf.test.publication.late.v1~")),
566            "{message}"
567        );
568
569        let succeeded = GtsDeploymentReport {
570            publishers: vec![("ok", GtsDeploymentOutcome::Published { documents: 1 })],
571        };
572        publication_result(&succeeded).expect("every publisher succeeded");
573    }
574}