Skip to main content

net_lattice_model/
event.rs

1use crate::ifaddr::InterfaceAddressId;
2use crate::interface::InterfaceId;
3use crate::neighbor::NeighborId;
4use crate::route::RouteId;
5
6/// What kind of change an [`Event`] reports.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum ChangeKind {
10    Added,
11    Removed,
12    /// Reserved for a future field-mask payload (`Changed { fields: ... }`)
13    /// — see ARCHITECTURE.md's note on `Event`. Carries no detail yet: a
14    /// consumer that needs to know what changed re-reads the object through
15    /// the relevant provider.
16    Changed,
17}
18
19/// A domain whose state must be re-read after an overflow notification.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[non_exhaustive]
22pub enum EventDomain {
23    Route,
24    Interface,
25    Neighbor,
26    Address,
27    All,
28}
29
30/// A composable filter for event domains and individual network objects.
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32pub struct EventFilter {
33    routes: bool,
34    interfaces: bool,
35    neighbors: bool,
36    addresses: bool,
37    route_ids: Option<Vec<RouteId>>,
38    interface_ids: Option<Vec<InterfaceId>>,
39    neighbor_ids: Option<Vec<NeighborId>>,
40    address_ids: Option<Vec<InterfaceAddressId>>,
41}
42
43impl EventFilter {
44    pub const ALL: Self = Self {
45        routes: true,
46        interfaces: true,
47        neighbors: true,
48        addresses: true,
49        route_ids: None,
50        interface_ids: None,
51        neighbor_ids: None,
52        address_ids: None,
53    };
54    pub const fn none() -> Self {
55        Self {
56            routes: false,
57            interfaces: false,
58            neighbors: false,
59            addresses: false,
60            route_ids: None,
61            interface_ids: None,
62            neighbor_ids: None,
63            address_ids: None,
64        }
65    }
66    pub const fn routes(mut self) -> Self {
67        self.routes = true;
68        self
69    }
70    pub const fn interfaces(mut self) -> Self {
71        self.interfaces = true;
72        self
73    }
74    pub const fn neighbors(mut self) -> Self {
75        self.neighbors = true;
76        self
77    }
78    pub const fn addresses(mut self) -> Self {
79        self.addresses = true;
80        self
81    }
82
83    /// Narrows route delivery to `id`. Repeated object selectors compose as
84    /// a union within their domain.
85    pub fn route(mut self, id: RouteId) -> Self {
86        self.routes = true;
87        add_selector(&mut self.route_ids, id);
88        self
89    }
90    /// Narrows interface delivery to `id`.
91    pub fn interface(mut self, id: InterfaceId) -> Self {
92        self.interfaces = true;
93        add_selector(&mut self.interface_ids, id);
94        self
95    }
96    /// Narrows neighbor delivery to `id`.
97    pub fn neighbor(mut self, id: NeighborId) -> Self {
98        self.neighbors = true;
99        add_selector(&mut self.neighbor_ids, id);
100        self
101    }
102    /// Narrows interface-address delivery to `id`.
103    pub fn address(mut self, id: InterfaceAddressId) -> Self {
104        self.addresses = true;
105        add_selector(&mut self.address_ids, id);
106        self
107    }
108
109    /// Whether this filter selects at least one event domain.
110    pub const fn is_empty(&self) -> bool {
111        !self.routes && !self.interfaces && !self.neighbors && !self.addresses
112    }
113
114    /// Whether this filter delivers `event`. Object selectors are applied
115    /// before a backend enqueues an ordinary event. A resynchronization event
116    /// has no object ID, so it is selected by its affected domain.
117    pub fn matches(&self, event: Event) -> bool {
118        match event {
119            Event::Route { id, .. } => self.routes && selected(&self.route_ids, id),
120            Event::Interface { id, .. } => self.interfaces && selected(&self.interface_ids, id),
121            Event::Neighbor { id, .. } => self.neighbors && selected(&self.neighbor_ids, id),
122            Event::Address { id, .. } => self.addresses && selected(&self.address_ids, id),
123            Event::ResyncRequired { domain } => match domain {
124                EventDomain::Route => self.routes,
125                EventDomain::Interface => self.interfaces,
126                EventDomain::Neighbor => self.neighbors,
127                EventDomain::Address => self.addresses,
128                EventDomain::All => {
129                    self.routes || self.interfaces || self.neighbors || self.addresses
130                }
131            },
132        }
133    }
134}
135
136fn add_selector<T: PartialEq>(selectors: &mut Option<Vec<T>>, value: T) {
137    let selectors = selectors.get_or_insert_with(Vec::new);
138    if !selectors.contains(&value) {
139        selectors.push(value);
140    }
141}
142
143fn selected<T: PartialEq>(selectors: &Option<Vec<T>>, value: T) -> bool {
144    selectors
145        .as_ref()
146        .is_none_or(|selectors| selectors.contains(&value))
147}
148impl Default for EventFilter {
149    fn default() -> Self {
150        Self::ALL
151    }
152}
153
154/// A signal that something changed in the system's networking state —
155/// carrying an ID and a [`ChangeKind`], not a clone of the full domain
156/// object.
157///
158/// Deliberately signal-shaped rather than snapshot-shaped (e.g.
159/// `Event::Route { id, kind }`, not `Event::RouteAdded(Route)`): native
160/// change notifications frequently don't hand over the full object in the
161/// first place (an `RTM_NEWROUTE` message or a Windows route-change
162/// callback can carry only what changed, not a complete record), and a
163/// consumer that only cares *that* something changed before deciding
164/// whether to re-query it shouldn't pay for a clone of the full object on
165/// every event. A consumer that needs the current value re-reads it
166/// through the relevant provider (`Lattice::routes()`, keyed by the ID
167/// carried here).
168///
169/// `#[non_exhaustive]`: DNS resolver configuration changes are a stated
170/// long-term goal for this enum (see ARCHITECTURE.md) but are not emitted
171/// by any backend yet — no platform in Stage 0.8 exposes a push
172/// notification for `/etc/resolv.conf`/per-adapter DNS settings changing
173/// without resorting to filesystem polling, which isn't a genuine push
174/// signal. Adding a `Dns` variant later is not a breaking change for
175/// consumers who already `match` non-exhaustively.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[non_exhaustive]
178pub enum Event {
179    Route {
180        id: RouteId,
181        kind: ChangeKind,
182    },
183    Interface {
184        id: InterfaceId,
185        kind: ChangeKind,
186    },
187    Neighbor {
188        id: NeighborId,
189        kind: ChangeKind,
190    },
191    Address {
192        id: InterfaceAddressId,
193        kind: ChangeKind,
194    },
195    /// Notifications were dropped because the bounded queue filled; re-read
196    /// the indicated domain before relying on later signals.
197    ResyncRequired {
198        domain: EventDomain,
199    },
200}
201impl Event {
202    pub const fn resync_all() -> Self {
203        Self::ResyncRequired {
204            domain: EventDomain::All,
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn events_carry_id_and_kind() {
215        let event = Event::Route {
216            id: RouteId::new(1),
217            kind: ChangeKind::Added,
218        };
219        assert_eq!(
220            event,
221            Event::Route {
222                id: RouteId::new(1),
223                kind: ChangeKind::Added,
224            }
225        );
226        assert_ne!(
227            event,
228            Event::Route {
229                id: RouteId::new(1),
230                kind: ChangeKind::Removed,
231            }
232        );
233    }
234
235    #[test]
236    fn object_selectors_compose_without_leaking_other_objects() {
237        let filter = EventFilter::none()
238            .route(RouteId::new(1))
239            .route(RouteId::new(2));
240        assert!(filter.matches(Event::Route {
241            id: RouteId::new(1),
242            kind: ChangeKind::Changed,
243        }));
244        assert!(filter.matches(Event::Route {
245            id: RouteId::new(2),
246            kind: ChangeKind::Changed,
247        }));
248        assert!(!filter.matches(Event::Route {
249            id: RouteId::new(3),
250            kind: ChangeKind::Changed,
251        }));
252    }
253
254    #[test]
255    fn resync_is_selected_by_domain_even_for_object_filter() {
256        let filter = EventFilter::none().route(RouteId::new(1));
257        assert!(filter.matches(Event::ResyncRequired {
258            domain: EventDomain::Route,
259        }));
260        assert!(!filter.matches(Event::ResyncRequired {
261            domain: EventDomain::Address,
262        }));
263    }
264}