Skip to main content

unifly_api/store/
data_store.rs

1// ── Central reactive data store ──
2//
3// Thread-safe, lock-free storage for all UniFi domain entities.
4// Mutations are broadcast to subscribers via `watch` channels.
5
6use std::sync::Arc;
7
8use chrono::{DateTime, Utc};
9use tokio::sync::watch;
10
11use super::collection::EntityCollection;
12use crate::model::{
13    AclRule, Client, Device, DnsPolicy, EntityId, Event, FirewallPolicy, FirewallZone,
14    HealthSummary, MacAddress, NatPolicy, Network, Site, TrafficMatchingList, Voucher,
15    WifiBroadcast,
16};
17use crate::stream::EntityStream;
18
19/// Central reactive store for all UniFi domain entities.
20///
21/// Thread-safe and lock-free: all reads are wait-free, writes use
22/// fine-grained per-shard locks within `DashMap`. Mutations are
23/// broadcast to subscribers via `watch` channels.
24pub struct DataStore {
25    pub(crate) devices: EntityCollection<Device>,
26    pub(crate) clients: EntityCollection<Client>,
27    pub(crate) networks: EntityCollection<Network>,
28    pub(crate) wifi_broadcasts: EntityCollection<WifiBroadcast>,
29    pub(crate) firewall_policies: EntityCollection<FirewallPolicy>,
30    pub(crate) firewall_zones: EntityCollection<FirewallZone>,
31    pub(crate) acl_rules: EntityCollection<AclRule>,
32    pub(crate) nat_policies: EntityCollection<NatPolicy>,
33    pub(crate) dns_policies: EntityCollection<DnsPolicy>,
34    pub(crate) vouchers: EntityCollection<Voucher>,
35    pub(crate) sites: EntityCollection<Site>,
36    pub(crate) events: EntityCollection<Event>,
37    pub(crate) traffic_matching_lists: EntityCollection<TrafficMatchingList>,
38    pub(crate) site_health: watch::Sender<Arc<Vec<HealthSummary>>>,
39    pub(crate) last_full_refresh: watch::Sender<Option<DateTime<Utc>>>,
40    pub(crate) last_ws_event: watch::Sender<Option<DateTime<Utc>>>,
41}
42
43impl DataStore {
44    pub fn new() -> Self {
45        let (site_health, _) = watch::channel(Arc::new(Vec::new()));
46        let (last_full_refresh, _) = watch::channel(None);
47        let (last_ws_event, _) = watch::channel(None);
48
49        Self {
50            devices: EntityCollection::new(),
51            clients: EntityCollection::new(),
52            networks: EntityCollection::new(),
53            wifi_broadcasts: EntityCollection::new(),
54            firewall_policies: EntityCollection::new(),
55            firewall_zones: EntityCollection::new(),
56            acl_rules: EntityCollection::new(),
57            nat_policies: EntityCollection::new(),
58            dns_policies: EntityCollection::new(),
59            vouchers: EntityCollection::new(),
60            sites: EntityCollection::new(),
61            events: EntityCollection::new(),
62            traffic_matching_lists: EntityCollection::new(),
63            site_health,
64            last_full_refresh,
65            last_ws_event,
66        }
67    }
68
69    // ── Snapshot accessors ───────────────────────────────────────────
70
71    pub fn devices_snapshot(&self) -> Arc<Vec<Arc<Device>>> {
72        self.devices.snapshot()
73    }
74
75    pub fn clients_snapshot(&self) -> Arc<Vec<Arc<Client>>> {
76        self.clients.snapshot()
77    }
78
79    pub fn networks_snapshot(&self) -> Arc<Vec<Arc<Network>>> {
80        self.networks.snapshot()
81    }
82
83    pub fn wifi_broadcasts_snapshot(&self) -> Arc<Vec<Arc<WifiBroadcast>>> {
84        self.wifi_broadcasts.snapshot()
85    }
86
87    pub fn firewall_policies_snapshot(&self) -> Arc<Vec<Arc<FirewallPolicy>>> {
88        self.firewall_policies.snapshot()
89    }
90
91    pub fn firewall_zones_snapshot(&self) -> Arc<Vec<Arc<FirewallZone>>> {
92        self.firewall_zones.snapshot()
93    }
94
95    pub fn acl_rules_snapshot(&self) -> Arc<Vec<Arc<AclRule>>> {
96        self.acl_rules.snapshot()
97    }
98
99    pub fn nat_policies_snapshot(&self) -> Arc<Vec<Arc<NatPolicy>>> {
100        self.nat_policies.snapshot()
101    }
102
103    pub fn dns_policies_snapshot(&self) -> Arc<Vec<Arc<DnsPolicy>>> {
104        self.dns_policies.snapshot()
105    }
106
107    pub fn vouchers_snapshot(&self) -> Arc<Vec<Arc<Voucher>>> {
108        self.vouchers.snapshot()
109    }
110
111    pub fn sites_snapshot(&self) -> Arc<Vec<Arc<Site>>> {
112        self.sites.snapshot()
113    }
114
115    pub fn events_snapshot(&self) -> Arc<Vec<Arc<Event>>> {
116        self.events.snapshot()
117    }
118
119    pub fn traffic_matching_lists_snapshot(&self) -> Arc<Vec<Arc<TrafficMatchingList>>> {
120        self.traffic_matching_lists.snapshot()
121    }
122
123    // ── Single-entity lookups ────────────────────────────────────────
124
125    pub fn device_by_mac(&self, mac: &MacAddress) -> Option<Arc<Device>> {
126        self.devices.get_by_key(mac.as_str())
127    }
128
129    pub fn device_by_id(&self, id: &EntityId) -> Option<Arc<Device>> {
130        self.devices.get_by_id(id)
131    }
132
133    pub fn client_by_mac(&self, mac: &MacAddress) -> Option<Arc<Client>> {
134        self.clients.get_by_key(mac.as_str())
135    }
136
137    pub fn client_by_id(&self, id: &EntityId) -> Option<Arc<Client>> {
138        self.clients.get_by_id(id)
139    }
140
141    pub fn network_by_id(&self, id: &EntityId) -> Option<Arc<Network>> {
142        self.networks.get_by_id(id)
143    }
144
145    // ── Count accessors ──────────────────────────────────────────────
146
147    pub fn device_count(&self) -> usize {
148        self.devices.len()
149    }
150
151    pub fn client_count(&self) -> usize {
152        self.clients.len()
153    }
154
155    pub fn network_count(&self) -> usize {
156        self.networks.len()
157    }
158
159    // ── Subscriptions ────────────────────────────────────────────────
160
161    pub fn subscribe_devices(&self) -> EntityStream<Device> {
162        EntityStream::new(self.devices.subscribe())
163    }
164
165    pub fn subscribe_clients(&self) -> EntityStream<Client> {
166        EntityStream::new(self.clients.subscribe())
167    }
168
169    pub fn subscribe_networks(&self) -> EntityStream<Network> {
170        EntityStream::new(self.networks.subscribe())
171    }
172
173    pub fn subscribe_wifi_broadcasts(&self) -> EntityStream<WifiBroadcast> {
174        EntityStream::new(self.wifi_broadcasts.subscribe())
175    }
176
177    pub fn subscribe_firewall_policies(&self) -> EntityStream<FirewallPolicy> {
178        EntityStream::new(self.firewall_policies.subscribe())
179    }
180
181    pub fn subscribe_firewall_zones(&self) -> EntityStream<FirewallZone> {
182        EntityStream::new(self.firewall_zones.subscribe())
183    }
184
185    pub fn subscribe_acl_rules(&self) -> EntityStream<AclRule> {
186        EntityStream::new(self.acl_rules.subscribe())
187    }
188
189    pub fn subscribe_nat_policies(&self) -> EntityStream<NatPolicy> {
190        EntityStream::new(self.nat_policies.subscribe())
191    }
192
193    pub fn subscribe_dns_policies(&self) -> EntityStream<DnsPolicy> {
194        EntityStream::new(self.dns_policies.subscribe())
195    }
196
197    pub fn subscribe_vouchers(&self) -> EntityStream<Voucher> {
198        EntityStream::new(self.vouchers.subscribe())
199    }
200
201    pub fn subscribe_sites(&self) -> EntityStream<Site> {
202        EntityStream::new(self.sites.subscribe())
203    }
204
205    pub fn subscribe_events(&self) -> EntityStream<Event> {
206        EntityStream::new(self.events.subscribe())
207    }
208
209    pub fn subscribe_traffic_matching_lists(&self) -> EntityStream<TrafficMatchingList> {
210        EntityStream::new(self.traffic_matching_lists.subscribe())
211    }
212
213    // ── Site health ──────────────────────────────────────────────────
214
215    pub fn site_health_snapshot(&self) -> Arc<Vec<HealthSummary>> {
216        self.site_health.borrow().clone()
217    }
218
219    pub fn subscribe_site_health(&self) -> watch::Receiver<Arc<Vec<HealthSummary>>> {
220        self.site_health.subscribe()
221    }
222
223    // ── Metadata ─────────────────────────────────────────────────────
224
225    pub fn last_full_refresh(&self) -> Option<DateTime<Utc>> {
226        *self.last_full_refresh.borrow()
227    }
228
229    pub fn last_ws_event(&self) -> Option<DateTime<Utc>> {
230        *self.last_ws_event.borrow()
231    }
232
233    pub(crate) fn mark_ws_event(&self, timestamp: DateTime<Utc>) {
234        let _ = self.last_ws_event.send(Some(timestamp));
235    }
236
237    /// How long ago the last full refresh occurred, or `None` if never refreshed.
238    pub fn data_age(&self) -> Option<chrono::Duration> {
239        self.last_full_refresh().map(|t| Utc::now() - t)
240    }
241}
242
243impl Default for DataStore {
244    fn default() -> Self {
245        Self::new()
246    }
247}