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::{Inbound, InboundPolicy};
13use crate::codec::{self, Strictness};
14use crate::message::{Message, MessageKind};
15use crate::model::{Explanation, explain};
16use crate::types::common::{
17 Consequence, ControlType, EnergyManagementRole, Handshake, InstructionStatus,
18 InstructionStatusUpdate, ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
19 SessionRequest, SessionRequestType,
20};
21use crate::types::{Duration, Id, ProtocolVersion, Timestamp, WireProfile};
22use crate::validate::{Report, Validate, rules};
23
24#[derive(Debug, Clone)]
26#[non_exhaustive]
27pub struct RmConfig {
28 pub negotiation: Negotiation,
30 pub offered_versions: Vec<ProtocolVersion>,
35 pub ack_timeout: Duration,
39 pub out_of_order: OutOfOrderPolicy,
41 pub skew_tolerance: Duration,
43 pub max_message_bytes: usize,
45 pub strictness: Strictness,
47 pub s2_connect: bool,
50 pub validate_outbound: bool,
52 pub reconnect_attempt: u32,
60}
61
62impl Default for RmConfig {
63 fn default() -> Self {
64 Self {
65 negotiation: Negotiation::Handshake,
66 offered_versions: alloc::vec![ProtocolVersion::V1_0_0, ProtocolVersion::V0_0_2_BETA,],
67 ack_timeout: Duration::from_secs(5),
68 out_of_order: OutOfOrderPolicy::Report,
69 skew_tolerance: Duration::from_secs(30),
70 max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
71 strictness: Strictness::Strict,
72 s2_connect: false,
73 validate_outbound: true,
74 reconnect_attempt: 0,
75 }
76 }
77}
78
79impl RmConfig {
80 #[must_use]
86 pub fn without_outbound_validation(mut self) -> Self {
87 self.validate_outbound = false;
88 self
89 }
90
91 #[must_use]
93 pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
94 self.negotiation = Negotiation::PreNegotiated(profile);
95 self.s2_connect = true;
96 self
97 }
98
99 #[must_use]
101 pub fn offering(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
102 self.offered_versions = versions.into_iter().collect();
103 self
104 }
105
106 #[must_use]
108 pub fn strict_ordering(mut self) -> Self {
109 self.out_of_order = OutOfOrderPolicy::Close;
110 self
111 }
112
113 #[must_use]
115 pub fn ack_timeout(mut self, timeout: Duration) -> Self {
116 self.ack_timeout = timeout;
117 self
118 }
119
120 #[must_use]
126 pub const fn after_failed_attempts(mut self, attempts: u32) -> Self {
127 self.reconnect_attempt = attempts;
128 self
129 }
130}
131
132#[derive(Debug, Clone, PartialEq)]
140pub struct Instructed {
141 pub id: Id,
143 pub kind: MessageKind,
145 pub message: Message,
147 pub explanation: Explanation,
149}
150
151#[derive(Debug, Clone, PartialEq)]
153#[non_exhaustive]
154pub enum RmEvent {
155 Negotiated {
157 version: ProtocolVersion,
159 profile: WireProfile,
161 },
162 Ready {
164 control_type: ControlType,
166 },
167 Deselected,
169 Instruction(Box<Instructed>),
171 DescriptionActivated {
173 kind: MessageKind,
175 },
176 Acked(MessageHandle),
178 Nacked {
180 handle: MessageHandle,
182 status: ReceptionStatusValues,
184 diagnostic: Option<String>,
186 consequence: Consequence,
188 },
189 AckTimedOut(MessageHandle),
191 UnmatchedAck {
193 subject: Id,
195 status: ReceptionStatusValues,
197 },
198 Revoked {
200 object_type: RevokableObjects,
202 object_id: Id,
204 },
205 SessionRequested {
207 request: SessionRequestType,
209 diagnostic: Option<String>,
211 },
212 Refused {
214 kind: Option<MessageKind>,
216 status: ReceptionStatusValues,
218 report: Report,
220 },
221 Warnings {
223 kind: MessageKind,
225 report: Report,
227 },
228 OutboundWarnings {
237 kind: MessageKind,
239 report: Report,
241 },
242 Closed {
244 reason: CloseReason,
246 reconnect_after: Option<Duration>,
252 },
253}
254
255pub struct RmSession {
280 core: SessionCore,
281 details: ResourceManagerDetails,
282 config: RmConfig,
283 events: VecDeque<RmEvent>,
284 peer_versions: Vec<ProtocolVersion>,
285 negotiated: Option<ProtocolVersion>,
286 handshake_seen: bool,
287 policy: Option<Box<dyn InboundPolicy + Send>>,
288 backoff: Backoff,
289}
290
291impl core::fmt::Debug for RmSession {
292 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
293 f.debug_struct("RmSession")
294 .field("state", &self.core.state)
295 .field("profile", &self.core.profile)
296 .field("outstanding_acks", &self.core.acks.outstanding())
297 .field("queued", &self.core.outbox.len())
298 .finish_non_exhaustive()
299 }
300}
301
302impl RmSession {
303 #[must_use]
305 pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
306 let core = SessionCore::new(CoreConfig {
307 role: EnergyManagementRole::Rm,
308 negotiation: config.negotiation.clone(),
309 ack_timeout: config.ack_timeout,
310 out_of_order: config.out_of_order,
311 skew_tolerance: config.skew_tolerance,
312 max_message_bytes: config.max_message_bytes,
313 strictness: config.strictness,
314 s2_connect: config.s2_connect,
315 reconnect_attempt: config.reconnect_attempt,
316 });
317 Self {
318 core,
319 details,
320 config,
321 events: VecDeque::new(),
322 peer_versions: Vec::new(),
323 negotiated: None,
324 handshake_seen: false,
325 policy: None,
326 backoff: Backoff::default(),
327 }
328 }
329
330 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
336 self.policy = Some(policy);
337 }
338
339 #[must_use]
341 pub fn state(&self) -> &SessionState {
342 &self.core.state
343 }
344
345 #[must_use]
347 pub fn profile(&self) -> WireProfile {
348 self.core.profile
349 }
350
351 #[must_use]
358 pub fn negotiated_version(&self) -> Option<&ProtocolVersion> {
359 self.negotiated.as_ref()
360 }
361
362 #[must_use]
366 pub fn stats(&self) -> super::core::Stats {
367 self.core.stats
368 }
369
370 #[must_use]
372 pub fn registry(&self) -> &super::core::Registry {
373 &self.core.registry
374 }
375
376 pub fn open(&mut self, now: Timestamp) {
382 if !matches!(self.core.state, SessionState::Idle) {
383 return;
384 }
385 match &self.config.negotiation {
386 Negotiation::Handshake => {
387 let handshake = Handshake {
388 message_id: self.core.next_message_id(),
389 role: EnergyManagementRole::Rm,
390 supported_protocol_versions: Some(self.config.offered_versions.clone()),
391 };
392 self.core.state = SessionState::Handshaking;
393 self.core.transmit(Message::from(handshake), now);
394 }
395 Negotiation::PreNegotiated(profile) => {
396 let profile = *profile;
397 self.core.profile = profile;
398 self.negotiated = Some(profile.version());
399 self.core.state = SessionState::Connected;
400 self.events.push_back(RmEvent::Negotiated {
401 version: profile.version(),
402 profile,
403 });
404 self.send_details(now);
405 }
406 }
407 }
408
409 fn send_details(&mut self, now: Timestamp) {
410 let mut details = self.details.clone();
411 details.message_id = self.core.next_message_id();
412 self.core.transmit(Message::from(details), now);
413 }
414
415 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
417 self.core.poll_transmit()
418 }
419
420 pub fn poll_event(&mut self) -> Option<RmEvent> {
422 self.events.pop_front()
423 }
424
425 #[must_use]
427 pub fn poll_timeout(&self) -> Option<Timestamp> {
428 self.core.poll_timeout()
429 }
430
431 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
439 if self.core.state.is_closed() {
440 let peek = crate::codec::peek(text).ok();
441 return Inbound {
442 kind: peek.as_ref().and_then(|p| p.kind),
443 message_id: peek.and_then(|p| p.message_id),
444 status: ReceptionStatusValues::Ok,
445 report: Report::new(),
446 };
447 }
448 self.core.stats.received = self.core.stats.received.saturating_add(1);
449 let options = self.core.decode_options();
450 match codec::decode_with(text, &options) {
451 Ok(decoded) => {
452 if !decoded.pruned.is_empty() {
453 let mut report = Report::new();
454 for path in &decoded.pruned {
455 report.push(
456 rules::UNKNOWN_PROPERTY,
457 path,
458 "property is not defined by the schema and was removed",
459 );
460 }
461 self.events.push_back(RmEvent::Warnings {
462 kind: decoded.message.kind(),
463 report,
464 });
465 }
466 self.handle_message(decoded.message, now)
467 }
468 Err(error) => {
469 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
470 let kind = error.peek().and_then(|p| p.kind);
471 let status = error.reception_status();
472 if kind != Some(MessageKind::ReceptionStatus) {
475 self.core.acknowledge(
476 status.subject_message_id,
477 status.status,
478 status.diagnostic_label.clone(),
479 now,
480 );
481 }
482 let mut report = Report::new();
483 report.push(rules::DECODE_FAILED, "", error.to_string());
484 self.events.push_back(RmEvent::Refused {
485 kind,
486 status: status.status,
487 report: report.clone(),
488 });
489 Inbound {
490 kind,
491 message_id: error.peek().and_then(|p| p.message_id),
492 status: status.status,
493 report,
494 }
495 }
496 }
497 }
498
499 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
501 if self.core.state.is_closed() {
502 return Inbound::ignored(message.kind(), message.id());
503 }
504
505 if let Message::ReceptionStatus(status) = &message {
507 self.on_reception_status(status, now);
508 return Inbound {
509 kind: Some(MessageKind::ReceptionStatus),
510 message_id: None,
511 status: ReceptionStatusValues::Ok,
512 report: Report::new(),
513 };
514 }
515
516 let kind = message.kind();
517 let Some(id) = message.id() else {
518 return Inbound::ignored(kind, None);
519 };
520
521 if let Some(previous) = self.core.acks.previous_answer(id) {
524 self.core.acknowledge(id, previous, None, now);
528 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
529 let mut report = Report::new();
530 report.push_related(
531 rules::DUPLICATE_MESSAGE_ID,
532 "/message_id",
533 alloc::format!("{id} was already answered {previous:?}; not processed again"),
534 [id],
535 );
536 self.events.push_back(RmEvent::Warnings {
537 kind,
538 report: report.clone(),
539 });
540 return Inbound {
541 kind: Some(kind),
542 message_id: Some(id),
543 status: previous,
544 report,
545 };
546 }
547
548 let seen = self.core.acks.seen_ids();
549 let report = {
550 let ctx = self.core.registry.context(
551 self.core.profile,
552 EnergyManagementRole::Cem,
553 self.core.state.phase(),
554 self.core.s2_connect,
555 now,
556 &seen,
557 self.core.skew_tolerance,
558 );
559 message.validate(&ctx)
560 };
561
562 if report.has_errors() {
563 let status = ReceptionStatusValues::InvalidContent;
564 self.core
565 .acknowledge(id, status, report.diagnostic_label(), now);
566 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
567 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
568 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
569 self.events.push_back(RmEvent::Refused {
570 kind: Some(kind),
571 status,
572 report: report.clone(),
573 });
574 if closing {
575 let reason = CloseReason::ProtocolError(
576 report
577 .diagnostic_label()
578 .unwrap_or_else(|| "out of order".to_string()),
579 );
580 self.close_with(reason);
581 }
582 return Inbound {
583 kind: Some(kind),
584 message_id: Some(id),
585 status,
586 report,
587 };
588 }
589
590 let policy = self
592 .policy
593 .as_mut()
594 .and_then(|policy| policy.review(&message));
595 if let Some((status, diagnostic)) = policy {
596 self.core
597 .acknowledge(id, status, Some(diagnostic.clone()), now);
598 let mut refusal = report.clone();
599 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
600 self.events.push_back(RmEvent::Refused {
601 kind: Some(kind),
602 status,
603 report: refusal,
604 });
605 return Inbound {
606 kind: Some(kind),
607 message_id: Some(id),
608 status,
609 report,
610 };
611 }
612
613 self.core
614 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
615 if !report.is_empty() {
616 self.core.stats.accepted_with_warnings =
617 self.core.stats.accepted_with_warnings.saturating_add(1);
618 self.events.push_back(RmEvent::Warnings {
619 kind,
620 report: report.clone(),
621 });
622 }
623 self.process(message, now);
624 Inbound {
625 kind: Some(kind),
626 message_id: Some(id),
627 status: ReceptionStatusValues::Ok,
628 report,
629 }
630 }
631
632 fn process(&mut self, message: Message, now: Timestamp) {
634 if self.core.s2_connect
639 && matches!(
640 message,
641 Message::Handshake(_) | Message::HandshakeResponse(_)
642 )
643 {
644 return;
645 }
646 match &message {
647 Message::Handshake(h) => {
648 self.handshake_seen = true;
649 if let Some(versions) = &h.supported_protocol_versions {
650 self.peer_versions.clone_from(versions);
651 }
652 }
653 Message::HandshakeResponse(response) => {
654 let selected = response.selected_protocol_version.clone();
655 if !self
660 .config
661 .offered_versions
662 .iter()
663 .any(|offered| offered.matches(&selected))
664 {
665 self.close_with(CloseReason::UnsupportedVersion { selected });
666 return;
667 }
668 let Some(profile) = selected.wire_profile() else {
669 self.close_with(CloseReason::UnsupportedVersion { selected });
670 return;
671 };
672 self.core.profile = profile;
673 self.negotiated = Some(selected.clone());
674 self.core.state = SessionState::Connected;
675 self.events.push_back(RmEvent::Negotiated {
676 version: selected,
677 profile,
678 });
679 self.send_details(now);
680 }
681 Message::SelectControlType(select) => {
682 let control_type = select.control_type;
683 if control_type == ControlType::NoSelection {
684 self.core.state = SessionState::Connected;
685 self.events.push_back(RmEvent::Deselected);
686 } else {
687 self.core.state = SessionState::ControlTypeSelected(control_type);
688 self.events.push_back(RmEvent::Ready { control_type });
689 }
690 }
691 Message::SessionRequest(request) => {
692 self.events.push_back(RmEvent::SessionRequested {
693 request: request.request,
694 diagnostic: request.diagnostic_label.clone(),
695 });
696 self.close_with(CloseReason::PeerRequested(request.request));
697 return;
698 }
699 Message::RevokeObject(revoke) => {
700 self.core
701 .registry
702 .revoke(revoke.object_type, revoke.object_id);
703 self.events.push_back(RmEvent::Revoked {
704 object_type: revoke.object_type,
705 object_id: revoke.object_id,
706 });
707 return;
708 }
709 _ => {}
710 }
711
712 self.core.registry.record(&message, Some(now));
713
714 if let Some(id) = message.instruction_id() {
715 let seen = self.core.acks.seen_ids();
716 let explanation = {
717 let ctx = self.core.registry.context(
718 self.core.profile,
719 EnergyManagementRole::Cem,
720 self.core.state.phase(),
721 self.core.s2_connect,
722 now,
723 &seen,
724 self.core.skew_tolerance,
725 );
726 explain(&message, &ctx)
727 };
728 if let Some(explanation) = explanation {
729 self.events
730 .push_back(RmEvent::Instruction(Box::new(Instructed {
731 id,
732 kind: message.kind(),
733 message,
734 explanation,
735 })));
736 }
737 }
738 }
739
740 fn on_reception_status(
741 &mut self,
742 status: &crate::types::common::ReceptionStatus,
743 now: Timestamp,
744 ) {
745 match self.core.acks.received(status, now) {
746 AckOutcome::Accepted { handle, latency } => {
747 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
748 self.core.stats.record_latency(latency);
749 self.events.push_back(RmEvent::Acked(handle));
750 }
751 AckOutcome::Refused {
752 handle,
753 status,
754 diagnostic,
755 consequence,
756 latency,
757 } => {
758 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
759 self.core.stats.record_latency(latency);
760 self.events.push_back(RmEvent::Nacked {
761 handle,
762 status,
763 diagnostic: diagnostic.clone(),
764 consequence,
765 });
766 if consequence == Consequence::Disconnect {
767 self.close_with(CloseReason::PermanentError(
768 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
769 ));
770 }
771 }
772 AckOutcome::TimedOut(handle) => {
773 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
774 self.events.push_back(RmEvent::AckTimedOut(handle));
775 }
776 AckOutcome::Unmatched { subject, status } => {
777 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
778 self.events
779 .push_back(RmEvent::UnmatchedAck { subject, status });
780 }
781 }
782 }
783
784 pub fn handle_timeout(&mut self, now: Timestamp) {
786 for handle in self.core.acks.expire(now) {
787 self.events.push_back(RmEvent::AckTimedOut(handle));
788 }
789 for message in self.core.registry.activate_due(now) {
790 self.events.push_back(RmEvent::DescriptionActivated {
791 kind: message.kind(),
792 });
793 }
794 }
795
796 pub fn transport_closed(&mut self, now: Timestamp) {
798 let _ = now;
799 self.close_with(CloseReason::TransportClosed);
800 }
801
802 pub fn send(
808 &mut self,
809 message: impl Into<Message>,
810 now: Timestamp,
811 ) -> Result<MessageHandle, SendError> {
812 let message = message.into();
813 let kind = message.kind();
814 if self.core.state.is_closed() {
815 return Err(SendError::Closed);
816 }
817 if !kind.exists_in(self.core.profile) {
818 return Err(SendError::NotInProfile {
819 kind,
820 profile: self.core.profile,
821 });
822 }
823 let allowance =
824 crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Rm, kind);
825 if !allowance.is_allowed() {
826 return Err(SendError::NotAllowed {
827 kind,
828 state: state_name(&self.core.state),
829 });
830 }
831 if self.config.validate_outbound {
832 let seen = self.core.acks.seen_ids();
833 let report = {
834 let ctx = self.core.registry.context(
835 self.core.profile,
836 EnergyManagementRole::Rm,
837 self.core.state.phase(),
838 self.core.s2_connect,
839 now,
840 &seen,
841 self.core.skew_tolerance,
842 );
843 message.validate(&ctx)
844 };
845 if let Some(violation) = report.first_error() {
846 return Err(SendError::Invalid(Box::new(violation.clone())));
847 }
848 if !report.is_empty() {
849 self.core.stats.sent_with_warnings =
850 self.core.stats.sent_with_warnings.saturating_add(1);
851 self.events
852 .push_back(RmEvent::OutboundWarnings { kind, report });
853 }
854 }
855 self.core.transmit(message, now).ok_or(SendError::Closed)
856 }
857
858 pub fn instruction_status(
863 &mut self,
864 instruction_id: Id,
865 status: InstructionStatus,
866 now: Timestamp,
867 ) -> Result<MessageHandle, SendError> {
868 let message_id = self.core.next_message_id();
869 self.send(
870 InstructionStatusUpdate {
871 message_id,
872 instruction_id,
873 status_type: status,
874 timestamp: now,
875 },
876 now,
877 )
878 }
879
880 pub fn request_session(
882 &mut self,
883 request: SessionRequestType,
884 diagnostic: Option<String>,
885 now: Timestamp,
886 ) -> Result<MessageHandle, SendError> {
887 let message_id = self.core.next_message_id();
888 let handle = self.send(
889 SessionRequest {
890 message_id,
891 request,
892 diagnostic_label: diagnostic,
893 },
894 now,
895 )?;
896 self.close_with(CloseReason::LocallyRequested(request));
899 Ok(handle)
900 }
901
902 pub fn close(&mut self) {
904 self.close_with(CloseReason::Local);
905 }
906
907 fn close_with(&mut self, reason: CloseReason) {
908 if self.core.state.is_closed() {
909 return;
910 }
911 let reconnect_after = match &reason {
912 CloseReason::Local => None,
914 CloseReason::PeerRequested(SessionRequestType::Reconnect)
917 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
918 #[cfg(feature = "std")]
923 _ => Some(self.backoff.delay_with(self.core.reconnect_attempt)),
924 #[cfg(not(feature = "std"))]
925 _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
926 };
927 self.core.state = SessionState::Closed(reason.clone());
928 self.events.push_back(RmEvent::Closed {
929 reason,
930 reconnect_after,
931 });
932 }
933}
934
935pub(crate) fn state_name(state: &SessionState) -> &'static str {
936 match state {
937 SessionState::Idle => "idle",
938 SessionState::Handshaking => "handshaking",
939 SessionState::Connected => "connected",
940 SessionState::ControlTypeSelected(_) => "control type selected",
941 SessionState::Closed(_) => "closed",
942 }
943}