syncular_client/
realtime_round.rs1use crate::{MessageStreamScanner, TransportError};
25
26pub const REALTIME_TAG_DELTA: u8 = 0x00;
28pub const REALTIME_TAG_ROUND: u8 = 0x01;
29
30#[derive(Debug)]
33pub enum RoundInbound {
34 Delta(Vec<u8>),
37 RoundProgress,
40 RoundComplete(Vec<u8>),
43 Ignored,
46}
47
48#[derive(Default)]
53pub struct RealtimeRound {
54 scanner: Option<MessageStreamScanner>,
58}
59
60impl RealtimeRound {
61 pub fn new() -> Self {
62 Self::default()
63 }
64
65 pub fn in_flight(&self) -> bool {
68 self.scanner.is_some()
69 }
70
71 pub fn begin(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
80 if self.scanner.is_some() {
81 return Err(TransportError::new(
82 "sync.transport_failed",
83 "a realtime sync round is already in flight (§8.7 one round per connection)",
84 ));
85 }
86 self.scanner = Some(MessageStreamScanner::new());
87 let mut framed = Vec::with_capacity(request.len() + 1);
88 framed.push(REALTIME_TAG_ROUND);
89 framed.extend_from_slice(request);
90 Ok(framed)
91 }
92
93 pub fn route_binary(&mut self, frame: &[u8]) -> Result<RoundInbound, TransportError> {
101 if frame.is_empty() {
102 return Ok(RoundInbound::Ignored);
103 }
104 let tag = frame[0];
105 let body = &frame[1..];
106 match tag {
107 REALTIME_TAG_ROUND => {
108 let Some(scanner) = self.scanner.as_mut() else {
109 return Ok(RoundInbound::Ignored);
113 };
114 match scanner.push(body) {
115 Ok(None) => Ok(RoundInbound::RoundProgress),
116 Ok(Some(done)) => {
117 self.scanner = None;
118 if done.excess > 0 {
119 return Err(TransportError::new(
120 "sync.transport_failed",
121 "realtime round response has bytes past END (§8.7)",
122 ));
123 }
124 Ok(RoundInbound::RoundComplete(done.message))
125 }
126 Err(error) => {
127 self.scanner = None;
128 Err(TransportError::new(
129 "sync.transport_failed",
130 format!("realtime round response decode error: {}", error.detail),
131 ))
132 }
133 }
134 }
135 REALTIME_TAG_DELTA => Ok(RoundInbound::Delta(body.to_vec())),
136 _ => Ok(RoundInbound::Ignored),
139 }
140 }
141
142 pub fn abort(&mut self) {
145 self.scanner = None;
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use ssp2::encode_message;
153 use ssp2::model::{Frame, Message, MsgKind};
154
155 fn response_bytes() -> Vec<u8> {
156 let message = Message {
158 wire_version: ssp2::decode::WIRE_VERSION,
159 msg_kind: MsgKind::Response,
160 frames: vec![Frame::RespHeader {
161 required_schema_version: None,
162 latest_schema_version: None,
163 log_epoch: "epoch-1".to_owned(),
164 reset_required: false,
165 }],
166 };
167 encode_message(&message)
168 }
169
170 fn tagged(tag: u8, body: &[u8]) -> Vec<u8> {
171 let mut v = vec![tag];
172 v.extend_from_slice(body);
173 v
174 }
175
176 #[test]
177 fn begin_frames_request_with_round_tag_and_marks_in_flight() {
178 let mut round = RealtimeRound::new();
179 assert!(!round.in_flight());
180 let framed = round.begin(&[0xde, 0xad]).unwrap();
181 assert_eq!(framed, vec![REALTIME_TAG_ROUND, 0xde, 0xad]);
182 assert!(round.in_flight());
183 }
184
185 #[test]
186 fn second_begin_while_in_flight_is_rejected() {
187 let mut round = RealtimeRound::new();
188 round.begin(&[0x01]).unwrap();
189 let err = round.begin(&[0x02]).unwrap_err();
190 assert_eq!(err.code, "sync.transport_failed");
191 assert!(err.message.contains("one round"));
192 }
193
194 #[test]
195 fn single_chunk_response_completes_and_clears_in_flight() {
196 let response = response_bytes();
197 let mut round = RealtimeRound::new();
198 round.begin(&[0x00]).unwrap();
199 let frame = tagged(REALTIME_TAG_ROUND, &response);
200 match round.route_binary(&frame).unwrap() {
201 RoundInbound::RoundComplete(bytes) => assert_eq!(bytes, response),
202 _ => panic!("expected RoundComplete"),
203 }
204 assert!(!round.in_flight(), "round clears after END");
205 }
206
207 #[test]
208 fn chunked_response_reassembles_across_arbitrary_boundaries() {
209 let response = response_bytes();
210 for split in 1..response.len() {
211 let mut round = RealtimeRound::new();
212 round.begin(&[0x00]).unwrap();
213 let first = tagged(REALTIME_TAG_ROUND, &response[..split]);
214 assert!(matches!(
215 round.route_binary(&first).unwrap(),
216 RoundInbound::RoundProgress
217 ));
218 let second = tagged(REALTIME_TAG_ROUND, &response[split..]);
219 match round.route_binary(&second).unwrap() {
220 RoundInbound::RoundComplete(bytes) => {
221 assert_eq!(bytes, response, "split {split}")
222 }
223 _ => panic!("split {split}: expected RoundComplete"),
224 }
225 }
226 }
227
228 #[test]
229 fn keepalive_chunks_keep_the_round_in_flight_until_the_response_ends() {
230 let header_len = response_bytes().len() - 5;
233 let mut message = ssp2::decode_message(&response_bytes()).unwrap();
234 message.frames.extend([Frame::Keepalive, Frame::Keepalive]);
235 let response = encode_message(&message);
236 let mut round = RealtimeRound::new();
237 round.begin(&[0x00]).unwrap();
238 let mut chunks = vec![&response[..header_len]];
239 chunks.extend(response[header_len..response.len() - 5].chunks(5));
240 for chunk in chunks {
241 assert!(matches!(
242 round
243 .route_binary(&tagged(REALTIME_TAG_ROUND, chunk))
244 .unwrap(),
245 RoundInbound::RoundProgress
246 ));
247 }
248 match round
249 .route_binary(&tagged(REALTIME_TAG_ROUND, &response[response.len() - 5..]))
250 .unwrap()
251 {
252 RoundInbound::RoundComplete(bytes) => assert_eq!(bytes, response),
253 _ => panic!("expected RoundComplete"),
254 }
255 }
256
257 #[test]
258 fn delta_during_round_is_queued_not_applied_to_round() {
259 let response = response_bytes();
260 let mut round = RealtimeRound::new();
261 round.begin(&[0x00]).unwrap();
262 let delta = tagged(REALTIME_TAG_DELTA, &[0xaa, 0xbb]);
266 match round.route_binary(&delta).unwrap() {
267 RoundInbound::Delta(body) => assert_eq!(body, vec![0xaa, 0xbb]),
268 _ => panic!("expected Delta"),
269 }
270 assert!(round.in_flight(), "delta does not end the round");
271 let frame = tagged(REALTIME_TAG_ROUND, &response);
273 assert!(matches!(
274 round.route_binary(&frame).unwrap(),
275 RoundInbound::RoundComplete(_)
276 ));
277 }
278
279 #[test]
280 fn bytes_past_end_fail_the_round() {
281 let mut response = response_bytes();
282 response.extend_from_slice(&[0xff, 0xff]);
283 let mut round = RealtimeRound::new();
284 round.begin(&[0x00]).unwrap();
285 let frame = tagged(REALTIME_TAG_ROUND, &response);
286 let err = round.route_binary(&frame).unwrap_err();
287 assert_eq!(err.code, "sync.transport_failed");
288 assert!(err.message.contains("past END"));
289 assert!(!round.in_flight());
290 }
291
292 #[test]
293 fn round_chunk_with_no_round_in_flight_is_ignored() {
294 let mut round = RealtimeRound::new();
295 let frame = tagged(REALTIME_TAG_ROUND, &[0x01, 0x02]);
296 assert!(matches!(
297 round.route_binary(&frame).unwrap(),
298 RoundInbound::Ignored
299 ));
300 }
301
302 #[test]
303 fn unknown_tag_is_ignored() {
304 let mut round = RealtimeRound::new();
305 round.begin(&[0x00]).unwrap();
306 let frame = tagged(0x7f, &[0x01]);
307 assert!(matches!(
308 round.route_binary(&frame).unwrap(),
309 RoundInbound::Ignored
310 ));
311 assert!(round.in_flight());
312 }
313}