1use crate::msg::{ExchangeId, SessionId};
34use crate::platform::{Duration, Instant};
35
36use super::status::Status;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40struct Window {
41 session: Option<SessionId>,
43 exchange: ExchangeId,
45 deadline: Instant,
47}
48
49#[derive(Debug, Clone)]
55pub struct TimedWindows<const N: usize> {
56 windows: [Option<Window>; N],
57}
58
59impl<const N: usize> Default for TimedWindows<N> {
60 fn default() -> Self {
61 Self::new()
62 }
63}
64
65impl<const N: usize> TimedWindows<N> {
66 #[must_use]
68 pub const fn new() -> Self {
69 Self { windows: [None; N] }
70 }
71
72 pub fn open(
87 &mut self,
88 session: Option<SessionId>,
89 exchange: ExchangeId,
90 timeout_ms: u16,
91 sent_at: Instant,
92 ) -> crate::Result<()> {
93 let window = Window {
94 session,
95 exchange,
96 deadline: sent_at.saturating_add(Duration::from_millis(u64::from(timeout_ms))),
97 };
98 if let Some(slot) = self.slot_for(session, exchange) {
99 *slot = Some(window);
100 return Ok(());
101 }
102 if let Some(slot) = self.windows.iter_mut().find(|slot| slot.is_none()) {
103 *slot = Some(window);
104 return Ok(());
105 }
106 let oldest_expired = self
111 .windows
112 .iter_mut()
113 .filter(|slot| slot.is_some_and(|w| w.deadline <= sent_at))
114 .min_by_key(|slot| slot.map(|w| w.deadline));
115 if let Some(slot) = oldest_expired {
116 *slot = Some(window);
117 return Ok(());
118 }
119 Err(crate::Error::new(crate::ErrorCode::NoSpace))
120 }
121
122 pub fn check(
136 &mut self,
137 session: Option<SessionId>,
138 exchange: ExchangeId,
139 timed_request: bool,
140 now: Instant,
141 ) -> core::result::Result<bool, Status> {
142 let Some(slot) = self.slot_for(session, exchange) else {
143 return if timed_request {
146 Err(Status::TimedRequestMismatch)
147 } else {
148 Ok(false)
149 };
150 };
151 let expired = slot.is_some_and(|window| now > window.deadline);
152 *slot = None;
153 if expired {
154 return Err(Status::Timeout);
158 }
159 if !timed_request {
160 return Err(Status::TimedRequestMismatch);
162 }
163 Ok(true)
164 }
165
166 pub fn close(&mut self, session: Option<SessionId>, exchange: ExchangeId) {
171 if let Some(slot) = self.slot_for(session, exchange) {
172 *slot = None;
173 }
174 }
175
176 pub fn close_session(&mut self, session: Option<SessionId>) {
178 for slot in &mut self.windows {
179 if slot.is_some_and(|window| window.session == session) {
180 *slot = None;
181 }
182 }
183 }
184
185 pub fn reap(&mut self, now: Instant) -> usize {
191 let mut reaped = 0usize;
192 for slot in &mut self.windows {
193 if slot.is_some_and(|window| now > window.deadline) {
194 *slot = None;
195 reaped = reaped.saturating_add(1);
196 }
197 }
198 reaped
199 }
200
201 #[must_use]
203 pub fn len(&self) -> usize {
204 self.windows.iter().filter(|slot| slot.is_some()).count()
205 }
206
207 #[must_use]
209 pub fn is_empty(&self) -> bool {
210 self.len() == 0
211 }
212
213 #[must_use]
215 pub fn next_deadline(&self) -> Option<Instant> {
216 self.windows
217 .iter()
218 .filter_map(|slot| slot.map(|window| window.deadline))
219 .min()
220 }
221
222 fn slot_for(
223 &mut self,
224 session: Option<SessionId>,
225 exchange: ExchangeId,
226 ) -> Option<&mut Option<Window>> {
227 self.windows.iter_mut().find(|slot| {
228 slot.is_some_and(|window| window.session == session && window.exchange == exchange)
229 })
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 const SESSION: Option<SessionId> = Some(SessionId(7));
238 const EXCHANGE: ExchangeId = ExchangeId(42);
239
240 fn at(ms: u64) -> Instant {
241 Instant::ZERO.saturating_add(Duration::from_millis(ms))
242 }
243
244 #[test]
245 fn an_untimed_request_with_no_window_proceeds() {
246 let mut windows = TimedWindows::<2>::new();
247 assert_eq!(windows.check(SESSION, EXCHANGE, false, at(0)), Ok(false));
248 }
249
250 #[test]
251 fn a_timed_request_inside_the_window_proceeds() {
252 let mut windows = TimedWindows::<2>::new();
253 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
254 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(999)), Ok(true));
255 }
256
257 #[test]
258 fn the_deadline_is_inclusive_of_its_last_instant() {
259 let mut windows = TimedWindows::<2>::new();
262 windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
263 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(100)), Ok(true));
264
265 let mut windows = TimedWindows::<2>::new();
266 windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
267 assert_eq!(
268 windows.check(SESSION, EXCHANGE, true, at(101)),
269 Err(Status::Timeout)
270 );
271 }
272
273 #[test]
274 fn the_clock_starts_when_the_status_response_is_sent() {
275 let mut windows = TimedWindows::<2>::new();
279 windows.open(SESSION, EXCHANGE, 100, at(50)).expect("open");
281 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(150)), Ok(true));
282 }
283
284 #[test]
285 fn an_expired_window_is_timeout_not_mismatch() {
286 let mut windows = TimedWindows::<2>::new();
287 windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
288 assert_eq!(
289 windows.check(SESSION, EXCHANGE, true, at(11)),
290 Err(Status::Timeout)
291 );
292 }
293
294 #[test]
295 fn expiry_is_checked_before_the_flag() {
296 let mut windows = TimedWindows::<2>::new();
299 windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
300 assert_eq!(
301 windows.check(SESSION, EXCHANGE, false, at(11)),
302 Err(Status::Timeout)
303 );
304 }
305
306 #[test]
307 fn a_timed_window_with_an_untimed_request_is_a_mismatch() {
308 let mut windows = TimedWindows::<2>::new();
310 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
311 assert_eq!(
312 windows.check(SESSION, EXCHANGE, false, at(1)),
313 Err(Status::TimedRequestMismatch)
314 );
315 }
316
317 #[test]
318 fn an_untimed_window_with_a_timed_request_is_a_mismatch() {
319 let mut windows = TimedWindows::<2>::new();
322 assert_eq!(
323 windows.check(SESSION, EXCHANGE, true, at(0)),
324 Err(Status::TimedRequestMismatch)
325 );
326 }
327
328 #[test]
329 fn a_window_is_consumed_by_the_request_it_admits() {
330 let mut windows = TimedWindows::<2>::new();
333 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
334 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
335 assert_eq!(
336 windows.check(SESSION, EXCHANGE, true, at(2)),
337 Err(Status::TimedRequestMismatch)
338 );
339 assert!(windows.is_empty());
340 }
341
342 #[test]
343 fn a_window_is_consumed_even_by_a_request_it_refuses() {
344 let mut windows = TimedWindows::<2>::new();
345 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
346 assert_eq!(
347 windows.check(SESSION, EXCHANGE, false, at(1)),
348 Err(Status::TimedRequestMismatch)
349 );
350 assert!(windows.is_empty());
351 }
352
353 #[test]
354 fn windows_are_scoped_to_their_exchange_and_session() {
355 let mut windows = TimedWindows::<4>::new();
358 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
359 assert_eq!(
360 windows.check(SESSION, ExchangeId(43), true, at(1)),
361 Err(Status::TimedRequestMismatch)
362 );
363 assert_eq!(
364 windows.check(Some(SessionId(8)), EXCHANGE, true, at(1)),
365 Err(Status::TimedRequestMismatch)
366 );
367 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
369 }
370
371 #[test]
372 fn a_second_timed_request_on_one_exchange_replaces_the_first() {
373 let mut windows = TimedWindows::<2>::new();
374 windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
375 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
376 assert_eq!(windows.len(), 1, "one transaction, one deadline");
377 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(500)), Ok(true));
378 }
379
380 #[test]
381 fn a_full_table_of_live_windows_refuses() {
382 let mut windows = TimedWindows::<2>::new();
383 windows
384 .open(SESSION, ExchangeId(1), 1000, at(0))
385 .expect("open");
386 windows
387 .open(SESSION, ExchangeId(2), 1000, at(0))
388 .expect("open");
389 assert!(
390 windows.open(SESSION, ExchangeId(3), 1000, at(0)).is_err(),
391 "§8.7.3.2's BUSY case"
392 );
393 assert_eq!(windows.check(SESSION, ExchangeId(1), true, at(1)), Ok(true));
395 }
396
397 #[test]
398 fn a_full_table_gives_up_its_oldest_expired_window_first() {
399 let mut windows = TimedWindows::<2>::new();
400 windows
401 .open(SESSION, ExchangeId(1), 10, at(0))
402 .expect("open");
403 windows
404 .open(SESSION, ExchangeId(2), 20, at(0))
405 .expect("open");
406 windows
407 .open(SESSION, ExchangeId(3), 1000, at(100))
408 .expect("open");
409 assert_eq!(
411 windows.check(SESSION, ExchangeId(1), true, at(101)),
412 Err(Status::TimedRequestMismatch)
413 );
414 assert_eq!(
415 windows.check(SESSION, ExchangeId(2), true, at(101)),
416 Err(Status::Timeout),
417 "the later-expiring window is still there to report TIMEOUT"
418 );
419 }
420
421 #[test]
422 fn closing_a_session_drops_its_windows_and_leaves_others() {
423 let mut windows = TimedWindows::<4>::new();
424 windows
425 .open(SESSION, ExchangeId(1), 1000, at(0))
426 .expect("open");
427 windows
428 .open(Some(SessionId(8)), ExchangeId(1), 1000, at(0))
429 .expect("open");
430 windows.close_session(SESSION);
431 assert_eq!(windows.len(), 1);
432 assert_eq!(
433 windows.check(Some(SessionId(8)), ExchangeId(1), true, at(1)),
434 Ok(true)
435 );
436 }
437
438 #[test]
439 fn reaping_trades_timeout_for_mismatch() {
440 let mut windows = TimedWindows::<2>::new();
441 windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
442 assert_eq!(windows.reap(at(11)), 1);
443 assert_eq!(
446 windows.check(SESSION, EXCHANGE, true, at(12)),
447 Err(Status::TimedRequestMismatch)
448 );
449 }
450
451 #[test]
452 fn reaping_leaves_live_windows_alone() {
453 let mut windows = TimedWindows::<2>::new();
454 windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
455 assert_eq!(windows.reap(at(11)), 0);
456 assert_eq!(windows.check(SESSION, EXCHANGE, true, at(12)), Ok(true));
457 }
458
459 #[test]
460 fn the_next_deadline_is_the_earliest() {
461 let mut windows = TimedWindows::<4>::new();
462 assert_eq!(windows.next_deadline(), None);
463 windows
464 .open(SESSION, ExchangeId(1), 500, at(0))
465 .expect("open");
466 windows
467 .open(SESSION, ExchangeId(2), 100, at(0))
468 .expect("open");
469 assert_eq!(windows.next_deadline(), Some(at(100)));
470 }
471
472 #[test]
473 fn a_zero_timeout_expires_immediately_but_still_reports_timeout() {
474 let mut windows = TimedWindows::<2>::new();
477 windows.open(SESSION, EXCHANGE, 0, at(0)).expect("open");
478 assert_eq!(
479 windows.check(SESSION, EXCHANGE, true, at(1)),
480 Err(Status::Timeout)
481 );
482 }
483}