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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use std::time::Duration;

use samod_core::{
    BackoffConfig, CommandResult, DialerConfig, DialerEvent, DialerId, ListenerConfig, ListenerId,
    StorageKey, UnixTimestamp,
    actors::hub::{DispatchedCommand, Hub, HubEvent, HubResults},
    io::{IoResult, StorageResult, StorageTask},
};

/// Helper: create a Hub via the loader.
fn make_hub(name: &str) -> Hub {
    use rand::SeedableRng;
    use samod_core::{LoaderState, PeerId, SamodLoader};
    use std::collections::HashMap;

    let peer_id = PeerId::from_string(name.to_string());
    let mut loader = SamodLoader::new(peer_id);
    let now = UnixTimestamp::from_millis(1000);
    let mut rng = rand::rngs::StdRng::seed_from_u64(42);
    let mut storage: HashMap<StorageKey, Vec<u8>> = HashMap::new();

    loop {
        match loader.step(&mut rng, now) {
            LoaderState::NeedIo(tasks) => {
                for task in tasks {
                    let result = match task.action {
                        StorageTask::Load { ref key } => StorageResult::Load {
                            value: storage.get(key).cloned(),
                        },
                        StorageTask::LoadRange { ref prefix } => StorageResult::LoadRange {
                            values: storage
                                .iter()
                                .filter(|(k, _)| prefix.is_prefix_of(k))
                                .map(|(k, v)| (k.clone(), v.clone()))
                                .collect(),
                        },
                        StorageTask::Put { ref key, ref value } => {
                            storage.insert(key.clone(), value.clone());
                            StorageResult::Put
                        }
                        StorageTask::Delete { ref key } => {
                            storage.remove(key);
                            StorageResult::Delete
                        }
                    };
                    loader.provide_io_result(IoResult {
                        task_id: task.task_id,
                        payload: result,
                    });
                }
            }
            LoaderState::Loaded(hub) => break *hub,
        }
    }
}

fn make_rng() -> rand::rngs::StdRng {
    use rand::SeedableRng;
    rand::rngs::StdRng::seed_from_u64(42)
}

/// Helper: process a hub event.
fn handle_event(
    hub: &mut Hub,
    rng: &mut impl rand::Rng,
    now: UnixTimestamp,
    event: HubEvent,
) -> HubResults {
    hub.handle_event(rng, now, event)
}

