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>,
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]
347 pub fn negotiated_version(&self) -> Option<&ProtocolVersion> {
348 self.negotiated.as_ref()
349 }
350
351 #[must_use]
355 pub fn stats(&self) -> super::core::Stats {
356 self.core.stats
357 }
358
359 #[must_use]
361 pub fn registry(&self) -> &super::core::Registry {
362 &self.core.registry
363 }
364
365 #[must_use]
367 pub fn details(&self) -> Option<&ResourceManagerDetails> {
368 self.core.registry.details.as_ref()
369 }
370
371 pub fn open(&mut self, now: Timestamp) {
377 if !matches!(self.core.state, SessionState::Idle) {
378 return;
379 }
380 match &self.config.negotiation {
381 Negotiation::Handshake => {
382 self.core.state = SessionState::Handshaking;
383 self.handshake_sent = true;
384 let handshake = Handshake {
385 message_id: self.core.next_message_id(),
386 role: EnergyManagementRole::Cem,
387 supported_protocol_versions: Some(self.config.supported_versions.clone()),
388 };
389 self.core.transmit(Message::from(handshake), now);
390 }
391 Negotiation::PreNegotiated(profile) => {
392 let profile = *profile;
393 self.core.profile = profile;
394 self.negotiated = Some(profile.version());
395 self.core.state = SessionState::Connected;
396 self.events.push_back(CemEvent::Negotiated {
397 version: profile.version(),
398 profile,
399 });
400 }
401 }
402 }
403
404 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
406 self.core.poll_transmit()
407 }
408
409 pub fn poll_event(&mut self) -> Option<CemEvent> {
411 self.events.pop_front()
412 }
413
414 #[must_use]
416 pub fn poll_timeout(&self) -> Option<Timestamp> {
417 self.core.poll_timeout()
418 }
419
420 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
428 if self.core.state.is_closed() {
429 let peek = crate::codec::peek(text).ok();
430 return Inbound {
431 kind: peek.as_ref().and_then(|p| p.kind),
432 message_id: peek.and_then(|p| p.message_id),
433 status: ReceptionStatusValues::Ok,
434 report: Report::new(),
435 };
436 }
437 self.core.stats.received = self.core.stats.received.saturating_add(1);
438 let options = self.core.decode_options();
439 match codec::decode_with(text, &options) {
440 Ok(decoded) => {
441 if !decoded.pruned.is_empty() {
442 let mut report = Report::new();
443 for path in &decoded.pruned {
444 report.push(
445 rules::UNKNOWN_PROPERTY,
446 path,
447 "property is not defined by the schema and was removed",
448 );
449 }
450 self.events.push_back(CemEvent::Warnings {
451 kind: decoded.message.kind(),
452 report,
453 });
454 }
455 self.handle_message(decoded.message, now)
456 }
457 Err(error) => {
458 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
459 let kind = error.peek().and_then(|p| p.kind);
460 let status = error.reception_status();
461 if kind != Some(MessageKind::ReceptionStatus) {
462 self.core.acknowledge(
463 status.subject_message_id,
464 status.status,
465 status.diagnostic_label.clone(),
466 now,
467 );
468 }
469 let mut report = Report::new();
470 report.push(rules::DECODE_FAILED, "", error.to_string());
471 self.events.push_back(CemEvent::Refused {
472 kind,
473 status: status.status,
474 report: report.clone(),
475 });
476 Inbound {
477 kind,
478 message_id: error.peek().and_then(|p| p.message_id),
479 status: status.status,
480 report,
481 }
482 }
483 }
484 }
485
486 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
488 if self.core.state.is_closed() {
489 return Inbound::ignored(message.kind(), message.id());
490 }
491
492 if let Message::ReceptionStatus(status) = &message {
493 self.on_reception_status(status, now);
494 return Inbound {
495 kind: Some(MessageKind::ReceptionStatus),
496 message_id: None,
497 status: ReceptionStatusValues::Ok,
498 report: Report::new(),
499 };
500 }
501
502 let kind = message.kind();
503 let Some(id) = message.id() else {
504 return Inbound::ignored(kind, None);
505 };
506
507 if let Some(previous) = self.core.acks.previous_answer(id) {
508 self.core.acknowledge(id, previous, None, now);
512 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
513 let mut report = Report::new();
514 report.push_related(
515 rules::DUPLICATE_MESSAGE_ID,
516 "/message_id",
517 alloc::format!("{id} was already answered {previous:?}; not processed again"),
518 [id],
519 );
520 self.events.push_back(CemEvent::Warnings {
521 kind,
522 report: report.clone(),
523 });
524 return Inbound {
525 kind: Some(kind),
526 message_id: Some(id),
527 status: previous,
528 report,
529 };
530 }
531
532 let seen = self.core.acks.seen_ids();
533 let report = {
534 let ctx = self.core.registry.context(
535 self.core.profile,
536 EnergyManagementRole::Rm,
537 self.core.state.phase(),
538 self.core.s2_connect,
539 now,
540 &seen,
541 self.core.skew_tolerance,
542 );
543 message.validate(&ctx)
544 };
545
546 if report.has_errors() {
547 let status = ReceptionStatusValues::InvalidContent;
548 self.core
549 .acknowledge(id, status, report.diagnostic_label(), now);
550 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
551 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
552 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
553 self.events.push_back(CemEvent::Refused {
554 kind: Some(kind),
555 status,
556 report: report.clone(),
557 });
558 if closing {
559 let reason = CloseReason::ProtocolError(
560 report
561 .diagnostic_label()
562 .unwrap_or_else(|| "out of order".to_string()),
563 );
564 self.close_with(reason);
565 }
566 return Inbound {
567 kind: Some(kind),
568 message_id: Some(id),
569 status,
570 report,
571 };
572 }
573
574 let policy = self
575 .policy
576 .as_mut()
577 .and_then(|policy| policy.review(&message));
578 if let Some((status, diagnostic)) = policy {
579 self.core
580 .acknowledge(id, status, Some(diagnostic.clone()), now);
581 let mut refusal = report.clone();
582 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
583 self.events.push_back(CemEvent::Refused {
584 kind: Some(kind),
585 status,
586 report: refusal,
587 });
588 return Inbound {
589 kind: Some(kind),
590 message_id: Some(id),
591 status,
592 report,
593 };
594 }
595
596 self.core
597 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
598 if !report.is_empty() {
599 self.core.stats.accepted_with_warnings =
600 self.core.stats.accepted_with_warnings.saturating_add(1);
601 self.events.push_back(CemEvent::Warnings {
602 kind,
603 report: report.clone(),
604 });
605 }
606 self.process(message, now);
607 Inbound {
608 kind: Some(kind),
609 message_id: Some(id),
610 status: ReceptionStatusValues::Ok,
611 report,
612 }
613 }
614
615 fn process(&mut self, message: Message, now: Timestamp) {
616 if self.core.s2_connect
621 && matches!(
622 message,
623 Message::Handshake(_) | Message::HandshakeResponse(_)
624 )
625 {
626 return;
627 }
628 match &message {
629 Message::Handshake(h) => {
630 if let Some(versions) = &h.supported_protocol_versions {
631 self.peer_versions.clone_from(versions);
632 }
633 let Some(chosen) = self
641 .config
642 .supported_versions
643 .iter()
644 .find(|ours| self.peer_versions.iter().any(|theirs| ours.matches(theirs)))
645 .cloned()
646 else {
647 self.close_with(CloseReason::NoCommonVersion);
648 return;
649 };
650 let Some(profile) = chosen.wire_profile() else {
651 self.close_with(CloseReason::NoCommonVersion);
652 return;
653 };
654 self.core.profile = profile;
655 self.negotiated = Some(chosen.clone());
656 self.core.state = SessionState::Connected;
657 let message_id = self.core.next_message_id();
658 self.core.transmit(
659 Message::from(HandshakeResponse {
660 message_id,
661 selected_protocol_version: chosen.clone(),
662 }),
663 now,
664 );
665 self.events.push_back(CemEvent::Negotiated {
666 version: chosen,
667 profile,
668 });
669 return;
670 }
671 Message::SessionRequest(request) => {
672 self.events.push_back(CemEvent::SessionRequested {
673 request: request.request,
674 diagnostic: request.diagnostic_label.clone(),
675 });
676 self.close_with(CloseReason::PeerRequested(request.request));
677 return;
678 }
679 Message::RevokeObject(revoke) => {
680 self.core
681 .registry
682 .revoke(revoke.object_type, revoke.object_id);
683 self.events.push_back(CemEvent::Revoked {
684 object_type: revoke.object_type,
685 object_id: revoke.object_id,
686 });
687 return;
688 }
689 _ => {}
690 }
691
692 self.core.registry.record(&message, Some(now));
693
694 let kind = message.kind();
695 match message {
696 Message::ResourceManagerDetails(details) => {
697 self.events.push_back(CemEvent::ResourceDescribed(details));
698 }
699 Message::PowerMeasurement(m) => {
700 self.events.push_back(CemEvent::Measurement(Box::new(m)));
701 }
702 Message::PowerForecast(f) => self.events.push_back(CemEvent::Forecast(f)),
703 Message::InstructionStatusUpdate(u) => {
704 self.events.push_back(CemEvent::InstructionStatus(u));
705 }
706 Message::FrbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
707 actuator: Some(s.actuator_id),
708 timer: s.timer_id,
709 finished_at: s.finished_at,
710 }),
711 Message::DdbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
712 actuator: Some(s.actuator_id),
713 timer: s.timer_id,
714 finished_at: s.finished_at,
715 }),
716 Message::OmbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
717 actuator: None,
718 timer: s.timer_id,
719 finished_at: s.finished_at,
720 }),
721 other => {
722 let is_description = matches!(
723 kind,
724 MessageKind::FrbcSystemDescription
725 | MessageKind::OmbcSystemDescription
726 | MessageKind::DdbcSystemDescription
727 | MessageKind::PebcPowerConstraints
728 | MessageKind::PebcEnergyConstraint
729 | MessageKind::PpbcPowerProfileDefinition
730 | MessageKind::FrbcLeakageBehaviour
731 | MessageKind::FrbcUsageForecast
732 | MessageKind::FrbcFillLevelTargetProfile
733 | MessageKind::DdbcAverageDemandRateForecast
734 );
735 if is_description {
736 self.events.push_back(CemEvent::Description {
737 kind,
738 message: other,
739 });
740 } else {
741 self.events.push_back(CemEvent::Status {
742 kind,
743 message: other,
744 });
745 }
746 }
747 }
748 }
749
750 fn on_reception_status(
751 &mut self,
752 status: &crate::types::common::ReceptionStatus,
753 now: Timestamp,
754 ) {
755 match self.core.acks.received(status, now) {
756 AckOutcome::Accepted { handle, latency } => {
757 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
758 self.core.stats.record_latency(latency);
759 if let Some((id, control_type)) = self.pending_control_type
762 && id == handle.id
763 {
764 self.pending_control_type = None;
765 if control_type == ControlType::NoSelection {
766 self.core.state = SessionState::Connected;
767 self.events.push_back(CemEvent::Deselected);
768 } else {
769 self.core.state = SessionState::ControlTypeSelected(control_type);
770 self.events.push_back(CemEvent::Ready { control_type });
771 }
772 }
773 self.events.push_back(CemEvent::Acked(handle));
774 }
775 AckOutcome::Refused {
776 handle,
777 status,
778 diagnostic,
779 consequence,
780 latency,
781 } => {
782 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
783 self.core.stats.record_latency(latency);
784 if self
785 .pending_control_type
786 .is_some_and(|(id, _)| id == handle.id)
787 {
788 self.pending_control_type = None;
789 }
790 self.events.push_back(CemEvent::Nacked {
791 handle,
792 status,
793 diagnostic: diagnostic.clone(),
794 consequence,
795 });
796 if consequence == Consequence::Disconnect {
797 self.close_with(CloseReason::PermanentError(
798 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
799 ));
800 }
801 }
802 AckOutcome::TimedOut(handle) => {
803 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
804 self.events.push_back(CemEvent::AckTimedOut(handle));
805 }
806 AckOutcome::Unmatched { subject, status } => {
807 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
808 self.events
809 .push_back(CemEvent::UnmatchedAck { subject, status });
810 }
811 }
812 }
813
814 pub fn handle_timeout(&mut self, now: Timestamp) {
816 for handle in self.core.acks.expire(now) {
817 if self
818 .pending_control_type
819 .is_some_and(|(id, _)| id == handle.id)
820 {
821 self.pending_control_type = None;
822 }
823 self.events.push_back(CemEvent::AckTimedOut(handle));
824 }
825 for message in self.core.registry.activate_due(now) {
826 self.events.push_back(CemEvent::DescriptionActivated {
827 kind: message.kind(),
828 });
829 }
830 }
831
832 pub fn transport_closed(&mut self, now: Timestamp) {
834 let _ = now;
835 self.close_with(CloseReason::TransportClosed);
836 }
837
838 pub fn select_control_type(
843 &mut self,
844 control_type: ControlType,
845 now: Timestamp,
846 ) -> Result<MessageHandle, SendError> {
847 let message_id = self.core.next_message_id();
848 let handle = self.send(
849 SelectControlType {
850 message_id,
851 control_type,
852 },
853 now,
854 )?;
855 self.pending_control_type = Some((handle.id, control_type));
856 Ok(handle)
857 }
858
859 pub fn instruct(
861 &mut self,
862 instruction: impl Into<Message>,
863 now: Timestamp,
864 ) -> Result<MessageHandle, SendError> {
865 let message = instruction.into();
866 if self.config.enforce_transitions {
867 let seen = self.core.acks.seen_ids();
868 let explanation = {
869 let ctx = self.core.registry.context(
870 self.core.profile,
871 EnergyManagementRole::Cem,
872 self.core.state.phase(),
873 self.core.s2_connect,
874 now,
875 &seen,
876 self.core.skew_tolerance,
877 );
878 crate::model::explain(&message, &ctx)
879 };
880 if let Some(explanation) = explanation.filter(|e| !e.is_actionable()) {
885 let (rule, reason) = if let Some((timer, label)) = explanation.blocked_by.first() {
886 (
887 rules::BLOCKED_BY_TIMER,
888 alloc::format!(
889 "{} {timer} has not finished, and it blocks this transition",
890 label.as_deref().unwrap_or("timer")
891 ),
892 )
893 } else {
894 (
895 rules::ABNORMAL_ONLY,
896 "this instruction uses an option marked abnormal_condition_only without setting abnormal_condition"
897 .to_string(),
898 )
899 };
900 let mut report = Report::new();
901 report.push(rule, "", reason);
902 if let Some(violation) = report.violations().first() {
903 return Err(SendError::Invalid(Box::new(violation.clone())));
904 }
905 }
906 }
907 self.send(message, now)
908 }
909
910 pub fn revoke(
912 &mut self,
913 object_type: RevokableObjects,
914 object_id: Id,
915 now: Timestamp,
916 ) -> Result<MessageHandle, SendError> {
917 let message_id = self.core.next_message_id();
918 let handle = self.send(
919 RevokeObject {
920 message_id,
921 object_type,
922 object_id,
923 },
924 now,
925 )?;
926 self.core.registry.revoke(object_type, object_id);
927 Ok(handle)
928 }
929
930 pub fn request_session(
932 &mut self,
933 request: SessionRequestType,
934 diagnostic: Option<String>,
935 now: Timestamp,
936 ) -> Result<MessageHandle, SendError> {
937 let message_id = self.core.next_message_id();
938 let handle = self.send(
939 SessionRequest {
940 message_id,
941 request,
942 diagnostic_label: diagnostic,
943 },
944 now,
945 )?;
946 self.close_with(CloseReason::LocallyRequested(request));
949 Ok(handle)
950 }
951
952 pub fn send(
954 &mut self,
955 message: impl Into<Message>,
956 now: Timestamp,
957 ) -> Result<MessageHandle, SendError> {
958 let message = message.into();
959 let kind = message.kind();
960 if self.core.state.is_closed() {
961 return Err(SendError::Closed);
962 }
963 if !kind.exists_in(self.core.profile) {
964 return Err(SendError::NotInProfile {
965 kind,
966 profile: self.core.profile,
967 });
968 }
969 let allowance =
970 crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Cem, kind);
971 if !allowance.is_allowed() {
972 return Err(SendError::NotAllowed {
973 kind,
974 state: state_name(&self.core.state),
975 });
976 }
977 if self.config.validate_outbound {
978 let seen = self.core.acks.seen_ids();
979 let report = {
980 let ctx = self.core.registry.context(
981 self.core.profile,
982 EnergyManagementRole::Cem,
983 self.core.state.phase(),
984 self.core.s2_connect,
985 now,
986 &seen,
987 self.core.skew_tolerance,
988 );
989 message.validate(&ctx)
990 };
991 if let Some(violation) = report.first_error() {
992 return Err(SendError::Invalid(Box::new(violation.clone())));
993 }
994 if !report.is_empty() {
995 self.core.stats.sent_with_warnings =
996 self.core.stats.sent_with_warnings.saturating_add(1);
997 self.events
998 .push_back(CemEvent::OutboundWarnings { kind, report });
999 }
1000 }
1001 self.core.transmit(message, now).ok_or(SendError::Closed)
1002 }
1003
1004 pub fn close(&mut self) {
1006 self.close_with(CloseReason::Local);
1007 }
1008
1009 fn close_with(&mut self, reason: CloseReason) {
1010 if self.core.state.is_closed() {
1011 return;
1012 }
1013 let reconnect_after = match &reason {
1014 CloseReason::Local => None,
1015 CloseReason::PeerRequested(SessionRequestType::Reconnect)
1018 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
1019 #[cfg(feature = "std")]
1024 _ => Some(self.backoff.delay_with(self.core.reconnect_attempt)),
1025 #[cfg(not(feature = "std"))]
1026 _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
1027 };
1028 self.core.state = SessionState::Closed(reason.clone());
1029 self.events.push_back(CemEvent::Closed {
1030 reason,
1031 reconnect_after,
1032 });
1033 }
1034}