ctb_workspace_ipc/
workspace_runner.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Generic workspace runner.
21//!
22//! This module provides a reusable [`WorkspaceRunner`] which encapsulates the
23//! IPC event loop for:
24//! - binding an IPC socket listener
25//! - accepting and handshaking child connections
26//! - routing child-to-parent messages into a workspace loop
27//! - handling spawn requests from children
28//! - requesting graceful shutdown of the workspace process tree
29//!
30//! It runs the workspace's [`Workspace::run`] concurrently with this IPC loop.
31
32#[allow(
33    unused_imports,
34    clippy::wildcard_imports,
35    reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38use crate::workspace_runner::workspace_runtime::{
39    ShutdownState, WorkspaceRuntime,
40};
41
42use std::collections::HashMap;
43use std::sync::Arc;
44use std::time::Duration;
45
46use tokio::sync::mpsc;
47
48use crate::auth::capability::{CapabilitySet, InMemoryTokenValidator};
49use crate::connection::WorkspaceConnectionHandler;
50use crate::multiplex::session::FramedSession;
51use crate::process_manager::{
52    ProcessManager, TokioProcessManager, shutdown_for_process_tree,
53};
54use crate::router::IpcRouter;
55use crate::services::io::IoClient;
56use crate::services::network::NetworkClient;
57use crate::services::parent::api::{ProxyCallRequest, ProxyCallResponse};
58use crate::services::parent::channel::ProxyCallWithResponse;
59use crate::services::parent::{ChannelParentMessenger, ParentRequestContext};
60use crate::services::parent::{
61    ParentMessageEvent, ParentMessageKind, SpawnChildRequest,
62    SpawnChildResponse, SpawnRequestWithResponse,
63};
64use crate::services::process::ShutdownChannelProcessService;
65use crate::services::storage::StorageClient;
66use crate::transport::{
67    LocalSocketFramedConnection, LocalSocketTransportFactory, TransportFactory,
68    TransportListener,
69};
70use crate::types::{ConnectionId, ProcessId};
71use ipc::ChildKind;
72
73use crate::peer::IpcPeer;
74
75pub mod cli;
76pub mod process;
77pub mod workspace_runtime;
78
79/// Container for singleton service dependencies injected into a workspace.
80///
81/// Each field corresponds to a [`ChildKind`] singleton service that can be
82/// requested via [`Workspace::services_needed`]. The runner will start the
83/// requested services and populate this struct before calling
84/// [`Workspace::boot`].
85#[derive(Debug, Clone, Default)]
86pub struct WorkspaceServices {
87    pub network: Option<NetworkClient>,
88    pub io: Option<IoClient>,
89    pub storage: Option<StorageClient>,
90}
91
92impl WorkspaceServices {
93    /// Return the network client.
94    ///
95    /// This returns an error if the workspace did not declare
96    /// [`ChildKind::Network`] in `services_needed()`.
97    pub fn network(&self) -> Result<&NetworkClient> {
98        self.network.as_ref().ok_or_else(|| {
99            anyhow::anyhow!(
100                "NetworkClient not available. Did you request ChildKind::Network in services_needed()?"
101            )
102        })
103    }
104
105    /// Return the IO client.
106    ///
107    /// This returns an error if the workspace did not declare [`ChildKind::Io`]
108    /// in `services_needed()`.
109    pub fn io(&self) -> Result<&IoClient> {
110        self.io.as_ref().ok_or_else(|| {
111            anyhow::anyhow!(
112                "IoClient not available. Did you request ChildKind::Io in services_needed()?"
113            )
114        })
115    }
116
117    /// Return the storage client.
118    ///
119    /// This returns an error if the workspace did not declare
120    /// [`ChildKind::Storage`] in `services_needed()`.
121    pub fn storage(&self) -> Result<&StorageClient> {
122        self.storage.as_ref().ok_or_else(|| {
123            anyhow::anyhow!(
124                "StorageClient not available. Did you request ChildKind::Storage in services_needed()?"
125            )
126        })
127    }
128}
129
130/// Extension trait providing ergonomic service access for workspaces.
131///
132/// Any type implementing [`Workspace`] automatically gets these helper methods.
133pub trait WorkspaceExt: Workspace {
134    /// Access the network client with clean syntax.
135    fn network(&self) -> Result<&NetworkClient> {
136        self.services().network()
137    }
138
139    /// Access the IO client with clean syntax.
140    fn io(&self) -> Result<&IoClient> {
141        self.services().io()
142    }
143
144    /// Access the storage client with clean syntax.
145    fn storage(&self) -> Result<&StorageClient> {
146        self.services().storage()
147    }
148}
149
150impl<W: Workspace> WorkspaceExt for W {}
151
152/// Configuration for the workspace runner.
153#[derive(Debug, Clone)]
154pub struct WorkspaceRunnerConfig {
155    /// Maximum time to wait for shutdown. If `None`, no timeout is enforced.
156    pub timeout: Option<Duration>,
157    /// Time to wait for the listener to start before calling `startup`.
158    pub listener_startup_delay: Duration,
159    /// Buffer size for message channels.
160    pub message_buffer_size: usize,
161    /// Buffer size for spawn request channels.
162    pub spawn_buffer_size: usize,
163    /// Event loop tick interval.
164    pub tick_interval: Duration,
165    /// Maximum time to wait for a child to connect before failing calls.
166    pub connect_timeout: Duration,
167    /// Grace period to allow a subtree to exit after acknowledging shutdown.
168    pub shutdown_grace: Duration,
169    /// How long to wait for a shutdown acknowledgement.
170    pub shutdown_ack_timeout: Duration,
171}
172
173impl Default for WorkspaceRunnerConfig {
174    fn default() -> Self {
175        Self {
176            timeout: None,
177            listener_startup_delay: Duration::from_millis(50),
178            message_buffer_size: 32,
179            spawn_buffer_size: 8,
180            tick_interval: Duration::from_millis(100),
181            connect_timeout: Duration::from_secs(5),
182            shutdown_grace: Duration::from_secs(30),
183            shutdown_ack_timeout: Duration::from_secs(1),
184        }
185    }
186}
187
188impl WorkspaceRunnerConfig {
189    /// Returns the default configuration with a timeout set.
190    pub fn default_with_timeout() -> Self {
191        Self {
192            timeout: Some(Duration::from_secs(10)),
193            ..Self::default()
194        }
195    }
196}
197
198/// Statistics collected during workspace execution.
199#[derive(Debug, Clone, Default)]
200pub struct WorkspaceStats {
201    /// Number of data-plane messages received from children.
202    pub data_plane_messages_received: usize,
203    /// Whether a shutdown was received.
204    pub shutdown_received: bool,
205    /// Reason for shutdown, if one was provided.
206    pub shutdown_reason: Option<String>,
207    /// Whether the runner had to force-terminate any process tree.
208    pub forced_termination: bool,
209}
210
211/// Identifies the sender of a spawn request.
212#[derive(Debug, Clone)]
213pub struct SpawnRequester {
214    pub ctx: ParentRequestContext,
215    /// Process id for the requester if it has been attached.
216    pub pid: Option<ProcessId>,
217}
218
219/// Decision returned by a workspace when evaluating a spawn request.
220#[derive(Debug, Clone)]
221pub enum SpawnRequestDecision {
222    Reject {
223        error: Option<String>,
224    },
225    Accept {
226        /// Optional override for the parent pid.
227        parent: Option<ProcessId>,
228        /// Capabilities bound to the spawned child's control connection.
229        caps: CapabilitySet,
230        /// Extra arguments to pass.
231        extra_args: Vec<String>,
232    },
233}
234
235/// Workspace behavior that can be plugged into [`WorkspaceRunner`].
236///
237/// Implementors should store a `WorkspaceServices` field and provide access
238/// via the `services()` and `set_services()` methods. The runner will call
239/// `set_services()` before `boot()` to inject the started services.
240#[async_trait::async_trait]
241pub trait Workspace: Send + Sync {
242    /// Return the list of singleton services this workspace needs.
243    ///
244    /// The runner will start these services before calling [`Workspace::boot`]
245    /// and inject them via `set_services`.
246    fn services_needed(&self) -> Vec<(ChildKind, CapabilitySet)> {
247        Vec::new()
248    }
249
250    /// Return the services container. Used by helper methods.
251    fn services(&self) -> &WorkspaceServices;
252
253    /// Set the services container. Called by the runner before `boot()`.
254    fn set_services(&mut self, services: WorkspaceServices);
255
256    /// Called after the IPC listener is bound and accepting connections.
257    async fn boot(&mut self, rt: &WorkspaceRuntime) -> Result<()>;
258
259    /// Main application task for the workspace.
260    ///
261    /// Simply explained:
262    /// - The runner has an internal IPC loop (accepts connections, routes
263    ///   messages, handles spawn/proxy calls).
264    /// - Your `run()` executes concurrently with that IPC loop.
265    /// - If you want `run()` to stay alive until shutdown, await
266    ///   `rt.wait_for_shutdown()` (usually via `tokio::select!`).
267    ///
268    /// Returning from `run()` will request workspace shutdown.
269    async fn run(&self, rt: &WorkspaceRuntime) -> Result<()>;
270
271    /// Called for each child-to-parent message.
272    async fn on_parent_message(
273        &self,
274        rt: &WorkspaceRuntime,
275        event: ParentMessageEvent,
276    ) -> Result<()>;
277
278    /// Evaluate a spawn request.
279    async fn evaluate_spawn_request(
280        &self,
281        rt: &WorkspaceRuntime,
282        requester: SpawnRequester,
283        request: SpawnChildRequest,
284    ) -> Result<SpawnRequestDecision>;
285}
286
287/// Encapsulates the workspace's main event loop and lifecycle management.
288#[derive(Debug)]
289pub struct WorkspaceRunner<W: Workspace> {
290    workspace: W,
291    config: WorkspaceRunnerConfig,
292    socket_path: String,
293    validator: Arc<InMemoryTokenValidator>,
294    router: Arc<IpcRouter>,
295    process_manager: Arc<TokioProcessManager>,
296    exe: Arc<std::path::PathBuf>,
297    pending_processes: Arc<tokio::sync::Mutex<HashMap<String, ProcessId>>>,
298    peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
299    pid_by_conn: Arc<tokio::sync::Mutex<HashMap<ConnectionId, ProcessId>>>,
300    root_pids: Arc<tokio::sync::Mutex<Vec<ProcessId>>>,
301    singleton_pids: Arc<tokio::sync::Mutex<HashMap<ChildKind, ProcessId>>>,
302    messages_rx: mpsc::Receiver<ParentMessageEvent>,
303    spawn_requests_rx: mpsc::Receiver<SpawnRequestWithResponse>,
304    proxy_calls_rx: mpsc::Receiver<ProxyCallWithResponse>,
305    shutdown_tx: mpsc::Sender<Option<String>>,
306    shutdown_rx: mpsc::Receiver<Option<String>>,
307    shutdown_state: Arc<tokio::sync::Mutex<ShutdownState>>,
308    shutdown_notify: Arc<tokio::sync::Notify>,
309}
310
311impl<W: Workspace> WorkspaceRunner<W> {
312    /// Create a new runner.
313    ///
314    /// If `router` is provided, the runner will install its own
315    /// parent-messenger and process-service into it.
316    pub fn new(
317        workspace: W,
318        config: WorkspaceRunnerConfig,
319        exe: Arc<std::path::PathBuf>,
320        router: Option<IpcRouter>,
321    ) -> Self {
322        let (messages_tx, messages_rx) =
323            mpsc::channel::<ParentMessageEvent>(config.message_buffer_size);
324        let (spawn_requests_tx, spawn_requests_rx) =
325            mpsc::channel::<SpawnRequestWithResponse>(config.spawn_buffer_size);
326        let (proxy_calls_tx, proxy_calls_rx) =
327            mpsc::channel::<ProxyCallWithResponse>(config.spawn_buffer_size);
328        let (shutdown_tx, shutdown_rx) = mpsc::channel::<Option<String>>(1);
329        let runtime_shutdown_tx = shutdown_tx.clone();
330
331        let shutdown_state =
332            Arc::new(tokio::sync::Mutex::new(ShutdownState::default()));
333        let shutdown_notify = Arc::new(tokio::sync::Notify::new());
334
335        let parent_messenger = Arc::new(ChannelParentMessenger::new(
336            messages_tx,
337            spawn_requests_tx,
338            proxy_calls_tx,
339        ));
340        let process_service =
341            Arc::new(ShutdownChannelProcessService::new(shutdown_tx));
342
343        // Reason for fallback: unconfigured IPC router builder defaults to empty router configuration
344        let router = router
345            .unwrap_or_default()
346            .with_parent_messenger(parent_messenger)
347            .with_process_service(process_service);
348
349        let validator = Arc::new(InMemoryTokenValidator::new());
350        let socket_path = crate::transport::unique_endpoint("workspace");
351        let process_manager = TokioProcessManager::new();
352
353        Self {
354            workspace,
355            config,
356            socket_path,
357            validator,
358            router: Arc::new(router),
359            process_manager,
360            exe,
361            pending_processes: Arc::new(
362                tokio::sync::Mutex::new(HashMap::new()),
363            ),
364            peers: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
365            pid_by_conn: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
366            root_pids: Arc::new(tokio::sync::Mutex::new(Vec::new())),
367            singleton_pids: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
368            messages_rx,
369            spawn_requests_rx,
370            proxy_calls_rx,
371            shutdown_tx: runtime_shutdown_tx,
372            shutdown_rx,
373            shutdown_state,
374            shutdown_notify,
375        }
376    }
377
378    /// Socket path for this workspace.
379    pub fn socket_path(&self) -> &str {
380        &self.socket_path
381    }
382
383    #[expect(dead_code, reason = "potentially unused API helper")]
384    fn runtime(&self) -> WorkspaceRuntime {
385        WorkspaceRuntime {
386            socket_path: self.socket_path.clone(),
387            validator: Arc::clone(&self.validator),
388            process_manager: Arc::clone(&self.process_manager),
389            exe: Arc::clone(&self.exe),
390            config: self.config.clone(),
391            pending_processes: Arc::clone(&self.pending_processes),
392            peers: Arc::clone(&self.peers),
393            pid_by_conn: Arc::clone(&self.pid_by_conn),
394            root_pids: Arc::clone(&self.root_pids),
395            singleton_pids: Arc::clone(&self.singleton_pids),
396            shutdown_tx: self.shutdown_tx.clone(),
397            shutdown_state: Arc::clone(&self.shutdown_state),
398            shutdown_notify: Arc::clone(&self.shutdown_notify),
399        }
400    }
401
402    /// Run the workspace to completion.
403    ///
404    /// Simply explained: there are two things happening at once:
405    /// - the IPC loop (accepting connections + routing messages)
406    /// - your workspace `run()` function
407    ///
408    /// The IPC loop starts first, then `run()` is awaited concurrently.
409    #[expect(
410        clippy::too_many_lines,
411        reason = "uniform runner run loop is naturally long"
412    )]
413    pub async fn run(self) -> Result<WorkspaceStats> {
414        // Simply explained: this function is the "real" top-level loop.
415        //
416        // It starts the IPC listener + routing loop, then runs the workspace
417        // application logic concurrently.
418        let WorkspaceRunner {
419            mut workspace,
420            config,
421            socket_path,
422            validator,
423            router,
424            process_manager,
425            exe,
426            pending_processes,
427            peers,
428            pid_by_conn,
429            root_pids,
430            singleton_pids,
431            messages_rx,
432            spawn_requests_rx,
433            proxy_calls_rx,
434            shutdown_tx,
435            shutdown_rx,
436            shutdown_state,
437            shutdown_notify,
438        } = self;
439
440        debug_fmt!("Starting workspace runner on socket: {}", socket_path);
441
442        #[cfg(unix)]
443        let _ = std::fs::remove_file(&socket_path);
444
445        let factory = LocalSocketTransportFactory;
446        let listener = factory.bind(&socket_path).await?;
447        let listener: Arc<
448            dyn TransportListener<Conn = LocalSocketFramedConnection>,
449        > = Arc::from(listener);
450
451        let accept_task = Self::spawn_accept_task(
452            Arc::clone(&router),
453            Arc::clone(&validator),
454            Arc::clone(&listener),
455            Arc::clone(&pending_processes),
456            Arc::clone(&peers),
457            Arc::clone(&pid_by_conn),
458            Arc::clone(&process_manager),
459        );
460        tokio::time::sleep(config.listener_startup_delay).await;
461
462        let rt = WorkspaceRuntime {
463            socket_path: socket_path.clone(),
464            validator: Arc::clone(&validator),
465            process_manager: Arc::clone(&process_manager),
466            exe: Arc::clone(&exe),
467            config: config.clone(),
468            pending_processes: Arc::clone(&pending_processes),
469            peers: Arc::clone(&peers),
470            pid_by_conn: Arc::clone(&pid_by_conn),
471            root_pids: Arc::clone(&root_pids),
472            singleton_pids: Arc::clone(&singleton_pids),
473            shutdown_tx: shutdown_tx.clone(),
474            shutdown_state: Arc::clone(&shutdown_state),
475            shutdown_notify: Arc::clone(&shutdown_notify),
476        };
477
478        // Start requested singleton services and build WorkspaceServices
479        let requested_services = workspace.services_needed();
480        let services =
481            Self::start_requested_services_static(&rt, &requested_services)
482                .await?;
483
484        workspace.set_services(services);
485
486        workspace.boot(&rt).await?;
487
488        // Run the IPC routing loop and the workspace application concurrently.
489        //
490        // Simply explained: shutdown can arrive (from a child) while the workspace
491        // is still awaiting some in-flight RPC. If we immediately proceed to
492        // tear down subprocess trees, those RPCs can fail with transport errors
493        // (e.g. broken pipe).
494        //
495        // So if the event loop ends first, we give `run()` a grace period to
496        // finish before shutting down process trees.
497        let event_loop = Self::run_event_loop_static(
498            &workspace,
499            &rt,
500            config.clone(),
501            messages_rx,
502            spawn_requests_rx,
503            proxy_calls_rx,
504            shutdown_rx,
505        );
506        tokio::pin!(event_loop);
507
508        let app_fut = workspace.run(&rt);
509        tokio::pin!(app_fut);
510
511        let mut stats = tokio::select! {
512            app_res = &mut app_fut => {
513                app_res?;
514                // If the app returns, request shutdown so the IPC loop exits.
515                let _ = rt
516                    .request_shutdown(Some("workspace run() returned".into()))
517                    .await;
518                event_loop.await?
519            }
520            stats_res = &mut event_loop => {
521                let stats = stats_res?;
522
523                match tokio::time::timeout(config.shutdown_grace, &mut app_fut).await {
524                    Ok(app_res) => {
525                        app_res?;
526                    }
527                    Err(_) => {
528                        warn_fmt!(
529                            "workspace run() did not exit within shutdown grace; canceling"
530                        );
531                    }
532                }
533
534                stats
535            }
536        };
537
538        // Ask each root process tree to shut down.
539        let roots = root_pids.lock().await.clone();
540        for pid in roots {
541            let outcome = shutdown_for_process_tree(
542                Arc::clone(&peers),
543                process_manager.as_ref(),
544                pid,
545                config.shutdown_ack_timeout,
546                config.shutdown_grace,
547                Some("workspace shutdown".into()),
548            )
549            .await
550            .map_err(|e| {
551                anyhow::anyhow!("shutdown_for_process_tree failed: {e:#}")
552            })?;
553
554            if outcome.forced {
555                stats.forced_termination = true;
556            }
557        }
558
559        listener.close().await?;
560        accept_task.abort();
561
562        #[cfg(unix)]
563        let _ = std::fs::remove_file(&socket_path);
564
565        Ok(stats)
566    }
567
568    /// Start all requested singleton services and return a `WorkspaceServices`.
569    async fn start_requested_services_static(
570        rt: &WorkspaceRuntime,
571        requested: &[(ChildKind, CapabilitySet)],
572    ) -> Result<WorkspaceServices> {
573        let mut services = WorkspaceServices::default();
574
575        for (kind, caps) in requested {
576            match kind {
577                ChildKind::Network => {
578                    let proc =
579                        rt.start_singleton_service(*kind, caps.clone()).await?;
580                    services.network = Some(NetworkClient::from_child(proc));
581                }
582                ChildKind::Io => {
583                    let proc =
584                        rt.start_singleton_service(*kind, caps.clone()).await?;
585                    services.io = Some(IoClient::from_child(proc));
586                }
587                ChildKind::Storage => {
588                    let proc =
589                        rt.start_singleton_service(*kind, caps.clone()).await?;
590                    services.storage = Some(StorageClient::from_child(proc));
591                }
592                _ => {
593                    log_fmt!("Unexpected service kind requested: {kind:?}");
594                }
595            }
596        }
597
598        Ok(services)
599    }
600
601    fn spawn_accept_task(
602        router: Arc<IpcRouter>,
603        validator: Arc<InMemoryTokenValidator>,
604        listener: Arc<
605            dyn TransportListener<Conn = LocalSocketFramedConnection>,
606        >,
607        pending: Arc<tokio::sync::Mutex<HashMap<String, ProcessId>>>,
608        peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
609        pid_by_conn: Arc<tokio::sync::Mutex<HashMap<ConnectionId, ProcessId>>>,
610        process_manager: Arc<TokioProcessManager>,
611    ) -> tokio::task::JoinHandle<()> {
612        let handler = WorkspaceConnectionHandler::new(router, validator);
613
614        tokio::spawn(async move {
615            loop {
616                let conn = match listener.accept().await {
617                    Ok(Some(c)) => c,
618                    Ok(None) => break,
619                    Err(e) => {
620                        warn_fmt!("Accept error: {e:#}");
621                        continue;
622                    }
623                };
624
625                let conn = Arc::new(conn);
626                let session = Arc::new(FramedSession::new(conn));
627                let conn_id = ConnectionId::new();
628
629                let handler = handler.clone();
630                let pending = Arc::clone(&pending);
631                let peers = Arc::clone(&peers);
632                let pid_by_conn = Arc::clone(&pid_by_conn);
633                let process_manager = Arc::clone(&process_manager);
634
635                tokio::spawn(async move {
636                    let process_manager: &dyn ProcessManager =
637                        process_manager.as_ref();
638
639                    let peer = match handler.accept_peer(session, conn_id).await
640                    {
641                        Ok(peer) => peer,
642                        Err(e) => {
643                            warn_fmt!("Handshake failed: {e:#}");
644                            return;
645                        }
646                    };
647
648                    match handler
649                        .attach_peer_by_process_kind(
650                            conn_id,
651                            Arc::clone(&peer),
652                            process_manager,
653                            pending.as_ref(),
654                            peers.as_ref(),
655                        )
656                        .await
657                    {
658                        Ok(Some(pid)) => {
659                            pid_by_conn.lock().await.insert(conn_id, pid);
660                        }
661                        Ok(None) => {}
662                        Err(e) => {
663                            warn_fmt!(
664                                "attach_peer_by_process_kind failed: {e:#}"
665                            );
666                        }
667                    }
668                });
669            }
670        })
671    }
672
673    async fn run_event_loop_static(
674        workspace: &W,
675        rt: &WorkspaceRuntime,
676        config: WorkspaceRunnerConfig,
677        mut messages_rx: mpsc::Receiver<ParentMessageEvent>,
678        mut spawn_requests_rx: mpsc::Receiver<SpawnRequestWithResponse>,
679        mut proxy_calls_rx: mpsc::Receiver<ProxyCallWithResponse>,
680        mut shutdown_rx: mpsc::Receiver<Option<String>>,
681    ) -> Result<WorkspaceStats> {
682        let mut stats = WorkspaceStats::default();
683        let start = std::time::Instant::now();
684
685        while !stats.shutdown_received {
686            if let Some(timeout) = config.timeout {
687                if start.elapsed() >= timeout {
688                    break;
689                }
690            }
691
692            tokio::select! {
693                maybe_msg = messages_rx.recv() => {
694                    let Some(event) = maybe_msg else {
695                        break;
696                    };
697
698                    if event.message.kind == ParentMessageKind::DataPlane {
699                        stats.data_plane_messages_received =
700                            stats.data_plane_messages_received.saturating_add(1);
701                    }
702
703                    if event.message.kind == ParentMessageKind::ShutdownRequest {
704                        stats.shutdown_received = true;
705                        if let Ok(sr) = event.message.as_shutdown_request() {
706                            stats.shutdown_reason = sr.reason;
707                        }
708                        rt.notify_shutdown(stats.shutdown_reason.clone()).await;
709                    }
710
711                    workspace.on_parent_message(rt, event).await?;
712                }
713                maybe_spawn = spawn_requests_rx.recv() => {
714                    let Some(req) = maybe_spawn else {
715                        break;
716                    };
717                    Self::handle_spawn_request_static(workspace, rt, req).await;
718                }
719                maybe_proxy = proxy_calls_rx.recv() => {
720                    let Some(req) = maybe_proxy else {
721                        break;
722                    };
723                    Self::handle_proxy_call_static(rt, req).await;
724                }
725                maybe_reason = shutdown_rx.recv() => {
726                    let Some(reason) = maybe_reason else {
727                        break;
728                    };
729                    stats.shutdown_received = true;
730                    stats.shutdown_reason = reason;
731                    rt.notify_shutdown(stats.shutdown_reason.clone()).await;
732                }
733                () = tokio::time::sleep(config.tick_interval) => {}
734            }
735        }
736
737        Ok(stats)
738    }
739
740    async fn handle_proxy_call_static(
741        rt: &WorkspaceRuntime,
742        req: ProxyCallWithResponse,
743    ) {
744        let ProxyCallWithResponse {
745            ctx,
746            request,
747            response_tx,
748        } = req;
749
750        let requester_pid = rt.pid_for_connection(ctx.connection_id).await;
751        let Some(requester_pid) = requester_pid else {
752            let _ = response_tx.send(ProxyCallResponse {
753                ok: false,
754                result: None,
755                error: Some(crate::protocol::RpcError {
756                    code: "unauthorized".into(),
757                    message: "unknown requester pid".into(),
758                }),
759            });
760            return;
761        };
762
763        let is_singleton_target = {
764            let singleton_pids = rt.singleton_pids.lock().await;
765            singleton_pids
766                .values()
767                .any(|&pid| pid == request.target_pid)
768        };
769
770        let allowed = if is_singleton_target {
771            true
772        } else {
773            match Self::is_owned_child(rt, requester_pid, request.target_pid)
774                .await
775            {
776                Ok(v) => v,
777                Err(e) => {
778                    let _ = response_tx.send(ProxyCallResponse {
779                        ok: false,
780                        result: None,
781                        error: Some(crate::protocol::RpcError {
782                            code: "internal".into(),
783                            message: format!("ownership check failed: {e:#}"),
784                        }),
785                    });
786                    return;
787                }
788            }
789        };
790
791        if !allowed {
792            let _ = response_tx.send(ProxyCallResponse {
793                ok: false,
794                result: None,
795                error: Some(crate::protocol::RpcError {
796                    code: "unauthorized".into(),
797                    message: "target pid is not owned by requester".into(),
798                }),
799            });
800            return;
801        }
802
803        let resp =
804            match Self::forward_call_to_child(rt, ctx.connection_id, &request)
805                .await
806            {
807                Ok(r) => r,
808                Err(e) => {
809                    let _ = response_tx.send(ProxyCallResponse {
810                        ok: false,
811                        result: None,
812                        error: Some(crate::protocol::RpcError {
813                            code: "internal".into(),
814                            message: format!("proxy call failed: {e:#}"),
815                        }),
816                    });
817                    return;
818                }
819            };
820
821        let _ = response_tx.send(resp);
822    }
823
824    async fn is_owned_child(
825        rt: &WorkspaceRuntime,
826        owner: crate::types::ProcessId,
827        target: crate::types::ProcessId,
828    ) -> Result<bool> {
829        let children = rt
830            .process_manager
831            .list_children()
832            .await
833            .map_err(|e| anyhow::anyhow!("list_children failed: {e:#}"))?;
834        Ok(children
835            .iter()
836            .any(|h| h.pid == target && h.parent == Some(owner)))
837    }
838
839    async fn forward_call_to_child(
840        rt: &WorkspaceRuntime,
841        requester_conn: crate::types::ConnectionId,
842        request: &ProxyCallRequest,
843    ) -> Result<ProxyCallResponse> {
844        let peer = rt.peer_for_pid(request.target_pid).await?;
845
846        #[cfg(unix)]
847        let resp = {
848            let fd_count = usize::try_from(request.fd_count)
849                .map_err(|e| anyhow::anyhow!("invalid fd_count: {e}"))?;
850
851            if fd_count == 0 {
852                peer.call(request.method.clone(), request.args.clone())
853                    .await?
854            } else {
855                let requester_peer = rt
856                    .peer_for_connection(requester_conn)
857                    .await
858                    .map_err(|e| {
859                        anyhow::anyhow!("requester peer lookup failed: {e:#}")
860                    })?;
861
862                let mut fds = Vec::with_capacity(fd_count);
863                for _ in 0..fd_count {
864                    let fd = requester_peer.recv_fd().await.map_err(|e| {
865                        anyhow::anyhow!("recv_fd failed: {e:#}")
866                    })?;
867                    fds.push(fd);
868                }
869
870                peer.call_raw_with_fds(
871                    request.method.clone(),
872                    request.args.clone(),
873                    fds,
874                )
875                .await?
876            }
877        };
878
879        #[cfg(not(unix))]
880        let resp = {
881            if request.fd_count != 0 {
882                anyhow::bail!(
883                    "proxy_call included fds but platform does not support fd passing"
884                );
885            }
886            peer.call(request.method.clone(), request.args.clone())
887                .await?
888        };
889
890        Ok(ProxyCallResponse {
891            ok: resp.ok,
892            result: resp.result,
893            error: resp.error,
894        })
895    }
896
897    async fn handle_spawn_request_static(
898        workspace: &W,
899        rt: &WorkspaceRuntime,
900        req: SpawnRequestWithResponse,
901    ) {
902        let SpawnRequestWithResponse {
903            ctx,
904            request,
905            response_tx,
906        } = req;
907
908        let requester_pid = rt.pid_for_connection(ctx.connection_id).await;
909        let requester = SpawnRequester {
910            ctx,
911            pid: requester_pid,
912        };
913
914        let decision = workspace
915            .evaluate_spawn_request(rt, requester, request.clone())
916            .await;
917
918        let (parent, caps, extra_args) = match decision {
919            Ok(SpawnRequestDecision::Accept {
920                parent,
921                caps,
922                extra_args,
923            }) => (parent, caps, extra_args),
924            Ok(SpawnRequestDecision::Reject { error }) => {
925                let _ = response_tx.send(SpawnChildResponse {
926                    accepted: false,
927                    child_pid: None,
928                    error,
929                });
930                return;
931            }
932            Err(e) => {
933                let _ = response_tx.send(SpawnChildResponse {
934                    accepted: false,
935                    child_pid: None,
936                    error: Some(format!("spawn evaluation failed: {e:#}")),
937                });
938                return;
939            }
940        };
941
942        // If the service is a singleton and it has already been spawned, return the
943        // existing PID instead of spawning a new instance.
944        let spawn_result = {
945            let singleton_pids = rt.singleton_pids.lock().await;
946            if let Some(&pid) = singleton_pids.get(&request.kind) {
947                Ok(process::ChildProcess {
948                    pid,
949                    rt: rt.clone(),
950                })
951            } else {
952                drop(singleton_pids);
953                let spawn_parent = parent.or(requester_pid);
954                rt.start_service_with_args(
955                    request.kind,
956                    caps,
957                    spawn_parent,
958                    extra_args,
959                )
960                .await
961            }
962        };
963
964        let child = match spawn_result {
965            Ok(child) => child,
966            Err(e) => {
967                let _ = response_tx.send(SpawnChildResponse {
968                    accepted: false,
969                    child_pid: None,
970                    error: Some(format!("spawn failed: {e:#}")),
971                });
972                return;
973            }
974        };
975
976        let pid = child.pid;
977        let _ = response_tx.send(SpawnChildResponse {
978            accepted: true,
979            child_pid: Some(pid),
980            error: None,
981        });
982    }
983}
984
985#[cfg(test)]
986#[allow(
987    clippy::panic,
988    clippy::expect_used,
989    clippy::unwrap_used,
990    clippy::unwrap_in_result,
991    clippy::panic_in_result_fn,
992    clippy::indexing_slicing,
993    clippy::arithmetic_side_effects,
994    reason = "Standard repository test boilerplate"
995)]
996mod tests {
997    use super::*;
998
999    #[derive(Debug, Default)]
1000    struct NoopWorkspace {
1001        services: WorkspaceServices,
1002    }
1003
1004    #[async_trait::async_trait]
1005    impl Workspace for NoopWorkspace {
1006        fn services(&self) -> &WorkspaceServices {
1007            &self.services
1008        }
1009
1010        fn set_services(&mut self, services: WorkspaceServices) {
1011            self.services = services;
1012        }
1013
1014        async fn boot(&mut self, _rt: &WorkspaceRuntime) -> Result<()> {
1015            Ok(())
1016        }
1017
1018        async fn run(&self, _rt: &WorkspaceRuntime) -> Result<()> {
1019            Ok(())
1020        }
1021
1022        async fn on_parent_message(
1023            &self,
1024            _rt: &WorkspaceRuntime,
1025            _event: ParentMessageEvent,
1026        ) -> Result<()> {
1027            Ok(())
1028        }
1029
1030        async fn evaluate_spawn_request(
1031            &self,
1032            _rt: &WorkspaceRuntime,
1033            _requester: SpawnRequester,
1034            _request: SpawnChildRequest,
1035        ) -> Result<SpawnRequestDecision> {
1036            Ok(SpawnRequestDecision::Reject { error: None })
1037        }
1038    }
1039
1040    #[crate::ctb_test]
1041    fn workspace_runner_creates_socket_path() {
1042        let runner = WorkspaceRunner::new(
1043            NoopWorkspace::default(),
1044            WorkspaceRunnerConfig::default_with_timeout(),
1045            Arc::new(std::path::PathBuf::from("ctb-example")),
1046            None,
1047        );
1048        assert!(runner.socket_path().contains("ctb-workspace-"));
1049    }
1050
1051    #[crate::ctb_test]
1052    fn workspace_runner_registers_tokens() {
1053        let runner = WorkspaceRunner::new(
1054            NoopWorkspace::default(),
1055            WorkspaceRunnerConfig::default_with_timeout(),
1056            Arc::new(std::path::PathBuf::from("ctb-example")),
1057            None,
1058        );
1059        let rt = runner.runtime();
1060
1061        let token = rt.register_token("test", CapabilitySet::default());
1062        assert!(token.starts_with("test-"));
1063        assert!(runner.validator.has_token(&token));
1064    }
1065}