nodedb 0.4.0

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// SPDX-License-Identifier: BUSL-1.1

//! Spatial geometry insert/delete handler for sync sessions.
//!
//! Decodes `SpatialInsertMsg` / `SpatialDeleteMsg` from a Lite client,
//! deserialises the geometry, allocates a surrogate for the document ID,
//! appends a WAL record on the Control Plane, dispatches
//! `SpatialOp::Insert` / `SpatialOp::Delete` to the Data Plane through
//! the idempotency gate, and returns an ACK frame.
//!
//! Handler methods live in `spatial_session.rs` to keep both files under
//! the 500-line limit.
//!
//! Structural pattern mirrors `vector_handler.rs`.

use async_trait::async_trait;

use nodedb_types::Surrogate;
use nodedb_types::geometry::Geometry;

use crate::types::{DatabaseId, TenantId, VShardId};

// ── Dispatcher trait ─────────────────────────────────────────────────────────

/// Parameters bundling the spatial-index target for a single insert dispatch.
///
/// Groups the four fields that together identify the geometry being written:
/// which collection, which field index, the stable surrogate ID, and the
/// geometry value itself.
#[derive(Debug)]
pub struct SpatialInsertTarget {
    pub collection: String,
    pub field: String,
    pub surrogate: Surrogate,
    pub geometry: Geometry,
}

