Skip to main content

allsource_core/infrastructure/query/
geospatial.rs

1//! Geospatial query support for AllSource events
2//!
3//! Enables spatial filtering of events based on coordinates stored in event
4//! metadata or payload. Supports:
5//!
6//! - **Bounding box queries**: Find events within a rectangular region
7//! - **Radius queries**: Find events within a distance of a point (haversine)
8//! - **Geospatial indexing**: In-memory spatial index using grid cells for O(1) lookups
9//!
10//! ## Coordinate extraction
11//!
12//! Coordinates are extracted from events by checking (in order):
13//! 1. `metadata.location.lat` / `metadata.location.lng`
14//! 2. `metadata.lat` / `metadata.lng`
15//! 3. `payload.location.lat` / `payload.location.lng`
16//! 4. `payload.lat` / `payload.lng`
17//! 5. `metadata.latitude` / `metadata.longitude`
18//! 6. `payload.latitude` / `payload.longitude`
19//!
20//! ## Limitations
21//!
22//! - Grid-based spatial index (not R-tree) — adequate for moderate datasets
23//! - Haversine assumes spherical Earth (max ~0.3% error vs ellipsoidal)
24//! - Events without coordinates are silently excluded from spatial queries
25
26use crate::infrastructure::{
27    hash_state::{FastDashMap, fast_dashmap},
28    memory::ledger::{MapCharge, Owner, Tally},
29};
30use serde::{Deserialize, Serialize};
31use std::{
32    mem::size_of,
33    sync::atomic::{AtomicU64, Ordering},
34};
35use uuid::Uuid;
36
37use crate::domain::entities::Event;
38
39/// Earth's radius in kilometers
40const EARTH_RADIUS_KM: f64 = 6371.0;
41
42/// Grid cell size in degrees (approximately 11km at equator)
43const GRID_CELL_SIZE: f64 = 0.1;
44
45/// Results per geo query when the request names no limit, and the ceiling for any limit.
46pub const GEO_QUERY_MAX_RESULTS: usize = 10_000;
47
48/// A geographic coordinate
49#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
50pub struct Coordinate {
51    pub lat: f64,
52    pub lng: f64,
53}
54
55impl Coordinate {
56    pub fn new(lat: f64, lng: f64) -> Result<Self, String> {
57        if !(-90.0..=90.0).contains(&lat) {
58            return Err(format!("Latitude {lat} out of range [-90, 90]"));
59        }
60        if !(-180.0..=180.0).contains(&lng) {
61            return Err(format!("Longitude {lng} out of range [-180, 180]"));
62        }
63        Ok(Self { lat, lng })
64    }
65}
66
67/// Bounding box for rectangular queries
68#[derive(Debug, Clone, Copy, Deserialize)]
69pub struct BoundingBox {
70    pub min_lat: f64,
71    pub min_lng: f64,
72    pub max_lat: f64,
73    pub max_lng: f64,
74}
75
76impl BoundingBox {
77    pub fn contains(&self, coord: &Coordinate) -> bool {
78        coord.lat >= self.min_lat
79            && coord.lat <= self.max_lat
80            && coord.lng >= self.min_lng
81            && coord.lng <= self.max_lng
82    }
83}
84
85/// Radius query parameters
86#[derive(Debug, Clone, Copy, Deserialize)]
87pub struct RadiusQuery {
88    pub center_lat: f64,
89    pub center_lng: f64,
90    /// Radius in kilometers
91    pub radius_km: f64,
92}
93
94/// Geospatial query request
95#[derive(Debug, Clone, Deserialize)]
96pub struct GeoQueryRequest {
97    /// Bounding box filter (optional)
98    pub bbox: Option<BoundingBox>,
99    /// Radius filter (optional, applied after bbox if both present)
100    pub radius: Option<RadiusQuery>,
101    /// Additional event_type filter
102    pub event_type: Option<String>,
103    /// Maximum results
104    pub limit: Option<usize>,
105    /// Sort by distance from a point (only meaningful with radius query)
106    pub sort_by_distance: Option<bool>,
107}
108
109/// A geo-enriched event result
110#[derive(Debug, Clone, Serialize)]
111pub struct GeoEventResult {
112    pub event: serde_json::Value,
113    pub coordinate: Coordinate,
114    /// Distance from query center in km (only set for radius queries)
115    pub distance_km: Option<f64>,
116}
117
118/// Grid cell key for the spatial index
119#[derive(Debug, Clone, Hash, Eq, PartialEq)]
120struct GridCell {
121    lat_cell: i32,
122    lng_cell: i32,
123}
124
125impl GridCell {
126    fn from_coordinate(coord: &Coordinate) -> Self {
127        Self {
128            lat_cell: (coord.lat / GRID_CELL_SIZE).floor() as i32,
129            lng_cell: (coord.lng / GRID_CELL_SIZE).floor() as i32,
130        }
131    }
132}
133
134/// In-memory geospatial index using grid cells
135pub struct GeoIndex {
136    /// Grid cell → list of (event_id, coordinate) entries
137    grid: FastDashMap<(i32, i32), Vec<(Uuid, Coordinate)>>,
138    grid_charge: MapCharge,
139    grid_entries: Tally,
140    /// Event ID → (index call sequence, coordinate). The sequence restores the
141    /// ingest order that query results have always had.
142    coordinates: FastDashMap<Uuid, (u64, Coordinate)>,
143    coordinates_charge: MapCharge,
144    next_sequence: AtomicU64,
145}
146
147impl Default for GeoIndex {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153impl GeoIndex {
154    pub fn new() -> Self {
155        Self {
156            grid: fast_dashmap(),
157            grid_charge: MapCharge::new(
158                Owner::GeoIndex,
159                size_of::<((i32, i32), Vec<(Uuid, Coordinate)>)>(),
160            ),
161            grid_entries: Tally::new(Owner::GeoIndex),
162            coordinates: fast_dashmap(),
163            coordinates_charge: MapCharge::new(
164                Owner::GeoIndex,
165                size_of::<(Uuid, (u64, Coordinate))>(),
166            ),
167            next_sequence: AtomicU64::new(0),
168        }
169    }
170
171    /// Index an event's coordinates (if extractable)
172    pub fn index_event(&self, event: &Event) {
173        if let Some(coord) = extract_coordinates(event) {
174            let sequence = self.next_sequence.fetch_add(1, Ordering::Relaxed);
175            let cell = GridCell::from_coordinate(&coord);
176            let key = (cell.lat_cell, cell.lng_cell);
177            self.grid_charge
178                .ensure(&self.grid, &key, || key, Vec::new, 0);
179            {
180                let mut entries = self.grid.entry(key).or_default();
181                let before = entries.capacity();
182                entries.push((event.id, coord));
183                self.grid_entries
184                    .grow(before, entries.capacity(), size_of::<(Uuid, Coordinate)>());
185            }
186            self.coordinates_charge.ensure(
187                &self.coordinates,
188                &event.id,
189                || event.id,
190                || (sequence, coord),
191                0,
192            );
193            self.coordinates.insert(event.id, (sequence, coord));
194        }
195    }
196
197    /// Get coordinate for an event
198    pub fn get_coordinate(&self, event_id: &Uuid) -> Option<Coordinate> {
199        self.coordinates.get(event_id).map(|c| c.1)
200    }
201
202    fn sequence_of(&self, event_id: &Uuid) -> Option<u64> {
203        self.coordinates.get(event_id).map(|c| c.0)
204    }
205
206    /// Find all event IDs within a bounding box
207    pub fn query_bbox(&self, bbox: &BoundingBox) -> Vec<(Uuid, Coordinate)> {
208        let min_cell = GridCell::from_coordinate(&Coordinate {
209            lat: bbox.min_lat,
210            lng: bbox.min_lng,
211        });
212        let max_cell = GridCell::from_coordinate(&Coordinate {
213            lat: bbox.max_lat,
214            lng: bbox.max_lng,
215        });
216
217        let mut results = Vec::new();
218        for lat_cell in min_cell.lat_cell..=max_cell.lat_cell {
219            for lng_cell in min_cell.lng_cell..=max_cell.lng_cell {
220                if let Some(entries) = self.grid.get(&(lat_cell, lng_cell)) {
221                    for (id, coord) in entries.iter() {
222                        if bbox.contains(coord) {
223                            results.push((*id, *coord));
224                        }
225                    }
226                }
227            }
228        }
229        results
230    }
231
232    /// Find all event IDs within a radius
233    pub fn query_radius(&self, query: &RadiusQuery) -> Vec<(Uuid, Coordinate, f64)> {
234        // Compute bounding box for the radius to narrow grid cells
235        let lat_delta = query.radius_km / 111.0; // ~111 km per degree latitude
236        let lng_delta = query.radius_km / (111.0 * query.center_lat.to_radians().cos().max(0.001));
237        let bbox = BoundingBox {
238            min_lat: query.center_lat - lat_delta,
239            max_lat: query.center_lat + lat_delta,
240            min_lng: query.center_lng - lng_delta,
241            max_lng: query.center_lng + lng_delta,
242        };
243
244        let candidates = self.query_bbox(&bbox);
245        let center = Coordinate {
246            lat: query.center_lat,
247            lng: query.center_lng,
248        };
249
250        candidates
251            .into_iter()
252            .filter_map(|(id, coord)| {
253                let dist = haversine_distance(&center, &coord);
254                if dist <= query.radius_km {
255                    Some((id, coord, dist))
256                } else {
257                    None
258                }
259            })
260            .collect()
261    }
262
263    /// Number of indexed events
264    pub fn len(&self) -> usize {
265        self.coordinates.len()
266    }
267
268    pub fn is_empty(&self) -> bool {
269        self.coordinates.is_empty()
270    }
271
272    /// Statistics about the geo index
273    pub fn stats(&self) -> GeoIndexStats {
274        GeoIndexStats {
275            indexed_events: self.coordinates.len(),
276            grid_cells: self.grid.len(),
277        }
278    }
279}
280
281/// Geo index statistics
282#[derive(Debug, Clone, Serialize)]
283pub struct GeoIndexStats {
284    pub indexed_events: usize,
285    pub grid_cells: usize,
286}
287
288/// Haversine distance between two coordinates in kilometers
289pub fn haversine_distance(a: &Coordinate, b: &Coordinate) -> f64 {
290    let d_lat = (b.lat - a.lat).to_radians();
291    let d_lng = (b.lng - a.lng).to_radians();
292    let lat1 = a.lat.to_radians();
293    let lat2 = b.lat.to_radians();
294
295    let h = (d_lat / 2.0).sin().powi(2) + lat1.cos() * lat2.cos() * (d_lng / 2.0).sin().powi(2);
296    let c = 2.0 * h.sqrt().asin();
297
298    EARTH_RADIUS_KM * c
299}
300
301/// Extract coordinates from an event's metadata or payload
302pub fn extract_coordinates(event: &Event) -> Option<Coordinate> {
303    // Try metadata first
304    if let Some(ref meta) = event.metadata
305        && let Some(coord) = try_extract_coord(meta)
306    {
307        return Some(coord);
308    }
309    // Fall back to payload
310    try_extract_coord(&event.payload)
311}
312
313/// Try to extract coordinates from a JSON value
314fn try_extract_coord(value: &serde_json::Value) -> Option<Coordinate> {
315    // Try nested location object
316    if let Some(loc) = value.get("location") {
317        if let (Some(lat), Some(lng)) = (
318            loc.get("lat").and_then(serde_json::Value::as_f64),
319            loc.get("lng").and_then(serde_json::Value::as_f64),
320        ) && let Ok(c) = Coordinate::new(lat, lng)
321        {
322            return Some(c);
323        }
324        if let (Some(lat), Some(lng)) = (
325            loc.get("latitude").and_then(serde_json::Value::as_f64),
326            loc.get("longitude").and_then(serde_json::Value::as_f64),
327        ) && let Ok(c) = Coordinate::new(lat, lng)
328        {
329            return Some(c);
330        }
331    }
332
333    // Try flat lat/lng
334    if let (Some(lat), Some(lng)) = (
335        value.get("lat").and_then(serde_json::Value::as_f64),
336        value.get("lng").and_then(serde_json::Value::as_f64),
337    ) && let Ok(c) = Coordinate::new(lat, lng)
338    {
339        return Some(c);
340    }
341
342    // Try flat latitude/longitude
343    if let (Some(lat), Some(lng)) = (
344        value.get("latitude").and_then(serde_json::Value::as_f64),
345        value.get("longitude").and_then(serde_json::Value::as_f64),
346    ) && let Ok(c) = Coordinate::new(lat, lng)
347    {
348        return Some(c);
349    }
350
351    None
352}
353
354/// Execute a geospatial query. `resolve` maps a candidate id to its event, or `None`
355/// when the event is not visible to the caller; only resolved events are materialized.
356pub fn execute_geo_query(
357    resolve: &dyn Fn(Uuid) -> Option<Event>,
358    geo_index: &GeoIndex,
359    request: &GeoQueryRequest,
360) -> Vec<GeoEventResult> {
361    let spatial: Vec<(Uuid, Coordinate, Option<f64>)> = if let Some(ref radius) = request.radius {
362        geo_index
363            .query_radius(radius)
364            .into_iter()
365            .map(|(id, coord, dist)| (id, coord, Some(dist)))
366            .collect()
367    } else if let Some(ref bbox) = request.bbox {
368        geo_index
369            .query_bbox(bbox)
370            .into_iter()
371            .map(|(id, coord)| (id, coord, None))
372            .collect()
373    } else {
374        geo_index
375            .coordinates
376            .iter()
377            .map(|entry| (*entry.key(), entry.value().1, None))
378            .collect()
379    };
380
381    let mut candidates: Vec<(u64, Uuid, Coordinate, Option<f64>)> = spatial
382        .into_iter()
383        .filter_map(|(id, coord, dist)| Some((geo_index.sequence_of(&id)?, id, coord, dist)))
384        .collect();
385    candidates.sort_unstable_by_key(|candidate| candidate.0);
386
387    let limit = request
388        .limit
389        .unwrap_or(GEO_QUERY_MAX_RESULTS)
390        .min(GEO_QUERY_MAX_RESULTS);
391    // A stable sort before resolution keeps the result identical to sorting the
392    // resolved events, and lets the loop stop at `limit` clones.
393    if request.sort_by_distance.unwrap_or(false) {
394        candidates.sort_by(|a, b| {
395            a.3.unwrap_or(f64::MAX)
396                .partial_cmp(&b.3.unwrap_or(f64::MAX))
397                .unwrap_or(std::cmp::Ordering::Equal)
398        });
399    }
400
401    let mut results: Vec<GeoEventResult> = Vec::new();
402    for (_, id, coord, dist) in candidates {
403        if results.len() == limit {
404            break;
405        }
406        let Some(event) = resolve(id) else {
407            continue;
408        };
409        if let Some(ref et) = request.event_type
410            && event.event_type_str() != et
411        {
412            continue;
413        }
414        results.push(GeoEventResult {
415            event: serde_json::json!({
416                "id": event.id.to_string(),
417                "event_type": event.event_type_str(),
418                "entity_id": event.entity_id_str(),
419                "tenant_id": event.tenant_id_str(),
420                "payload": event.payload,
421                "metadata": event.metadata,
422                "timestamp": event.timestamp.to_rfc3339(),
423                "version": event.version,
424            }),
425            coordinate: coord,
426            distance_km: dist,
427        });
428    }
429
430    results
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    fn make_geo_event(entity: &str, lat: f64, lng: f64) -> Event {
438        Event::from_strings(
439            "location.update".to_string(),
440            entity.to_string(),
441            "default".to_string(),
442            serde_json::json!({"action": "checkin"}),
443            Some(serde_json::json!({"location": {"lat": lat, "lng": lng}})),
444        )
445        .unwrap()
446    }
447
448    #[test]
449    fn test_haversine_same_point() {
450        let a = Coordinate { lat: 0.0, lng: 0.0 };
451        assert!((haversine_distance(&a, &a) - 0.0).abs() < 0.001);
452    }
453
454    #[test]
455    fn test_haversine_known_distance() {
456        // NYC to London is approximately 5570 km
457        let nyc = Coordinate {
458            lat: 40.7128,
459            lng: -74.0060,
460        };
461        let london = Coordinate {
462            lat: 51.5074,
463            lng: -0.1278,
464        };
465        let dist = haversine_distance(&nyc, &london);
466        assert!((dist - 5570.0).abs() < 50.0, "NYC-London: {dist} km");
467    }
468
469    #[test]
470    fn test_coordinate_validation() {
471        assert!(Coordinate::new(45.0, 90.0).is_ok());
472        assert!(Coordinate::new(91.0, 0.0).is_err());
473        assert!(Coordinate::new(0.0, 181.0).is_err());
474    }
475
476    #[test]
477    fn test_bounding_box_contains() {
478        let bbox = BoundingBox {
479            min_lat: 40.0,
480            max_lat: 42.0,
481            min_lng: -75.0,
482            max_lng: -73.0,
483        };
484        assert!(bbox.contains(&Coordinate {
485            lat: 41.0,
486            lng: -74.0
487        }));
488        assert!(!bbox.contains(&Coordinate {
489            lat: 43.0,
490            lng: -74.0
491        }));
492    }
493
494    #[test]
495    fn test_extract_coordinates_from_metadata_location() {
496        let event = make_geo_event("e1", 40.7128, -74.0060);
497        let coord = extract_coordinates(&event).unwrap();
498        assert!((coord.lat - 40.7128).abs() < 0.001);
499        assert!((coord.lng - (-74.0060)).abs() < 0.001);
500    }
501
502    #[test]
503    fn test_extract_coordinates_from_payload_flat() {
504        let event = Event::from_strings(
505            "location.update".to_string(),
506            "e1".to_string(),
507            "default".to_string(),
508            serde_json::json!({"lat": 51.5074, "lng": -0.1278}),
509            None,
510        )
511        .unwrap();
512        let coord = extract_coordinates(&event).unwrap();
513        assert!((coord.lat - 51.5074).abs() < 0.001);
514    }
515
516    #[test]
517    fn test_no_coordinates() {
518        let event = Event::from_strings(
519            "user.created".to_string(),
520            "u1".to_string(),
521            "default".to_string(),
522            serde_json::json!({"name": "Alice"}),
523            None,
524        )
525        .unwrap();
526        assert!(extract_coordinates(&event).is_none());
527    }
528
529    #[test]
530    fn test_geo_index_and_bbox_query() {
531        let index = GeoIndex::new();
532        let events = vec![
533            make_geo_event("e1", 40.7128, -74.0060), // NYC
534            make_geo_event("e2", 51.5074, -0.1278),  // London
535            make_geo_event("e3", 41.0, -73.5),       // Near NYC
536        ];
537        for e in &events {
538            index.index_event(e);
539        }
540        assert_eq!(index.len(), 3);
541
542        let bbox = BoundingBox {
543            min_lat: 40.0,
544            max_lat: 42.0,
545            min_lng: -75.0,
546            max_lng: -73.0,
547        };
548        let results = index.query_bbox(&bbox);
549        assert_eq!(results.len(), 2); // NYC and Near NYC
550    }
551
552    #[test]
553    fn test_geo_index_radius_query() {
554        let index = GeoIndex::new();
555        let events = vec![
556            make_geo_event("e1", 40.7128, -74.0060), // NYC
557            make_geo_event("e2", 51.5074, -0.1278),  // London
558            make_geo_event("e3", 40.75, -73.99),     // Near NYC (~5km)
559        ];
560        for e in &events {
561            index.index_event(e);
562        }
563
564        let query = RadiusQuery {
565            center_lat: 40.7128,
566            center_lng: -74.0060,
567            radius_km: 10.0,
568        };
569        let results = index.query_radius(&query);
570        assert_eq!(results.len(), 2); // NYC and Near NYC
571        for (_, _, dist) in &results {
572            assert!(*dist <= 10.0);
573        }
574    }
575
576    #[test]
577    fn test_execute_geo_query_with_type_filter() {
578        let index = GeoIndex::new();
579        let mut events = vec![make_geo_event("e1", 40.7128, -74.0060)];
580        let other = Event::from_strings(
581            "user.created".to_string(),
582            "e2".to_string(),
583            "default".to_string(),
584            serde_json::json!({"lat": 40.75, "lng": -73.99}),
585            None,
586        )
587        .unwrap();
588        events.push(other);
589        for e in &events {
590            index.index_event(e);
591        }
592
593        let req = GeoQueryRequest {
594            bbox: Some(BoundingBox {
595                min_lat: 40.0,
596                max_lat: 42.0,
597                min_lng: -75.0,
598                max_lng: -73.0,
599            }),
600            radius: None,
601            event_type: Some("location.update".to_string()),
602            limit: None,
603            sort_by_distance: None,
604        };
605        let resolve = |id: Uuid| events.iter().find(|e| e.id == id).cloned();
606        let results = execute_geo_query(&resolve, &index, &req);
607        assert_eq!(results.len(), 1);
608    }
609
610    #[test]
611    fn test_geo_index_stats() {
612        let index = GeoIndex::new();
613        let events = vec![
614            make_geo_event("e1", 40.7128, -74.0060),
615            make_geo_event("e2", 51.5074, -0.1278),
616        ];
617        for e in &events {
618            index.index_event(e);
619        }
620        let stats = index.stats();
621        assert_eq!(stats.indexed_events, 2);
622        assert!(stats.grid_cells >= 1);
623    }
624}