use core::marker::PhantomData;
use heapless::Vec;
use super::mrp::{Mrp, MrpParams};
use crate::config::{AssertValid, Config};
use crate::error::{Error, ErrorCode, Result};
use crate::msg::{ExchangeId, ProtocolId, SessionId};
use crate::platform::{Duration, Instant, Peer};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
Initiator,
Responder,
}
impl Role {
#[must_use]
pub const fn peer(self) -> Self {
match self {
Self::Initiator => Self::Responder,
Self::Responder => Self::Initiator,
}
}
#[must_use]
pub const fn is_initiator(self) -> bool {
matches!(self, Self::Initiator)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExchangeKey {
pub session: SessionId,
pub id: ExchangeId,
pub role: Role,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exchange {
pub key: ExchangeKey,
pub protocol: ProtocolId,
pub mrp: Mrp,
pub peer: Option<Peer>,
pub opened: Instant,
pub last_activity: Instant,
pub ephemeral: bool,
}
impl Exchange {
#[must_use]
pub fn new(key: ExchangeKey, protocol: ProtocolId, params: MrpParams, now: Instant) -> Self {
Self {
key,
protocol,
mrp: Mrp::new(params),
peer: None,
opened: now,
last_activity: now,
ephemeral: false,
}
}
#[must_use]
pub const fn ephemeral(mut self) -> Self {
self.ephemeral = true;
self
}
pub const fn touch(&mut self, now: Instant) {
self.last_activity = now;
}
#[must_use]
pub fn is_abandoned(&self, now: Instant, idle: Duration) -> bool {
if self.mrp.is_awaiting_ack() {
return false;
}
now.as_micros()
.saturating_sub(self.last_activity.as_micros())
> idle.as_micros()
}
#[must_use]
pub fn to_peer(mut self, peer: Peer) -> Self {
self.peer = Some(peer);
self
}
#[must_use]
pub fn is_transport_reliable(&self) -> bool {
self.peer.is_some_and(|p| p.is_reliable())
}
}
pub const EXCHANGE_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Debug)]
pub struct ExchangeTable<C: Config, const N: usize = 64> {
open: Vec<Exchange, N>,
next_id: u16,
_config: PhantomData<C>,
}
impl<C: Config, const N: usize> Default for ExchangeTable<C, N> {
fn default() -> Self {
Self::new(0)
}
}
impl<C: Config, const N: usize> crate::config::Capacity for ExchangeTable<C, N> {
const TOTAL: usize = N;
const PER_FABRIC: usize = N;
}
impl<C: Config, const N: usize> ExchangeTable<C, N> {
#[must_use]
pub fn new(first_id: u16) -> Self {
let () = AssertValid::<C>::CHECK;
Self {
open: Vec::new(),
next_id: first_id,
_config: PhantomData,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.open.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.open.is_empty()
}
#[must_use]
pub fn capacity_remaining(&self) -> usize {
N.saturating_sub(self.open.len())
}
pub fn open_initiator(
&mut self,
session: SessionId,
protocol: ProtocolId,
params: MrpParams,
peer: Option<Peer>,
now: Instant,
) -> Result<ExchangeKey> {
let id = self.allocate_id(session)?;
let key = ExchangeKey {
session,
id,
role: Role::Initiator,
};
let exchange = Exchange::new(key, protocol, params, now);
self.insert(match peer {
Some(peer) => exchange.to_peer(peer),
None => exchange,
})?;
Ok(key)
}
pub fn open_responder(
&mut self,
session: SessionId,
id: ExchangeId,
protocol: ProtocolId,
params: MrpParams,
now: Instant,
) -> Result<ExchangeKey> {
let key = ExchangeKey {
session,
id,
role: Role::Responder,
};
if self.find(key).is_some() {
return Err(Error::new(ErrorCode::InvalidState));
}
self.insert_under_pressure(Exchange::new(key, protocol, params, now), now)?;
Ok(key)
}
pub fn open_ephemeral(
&mut self,
session: SessionId,
id: ExchangeId,
protocol: ProtocolId,
params: MrpParams,
now: Instant,
) -> Result<ExchangeKey> {
let key = ExchangeKey {
session,
id,
role: Role::Responder,
};
if let Some(existing) = self.find(key) {
return Ok(existing.key);
}
self.insert_under_pressure(Exchange::new(key, protocol, params, now).ephemeral(), now)?;
Ok(key)
}
fn insert_under_pressure(&mut self, exchange: Exchange, now: Instant) -> Result<()> {
if self.open.is_full() {
self.reap(now, EXCHANGE_IDLE_TIMEOUT);
}
self.insert(exchange)
}
fn insert(&mut self, exchange: Exchange) -> Result<()> {
self.open
.push(exchange)
.map_err(|_| Error::new(ErrorCode::NoSpace))
}
pub fn reap(&mut self, now: Instant, idle: Duration) -> usize {
let before = self.open.len();
self.open.retain(|e| !e.is_abandoned(now, idle));
before.saturating_sub(self.open.len())
}
#[must_use]
pub fn reap_deadline(&self, idle: Duration) -> Option<Instant> {
self.open
.iter()
.filter(|e| !e.mrp.is_awaiting_ack())
.map(|e| e.last_activity.saturating_add(idle))
.min()
}
fn allocate_id(&mut self, session: SessionId) -> Result<ExchangeId> {
for _ in 0..=u16::MAX {
let id = ExchangeId(self.next_id);
self.next_id = self.next_id.wrapping_add(1);
let key = ExchangeKey {
session,
id,
role: Role::Initiator,
};
if self.find(key).is_none() {
return Ok(id);
}
}
Err(Error::new(ErrorCode::NoSpace))
}
#[must_use]
pub fn find(&self, key: ExchangeKey) -> Option<&Exchange> {
self.open.iter().find(|e| e.key == key)
}
pub fn find_mut(&mut self, key: ExchangeKey) -> Option<&mut Exchange> {
self.open.iter_mut().find(|e| e.key == key)
}
#[must_use]
pub fn find_for_message(
&self,
session: SessionId,
id: ExchangeId,
from_initiator: bool,
) -> Option<&Exchange> {
let role = if from_initiator {
Role::Responder
} else {
Role::Initiator
};
self.find(ExchangeKey { session, id, role })
}
pub fn close(&mut self, key: ExchangeKey) -> bool {
let Some(i) = self.open.iter().position(|e| e.key == key) else {
return false;
};
if let Some(e) = self.open.get_mut(i) {
e.mrp.close();
}
self.open.swap_remove(i);
true
}
pub fn close_session(&mut self, session: SessionId) -> usize {
let before = self.open.len();
self.open.retain(|e| e.key.session != session);
before.saturating_sub(self.open.len())
}
#[must_use]
pub fn poll_deadline(&self) -> Option<Instant> {
self.open.iter().filter_map(|e| e.mrp.poll_deadline()).min()
}
pub fn on_timeout(
&mut self,
now: Instant,
randomness: u32,
mut on_action: impl FnMut(ExchangeKey, super::OnTimeout),
) -> usize {
let mut count = 0usize;
for exchange in &mut self.open {
loop {
let action = exchange.mrp.on_timeout(now, randomness);
if matches!(action, super::OnTimeout::Nothing) {
break;
}
on_action(exchange.key, action);
count = count.saturating_add(1);
}
}
count
}
pub fn iter(&self) -> impl Iterator<Item = &Exchange> {
self.open.iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DefaultConfig;
use crate::exchange::OnTimeout;
type Table = ExchangeTable<DefaultConfig, 8>;
#[test]
fn an_initiated_exchange_gets_an_unused_id() {
let mut t = Table::new(100);
let a = t
.open_initiator(
SessionId(1),
ProtocolId::INTERACTION_MODEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
let b = t
.open_initiator(
SessionId(1),
ProtocolId::INTERACTION_MODEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
assert_ne!(a.id, b.id);
assert_eq!(a.id, ExchangeId(100));
assert_eq!(t.len(), 2);
}
#[test]
fn the_same_id_in_both_roles_is_two_exchanges() {
let mut t = Table::new(7);
let mine = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("mine");
assert_eq!(mine.id, ExchangeId(7));
let theirs = t
.open_responder(
SessionId(1),
ExchangeId(7),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
Instant::ZERO,
)
.expect("theirs");
assert_eq!(t.len(), 2, "two distinct exchanges");
assert_ne!(mine, theirs);
assert!(t.find(mine).is_some());
assert!(t.find(theirs).is_some());
}
#[test]
fn an_arriving_message_finds_the_opposite_role() {
let mut t = Table::new(0);
let mine = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
let found = t
.find_for_message(SessionId(1), mine.id, false)
.expect("the reply belongs to my exchange");
assert_eq!(found.key, mine);
assert!(t.find_for_message(SessionId(1), mine.id, true).is_none());
}
#[test]
fn a_peer_reusing_a_live_id_is_refused() {
let mut t = Table::new(0);
t.open_responder(
SessionId(1),
ExchangeId(3),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
Instant::ZERO,
)
.expect("first");
assert_eq!(
t.open_responder(
SessionId(1),
ExchangeId(3),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
Instant::ZERO,
)
.unwrap_err()
.code(),
ErrorCode::InvalidState
);
}
#[test]
fn the_same_id_on_two_sessions_is_two_exchanges() {
let mut t = Table::new(0);
t.open_responder(
SessionId(1),
ExchangeId(5),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
Instant::ZERO,
)
.expect("session 1");
t.open_responder(
SessionId(2),
ExchangeId(5),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
Instant::ZERO,
)
.expect("session 2");
assert_eq!(t.len(), 2);
}
#[test]
fn a_full_table_is_a_value_not_an_abort() {
let mut t = Table::new(0);
for _ in 0..8 {
t.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("fits");
}
assert_eq!(t.capacity_remaining(), 0);
assert_eq!(
t.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.unwrap_err()
.code(),
ErrorCode::NoSpace
);
}
#[test]
fn closing_a_session_closes_its_exchanges() {
let mut t = Table::new(0);
for session in [1u16, 1, 2] {
t.open_initiator(
SessionId(session),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
}
assert_eq!(t.close_session(SessionId(1)), 2);
assert_eq!(t.len(), 1);
assert_eq!(t.close_session(SessionId(1)), 0);
}
#[test]
fn close_reports_whether_it_did_anything() {
let mut t = Table::new(0);
let k = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
assert!(t.close(k));
assert!(!t.close(k));
assert!(t.is_empty());
}
#[test]
fn the_table_deadline_is_the_earliest_of_them() {
let mut t = Table::new(0);
let slow = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
let fast = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
assert_eq!(t.poll_deadline(), None, "nothing is in flight yet");
if let Some(e) = t.find_mut(slow) {
e.mrp.on_send(1, Instant::ZERO, 0).expect("send");
}
if let Some(e) = t.find_mut(fast) {
e.mrp.note_peer_activity(Instant::ZERO);
e.mrp.on_send(2, Instant::ZERO, 0).expect("send");
}
let deadline = t.poll_deadline().expect("a deadline");
assert_eq!(deadline.as_micros(), 330_000);
}
#[test]
fn timeouts_are_reported_per_exchange() {
let mut t = Table::new(0);
let k = t
.open_initiator(
SessionId(1),
ProtocolId::SECURE_CHANNEL,
MrpParams::default(),
None,
Instant::ZERO,
)
.expect("open");
if let Some(e) = t.find_mut(k) {
e.mrp.on_send(9, Instant::ZERO, 0).expect("send");
}
let deadline = t.poll_deadline().expect("a deadline");
let mut seen = heapless::Vec::<(ExchangeKey, u32), 4>::new();
let n = t.on_timeout(deadline, 0, |key, action| {
if let OnTimeout::Retransmit { counter, .. } = action {
let _ = seen.push((key, counter));
}
});
assert_eq!(n, 1);
assert_eq!(&seen[..], &[(k, 9)]);
}
}