use heapless::Vec;
use crate::config::{AssertValid, Config};
use crate::error::{Error, ErrorCode};
use crate::im::path::{AttributePath, EventPath};
use crate::im::{ClusterId, EndpointId};
use crate::msg::{FabricIndex, NodeId, SessionId};
use crate::platform::{Duration, Instant};
pub const MAX_INTERVAL_PUBLISHER_LIMIT_S: u16 = 3600;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubscriptionPolicy {
pub max_interval_limit_s: u16,
pub preferred_max_interval_s: Option<u16>,
}
impl Default for SubscriptionPolicy {
fn default() -> Self {
Self {
max_interval_limit_s: MAX_INTERVAL_PUBLISHER_LIMIT_S,
preferred_max_interval_s: None,
}
}
}
impl SubscriptionPolicy {
#[must_use]
pub fn max_interval(&self, floor_s: u16, ceiling_s: u16) -> u16 {
let upper = self.max_interval_limit_s.max(ceiling_s);
let wanted = self.preferred_max_interval_s.unwrap_or(ceiling_s);
wanted.clamp(floor_s.min(upper), upper)
}
}
#[derive(Debug, Clone)]
pub struct DirtySet<const N: usize> {
paths: Vec<AttributePath, N>,
overflowed: bool,
}
impl<const N: usize> Default for DirtySet<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> DirtySet<N> {
#[must_use]
pub const fn new() -> Self {
Self {
paths: Vec::new(),
overflowed: false,
}
}
pub fn insert(&mut self, path: AttributePath) {
if self.overflowed || self.paths.contains(&path) {
return;
}
if self.paths.push(path).is_err() {
self.overflowed = true;
self.paths.clear();
}
}
#[must_use]
pub fn paths(&self) -> &[AttributePath] {
&self.paths
}
#[must_use]
pub fn is_dirty(&self) -> bool {
self.overflowed || !self.paths.is_empty()
}
#[must_use]
pub const fn must_reprime(&self) -> bool {
self.overflowed
}
pub fn clear(&mut self) {
self.paths.clear();
self.overflowed = false;
}
pub fn reprime(&mut self) {
self.paths.clear();
self.overflowed = true;
}
}
pub const DIRTY_PATHS: usize = 8;
#[derive(Debug, Clone)]
pub struct Subscription<const P: usize> {
pub id: u32,
pub session: Option<SessionId>,
pub fabric_index: Option<FabricIndex>,
pub peer_node_id: Option<NodeId>,
pub fabric_filtered: bool,
pub min_interval_s: u16,
pub max_interval_s: u16,
pub paths: Vec<AttributePath, P>,
pub last_report: Instant,
pub event_paths: Vec<EventPath, P>,
pub dirty: DirtySet<DIRTY_PATHS>,
pub next_event_number: u64,
urgent: bool,
reported_through: u64,
pub(crate) cursor: crate::im::server::ReadCursor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReportReason {
Data,
KeepAlive,
}
impl<const P: usize> Subscription<P> {
pub fn reprime(&mut self) {
self.dirty.reprime();
self.cursor = crate::im::server::ReadCursor::START;
}
pub(crate) fn report_source(
&mut self,
) -> (
&[AttributePath],
&[EventPath],
u64,
&mut crate::im::server::ReadCursor,
) {
let Self {
paths,
dirty,
cursor,
event_paths,
next_event_number,
..
} = self;
let source = if dirty.must_reprime() {
paths.as_slice()
} else {
dirty.paths()
};
(source, event_paths.as_slice(), *next_event_number, cursor)
}
#[must_use]
pub fn earliest_report(&self) -> Instant {
self.last_report
.saturating_add(Duration::from_secs(u64::from(self.min_interval_s)))
}
#[must_use]
pub fn latest_report(&self) -> Instant {
self.last_report
.saturating_add(Duration::from_secs(u64::from(self.max_interval_s)))
}
#[must_use]
pub fn has_pending(&self) -> bool {
self.dirty.is_dirty() || self.urgent
}
#[must_use]
pub fn due(&self, now: Instant) -> Option<ReportReason> {
if now >= self.latest_report() {
return Some(if self.has_pending() {
ReportReason::Data
} else {
ReportReason::KeepAlive
});
}
if self.has_pending() && now >= self.earliest_report() {
return Some(ReportReason::Data);
}
None
}
#[must_use]
pub fn next_deadline(&self) -> Instant {
if self.has_pending() {
self.earliest_report().min(self.latest_report())
} else {
self.latest_report()
}
}
pub fn reported(&mut self, now: Instant) {
self.last_report = now;
self.dirty.clear();
self.cursor = crate::im::server::ReadCursor::START;
self.urgent = false;
self.next_event_number = self.next_event_number.max(self.reported_through);
self.reported_through = 0;
}
pub(crate) fn note_reported_through(&mut self, through: u64) {
self.reported_through = self.reported_through.max(through);
}
#[must_use]
pub fn event_urgency(&self, endpoint: u16, cluster: u32, event: u32) -> Option<bool> {
let mut urgent = None;
for path in &self.event_paths {
let covers = path.endpoint.is_none_or(|wanted| wanted == endpoint)
&& path.cluster.is_none_or(|wanted| wanted == cluster)
&& path.event.is_none_or(|wanted| wanted == event);
if covers {
urgent = Some(urgent.unwrap_or(false) || path.is_urgent.unwrap_or(false));
}
}
urgent
}
pub fn note_event(&mut self, endpoint: u16, cluster: u32, event: u32) -> bool {
match self.event_urgency(endpoint, cluster, event) {
Some(true) => {
self.urgent = true;
true
}
_ => false,
}
}
#[must_use]
pub fn covers(&self, path: &AttributePath) -> bool {
self.paths.iter().any(|subscribed| covers(subscribed, path))
}
pub fn note_change(&mut self, path: &AttributePath) -> bool {
if !self.covers(path) {
return false;
}
self.dirty.insert(*path);
true
}
}
fn covers(subscribed: &AttributePath, concrete: &AttributePath) -> bool {
let matches = |wanted: Option<u32>, have: Option<u32>| match wanted {
None => true,
Some(wanted) => have == Some(wanted),
};
matches(
subscribed.endpoint.map(u32::from),
concrete.endpoint.map(u32::from),
) && matches(subscribed.cluster, concrete.cluster)
&& matches(subscribed.attribute, concrete.attribute)
}
fn intersect_cluster(
subscribed: &AttributePath,
endpoint: EndpointId,
cluster: ClusterId,
) -> Option<AttributePath> {
if subscribed.endpoint.is_some_and(|wanted| wanted != endpoint) {
return None;
}
if subscribed.cluster.is_some_and(|wanted| wanted != cluster) {
return None;
}
Some(AttributePath {
endpoint: Some(endpoint),
cluster: Some(cluster),
attribute: subscribed.attribute,
..*subscribed
})
}
#[derive(Debug)]
pub struct SubscriptionTable<C: Config, const N: usize = 15, const P: usize = 3> {
subscriptions: Vec<Subscription<P>, N>,
last_id: u32,
_config: core::marker::PhantomData<C>,
}
impl<C: Config, const N: usize, const P: usize> crate::config::Capacity
for SubscriptionTable<C, N, P>
{
const TOTAL: usize = N;
const PER_FABRIC: usize = C::SUBSCRIPTIONS_PER_FABRIC;
}
impl<C: Config, const N: usize, const P: usize> crate::config::SubscriptionCapacity
for SubscriptionTable<C, N, P>
{
const PATHS: usize = P;
}
impl<C: Config, const N: usize, const P: usize> SubscriptionTable<C, N, P> {
pub const CHECK: () = {
let () = Self::CHECK;
assert!(
N >= C::SUBSCRIPTIONS_PER_FABRIC * C::FABRICS,
"SubscriptionTable: Core §2.11.2.2 promises SUBSCRIPTIONS_PER_FABRIC to every \
fabric, so the table must hold FABRICS × that many"
);
assert!(
P >= 3,
"SubscriptionTable: Core §2.11.2.2 requires at least 3 paths per subscription"
);
};
}
impl<C: Config, const N: usize, const P: usize> Default for SubscriptionTable<C, N, P> {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubscribeError {
NoPaths,
TooManyPaths,
Full,
FabricQuota,
}
impl SubscribeError {
#[must_use]
pub const fn status(self) -> crate::im::Status {
match self {
Self::NoPaths => crate::im::Status::InvalidAction,
Self::TooManyPaths => crate::im::Status::PathsExhausted,
Self::Full | Self::FabricQuota => crate::im::Status::ResourceExhausted,
}
}
}
impl<C: Config, const N: usize, const P: usize> SubscriptionTable<C, N, P> {
#[must_use]
pub fn new() -> Self {
let () = AssertValid::<C>::CHECK;
Self {
subscriptions: Vec::new(),
last_id: 0,
_config: core::marker::PhantomData,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.subscriptions.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.subscriptions.is_empty()
}
#[must_use]
pub const fn capacity(&self) -> usize {
N
}
pub fn iter(&self) -> impl Iterator<Item = &Subscription<P>> {
self.subscriptions.iter()
}
#[must_use]
pub fn find(&self, id: u32) -> Option<&Subscription<P>> {
self.subscriptions.iter().find(|s| s.id == id)
}
pub fn find_mut(&mut self, id: u32) -> Option<&mut Subscription<P>> {
self.subscriptions.iter_mut().find(|s| s.id == id)
}
pub fn remove(&mut self, id: u32) -> bool {
match self.subscriptions.iter().position(|s| s.id == id) {
Some(index) => {
self.subscriptions.remove(index);
true
}
None => false,
}
}
pub fn remove_for_session(&mut self, session: Option<SessionId>) -> usize {
let before = self.subscriptions.len();
self.subscriptions.retain(|s| s.session != session);
before.saturating_sub(self.subscriptions.len())
}
pub fn remove_for_fabric(&mut self, fabric: FabricIndex) -> usize {
let before = self.subscriptions.len();
self.subscriptions
.retain(|s| s.fabric_index != Some(fabric));
before.saturating_sub(self.subscriptions.len())
}
pub fn note_event(&mut self, endpoint: u16, cluster: u32, event: u32) -> usize {
let mut urgent = 0usize;
for subscription in &mut self.subscriptions {
if subscription.note_event(endpoint, cluster, event) {
urgent = urgent.saturating_add(1);
}
}
urgent
}
pub fn note_change(&mut self, path: &AttributePath) -> usize {
let mut dirtied = 0usize;
for subscription in &mut self.subscriptions {
if subscription.note_change(path) {
dirtied = dirtied.saturating_add(1);
}
}
dirtied
}
pub fn reprime_all(&mut self) {
for subscription in &mut self.subscriptions {
subscription.dirty.reprime();
}
}
#[must_use]
pub fn next_deadline(&self) -> Option<Instant> {
self.subscriptions
.iter()
.filter(|s| s.session.is_some())
.map(Subscription::next_deadline)
.min()
}
pub fn due(&self, now: Instant) -> impl Iterator<Item = (&Subscription<P>, ReportReason)> {
self.subscriptions
.iter()
.filter(|s| s.session.is_some())
.filter_map(move |s| s.due(now).map(|reason| (s, reason)))
}
pub fn subscribe(
&mut self,
request: &NewSubscription<'_>,
now: Instant,
) -> core::result::Result<u32, SubscribeError> {
if !request.keep_subscriptions {
self.remove_for_session(request.session);
}
if request.paths.is_empty() && request.event_paths.is_empty() {
return Err(SubscribeError::NoPaths);
}
if request.paths.len() > P || request.event_paths.len() > P {
return Err(SubscribeError::TooManyPaths);
}
if self.subscriptions.len() >= N {
return Err(SubscribeError::Full);
}
self.admit(request.fabric_index)?;
let mut paths = Vec::new();
for path in request.paths {
paths
.push(*path)
.map_err(|_| SubscribeError::TooManyPaths)?;
}
let mut event_paths = Vec::new();
for path in request.event_paths {
event_paths
.push(*path)
.map_err(|_| SubscribeError::TooManyPaths)?;
}
let id = self.allocate_id();
let subscription = Subscription {
id,
session: request.session,
fabric_index: request.fabric_index,
peer_node_id: request.peer_node_id,
fabric_filtered: request.fabric_filtered,
min_interval_s: request.min_interval_s,
max_interval_s: request.max_interval_s,
paths,
event_paths,
last_report: now,
dirty: DirtySet::new(),
next_event_number: request.min_event_number,
urgent: false,
reported_through: 0,
cursor: crate::im::server::ReadCursor::START,
};
self.subscriptions
.push(subscription)
.map_err(|_| SubscribeError::Full)?;
Ok(id)
}
pub fn note_cluster_change(&mut self, endpoint: EndpointId, cluster: ClusterId) -> usize {
let mut dirtied: usize = 0;
for subscription in &mut self.subscriptions {
let mut hit = false;
let mut overlaps: Vec<AttributePath, P> = Vec::new();
for subscribed in &subscription.paths {
if let Some(path) = intersect_cluster(subscribed, endpoint, cluster) {
let _ = overlaps.push(path);
}
}
for path in overlaps {
subscription.dirty.insert(path);
hit = true;
}
if hit {
dirtied = dirtied.saturating_add(1);
}
}
dirtied
}
pub(crate) fn reserve_id(&mut self, id: u32) {
if id > self.last_id {
self.last_id = id;
}
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Subscription<P>> {
self.subscriptions.iter_mut()
}
pub(crate) fn insert_restored(
&mut self,
durable: crate::im::persist::Durable<P>,
now: Instant,
) -> core::result::Result<(), Error> {
if self.find(durable.id).is_some() {
return Err(Error::new(ErrorCode::AlreadyExists));
}
let mut subscription = Subscription {
id: durable.id,
session: None,
fabric_index: Some(durable.fabric_index),
peer_node_id: Some(durable.peer_node_id),
fabric_filtered: durable.fabric_filtered,
min_interval_s: durable.min_interval_s,
max_interval_s: durable.max_interval_s,
paths: durable.paths,
event_paths: durable.event_paths,
last_report: now,
dirty: DirtySet::new(),
next_event_number: durable.next_event_number,
urgent: false,
reported_through: 0,
cursor: crate::im::server::ReadCursor::START,
};
subscription.reprime();
self.subscriptions
.push(subscription)
.map_err(|_| Error::new(ErrorCode::NoSpace))
}
#[must_use]
pub fn len_of_fabric(&self, fabric: Option<FabricIndex>) -> usize {
self.subscriptions
.iter()
.filter(|s| s.fabric_index == fabric)
.count()
}
fn admit(&self, fabric: Option<FabricIndex>) -> core::result::Result<(), SubscribeError> {
let share = <Self as crate::config::Capacity>::PER_FABRIC;
if fabric.is_some() {
return if self.len_of_fabric(fabric) >= share {
Err(SubscribeError::FabricQuota)
} else {
Ok(())
};
}
let promised = C::FABRICS.saturating_mul(share);
let claimed = self
.subscriptions
.iter()
.filter(|s| s.fabric_index.is_some())
.count();
let still_owed = promised.saturating_sub(claimed);
let free = N.saturating_sub(self.subscriptions.len());
if free > still_owed {
Ok(())
} else {
Err(SubscribeError::Full)
}
}
fn allocate_id(&mut self) -> u32 {
for _ in 0..=u32::from(u16::MAX) {
self.last_id = self.last_id.wrapping_add(1);
if self.last_id != 0 && self.find(self.last_id).is_none() {
return self.last_id;
}
}
self.last_id
}
}
#[derive(Debug, Clone, Copy)]
pub struct NewSubscription<'a> {
pub session: Option<SessionId>,
pub fabric_index: Option<FabricIndex>,
pub peer_node_id: Option<NodeId>,
pub fabric_filtered: bool,
pub keep_subscriptions: bool,
pub min_interval_s: u16,
pub max_interval_s: u16,
pub paths: &'a [AttributePath],
pub event_paths: &'a [EventPath],
pub min_event_number: u64,
}
impl From<SubscribeError> for Error {
fn from(error: SubscribeError) -> Self {
match error {
SubscribeError::NoPaths => Self::new(ErrorCode::InvalidArgument),
SubscribeError::TooManyPaths | SubscribeError::Full | SubscribeError::FabricQuota => {
Self::new(ErrorCode::NoSpace)
}
}
}
}