1use crate::{PlaybackHandle, RequestEnvelope, Response};
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct ServerInstance {
11 pub id: String,
12 pub time_ms: u64,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Operation {
19 pub id: String,
20 pub instance: String,
21 pub expires_at_ms: u64,
22}
23
24pub const OPERATION_WINDOW_MS: u64 = 15 * 60 * 1000;
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct RpcRequest {
28 pub envelope: RequestEnvelope,
29 pub operation: Option<Operation>,
30 pub expected_revision: Option<u64>,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct PlaybackRevision {
35 pub handle: PlaybackHandle,
36 pub revision: u64,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct RpcReply {
41 pub response: Response,
42 pub playback: Option<PlaybackRevision>,
43}
44
45impl From<Response> for RpcReply {
46 fn from(response: Response) -> Self {
47 Self {
48 response,
49 playback: None,
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct RpcResponse {
56 pub server: ServerInstance,
57 pub reply: RpcReply,
58}
59
60#[cfg(test)]
61mod tests {
62 use crate::codec::{self, CodecError, MAX_FRAME, MAX_REPLY};
64 use crate::rpc::{RpcRequest, RpcResponse, ServerInstance};
65 use crate::{Reply, Request, RequestEnvelope, Response};
66
67 #[test]
68 fn a_revision_one_envelope_is_not_a_revision_two_request() {
69 let old = RequestEnvelope {
70 session: None,
71 request: Request::Ping,
72 };
73 assert!(codec::decode::<RpcRequest>(&codec::encode(&old).unwrap()).is_err());
74 }
75
76 #[tokio::test]
77 async fn a_large_reply_round_trips_across_bounded_chunks() {
78 let reply = RpcResponse {
79 server: ServerInstance {
80 id: "process".into(),
81 time_ms: 1,
82 },
83 reply: Response::Ok(Reply::Manifest {
84 text: "x".repeat(MAX_FRAME as usize * 2),
85 })
86 .into(),
87 };
88 let mut bytes = Vec::new();
89 codec::write_reply(&mut bytes, &reply).await.unwrap();
90 let mut offset = 8;
91 while offset < bytes.len() {
92 let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap());
93 assert!(length > 0 && length <= MAX_FRAME);
94 offset += 4 + length as usize;
95 }
96 assert_eq!(offset, bytes.len());
97 assert_eq!(
98 codec::read_reply::<_, RpcResponse>(&mut bytes.as_slice())
99 .await
100 .unwrap(),
101 reply
102 );
103 }
104
105 #[tokio::test]
109 async fn a_reply_that_stalls_holds_little_more_than_what_arrived() {
110 use std::future::Future;
111 use std::task::{Context, Waker};
112 use tokio::io::AsyncWriteExt;
113 let (mut reader, mut writer) = tokio::io::duplex(1 << 16);
114 let head = [
117 (MAX_REPLY as u64).to_be_bytes().as_slice(),
118 MAX_FRAME.to_be_bytes().as_slice(),
119 &[0; 100],
120 ]
121 .concat();
122 writer.write_all(&head).await.unwrap();
123 let mut bytes = Vec::new();
124 {
125 let read = std::pin::pin!(codec::read_reply_bytes(&mut reader, &mut bytes, MAX_REPLY));
126 let polled = read.poll(&mut Context::from_waker(Waker::noop()));
128 assert!(polled.is_pending());
129 }
130 assert!(
131 bytes.capacity() <= 64 << 10,
132 "{} bytes held for 100 received",
133 bytes.capacity()
134 );
135 drop(writer);
136 }
137
138 #[tokio::test]
139 async fn oversized_and_malformed_replies_are_refused_before_allocation_or_decode() {
140 for length in [0, MAX_REPLY as u64 + 1, u64::MAX] {
141 assert!(matches!(
142 codec::read_reply::<_, Response>(&mut length.to_be_bytes().as_slice()).await,
143 Err(CodecError::TooLarge { .. })
144 ));
145 }
146 for (length, chunk) in [(10u64, 0u32), (10, 11), (MAX_REPLY as u64, MAX_FRAME + 1)] {
147 let bytes = [
148 length.to_be_bytes().as_slice(),
149 chunk.to_be_bytes().as_slice(),
150 ]
151 .concat();
152 assert!(matches!(
153 codec::read_reply::<_, Response>(&mut bytes.as_slice()).await,
154 Err(CodecError::Decode(_))
155 ));
156 }
157 let truncated = [
158 10u64.to_be_bytes().as_slice(),
159 10u32.to_be_bytes().as_slice(),
160 b"short",
161 ]
162 .concat();
163 assert!(matches!(
164 codec::read_reply::<_, Response>(&mut truncated.as_slice()).await,
165 Err(CodecError::Io(_))
166 ));
167 let mut bytes = Vec::new();
168 assert!(matches!(
169 codec::write_reply(&mut bytes, &"x".repeat(MAX_REPLY + 1)).await,
170 Err(CodecError::TooLarge { .. })
171 ));
172 assert!(bytes.is_empty());
173 }
174}