ctb_workspace_ipc/
protocol.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 protocol types and message envelopes for workspace communication.
21//!
22//! This module defines transport-level envelopes and streaming controls. It
23//! intentionally avoids embedding business logic; services should delegate to
24//! external modules for actual work.
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use crate::auth::capability::{CapabilitySet, CapabilityToken};
34use crate::shared_memory::BlobToken;
35use crate::types::{RequestId, StreamId};
36use serde::{Deserialize, Serialize};
37
38/// Top-level message envelope for framed transport.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub enum Message {
41    /// Initial handshake from client to server (child -> workspace or workspace -> service).
42    Hello(Hello),
43    /// Response to Hello with bound capabilities or an error.
44    HelloOk(HelloOk),
45    HelloErr(HelloErr),
46
47    /// RPC request with correlation id.
48    Request(Request),
49    /// RPC response associated with a request id.
50    Response(Response),
51
52    /// Event (server-initiated notification).
53    Event(Event),
54
55    /// Stream control messages for high-volume data.
56    Stream(StreamControl),
57
58    /// Cancel a pending request id.
59    Cancel(Cancel),
60}
61
62/// Authentication handshake payload.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct Hello {
65    pub token: CapabilityToken,
66    /// Optional client info (version, process kind).
67    pub client_info: Option<ClientInfo>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ClientInfo {
72    pub name: String,
73    pub version: String,
74    pub process_kind: String,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct HelloOk {
79    pub bound_capabilities: CapabilitySet,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct HelloErr {
84    pub message: String,
85}
86
87/// Request envelope. The `method` is a typed identifier, and `args` is a postcard-encoded payload for the method.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Request {
90    pub id: RequestId,
91    pub method: MethodId,
92    /// Postcard-encoded args for the method.
93    pub args: Vec<u8>,
94}
95
96/// Response envelope. Either ok with a postcard-encoded result or error with a message/code.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Response {
99    pub id: RequestId,
100    pub ok: bool,
101    /// If ok, postcard-encoded result.
102    pub result: Option<Vec<u8>>,
103    /// If error, a short machine-readable code and message.
104    pub error: Option<RpcError>,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct RpcError {
109    pub code: String,
110    pub message: String,
111}
112
113/// Events are server-initiated notifications (e.g., `child_exit`,
114/// `permission_changed`).
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct Event {
117    pub topic: EventTopic,
118    /// Postcard-encoded payload per topic.
119    pub payload: Vec<u8>,
120}
121
122impl Event {
123    /// Construct an empty heartbeat event payload.
124    pub fn heartbeat() -> Self {
125        Self {
126            topic: EventTopic::Heartbeat,
127            payload: Vec::new(),
128        }
129    }
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub enum EventTopic {
134    Heartbeat,
135    ChildExited,
136    PermissionChanged,
137    StorageCompacted,
138    Custom(String),
139}
140
141/// Stream controls for large flows.
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub enum StreamControl {
144    Start {
145        id: StreamId,
146        /// Optionally pass a blob token for data plane.
147        blob: Option<BlobToken>,
148    },
149    Next {
150        id: StreamId,
151        /// Raw chunk if using control-plane streaming, else omitted when using blob.
152        chunk: Option<Vec<u8>>,
153    },
154    End {
155        id: StreamId,
156        ok: bool,
157        error: Option<String>,
158    },
159}
160
161/// A compact method identifier (service + method).
162#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
163pub struct MethodId {
164    pub service: String,
165    pub method: String,
166}
167
168/// Request cancellation for a given id.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct Cancel {
171    pub id: RequestId,
172}
173
174impl Hello {
175    /// Construct a Hello message payload.
176    pub fn new(
177        token: CapabilityToken,
178        client_info: Option<ClientInfo>,
179    ) -> Self {
180        Self { token, client_info }
181    }
182}
183
184impl HelloOk {
185    /// Construct a successful handshake response.
186    pub fn new(bound_capabilities: CapabilitySet) -> Self {
187        Self { bound_capabilities }
188    }
189}
190
191impl HelloErr {
192    /// Construct a failed handshake response with a reason.
193    pub fn new<S: Into<String>>(message: S) -> Self {
194        Self {
195            message: message.into(),
196        }
197    }
198}
199
200/// Compact helper for building a `MethodId`.
201impl MethodId {
202    pub fn new<S1, S2>(service: S1, method: S2) -> Self
203    where
204        S1: Into<String>,
205        S2: Into<String>,
206    {
207        Self {
208            service: service.into(),
209            method: method.into(),
210        }
211    }
212}
213
214impl RpcError {
215    /// Create an "unauthorized" error.
216    pub fn unauthorized<S: Into<String>>(message: S) -> Self {
217        Self {
218            code: RPC_ERROR_CODE_UNAUTHORIZED.into(),
219            message: message.into(),
220        }
221    }
222
223    /// Create a "`capability_denied`" error (e.g., quota/rate limit exceeded).
224    pub fn capability_denied<S: Into<String>>(message: S) -> Self {
225        Self {
226            code: RPC_ERROR_CODE_CAPABILITY_DENIED.into(),
227            message: message.into(),
228        }
229    }
230
231    /// Create a "cancelled" error.
232    pub fn cancelled<S: Into<String>>(message: S) -> Self {
233        Self {
234            code: RPC_ERROR_CODE_CANCELLED.into(),
235            message: message.into(),
236        }
237    }
238
239    /// Create an "internal" error.
240    pub fn internal<S: Into<String>>(message: S) -> Self {
241        Self {
242            code: RPC_ERROR_CODE_INTERNAL.into(),
243            message: message.into(),
244        }
245    }
246}
247
248impl Cancel {
249    /// Construct a Cancel payload.
250    pub fn new(id: RequestId) -> Self {
251        Self { id }
252    }
253}
254
255/// Standard RPC error codes used across the IPC boundary.
256pub const RPC_ERROR_CODE_UNAUTHORIZED: &str = "unauthorized";
257pub const RPC_ERROR_CODE_CAPABILITY_DENIED: &str = "capability_denied";
258pub const RPC_ERROR_CODE_RATE_LIMITED: &str = "rate_limited";
259pub const RPC_ERROR_CODE_CANCELLED: &str = "cancelled";
260pub const RPC_ERROR_CODE_INTERNAL: &str = "internal";
261pub const RPC_ERROR_CODE_NOT_IMPLEMENTED: &str = "not_implemented";
262
263/// When payloads are larger than this threshold, prefer blob-backed flows.
264///
265/// This is a protocol-level constant so clients and servers agree on the
266/// heuristic, but callers may still override it (e.g., for testing).
267pub const IO_NETWORK_BLOB_THRESHOLD_BYTES: u64 = 256 * 1024;
268
269/// Default chunk size used for control-plane streaming via `StreamControl::Next`.
270pub const STREAM_CONTROL_PLANE_CHUNK_BYTES: usize = 16 * 1024;
271
272impl Request {
273    /// Create a `tracing` span for handling this request.
274    ///
275    /// The span carries `request_id`, `service`, and `method` so downstream logs
276    /// can be correlated without manually repeating those fields.
277    #[must_use]
278    pub fn span(&self) -> tracing::Span {
279        tracing::info_span!(
280            "ipc.request",
281            request_id = self.id,
282            service = %self.method.service,
283            method = %self.method.method
284        )
285    }
286}
287
288impl StreamControl {
289    /// Return the stream id for all `StreamControl` variants.
290    #[must_use]
291    pub fn stream_id(&self) -> StreamId {
292        match self {
293            StreamControl::Start { id, .. } => *id,
294            StreamControl::Next { id, .. } => *id,
295            StreamControl::End { id, .. } => *id,
296        }
297    }
298
299    /// Create a `tracing` span for handling this stream control message.
300    ///
301    /// Carries `stream_id`, `variant`, `kind` (when present), and blob metadata
302    /// (when present) to correlate logs across the stream lifecycle.
303    #[must_use]
304    pub fn span(&self) -> tracing::Span {
305        match self {
306            StreamControl::Start { id, blob } => tracing::info_span!(
307                "ipc.stream",
308                stream_id = *id,
309                variant = "start",
310                blob_id =
311                    blob.as_ref().map(|b| b.id).map(tracing::field::display),
312                blob_size = blob.as_ref().map(|b| b.size),
313                blob_lease_ms = blob.as_ref().and_then(|b| b.lease_ms),
314            ),
315            StreamControl::Next { id, chunk } => tracing::info_span!(
316                "ipc.stream",
317                stream_id = *id,
318                variant = "next",
319                chunk_len = chunk.as_ref().map(std::vec::Vec::len),
320            ),
321            StreamControl::End { id, ok, error } => tracing::info_span!(
322                "ipc.stream",
323                stream_id = *id,
324                variant = "end",
325                ok = *ok,
326                error = error.as_deref(),
327            ),
328        }
329    }
330}
331
332#[cfg(test)]
333#[allow(
334    clippy::panic,
335    clippy::expect_used,
336    clippy::unwrap_used,
337    clippy::unwrap_in_result,
338    clippy::panic_in_result_fn,
339    clippy::indexing_slicing,
340    clippy::arithmetic_side_effects,
341    reason = "Standard repository test boilerplate"
342)]
343mod tests {
344    use super::*;
345    use anyhow::{Result, ensure};
346
347    use std::collections::HashMap;
348    use std::sync::Mutex;
349    use tracing::field::{Field, Visit};
350    use tracing_subscriber::layer::{Context as LayerContext, Layer};
351
352    use tracing_subscriber::registry::LookupSpan;
353
354    #[derive(Default)]
355    struct FieldCaptureVisitor {
356        fields: HashMap<String, String>,
357    }
358
359    impl Visit for FieldCaptureVisitor {
360        fn record_str(&mut self, field: &Field, value: &str) {
361            let _ = self
362                .fields
363                .insert(field.name().to_string(), value.to_string());
364        }
365
366        fn record_u64(&mut self, field: &Field, value: u64) {
367            let _ = self
368                .fields
369                .insert(field.name().to_string(), value.to_string());
370        }
371
372        fn record_i64(&mut self, field: &Field, value: i64) {
373            let _ = self
374                .fields
375                .insert(field.name().to_string(), value.to_string());
376        }
377
378        fn record_bool(&mut self, field: &Field, value: bool) {
379            let _ = self
380                .fields
381                .insert(field.name().to_string(), value.to_string());
382        }
383
384        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
385            let _ = self
386                .fields
387                .insert(field.name().to_string(), format!("{value:?}"));
388        }
389    }
390
391    #[derive(Default)]
392    struct CaptureLayer {
393        spans: Mutex<HashMap<tracing::span::Id, HashMap<String, String>>>,
394        events: Mutex<Vec<HashMap<String, String>>>,
395    }
396
397    impl CaptureLayer {
398        fn drain_events(&self) -> Vec<HashMap<String, String>> {
399            if let Ok(mut guard) = self.events.lock() {
400                std::mem::take(&mut *guard)
401            } else {
402                Vec::new()
403            }
404        }
405    }
406
407    impl<S> Layer<S> for CaptureLayer
408    where
409        S: tracing::Subscriber + for<'a> LookupSpan<'a>,
410    {
411        fn on_new_span(
412            &self,
413            attrs: &tracing::span::Attributes<'_>,
414            id: &tracing::span::Id,
415            _ctx: LayerContext<'_, S>,
416        ) {
417            let mut v = FieldCaptureVisitor::default();
418            attrs.record(&mut v);
419
420            if let Ok(mut spans) = self.spans.lock() {
421                let _ = spans.insert(id.clone(), v.fields);
422            }
423        }
424
425        fn on_event(
426            &self,
427            event: &tracing::Event<'_>,
428            ctx: LayerContext<'_, S>,
429        ) {
430            let mut merged: HashMap<String, String> = HashMap::new();
431
432            if let Some(scope) = ctx.event_scope(event)
433                && let Ok(spans) = self.spans.lock()
434            {
435                for span in scope.from_root() {
436                    if let Some(fields) = spans.get(&span.id()) {
437                        merged.extend(fields.clone());
438                    }
439                }
440            }
441
442            let mut v = FieldCaptureVisitor::default();
443            event.record(&mut v);
444            merged.extend(v.fields);
445
446            if let Ok(mut events) = self.events.lock() {
447                events.push(merged);
448            }
449        }
450    }
451
452    #[crate::ctb_test]
453    fn spans_attach_request_and_stream_fields() -> Result<()> {
454        // If this test mysteriously fails, it may be because of an issue with
455        // the logging filter. Check what get_workspace_filter is returning;
456        // maybe try just running with `trace` as the filter.
457        let req = Request {
458            id: 42,
459            method: MethodId::new("svc", "do_work"),
460            args: vec![],
461        };
462
463        let stream = StreamControl::Start {
464            id: 7,
465            blob: Some(BlobToken {
466                id: Default::default(),
467                size: 123,
468                lease_ms: Some(456),
469            }),
470        };
471
472        req.span().in_scope(|| {
473            tracing::info!("inside request span");
474        });
475
476        stream.span().in_scope(|| {
477            tracing::info!("inside stream span");
478        });
479
480        // The macro injects logs_contain() function
481        assert!(logs_contain("inside request span"));
482        assert!(logs_contain("inside stream span"));
483
484        Ok(())
485    }
486
487    /// Round-trip a value via postcard, ensuring serialized bytes are stable.
488    fn roundtrip_bytes<T>(value: &T) -> Result<()>
489    where
490        T: serde::Serialize + for<'de> serde::de::Deserialize<'de>,
491    {
492        let bytes = postcard_helpers::encode(value, "test value")?;
493        let decoded: T = postcard_helpers::decode(&bytes, "test value")?;
494        let bytes2 = postcard_helpers::encode(&decoded, "test value")?;
495        ensure!(bytes == bytes2, "postcard roundtrip bytes mismatch");
496        Ok(())
497    }
498
499    /// Round-trip `Message::Hello` via postcard.
500    #[crate::ctb_test]
501    fn message_hello_roundtrip() -> Result<()> {
502        let msg = Message::Hello(Hello {
503            token: Default::default(),
504            client_info: Some(ClientInfo {
505                name: "client".into(),
506                version: "1.0.0".into(),
507                process_kind: "test".into(),
508            }),
509        });
510        roundtrip_bytes(&msg)
511    }
512
513    /// Round-trip `Message::HelloOk` via postcard.
514    #[crate::ctb_test]
515    fn message_hello_ok_roundtrip() -> Result<()> {
516        let msg = Message::HelloOk(HelloOk {
517            bound_capabilities: Default::default(),
518        });
519        roundtrip_bytes(&msg)
520    }
521
522    /// Round-trip `Message::HelloErr` via postcard.
523    #[crate::ctb_test]
524    fn message_hello_err_roundtrip() -> Result<()> {
525        let msg = Message::HelloErr(HelloErr {
526            message: "handshake failed".into(),
527        });
528        roundtrip_bytes(&msg)
529    }
530
531    /// Round-trip `Message::Request` via postcard.
532    #[crate::ctb_test]
533    fn message_request_roundtrip() -> Result<()> {
534        let msg = Message::Request(Request {
535            id: Default::default(),
536            method: MethodId {
537                service: "svc".into(),
538                method: "do_work".into(),
539            },
540            args: vec![0x01, 0x02, 0x03],
541        });
542        roundtrip_bytes(&msg)
543    }
544
545    /// Round-trip `Message::Response(ok)` via postcard.
546    #[crate::ctb_test]
547    fn message_response_ok_roundtrip() -> Result<()> {
548        let msg = Message::Response(Response {
549            id: Default::default(),
550            ok: true,
551            result: Some(vec![0xAA, 0xBB]),
552            error: None,
553        });
554        roundtrip_bytes(&msg)
555    }
556
557    /// Round-trip `Message::Response(err)` via postcard.
558    #[crate::ctb_test]
559    fn message_response_err_roundtrip() -> Result<()> {
560        let msg = Message::Response(Response {
561            id: Default::default(),
562            ok: false,
563            result: None,
564            error: Some(RpcError {
565                code: "bad_request".into(),
566                message: "invalid input".into(),
567            }),
568        });
569        roundtrip_bytes(&msg)
570    }
571
572    /// Round-trip `Message::Event` via postcard.
573    #[crate::ctb_test]
574    fn message_event_roundtrip() -> Result<()> {
575        let msg = Message::Event(Event {
576            topic: EventTopic::Custom("custom.topic".into()),
577            payload: vec![0x10, 0x20],
578        });
579        roundtrip_bytes(&msg)
580    }
581
582    /// Round-trip `Message::Event(Heartbeat)` via postcard.
583    #[crate::ctb_test]
584    fn message_event_heartbeat_roundtrip() -> Result<()> {
585        let msg = Message::Event(Event::heartbeat());
586        roundtrip_bytes(&msg)
587    }
588
589    /// Round-trip `Message::Stream(Start)` via postcard.
590    #[crate::ctb_test]
591    fn message_stream_start_roundtrip() -> Result<()> {
592        let msg = Message::Stream(StreamControl::Start {
593            id: Default::default(),
594            blob: Some(Default::default()),
595        });
596        roundtrip_bytes(&msg)
597    }
598
599    /// Round-trip `Message::Stream(Next)` via postcard.
600    #[crate::ctb_test]
601    fn message_stream_next_roundtrip() -> Result<()> {
602        let msg = Message::Stream(StreamControl::Next {
603            id: Default::default(),
604            chunk: Some(vec![1, 2, 3, 4]),
605        });
606        roundtrip_bytes(&msg)
607    }
608
609    /// Round-trip `Message::Stream(End)` via postcard.
610    #[crate::ctb_test]
611    fn message_stream_end_roundtrip() -> Result<()> {
612        let msg = Message::Stream(StreamControl::End {
613            id: Default::default(),
614            ok: false,
615            error: Some("stream error".into()),
616        });
617        roundtrip_bytes(&msg)
618    }
619
620    /// Round-trip `Message::Cancel` via postcard.
621    #[crate::ctb_test]
622    fn message_cancel_roundtrip() -> Result<()> {
623        let msg = Message::Cancel(Cancel {
624            id: Default::default(),
625        });
626        roundtrip_bytes(&msg)
627    }
628}