1use alloc::boxed::Box;
4use alloc::collections::VecDeque;
5use alloc::string::{String, ToString};
6use alloc::vec::Vec;
7
8use super::core::{
9 AckOutcome, Backoff, CloseReason, CoreConfig, MessageHandle, Negotiation, OutOfOrderPolicy,
10 Outgoing, SendError, SessionCore, SessionState,
11};
12use super::rm::state_name;
13use super::{Inbound, InboundPolicy};
14use crate::codec::{self, Strictness};
15use crate::message::{Message, MessageKind};
16use crate::types::common::{
17 Consequence, ControlType, EnergyManagementRole, Handshake, HandshakeResponse,
18 InstructionStatus, PowerForecast, PowerMeasurement, ReceptionStatusValues,
19 ResourceManagerDetails, RevokableObjects, RevokeObject, SelectControlType, SessionRequest,
20 SessionRequestType,
21};
22use crate::types::{Duration, Id, ProtocolVersion, Timestamp, WireProfile};
23use crate::validate::{Report, Validate, rules};
24
25#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct CemConfig {
29 pub negotiation: Negotiation,
31 pub supported_versions: Vec<ProtocolVersion>,
33 pub ack_timeout: Duration,
35 pub out_of_order: OutOfOrderPolicy,
37 pub skew_tolerance: Duration,
39 pub max_message_bytes: usize,
41 pub strictness: Strictness,
43 pub s2_connect: bool,
45 pub validate_outbound: bool,
47 pub enforce_transitions: bool,
54}
55
56impl Default for CemConfig {
57 fn default() -> Self {
58 Self {
59 negotiation: Negotiation::Handshake,
60 supported_versions: alloc::vec![
61 ProtocolVersion::new(ProtocolVersion::V1_0_0),
62 ProtocolVersion::new(ProtocolVersion::V0_0_2_BETA),
63 ],
64 ack_timeout: Duration::from_secs(5),
65 out_of_order: OutOfOrderPolicy::Report,
66 skew_tolerance: Duration::from_secs(30),
67 max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
68 strictness: Strictness::Strict,
69 s2_connect: false,
70 validate_outbound: true,
71 enforce_transitions: false,
72 }
73 }
74}
75
76impl CemConfig {
77 #[must_use]
83 pub fn without_outbound_validation(mut self) -> Self {
84 self.validate_outbound = false;
85 self
86 }
87
88 #[must_use]
90 pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
91 self.negotiation = Negotiation::PreNegotiated(profile);
92 self.s2_connect = true;
93 self
94 }
95
96 #[must_use]
98 pub fn supporting(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
99 self.supported_versions = versions.into_iter().collect();
100 self
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
106#[non_exhaustive]
107pub enum CemEvent {
108 Negotiated {
110 version: ProtocolVersion,
112 profile: WireProfile,
114 },
115 ResourceDescribed(Box<ResourceManagerDetails>),
117 Ready {
119 control_type: ControlType,
121 },
122 Deselected,
124 Description {
126 kind: MessageKind,
128 message: Message,
130 },
131 Status {
133 kind: MessageKind,
135 message: Message,
137 },
138 Measurement(Box<PowerMeasurement>),
140 Forecast(Box<PowerForecast>),
142 InstructionStatus {
144 instruction_id: Id,
146 status: InstructionStatus,
148 },
149 TimerFinished {
151 actuator: Option<Id>,
153 timer: Id,
155 finished_at: Timestamp,
157 },
158 DescriptionActivated {
160 kind: MessageKind,
162 },
163 Revoked {
165 object_type: RevokableObjects,
167 object_id: Id,
169 },
170 Acked(MessageHandle),
172 Nacked {
174 handle: MessageHandle,
176 status: ReceptionStatusValues,
178 diagnostic: Option<String>,
180 consequence: Consequence,
182 },
183 AckTimedOut(MessageHandle),
185 UnmatchedAck {
187 subject: Id,
189 status: ReceptionStatusValues,
191 },
192 SessionRequested {
194 request: SessionRequestType,
196 diagnostic: Option<String>,
198 },
199 Refused {
201 kind: Option<MessageKind>,
203 status: ReceptionStatusValues,
205 report: Report,
207 },
208 Warnings {
210 kind: MessageKind,
212 report: Report,
214 },
215 Closed {
217 reason: CloseReason,
219 reconnect_after: Option<Duration>,
221 },
222}
223
224pub struct CemSession {
231 core: SessionCore,
232 config: CemConfig,
233 events: VecDeque<CemEvent>,
234 peer_versions: Vec<ProtocolVersion>,
235 negotiated: Option<ProtocolVersion>,
236 handshake_sent: bool,
237 pending_control_type: Option<(Id, ControlType)>,
238 policy: Option<Box<dyn InboundPolicy + Send>>,
239 backoff: Backoff,
240}
241
242impl core::fmt::Debug for CemSession {
243 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
244 f.debug_struct("CemSession")
245 .field("state", &self.core.state)
246 .field("profile", &self.core.profile)
247 .field("outstanding_acks", &self.core.acks.outstanding())
248 .field("queued", &self.core.outbox.len())
249 .finish_non_exhaustive()
250 }
251}
252
253impl CemSession {
254 #[must_use]
256 pub fn new(config: CemConfig) -> Self {
257 let core = SessionCore::new(CoreConfig {
258 role: EnergyManagementRole::Cem,
259 negotiation: config.negotiation.clone(),
260 ack_timeout: config.ack_timeout,
261 out_of_order: config.out_of_order,
262 skew_tolerance: config.skew_tolerance,
263 max_message_bytes: config.max_message_bytes,
264 strictness: config.strictness,
265 s2_connect: config.s2_connect,
266 });
267 Self {
268 core,
269 config,
270 events: VecDeque::new(),
271 peer_versions: Vec::new(),
272 negotiated: None,
273 handshake_sent: false,
274 pending_control_type: None,
275 policy: None,
276 backoff: Backoff::default(),
277 }
278 }
279
280 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
282 self.policy = Some(policy);
283 }
284
285 #[must_use]
287 pub fn state(&self) -> &SessionState {
288 &self.core.state
289 }
290
291 #[must_use]
293 pub fn profile(&self) -> WireProfile {
294 self.core.profile
295 }
296
297 #[must_use]
301 pub fn stats(&self) -> super::core::Stats {
302 self.core.stats
303 }
304
305 #[must_use]
307 pub fn registry(&self) -> &super::core::Registry {
308 &self.core.registry
309 }
310
311 #[must_use]
313 pub fn details(&self) -> Option<&ResourceManagerDetails> {
314 self.core.registry.details.as_ref()
315 }
316
317 pub fn open(&mut self, now: Timestamp) {
323 if !matches!(self.core.state, SessionState::Idle) {
324 return;
325 }
326 match &self.config.negotiation {
327 Negotiation::Handshake => {
328 self.core.state = SessionState::Handshaking;
329 self.handshake_sent = true;
330 let handshake = Handshake {
331 message_id: self.core.next_message_id(),
332 role: EnergyManagementRole::Cem,
333 supported_protocol_versions: Some(self.config.supported_versions.clone()),
334 };
335 self.core.transmit(Message::from(handshake), now);
336 }
337 Negotiation::PreNegotiated(profile) => {
338 let profile = *profile;
339 self.core.profile = profile;
340 self.negotiated = Some(profile.version());
341 self.core.state = SessionState::Connected;
342 self.events.push_back(CemEvent::Negotiated {
343 version: profile.version(),
344 profile,
345 });
346 }
347 }
348 }
349
350 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
352 self.core.poll_transmit()
353 }
354
355 pub fn poll_event(&mut self) -> Option<CemEvent> {
357 self.events.pop_front()
358 }
359
360 #[must_use]
362 pub fn poll_timeout(&self) -> Option<Timestamp> {
363 self.core.poll_timeout()
364 }
365
366 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
374 if self.core.state.is_closed() {
375 return Inbound {
376 kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
377 status: ReceptionStatusValues::Ok,
378 report: Report::new(),
379 };
380 }
381 self.core.stats.received = self.core.stats.received.saturating_add(1);
382 let options = self.core.decode_options();
383 match codec::decode_with(text, &options) {
384 Ok(decoded) => {
385 if !decoded.pruned.is_empty() {
386 let mut report = Report::new();
387 for path in &decoded.pruned {
388 report.push(
389 rules::UNKNOWN_PROPERTY,
390 path,
391 "property is not defined by the schema and was removed",
392 );
393 }
394 self.events.push_back(CemEvent::Warnings {
395 kind: decoded.message.kind(),
396 report,
397 });
398 }
399 self.handle_message(decoded.message, now)
400 }
401 Err(error) => {
402 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
403 let kind = error.peek().and_then(|p| p.kind);
404 let status = error.reception_status();
405 if kind != Some(MessageKind::ReceptionStatus) {
406 self.core.acknowledge(
407 status.subject_message_id,
408 status.status,
409 status.diagnostic_label.clone(),
410 now,
411 );
412 }
413 let mut report = Report::new();
414 report.push(rules::DECODE_FAILED, "", error.to_string());
415 self.events.push_back(CemEvent::Refused {
416 kind,
417 status: status.status,
418 report: report.clone(),
419 });
420 Inbound {
421 kind,
422 status: status.status,
423 report,
424 }
425 }
426 }
427 }
428
429 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
431 if self.core.state.is_closed() {
432 return Inbound::ignored(message.kind());
433 }
434
435 if let Message::ReceptionStatus(status) = &message {
436 self.on_reception_status(status, now);
437 return Inbound {
438 kind: Some(MessageKind::ReceptionStatus),
439 status: ReceptionStatusValues::Ok,
440 report: Report::new(),
441 };
442 }
443
444 let kind = message.kind();
445 let Some(id) = message.id() else {
446 return Inbound::ignored(kind);
447 };
448
449 if let Some(previous) = self.core.acks.previous_answer(id) {
450 self.core.acknowledge(id, previous, None, now);
454 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
455 let mut report = Report::new();
456 report.push_related(
457 rules::DUPLICATE_MESSAGE_ID,
458 "/message_id",
459 alloc::format!("{id} was already answered {previous:?}; not processed again"),
460 [id],
461 );
462 self.events.push_back(CemEvent::Warnings {
463 kind,
464 report: report.clone(),
465 });
466 return Inbound {
467 kind: Some(kind),
468 status: previous,
469 report,
470 };
471 }
472
473 let seen = self.core.acks.seen_ids();
474 let report = {
475 let ctx = self.core.registry.context(
476 self.core.profile,
477 EnergyManagementRole::Rm,
478 self.core.state.active_control_type(),
479 self.core.s2_connect,
480 now,
481 &seen,
482 self.core.skew_tolerance,
483 );
484 message.validate(&ctx)
485 };
486
487 if report.has_errors() {
488 let status = ReceptionStatusValues::InvalidContent;
489 self.core
490 .acknowledge(id, status, report.diagnostic_label(), now);
491 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
492 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
493 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
494 self.events.push_back(CemEvent::Refused {
495 kind: Some(kind),
496 status,
497 report: report.clone(),
498 });
499 if closing {
500 let reason = CloseReason::ProtocolError(
501 report
502 .diagnostic_label()
503 .unwrap_or_else(|| "out of order".to_string()),
504 );
505 self.close_with(reason);
506 }
507 return Inbound {
508 kind: Some(kind),
509 status,
510 report,
511 };
512 }
513
514 let policy = self
515 .policy
516 .as_mut()
517 .and_then(|policy| policy.review(&message));
518 if let Some((status, diagnostic)) = policy {
519 self.core
520 .acknowledge(id, status, Some(diagnostic.clone()), now);
521 let mut refusal = report.clone();
522 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
523 self.events.push_back(CemEvent::Refused {
524 kind: Some(kind),
525 status,
526 report: refusal,
527 });
528 return Inbound {
529 kind: Some(kind),
530 status,
531 report,
532 };
533 }
534
535 self.core
536 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
537 if !report.is_empty() {
538 self.core.stats.accepted_with_warnings =
539 self.core.stats.accepted_with_warnings.saturating_add(1);
540 self.events.push_back(CemEvent::Warnings {
541 kind,
542 report: report.clone(),
543 });
544 }
545 self.process(message, now);
546 Inbound {
547 kind: Some(kind),
548 status: ReceptionStatusValues::Ok,
549 report,
550 }
551 }
552
553 fn process(&mut self, message: Message, now: Timestamp) {
554 match &message {
555 Message::Handshake(h) => {
556 if let Some(versions) = &h.supported_protocol_versions {
557 self.peer_versions.clone_from(versions);
558 }
559 let Some(chosen) = self
567 .config
568 .supported_versions
569 .iter()
570 .find(|ours| self.peer_versions.iter().any(|theirs| ours.matches(theirs)))
571 .cloned()
572 else {
573 self.close_with(CloseReason::NoCommonVersion);
574 return;
575 };
576 let Some(profile) = chosen.wire_profile() else {
577 self.close_with(CloseReason::NoCommonVersion);
578 return;
579 };
580 self.core.profile = profile;
581 self.negotiated = Some(chosen.clone());
582 self.core.state = SessionState::Connected;
583 let message_id = self.core.next_message_id();
584 self.core.transmit(
585 Message::from(HandshakeResponse {
586 message_id,
587 selected_protocol_version: chosen.clone(),
588 }),
589 now,
590 );
591 self.events.push_back(CemEvent::Negotiated {
592 version: chosen,
593 profile,
594 });
595 return;
596 }
597 Message::SessionRequest(request) => {
598 self.events.push_back(CemEvent::SessionRequested {
599 request: request.request,
600 diagnostic: request.diagnostic_label.clone(),
601 });
602 self.close_with(CloseReason::PeerRequested(request.request));
603 return;
604 }
605 Message::RevokeObject(revoke) => {
606 self.core
607 .registry
608 .revoke(revoke.object_type, revoke.object_id);
609 self.events.push_back(CemEvent::Revoked {
610 object_type: revoke.object_type,
611 object_id: revoke.object_id,
612 });
613 return;
614 }
615 _ => {}
616 }
617
618 self.core.registry.record(&message, Some(now));
619
620 let kind = message.kind();
621 match message {
622 Message::ResourceManagerDetails(details) => {
623 self.events.push_back(CemEvent::ResourceDescribed(details));
624 }
625 Message::PowerMeasurement(m) => {
626 self.events.push_back(CemEvent::Measurement(Box::new(m)));
627 }
628 Message::PowerForecast(f) => self.events.push_back(CemEvent::Forecast(f)),
629 Message::InstructionStatusUpdate(u) => {
630 self.events.push_back(CemEvent::InstructionStatus {
631 instruction_id: u.instruction_id,
632 status: u.status_type,
633 });
634 }
635 Message::FrbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerFinished {
636 actuator: Some(s.actuator_id),
637 timer: s.timer_id,
638 finished_at: s.finished_at,
639 }),
640 Message::DdbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerFinished {
641 actuator: Some(s.actuator_id),
642 timer: s.timer_id,
643 finished_at: s.finished_at,
644 }),
645 Message::OmbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerFinished {
646 actuator: None,
647 timer: s.timer_id,
648 finished_at: s.finished_at,
649 }),
650 other => {
651 let is_description = matches!(
652 kind,
653 MessageKind::FrbcSystemDescription
654 | MessageKind::OmbcSystemDescription
655 | MessageKind::DdbcSystemDescription
656 | MessageKind::PebcPowerConstraints
657 | MessageKind::PebcEnergyConstraint
658 | MessageKind::PpbcPowerProfileDefinition
659 | MessageKind::FrbcLeakageBehaviour
660 | MessageKind::FrbcUsageForecast
661 | MessageKind::FrbcFillLevelTargetProfile
662 | MessageKind::DdbcAverageDemandRateForecast
663 );
664 if is_description {
665 self.events.push_back(CemEvent::Description {
666 kind,
667 message: other,
668 });
669 } else {
670 self.events.push_back(CemEvent::Status {
671 kind,
672 message: other,
673 });
674 }
675 }
676 }
677 }
678
679 fn on_reception_status(
680 &mut self,
681 status: &crate::types::common::ReceptionStatus,
682 now: Timestamp,
683 ) {
684 match self.core.acks.received(status, now) {
685 AckOutcome::Accepted { handle, latency } => {
686 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
687 self.core.stats.record_latency(latency);
688 if let Some((id, control_type)) = self.pending_control_type
691 && id == handle.id
692 {
693 self.pending_control_type = None;
694 if control_type == ControlType::NoSelection {
695 self.core.state = SessionState::Connected;
696 self.events.push_back(CemEvent::Deselected);
697 } else {
698 self.core.state = SessionState::ControlTypeSelected(control_type);
699 self.events.push_back(CemEvent::Ready { control_type });
700 }
701 }
702 self.events.push_back(CemEvent::Acked(handle));
703 }
704 AckOutcome::Refused {
705 handle,
706 status,
707 diagnostic,
708 consequence,
709 latency,
710 } => {
711 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
712 self.core.stats.record_latency(latency);
713 if self
714 .pending_control_type
715 .is_some_and(|(id, _)| id == handle.id)
716 {
717 self.pending_control_type = None;
718 }
719 self.events.push_back(CemEvent::Nacked {
720 handle,
721 status,
722 diagnostic: diagnostic.clone(),
723 consequence,
724 });
725 if consequence == Consequence::Disconnect {
726 self.close_with(CloseReason::PermanentError(
727 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
728 ));
729 }
730 }
731 AckOutcome::TimedOut(handle) => {
732 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
733 self.events.push_back(CemEvent::AckTimedOut(handle));
734 }
735 AckOutcome::Unmatched { subject, status } => {
736 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
737 self.events
738 .push_back(CemEvent::UnmatchedAck { subject, status });
739 }
740 }
741 }
742
743 pub fn handle_timeout(&mut self, now: Timestamp) {
745 for handle in self.core.acks.expire(now) {
746 if self
747 .pending_control_type
748 .is_some_and(|(id, _)| id == handle.id)
749 {
750 self.pending_control_type = None;
751 }
752 self.events.push_back(CemEvent::AckTimedOut(handle));
753 }
754 for message in self.core.registry.activate_due(now) {
755 self.events.push_back(CemEvent::DescriptionActivated {
756 kind: message.kind(),
757 });
758 }
759 }
760
761 pub fn transport_closed(&mut self, now: Timestamp) {
763 let _ = now;
764 self.close_with(CloseReason::TransportClosed);
765 }
766
767 pub fn select_control_type(
772 &mut self,
773 control_type: ControlType,
774 now: Timestamp,
775 ) -> Result<MessageHandle, SendError> {
776 let message_id = self.core.next_message_id();
777 let handle = self.send(
778 SelectControlType {
779 message_id,
780 control_type,
781 },
782 now,
783 )?;
784 self.pending_control_type = Some((handle.id, control_type));
785 Ok(handle)
786 }
787
788 pub fn instruct(
790 &mut self,
791 instruction: impl Into<Message>,
792 now: Timestamp,
793 ) -> Result<MessageHandle, SendError> {
794 let message = instruction.into();
795 if self.config.enforce_transitions {
796 let seen = self.core.acks.seen_ids();
797 let explanation = {
798 let ctx = self.core.registry.context(
799 self.core.profile,
800 EnergyManagementRole::Cem,
801 self.core.state.active_control_type(),
802 self.core.s2_connect,
803 now,
804 &seen,
805 self.core.skew_tolerance,
806 );
807 crate::model::explain(&message, &ctx)
808 };
809 if let Some(explanation) = explanation.filter(|e| !e.is_actionable()) {
814 let (rule, reason) = if let Some((timer, label)) = explanation.blocked_by.first() {
815 (
816 rules::BLOCKED_BY_TIMER,
817 alloc::format!(
818 "{} {timer} has not finished, and it blocks this transition",
819 label.as_deref().unwrap_or("timer")
820 ),
821 )
822 } else {
823 (
824 rules::ABNORMAL_ONLY,
825 "this instruction uses an option marked abnormal_condition_only without setting abnormal_condition"
826 .to_string(),
827 )
828 };
829 let mut report = Report::new();
830 report.push(rule, "", reason);
831 if let Some(violation) = report.violations().first() {
832 return Err(SendError::Invalid(Box::new(violation.clone())));
833 }
834 }
835 }
836 self.send(message, now)
837 }
838
839 pub fn revoke(
841 &mut self,
842 object_type: RevokableObjects,
843 object_id: Id,
844 now: Timestamp,
845 ) -> Result<MessageHandle, SendError> {
846 let message_id = self.core.next_message_id();
847 let handle = self.send(
848 RevokeObject {
849 message_id,
850 object_type,
851 object_id,
852 },
853 now,
854 )?;
855 self.core.registry.revoke(object_type, object_id);
856 Ok(handle)
857 }
858
859 pub fn request_session(
861 &mut self,
862 request: SessionRequestType,
863 diagnostic: Option<String>,
864 now: Timestamp,
865 ) -> Result<MessageHandle, SendError> {
866 let message_id = self.core.next_message_id();
867 let handle = self.send(
868 SessionRequest {
869 message_id,
870 request,
871 diagnostic_label: diagnostic,
872 },
873 now,
874 )?;
875 self.close_with(CloseReason::LocallyRequested(request));
878 Ok(handle)
879 }
880
881 pub fn send(
883 &mut self,
884 message: impl Into<Message>,
885 now: Timestamp,
886 ) -> Result<MessageHandle, SendError> {
887 let message = message.into();
888 let kind = message.kind();
889 if self.core.state.is_closed() {
890 return Err(SendError::Closed);
891 }
892 if !kind.exists_in(self.core.profile) {
893 return Err(SendError::NotInProfile {
894 kind,
895 profile: self.core.profile,
896 });
897 }
898 let allowance = crate::validate::allowed(
899 self.core.state.active_control_type(),
900 EnergyManagementRole::Cem,
901 kind,
902 );
903 if !allowance.is_allowed() {
904 return Err(SendError::NotAllowed {
905 kind,
906 state: state_name(&self.core.state),
907 });
908 }
909 if self.config.validate_outbound {
910 let seen = self.core.acks.seen_ids();
911 let report = {
912 let ctx = self.core.registry.context(
913 self.core.profile,
914 EnergyManagementRole::Cem,
915 self.core.state.active_control_type(),
916 self.core.s2_connect,
917 now,
918 &seen,
919 self.core.skew_tolerance,
920 );
921 message.validate(&ctx)
922 };
923 if let Some(violation) = report.first_error() {
924 return Err(SendError::Invalid(Box::new(violation.clone())));
925 }
926 }
927 self.core.transmit(message, now).ok_or(SendError::Closed)
928 }
929
930 pub fn close(&mut self) {
932 self.close_with(CloseReason::Local);
933 }
934
935 fn close_with(&mut self, reason: CloseReason) {
936 if self.core.state.is_closed() {
937 return;
938 }
939 let reconnect_after = match &reason {
940 CloseReason::Local => None,
941 CloseReason::PeerRequested(SessionRequestType::Reconnect)
944 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
945 _ => {
946 let delay = self.backoff.ceiling(self.core.reconnect_attempt);
947 self.core.reconnect_attempt = self.core.reconnect_attempt.saturating_add(1);
948 Some(delay)
949 }
950 };
951 self.core.state = SessionState::Closed(reason.clone());
952 self.events.push_back(CemEvent::Closed {
953 reason,
954 reconnect_after,
955 });
956 }
957}