ctb_workspace_ipc/
connection.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//! IPC socket connection management and framing abstractions.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::collections::HashMap;
30use std::sync::Arc;
31
32use async_trait::async_trait;
33use ctb_utilities::ipc::service_traits::{
34    ChildIpcContext, FormatsClientTrait, IoClientTrait, NetworkClientTrait,
35    RendererClientTrait, RuntimeClientTrait, StorageClientTrait,
36};
37use once_cell::sync::OnceCell;
38
39use crate::auth::capability::CapabilityToken;
40use crate::auth::capability::TokenValidator;
41use crate::auth::capability::trusted_workspace_capabilities;
42use crate::multiplex::session::{FramedSession, Session};
43use crate::peer::IpcPeer;
44use crate::process_manager::ProcessManager;
45use crate::protocol::{ClientInfo, Hello, MethodId};
46use crate::router::{ConnectionContext, IpcRouter};
47use crate::transport::{LocalSocketTransportFactory, TransportFactory};
48use crate::types::{ConnectionId, ProcessId};
49use ipc::ChildKind;
50
51pub async fn connect_to_workspace(
52    socket_path: &str,
53    token: &str,
54    client: ClientInfo,
55    router: IpcRouter,
56) -> Result<Arc<IpcPeer>> {
57    // Connect to parent
58    let factory = LocalSocketTransportFactory;
59    let conn = factory.connect(socket_path).await?;
60    let conn = Arc::new(conn);
61    let session = Arc::new(FramedSession::new(conn));
62
63    // Perform handshake
64    let hello =
65        Hello::new(CapabilityToken(token.to_string()), Some(client.clone()));
66    let caps = session.client_handshake(hello).await?;
67    let cap_keys = format!("{:?}", caps.allowed.keys());
68
69    // NOTE: `caps` returned from the handshake represent what *this child* is
70    // allowed to call on the workspace. Incoming requests on this connection
71    // originate from the workspace, so we authorize them using a trusted
72    // workspace capability set.
73    let ctx = ConnectionContext {
74        id: ConnectionId::default(),
75        capabilities: trusted_workspace_capabilities(),
76        metadata: None,
77    };
78
79    let session: Arc<dyn Session> = session;
80    let peer = IpcPeer::new(session, Arc::new(router), ctx);
81
82    debug_fmt!(
83        "[{:?}] Connected with capabilities: {:?}",
84        client.process_kind,
85        cap_keys
86    );
87
88    Ok(peer)
89}
90
91/// Shared, reusable server-side IPC connection wiring.
92///
93/// This encapsulates the handshake + peer creation that most workspaces need.
94/// Callers can optionally use [`WorkspaceConnectionHandler::attach_peer_by_process_kind`]
95/// to map the connection to a pending child process.
96#[derive(Debug, Clone)]
97pub struct WorkspaceConnectionHandler {
98    router: Arc<IpcRouter>,
99    validator: Arc<dyn TokenValidator>,
100}
101
102impl WorkspaceConnectionHandler {
103    /// Construct a new handler.
104    pub fn new(
105        router: Arc<IpcRouter>,
106        validator: Arc<dyn TokenValidator>,
107    ) -> Self {
108        Self { router, validator }
109    }
110
111    /// Perform server handshake and create a new [`IpcPeer`].
112    pub async fn accept_peer<T>(
113        &self,
114        session: Arc<FramedSession<T>>,
115        conn_id: ConnectionId,
116    ) -> Result<Arc<IpcPeer>>
117    where
118        T: crate::transport::FramedConnection
119            + Clone
120            + std::fmt::Debug
121            + 'static,
122    {
123        let _caps = session
124            .server_handshake(
125                self.validator.as_ref(),
126                self.router.as_ref(),
127                conn_id,
128            )
129            .await
130            .context("server handshake")?;
131
132        let ctx = self.router.get(&conn_id).ok_or_else(|| {
133            anyhow::anyhow!("connection context missing for {conn_id}")
134        })?;
135
136        let session: Arc<dyn Session> = session;
137        Ok(IpcPeer::new(session, Arc::clone(&self.router), ctx))
138    }
139
140    /// Best-effort attach a peer to a known pending process based on
141    /// `process_kind` handshake metadata.
142    ///
143    /// This is a convenience for the common pattern:
144    /// - workspace spawns a child and records its PID under a process kind key
145    /// - child connects and identifies itself (`process_kind`)
146    /// - workspace attaches the connection id to that PID and stores the peer
147    pub async fn attach_peer_by_process_kind(
148        &self,
149        conn_id: ConnectionId,
150        peer: Arc<IpcPeer>,
151        process_manager: &dyn ProcessManager,
152        pending_processes: &tokio::sync::Mutex<HashMap<String, ProcessId>>,
153        peers: &tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>,
154    ) -> Result<Option<ProcessId>> {
155        let Some(ctx) = self.router.get(&conn_id) else {
156            return Ok(None);
157        };
158
159        let kind = ctx
160            .metadata
161            .as_ref()
162            .and_then(|m| m.get("process_kind"))
163            .and_then(|v| v.as_str())
164            .map(ToString::to_string);
165
166        let Some(kind) = kind else {
167            return Ok(None);
168        };
169
170        let maybe_pid = pending_processes.lock().await.remove(&kind);
171        let Some(pid) = maybe_pid else {
172            return Ok(None);
173        };
174
175        if let Err(e) = process_manager.attach_connection(pid, conn_id).await {
176            tracing::warn!(
177                "attach_connection failed for pid={pid} conn_id={conn_id}: {e:#}"
178            );
179        }
180
181        peers.lock().await.insert(pid, peer);
182        Ok(Some(pid))
183    }
184
185    /// End-to-end helper: accept + create peer, then best-effort attach.
186    pub async fn handle_connection_with_pending_processes<T>(
187        &self,
188        session: Arc<FramedSession<T>>,
189        conn_id: ConnectionId,
190        process_manager: &dyn ProcessManager,
191        pending_processes: &tokio::sync::Mutex<HashMap<String, ProcessId>>,
192        peers: &tokio::sync::Mutex<HashMap<ProcessId, Arc<IpcPeer>>>,
193    ) -> Result<()>
194    where
195        T: crate::transport::FramedConnection
196            + Clone
197            + std::fmt::Debug
198            + 'static,
199    {
200        let peer = self.accept_peer(session, conn_id).await?;
201        let _ = self
202            .attach_peer_by_process_kind(
203                conn_id,
204                peer,
205                process_manager,
206                pending_processes,
207                peers,
208            )
209            .await?;
210        Ok(())
211    }
212}
213
214/// IPC context implementation for child processes using an `IpcPeer`.
215///
216/// This struct wraps an `Arc<IpcPeer>` and implements `ChildIpcContext`,
217/// enabling child processes to request spawning of sub-processes and
218/// communicate with the workspace.
219#[derive(Debug, Clone)]
220pub struct PeerChildIpcContext {
221    peer: Arc<IpcPeer>,
222}
223
224impl PeerChildIpcContext {
225    /// Create a new `PeerChildIpcContext` from an `IpcPeer`.
226    pub fn new(peer: Arc<IpcPeer>) -> Self {
227        Self { peer }
228    }
229
230    pub(crate) fn peer(&self) -> Arc<IpcPeer> {
231        Arc::clone(&self.peer)
232    }
233}
234
235/// A `ChildIpcContext` that can be wired up after connecting.
236///
237/// Child processes need an `IpcRouter` (and thus their services) constructed
238/// before the IPC handshake completes. Some services (notably the runtime)
239/// need a `ChildIpcContext` to make outbound IPC calls back to the workspace.
240///
241/// This type enables that wiring without requiring the service constructors to
242/// have direct access to the eventually-created `IpcPeer`.
243#[derive(Debug, Default)]
244pub struct DeferredChildIpcContext {
245    inner: OnceCell<PeerChildIpcContext>,
246}
247
248impl DeferredChildIpcContext {
249    /// Create a new deferred IPC context.
250    pub fn new() -> Self {
251        Self::default()
252    }
253
254    /// Attach the connected peer.
255    ///
256    /// This should be called exactly once after `connect_to_workspace`.
257    pub fn attach_peer(&self, peer: Arc<IpcPeer>) -> Result<()> {
258        if self.inner.set(PeerChildIpcContext::new(peer)).is_err() {
259            anyhow::bail!("IPC context already initialized");
260        }
261        Ok(())
262    }
263
264    fn ctx(&self) -> Result<&PeerChildIpcContext> {
265        self.inner
266            .get()
267            .ok_or_else(|| anyhow::anyhow!("IPC context not initialized yet"))
268    }
269
270    pub(crate) fn peer(&self) -> Result<Arc<IpcPeer>> {
271        Ok(self.ctx()?.peer())
272    }
273}
274
275#[async_trait]
276impl ChildIpcContext for DeferredChildIpcContext {
277    async fn request_spawn_formats(
278        &self,
279        init_data: Option<Vec<u8>>,
280    ) -> Result<Box<dyn FormatsClientTrait>> {
281        self.ctx()?.request_spawn_formats(init_data).await
282    }
283
284    async fn request_spawn_io(
285        &self,
286        init_data: Option<Vec<u8>>,
287    ) -> Result<Box<dyn IoClientTrait>> {
288        self.ctx()?.request_spawn_io(init_data).await
289    }
290
291    async fn request_spawn_network(
292        &self,
293        init_data: Option<Vec<u8>>,
294    ) -> Result<Box<dyn NetworkClientTrait>> {
295        self.ctx()?.request_spawn_network(init_data).await
296    }
297
298    async fn request_spawn_renderer(
299        &self,
300        init_data: Option<Vec<u8>>,
301    ) -> Result<Box<dyn RendererClientTrait>> {
302        self.ctx()?.request_spawn_renderer(init_data).await
303    }
304
305    async fn request_spawn_runtime(
306        &self,
307        init_data: Option<Vec<u8>>,
308    ) -> Result<Box<dyn RuntimeClientTrait>> {
309        self.ctx()?.request_spawn_runtime(init_data).await
310    }
311
312    async fn request_spawn_storage(
313        &self,
314        init_data: Option<Vec<u8>>,
315    ) -> Result<Box<dyn StorageClientTrait>> {
316        self.ctx()?.request_spawn_storage(init_data).await
317    }
318
319    async fn send_to_parent(&self, message: &str) -> Result<()> {
320        self.ctx()?.send_to_parent(message).await
321    }
322
323    async fn send_data_plane_message(
324        &self,
325        bytes: Vec<u8>,
326        content_type: &str,
327    ) -> Result<()> {
328        self.ctx()?
329            .send_data_plane_message(bytes, content_type)
330            .await
331    }
332
333    async fn request_workspace_shutdown(
334        &self,
335        reason: Option<String>,
336    ) -> Result<()> {
337        self.ctx()?.request_workspace_shutdown(reason).await
338    }
339
340    async fn call_raw(
341        &self,
342        service: &str,
343        method: &str,
344        args: Vec<u8>,
345    ) -> Result<Vec<u8>> {
346        self.ctx()?.call_raw(service, method, args).await
347    }
348}
349
350#[async_trait]
351impl ChildIpcContext for PeerChildIpcContext {
352    async fn request_spawn_formats(
353        &self,
354        init_data: Option<Vec<u8>>,
355    ) -> Result<Box<dyn FormatsClientTrait>> {
356        let pid = crate::peer_clients::request_spawn_child(
357            &self.peer,
358            ChildKind::Formats,
359            init_data,
360        )
361        .await?;
362        Ok(crate::services::formats::peer_formats_client(
363            Arc::clone(&self.peer),
364            pid,
365        ))
366    }
367
368    async fn request_spawn_io(
369        &self,
370        init_data: Option<Vec<u8>>,
371    ) -> Result<Box<dyn IoClientTrait>> {
372        let pid = crate::peer_clients::request_spawn_child(
373            &self.peer,
374            ChildKind::Io,
375            init_data,
376        )
377        .await?;
378        Ok(crate::services::io::peer_io_client(
379            Arc::clone(&self.peer),
380            pid,
381        ))
382    }
383
384    async fn request_spawn_network(
385        &self,
386        init_data: Option<Vec<u8>>,
387    ) -> Result<Box<dyn NetworkClientTrait>> {
388        let pid = crate::peer_clients::request_spawn_child(
389            &self.peer,
390            ChildKind::Network,
391            init_data,
392        )
393        .await?;
394        Ok(crate::services::network::peer_network_client(
395            Arc::clone(&self.peer),
396            pid,
397        ))
398    }
399
400    async fn request_spawn_runtime(
401        &self,
402        init_data: Option<Vec<u8>>,
403    ) -> Result<Box<dyn RuntimeClientTrait>> {
404        let pid = crate::peer_clients::request_spawn_child(
405            &self.peer,
406            ChildKind::Runtime,
407            init_data,
408        )
409        .await?;
410        Ok(crate::services::runtime::peer_runtime_client(
411            Arc::clone(&self.peer),
412            pid,
413        ))
414    }
415
416    async fn request_spawn_renderer(
417        &self,
418        init_data: Option<Vec<u8>>,
419    ) -> Result<Box<dyn RendererClientTrait>> {
420        let pid = crate::peer_clients::request_spawn_child(
421            &self.peer,
422            ChildKind::Renderer,
423            init_data,
424        )
425        .await?;
426        Ok(crate::services::renderer::peer_renderer_client(
427            Arc::clone(&self.peer),
428            pid,
429        ))
430    }
431
432    async fn request_spawn_storage(
433        &self,
434        init_data: Option<Vec<u8>>,
435    ) -> Result<Box<dyn StorageClientTrait>> {
436        let pid = crate::peer_clients::request_spawn_child(
437            &self.peer,
438            ChildKind::Storage,
439            init_data,
440        )
441        .await?;
442        Ok(crate::services::storage::peer_storage_client(
443            Arc::clone(&self.peer),
444            pid,
445        ))
446    }
447
448    async fn send_to_parent(&self, message: &str) -> Result<()> {
449        crate::peer_clients::send_to_parent(&self.peer, message).await
450    }
451
452    async fn send_data_plane_message(
453        &self,
454        bytes: Vec<u8>,
455        content_type: &str,
456    ) -> Result<()> {
457        crate::peer_clients::send_data_plane_message(
458            &self.peer,
459            bytes,
460            content_type,
461        )
462        .await
463    }
464
465    async fn request_workspace_shutdown(
466        &self,
467        reason: Option<String>,
468    ) -> Result<()> {
469        crate::peer_clients::request_workspace_shutdown(&self.peer, reason)
470            .await
471    }
472
473    async fn call_raw(
474        &self,
475        service: &str,
476        method: &str,
477        args: Vec<u8>,
478    ) -> Result<Vec<u8>> {
479        let resp = self
480            .peer
481            .call(
482                MethodId {
483                    service: service.to_string(),
484                    method: method.to_string(),
485                },
486                args,
487            )
488            .await
489            .map_err(|e| anyhow::anyhow!("IPC call_raw failed: {e}"))?;
490
491        crate::ensure_response_ok(&resp, "IPC call_raw")?;
492        // Reason for fallback: successful IPC response with null result defaults to serde_json::Value::Null
493        Ok(resp.result.unwrap_or_default())
494    }
495}