samod-core 0.12.0

the core library for the samod automerge-repo implementation
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
//! Tests for waiting on connecting dialers before marking documents as NotFound.
//!
//! When a document actor has no connected peers but there is a dialer actively
//! connecting (in NeedTransport or TransportPending state), the document should
//! not be marked NotFound — it should wait for the dialer to either connect
//! (at which point sync can proceed) or fail permanently (at which point we
//! give up).

use std::time::Duration;

use automerge::{ROOT, ReadDoc, transaction::Transactable};
use samod_core::{BackoffConfig, DialerConfig, DocSearchPhase, DocumentId};
use samod_test_harness::{Network, RunningDocIds};

fn init_logging() {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .try_init();
}

/// A dialer config with a long backoff so it stays in TransportPending and
/// doesn't auto-retry during the test.
fn non_retrying_dialer(url: &str) -> DialerConfig {
    DialerConfig {
        url: url::Url::parse(url).unwrap(),
        backoff: BackoffConfig {
            initial_delay: Duration::from_secs(999),
            max_delay: Duration::from_secs(999),
            max_retries: Some(0),
        },
    }
}

/// Helper macro: create a document on a peer, write some data, return the doc ID.
/// (Macro because SamodId is not publicly exported from the test harness.)
macro_rules! create_doc_with_data {
    ($network:expr, $peer:expr) => {{
        let RunningDocIds { doc_id, actor_id } = $network.samod(&$peer).create_document();
        $network
            .samod(&$peer)
            .with_document_by_actor(actor_id, |doc| {
                let mut tx = doc.transaction();
                tx.put(ROOT, "key", "value").unwrap();
                tx.commit();
            })
            .unwrap();
        doc_id
    }};
}

// =============================================================================
// Tests
// =============================================================================

/// When there are no dialers and no connections, find should resolve to
/// NotFound immediately (baseline behavior, unchanged).
#[test]
fn find_without_dialers_resolves_to_not_found() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    let fake_doc_id = DocumentId::new(&mut rand::rng());
    let result = network.samod(&bob).find_document(&fake_doc_id);

    assert!(result.is_none(), "document should not be found");
}

/// When a dialer is in TransportPending state, find should NOT resolve to
/// NotFound — it should stay pending, waiting for the dialer to connect.
#[test]
fn find_with_connecting_dialer_stays_pending() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add a dialer — it enters TransportPending immediately
    let _dialer_id = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://sync.example.com"));

    // Start a search for a document that doesn't exist locally
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);

    // Process events
    network.run_until_quiescent();

    // The search should NOT have completed — the dialer is still connecting
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .expect("search status should exist")
        .clone();
    assert!(
        !search_status.is_currently_unavailable(),
        "search should still be running while dialer is connecting"
    );
}

#[test]
fn connected_with_long_handshake_does_not_mark_notfound() {
    // When a dialer connects in the hub, the status switches to
    // DialerStatus::Connected, but this doesn't mean the handshake is complete
    // which means that from the perspective of the document actor, the
    // connection is not yet ready. We want to make sure we wait until
    // the handshake is ready before returning NotFound
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add a dialer — it enters TransportPending immediately
    let dialer_id = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://sync.example.com"));

    // Start a find for a document that doesn't exist locally
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);

    // Process events
    network.run_until_quiescent();

    // Now mark the dialer as connected in the hub, but don't complete the handshake
    network.samod(&bob).create_dialer_connection(dialer_id);

    // The find should NOT have completed — the dialer is still connecting
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .expect("search status should exist")
        .clone();
    assert!(
        !search_status.is_currently_unavailable(),
        "search should still be pending while dialer is connecting, got {search_status:?}"
    );
}

/// When a dialer connects and the remote peer has the document, the search
/// should resolve to Ready. We connect the dialer before issuing search
/// because in the real runtime the handshake completes within the same
/// event loop iteration as `create_dialer_connection`, so the document
/// actor receives `NewConnection` before it can check dialer states.
#[test]
fn find_resolves_when_dialer_connects() {
    init_logging();

    let mut network = Network::new();
    let alice = network.create_samod("Alice");
    let bob = network.create_samod("Bob");

    // Alice creates a document with some data
    let doc_id = create_doc_with_data!(network, alice);

    // Bob adds a dialer and it connects to Alice
    let dialer_id = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://alice.example.com"));
    network.connect_with_dialer(bob, dialer_id, alice);
    network.run_until_quiescent();

    // Now Bob finds the document — should sync from Alice and complete
    network.samod(&bob).search_for_doc(&doc_id);
    let search_status = network
        .samod(&bob)
        .search_status(&doc_id)
        .expect("search status should exist")
        .clone();
    assert_eq!(search_status.phase(), &DocSearchPhase::Ready);

    // Verify the document content was synced
    let bob_ref = network.samod(&bob);
    let bob_doc = bob_ref.document(&doc_id).unwrap();
    let val = bob_doc
        .get(ROOT, "key")
        .unwrap()
        .map(|(v, _)| v.to_string())
        .unwrap_or_default();
    assert_eq!(val, r#""value""#);
}

/// When a dialer fails permanently (max retries exhausted), the find should
/// resolve to NotFound.
#[test]
fn find_resolves_to_not_found_when_dialer_fails() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add a dialer with max_retries=0 so it fails permanently on first failure
    let dialer_id = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://unreachable.example.com"));

    // Start finding a document
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);
    network.run_until_quiescent();

    // Find should still be pending
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .expect("search status should exist")
        .clone();
    assert!(matches!(
        search_status.phase(),
        DocSearchPhase::Searching(_)
    ));
    assert!(
        !search_status.is_currently_unavailable(),
        "search should still be running while dialer is connecting"
    );

    // Dialer fails permanently
    network
        .samod(&bob)
        .dial_failed(dialer_id, "connection refused".to_string());
    network.run_until_quiescent();

    // Now the find should complete as NotFound
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .expect("search status should exist")
        .clone();
    assert!(
        search_status.is_currently_unavailable(),
        "search should resolve to not found after dialer fails: got {search_status:?}",
    );
}

