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![
67 ProtocolVersion::new(ProtocolVersion::V1_0_0),
68 ProtocolVersion::new(ProtocolVersion::V0_0_2_BETA),
69 ],
70 ack_timeout: Duration::from_secs(5),
71 out_of_order: OutOfOrderPolicy::Report,
72 skew_tolerance: Duration::from_secs(30),
73 max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
74 strictness: Strictness::Strict,
75 s2_connect: false,
76 validate_outbound: true,
77 reconnect_attempt: 0,
78 }
79 }
80}
81
82impl RmConfig {
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 offering(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
105 self.offered_versions = versions.into_iter().collect();
106 self
107 }
108
109 #[must_use]
111 pub fn strict_ordering(mut self) -> Self {
112 self.out_of_order = OutOfOrderPolicy::Close;
113 self
114 }
115
116 #[must_use]
118 pub fn ack_timeout(mut self, timeout: Duration) -> Self {
119 self.ack_timeout = timeout;
120 self
121 }
122
123 #[must_use]
129 pub const fn after_failed_attempts(mut self, attempts: u32) -> Self {
130 self.reconnect_attempt = attempts;
131 self
132 }
133}
134
135#[derive(Debug, Clone, PartialEq)]
143pub struct Instructed {
144 pub id: Id,
146 pub kind: MessageKind,
148 pub message: Message,
150 pub explanation: Explanation,
152}
153
154#[derive(Debug, Clone, PartialEq)]
156#[non_exhaustive]
157pub enum RmEvent {
158 Negotiated {
160 version: ProtocolVersion,
162 profile: WireProfile,
164 },
165 Ready {
167 control_type: ControlType,
169 },
170 Deselected,
172 Instruction(Box<Instructed>),
174 DescriptionActivated {
176 kind: MessageKind,
178 },
179 Acked(MessageHandle),
181 Nacked {
183 handle: MessageHandle,
185 status: ReceptionStatusValues,
187 diagnostic: Option<String>,
189 consequence: Consequence,
191 },
192 AckTimedOut(MessageHandle),
194 UnmatchedAck {
196 subject: Id,
198 status: ReceptionStatusValues,
200 },
201 Revoked {
203 object_type: RevokableObjects,
205 object_id: Id,
207 },
208 SessionRequested {
210 request: SessionRequestType,
212 diagnostic: Option<String>,
214 },
215 Refused {
217 kind: Option<MessageKind>,
219 status: ReceptionStatusValues,
221 report: Report,
223 },
224 Warnings {
226 kind: MessageKind,
228 report: Report,
230 },
231 OutboundWarnings {
240 kind: MessageKind,
242 report: Report,
244 },
245 Closed {
247 reason: CloseReason,
249 reconnect_after: Option<Duration>,
251 },
252}
253
254pub struct RmSession {
279 core: SessionCore,
280 details: ResourceManagerDetails,
281 config: RmConfig,
282 events: VecDeque<RmEvent>,
283 peer_versions: Vec<ProtocolVersion>,
284 negotiated: Option<ProtocolVersion>,
285 handshake_seen: bool,
286 policy: Option<Box<dyn InboundPolicy + Send>>,
287 backoff: Backoff,
288}
289
290impl core::fmt::Debug for RmSession {
291 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
292 f.debug_struct("RmSession")
293 .field("state", &self.core.state)
294 .field("profile", &self.core.profile)
295 .field("outstanding_acks", &self.core.acks.outstanding())
296 .field("queued", &self.core.outbox.len())
297 .finish_non_exhaustive()
298 }
299}
300
301impl RmSession {
302 #[must_use]
304 pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
305 let core = SessionCore::new(CoreConfig {
306 role: EnergyManagementRole::Rm,
307 negotiation: config.negotiation.clone(),
308 ack_timeout: config.ack_timeout,
309 out_of_order: config.out_of_order,
310 skew_tolerance: config.skew_tolerance,
311 max_message_bytes: config.max_message_bytes,
312 strictness: config.strictness,
313 s2_connect: config.s2_connect,
314 reconnect_attempt: config.reconnect_attempt,
315 });
316 Self {
317 core,
318 details,
319 config,
320 events: VecDeque::new(),
321 peer_versions: Vec::new(),
322 negotiated: None,
323 handshake_seen: false,
324 policy: None,
325 backoff: Backoff::default(),
326 }
327 }
328
329 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
335 self.policy = Some(policy);
336 }
337
338 #[must_use]
340 pub fn state(&self) -> &SessionState {
341 &self.core.state
342 }
343
344 #[must_use]
346 pub fn profile(&self) -> WireProfile {
347 self.core.profile
348 }
349
350 #[must_use]
354 pub fn stats(&self) -> super::core::Stats {
355 self.core.stats
356 }
357
358 #[must_use]
360 pub fn registry(&self) -> &super::core::Registry {
361 &self.core.registry
362 }
363
364 pub fn open(&mut self, now: Timestamp) {
370 if !matches!(self.core.state, SessionState::Idle) {
371 return;
372 }
373 match &self.config.negotiation {
374 Negotiation::Handshake => {
375 let handshake = Handshake {
376 message_id: self.core.next_message_id(),
377 role: EnergyManagementRole::Rm,
378 supported_protocol_versions: Some(self.config.offered_versions.clone()),
379 };
380 self.core.state = SessionState::Handshaking;
381 self.core.transmit(Message::from(handshake), now);
382 }
383 Negotiation::PreNegotiated(profile) => {
384 let profile = *profile;
385 self.core.profile = profile;
386 self.negotiated = Some(profile.version());
387 self.core.state = SessionState::Connected;
388 self.events.push_back(RmEvent::Negotiated {
389 version: profile.version(),
390 profile,
391 });
392 self.send_details(now);
393 }
394 }
395 }
396
397 fn send_details(&mut self, now: Timestamp) {
398 let mut details = self.details.clone();
399 details.message_id = self.core.next_message_id();
400 self.core.transmit(Message::from(details), now);
401 }
402
403 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
405 self.core.poll_transmit()
406 }
407
408 pub fn poll_event(&mut self) -> Option<RmEvent> {
410 self.events.pop_front()
411 }
412
413 #[must_use]
415 pub fn poll_timeout(&self) -> Option<Timestamp> {
416 self.core.poll_timeout()
417 }
418
419 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
427 if self.core.state.is_closed() {
428 return Inbound {
429 kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
430 status: ReceptionStatusValues::Ok,
431 report: Report::new(),
432 };
433 }
434 self.core.stats.received = self.core.stats.received.saturating_add(1);
435 let options = self.core.decode_options();
436 match codec::decode_with(text, &options) {
437 Ok(decoded) => {
438 if !decoded.pruned.is_empty() {
439 let mut report = Report::new();
440 for path in &decoded.pruned {
441 report.push(
442 rules::UNKNOWN_PROPERTY,
443 path,
444 "property is not defined by the schema and was removed",
445 );
446 }
447 self.events.push_back(RmEvent::Warnings {
448 kind: decoded.message.kind(),
449 report,
450 });
451 }
452 self.handle_message(decoded.message, now)
453 }
454 Err(error) => {
455 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
456 let kind = error.peek().and_then(|p| p.kind);
457 let status = error.reception_status();
458 if kind != Some(MessageKind::ReceptionStatus) {
461 self.core.acknowledge(
462 status.subject_message_id,
463 status.status,
464 status.diagnostic_label.clone(),
465 now,
466 );
467 }
468 let mut report = Report::new();
469 report.push(rules::DECODE_FAILED, "", error.to_string());
470 self.events.push_back(RmEvent::Refused {
471 kind,
472 status: status.status,
473 report: report.clone(),
474 });
475 Inbound {
476 kind,
477 status: status.status,
478 report,
479 }
480 }
481 }
482 }
483
484 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
486 if self.core.state.is_closed() {
487 return Inbound::ignored(message.kind());
488 }
489
490 if let Message::ReceptionStatus(status) = &message {
492 self.on_reception_status(status, now);
493 return Inbound {
494 kind: Some(MessageKind::ReceptionStatus),
495 status: ReceptionStatusValues::Ok,
496 report: Report::new(),
497 };
498 }
499
500 let kind = message.kind();
501 let Some(id) = message.id() else {
502 return Inbound::ignored(kind);
503 };
504
505 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(RmEvent::Warnings {
521 kind,
522 report: report.clone(),
523 });
524 return Inbound {
525 kind: Some(kind),
526 status: previous,
527 report,
528 };
529 }
530
531 let seen = self.core.acks.seen_ids();
532 let report = {
533 let ctx = self.core.registry.context(
534 self.core.profile,
535 EnergyManagementRole::Cem,
536 self.core.state.phase(),
537 self.core.s2_connect,
538 now,
539 &seen,
540 self.core.skew_tolerance,
541 );
542 message.validate(&ctx)
543 };
544
545 if report.has_errors() {
546 let status = ReceptionStatusValues::InvalidContent;
547 self.core
548 .acknowledge(id, status, report.diagnostic_label(), now);
549 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
550 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
551 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
552 self.events.push_back(RmEvent::Refused {
553 kind: Some(kind),
554 status,
555 report: report.clone(),
556 });
557 if closing {
558 let reason = CloseReason::ProtocolError(
559 report
560 .diagnostic_label()
561 .unwrap_or_else(|| "out of order".to_string()),
562 );
563 self.close_with(reason);
564 }
565 return Inbound {
566 kind: Some(kind),
567 status,
568 report,
569 };
570 }
571
572 let policy = self
574 .policy
575 .as_mut()
576 .and_then(|policy| policy.review(&message));
577 if let Some((status, diagnostic)) = policy {
578 self.core
579 .acknowledge(id, status, Some(diagnostic.clone()), now);
580 let mut refusal = report.clone();
581 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
582 self.events.push_back(RmEvent::Refused {
583 kind: Some(kind),
584 status,
585 report: refusal,
586 });
587 return Inbound {
588 kind: Some(kind),
589 status,
590 report,
591 };
592 }
593
594 self.core
595 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
596 if !report.is_empty() {
597 self.core.stats.accepted_with_warnings =
598 self.core.stats.accepted_with_warnings.saturating_add(1);
599 self.events.push_back(RmEvent::Warnings {
600 kind,
601 report: report.clone(),
602 });
603 }
604 self.process(message, now);
605 Inbound {
606 kind: Some(kind),
607 status: ReceptionStatusValues::Ok,
608 report,
609 }
610 }
611
612 fn process(&mut self, message: Message, now: Timestamp) {
614 match &message {
615 Message::Handshake(h) => {
616 self.handshake_seen = true;
617 if let Some(versions) = &h.supported_protocol_versions {
618 self.peer_versions.clone_from(versions);
619 }
620 }
621 Message::HandshakeResponse(response) => {
622 let selected = response.selected_protocol_version.clone();
623 if !self
628 .config
629 .offered_versions
630 .iter()
631 .any(|offered| offered.matches(&selected))
632 {
633 self.close_with(CloseReason::UnsupportedVersion { selected });
634 return;
635 }
636 let Some(profile) = selected.wire_profile() else {
637 self.close_with(CloseReason::UnsupportedVersion { selected });
638 return;
639 };
640 self.core.profile = profile;
641 self.negotiated = Some(selected.clone());
642 self.core.state = SessionState::Connected;
643 self.events.push_back(RmEvent::Negotiated {
644 version: selected,
645 profile,
646 });
647 self.send_details(now);
648 }
649 Message::SelectControlType(select) => {
650 let control_type = select.control_type;
651 if control_type == ControlType::NoSelection {
652 self.core.state = SessionState::Connected;
653 self.events.push_back(RmEvent::Deselected);
654 } else {
655 self.core.state = SessionState::ControlTypeSelected(control_type);
656 self.events.push_back(RmEvent::Ready { control_type });
657 }
658 }
659 Message::SessionRequest(request) => {
660 self.events.push_back(RmEvent::SessionRequested {
661 request: request.request,
662 diagnostic: request.diagnostic_label.clone(),
663 });
664 self.close_with(CloseReason::PeerRequested(request.request));
665 return;
666 }
667 Message::RevokeObject(revoke) => {
668 self.core
669 .registry
670 .revoke(revoke.object_type, revoke.object_id);
671 self.events.push_back(RmEvent::Revoked {
672 object_type: revoke.object_type,
673 object_id: revoke.object_id,
674 });
675 return;
676 }
677 _ => {}
678 }
679
680 self.core.registry.record(&message, Some(now));
681
682 if let Some(id) = message.instruction_id() {
683 let seen = self.core.acks.seen_ids();
684 let explanation = {
685 let ctx = self.core.registry.context(
686 self.core.profile,
687 EnergyManagementRole::Cem,
688 self.core.state.phase(),
689 self.core.s2_connect,
690 now,
691 &seen,
692 self.core.skew_tolerance,
693 );
694 explain(&message, &ctx)
695 };
696 if let Some(explanation) = explanation {
697 self.events
698 .push_back(RmEvent::Instruction(Box::new(Instructed {
699 id,
700 kind: message.kind(),
701 message,
702 explanation,
703 })));
704 }
705 }
706 }
707
708 fn on_reception_status(
709 &mut self,
710 status: &crate::types::common::ReceptionStatus,
711 now: Timestamp,
712 ) {
713 match self.core.acks.received(status, now) {
714 AckOutcome::Accepted { handle, latency } => {
715 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
716 self.core.stats.record_latency(latency);
717 self.events.push_back(RmEvent::Acked(handle));
718 }
719 AckOutcome::Refused {
720 handle,
721 status,
722 diagnostic,
723 consequence,
724 latency,
725 } => {
726 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
727 self.core.stats.record_latency(latency);
728 self.events.push_back(RmEvent::Nacked {
729 handle,
730 status,
731 diagnostic: diagnostic.clone(),
732 consequence,
733 });
734 if consequence == Consequence::Disconnect {
735 self.close_with(CloseReason::PermanentError(
736 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
737 ));
738 }
739 }
740 AckOutcome::TimedOut(handle) => {
741 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
742 self.events.push_back(RmEvent::AckTimedOut(handle));
743 }
744 AckOutcome::Unmatched { subject, status } => {
745 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
746 self.events
747 .push_back(RmEvent::UnmatchedAck { subject, status });
748 }
749 }
750 }
751
752 pub fn handle_timeout(&mut self, now: Timestamp) {
754 for handle in self.core.acks.expire(now) {
755 self.events.push_back(RmEvent::AckTimedOut(handle));
756 }
757 for message in self.core.registry.activate_due(now) {
758 self.events.push_back(RmEvent::DescriptionActivated {
759 kind: message.kind(),
760 });
761 }
762 }
763
764 pub fn transport_closed(&mut self, now: Timestamp) {
766 let _ = now;
767 self.close_with(CloseReason::TransportClosed);
768 }
769
770 pub fn send(
776 &mut self,
777 message: impl Into<Message>,
778 now: Timestamp,
779 ) -> Result<MessageHandle, SendError> {
780 let message = message.into();
781 let kind = message.kind();
782 if self.core.state.is_closed() {
783 return Err(SendError::Closed);
784 }
785 if !kind.exists_in(self.core.profile) {
786 return Err(SendError::NotInProfile {
787 kind,
788 profile: self.core.profile,
789 });
790 }
791 let allowance =
792 crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Rm, kind);
793 if !allowance.is_allowed() {
794 return Err(SendError::NotAllowed {
795 kind,
796 state: state_name(&self.core.state),
797 });
798 }
799 if self.config.validate_outbound {
800 let seen = self.core.acks.seen_ids();
801 let report = {
802 let ctx = self.core.registry.context(
803 self.core.profile,
804 EnergyManagementRole::Rm,
805 self.core.state.phase(),
806 self.core.s2_connect,
807 now,
808 &seen,
809 self.core.skew_tolerance,
810 );
811 message.validate(&ctx)
812 };
813 if let Some(violation) = report.first_error() {
814 return Err(SendError::Invalid(Box::new(violation.clone())));
815 }
816 if !report.is_empty() {
817 self.core.stats.sent_with_warnings =
818 self.core.stats.sent_with_warnings.saturating_add(1);
819 self.events
820 .push_back(RmEvent::OutboundWarnings { kind, report });
821 }
822 }
823 self.core.transmit(message, now).ok_or(SendError::Closed)
824 }
825
826 pub fn instruction_status(
831 &mut self,
832 instruction_id: Id,
833 status: InstructionStatus,
834 now: Timestamp,
835 ) -> Result<MessageHandle, SendError> {
836 let message_id = self.core.next_message_id();
837 self.send(
838 InstructionStatusUpdate {
839 message_id,
840 instruction_id,
841 status_type: status,
842 timestamp: now,
843 },
844 now,
845 )
846 }
847
848 pub fn request_session(
850 &mut self,
851 request: SessionRequestType,
852 diagnostic: Option<String>,
853 now: Timestamp,
854 ) -> Result<MessageHandle, SendError> {
855 let message_id = self.core.next_message_id();
856 let handle = self.send(
857 SessionRequest {
858 message_id,
859 request,
860 diagnostic_label: diagnostic,
861 },
862 now,
863 )?;
864 self.close_with(CloseReason::LocallyRequested(request));
867 Ok(handle)
868 }
869
870 pub fn close(&mut self) {
872 self.close_with(CloseReason::Local);
873 }
874
875 fn close_with(&mut self, reason: CloseReason) {
876 if self.core.state.is_closed() {
877 return;
878 }
879 let reconnect_after = match &reason {
880 CloseReason::Local => None,
882 CloseReason::PeerRequested(SessionRequestType::Reconnect)
885 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
886 _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
887 };
888 self.core.state = SessionState::Closed(reason.clone());
889 self.events.push_back(RmEvent::Closed {
890 reason,
891 reconnect_after,
892 });
893 }
894}
895
896pub(crate) fn state_name(state: &SessionState) -> &'static str {
897 match state {
898 SessionState::Idle => "idle",
899 SessionState::Handshaking => "handshaking",
900 SessionState::Connected => "connected",
901 SessionState::ControlTypeSelected(_) => "control type selected",
902 SessionState::Closed(_) => "closed",
903 }
904}