nodedb-lite 0.1.0

Embedded edge client for NodeDB — offline vector search, graph traversal, and CRDT sync
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! §7.7 — Automated test coverage from `examples/live_sync.rs`.
//!
//! All tests from the example are now automated and run in CI. The example
//! file remains as a human-runnable dev tool; this file is the automated gate.
//!
//! Each test spawns its own Origin instance with a fresh temp data dir.

pub mod common;

use std::time::Duration;

use futures::{SinkExt, StreamExt};
use nodedb_lite::engine::crdt::CrdtEngine;
use nodedb_types::sync::shape::{ShapeDefinition, ShapeType};
use nodedb_types::sync::wire::{
    DeltaPushMsg, HandshakeMsg, PingPongMsg, ShapeSnapshotMsg, ShapeSubscribeMsg, SyncFrame,
    SyncMessageType, VectorClockSyncMsg,
};
use nodedb_types::wire_version::WIRE_FORMAT_VERSION;
use tokio_tungstenite::tungstenite::Message;

use common::origin::{OriginServer, connect_and_handshake};

// ── handshake ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn live_handshake() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let (mut ws, _) = tokio_tungstenite::connect_async(_server.ws_url)
        .await
        .expect("connect");

    let hs = HandshakeMsg {
        jwt_token: String::new(),
        vector_clock: std::collections::HashMap::new(),
        subscribed_shapes: Vec::new(),
        client_version: "live-test".into(),
        lite_id: String::new(),
        epoch: 0,
        wire_version: WIRE_FORMAT_VERSION,
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::Handshake, &hs)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
        .await
        .expect("timeout")
        .expect("closed")
        .expect("error");

    let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode frame");
    assert_eq!(frame.msg_type, SyncMessageType::HandshakeAck);

    let ack: nodedb_types::sync::wire::HandshakeAckMsg = frame.decode_body().expect("decode");
    assert!(ack.success, "handshake failed: {:?}", ack.error);
}

// ── delta push ────────────────────────────────────────────────────────────────

#[tokio::test]
async fn live_delta_push() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let payload =
        nodedb_types::json_to_msgpack(&serde_json::json!({"key": "value"})).expect("serialize");

    let delta = DeltaPushMsg {
        collection: "live_test".into(),
        document_id: "d1".into(),
        delta: payload,
        peer_id: 42,
        mutation_id: 1,
        checksum: 0,
        device_valid_time_ms: None,
        producer_id: 0,
        epoch: 0,
        seq: 0,
        device_id: 0,
        delta_signature: [0u8; 32],
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::DeltaPush, &delta)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
        .await
        .expect("timeout")
        .expect("closed")
        .expect("error");

    let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode");
    assert!(
        frame.msg_type == SyncMessageType::DeltaAck
            || frame.msg_type == SyncMessageType::DeltaReject,
        "unexpected frame type {:?}",
        frame.msg_type
    );
}

// ── ping/pong ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn live_ping_pong() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let ping = PingPongMsg {
        timestamp_ms: 123_456_789,
        is_pong: false,
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::PingPong, &ping)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
        .await
        .expect("timeout")
        .expect("closed")
        .expect("error");

    let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode");
    assert_eq!(frame.msg_type, SyncMessageType::PingPong);

    let pong: PingPongMsg = frame.decode_body().expect("decode PingPongMsg");
    assert!(pong.is_pong, "response must have is_pong=true");
    assert_eq!(pong.timestamp_ms, 123_456_789);
}

// ── reconnect latency ─────────────────────────────────────────────────────────

#[tokio::test]
async fn live_reconnect_under_200ms() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let start = std::time::Instant::now();
    let _ws = connect_and_handshake(_server.ws_url).await;
    let elapsed = start.elapsed();
    assert!(
        elapsed.as_millis() < 200,
        "reconnect took {}ms, target < 200ms",
        elapsed.as_millis()
    );
}

// ── vector clock sync ─────────────────────────────────────────────────────────

