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 [`Config::SUBSCRIPTIONS`] 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 [`Config::SUBSCRIPTIONS`], whose compile-time assert holds it 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, const P: usize> {
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> Default for SubscriptionTable<C, N, P> {
550    fn default() -> Self {
551        Self::new()
552    }
553}
554
555/// Why a `SubscribeRequest` was refused.
556#[derive(Debug, Clone, Copy, PartialEq, Eq)]
557pub enum SubscribeError {
558    /// §8.5.2.2: "At least one attribute or event SHALL be indicated in the action."
559    NoPaths,
560    /// More paths than [`Config::SUB_PATHS`] admits.
561    TooManyPaths,
562    /// More subscriptions than [`Config::SUBSCRIPTIONS`] admits. §8.10's `RESOURCE_EXHAUSTED`.
563    Full,
564    /// This fabric already holds [`Config::SUBSCRIPTIONS_PER_FABRIC`] subscriptions.
565    ///
566    /// Distinct from [`SubscribeError::Full`] because the table may have plenty of room: the
567    /// slots left are promised to *other* fabrics, and handing them out would break §2.11.2.2's
568    /// guarantee that "every fabric the node is commissioned into can support at least three
569    /// Subscribe Interactions". Both answer `RESOURCE_EXHAUSTED` on the wire — there is no
570    /// status for "not yours" — but an integrator reading a log needs to tell them apart.
571    FabricQuota,
572}
573
574impl SubscribeError {
575    /// The status a `StatusResponse` carries for this refusal.
576    #[must_use]
577    pub const fn status(self) -> crate::im::Status {
578        match self {
579            // §8.10.1: "INVALID_ACTION — the request is malformed, has missing fields, or
580            // fields with invalid values." A subscription to nothing is all three.
581            Self::NoPaths => crate::im::Status::InvalidAction,
582            // §8.10.1's `PATHS_EXHAUSTED`: "The request is not possible due to the number of
583            // paths requested."
584            Self::TooManyPaths => crate::im::Status::PathsExhausted,
585            Self::Full | Self::FabricQuota => crate::im::Status::ResourceExhausted,
586        }
587    }
588}
589
590impl<C: Config, const N: usize, const P: usize> SubscriptionTable<C, N, P> {
591    /// An empty table.
592    #[must_use]
593    pub fn new() -> Self {
594        let () = AssertValid::<C>::CHECK;
595        Self {
596            subscriptions: Vec::new(),
597            last_id: 0,
598            _config: core::marker::PhantomData,
599        }
600    }
601
602    /// How many subscriptions are active.
603    #[must_use]
604    pub fn len(&self) -> usize {
605        self.subscriptions.len()
606    }
607
608    /// Whether none are.
609    #[must_use]
610    pub fn is_empty(&self) -> bool {
611        self.subscriptions.is_empty()
612    }
613
614    /// How many this node can serve.
615    #[must_use]
616    pub const fn capacity(&self) -> usize {
617        N
618    }
619
620    /// The subscriptions, in creation order.
621    pub fn iter(&self) -> impl Iterator<Item = &Subscription<P>> {
622        self.subscriptions.iter()
623    }
624
625    /// The subscription with this id.
626    #[must_use]
627    pub fn find(&self, id: u32) -> Option<&Subscription<P>> {
628        self.subscriptions.iter().find(|s| s.id == id)
629    }
630
631    /// The subscription with this id, mutably.
632    pub fn find_mut(&mut self, id: u32) -> Option<&mut Subscription<P>> {
633        self.subscriptions.iter_mut().find(|s| s.id == id)
634    }
635
636    /// Ends a subscription.
637    ///
638    /// §8.5: "When a Subscribe interaction is terminated on the publisher or subscriber, the
639    /// subscription, identified by a SubscriptionId, SHALL also be terminated."
640    pub fn remove(&mut self, id: u32) -> bool {
641        match self.subscriptions.iter().position(|s| s.id == id) {
642            Some(index) => {
643                self.subscriptions.remove(index);
644                true
645            }
646            None => false,
647        }
648    }
649
650    /// Ends every subscription belonging to one session — §8.5.2.3's `KeepSubscriptions`.
651    ///
652    /// > If KeepSubscriptions is FALSE, all existing or pending subscriptions on the publisher
653    /// > for this subscriber SHALL be terminated.
654    ///
655    /// Returns how many went. A subscriber that re-subscribes without the flag is saying "I
656    /// have restarted, forget what you knew about me" — and a publisher that kept the old
657    /// subscriptions would report to a twin that no longer exists until the maximum interval
658    /// ran out on each.
659    pub fn remove_for_session(&mut self, session: Option<SessionId>) -> usize {
660        let before = self.subscriptions.len();
661        self.subscriptions.retain(|s| s.session != session);
662        before.saturating_sub(self.subscriptions.len())
663    }
664
665    /// Ends every subscription scoped to a fabric — what `RemoveFabric` cascades into.
666    pub fn remove_for_fabric(&mut self, fabric: FabricIndex) -> usize {
667        let before = self.subscriptions.len();
668        self.subscriptions
669            .retain(|s| s.fabric_index != Some(fabric));
670        before.saturating_sub(self.subscriptions.len())
671    }
672
673    /// Records a queued event against every subscription that wants it.
674    ///
675    /// Returns how many were made *pending* — that is, how many had marked the path urgent.
676    /// A subscription that wants the event but did not ask urgently still receives it, on
677    /// whatever report happens next; §8.5 is explicit that non-urgent queueing "does not
678    /// automatically trigger a Report transaction".
679    pub fn note_event(&mut self, endpoint: u16, cluster: u32, event: u32) -> usize {
680        let mut urgent = 0usize;
681        for subscription in &mut self.subscriptions {
682            if subscription.note_event(endpoint, cluster, event) {
683                urgent = urgent.saturating_add(1);
684            }
685        }
686        urgent
687    }
688
689    /// Records a change against every subscription that covers it.
690    ///
691    /// This is the whole of the reporting engine's input: a cluster whose value changed calls
692    /// it once, and each subscription decides for itself whether it cares and when it will
693    /// say so.
694    ///
695    /// **Not** for an attribute with the `C` quality. §8.5: a report carries every change
696    /// "with the exception of attribute data with the Changes Omitted (C) quality" — a client
697    /// polls for those, and reporting one would be reporting what the specification asked a
698    /// publisher not to.
699    pub fn note_change(&mut self, path: &AttributePath) -> usize {
700        let mut dirtied = 0usize;
701        for subscription in &mut self.subscriptions {
702            if subscription.note_change(path) {
703                dirtied = dirtied.saturating_add(1);
704            }
705        }
706        dirtied
707    }
708
709    /// Marks every subscription for a full re-prime — what a lost acknowledgement calls for.
710    pub fn reprime_all(&mut self) {
711        for subscription in &mut self.subscriptions {
712            subscription.dirty.reprime();
713        }
714    }
715
716    /// The earliest moment any subscription needs attention, if there are any.
717    ///
718    /// A device sleeps until this. An intermittently connected one uses it to decide whether
719    /// it can stay idle, which is why §2.11.2.2 lets it choose a long maximum interval.
720    ///
721    /// Unbound subscriptions are skipped for the same reason [`SubscriptionTable::due`] skips
722    /// them: waking for one would be waking to do nothing.
723    #[must_use]
724    pub fn next_deadline(&self) -> Option<Instant> {
725        self.subscriptions
726            .iter()
727            .filter(|s| s.session.is_some())
728            .map(Subscription::next_deadline)
729            .min()
730    }
731
732    /// The subscriptions with a report due at `now`, and why.
733    ///
734    /// A subscription with no session is skipped however overdue it is, because there is
735    /// nowhere to send the report — that is the state a subscription restored from storage
736    /// begins in ([`persist`](crate::im::persist)), waiting for its subscriber to come back
737    /// on a new CASE session. Handing it to a caller that could only discard it would make
738    /// every poll return work that cannot be done.
739    pub fn due(&self, now: Instant) -> impl Iterator<Item = (&Subscription<P>, ReportReason)> {
740        self.subscriptions
741            .iter()
742            .filter(|s| s.session.is_some())
743            .filter_map(move |s| s.due(now).map(|reason| (s, reason)))
744    }
745
746    /// Creates a subscription, allocating an id.
747    ///
748    /// `keep_subscriptions` is the request's flag: when false, every existing subscription
749    /// for this session goes first (§8.5.2.3). That happens *before* the capacity check, so a
750    /// subscriber re-subscribing at the table's limit succeeds rather than being refused with
751    /// its own stale subscriptions in the way.
752    pub fn subscribe(
753        &mut self,
754        request: &NewSubscription<'_>,
755        now: Instant,
756    ) -> core::result::Result<u32, SubscribeError> {
757        if !request.keep_subscriptions {
758            self.remove_for_session(request.session);
759        }
760        // §8.5.2.2: "At least one attribute or event SHALL be indicated in the action." An
761        // event-only subscription is perfectly ordinary — a door lock reporting `LockOperation`
762        // subscribes to no attribute at all.
763        if request.paths.is_empty() && request.event_paths.is_empty() {
764            return Err(SubscribeError::NoPaths);
765        }
766        if request.paths.len() > P || request.event_paths.len() > P {
767            return Err(SubscribeError::TooManyPaths);
768        }
769        if self.subscriptions.len() >= N {
770            return Err(SubscribeError::Full);
771        }
772        self.admit(request.fabric_index)?;
773
774        let mut paths = Vec::new();
775        for path in request.paths {
776            paths
777                .push(*path)
778                .map_err(|_| SubscribeError::TooManyPaths)?;
779        }
780        let mut event_paths = Vec::new();
781        for path in request.event_paths {
782            event_paths
783                .push(*path)
784                .map_err(|_| SubscribeError::TooManyPaths)?;
785        }
786        let id = self.allocate_id();
787        let subscription = Subscription {
788            id,
789            session: request.session,
790            fabric_index: request.fabric_index,
791            peer_node_id: request.peer_node_id,
792            fabric_filtered: request.fabric_filtered,
793            min_interval_s: request.min_interval_s,
794            max_interval_s: request.max_interval_s,
795            paths,
796            event_paths,
797            // §8.5.3.4: "Upon subscription activation, the minimum and maximum interval
798            // parameters SHALL take effect" — and the priming report is the first report, so
799            // both timers start from it.
800            last_report: now,
801            dirty: DirtySet::new(),
802            // `EventFilters` is "a one time parameter for the priming of the subscription",
803            // so the subscriber's minimum event number starts the bookmark and the
804            // subscription keeps its own position from then on.
805            next_event_number: request.min_event_number,
806            urgent: false,
807            reported_through: 0,
808            cursor: crate::im::server::ReadCursor::START,
809        };
810        self.subscriptions
811            .push(subscription)
812            .map_err(|_| SubscribeError::Full)?;
813        Ok(id)
814    }
815
816    /// Records that an attribute of one cluster instance changed, dirtying every subscription
817    /// that overlaps it. Returns how many.
818    ///
819    /// This is the cluster-grained counterpart to [`SubscriptionTable::note_change`], and it is
820    /// what [`DataVersions::drain_changes`](crate::dm::DataVersions::drain_changes) feeds. The
821    /// grain is the cluster because that is the grain §7.10.3 records changes at: "A cluster
822    /// data version SHALL be incremented if any attribute data changes" says *which cluster*,
823    /// never which attribute.
824    ///
825    /// Reporting a whole cluster when one attribute of it moved is more than the minimum and
826    /// never less, which is the safe direction: §8.5 already allows a report to carry more than
827    /// changed — a re-prime carries everything — and a subscriber that is told too much is
828    /// correct where one that is told too little is not.
829    pub fn note_cluster_change(&mut self, endpoint: EndpointId, cluster: ClusterId) -> usize {
830        let mut dirtied: usize = 0;
831        for subscription in &mut self.subscriptions {
832            let mut hit = false;
833            // Collected first: `paths` is borrowed while it is walked, and the dirty set it
834            // feeds lives on the same subscription.
835            let mut overlaps: Vec<AttributePath, P> = Vec::new();
836            for subscribed in &subscription.paths {
837                if let Some(path) = intersect_cluster(subscribed, endpoint, cluster) {
838                    let _ = overlaps.push(path);
839                }
840            }
841            for path in overlaps {
842                subscription.dirty.insert(path);
843                hit = true;
844            }
845            if hit {
846                dirtied = dirtied.saturating_add(1);
847            }
848        }
849        dirtied
850    }
851
852    /// Ensures the next allocated id is above `id`, which restoring a persisted subscription
853    /// needs (§8.5.3.1's ids must stay unique across a reboot).
854    pub(crate) fn reserve_id(&mut self, id: u32) {
855        if id > self.last_id {
856            self.last_id = id;
857        }
858    }
859
860    /// Every subscription, mutably.
861    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Subscription<P>> {
862        self.subscriptions.iter_mut()
863    }
864
865    /// Adds a subscription restored from storage, keeping its id.
866    ///
867    /// Separate from [`SubscriptionTable::subscribe`] because none of that method's work
868    /// applies: there is no request to validate, no id to allocate, and — crucially — no
869    /// `KeepSubscriptions` rule to apply, since a restored subscription must not terminate
870    /// another restored one belonging to the same subscriber. They were all agreed before the
871    /// reboot and all of them are still owed.
872    pub(crate) fn insert_restored(
873        &mut self,
874        durable: crate::im::persist::Durable<P>,
875        now: Instant,
876    ) -> core::result::Result<(), Error> {
877        if self.find(durable.id).is_some() {
878            return Err(Error::new(ErrorCode::AlreadyExists));
879        }
880        let mut subscription = Subscription {
881            id: durable.id,
882            // Deliberately not restored: a session id from before the reboot names whatever
883            // session holds that number now, which is at best nobody and at worst somebody
884            // else. `persist::rebind` supplies the real one.
885            session: None,
886            fabric_index: Some(durable.fabric_index),
887            peer_node_id: Some(durable.peer_node_id),
888            fabric_filtered: durable.fabric_filtered,
889            min_interval_s: durable.min_interval_s,
890            max_interval_s: durable.max_interval_s,
891            paths: durable.paths,
892            event_paths: durable.event_paths,
893            // The clock restarted at zero; treating a stored instant as elapsed time would
894            // either fire a report immediately or suppress one for as long as the device was
895            // off.
896            last_report: now,
897            dirty: DirtySet::new(),
898            next_event_number: durable.next_event_number,
899            urgent: false,
900            reported_through: 0,
901            cursor: crate::im::server::ReadCursor::START,
902        };
903        // The device has no record of what changed while it was off, so nothing about the
904        // subscriber's twin can be trusted — it is unknown rather than stale in some
905        // identified way. §8.5.3.4's priming report is the only honest answer.
906        subscription.reprime();
907        self.subscriptions
908            .push(subscription)
909            .map_err(|_| Error::new(ErrorCode::NoSpace))
910    }
911
912    /// How many subscriptions one fabric holds. `None` counts the fabric-less ones.
913    #[must_use]
914    pub fn len_of_fabric(&self, fabric: Option<FabricIndex>) -> usize {
915        self.subscriptions
916            .iter()
917            .filter(|s| s.fabric_index == fabric)
918            .count()
919    }
920
921    /// §2.11.2.2's per-fabric guarantee, applied to one arriving request.
922    ///
923    /// A fabric-scoped subscription gets a fixed share. A fabric-*less* one — §2.11.2.2 permits
924    /// them "subject to available resources (e.g over PASE)" — gets only what is not promised
925    /// to a fabric, because a `MAY` must never consume a `SHALL`. On a node sized to the
926    /// minimum there is nothing left over and PASE subscriptions are refused, which is what
927    /// "subject to available resources" means when there are none.
928    fn admit(&self, fabric: Option<FabricIndex>) -> core::result::Result<(), SubscribeError> {
929        if fabric.is_some() {
930            return if self.len_of_fabric(fabric) >= C::SUBSCRIPTIONS_PER_FABRIC {
931                Err(SubscribeError::FabricQuota)
932            } else {
933                Ok(())
934            };
935        }
936        let promised = C::FABRICS.saturating_mul(C::SUBSCRIPTIONS_PER_FABRIC);
937        let claimed = self
938            .subscriptions
939            .iter()
940            .filter(|s| s.fabric_index.is_some())
941            .count();
942        let still_owed = promised.saturating_sub(claimed);
943        let free = N.saturating_sub(self.subscriptions.len());
944        if free > still_owed {
945            Ok(())
946        } else {
947            Err(SubscribeError::Full)
948        }
949    }
950
951    /// Allocates the next unused id, never zero.
952    ///
953    /// Monotonic and wrapping, like a fabric index and for the same reason: a subscriber
954    /// caches its id, and handing a freed one straight back out would point a stale
955    /// `SubscriptionId` at somebody else's subscription. Zero is skipped so that it can mean
956    /// "no subscription" in a caller's own bookkeeping.
957    fn allocate_id(&mut self) -> u32 {
958        for _ in 0..=u32::from(u16::MAX) {
959            self.last_id = self.last_id.wrapping_add(1);
960            if self.last_id != 0 && self.find(self.last_id).is_none() {
961                return self.last_id;
962            }
963        }
964        // Unreachable while `N` is far below the id space; returning a duplicate would be
965        // worse than returning one that is merely unlikely to collide.
966        self.last_id
967    }
968}
969
970/// What a `SubscribeRequest` asks for, after its paths have been validated.
971#[derive(Debug, Clone, Copy)]
972pub struct NewSubscription<'a> {
973    /// The session the request arrived on.
974    pub session: Option<SessionId>,
975    /// The accessing fabric, if any.
976    pub fabric_index: Option<FabricIndex>,
977    /// The subscriber's operational Node ID, from the session (§6.6.6.3). `None` over PASE.
978    pub peer_node_id: Option<NodeId>,
979    /// `FabricFiltered`.
980    pub fabric_filtered: bool,
981    /// `KeepSubscriptions`.
982    pub keep_subscriptions: bool,
983    /// The negotiated minimum interval — the request's `MinIntervalFloor`.
984    pub min_interval_s: u16,
985    /// The negotiated maximum interval, from [`SubscriptionPolicy::max_interval`].
986    pub max_interval_s: u16,
987    /// The attribute paths, as requested.
988    pub paths: &'a [AttributePath],
989    /// The event paths, as requested.
990    pub event_paths: &'a [EventPath],
991    /// The lowest event number to report, from the request's `EventFilters`.
992    ///
993    /// §8.5.3.4: "The EventFilters and DataVersionFilters fields in the Subscribe Request are
994    /// one time parameters for the priming of the subscription" — so this seeds the bookmark
995    /// and is never consulted again.
996    pub min_event_number: u64,
997}
998
999/// Builds the `Err` for a refusal, so a caller can answer a `StatusResponse`.
1000impl From<SubscribeError> for Error {
1001    fn from(error: SubscribeError) -> Self {
1002        match error {
1003            SubscribeError::NoPaths => Self::new(ErrorCode::InvalidArgument),
1004            SubscribeError::TooManyPaths | SubscribeError::Full | SubscribeError::FabricQuota => {
1005                Self::new(ErrorCode::NoSpace)
1006            }
1007        }
1008    }
1009}