ctb_workspace_ipc/workspace_runner/
process.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//! Process execution, environment setup, and child handle lifecycle.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::path::PathBuf;
30use std::sync::Arc;
31use std::time::Duration;
32
33use crate::types::ProcessId;
34
35use crate::data_plane::shared_memory::SharedBlobDescriptor;
36use crate::peer::IpcPeer;
37
38use crate::workspace_runner::workspace_runtime::WorkspaceRuntime;
39
40use ctb_utilities::ipc::registry::{IpcCallFuture, IpcCaller};
41
42/// Command line / program specification for a child process.
43#[derive(Debug, Clone)]
44pub struct ChildCommand {
45    pub program: std::path::PathBuf,
46    pub args: Vec<String>,
47    pub env: Vec<(String, String)>,
48    pub cwd: Option<String>,
49}
50
51#[derive(Debug)]
52pub struct CommandBuilder {
53    pub exe: PathBuf,
54}
55
56/// A handle to a spawned child process.
57#[derive(Debug, Clone)]
58pub struct ChildProcess {
59    pub pid: ProcessId,
60    pub(crate) rt: WorkspaceRuntime,
61}
62
63impl ChildProcess {
64    /// Wait for the child's control connection and return its peer.
65    pub async fn peer(&self) -> Result<Arc<IpcPeer>> {
66        let pid = self.pid;
67        let peers = Arc::clone(&self.rt.peers);
68        let timeout = self.rt.config.connect_timeout;
69
70        tokio::time::timeout(timeout, async move {
71            loop {
72                if let Some(peer) = peers.lock().await.get(&pid).cloned() {
73                    return Ok(peer);
74                }
75                tokio::time::sleep(Duration::from_millis(10)).await;
76            }
77        })
78        .await
79        .map_err(|_elapsed| {
80            anyhow::anyhow!("timed out waiting for child to connect")
81        })?
82    }
83
84    /// Make a postcard RPC call and decode the postcard response.
85    pub async fn call_postcard<Req, Resp>(
86        &self,
87        service: &str,
88        method: &str,
89        req: &Req,
90    ) -> Result<Resp>
91    where
92        Req: serde::Serialize,
93        Resp: for<'de> serde::Deserialize<'de>,
94    {
95        let args = postcard_helpers::encode(req, "request")?;
96        let resp = self
97            .peer()
98            .await?
99            .call(
100                crate::protocol::MethodId {
101                    service: service.into(),
102                    method: method.into(),
103                },
104                args,
105            )
106            .await?;
107
108        let bytes = crate::response_result_bytes(resp, "IPC call_postcard")?;
109
110        postcard_helpers::decode::<Resp>(&bytes, "response")
111    }
112
113    #[cfg(unix)]
114    pub async fn call_postcard_with_blob_fd<Req, Resp>(
115        &self,
116        service: &str,
117        method: &str,
118        req: &Req,
119        blob_descriptor: &SharedBlobDescriptor,
120    ) -> Result<Resp>
121    where
122        Req: serde::Serialize,
123        Resp: for<'de> serde::Deserialize<'de>,
124    {
125        let resp = self
126            .peer()
127            .await?
128            .call_postcard_with_blob_fd(service, method, req, blob_descriptor)
129            .await?;
130        Ok(resp)
131    }
132}
133
134impl IpcCaller for ChildProcess {
135    fn call_raw(
136        &self,
137        service: &str,
138        method: &str,
139        args: Vec<u8>,
140    ) -> IpcCallFuture<'_> {
141        let service = service.to_string();
142        let method = method.to_string();
143        Box::pin(async move {
144            let resp = self
145                .peer()
146                .await?
147                .call(crate::protocol::MethodId { service, method }, args)
148                .await?;
149
150            crate::response_result_bytes(resp, "IPC call_raw")
151        })
152    }
153}
154
155#[cfg(unix)]
156impl ctb_utilities::ipc::registry::IpcCallerWithFds for ChildProcess {
157    fn call_raw_with_fds(
158        &self,
159        service: &str,
160        method: &str,
161        args: Vec<u8>,
162        fds: Vec<std::os::unix::io::RawFd>,
163    ) -> ctb_utilities::ipc::registry::IpcCallFuture<'_> {
164        let service = service.to_string();
165        let method = method.to_string();
166        Box::pin(async move {
167            let resp = self
168                .peer()
169                .await?
170                .call_raw_with_fds(
171                    crate::protocol::MethodId { service, method },
172                    args,
173                    fds,
174                )
175                .await?;
176
177            crate::response_result_bytes(resp, "IPC call_raw_with_fds")
178        })
179    }
180}