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>,
248 },
249}
250
251pub struct RmSession {
276 core: SessionCore,
277 details: ResourceManagerDetails,
278 config: RmConfig,
279 events: VecDeque<RmEvent>,
280 peer_versions: Vec<ProtocolVersion>,
281 negotiated: Option<ProtocolVersion>,
282 handshake_seen: bool,
283 policy: Option<Box<dyn InboundPolicy + Send>>,
284 backoff: Backoff,
285}
286
287impl core::fmt::Debug for RmSession {
288 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289 f.debug_struct("RmSession")
290 .field("state", &self.core.state)
291 .field("profile", &self.core.profile)
292 .field("outstanding_acks", &self.core.acks.outstanding())
293 .field("queued", &self.core.outbox.len())
294 .finish_non_exhaustive()
295 }
296}
297
298impl RmSession {
299 #[must_use]
301 pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
302 let core = SessionCore::new(CoreConfig {
303 role: EnergyManagementRole::Rm,
304 negotiation: config.negotiation.clone(),
305 ack_timeout: config.ack_timeout,
306 out_of_order: config.out_of_order,
307 skew_tolerance: config.skew_tolerance,
308 max_message_bytes: config.max_message_bytes,
309 strictness: config.strictness,
310 s2_connect: config.s2_connect,
311 reconnect_attempt: config.reconnect_attempt,
312 });
313 Self {
314 core,
315 details,
316 config,
317 events: VecDeque::new(),
318 peer_versions: Vec::new(),
319 negotiated: None,
320 handshake_seen: false,
321 policy: None,
322 backoff: Backoff::default(),
323 }
324 }
325
326 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
332 self.policy = Some(policy);
333 }
334
335 #[must_use]
337 pub fn state(&self) -> &SessionState {
338 &self.core.state
339 }
340
341 #[must_use]
343 pub fn profile(&self) -> WireProfile {
344 self.core.profile
345 }
346
347 #[must_use]
351 pub fn stats(&self) -> super::core::Stats {
352 self.core.stats
353 }
354
355 #[must_use]
357 pub fn registry(&self) -> &super::core::Registry {
358 &self.core.registry
359 }
360
361 pub fn open(&mut self, now: Timestamp) {
367 if !matches!(self.core.state, SessionState::Idle) {
368 return;
369 }
370 match &self.config.negotiation {
371 Negotiation::Handshake => {
372 let handshake = Handshake {
373 message_id: self.core.next_message_id(),
374 role: EnergyManagementRole::Rm,
375 supported_protocol_versions: Some(self.config.offered_versions.clone()),
376 };
377 self.core.state = SessionState::Handshaking;
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(RmEvent::Negotiated {
386 version: profile.version(),
387 profile,
388 });
389 self.send_details(now);
390 }
391 }
392 }
393
394 fn send_details(&mut self, now: Timestamp) {
395 let mut details = self.details.clone();
396 details.message_id = self.core.next_message_id();
397 self.core.transmit(Message::from(details), now);
398 }
399
400 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
402 self.core.poll_transmit()
403 }
404
405 pub fn poll_event(&mut self) -> Option<RmEvent> {
407 self.events.pop_front()
408 }
409
410 #[must_use]
412 pub fn poll_timeout(&self) -> Option<Timestamp> {
413 self.core.poll_timeout()
414 }
415
416 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
424 if self.core.state.is_closed() {
425 return Inbound {
426 kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
427 status: ReceptionStatusValues::Ok,
428 report: Report::new(),
429 };
430 }
431 self.core.stats.received = self.core.stats.received.saturating_add(1);
432 let options = self.core.decode_options();
433 match codec::decode_with(text, &options) {
434 Ok(decoded) => {
435 if !decoded.pruned.is_empty() {
436 let mut report = Report::new();
437 for path in &decoded.pruned {
438 report.push(
439 rules::UNKNOWN_PROPERTY,
440 path,
441 "property is not defined by the schema and was removed",
442 );
443 }
444 self.events.push_back(RmEvent::Warnings {
445 kind: decoded.message.kind(),
446 report,
447 });
448 }
449 self.handle_message(decoded.message, now)
450 }
451 Err(error) => {
452 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
453 let kind = error.peek().and_then(|p| p.kind);
454 let status = error.reception_status();
455 if kind != Some(MessageKind::ReceptionStatus) {
458 self.core.acknowledge(
459 status.subject_message_id,
460 status.status,
461 status.diagnostic_label.clone(),
462 now,
463 );
464 }
465 let mut report = Report::new();
466 report.push(rules::DECODE_FAILED, "", error.to_string());
467 self.events.push_back(RmEvent::Refused {
468 kind,
469 status: status.status,
470 report: report.clone(),
471 });
472 Inbound {
473 kind,
474 status: status.status,
475 report,
476 }
477 }
478 }
479 }
480
481 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
483 if self.core.state.is_closed() {
484 return Inbound::ignored(message.kind());
485 }
486
487 if let Message::ReceptionStatus(status) = &message {
489 self.on_reception_status(status, now);
490 return Inbound {
491 kind: Some(MessageKind::ReceptionStatus),
492 status: ReceptionStatusValues::Ok,
493 report: Report::new(),
494 };
495 }
496
497 let kind = message.kind();
498 let Some(id) = message.id() else {
499 return Inbound::ignored(kind);
500 };
501
502 if let Some(previous) = self.core.acks.previous_answer(id) {
505 self.core.acknowledge(id, previous, None, now);
509 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
510 let mut report = Report::new();
511 report.push_related(
512 rules::DUPLICATE_MESSAGE_ID,
513 "/message_id",
514 alloc::format!("{id} was already answered {previous:?}; not processed again"),
515 [id],
516 );
517 self.events.push_back(RmEvent::Warnings {
518 kind,
519 report: report.clone(),
520 });
521 return Inbound {
522 kind: Some(kind),
523 status: previous,
524 report,
525 };
526 }
527
528 let seen = self.core.acks.seen_ids();
529 let report = {
530 let ctx = self.core.registry.context(
531 self.core.profile,
532 EnergyManagementRole::Cem,
533 self.core.state.phase(),
534 self.core.s2_connect,
535 now,
536 &seen,
537 self.core.skew_tolerance,
538 );
539 message.validate(&ctx)
540 };
541
542 if report.has_errors() {
543 let status = ReceptionStatusValues::InvalidContent;
544 self.core
545 .acknowledge(id, status, report.diagnostic_label(), now);
546 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
547 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
548 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
549 self.events.push_back(RmEvent::Refused {
550 kind: Some(kind),
551 status,
552 report: report.clone(),
553 });
554 if closing {
555 let reason = CloseReason::ProtocolError(
556 report
557 .diagnostic_label()
558 .unwrap_or_else(|| "out of order".to_string()),
559 );
560 self.close_with(reason);
561 }
562 return Inbound {
563 kind: Some(kind),
564 status,
565 report,
566 };
567 }
568
569 let policy = self
571 .policy
572 .as_mut()
573 .and_then(|policy| policy.review(&message));
574 if let Some((status, diagnostic)) = policy {
575 self.core
576 .acknowledge(id, status, Some(diagnostic.clone()), now);
577 let mut refusal = report.clone();
578 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
579 self.events.push_back(RmEvent::Refused {
580 kind: Some(kind),
581 status,
582 report: refusal,
583 });
584 return Inbound {
585 kind: Some(kind),
586 status,
587 report,
588 };
589 }
590
591 self.core
592 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
593 if !report.is_empty() {
594 self.core.stats.accepted_with_warnings =
595 self.core.stats.accepted_with_warnings.saturating_add(1);
596 self.events.push_back(RmEvent::Warnings {
597 kind,
598 report: report.clone(),
599 });
600 }
601 self.process(message, now);
602 Inbound {
603 kind: Some(kind),
604 status: ReceptionStatusValues::Ok,
605 report,
606 }
607 }
608
609 fn process(&mut self, message: Message, now: Timestamp) {
611 match &message {
612 Message::Handshake(h) => {
613 self.handshake_seen = true;
614 if let Some(versions) = &h.supported_protocol_versions {
615 self.peer_versions.clone_from(versions);
616 }
617 }
618 Message::HandshakeResponse(response) => {
619 let selected = response.selected_protocol_version.clone();
620 if !self
625 .config
626 .offered_versions
627 .iter()
628 .any(|offered| offered.matches(&selected))
629 {
630 self.close_with(CloseReason::UnsupportedVersion { selected });
631 return;
632 }
633 let Some(profile) = selected.wire_profile() else {
634 self.close_with(CloseReason::UnsupportedVersion { selected });
635 return;
636 };
637 self.core.profile = profile;
638 self.negotiated = Some(selected.clone());
639 self.core.state = SessionState::Connected;
640 self.events.push_back(RmEvent::Negotiated {
641 version: selected,
642 profile,
643 });
644 self.send_details(now);
645 }
646 Message::SelectControlType(select) => {
647 let control_type = select.control_type;
648 if control_type == ControlType::NoSelection {
649 self.core.state = SessionState::Connected;
650 self.events.push_back(RmEvent::Deselected);
651 } else {
652 self.core.state = SessionState::ControlTypeSelected(control_type);
653 self.events.push_back(RmEvent::Ready { control_type });
654 }
655 }
656 Message::SessionRequest(request) => {
657 self.events.push_back(RmEvent::SessionRequested {
658 request: request.request,
659 diagnostic: request.diagnostic_label.clone(),
660 });
661 self.close_with(CloseReason::PeerRequested(request.request));
662 return;
663 }
664 Message::RevokeObject(revoke) => {
665 self.core
666 .registry
667 .revoke(revoke.object_type, revoke.object_id);
668 self.events.push_back(RmEvent::Revoked {
669 object_type: revoke.object_type,
670 object_id: revoke.object_id,
671 });
672 return;
673 }
674 _ => {}
675 }
676
677 self.core.registry.record(&message, Some(now));
678
679 if let Some(id) = message.instruction_id() {
680 let seen = self.core.acks.seen_ids();
681 let explanation = {
682 let ctx = self.core.registry.context(
683 self.core.profile,
684 EnergyManagementRole::Cem,
685 self.core.state.phase(),
686 self.core.s2_connect,
687 now,
688 &seen,
689 self.core.skew_tolerance,
690 );
691 explain(&message, &ctx)
692 };
693 if let Some(explanation) = explanation {
694 self.events
695 .push_back(RmEvent::Instruction(Box::new(Instructed {
696 id,
697 kind: message.kind(),
698 message,
699 explanation,
700 })));
701 }
702 }
703 }
704
705 fn on_reception_status(
706 &mut self,
707 status: &crate::types::common::ReceptionStatus,
708 now: Timestamp,
709 ) {
710 match self.core.acks.received(status, now) {
711 AckOutcome::Accepted { handle, latency } => {
712 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
713 self.core.stats.record_latency(latency);
714 self.events.push_back(RmEvent::Acked(handle));
715 }
716 AckOutcome::Refused {
717 handle,
718 status,
719 diagnostic,
720 consequence,
721 latency,
722 } => {
723 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
724 self.core.stats.record_latency(latency);
725 self.events.push_back(RmEvent::Nacked {
726 handle,
727 status,
728 diagnostic: diagnostic.clone(),
729 consequence,
730 });
731 if consequence == Consequence::Disconnect {
732 self.close_with(CloseReason::PermanentError(
733 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
734 ));
735 }
736 }
737 AckOutcome::TimedOut(handle) => {
738 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
739 self.events.push_back(RmEvent::AckTimedOut(handle));
740 }
741 AckOutcome::Unmatched { subject, status } => {
742 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
743 self.events
744 .push_back(RmEvent::UnmatchedAck { subject, status });
745 }
746 }
747 }
748
749 pub fn handle_timeout(&mut self, now: Timestamp) {
751 for handle in self.core.acks.expire(now) {
752 self.events.push_back(RmEvent::AckTimedOut(handle));
753 }
754 for message in self.core.registry.activate_due(now) {
755 self.events.push_back(RmEvent::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 send(
773 &mut self,
774 message: impl Into<Message>,
775 now: Timestamp,
776 ) -> Result<MessageHandle, SendError> {
777 let message = message.into();
778 let kind = message.kind();
779 if self.core.state.is_closed() {
780 return Err(SendError::Closed);
781 }
782 if !kind.exists_in(self.core.profile) {
783 return Err(SendError::NotInProfile {
784 kind,
785 profile: self.core.profile,
786 });
787 }
788 let allowance =
789 crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Rm, kind);
790 if !allowance.is_allowed() {
791 return Err(SendError::NotAllowed {
792 kind,
793 state: state_name(&self.core.state),
794 });
795 }
796 if self.config.validate_outbound {
797 let seen = self.core.acks.seen_ids();
798 let report = {
799 let ctx = self.core.registry.context(
800 self.core.profile,
801 EnergyManagementRole::Rm,
802 self.core.state.phase(),
803 self.core.s2_connect,
804 now,
805 &seen,
806 self.core.skew_tolerance,
807 );
808 message.validate(&ctx)
809 };
810 if let Some(violation) = report.first_error() {
811 return Err(SendError::Invalid(Box::new(violation.clone())));
812 }
813 if !report.is_empty() {
814 self.core.stats.sent_with_warnings =
815 self.core.stats.sent_with_warnings.saturating_add(1);
816 self.events
817 .push_back(RmEvent::OutboundWarnings { kind, report });
818 }
819 }
820 self.core.transmit(message, now).ok_or(SendError::Closed)
821 }
822
823 pub fn instruction_status(
828 &mut self,
829 instruction_id: Id,
830 status: InstructionStatus,
831 now: Timestamp,
832 ) -> Result<MessageHandle, SendError> {
833 let message_id = self.core.next_message_id();
834 self.send(
835 InstructionStatusUpdate {
836 message_id,
837 instruction_id,
838 status_type: status,
839 timestamp: now,
840 },
841 now,
842 )
843 }
844
845 pub fn request_session(
847 &mut self,
848 request: SessionRequestType,
849 diagnostic: Option<String>,
850 now: Timestamp,
851 ) -> Result<MessageHandle, SendError> {
852 let message_id = self.core.next_message_id();
853 let handle = self.send(
854 SessionRequest {
855 message_id,
856 request,
857 diagnostic_label: diagnostic,
858 },
859 now,
860 )?;
861 self.close_with(CloseReason::LocallyRequested(request));
864 Ok(handle)
865 }
866
867 pub fn close(&mut self) {
869 self.close_with(CloseReason::Local);
870 }
871
872 fn close_with(&mut self, reason: CloseReason) {
873 if self.core.state.is_closed() {
874 return;
875 }
876 let reconnect_after = match &reason {
877 CloseReason::Local => None,
879 CloseReason::PeerRequested(SessionRequestType::Reconnect)
882 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
883 _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
884 };
885 self.core.state = SessionState::Closed(reason.clone());
886 self.events.push_back(RmEvent::Closed {
887 reason,
888 reconnect_after,
889 });
890 }
891}
892
893pub(crate) fn state_name(state: &SessionState) -> &'static str {
894 match state {
895 SessionState::Idle => "idle",
896 SessionState::Handshaking => "handshaking",
897 SessionState::Connected => "connected",
898 SessionState::ControlTypeSelected(_) => "control type selected",
899 SessionState::Closed(_) => "closed",
900 }
901}