/// A dialer in WaitingToRetry state should NOT block NotFound. WaitingToRetry
/// means the dialer will try again later, but we don't hold up the find for it.
#[test]
fn waiting_to_retry_does_not_block_not_found() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add a dialer that will retry (not capped) with a long delay
    let dialer_id = network.samod(&bob).add_dialer(DialerConfig {
        url: url::Url::parse("wss://flaky.example.com").unwrap(),
        backoff: BackoffConfig {
            initial_delay: Duration::from_secs(999),
            max_delay: Duration::from_secs(999),
            max_retries: None, // will retry indefinitely
        },
    });

    // Start finding a document — pending because dialer is connecting
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);
    network.run_until_quiescent();

    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(matches!(
        search_status.phase(),
        &DocSearchPhase::Searching(_)
    ));
    assert!(
        !search_status.is_currently_unavailable(),
        "search should be pending while dialer is connecting"
    );

    // Dialer fails but will retry — transitions to WaitingToRetry
    network
        .samod(&bob)
        .dial_failed(dialer_id, "connection refused".to_string());
    network.run_until_quiescent();

    // WaitingToRetry should NOT block NotFound
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(
        search_status.is_currently_unavailable(),
        "search should resolve to unavailable when dialer is in WaitingToRetry: got {search_status:?}"
    );
}

/// Removing a dialer while a find is waiting on it should cause the find to
/// resolve to NotFound (assuming no other connections or connecting dialers).
#[test]
fn removing_dialer_while_waiting_triggers_not_found() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add a dialer
    let dialer_id = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://sync.example.com"));

    // Start finding a document
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);
    network.run_until_quiescent();

    // Find should be pending
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(
        !search_status.is_currently_unavailable(),
        "find should be pending while dialer exists"
    );

    // Remove the dialer entirely
    network.samod(&bob).remove_dialer(dialer_id);
    network.run_until_quiescent();

    // Find should now complete as NotFound
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(
        search_status.is_currently_unavailable(),
        "search should resolve to not found after dialer is removed: got {search_status:?}"
    );
}

/// With multiple dialers, the find should stay pending as long as ANY dialer
/// is still connecting, even if others have failed.
#[test]
fn multiple_dialers_stays_pending_while_any_connecting() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add two dialers
    let dialer1 = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://server1.example.com"));
    let _dialer2 = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://server2.example.com"));

    // Start finding a document
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);
    network.run_until_quiescent();

    // Find should be pending
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(matches!(
        search_status.phase(),
        DocSearchPhase::Searching(_)
    ));
    assert!(
        !search_status.is_currently_unavailable(),
        "search should be pending with two connecting dialers"
    );

    // First dialer fails permanently
    network
        .samod(&bob)
        .dial_failed(dialer1, "connection refused".to_string());
    network.run_until_quiescent();

    // Find should STILL be pending — dialer2 is still connecting
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(
        !search_status.is_currently_unavailable(),
        "search should still be pending while second dialer is connecting: got {search_status:?}"
    );
}

/// With multiple dialers, the find should resolve to NotFound only when ALL
/// connecting dialers have failed.
#[test]
fn multiple_dialers_not_found_when_all_fail() {
    init_logging();

    let mut network = Network::new();
    let bob = network.create_samod("Bob");

    // Add two dialers
    let dialer1 = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://server1.example.com"));
    let dialer2 = network
        .samod(&bob)
        .add_dialer(non_retrying_dialer("wss://server2.example.com"));

    // Start finding a document
    let fake_doc_id = DocumentId::new(&mut rand::rng());
    network.samod(&bob).search_for_doc(&fake_doc_id);
    network.run_until_quiescent();

    // Both dialers fail
    network
        .samod(&bob)
        .dial_failed(dialer1, "connection refused".to_string());
    network
        .samod(&bob)
        .dial_failed(dialer2, "connection refused".to_string());
    network.run_until_quiescent();

    // Now find should resolve to NotFound
    let search_status = network
        .samod(&bob)
        .search_status(&fake_doc_id)
        .unwrap()
        .clone();
    assert!(
        search_status.is_currently_unavailable(),
        "search should resolve to not found when all dialers have failed: got {search_status:?}"
    );
}