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}
53
54impl Default for RmConfig {
55 fn default() -> Self {
56 Self {
57 negotiation: Negotiation::Handshake,
58 offered_versions: alloc::vec![
59 ProtocolVersion::new(ProtocolVersion::V1_0_0),
60 ProtocolVersion::new(ProtocolVersion::V0_0_2_BETA),
61 ],
62 ack_timeout: Duration::from_secs(5),
63 out_of_order: OutOfOrderPolicy::Report,
64 skew_tolerance: Duration::from_secs(30),
65 max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
66 strictness: Strictness::Strict,
67 s2_connect: false,
68 validate_outbound: true,
69 }
70 }
71}
72
73impl RmConfig {
74 #[must_use]
80 pub fn without_outbound_validation(mut self) -> Self {
81 self.validate_outbound = false;
82 self
83 }
84
85 #[must_use]
87 pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
88 self.negotiation = Negotiation::PreNegotiated(profile);
89 self.s2_connect = true;
90 self
91 }
92
93 #[must_use]
95 pub fn offering(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
96 self.offered_versions = versions.into_iter().collect();
97 self
98 }
99
100 #[must_use]
102 pub fn strict_ordering(mut self) -> Self {
103 self.out_of_order = OutOfOrderPolicy::Close;
104 self
105 }
106
107 #[must_use]
109 pub fn ack_timeout(mut self, timeout: Duration) -> Self {
110 self.ack_timeout = timeout;
111 self
112 }
113}
114
115#[derive(Debug, Clone, PartialEq)]
123pub struct Instructed {
124 pub id: Id,
126 pub kind: MessageKind,
128 pub message: Message,
130 pub explanation: Explanation,
132}
133
134#[derive(Debug, Clone, PartialEq)]
136#[non_exhaustive]
137pub enum RmEvent {
138 Negotiated {
140 version: ProtocolVersion,
142 profile: WireProfile,
144 },
145 Ready {
147 control_type: ControlType,
149 },
150 Deselected,
152 Instruction(Box<Instructed>),
154 DescriptionActivated {
156 kind: MessageKind,
158 },
159 Acked(MessageHandle),
161 Nacked {
163 handle: MessageHandle,
165 status: ReceptionStatusValues,
167 diagnostic: Option<String>,
169 consequence: Consequence,
171 },
172 AckTimedOut(MessageHandle),
174 UnmatchedAck {
176 subject: Id,
178 status: ReceptionStatusValues,
180 },
181 Revoked {
183 object_type: RevokableObjects,
185 object_id: Id,
187 },
188 SessionRequested {
190 request: SessionRequestType,
192 diagnostic: Option<String>,
194 },
195 Refused {
197 kind: Option<MessageKind>,
199 status: ReceptionStatusValues,
201 report: Report,
203 },
204 Warnings {
206 kind: MessageKind,
208 report: Report,
210 },
211 Closed {
213 reason: CloseReason,
215 reconnect_after: Option<Duration>,
217 },
218}
219
220pub struct RmSession {
245 core: SessionCore,
246 details: ResourceManagerDetails,
247 config: RmConfig,
248 events: VecDeque<RmEvent>,
249 peer_versions: Vec<ProtocolVersion>,
250 negotiated: Option<ProtocolVersion>,
251 handshake_seen: bool,
252 policy: Option<Box<dyn InboundPolicy + Send>>,
253 backoff: Backoff,
254}
255
256impl core::fmt::Debug for RmSession {
257 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
258 f.debug_struct("RmSession")
259 .field("state", &self.core.state)
260 .field("profile", &self.core.profile)
261 .field("outstanding_acks", &self.core.acks.outstanding())
262 .field("queued", &self.core.outbox.len())
263 .finish_non_exhaustive()
264 }
265}
266
267impl RmSession {
268 #[must_use]
270 pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
271 let core = SessionCore::new(CoreConfig {
272 role: EnergyManagementRole::Rm,
273 negotiation: config.negotiation.clone(),
274 ack_timeout: config.ack_timeout,
275 out_of_order: config.out_of_order,
276 skew_tolerance: config.skew_tolerance,
277 max_message_bytes: config.max_message_bytes,
278 strictness: config.strictness,
279 s2_connect: config.s2_connect,
280 });
281 Self {
282 core,
283 details,
284 config,
285 events: VecDeque::new(),
286 peer_versions: Vec::new(),
287 negotiated: None,
288 handshake_seen: false,
289 policy: None,
290 backoff: Backoff::default(),
291 }
292 }
293
294 pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
300 self.policy = Some(policy);
301 }
302
303 #[must_use]
305 pub fn state(&self) -> &SessionState {
306 &self.core.state
307 }
308
309 #[must_use]
311 pub fn profile(&self) -> WireProfile {
312 self.core.profile
313 }
314
315 #[must_use]
319 pub fn stats(&self) -> super::core::Stats {
320 self.core.stats
321 }
322
323 #[must_use]
325 pub fn registry(&self) -> &super::core::Registry {
326 &self.core.registry
327 }
328
329 pub fn open(&mut self, now: Timestamp) {
335 if !matches!(self.core.state, SessionState::Idle) {
336 return;
337 }
338 match &self.config.negotiation {
339 Negotiation::Handshake => {
340 let handshake = Handshake {
341 message_id: self.core.next_message_id(),
342 role: EnergyManagementRole::Rm,
343 supported_protocol_versions: Some(self.config.offered_versions.clone()),
344 };
345 self.core.state = SessionState::Handshaking;
346 self.core.transmit(Message::from(handshake), now);
347 }
348 Negotiation::PreNegotiated(profile) => {
349 let profile = *profile;
350 self.core.profile = profile;
351 self.negotiated = Some(profile.version());
352 self.core.state = SessionState::Connected;
353 self.events.push_back(RmEvent::Negotiated {
354 version: profile.version(),
355 profile,
356 });
357 self.send_details(now);
358 }
359 }
360 }
361
362 fn send_details(&mut self, now: Timestamp) {
363 let mut details = self.details.clone();
364 details.message_id = self.core.next_message_id();
365 self.core.transmit(Message::from(details), now);
366 }
367
368 pub fn poll_transmit(&mut self) -> Option<Outgoing> {
370 self.core.poll_transmit()
371 }
372
373 pub fn poll_event(&mut self) -> Option<RmEvent> {
375 self.events.pop_front()
376 }
377
378 #[must_use]
380 pub fn poll_timeout(&self) -> Option<Timestamp> {
381 self.core.poll_timeout()
382 }
383
384 pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
392 if self.core.state.is_closed() {
393 return Inbound {
394 kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
395 status: ReceptionStatusValues::Ok,
396 report: Report::new(),
397 };
398 }
399 self.core.stats.received = self.core.stats.received.saturating_add(1);
400 let options = self.core.decode_options();
401 match codec::decode_with(text, &options) {
402 Ok(decoded) => {
403 if !decoded.pruned.is_empty() {
404 let mut report = Report::new();
405 for path in &decoded.pruned {
406 report.push(
407 rules::UNKNOWN_PROPERTY,
408 path,
409 "property is not defined by the schema and was removed",
410 );
411 }
412 self.events.push_back(RmEvent::Warnings {
413 kind: decoded.message.kind(),
414 report,
415 });
416 }
417 self.handle_message(decoded.message, now)
418 }
419 Err(error) => {
420 self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
421 let kind = error.peek().and_then(|p| p.kind);
422 let status = error.reception_status();
423 if kind != Some(MessageKind::ReceptionStatus) {
426 self.core.acknowledge(
427 status.subject_message_id,
428 status.status,
429 status.diagnostic_label.clone(),
430 now,
431 );
432 }
433 let mut report = Report::new();
434 report.push(rules::DECODE_FAILED, "", error.to_string());
435 self.events.push_back(RmEvent::Refused {
436 kind,
437 status: status.status,
438 report: report.clone(),
439 });
440 Inbound {
441 kind,
442 status: status.status,
443 report,
444 }
445 }
446 }
447 }
448
449 pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
451 if self.core.state.is_closed() {
452 return Inbound::ignored(message.kind());
453 }
454
455 if let Message::ReceptionStatus(status) = &message {
457 self.on_reception_status(status, now);
458 return Inbound {
459 kind: Some(MessageKind::ReceptionStatus),
460 status: ReceptionStatusValues::Ok,
461 report: Report::new(),
462 };
463 }
464
465 let kind = message.kind();
466 let Some(id) = message.id() else {
467 return Inbound::ignored(kind);
468 };
469
470 if let Some(previous) = self.core.acks.previous_answer(id) {
473 self.core.acknowledge(id, previous, None, now);
477 self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
478 let mut report = Report::new();
479 report.push_related(
480 rules::DUPLICATE_MESSAGE_ID,
481 "/message_id",
482 alloc::format!("{id} was already answered {previous:?}; not processed again"),
483 [id],
484 );
485 self.events.push_back(RmEvent::Warnings {
486 kind,
487 report: report.clone(),
488 });
489 return Inbound {
490 kind: Some(kind),
491 status: previous,
492 report,
493 };
494 }
495
496 let seen = self.core.acks.seen_ids();
497 let report = {
498 let ctx = self.core.registry.context(
499 self.core.profile,
500 EnergyManagementRole::Cem,
501 self.core.state.active_control_type(),
502 self.core.s2_connect,
503 now,
504 &seen,
505 self.core.skew_tolerance,
506 );
507 message.validate(&ctx)
508 };
509
510 if report.has_errors() {
511 let status = ReceptionStatusValues::InvalidContent;
512 self.core
513 .acknowledge(id, status, report.diagnostic_label(), now);
514 let closing = self.config.out_of_order == OutOfOrderPolicy::Close
515 && (report.contains(rules::NOT_ALLOWED_IN_STATE)
516 || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
517 self.events.push_back(RmEvent::Refused {
518 kind: Some(kind),
519 status,
520 report: report.clone(),
521 });
522 if closing {
523 let reason = CloseReason::ProtocolError(
524 report
525 .diagnostic_label()
526 .unwrap_or_else(|| "out of order".to_string()),
527 );
528 self.close_with(reason);
529 }
530 return Inbound {
531 kind: Some(kind),
532 status,
533 report,
534 };
535 }
536
537 let policy = self
539 .policy
540 .as_mut()
541 .and_then(|policy| policy.review(&message));
542 if let Some((status, diagnostic)) = policy {
543 self.core
544 .acknowledge(id, status, Some(diagnostic.clone()), now);
545 let mut refusal = report.clone();
546 refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
547 self.events.push_back(RmEvent::Refused {
548 kind: Some(kind),
549 status,
550 report: refusal,
551 });
552 return Inbound {
553 kind: Some(kind),
554 status,
555 report,
556 };
557 }
558
559 self.core
560 .acknowledge(id, ReceptionStatusValues::Ok, None, now);
561 if !report.is_empty() {
562 self.core.stats.accepted_with_warnings =
563 self.core.stats.accepted_with_warnings.saturating_add(1);
564 self.events.push_back(RmEvent::Warnings {
565 kind,
566 report: report.clone(),
567 });
568 }
569 self.process(message, now);
570 Inbound {
571 kind: Some(kind),
572 status: ReceptionStatusValues::Ok,
573 report,
574 }
575 }
576
577 fn process(&mut self, message: Message, now: Timestamp) {
579 match &message {
580 Message::Handshake(h) => {
581 self.handshake_seen = true;
582 if let Some(versions) = &h.supported_protocol_versions {
583 self.peer_versions.clone_from(versions);
584 }
585 }
586 Message::HandshakeResponse(response) => {
587 let selected = response.selected_protocol_version.clone();
588 if !self
593 .config
594 .offered_versions
595 .iter()
596 .any(|offered| offered.matches(&selected))
597 {
598 self.close_with(CloseReason::UnsupportedVersion { selected });
599 return;
600 }
601 let Some(profile) = selected.wire_profile() else {
602 self.close_with(CloseReason::UnsupportedVersion { selected });
603 return;
604 };
605 self.core.profile = profile;
606 self.negotiated = Some(selected.clone());
607 self.core.state = SessionState::Connected;
608 self.events.push_back(RmEvent::Negotiated {
609 version: selected,
610 profile,
611 });
612 self.send_details(now);
613 }
614 Message::SelectControlType(select) => {
615 let control_type = select.control_type;
616 if control_type == ControlType::NoSelection {
617 self.core.state = SessionState::Connected;
618 self.events.push_back(RmEvent::Deselected);
619 } else {
620 self.core.state = SessionState::ControlTypeSelected(control_type);
621 self.events.push_back(RmEvent::Ready { control_type });
622 }
623 }
624 Message::SessionRequest(request) => {
625 self.events.push_back(RmEvent::SessionRequested {
626 request: request.request,
627 diagnostic: request.diagnostic_label.clone(),
628 });
629 self.close_with(CloseReason::PeerRequested(request.request));
630 return;
631 }
632 Message::RevokeObject(revoke) => {
633 self.core
634 .registry
635 .revoke(revoke.object_type, revoke.object_id);
636 self.events.push_back(RmEvent::Revoked {
637 object_type: revoke.object_type,
638 object_id: revoke.object_id,
639 });
640 return;
641 }
642 _ => {}
643 }
644
645 self.core.registry.record(&message, Some(now));
646
647 if let Some(id) = message.instruction_id() {
648 let seen = self.core.acks.seen_ids();
649 let explanation = {
650 let ctx = self.core.registry.context(
651 self.core.profile,
652 EnergyManagementRole::Cem,
653 self.core.state.active_control_type(),
654 self.core.s2_connect,
655 now,
656 &seen,
657 self.core.skew_tolerance,
658 );
659 explain(&message, &ctx)
660 };
661 if let Some(explanation) = explanation {
662 self.events
663 .push_back(RmEvent::Instruction(Box::new(Instructed {
664 id,
665 kind: message.kind(),
666 message,
667 explanation,
668 })));
669 }
670 }
671 }
672
673 fn on_reception_status(
674 &mut self,
675 status: &crate::types::common::ReceptionStatus,
676 now: Timestamp,
677 ) {
678 match self.core.acks.received(status, now) {
679 AckOutcome::Accepted { handle, latency } => {
680 self.core.stats.acked = self.core.stats.acked.saturating_add(1);
681 self.core.stats.record_latency(latency);
682 self.events.push_back(RmEvent::Acked(handle));
683 }
684 AckOutcome::Refused {
685 handle,
686 status,
687 diagnostic,
688 consequence,
689 latency,
690 } => {
691 self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
692 self.core.stats.record_latency(latency);
693 self.events.push_back(RmEvent::Nacked {
694 handle,
695 status,
696 diagnostic: diagnostic.clone(),
697 consequence,
698 });
699 if consequence == Consequence::Disconnect {
700 self.close_with(CloseReason::PermanentError(
701 diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
702 ));
703 }
704 }
705 AckOutcome::TimedOut(handle) => {
706 self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
707 self.events.push_back(RmEvent::AckTimedOut(handle));
708 }
709 AckOutcome::Unmatched { subject, status } => {
710 self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
711 self.events
712 .push_back(RmEvent::UnmatchedAck { subject, status });
713 }
714 }
715 }
716
717 pub fn handle_timeout(&mut self, now: Timestamp) {
719 for handle in self.core.acks.expire(now) {
720 self.events.push_back(RmEvent::AckTimedOut(handle));
721 }
722 for message in self.core.registry.activate_due(now) {
723 self.events.push_back(RmEvent::DescriptionActivated {
724 kind: message.kind(),
725 });
726 }
727 }
728
729 pub fn transport_closed(&mut self, now: Timestamp) {
731 let _ = now;
732 self.close_with(CloseReason::TransportClosed);
733 }
734
735 pub fn send(
741 &mut self,
742 message: impl Into<Message>,
743 now: Timestamp,
744 ) -> Result<MessageHandle, SendError> {
745 let message = message.into();
746 let kind = message.kind();
747 if self.core.state.is_closed() {
748 return Err(SendError::Closed);
749 }
750 if !kind.exists_in(self.core.profile) {
751 return Err(SendError::NotInProfile {
752 kind,
753 profile: self.core.profile,
754 });
755 }
756 let allowance = crate::validate::allowed(
757 self.core.state.active_control_type(),
758 EnergyManagementRole::Rm,
759 kind,
760 );
761 if !allowance.is_allowed() {
762 return Err(SendError::NotAllowed {
763 kind,
764 state: state_name(&self.core.state),
765 });
766 }
767 if self.config.validate_outbound {
768 let seen = self.core.acks.seen_ids();
769 let report = {
770 let ctx = self.core.registry.context(
771 self.core.profile,
772 EnergyManagementRole::Rm,
773 self.core.state.active_control_type(),
774 self.core.s2_connect,
775 now,
776 &seen,
777 self.core.skew_tolerance,
778 );
779 message.validate(&ctx)
780 };
781 if let Some(violation) = report.first_error() {
782 return Err(SendError::Invalid(Box::new(violation.clone())));
783 }
784 }
785 self.core.transmit(message, now).ok_or(SendError::Closed)
786 }
787
788 pub fn instruction_status(
793 &mut self,
794 instruction_id: Id,
795 status: InstructionStatus,
796 now: Timestamp,
797 ) -> Result<MessageHandle, SendError> {
798 let message_id = self.core.next_message_id();
799 self.send(
800 InstructionStatusUpdate {
801 message_id,
802 instruction_id,
803 status_type: status,
804 timestamp: now,
805 },
806 now,
807 )
808 }
809
810 pub fn request_session(
812 &mut self,
813 request: SessionRequestType,
814 diagnostic: Option<String>,
815 now: Timestamp,
816 ) -> Result<MessageHandle, SendError> {
817 let message_id = self.core.next_message_id();
818 let handle = self.send(
819 SessionRequest {
820 message_id,
821 request,
822 diagnostic_label: diagnostic,
823 },
824 now,
825 )?;
826 self.close_with(CloseReason::LocallyRequested(request));
829 Ok(handle)
830 }
831
832 pub fn close(&mut self) {
834 self.close_with(CloseReason::Local);
835 }
836
837 fn close_with(&mut self, reason: CloseReason) {
838 if self.core.state.is_closed() {
839 return;
840 }
841 let reconnect_after = match &reason {
842 CloseReason::Local => None,
844 CloseReason::PeerRequested(SessionRequestType::Reconnect)
847 | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
848 _ => {
849 let delay = self.backoff.ceiling(self.core.reconnect_attempt);
850 self.core.reconnect_attempt = self.core.reconnect_attempt.saturating_add(1);
851 Some(delay)
852 }
853 };
854 self.core.state = SessionState::Closed(reason.clone());
855 self.events.push_back(RmEvent::Closed {
856 reason,
857 reconnect_after,
858 });
859 }
860}
861
862pub(crate) fn state_name(state: &SessionState) -> &'static str {
863 match state {
864 SessionState::Idle => "idle",
865 SessionState::Handshaking => "handshaking",
866 SessionState::Connected => "connected",
867 SessionState::ControlTypeSelected(_) => "control type selected",
868 SessionState::Closed(_) => "closed",
869 }
870}