use alloc::boxed::Box;
use alloc::collections::VecDeque;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use super::core::{
AckOutcome, Backoff, CloseReason, CoreConfig, MessageHandle, Negotiation, OutOfOrderPolicy,
Outgoing, SendError, SessionCore, SessionState,
};
use super::{Inbound, InboundPolicy};
use crate::codec::{self, Strictness};
use crate::message::{Message, MessageKind};
use crate::model::{Explanation, explain};
use crate::types::common::{
Consequence, ControlType, EnergyManagementRole, Handshake, InstructionStatus,
InstructionStatusUpdate, ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
SessionRequest, SessionRequestType,
};
use crate::types::{Duration, Id, ProtocolVersion, Timestamp, WireProfile};
use crate::validate::{Report, Validate, rules};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RmConfig {
pub negotiation: Negotiation,
pub offered_versions: Vec<ProtocolVersion>,
pub ack_timeout: Duration,
pub out_of_order: OutOfOrderPolicy,
pub skew_tolerance: Duration,
pub max_message_bytes: usize,
pub strictness: Strictness,
pub s2_connect: bool,
pub validate_outbound: bool,
pub reconnect_attempt: u32,
}
impl Default for RmConfig {
fn default() -> Self {
Self {
negotiation: Negotiation::Handshake,
offered_versions: alloc::vec![ProtocolVersion::V1_0_0, ProtocolVersion::V0_0_2_BETA,],
ack_timeout: Duration::from_secs(5),
out_of_order: OutOfOrderPolicy::Report,
skew_tolerance: Duration::from_secs(30),
max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
strictness: Strictness::Strict,
s2_connect: false,
validate_outbound: true,
reconnect_attempt: 0,
}
}
}
impl RmConfig {
#[must_use]
pub fn without_outbound_validation(mut self) -> Self {
self.validate_outbound = false;
self
}
#[must_use]
pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
self.negotiation = Negotiation::PreNegotiated(profile);
self.s2_connect = true;
self
}
#[must_use]
pub fn offering(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
self.offered_versions = versions.into_iter().collect();
self
}
#[must_use]
pub fn strict_ordering(mut self) -> Self {
self.out_of_order = OutOfOrderPolicy::Close;
self
}
#[must_use]
pub fn ack_timeout(mut self, timeout: Duration) -> Self {
self.ack_timeout = timeout;
self
}
#[must_use]
pub const fn after_failed_attempts(mut self, attempts: u32) -> Self {
self.reconnect_attempt = attempts;
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Instructed {
pub id: Id,
pub kind: MessageKind,
pub message: Message,
pub explanation: Explanation,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RmEvent {
Negotiated {
version: ProtocolVersion,
profile: WireProfile,
},
Ready {
control_type: ControlType,
},
Deselected,
Instruction(Box<Instructed>),
DescriptionActivated {
kind: MessageKind,
},
Acked(MessageHandle),
Nacked {
handle: MessageHandle,
status: ReceptionStatusValues,
diagnostic: Option<String>,
consequence: Consequence,
},
AckTimedOut(MessageHandle),
UnmatchedAck {
subject: Id,
status: ReceptionStatusValues,
},
Revoked {
object_type: RevokableObjects,
object_id: Id,
},
SessionRequested {
request: SessionRequestType,
diagnostic: Option<String>,
},
Refused {
kind: Option<MessageKind>,
status: ReceptionStatusValues,
report: Report,
},
Warnings {
kind: MessageKind,
report: Report,
},
OutboundWarnings {
kind: MessageKind,
report: Report,
},
Closed {
reason: CloseReason,
reconnect_after: Option<Duration>,
},
}
pub struct RmSession {
core: SessionCore,
details: ResourceManagerDetails,
config: RmConfig,
events: VecDeque<RmEvent>,
peer_versions: Vec<ProtocolVersion>,
negotiated: Option<ProtocolVersion>,
handshake_seen: bool,
policy: Option<Box<dyn InboundPolicy + Send>>,
backoff: Backoff,
}
impl core::fmt::Debug for RmSession {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RmSession")
.field("state", &self.core.state)
.field("profile", &self.core.profile)
.field("outstanding_acks", &self.core.acks.outstanding())
.field("queued", &self.core.outbox.len())
.finish_non_exhaustive()
}
}
impl RmSession {
#[must_use]
pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
let core = SessionCore::new(CoreConfig {
role: EnergyManagementRole::Rm,
negotiation: config.negotiation.clone(),
ack_timeout: config.ack_timeout,
out_of_order: config.out_of_order,
skew_tolerance: config.skew_tolerance,
max_message_bytes: config.max_message_bytes,
strictness: config.strictness,
s2_connect: config.s2_connect,
reconnect_attempt: config.reconnect_attempt,
});
Self {
core,
details,
config,
events: VecDeque::new(),
peer_versions: Vec::new(),
negotiated: None,
handshake_seen: false,
policy: None,
backoff: Backoff::default(),
}
}
pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
self.policy = Some(policy);
}
#[must_use]
pub fn state(&self) -> &SessionState {
&self.core.state
}
#[must_use]
pub fn profile(&self) -> WireProfile {
self.core.profile
}
#[must_use]
pub fn stats(&self) -> super::core::Stats {
self.core.stats
}
#[must_use]
pub fn registry(&self) -> &super::core::Registry {
&self.core.registry
}
pub fn open(&mut self, now: Timestamp) {
if !matches!(self.core.state, SessionState::Idle) {
return;
}
match &self.config.negotiation {
Negotiation::Handshake => {
let handshake = Handshake {
message_id: self.core.next_message_id(),
role: EnergyManagementRole::Rm,
supported_protocol_versions: Some(self.config.offered_versions.clone()),
};
self.core.state = SessionState::Handshaking;
self.core.transmit(Message::from(handshake), now);
}
Negotiation::PreNegotiated(profile) => {
let profile = *profile;
self.core.profile = profile;
self.negotiated = Some(profile.version());
self.core.state = SessionState::Connected;
self.events.push_back(RmEvent::Negotiated {
version: profile.version(),
profile,
});
self.send_details(now);
}
}
}
fn send_details(&mut self, now: Timestamp) {
let mut details = self.details.clone();
details.message_id = self.core.next_message_id();
self.core.transmit(Message::from(details), now);
}
pub fn poll_transmit(&mut self) -> Option<Outgoing> {
self.core.poll_transmit()
}
pub fn poll_event(&mut self) -> Option<RmEvent> {
self.events.pop_front()
}
#[must_use]
pub fn poll_timeout(&self) -> Option<Timestamp> {
self.core.poll_timeout()
}
pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
if self.core.state.is_closed() {
return Inbound {
kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
status: ReceptionStatusValues::Ok,
report: Report::new(),
};
}
self.core.stats.received = self.core.stats.received.saturating_add(1);
let options = self.core.decode_options();
match codec::decode_with(text, &options) {
Ok(decoded) => {
if !decoded.pruned.is_empty() {
let mut report = Report::new();
for path in &decoded.pruned {
report.push(
rules::UNKNOWN_PROPERTY,
path,
"property is not defined by the schema and was removed",
);
}
self.events.push_back(RmEvent::Warnings {
kind: decoded.message.kind(),
report,
});
}
self.handle_message(decoded.message, now)
}
Err(error) => {
self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
let kind = error.peek().and_then(|p| p.kind);
let status = error.reception_status();
if kind != Some(MessageKind::ReceptionStatus) {
self.core.acknowledge(
status.subject_message_id,
status.status,
status.diagnostic_label.clone(),
now,
);
}
let mut report = Report::new();
report.push(rules::DECODE_FAILED, "", error.to_string());
self.events.push_back(RmEvent::Refused {
kind,
status: status.status,
report: report.clone(),
});
Inbound {
kind,
status: status.status,
report,
}
}
}
}
pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
if self.core.state.is_closed() {
return Inbound::ignored(message.kind());
}
if let Message::ReceptionStatus(status) = &message {
self.on_reception_status(status, now);
return Inbound {
kind: Some(MessageKind::ReceptionStatus),
status: ReceptionStatusValues::Ok,
report: Report::new(),
};
}
let kind = message.kind();
let Some(id) = message.id() else {
return Inbound::ignored(kind);
};
if let Some(previous) = self.core.acks.previous_answer(id) {
self.core.acknowledge(id, previous, None, now);
self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
let mut report = Report::new();
report.push_related(
rules::DUPLICATE_MESSAGE_ID,
"/message_id",
alloc::format!("{id} was already answered {previous:?}; not processed again"),
[id],
);
self.events.push_back(RmEvent::Warnings {
kind,
report: report.clone(),
});
return Inbound {
kind: Some(kind),
status: previous,
report,
};
}
let seen = self.core.acks.seen_ids();
let report = {
let ctx = self.core.registry.context(
self.core.profile,
EnergyManagementRole::Cem,
self.core.state.phase(),
self.core.s2_connect,
now,
&seen,
self.core.skew_tolerance,
);
message.validate(&ctx)
};
if report.has_errors() {
let status = ReceptionStatusValues::InvalidContent;
self.core
.acknowledge(id, status, report.diagnostic_label(), now);
let closing = self.config.out_of_order == OutOfOrderPolicy::Close
&& (report.contains(rules::NOT_ALLOWED_IN_STATE)
|| report.contains(rules::NOT_ALLOWED_FOR_ROLE));
self.events.push_back(RmEvent::Refused {
kind: Some(kind),
status,
report: report.clone(),
});
if closing {
let reason = CloseReason::ProtocolError(
report
.diagnostic_label()
.unwrap_or_else(|| "out of order".to_string()),
);
self.close_with(reason);
}
return Inbound {
kind: Some(kind),
status,
report,
};
}
let policy = self
.policy
.as_mut()
.and_then(|policy| policy.review(&message));
if let Some((status, diagnostic)) = policy {
self.core
.acknowledge(id, status, Some(diagnostic.clone()), now);
let mut refusal = report.clone();
refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
self.events.push_back(RmEvent::Refused {
kind: Some(kind),
status,
report: refusal,
});
return Inbound {
kind: Some(kind),
status,
report,
};
}
self.core
.acknowledge(id, ReceptionStatusValues::Ok, None, now);
if !report.is_empty() {
self.core.stats.accepted_with_warnings =
self.core.stats.accepted_with_warnings.saturating_add(1);
self.events.push_back(RmEvent::Warnings {
kind,
report: report.clone(),
});
}
self.process(message, now);
Inbound {
kind: Some(kind),
status: ReceptionStatusValues::Ok,
report,
}
}
fn process(&mut self, message: Message, now: Timestamp) {
match &message {
Message::Handshake(h) => {
self.handshake_seen = true;
if let Some(versions) = &h.supported_protocol_versions {
self.peer_versions.clone_from(versions);
}
}
Message::HandshakeResponse(response) => {
let selected = response.selected_protocol_version.clone();
if !self
.config
.offered_versions
.iter()
.any(|offered| offered.matches(&selected))
{
self.close_with(CloseReason::UnsupportedVersion { selected });
return;
}
let Some(profile) = selected.wire_profile() else {
self.close_with(CloseReason::UnsupportedVersion { selected });
return;
};
self.core.profile = profile;
self.negotiated = Some(selected.clone());
self.core.state = SessionState::Connected;
self.events.push_back(RmEvent::Negotiated {
version: selected,
profile,
});
self.send_details(now);
}
Message::SelectControlType(select) => {
let control_type = select.control_type;
if control_type == ControlType::NoSelection {
self.core.state = SessionState::Connected;
self.events.push_back(RmEvent::Deselected);
} else {
self.core.state = SessionState::ControlTypeSelected(control_type);
self.events.push_back(RmEvent::Ready { control_type });
}
}
Message::SessionRequest(request) => {
self.events.push_back(RmEvent::SessionRequested {
request: request.request,
diagnostic: request.diagnostic_label.clone(),
});
self.close_with(CloseReason::PeerRequested(request.request));
return;
}
Message::RevokeObject(revoke) => {
self.core
.registry
.revoke(revoke.object_type, revoke.object_id);
self.events.push_back(RmEvent::Revoked {
object_type: revoke.object_type,
object_id: revoke.object_id,
});
return;
}
_ => {}
}
self.core.registry.record(&message, Some(now));
if let Some(id) = message.instruction_id() {
let seen = self.core.acks.seen_ids();
let explanation = {
let ctx = self.core.registry.context(
self.core.profile,
EnergyManagementRole::Cem,
self.core.state.phase(),
self.core.s2_connect,
now,
&seen,
self.core.skew_tolerance,
);
explain(&message, &ctx)
};
if let Some(explanation) = explanation {
self.events
.push_back(RmEvent::Instruction(Box::new(Instructed {
id,
kind: message.kind(),
message,
explanation,
})));
}
}
}
fn on_reception_status(
&mut self,
status: &crate::types::common::ReceptionStatus,
now: Timestamp,
) {
match self.core.acks.received(status, now) {
AckOutcome::Accepted { handle, latency } => {
self.core.stats.acked = self.core.stats.acked.saturating_add(1);
self.core.stats.record_latency(latency);
self.events.push_back(RmEvent::Acked(handle));
}
AckOutcome::Refused {
handle,
status,
diagnostic,
consequence,
latency,
} => {
self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
self.core.stats.record_latency(latency);
self.events.push_back(RmEvent::Nacked {
handle,
status,
diagnostic: diagnostic.clone(),
consequence,
});
if consequence == Consequence::Disconnect {
self.close_with(CloseReason::PermanentError(
diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
));
}
}
AckOutcome::TimedOut(handle) => {
self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
self.events.push_back(RmEvent::AckTimedOut(handle));
}
AckOutcome::Unmatched { subject, status } => {
self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
self.events
.push_back(RmEvent::UnmatchedAck { subject, status });
}
}
}
pub fn handle_timeout(&mut self, now: Timestamp) {
for handle in self.core.acks.expire(now) {
self.events.push_back(RmEvent::AckTimedOut(handle));
}
for message in self.core.registry.activate_due(now) {
self.events.push_back(RmEvent::DescriptionActivated {
kind: message.kind(),
});
}
}
pub fn transport_closed(&mut self, now: Timestamp) {
let _ = now;
self.close_with(CloseReason::TransportClosed);
}
pub fn send(
&mut self,
message: impl Into<Message>,
now: Timestamp,
) -> Result<MessageHandle, SendError> {
let message = message.into();
let kind = message.kind();
if self.core.state.is_closed() {
return Err(SendError::Closed);
}
if !kind.exists_in(self.core.profile) {
return Err(SendError::NotInProfile {
kind,
profile: self.core.profile,
});
}
let allowance =
crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Rm, kind);
if !allowance.is_allowed() {
return Err(SendError::NotAllowed {
kind,
state: state_name(&self.core.state),
});
}
if self.config.validate_outbound {
let seen = self.core.acks.seen_ids();
let report = {
let ctx = self.core.registry.context(
self.core.profile,
EnergyManagementRole::Rm,
self.core.state.phase(),
self.core.s2_connect,
now,
&seen,
self.core.skew_tolerance,
);
message.validate(&ctx)
};
if let Some(violation) = report.first_error() {
return Err(SendError::Invalid(Box::new(violation.clone())));
}
if !report.is_empty() {
self.core.stats.sent_with_warnings =
self.core.stats.sent_with_warnings.saturating_add(1);
self.events
.push_back(RmEvent::OutboundWarnings { kind, report });
}
}
self.core.transmit(message, now).ok_or(SendError::Closed)
}
pub fn instruction_status(
&mut self,
instruction_id: Id,
status: InstructionStatus,
now: Timestamp,
) -> Result<MessageHandle, SendError> {
let message_id = self.core.next_message_id();
self.send(
InstructionStatusUpdate {
message_id,
instruction_id,
status_type: status,
timestamp: now,
},
now,
)
}
pub fn request_session(
&mut self,
request: SessionRequestType,
diagnostic: Option<String>,
now: Timestamp,
) -> Result<MessageHandle, SendError> {
let message_id = self.core.next_message_id();
let handle = self.send(
SessionRequest {
message_id,
request,
diagnostic_label: diagnostic,
},
now,
)?;
self.close_with(CloseReason::LocallyRequested(request));
Ok(handle)
}
pub fn close(&mut self) {
self.close_with(CloseReason::Local);
}
fn close_with(&mut self, reason: CloseReason) {
if self.core.state.is_closed() {
return;
}
let reconnect_after = match &reason {
CloseReason::Local => None,
CloseReason::PeerRequested(SessionRequestType::Reconnect)
| CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
_ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
};
self.core.state = SessionState::Closed(reason.clone());
self.events.push_back(RmEvent::Closed {
reason,
reconnect_after,
});
}
}
pub(crate) fn state_name(state: &SessionState) -> &'static str {
match state {
SessionState::Idle => "idle",
SessionState::Handshaking => "handshaking",
SessionState::Connected => "connected",
SessionState::ControlTypeSelected(_) => "control type selected",
SessionState::Closed(_) => "closed",
}
}