/// Encapsulates async Data Plane dispatch for spatial insert/delete.
///
/// Returns the raw `Response.payload` bytes so the handler can decode the
/// [`SyncAckResult`] for gate status propagation to the Lite client.
#[async_trait]
pub trait SpatialDispatcher: Send + Sync {
    /// Insert a geometry into the R-tree on the Data Plane.
    async fn dispatch_insert(
        &self,
        tenant_id: TenantId,
        vshard: VShardId,
        target: SpatialInsertTarget,
        provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>>;

    /// Remove a document's geometry from the R-tree on the Data Plane.
    async fn dispatch_delete(
        &self,
        tenant_id: TenantId,
        vshard: VShardId,
        collection: String,
        field: String,
        surrogate: Surrogate,
        provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>>;

    /// Assign a stable surrogate for `(collection, doc_id)`.
    fn assign_surrogate(
        &self,
        database_id: DatabaseId,
        tenant_id: TenantId,
        collection: &str,
        doc_id: &str,
    ) -> crate::Result<Surrogate>;
}

// ── SharedState adapter ──────────────────────────────────────────────────────

/// Production dispatcher: routes spatial ops to the Data Plane via the SPSC bridge.
pub struct SharedStateSpatialDispatcher<'a> {
    pub shared: &'a crate::control::state::SharedState,
}

#[async_trait]
impl<'a> SpatialDispatcher for SharedStateSpatialDispatcher<'a> {
    async fn dispatch_insert(
        &self,
        tenant_id: TenantId,
        vshard: VShardId,
        target: SpatialInsertTarget,
        provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>> {
        use crate::bridge::envelope::PhysicalPlan;
        use crate::control::server::wal_dispatch::wal_append_spatial_put;
        use crate::control::server::wal_dispatch_fts_spatial::encode_spatial_put_payload;
        use nodedb_physical::physical_plan::SpatialOp;

        let prov = provenance;
        let SpatialInsertTarget {
            collection,
            field,
            surrogate,
            geometry,
        } = target;

        let spatial_put_payload =
            encode_spatial_put_payload(&collection, &field, surrogate, &geometry, &prov)?;
        wal_append_spatial_put(
            &self.shared.wal,
            tenant_id,
            vshard,
            DatabaseId::DEFAULT,
            &spatial_put_payload,
        )?;

        let plan = PhysicalPlan::Spatial(SpatialOp::Insert {
            collection,
            field,
            surrogate,
            geometry,
            provenance: Some(prov),
        });

        super::raft_dispatch::dispatch_sync_payload(self.shared, tenant_id, vshard, plan).await
    }

    async fn dispatch_delete(
        &self,
        tenant_id: TenantId,
        vshard: VShardId,
        collection: String,
        field: String,
        surrogate: Surrogate,
        provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>> {
        use crate::bridge::envelope::PhysicalPlan;
        use crate::control::server::wal_dispatch::wal_append_spatial_delete;
        use crate::control::server::wal_dispatch_fts_spatial::encode_spatial_delete_payload;
        use nodedb_physical::physical_plan::SpatialOp;

        let prov = provenance;

        let spatial_delete_payload =
            encode_spatial_delete_payload(&collection, &field, surrogate, &prov);
        wal_append_spatial_delete(
            &self.shared.wal,
            tenant_id,
            vshard,
            DatabaseId::DEFAULT,
            &spatial_delete_payload,
        )?;

        let plan = PhysicalPlan::Spatial(SpatialOp::Delete {
            collection,
            field,
            surrogate,
            provenance: Some(prov),
        });

        super::raft_dispatch::dispatch_sync_payload(self.shared, tenant_id, vshard, plan).await
    }

    fn assign_surrogate(
        &self,
        database_id: DatabaseId,
        tenant_id: TenantId,
        collection: &str,
        doc_id: &str,
    ) -> crate::Result<Surrogate> {
        self.shared
            .surrogate_assigner
            .assign(database_id, tenant_id, collection, doc_id.as_bytes())
    }
}

// ── NoOp dispatcher (loud failure) ──────────────────────────────────────────

/// Dispatcher used when `SharedState` is unavailable.
pub struct NoOpSpatialDispatcher;

#[async_trait]
impl SpatialDispatcher for NoOpSpatialDispatcher {
    async fn dispatch_insert(
        &self,
        _tenant_id: TenantId,
        _vshard: VShardId,
        _target: SpatialInsertTarget,
        _provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>> {
        Err(super::raft_dispatch::noop_dispatch_error("spatial insert"))
    }

    async fn dispatch_delete(
        &self,
        _tenant_id: TenantId,
        _vshard: VShardId,
        _collection: String,
        _field: String,
        _surrogate: Surrogate,
        _provenance: nodedb_types::sync::wire::SyncProvenance,
    ) -> crate::Result<Vec<u8>> {
        Err(super::raft_dispatch::noop_dispatch_error("spatial delete"))
    }

    fn assign_surrogate(
        &self,
        _database_id: DatabaseId,
        _tenant_id: TenantId,
        _collection: &str,
        _doc_id: &str,
    ) -> crate::Result<Surrogate> {
        Ok(Surrogate::ZERO)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use super::super::session::SyncSession;
    use super::super::wire::*;
    use super::*;

    type MockCallLog = Arc<Mutex<Vec<(TenantId, String, String)>>>;

    struct MockDispatcher {
        insert_calls: MockCallLog,
        delete_calls: MockCallLog,
        result: crate::Result<()>,
    }

    impl MockDispatcher {
        fn ok() -> (Self, MockCallLog, MockCallLog) {
            let inserts = Arc::new(Mutex::new(Vec::new()));
            let deletes = Arc::new(Mutex::new(Vec::new()));
            (
                Self {
                    insert_calls: inserts.clone(),
                    delete_calls: deletes.clone(),
                    result: Ok(()),
                },
                inserts,
                deletes,
            )
        }

        fn err() -> Self {
            Self {
                insert_calls: Arc::new(Mutex::new(Vec::new())),
                delete_calls: Arc::new(Mutex::new(Vec::new())),
                result: Err(crate::Error::Internal {
                    detail: "mock failure".to_string(),
                }),
            }
        }
    }

    #[async_trait]
    impl SpatialDispatcher for MockDispatcher {
        async fn dispatch_insert(
            &self,
            tenant_id: TenantId,
            _vshard: VShardId,
            target: SpatialInsertTarget,
            provenance: nodedb_types::sync::wire::SyncProvenance,
        ) -> crate::Result<Vec<u8>> {
            let seq = provenance.seq;
            self.insert_calls
                .lock()
                .unwrap()
                .push((tenant_id, target.collection, target.field));
            super::super::test_support::mock_applied_ack(&self.result, seq)
        }

        async fn dispatch_delete(
            &self,
            tenant_id: TenantId,
            _vshard: VShardId,
            collection: String,
            field: String,
            _surrogate: Surrogate,
            provenance: nodedb_types::sync::wire::SyncProvenance,
        ) -> crate::Result<Vec<u8>> {
            let seq = provenance.seq;
            self.delete_calls
                .lock()
                .unwrap()
                .push((tenant_id, collection, field));
            super::super::test_support::mock_applied_ack(&self.result, seq)
        }

        fn assign_surrogate(
            &self,
            _database_id: DatabaseId,
            _tenant_id: TenantId,
            _collection: &str,
            _doc_id: &str,
        ) -> crate::Result<Surrogate> {
            Ok(Surrogate::ZERO)
        }
    }

    fn make_session() -> SyncSession {
        SyncSession::new("test-spatial-session".to_string())
    }

    fn make_point_geometry_bytes() -> Vec<u8> {
        let geom = nodedb_types::geometry::Geometry::point(10.0, 20.0);
        zerompk::to_msgpack_vec(&geom).unwrap()
    }

    fn make_insert_msg(collection: &str, field: &str, doc_id: &str) -> SpatialInsertMsg {
        SpatialInsertMsg {
            lite_id: "lite-test".to_string(),
            collection: collection.to_string(),
            field: field.to_string(),
            doc_id: doc_id.to_string(),
            geometry_bytes: make_point_geometry_bytes(),
            batch_id: 1,
            producer_id: 0,
            epoch: 0,
            seq: 0,
        }
    }

    fn make_delete_msg(collection: &str, field: &str, doc_id: &str) -> SpatialDeleteMsg {
        SpatialDeleteMsg {
            lite_id: "lite-test".to_string(),
            collection: collection.to_string(),
            field: field.to_string(),
            doc_id: doc_id.to_string(),
            batch_id: 2,
            producer_id: 0,
            epoch: 0,
            seq: 0,
        }
    }

    #[tokio::test]
    async fn unauthenticated_insert_returns_rejection() {
        let mut session = make_session();
        let (mock, inserts, _) = MockDispatcher::ok();
        let msg = make_insert_msg("places", "loc", "d1");

        let frame = session.handle_spatial_insert(&msg, &mock).await;
        assert!(frame.is_some());
        let ack: SpatialInsertAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(!ack.accepted);
        assert!(inserts.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn authenticated_insert_dispatches_and_acks() {
        let mut session = make_session();
        session.authenticated = true;
        let (mock, inserts, _) = MockDispatcher::ok();
        let msg = make_insert_msg("places", "loc", "d1");

        let frame = session.handle_spatial_insert(&msg, &mock).await;
        assert!(frame.is_some());
        let ack: SpatialInsertAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(ack.accepted);
        assert_eq!(ack.doc_id, "d1");
        assert_eq!(ack.field, "loc");
        assert_eq!(inserts.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn insert_dispatch_failure_rejects() {
        let mut session = make_session();
        session.authenticated = true;
        let mock = MockDispatcher::err();
        let msg = make_insert_msg("places", "loc", "d1");

        let frame = session.handle_spatial_insert(&msg, &mock).await;
        let ack: SpatialInsertAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(!ack.accepted);
        assert!(ack.reject_reason.is_some());
    }

    #[tokio::test]
    async fn authenticated_delete_dispatches_and_acks() {
        let mut session = make_session();
        session.authenticated = true;
        let (mock, _, deletes) = MockDispatcher::ok();
        let msg = make_delete_msg("places", "loc", "d1");

        let frame = session.handle_spatial_delete(&msg, &mock).await;
        let ack: SpatialDeleteAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(ack.accepted);
        assert_eq!(ack.doc_id, "d1");
        assert_eq!(deletes.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn unauthenticated_delete_returns_rejection() {
        let mut session = make_session();
        let (mock, _, deletes) = MockDispatcher::ok();
        let msg = make_delete_msg("places", "loc", "d1");

        let frame = session.handle_spatial_delete(&msg, &mock).await;
        let ack: SpatialDeleteAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(!ack.accepted);
        assert!(deletes.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn invalid_geometry_bytes_rejects_insert() {
        let mut session = make_session();
        session.authenticated = true;
        let (mock, inserts, _) = MockDispatcher::ok();

        let msg = SpatialInsertMsg {
            lite_id: "lite-test".to_string(),
            collection: "places".to_string(),
            field: "loc".to_string(),
            doc_id: "d1".to_string(),
            geometry_bytes: vec![0xFF, 0xFF, 0xFF], // invalid msgpack
            batch_id: 1,
            producer_id: 0,
            epoch: 0,
            seq: 0,
        };

        let frame = session.handle_spatial_insert(&msg, &mock).await;
        let ack: SpatialInsertAckMsg = frame.unwrap().decode_body().unwrap();
        assert!(!ack.accepted);
        assert!(ack.reject_reason.is_some());
        assert!(inserts.lock().unwrap().is_empty());
    }
}