ctb_workspace_ipc/multiplex/
client.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//! RPC client helpers for the multiplexed IPC layer.
21
22use crate::multiplex::session::Session;
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::error::Error;
31use crate::error::to_ipc_error;
32use crate::protocol::{
33    Cancel, Event, Message, Request, Response, RpcError, StreamControl,
34};
35use crate::types::{ConnectionId, RequestId, StreamId};
36use anyhow::anyhow;
37use async_trait::async_trait;
38use bytes::Bytes;
39use futures_core::Stream;
40use std::collections::HashMap;
41use std::pin::Pin;
42use std::sync::Arc;
43use tokio::sync::{mpsc, oneshot};
44use tokio_stream::wrappers::ReceiverStream;
45use tracing::Instrument as _;
46
47#[expect(dead_code, reason = "potentially unused API helper")]
48pub(crate) const DEFAULT_EVENTS_CAPACITY: usize = 64;
49
50/// RPC client interface layered on a Session, with request/response correlation and cancellation.
51#[async_trait]
52pub trait RpcClient: Send + Sync {
53    /// Send a request; returns immediately after sending.
54    async fn send_request(&self, req: Request) -> Result<(), Error>;
55
56    /// Await a response with the given id.
57    async fn recv_response(&self, id: RequestId) -> Result<Response, Error>;
58
59    /// Cancel a request by id.
60    async fn cancel(&self, cancel: Cancel) -> Result<(), Error>;
61
62    /// Receive server-initiated events.
63    fn events(&self) -> Pin<Box<dyn Stream<Item = Event> + Send>>;
64}
65
66/// Streaming control plane to coordinate substreams or blob-backed flows.
67/// TODO (maybe): wire up streaming
68#[async_trait]
69pub trait StreamManager: Send + Sync {
70    async fn start(&self, ctl: StreamControl) -> Result<(), Error>;
71    async fn next(&self, ctl: StreamControl) -> Result<(), Error>;
72    async fn end(&self, ctl: StreamControl) -> Result<(), Error>;
73
74    /// Optional helper for control-plane streaming (chunked via frames).
75    fn stream_incoming(
76        &self,
77        id: StreamId,
78    ) -> Pin<Box<dyn Stream<Item = Bytes> + Send>>;
79}
80
81// ---- Default RpcClient implementation ----
82
83/// Default `RpcClient` built over a Session. It:
84/// - Correlates responses by `RequestId`.
85/// - Forwards cancellation requests (server-driven cancellation is expected).
86/// - Emits server Events via a bounded mpsc channel with backpressure.
87///
88/// The client spawns a background task to dispatch incoming Messages.
89#[derive(Default)]
90struct RpcCorrelationState {
91    inflight: HashMap<RequestId, oneshot::Sender<Response>>,
92    pending: HashMap<RequestId, Response>,
93}
94
95pub struct DefaultRpcClient<S: Session> {
96    session: Arc<S>,
97    connection_id: Option<ConnectionId>,
98    correlation: tokio::sync::Mutex<RpcCorrelationState>,
99    events_tx: mpsc::Sender<Event>,
100    events_rx: std::sync::Mutex<Option<mpsc::Receiver<Event>>>,
101    streams: Arc<tokio::sync::Mutex<HashMap<StreamId, IncomingStreamState>>>,
102}
103
104impl<S: Session + 'static> DefaultRpcClient<S> {
105    /// Construct a new `RpcClient` over the given Session. The events channel is
106    /// bounded by `events_capacity` to provide backpressure.
107    pub fn new(
108        session: std::sync::Arc<S>,
109        events_capacity: usize,
110    ) -> std::sync::Arc<Self> {
111        Self::new_with_connection_id(session, None, events_capacity)
112    }
113
114    /// Construct a new `RpcClient` with an optional connection id for logging.
115    pub fn new_with_connection_id(
116        session: std::sync::Arc<S>,
117        connection_id: Option<ConnectionId>,
118        events_capacity: usize,
119    ) -> std::sync::Arc<Self> {
120        let (events_tx, events_rx) = mpsc::channel(events_capacity);
121        let client = std::sync::Arc::new(Self {
122            session: session.clone(),
123            connection_id,
124            correlation: tokio::sync::Mutex::new(RpcCorrelationState::default()),
125            events_tx,
126            events_rx: std::sync::Mutex::new(Some(events_rx)),
127            streams: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
128        });
129
130        Self::spawn_dispatcher(client.clone());
131        client
132    }
133
134    async fn handle_stream_control(
135        &self,
136        ctl: StreamControl,
137    ) -> Result<(), Error> {
138        let id = match &ctl {
139            StreamControl::Start { id, .. } => *id,
140            StreamControl::Next { id, .. } => *id,
141            StreamControl::End { id, .. } => *id,
142        };
143
144        let span = if let Some(conn_id) = self.connection_id {
145            tracing::info_span!("ipc.rpc.stream_control", conn_id = %conn_id, stream_id = id)
146        } else {
147            tracing::info_span!("ipc.rpc.stream_control", stream_id = id)
148        };
149
150        async move {
151            match ctl {
152                StreamControl::Start { .. } => {
153                    let mut guard = self.streams.lock().await;
154                    guard
155                        .entry(id)
156                        .or_insert_with(|| IncomingStreamState::new(64));
157                    Ok(())
158                }
159                StreamControl::Next { chunk, .. } => {
160                    let Some(chunk) = chunk else {
161                        // Blob-backed or out-of-band; nothing to deliver on control plane.
162                        return Ok(());
163                    };
164
165                    let mut guard = self.streams.lock().await;
166                    let st = guard
167                        .entry(id)
168                        .or_insert_with(|| IncomingStreamState::new(64));
169                    st.tx.send(Bytes::from(chunk)).await.map_err(|e| {
170                        to_ipc_error(anyhow!("stream send failed: {e}"))
171                    })?;
172                    Ok(())
173                }
174                StreamControl::End { .. } => {
175                    let mut guard = self.streams.lock().await;
176                    guard.remove(&id);
177                    Ok(())
178                }
179            }
180        }
181        .instrument(span)
182        .await
183    }
184
185    #[cfg(test)]
186    async fn stream_count(&self) -> usize {
187        let guard = self.streams.lock().await;
188        guard.len()
189    }
190}
191
192struct IncomingStreamState {
193    tx: mpsc::Sender<Bytes>,
194    rx: Option<mpsc::Receiver<Bytes>>,
195}
196
197impl IncomingStreamState {
198    fn new(capacity: usize) -> Self {
199        let (tx, rx) = mpsc::channel(capacity);
200        Self { tx, rx: Some(rx) }
201    }
202}
203
204impl<S: Session + 'static> DefaultRpcClient<S> {
205    fn spawn_dispatcher(client: std::sync::Arc<Self>) {
206        tokio::spawn(async move {
207            loop {
208                let msg = match client.session.recv().await {
209                    Ok(Some(m)) => m,
210                    Ok(None) => {
211                        // EOF: fail all inflight waiters with an error.
212                        let mut corr = client.correlation.lock().await;
213                        for (id, sender) in corr.inflight.drain() {
214                            let _ = sender.send(Response {
215                                id,
216                                ok: false,
217                                result: None,
218                                error: Some(RpcError {
219                                    code: "eof".to_string(),
220                                    message:
221                                        "session closed while awaiting response"
222                                            .to_string(),
223                                }),
224                            });
225                        }
226                        break;
227                    }
228                    Err(e) => {
229                        // On session error, fail all inflight waiters.
230                        let mut corr = client.correlation.lock().await;
231                        for (id, sender) in corr.inflight.drain() {
232                            let _ = sender.send(Response {
233                                id,
234                                ok: false,
235                                result: None,
236                                error: Some(RpcError {
237                                    code: "session_recv_error".to_string(),
238                                    message: format!("{e:#}"),
239                                }),
240                            });
241                        }
242                        break;
243                    }
244                };
245
246                match msg {
247                    Message::Response(resp) => {
248                        let id = response_id(&resp);
249                        let span = if let Some(conn_id) = client.connection_id {
250                            tracing::info_span!("ipc.rpc.recv_response_msg", conn_id = %conn_id, request_id = id)
251                        } else {
252                            tracing::info_span!(
253                                "ipc.rpc.recv_response_msg",
254                                request_id = id
255                            )
256                        };
257                        async {
258                            let mut corr = client.correlation.lock().await;
259                            if let Some(sender) = corr.inflight.remove(&id) {
260                                let _ = sender.send(resp);
261                            } else {
262                                corr.pending.insert(id, resp);
263                            }
264                        }
265                        .instrument(span)
266                        .await;
267                    }
268                    Message::Event(ev) => {
269                        // Apply backpressure by awaiting send.
270                        if let Err(_e) = client.events_tx.send(ev).await {
271                            // Receiver dropped; ignore but keep draining input.
272                        }
273                    }
274                    Message::Stream(ctl) => {
275                        let _ = client.handle_stream_control(ctl).await;
276                    }
277                    // Not handled by client:
278                    Message::Hello(_)
279                    | Message::HelloOk(_)
280                    | Message::HelloErr(_)
281                    | Message::Request(_)
282                    | Message::Cancel(_) => {}
283                }
284            }
285        });
286    }
287
288    async fn handle_pending_response(
289        &self,
290        id: RequestId,
291    ) -> Result<Response, Error> {
292        let rx = {
293            let mut corr = self.correlation.lock().await;
294            if let Some(resp) = corr.pending.remove(&id) {
295                return Ok(resp);
296            }
297            let (tx, rx) = oneshot::channel();
298            corr.inflight.insert(id, tx);
299            rx
300        };
301
302        match rx.await {
303            Ok(resp) => Ok(resp),
304            Err(e) => Err(to_ipc_error(anyhow!(
305                "response waiter dropped for id={id:?}: {e}"
306            ))),
307        }
308    }
309}
310
311#[async_trait]
312impl<S: Session + 'static> RpcClient for DefaultRpcClient<S> {
313    /// Send the request envelope to the remote endpoint.
314    async fn send_request(&self, req: Request) -> Result<(), Error> {
315        let span = if let Some(conn_id) = self.connection_id {
316            tracing::info_span!("ipc.rpc.send_request", conn_id = %conn_id, request_id = req.id, service = %req.method.service, method = %req.method.method)
317        } else {
318            tracing::info_span!("ipc.rpc.send_request", request_id = req.id, service = %req.method.service, method = %req.method.method)
319        };
320        async move { self.session.send(&Message::Request(req)).await }
321            .instrument(span)
322            .await
323    }
324
325    /// Await the response correlated by `RequestId`. If the response arrived
326    /// before this method was called, it is returned immediately.
327    async fn recv_response(&self, id: RequestId) -> Result<Response, Error> {
328        let span = if let Some(conn_id) = self.connection_id {
329            tracing::info_span!("ipc.rpc.recv_response", conn_id = %conn_id, request_id = id)
330        } else {
331            tracing::info_span!("ipc.rpc.recv_response", request_id = id)
332        };
333        async move { self.handle_pending_response(id).await }
334            .instrument(span)
335            .await
336    }
337
338    /// Forward the cancellation to the server. Server-driven cancellation is
339    /// expected to materialize as a Response that the dispatcher routes to the
340    /// waiter. This method does not fail the waiter eagerly.
341    async fn cancel(&self, cancel: Cancel) -> Result<(), Error> {
342        let span = if let Some(conn_id) = self.connection_id {
343            tracing::info_span!("ipc.rpc.cancel", conn_id = %conn_id, request_id = cancel.id)
344        } else {
345            tracing::info_span!("ipc.rpc.cancel", request_id = cancel.id)
346        };
347        async move {
348            // Resolve any local waiter immediately.
349            {
350                let mut corr = self.correlation.lock().await;
351                if let Some(sender) = corr.inflight.remove(&cancel.id) {
352                    let _ = sender.send(Response {
353                        id: cancel.id,
354                        ok: false,
355                        result: None,
356                        error: Some(RpcError::cancelled(
357                            "request cancelled by client",
358                        )),
359                    });
360                }
361                let _ = corr.pending.remove(&cancel.id);
362            }
363
364            self.session.send(&Message::Cancel(cancel)).await
365        }
366        .instrument(span)
367        .await
368    }
369
370    fn events(&self) -> Pin<Box<dyn Stream<Item = Event> + Send>> {
371        let mut guard = match self.events_rx.lock() {
372            Ok(g) => g,
373            Err(_) => return Box::pin(futures_util::stream::empty()),
374        };
375
376        if let Some(rx) = guard.take() {
377            Box::pin(ReceiverStream::new(rx))
378        } else {
379            Box::pin(futures_util::stream::empty())
380        }
381    }
382}
383
384#[async_trait]
385impl<S: Session + 'static> StreamManager for DefaultRpcClient<S> {
386    async fn start(&self, ctl: StreamControl) -> Result<(), Error> {
387        self.session.send(&Message::Stream(ctl)).await
388    }
389
390    async fn next(&self, ctl: StreamControl) -> Result<(), Error> {
391        self.session.send(&Message::Stream(ctl)).await
392    }
393
394    async fn end(&self, ctl: StreamControl) -> Result<(), Error> {
395        self.session.send(&Message::Stream(ctl)).await
396    }
397
398    fn stream_incoming(
399        &self,
400        id: StreamId,
401    ) -> Pin<Box<dyn Stream<Item = Bytes> + Send>> {
402        let streams = self.streams.clone();
403        let (tx, rx) = mpsc::channel::<Bytes>(1);
404
405        tokio::spawn(async move {
406            let mut guard = streams.lock().await;
407            if let Some(state) = guard.get_mut(&id)
408                && let Some(mut original_rx) = state.rx.take()
409            {
410                drop(guard);
411                while let Some(bytes) = original_rx.recv().await {
412                    if tx.send(bytes).await.is_err() {
413                        break;
414                    }
415                }
416            }
417        });
418
419        Box::pin(ReceiverStream::new(rx))
420    }
421}
422
423// ---- Helpers (minimal assumptions about protocol types) ----
424
425/// Extract the `RequestId` from a Response.
426fn response_id(resp: &Response) -> RequestId {
427    resp.id
428}