ctb_workspace_ipc/workspace_runner/
workspace_runtime.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//! Workspace runtime loop supervising child processes and IPC services.
21
22use crate::services::renderer::RendererClient;
23use crate::services::runtime::RuntimeClient;
24#[allow(
25    unused_imports,
26    clippy::wildcard_imports,
27    reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30use crate::workspace_runner::WorkspaceRunnerConfig;
31use crate::workspace_runner::process::{ChildCommand, ChildProcess};
32
33use async_trait::async_trait;
34use ctb_utilities::ipc::service_traits::RuntimeClientTrait;
35use ctb_utilities::ipc::service_traits::runtime::RuntimeSpawner;
36
37use std::collections::HashMap;
38use std::sync::Arc;
39
40use ctb_utilities::ipc::IPC_ARG;
41use uuid::Uuid;
42
43use crate::auth::capability::{
44    CapabilityBundle, CapabilitySet, CapabilityToken, InMemoryTokenValidator,
45};
46use crate::process_manager::{
47    ProcessManager, SpawnParams, TokioProcessManager,
48};
49use crate::services::network::NetworkClient;
50use crate::services::parent::api::DataPlaneRef;
51use crate::services::parent::api::{ParentMessageKind, ShutdownRequest};
52use crate::services::parent::channel::ParentMessageEvent;
53use crate::types::{ConnectionId, ProcessId};
54use ipc::ChildKind;
55
56use crate::peer::IpcPeer;
57
58#[derive(Debug, Clone, Default)]
59pub(crate) struct ShutdownState {
60    pub(crate) requested: bool,
61    pub(crate) reason: Option<String>,
62}
63
64/// A small runtime handle provided to the workspace implementation.
65#[derive(Debug, Clone)]
66pub struct WorkspaceRuntime {
67    pub(crate) socket_path: String,
68    pub(crate) validator: Arc<InMemoryTokenValidator>,
69    pub(crate) process_manager: Arc<TokioProcessManager>,
70    pub(crate) exe: Arc<std::path::PathBuf>,
71    pub(crate) config: WorkspaceRunnerConfig,
72    pub(crate) pending_processes:
73        Arc<tokio::sync::Mutex<HashMap<String, ProcessId>>>,
74    pub(crate) peers: Arc<tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>>,
75    pub(crate) pid_by_conn:
76        Arc<tokio::sync::Mutex<HashMap<ConnectionId, ProcessId>>>,
77    pub(crate) root_pids: Arc<tokio::sync::Mutex<Vec<ProcessId>>>,
78    pub(crate) singleton_pids:
79        Arc<tokio::sync::Mutex<HashMap<ChildKind, ProcessId>>>,
80    pub(crate) shutdown_tx: tokio::sync::mpsc::Sender<Option<String>>,
81    pub(crate) shutdown_state: Arc<tokio::sync::Mutex<ShutdownState>>,
82    pub(crate) shutdown_notify: Arc<tokio::sync::Notify>,
83}
84
85impl WorkspaceRuntime {
86    /// Socket path children should connect to.
87    pub fn socket_path(&self) -> &str {
88        &self.socket_path
89    }
90
91    /// Check if a singleton service is running and return its `ProcessId`.
92    pub async fn get_singleton_pid(
93        &self,
94        kind: ChildKind,
95    ) -> Option<ProcessId> {
96        let guard = self.singleton_pids.lock().await;
97        guard.get(&kind).copied()
98    }
99
100    /// Wait until the workspace runner requests shutdown.
101    ///
102    /// Simply explained: the runner has its own internal IPC loop which listens for
103    /// shutdown requests (Ctrl-C, child requests, timeouts). Your
104    /// `Workspace::run()` should usually `select!` on this signal so it can exit
105    /// cleanly.
106    pub async fn wait_for_shutdown(&self) -> Option<String> {
107        loop {
108            {
109                let guard = self.shutdown_state.lock().await;
110                if guard.requested {
111                    return guard.reason.clone();
112                }
113            }
114            self.shutdown_notify.notified().await;
115        }
116    }
117
118    pub(crate) async fn notify_shutdown(&self, reason: Option<String>) {
119        let mut guard = self.shutdown_state.lock().await;
120        guard.requested = true;
121        guard.reason = reason;
122        drop(guard);
123        self.shutdown_notify.notify_waiters();
124    }
125
126    /// Start a process as a "singleton" service (one instance per `ChildKind`).
127    ///
128    /// This is meant for workspace-level services like network/io/storage.
129    pub async fn start_singleton_service(
130        &self,
131        kind: ChildKind,
132        caps: CapabilitySet,
133    ) -> Result<ChildProcess> {
134        let mut guard = self.singleton_pids.lock().await;
135        if let Some(pid) = guard.get(&kind).copied() {
136            return Ok(ChildProcess {
137                pid,
138                rt: self.clone(),
139            });
140        }
141        let child = self.start_service(kind, caps, None).await?;
142        guard.insert(kind, child.pid);
143        Ok(child)
144    }
145
146    /// Start a child process.
147    pub async fn start_service(
148        &self,
149        kind: ChildKind,
150        caps: CapabilitySet,
151        parent: Option<ProcessId>,
152    ) -> Result<ChildProcess> {
153        self.start_service_with_args(kind, caps, parent, vec![])
154            .await
155    }
156
157    /// Start a child process with extra command-line arguments.
158    pub async fn start_service_with_args(
159        &self,
160        kind: ChildKind,
161        caps: CapabilitySet,
162        parent: Option<ProcessId>,
163        extra_args: Vec<String>,
164    ) -> Result<ChildProcess> {
165        let mut args = invocation_settings::get_settings().command_line_args();
166        args.extend(extra_args);
167
168        let pid = self
169            .spawn_child_with_command(kind, parent, caps, args)
170            .await?;
171
172        Ok(ChildProcess {
173            pid,
174            rt: self.clone(),
175        })
176    }
177
178    /// Convenience: start a network service and return a typed client.
179    pub async fn start_network_service(
180        &self,
181        caps: CapabilitySet,
182        parent: Option<ProcessId>,
183    ) -> Result<NetworkClient> {
184        let proc = self.start_service(ChildKind::Network, caps, parent).await?;
185        Ok(NetworkClient::from_child(proc))
186    }
187
188    /// Convenience: start a renderer service and return a typed client.
189    pub async fn start_renderer_service(
190        &self,
191        caps: CapabilitySet,
192        parent: Option<ProcessId>,
193    ) -> Result<RendererClient> {
194        let proc = self
195            .start_service(ChildKind::Renderer, caps, parent)
196            .await?;
197        Ok(RendererClient::from_child(proc))
198    }
199
200    /// Convenience: start a runtime service and return a typed client.
201    pub async fn start_runtime_service(
202        &self,
203        caps: CapabilitySet,
204        parent: Option<ProcessId>,
205    ) -> Result<RuntimeClient> {
206        let proc = self.start_service(ChildKind::Runtime, caps, parent).await?;
207        Ok(RuntimeClient::from_child(proc))
208    }
209
210    async fn spawn_child_with_command(
211        &self,
212        kind: ChildKind,
213        parent: Option<ProcessId>,
214        caps: CapabilitySet,
215        extra_args: Vec<String>,
216    ) -> Result<ProcessId> {
217        let token_for = ipc::format_child_kind(&kind);
218        let token = self.register_token(token_for, caps.clone());
219
220        let mut cmd = ChildCommand {
221            program: self.exe.to_path_buf(),
222            args: vec![],
223            env: vec![],
224            cwd: None,
225        };
226
227        // Built the command-line arguments, inserting them before any custom
228        // arguments. Note that because they are un-shifted onto the beginning of the
229        // arguemnt list, they are in reverse order here.
230        cmd.args.insert(0, "--".into());
231        cmd.args.insert(0, self.socket_path.clone());
232        cmd.args.insert(0, "--socket".into());
233        cmd.args.insert(0, format!("--{token_for}"));
234        cmd.args.insert(0, IPC_ARG.into());
235
236        // Append any extra arguments
237        cmd.args.extend(extra_args);
238
239        let program = cmd.program.to_string_lossy().into_owned();
240
241        debug_fmt!("spawning child {:?} {:?}", cmd.program, cmd.args);
242
243        let handle = self
244            .process_manager
245            .spawn_child(SpawnParams {
246                kind,
247                parent,
248                program: Some(program),
249                args: cmd.args,
250                env: cmd.env,
251                cwd: cmd.cwd,
252                capabilities: CapabilityBundle {
253                    token: CapabilityToken(token),
254                    capabilities: caps,
255                },
256            })
257            .await
258            .map_err(|e| anyhow::anyhow!("spawn_child failed: {e:#}"))?;
259
260        self.pending_processes
261            .lock()
262            .await
263            .insert(token_for.to_string(), handle.pid);
264
265        if parent.is_none() {
266            self.root_pids.lock().await.push(handle.pid);
267        }
268
269        Ok(handle.pid)
270    }
271
272    /// Resolve the pid associated with a connection, if known.
273    pub async fn pid_for_connection(
274        &self,
275        conn: ConnectionId,
276    ) -> Option<ProcessId> {
277        self.pid_by_conn.lock().await.get(&conn).copied()
278    }
279
280    /// Wait for the peer associated with `pid` to be connected.
281    pub async fn peer_for_pid(&self, pid: ProcessId) -> Result<Arc<IpcPeer>> {
282        let peers = Arc::clone(&self.peers);
283        let timeout = self.config.connect_timeout;
284
285        tokio::time::timeout(timeout, async move {
286            loop {
287                if let Some(peer) = peers.lock().await.get(&pid).cloned() {
288                    return Ok(peer);
289                }
290                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
291            }
292        })
293        .await
294        .map_err(|_elapsed| {
295            anyhow::anyhow!("timed out waiting for child peer")
296        })?
297    }
298
299    /// Wait for the peer associated with `conn` to be connected.
300    pub async fn peer_for_connection(
301        &self,
302        conn: ConnectionId,
303    ) -> Result<Arc<IpcPeer>> {
304        let Some(pid) = self.pid_for_connection(conn).await else {
305            anyhow::bail!("no pid registered for connection {conn}");
306        };
307        self.peer_for_pid(pid).await
308    }
309
310    /// Read a data-plane blob referenced by a parent message.
311    ///
312    /// This intentionally hides FD-transfer and descriptor handling from
313    /// workspace implementations.
314    pub async fn read_data_plane_ref_bytes(
315        &self,
316        conn: ConnectionId,
317        data_ref: &DataPlaneRef,
318    ) -> Result<Vec<u8>> {
319        let mut descriptor = data_ref.descriptor.clone();
320
321        #[cfg(unix)]
322        {
323            if crate::data_plane::shared_memory::descriptor_requires_fd_transfer(
324                &descriptor,
325            ) {
326                let peer = self.peer_for_connection(conn).await?;
327                descriptor = crate::data_plane::recv_blob_fd(
328                    peer.session(),
329                    &descriptor,
330                )
331                .await
332                .map_err(|e| anyhow::anyhow!("recv_blob_fd failed: {e}"))?;
333            }
334        }
335
336        ctb_utilities::shared_memory::read_blob_contents(
337            &descriptor,
338            data_ref.token.size,
339        )
340        .context("read_blob_contents")
341    }
342
343    /// Resolve an incoming parent message into a high-level representation.
344    ///
345    /// Workspace implementations should prefer this over manually decoding
346    /// `DataPlaneRef` payloads to avoid coupling example logic to the IPC
347    /// data-plane implementation details (including FD transfer).
348    pub async fn resolve_parent_message(
349        &self,
350        event: &ParentMessageEvent,
351    ) -> Result<ResolvedParentMessage> {
352        match event.message.kind {
353            ParentMessageKind::DataPlane => {
354                let data_ref =
355                    event.message.as_data_plane_ref().map_err(|e| {
356                        anyhow::anyhow!("decode data plane ref failed: {e:#}")
357                    })?;
358
359                match self
360                    .read_data_plane_ref_bytes(
361                        event.ctx.connection_id,
362                        &data_ref,
363                    )
364                    .await
365                {
366                    Ok(bytes) => Ok(ResolvedParentMessage::DataPlaneBytes {
367                        bytes,
368                        content_type: data_ref.content_type,
369                        sequence: data_ref.sequence,
370                    }),
371                    Err(error) => {
372                        Ok(ResolvedParentMessage::DataPlaneReadFailed {
373                            error,
374                            content_type: data_ref.content_type,
375                            sequence: data_ref.sequence,
376                        })
377                    }
378                }
379            }
380            ParentMessageKind::Text => {
381                let text = event.message.as_text().map_err(|e| {
382                    anyhow::anyhow!("decode text message failed: {e:#}")
383                })?;
384                Ok(ResolvedParentMessage::Text(text))
385            }
386            ParentMessageKind::ShutdownRequest => {
387                let ShutdownRequest { reason } =
388                    event.message.as_shutdown_request().map_err(|e| {
389                        anyhow::anyhow!("decode shutdown request failed: {e:#}")
390                    })?;
391                Ok(ResolvedParentMessage::ShutdownRequest { reason })
392            }
393            other => Ok(ResolvedParentMessage::Other { kind: other }),
394        }
395    }
396
397    /// Request that the workspace event loop shuts down.
398    pub async fn request_shutdown(&self, reason: Option<String>) -> Result<()> {
399        self.shutdown_tx.send(reason).await.map_err(|e| {
400            anyhow::anyhow!("failed to send shutdown request: {e}")
401        })?;
402        Ok(())
403    }
404
405    /// Register a token with capabilities and return the token string.
406    pub fn register_token(
407        &self,
408        token_for: &str,
409        caps: CapabilitySet,
410    ) -> String {
411        let token = format!("{token_for}-{}", Uuid::new_v4());
412        self.validator.register_token(&token, caps);
413        token
414    }
415}
416
417/// A high-level decoded parent message.
418#[derive(Debug)]
419pub enum ResolvedParentMessage {
420    /// A successfully resolved data-plane message.
421    DataPlaneBytes {
422        bytes: Vec<u8>,
423        content_type: String,
424        sequence: Option<u64>,
425    },
426    /// A data-plane message whose reference decoded, but whose bytes could
427    /// not be read.
428    DataPlaneReadFailed {
429        error: anyhow::Error,
430        content_type: String,
431        sequence: Option<u64>,
432    },
433    /// A plain text message.
434    Text(String),
435    /// A workspace shutdown request.
436    ShutdownRequest { reason: Option<String> },
437    /// Any other message kind.
438    Other { kind: ParentMessageKind },
439}
440
441#[async_trait]
442impl RuntimeSpawner for WorkspaceRuntime {
443    async fn spawn_runtime(&self) -> Result<Box<dyn RuntimeClientTrait>> {
444        // Use default/empty capabilities for trait-based spawning.
445        // Callers needing specific capabilities should use
446        // `start_runtime_service` directly.
447        let caps = CapabilitySet::default();
448        let client = self.start_runtime_service(caps, None).await?;
449        Ok(Box::new(client))
450    }
451}