ctb_workspace_ipc/services/parent/
api.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//! Parent service API definitions.
21//!
22//! This service provides the ability for child processes (renderers, etc.)
23//! to send messages to their parent process. Messages can be data plane
24//! references (for shared-memory transfers), control requests (like spawning
25//! a child), or status notifications.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use anyhow::Result;
35use async_trait::async_trait;
36use ctb_utilities::shared_memory::BlobToken;
37use serde::{Deserialize, Serialize};
38
39use crate::data_plane::shared_memory::SharedBlobDescriptor;
40use crate::error::Error;
41use crate::types::{ConnectionId, ProcessId};
42use ipc::ChildKind;
43
44/// Method name for sending a message to the parent.
45pub const METHOD_MESSAGE_PARENT: &str = "message_parent";
46
47/// Method name for requesting that the parent spawn a child process.
48pub const METHOD_REQUEST_SPAWN_CHILD: &str = "request_spawn_child";
49
50/// Method name for asking the parent to proxy an IPC call to one of the
51/// caller's own child processes.
52pub const METHOD_PROXY_CALL: &str = "proxy_call";
53
54/// A message that can be sent from a child process to its parent.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct ParentMessage {
57    /// The kind of message being sent.
58    pub kind: ParentMessageKind,
59    /// Optional payload (postcard-encoded based on kind).
60    pub payload: Vec<u8>,
61}
62
63impl ParentMessage {
64    /// Create a data plane message (shared memory reference).
65    pub fn data_plane(data_ref: &DataPlaneRef) -> Result<Self, Error> {
66        let payload = postcard_helpers::encode(data_ref, "data plane ref")
67            .map_err(|e| Error::Serialization(e.to_string()))?;
68        Ok(Self {
69            kind: ParentMessageKind::DataPlane,
70            payload,
71        })
72    }
73
74    /// Create a text message.
75    pub fn text<S: Into<String>>(text: S) -> Self {
76        Self {
77            kind: ParentMessageKind::Text,
78            payload: text.into().into_bytes(),
79        }
80    }
81
82    /// Create a shutdown request message.
83    pub fn shutdown_request(reason: Option<String>) -> Result<Self, Error> {
84        let payload = postcard_helpers::encode(
85            &ShutdownRequest { reason },
86            "shutdown request",
87        )
88        .map_err(|e| Error::Serialization(e.to_string()))?;
89        Ok(Self {
90            kind: ParentMessageKind::ShutdownRequest,
91            payload,
92        })
93    }
94
95    /// Decode the payload as a data plane reference.
96    pub fn as_data_plane_ref(&self) -> Result<DataPlaneRef, Error> {
97        if self.kind != ParentMessageKind::DataPlane {
98            return Err(Error::Internal("not a data plane message".into()));
99        }
100        postcard_helpers::decode(&self.payload, "data plane ref")
101            .map_err(|e| Error::Serialization(e.to_string()))
102    }
103
104    /// Decode the payload as text.
105    pub fn as_text(&self) -> Result<String, Error> {
106        if self.kind != ParentMessageKind::Text {
107            return Err(Error::Internal("not a text message".into()));
108        }
109        String::from_utf8(self.payload.clone())
110            .map_err(|e| Error::Serialization(e.to_string()))
111    }
112
113    /// Decode the payload as a shutdown request.
114    pub fn as_shutdown_request(&self) -> Result<ShutdownRequest, Error> {
115        if self.kind != ParentMessageKind::ShutdownRequest {
116            return Err(Error::Internal("not a shutdown request".into()));
117        }
118        postcard_helpers::decode(&self.payload, "shutdown request")
119            .map_err(|e| Error::Serialization(e.to_string()))
120    }
121}
122
123/// Kinds of messages that can be sent to a parent.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125pub enum ParentMessageKind {
126    /// A data plane reference (shared memory) for display or processing.
127    DataPlane,
128    /// A simple text message.
129    Text,
130    /// A request to shut down the entire workspace.
131    ShutdownRequest,
132    /// A status notification (e.g., loading progress).
133    Status,
134    /// An error notification.
135    Error,
136}
137
138/// A reference to shared memory data on the data plane.
139///
140/// Rather than embedding data inline, this struct references a blob in
141/// shared memory that can be mapped by the recipient process.
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct DataPlaneRef {
144    /// Frame sequence number (optional, for ordering).
145    pub sequence: Option<u64>,
146    /// The content type (e.g., "text/html", "application/octet-stream").
147    pub content_type: String,
148    /// Token authorizing access to the shared memory blob.
149    pub token: BlobToken,
150    /// Descriptor for mapping the shared memory.
151    pub descriptor: SharedBlobDescriptor,
152}
153
154impl DataPlaneRef {
155    /// Create a data plane reference from a blob token and descriptor.
156    pub fn new(
157        token: BlobToken,
158        descriptor: SharedBlobDescriptor,
159        content_type: impl Into<String>,
160    ) -> Self {
161        Self {
162            sequence: None,
163            content_type: content_type.into(),
164            token,
165            descriptor,
166        }
167    }
168
169    /// Create a data plane reference with a sequence number.
170    #[must_use]
171    pub fn with_sequence(mut self, seq: u64) -> Self {
172        self.sequence = Some(seq);
173        self
174    }
175}
176
177/// Shutdown request payload.
178#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct ShutdownRequest {
180    /// Optional reason for the shutdown.
181    pub reason: Option<String>,
182}
183
184/// Request to send a message to the parent process.
185#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct MessageToParentRequest {
187    /// The message to send.
188    pub message: ParentMessage,
189}
190
191/// Response from sending a message to the parent.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct MessageToParentResponse {
194    /// Whether the message was accepted.
195    pub accepted: bool,
196    /// Optional response data from the parent.
197    pub response: Option<Vec<u8>>,
198}
199
200/// Request to spawn a child process owned by the requesting process.
201#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct SpawnChildRequest {
203    /// The kind of child to spawn.
204    pub kind: ChildKind,
205    /// Initial document or configuration data for the child.
206    pub init_data: Option<Vec<u8>>,
207}
208
209/// Response from requesting a child spawn.
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct SpawnChildResponse {
212    /// Whether the spawn was accepted.
213    pub accepted: bool,
214    /// The process ID of the newly spawned child (if accepted).
215    pub child_pid: Option<ProcessId>,
216    /// Error message if not accepted.
217    pub error: Option<String>,
218}
219
220/// Request for the parent to proxy an IPC call to a specific child pid.
221///
222/// The workspace is responsible for enforcing that the `target_pid` is owned
223/// by the requesting process.
224#[derive(Debug, Clone, Serialize, Deserialize)]
225pub struct ProxyCallRequest {
226    pub target_pid: ProcessId,
227    pub method: crate::protocol::MethodId,
228    pub args: Vec<u8>,
229    /// Number of Unix file descriptors attached to this request.
230    ///
231    /// This is used for shared-memory (data plane) parameters where the
232    /// descriptor metadata is carried in `args` and the actual FD(s) are sent
233    /// out-of-band via the underlying session.
234    ///
235    /// When `0`, no FD transfer is expected.
236    #[serde(default)]
237    pub fd_count: u32,
238}
239
240/// Response from a proxied IPC call.
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct ProxyCallResponse {
243    pub ok: bool,
244    pub result: Option<Vec<u8>>,
245    pub error: Option<crate::protocol::RpcError>,
246}
247
248/// Minimal metadata about a child-to-parent request.
249///
250/// This is provided by the server-side router, based on the connection's
251/// handshake metadata.
252#[derive(Debug, Clone)]
253pub struct ParentRequestContext {
254    /// Connection id the request came from.
255    pub connection_id: ConnectionId,
256    /// Optional process kind provided during handshake (e.g. "renderer").
257    pub process_kind: Option<String>,
258}
259
260/// Trait for sending messages to the parent process.
261///
262/// This is implemented by the IPC infrastructure and injected into child
263/// process routers to enable parent communication.
264#[async_trait]
265pub trait ParentMessenger: Send + Sync + std::fmt::Debug {
266    /// Send a message to the parent process.
267    async fn send_message(
268        &self,
269        ctx: ParentRequestContext,
270        message: ParentMessage,
271    ) -> Result<MessageToParentResponse, Error>;
272
273    /// Request that the parent spawn a child process owned by the caller.
274    async fn request_spawn_child(
275        &self,
276        ctx: ParentRequestContext,
277        request: SpawnChildRequest,
278    ) -> Result<SpawnChildResponse, Error>;
279
280    /// Ask the workspace to proxy an IPC call to a specific child process.
281    async fn proxy_call(
282        &self,
283        ctx: ParentRequestContext,
284        request: ProxyCallRequest,
285    ) -> Result<ProxyCallResponse, Error>;
286}
287
288/// A mock parent messenger for testing.
289#[derive(Debug, Default)]
290pub struct MockParentMessenger {
291    messages: std::sync::Mutex<Vec<ParentMessage>>,
292    spawn_requests: std::sync::Mutex<Vec<SpawnChildRequest>>,
293}
294
295impl MockParentMessenger {
296    /// Create a new mock messenger.
297    pub fn new() -> Self {
298        Self::default()
299    }
300
301    /// Get all received messages.
302    pub fn messages(&self) -> Vec<ParentMessage> {
303        // Reason for fallback: poisoned mutex lock in mock test harness returns empty vector of messages
304        self.messages.lock().map(|g| g.clone()).unwrap_or_default()
305    }
306
307    /// Get all spawn requests.
308    pub fn spawn_requests(&self) -> Vec<SpawnChildRequest> {
309        // Reason for fallback: poisoned mutex lock in mock test harness returns empty vector of spawn requests
310        self.spawn_requests
311            .lock()
312            .map(|g| g.clone())
313            .unwrap_or_default()
314    }
315}
316#[async_trait]
317impl ParentMessenger for MockParentMessenger {
318    async fn send_message(
319        &self,
320        _ctx: ParentRequestContext,
321        message: ParentMessage,
322    ) -> Result<MessageToParentResponse, Error> {
323        if let Ok(mut guard) = self.messages.lock() {
324            guard.push(message);
325        }
326        Ok(MessageToParentResponse {
327            accepted: true,
328            response: None,
329        })
330    }
331
332    async fn request_spawn_child(
333        &self,
334        _ctx: ParentRequestContext,
335        request: SpawnChildRequest,
336    ) -> Result<SpawnChildResponse, Error> {
337        if let Ok(mut guard) = self.spawn_requests.lock() {
338            guard.push(request);
339        }
340        Ok(SpawnChildResponse {
341            accepted: true,
342            child_pid: Some(ProcessId::new()),
343            error: None,
344        })
345    }
346
347    async fn proxy_call(
348        &self,
349        _ctx: ParentRequestContext,
350        _request: ProxyCallRequest,
351    ) -> Result<ProxyCallResponse, Error> {
352        Ok(ProxyCallResponse {
353            ok: false,
354            result: None,
355            error: Some(crate::protocol::RpcError {
356                code: "not_implemented".into(),
357                message: "mock does not proxy calls".into(),
358            }),
359        })
360    }
361}
362
363#[cfg(test)]
364#[allow(
365    clippy::panic,
366    clippy::expect_used,
367    clippy::unwrap_used,
368    clippy::unwrap_in_result,
369    clippy::panic_in_result_fn,
370    clippy::indexing_slicing,
371    clippy::arithmetic_side_effects,
372    reason = "Standard repository test boilerplate"
373)]
374mod tests {
375    use super::*;
376
377    #[crate::ctb_test("tokio")]
378    async fn mock_messenger_records_messages() -> Result<()> {
379        let messenger = MockParentMessenger::new();
380
381        let ctx = ParentRequestContext {
382            connection_id: ConnectionId::default(),
383            process_kind: Some("test".into()),
384        };
385
386        messenger
387            .send_message(ctx.clone(), ParentMessage::text("hello"))
388            .await?;
389        messenger
390            .send_message(ctx.clone(), ParentMessage::text("world"))
391            .await?;
392
393        let messages = messenger.messages();
394        assert_eq!(messages.len(), 2);
395        assert_eq!(messages[0].as_text()?, "hello");
396        assert_eq!(messages[1].as_text()?, "world");
397        Ok(())
398    }
399
400    #[crate::ctb_test("tokio")]
401    async fn mock_messenger_records_spawn_requests() -> Result<()> {
402        let messenger = MockParentMessenger::new();
403
404        let ctx = ParentRequestContext {
405            connection_id: ConnectionId::default(),
406            process_kind: Some("test".into()),
407        };
408
409        let resp = messenger
410            .request_spawn_child(
411                ctx,
412                SpawnChildRequest {
413                    kind: ChildKind::Renderer,
414                    init_data: None,
415                },
416            )
417            .await?;
418
419        assert!(resp.accepted);
420        assert!(resp.child_pid.is_some());
421
422        let requests = messenger.spawn_requests();
423        assert_eq!(requests.len(), 1);
424        assert_eq!(requests[0].kind, ChildKind::Renderer);
425        Ok(())
426    }
427
428    #[crate::ctb_test]
429    fn data_plane_ref_roundtrip() -> Result<()> {
430        use crate::data_plane::shared_memory::SharedBlobDescriptor;
431        use shared_memory::BlobId;
432        use uuid::Uuid;
433
434        let token = BlobToken {
435            id: BlobId(Uuid::new_v4()),
436            size: 128,
437            lease_ms: None,
438        };
439        let descriptor = SharedBlobDescriptor::Named("test-blob".into());
440        let data_ref =
441            DataPlaneRef::new(token.clone(), descriptor, "text/plain");
442        let msg = ParentMessage::data_plane(&data_ref)?;
443        let decoded = msg.as_data_plane_ref()?;
444        anyhow::ensure!(decoded.token == token, "tokens should match");
445        anyhow::ensure!(
446            decoded.content_type == "text/plain",
447            "content types should match"
448        );
449        Ok(())
450    }
451}