Skip to main content

matter_kit/im/
subscription.rs

1//! Subscriptions and the reporting engine (Core §8.5, §8.6).
2//!
3//! > This allows the subscriber to maintain a coherent snapshot, or twin, of the subscription
4//! > data as it currently exists on the publisher.
5//!
6//! A subscription is a standing read: the subscriber names some paths once, and the publisher
7//! reports every change to them for the life of the subscription. It is how a light tells a
8//! controller it was switched on at the wall — and it is the only interaction where the
9//! *publisher* decides when to speak.
10//!
11//! # Two intervals, doing opposite jobs
12//!
13//! `MinInterval` is a **floor on frequency**: "Each Report transaction SHALL NOT be initiated
14//! by the publisher until the minimum interval has expired since the last Report transaction."
15//! It is what stops a flapping sensor from flooding a network.
16//!
17//! `MaxInterval` is a **ceiling on silence**: "To keep the subscription alive, a Report
18//! transaction is sent from the publisher every maximum interval, or possibly more
19//! frequently." A report that carries nothing is still a report — it is how the subscriber
20//! knows the publisher is alive, and "If the subscriber does not receive a Report transaction
21//! within the maximum interval from the last Report Data, the subscriber SHALL terminate the
22//! Subscribe interaction."
23//!
24//! So between `last + min` and `last + max` the publisher reports *if it has something*, and
25//! at `last + max` it reports regardless.
26//!
27//! # The negotiation is stranger than it looks
28//!
29//! §8.5.3.2: `MinIntervalFloor ≤ MaxInterval ≤ MAX(SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT,
30//! MaxIntervalCeiling)`.
31//!
32//! That is **`MAX`**, not `MIN`. The upper bound is the *larger* of the publisher's own limit
33//! and what the subscriber asked for — so a publisher may legally stay silent for longer than
34//! the subscriber's ceiling, up to an hour. That is deliberate: §2.11.2.2 sets the limit to
35//! "the Idle Mode Duration or 60 minutes, whichever is greater" for an intermittently
36//! connected device, and a battery-powered sensor that woke every thirty seconds because a
37//! controller asked would not last. Reading it as `MIN` would make an ICD unimplementable.
38//!
39//! # What a report contains
40//!
41//! Every change since the last report — "with the exception of attribute data with the Changes
42//! Omitted (C) quality", which a client must poll for. Tracking those would report values the
43//! specification asks a publisher *not* to report.
44//!
45//! When there is more to say than fits in a [`DirtySet`], the subscription re-primes: it
46//! reports everything it covers. §8.5 permits exactly that — "Including all subscription data
47//! to re-prime the subscription" — so overflowing is degradation, not failure.
48
49use heapless::Vec;
50
51use crate::config::{AssertValid, Config};
52use crate::error::{Error, ErrorCode};
53use crate::im::path::{AttributePath, EventPath};
54use crate::im::{ClusterId, EndpointId};
55use crate::msg::{FabricIndex, NodeId, SessionId};
56use crate::platform::{Duration, Instant};
57
58/// `SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT` (§2.11.2.2) — 60 minutes, in seconds.
59///
60/// "If the publisher is an ICD, this SHALL be set to the Idle Mode Duration or 60 minutes,
61/// whichever is greater. Otherwise, this SHALL be set to 60 minutes." A device with a longer
62/// idle duration raises it through [`SubscriptionPolicy::max_interval_limit_s`].
63pub const MAX_INTERVAL_PUBLISHER_LIMIT_S: u16 = 3600;
64
65/// How a publisher answers a subscriber's requested bounds.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct SubscriptionPolicy {
68    /// `SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT` for this node.
69    ///
70    /// An ICD raises it to its Idle Mode Duration; §2.11.2.2 says "whichever is greater", so
71    /// it is never below [`MAX_INTERVAL_PUBLISHER_LIMIT_S`].
72    pub max_interval_limit_s: u16,
73    /// The interval this publisher would *prefer*, before the subscriber's bounds are applied.
74    ///
75    /// `None` means "honour the subscriber's ceiling", which is the polite default and what a
76    /// mains-powered device should do. A battery-powered one names a longer value here, and
77    /// §8.5.3.2's `MAX(limit, ceiling)` upper bound is what makes that legal.
78    pub preferred_max_interval_s: Option<u16>,
79}
80
81impl Default for SubscriptionPolicy {
82    fn default() -> Self {
83        Self {
84            max_interval_limit_s: MAX_INTERVAL_PUBLISHER_LIMIT_S,
85            preferred_max_interval_s: None,
86        }
87    }
88}
89
90impl SubscriptionPolicy {
91    /// The `MaxInterval` to put in the `SubscribeResponse` (§8.5.3.2).
92    ///
93    /// > This SHALL respect the following constraint: MinIntervalFloor ≤ MaxInterval ≤
94    /// > MAX(SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT, MaxIntervalCeiling)
95    ///
96    /// The floor wins over the ceiling when a subscriber asks for a ceiling below its own
97    /// floor — which is a contradictory request, and the constraint resolves it in exactly one
98    /// direction.
99    #[must_use]
100    pub fn max_interval(&self, floor_s: u16, ceiling_s: u16) -> u16 {
101        let upper = self.max_interval_limit_s.max(ceiling_s);
102        let wanted = self.preferred_max_interval_s.unwrap_or(ceiling_s);
103        wanted.clamp(floor_s.min(upper), upper)
104    }
105}
106
107/// One attribute path that has changed since the last report.
108///
109/// A fixed-capacity set, because a subscription's report must be bounded and a device cannot
110/// allocate. When it fills, the subscription stops tracking individual paths and re-primes on
111/// the next report — §8.5's own recovery: "Including all subscription data to re-prime the
112/// subscription".
113#[derive(Debug, Clone)]
114pub struct DirtySet<const N: usize> {
115    paths: Vec<AttributePath, N>,
116    /// Whether so much changed that the next report has to carry everything.
117    overflowed: bool,
118}
119
120impl<const N: usize> Default for DirtySet<N> {
121    fn default() -> Self {
122        Self::new()
123    }
124}
125
126impl<const N: usize> DirtySet<N> {
127    /// An empty set — nothing has changed.
128    #[must_use]
129    pub const fn new() -> Self {
130        Self {
131            paths: Vec::new(),
132            overflowed: false,
133        }
134    }
135
136    /// Records a change to a concrete path.
137    ///
138    /// Duplicates are dropped: a value that changed twice between reports is reported once,
139    /// with its latest value — §8.5 asks for "the attribute data that has changed", not a
140    /// history of it.
141    pub fn insert(&mut self, path: AttributePath) {
142        if self.overflowed || self.paths.contains(&path) {
143            return;
144        }
145        if self.paths.push(path).is_err() {
146            // More changed than can be listed. Reporting everything is correct and merely
147            // wasteful; reporting a truncated list would leave the subscriber's twin
148            // permanently wrong about whatever fell off the end.
149            self.overflowed = true;
150            self.paths.clear();
151        }
152    }
153
154    /// The changed paths, or empty when the set has overflowed.
155    #[must_use]
156    pub fn paths(&self) -> &[AttributePath] {
157        &self.paths
158    }
159
160    /// Whether anything has changed.
161    #[must_use]
162    pub fn is_dirty(&self) -> bool {
163        self.overflowed || !self.paths.is_empty()
164    }
165
166    /// Whether the next report must carry the whole subscription.
167    #[must_use]
168    pub const fn must_reprime(&self) -> bool {
169        self.overflowed
170    }
171
172    /// Forgets everything — what a completed report does.
173    pub fn clear(&mut self) {
174        self.paths.clear();
175        self.overflowed = false;
176    }
177
178    /// Marks the subscription for a full re-prime.
179    ///
180    /// §8.5: "If the publisher does not receive a Status Response action in response to a
181    /// Report Data action … the publisher MAY terminate the Subscribe interaction or SHALL
182    /// re-synchronize the subscription in the next Report Data transaction by … Including all
183    /// subscription data to re-prime the subscription."
184    pub fn reprime(&mut self) {
185        self.paths.clear();
186        self.overflowed = true;
187    }
188}
189
190/// How many paths one subscription tracks as dirty before it re-primes.
191///
192/// Small on purpose: a device with a hundred subscribed attributes that all change at once is
193/// better served by one full report than by a hundred entries, and the fixed cost per
194/// subscription is what makes a table of them affordable.
195pub const DIRTY_PATHS: usize = 8;
196
197/// One active subscription (§8.5).
198#[derive(Debug, Clone)]
199pub struct Subscription<const P: usize> {
200    /// `SubscriptionId` — "generated by the publisher", unique among its subscriptions.
201    pub id: u32,
202    /// The session it was created on.
203    ///
204    /// §8.5.2.3: "If KeepSubscriptions is FALSE, all existing or pending subscriptions on the
205    /// publisher **for this subscriber** SHALL be terminated" — so a subscription has to
206    /// remember whose it is.
207    pub session: Option<SessionId>,
208    /// The accessing fabric, if the session has one. §2.11.2.2 permits a subscription with
209    /// none: "A server MAY permit Subscribe Interactions even when there is no accessing
210    /// fabric, subject to available resources (e.g over PASE)."
211    pub fabric_index: Option<FabricIndex>,
212    /// Whose subscription it is, as CASE proved it.
213    ///
214    /// A `SessionId` names a session, and a session does not survive a reboot; this names the
215    /// *node*, and does. It is what [`persist`](crate::im::persist) rebinds a restored
216    /// subscription by, and `None` on a PASE session, which has no operational identity.
217    pub peer_node_id: Option<NodeId>,
218    /// `FabricFiltered`, which "SHALL remain in effect for all data reported during the
219    /// interaction" — a one-time parameter that outlives the request carrying it.
220    pub fabric_filtered: bool,
221    /// The negotiated minimum interval, in seconds — the subscriber's requested floor.
222    ///
223    /// §8.5.3.2: the subscription becomes active "with a min interval equal to the requested
224    /// MinIntervalFloor", so the publisher does not choose this one.
225    pub min_interval_s: u16,
226    /// The negotiated maximum interval, in seconds — what went in the `SubscribeResponse`.
227    pub max_interval_s: u16,
228    /// The subscribed attribute paths, as requested. Wildcards are kept as wildcards and
229    /// expanded at report time, so a path that starts matching a newly-added endpoint is
230    /// reported without the subscription being rebuilt.
231    pub paths: Vec<AttributePath, P>,
232    /// When the last report went out.
233    pub last_report: Instant,
234    /// The subscribed event paths, as requested.
235    ///
236    /// Separate from the attribute paths because they behave differently: an attribute change
237    /// dirties a set that a report drains, while an event is *queued* and delivered in order.
238    pub event_paths: Vec<EventPath, P>,
239    /// What has changed since.
240    pub dirty: DirtySet<DIRTY_PATHS>,
241    /// The event number the next report starts from.
242    ///
243    /// §8.5.3.4: "Subsequent ReportData actions, as part of the subscription, SHALL include
244    /// the latest EventNo associated with each node generating new events." This is the
245    /// bookmark that makes that possible — and the reason `EventFilters` is "a one time
246    /// parameter for the priming of the subscription": after the priming report the
247    /// subscription tracks its own position.
248    pub next_event_number: u64,
249    /// Whether an event matching an urgent path has been queued since the last report.
250    ///
251    /// §8.5: "When the IsUrgent flag is TRUE for a subscription's event path in the
252    /// EventPathIB, the queueing of such an event SHALL trigger a Report transaction for the
253    /// subscription, subject to all Report transaction rules." Without the flag, "event
254    /// queueing does not automatically trigger a Report transaction" — the events wait for the
255    /// next report, whenever it happens.
256    urgent: bool,
257    /// One past the highest event number the report currently being built carries, from the
258    /// server rather than from the device. See [`Subscription::reported`].
259    reported_through: u64,
260    /// How far through its current report this subscription has got.
261    ///
262    /// Per subscription, and deliberately not the integrator's to hold: a report over a
263    /// wildcard subscription chunks (§10.2.3), a chunked series spans several messages, and
264    /// two subscribers report concurrently. One cursor shared between them resumes each
265    /// subscriber's report where the *other* one left off, which fails silently — every
266    /// message is well-formed, it just describes the wrong twin.
267    pub(crate) cursor: crate::im::server::ReadCursor,
268}
269
270/// Why a report is due now.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub enum ReportReason {
273    /// Something changed and the minimum interval has passed.
274    ///
275    /// "Something" is an attribute change, a queued urgent event, or a re-prime — all three
276    /// produce a report that carries data and expects a `StatusResponse`.
277    Data,
278    /// Nothing changed, but the maximum interval has — "to keep the subscription alive".
279    ///
280    /// §8.6.2's Report Transaction Empty: "report with no data or events with
281    /// SuppressResponse set to TRUE". An empty report needs no acknowledgement, because
282    /// its only job is to prove the publisher is still there.
283    KeepAlive,
284}
285
286impl<const P: usize> Subscription<P> {
287    /// Marks every path dirty, so the next report is a full one (§8.5.3.4).
288    ///
289    /// What a re-prime says is not "these things changed" but "I no longer know what you
290    /// have" — after a dirty-set overflow, or after a reboot, the subscriber's twin is
291    /// unknown rather than stale in some identified way.
292    pub fn reprime(&mut self) {
293        self.dirty.reprime();
294        // Re-priming swaps the dirty set for the full path list. A cursor part-way through
295        // the old list indexes the new one meaninglessly, so the series restarts — the
296        // subscriber may see a path twice, which is recoverable, rather than miss one, which
297        // is not.
298        self.cursor = crate::im::server::ReadCursor::START;
299    }
300
301    /// The paths this subscription's next report draws from, and where it is up to.
302    ///
303    /// One call, because the two are a matched pair: the cursor indexes *this* list, and
304    /// handing them out separately is what lets them drift apart.
305    pub(crate) fn report_source(
306        &mut self,
307    ) -> (
308        &[AttributePath],
309        &[EventPath],
310        u64,
311        &mut crate::im::server::ReadCursor,
312    ) {
313        let Self {
314            paths,
315            dirty,
316            cursor,
317            event_paths,
318            next_event_number,
319            ..
320        } = self;
321        // §8.5.3.4: a re-primed subscription reports everything it subscribed to; otherwise
322        // it reports only what changed.
323        let source = if dirty.must_reprime() {
324            paths.as_slice()
325        } else {
326            dirty.paths()
327        };
328        (source, event_paths.as_slice(), *next_event_number, cursor)
329    }
330
331    /// The earliest a report may go out — `last_report + min_interval`.
332    #[must_use]
333    pub fn earliest_report(&self) -> Instant {
334        self.last_report
335            .saturating_add(Duration::from_secs(u64::from(self.min_interval_s)))
336    }
337
338    /// The latest a report may go out — `last_report + max_interval`.
339    #[must_use]
340    pub fn latest_report(&self) -> Instant {
341        self.last_report
342            .saturating_add(Duration::from_secs(u64::from(self.max_interval_s)))
343    }
344
345    /// Whether anything is waiting to be reported.
346    ///
347    /// An attribute change, or an event queued against a path the subscriber marked urgent.
348    /// A non-urgent event is *not* pending: §8.5 says its queueing "does not automatically
349    /// trigger a Report transaction", and it rides out with the next one.
350    #[must_use]
351    pub fn has_pending(&self) -> bool {
352        self.dirty.is_dirty() || self.urgent
353    }
354
355    /// Whether a report is due now, and why.
356    ///
357    /// The two rules, in the order they bind: nothing before the minimum interval, and
358    /// something by the maximum. In between, a report goes out exactly when there is
359    /// something to say — "Attribute changes SHALL be delivered as soon as possible, taking
360    /// into account the minimum interval".
361    #[must_use]
362    pub fn due(&self, now: Instant) -> Option<ReportReason> {
363        if now >= self.latest_report() {
364            // The keep-alive deadline binds even when nothing changed — and when something
365            // did, this is still a data report.
366            return Some(if self.has_pending() {
367                ReportReason::Data
368            } else {
369                ReportReason::KeepAlive
370            });
371        }
372        if self.has_pending() && now >= self.earliest_report() {
373            return Some(ReportReason::Data);
374        }
375        None
376    }
377
378    /// When this subscription next needs attention.
379    ///
380    /// A device sleeps until the earliest deadline across its subscriptions; an
381    /// intermittently connected one uses it to decide whether it can stay idle. Dirty data
382    /// pulls the deadline in to the minimum interval, clean data leaves it at the maximum.
383    #[must_use]
384    pub fn next_deadline(&self) -> Instant {
385        if self.has_pending() {
386            self.earliest_report().min(self.latest_report())
387        } else {
388            self.latest_report()
389        }
390    }
391
392    /// Records that a report went out, resetting both timers and everything pending.
393    ///
394    /// The event bookmark comes from the report the server built, not from the caller.
395    /// [`Server::report_chunk`](crate::im::Server::report_chunk) leaves
396    /// [`ReadOutcome::events_through`](crate::im::server::ReadOutcome::events_through) here as
397    /// it writes, so §8.5.3.4's "the next report resumes after the last event delivered" is a
398    /// fact the server already has rather than a number the device is asked to reconstruct.
399    ///
400    /// Not a parameter, because it is not a number a caller can compute: a report is built path
401    /// by path and the cursor's position is reset between them, so the answer every caller
402    /// reaches for is `0` — and a bookmark stuck at zero re-sends the subscriber's whole event
403    /// history on every report, for the life of the subscription.
404    pub fn reported(&mut self, now: Instant) {
405        self.last_report = now;
406        self.dirty.clear();
407        // The next report is a new series over a different path list, so it starts at the
408        // beginning rather than wherever this one ended.
409        self.cursor = crate::im::server::ReadCursor::START;
410        self.urgent = false;
411        self.next_event_number = self.next_event_number.max(self.reported_through);
412        // Consumed: the next series accumulates its own, and a report that carries no events
413        // must not re-apply the last one's.
414        self.reported_through = 0;
415    }
416
417    /// Where the report the server has just built left the event bookmark.
418    ///
419    /// Set by [`Server::report_chunk`](crate::im::Server::report_chunk) and consumed by
420    /// [`reported`](Self::reported), which is only called once the report has actually gone
421    /// out: a report that was built and never sent must not advance the bookmark past events
422    /// the subscriber never saw.
423    pub(crate) fn note_reported_through(&mut self, through: u64) {
424        self.reported_through = self.reported_through.max(through);
425    }
426
427    /// Whether this subscription asked for `path`, and whether it asked urgently.
428    ///
429    /// Returns `None` when no subscribed path covers the event. §10.6.8's `IsUrgent` is a
430    /// property of the *path*, not of the event, so the same event may be urgent to one
431    /// subscriber and not to another.
432    #[must_use]
433    pub fn event_urgency(&self, endpoint: u16, cluster: u32, event: u32) -> Option<bool> {
434        let mut urgent = None;
435        for path in &self.event_paths {
436            let covers = path.endpoint.is_none_or(|wanted| wanted == endpoint)
437                && path.cluster.is_none_or(|wanted| wanted == cluster)
438                && path.event.is_none_or(|wanted| wanted == event);
439            if covers {
440                // Several paths may cover one event; urgency is the union, because a
441                // subscriber that asked urgently anywhere asked urgently.
442                urgent = Some(urgent.unwrap_or(false) || path.is_urgent.unwrap_or(false));
443            }
444        }
445        urgent
446    }
447
448    /// Records that an event was queued, if this subscription wants it.
449    ///
450    /// Returns whether the event triggers a report — which is only when the subscriber marked
451    /// the path urgent. §8.5: "When the IsUrgent flag is FALSE or absent … event queueing does
452    /// not automatically trigger a Report transaction."
453    pub fn note_event(&mut self, endpoint: u16, cluster: u32, event: u32) -> bool {
454        match self.event_urgency(endpoint, cluster, event) {
455            Some(true) => {
456                self.urgent = true;
457                true
458            }
459            _ => false,
460        }
461    }
462
463    /// Whether this subscription covers `path` — the test a change has to pass before it
464    /// dirties anything.
465    ///
466    /// A subscribed path may be a wildcard, so this is containment rather than equality: a
467    /// subscription to "every attribute of cluster 6 on every endpoint" is dirtied by a
468    /// change to endpoint 1's `OnOff`.
469    #[must_use]
470    pub fn covers(&self, path: &AttributePath) -> bool {
471        self.paths.iter().any(|subscribed| covers(subscribed, path))
472    }
473
474    /// Records a change, if this subscription covers it.
475    ///
476    /// Returns whether it did, so a caller can tell whether a report is now pending.
477    pub fn note_change(&mut self, path: &AttributePath) -> bool {
478        if !self.covers(path) {
479            return false;
480        }
481        self.dirty.insert(*path);
482        true
483    }
484}
485
486/// Whether `subscribed` — possibly a wildcard — names `concrete`.
487///
488/// §10.6.2.1: "omission of any of the tags in question … indicates wildcard semantics", so an
489/// absent field matches anything. `Node` is the exception and is not compared: a path with a
490/// node id names *this* node, which is the only node a subscription can be about.
491fn covers(subscribed: &AttributePath, concrete: &AttributePath) -> bool {
492    let matches = |wanted: Option<u32>, have: Option<u32>| match wanted {
493        None => true,
494        Some(wanted) => have == Some(wanted),
495    };
496    matches(
497        subscribed.endpoint.map(u32::from),
498        concrete.endpoint.map(u32::from),
499    ) && matches(subscribed.cluster, concrete.cluster)
500        && matches(subscribed.attribute, concrete.attribute)
501}
502
503/// Whether a subscribed path and a whole cluster instance overlap, and what of the
504/// subscription falls inside it.
505///
506/// This is *not* [`covers`], and the difference is the whole point. `covers` asks whether a
507/// subscribed wildcard names one concrete attribute; this asks whether a subscription and a
508/// changed cluster have anything in common. A subscription on
509/// `(endpoint 0, cluster 0x0030, attribute 0x0000)` overlaps a change to all of
510/// `(0, 0x0030)` — `covers` would say no, because an absent attribute on the *changed* side is
511/// not a wildcard, it is "no attribute named".
512///
513/// What comes back is the intersection, which is what belongs in the dirty set: the changed
514/// cluster with the subscription's own attribute, or the whole cluster when the subscription
515/// asked for all of it.
516fn intersect_cluster(
517    subscribed: &AttributePath,
518    endpoint: EndpointId,
519    cluster: ClusterId,
520) -> Option<AttributePath> {
521    if subscribed.endpoint.is_some_and(|wanted| wanted != endpoint) {
522        return None;
523    }
524    if subscribed.cluster.is_some_and(|wanted| wanted != cluster) {
525        return None;
526    }
527    Some(AttributePath {
528        endpoint: Some(endpoint),
529        cluster: Some(cluster),
530        attribute: subscribed.attribute,
531        ..*subscribed
532    })
533}
534
535/// The publisher's set of active subscriptions.
536///
537/// Fixed capacity from `N`, which [`SubscriptionTable::CHECK`] holds to
538/// §2.11.2.2's "at least three Subscribe Interactions" per fabric.
539#[derive(Debug)]
540pub struct SubscriptionTable<C: Config, const N: usize = 15, const P: usize = 3> {
541    subscriptions: Vec<Subscription<P>, N>,
542    /// The last id handed out. Ids are monotonic for the same reason fabric indices are: a
543    /// subscriber caches one, and reusing it points a stale reference at somebody else's
544    /// subscription.
545    last_id: u32,
546    _config: core::marker::PhantomData<C>,
547}
548
549impl<C: Config, const N: usize, const P: usize> crate::config::Capacity
550    for SubscriptionTable<C, N, P>
551{
552    const TOTAL: usize = N;
553    /// §11.1.4.4's `SubscriptionsPerFabric`: the fixed share each fabric is promised.
554    ///
555    /// The policy figure rather than `N / FABRICS`, because the share is what
556    /// `SubscriptionTable::admit` enforces — and [`SubscriptionTable::CHECK`] is what makes
557    /// the two agree.
558    const PER_FABRIC: usize = C::SUBSCRIPTIONS_PER_FABRIC;
559}
560
561impl<C: Config, const N: usize, const P: usize> crate::config::SubscriptionCapacity
562    for SubscriptionTable<C, N, P>
563{
564    const PATHS: usize = P;
565}
566
567impl<C: Config, const N: usize, const P: usize> SubscriptionTable<C, N, P> {
568    /// Compile-time proof that this table can keep §2.11.2.2's promise.
569    ///
570    /// > A publisher SHALL ensure that every fabric the node is commissioned into can support
571    /// > at least three Subscribe Interactions to the publisher.
572    ///
573    /// A promise of `SUBSCRIPTIONS_PER_FABRIC` to each of `FABRICS` fabrics needs room for
574    /// their product. Without this the node advertises a guarantee it cannot keep, and the
575    /// fabric that finds out is the last one commissioned.
576    pub const CHECK: () = {
577        let () = Self::CHECK;
578        assert!(
579            N >= C::SUBSCRIPTIONS_PER_FABRIC * C::FABRICS,
580            "SubscriptionTable: Core §2.11.2.2 promises SUBSCRIPTIONS_PER_FABRIC to every \
581             fabric, so the table must hold FABRICS × that many"
582        );
583        assert!(
584            P >= 3,
585            "SubscriptionTable: Core §2.11.2.2 requires at least 3 paths per subscription"
586        );
587    };
588}
589
590impl<C: Config, const N: usize, const P: usize> Default for SubscriptionTable<C, N, P> {
591    fn default() -> Self {
592        Self::new()
593    }
594}
595
596/// Why a `SubscribeRequest` was refused.
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
598pub enum SubscribeError {
599    /// §8.5.2.2: "At least one attribute or event SHALL be indicated in the action."
600    NoPaths,
601    /// More paths than the table's `P` admits — §11.1.4.4's `SubscribePathsSupported`.
602    TooManyPaths,
603    /// More subscriptions than the table's `N` admits. §8.10's `RESOURCE_EXHAUSTED`.
604    Full,
605    /// This fabric already holds [`Config::SUBSCRIPTIONS_PER_FABRIC`] subscriptions.
606    ///
607    /// Distinct from [`SubscribeError::Full`] because the table may have plenty of room: the
608    /// slots left are promised to *other* fabrics, and handing them out would break §2.11.2.2's
609    /// guarantee that "every fabric the node is commissioned into can support at least three
610    /// Subscribe Interactions". Both answer `RESOURCE_EXHAUSTED` on the wire — there is no
611    /// status for "not yours" — but an integrator reading a log needs to tell them apart.
612    FabricQuota,
613}
614
615impl SubscribeError {
616    /// The status a `StatusResponse` carries for this refusal.
617    #[must_use]
618    pub const fn status(self) -> crate::im::Status {
619        match self {
620            // §8.10.1: "INVALID_ACTION — the request is malformed, has missing fields, or
621            // fields with invalid values." A subscription to nothing is all three.
622            Self::NoPaths => crate::im::Status::InvalidAction,
623            // §8.10.1's `PATHS_EXHAUSTED`: "The request is not possible due to the number of
624            // paths requested."
625            Self::TooManyPaths => crate::im::Status::PathsExhausted,
626            Self::Full | Self::FabricQuota => crate::im::Status::ResourceExhausted,
627        }
628    }
629}
630
631impl<C: Config, const N: usize, const P: usize> SubscriptionTable<C, N, P> {
632    /// An empty table.
633    #[must_use]
634    pub fn new() -> Self {
635        let () = AssertValid::<C>::CHECK;
636        Self {
637            subscriptions: Vec::new(),
638            last_id: 0,
639            _config: core::marker::PhantomData,
640        }
641    }
642
643    /// How many subscriptions are active.
644    #[must_use]
645    pub fn len(&self) -> usize {
646        self.subscriptions.len()
647    }
648
649    /// Whether none are.
650    #[must_use]
651    pub fn is_empty(&self) -> bool {
652        self.subscriptions.is_empty()
653    }
654
655    /// How many this node can serve.
656    #[must_use]
657    pub const fn capacity(&self) -> usize {
658        N
659    }
660
661    /// The subscriptions, in creation order.
662    pub fn iter(&self) -> impl Iterator<Item = &Subscription<P>> {
663        self.subscriptions.iter()
664    }
665
666    /// The subscription with this id.
667    #[must_use]
668    pub fn find(&self, id: u32) -> Option<&Subscription<P>> {
669        self.subscriptions.iter().find(|s| s.id == id)
670    }
671
672    /// The subscription with this id, mutably.
673    pub fn find_mut(&mut self, id: u32) -> Option<&mut Subscription<P>> {
674        self.subscriptions.iter_mut().find(|s| s.id == id)
675    }
676
677    /// Ends a subscription.
678    ///
679    /// §8.5: "When a Subscribe interaction is terminated on the publisher or subscriber, the
680    /// subscription, identified by a SubscriptionId, SHALL also be terminated."
681    pub fn remove(&mut self, id: u32) -> bool {
682        match self.subscriptions.iter().position(|s| s.id == id) {
683            Some(index) => {
684                self.subscriptions.remove(index);
685                true
686            }
687            None => false,
688        }
689    }
690
691    /// Ends every subscription belonging to one session — §8.5.2.3's `KeepSubscriptions`.
692    ///
693    /// > If KeepSubscriptions is FALSE, all existing or pending subscriptions on the publisher
694    /// > for this subscriber SHALL be terminated.
695    ///
696    /// Returns how many went. A subscriber that re-subscribes without the flag is saying "I
697    /// have restarted, forget what you knew about me" — and a publisher that kept the old
698    /// subscriptions would report to a twin that no longer exists until the maximum interval
699    /// ran out on each.
700    pub fn remove_for_session(&mut self, session: Option<SessionId>) -> usize {
701        let before = self.subscriptions.len();
702        self.subscriptions.retain(|s| s.session != session);
703        before.saturating_sub(self.subscriptions.len())
704    }
705
706    /// Ends every subscription scoped to a fabric — what `RemoveFabric` cascades into.
707    pub fn remove_for_fabric(&mut self, fabric: FabricIndex) -> usize {
708        let before = self.subscriptions.len();
709        self.subscriptions
710            .retain(|s| s.fabric_index != Some(fabric));
711        before.saturating_sub(self.subscriptions.len())
712    }
713
714    /// Records a queued event against every subscription that wants it.
715    ///
716    /// Returns how many were made *pending* — that is, how many had marked the path urgent.
717    /// A subscription that wants the event but did not ask urgently still receives it, on
718    /// whatever report happens next; §8.5 is explicit that non-urgent queueing "does not
719    /// automatically trigger a Report transaction".
720    pub fn note_event(&mut self, endpoint: u16, cluster: u32, event: u32) -> usize {
721        let mut urgent = 0usize;
722        for subscription in &mut self.subscriptions {
723            if subscription.note_event(endpoint, cluster, event) {
724                urgent = urgent.saturating_add(1);
725            }
726        }
727        urgent
728    }
729
730    /// Records a change against every subscription that covers it.
731    ///
732    /// This is the whole of the reporting engine's input: a cluster whose value changed calls
733    /// it once, and each subscription decides for itself whether it cares and when it will
734    /// say so.
735    ///
736    /// **Not** for an attribute with the `C` quality. §8.5: a report carries every change
737    /// "with the exception of attribute data with the Changes Omitted (C) quality" — a client
738    /// polls for those, and reporting one would be reporting what the specification asked a
739    /// publisher not to.
740    pub fn note_change(&mut self, path: &AttributePath) -> usize {
741        let mut dirtied = 0usize;
742        for subscription in &mut self.subscriptions {
743            if subscription.note_change(path) {
744                dirtied = dirtied.saturating_add(1);
745            }
746        }
747        dirtied
748    }
749
750    /// Marks every subscription for a full re-prime — what a lost acknowledgement calls for.
751    pub fn reprime_all(&mut self) {
752        for subscription in &mut self.subscriptions {
753            subscription.dirty.reprime();
754        }
755    }
756
757    /// The earliest moment any subscription needs attention, if there are any.
758    ///
759    /// A device sleeps until this. An intermittently connected one uses it to decide whether
760    /// it can stay idle, which is why §2.11.2.2 lets it choose a long maximum interval.
761    ///
762    /// Unbound subscriptions are skipped for the same reason [`SubscriptionTable::due`] skips
763    /// them: waking for one would be waking to do nothing.
764    #[must_use]
765    pub fn next_deadline(&self) -> Option<Instant> {
766        self.subscriptions
767            .iter()
768            .filter(|s| s.session.is_some())
769            .map(Subscription::next_deadline)
770            .min()
771    }
772
773    /// The subscriptions with a report due at `now`, and why.
774    ///
775    /// A subscription with no session is skipped however overdue it is, because there is
776    /// nowhere to send the report — that is the state a subscription restored from storage
777    /// begins in ([`persist`](crate::im::persist)), waiting for its subscriber to come back
778    /// on a new CASE session. Handing it to a caller that could only discard it would make
779    /// every poll return work that cannot be done.
780    pub fn due(&self, now: Instant) -> impl Iterator<Item = (&Subscription<P>, ReportReason)> {
781        self.subscriptions
782            .iter()
783            .filter(|s| s.session.is_some())
784            .filter_map(move |s| s.due(now).map(|reason| (s, reason)))
785    }
786
787    /// Creates a subscription, allocating an id.
788    ///
789    /// `keep_subscriptions` is the request's flag: when false, every existing subscription
790    /// for this session goes first (§8.5.2.3). That happens *before* the capacity check, so a
791    /// subscriber re-subscribing at the table's limit succeeds rather than being refused with
792    /// its own stale subscriptions in the way.
793    pub fn subscribe(
794        &mut self,
795        request: &NewSubscription<'_>,
796        now: Instant,
797    ) -> core::result::Result<u32, SubscribeError> {
798        if !request.keep_subscriptions {
799            self.remove_for_session(request.session);
800        }
801        // §8.5.2.2: "At least one attribute or event SHALL be indicated in the action." An
802        // event-only subscription is perfectly ordinary — a door lock reporting `LockOperation`
803        // subscribes to no attribute at all.
804        if request.paths.is_empty() && request.event_paths.is_empty() {
805            return Err(SubscribeError::NoPaths);
806        }
807        if request.paths.len() > P || request.event_paths.len() > P {
808            return Err(SubscribeError::TooManyPaths);
809        }
810        if self.subscriptions.len() >= N {
811            return Err(SubscribeError::Full);
812        }
813        self.admit(request.fabric_index)?;
814
815        let mut paths = Vec::new();
816        for path in request.paths {
817            paths
818                .push(*path)
819                .map_err(|_| SubscribeError::TooManyPaths)?;
820        }
821        let mut event_paths = Vec::new();
822        for path in request.event_paths {
823            event_paths
824                .push(*path)
825                .map_err(|_| SubscribeError::TooManyPaths)?;
826        }
827        let id = self.allocate_id();
828        let subscription = Subscription {
829            id,
830            session: request.session,
831            fabric_index: request.fabric_index,
832            peer_node_id: request.peer_node_id,
833            fabric_filtered: request.fabric_filtered,
834            min_interval_s: request.min_interval_s,
835            max_interval_s: request.max_interval_s,
836            paths,
837            event_paths,
838            // §8.5.3.4: "Upon subscription activation, the minimum and maximum interval
839            // parameters SHALL take effect" — and the priming report is the first report, so
840            // both timers start from it.
841            last_report: now,
842            dirty: DirtySet::new(),
843            // `EventFilters` is "a one time parameter for the priming of the subscription",
844            // so the subscriber's minimum event number starts the bookmark and the
845            // subscription keeps its own position from then on.
846            next_event_number: request.min_event_number,
847            urgent: false,
848            reported_through: 0,
849            cursor: crate::im::server::ReadCursor::START,
850        };
851        self.subscriptions
852            .push(subscription)
853            .map_err(|_| SubscribeError::Full)?;
854        Ok(id)
855    }
856
857    /// Records that an attribute of one cluster instance changed, dirtying every subscription
858    /// that overlaps it. Returns how many.
859    ///
860    /// This is the cluster-grained counterpart to [`SubscriptionTable::note_change`], and it is
861    /// what [`DataVersions::drain_changes`](crate::dm::DataVersions::drain_changes) feeds. The
862    /// grain is the cluster because that is the grain §7.10.3 records changes at: "A cluster
863    /// data version SHALL be incremented if any attribute data changes" says *which cluster*,
864    /// never which attribute.
865    ///
866    /// Reporting a whole cluster when one attribute of it moved is more than the minimum and
867    /// never less, which is the safe direction: §8.5 already allows a report to carry more than
868    /// changed — a re-prime carries everything — and a subscriber that is told too much is
869    /// correct where one that is told too little is not.
870    pub fn note_cluster_change(&mut self, endpoint: EndpointId, cluster: ClusterId) -> usize {
871        let mut dirtied: usize = 0;
872        for subscription in &mut self.subscriptions {
873            let mut hit = false;
874            // Collected first: `paths` is borrowed while it is walked, and the dirty set it
875            // feeds lives on the same subscription.
876            let mut overlaps: Vec<AttributePath, P> = Vec::new();
877            for subscribed in &subscription.paths {
878                if let Some(path) = intersect_cluster(subscribed, endpoint, cluster) {
879                    let _ = overlaps.push(path);
880                }
881            }
882            for path in overlaps {
883                subscription.dirty.insert(path);
884                hit = true;
885            }
886            if hit {
887                dirtied = dirtied.saturating_add(1);
888            }
889        }
890        dirtied
891    }
892
893    /// Ensures the next allocated id is above `id`, which restoring a persisted subscription
894    /// needs (§8.5.3.1's ids must stay unique across a reboot).
895    pub(crate) fn reserve_id(&mut self, id: u32) {
896        if id > self.last_id {
897            self.last_id = id;
898        }
899    }
900
901    /// Every subscription, mutably.
902    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Subscription<P>> {
903        self.subscriptions.iter_mut()
904    }
905
906    /// Adds a subscription restored from storage, keeping its id.
907    ///
908    /// Separate from [`SubscriptionTable::subscribe`] because none of that method's work
909    /// applies: there is no request to validate, no id to allocate, and — crucially — no
910    /// `KeepSubscriptions` rule to apply, since a restored subscription must not terminate
911    /// another restored one belonging to the same subscriber. They were all agreed before the
912    /// reboot and all of them are still owed.
913    pub(crate) fn insert_restored(
914        &mut self,
915        durable: crate::im::persist::Durable<P>,
916        now: Instant,
917    ) -> core::result::Result<(), Error> {
918        if self.find(durable.id).is_some() {
919            return Err(Error::new(ErrorCode::AlreadyExists));
920        }
921        let mut subscription = Subscription {
922            id: durable.id,
923            // Deliberately not restored: a session id from before the reboot names whatever
924            // session holds that number now, which is at best nobody and at worst somebody
925            // else. `persist::rebind` supplies the real one.
926            session: None,
927            fabric_index: Some(durable.fabric_index),
928            peer_node_id: Some(durable.peer_node_id),
929            fabric_filtered: durable.fabric_filtered,
930            min_interval_s: durable.min_interval_s,
931            max_interval_s: durable.max_interval_s,
932            paths: durable.paths,
933            event_paths: durable.event_paths,
934            // The clock restarted at zero; treating a stored instant as elapsed time would
935            // either fire a report immediately or suppress one for as long as the device was
936            // off.
937            last_report: now,
938            dirty: DirtySet::new(),
939            next_event_number: durable.next_event_number,
940            urgent: false,
941            reported_through: 0,
942            cursor: crate::im::server::ReadCursor::START,
943        };
944        // The device has no record of what changed while it was off, so nothing about the
945        // subscriber's twin can be trusted — it is unknown rather than stale in some
946        // identified way. §8.5.3.4's priming report is the only honest answer.
947        subscription.reprime();
948        self.subscriptions
949            .push(subscription)
950            .map_err(|_| Error::new(ErrorCode::NoSpace))
951    }
952
953    /// How many subscriptions one fabric holds. `None` counts the fabric-less ones.
954    #[must_use]
955    pub fn len_of_fabric(&self, fabric: Option<FabricIndex>) -> usize {
956        self.subscriptions
957            .iter()
958            .filter(|s| s.fabric_index == fabric)
959            .count()
960    }
961
962    /// §2.11.2.2's per-fabric guarantee, applied to one arriving request.
963    ///
964    /// A fabric-scoped subscription gets a fixed share. A fabric-*less* one — §2.11.2.2 permits
965    /// them "subject to available resources (e.g over PASE)" — gets only what is not promised
966    /// to a fabric, because a `MAY` must never consume a `SHALL`. On a node sized to the
967    /// minimum there is nothing left over and PASE subscriptions are refused, which is what
968    /// "subject to available resources" means when there are none.
969    fn admit(&self, fabric: Option<FabricIndex>) -> core::result::Result<(), SubscribeError> {
970        let share = <Self as crate::config::Capacity>::PER_FABRIC;
971        if fabric.is_some() {
972            return if self.len_of_fabric(fabric) >= share {
973                Err(SubscribeError::FabricQuota)
974            } else {
975                Ok(())
976            };
977        }
978        // `Self::CHECK` has already refused, at compile time, a table too small to owe every
979        // fabric its share — so this subtraction cannot be hiding a promise the node has
980        // already broken.
981        let promised = C::FABRICS.saturating_mul(share);
982        let claimed = self
983            .subscriptions
984            .iter()
985            .filter(|s| s.fabric_index.is_some())
986            .count();
987        let still_owed = promised.saturating_sub(claimed);
988        let free = N.saturating_sub(self.subscriptions.len());
989        if free > still_owed {
990            Ok(())
991        } else {
992            Err(SubscribeError::Full)
993        }
994    }
995
996    /// Allocates the next unused id, never zero.
997    ///
998    /// Monotonic and wrapping, like a fabric index and for the same reason: a subscriber
999    /// caches its id, and handing a freed one straight back out would point a stale
1000    /// `SubscriptionId` at somebody else's subscription. Zero is skipped so that it can mean
1001    /// "no subscription" in a caller's own bookkeeping.
1002    fn allocate_id(&mut self) -> u32 {
1003        for _ in 0..=u32::from(u16::MAX) {
1004            self.last_id = self.last_id.wrapping_add(1);
1005            if self.last_id != 0 && self.find(self.last_id).is_none() {
1006                return self.last_id;
1007            }
1008        }
1009        // Unreachable while `N` is far below the id space; returning a duplicate would be
1010        // worse than returning one that is merely unlikely to collide.
1011        self.last_id
1012    }
1013}
1014
1015/// What a `SubscribeRequest` asks for, after its paths have been validated.
1016#[derive(Debug, Clone, Copy)]
1017pub struct NewSubscription<'a> {
1018    /// The session the request arrived on.
1019    pub session: Option<SessionId>,
1020    /// The accessing fabric, if any.
1021    pub fabric_index: Option<FabricIndex>,
1022    /// The subscriber's operational Node ID, from the session (§6.6.6.3). `None` over PASE.
1023    pub peer_node_id: Option<NodeId>,
1024    /// `FabricFiltered`.
1025    pub fabric_filtered: bool,
1026    /// `KeepSubscriptions`.
1027    pub keep_subscriptions: bool,
1028    /// The negotiated minimum interval — the request's `MinIntervalFloor`.
1029    pub min_interval_s: u16,
1030    /// The negotiated maximum interval, from [`SubscriptionPolicy::max_interval`].
1031    pub max_interval_s: u16,
1032    /// The attribute paths, as requested.
1033    pub paths: &'a [AttributePath],
1034    /// The event paths, as requested.
1035    pub event_paths: &'a [EventPath],
1036    /// The lowest event number to report, from the request's `EventFilters`.
1037    ///
1038    /// §8.5.3.4: "The EventFilters and DataVersionFilters fields in the Subscribe Request are
1039    /// one time parameters for the priming of the subscription" — so this seeds the bookmark
1040    /// and is never consulted again.
1041    pub min_event_number: u64,
1042}
1043
1044/// Builds the `Err` for a refusal, so a caller can answer a `StatusResponse`.
1045impl From<SubscribeError> for Error {
1046    fn from(error: SubscribeError) -> Self {
1047        match error {
1048            SubscribeError::NoPaths => Self::new(ErrorCode::InvalidArgument),
1049            SubscribeError::TooManyPaths | SubscribeError::Full | SubscribeError::FabricQuota => {
1050                Self::new(ErrorCode::NoSpace)
1051            }
1052        }
1053    }
1054}