#[tokio::test]
async fn live_vector_clock_sync() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let clock = VectorClockSyncMsg {
        clocks: {
            let mut m = std::collections::HashMap::new();
            m.insert("0000000000000001".to_string(), 42u64);
            m
        },
        sender_id: 1,
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::VectorClockSync, &clock)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let result = tokio::time::timeout(Duration::from_secs(2), ws.next()).await;
    match result {
        Err(_) => {}
        Ok(Some(Ok(Message::Close(_)))) => {
            panic!("Origin closed session after VectorClockSync");
        }
        _ => {}
    }
}

// ── shape subscribe ───────────────────────────────────────────────────────────

#[tokio::test]
async fn live_shape_subscribe() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let subscribe = ShapeSubscribeMsg {
        shape: ShapeDefinition {
            shape_id: "live-test-shape".into(),
            tenant_id: 0,
            shape_type: ShapeType::Document {
                collection: "orders".into(),
                predicate: Vec::new(),
            },
            description: "live test".into(),
            field_filter: vec![],
        },
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::ShapeSubscribe, &subscribe)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
        .await
        .expect("timeout")
        .expect("closed")
        .expect("error");

    let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode");
    assert_eq!(frame.msg_type, SyncMessageType::ShapeSnapshot);

    let snapshot: ShapeSnapshotMsg = frame.decode_body().expect("decode ShapeSnapshotMsg");
    assert_eq!(snapshot.shape_id, "live-test-shape");
}

// ── real loro delta ───────────────────────────────────────────────────────────

#[tokio::test]
async fn live_real_loro_delta_push() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let mut engine = CrdtEngine::new(100).expect("crdt engine");
    engine
        .upsert(
            "users",
            "alice",
            &[("name", loro::LoroValue::String("Alice".into()))],
        )
        .expect("upsert");

    let deltas = engine.pending_deltas();
    assert!(!deltas.is_empty(), "no deltas generated");

    let msg = DeltaPushMsg {
        collection: "users".into(),
        document_id: "alice".into(),
        delta: deltas[0].delta_bytes.clone(),
        peer_id: 100,
        mutation_id: 1,
        checksum: 0,
        device_valid_time_ms: None,
        producer_id: 0,
        epoch: 0,
        seq: 0,
        device_id: 0,
        delta_signature: [0u8; 32],
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::DeltaPush, &msg)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
        .await
        .expect("timeout")
        .expect("closed")
        .expect("error");

    let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode");
    assert!(
        frame.msg_type == SyncMessageType::DeltaAck
            || frame.msg_type == SyncMessageType::DeltaReject,
        "unexpected: {:?}",
        frame.msg_type
    );
}

// ── concurrent delta push ─────────────────────────────────────────────────────

#[tokio::test]
async fn live_concurrent_delta_push() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let mut engine1 = CrdtEngine::new(201).expect("engine1");
    engine1
        .upsert(
            "notes",
            "n1",
            &[("author", loro::LoroValue::String("peer1".into()))],
        )
        .expect("upsert1");

    let mut engine2 = CrdtEngine::new(202).expect("engine2");
    engine2
        .upsert(
            "notes",
            "n2",
            &[("author", loro::LoroValue::String("peer2".into()))],
        )
        .expect("upsert2");

    for (i, (engine, doc_id)) in [(engine1, "n1"), (engine2, "n2")].iter().enumerate() {
        let deltas = engine.pending_deltas();
        assert!(!deltas.is_empty(), "no deltas from engine {i}");
        let msg = DeltaPushMsg {
            collection: "notes".into(),
            document_id: doc_id.to_string(),
            delta: deltas[0].delta_bytes.clone(),
            peer_id: 200 + i as u64 + 1,
            mutation_id: i as u64 + 1,
            checksum: 0,
            device_valid_time_ms: None,
            producer_id: 0,
            epoch: 0,
            seq: 0,
            device_id: 0,
            delta_signature: [0u8; 32],
        };
        ws.send(Message::Binary(
            SyncFrame::try_encode(SyncMessageType::DeltaPush, &msg)
                .expect("encode")
                .to_bytes()
                .into(),
        ))
        .await
        .expect("send");
    }

    // Collect the two terminal responses. The connection is full-duplex and
    // Origin also pushes server-initiated frames (the CRDT delta fan-out to
    // subscribed sessions), which can interleave with the acks in any order.
    // Skip anything that is not a terminal response to our pushes rather than
    // asserting on arrival order the protocol does not guarantee.
    let mut terminal = 0;
    while terminal < 2 {
        let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
            .await
            .unwrap_or_else(|_| panic!("timeout after {terminal} terminal response(s)"))
            .unwrap_or_else(|| panic!("closed after {terminal} terminal response(s)"))
            .unwrap_or_else(|e| panic!("error after {terminal} terminal response(s): {e}"));
        let frame = SyncFrame::from_bytes(resp.into_data().as_ref())
            .unwrap_or_else(|| panic!("bad frame after {terminal} terminal response(s)"));
        match frame.msg_type {
            SyncMessageType::DeltaAck | SyncMessageType::DeltaReject => terminal += 1,
            other => {
                eprintln!("skipping server-initiated frame while awaiting acks: {other:?}");
            }
        }
    }
}

