use alloc::boxed::Box;
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;
use crate::codec::{self, DecodeOptions};
use crate::message::{Message, MessageKind};
use crate::types::common::{
Consequence, ControlType, EnergyManagementRole, InstructionStatus, ReceptionStatus,
ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
};
use crate::types::{Duration, Id, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc};
use crate::validate::{Context, TimerState};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outgoing {
pub text: String,
pub kind: MessageKind,
pub message_id: Option<Id>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MessageHandle {
pub id: Id,
pub kind: MessageKind,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Negotiation {
#[default]
Handshake,
PreNegotiated(WireProfile),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionState {
Idle,
Handshaking,
Connected,
ControlTypeSelected(ControlType),
Closed(CloseReason),
}
impl SessionState {
#[must_use]
pub fn phase(&self) -> crate::validate::Phase {
use crate::validate::Phase;
match self {
SessionState::Idle | SessionState::Handshaking => Phase::Negotiating,
SessionState::Connected | SessionState::Closed(_) => Phase::Connected,
SessionState::ControlTypeSelected(c) => Phase::selected(*c),
}
}
#[must_use]
pub fn active_control_type(&self) -> Option<ControlType> {
match self {
SessionState::ControlTypeSelected(c) if c.is_controllable() => Some(*c),
_ => None,
}
}
#[must_use]
pub fn is_active(&self) -> bool {
self.active_control_type().is_some()
}
#[must_use]
pub fn is_closed(&self) -> bool {
matches!(self, SessionState::Closed(_))
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CloseReason {
#[error("closed locally")]
Local,
#[error("the peer asked to {0:?}")]
PeerRequested(crate::types::common::SessionRequestType),
#[error("this side asked to {0:?}")]
LocallyRequested(crate::types::common::SessionRequestType),
#[error("the transport closed")]
TransportClosed,
#[error("the peer selected protocol version {selected}, which was not offered")]
UnsupportedVersion {
selected: crate::types::ProtocolVersion,
},
#[error("no protocol version is supported by both sides")]
NoCommonVersion,
#[error("the peer reported a permanent error: {0}")]
PermanentError(String),
#[error("protocol error: {0}")]
ProtocolError(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutOfOrderPolicy {
#[default]
Report,
Close,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SendError {
#[error("the session is closed")]
Closed,
#[error("{kind} is not allowed while the session is {state}")]
NotAllowed {
kind: MessageKind,
state: &'static str,
},
#[error("{kind} does not exist in S2 JSON {profile}")]
NotInProfile {
kind: MessageKind,
profile: WireProfile,
},
#[error("{0}")]
Invalid(Box<crate::validate::Violation>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AckOutcome {
Accepted {
handle: MessageHandle,
latency: Duration,
},
Refused {
handle: MessageHandle,
status: ReceptionStatusValues,
diagnostic: Option<String>,
consequence: Consequence,
latency: Duration,
},
TimedOut(MessageHandle),
Unmatched {
subject: Id,
status: ReceptionStatusValues,
},
}
#[derive(Debug, Clone, Copy)]
struct Outstanding {
handle: MessageHandle,
sent_at: Timestamp,
deadline: Timestamp,
}
#[derive(Debug, Clone, Default)]
pub struct AckLedger {
pending: Vec<Outstanding>,
answered: VecDeque<(Id, ReceptionStatusValues)>,
max_answered: usize,
}
impl AckLedger {
#[must_use]
pub fn new(max_answered: usize) -> Self {
Self {
pending: Vec::new(),
answered: VecDeque::new(),
max_answered,
}
}
pub fn sent(&mut self, handle: MessageHandle, sent_at: Timestamp, deadline: Timestamp) {
self.pending.push(Outstanding {
handle,
sent_at,
deadline,
});
}
#[allow(clippy::needless_pass_by_value)]
pub fn received(&mut self, status: &ReceptionStatus, now: Timestamp) -> AckOutcome {
let Some(position) = self
.pending
.iter()
.position(|entry| entry.handle.id == status.subject_message_id)
else {
return AckOutcome::Unmatched {
subject: status.subject_message_id,
status: status.status,
};
};
let entry = self.pending.remove(position);
let latency = now.saturating_duration_since(entry.sent_at);
if status.status == ReceptionStatusValues::Ok {
AckOutcome::Accepted {
handle: entry.handle,
latency,
}
} else {
AckOutcome::Refused {
handle: entry.handle,
status: status.status,
diagnostic: status.diagnostic_label.clone(),
consequence: status.status.consequence(),
latency,
}
}
}
pub fn expire(&mut self, now: Timestamp) -> Vec<MessageHandle> {
let mut out = Vec::new();
self.pending.retain(|entry| {
if entry.deadline <= now {
out.push(entry.handle);
false
} else {
true
}
});
out
}
#[must_use]
pub fn next_deadline(&self) -> Option<Timestamp> {
self.pending.iter().map(|entry| entry.deadline).min()
}
#[must_use]
pub fn outstanding(&self) -> usize {
self.pending.len()
}
pub fn answered(&mut self, id: Id, status: ReceptionStatusValues) {
if self.answered.len() >= self.max_answered {
self.answered.pop_front();
}
self.answered.push_back((id, status));
}
#[must_use]
pub fn previous_answer(&self, id: Id) -> Option<ReceptionStatusValues> {
self.answered
.iter()
.rev()
.find(|(seen, _)| *seen == id)
.map(|(_, status)| *status)
}
#[must_use]
pub fn has_seen(&self, id: Id) -> bool {
self.previous_answer(id).is_some()
}
pub fn seen_ids(&self) -> Vec<Id> {
self.answered.iter().map(|(id, _)| *id).collect()
}
}
#[derive(Debug, Clone, Default)]
pub struct Registry {
pub details: Option<ResourceManagerDetails>,
pub frbc: Option<frbc::SystemDescription>,
pub ombc: Option<ombc::SystemDescription>,
pub ddbc: Option<ddbc::SystemDescription>,
pub scheduled: Vec<(Timestamp, Message)>,
pub pebc_constraints: Vec<pebc::PowerConstraints>,
pub pebc_energy: Vec<pebc::EnergyConstraint>,
pub ppbc_profiles: Vec<ppbc::PowerProfileDefinition>,
pub instructions: Vec<Id>,
pub instruction_messages: Vec<(Id, Id)>,
pub instruction_statuses: Vec<(Id, InstructionStatus)>,
pub published: Vec<(RevokableObjects, Id)>,
pub active_modes: Vec<(Id, Id)>,
pub timers: Vec<TimerState>,
pub fill_level: Option<f64>,
}
impl Registry {
pub const MAX_TRACKED: usize = 4096;
pub const MAX_SCHEDULED: usize = 16;
fn bound<T>(v: &mut Vec<T>) {
if v.len() > Self::MAX_TRACKED {
v.remove(0);
}
}
fn upsert<T, K: PartialEq>(v: &mut Vec<T>, key: &K, value: T, key_of: impl Fn(&T) -> K) {
if let Some(slot) = v.iter_mut().find(|existing| key_of(existing) == *key) {
*slot = value;
} else {
v.push(value);
Self::bound(v);
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn record(&mut self, message: &Message, now: Option<Timestamp>) {
if let Some((object_type, id)) = message.revokable_id() {
Self::upsert(
&mut self.published,
&(object_type, id),
(object_type, id),
|(t, i)| (*t, *i),
);
}
if let Some(id) = message.instruction_id() {
if !self.instructions.contains(&id) {
self.instructions.push(id);
Self::bound(&mut self.instructions);
}
if let Some(message_id) = message.id() {
Self::upsert(
&mut self.instruction_messages,
&message_id,
(message_id, id),
|(m, _)| *m,
);
}
}
let scheduled_for = match message {
Message::FrbcSystemDescription(d) => Some(d.valid_from),
Message::OmbcSystemDescription(d) => Some(d.valid_from),
Message::DdbcSystemDescription(d) => Some(d.valid_from),
_ => None,
};
if let (Some(valid_from), Some(now)) = (scheduled_for, now)
&& valid_from > now
{
self.schedule(valid_from, message);
return;
}
self.apply(message);
}
fn schedule(&mut self, valid_from: Timestamp, message: &Message) {
let identity = message.revokable_id();
if let Some(slot) = self
.scheduled
.iter_mut()
.find(|(_, queued)| queued.revokable_id() == identity)
{
*slot = (valid_from, message.clone());
return;
}
self.scheduled.push((valid_from, message.clone()));
while self.scheduled.len() > Self::MAX_SCHEDULED {
if let Some(furthest) = self
.scheduled
.iter()
.enumerate()
.max_by_key(|(_, (at, _))| *at)
.map(|(i, _)| i)
{
self.scheduled.remove(furthest);
} else {
break;
}
}
}
fn apply(&mut self, message: &Message) {
match message {
Message::ResourceManagerDetails(d) => self.details = Some((**d).clone()),
Message::FrbcSystemDescription(d) => {
self.frbc = Some((**d).clone());
self.forget_actuator_state();
}
Message::OmbcSystemDescription(d) => {
self.ombc = Some((**d).clone());
self.forget_actuator_state();
}
Message::DdbcSystemDescription(d) => {
self.ddbc = Some((**d).clone());
self.forget_actuator_state();
}
Message::PebcPowerConstraints(c) => Self::upsert(
&mut self.pebc_constraints,
&c.id,
(**c).clone(),
|existing| existing.id,
),
Message::PebcEnergyConstraint(c) => {
Self::upsert(&mut self.pebc_energy, &c.id, (**c).clone(), |e| e.id);
}
Message::PpbcPowerProfileDefinition(p) => {
Self::upsert(&mut self.ppbc_profiles, &p.id, (**p).clone(), |e| e.id);
}
Message::FrbcStorageStatus(s) => self.fill_level = Some(s.present_fill_level),
Message::FrbcActuatorStatus(s) => {
Self::upsert(
&mut self.active_modes,
&s.actuator_id,
(s.actuator_id, s.active_operation_mode_id),
|(a, _)| *a,
);
}
Message::DdbcActuatorStatus(s) => {
Self::upsert(
&mut self.active_modes,
&s.actuator_id,
(s.actuator_id, s.active_operation_mode_id),
|(a, _)| *a,
);
}
Message::OmbcStatus(s) => {
Self::upsert(
&mut self.active_modes,
&Id::NIL,
(Id::NIL, s.active_operation_mode_id),
|(a, _)| *a,
);
}
Message::FrbcTimerStatus(s) => {
let actuator = s.actuator_id;
Self::upsert(
&mut self.timers,
&(actuator, s.timer_id),
TimerState {
actuator,
timer: s.timer_id,
finished_at: s.finished_at,
},
|t| (t.actuator, t.timer),
);
}
Message::DdbcTimerStatus(s) => {
let actuator = s.actuator_id;
Self::upsert(
&mut self.timers,
&(actuator, s.timer_id),
TimerState {
actuator,
timer: s.timer_id,
finished_at: s.finished_at,
},
|t| (t.actuator, t.timer),
);
}
Message::OmbcTimerStatus(s) => {
let actuator = Id::NIL;
Self::upsert(
&mut self.timers,
&(actuator, s.timer_id),
TimerState {
actuator,
timer: s.timer_id,
finished_at: s.finished_at,
},
|t| (t.actuator, t.timer),
);
}
Message::InstructionStatusUpdate(u) => Self::upsert(
&mut self.instruction_statuses,
&u.instruction_id,
(u.instruction_id, u.status_type),
|(i, _)| *i,
),
Message::RevokeObject(r) => self.revoke(r.object_type, r.object_id),
_ => {}
}
}
fn forget_actuator_state(&mut self) {
self.active_modes.clear();
self.timers.clear();
}
pub fn activate_due(&mut self, now: Timestamp) -> Vec<Message> {
let mut due = Vec::new();
self.scheduled.retain(|(at, message)| {
if *at <= now {
due.push(message.clone());
false
} else {
true
}
});
for message in &due {
self.apply(message);
}
due
}
#[must_use]
pub fn next_activation(&self) -> Option<Timestamp> {
self.scheduled.iter().map(|(at, _)| *at).min()
}
pub fn revoke(&mut self, object_type: RevokableObjects, object_id: Id) {
self.published
.retain(|(t, i)| !(*t == object_type && *i == object_id));
self.scheduled
.retain(|(_, message)| message.revokable_id() != Some((object_type, object_id)));
match object_type {
RevokableObjects::PebcPowerConstraints => {
self.pebc_constraints.retain(|c| c.id != object_id);
}
RevokableObjects::PebcEnergyConstraint => {
self.pebc_energy.retain(|c| c.id != object_id);
}
RevokableObjects::PpbcPowerProfileDefinition => {
self.ppbc_profiles.retain(|p| p.id != object_id);
}
RevokableObjects::FrbcSystemDescription => {
if self
.frbc
.as_ref()
.is_some_and(|d| d.message_id == object_id)
{
self.frbc = None;
self.forget_actuator_state();
}
}
RevokableObjects::OmbcSystemDescription => {
if self
.ombc
.as_ref()
.is_some_and(|d| d.message_id == object_id)
{
self.ombc = None;
self.forget_actuator_state();
}
}
RevokableObjects::DdbcSystemDescription => {
if self
.ddbc
.as_ref()
.is_some_and(|d| d.message_id == object_id)
{
self.ddbc = None;
self.forget_actuator_state();
}
}
_ => {
Self::upsert(
&mut self.instruction_statuses,
&object_id,
(object_id, InstructionStatus::Revoked),
|(i, _)| *i,
);
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn context<'a>(
&'a self,
profile: WireProfile,
sender: EnergyManagementRole,
phase: crate::validate::Phase,
s2_connect: bool,
now: Timestamp,
seen: &'a [Id],
skew_tolerance: Duration,
) -> Context<'a> {
Context {
profile,
sender: Some(sender),
phase,
s2_connect,
details: self.details.as_ref(),
frbc: self.frbc.as_ref(),
ombc: self.ombc.as_ref(),
ddbc: self.ddbc.as_ref(),
pebc_constraints: &self.pebc_constraints,
ppbc_profiles: &self.ppbc_profiles,
instructions: &self.instructions,
instruction_messages: &self.instruction_messages,
instruction_statuses: &self.instruction_statuses,
seen_message_ids: seen,
published: &self.published,
active_modes: &self.active_modes,
timers: &self.timers,
fill_level: self.fill_level,
now: Some(now),
skew_tolerance,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stats {
pub sent: u64,
pub received: u64,
pub undecodable: u64,
pub refused: u64,
pub accepted_with_warnings: u64,
pub sent_with_warnings: u64,
pub duplicates: u64,
pub acked: u64,
pub nacked: u64,
pub ack_timeouts: u64,
pub unmatched_acks: u64,
pub ack_latency_total_ms: u64,
pub ack_latency_max_ms: u64,
}
impl Stats {
#[must_use]
pub const fn answered(&self) -> u64 {
self.acked + self.nacked
}
#[must_use]
pub const fn mean_ack_latency_ms(&self) -> Option<u64> {
match self.answered() {
0 => None,
n => Some(self.ack_latency_total_ms / n),
}
}
pub(crate) fn record_latency(&mut self, latency: Duration) {
let ms = latency.as_millis();
self.ack_latency_total_ms = self.ack_latency_total_ms.saturating_add(ms);
self.ack_latency_max_ms = self.ack_latency_max_ms.max(ms);
}
}
#[derive(Debug, Clone)]
pub struct SessionCore {
pub state: SessionState,
pub negotiation: Negotiation,
pub profile: WireProfile,
pub s2_connect: bool,
pub outbox: VecDeque<Outgoing>,
pub acks: AckLedger,
pub registry: Registry,
pub ack_timeout: Duration,
pub out_of_order: OutOfOrderPolicy,
pub skew_tolerance: Duration,
pub max_message_bytes: usize,
pub strictness: codec::Strictness,
pub reconnect_attempt: u32,
pub stats: Stats,
#[cfg_attr(feature = "uuid", allow(dead_code))]
role: EnergyManagementRole,
minted: u64,
}
pub(crate) struct CoreConfig {
pub role: EnergyManagementRole,
pub negotiation: Negotiation,
pub ack_timeout: Duration,
pub out_of_order: OutOfOrderPolicy,
pub skew_tolerance: Duration,
pub max_message_bytes: usize,
pub strictness: codec::Strictness,
pub s2_connect: bool,
pub reconnect_attempt: u32,
}
impl SessionCore {
pub(crate) fn new(cfg: CoreConfig) -> Self {
let CoreConfig {
role,
negotiation,
ack_timeout,
out_of_order,
skew_tolerance,
max_message_bytes,
strictness,
s2_connect,
reconnect_attempt,
} = cfg;
let profile = match &negotiation {
Negotiation::PreNegotiated(p) => *p,
Negotiation::Handshake => WireProfile::V1_0_0,
};
Self {
state: SessionState::Idle,
negotiation,
profile,
s2_connect,
outbox: VecDeque::new(),
acks: AckLedger::new(256),
registry: Registry::default(),
ack_timeout,
out_of_order,
skew_tolerance,
max_message_bytes,
strictness,
reconnect_attempt,
stats: Stats::default(),
role,
minted: 0,
}
}
pub(crate) fn next_message_id(&mut self) -> Id {
self.minted = self.minted.wrapping_add(1);
#[cfg(feature = "uuid")]
{
Id::generate()
}
#[cfg(not(feature = "uuid"))]
{
use core::fmt::Write as _;
let mut buffer = alloc::string::String::new();
let prefix = match self.role {
EnergyManagementRole::Rm => "rm",
EnergyManagementRole::Cem => "cem",
};
let _ = write!(buffer, "{prefix}-{}", self.minted);
Id::parse(&buffer).unwrap_or(Id::NIL)
}
}
pub(crate) fn decode_options(&self) -> DecodeOptions {
DecodeOptions {
strictness: self.strictness,
profile: self.profile,
max_bytes: self.max_message_bytes,
}
}
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn transmit(&mut self, message: Message, now: Timestamp) -> Option<MessageHandle> {
let kind = message.kind();
let id = message.id();
self.registry.record(&message, Some(now));
self.outbox.push_back(Outgoing {
text: codec::encode(&message),
kind,
message_id: id,
});
self.stats.sent = self.stats.sent.saturating_add(1);
let handle = id.map(|id| MessageHandle { id, kind })?;
let deadline = now
.checked_add(self.ack_timeout)
.unwrap_or(Timestamp::UNIX_EPOCH);
self.acks.sent(handle, now, deadline);
Some(handle)
}
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn acknowledge(
&mut self,
subject: Id,
status: ReceptionStatusValues,
diagnostic: Option<String>,
now: Timestamp,
) {
let _ = now;
self.acks.answered(subject, status);
if status != ReceptionStatusValues::Ok {
self.stats.refused = self.stats.refused.saturating_add(1);
}
let message = Message::from(ReceptionStatus {
subject_message_id: subject,
status,
diagnostic_label: diagnostic,
});
self.outbox.push_back(Outgoing {
text: codec::encode(&message),
kind: MessageKind::ReceptionStatus,
message_id: None,
});
self.stats.sent = self.stats.sent.saturating_add(1);
}
#[must_use]
pub fn poll_timeout(&self) -> Option<Timestamp> {
if self.state.is_closed() {
return None;
}
match (self.acks.next_deadline(), self.registry.next_activation()) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
pub fn poll_transmit(&mut self) -> Option<Outgoing> {
self.outbox.pop_front()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Backoff {
pub base: Duration,
pub max: Duration,
}
impl Default for Backoff {
fn default() -> Self {
Self {
base: Duration::from_secs(2),
max: Duration::from_secs(600),
}
}
}
impl Backoff {
#[must_use]
pub fn ceiling(self, attempt: u32) -> Duration {
let scaled = self
.base
.as_millis()
.saturating_mul(1u64 << attempt.min(40));
Duration::from_millis(scaled.min(self.max.as_millis()))
}
#[must_use]
pub fn delay(self, attempt: u32, random: f64) -> Duration {
let ceiling = self.ceiling(attempt).as_millis();
#[allow(
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)]
Duration::from_millis((ceiling as f64 * random.clamp(0.0, 1.0)) as u64)
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
#[must_use]
pub fn delay_with(self, attempt: u32) -> Duration {
use rand::RngExt as _;
let mut rng = rand::rng();
self.delay(attempt, rng.random_range(0.0..1.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::common::{NumberRange, SessionRequestType};
use alloc::vec;
fn at(s: &str) -> Timestamp {
s.parse().unwrap()
}
fn core_config(role: EnergyManagementRole) -> CoreConfig {
CoreConfig {
role,
negotiation: Negotiation::Handshake,
ack_timeout: Duration::from_secs(5),
out_of_order: OutOfOrderPolicy::Report,
skew_tolerance: Duration::from_secs(30),
max_message_bytes: 1024,
strictness: codec::Strictness::Strict,
s2_connect: false,
reconnect_attempt: 0,
}
}
#[test]
fn every_identifier_the_engine_mints_is_different() {
let mut core = SessionCore::new(core_config(EnergyManagementRole::Rm));
let minted: Vec<Id> = (0..64).map(|_| core.next_message_id()).collect();
let mut unique = minted.clone();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), minted.len(), "identifiers must not repeat");
assert!(
!minted.contains(&Id::NIL),
"the nil identifier means `no message to name`, not `this message`"
);
let mut cem = SessionCore::new(core_config(EnergyManagementRole::Cem));
let theirs = cem.next_message_id();
assert_ne!(theirs, minted[0]);
#[cfg(not(feature = "uuid"))]
{
assert!(minted[0].as_str().starts_with("rm-"));
assert!(theirs.as_str().starts_with("cem-"));
}
}
#[test]
fn the_ledger_matches_answers_to_what_they_answer() {
let mut ledger = AckLedger::new(8);
let handle = MessageHandle {
id: Id::new_const("m1"),
kind: MessageKind::FrbcStorageStatus,
};
ledger.sent(
handle,
at("2024-01-01T12:00:00Z"),
at("2024-01-01T12:00:05Z"),
);
assert_eq!(ledger.outstanding(), 1);
let outcome = ledger.received(
&ReceptionStatus::ok(Id::new_const("m1")),
at("2024-01-01T12:00:00.250Z"),
);
assert_eq!(
outcome,
AckOutcome::Accepted {
handle,
latency: Duration::from_millis(250)
}
);
assert_eq!(ledger.outstanding(), 0);
let outcome = ledger.received(
&ReceptionStatus::ok(Id::new_const("m1")),
at("2024-01-01T12:00:01Z"),
);
assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
}
#[test]
fn an_unanswered_message_times_out_rather_than_blocking() {
let mut ledger = AckLedger::new(8);
let handle = MessageHandle {
id: Id::new_const("m1"),
kind: MessageKind::FrbcStorageStatus,
};
ledger.sent(
handle,
at("2024-01-01T12:00:00Z"),
at("2024-01-01T12:00:05Z"),
);
assert_eq!(ledger.next_deadline(), Some(at("2024-01-01T12:00:05Z")));
assert!(ledger.expire(at("2024-01-01T12:00:04Z")).is_empty());
assert_eq!(ledger.expire(at("2024-01-01T12:00:05Z")), vec![handle]);
assert_eq!(ledger.next_deadline(), None);
let outcome = ledger.received(
&ReceptionStatus::ok(Id::new_const("m1")),
at("2024-01-01T12:00:01Z"),
);
assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
}
#[test]
fn a_refusal_carries_the_standards_own_consequence() {
let mut ledger = AckLedger::new(8);
let handle = MessageHandle {
id: Id::new_const("m1"),
kind: MessageKind::FrbcInstruction,
};
ledger.sent(
handle,
at("2024-01-01T12:00:00Z"),
at("2024-01-01T12:00:05Z"),
);
let outcome = ledger.received(
&ReceptionStatus::error(
Id::new_const("m1"),
ReceptionStatusValues::TemporaryError,
"busy",
),
at("2024-01-01T12:00:01Z"),
);
match outcome {
AckOutcome::Refused { consequence, .. } => {
assert_eq!(consequence, Consequence::Retry);
}
other => panic!("{other:?}"),
}
}
#[test]
fn the_answered_ring_is_bounded_and_remembers_the_answer() {
let mut ledger = AckLedger::new(2);
ledger.answered(Id::new_const("m1"), ReceptionStatusValues::Ok);
ledger.answered(Id::new_const("m2"), ReceptionStatusValues::InvalidContent);
assert_eq!(
ledger.previous_answer(Id::new_const("m2")),
Some(ReceptionStatusValues::InvalidContent)
);
ledger.answered(Id::new_const("m3"), ReceptionStatusValues::Ok);
assert_eq!(ledger.previous_answer(Id::new_const("m1")), None);
assert!(ledger.has_seen(Id::new_const("m3")));
}
#[test]
fn a_description_valid_in_the_future_waits_its_turn() {
let mut registry = Registry::default();
let later = at("2024-01-01T13:00:00Z");
let now = at("2024-01-01T12:00:00Z");
let description = Message::from(frbc::SystemDescription {
message_id: Id::new_const("m1"),
valid_from: later,
actuators: vec![],
storage: frbc::StorageDescription {
diagnostic_label: None,
fill_level_label: None,
provides_leakage_behaviour: false,
provides_fill_level_target_profile: false,
provides_usage_forecast: false,
fill_level_range: NumberRange::new(0.0, 100.0),
},
});
registry.record(&description, Some(now));
assert!(registry.frbc.is_none(), "not effective yet");
assert_eq!(registry.next_activation(), Some(later));
assert!(registry.activate_due(at("2024-01-01T12:59:59Z")).is_empty());
let due = registry.activate_due(later);
assert_eq!(due.len(), 1);
assert!(registry.frbc.is_some());
assert_eq!(registry.next_activation(), None);
}
#[test]
fn revoking_removes_the_object_and_marks_an_instruction_revoked() {
let mut registry = Registry::default();
let constraints = pebc::PowerConstraints {
message_id: Id::new_const("m1"),
id: Id::new_const("pc1"),
valid_from: at("2024-01-01T12:00:00Z"),
valid_until: None,
consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
allowed_limit_ranges: vec![],
};
registry.record(&Message::from(constraints), None);
assert_eq!(registry.pebc_constraints.len(), 1);
assert_eq!(registry.published.len(), 1);
registry.revoke(RevokableObjects::PebcPowerConstraints, Id::new_const("pc1"));
assert!(registry.pebc_constraints.is_empty());
assert!(registry.published.is_empty());
registry.revoke(RevokableObjects::FrbcInstruction, Id::new_const("i1"));
assert_eq!(
registry.instruction_statuses,
vec![(Id::new_const("i1"), InstructionStatus::Revoked)]
);
}
fn frbc_description(message_id: Id, valid_from: Timestamp) -> Message {
Message::from(frbc::SystemDescription {
message_id,
valid_from,
actuators: vec![],
storage: frbc::StorageDescription {
diagnostic_label: None,
fill_level_label: None,
provides_leakage_behaviour: false,
provides_fill_level_target_profile: false,
provides_usage_forecast: false,
fill_level_range: NumberRange::new(0.0, 100.0),
},
})
}
#[test]
fn revoking_a_superseded_description_leaves_the_live_one_alone() {
let mut registry = Registry::default();
let now = at("2024-01-01T12:00:00Z");
registry.record(&frbc_description(Id::new_const("sd-a"), now), Some(now));
registry.record(&frbc_description(Id::new_const("sd-b"), now), Some(now));
assert_eq!(
registry.frbc.as_ref().map(|d| d.message_id),
Some(Id::new_const("sd-b"))
);
registry.revoke(
RevokableObjects::FrbcSystemDescription,
Id::new_const("sd-a"),
);
assert_eq!(
registry.frbc.as_ref().map(|d| d.message_id),
Some(Id::new_const("sd-b")),
"revoking the superseded description must not clear the live one"
);
registry.revoke(
RevokableObjects::FrbcSystemDescription,
Id::new_const("sd-b"),
);
assert!(registry.frbc.is_none());
}
#[test]
fn revoking_a_description_that_has_not_taken_effect_yet_cancels_it() {
let mut registry = Registry::default();
let now = at("2024-01-01T12:00:00Z");
let later = at("2024-01-01T13:00:00Z");
registry.record(&frbc_description(Id::new_const("sd-a"), later), Some(now));
assert_eq!(registry.next_activation(), Some(later));
registry.revoke(
RevokableObjects::FrbcSystemDescription,
Id::new_const("sd-a"),
);
assert_eq!(registry.next_activation(), None);
assert!(registry.activate_due(later).is_empty());
assert!(registry.frbc.is_none(), "a revoked description never runs");
}
#[test]
fn the_queue_of_future_descriptions_is_bounded_by_message_count_not_identifier_count() {
let mut registry = Registry::default();
let now = at("2024-01-01T12:00:00Z");
for minute in 0..100u32 {
let at_time = now
.checked_add(Duration::from_secs(u64::from(minute) * 60 + 60))
.unwrap();
let id_str = alloc::format!("sd-{minute:04}");
registry.record(
&frbc_description(Id::parse(&id_str).unwrap(), at_time),
Some(now),
);
}
assert_eq!(registry.scheduled.len(), Registry::MAX_SCHEDULED);
let furthest = registry.scheduled.iter().map(|(at, _)| *at).max().unwrap();
assert_eq!(
furthest,
now.checked_add(Duration::from_secs(Registry::MAX_SCHEDULED as u64 * 60))
.unwrap()
);
}
#[test]
fn re_announcing_a_future_description_corrects_it_rather_than_queueing_twice() {
let mut registry = Registry::default();
let now = at("2024-01-01T12:00:00Z");
let first = at("2024-01-01T13:00:00Z");
let corrected = at("2024-01-01T14:00:00Z");
registry.record(&frbc_description(Id::new_const("sd-a"), first), Some(now));
registry.record(
&frbc_description(Id::new_const("sd-a"), corrected),
Some(now),
);
assert_eq!(registry.scheduled.len(), 1);
assert_eq!(registry.next_activation(), Some(corrected));
}
#[test]
fn two_actuators_may_share_a_timer_identifier() {
let mut registry = Registry::default();
let mut status = |actuator: &'static str, finished_at: &str| {
registry.record(
&Message::from(frbc::TimerStatus {
message_id: Id::new_const("m1"),
timer_id: Id::new_const("timer1"),
actuator_id: Id::new_const(actuator),
finished_at: at(finished_at),
}),
None,
);
};
status("actuator1", "2024-01-01T13:00:00Z");
status("actuator2", "2024-01-01T11:00:00Z");
assert_eq!(registry.timers.len(), 2, "one entry per actuator");
let finished_at = |actuator: &'static str| {
registry
.timers
.iter()
.find(|t| t.actuator == Id::new_const(actuator) && t.timer == "timer1")
.map(|t| t.finished_at)
};
assert_eq!(finished_at("actuator1"), Some(at("2024-01-01T13:00:00Z")));
assert_eq!(finished_at("actuator2"), Some(at("2024-01-01T11:00:00Z")));
}
#[test]
fn resending_a_description_replaces_rather_than_accumulates() {
let mut registry = Registry::default();
for level in [10.0, 20.0] {
registry.record(
&Message::from(frbc::StorageStatus {
message_id: Id::new_const("m1"),
present_fill_level: level,
}),
None,
);
}
assert_eq!(registry.fill_level, Some(20.0));
let make = |id: &'static str, until: &str| pebc::PowerConstraints {
message_id: Id::new_const("mm"),
id: Id::new_const(id),
valid_from: at("2024-01-01T12:00:00Z"),
valid_until: Some(at(until)),
consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
allowed_limit_ranges: vec![],
};
registry.record(&Message::from(make("pc1", "2024-01-01T13:00:00Z")), None);
registry.record(&Message::from(make("pc1", "2024-01-01T14:00:00Z")), None);
assert_eq!(registry.pebc_constraints.len(), 1);
assert_eq!(
registry.pebc_constraints[0].valid_until,
Some(at("2024-01-01T14:00:00Z"))
);
}
#[test]
fn the_backoff_is_the_one_s2_connect_prescribes() {
let b = Backoff::default();
assert_eq!(b.ceiling(0), Duration::from_secs(2));
assert_eq!(b.ceiling(1), Duration::from_secs(4));
assert_eq!(b.ceiling(2), Duration::from_secs(8));
assert_eq!(b.ceiling(20), Duration::from_secs(600));
assert_eq!(b.ceiling(100), Duration::from_secs(600));
assert_eq!(b.delay(3, 0.0), Duration::ZERO);
assert_eq!(b.delay(3, 1.0), Duration::from_secs(16));
assert_eq!(b.delay(3, 0.5), Duration::from_secs(8));
}
#[test]
fn session_state_reports_what_may_flow() {
assert!(!SessionState::Connected.is_active());
assert_eq!(SessionState::Connected.active_control_type(), None);
let active = SessionState::ControlTypeSelected(ControlType::FillRateBasedControl);
assert!(active.is_active());
let inert = SessionState::ControlTypeSelected(ControlType::NotControllable);
assert!(!inert.is_active());
assert!(SessionState::Closed(CloseReason::Local).is_closed());
let _ = SessionRequestType::Terminate;
}
}