rustflexstack/facilities/local_dynamic_map/ldm_maintenance.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 maintenance — background garbage-collection and subscription firing.
5//!
6//! `LdmMaintenance::spawn` starts a 1 Hz thread that:
7//! 1. Removes expired records (past their `time_validity_s` window).
8//! 2. Removes records outside the local station's maintenance area
9//! (using correct Haversine distance — fixes the Python Euclidean bug).
10//! 3. Calls `LdmService::fire_subscriptions` to deliver periodic push
11//! notifications to all active subscribers.
12//!
13//! The maintenance area centre can be updated dynamically via
14//! [`AreaCenter::update`], e.g. from GPS fixes, so the LDM always tracks
15//! the local station's current position.
16//!
17//! The thread holds only `Arc` handles; it exits cleanly when all owners of
18//! `LdmService` have been dropped (the `Arc` reference count reaches zero
19//! and `fire_subscriptions` becomes a no-op on the last cycle before the
20//! `Arc` upgrade returns `None`).
21
22use std::sync::atomic::{AtomicI32, Ordering};
23use std::sync::Arc;
24use std::thread;
25use std::time::Duration;
26
27use crate::facilities::local_dynamic_map::ldm_service::LdmService;
28
29/// Thread-safe, dynamically updatable maintenance area centre.
30///
31/// Created by [`LdmMaintenance::spawn`] and returned so that callers can
32/// update the centre from GPS fixes.
33#[derive(Clone)]
34pub struct AreaCenter {
35 lat: Arc<AtomicI32>,
36 lon: Arc<AtomicI32>,
37}
38
39impl AreaCenter {
40 /// Create a new `AreaCenter` set to the given ETSI coordinates.
41 fn new(lat_etsi: i32, lon_etsi: i32) -> Self {
42 AreaCenter {
43 lat: Arc::new(AtomicI32::new(lat_etsi)),
44 lon: Arc::new(AtomicI32::new(lon_etsi)),
45 }
46 }
47
48 /// Update the maintenance area centre (thread-safe).
49 ///
50 /// Call this whenever a new GPS fix arrives so that the spatial GC always
51 /// uses the station's current position.
52 pub fn update(&self, lat_etsi: i32, lon_etsi: i32) {
53 self.lat.store(lat_etsi, Ordering::Relaxed);
54 self.lon.store(lon_etsi, Ordering::Relaxed);
55 }
56
57 /// Read the current centre latitude (ETSI × 1e7).
58 fn lat(&self) -> i32 {
59 self.lat.load(Ordering::Relaxed)
60 }
61
62 /// Read the current centre longitude (ETSI × 1e7).
63 fn lon(&self) -> i32 {
64 self.lon.load(Ordering::Relaxed)
65 }
66}
67
68/// LDM maintenance controller.
69pub struct LdmMaintenance;
70
71impl LdmMaintenance {
72 /// Spawn the maintenance thread.
73 ///
74 /// # Arguments
75 /// * `service` — shared reference to the `LdmService`.
76 /// * `area_lat_etsi` — initial latitude of the LDM maintenance area centre (ETSI × 1e7).
77 /// * `area_lon_etsi` — initial longitude of the LDM maintenance area centre (ETSI × 1e7).
78 /// * `area_radius_m` — radius of the maintenance area in metres.
79 ///
80 /// Records outside the area or past their validity window are deleted on
81 /// each maintenance cycle. A zero or negative `area_radius_m` disables
82 /// the spatial GC (only expiry-based GC runs).
83 ///
84 /// # Returns
85 /// An [`AreaCenter`] handle that can be used to update the maintenance
86 /// area centre dynamically (e.g. from GPS fixes).
87 pub fn spawn(
88 service: Arc<LdmService>,
89 area_lat_etsi: i32,
90 area_lon_etsi: i32,
91 area_radius_m: f64,
92 ) -> AreaCenter {
93 let center = AreaCenter::new(area_lat_etsi, area_lon_etsi);
94 let center_clone = center.clone();
95
96 // Downgrade to a Weak pointer so the maintenance thread does not
97 // prevent the LDM from being dropped when all other owners are gone.
98 let weak = Arc::downgrade(&service);
99
100 thread::Builder::new()
101 .name("ldm-maintenance".into())
102 .spawn(move || {
103 loop {
104 thread::sleep(Duration::from_secs(1));
105
106 // If all strong references are gone, exit cleanly.
107 let Some(svc) = weak.upgrade() else { break };
108
109 {
110 let mut store = svc.store.write().unwrap();
111
112 // 1. Expiry-based garbage collection.
113 let _ = store.remove_expired();
114
115 // 2. Spatial garbage collection (if area is defined).
116 if area_radius_m > 0.0 {
117 let _ = store.remove_out_of_area(
118 center_clone.lat(),
119 center_clone.lon(),
120 area_radius_m,
121 );
122 }
123 } // write lock released here
124
125 // 3. Fire subscriptions (takes store read-lock internally).
126 svc.fire_subscriptions();
127 }
128 })
129 .expect("failed to spawn ldm-maintenance thread");
130
131 center
132 }
133}