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 InstructionStatusUpdate, 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 pub reconnect_attempt: u32,
62}
63
64impl Default for CemConfig {
65 fn default() -> Self {
66 Self {
67 negotiation: Negotiation::Handshake,
68 supported_versions: alloc::vec![ProtocolVersion::V1_0_0, ProtocolVersion::V0_0_2_BETA,],
69 ack_timeout: Duration::from_secs(5),
70 out_of_order: OutOfOrderPolicy::Report,
71 skew_tolerance: Duration::from_secs(30),
72 max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
73 strictness: Strictness::Strict,
74 s2_connect: false,
75 validate_outbound: true,
76 enforce_transitions: false,
77 reconnect_attempt: 0,
78 }
79 }
80}
81
82impl CemConfig {
83 #[must_use]
89 pub fn without_outbound_validation(mut self) -> Self {
90 self.validate_outbound = false;
91 self
92 }
93
94 #[must_use]
96 pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
97 self.negotiation = Negotiation::PreNegotiated(profile);
98 self.s2_connect = true;
99 self
100 }
101
102 #[must_use]
104 pub fn supporting(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
105 self.supported_versions = versions.into_iter().collect();
106 self
107 }
108
109 #[must_use]
115 pub const fn after_failed_attempts(mut self, attempts: u32) -> Self {
116 self.reconnect_attempt = attempts;
117 self
118 }
119}
120
121#[derive(Debug, Clone, PartialEq)]
123#[non_exhaustive]
124pub enum CemEvent {
125 Negotiated {
127 version: ProtocolVersion,
129 profile: WireProfile,
131 },
132 ResourceDescribed(Box<ResourceManagerDetails>),
134 Ready {
136 control_type: ControlType,
138 },
139 Deselected,
141 Description {
143 kind: MessageKind,
145 message: Message,
147 },
148 Status {
150 kind: MessageKind,
152 message: Message,
154 },
155 Measurement(Box<PowerMeasurement>),
157 Forecast(Box<PowerForecast>),
159 InstructionStatus(InstructionStatusUpdate),
165 TimerReported {
174 actuator: Option<Id>,
176 timer: Id,
178 finished_at: Timestamp,
181 },
182 DescriptionActivated {
184 kind: MessageKind,
186 },
187 Revoked {
189 object_type: RevokableObjects,
191 object_id: Id,
193 },
194 Acked(MessageHandle),
196 Nacked {
198 handle: MessageHandle,
200 status: ReceptionStatusValues,
202 diagnostic: Option<String>,
204 consequence: Consequence,
206 },
207 AckTimedOut(MessageHandle),
209 UnmatchedAck {
211 subject: Id,
213 status: ReceptionStatusValues,
215 },
216 SessionRequested {
218 request: SessionRequestType,
220 diagnostic: Option<String>,
222 },
223 Refused {
225 kind: Option<MessageKind>,
227 status: ReceptionStatusValues,
229 report: Report,
231 },
232 Warnings {
234 kind: MessageKind,
236 report: Report,
238 },
239 OutboundWarnings {
248 kind: MessageKind,
250 report: Report,
252 },
253 Closed {
255 reason: CloseReason,
257 reconnect_after: Option<Duration>,
259 },
260}
261
262pub struct CemSession {
269 core: SessionCore,
270 config: CemConfig,
271 events: VecDeque<CemEvent>,
272 peer_versions: Vec<ProtocolVersion>,
273 negotiated: Option<ProtocolVersion>,
274 handshake_sent: bool,
275 pending_control_type: Option<(Id, ControlType)>,
276 policy: Option<Box<dyn InboundPolicy + Send>>,
277 backoff: Backoff,
278}
279
280impl core::fmt::Debug for CemSession {
281 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
282 f.debug_struct("CemSession")
283 .field("state", &self.core.state)
284 .field("profile", &self.core.profile)
285 .field("outstanding_acks", &self.core.acks.outstanding())
286 .field("queued", &self.core.outbox.len())
287 .finish_non_exhaustive()
288 }
289}
290
291impl CemSession {
292 #[must_use]
294 pub fn new(config: CemConfig) -> Self {
295 let core = SessionCore::new(CoreConfig {
296 role: EnergyManagementRole::Cem,
297 negotiation: config.negotiation.clone(),
298 ack_timeout: config.ack_timeout,
299 out_of_order: config.out_of_order,
300 skew_tolerance: config.skew_tolerance,
301 max_message_bytes: config.max_message_bytes,
302 strictness: config.strictness,
303 s2_connect: config.s2_connect,
304 reconnect_attempt: config.reconnect_attempt,
305 });
306 Self {
307 core,
308 config,
309 events: VecDeque::new(),
310 peer_versions: Vec::new(),
311 negotiated: None,
312 handshake_sent: false,
313 pending_control_type: None,
314 policy: None,
315 backoff: Backoff::default(),
316 }
317 }
318
319 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
321 self.policy = Some(policy);
322 }
323
324 #[must_use]
326 pub fn state(&self) -> &SessionState {
327 &self.core.state
328 }
329
330 #[must_use]
332 pub fn profile(&self) -> WireProfile {
333 self.core.profile
334 }
335
336 #[must_use]
340 pub fn stats(&self) -> super::core::Stats {
341 self.core.stats
342 }
343
344 #[must_use]
346 pub fn registry(&self) -> &super::core::Registry {
347 &self.core.registry
348 }
349
350 #[must_use]
352 pub fn details(&self) -> Option<&ResourceManagerDetails> {
353 self.core.registry.details.as_ref()
354 }
355
356 pub fn open(&mut self, now: Timestamp) {
362 if !matches!(self.core.state, SessionState::Idle) {
363 return;
364 }
365 match &self.config.negotiation {
366 Negotiation::Handshake => {
367 self.core.state = SessionState::Handshaking;
368 self.handshake_sent = true;
369 let handshake = Handshake {
370 message_id: self.core.next_message_id(),
371 role: EnergyManagementRole::Cem,
372 supported_protocol_versions: Some(self.config.supported_versions.clone()),
373 };
374 self.core.transmit(Message::from(handshake), now);
375 }
376 Negotiation::PreNegotiated(profile) => {
377 let profile = *profile;
378 self.core.profile = profile;
379 self.negotiated = Some(profile.version());
380 self.core.state = SessionState::Connected;
381 self.events.push_back(CemEvent::Negotiated {
382 version: profile.version(),
383 profile,
384 });
385 }
386 }
387 }
388
389 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
391 self.core.poll_transmit()
392 }
393
394 pub fn poll_event(&mut self) -> Option<CemEvent> {
396 self.events.pop_front()
397 }
398
399 #[must_use]
401 pub fn poll_timeout(&self) -> Option<Timestamp> {
402 self.core.poll_timeout()
403 }
404
405 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
413 if self.core.state.is_closed() {
414 return Inbound {
415 kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
416 status: ReceptionStatusValues::Ok,
417 report: Report::new(),
418 };
419 }
420 self.core.stats.received = self.core.stats.received.saturating_add(1);
421 let options = self.core.decode_options();
422 match codec::decode_with(text, &options) {
423 Ok(decoded) => {
424 if !decoded.pruned.is_empty() {
425 let mut report = Report::new();
426 for path in &decoded.pruned {
427 report.push(
428 rules::UNKNOWN_PROPERTY,
429 path,
430 "property is not defined by the schema and was removed",
431 );
432 }
433 self.events.push_back(CemEvent::Warnings {
434 kind: decoded.message.kind(),
435 report,
436 });
437 }
438 self.handle_message(decoded.message, now)
439 }
440 Err(error) => {
441 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
442 let kind = error.peek().and_then(|p| p.kind);
443 let status = error.reception_status();
444 if kind != Some(MessageKind::ReceptionStatus) {
445 self.core.acknowledge(
446 status.subject_message_id,
447 status.status,
448 status.diagnostic_label.clone(),
449 now,
450 );
451 }
452 let mut report = Report::new();
453 report.push(rules::DECODE_FAILED, "", error.to_string());
454 self.events.push_back(CemEvent::Refused {
455 kind,
456 status: status.status,
457 report: report.clone(),
458 });
459 Inbound {
460 kind,
461 status: status.status,
462 report,
463 }
464 }
465 }
466 }
467
468 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
470 if self.core.state.is_closed() {
471 return Inbound::ignored(message.kind());
472 }
473
474 if let Message::ReceptionStatus(status) = &message {
475 self.on_reception_status(status, now);
476 return Inbound {
477 kind: Some(MessageKind::ReceptionStatus),
478 status: ReceptionStatusValues::Ok,
479 report: Report::new(),
480 };
481 }
482
483 let kind = message.kind();
484 let Some(id) = message.id() else {
485 return Inbound::ignored(kind);
486 };
487
488 if let Some(previous) = self.core.acks.previous_answer(id) {
489 self.core.acknowledge(id, previous, None, now);
493 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
494 let mut report = Report::new();
495 report.push_related(
496 rules::DUPLICATE_MESSAGE_ID,
497 "/message_id",
498 alloc::format!("{id} was already answered {previous:?}; not processed again"),
499 [id],
500 );
501 self.events.push_back(CemEvent::Warnings {
502 kind,
503 report: report.clone(),
504 });
505 return Inbound {
506 kind: Some(kind),
507 status: previous,
508 report,
509 };
510 }
511
512 let seen = self.core.acks.seen_ids();
513 let report = {
514 let ctx = self.core.registry.context(
515 self.core.profile,
516 EnergyManagementRole::Rm,
517 self.core.state.phase(),
518 self.core.s2_connect,
519 now,
520 &seen,
521 self.core.skew_tolerance,
522 );
523 message.validate(&ctx)
524 };
525
526 if report.has_errors() {
527 let status = ReceptionStatusValues::InvalidContent;
528 self.core
529 .acknowledge(id, status, report.diagnostic_label(), now);
530 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
531 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
532 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
533 self.events.push_back(CemEvent::Refused {
534 kind: Some(kind),
535 status,
536 report: report.clone(),
537 });
538 if closing {
539 let reason = CloseReason::ProtocolError(
540 report
541 .diagnostic_label()
542 .unwrap_or_else(|| "out of order".to_string()),
543 );
544 self.close_with(reason);
545 }
546 return Inbound {
547 kind: Some(kind),
548 status,
549 report,
550 };
551 }
552
553 let policy = self
554 .policy
555 .as_mut()
556 .and_then(|policy| policy.review(&message));
557 if let Some((status, diagnostic)) = policy {
558 self.core
559 .acknowledge(id, status, Some(diagnostic.clone()), now);
560 let mut refusal = report.clone();
561 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
562 self.events.push_back(CemEvent::Refused {
563 kind: Some(kind),
564 status,
565 report: refusal,
566 });
567 return Inbound {
568 kind: Some(kind),
569 status,
570 report,
571 };
572 }
573
574 self.core
575 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
576 if !report.is_empty() {
577 self.core.stats.accepted_with_warnings =
578 self.core.stats.accepted_with_warnings.saturating_add(1);
579 self.events.push_back(CemEvent::Warnings {
580 kind,
581 report: report.clone(),
582 });
583 }
584 self.process(message, now);
585 Inbound {
586 kind: Some(kind),
587 status: ReceptionStatusValues::Ok,
588 report,
589 }
590 }
591
592 fn process(&mut self, message: Message, now: Timestamp) {
593 match &message {
594 Message::Handshake(h) => {
595 if let Some(versions) = &h.supported_protocol_versions {
596 self.peer_versions.clone_from(versions);
597 }
598 let Some(chosen) = self
606 .config
607 .supported_versions
608 .iter()
609 .find(|ours| self.peer_versions.iter().any(|theirs| ours.matches(theirs)))
610 .cloned()
611 else {
612 self.close_with(CloseReason::NoCommonVersion);
613 return;
614 };
615 let Some(profile) = chosen.wire_profile() else {
616 self.close_with(CloseReason::NoCommonVersion);
617 return;
618 };
619 self.core.profile = profile;
620 self.negotiated = Some(chosen.clone());
621 self.core.state = SessionState::Connected;
622 let message_id = self.core.next_message_id();
623 self.core.transmit(
624 Message::from(HandshakeResponse {
625 message_id,
626 selected_protocol_version: chosen.clone(),
627 }),
628 now,
629 );
630 self.events.push_back(CemEvent::Negotiated {
631 version: chosen,
632 profile,
633 });
634 return;
635 }
636 Message::SessionRequest(request) => {
637 self.events.push_back(CemEvent::SessionRequested {
638 request: request.request,
639 diagnostic: request.diagnostic_label.clone(),
640 });
641 self.close_with(CloseReason::PeerRequested(request.request));
642 return;
643 }
644 Message::RevokeObject(revoke) => {
645 self.core
646 .registry
647 .revoke(revoke.object_type, revoke.object_id);
648 self.events.push_back(CemEvent::Revoked {
649 object_type: revoke.object_type,
650 object_id: revoke.object_id,
651 });
652 return;
653 }
654 _ => {}
655 }
656
657 self.core.registry.record(&message, Some(now));
658
659 let kind = message.kind();
660 match message {
661 Message::ResourceManagerDetails(details) => {
662 self.events.push_back(CemEvent::ResourceDescribed(details));
663 }
664 Message::PowerMeasurement(m) => {
665 self.events.push_back(CemEvent::Measurement(Box::new(m)));
666 }
667 Message::PowerForecast(f) => self.events.push_back(CemEvent::Forecast(f)),
668 Message::InstructionStatusUpdate(u) => {
669 self.events.push_back(CemEvent::InstructionStatus(u));
670 }
671 Message::FrbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
672 actuator: Some(s.actuator_id),
673 timer: s.timer_id,
674 finished_at: s.finished_at,
675 }),
676 Message::DdbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
677 actuator: Some(s.actuator_id),
678 timer: s.timer_id,
679 finished_at: s.finished_at,
680 }),
681 Message::OmbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
682 actuator: None,
683 timer: s.timer_id,
684 finished_at: s.finished_at,
685 }),
686 other => {
687 let is_description = matches!(
688 kind,
689 MessageKind::FrbcSystemDescription
690 | MessageKind::OmbcSystemDescription
691 | MessageKind::DdbcSystemDescription
692 | MessageKind::PebcPowerConstraints
693 | MessageKind::PebcEnergyConstraint
694 | MessageKind::PpbcPowerProfileDefinition
695 | MessageKind::FrbcLeakageBehaviour
696 | MessageKind::FrbcUsageForecast
697 | MessageKind::FrbcFillLevelTargetProfile
698 | MessageKind::DdbcAverageDemandRateForecast
699 );
700 if is_description {
701 self.events.push_back(CemEvent::Description {
702 kind,
703 message: other,
704 });
705 } else {
706 self.events.push_back(CemEvent::Status {
707 kind,
708 message: other,
709 });
710 }
711 }
712 }
713 }
714
715 fn on_reception_status(
716 &mut self,
717 status: &crate::types::common::ReceptionStatus,
718 now: Timestamp,
719 ) {
720 match self.core.acks.received(status, now) {
721 AckOutcome::Accepted { handle, latency } => {
722 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
723 self.core.stats.record_latency(latency);
724 if let Some((id, control_type)) = self.pending_control_type
727 && id == handle.id
728 {
729 self.pending_control_type = None;
730 if control_type == ControlType::NoSelection {
731 self.core.state = SessionState::Connected;
732 self.events.push_back(CemEvent::Deselected);
733 } else {
734 self.core.state = SessionState::ControlTypeSelected(control_type);
735 self.events.push_back(CemEvent::Ready { control_type });
736 }
737 }
738 self.events.push_back(CemEvent::Acked(handle));
739 }
740 AckOutcome::Refused {
741 handle,
742 status,
743 diagnostic,
744 consequence,
745 latency,
746 } => {
747 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
748 self.core.stats.record_latency(latency);
749 if self
750 .pending_control_type
751 .is_some_and(|(id, _)| id == handle.id)
752 {
753 self.pending_control_type = None;
754 }
755 self.events.push_back(CemEvent::Nacked {
756 handle,
757 status,
758 diagnostic: diagnostic.clone(),
759 consequence,
760 });
761 if consequence == Consequence::Disconnect {
762 self.close_with(CloseReason::PermanentError(
763 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
764 ));
765 }
766 }
767 AckOutcome::TimedOut(handle) => {
768 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
769 self.events.push_back(CemEvent::AckTimedOut(handle));
770 }
771 AckOutcome::Unmatched { subject, status } => {
772 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
773 self.events
774 .push_back(CemEvent::UnmatchedAck { subject, status });
775 }
776 }
777 }
778
779 pub fn handle_timeout(&mut self, now: Timestamp) {
781 for handle in self.core.acks.expire(now) {
782 if self
783 .pending_control_type
784 .is_some_and(|(id, _)| id == handle.id)
785 {
786 self.pending_control_type = None;
787 }
788 self.events.push_back(CemEvent::AckTimedOut(handle));
789 }
790 for message in self.core.registry.activate_due(now) {
791 self.events.push_back(CemEvent::DescriptionActivated {
792 kind: message.kind(),
793 });
794 }
795 }
796
797 pub fn transport_closed(&mut self, now: Timestamp) {
799 let _ = now;
800 self.close_with(CloseReason::TransportClosed);
801 }
802
803 pub fn select_control_type(
808 &mut self,
809 control_type: ControlType,
810 now: Timestamp,
811 ) -> Result<MessageHandle, SendError> {
812 let message_id = self.core.next_message_id();
813 let handle = self.send(
814 SelectControlType {
815 message_id,
816 control_type,
817 },
818 now,
819 )?;
820 self.pending_control_type = Some((handle.id, control_type));
821 Ok(handle)
822 }
823
824 pub fn instruct(
826 &mut self,
827 instruction: impl Into<Message>,
828 now: Timestamp,
829 ) -> Result<MessageHandle, SendError> {
830 let message = instruction.into();
831 if self.config.enforce_transitions {
832 let seen = self.core.acks.seen_ids();
833 let explanation = {
834 let ctx = self.core.registry.context(
835 self.core.profile,
836 EnergyManagementRole::Cem,
837 self.core.state.phase(),
838 self.core.s2_connect,
839 now,
840 &seen,
841 self.core.skew_tolerance,
842 );
843 crate::model::explain(&message, &ctx)
844 };
845 if let Some(explanation) = explanation.filter(|e| !e.is_actionable()) {
850 let (rule, reason) = if let Some((timer, label)) = explanation.blocked_by.first() {
851 (
852 rules::BLOCKED_BY_TIMER,
853 alloc::format!(
854 "{} {timer} has not finished, and it blocks this transition",
855 label.as_deref().unwrap_or("timer")
856 ),
857 )
858 } else {
859 (
860 rules::ABNORMAL_ONLY,
861 "this instruction uses an option marked abnormal_condition_only without setting abnormal_condition"
862 .to_string(),
863 )
864 };
865 let mut report = Report::new();
866 report.push(rule, "", reason);
867 if let Some(violation) = report.violations().first() {
868 return Err(SendError::Invalid(Box::new(violation.clone())));
869 }
870 }
871 }
872 self.send(message, now)
873 }
874
875 pub fn revoke(
877 &mut self,
878 object_type: RevokableObjects,
879 object_id: Id,
880 now: Timestamp,
881 ) -> Result<MessageHandle, SendError> {
882 let message_id = self.core.next_message_id();
883 let handle = self.send(
884 RevokeObject {
885 message_id,
886 object_type,
887 object_id,
888 },
889 now,
890 )?;
891 self.core.registry.revoke(object_type, object_id);
892 Ok(handle)
893 }
894
895 pub fn request_session(
897 &mut self,
898 request: SessionRequestType,
899 diagnostic: Option<String>,
900 now: Timestamp,
901 ) -> Result<MessageHandle, SendError> {
902 let message_id = self.core.next_message_id();
903 let handle = self.send(
904 SessionRequest {
905 message_id,
906 request,
907 diagnostic_label: diagnostic,
908 },
909 now,
910 )?;
911 self.close_with(CloseReason::LocallyRequested(request));
914 Ok(handle)
915 }
916
917 pub fn send(
919 &mut self,
920 message: impl Into<Message>,
921 now: Timestamp,
922 ) -> Result<MessageHandle, SendError> {
923 let message = message.into();
924 let kind = message.kind();
925 if self.core.state.is_closed() {
926 return Err(SendError::Closed);
927 }
928 if !kind.exists_in(self.core.profile) {
929 return Err(SendError::NotInProfile {
930 kind,
931 profile: self.core.profile,
932 });
933 }
934 let allowance =
935 crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Cem, kind);
936 if !allowance.is_allowed() {
937 return Err(SendError::NotAllowed {
938 kind,
939 state: state_name(&self.core.state),
940 });
941 }
942 if self.config.validate_outbound {
943 let seen = self.core.acks.seen_ids();
944 let report = {
945 let ctx = self.core.registry.context(
946 self.core.profile,
947 EnergyManagementRole::Cem,
948 self.core.state.phase(),
949 self.core.s2_connect,
950 now,
951 &seen,
952 self.core.skew_tolerance,
953 );
954 message.validate(&ctx)
955 };
956 if let Some(violation) = report.first_error() {
957 return Err(SendError::Invalid(Box::new(violation.clone())));
958 }
959 if !report.is_empty() {
960 self.core.stats.sent_with_warnings =
961 self.core.stats.sent_with_warnings.saturating_add(1);
962 self.events
963 .push_back(CemEvent::OutboundWarnings { kind, report });
964 }
965 }
966 self.core.transmit(message, now).ok_or(SendError::Closed)
967 }
968
969 pub fn close(&mut self) {
971 self.close_with(CloseReason::Local);
972 }
973
974 fn close_with(&mut self, reason: CloseReason) {
975 if self.core.state.is_closed() {
976 return;
977 }
978 let reconnect_after = match &reason {
979 CloseReason::Local => None,
980 CloseReason::PeerRequested(SessionRequestType::Reconnect)
983 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
984 _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
985 };
986 self.core.state = SessionState::Closed(reason.clone());
987 self.events.push_back(CemEvent::Closed {
988 reason,
989 reconnect_after,
990 });
991 }
992}