ctb_workspace_ipc/
peer.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//! Bidirectional IPC peer.
21//!
22//! The IPC stack supports a single multiplexed session that can carry both
23//! Requests and Responses. Many processes need to act as both:
24//! - a server (dispatch incoming Requests through an `IpcRouter`)
25//! - a client (send Requests and await correlated Responses)
26//!
27//! `IpcPeer` runs a background receive loop that handles both directions over
28//! one connection.
29
30#[allow(
31    unused_imports,
32    clippy::wildcard_imports,
33    reason = "Standard workspace module prelude"
34)]
35use crate::utilities::*;
36
37use crate::error::Error;
38use crate::multiplex::session::Session;
39use crate::protocol::{Cancel, Message, MethodId, Request, Response, RpcError};
40use crate::router::{ConnectionContext, IpcRouter, Router};
41use crate::types::RequestId;
42
43use std::collections::HashMap;
44use std::sync::Arc;
45use std::sync::atomic::AtomicBool;
46use std::sync::atomic::{AtomicU64, Ordering};
47
48use tokio::sync::{Mutex, Notify, oneshot};
49
50/// A bidirectional peer over a single [`Session`].
51///
52/// The peer owns a background receive loop that:
53/// - dispatches incoming requests through the provided router
54/// - correlates incoming responses with inflight client calls
55#[derive(Debug)]
56pub struct IpcPeer {
57    session: Arc<dyn Session>,
58    router: Arc<IpcRouter>,
59    ctx: ConnectionContext,
60    send_lock: Mutex<()>,
61    next_id: AtomicU64,
62    inflight: Mutex<HashMap<RequestId, oneshot::Sender<Response>>>,
63    active_requests: Mutex<HashMap<RequestId, Option<oneshot::Sender<()>>>>,
64    pending: Mutex<HashMap<RequestId, Response>>,
65    closed: AtomicBool,
66    closed_notify: Notify,
67}
68
69impl IpcPeer {
70    pub fn session(&self) -> &dyn Session {
71        self.session.as_ref()
72    }
73
74    /// Create a new peer and spawn its background dispatcher.
75    pub fn new(
76        session: Arc<dyn Session>,
77        router: Arc<IpcRouter>,
78        ctx: ConnectionContext,
79    ) -> Arc<Self> {
80        let peer = Arc::new(Self {
81            session,
82            router,
83            ctx,
84            send_lock: Mutex::new(()),
85            next_id: AtomicU64::new(1),
86            inflight: Mutex::new(HashMap::new()),
87            active_requests: Mutex::new(HashMap::new()),
88            pending: Mutex::new(HashMap::new()),
89            closed: AtomicBool::new(false),
90            closed_notify: Notify::new(),
91        });
92
93        Self::spawn_dispatch_loop(Arc::clone(&peer));
94        peer
95    }
96
97    fn spawn_dispatch_loop(peer: Arc<Self>) {
98        tokio::spawn(async move {
99            loop {
100                let msg = match peer.session.recv().await {
101                    Ok(Some(m)) => m,
102                    Ok(None) => break,
103                    Err(e) => {
104                        tracing::warn!("[peer] recv error: {e:#}");
105                        break;
106                    }
107                };
108
109                match msg {
110                    Message::Request(req) => {
111                        let request_id = req.id;
112                        let (cancel_tx, cancel_rx) = oneshot::channel();
113                        {
114                            let mut active = peer.active_requests.lock().await;
115                            if let std::collections::hash_map::Entry::Vacant(
116                                entry,
117                            ) = active.entry(request_id)
118                            {
119                                entry.insert(Some(cancel_tx));
120                            } else {
121                                warn_fmt!(
122                                    "Duplicate active IPC request id: {}",
123                                    request_id
124                                );
125                                continue;
126                            }
127                        }
128                        // Important: request handlers may perform outbound
129                        // calls (and await responses) over the same session.
130                        // If we await the handler inline here, the receive
131                        // loop can't process those responses and can
132                        // deadlock. Spawn per-request tasks to keep the recv
133                        // loop responsive.
134                        let peer = Arc::clone(&peer);
135                        tokio::spawn(async move {
136                            let resp = tokio::select! {
137                                biased;
138                                _ = cancel_rx => Response {
139                                    id: request_id,
140                                    ok: false,
141                                    result: None,
142                                    error: Some(RpcError::cancelled("Request cancelled")),
143                                },
144                                result = peer.router.dispatch_with_session(
145                                    &peer.ctx, Arc::clone(&peer.session), req,
146                                ) => match result {
147                                    Ok(response) => response,
148                                    Err(error) => {
149                                        warn_fmt!("IPC dispatch error for request {}: {:#}", request_id, error);
150                                        IpcRouter::error_response(
151                                            request_id, "internal", &format!("dispatch failed: {error:#}"),
152                                        )
153                                    }
154                                }
155                            };
156                            peer.active_requests
157                                .lock()
158                                .await
159                                .remove(&request_id);
160
161                            let _guard = peer.send_lock.lock().await;
162                            if let Err(e) = peer
163                                .session
164                                .send(&Message::Response(resp))
165                                .await
166                            {
167                                tracing::warn!(
168                                    "[peer] send error (response) for request_id={request_id}: {e:#}"
169                                );
170                            }
171                        });
172                    }
173                    Message::Response(resp) => {
174                        let id = resp.id;
175                        if let Some(sender) =
176                            peer.inflight.lock().await.remove(&id)
177                        {
178                            let _ = sender.send(resp);
179                        } else {
180                            peer.pending.lock().await.insert(id, resp);
181                        }
182                    }
183                    Message::Cancel(Cancel { id }) => {
184                        let cancel_tx = peer
185                            .active_requests
186                            .lock()
187                            .await
188                            .get_mut(&id)
189                            .and_then(Option::take);
190                        if let Some(cancel_tx) = cancel_tx {
191                            let _ = cancel_tx.send(());
192                        }
193                        if let Err(error) =
194                            peer.router.observe_cancel(&peer.ctx, id).await
195                        {
196                            warn_fmt!(
197                                "Failed to observe IPC cancellation {}: {:#}",
198                                id,
199                                error
200                            );
201                        }
202                    }
203                    // Not handled by the peer today.
204                    Message::Event(_)
205                    | Message::Stream(_)
206                    | Message::Hello(_)
207                    | Message::HelloOk(_)
208                    | Message::HelloErr(_) => {}
209                }
210            }
211
212            peer.active_requests.lock().await.clear();
213            // Fail any inflight waiters on exit.
214            let mut inflight = peer.inflight.lock().await;
215            for (id, sender) in inflight.drain() {
216                let _ = sender.send(Response {
217                    id,
218                    ok: false,
219                    result: None,
220                    error: Some(RpcError {
221                        code: "eof".to_string(),
222                        message: "session closed".to_string(),
223                    }),
224                });
225            }
226
227            peer.closed.store(true, Ordering::Release);
228            peer.closed_notify.notify_waiters();
229        });
230    }
231
232    fn next_request_id(&self) -> RequestId {
233        self.next_id.fetch_add(1, Ordering::Relaxed)
234    }
235
236    async fn take_pending(&self, id: RequestId) -> Option<Response> {
237        self.pending.lock().await.remove(&id)
238    }
239
240    /// Wait until the underlying session receive loop exits.
241    pub async fn wait_closed(&self) {
242        if self.closed.load(Ordering::Acquire) {
243            return;
244        }
245        self.closed_notify.notified().await;
246    }
247
248    /// Send an RPC request and await its response.
249    pub async fn call(
250        &self,
251        method: MethodId,
252        args: Vec<u8>,
253    ) -> Result<Response, Error> {
254        let id = self.next_request_id();
255
256        if let Some(resp) = self.take_pending(id).await {
257            return Ok(resp);
258        }
259
260        let (tx, rx) = oneshot::channel();
261        self.inflight.lock().await.insert(id, tx);
262
263        let req = Request { id, method, args };
264        let _guard = self.send_lock.lock().await;
265        self.session.send(&Message::Request(req)).await?;
266        drop(_guard);
267
268        rx.await.map_err(|e| {
269            anyhow::anyhow!("response waiter dropped for id={id}: {e}").into()
270        })
271    }
272
273    #[cfg(unix)]
274    pub async fn recv_fd(&self) -> Result<std::os::unix::io::RawFd, Error> {
275        self.session.recv_fd().await
276    }
277
278    /// Send an RPC request and associated Unix FDs, then await its response.
279    ///
280    /// This is used for data-plane parameters (memfd + `SCM_RIGHTS`) where the
281    /// control message contains metadata and the actual FD is transferred
282    /// out-of-band.
283    #[cfg(unix)]
284    pub async fn call_raw_with_fds(
285        &self,
286        method: MethodId,
287        args: Vec<u8>,
288        fds: Vec<std::os::unix::io::RawFd>,
289    ) -> Result<Response, Error> {
290        let id = self.next_request_id();
291
292        if let Some(resp) = self.take_pending(id).await {
293            return Ok(resp);
294        }
295
296        let (tx, rx) = oneshot::channel();
297        self.inflight.lock().await.insert(id, tx);
298
299        let req = Request { id, method, args };
300
301        {
302            let _guard = self.send_lock.lock().await;
303            self.session.send(&Message::Request(req)).await?;
304
305            for fd in fds {
306                self.session.send_fd(fd).await?;
307            }
308        }
309
310        rx.await.map_err(|e| {
311            Error::from(anyhow::anyhow!(
312                "response waiter dropped for id={id}: {e}"
313            ))
314        })
315    }
316
317    #[cfg(unix)]
318    pub async fn call_postcard_with_blob_fd<Req, Resp>(
319        &self,
320        service: &str,
321        method: &str,
322        req: &Req,
323        blob_descriptor: &crate::data_plane::shared_memory::SharedBlobDescriptor,
324    ) -> Result<Resp, Error>
325    where
326        Req: serde::Serialize,
327        Resp: for<'de> serde::Deserialize<'de>,
328    {
329        let args =
330            postcard_helpers::encode(req, "request").map_err(Error::from)?;
331
332        let id = self.next_request_id();
333
334        if let Some(resp) = self.take_pending(id).await {
335            if !resp.ok {
336                // Reason for fallback: failed IPC call response lacking error detail defaults to "unknown error"
337                let msg = resp
338                    .error
339                    .map_or_else(|| "unknown error".into(), |e| e.message);
340                return Err(anyhow::anyhow!("IPC call failed: {msg}").into());
341            }
342            let Some(bytes) = resp.result else {
343                return Err(anyhow::anyhow!("IPC call missing result").into());
344            };
345            return postcard_helpers::decode::<Resp>(&bytes, "response")
346                .map_err(Error::from);
347        }
348
349        let (tx, rx) = oneshot::channel();
350        self.inflight.lock().await.insert(id, tx);
351
352        let req_msg = Request {
353            id,
354            method: MethodId {
355                service: service.into(),
356                method: method.into(),
357            },
358            args,
359        };
360
361        {
362            let _guard = self.send_lock.lock().await;
363            self.session.send(&Message::Request(req_msg)).await?;
364
365            if crate::data_plane::shared_memory::descriptor_requires_fd_transfer(
366                blob_descriptor,
367            ) {
368                crate::data_plane::send_blob_fd(
369                    self.session(),
370                    blob_descriptor,
371                )
372                .await?;
373            }
374        }
375
376        let resp = rx.await.map_err(|e| {
377            Error::from(anyhow::anyhow!(
378                "response waiter dropped for id={id}: {e}"
379            ))
380        })?;
381        if !resp.ok {
382            // Reason for fallback: failed IPC call response lacking error detail defaults to "unknown error"
383            let msg = resp
384                .error
385                .map_or_else(|| "unknown error".into(), |e| e.message);
386            return Err(anyhow::anyhow!("IPC call failed: {msg}").into());
387        }
388
389        let Some(bytes) = resp.result else {
390            return Err(anyhow::anyhow!("IPC call missing result").into());
391        };
392
393        postcard_helpers::decode::<Resp>(&bytes, "response")
394            .map_err(Error::from)
395    }
396}