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