ctb_workspace_ipc/
peer_clients.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//! Cross-service IPC helper utilities.
21//!
22//! `connection.rs` is intended to be transport/handshake focused. Service-
23//! specific client implementations should live under `services/`.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32use std::sync::Arc;
33
34use crate::data_plane::send_blob_fd;
35use crate::data_plane::shared_memory::{
36    BlobAllocator, BlobBackend, SharedMemoryBlobs,
37    descriptor_requires_fd_transfer,
38};
39use crate::peer::IpcPeer;
40use crate::protocol::MethodId;
41use crate::services::parent::SERVICE_NAME as PARENT_SERVICE_NAME;
42use crate::services::parent::api::{
43    DataPlaneRef, METHOD_MESSAGE_PARENT, METHOD_PROXY_CALL,
44    METHOD_REQUEST_SPAWN_CHILD, MessageToParentRequest, ParentMessage,
45    ProxyCallRequest, ProxyCallResponse, SpawnChildRequest, SpawnChildResponse,
46};
47use crate::types::ProcessId;
48use ipc::ChildKind;
49
50#[cfg(unix)]
51use ctb_utilities::ipc::registry::IpcCallerWithFds;
52use ctb_utilities::ipc::registry::{IpcCallFuture, IpcCaller};
53
54/// Send a text message to the parent process.
55pub(crate) async fn send_to_parent(
56    peer: &Arc<IpcPeer>,
57    message: &str,
58) -> Result<()> {
59    send_parent_message(peer, ParentMessage::text(message)).await
60}
61
62/// Send a data-plane message to the parent process.
63///
64/// This allocates a shared-memory blob, writes `bytes`, sends a parent message
65/// containing a `DataPlaneRef`, and performs FD transfer if required.
66pub(crate) async fn send_data_plane_message(
67    peer: &Arc<IpcPeer>,
68    bytes: Vec<u8>,
69    content_type: &str,
70) -> Result<()> {
71    let blobs = SharedMemoryBlobs::new(BlobBackend::PlatformDefault);
72    let size = u64::try_from(bytes.len())
73        .map_err(|e| anyhow::anyhow!("blob too large: {e}"))?;
74
75    let blob = blobs
76        .create(size)
77        .await
78        .map_err(|e| anyhow::anyhow!("failed to allocate blob: {e}"))?;
79
80    blob.write_all(&bytes)
81        .map_err(|e| anyhow::anyhow!("failed to write blob: {e}"))?;
82
83    let data_ref = DataPlaneRef::new(
84        blob.token.clone(),
85        blob.descriptor.clone(),
86        content_type.to_string(),
87    );
88
89    let msg = ParentMessage::data_plane(&data_ref).map_err(|e| {
90        anyhow::anyhow!("failed to encode data plane message: {e}")
91    })?;
92
93    send_parent_message(peer, msg).await?;
94
95    if descriptor_requires_fd_transfer(&blob.descriptor) {
96        send_blob_fd(peer.session(), &blob.descriptor)
97            .await
98            .map_err(|e| anyhow::anyhow!("failed to send blob fd: {e}"))?;
99    }
100
101    Ok(())
102}
103
104/// Send a shutdown request to the workspace parent.
105pub(crate) async fn request_workspace_shutdown(
106    peer: &Arc<IpcPeer>,
107    reason: Option<String>,
108) -> Result<()> {
109    let msg = ParentMessage::shutdown_request(reason).map_err(|e| {
110        anyhow::anyhow!("failed to encode shutdown request: {e}")
111    })?;
112    send_parent_message(peer, msg).await
113}
114
115/// Request that the parent spawn a child process and return its PID.
116pub(crate) async fn request_spawn_child(
117    peer: &Arc<IpcPeer>,
118    kind: ChildKind,
119    init_data: Option<Vec<u8>>,
120) -> Result<ProcessId> {
121    let spawn_req = SpawnChildRequest { kind, init_data };
122    let args = postcard_helpers::encode(&spawn_req, "spawn request")?;
123
124    let resp = peer
125        .call(
126            MethodId {
127                service: PARENT_SERVICE_NAME.into(),
128                method: METHOD_REQUEST_SPAWN_CHILD.into(),
129            },
130            args,
131        )
132        .await
133        .map_err(|e| anyhow::anyhow!("spawn request IPC call failed: {e}"))?;
134
135    let bytes = crate::response_result_bytes(resp, "spawn request")?;
136    let result: SpawnChildResponse =
137        postcard_helpers::decode(&bytes, "spawn response")?;
138
139    if !result.accepted {
140        anyhow::bail!(
141            "spawn request rejected: {}",
142            // Reason for fallback: spawn rejection without explicit message defaults to "no reason"
143            result.error.unwrap_or_else(|| "no reason".into())
144        );
145    }
146
147    result
148        .child_pid
149        .ok_or_else(|| anyhow::anyhow!("spawn response missing child pid"))
150}
151
152async fn send_parent_message(
153    peer: &Arc<IpcPeer>,
154    message: ParentMessage,
155) -> Result<()> {
156    let req = MessageToParentRequest { message };
157    let args = postcard_helpers::encode(&req, "parent message")?;
158
159    let resp = peer
160        .call(
161            MethodId {
162                service: PARENT_SERVICE_NAME.into(),
163                method: METHOD_MESSAGE_PARENT.into(),
164            },
165            args,
166        )
167        .await
168        .map_err(|e| {
169            anyhow::anyhow!("send_parent_message IPC call failed: {e}")
170        })?;
171
172    crate::ensure_response_ok(&resp, "send_parent_message")?;
173
174    Ok(())
175}
176
177/// Shared helper for proxied child IPC calls (via the parent `proxy_call`).
178#[derive(Debug, Clone)]
179pub(crate) struct PeerProxiedClient {
180    peer: Arc<IpcPeer>,
181    target_pid: ProcessId,
182}
183
184impl PeerProxiedClient {
185    pub(crate) fn new(peer: Arc<IpcPeer>, target_pid: ProcessId) -> Self {
186        Self { peer, target_pid }
187    }
188
189    async fn proxy_call(
190        &self,
191        method: MethodId,
192        args: Vec<u8>,
193    ) -> Result<ProxyCallResponse> {
194        let req = ProxyCallRequest {
195            target_pid: self.target_pid,
196            method,
197            args,
198            fd_count: 0,
199        };
200        let payload = postcard_helpers::encode(&req, "proxy request")?;
201
202        let resp = self
203            .peer
204            .call(
205                MethodId {
206                    service: PARENT_SERVICE_NAME.into(),
207                    method: METHOD_PROXY_CALL.into(),
208                },
209                payload,
210            )
211            .await
212            .map_err(|e| anyhow::anyhow!("proxy_call IPC call failed: {e}"))?;
213
214        let bytes = crate::response_result_bytes(resp, "proxy_call")?;
215        let result: ProxyCallResponse =
216            postcard_helpers::decode(&bytes, "proxy_call response")?;
217        Ok(result)
218    }
219
220    #[cfg(unix)]
221    async fn proxy_call_with_fds(
222        &self,
223        method: MethodId,
224        args: Vec<u8>,
225        fds: Vec<std::os::unix::io::RawFd>,
226    ) -> Result<ProxyCallResponse> {
227        let fd_count = u32::try_from(fds.len())
228            .map_err(|e| anyhow::anyhow!("too many fds for proxy call: {e}"))?;
229
230        let req = ProxyCallRequest {
231            target_pid: self.target_pid,
232            method,
233            args,
234            fd_count,
235        };
236
237        let payload = postcard_helpers::encode(&req, "proxy request")?;
238
239        let resp = self
240            .peer
241            .call_raw_with_fds(
242                MethodId {
243                    service: PARENT_SERVICE_NAME.into(),
244                    method: METHOD_PROXY_CALL.into(),
245                },
246                payload,
247                fds,
248            )
249            .await
250            .map_err(|e| anyhow::anyhow!("proxy_call IPC call failed: {e}"))?;
251
252        let bytes = crate::response_result_bytes(resp, "proxy_call")?;
253        let result: ProxyCallResponse =
254            postcard_helpers::decode(&bytes, "proxy_call response")?;
255        Ok(result)
256    }
257
258    pub(crate) async fn call_postcard<Req, Resp>(
259        &self,
260        service: &str,
261        method: &str,
262        req: &Req,
263    ) -> Result<Resp>
264    where
265        Req: serde::Serialize + Send + Sync,
266        Resp: serde::de::DeserializeOwned,
267    {
268        let args = postcard_helpers::encode(req, "request")?;
269
270        let proxied = self
271            .proxy_call(
272                MethodId {
273                    service: service.to_string(),
274                    method: method.to_string(),
275                },
276                args,
277            )
278            .await?;
279
280        if !proxied.ok {
281            // Reason for fallback: proxied IPC call failure without error message defaults to "unknown error"
282            let msg = proxied
283                .error
284                .map_or_else(|| "unknown error".to_string(), |e| e.message);
285            anyhow::bail!("proxied call failed: {msg}");
286        }
287
288        let result = proxied
289            .result
290            .as_ref()
291            .ok_or_else(|| anyhow::anyhow!("response missing result"))
292            .and_then(|bytes| postcard_helpers::decode(bytes, "response"))?;
293
294        Ok(result)
295    }
296}
297
298impl IpcCaller for PeerProxiedClient {
299    fn call_raw(
300        &self,
301        service: &str,
302        method: &str,
303        args: Vec<u8>,
304    ) -> IpcCallFuture<'_> {
305        let service = service.to_string();
306        let method = method.to_string();
307
308        Box::pin(async move {
309            let proxied =
310                self.proxy_call(MethodId { service, method }, args).await?;
311
312            proxied_result_bytes(proxied, "proxied call")
313        })
314    }
315}
316
317#[cfg(unix)]
318impl IpcCallerWithFds for PeerProxiedClient {
319    fn call_raw_with_fds(
320        &self,
321        service: &str,
322        method: &str,
323        args: Vec<u8>,
324        fds: Vec<std::os::unix::io::RawFd>,
325    ) -> IpcCallFuture<'_> {
326        let service = service.to_string();
327        let method = method.to_string();
328
329        Box::pin(async move {
330            let proxied = self
331                .proxy_call_with_fds(MethodId { service, method }, args, fds)
332                .await?;
333
334            proxied_result_bytes(proxied, "proxied call")
335        })
336    }
337}
338
339fn proxied_result_bytes(
340    proxied: ProxyCallResponse,
341    context: &str,
342) -> Result<Vec<u8>> {
343    if !proxied.ok {
344        // Reason for fallback: proxied response failure without error message defaults to "unknown error"
345        let msg = proxied
346            .error
347            .as_ref()
348            .map_or_else(|| "unknown error".to_string(), |e| e.message.clone());
349        anyhow::bail!("{context} failed: {msg}");
350    }
351
352    proxied
353        .result
354        .ok_or_else(|| anyhow::anyhow!("{context} missing result"))
355}