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]
73 pub fn active_control_type(&self) -> Option<ControlType> {
74 match self {
75 SessionState::ControlTypeSelected(c) if c.is_controllable() => Some(*c),
76 _ => None,
77 }
78 }
79
80 #[must_use]
82 pub fn is_active(&self) -> bool {
83 self.active_control_type().is_some()
84 }
85
86 #[must_use]
88 pub fn is_closed(&self) -> bool {
89 matches!(self, SessionState::Closed(_))
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
95#[non_exhaustive]
96pub enum CloseReason {
97 #[error("closed locally")]
99 Local,
100 #[error("the peer asked to {0:?}")]
102 PeerRequested(crate::types::common::SessionRequestType),
103 #[error("this side asked to {0:?}")]
111 LocallyRequested(crate::types::common::SessionRequestType),
112 #[error("the transport closed")]
114 TransportClosed,
115 #[error("the peer selected protocol version {selected}, which was not offered")]
117 UnsupportedVersion {
118 selected: crate::types::ProtocolVersion,
120 },
121 #[error("no protocol version is supported by both sides")]
123 NoCommonVersion,
124 #[error("the peer reported a permanent error: {0}")]
128 PermanentError(String),
129 #[error("protocol error: {0}")]
132 ProtocolError(String),
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum OutOfOrderPolicy {
138 #[default]
145 Report,
146 Close,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
152#[non_exhaustive]
153pub enum SendError {
154 #[error("the session is closed")]
156 Closed,
157 #[error("{kind} is not allowed while the session is {state}")]
160 NotAllowed {
161 kind: MessageKind,
163 state: &'static str,
165 },
166 #[error("{kind} does not exist in S2 JSON {profile}")]
168 NotInProfile {
169 kind: MessageKind,
171 profile: WireProfile,
173 },
174 #[error("{0}")]
176 Invalid(Box<crate::validate::Violation>),
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum AckOutcome {
182 Accepted {
184 handle: MessageHandle,
186 latency: Duration,
188 },
189 Refused {
191 handle: MessageHandle,
193 status: ReceptionStatusValues,
195 diagnostic: Option<String>,
197 consequence: Consequence,
199 latency: Duration,
201 },
202 TimedOut(MessageHandle),
204 Unmatched {
206 subject: Id,
208 status: ReceptionStatusValues,
210 },
211}
212
213#[derive(Debug, Clone, Copy)]
215struct Outstanding {
216 handle: MessageHandle,
217 sent_at: Timestamp,
219 deadline: Timestamp,
221}
222
223#[derive(Debug, Clone, Default)]
229pub struct AckLedger {
230 pending: Vec<Outstanding>,
231 answered: VecDeque<(Id, ReceptionStatusValues)>,
234 max_answered: usize,
235}
236
237impl AckLedger {
238 #[must_use]
240 pub fn new(max_answered: usize) -> Self {
241 Self {
242 pending: Vec::new(),
243 answered: VecDeque::new(),
244 max_answered,
245 }
246 }
247
248 pub fn sent(&mut self, handle: MessageHandle, sent_at: Timestamp, deadline: Timestamp) {
250 self.pending.push(Outstanding {
251 handle,
252 sent_at,
253 deadline,
254 });
255 }
256
257 #[allow(clippy::needless_pass_by_value)]
260 pub fn received(&mut self, status: &ReceptionStatus, now: Timestamp) -> AckOutcome {
261 let Some(position) = self
262 .pending
263 .iter()
264 .position(|entry| entry.handle.id == status.subject_message_id)
265 else {
266 return AckOutcome::Unmatched {
267 subject: status.subject_message_id,
268 status: status.status,
269 };
270 };
271 let entry = self.pending.remove(position);
272 let latency = now.saturating_duration_since(entry.sent_at);
273 if status.status == ReceptionStatusValues::Ok {
274 AckOutcome::Accepted {
275 handle: entry.handle,
276 latency,
277 }
278 } else {
279 AckOutcome::Refused {
280 handle: entry.handle,
281 status: status.status,
282 diagnostic: status.diagnostic_label.clone(),
283 consequence: status.status.consequence(),
284 latency,
285 }
286 }
287 }
288
289 pub fn expire(&mut self, now: Timestamp) -> Vec<MessageHandle> {
291 let mut out = Vec::new();
292 self.pending.retain(|entry| {
293 if entry.deadline <= now {
294 out.push(entry.handle);
295 false
296 } else {
297 true
298 }
299 });
300 out
301 }
302
303 #[must_use]
305 pub fn next_deadline(&self) -> Option<Timestamp> {
306 self.pending.iter().map(|entry| entry.deadline).min()
307 }
308
309 #[must_use]
311 pub fn outstanding(&self) -> usize {
312 self.pending.len()
313 }
314
315 pub fn answered(&mut self, id: Id, status: ReceptionStatusValues) {
317 if self.answered.len() >= self.max_answered {
318 self.answered.pop_front();
319 }
320 self.answered.push_back((id, status));
321 }
322
323 #[must_use]
325 pub fn previous_answer(&self, id: Id) -> Option<ReceptionStatusValues> {
326 self.answered
327 .iter()
328 .rev()
329 .find(|(seen, _)| *seen == id)
330 .map(|(_, status)| *status)
331 }
332
333 #[must_use]
335 pub fn has_seen(&self, id: Id) -> bool {
336 self.previous_answer(id).is_some()
337 }
338
339 pub fn seen_ids(&self) -> Vec<Id> {
341 self.answered.iter().map(|(id, _)| *id).collect()
342 }
343}
344
345#[derive(Debug, Clone, Default)]
350pub struct Registry {
351 pub details: Option<ResourceManagerDetails>,
353 pub frbc: Option<frbc::SystemDescription>,
355 pub ombc: Option<ombc::SystemDescription>,
357 pub ddbc: Option<ddbc::SystemDescription>,
359 pub scheduled: Vec<(Timestamp, Message)>,
361 pub pebc_constraints: Vec<pebc::PowerConstraints>,
363 pub pebc_energy: Vec<pebc::EnergyConstraint>,
365 pub ppbc_profiles: Vec<ppbc::PowerProfileDefinition>,
367 pub instructions: Vec<Id>,
369 pub instruction_statuses: Vec<(Id, InstructionStatus)>,
371 pub published: Vec<(RevokableObjects, Id)>,
373 pub active_modes: Vec<(Id, Id)>,
375 pub timers: Vec<TimerState>,
378 pub fill_level: Option<f64>,
380}
381
382impl Registry {
383 pub const MAX_TRACKED: usize = 4096;
385
386 pub const MAX_SCHEDULED: usize = 16;
392
393 fn bound<T>(v: &mut Vec<T>) {
394 if v.len() > Self::MAX_TRACKED {
395 v.remove(0);
396 }
397 }
398
399 fn upsert<T, K: PartialEq>(v: &mut Vec<T>, key: &K, value: T, key_of: impl Fn(&T) -> K) {
400 if let Some(slot) = v.iter_mut().find(|existing| key_of(existing) == *key) {
401 *slot = value;
402 } else {
403 v.push(value);
404 Self::bound(v);
405 }
406 }
407
408 #[allow(clippy::needless_pass_by_value)]
414 pub fn record(&mut self, message: &Message, now: Option<Timestamp>) {
415 if let Some((object_type, id)) = message.revokable_id() {
416 Self::upsert(
417 &mut self.published,
418 &(object_type, id),
419 (object_type, id),
420 |(t, i)| (*t, *i),
421 );
422 }
423 if let Some(id) = message.instruction_id()
424 && !self.instructions.contains(&id)
425 {
426 self.instructions.push(id);
427 Self::bound(&mut self.instructions);
428 }
429
430 let scheduled_for = match message {
431 Message::FrbcSystemDescription(d) => Some(d.valid_from),
432 Message::OmbcSystemDescription(d) => Some(d.valid_from),
433 Message::DdbcSystemDescription(d) => Some(d.valid_from),
434 _ => None,
435 };
436 if let (Some(valid_from), Some(now)) = (scheduled_for, now)
437 && valid_from > now
438 {
439 self.schedule(valid_from, message);
440 return;
441 }
442
443 self.apply(message);
444 }
445
446 fn schedule(&mut self, valid_from: Timestamp, message: &Message) {
448 let identity = message.revokable_id();
451 if let Some(slot) = self
452 .scheduled
453 .iter_mut()
454 .find(|(_, queued)| queued.revokable_id() == identity)
455 {
456 *slot = (valid_from, message.clone());
457 return;
458 }
459 self.scheduled.push((valid_from, message.clone()));
460 while self.scheduled.len() > Self::MAX_SCHEDULED {
461 if let Some(furthest) = self
463 .scheduled
464 .iter()
465 .enumerate()
466 .max_by_key(|(_, (at, _))| *at)
467 .map(|(i, _)| i)
468 {
469 self.scheduled.remove(furthest);
470 } else {
471 break;
472 }
473 }
474 }
475
476 fn apply(&mut self, message: &Message) {
478 match message {
479 Message::ResourceManagerDetails(d) => self.details = Some((**d).clone()),
480 Message::FrbcSystemDescription(d) => {
487 self.frbc = Some((**d).clone());
488 self.forget_actuator_state();
489 }
490 Message::OmbcSystemDescription(d) => {
491 self.ombc = Some((**d).clone());
492 self.forget_actuator_state();
493 }
494 Message::DdbcSystemDescription(d) => {
495 self.ddbc = Some((**d).clone());
496 self.forget_actuator_state();
497 }
498 Message::PebcPowerConstraints(c) => Self::upsert(
499 &mut self.pebc_constraints,
500 &c.id,
501 (**c).clone(),
502 |existing| existing.id,
503 ),
504 Message::PebcEnergyConstraint(c) => {
505 Self::upsert(&mut self.pebc_energy, &c.id, (**c).clone(), |e| e.id);
506 }
507 Message::PpbcPowerProfileDefinition(p) => {
508 Self::upsert(&mut self.ppbc_profiles, &p.id, (**p).clone(), |e| e.id);
509 }
510 Message::FrbcStorageStatus(s) => self.fill_level = Some(s.present_fill_level),
511 Message::FrbcActuatorStatus(s) => {
512 Self::upsert(
513 &mut self.active_modes,
514 &s.actuator_id,
515 (s.actuator_id, s.active_operation_mode_id),
516 |(a, _)| *a,
517 );
518 }
519 Message::DdbcActuatorStatus(s) => {
520 Self::upsert(
521 &mut self.active_modes,
522 &s.actuator_id,
523 (s.actuator_id, s.active_operation_mode_id),
524 |(a, _)| *a,
525 );
526 }
527 Message::OmbcStatus(s) => {
528 Self::upsert(
529 &mut self.active_modes,
530 &Id::NIL,
531 (Id::NIL, s.active_operation_mode_id),
532 |(a, _)| *a,
533 );
534 }
535 Message::FrbcTimerStatus(s) => {
536 let actuator = s.actuator_id;
537 Self::upsert(
538 &mut self.timers,
539 &(actuator, s.timer_id),
540 TimerState {
541 actuator,
542 timer: s.timer_id,
543 finished_at: s.finished_at,
544 },
545 |t| (t.actuator, t.timer),
546 );
547 }
548 Message::DdbcTimerStatus(s) => {
549 let actuator = s.actuator_id;
550 Self::upsert(
551 &mut self.timers,
552 &(actuator, s.timer_id),
553 TimerState {
554 actuator,
555 timer: s.timer_id,
556 finished_at: s.finished_at,
557 },
558 |t| (t.actuator, t.timer),
559 );
560 }
561 Message::OmbcTimerStatus(s) => {
562 let actuator = Id::NIL;
563 Self::upsert(
564 &mut self.timers,
565 &(actuator, s.timer_id),
566 TimerState {
567 actuator,
568 timer: s.timer_id,
569 finished_at: s.finished_at,
570 },
571 |t| (t.actuator, t.timer),
572 );
573 }
574 Message::InstructionStatusUpdate(u) => Self::upsert(
575 &mut self.instruction_statuses,
576 &u.instruction_id,
577 (u.instruction_id, u.status_type),
578 |(i, _)| *i,
579 ),
580 Message::RevokeObject(r) => self.revoke(r.object_type, r.object_id),
581 _ => {}
582 }
583 }
584
585 fn forget_actuator_state(&mut self) {
588 self.active_modes.clear();
589 self.timers.clear();
590 }
591
592 pub fn activate_due(&mut self, now: Timestamp) -> Vec<Message> {
594 let mut due = Vec::new();
595 self.scheduled.retain(|(at, message)| {
596 if *at <= now {
597 due.push(message.clone());
598 false
599 } else {
600 true
601 }
602 });
603 for message in &due {
604 self.apply(message);
605 }
606 due
607 }
608
609 #[must_use]
611 pub fn next_activation(&self) -> Option<Timestamp> {
612 self.scheduled.iter().map(|(at, _)| *at).min()
613 }
614
615 pub fn revoke(&mut self, object_type: RevokableObjects, object_id: Id) {
623 self.published
624 .retain(|(t, i)| !(*t == object_type && *i == object_id));
625 self.scheduled
628 .retain(|(_, message)| message.revokable_id() != Some((object_type, object_id)));
629 match object_type {
630 RevokableObjects::PebcPowerConstraints => {
631 self.pebc_constraints.retain(|c| c.id != object_id);
632 }
633 RevokableObjects::PebcEnergyConstraint => {
634 self.pebc_energy.retain(|c| c.id != object_id);
635 }
636 RevokableObjects::PpbcPowerProfileDefinition => {
637 self.ppbc_profiles.retain(|p| p.id != object_id);
638 }
639 RevokableObjects::FrbcSystemDescription => {
640 if self
641 .frbc
642 .as_ref()
643 .is_some_and(|d| d.message_id == object_id)
644 {
645 self.frbc = None;
646 self.forget_actuator_state();
647 }
648 }
649 RevokableObjects::OmbcSystemDescription => {
650 if self
651 .ombc
652 .as_ref()
653 .is_some_and(|d| d.message_id == object_id)
654 {
655 self.ombc = None;
656 self.forget_actuator_state();
657 }
658 }
659 RevokableObjects::DdbcSystemDescription => {
660 if self
661 .ddbc
662 .as_ref()
663 .is_some_and(|d| d.message_id == object_id)
664 {
665 self.ddbc = None;
666 self.forget_actuator_state();
667 }
668 }
669 _ => {
670 Self::upsert(
673 &mut self.instruction_statuses,
674 &object_id,
675 (object_id, InstructionStatus::Revoked),
676 |(i, _)| *i,
677 );
678 }
679 }
680 }
681
682 #[allow(clippy::too_many_arguments)]
687 pub fn context<'a>(
688 &'a self,
689 profile: WireProfile,
690 sender: EnergyManagementRole,
691 active: Option<ControlType>,
692 s2_connect: bool,
693 now: Timestamp,
694 seen: &'a [Id],
695 skew_tolerance: Duration,
696 ) -> Context<'a> {
697 Context {
698 profile,
699 sender: Some(sender),
700 active_control_type: active,
701 s2_connect,
702 details: self.details.as_ref(),
703 frbc: self.frbc.as_ref(),
704 ombc: self.ombc.as_ref(),
705 ddbc: self.ddbc.as_ref(),
706 pebc_constraints: &self.pebc_constraints,
707 ppbc_profiles: &self.ppbc_profiles,
708 instructions: &self.instructions,
709 instruction_statuses: &self.instruction_statuses,
710 seen_message_ids: seen,
711 published: &self.published,
712 active_modes: &self.active_modes,
713 timers: &self.timers,
714 fill_level: self.fill_level,
715 now: Some(now),
716 skew_tolerance,
717 }
718 }
719}
720
721#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
730#[non_exhaustive]
731pub struct Stats {
732 pub sent: u64,
734 pub received: u64,
736 pub undecodable: u64,
738 pub refused: u64,
740 pub accepted_with_warnings: u64,
743 pub duplicates: u64,
745 pub acked: u64,
747 pub nacked: u64,
749 pub ack_timeouts: u64,
751 pub unmatched_acks: u64,
753 pub ack_latency_total_ms: u64,
758 pub ack_latency_max_ms: u64,
760}
761
762impl Stats {
763 #[must_use]
765 pub const fn answered(&self) -> u64 {
766 self.acked + self.nacked
767 }
768
769 #[must_use]
771 pub const fn mean_ack_latency_ms(&self) -> Option<u64> {
772 match self.answered() {
773 0 => None,
774 n => Some(self.ack_latency_total_ms / n),
775 }
776 }
777
778 pub(crate) fn record_latency(&mut self, latency: Duration) {
779 let ms = latency.as_millis();
780 self.ack_latency_total_ms = self.ack_latency_total_ms.saturating_add(ms);
781 self.ack_latency_max_ms = self.ack_latency_max_ms.max(ms);
782 }
783}
784
785#[derive(Debug, Clone)]
787pub struct SessionCore {
788 pub state: SessionState,
790 pub negotiation: Negotiation,
792 pub profile: WireProfile,
794 pub s2_connect: bool,
796 pub outbox: VecDeque<Outgoing>,
798 pub acks: AckLedger,
800 pub registry: Registry,
802 pub ack_timeout: Duration,
804 pub out_of_order: OutOfOrderPolicy,
806 pub skew_tolerance: Duration,
808 pub max_message_bytes: usize,
810 pub strictness: codec::Strictness,
812 pub reconnect_attempt: u32,
814 pub stats: Stats,
816 #[cfg_attr(feature = "uuid", allow(dead_code))]
821 role: EnergyManagementRole,
822 minted: u64,
824}
825
826pub(crate) struct CoreConfig {
833 pub role: EnergyManagementRole,
834 pub negotiation: Negotiation,
835 pub ack_timeout: Duration,
836 pub out_of_order: OutOfOrderPolicy,
837 pub skew_tolerance: Duration,
838 pub max_message_bytes: usize,
839 pub strictness: codec::Strictness,
840 pub s2_connect: bool,
841}
842
843impl SessionCore {
844 pub(crate) fn new(cfg: CoreConfig) -> Self {
845 let CoreConfig {
846 role,
847 negotiation,
848 ack_timeout,
849 out_of_order,
850 skew_tolerance,
851 max_message_bytes,
852 strictness,
853 s2_connect,
854 } = cfg;
855 let profile = match &negotiation {
856 Negotiation::PreNegotiated(p) => *p,
857 Negotiation::Handshake => WireProfile::V1_0_0,
858 };
859 Self {
860 state: SessionState::Idle,
861 negotiation,
862 profile,
863 s2_connect,
864 outbox: VecDeque::new(),
865 acks: AckLedger::new(256),
866 registry: Registry::default(),
867 ack_timeout,
868 out_of_order,
869 skew_tolerance,
870 max_message_bytes,
871 strictness,
872 reconnect_attempt: 0,
873 stats: Stats::default(),
874 role,
875 minted: 0,
876 }
877 }
878
879 pub(crate) fn next_message_id(&mut self) -> Id {
886 self.minted = self.minted.wrapping_add(1);
887 #[cfg(feature = "uuid")]
888 {
889 Id::generate()
890 }
891 #[cfg(not(feature = "uuid"))]
892 {
893 use core::fmt::Write as _;
894 let mut buffer = alloc::string::String::new();
895 let prefix = match self.role {
896 EnergyManagementRole::Rm => "rm",
897 EnergyManagementRole::Cem => "cem",
898 };
899 let _ = write!(buffer, "{prefix}-{}", self.minted);
901 Id::parse(&buffer).unwrap_or(Id::NIL)
902 }
903 }
904
905 pub(crate) fn decode_options(&self) -> DecodeOptions {
906 DecodeOptions {
907 strictness: self.strictness,
908 profile: self.profile,
909 max_bytes: self.max_message_bytes,
910 }
911 }
912
913 #[allow(clippy::needless_pass_by_value)]
917 pub(crate) fn transmit(&mut self, message: Message, now: Timestamp) -> Option<MessageHandle> {
918 let kind = message.kind();
919 let id = message.id();
920 self.registry.record(&message, Some(now));
921 self.outbox.push_back(Outgoing {
922 text: codec::encode(&message),
923 kind,
924 message_id: id,
925 });
926 self.stats.sent = self.stats.sent.saturating_add(1);
927 let handle = id.map(|id| MessageHandle { id, kind })?;
932 let deadline = now
933 .checked_add(self.ack_timeout)
934 .unwrap_or(Timestamp::UNIX_EPOCH);
935 self.acks.sent(handle, now, deadline);
936 Some(handle)
937 }
938
939 #[allow(clippy::needless_pass_by_value)]
942 pub(crate) fn acknowledge(
943 &mut self,
944 subject: Id,
945 status: ReceptionStatusValues,
946 diagnostic: Option<String>,
947 now: Timestamp,
948 ) {
949 let _ = now;
950 self.acks.answered(subject, status);
951 if status != ReceptionStatusValues::Ok {
952 self.stats.refused = self.stats.refused.saturating_add(1);
953 }
954 let message = Message::from(ReceptionStatus {
955 subject_message_id: subject,
956 status,
957 diagnostic_label: diagnostic,
958 });
959 self.outbox.push_back(Outgoing {
960 text: codec::encode(&message),
961 kind: MessageKind::ReceptionStatus,
962 message_id: None,
963 });
964 self.stats.sent = self.stats.sent.saturating_add(1);
965 }
966
967 #[must_use]
975 pub fn poll_timeout(&self) -> Option<Timestamp> {
976 if self.state.is_closed() {
977 return None;
978 }
979 match (self.acks.next_deadline(), self.registry.next_activation()) {
980 (Some(a), Some(b)) => Some(a.min(b)),
981 (a, b) => a.or(b),
982 }
983 }
984
985 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
987 self.outbox.pop_front()
988 }
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
999pub struct Backoff {
1000 pub base: Duration,
1002 pub max: Duration,
1004}
1005
1006impl Default for Backoff {
1007 fn default() -> Self {
1008 Self {
1009 base: Duration::from_secs(2),
1010 max: Duration::from_secs(600),
1011 }
1012 }
1013}
1014
1015impl Backoff {
1016 #[must_use]
1018 pub fn ceiling(self, attempt: u32) -> Duration {
1019 let scaled = self
1020 .base
1021 .as_millis()
1022 .saturating_mul(1u64 << attempt.min(40));
1023 Duration::from_millis(scaled.min(self.max.as_millis()))
1024 }
1025
1026 #[must_use]
1028 pub fn delay(self, attempt: u32, random: f64) -> Duration {
1029 let ceiling = self.ceiling(attempt).as_millis();
1030 #[allow(
1031 clippy::cast_precision_loss,
1032 clippy::cast_sign_loss,
1033 clippy::cast_possible_truncation
1034 )]
1035 Duration::from_millis((ceiling as f64 * random.clamp(0.0, 1.0)) as u64)
1036 }
1037
1038 #[cfg(feature = "std")]
1040 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1041 #[must_use]
1042 pub fn delay_with(self, attempt: u32) -> Duration {
1043 use rand::RngExt as _;
1044 let mut rng = rand::rng();
1045 self.delay(attempt, rng.random_range(0.0..1.0))
1046 }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052 use crate::types::common::{NumberRange, SessionRequestType};
1053 use alloc::vec;
1054
1055 fn at(s: &str) -> Timestamp {
1056 s.parse().unwrap()
1057 }
1058
1059 fn core_config(role: EnergyManagementRole) -> CoreConfig {
1060 CoreConfig {
1061 role,
1062 negotiation: Negotiation::Handshake,
1063 ack_timeout: Duration::from_secs(5),
1064 out_of_order: OutOfOrderPolicy::Report,
1065 skew_tolerance: Duration::from_secs(30),
1066 max_message_bytes: 1024,
1067 strictness: codec::Strictness::Strict,
1068 s2_connect: false,
1069 }
1070 }
1071
1072 #[test]
1073 fn every_identifier_the_engine_mints_is_different() {
1074 let mut core = SessionCore::new(core_config(EnergyManagementRole::Rm));
1077 let minted: Vec<Id> = (0..64).map(|_| core.next_message_id()).collect();
1078 let mut unique = minted.clone();
1079 unique.sort_unstable();
1080 unique.dedup();
1081 assert_eq!(unique.len(), minted.len(), "identifiers must not repeat");
1082 assert!(
1083 !minted.contains(&Id::NIL),
1084 "the nil identifier means `no message to name`, not `this message`"
1085 );
1086
1087 let mut cem = SessionCore::new(core_config(EnergyManagementRole::Cem));
1090 let theirs = cem.next_message_id();
1091 assert_ne!(theirs, minted[0]);
1092 #[cfg(not(feature = "uuid"))]
1093 {
1094 assert!(minted[0].as_str().starts_with("rm-"));
1095 assert!(theirs.as_str().starts_with("cem-"));
1096 }
1097 }
1098
1099 #[test]
1100 fn the_ledger_matches_answers_to_what_they_answer() {
1101 let mut ledger = AckLedger::new(8);
1102 let handle = MessageHandle {
1103 id: Id::new_const("m1"),
1104 kind: MessageKind::FrbcStorageStatus,
1105 };
1106 ledger.sent(
1107 handle,
1108 at("2024-01-01T12:00:00Z"),
1109 at("2024-01-01T12:00:05Z"),
1110 );
1111 assert_eq!(ledger.outstanding(), 1);
1112
1113 let outcome = ledger.received(
1114 &ReceptionStatus::ok(Id::new_const("m1")),
1115 at("2024-01-01T12:00:00.250Z"),
1116 );
1117 assert_eq!(
1120 outcome,
1121 AckOutcome::Accepted {
1122 handle,
1123 latency: Duration::from_millis(250)
1124 }
1125 );
1126 assert_eq!(ledger.outstanding(), 0);
1127
1128 let outcome = ledger.received(
1130 &ReceptionStatus::ok(Id::new_const("m1")),
1131 at("2024-01-01T12:00:01Z"),
1132 );
1133 assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1134 }
1135
1136 #[test]
1137 fn an_unanswered_message_times_out_rather_than_blocking() {
1138 let mut ledger = AckLedger::new(8);
1139 let handle = MessageHandle {
1140 id: Id::new_const("m1"),
1141 kind: MessageKind::FrbcStorageStatus,
1142 };
1143 ledger.sent(
1144 handle,
1145 at("2024-01-01T12:00:00Z"),
1146 at("2024-01-01T12:00:05Z"),
1147 );
1148 assert_eq!(ledger.next_deadline(), Some(at("2024-01-01T12:00:05Z")));
1149 assert!(ledger.expire(at("2024-01-01T12:00:04Z")).is_empty());
1150 assert_eq!(ledger.expire(at("2024-01-01T12:00:05Z")), vec![handle]);
1151 assert_eq!(ledger.next_deadline(), None);
1152
1153 let outcome = ledger.received(
1155 &ReceptionStatus::ok(Id::new_const("m1")),
1156 at("2024-01-01T12:00:01Z"),
1157 );
1158 assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1159 }
1160
1161 #[test]
1162 fn a_refusal_carries_the_standards_own_consequence() {
1163 let mut ledger = AckLedger::new(8);
1164 let handle = MessageHandle {
1165 id: Id::new_const("m1"),
1166 kind: MessageKind::FrbcInstruction,
1167 };
1168 ledger.sent(
1169 handle,
1170 at("2024-01-01T12:00:00Z"),
1171 at("2024-01-01T12:00:05Z"),
1172 );
1173 let outcome = ledger.received(
1174 &ReceptionStatus::error(
1175 Id::new_const("m1"),
1176 ReceptionStatusValues::TemporaryError,
1177 "busy",
1178 ),
1179 at("2024-01-01T12:00:01Z"),
1180 );
1181 match outcome {
1182 AckOutcome::Refused { consequence, .. } => {
1183 assert_eq!(consequence, Consequence::Retry);
1184 }
1185 other => panic!("{other:?}"),
1186 }
1187 }
1188
1189 #[test]
1190 fn the_answered_ring_is_bounded_and_remembers_the_answer() {
1191 let mut ledger = AckLedger::new(2);
1192 ledger.answered(Id::new_const("m1"), ReceptionStatusValues::Ok);
1193 ledger.answered(Id::new_const("m2"), ReceptionStatusValues::InvalidContent);
1194 assert_eq!(
1195 ledger.previous_answer(Id::new_const("m2")),
1196 Some(ReceptionStatusValues::InvalidContent)
1197 );
1198 ledger.answered(Id::new_const("m3"), ReceptionStatusValues::Ok);
1199 assert_eq!(ledger.previous_answer(Id::new_const("m1")), None);
1201 assert!(ledger.has_seen(Id::new_const("m3")));
1202 }
1203
1204 #[test]
1205 fn a_description_valid_in_the_future_waits_its_turn() {
1206 let mut registry = Registry::default();
1207 let later = at("2024-01-01T13:00:00Z");
1208 let now = at("2024-01-01T12:00:00Z");
1209 let description = Message::from(frbc::SystemDescription {
1210 message_id: Id::new_const("m1"),
1211 valid_from: later,
1212 actuators: vec![],
1213 storage: frbc::StorageDescription {
1214 diagnostic_label: None,
1215 fill_level_label: None,
1216 provides_leakage_behaviour: false,
1217 provides_fill_level_target_profile: false,
1218 provides_usage_forecast: false,
1219 fill_level_range: NumberRange::new(0.0, 100.0),
1220 },
1221 });
1222
1223 registry.record(&description, Some(now));
1224 assert!(registry.frbc.is_none(), "not effective yet");
1225 assert_eq!(registry.next_activation(), Some(later));
1226 assert!(registry.activate_due(at("2024-01-01T12:59:59Z")).is_empty());
1227
1228 let due = registry.activate_due(later);
1229 assert_eq!(due.len(), 1);
1230 assert!(registry.frbc.is_some());
1231 assert_eq!(registry.next_activation(), None);
1232 }
1233
1234 #[test]
1235 fn revoking_removes_the_object_and_marks_an_instruction_revoked() {
1236 let mut registry = Registry::default();
1237 let constraints = pebc::PowerConstraints {
1238 message_id: Id::new_const("m1"),
1239 id: Id::new_const("pc1"),
1240 valid_from: at("2024-01-01T12:00:00Z"),
1241 valid_until: None,
1242 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1243 allowed_limit_ranges: vec![],
1244 };
1245 registry.record(&Message::from(constraints), None);
1246 assert_eq!(registry.pebc_constraints.len(), 1);
1247 assert_eq!(registry.published.len(), 1);
1248
1249 registry.revoke(RevokableObjects::PebcPowerConstraints, Id::new_const("pc1"));
1250 assert!(registry.pebc_constraints.is_empty());
1251 assert!(registry.published.is_empty());
1252
1253 registry.revoke(RevokableObjects::FrbcInstruction, Id::new_const("i1"));
1254 assert_eq!(
1255 registry.instruction_statuses,
1256 vec![(Id::new_const("i1"), InstructionStatus::Revoked)]
1257 );
1258 }
1259
1260 fn frbc_description(message_id: Id, valid_from: Timestamp) -> Message {
1261 Message::from(frbc::SystemDescription {
1262 message_id,
1263 valid_from,
1264 actuators: vec![],
1265 storage: frbc::StorageDescription {
1266 diagnostic_label: None,
1267 fill_level_label: None,
1268 provides_leakage_behaviour: false,
1269 provides_fill_level_target_profile: false,
1270 provides_usage_forecast: false,
1271 fill_level_range: NumberRange::new(0.0, 100.0),
1272 },
1273 })
1274 }
1275
1276 #[test]
1277 fn revoking_a_superseded_description_leaves_the_live_one_alone() {
1278 let mut registry = Registry::default();
1283 let now = at("2024-01-01T12:00:00Z");
1284 registry.record(&frbc_description(Id::new_const("sd-a"), now), Some(now));
1285 registry.record(&frbc_description(Id::new_const("sd-b"), now), Some(now));
1286 assert_eq!(
1287 registry.frbc.as_ref().map(|d| d.message_id),
1288 Some(Id::new_const("sd-b"))
1289 );
1290
1291 registry.revoke(
1292 RevokableObjects::FrbcSystemDescription,
1293 Id::new_const("sd-a"),
1294 );
1295 assert_eq!(
1296 registry.frbc.as_ref().map(|d| d.message_id),
1297 Some(Id::new_const("sd-b")),
1298 "revoking the superseded description must not clear the live one"
1299 );
1300
1301 registry.revoke(
1303 RevokableObjects::FrbcSystemDescription,
1304 Id::new_const("sd-b"),
1305 );
1306 assert!(registry.frbc.is_none());
1307 }
1308
1309 #[test]
1310 fn revoking_a_description_that_has_not_taken_effect_yet_cancels_it() {
1311 let mut registry = Registry::default();
1312 let now = at("2024-01-01T12:00:00Z");
1313 let later = at("2024-01-01T13:00:00Z");
1314 registry.record(&frbc_description(Id::new_const("sd-a"), later), Some(now));
1315 assert_eq!(registry.next_activation(), Some(later));
1316
1317 registry.revoke(
1318 RevokableObjects::FrbcSystemDescription,
1319 Id::new_const("sd-a"),
1320 );
1321 assert_eq!(registry.next_activation(), None);
1322 assert!(registry.activate_due(later).is_empty());
1323 assert!(registry.frbc.is_none(), "a revoked description never runs");
1324 }
1325
1326 #[test]
1327 fn the_queue_of_future_descriptions_is_bounded_by_message_count_not_identifier_count() {
1328 let mut registry = Registry::default();
1332 let now = at("2024-01-01T12:00:00Z");
1333 for minute in 0..100u32 {
1334 let at_time = now
1335 .checked_add(Duration::from_secs(u64::from(minute) * 60 + 60))
1336 .unwrap();
1337 let id_str = alloc::format!("sd-{minute:04}");
1338 registry.record(
1339 &frbc_description(Id::parse(&id_str).unwrap(), at_time),
1340 Some(now),
1341 );
1342 }
1343 assert_eq!(registry.scheduled.len(), Registry::MAX_SCHEDULED);
1344 let furthest = registry.scheduled.iter().map(|(at, _)| *at).max().unwrap();
1347 assert_eq!(
1348 furthest,
1349 now.checked_add(Duration::from_secs(Registry::MAX_SCHEDULED as u64 * 60))
1350 .unwrap()
1351 );
1352 }
1353
1354 #[test]
1355 fn re_announcing_a_future_description_corrects_it_rather_than_queueing_twice() {
1356 let mut registry = Registry::default();
1357 let now = at("2024-01-01T12:00:00Z");
1358 let first = at("2024-01-01T13:00:00Z");
1359 let corrected = at("2024-01-01T14:00:00Z");
1360 registry.record(&frbc_description(Id::new_const("sd-a"), first), Some(now));
1361 registry.record(
1362 &frbc_description(Id::new_const("sd-a"), corrected),
1363 Some(now),
1364 );
1365 assert_eq!(registry.scheduled.len(), 1);
1366 assert_eq!(registry.next_activation(), Some(corrected));
1367 }
1368
1369 #[test]
1370 fn two_actuators_may_share_a_timer_identifier() {
1371 let mut registry = Registry::default();
1375 let mut status = |actuator: &'static str, finished_at: &str| {
1376 registry.record(
1377 &Message::from(frbc::TimerStatus {
1378 message_id: Id::new_const("m1"),
1379 timer_id: Id::new_const("timer1"),
1380 actuator_id: Id::new_const(actuator),
1381 finished_at: at(finished_at),
1382 }),
1383 None,
1384 );
1385 };
1386 status("actuator1", "2024-01-01T13:00:00Z");
1387 status("actuator2", "2024-01-01T11:00:00Z");
1388
1389 assert_eq!(registry.timers.len(), 2, "one entry per actuator");
1390 let finished_at = |actuator: &'static str| {
1391 registry
1392 .timers
1393 .iter()
1394 .find(|t| t.actuator == Id::new_const(actuator) && t.timer == "timer1")
1395 .map(|t| t.finished_at)
1396 };
1397 assert_eq!(finished_at("actuator1"), Some(at("2024-01-01T13:00:00Z")));
1398 assert_eq!(finished_at("actuator2"), Some(at("2024-01-01T11:00:00Z")));
1399 }
1400
1401 #[test]
1402 fn resending_a_description_replaces_rather_than_accumulates() {
1403 let mut registry = Registry::default();
1404 for level in [10.0, 20.0] {
1405 registry.record(
1406 &Message::from(frbc::StorageStatus {
1407 message_id: Id::new_const("m1"),
1408 present_fill_level: level,
1409 }),
1410 None,
1411 );
1412 }
1413 assert_eq!(registry.fill_level, Some(20.0));
1414
1415 let make = |id: &'static str, until: &str| pebc::PowerConstraints {
1416 message_id: Id::new_const("mm"),
1417 id: Id::new_const(id),
1418 valid_from: at("2024-01-01T12:00:00Z"),
1419 valid_until: Some(at(until)),
1420 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1421 allowed_limit_ranges: vec![],
1422 };
1423 registry.record(&Message::from(make("pc1", "2024-01-01T13:00:00Z")), None);
1424 registry.record(&Message::from(make("pc1", "2024-01-01T14:00:00Z")), None);
1425 assert_eq!(registry.pebc_constraints.len(), 1);
1426 assert_eq!(
1427 registry.pebc_constraints[0].valid_until,
1428 Some(at("2024-01-01T14:00:00Z"))
1429 );
1430 }
1431
1432 #[test]
1433 fn the_backoff_is_the_one_s2_connect_prescribes() {
1434 let b = Backoff::default();
1435 assert_eq!(b.ceiling(0), Duration::from_secs(2));
1437 assert_eq!(b.ceiling(1), Duration::from_secs(4));
1438 assert_eq!(b.ceiling(2), Duration::from_secs(8));
1439 assert_eq!(b.ceiling(20), Duration::from_secs(600));
1440 assert_eq!(b.ceiling(100), Duration::from_secs(600));
1441 assert_eq!(b.delay(3, 0.0), Duration::ZERO);
1443 assert_eq!(b.delay(3, 1.0), Duration::from_secs(16));
1444 assert_eq!(b.delay(3, 0.5), Duration::from_secs(8));
1445 }
1446
1447 #[test]
1448 fn session_state_reports_what_may_flow() {
1449 assert!(!SessionState::Connected.is_active());
1450 assert_eq!(SessionState::Connected.active_control_type(), None);
1451 let active = SessionState::ControlTypeSelected(ControlType::FillRateBasedControl);
1452 assert!(active.is_active());
1453 let inert = SessionState::ControlTypeSelected(ControlType::NotControllable);
1455 assert!(!inert.is_active());
1456 assert!(SessionState::Closed(CloseReason::Local).is_closed());
1457 let _ = SessionRequestType::Terminate;
1458 }
1459}