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