Skip to main content

spoolframe_protocol/
rpc.rs

1//! The RPC stream of `spoolframe/client/1`. Every request goes in this
2//! wrapper: a peer that does not know it fails to decode the request, so
3//! it never loses the wrapper's guarantees without notice.
4
5use crate::{PlaybackHandle, RequestEnvelope, Response};
6use serde::{Deserialize, Serialize};
7
8/// A process incarnation and its clock at the time of the reply. Operation
9/// expiry uses this clock, not the client's wall clock.
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct ServerInstance {
12    pub id: String,
13    pub time_ms: u64,
14}
15
16/// One invocation, retained across transport retries. An expired invocation
17/// or one from another server incarnation must never execute again.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct Operation {
20    pub id: String,
21    pub instance: String,
22    pub expires_at_ms: u64,
23}
24
25pub const OPERATION_WINDOW_MS: u64 = 15 * 60 * 1000;
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct RpcRequest {
29    pub envelope: RequestEnvelope,
30    pub operation: Option<Operation>,
31    pub expected_revision: Option<u64>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct PlaybackRevision {
36    pub handle: PlaybackHandle,
37    pub revision: u64,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct RpcReply {
42    pub response: Response,
43    pub playback: Option<PlaybackRevision>,
44}
45
46impl From<Response> for RpcReply {
47    fn from(response: Response) -> Self {
48        Self {
49            response,
50            playback: None,
51        }
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct RpcResponse {
57    pub server: ServerInstance,
58    pub reply: RpcReply,
59}
60
61#[cfg(test)]
62mod tests {
63    //! Mandatory revision-2 envelopes and bounded multipart replies.
64    use crate::codec::{self, CodecError, MAX_FRAME, MAX_REPLY};
65    use crate::rpc::{RpcRequest, RpcResponse, ServerInstance};
66    use crate::{Reply, Request, RequestEnvelope, Response};
67
68    #[test]
69    fn a_revision_one_envelope_is_not_a_revision_two_request() {
70        let old = RequestEnvelope {
71            session: None,
72            request: Request::Ping,
73        };
74        assert!(codec::decode::<RpcRequest>(&codec::encode(&old).unwrap()).is_err());
75    }
76
77    #[tokio::test]
78    async fn a_large_reply_round_trips_across_bounded_chunks() {
79        let reply = RpcResponse {
80            server: ServerInstance {
81                id: "process".into(),
82                time_ms: 1,
83            },
84            reply: Response::Ok(Reply::Manifest {
85                text: "x".repeat(MAX_FRAME as usize * 2),
86            })
87            .into(),
88        };
89        let mut bytes = Vec::new();
90        codec::write_reply(&mut bytes, &reply).await.unwrap();
91        let mut offset = 8;
92        while offset < bytes.len() {
93            let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap());
94            assert!(length > 0 && length <= MAX_FRAME);
95            offset += 4 + length as usize;
96        }
97        assert_eq!(offset, bytes.len());
98        assert_eq!(
99            codec::read_reply::<_, RpcResponse>(&mut bytes.as_slice())
100                .await
101                .unwrap(),
102            reply
103        );
104    }
105
106    /// Review 2026-10-12: the whole announced length was reserved as soon
107    /// as it was read, so a reply announcing 64 MiB and sending 100 bytes
108    /// held 64 MiB.
109    #[tokio::test]
110    async fn a_reply_that_stalls_holds_little_more_than_what_arrived() {
111        use std::future::Future;
112        use std::task::{Context, Waker};
113        use tokio::io::AsyncWriteExt;
114        let (mut reader, mut writer) = tokio::io::duplex(1 << 16);
115        // The largest reply announced, and 100 bytes of its first frame
116        // sent. The writer stays open: the read waits for the rest.
117        let head = [
118            (MAX_REPLY as u64).to_be_bytes().as_slice(),
119            MAX_FRAME.to_be_bytes().as_slice(),
120            &[0; 100],
121        ]
122        .concat();
123        writer.write_all(&head).await.unwrap();
124        let mut bytes = Vec::new();
125        {
126            let read = std::pin::pin!(codec::read_reply_bytes(&mut reader, &mut bytes, MAX_REPLY));
127            // One poll reads all that was sent, then waits.
128            let polled = read.poll(&mut Context::from_waker(Waker::noop()));
129            assert!(polled.is_pending());
130        }
131        assert!(
132            bytes.capacity() <= 64 << 10,
133            "{} bytes held for 100 received",
134            bytes.capacity()
135        );
136        drop(writer);
137    }
138
139    #[tokio::test]
140    async fn oversized_and_malformed_replies_are_refused_before_allocation_or_decode() {
141        for length in [0, MAX_REPLY as u64 + 1, u64::MAX] {
142            assert!(matches!(
143                codec::read_reply::<_, Response>(&mut length.to_be_bytes().as_slice()).await,
144                Err(CodecError::TooLarge { .. })
145            ));
146        }
147        for (length, chunk) in [(10u64, 0u32), (10, 11), (MAX_REPLY as u64, MAX_FRAME + 1)] {
148            let bytes = [
149                length.to_be_bytes().as_slice(),
150                chunk.to_be_bytes().as_slice(),
151            ]
152            .concat();
153            assert!(matches!(
154                codec::read_reply::<_, Response>(&mut bytes.as_slice()).await,
155                Err(CodecError::Decode(_))
156            ));
157        }
158        let truncated = [
159            10u64.to_be_bytes().as_slice(),
160            10u32.to_be_bytes().as_slice(),
161            b"short",
162        ]
163        .concat();
164        assert!(matches!(
165            codec::read_reply::<_, Response>(&mut truncated.as_slice()).await,
166            Err(CodecError::Io(_))
167        ));
168        let mut bytes = Vec::new();
169        assert!(matches!(
170            codec::write_reply(&mut bytes, &"x".repeat(MAX_REPLY + 1)).await,
171            Err(CodecError::TooLarge { .. })
172        ));
173        assert!(bytes.is_empty());
174    }
175}