Skip to main content

toolkit/runtime/
runner.rs

1//! `ToolKit` runtime runner.
2//!
3//! Supported DB modes:
4//!   - `DbOptions::None` — gears get no DB in their contexts.
5//!   - `DbOptions::Manager` — gears use `GearContextBuilder` to resolve per-gear `DbHandles`.
6//!
7//! Design notes:
8//! - We use **`GearContextBuilder`** to resolve per-gear `DbHandles` at runtime.
9//! - Phase order is orchestrated by `HostRuntime` (see `runtime/host_runtime.rs` docs).
10//! - Gears receive a fully-scoped `GearCtx` with a resolved Option<DbHandle>.
11//! - Shutdown can be driven by OS signals, an external `CancellationToken`,
12//!   or an arbitrary future.
13//! - Pre-registered clients can be injected into the `ClientHub` via `RunOptions::clients`.
14//! - `OoP` gears are spawned after the start phase so that `grpc-hub` is already running
15//!   and the real directory endpoint is known.
16
17use crate::backends::OopBackend;
18use crate::client_hub::ClientHub;
19use crate::config::ConfigProvider;
20use crate::registry::GearRegistry;
21use crate::runtime::shutdown;
22use crate::runtime::{DbOptions, HostRuntime};
23use std::collections::HashMap;
24use std::path::PathBuf;
25use std::{future::Future, pin::Pin, sync::Arc};
26use tokio_util::sync::CancellationToken;
27use uuid::Uuid;
28
29/// A type-erased client registration for injecting clients into the `ClientHub`.
30///
31/// This is used to pass pre-created clients (like gRPC clients) from bootstrap code
32/// into the runtime's `ClientHub` before gears are initialized.
33pub struct ClientRegistration {
34    /// Callback that registers the client into the hub.
35    register_fn: Box<dyn FnOnce(&ClientHub) + Send>,
36}
37
38impl ClientRegistration {
39    /// Create a new client registration for a trait object type.
40    ///
41    /// # Example
42    /// ```ignore
43    /// let api: Arc<dyn DirectoryClient> = Arc::new(client);
44    /// ClientRegistration::new::<dyn DirectoryClient>(api)
45    /// ```
46    pub fn new<T>(client: Arc<T>) -> Self
47    where
48        T: ?Sized + Send + Sync + 'static,
49    {
50        Self {
51            register_fn: Box::new(move |hub| {
52                hub.register::<T>(client);
53            }),
54        }
55    }
56
57    /// Execute the registration against the given hub.
58    pub(crate) fn apply(self, hub: &ClientHub) {
59        (self.register_fn)(hub);
60    }
61}
62
63/// How the runtime should decide when to stop.
64pub enum ShutdownOptions {
65    /// Listen for OS signals (Ctrl+C / SIGTERM).
66    Signals,
67    /// An external `CancellationToken` controls the lifecycle.
68    Token(CancellationToken),
69    /// An arbitrary future; when it completes, we initiate shutdown.
70    Future(Pin<Box<dyn Future<Output = ()> + Send>>),
71}
72
73/// Configuration for a single `OoP` gear to be spawned.
74#[derive(Clone)]
75pub struct OopGearSpawnConfig {
76    /// Name of the gear (e.g., "calculator").
77    pub gear_name: String,
78    /// Path to the gear executable.
79    pub binary: PathBuf,
80    /// Command-line arguments passed to the gear binary.
81    ///
82    /// Note: the user controls `--config` via `execution.args` in the master config.
83    pub args: Vec<String>,
84    /// Environment variables to set for the spawned process.
85    pub env: HashMap<String, String>,
86    /// Working directory for the spawned process.
87    pub working_directory: Option<String>,
88    /// Rendered gear configuration JSON, injected as the `TOOLKIT_MODULE_CONFIG` environment variable.
89    pub rendered_config_json: String,
90}
91
92/// Options for spawning `OoP` gears.
93pub struct OopSpawnOptions {
94    /// Gears to spawn after the start phase, once shared infrastructure is ready.
95    pub gears: Vec<OopGearSpawnConfig>,
96    /// Backend used to spawn gear processes (e.g. `LocalProcessBackend`).
97    pub backend: Box<dyn OopBackend>,
98}
99
100/// Options for running the `ToolKit` runner.
101///
102/// `#[non_exhaustive]`: construct via [`RunOptions::new`] + the `with_*`
103/// builders rather than a struct literal, so adding a new optional field does
104/// not break every call site (and out-of-crate consumers get a deprecation-free
105/// upgrade path). The four arguments to `new` are the always-required fields;
106/// everything else defaults to "off".
107#[non_exhaustive]
108pub struct RunOptions {
109    /// Provider of gear config sections (raw JSON by gear name).
110    pub gears_cfg: Arc<dyn ConfigProvider>,
111    /// DB strategy: none, or `DbManager`.
112    pub db: DbOptions,
113    /// Shutdown strategy.
114    pub shutdown: ShutdownOptions,
115    /// Pre-registered clients to inject into the `ClientHub` before gear initialization.
116    ///
117    /// This is useful for `OoP` bootstrap where clients (like `DirectoryGrpcClient`)
118    /// are created before calling `run()` and need to be available in the `ClientHub`.
119    pub clients: Vec<ClientRegistration>,
120    /// Process-level instance ID.
121    ///
122    /// This is a unique identifier for this process instance, generated once at bootstrap
123    /// (either in `run_oop_with_options` for `OoP` gears or in the main host).
124    /// It is propagated to all gears via `GearCtx::instance_id()` and `SystemContext::instance_id()`.
125    pub instance_id: Uuid,
126    /// `OoP` gear spawn configuration.
127    ///
128    /// These gears are spawned after the start phase, once `grpc-hub` is running
129    /// and the real directory endpoint is known.
130    pub oop: Option<OopSpawnOptions>,
131    /// Maximum time allowed for each gear's graceful shutdown before hard-stop.
132    ///
133    /// If `None`, uses [`DEFAULT_SHUTDOWN_DEADLINE`](crate::runtime::DEFAULT_SHUTDOWN_DEADLINE) (35 seconds).
134    ///
135    /// See `HostRuntime::with_shutdown_deadline` for details on the relationship
136    /// with `WithLifecycle::stop_timeout`.
137    pub shutdown_deadline: Option<std::time::Duration>,
138    /// Per-gear deadline for context construction and [`Gear::init`](crate::contracts::Gear::init).
139    /// `None` uses [`DEFAULT_INIT_DEADLINE`](crate::runtime::DEFAULT_INIT_DEADLINE); see
140    /// `HostRuntime::with_init_deadline` for the two-tier (error / force-exit) behavior.
141    pub init_deadline: Option<std::time::Duration>,
142    /// Process-wide platform-plane credential source (the selected
143    /// `InternalCredential`), threaded into every [`GearCtx`] so
144    /// `#[toolkit::provides]`-generated clients attach `X-ToolKit-Internal-Token`
145    /// on platform-plane (`PlatformSecurityContext`) methods. `None` (Profile 1
146    /// / in-process, or no credential configured) attaches nothing.
147    pub internal_token_provider: Option<toolkit_contract::runtime::config::InternalTokenProvider>,
148}
149
150impl RunOptions {
151    /// Create `RunOptions` with the four always-required fields; all optional
152    /// fields default to "off" (`clients` empty, no `oop`, default shutdown
153    /// deadline, no platform credential). Layer options on with the `with_*`
154    /// builders.
155    #[must_use]
156    pub fn new(
157        gears_cfg: Arc<dyn ConfigProvider>,
158        db: DbOptions,
159        shutdown: ShutdownOptions,
160        instance_id: Uuid,
161    ) -> Self {
162        Self {
163            gears_cfg,
164            db,
165            shutdown,
166            clients: Vec::new(),
167            instance_id,
168            oop: None,
169            shutdown_deadline: None,
170            init_deadline: None,
171            internal_token_provider: None,
172        }
173    }
174
175    /// Pre-register clients to inject into the `ClientHub` before gear init.
176    #[must_use]
177    pub fn with_clients(mut self, clients: Vec<ClientRegistration>) -> Self {
178        self.clients = clients;
179        self
180    }
181
182    /// Set the `OoP` gear spawn configuration.
183    #[must_use]
184    pub fn with_oop(mut self, oop: Option<OopSpawnOptions>) -> Self {
185        self.oop = oop;
186        self
187    }
188
189    /// Override the per-gear graceful-shutdown deadline.
190    #[must_use]
191    pub fn with_shutdown_deadline(mut self, deadline: Option<std::time::Duration>) -> Self {
192        self.shutdown_deadline = deadline;
193        self
194    }
195
196    /// Override the per-gear `init()` deadline.
197    #[must_use]
198    pub fn with_init_deadline(mut self, deadline: Option<std::time::Duration>) -> Self {
199        self.init_deadline = deadline;
200        self
201    }
202
203    /// Set the process-wide platform-plane credential source (see the field).
204    #[must_use]
205    pub fn with_internal_token_provider(
206        mut self,
207        provider: Option<toolkit_contract::runtime::config::InternalTokenProvider>,
208    ) -> Self {
209        self.internal_token_provider = provider;
210        self
211    }
212}
213
214/// Construct a `HostRuntime` by wiring shutdown, discovering gears, building
215/// the `ClientHub`, and injecting pre-registered clients.
216///
217/// Shared by [`run`] and [`run_oop_serving`]. `opts` is consumed; the returned
218/// `HostRuntime` owns the root lifecycle `CancellationToken`.
219fn build_host_runtime(opts: RunOptions) -> anyhow::Result<HostRuntime> {
220    // 1. Prepare cancellation token based on shutdown options.
221    let cancel = match &opts.shutdown {
222        ShutdownOptions::Token(t) => t.clone(),
223        _ => CancellationToken::new(),
224    };
225
226    // 2. Spawn shutdown waiter (Signals / Future).
227    match opts.shutdown {
228        ShutdownOptions::Signals => {
229            let c = cancel.clone();
230            tokio::spawn(async move {
231                match shutdown::wait_for_shutdown().await {
232                    Ok(()) => {
233                        tracing::info!(target: "", "------------------");
234                        tracing::info!("shutdown: signal received");
235                    }
236                    Err(e) => {
237                        tracing::warn!(
238                            error = %e,
239                            "shutdown: primary waiter failed; falling back to ctrl_c()"
240                        );
241                        _ = tokio::signal::ctrl_c().await;
242                    }
243                }
244                c.cancel();
245            });
246        }
247        ShutdownOptions::Future(waiter) => {
248            let c = cancel.clone();
249            tokio::spawn(async move {
250                waiter.await;
251                tracing::info!("shutdown: external future completed");
252                c.cancel();
253            });
254        }
255        ShutdownOptions::Token(_) => {
256            tracing::info!("shutdown: external token will control lifecycle");
257        }
258    }
259
260    // 3. Discover gears.
261    let registry = GearRegistry::discover_and_build()?;
262
263    // 4. Build shared `ClientHub` and inject pre-registered clients.
264    let hub = Arc::new(ClientHub::default());
265    for registration in opts.clients {
266        registration.apply(&hub);
267    }
268
269    // 5. Instantiate `HostRuntime`.
270    let mut host = HostRuntime::new(
271        registry,
272        opts.gears_cfg.clone(),
273        opts.db,
274        hub,
275        cancel,
276        opts.instance_id,
277        opts.oop,
278    );
279    if let Some(deadline) = opts.shutdown_deadline {
280        host = host.with_shutdown_deadline(deadline);
281    }
282    if let Some(deadline) = opts.init_deadline {
283        host = host.with_init_deadline(deadline);
284    }
285    host = host.with_internal_token_provider(opts.internal_token_provider);
286
287    Ok(host)
288}
289
290/// Run the full gear lifecycle.
291///
292/// Discovers gears, wires shutdown, and delegates phase execution to [`HostRuntime`].
293///
294/// # Errors
295/// Returns an error if any lifecycle phase fails.
296pub async fn run(opts: RunOptions) -> anyhow::Result<()> {
297    let host = build_host_runtime(opts)?;
298    host.run_gear_phases().await
299}
300
301/// Run an out-of-process gear and serve its HTTP routes.
302///
303/// Uses the same setup as [`run`], then drives the `OoP` serving lifecycle:
304/// lifecycle phases, an Axum HTTP server with framework probes, background
305/// self-registration, dependency resolution, and graceful drain.
306///
307/// # Errors
308/// Returns an error if discovery, any lifecycle phase, or the HTTP server fails.
309#[cfg(feature = "bootstrap")]
310pub async fn run_oop_serving(
311    opts: RunOptions,
312    serve: crate::runtime::OopServeOptions,
313) -> anyhow::Result<()> {
314    let host = build_host_runtime(opts)?;
315    host.run_oop_serving(serve).await
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    struct EmptyConfigProvider;
323    impl ConfigProvider for EmptyConfigProvider {
324        fn get_gear_config(&self, _gear_name: &str) -> Option<&serde_json::Value> {
325            None
326        }
327    }
328
329    fn opts() -> RunOptions {
330        RunOptions::new(
331            Arc::new(EmptyConfigProvider),
332            DbOptions::None,
333            ShutdownOptions::Token(CancellationToken::new()),
334            Uuid::new_v4(),
335        )
336    }
337
338    #[test]
339    fn build_host_runtime_applies_the_init_deadline() {
340        // `Some` must reach `HostRuntime::with_init_deadline`; `None` leaves the
341        // `DEFAULT_INIT_DEADLINE` in place.
342        let deadline = std::time::Duration::from_secs(7);
343        let host = build_host_runtime(opts().with_init_deadline(Some(deadline))).unwrap();
344        assert_eq!(host.init_deadline(), deadline);
345
346        let host = build_host_runtime(opts()).unwrap();
347        assert_eq!(host.init_deadline(), crate::runtime::DEFAULT_INIT_DEADLINE);
348    }
349}