// ── shape snapshot with WAL LSN ───────────────────────────────────────────────

#[tokio::test]
async fn live_shape_snapshot_with_wal_lsn() {
    let Some(_server) = OriginServer::try_spawn() else {
        eprintln!("SKIP: Origin binary unavailable (set NODEDB_BIN or run via `cargo nextest`)");
        return;
    };
    let mut ws = connect_and_handshake(_server.ws_url).await;

    let mut engine = CrdtEngine::new(300).expect("engine");
    engine
        .upsert("lsn_test", "d1", &[("x", loro::LoroValue::I64(1))])
        .expect("upsert");
    if let Some(d) = engine.pending_deltas().first() {
        let msg = DeltaPushMsg {
            collection: "lsn_test".into(),
            document_id: "d1".into(),
            delta: d.delta_bytes.clone(),
            peer_id: 300,
            mutation_id: 1,
            checksum: 0,
            device_valid_time_ms: None,
            producer_id: 0,
            epoch: 0,
            seq: 0,
            device_id: 0,
            delta_signature: [0u8; 32],
        };
        ws.send(Message::Binary(
            SyncFrame::try_encode(SyncMessageType::DeltaPush, &msg)
                .expect("encode")
                .to_bytes()
                .into(),
        ))
        .await
        .expect("send");
        let _ = tokio::time::timeout(Duration::from_secs(5), ws.next()).await;
    }

    let subscribe = ShapeSubscribeMsg {
        shape: ShapeDefinition {
            shape_id: "lsn-live-shape".into(),
            tenant_id: 0,
            shape_type: ShapeType::Document {
                collection: "lsn_test".into(),
                predicate: Vec::new(),
            },
            description: "lsn test".into(),
            field_filter: vec![],
        },
    };
    ws.send(Message::Binary(
        SyncFrame::try_encode(SyncMessageType::ShapeSubscribe, &subscribe)
            .expect("encode")
            .to_bytes()
            .into(),
    ))
    .await
    .expect("send");

    // Full-duplex channel: Origin may interleave a server-initiated frame
    // (e.g. a `DeltaPush` for a concurrent write) ahead of the `ShapeSnapshot`
    // answering our subscribe. Demultiplex by frame type rather than assuming
    // the next frame is the snapshot.
    let frame = loop {
        let resp = tokio::time::timeout(Duration::from_secs(5), ws.next())
            .await
            .expect("timeout")
            .expect("closed")
            .expect("error");

        let frame = SyncFrame::from_bytes(resp.into_data().as_ref()).expect("decode");
        if frame.msg_type == SyncMessageType::ShapeSnapshot {
            break frame;
        }
    };

    let snapshot: ShapeSnapshotMsg = frame.decode_body().expect("decode");
    assert_eq!(snapshot.shape_id, "lsn-live-shape");
    let _ = snapshot.snapshot_lsn;
}