1use alloc::boxed::Box;
5use alloc::collections::VecDeque;
6use alloc::string::String;
7use alloc::vec::Vec;
8
9use crate::codec::{self, DecodeOptions};
10use crate::message::{Message, MessageKind};
11use crate::types::common::{
12 Consequence, ControlType, EnergyManagementRole, InstructionStatus, ReceptionStatus,
13 ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
14};
15use crate::types::{Duration, Id, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc};
16use crate::validate::{Context, TimerState};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Outgoing {
21 pub text: String,
23 pub kind: MessageKind,
25 pub message_id: Option<Id>,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct MessageHandle {
32 pub id: Id,
34 pub kind: MessageKind,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub enum Negotiation {
41 #[default]
43 Handshake,
44 PreNegotiated(WireProfile),
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum SessionState {
57 Idle,
59 Handshaking,
61 Connected,
63 ControlTypeSelected(ControlType),
66 Closed(CloseReason),
68}
69
70impl SessionState {
71 #[must_use]
84 pub fn phase(&self) -> crate::validate::Phase {
85 use crate::validate::Phase;
86 match self {
87 SessionState::Idle | SessionState::Handshaking => Phase::Negotiating,
88 SessionState::Connected | SessionState::Closed(_) => Phase::Connected,
89 SessionState::ControlTypeSelected(c) => Phase::selected(*c),
90 }
91 }
92
93 #[must_use]
95 pub fn active_control_type(&self) -> Option<ControlType> {
96 match self {
97 SessionState::ControlTypeSelected(c) if c.is_controllable() => Some(*c),
98 _ => None,
99 }
100 }
101
102 #[must_use]
104 pub fn is_active(&self) -> bool {
105 self.active_control_type().is_some()
106 }
107
108 #[must_use]
110 pub fn is_closed(&self) -> bool {
111 matches!(self, SessionState::Closed(_))
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
117#[non_exhaustive]
118pub enum CloseReason {
119 #[error("closed locally")]
121 Local,
122 #[error("the peer asked to {0:?}")]
124 PeerRequested(crate::types::common::SessionRequestType),
125 #[error("this side asked to {0:?}")]
133 LocallyRequested(crate::types::common::SessionRequestType),
134 #[error("the transport closed")]
136 TransportClosed,
137 #[error("the peer selected protocol version {selected}, which was not offered")]
139 UnsupportedVersion {
140 selected: crate::types::ProtocolVersion,
142 },
143 #[error("no protocol version is supported by both sides")]
145 NoCommonVersion,
146 #[error("the peer reported a permanent error: {0}")]
150 PermanentError(String),
151 #[error("protocol error: {0}")]
154 ProtocolError(String),
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
159pub enum OutOfOrderPolicy {
160 #[default]
167 Report,
168 Close,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
174#[non_exhaustive]
175pub enum SendError {
176 #[error("the session is closed")]
178 Closed,
179 #[error("{kind} is not allowed while the session is {state}")]
182 NotAllowed {
183 kind: MessageKind,
185 state: &'static str,
187 },
188 #[error("{kind} does not exist in S2 JSON {profile}")]
190 NotInProfile {
191 kind: MessageKind,
193 profile: WireProfile,
195 },
196 #[error("{0}")]
198 Invalid(Box<crate::validate::Violation>),
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum AckOutcome {
204 Accepted {
206 handle: MessageHandle,
208 latency: Duration,
210 },
211 Refused {
213 handle: MessageHandle,
215 status: ReceptionStatusValues,
217 diagnostic: Option<String>,
219 consequence: Consequence,
221 latency: Duration,
223 },
224 TimedOut(MessageHandle),
226 Unmatched {
228 subject: Id,
230 status: ReceptionStatusValues,
232 },
233}
234
235#[derive(Debug, Clone, Copy)]
237struct Outstanding {
238 handle: MessageHandle,
239 sent_at: Timestamp,
241 deadline: Timestamp,
243}
244
245#[derive(Debug, Clone, Default)]
251pub struct AckLedger {
252 pending: Vec<Outstanding>,
253 answered: VecDeque<(Id, ReceptionStatusValues)>,
256 max_answered: usize,
257}
258
259impl AckLedger {
260 #[must_use]
262 pub fn new(max_answered: usize) -> Self {
263 Self {
264 pending: Vec::new(),
265 answered: VecDeque::new(),
266 max_answered,
267 }
268 }
269
270 pub fn sent(&mut self, handle: MessageHandle, sent_at: Timestamp, deadline: Timestamp) {
272 self.pending.push(Outstanding {
273 handle,
274 sent_at,
275 deadline,
276 });
277 }
278
279 #[allow(clippy::needless_pass_by_value)]
282 pub fn received(&mut self, status: &ReceptionStatus, now: Timestamp) -> AckOutcome {
283 let Some(position) = self
284 .pending
285 .iter()
286 .position(|entry| entry.handle.id == status.subject_message_id)
287 else {
288 return AckOutcome::Unmatched {
289 subject: status.subject_message_id,
290 status: status.status,
291 };
292 };
293 let entry = self.pending.remove(position);
294 let latency = now.saturating_duration_since(entry.sent_at);
295 if status.status == ReceptionStatusValues::Ok {
296 AckOutcome::Accepted {
297 handle: entry.handle,
298 latency,
299 }
300 } else {
301 AckOutcome::Refused {
302 handle: entry.handle,
303 status: status.status,
304 diagnostic: status.diagnostic_label.clone(),
305 consequence: status.status.consequence(),
306 latency,
307 }
308 }
309 }
310
311 pub fn expire(&mut self, now: Timestamp) -> Vec<MessageHandle> {
313 let mut out = Vec::new();
314 self.pending.retain(|entry| {
315 if entry.deadline <= now {
316 out.push(entry.handle);
317 false
318 } else {
319 true
320 }
321 });
322 out
323 }
324
325 #[must_use]
327 pub fn next_deadline(&self) -> Option<Timestamp> {
328 self.pending.iter().map(|entry| entry.deadline).min()
329 }
330
331 #[must_use]
333 pub fn outstanding(&self) -> usize {
334 self.pending.len()
335 }
336
337 pub fn answered(&mut self, id: Id, status: ReceptionStatusValues) {
339 if self.answered.len() >= self.max_answered {
340 self.answered.pop_front();
341 }
342 self.answered.push_back((id, status));
343 }
344
345 #[must_use]
347 pub fn previous_answer(&self, id: Id) -> Option<ReceptionStatusValues> {
348 self.answered
349 .iter()
350 .rev()
351 .find(|(seen, _)| *seen == id)
352 .map(|(_, status)| *status)
353 }
354
355 #[must_use]
357 pub fn has_seen(&self, id: Id) -> bool {
358 self.previous_answer(id).is_some()
359 }
360
361 pub fn seen_ids(&self) -> Vec<Id> {
363 self.answered.iter().map(|(id, _)| *id).collect()
364 }
365}
366
367#[derive(Debug, Clone, Default)]
372pub struct Registry {
373 pub details: Option<ResourceManagerDetails>,
375 pub frbc: Option<frbc::SystemDescription>,
377 pub ombc: Option<ombc::SystemDescription>,
379 pub ddbc: Option<ddbc::SystemDescription>,
381 pub scheduled: Vec<(Timestamp, Message)>,
383 pub pebc_constraints: Vec<pebc::PowerConstraints>,
385 pub pebc_energy: Vec<pebc::EnergyConstraint>,
387 pub ppbc_profiles: Vec<ppbc::PowerProfileDefinition>,
389 pub instructions: Vec<Id>,
391 pub instruction_messages: Vec<(Id, Id)>,
400 pub instruction_statuses: Vec<(Id, InstructionStatus)>,
402 pub published: Vec<(RevokableObjects, Id)>,
404 pub active_modes: Vec<(Id, Id)>,
406 pub timers: Vec<TimerState>,
409 pub fill_level: Option<f64>,
411}
412
413impl Registry {
414 pub const MAX_TRACKED: usize = 4096;
416
417 pub const MAX_SCHEDULED: usize = 16;
423
424 fn bound<T>(v: &mut Vec<T>) {
425 if v.len() > Self::MAX_TRACKED {
426 v.remove(0);
427 }
428 }
429
430 fn upsert<T, K: PartialEq>(v: &mut Vec<T>, key: &K, value: T, key_of: impl Fn(&T) -> K) {
431 if let Some(slot) = v.iter_mut().find(|existing| key_of(existing) == *key) {
432 *slot = value;
433 } else {
434 v.push(value);
435 Self::bound(v);
436 }
437 }
438
439 #[allow(clippy::needless_pass_by_value)]
445 pub fn record(&mut self, message: &Message, now: Option<Timestamp>) {
446 if let Some((object_type, id)) = message.revokable_id() {
447 Self::upsert(
448 &mut self.published,
449 &(object_type, id),
450 (object_type, id),
451 |(t, i)| (*t, *i),
452 );
453 }
454 if let Some(id) = message.instruction_id() {
455 if !self.instructions.contains(&id) {
456 self.instructions.push(id);
457 Self::bound(&mut self.instructions);
458 }
459 if let Some(message_id) = message.id() {
460 Self::upsert(
461 &mut self.instruction_messages,
462 &message_id,
463 (message_id, id),
464 |(m, _)| *m,
465 );
466 }
467 }
468
469 let scheduled_for = match message {
470 Message::FrbcSystemDescription(d) => Some(d.valid_from),
471 Message::OmbcSystemDescription(d) => Some(d.valid_from),
472 Message::DdbcSystemDescription(d) => Some(d.valid_from),
473 _ => None,
474 };
475 if let (Some(valid_from), Some(now)) = (scheduled_for, now)
476 && valid_from > now
477 {
478 self.schedule(valid_from, message);
479 return;
480 }
481
482 self.apply(message);
483 }
484
485 fn schedule(&mut self, valid_from: Timestamp, message: &Message) {
487 let identity = message.revokable_id();
490 if let Some(slot) = self
491 .scheduled
492 .iter_mut()
493 .find(|(_, queued)| queued.revokable_id() == identity)
494 {
495 *slot = (valid_from, message.clone());
496 return;
497 }
498 self.scheduled.push((valid_from, message.clone()));
499 while self.scheduled.len() > Self::MAX_SCHEDULED {
500 if let Some(furthest) = self
502 .scheduled
503 .iter()
504 .enumerate()
505 .max_by_key(|(_, (at, _))| *at)
506 .map(|(i, _)| i)
507 {
508 self.scheduled.remove(furthest);
509 } else {
510 break;
511 }
512 }
513 }
514
515 fn apply(&mut self, message: &Message) {
517 match message {
518 Message::ResourceManagerDetails(d) => self.details = Some((**d).clone()),
519 Message::FrbcSystemDescription(d) => {
526 self.frbc = Some((**d).clone());
527 self.forget_actuator_state();
528 }
529 Message::OmbcSystemDescription(d) => {
530 self.ombc = Some((**d).clone());
531 self.forget_actuator_state();
532 }
533 Message::DdbcSystemDescription(d) => {
534 self.ddbc = Some((**d).clone());
535 self.forget_actuator_state();
536 }
537 Message::PebcPowerConstraints(c) => Self::upsert(
538 &mut self.pebc_constraints,
539 &c.id,
540 (**c).clone(),
541 |existing| existing.id,
542 ),
543 Message::PebcEnergyConstraint(c) => {
544 Self::upsert(&mut self.pebc_energy, &c.id, (**c).clone(), |e| e.id);
545 }
546 Message::PpbcPowerProfileDefinition(p) => {
547 Self::upsert(&mut self.ppbc_profiles, &p.id, (**p).clone(), |e| e.id);
548 }
549 Message::FrbcStorageStatus(s) => self.fill_level = Some(s.present_fill_level),
550 Message::FrbcActuatorStatus(s) => {
551 Self::upsert(
552 &mut self.active_modes,
553 &s.actuator_id,
554 (s.actuator_id, s.active_operation_mode_id),
555 |(a, _)| *a,
556 );
557 }
558 Message::DdbcActuatorStatus(s) => {
559 Self::upsert(
560 &mut self.active_modes,
561 &s.actuator_id,
562 (s.actuator_id, s.active_operation_mode_id),
563 |(a, _)| *a,
564 );
565 }
566 Message::OmbcStatus(s) => {
567 Self::upsert(
568 &mut self.active_modes,
569 &Id::NIL,
570 (Id::NIL, s.active_operation_mode_id),
571 |(a, _)| *a,
572 );
573 }
574 Message::FrbcTimerStatus(s) => {
575 let actuator = s.actuator_id;
576 Self::upsert(
577 &mut self.timers,
578 &(actuator, s.timer_id),
579 TimerState {
580 actuator,
581 timer: s.timer_id,
582 finished_at: s.finished_at,
583 },
584 |t| (t.actuator, t.timer),
585 );
586 }
587 Message::DdbcTimerStatus(s) => {
588 let actuator = s.actuator_id;
589 Self::upsert(
590 &mut self.timers,
591 &(actuator, s.timer_id),
592 TimerState {
593 actuator,
594 timer: s.timer_id,
595 finished_at: s.finished_at,
596 },
597 |t| (t.actuator, t.timer),
598 );
599 }
600 Message::OmbcTimerStatus(s) => {
601 let actuator = Id::NIL;
602 Self::upsert(
603 &mut self.timers,
604 &(actuator, s.timer_id),
605 TimerState {
606 actuator,
607 timer: s.timer_id,
608 finished_at: s.finished_at,
609 },
610 |t| (t.actuator, t.timer),
611 );
612 }
613 Message::InstructionStatusUpdate(u) => Self::upsert(
614 &mut self.instruction_statuses,
615 &u.instruction_id,
616 (u.instruction_id, u.status_type),
617 |(i, _)| *i,
618 ),
619 Message::RevokeObject(r) => self.revoke(r.object_type, r.object_id),
620 _ => {}
621 }
622 }
623
624 fn forget_actuator_state(&mut self) {
627 self.active_modes.clear();
628 self.timers.clear();
629 }
630
631 pub fn activate_due(&mut self, now: Timestamp) -> Vec<Message> {
633 let mut due = Vec::new();
634 self.scheduled.retain(|(at, message)| {
635 if *at <= now {
636 due.push(message.clone());
637 false
638 } else {
639 true
640 }
641 });
642 for message in &due {
643 self.apply(message);
644 }
645 due
646 }
647
648 #[must_use]
650 pub fn next_activation(&self) -> Option<Timestamp> {
651 self.scheduled.iter().map(|(at, _)| *at).min()
652 }
653
654 pub fn revoke(&mut self, object_type: RevokableObjects, object_id: Id) {
662 self.published
663 .retain(|(t, i)| !(*t == object_type && *i == object_id));
664 self.scheduled
667 .retain(|(_, message)| message.revokable_id() != Some((object_type, object_id)));
668 match object_type {
669 RevokableObjects::PebcPowerConstraints => {
670 self.pebc_constraints.retain(|c| c.id != object_id);
671 }
672 RevokableObjects::PebcEnergyConstraint => {
673 self.pebc_energy.retain(|c| c.id != object_id);
674 }
675 RevokableObjects::PpbcPowerProfileDefinition => {
676 self.ppbc_profiles.retain(|p| p.id != object_id);
677 }
678 RevokableObjects::FrbcSystemDescription => {
679 if self
680 .frbc
681 .as_ref()
682 .is_some_and(|d| d.message_id == object_id)
683 {
684 self.frbc = None;
685 self.forget_actuator_state();
686 }
687 }
688 RevokableObjects::OmbcSystemDescription => {
689 if self
690 .ombc
691 .as_ref()
692 .is_some_and(|d| d.message_id == object_id)
693 {
694 self.ombc = None;
695 self.forget_actuator_state();
696 }
697 }
698 RevokableObjects::DdbcSystemDescription => {
699 if self
700 .ddbc
701 .as_ref()
702 .is_some_and(|d| d.message_id == object_id)
703 {
704 self.ddbc = None;
705 self.forget_actuator_state();
706 }
707 }
708 _ => {
709 Self::upsert(
712 &mut self.instruction_statuses,
713 &object_id,
714 (object_id, InstructionStatus::Revoked),
715 |(i, _)| *i,
716 );
717 }
718 }
719 }
720
721 #[allow(clippy::too_many_arguments)]
726 pub fn context<'a>(
727 &'a self,
728 profile: WireProfile,
729 sender: EnergyManagementRole,
730 phase: crate::validate::Phase,
731 s2_connect: bool,
732 now: Timestamp,
733 seen: &'a [Id],
734 skew_tolerance: Duration,
735 ) -> Context<'a> {
736 Context {
737 profile,
738 sender: Some(sender),
739 phase,
740 s2_connect,
741 details: self.details.as_ref(),
742 frbc: self.frbc.as_ref(),
743 ombc: self.ombc.as_ref(),
744 ddbc: self.ddbc.as_ref(),
745 pebc_constraints: &self.pebc_constraints,
746 ppbc_profiles: &self.ppbc_profiles,
747 instructions: &self.instructions,
748 instruction_messages: &self.instruction_messages,
749 instruction_statuses: &self.instruction_statuses,
750 seen_message_ids: seen,
751 published: &self.published,
752 active_modes: &self.active_modes,
753 timers: &self.timers,
754 fill_level: self.fill_level,
755 now: Some(now),
756 skew_tolerance,
757 }
758 }
759}
760
761#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
770#[non_exhaustive]
771pub struct Stats {
772 pub sent: u64,
774 pub received: u64,
776 pub undecodable: u64,
778 pub refused: u64,
780 pub accepted_with_warnings: u64,
783 pub sent_with_warnings: u64,
790 pub duplicates: u64,
792 pub acked: u64,
794 pub nacked: u64,
796 pub ack_timeouts: u64,
798 pub unmatched_acks: u64,
800 pub ack_latency_total_ms: u64,
805 pub ack_latency_max_ms: u64,
807}
808
809impl Stats {
810 #[must_use]
812 pub const fn answered(&self) -> u64 {
813 self.acked + self.nacked
814 }
815
816 #[must_use]
818 pub const fn mean_ack_latency_ms(&self) -> Option<u64> {
819 match self.answered() {
820 0 => None,
821 n => Some(self.ack_latency_total_ms / n),
822 }
823 }
824
825 pub(crate) fn record_latency(&mut self, latency: Duration) {
826 let ms = latency.as_millis();
827 self.ack_latency_total_ms = self.ack_latency_total_ms.saturating_add(ms);
828 self.ack_latency_max_ms = self.ack_latency_max_ms.max(ms);
829 }
830}
831
832#[derive(Debug, Clone)]
834pub struct SessionCore {
835 pub state: SessionState,
837 pub negotiation: Negotiation,
839 pub profile: WireProfile,
841 pub s2_connect: bool,
843 pub outbox: VecDeque<Outgoing>,
845 pub acks: AckLedger,
847 pub registry: Registry,
849 pub ack_timeout: Duration,
851 pub out_of_order: OutOfOrderPolicy,
853 pub skew_tolerance: Duration,
855 pub max_message_bytes: usize,
857 pub strictness: codec::Strictness,
859 pub reconnect_attempt: u32,
867 pub stats: Stats,
869 #[cfg_attr(feature = "uuid", allow(dead_code))]
874 role: EnergyManagementRole,
875 minted: u64,
877}
878
879pub(crate) struct CoreConfig {
886 pub role: EnergyManagementRole,
887 pub negotiation: Negotiation,
888 pub ack_timeout: Duration,
889 pub out_of_order: OutOfOrderPolicy,
890 pub skew_tolerance: Duration,
891 pub max_message_bytes: usize,
892 pub strictness: codec::Strictness,
893 pub s2_connect: bool,
894 pub reconnect_attempt: u32,
895}
896
897impl SessionCore {
898 pub(crate) fn new(cfg: CoreConfig) -> Self {
899 let CoreConfig {
900 role,
901 negotiation,
902 ack_timeout,
903 out_of_order,
904 skew_tolerance,
905 max_message_bytes,
906 strictness,
907 s2_connect,
908 reconnect_attempt,
909 } = cfg;
910 let profile = match &negotiation {
911 Negotiation::PreNegotiated(p) => *p,
912 Negotiation::Handshake => WireProfile::V1_0_0,
913 };
914 Self {
915 state: SessionState::Idle,
916 negotiation,
917 profile,
918 s2_connect,
919 outbox: VecDeque::new(),
920 acks: AckLedger::new(256),
921 registry: Registry::default(),
922 ack_timeout,
923 out_of_order,
924 skew_tolerance,
925 max_message_bytes,
926 strictness,
927 reconnect_attempt,
928 stats: Stats::default(),
929 role,
930 minted: 0,
931 }
932 }
933
934 pub(crate) fn next_message_id(&mut self) -> Id {
941 self.minted = self.minted.wrapping_add(1);
942 #[cfg(feature = "uuid")]
943 {
944 Id::generate()
945 }
946 #[cfg(not(feature = "uuid"))]
947 {
948 use core::fmt::Write as _;
949 let mut buffer = alloc::string::String::new();
950 let prefix = match self.role {
951 EnergyManagementRole::Rm => "rm",
952 EnergyManagementRole::Cem => "cem",
953 };
954 let _ = write!(buffer, "{prefix}-{}", self.minted);
956 Id::parse(&buffer).unwrap_or(Id::NIL)
957 }
958 }
959
960 pub(crate) fn decode_options(&self) -> DecodeOptions {
961 DecodeOptions {
962 strictness: self.strictness,
963 profile: self.profile,
964 max_bytes: self.max_message_bytes,
965 }
966 }
967
968 #[allow(clippy::needless_pass_by_value)]
972 pub(crate) fn transmit(&mut self, message: Message, now: Timestamp) -> Option<MessageHandle> {
973 let kind = message.kind();
974 let id = message.id();
975 self.registry.record(&message, Some(now));
976 self.outbox.push_back(Outgoing {
977 text: codec::encode(&message),
978 kind,
979 message_id: id,
980 });
981 self.stats.sent = self.stats.sent.saturating_add(1);
982 let handle = id.map(|id| MessageHandle { id, kind })?;
987 let deadline = now
988 .checked_add(self.ack_timeout)
989 .unwrap_or(Timestamp::UNIX_EPOCH);
990 self.acks.sent(handle, now, deadline);
991 Some(handle)
992 }
993
994 #[allow(clippy::needless_pass_by_value)]
997 pub(crate) fn acknowledge(
998 &mut self,
999 subject: Id,
1000 status: ReceptionStatusValues,
1001 diagnostic: Option<String>,
1002 now: Timestamp,
1003 ) {
1004 let _ = now;
1005 self.acks.answered(subject, status);
1006 if status != ReceptionStatusValues::Ok {
1007 self.stats.refused = self.stats.refused.saturating_add(1);
1008 }
1009 let message = Message::from(ReceptionStatus {
1010 subject_message_id: subject,
1011 status,
1012 diagnostic_label: diagnostic,
1013 });
1014 self.outbox.push_back(Outgoing {
1015 text: codec::encode(&message),
1016 kind: MessageKind::ReceptionStatus,
1017 message_id: None,
1018 });
1019 self.stats.sent = self.stats.sent.saturating_add(1);
1020 }
1021
1022 #[must_use]
1030 pub fn poll_timeout(&self) -> Option<Timestamp> {
1031 if self.state.is_closed() {
1032 return None;
1033 }
1034 match (self.acks.next_deadline(), self.registry.next_activation()) {
1035 (Some(a), Some(b)) => Some(a.min(b)),
1036 (a, b) => a.or(b),
1037 }
1038 }
1039
1040 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
1042 self.outbox.pop_front()
1043 }
1044}
1045
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1054pub struct Backoff {
1055 pub base: Duration,
1057 pub max: Duration,
1059}
1060
1061impl Default for Backoff {
1062 fn default() -> Self {
1063 Self {
1064 base: Duration::from_secs(2),
1065 max: Duration::from_secs(600),
1066 }
1067 }
1068}
1069
1070impl Backoff {
1071 #[must_use]
1073 pub fn ceiling(self, attempt: u32) -> Duration {
1074 let scaled = self
1075 .base
1076 .as_millis()
1077 .saturating_mul(1u64 << attempt.min(40));
1078 Duration::from_millis(scaled.min(self.max.as_millis()))
1079 }
1080
1081 #[must_use]
1083 pub fn delay(self, attempt: u32, random: f64) -> Duration {
1084 let ceiling = self.ceiling(attempt).as_millis();
1085 #[allow(
1086 clippy::cast_precision_loss,
1087 clippy::cast_sign_loss,
1088 clippy::cast_possible_truncation
1089 )]
1090 Duration::from_millis((ceiling as f64 * random.clamp(0.0, 1.0)) as u64)
1091 }
1092
1093 #[cfg(feature = "std")]
1095 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1096 #[must_use]
1097 pub fn delay_with(self, attempt: u32) -> Duration {
1098 use rand::RngExt as _;
1099 let mut rng = rand::rng();
1100 self.delay(attempt, rng.random_range(0.0..1.0))
1101 }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106 use super::*;
1107 use crate::types::common::{NumberRange, SessionRequestType};
1108 use alloc::vec;
1109
1110 fn at(s: &str) -> Timestamp {
1111 s.parse().unwrap()
1112 }
1113
1114 fn core_config(role: EnergyManagementRole) -> CoreConfig {
1115 CoreConfig {
1116 role,
1117 negotiation: Negotiation::Handshake,
1118 ack_timeout: Duration::from_secs(5),
1119 out_of_order: OutOfOrderPolicy::Report,
1120 skew_tolerance: Duration::from_secs(30),
1121 max_message_bytes: 1024,
1122 strictness: codec::Strictness::Strict,
1123 s2_connect: false,
1124 reconnect_attempt: 0,
1125 }
1126 }
1127
1128 #[test]
1129 fn every_identifier_the_engine_mints_is_different() {
1130 let mut core = SessionCore::new(core_config(EnergyManagementRole::Rm));
1133 let minted: Vec<Id> = (0..64).map(|_| core.next_message_id()).collect();
1134 let mut unique = minted.clone();
1135 unique.sort_unstable();
1136 unique.dedup();
1137 assert_eq!(unique.len(), minted.len(), "identifiers must not repeat");
1138 assert!(
1139 !minted.contains(&Id::NIL),
1140 "the nil identifier means `no message to name`, not `this message`"
1141 );
1142
1143 let mut cem = SessionCore::new(core_config(EnergyManagementRole::Cem));
1146 let theirs = cem.next_message_id();
1147 assert_ne!(theirs, minted[0]);
1148 #[cfg(not(feature = "uuid"))]
1149 {
1150 assert!(minted[0].as_str().starts_with("rm-"));
1151 assert!(theirs.as_str().starts_with("cem-"));
1152 }
1153 }
1154
1155 #[test]
1156 fn the_ledger_matches_answers_to_what_they_answer() {
1157 let mut ledger = AckLedger::new(8);
1158 let handle = MessageHandle {
1159 id: Id::new_const("m1"),
1160 kind: MessageKind::FrbcStorageStatus,
1161 };
1162 ledger.sent(
1163 handle,
1164 at("2024-01-01T12:00:00Z"),
1165 at("2024-01-01T12:00:05Z"),
1166 );
1167 assert_eq!(ledger.outstanding(), 1);
1168
1169 let outcome = ledger.received(
1170 &ReceptionStatus::ok(Id::new_const("m1")),
1171 at("2024-01-01T12:00:00.250Z"),
1172 );
1173 assert_eq!(
1176 outcome,
1177 AckOutcome::Accepted {
1178 handle,
1179 latency: Duration::from_millis(250)
1180 }
1181 );
1182 assert_eq!(ledger.outstanding(), 0);
1183
1184 let outcome = ledger.received(
1186 &ReceptionStatus::ok(Id::new_const("m1")),
1187 at("2024-01-01T12:00:01Z"),
1188 );
1189 assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1190 }
1191
1192 #[test]
1193 fn an_unanswered_message_times_out_rather_than_blocking() {
1194 let mut ledger = AckLedger::new(8);
1195 let handle = MessageHandle {
1196 id: Id::new_const("m1"),
1197 kind: MessageKind::FrbcStorageStatus,
1198 };
1199 ledger.sent(
1200 handle,
1201 at("2024-01-01T12:00:00Z"),
1202 at("2024-01-01T12:00:05Z"),
1203 );
1204 assert_eq!(ledger.next_deadline(), Some(at("2024-01-01T12:00:05Z")));
1205 assert!(ledger.expire(at("2024-01-01T12:00:04Z")).is_empty());
1206 assert_eq!(ledger.expire(at("2024-01-01T12:00:05Z")), vec![handle]);
1207 assert_eq!(ledger.next_deadline(), None);
1208
1209 let outcome = ledger.received(
1211 &ReceptionStatus::ok(Id::new_const("m1")),
1212 at("2024-01-01T12:00:01Z"),
1213 );
1214 assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1215 }
1216
1217 #[test]
1218 fn a_refusal_carries_the_standards_own_consequence() {
1219 let mut ledger = AckLedger::new(8);
1220 let handle = MessageHandle {
1221 id: Id::new_const("m1"),
1222 kind: MessageKind::FrbcInstruction,
1223 };
1224 ledger.sent(
1225 handle,
1226 at("2024-01-01T12:00:00Z"),
1227 at("2024-01-01T12:00:05Z"),
1228 );
1229 let outcome = ledger.received(
1230 &ReceptionStatus::error(
1231 Id::new_const("m1"),
1232 ReceptionStatusValues::TemporaryError,
1233 "busy",
1234 ),
1235 at("2024-01-01T12:00:01Z"),
1236 );
1237 match outcome {
1238 AckOutcome::Refused { consequence, .. } => {
1239 assert_eq!(consequence, Consequence::Retry);
1240 }
1241 other => panic!("{other:?}"),
1242 }
1243 }
1244
1245 #[test]
1246 fn the_answered_ring_is_bounded_and_remembers_the_answer() {
1247 let mut ledger = AckLedger::new(2);
1248 ledger.answered(Id::new_const("m1"), ReceptionStatusValues::Ok);
1249 ledger.answered(Id::new_const("m2"), ReceptionStatusValues::InvalidContent);
1250 assert_eq!(
1251 ledger.previous_answer(Id::new_const("m2")),
1252 Some(ReceptionStatusValues::InvalidContent)
1253 );
1254 ledger.answered(Id::new_const("m3"), ReceptionStatusValues::Ok);
1255 assert_eq!(ledger.previous_answer(Id::new_const("m1")), None);
1257 assert!(ledger.has_seen(Id::new_const("m3")));
1258 }
1259
1260 #[test]
1261 fn a_description_valid_in_the_future_waits_its_turn() {
1262 let mut registry = Registry::default();
1263 let later = at("2024-01-01T13:00:00Z");
1264 let now = at("2024-01-01T12:00:00Z");
1265 let description = Message::from(frbc::SystemDescription {
1266 message_id: Id::new_const("m1"),
1267 valid_from: later,
1268 actuators: vec![],
1269 storage: frbc::StorageDescription {
1270 diagnostic_label: None,
1271 fill_level_label: None,
1272 provides_leakage_behaviour: false,
1273 provides_fill_level_target_profile: false,
1274 provides_usage_forecast: false,
1275 fill_level_range: NumberRange::new(0.0, 100.0),
1276 },
1277 });
1278
1279 registry.record(&description, Some(now));
1280 assert!(registry.frbc.is_none(), "not effective yet");
1281 assert_eq!(registry.next_activation(), Some(later));
1282 assert!(registry.activate_due(at("2024-01-01T12:59:59Z")).is_empty());
1283
1284 let due = registry.activate_due(later);
1285 assert_eq!(due.len(), 1);
1286 assert!(registry.frbc.is_some());
1287 assert_eq!(registry.next_activation(), None);
1288 }
1289
1290 #[test]
1291 fn revoking_removes_the_object_and_marks_an_instruction_revoked() {
1292 let mut registry = Registry::default();
1293 let constraints = pebc::PowerConstraints {
1294 message_id: Id::new_const("m1"),
1295 id: Id::new_const("pc1"),
1296 valid_from: at("2024-01-01T12:00:00Z"),
1297 valid_until: None,
1298 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1299 allowed_limit_ranges: vec![],
1300 };
1301 registry.record(&Message::from(constraints), None);
1302 assert_eq!(registry.pebc_constraints.len(), 1);
1303 assert_eq!(registry.published.len(), 1);
1304
1305 registry.revoke(RevokableObjects::PebcPowerConstraints, Id::new_const("pc1"));
1306 assert!(registry.pebc_constraints.is_empty());
1307 assert!(registry.published.is_empty());
1308
1309 registry.revoke(RevokableObjects::FrbcInstruction, Id::new_const("i1"));
1310 assert_eq!(
1311 registry.instruction_statuses,
1312 vec![(Id::new_const("i1"), InstructionStatus::Revoked)]
1313 );
1314 }
1315
1316 fn frbc_description(message_id: Id, valid_from: Timestamp) -> Message {
1317 Message::from(frbc::SystemDescription {
1318 message_id,
1319 valid_from,
1320 actuators: vec![],
1321 storage: frbc::StorageDescription {
1322 diagnostic_label: None,
1323 fill_level_label: None,
1324 provides_leakage_behaviour: false,
1325 provides_fill_level_target_profile: false,
1326 provides_usage_forecast: false,
1327 fill_level_range: NumberRange::new(0.0, 100.0),
1328 },
1329 })
1330 }
1331
1332 #[test]
1333 fn revoking_a_superseded_description_leaves_the_live_one_alone() {
1334 let mut registry = Registry::default();
1339 let now = at("2024-01-01T12:00:00Z");
1340 registry.record(&frbc_description(Id::new_const("sd-a"), now), Some(now));
1341 registry.record(&frbc_description(Id::new_const("sd-b"), now), Some(now));
1342 assert_eq!(
1343 registry.frbc.as_ref().map(|d| d.message_id),
1344 Some(Id::new_const("sd-b"))
1345 );
1346
1347 registry.revoke(
1348 RevokableObjects::FrbcSystemDescription,
1349 Id::new_const("sd-a"),
1350 );
1351 assert_eq!(
1352 registry.frbc.as_ref().map(|d| d.message_id),
1353 Some(Id::new_const("sd-b")),
1354 "revoking the superseded description must not clear the live one"
1355 );
1356
1357 registry.revoke(
1359 RevokableObjects::FrbcSystemDescription,
1360 Id::new_const("sd-b"),
1361 );
1362 assert!(registry.frbc.is_none());
1363 }
1364
1365 #[test]
1366 fn revoking_a_description_that_has_not_taken_effect_yet_cancels_it() {
1367 let mut registry = Registry::default();
1368 let now = at("2024-01-01T12:00:00Z");
1369 let later = at("2024-01-01T13:00:00Z");
1370 registry.record(&frbc_description(Id::new_const("sd-a"), later), Some(now));
1371 assert_eq!(registry.next_activation(), Some(later));
1372
1373 registry.revoke(
1374 RevokableObjects::FrbcSystemDescription,
1375 Id::new_const("sd-a"),
1376 );
1377 assert_eq!(registry.next_activation(), None);
1378 assert!(registry.activate_due(later).is_empty());
1379 assert!(registry.frbc.is_none(), "a revoked description never runs");
1380 }
1381
1382 #[test]
1383 fn the_queue_of_future_descriptions_is_bounded_by_message_count_not_identifier_count() {
1384 let mut registry = Registry::default();
1388 let now = at("2024-01-01T12:00:00Z");
1389 for minute in 0..100u32 {
1390 let at_time = now
1391 .checked_add(Duration::from_secs(u64::from(minute) * 60 + 60))
1392 .unwrap();
1393 let id_str = alloc::format!("sd-{minute:04}");
1394 registry.record(
1395 &frbc_description(Id::parse(&id_str).unwrap(), at_time),
1396 Some(now),
1397 );
1398 }
1399 assert_eq!(registry.scheduled.len(), Registry::MAX_SCHEDULED);
1400 let furthest = registry.scheduled.iter().map(|(at, _)| *at).max().unwrap();
1403 assert_eq!(
1404 furthest,
1405 now.checked_add(Duration::from_secs(Registry::MAX_SCHEDULED as u64 * 60))
1406 .unwrap()
1407 );
1408 }
1409
1410 #[test]
1411 fn re_announcing_a_future_description_corrects_it_rather_than_queueing_twice() {
1412 let mut registry = Registry::default();
1413 let now = at("2024-01-01T12:00:00Z");
1414 let first = at("2024-01-01T13:00:00Z");
1415 let corrected = at("2024-01-01T14:00:00Z");
1416 registry.record(&frbc_description(Id::new_const("sd-a"), first), Some(now));
1417 registry.record(
1418 &frbc_description(Id::new_const("sd-a"), corrected),
1419 Some(now),
1420 );
1421 assert_eq!(registry.scheduled.len(), 1);
1422 assert_eq!(registry.next_activation(), Some(corrected));
1423 }
1424
1425 #[test]
1426 fn two_actuators_may_share_a_timer_identifier() {
1427 let mut registry = Registry::default();
1431 let mut status = |actuator: &'static str, finished_at: &str| {
1432 registry.record(
1433 &Message::from(frbc::TimerStatus {
1434 message_id: Id::new_const("m1"),
1435 timer_id: Id::new_const("timer1"),
1436 actuator_id: Id::new_const(actuator),
1437 finished_at: at(finished_at),
1438 }),
1439 None,
1440 );
1441 };
1442 status("actuator1", "2024-01-01T13:00:00Z");
1443 status("actuator2", "2024-01-01T11:00:00Z");
1444
1445 assert_eq!(registry.timers.len(), 2, "one entry per actuator");
1446 let finished_at = |actuator: &'static str| {
1447 registry
1448 .timers
1449 .iter()
1450 .find(|t| t.actuator == Id::new_const(actuator) && t.timer == "timer1")
1451 .map(|t| t.finished_at)
1452 };
1453 assert_eq!(finished_at("actuator1"), Some(at("2024-01-01T13:00:00Z")));
1454 assert_eq!(finished_at("actuator2"), Some(at("2024-01-01T11:00:00Z")));
1455 }
1456
1457 #[test]
1458 fn resending_a_description_replaces_rather_than_accumulates() {
1459 let mut registry = Registry::default();
1460 for level in [10.0, 20.0] {
1461 registry.record(
1462 &Message::from(frbc::StorageStatus {
1463 message_id: Id::new_const("m1"),
1464 present_fill_level: level,
1465 }),
1466 None,
1467 );
1468 }
1469 assert_eq!(registry.fill_level, Some(20.0));
1470
1471 let make = |id: &'static str, until: &str| pebc::PowerConstraints {
1472 message_id: Id::new_const("mm"),
1473 id: Id::new_const(id),
1474 valid_from: at("2024-01-01T12:00:00Z"),
1475 valid_until: Some(at(until)),
1476 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1477 allowed_limit_ranges: vec![],
1478 };
1479 registry.record(&Message::from(make("pc1", "2024-01-01T13:00:00Z")), None);
1480 registry.record(&Message::from(make("pc1", "2024-01-01T14:00:00Z")), None);
1481 assert_eq!(registry.pebc_constraints.len(), 1);
1482 assert_eq!(
1483 registry.pebc_constraints[0].valid_until,
1484 Some(at("2024-01-01T14:00:00Z"))
1485 );
1486 }
1487
1488 #[test]
1489 fn the_backoff_is_the_one_s2_connect_prescribes() {
1490 let b = Backoff::default();
1491 assert_eq!(b.ceiling(0), Duration::from_secs(2));
1493 assert_eq!(b.ceiling(1), Duration::from_secs(4));
1494 assert_eq!(b.ceiling(2), Duration::from_secs(8));
1495 assert_eq!(b.ceiling(20), Duration::from_secs(600));
1496 assert_eq!(b.ceiling(100), Duration::from_secs(600));
1497 assert_eq!(b.delay(3, 0.0), Duration::ZERO);
1499 assert_eq!(b.delay(3, 1.0), Duration::from_secs(16));
1500 assert_eq!(b.delay(3, 0.5), Duration::from_secs(8));
1501 }
1502
1503 #[test]
1504 fn session_state_reports_what_may_flow() {
1505 assert!(!SessionState::Connected.is_active());
1506 assert_eq!(SessionState::Connected.active_control_type(), None);
1507 let active = SessionState::ControlTypeSelected(ControlType::FillRateBasedControl);
1508 assert!(active.is_active());
1509 let inert = SessionState::ControlTypeSelected(ControlType::NotControllable);
1511 assert!(!inert.is_active());
1512 assert!(SessionState::Closed(CloseReason::Local).is_closed());
1513 let _ = SessionRequestType::Terminate;
1514 }
1515}