Skip to main content

rustflexstack/facilities/local_dynamic_map/
ldm_storage.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! LDM in-memory storage — `ItsDataObject`, `StoredRecord`, `LdmStore`.
5//!
6//! `LdmStore` is the sole mutable state of the LDM; it is always wrapped in
7//! `Arc<RwLock<LdmStore>>` so that readers (queries, subscription checks) can
8//! proceed concurrently while writers (insert / update / delete) hold an
9//! exclusive lock.
10//!
11//! # Design choices
12//! * **`ItsDataObject` is a typed enum** — zero runtime overhead; no dynamic
13//!   dispatch, no heap-allocated trait objects, no schema-on-the-wire parsing.
14//! * **`HashMap<u64, StoredRecord>`** — O(1) lookup/insert/delete vs. the
15//!   Python `TinyDB` O(n) list scans.
16//! * **Record IDs** are generated from a monotonically increasing `u64`
17//!   counter; they never repeat within a process lifetime.
18
19use crate::facilities::ca_basic_service::cam_coder::Cam;
20use crate::facilities::decentralized_environmental_notification_service::denm_coder::Denm;
21use crate::facilities::local_dynamic_map::ldm_constants::now_its_ms;
22use crate::facilities::vru_awareness_service::vam_coder::Vam;
23
24use std::collections::HashMap;
25
26// ─── ITS data object (typed enum, Option A) ──────────────────────────────────
27
28/// A typed ITS data object stored in the LDM.
29///
30/// Each variant boxes the full PDU to keep `StoredRecord` lean when the LDM
31/// holds a large population of mixed types.
32#[derive(Debug)]
33pub enum ItsDataObject {
34    /// ETSI EN 302 637-2 Cooperative Awareness Message.
35    Cam(Box<Cam>),
36    /// ETSI EN 302 637-3 Decentralized Environmental Notification Message.
37    Denm(Box<Denm>),
38    /// ETSI TS 103 300-3 VRU Awareness Message.
39    Vam(Box<Vam>),
40    /// Unknown or future message type — stored as raw bytes.
41    Unknown { its_aid: u32, raw: Vec<u8> },
42}
43
44impl ItsDataObject {
45    /// Return the ITS-AID of this object's application type.
46    pub fn its_aid(&self) -> u32 {
47        use crate::facilities::local_dynamic_map::ldm_constants::{
48            ITS_AID_CAM, ITS_AID_DENM, ITS_AID_VAM,
49        };
50        match self {
51            ItsDataObject::Cam(_) => ITS_AID_CAM,
52            ItsDataObject::Denm(_) => ITS_AID_DENM,
53            ItsDataObject::Vam(_) => ITS_AID_VAM,
54            ItsDataObject::Unknown { its_aid, .. } => *its_aid,
55        }
56    }
57}
58
59// ─── Stored record ────────────────────────────────────────────────────────────
60
61/// A single LDM record.
62///
63/// All fields except `data_object` are plain integers or scalars so that
64/// filtering and maintenance can inspect them without decoding the PDU.
65#[derive(Debug)]
66pub struct StoredRecord {
67    /// LDM-assigned monotonic identifier.
68    pub id: u64,
69    /// ITS-AID of the data provider.
70    pub application_id: u32,
71    /// Time this record was inserted / last updated (ms since ITS epoch).
72    pub timestamp_its_ms: u64,
73    /// Validity window in seconds; record expires when
74    /// `timestamp_its_ms + time_validity_s * 1000 < now`.
75    pub time_validity_s: u32,
76    /// Position latitude (ETSI × 1e7 integer units).
77    pub lat_etsi: i32,
78    /// Position longitude (ETSI × 1e7 integer units).
79    pub lon_etsi: i32,
80    /// Altitude in centimetres above WGS-84 ellipsoid.
81    pub altitude_cm: i32,
82    /// The ITS data object.
83    pub data_object: ItsDataObject,
84}
85
86impl StoredRecord {
87    /// Return `true` if this record has passed its validity horizon.
88    pub fn is_expired(&self) -> bool {
89        let expiry_ms = self.timestamp_its_ms + (self.time_validity_s as u64) * 1000;
90        now_its_ms() > expiry_ms
91    }
92}
93
94// ─── LDM store ───────────────────────────────────────────────────────────────
95
96/// In-memory LDM record store.
97///
98/// Always shared behind `Arc<RwLock<LdmStore>>`.
99pub struct LdmStore {
100    records: HashMap<u64, StoredRecord>,
101    next_id: u64,
102}
103
104impl LdmStore {
105    /// Create an empty store.
106    pub fn new() -> Self {
107        LdmStore {
108            records: HashMap::new(),
109            next_id: 1,
110        }
111    }
112
113    // ── Write operations ──────────────────────────────────────────────────
114
115    /// Insert a new record and return its assigned ID.
116    #[allow(clippy::too_many_arguments)]
117    pub fn insert(
118        &mut self,
119        application_id: u32,
120        timestamp_its_ms: u64,
121        time_validity_s: u32,
122        lat_etsi: i32,
123        lon_etsi: i32,
124        altitude_cm: i32,
125        data_object: ItsDataObject,
126    ) -> u64 {
127        let id = self.next_id;
128        self.next_id += 1;
129        self.records.insert(
130            id,
131            StoredRecord {
132                id,
133                application_id,
134                timestamp_its_ms,
135                time_validity_s,
136                lat_etsi,
137                lon_etsi,
138                altitude_cm,
139                data_object,
140            },
141        );
142        id
143    }
144
145    /// Replace an existing record's payload and metadata.
146    ///
147    /// Returns `false` when `id` is not found.
148    #[allow(clippy::too_many_arguments)]
149    pub fn update(
150        &mut self,
151        id: u64,
152        timestamp_its_ms: u64,
153        time_validity_s: u32,
154        lat_etsi: i32,
155        lon_etsi: i32,
156        altitude_cm: i32,
157        data_object: ItsDataObject,
158    ) -> bool {
159        if let Some(rec) = self.records.get_mut(&id) {
160            rec.timestamp_its_ms = timestamp_its_ms;
161            rec.time_validity_s = time_validity_s;
162            rec.lat_etsi = lat_etsi;
163            rec.lon_etsi = lon_etsi;
164            rec.altitude_cm = altitude_cm;
165            rec.data_object = data_object;
166            true
167        } else {
168            false
169        }
170    }
171
172    /// Remove a record by ID.  Returns `true` if the record existed.
173    pub fn remove(&mut self, id: u64) -> bool {
174        self.records.remove(&id).is_some()
175    }
176
177    /// Remove all expired records and return the count removed.
178    pub fn remove_expired(&mut self) -> usize {
179        let expired: Vec<u64> = self
180            .records
181            .values()
182            .filter(|r| r.is_expired())
183            .map(|r| r.id)
184            .collect();
185        let n = expired.len();
186        for id in expired {
187            self.records.remove(&id);
188        }
189        n
190    }
191
192    /// Remove all records whose position is outside a radius (metres) from
193    /// a reference point, using the Haversine formula.
194    pub fn remove_out_of_area(
195        &mut self,
196        area_lat_etsi: i32,
197        area_lon_etsi: i32,
198        area_radius_m: f64,
199    ) -> usize {
200        use crate::facilities::local_dynamic_map::ldm_constants::haversine_m;
201        let out: Vec<u64> = self
202            .records
203            .values()
204            .filter(|r| {
205                haversine_m(r.lat_etsi, r.lon_etsi, area_lat_etsi, area_lon_etsi) > area_radius_m
206            })
207            .map(|r| r.id)
208            .collect();
209        let n = out.len();
210        for id in out {
211            self.records.remove(&id);
212        }
213        n
214    }
215
216    // ── Read operations ───────────────────────────────────────────────────
217
218    /// Iterate over all stored records (immutable).
219    pub fn iter(&self) -> impl Iterator<Item = &StoredRecord> {
220        self.records.values()
221    }
222
223    /// Return the number of records currently in the store.
224    pub fn len(&self) -> usize {
225        self.records.len()
226    }
227
228    /// Return `true` when the store is empty.
229    pub fn is_empty(&self) -> bool {
230        self.records.is_empty()
231    }
232}
233
234impl Default for LdmStore {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn store_new_empty() {
246        let store = LdmStore::new();
247        assert!(store.is_empty());
248        assert_eq!(store.len(), 0);
249    }
250
251    #[test]
252    fn store_default() {
253        let store = LdmStore::default();
254        assert!(store.is_empty());
255    }
256
257    #[test]
258    fn store_insert_returns_ids() {
259        let mut store = LdmStore::new();
260        let id1 = store.insert(
261            36,
262            1_000_000,
263            60,
264            415520000,
265            21340000,
266            12000,
267            ItsDataObject::Unknown {
268                its_aid: 36,
269                raw: vec![0xCA],
270            },
271        );
272        let id2 = store.insert(
273            37,
274            1_000_001,
275            60,
276            415520000,
277            21340000,
278            12000,
279            ItsDataObject::Unknown {
280                its_aid: 37,
281                raw: vec![0xDE],
282            },
283        );
284        assert_eq!(id1, 1);
285        assert_eq!(id2, 2);
286        assert_eq!(store.len(), 2);
287    }
288
289    #[test]
290    fn store_update_existing() {
291        let mut store = LdmStore::new();
292        let id = store.insert(
293            36,
294            1_000_000,
295            60,
296            0,
297            0,
298            0,
299            ItsDataObject::Unknown {
300                its_aid: 36,
301                raw: vec![],
302            },
303        );
304        let ok = store.update(
305            id,
306            2_000_000,
307            120,
308            100,
309            200,
310            300,
311            ItsDataObject::Unknown {
312                its_aid: 36,
313                raw: vec![1],
314            },
315        );
316        assert!(ok);
317        let rec = store.iter().find(|r| r.id == id).unwrap();
318        assert_eq!(rec.timestamp_its_ms, 2_000_000);
319        assert_eq!(rec.time_validity_s, 120);
320    }
321
322    #[test]
323    fn store_update_nonexistent() {
324        let mut store = LdmStore::new();
325        let ok = store.update(
326            999,
327            0,
328            0,
329            0,
330            0,
331            0,
332            ItsDataObject::Unknown {
333                its_aid: 0,
334                raw: vec![],
335            },
336        );
337        assert!(!ok);
338    }
339
340    #[test]
341    fn store_remove() {
342        let mut store = LdmStore::new();
343        let id = store.insert(
344            36,
345            0,
346            60,
347            0,
348            0,
349            0,
350            ItsDataObject::Unknown {
351                its_aid: 36,
352                raw: vec![],
353            },
354        );
355        assert!(store.remove(id));
356        assert!(store.is_empty());
357        assert!(!store.remove(id));
358    }
359
360    #[test]
361    fn store_remove_expired() {
362        let mut store = LdmStore::new();
363        // Insert a record that expired long ago
364        store.insert(
365            36,
366            0, // timestamp = epoch
367            1, // validity = 1 second
368            0,
369            0,
370            0,
371            ItsDataObject::Unknown {
372                its_aid: 36,
373                raw: vec![],
374            },
375        );
376        let removed = store.remove_expired();
377        assert_eq!(removed, 1);
378        assert!(store.is_empty());
379    }
380
381    #[test]
382    fn store_remove_out_of_area() {
383        let mut store = LdmStore::new();
384        // Insert a record at Barcelona (lat 41.552, lon 2.134)
385        store.insert(
386            36,
387            now_its_ms(),
388            3600,
389            415520000,
390            21340000,
391            0,
392            ItsDataObject::Unknown {
393                its_aid: 36,
394                raw: vec![],
395            },
396        );
397        // Remove everything outside 1m of Madrid (40.4168, -3.7038)
398        let removed = store.remove_out_of_area(404168000, -37038000, 1.0);
399        assert_eq!(removed, 1);
400    }
401
402    #[test]
403    fn store_iter() {
404        let mut store = LdmStore::new();
405        store.insert(
406            36,
407            0,
408            3600,
409            0,
410            0,
411            0,
412            ItsDataObject::Unknown {
413                its_aid: 36,
414                raw: vec![],
415            },
416        );
417        store.insert(
418            37,
419            0,
420            3600,
421            0,
422            0,
423            0,
424            ItsDataObject::Unknown {
425                its_aid: 37,
426                raw: vec![],
427            },
428        );
429        let count = store.iter().count();
430        assert_eq!(count, 2);
431    }
432
433    #[test]
434    fn its_data_object_its_aid() {
435        assert_eq!(
436            ItsDataObject::Unknown {
437                its_aid: 99,
438                raw: vec![]
439            }
440            .its_aid(),
441            99
442        );
443    }
444}