/// Helper: add a dialer and return (dialer_id, results).
fn add_dialer(
    hub: &mut Hub,
    rng: &mut impl rand::Rng,
    now: UnixTimestamp,
    config: DialerConfig,
) -> (DialerId, HubResults) {
    let DispatchedCommand { command_id, event } = HubEvent::add_dialer(config);
    let results = handle_event(hub, rng, now, event);

    let dialer_id = results
        .completed_commands
        .iter()
        .find_map(|(cid, result)| {
            if *cid == command_id {
                if let CommandResult::AddDialer { dialer_id } = result {
                    Some(*dialer_id)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("add_dialer should complete immediately");

    (dialer_id, results)
}

/// Helper: add a listener and return (listener_id, results).
fn add_listener(
    hub: &mut Hub,
    rng: &mut impl rand::Rng,
    now: UnixTimestamp,
    config: ListenerConfig,
) -> (ListenerId, HubResults) {
    let DispatchedCommand { command_id, event } = HubEvent::add_listener(config);
    let results = handle_event(hub, rng, now, event);

    let listener_id = results
        .completed_commands
        .iter()
        .find_map(|(cid, result)| {
            if *cid == command_id {
                if let CommandResult::AddListener { listener_id } = result {
                    Some(*listener_id)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("add_listener should complete immediately");

    (listener_id, results)
}

/// Helper: create a connection for a dialer and return the connection_id.
fn create_dialer_connection(
    hub: &mut Hub,
    rng: &mut impl rand::Rng,
    now: UnixTimestamp,
    dialer_id: DialerId,
) -> samod_core::ConnectionId {
    let DispatchedCommand { command_id, event } = HubEvent::create_dialer_connection(dialer_id);
    let results = handle_event(hub, rng, now, event);
    results
        .completed_commands
        .iter()
        .find_map(|(cid, result)| {
            if *cid == command_id {
                if let CommandResult::CreateConnection { connection_id } = result {
                    Some(*connection_id)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("create_dialer_connection should complete immediately")
}

/// Helper: create a connection for a listener and return the connection_id.
fn create_listener_connection(
    hub: &mut Hub,
    rng: &mut impl rand::Rng,
    now: UnixTimestamp,
    listener_id: ListenerId,
) -> samod_core::ConnectionId {
    let DispatchedCommand { command_id, event } = HubEvent::create_listener_connection(listener_id);
    let results = handle_event(hub, rng, now, event);
    results
        .completed_commands
        .iter()
        .find_map(|(cid, result)| {
            if *cid == command_id {
                if let CommandResult::CreateConnection { connection_id } = result {
                    Some(*connection_id)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("create_listener_connection should complete immediately")
}

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

#[test]
fn dialer_emits_dial_request_on_add() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url: url.clone(),
        backoff: BackoffConfig::default(),
    };

    let (dialer_id, results) = add_dialer(&mut hub, &mut rng, now, config);

    // Should emit exactly one dial request for the dialer
    assert_eq!(results.dial_requests.len(), 1);
    assert_eq!(results.dial_requests[0].dialer_id, dialer_id);
    assert_eq!(results.dial_requests[0].url.as_str(), url.as_str());
}

#[test]
fn listener_does_not_emit_dial_request() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("ws://0.0.0.0:8080").unwrap();
    let config = ListenerConfig { url };

    let (_listener_id, results) = add_listener(&mut hub, &mut rng, now, config);

    assert!(results.dial_requests.is_empty());
}

#[test]
fn dialer_create_connection_transitions_to_connected() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig::default(),
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    // Atomically create a connection for the dialer (replaces old transport_ready)
    let _connection_id = create_dialer_connection(&mut hub, &mut rng, now, dialer_id);

    // No further dial requests should be emitted (dialer is now connected)
    let results = handle_event(&mut hub, &mut rng, now, HubEvent::tick());
    assert!(results.dial_requests.is_empty());
    assert!(results.dialer_events.is_empty());
}

#[test]
fn dialer_dial_failed_schedules_retry() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: None,
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    let results = handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "connection refused".to_string()),
    );

    // Should NOT immediately emit a new dial request (waiting for backoff)
    assert!(results.dial_requests.is_empty());
    // Not failed permanently (unlimited retries)
    assert!(results.dialer_events.is_empty());
}

#[test]
fn dialer_retries_after_tick() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url: url.clone(),
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: None,
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "connection refused".to_string()),
    );

    // Tick too early
    let early_tick = now + Duration::from_millis(10);
    let results = handle_event(&mut hub, &mut rng, early_tick, HubEvent::tick());
    assert!(results.dial_requests.is_empty());

    // Tick well after backoff
    let late_tick = now + Duration::from_secs(1);
    let results = handle_event(&mut hub, &mut rng, late_tick, HubEvent::tick());
    assert_eq!(results.dial_requests.len(), 1);
    assert_eq!(results.dial_requests[0].dialer_id, dialer_id);
}

#[test]
fn dialer_max_retries_reached() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let mut now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url: url.clone(),
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: Some(2),
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    // Fail attempt 1
    handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "fail 1".to_string()),
    );

    now += Duration::from_secs(10);
    let results = handle_event(&mut hub, &mut rng, now, HubEvent::tick());
    assert_eq!(
        results.dial_requests.len(),
        1,
        "should retry after first failure"
    );

    // Fail attempt 2
    let results = handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "fail 2".to_string()),
    );
    assert!(results.dialer_events.is_empty());

    now += Duration::from_secs(10);
    let results = handle_event(&mut hub, &mut rng, now, HubEvent::tick());
    assert_eq!(
        results.dial_requests.len(),
        1,
        "should retry after second failure"
    );

    // Fail attempt 3 - exceeds max_retries of 2
    let results = handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "fail 3".to_string()),
    );

    assert_eq!(results.dialer_events.len(), 1);
    match &results.dialer_events[0] {
        DialerEvent::MaxRetriesReached {
            dialer_id: did,
            url: event_url,
        } => {
            assert_eq!(*did, dialer_id);
            assert_eq!(event_url.as_str(), url.as_str());
        }
    }

    // Permanently failed - no more retries
    now += Duration::from_secs(100);
    let results = handle_event(&mut hub, &mut rng, now, HubEvent::tick());
    assert!(results.dial_requests.is_empty());
}

#[test]
fn dialer_connection_lost_triggers_backoff() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: None,
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    let connection_id = create_dialer_connection(&mut hub, &mut rng, now, dialer_id);

    let results = handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::connection_lost(connection_id),
    );

    assert!(results.dial_requests.is_empty());
    assert!(results.dialer_events.is_empty());

    let later = now + Duration::from_secs(1);
    let results = handle_event(&mut hub, &mut rng, later, HubEvent::tick());
    assert_eq!(results.dial_requests.len(), 1);
}

