ctb_workspace_ipc/services/
parent.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 messaging service for child-to-parent communication within process
21//! trees.
22//!
23//! This module provides the infrastructure for renderer and other child
24//! processes to send messages to their parent process. Messages can be:
25//! - Data plane references (shared memory for rendered output)
26//! - Control messages (e.g., requesting subprocess creation)
27//! - Status notifications
28//!
29//! The parent messenger is transport-agnostic; the actual sending is handled
30//! by the IPC session.
31
32#[allow(
33    unused_imports,
34    clippy::wildcard_imports,
35    reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38
39use anyhow::Result;
40
41use crate::error::Error;
42use crate::protocol::{Request, Response};
43use crate::router::ConnectionContext;
44use crate::router::IpcRouter;
45
46pub mod api;
47pub mod channel;
48
49pub use api::{
50    DataPlaneRef, METHOD_MESSAGE_PARENT, METHOD_PROXY_CALL,
51    METHOD_REQUEST_SPAWN_CHILD, MessageToParentRequest,
52    MessageToParentResponse, ParentMessage, ParentMessageKind, ParentMessenger,
53    ParentRequestContext, ProxyCallRequest, ProxyCallResponse,
54    SpawnChildRequest, SpawnChildResponse,
55};
56
57pub use channel::{
58    ChannelParentMessenger, ParentMessageEvent, SpawnRequestWithResponse,
59};
60
61/// Service name for parent-messaging operations.
62pub const SERVICE_NAME: &str = "parent";
63
64/// Dispatch parent service requests.
65pub(crate) async fn dispatch_parent(
66    router: &IpcRouter,
67    ctx: &ConnectionContext,
68    request: Request,
69) -> Result<Response, Error> {
70    if let Err(resp) = IpcRouter::check_service(
71        router.parent_messenger.as_ref(),
72        "parent",
73        request.id,
74    ) {
75        return Ok(resp);
76    }
77    let Some(messenger) = router.parent_messenger.as_ref() else {
78        return Ok(IpcRouter::error_response(
79            request.id,
80            "not_implemented",
81            "parent service not configured",
82        ));
83    };
84
85    let req_ctx = ParentRequestContext {
86        connection_id: ctx.id,
87        process_kind: ctx
88            .metadata
89            .as_ref()
90            .and_then(|m| m.get("process_kind"))
91            .and_then(|v| v.as_str())
92            .map(ToString::to_string),
93    };
94
95    match request.method.method.as_str() {
96        METHOD_MESSAGE_PARENT => {
97            let req: MessageToParentRequest = match IpcRouter::decode_request(
98                &request.args,
99                "parent.message_parent",
100                request.id,
101            ) {
102                Ok(req) => req,
103                Err(resp) => return Ok(resp),
104            };
105            router
106                .handle_service_call(
107                    messenger.send_message(req_ctx.clone(), req.message),
108                    request.id,
109                )
110                .await
111        }
112        METHOD_REQUEST_SPAWN_CHILD => {
113            let req: SpawnChildRequest = match IpcRouter::decode_request(
114                &request.args,
115                "parent.request_spawn_child",
116                request.id,
117            ) {
118                Ok(req) => req,
119                Err(resp) => return Ok(resp),
120            };
121            router
122                .handle_service_call(
123                    messenger.request_spawn_child(req_ctx.clone(), req),
124                    request.id,
125                )
126                .await
127        }
128        METHOD_PROXY_CALL => {
129            let req: ProxyCallRequest = match IpcRouter::decode_request(
130                &request.args,
131                "parent.proxy_call",
132                request.id,
133            ) {
134                Ok(req) => req,
135                Err(resp) => return Ok(resp),
136            };
137            router
138                .handle_service_call(
139                    messenger.proxy_call(req_ctx.clone(), req),
140                    request.id,
141                )
142                .await
143        }
144        _ => Ok(IpcRouter::error_response(
145            request.id,
146            "not_implemented",
147            "method not implemented",
148        )),
149    }
150}
151
152#[cfg(test)]
153#[allow(
154    clippy::panic,
155    clippy::expect_used,
156    clippy::unwrap_used,
157    clippy::unwrap_in_result,
158    clippy::panic_in_result_fn,
159    clippy::indexing_slicing,
160    clippy::arithmetic_side_effects,
161    reason = "Standard repository test boilerplate"
162)]
163mod tests {
164    use super::*;
165    use crate::auth::capability::{
166        CapabilitySet, MethodRule, MethodSelector, ServiceName,
167    };
168    use crate::protocol::MethodId;
169    use crate::router::{ConnectionContext, Router};
170    use crate::types::ConnectionId;
171    use ipc::ChildKind;
172    use std::collections::HashMap;
173    use std::sync::Arc;
174
175    #[crate::ctb_test("tokio")]
176    async fn routes_parent_message_parent() -> Result<()> {
177        let mock = api::MockParentMessenger::new();
178        let router = IpcRouter::new().with_parent_messenger(Arc::new(mock));
179
180        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
181        allowed.insert(
182            ServiceName(SERVICE_NAME.to_string()),
183            vec![MethodRule {
184                method: MethodSelector::Exact(METHOD_MESSAGE_PARENT.into()),
185                quotas: None,
186            }],
187        );
188
189        let ctx = ConnectionContext {
190            id: ConnectionId::default(),
191            capabilities: CapabilitySet {
192                allowed,
193                global_limits: None,
194            },
195            metadata: None,
196        };
197
198        let req_payload = MessageToParentRequest {
199            message: ParentMessage::text("hello from child"),
200        };
201        let args = postcard_helpers::encode(&req_payload, "request")?;
202        let req = Request {
203            id: 1,
204            method: MethodId {
205                service: SERVICE_NAME.into(),
206                method: METHOD_MESSAGE_PARENT.into(),
207            },
208            args,
209        };
210
211        let resp = router.dispatch(&ctx, req).await?;
212        anyhow::ensure!(resp.ok, "expected ok response: {resp:?}");
213        Ok(())
214    }
215
216    #[crate::ctb_test("tokio")]
217    async fn routes_parent_request_spawn_child() -> Result<()> {
218        let mock = api::MockParentMessenger::new();
219        let router = IpcRouter::new().with_parent_messenger(Arc::new(mock));
220
221        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
222        allowed.insert(
223            ServiceName(SERVICE_NAME.to_string()),
224            vec![MethodRule {
225                method: MethodSelector::Exact(
226                    METHOD_REQUEST_SPAWN_CHILD.into(),
227                ),
228                quotas: None,
229            }],
230        );
231
232        let ctx = ConnectionContext {
233            id: ConnectionId::default(),
234            capabilities: CapabilitySet {
235                allowed,
236                global_limits: None,
237            },
238            metadata: None,
239        };
240
241        let req_payload = SpawnChildRequest {
242            kind: ChildKind::Renderer,
243            init_data: Some(b"initial doc".to_vec()),
244        };
245        let args = postcard_helpers::encode(&req_payload, "request")?;
246        let req = Request {
247            id: 2,
248            method: MethodId {
249                service: SERVICE_NAME.into(),
250                method: METHOD_REQUEST_SPAWN_CHILD.into(),
251            },
252            args,
253        };
254
255        let resp = router.dispatch(&ctx, req).await?;
256        anyhow::ensure!(resp.ok, "expected ok response: {resp:?}");
257        let decoded: SpawnChildResponse = postcard_helpers::decode(
258            resp.result.as_deref().ok_or_else(|| {
259                anyhow::anyhow!("missing result bytes: {resp:?}")
260            })?,
261            "spawn response",
262        )?;
263        anyhow::ensure!(decoded.accepted, "expected accepted response");
264        anyhow::ensure!(decoded.child_pid.is_some(), "missing child pid");
265        Ok(())
266    }
267
268    #[crate::ctb_test("tokio")]
269    async fn parent_service_unauthorized_without_capability() -> Result<()> {
270        let mock = api::MockParentMessenger::new();
271        let router = IpcRouter::new().with_parent_messenger(Arc::new(mock));
272
273        // No capabilities granted
274        let ctx = ConnectionContext {
275            id: ConnectionId::default(),
276            capabilities: CapabilitySet::default(),
277            metadata: None,
278        };
279
280        let req_payload = MessageToParentRequest {
281            message: ParentMessage::text("hello"),
282        };
283        let args = postcard_helpers::encode(&req_payload, "request")?;
284        let req = Request {
285            id: 3,
286            method: MethodId {
287                service: SERVICE_NAME.into(),
288                method: METHOD_MESSAGE_PARENT.into(),
289            },
290            args,
291        };
292
293        let resp = router.dispatch(&ctx, req).await?;
294        anyhow::ensure!(!resp.ok, "expected denied response: {resp:?}");
295        let err = resp
296            .error
297            .as_ref()
298            .ok_or_else(|| anyhow::anyhow!("missing error: {resp:?}"))?;
299        anyhow::ensure!(
300            err.code == "unauthorized",
301            "unexpected error: {err:?}"
302        );
303        Ok(())
304    }
305}