ctb_workspace_ipc/
multiplex.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//! Session and RPC client implementations for framed IPC with postcard.
21//!
22//! This module provides:
23//! - A Session implementation that serializes and deserializes Message values
24//!   using postcard over a framed transport.
25//! - A default `RpcClient` that correlates request/response pairs by `RequestId`,
26//!   forwards cancellations, and exposes an events stream with bounded
27//!   backpressure.
28//!
29//! `StreamManager` is transport-only; data processing is delegated to services.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace prelude"
35)]
36use crate::utilities::*;
37
38pub mod blob_store;
39pub mod client;
40pub mod session;
41
42// ---- Tests: mocked Session, correlation, out-of-order, cancellation ----
43// These tests use a mock Session and the public RpcClient API.
44
45#[cfg(test)]
46#[allow(
47    clippy::panic,
48    clippy::expect_used,
49    clippy::unwrap_used,
50    clippy::unwrap_in_result,
51    clippy::panic_in_result_fn,
52    clippy::indexing_slicing,
53    clippy::arithmetic_side_effects,
54    reason = "Standard repository test boilerplate"
55)]
56mod tests {
57    use crate::error::{Error, to_ipc_error};
58    use crate::multiplex::client::{
59        DEFAULT_EVENTS_CAPACITY, DefaultRpcClient, RpcClient,
60    };
61    use crate::multiplex::session::Session;
62    use crate::protocol::MethodId;
63    use crate::protocol::RpcError;
64    use crate::protocol::{Cancel, Message, Request, Response};
65    use anyhow::anyhow;
66    use async_trait::async_trait;
67    use tokio::sync::mpsc;
68
69    use super::*;
70    use anyhow::Result;
71
72    /// A simple in-memory Session mock backed by channels carrying Message.
73    #[derive(Debug)]
74    struct MockSession {
75        to_server: mpsc::Sender<Message>,
76        from_server: tokio::sync::Mutex<mpsc::Receiver<Message>>,
77    }
78
79    #[async_trait]
80    impl Session for MockSession {
81        async fn send(&self, msg: &Message) -> Result<(), Error> {
82            self.to_server
83                .send(msg.clone())
84                .await
85                .map_err(|e| to_ipc_error(anyhow!("send failed: {e}")))
86        }
87
88        async fn recv(&self) -> Result<Option<Message>, Error> {
89            let mut rx = self.from_server.lock().await;
90            Ok(rx.recv().await)
91        }
92    }
93
94    fn make_mock_session() -> (
95        std::sync::Arc<MockSession>,
96        mpsc::Receiver<Message>,
97        mpsc::Sender<Message>,
98    ) {
99        let (to_server_tx, to_server_rx) = mpsc::channel(16);
100        let (from_server_tx, from_server_rx) = mpsc::channel(16);
101        let session = std::sync::Arc::new(MockSession {
102            to_server: to_server_tx,
103            from_server: tokio::sync::Mutex::new(from_server_rx),
104        });
105        (session, to_server_rx, from_server_tx)
106    }
107
108    /// Sends two concurrent requests and verifies that out-of-order responses
109    /// are matched to the correct waiters.
110    #[crate::ctb_test("tokio")]
111    async fn rpc_correlation_out_of_order() -> Result<()> {
112        let (session, mut to_server_rx, from_server_tx) = make_mock_session();
113        let client = DefaultRpcClient::new(session, DEFAULT_EVENTS_CAPACITY);
114
115        // Create two requests
116        let req1 = Request {
117            id: 1,
118            method: MethodId {
119                service: "test".to_string(),
120                method: "method1".to_string(),
121            },
122            args: vec![],
123        };
124        let req2 = Request {
125            id: 2,
126            method: MethodId {
127                service: "test".to_string(),
128                method: "method2".to_string(),
129            },
130            args: vec![],
131        };
132
133        // Send requests concurrently
134        let send1 = client.send_request(req1.clone());
135        let send2 = client.send_request(req2.clone());
136        tokio::try_join!(send1, send2)?;
137
138        let sent_req1 = to_server_rx.recv().await.context("missing req1")?;
139        let sent_req2 = to_server_rx.recv().await.context("missing req2")?;
140        assert!(matches!(sent_req1, Message::Request(r) if r.id == 1));
141        assert!(matches!(sent_req2, Message::Request(r) if r.id == 2));
142
143        // Spawn tasks to await responses
144        let client2 = client.clone();
145        let recv1_handle =
146            tokio::spawn(async move { client.recv_response(1).await });
147        let recv2_handle =
148            tokio::spawn(async move { client2.recv_response(2).await });
149
150        // Send responses out of order (id 2 first, then id 1)
151        let resp2 = Response {
152            id: 2,
153            ok: true,
154            result: Some(vec![0xBB]),
155            error: None,
156        };
157        let resp1 = Response {
158            id: 1,
159            ok: true,
160            result: Some(vec![0xAA]),
161            error: None,
162        };
163        from_server_tx.send(Message::Response(resp2)).await?;
164        from_server_tx.send(Message::Response(resp1)).await?;
165
166        let (resp1_recv, resp2_recv) =
167            tokio::try_join!(recv1_handle, recv2_handle)?;
168        let resp1_recv = resp1_recv?;
169        let resp2_recv = resp2_recv?;
170        assert_eq!(resp1_recv.id, 1);
171        assert_eq!(resp1_recv.result, Some(vec![0xAA]));
172        assert_eq!(resp2_recv.id, 2);
173        assert_eq!(resp2_recv.result, Some(vec![0xBB]));
174        Ok(())
175    }
176
177    /// Cancels a request and verifies downstream behavior (e.g., server sends
178    /// a cancellation response routed to the correct waiter).
179    #[crate::ctb_test("tokio")]
180    async fn rpc_cancellation() -> Result<()> {
181        let (session, mut to_server_rx, from_server_tx) = make_mock_session();
182        let client = DefaultRpcClient::new(session, DEFAULT_EVENTS_CAPACITY);
183
184        // Send a request
185        let req = Request {
186            id: 1,
187            method: MethodId {
188                service: "test".to_string(),
189                method: "method".to_string(),
190            },
191            args: vec![],
192        };
193        client.send_request(req).await?;
194
195        // Verify request was sent
196        let sent_req = to_server_rx.recv().await.context("missing request")?;
197        assert!(matches!(sent_req, Message::Request(r) if r.id == 1));
198
199        // Cancel the request
200        let cancel = Cancel { id: 1 };
201        client.cancel(cancel).await?;
202
203        // Verify cancel was sent
204        let sent_cancel =
205            to_server_rx.recv().await.context("missing cancel")?;
206        assert!(matches!(sent_cancel, Message::Cancel(c) if c.id == 1));
207
208        // Server sends a cancellation response too (client should handle either).
209        let resp = Response {
210            id: 1,
211            ok: false,
212            result: None,
213            error: Some(RpcError::cancelled("request cancelled")),
214        };
215        from_server_tx.send(Message::Response(resp)).await?;
216
217        let recv_resp = client.recv_response(1).await?;
218        assert_eq!(recv_resp.id, 1);
219        assert!(!recv_resp.ok);
220        assert_eq!(recv_resp.error.unwrap().code, "cancelled");
221        Ok(())
222    }
223
224    static CANCEL_TEST_STARTED: tokio::sync::Notify =
225        tokio::sync::Notify::const_new();
226    static CANCEL_TEST_DROPPED: tokio::sync::Notify =
227        tokio::sync::Notify::const_new();
228
229    #[ipc_method]
230    async fn wait_for_cancellation() -> Result<()> {
231        struct WorkGuard;
232        impl Drop for WorkGuard {
233            fn drop(&mut self) {
234                CANCEL_TEST_DROPPED.notify_one();
235            }
236        }
237        let _guard = WorkGuard;
238        CANCEL_TEST_STARTED.notify_one();
239        std::future::pending::<()>().await;
240        Ok(())
241    }
242
243    /// Cancel an in-flight request and ensure work stops and a cancelled
244    /// response is sent by the real peer dispatcher.
245    #[crate::ctb_test("tokio")]
246    async fn server_cancel_stops_inflight_fetch() -> Result<()> {
247        use crate::auth::capability::{
248            CapabilitySet, MethodRule, MethodSelector, ServiceName,
249        };
250        use crate::router::{ConnectionContext, IpcRouter};
251        let (session, mut to_server_rx, from_server_tx) = make_mock_session();
252        let method = "ipc.wait_for_cancellation";
253        let mut allowed = std::collections::HashMap::new();
254        allowed.insert(
255            ServiceName("workspace".to_string()),
256            vec![MethodRule {
257                method: MethodSelector::Exact(method.to_string()),
258                quotas: None,
259            }],
260        );
261        let context = ConnectionContext {
262            id: crate::types::ConnectionId::default(),
263            capabilities: CapabilitySet {
264                allowed,
265                global_limits: None,
266            },
267            metadata: None,
268        };
269        let peer = crate::peer::IpcPeer::new(
270            session,
271            std::sync::Arc::new(IpcRouter::new()),
272            context,
273        );
274        from_server_tx
275            .send(Message::Request(Request {
276                id: 7,
277                method: MethodId {
278                    service: "workspace".into(),
279                    method: method.into(),
280                },
281                args: postcard_helpers::encode(
282                    &(),
283                    "cancellation test arguments",
284                )?,
285            }))
286            .await?;
287        let timeout = std::time::Duration::from_secs(10);
288        tokio::time::timeout(timeout, CANCEL_TEST_STARTED.notified()).await?;
289        from_server_tx.send(Message::Cancel(Cancel::new(7))).await?;
290        let msg = tokio::time::timeout(timeout, to_server_rx.recv())
291            .await?
292            .context("missing response")?;
293        let Message::Response(resp) = msg else {
294            anyhow::bail!("expected Response");
295        };
296        assert_eq!(resp.id, 7);
297        assert!(!resp.ok);
298        assert_eq!(resp.error.context("missing error")?.code, "cancelled");
299        tokio::time::timeout(timeout, CANCEL_TEST_DROPPED.notified()).await?;
300        to_server_rx.try_recv().unwrap_err();
301        drop(from_server_tx);
302        tokio::time::timeout(timeout, peer.wait_closed()).await?;
303        Ok(())
304    }
305}