Skip to main content

toolkit/backends/
mod.rs

1//! Backend abstraction for out-of-process gear management
2//!
3//! This gear provides traits and types for spawning and managing `OoP` gear instances.
4
5use anyhow::Result;
6use async_trait::async_trait;
7use std::collections::HashMap;
8use std::path::PathBuf;
9use std::time::Instant;
10use uuid::Uuid;
11
12/// The kind of backend used to spawn and manage gear instances
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum BackendKind {
15    LocalProcess,
16    K8s,
17    Static,
18    Mock,
19}
20
21/// Configuration for an out-of-process gear
22pub struct OopGearConfig {
23    pub name: String,
24    pub binary: Option<PathBuf>,
25    pub args: Vec<String>,
26    pub env: HashMap<String, String>,
27    pub working_directory: Option<String>,
28    pub backend: BackendKind,
29    pub version: Option<String>,
30}
31
32impl OopGearConfig {
33    pub fn new(name: impl Into<String>, backend: BackendKind) -> Self {
34        Self {
35            name: name.into(),
36            binary: None,
37            args: Vec::new(),
38            env: HashMap::new(),
39            working_directory: None,
40            backend,
41            version: None,
42        }
43    }
44}
45
46/// A handle to a running gear instance
47#[derive(Clone)]
48pub struct InstanceHandle {
49    pub gear: String,
50    pub instance_id: Uuid,
51    pub backend: BackendKind,
52    pub pid: Option<u32>,
53    pub created_at: Instant,
54}
55
56impl std::fmt::Debug for InstanceHandle {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("InstanceHandle")
59            .field("gear", &self.gear)
60            .field("instance_id", &self.instance_id)
61            .field("backend", &self.backend)
62            .field("pid", &self.pid)
63            .field("created_at", &self.created_at)
64            .finish()
65    }
66}
67
68/// Trait for backends that can spawn and manage gear instances
69#[async_trait]
70pub trait GearRuntimeBackend: Send + Sync {
71    async fn spawn_instance(&self, cfg: &OopGearConfig) -> Result<InstanceHandle>;
72    async fn stop_instance(&self, handle: &InstanceHandle) -> Result<()>;
73    async fn list_instances(&self, gear: &str) -> Result<Vec<InstanceHandle>>;
74}
75
76/// Configuration passed to `OopBackend::spawn`
77pub struct OopSpawnConfig {
78    pub gear_name: String,
79    pub binary: PathBuf,
80    pub args: Vec<String>,
81    pub env: HashMap<String, String>,
82    pub working_directory: Option<String>,
83}
84
85/// A type-erased backend for spawning `OoP` gears.
86///
87/// This trait is used by `HostRuntime` to spawn `OoP` gears after the start phase.
88#[async_trait]
89pub trait OopBackend: Send + Sync {
90    /// Spawn an `OoP` gear instance.
91    async fn spawn(&self, config: OopSpawnConfig) -> Result<()>;
92
93    /// Stop every spawned instance and wait for it to end: the runtime calls
94    /// it when startup fails after a spawn, and at shutdown. The runtime waits
95    /// at most its shutdown deadline, then stops its in-process gears anyway.
96    async fn shutdown_all(&self);
97}
98
99pub mod local;
100pub mod log_forwarder;
101
102pub use local::LocalProcessBackend;
103
104/// Adapter that implements `OopBackend` trait for `LocalProcessBackend`.
105///
106/// This allows `LocalProcessBackend` to be used by `HostRuntime` for spawning `OoP` gears.
107#[async_trait]
108impl OopBackend for LocalProcessBackend {
109    async fn spawn(&self, config: OopSpawnConfig) -> Result<()> {
110        let mut oop_config = OopGearConfig::new(&config.gear_name, BackendKind::LocalProcess);
111        oop_config.binary = Some(config.binary);
112        oop_config.args = config.args;
113        oop_config.env = config.env;
114        oop_config.working_directory = config.working_directory;
115
116        self.spawn_instance(&oop_config).await?;
117        Ok(())
118    }
119
120    async fn shutdown_all(&self) {
121        // Stops and joins every instance still tracked, now: a failed startup
122        // ends its children without cancelling the host's (possibly borrowed)
123        // token. The cancellation task stops whatever is left on shutdown.
124        self.stop_all().await;
125    }
126}
127
128#[cfg(test)]
129#[cfg_attr(coverage_nightly, coverage(off))]
130mod tests {
131    use super::*;
132    use std::path::PathBuf;
133
134    #[test]
135    fn test_oop_gear_config_builder() {
136        let mut cfg = OopGearConfig::new("my_gear", BackendKind::LocalProcess);
137        cfg.binary = Some(PathBuf::from("/usr/bin/myapp"));
138        cfg.args = vec!["--port".to_owned(), "8080".to_owned()];
139        cfg.env.insert("LOG_LEVEL".to_owned(), "debug".to_owned());
140        cfg.version = Some("1.0.0".to_owned());
141
142        assert_eq!(cfg.name, "my_gear");
143        assert_eq!(cfg.backend, BackendKind::LocalProcess);
144        assert_eq!(cfg.binary, Some(PathBuf::from("/usr/bin/myapp")));
145        assert_eq!(cfg.args.len(), 2);
146        assert_eq!(cfg.env.len(), 1);
147        assert_eq!(cfg.version, Some("1.0.0".to_owned()));
148    }
149
150    #[test]
151    fn test_backend_kind_equality() {
152        assert_eq!(BackendKind::LocalProcess, BackendKind::LocalProcess);
153        assert_ne!(BackendKind::LocalProcess, BackendKind::K8s);
154        assert_ne!(BackendKind::K8s, BackendKind::Static);
155        assert_ne!(BackendKind::Static, BackendKind::Mock);
156    }
157
158    #[test]
159    fn test_instance_handle_debug() {
160        let instance_id = Uuid::new_v4();
161        let handle = InstanceHandle {
162            gear: "test_gear".to_owned(),
163            instance_id,
164            backend: BackendKind::LocalProcess,
165            pid: Some(12345),
166            created_at: Instant::now(),
167        };
168
169        let debug_str = format!("{handle:?}");
170        assert!(debug_str.contains("test_gear"));
171        assert!(debug_str.contains(&instance_id.to_string()));
172        assert!(debug_str.contains("LocalProcess"));
173        assert!(debug_str.contains("12345"));
174    }
175}