use crate::msg::{ExchangeId, SessionId};
use crate::platform::{Duration, Instant};
use super::status::Status;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Window {
session: Option<SessionId>,
exchange: ExchangeId,
deadline: Instant,
}
#[derive(Debug, Clone)]
pub struct TimedWindows<const N: usize> {
windows: [Option<Window>; N],
}
impl<const N: usize> Default for TimedWindows<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> TimedWindows<N> {
#[must_use]
pub const fn new() -> Self {
Self { windows: [None; N] }
}
pub fn open(
&mut self,
session: Option<SessionId>,
exchange: ExchangeId,
timeout_ms: u16,
sent_at: Instant,
) -> crate::Result<()> {
let window = Window {
session,
exchange,
deadline: sent_at.saturating_add(Duration::from_millis(u64::from(timeout_ms))),
};
if let Some(slot) = self.slot_for(session, exchange) {
*slot = Some(window);
return Ok(());
}
if let Some(slot) = self.windows.iter_mut().find(|slot| slot.is_none()) {
*slot = Some(window);
return Ok(());
}
let oldest_expired = self
.windows
.iter_mut()
.filter(|slot| slot.is_some_and(|w| w.deadline <= sent_at))
.min_by_key(|slot| slot.map(|w| w.deadline));
if let Some(slot) = oldest_expired {
*slot = Some(window);
return Ok(());
}
Err(crate::Error::new(crate::ErrorCode::NoSpace))
}
pub fn check(
&mut self,
session: Option<SessionId>,
exchange: ExchangeId,
timed_request: bool,
now: Instant,
) -> core::result::Result<bool, Status> {
let Some(slot) = self.slot_for(session, exchange) else {
return if timed_request {
Err(Status::TimedRequestMismatch)
} else {
Ok(false)
};
};
let expired = slot.is_some_and(|window| now > window.deadline);
*slot = None;
if expired {
return Err(Status::Timeout);
}
if !timed_request {
return Err(Status::TimedRequestMismatch);
}
Ok(true)
}
pub fn close(&mut self, session: Option<SessionId>, exchange: ExchangeId) {
if let Some(slot) = self.slot_for(session, exchange) {
*slot = None;
}
}
pub fn close_session(&mut self, session: Option<SessionId>) {
for slot in &mut self.windows {
if slot.is_some_and(|window| window.session == session) {
*slot = None;
}
}
}
pub fn reap(&mut self, now: Instant) -> usize {
let mut reaped = 0usize;
for slot in &mut self.windows {
if slot.is_some_and(|window| now > window.deadline) {
*slot = None;
reaped = reaped.saturating_add(1);
}
}
reaped
}
#[must_use]
pub fn len(&self) -> usize {
self.windows.iter().filter(|slot| slot.is_some()).count()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub fn next_deadline(&self) -> Option<Instant> {
self.windows
.iter()
.filter_map(|slot| slot.map(|window| window.deadline))
.min()
}
fn slot_for(
&mut self,
session: Option<SessionId>,
exchange: ExchangeId,
) -> Option<&mut Option<Window>> {
self.windows.iter_mut().find(|slot| {
slot.is_some_and(|window| window.session == session && window.exchange == exchange)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
const SESSION: Option<SessionId> = Some(SessionId(7));
const EXCHANGE: ExchangeId = ExchangeId(42);
fn at(ms: u64) -> Instant {
Instant::ZERO.saturating_add(Duration::from_millis(ms))
}
#[test]
fn an_untimed_request_with_no_window_proceeds() {
let mut windows = TimedWindows::<2>::new();
assert_eq!(windows.check(SESSION, EXCHANGE, false, at(0)), Ok(false));
}
#[test]
fn a_timed_request_inside_the_window_proceeds() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(999)), Ok(true));
}
#[test]
fn the_deadline_is_inclusive_of_its_last_instant() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(100)), Ok(true));
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(101)),
Err(Status::Timeout)
);
}
#[test]
fn the_clock_starts_when_the_status_response_is_sent() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 100, at(50)).expect("open");
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(150)), Ok(true));
}
#[test]
fn an_expired_window_is_timeout_not_mismatch() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(11)),
Err(Status::Timeout)
);
}
#[test]
fn expiry_is_checked_before_the_flag() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, false, at(11)),
Err(Status::Timeout)
);
}
#[test]
fn a_timed_window_with_an_untimed_request_is_a_mismatch() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, false, at(1)),
Err(Status::TimedRequestMismatch)
);
}
#[test]
fn an_untimed_window_with_a_timed_request_is_a_mismatch() {
let mut windows = TimedWindows::<2>::new();
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(0)),
Err(Status::TimedRequestMismatch)
);
}
#[test]
fn a_window_is_consumed_by_the_request_it_admits() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(2)),
Err(Status::TimedRequestMismatch)
);
assert!(windows.is_empty());
}
#[test]
fn a_window_is_consumed_even_by_a_request_it_refuses() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, false, at(1)),
Err(Status::TimedRequestMismatch)
);
assert!(windows.is_empty());
}
#[test]
fn windows_are_scoped_to_their_exchange_and_session() {
let mut windows = TimedWindows::<4>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, ExchangeId(43), true, at(1)),
Err(Status::TimedRequestMismatch)
);
assert_eq!(
windows.check(Some(SessionId(8)), EXCHANGE, true, at(1)),
Err(Status::TimedRequestMismatch)
);
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
}
#[test]
fn a_second_timed_request_on_one_exchange_replaces_the_first() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(windows.len(), 1, "one transaction, one deadline");
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(500)), Ok(true));
}
#[test]
fn a_full_table_of_live_windows_refuses() {
let mut windows = TimedWindows::<2>::new();
windows
.open(SESSION, ExchangeId(1), 1000, at(0))
.expect("open");
windows
.open(SESSION, ExchangeId(2), 1000, at(0))
.expect("open");
assert!(
windows.open(SESSION, ExchangeId(3), 1000, at(0)).is_err(),
"§8.7.3.2's BUSY case"
);
assert_eq!(windows.check(SESSION, ExchangeId(1), true, at(1)), Ok(true));
}
#[test]
fn a_full_table_gives_up_its_oldest_expired_window_first() {
let mut windows = TimedWindows::<2>::new();
windows
.open(SESSION, ExchangeId(1), 10, at(0))
.expect("open");
windows
.open(SESSION, ExchangeId(2), 20, at(0))
.expect("open");
windows
.open(SESSION, ExchangeId(3), 1000, at(100))
.expect("open");
assert_eq!(
windows.check(SESSION, ExchangeId(1), true, at(101)),
Err(Status::TimedRequestMismatch)
);
assert_eq!(
windows.check(SESSION, ExchangeId(2), true, at(101)),
Err(Status::Timeout),
"the later-expiring window is still there to report TIMEOUT"
);
}
#[test]
fn closing_a_session_drops_its_windows_and_leaves_others() {
let mut windows = TimedWindows::<4>::new();
windows
.open(SESSION, ExchangeId(1), 1000, at(0))
.expect("open");
windows
.open(Some(SessionId(8)), ExchangeId(1), 1000, at(0))
.expect("open");
windows.close_session(SESSION);
assert_eq!(windows.len(), 1);
assert_eq!(
windows.check(Some(SessionId(8)), ExchangeId(1), true, at(1)),
Ok(true)
);
}
#[test]
fn reaping_trades_timeout_for_mismatch() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
assert_eq!(windows.reap(at(11)), 1);
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(12)),
Err(Status::TimedRequestMismatch)
);
}
#[test]
fn reaping_leaves_live_windows_alone() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
assert_eq!(windows.reap(at(11)), 0);
assert_eq!(windows.check(SESSION, EXCHANGE, true, at(12)), Ok(true));
}
#[test]
fn the_next_deadline_is_the_earliest() {
let mut windows = TimedWindows::<4>::new();
assert_eq!(windows.next_deadline(), None);
windows
.open(SESSION, ExchangeId(1), 500, at(0))
.expect("open");
windows
.open(SESSION, ExchangeId(2), 100, at(0))
.expect("open");
assert_eq!(windows.next_deadline(), Some(at(100)));
}
#[test]
fn a_zero_timeout_expires_immediately_but_still_reports_timeout() {
let mut windows = TimedWindows::<2>::new();
windows.open(SESSION, EXCHANGE, 0, at(0)).expect("open");
assert_eq!(
windows.check(SESSION, EXCHANGE, true, at(1)),
Err(Status::Timeout)
);
}
}