Skip to main content

toolkit/backends/
local.rs

1//! Local process backend implementation
2
3use anyhow::{Context, Result, bail};
4use async_trait::async_trait;
5use parking_lot::RwLock;
6use std::collections::HashMap;
7use std::path::Path;
8use std::process::Stdio;
9use std::sync::Arc;
10use std::time::Duration;
11use tokio::process::{Child, Command};
12use tokio::task::JoinHandle;
13use tokio_util::sync::CancellationToken;
14use uuid::Uuid;
15
16use super::log_forwarder::{StreamKind, spawn_stream_forwarder};
17use super::{BackendKind, GearRuntimeBackend, InstanceHandle, OopGearConfig};
18
19/// Grace period before force-killing processes on shutdown
20const SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(5);
21
22/// Grace period for individual instance stop
23const INSTANCE_STOP_GRACE_PERIOD: Duration = Duration::from_secs(2);
24
25/// Timeout for waiting on forwarder tasks during shutdown
26const FORWARDER_DRAIN_TIMEOUT: Duration = Duration::from_millis(100);
27
28/// Send graceful termination signal to a child process.
29///
30/// # Returns
31/// - `true` if signal was successfully sent
32/// - `false` if:
33///   - Process has no PID (already exited)
34///   - PID cannot be converted to i32 (extremely rare: PID > 2,147,483,647)
35///   - Signal delivery fails
36///
37/// On Unix: Sends SIGTERM which the process can handle for cleanup.
38/// On Windows: Returns false since there's no reliable graceful termination
39/// method for console applications.
40#[cfg(unix)]
41fn send_terminate_signal(child: &Child) -> bool {
42    use nix::sys::signal::{Signal, kill};
43    use nix::unistd::Pid;
44
45    let Some(pid) = child.id() else {
46        return false;
47    };
48
49    let Ok(pid_i32) = i32::try_from(pid) else {
50        tracing::warn!(
51            pid = pid,
52            "Failed to convert PID to i32, cannot send SIGTERM (PID exceeds i32::MAX: {})",
53            i32::MAX
54        );
55        return false;
56    };
57
58    kill(Pid::from_raw(pid_i32), Signal::SIGTERM).is_ok()
59}
60
61/// Send graceful termination signal to a child process.
62///
63/// # Returns
64/// - `false` always on Windows (no reliable graceful termination available)
65///
66/// On Windows there's no reliable SIGTERM equivalent for console applications.
67/// We return false to indicate that graceful termination is not available,
68/// and the caller should proceed with force kill.
69#[cfg(windows)]
70fn send_terminate_signal(_child: &Child) -> bool {
71    false
72}
73
74/// Stop a child process with graceful termination and timeout.
75///
76/// 1. Sends SIGTERM (Unix) via `send_terminate_signal`
77/// 2. Waits for process exit within `grace` period
78/// 3. On timeout: force kills the process
79async fn stop_child_with_grace(
80    child: &mut Child,
81    handle: &InstanceHandle,
82    grace: Duration,
83    context: &str,
84) {
85    let pid = child.id();
86    let sent = send_terminate_signal(child);
87
88    // Log with gear context if termination signal failed
89    if !sent && pid.is_some() {
90        tracing::debug!(
91            gear =  %handle.gear,
92            instance_id = %handle.instance_id,
93            pid = ?pid,
94            "{context}: graceful termination not available, will force kill"
95        );
96    }
97
98    tracing::debug!(
99        gear =  %handle.gear,
100        instance_id = %handle.instance_id,
101        pid = ?pid,
102        graceful = sent,
103        "{context}: sent termination signal"
104    );
105
106    match tokio::time::timeout(grace, child.wait()).await {
107        Ok(Ok(status)) => {
108            tracing::debug!(
109                gear =  %handle.gear,
110                instance_id = %handle.instance_id,
111                status = ?status,
112                "{context}: process exited gracefully"
113            );
114        }
115        Ok(Err(e)) => {
116            tracing::warn!(
117                gear =  %handle.gear,
118                instance_id = %handle.instance_id,
119                error = %e,
120                "{context}: failed to wait for process"
121            );
122        }
123        Err(_) => {
124            tracing::debug!(
125                gear =  %handle.gear,
126                instance_id = %handle.instance_id,
127                "{context}: grace period expired, force killing"
128            );
129            if let Err(e) = child.kill().await {
130                tracing::warn!(
131                    gear =  %handle.gear,
132                    instance_id = %handle.instance_id,
133                    error = %e,
134                    "{context}: failed to force kill"
135                );
136            }
137        }
138    }
139}
140
141/// Wait for a log forwarder task to finish with timeout.
142async fn wait_forwarder(
143    handle: Option<JoinHandle<()>>,
144    gear: &str,
145    instance_id: uuid::Uuid,
146    stream: &str,
147) {
148    let Some(h) = handle else { return };
149    match tokio::time::timeout(FORWARDER_DRAIN_TIMEOUT, h).await {
150        Ok(Ok(())) => {}
151        Ok(Err(e)) => {
152            if e.is_panic() {
153                tracing::warn!(gear, %instance_id, stream, error = %e, "log forwarder task panicked");
154            } else {
155                tracing::warn!(gear, %instance_id, stream, error = %e, "log forwarder task cancelled");
156            }
157        }
158        Err(_) => {
159            tracing::warn!(
160                gear,
161                %instance_id,
162                stream,
163                timeout_ms = FORWARDER_DRAIN_TIMEOUT.as_millis(),
164                "log forwarder did not finish within drain timeout",
165            );
166        }
167    }
168}
169
170/// Internal representation of a local process instance
171struct LocalInstance {
172    handle: InstanceHandle,
173    child: Child,
174    /// Task handle for stdout log forwarder
175    stdout_forwarder: Option<JoinHandle<()>>,
176    /// Task handle for stderr log forwarder
177    stderr_forwarder: Option<JoinHandle<()>>,
178}
179
180/// Map key type for instances - uses Uuid directly
181type InstanceMap = HashMap<Uuid, LocalInstance>;
182
183/// Backend that spawns gears as local child processes and manages their lifecycle.
184///
185/// When the cancellation token is triggered, the backend will:
186/// 1. Send termination signal to all processes (SIGTERM on Unix, `TerminateProcess` on Windows)
187/// 2. Wait up to 5 seconds for graceful shutdown
188/// 3. Force kill any remaining processes
189pub struct LocalProcessBackend {
190    instances: Arc<RwLock<InstanceMap>>,
191    cancel: CancellationToken,
192    /// Shared shutdown task: cancellation and `stop_all` await it;
193    /// dropping the backend triggers it. Dropping a waiter does not stop it.
194    shutdown: Arc<Shutdown>,
195    /// Cancelled on drop: the watcher then stops the children, although the
196    /// caller's token, which the backend only borrows, stays live.
197    dropped: CancellationToken,
198}
199
200/// See [`LocalProcessBackend::shutdown`].
201struct Shutdown {
202    instances: Arc<RwLock<InstanceMap>>,
203    /// Set under the instances lock when shutdown takes them; refuses racing spawns.
204    stopping: std::sync::atomic::AtomicBool,
205    started: std::sync::atomic::AtomicBool,
206    done: tokio::sync::watch::Sender<bool>,
207}
208
209impl Shutdown {
210    /// Start the run once, on a task of its own, and wait until it ended.
211    async fn run(self: &Arc<Self>) {
212        self.run_with(|shutdown| {
213            Box::pin(async move { LocalProcessBackend::shutdown_all_instances(&shutdown).await })
214        })
215        .await;
216    }
217
218    /// [`run`](Self::run) with `body` as the run: started once, and ended for
219    /// every waiter however it ends, a panic included.
220    async fn run_with(
221        self: &Arc<Self>,
222        body: impl FnOnce(Arc<Self>) -> futures_util::future::BoxFuture<'static, ()>,
223    ) {
224        let mut done = self.done.subscribe();
225        if !self.started.swap(true, std::sync::atomic::Ordering::AcqRel) {
226            let ended = RunEnded(Arc::clone(self));
227            let run = body(Arc::clone(self));
228            tokio::spawn(async move {
229                let _ended = ended;
230                run.await;
231            });
232        }
233        drop(done.wait_for(|done| *done).await);
234    }
235}
236
237/// Wake shutdown waiters on completion or panic.
238struct RunEnded(Arc<Shutdown>);
239
240impl Drop for RunEnded {
241    fn drop(&mut self) {
242        if std::thread::panicking() {
243            tracing::error!(
244                "LocalProcessBackend: the shutdown run panicked; children it had not stopped may still run"
245            );
246        }
247        self.0.done.send_replace(true);
248    }
249}
250
251impl Drop for LocalProcessBackend {
252    fn drop(&mut self) {
253        self.dropped.cancel();
254    }
255}
256
257impl LocalProcessBackend {
258    /// Create a new `LocalProcessBackend` with the given cancellation token.
259    ///
260    /// When the token is cancelled, or the backend is dropped, all spawned
261    /// processes will be gracefully stopped.
262    #[must_use]
263    pub fn new(cancel: CancellationToken) -> Self {
264        let instances = Arc::new(RwLock::new(HashMap::new()));
265        let backend = Self {
266            instances: Arc::clone(&instances),
267            cancel: cancel.clone(),
268            shutdown: Arc::new(Shutdown {
269                instances,
270                stopping: std::sync::atomic::AtomicBool::new(false),
271                started: std::sync::atomic::AtomicBool::new(false),
272                done: tokio::sync::watch::Sender::new(false),
273            }),
274            dropped: CancellationToken::new(),
275        };
276
277        // Spawn background task to handle shutdown
278        let shutdown = Arc::clone(&backend.shutdown);
279        let dropped = backend.dropped.clone();
280        tokio::spawn(async move {
281            tokio::select! {
282                () = cancel.cancelled() => {
283                    tracing::info!("LocalProcessBackend: shutdown signal received, stopping all processes");
284                }
285                () = dropped.cancelled() => {
286                    tracing::info!("LocalProcessBackend: dropped, stopping all processes");
287                }
288            }
289            shutdown.run().await;
290        });
291
292        backend
293    }
294
295    /// Gracefully stop every tracked instance, with the shutdown grace
296    /// period, and wait until each ended — also when the cancellation
297    /// watcher began that shutdown first. Later spawns are refused.
298    pub async fn stop_all(&self) {
299        self.shutdown.run().await;
300    }
301
302    /// Gracefully stop all tracked instances with timeout.
303    async fn shutdown_all_instances(shutdown: &Shutdown) {
304        let mut all_instances: Vec<LocalInstance> = {
305            let mut guard = shutdown.instances.write();
306            shutdown
307                .stopping
308                .store(true, std::sync::atomic::Ordering::Release);
309            guard.drain().map(|(_, inst)| inst).collect()
310        };
311
312        if all_instances.is_empty() {
313            return;
314        }
315
316        tracing::info!(count = all_instances.len(), "Stopping OoP gear processes");
317
318        // Stop all processes with grace period, concurrently: the run takes one
319        // grace period, not one per child.
320        futures_util::future::join_all(all_instances.iter_mut().map(|inst| {
321            stop_child_with_grace(
322                &mut inst.child,
323                &inst.handle,
324                SHUTDOWN_GRACE_PERIOD,
325                "shutdown",
326            )
327        }))
328        .await;
329
330        // Wait for forwarders to drain
331        for inst in all_instances {
332            wait_forwarder(
333                inst.stdout_forwarder,
334                &inst.handle.gear,
335                inst.handle.instance_id,
336                "stdout",
337            )
338            .await;
339            wait_forwarder(
340                inst.stderr_forwarder,
341                &inst.handle.gear,
342                inst.handle.instance_id,
343                "stderr",
344            )
345            .await;
346        }
347
348        tracing::info!("All OoP gear processes stopped");
349    }
350}
351
352#[async_trait]
353impl GearRuntimeBackend for LocalProcessBackend {
354    async fn spawn_instance(&self, cfg: &OopGearConfig) -> Result<InstanceHandle> {
355        // Verify backend kind
356        if cfg.backend != BackendKind::LocalProcess {
357            bail!(
358                "LocalProcessBackend can only spawn LocalProcess instances, got {:?}",
359                cfg.backend
360            );
361        }
362
363        // Ensure binary is set
364        let binary = cfg
365            .binary
366            .as_ref()
367            .context("executable_path must be set for LocalProcess backend")?;
368
369        // Generate unique instance ID using UUID v7
370        let instance_id = Uuid::now_v7();
371
372        // Build command
373        let mut cmd = Command::new(binary);
374        cmd.args(&cfg.args);
375        cmd.envs(&cfg.env);
376
377        // A child whose handle is dropped unstopped is killed, never orphaned.
378        cmd.kill_on_drop(true);
379
380        // Pipe stdout/stderr for log forwarding
381        cmd.stdout(Stdio::piped());
382        cmd.stderr(Stdio::piped());
383
384        // Set working directory if specified
385        if let Some(ref working_dir) = cfg.working_directory {
386            let path = Path::new(working_dir);
387            if path.exists() && path.is_dir() {
388                cmd.current_dir(path);
389            } else {
390                tracing::warn!(
391                    gear =  %cfg.name,
392                    working_dir = %working_dir,
393                    "Working directory does not exist or is not a directory, using current dir"
394                );
395            }
396        }
397
398        // Spawn the process
399        let mut child = cmd
400            .spawn()
401            .with_context(|| format!("failed to spawn process: {}", binary.display()))?;
402
403        // Get PID
404        let pid = child.id();
405
406        // Spawn log forwarder tasks for stdout/stderr with cancellation support
407        let gear_name = cfg.name.clone();
408        let cancel = self.cancel.clone();
409        let stdout_forwarder = child.stdout.take().map(|stdout| {
410            spawn_stream_forwarder(
411                stdout,
412                gear_name.clone(),
413                instance_id,
414                cancel.clone(),
415                StreamKind::Stdout,
416            )
417        });
418        let stderr_forwarder = child.stderr.take().map(|stderr| {
419            spawn_stream_forwarder(
420                stderr,
421                gear_name.clone(),
422                instance_id,
423                cancel.clone(),
424                StreamKind::Stderr,
425            )
426        });
427
428        tracing::info!(
429            gear =  %cfg.name,
430            instance_id = %instance_id,
431            pid = ?pid,
432            "Spawned OoP gear with log forwarding"
433        );
434
435        // Create handle
436        let handle = InstanceHandle {
437            gear: cfg.name.clone(),
438            instance_id,
439            backend: BackendKind::LocalProcess,
440            pid,
441            created_at: std::time::Instant::now(),
442        };
443
444        // Store in instances map, unless the backend is shutting down.
445        {
446            let mut instances = self.instances.write();
447            if self
448                .shutdown
449                .stopping
450                .load(std::sync::atomic::Ordering::Acquire)
451            {
452                drop(instances);
453                if let Err(e) = child.start_kill() {
454                    tracing::warn!(gear = %cfg.name, error = %e, "failed to kill a process spawned during shutdown");
455                }
456                drop(child.wait().await);
457                bail!(
458                    "LocalProcessBackend is shutting down; {} was not started",
459                    cfg.name
460                );
461            }
462            instances.insert(
463                instance_id,
464                LocalInstance {
465                    handle: handle.clone(),
466                    child,
467                    stdout_forwarder,
468                    stderr_forwarder,
469                },
470            );
471        }
472
473        Ok(handle)
474    }
475
476    async fn stop_instance(&self, handle: &InstanceHandle) -> Result<()> {
477        let local = {
478            let mut instances = self.instances.write();
479            instances.remove(&handle.instance_id)
480        };
481
482        if let Some(mut local) = local {
483            stop_child_with_grace(
484                &mut local.child,
485                &local.handle,
486                INSTANCE_STOP_GRACE_PERIOD,
487                "stop_instance",
488            )
489            .await;
490
491            // we do not await forwarders here, they'll stop on their own via CancellationToken and pipe close;
492            // shutdown_all_instances handles draining for global shutdown
493        } else {
494            tracing::debug!(
495                gear =  %handle.gear,
496                instance_id = %handle.instance_id,
497                "stop_instance called for unknown instance, ignoring"
498            );
499        }
500
501        Ok(())
502    }
503
504    async fn list_instances(&self, gear: &str) -> Result<Vec<InstanceHandle>> {
505        let instances = self.instances.read();
506
507        let result = instances
508            .values()
509            .filter(|inst| inst.handle.gear == gear)
510            .map(|inst| inst.handle.clone())
511            .collect();
512
513        Ok(result)
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use std::path::PathBuf;
521    use std::time::Instant;
522
523    fn test_backend() -> LocalProcessBackend {
524        LocalProcessBackend::new(CancellationToken::new())
525    }
526
527    #[tokio::test]
528    async fn test_spawn_instance_requires_binary() {
529        let backend = test_backend();
530        let cfg = OopGearConfig::new("test_gear", BackendKind::LocalProcess);
531
532        let result = backend.spawn_instance(&cfg).await;
533        assert!(result.is_err());
534        assert!(
535            result
536                .unwrap_err()
537                .to_string()
538                .contains("executable_path must be set")
539        );
540    }
541
542    #[tokio::test]
543    async fn test_spawn_instance_requires_correct_backend() {
544        let backend = test_backend();
545        let mut cfg = OopGearConfig::new("test_gear", BackendKind::K8s);
546        cfg.binary = Some(PathBuf::from("/bin/echo"));
547
548        let result = backend.spawn_instance(&cfg).await;
549        assert!(result.is_err());
550        assert!(
551            result
552                .unwrap_err()
553                .to_string()
554                .contains("can only spawn LocalProcess")
555        );
556    }
557
558    #[tokio::test]
559    async fn test_spawn_list_stop_lifecycle() {
560        let backend = test_backend();
561
562        // Create config with a valid binary that exists on most systems
563        let mut cfg = OopGearConfig::new("test_gear", BackendKind::LocalProcess);
564
565        // Use a simple command that exists cross-platform
566        #[cfg(windows)]
567        let binary = PathBuf::from("C:\\Windows\\System32\\cmd.exe");
568        #[cfg(not(windows))]
569        let binary = PathBuf::from("/bin/sleep");
570
571        cfg.binary = Some(binary);
572        cfg.args = vec!["10".to_owned()]; // sleep for 10 seconds
573
574        // Spawn instance
575        let handle = backend
576            .spawn_instance(&cfg)
577            .await
578            .expect("should spawn instance");
579
580        assert_eq!(handle.gear, "test_gear");
581        assert!(!handle.instance_id.is_nil());
582        assert_eq!(handle.backend, BackendKind::LocalProcess);
583
584        // List instances
585        let instances = backend
586            .list_instances("test_gear")
587            .await
588            .expect("should list instances");
589        assert_eq!(instances.len(), 1);
590        assert_eq!(instances[0].gear, "test_gear");
591        assert_eq!(instances[0].instance_id, handle.instance_id);
592
593        // Stop instance
594        backend
595            .stop_instance(&handle)
596            .await
597            .expect("should stop instance");
598
599        // Verify it's removed
600        let instances = backend
601            .list_instances("test_gear")
602            .await
603            .expect("should list instances");
604        assert_eq!(instances.len(), 0);
605    }
606
607    #[tokio::test]
608    async fn test_list_instances_filters_by_gear() {
609        let backend = test_backend();
610
611        #[cfg(windows)]
612        let binary = PathBuf::from("C:\\Windows\\System32\\cmd.exe");
613        #[cfg(not(windows))]
614        let binary = PathBuf::from("/bin/sleep");
615
616        // Spawn instance for gear_a
617        let mut cfg_a = OopGearConfig::new("gear_a", BackendKind::LocalProcess);
618        cfg_a.binary = Some(binary.clone());
619        cfg_a.args = vec!["10".to_owned()];
620
621        let handle_a = backend
622            .spawn_instance(&cfg_a)
623            .await
624            .expect("should spawn gear_a");
625
626        // Spawn instance for gear_b
627        let mut cfg_b = OopGearConfig::new("gear_b", BackendKind::LocalProcess);
628        cfg_b.binary = Some(binary);
629        cfg_b.args = vec!["10".to_owned()];
630
631        let handle_b = backend
632            .spawn_instance(&cfg_b)
633            .await
634            .expect("should spawn gear_b");
635
636        // List gear_a instances
637        let instances_a = backend
638            .list_instances("gear_a")
639            .await
640            .expect("should list gear_a");
641        assert_eq!(instances_a.len(), 1);
642        assert_eq!(instances_a[0].gear, "gear_a");
643
644        // List gear_b instances
645        let instances_b = backend
646            .list_instances("gear_b")
647            .await
648            .expect("should list gear_b");
649        assert_eq!(instances_b.len(), 1);
650        assert_eq!(instances_b[0].gear, "gear_b");
651
652        // Clean up
653        backend.stop_instance(&handle_a).await.ok();
654        backend.stop_instance(&handle_b).await.ok();
655    }
656
657    #[tokio::test]
658    async fn test_stop_nonexistent_instance() {
659        let backend = test_backend();
660        let handle = InstanceHandle {
661            gear: "test_gear".to_owned(),
662            instance_id: Uuid::new_v4(),
663            backend: BackendKind::LocalProcess,
664            pid: None,
665            created_at: Instant::now(),
666        };
667
668        // Should not error even if instance doesn't exist
669        let result = backend.stop_instance(&handle).await;
670        assert!(result.is_ok());
671    }
672
673    #[tokio::test]
674    async fn test_list_instances_empty() {
675        let backend = test_backend();
676        let instances = backend
677            .list_instances("nonexistent_gear")
678            .await
679            .expect("should list instances");
680        assert_eq!(instances.len(), 0);
681    }
682
683    mod send_terminate_signal_tests {
684        #[cfg(unix)]
685        use {super::send_terminate_signal, std::time::Duration};
686
687        #[cfg(unix)]
688        #[tokio::test]
689        async fn test_send_terminate_signal_to_valid_process() {
690            // Spawn a long-running process
691            let mut cmd = tokio::process::Command::new("sleep");
692            cmd.args(["30"]);
693
694            let mut child = cmd.spawn().expect("should spawn test process");
695
696            // Send termination signal
697            let result = send_terminate_signal(&child);
698
699            // Should return true indicating signal was sent
700            assert!(result, "Should successfully send SIGTERM to valid process");
701
702            // Wait briefly for graceful shutdown
703            tokio::time::timeout(Duration::from_secs(1), child.wait())
704                .await
705                .expect("process should exit within timeout")
706                .expect("wait should succeed");
707        }
708
709        #[cfg(unix)]
710        #[tokio::test]
711        async fn test_send_terminate_signal_to_exited_process() {
712            // Spawn a process that exits immediately using sh -c 'exit 0'
713            // This works on all Unix systems (Linux, macOS, BSD)
714            let mut cmd = tokio::process::Command::new("/bin/sh");
715            cmd.args(["-c", "exit 0"]);
716            let mut child = cmd.spawn().expect("should spawn test process");
717
718            // Wait for it to exit
719            tokio::time::timeout(Duration::from_secs(2), child.wait())
720                .await
721                .expect("process should exit within timeout")
722                .expect("wait should succeed");
723
724            // Try to send termination signal to exited process
725            let result = send_terminate_signal(&child);
726
727            // Should return false because PID is no longer available
728            assert!(!result, "Should return false for already-exited process");
729        }
730
731        #[cfg(unix)]
732        #[test]
733        fn test_pid_conversion_edge_case_documentation() {
734            // This test documents the edge case behavior for PIDs > i32::MAX
735            // In practice, this is extremely rare as it would require:
736            // 1. System uptime of weeks/months without reboot
737            // 2. PID counter to wrap around multiple times
738            // 3. Specific kernel configuration
739
740            // The maximum value a u32 PID can have
741            let max_u32_pid: u32 = u32::MAX;
742
743            // This would fail to convert to i32
744            let result = i32::try_from(max_u32_pid);
745            assert!(result.is_err(), "u32::MAX should not fit in i32");
746
747            // Our code handles this by logging a warning and returning false
748            // preventing the dangerous unwrap_or(0) that would signal PID 0
749        }
750
751        #[cfg(unix)]
752        #[test]
753        fn test_pid_conversion_normal_range() {
754            // Test that normal PIDs convert successfully
755            let normal_pid: u32 = 12345;
756            let result = i32::try_from(normal_pid);
757            assert!(result.is_ok(), "Normal PID should convert to i32");
758            assert_eq!(result.unwrap(), 12345);
759        }
760    }
761
762    /// A process ignoring SIGTERM, for the grace-period paths, and the marker
763    /// file it creates once it ignores it: see [`ignoring_sigterm`].
764    #[cfg(unix)]
765    fn stubborn() -> (OopGearConfig, PathBuf) {
766        let marker = std::env::temp_dir().join(format!("stubborn-{}", Uuid::new_v4()));
767        let mut cfg = OopGearConfig::new("stubborn", BackendKind::LocalProcess);
768        cfg.binary = Some(PathBuf::from("/bin/sh"));
769        // `exec`: the tracked process is the one ignoring SIGTERM, with no
770        // untracked grandchild left behind by a kill. An ignored signal stays
771        // ignored across `exec`.
772        cfg.args = vec![
773            "-c".to_owned(),
774            r#"trap '' TERM; : > "$1"; exec sleep 60"#.to_owned(),
775            "stubborn".to_owned(),
776            marker.display().to_string(),
777        ];
778        (cfg, marker)
779    }
780
781    /// Wait until the stubborn child ignores SIGTERM, then remove its marker.
782    #[cfg(unix)]
783    async fn ignoring_sigterm(marker: &std::path::Path) {
784        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
785        while !marker.exists() {
786            assert!(
787                tokio::time::Instant::now() < deadline,
788                "the stubborn child never installed its SIGTERM trap"
789            );
790            tokio::time::sleep(Duration::from_millis(10)).await;
791        }
792        std::fs::remove_file(marker).ok();
793    }
794
795    #[cfg(unix)]
796    fn alive(pid: u32) -> bool {
797        std::process::Command::new("kill")
798            .args(["-0", &pid.to_string()])
799            .status()
800            .is_ok_and(|status| status.success())
801    }
802
803    /// `stop_all` racing the cancellation watcher returns only once the child
804    /// ended, though the watcher took the instances first.
805    #[cfg(unix)]
806    #[tokio::test]
807    async fn stop_all_waits_for_a_shutdown_the_watcher_began() {
808        let cancel = CancellationToken::new();
809        let backend = LocalProcessBackend::new(cancel.clone());
810        let (stubborn_cfg, marker) = stubborn();
811        let handle = backend.spawn_instance(&stubborn_cfg).await.expect("spawn");
812        let pid = handle.pid.expect("a pid");
813        ignoring_sigterm(&marker).await;
814
815        cancel.cancel();
816        while backend.instances.read().contains_key(&handle.instance_id) {
817            tokio::task::yield_now().await;
818        }
819        backend.stop_all().await;
820
821        assert!(!alive(pid), "the child ended before stop_all returned");
822        assert!(
823            backend.spawn_instance(&stubborn().0).await.is_err(),
824            "no spawn after shutdown"
825        );
826    }
827
828    /// Dropping the backend stops its children though the caller's token,
829    /// which it only borrows, stays live.
830    #[cfg(unix)]
831    #[tokio::test]
832    async fn dropping_the_backend_stops_its_children() {
833        let cancel = CancellationToken::new();
834        let backend = LocalProcessBackend::new(cancel.clone());
835        let mut cfg = OopGearConfig::new("sleeper", BackendKind::LocalProcess);
836        cfg.binary = Some(PathBuf::from("/bin/sleep"));
837        cfg.args = vec!["60".to_owned()];
838        let pid = backend
839            .spawn_instance(&cfg)
840            .await
841            .expect("spawn")
842            .pid
843            .expect("a pid");
844
845        drop(backend);
846
847        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
848        while alive(pid) {
849            assert!(
850                tokio::time::Instant::now() < deadline,
851                "the child outlived the backend"
852            );
853            tokio::time::sleep(Duration::from_millis(50)).await;
854        }
855        assert!(!cancel.is_cancelled());
856    }
857
858    /// A `stop_all` abandoned mid-run — its future dropped while the stubborn
859    /// child sits in its grace period — and then the backend dropped: the run
860    /// belongs to its own task, so the child still ends.
861    #[cfg(unix)]
862    #[tokio::test]
863    async fn an_abandoned_stop_all_still_stops_the_child() {
864        let cancel = CancellationToken::new();
865        let backend = LocalProcessBackend::new(cancel.clone());
866        let (stubborn_cfg, marker) = stubborn();
867        let handle = backend.spawn_instance(&stubborn_cfg).await.expect("spawn");
868        let pid = handle.pid.expect("a pid");
869        ignoring_sigterm(&marker).await;
870
871        let stopping = tokio::time::timeout(Duration::from_millis(200), backend.stop_all()).await;
872        assert!(
873            stopping.is_err(),
874            "abandoned while the child ignores SIGTERM"
875        );
876        assert!(
877            backend.instances.read().is_empty(),
878            "the run took the instances"
879        );
880        drop(backend);
881
882        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
883        while alive(pid) {
884            assert!(
885                tokio::time::Instant::now() < deadline,
886                "the child outlived the abandoned stop"
887            );
888            tokio::time::sleep(Duration::from_millis(50)).await;
889        }
890        assert!(!cancel.is_cancelled());
891    }
892    /// A shutdown run that panics still ends every wait for it.
893    #[tokio::test]
894    async fn a_panicking_shutdown_run_releases_its_waiters() {
895        let shutdown = Arc::new(Shutdown {
896            instances: Arc::new(RwLock::new(HashMap::new())),
897            stopping: std::sync::atomic::AtomicBool::new(false),
898            started: std::sync::atomic::AtomicBool::new(false),
899            done: tokio::sync::watch::Sender::new(false),
900        });
901
902        let first = tokio::time::timeout(
903            Duration::from_secs(5),
904            shutdown.run_with(|_| Box::pin(async { panic!("the run failed") })),
905        )
906        .await;
907        let second = tokio::time::timeout(Duration::from_secs(5), shutdown.run()).await;
908
909        assert!(first.is_ok(), "the waiter of the panicking run returns");
910        assert!(second.is_ok(), "a later waiter returns too");
911    }
912}