1#[allow(
29 unused_imports,
30 clippy::wildcard_imports,
31 reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use crate::auth::capability::CapabilityBundle;
36use crate::error::Error;
37use crate::peer::IpcPeer;
38use crate::services::process::SERVICE_NAME as PROCESS_SERVICE_NAME;
39use crate::services::process::api::{
40 METHOD_SHUTDOWN_TREE, ShutdownTreeRequest, ShutdownTreeResponse,
41};
42use crate::types::{ConnectionId, ProcessId};
43use async_trait::async_trait;
44use ipc::ChildKind;
45use serde::{Deserialize, Serialize};
46use std::collections::HashMap;
47use std::future::Future;
48use std::sync::Arc;
49use std::time::Duration;
50use tokio::time;
51
52pub mod unix;
53pub mod windows;
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct SpawnParams {
58 pub kind: ChildKind,
59 pub parent: Option<ProcessId>,
61 pub program: Option<String>,
63 pub args: Vec<String>,
65 pub env: Vec<(String, String)>,
67 pub cwd: Option<String>,
69 pub capabilities: CapabilityBundle,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct ChildHandle {
76 pub pid: ProcessId,
77 pub kind: ChildKind,
78 pub parent: Option<ProcessId>,
79 pub connection: Option<ConnectionId>,
80}
81
82#[async_trait]
85pub trait ProcessManager: Send + Sync + std::fmt::Debug {
86 async fn spawn_child(
87 &self,
88 params: SpawnParams,
89 ) -> Result<ChildHandle, Error>;
90
91 async fn attach_connection(
92 &self,
93 pid: ProcessId,
94 conn: ConnectionId,
95 ) -> Result<(), Error>;
96
97 async fn list_children(&self) -> Result<Vec<ChildHandle>, Error>;
98
99 async fn terminate_tree(
102 &self,
103 pid: ProcessId,
104 force: bool,
105 ) -> Result<(), Error>;
106
107 async fn wait_for_exit(
116 &self,
117 _pid: ProcessId,
118 timeout: Duration,
119 ) -> Result<bool, Error> {
120 time::sleep(timeout).await;
121 Ok(false)
122 }
123
124 async fn kill_tree(&self, pid: ProcessId) -> Result<(), Error> {
128 self.terminate_tree(pid, true).await
129 }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct GracefulShutdownOutcome {
135 pub acknowledged: bool,
137 pub exited: bool,
139 pub forced: bool,
141}
142
143pub async fn graceful_shutdown_tree<F, Fut>(
157 process_manager: &dyn ProcessManager,
158 pid: ProcessId,
159 send_shutdown: F,
160 ack_timeout: Duration,
161 exit_timeout: Duration,
162) -> Result<GracefulShutdownOutcome, Error>
163where
164 F: FnOnce() -> Fut + Send,
165 Fut: Future<Output = Result<ShutdownTreeResponse, Error>> + Send,
166{
167 let already_exited = process_manager
171 .wait_for_exit(pid, Duration::from_millis(0))
172 .await?;
173 if already_exited {
174 return Ok(GracefulShutdownOutcome {
175 acknowledged: false,
176 exited: true,
177 forced: false,
178 });
179 }
180
181 let acknowledged = match time::timeout(ack_timeout, send_shutdown()).await {
182 Ok(Ok(resp)) => resp.acknowledged,
183 Ok(Err(_)) => {
184 let exited =
185 process_manager.wait_for_exit(pid, exit_timeout).await?;
186 if exited {
187 return Ok(GracefulShutdownOutcome {
188 acknowledged: false,
189 exited: true,
190 forced: false,
191 });
192 }
193 false
194 }
195 Err(_elapsed) => false,
196 };
197
198 if acknowledged {
199 let exited = process_manager.wait_for_exit(pid, exit_timeout).await?;
200 if exited {
201 return Ok(GracefulShutdownOutcome {
202 acknowledged,
203 exited,
204 forced: false,
205 });
206 }
207 } else {
208 let exited = process_manager
209 .wait_for_exit(pid, Duration::from_millis(0))
210 .await?;
211 if exited {
212 return Ok(GracefulShutdownOutcome {
213 acknowledged: false,
214 exited: true,
215 forced: false,
216 });
217 }
218 }
219
220 process_manager.kill_tree(pid).await?;
221 let exited = process_manager.wait_for_exit(pid, exit_timeout).await?;
222
223 Ok(GracefulShutdownOutcome {
224 acknowledged,
225 exited,
226 forced: true,
227 })
228}
229
230async fn send_shutdown_request(
236 #[expect(
237 clippy::implicit_hasher,
238 reason = "uniform peer dictionary mapping type interface"
239 )]
240 peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
241 pid: ProcessId,
242 reason: Option<String>,
243) -> Result<ShutdownTreeResponse, Error> {
244 let req = ShutdownTreeRequest { reason };
245 let args = postcard_helpers::encode(&req, "shutdown request")
246 .map_err(|e| crate::error::Error::Serialization(e.to_string()))?;
247
248 let (parent_peer, other_peers) = {
249 let guard = peers.lock().await;
250 let parent_peer = guard.get(&pid).cloned().ok_or_else(|| {
251 crate::error::Error::Internal("target peer not connected".into())
252 })?;
253
254 let mut others: Vec<Arc<IpcPeer>> = Vec::new();
255 for (peer_pid, peer) in &*guard {
256 if *peer_pid != pid {
257 others.push(Arc::clone(peer));
258 }
259 }
260
261 (parent_peer, others)
262 };
263
264 for peer in other_peers {
267 let args_clone = args.clone();
268 drop(tokio::spawn(async move {
269 let _ = peer
270 .call(
271 crate::protocol::MethodId {
272 service: PROCESS_SERVICE_NAME.into(),
273 method: METHOD_SHUTDOWN_TREE.into(),
274 },
275 args_clone,
276 )
277 .await;
278 }));
279 }
280
281 let resp = parent_peer
282 .call(
283 crate::protocol::MethodId {
284 service: PROCESS_SERVICE_NAME.into(),
285 method: METHOD_SHUTDOWN_TREE.into(),
286 },
287 args,
288 )
289 .await?;
290
291 if !resp.ok {
292 return Err(Error::from(resp));
293 }
294
295 let Some(bytes) = resp.result else {
296 return Err(Error::Serialization(
297 "missing result payload in shutdown response".into(),
298 ));
299 };
300
301 postcard_helpers::decode::<ShutdownTreeResponse>(
302 &bytes,
303 "shutdown response",
304 )
305 .map_err(|e| crate::error::Error::Serialization(e.to_string()))
306}
307
308pub async fn shutdown_for_process_tree(
313 #[expect(
314 clippy::implicit_hasher,
315 reason = "uniform peer dictionary mapping type interface"
316 )]
317 peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
318 process_manager: &dyn ProcessManager,
319 pid: ProcessId,
320 ack_timeout: Duration,
321 exit_timeout: Duration,
322 reason: Option<String>,
323) -> Result<GracefulShutdownOutcome, Error> {
324 graceful_shutdown_tree(
325 process_manager,
326 pid,
327 || send_shutdown_request(Arc::clone(&peers), pid, reason.clone()),
328 ack_timeout,
329 exit_timeout,
330 )
331 .await
332}
333
334#[derive(Debug, Default)]
335pub(crate) struct MockProcessManager {
336 terminated: std::sync::Mutex<Vec<(ProcessId, bool)>>,
337 killed: std::sync::atomic::AtomicUsize,
338 waited: std::sync::atomic::AtomicUsize,
339 exited: Arc<tokio::sync::Notify>,
340}
341
342impl MockProcessManager {
343 pub(crate) fn new(exited: Arc<tokio::sync::Notify>) -> Self {
344 Self {
345 terminated: Default::default(),
346 killed: std::sync::atomic::AtomicUsize::new(0),
347 waited: std::sync::atomic::AtomicUsize::new(0),
348 exited,
349 }
350 }
351
352 pub(crate) fn terminations(&self) -> Vec<(ProcessId, bool)> {
353 if let Ok(guard) = self.terminated.lock() {
354 guard.clone()
355 } else {
356 Vec::new()
357 }
358 }
359}
360
361#[async_trait]
362impl ProcessManager for MockProcessManager {
363 async fn spawn_child(
364 &self,
365 _params: SpawnParams,
366 ) -> Result<ChildHandle, Error> {
367 Ok(ChildHandle {
368 pid: ProcessId::default(),
369 kind: ChildKind::Renderer,
370 parent: None,
371 connection: None,
372 })
373 }
374
375 async fn attach_connection(
376 &self,
377 _pid: ProcessId,
378 _conn: ConnectionId,
379 ) -> Result<(), Error> {
380 Ok(())
381 }
382
383 async fn list_children(&self) -> Result<Vec<ChildHandle>, Error> {
384 Ok(Vec::new())
385 }
386
387 async fn terminate_tree(
388 &self,
389 pid: ProcessId,
390 force: bool,
391 ) -> Result<(), Error> {
392 if let Ok(mut guard) = self.terminated.lock() {
393 guard.push((pid, force));
394 }
395 self.killed
396 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
397 let exited = Arc::new(self.exited.clone());
398 tokio::spawn(async move {
399 time::sleep(Duration::from_millis(1)).await;
400 exited.notify_waiters();
401 });
402 Ok(())
403 }
404
405 async fn wait_for_exit(
406 &self,
407 _pid: ProcessId,
408 timeout: Duration,
409 ) -> Result<bool, Error> {
410 self.waited
411 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
412 match time::timeout(timeout, self.exited.notified()).await {
413 Ok(()) => Ok(true),
414 Err(_elapsed) => Ok(false),
415 }
416 }
417}
418
419#[cfg(unix)]
420pub use unix::TokioProcessManager;
421#[cfg(windows)]
422pub use windows::TokioProcessManager;
423
424#[cfg(test)]
425#[allow(
426 clippy::panic,
427 clippy::expect_used,
428 clippy::unwrap_used,
429 clippy::unwrap_in_result,
430 clippy::panic_in_result_fn,
431 clippy::indexing_slicing,
432 clippy::arithmetic_side_effects,
433 reason = "Standard repository test boilerplate"
434)]
435mod tests {
436 use super::*;
437
438 use anyhow::Result;
439 use std::sync::Arc;
440 use std::sync::atomic::Ordering;
441
442 #[crate::ctb_test("tokio")]
443 async fn graceful_shutdown_cooperative_child() -> Result<()> {
444 let exited = Arc::new(tokio::sync::Notify::new());
445 let pm = MockProcessManager::new(exited.clone());
446 let pid = ProcessId::default();
447
448 let outcome = graceful_shutdown_tree(
449 &pm,
450 pid,
451 || async {
452 let exited = exited.clone();
453 drop(tokio::spawn(async move {
454 time::sleep(Duration::from_millis(10)).await;
455 exited.notify_waiters();
456 }));
457 Ok(ShutdownTreeResponse { acknowledged: true })
458 },
459 Duration::from_millis(50),
460 Duration::from_millis(200),
461 )
462 .await?;
463
464 anyhow::ensure!(
465 outcome
466 == GracefulShutdownOutcome {
467 acknowledged: true,
468 exited: true,
469 forced: false,
470 },
471 "unexpected outcome: {outcome:?}"
472 );
473 anyhow::ensure!(pm.killed.load(Ordering::SeqCst) == 0);
474 anyhow::ensure!(pm.waited.load(Ordering::SeqCst) >= 1);
475 Ok(())
476 }
477
478 #[crate::ctb_test("tokio")]
479 async fn graceful_shutdown_ignoring_child_forces_kill() -> Result<()> {
480 let exited = Arc::new(tokio::sync::Notify::new());
481 let pm = MockProcessManager::new(exited.clone());
482 let pid = ProcessId::default();
483
484 let outcome = graceful_shutdown_tree(
485 &pm,
486 pid,
487 || async {
488 std::future::pending::<Result<ShutdownTreeResponse, Error>>()
489 .await
490 },
491 Duration::from_millis(20),
492 Duration::from_millis(200),
493 )
494 .await?;
495
496 anyhow::ensure!(!outcome.acknowledged);
497 anyhow::ensure!(outcome.forced);
498 anyhow::ensure!(outcome.exited);
499 anyhow::ensure!(pm.killed.load(Ordering::SeqCst) == 1);
500 anyhow::ensure!(pm.waited.load(Ordering::SeqCst) >= 1);
501 Ok(())
502 }
503
504 #[crate::ctb_test("tokio")]
505 async fn graceful_shutdown_closed_connection_child_exits_cleanly()
506 -> Result<()> {
507 let exited = Arc::new(tokio::sync::Notify::new());
508 let pm = MockProcessManager::new(exited.clone());
509 let pid = ProcessId::default();
510
511 let exited_clone = exited.clone();
512 drop(tokio::spawn(async move {
513 time::sleep(Duration::from_millis(10)).await;
514 exited_clone.notify_waiters();
515 }));
516
517 let outcome = graceful_shutdown_tree(
518 &pm,
519 pid,
520 || async {
521 Err(Error::Internal("target peer not connected".into()))
522 },
523 Duration::from_millis(50),
524 Duration::from_millis(200),
525 )
526 .await?;
527
528 anyhow::ensure!(!outcome.acknowledged);
529 anyhow::ensure!(!outcome.forced);
530 anyhow::ensure!(outcome.exited);
531 anyhow::ensure!(pm.killed.load(Ordering::SeqCst) == 0);
532 anyhow::ensure!(pm.waited.load(Ordering::SeqCst) >= 1);
533 Ok(())
534 }
535
536 #[crate::ctb_test("tokio")]
537 async fn graceful_shutdown_closed_connection_child_hung_forces_kill()
538 -> Result<()> {
539 let exited = Arc::new(tokio::sync::Notify::new());
540 let pm = MockProcessManager::new(exited.clone());
541 let pid = ProcessId::default();
542
543 let outcome = graceful_shutdown_tree(
544 &pm,
545 pid,
546 || async {
547 Err(Error::Internal("target peer not connected".into()))
548 },
549 Duration::from_millis(50),
550 Duration::from_millis(200),
551 )
552 .await?;
553
554 anyhow::ensure!(!outcome.acknowledged);
555 anyhow::ensure!(outcome.forced);
556 anyhow::ensure!(outcome.exited);
557 anyhow::ensure!(pm.killed.load(Ordering::SeqCst) == 1);
558 anyhow::ensure!(pm.waited.load(Ordering::SeqCst) >= 1);
559 Ok(())
560 }
561}