#[test]
fn listener_accepts_multiple_connections() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("ws://0.0.0.0:8080").unwrap();
    let config = ListenerConfig { url };

    let (listener_id, _results) = add_listener(&mut hub, &mut rng, now, config);

    let _conn1 = create_listener_connection(&mut hub, &mut rng, now, listener_id);
    let _conn2 = create_listener_connection(&mut hub, &mut rng, now, listener_id);

    assert_eq!(hub.connections().len(), 2);
}

#[test]
fn listener_connection_lost_does_not_retry() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("ws://0.0.0.0:8080").unwrap();
    let config = ListenerConfig { url };

    let (listener_id, _results) = add_listener(&mut hub, &mut rng, now, config);

    let conn1 = create_listener_connection(&mut hub, &mut rng, now, listener_id);

    let results = handle_event(&mut hub, &mut rng, now, HubEvent::connection_lost(conn1));

    assert!(results.dial_requests.is_empty());
    assert!(results.dialer_events.is_empty());

    let later = now + Duration::from_secs(10);
    let results = handle_event(&mut hub, &mut rng, later, HubEvent::tick());
    assert!(results.dial_requests.is_empty());
}

#[test]
fn remove_dialer_stops_retries() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig::default(),
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    handle_event(&mut hub, &mut rng, now, HubEvent::remove_dialer(dialer_id));

    let later = now + Duration::from_secs(100);
    let results = handle_event(&mut hub, &mut rng, later, HubEvent::tick());
    assert!(results.dial_requests.is_empty());
}

#[test]
fn backoff_delay_increases_exponentially() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1_000_000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(1000),
            max_delay: Duration::from_secs(60),
            max_retries: None,
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    let mut retry_triggers = Vec::new();

    for i in 0..5 {
        handle_event(
            &mut hub,
            &mut rng,
            now,
            HubEvent::dial_failed(dialer_id, format!("fail {i}")),
        );

        let mut tick_time = now;
        loop {
            tick_time += Duration::from_millis(100);
            let results = handle_event(&mut hub, &mut rng, tick_time, HubEvent::tick());
            if !results.dial_requests.is_empty() {
                retry_triggers.push(tick_time - now);
                break;
            }
            if (tick_time - now) > Duration::from_secs(120) {
                panic!("retry never triggered for attempt {i}");
            }
        }
    }

    // Later retries should take longer than earlier ones
    assert!(
        retry_triggers[4] > retry_triggers[0],
        "fifth retry delay {:?} should be larger than first {:?}",
        retry_triggers[4],
        retry_triggers[0],
    );
}

#[test]
fn backoff_capped_at_max_delay() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1_000_000);

    let max_delay = Duration::from_secs(2);
    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay,
            max_retries: None,
        },
    };

    let (dialer_id, _results) = add_dialer(&mut hub, &mut rng, now, config);

    for i in 0..20 {
        handle_event(
            &mut hub,
            &mut rng,
            now,
            HubEvent::dial_failed(dialer_id, format!("fail {i}")),
        );

        let tick_time = now + max_delay + Duration::from_millis(100);
        let results = handle_event(&mut hub, &mut rng, tick_time, HubEvent::tick());
        assert!(
            !results.dial_requests.is_empty(),
            "retry should trigger within max_delay + margin on attempt {i}"
        );
    }
}

#[test]
fn find_listener_for_url() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let now = UnixTimestamp::from_millis(1000);

    let url1 = url::Url::parse("ws://0.0.0.0:8080").unwrap();
    let url2 = url::Url::parse("ws://0.0.0.0:9090").unwrap();

    assert!(hub.find_listener_for_url(&url1).is_none());

    let config = ListenerConfig { url: url1.clone() };
    let (listener_id, _) = add_listener(&mut hub, &mut rng, now, config);

    assert_eq!(hub.find_listener_for_url(&url1), Some(listener_id));
    assert!(hub.find_listener_for_url(&url2).is_none());
}

#[test]
fn dialer_attempt_tracking() {
    let mut hub = make_hub("alice");
    let mut rng = make_rng();
    let mut now = UnixTimestamp::from_millis(1000);

    let url = url::Url::parse("wss://sync.example.com").unwrap();
    let config = DialerConfig {
        url,
        backoff: BackoffConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: None,
        },
    };

    let (dialer_id, _) = add_dialer(&mut hub, &mut rng, now, config);

    assert_eq!(hub.dialer_attempt(dialer_id), Some(0));

    handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "fail".to_string()),
    );
    assert_eq!(hub.dialer_attempt(dialer_id), Some(1));

    now += Duration::from_secs(10);
    handle_event(&mut hub, &mut rng, now, HubEvent::tick());

    handle_event(
        &mut hub,
        &mut rng,
        now,
        HubEvent::dial_failed(dialer_id, "fail".to_string()),
    );
    assert_eq!(hub.dialer_attempt(dialer_id), Some(2));
}