samod 0.9.0

A rust library for managing automerge documents, compatible with the js automerge-repo library
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
#![cfg(feature = "tokio")]

use std::{
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

use automerge::{Automerge, ReadDoc};
use futures::{Sink, SinkExt, Stream, StreamExt};
use samod::{
    AcceptorEvent, AcceptorHandle, BackoffConfig, Dialer, DialerEvent, PeerId, Repo, Transport,
};
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::PollSender;
use url::Url;

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

// =============================================================================
// In-memory transport helpers
// =============================================================================

#[derive(Debug)]
struct MemError(String);

impl std::fmt::Display for MemError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for MemError {}

/// One side of an in-memory transport.
struct MemTransportSide {
    send: Box<dyn Send + Unpin + Sink<Vec<u8>, Error = MemError>>,
    recv: Box<dyn Send + Unpin + Stream<Item = Result<Vec<u8>, MemError>>>,
}

/// Create a pair of in-memory transport sides.
fn mem_transport_pair() -> (MemTransportSide, MemTransportSide) {
    let (a_tx, b_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(16);
    let (b_tx, a_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(16);

    let a = MemTransportSide {
        send: Box::new(
            PollSender::new(a_tx).sink_map_err(|e| MemError(format!("send error: {e:?}"))),
        ),
        recv: Box::new(ReceiverStream::new(a_rx).map(Ok)),
    };

    let b = MemTransportSide {
        send: Box::new(
            PollSender::new(b_tx).sink_map_err(|e| MemError(format!("send error: {e:?}"))),
        ),
        recv: Box::new(ReceiverStream::new(b_rx).map(Ok)),
    };

    (a, b)
}

// =============================================================================
// Mock Dialer: connects via in-memory channels to an acceptor handle
// =============================================================================

/// A mock dialer that connects to a target `AcceptorHandle` via in-memory channels.
///
/// Each call to `connect()` creates a fresh pair of in-memory channels,
/// feeds one side to the acceptor, and returns the other as a `Transport`.
struct MockDialer {
    url: Url,
    acceptor: AcceptorHandle,
    connect_count: AtomicUsize,
}

impl MockDialer {
    fn new(url: Url, acceptor: AcceptorHandle) -> Self {
        Self {
            url,
            acceptor,
            connect_count: AtomicUsize::new(0),
        }
    }
}

impl Dialer for MockDialer {
    fn url(&self) -> Url {
        self.url.clone()
    }

    fn connect(
        &self,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<Transport, Box<dyn std::error::Error + Send + Sync + 'static>>,
                > + Send,
        >,
    > {
        self.connect_count.fetch_add(1, Ordering::SeqCst);

        let (dialer_side, acceptor_side) = mem_transport_pair();
        let acceptor = self.acceptor.clone();

        Box::pin(async move {
            // Feed the acceptor side to the acceptor handle
            acceptor
                .accept(Transport::new(acceptor_side.recv, acceptor_side.send))
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync + 'static>)?;

            Ok(Transport::new(dialer_side.recv, dialer_side.send))
        })
    }
}

/// A mock dialer that always fails.
struct FailingDialer {
    url: Url,
    fail_count: AtomicUsize,
}

impl FailingDialer {
    fn new(url: Url) -> Self {
        Self {
            url,
            fail_count: AtomicUsize::new(0),
        }
    }
}

impl Dialer for FailingDialer {
    fn url(&self) -> Url {
        self.url.clone()
    }

    fn connect(
        &self,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<Transport, Box<dyn std::error::Error + Send + Sync + 'static>>,
                > + Send,
        >,
    > {
        self.fail_count.fetch_add(1, Ordering::SeqCst);
        Box::pin(async { Err("connection refused".into()) })
    }
}

/// A mock dialer that fails N times then succeeds by connecting to an acceptor.
struct FailThenSucceedDialer {
    url: Url,
    acceptor: AcceptorHandle,
    fail_times: usize,
    attempt: AtomicUsize,
}

impl FailThenSucceedDialer {
    fn new(url: Url, acceptor: AcceptorHandle, fail_times: usize) -> Self {
        Self {
            url,
            acceptor,
            fail_times,
            attempt: AtomicUsize::new(0),
        }
    }
}

impl Dialer for FailThenSucceedDialer {
    fn url(&self) -> Url {
        self.url.clone()
    }

    fn connect(
        &self,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<Transport, Box<dyn std::error::Error + Send + Sync + 'static>>,
                > + Send,
        >,
    > {
        let attempt = self.attempt.fetch_add(1, Ordering::SeqCst);
        if attempt < self.fail_times {
            Box::pin(async move { Err(format!("connection refused (attempt {attempt})").into()) })
        } else {
            let (dialer_side, acceptor_side) = mem_transport_pair();
            let acceptor = self.acceptor.clone();
            Box::pin(async move {
                acceptor
                    .accept(Transport::new(acceptor_side.recv, acceptor_side.send))
                    .map_err(|e| {
                        Box::new(e) as Box<dyn std::error::Error + Send + Sync + 'static>
                    })?;
                Ok(Transport::new(dialer_side.recv, dialer_side.send))
            })
        }
    }
}

// =============================================================================
// Acceptor tests
// =============================================================================

#[tokio::test]
async fn acceptor_returns_handle_with_valid_id() {
    init_logging();
    let repo = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

    let url = Url::parse("ws://0.0.0.0:8080").unwrap();
    let handle = repo.make_acceptor(url).unwrap();

    // Should have a valid connector ID
    assert_eq!(handle.connection_count(), 0);

    repo.stop().await;
}

#[tokio::test]
async fn acceptor_accept_wires_connection() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

    let client = Repo::build_tokio()
        .with_peer_id(PeerId::from("client"))
        .load()
        .await;

    let url = Url::parse("ws://0.0.0.0:8080").unwrap();
    let acceptor = server.make_acceptor(url.clone()).unwrap();
    let mut events = acceptor.events();

    // Client dials the server via MockDialer
    let dialer = MockDialer::new(url, acceptor.clone());
    let handle = client
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    // Wait for handshake on client side
    let peer_info = tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("handshake timed out")
        .expect("handshake failed");

    assert_eq!(peer_info.peer_id, PeerId::from("server"));

    // Check acceptor event
    let event = tokio::time::timeout(Duration::from_secs(5), events.next())
        .await
        .expect("event timed out")
        .expect("event stream ended");

    match event {
        AcceptorEvent::ClientConnected { peer_info, .. } => {
            assert_eq!(peer_info.peer_id, PeerId::from("client"));
        }
        other => panic!("expected ClientConnected, got {:?}", other),
    }

    assert_eq!(acceptor.connection_count(), 1);

    handle.close();
    server.stop().await;
    client.stop().await;
}

#[tokio::test]
async fn acceptor_multiple_clients() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

    let url = Url::parse("ws://0.0.0.0:8080").unwrap();
    let acceptor = server.make_acceptor(url.clone()).unwrap();

    // Accept two clients via MockDialer
    for i in 0..2 {
        let client = Repo::build_tokio()
            .with_peer_id(PeerId::from(format!("client-{i}")))
            .load()
            .await;

        let dialer = MockDialer::new(url.clone(), acceptor.clone());
        let handle = client
            .dial(BackoffConfig::default(), Arc::new(dialer))
            .unwrap();

        tokio::time::timeout(Duration::from_secs(5), handle.established())
            .await
            .expect("handshake timed out")
            .expect("handshake failed");
    }

    assert_eq!(acceptor.connection_count(), 2);

    server.stop().await;
}

#[tokio::test]
async fn acceptor_close_disconnects_all() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

    let url = Url::parse("ws://0.0.0.0:8080").unwrap();
    let acceptor = server.make_acceptor(url.clone()).unwrap();

    // Accept one client via MockDialer
    let client = Repo::build_tokio()
        .with_peer_id(PeerId::from("client"))
        .load()
        .await;

    let dialer = MockDialer::new(url, acceptor.clone());
    let handle = client
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("handshake timed out")
        .expect("handshake failed");

    assert_eq!(acceptor.connection_count(), 1);

    // Close the acceptor — should not panic
    acceptor.close();

    // Server should still stop cleanly after closing the acceptor
    tokio::time::timeout(Duration::from_secs(5), server.stop())
        .await
        .expect("server.stop() timed out");
    client.stop().await;
}

// =============================================================================
// Acceptor URL reuse tests
// =============================================================================

#[tokio::test]
async fn acceptor_same_url_returns_same_handle() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

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

    let handle1 = server.make_acceptor(url.clone()).unwrap();
    let handle2 = server.make_acceptor(url).unwrap();

    // Both should use the same listener (same URL)
    assert_eq!(handle1.id(), handle2.id());

    server.stop().await;
}

#[tokio::test]
async fn acceptor_different_urls_create_separate_listeners() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

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

    let handle1 = server.make_acceptor(url1).unwrap();
    let handle2 = server.make_acceptor(url2).unwrap();

    // Different URLs should create different listeners
    assert_ne!(handle1.id(), handle2.id());

    server.stop().await;
}

// =============================================================================
// Dialer tests
// =============================================================================

#[tokio::test]
async fn dial_returns_handle() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    // Should not be connected yet (async handshake hasn't completed)
    // Note: it might connect very fast in tests, so we just check the handle exists
    let _id = handle.id();

    // Clean up
    handle.close();
    alice.stop().await;
    bob.stop().await;
}

#[tokio::test]
async fn dial_established_resolves_on_connect() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    let peer_info = tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed");

    assert_eq!(peer_info.peer_id, PeerId::from("bob"));
    assert!(handle.is_connected());
    assert_eq!(
        handle.peer_info().map(|p| p.peer_id),
        Some(PeerId::from("bob"))
    );

    handle.close();
    alice.stop().await;
    bob.stop().await;
}

#[tokio::test]
async fn dial_events_stream_connected() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    let mut events = handle.events();

    let event = tokio::time::timeout(Duration::from_secs(5), events.next())
        .await
        .expect("event timed out")
        .expect("event stream ended");

    match event {
        DialerEvent::Connected { peer_info } => {
            assert_eq!(peer_info.peer_id, PeerId::from("bob"));
        }
        other => panic!("expected Connected, got {:?}", other),
    }

    handle.close();
    alice.stop().await;
    bob.stop().await;
}

#[tokio::test]
async fn dial_and_accept_sync_documents() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let acceptor_for_events = acceptor.clone();
    let mut acceptor_events = acceptor_for_events.events();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    // Wait for connection on Alice's side
    tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed");

    // Get Bob's connection ID from the acceptor event
    let bob_conn_id = match tokio::time::timeout(Duration::from_secs(5), acceptor_events.next())
        .await
        .expect("acceptor event timed out")
        .expect("acceptor event stream ended")
    {
        AcceptorEvent::ClientConnected { connection_id, .. } => connection_id,
        other => panic!("expected ClientConnected, got {:?}", other),
    };

    // Create a document on Alice
    let alice_doc = alice.create(Automerge::new()).await.unwrap();
    alice_doc.with_document(|am| {
        use automerge::{AutomergeError, ROOT};
        am.transact::<_, _, AutomergeError>(|tx| {
            use automerge::transaction::Transactable;
            tx.put(ROOT, "hello", "world")?;
            Ok(())
        })
        .unwrap();
    });

    // Alice waits until her changes are sent to Bob
    let alice_conn_id = handle.connection_id().expect("should be connected");
    tokio::time::timeout(
        Duration::from_secs(5),
        alice_doc.they_have_our_changes(alice_conn_id),
    )
    .await
    .expect("alice -> bob sync timed out");

    // Bob should be able to find the document
    let bob_doc = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if let Some(doc) = bob.find(alice_doc.document_id().clone()).await.unwrap() {
                return doc;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("bob never found alice's document");

    // Wait for Bob to have Alice's changes
    tokio::time::timeout(
        Duration::from_secs(5),
        bob_doc.we_have_their_changes(bob_conn_id),
    )
    .await
    .expect("bob content sync timed out");

    bob_doc.with_document(|am| {
        let value = am
            .get(automerge::ROOT, "hello")
            .unwrap()
            .map(|(v, _)| v.into_string().unwrap());
        assert_eq!(value.as_deref(), Some("world"));
    });

    handle.close();
    alice.stop().await;
    bob.stop().await;
}

#[tokio::test]
async fn dial_bidirectional_sync() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed");

    // Create doc on Alice
    let alice_doc = alice.create(Automerge::new()).await.unwrap();
    alice_doc.with_document(|am| {
        use automerge::{AutomergeError, ROOT};
        am.transact::<_, _, AutomergeError>(|tx| {
            use automerge::transaction::Transactable;
            tx.put(ROOT, "from", "alice")?;
            Ok(())
        })
        .unwrap();
    });

    // Create doc on Bob
    let bob_doc = bob.create(Automerge::new()).await.unwrap();
    bob_doc.with_document(|am| {
        use automerge::{AutomergeError, ROOT};
        am.transact::<_, _, AutomergeError>(|tx| {
            use automerge::transaction::Transactable;
            tx.put(ROOT, "from", "bob")?;
            Ok(())
        })
        .unwrap();
    });

    // Wait for Alice to find Bob's doc
    let _alice_finds_bob = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if let Some(doc) = alice.find(bob_doc.document_id().clone()).await.unwrap() {
                return doc;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("alice never found bob's document");

    // Wait for Bob to find Alice's doc
    let _bob_finds_alice = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if let Some(doc) = bob.find(alice_doc.document_id().clone()).await.unwrap() {
                return doc;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("bob never found alice's document");

    handle.close();
    alice.stop().await;
    bob.stop().await;
}

// =============================================================================
// Failure / retry tests
// =============================================================================

#[tokio::test]
async fn dial_max_retries_emits_failure() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:9999").unwrap();
    let dialer = Arc::new(FailingDialer::new(url));

    let handle = alice
        .dial(
            BackoffConfig {
                initial_delay: Duration::from_millis(10),
                max_delay: Duration::from_millis(50),
                max_retries: Some(2),
            },
            dialer.clone(),
        )
        .unwrap();

    // established() should return Err when max retries are reached
    let result = tokio::time::timeout(Duration::from_secs(10), handle.established())
        .await
        .expect("established timed out");

    assert!(result.is_err());
    assert!(!handle.is_connected());

    alice.stop().await;
}

#[tokio::test]
async fn dial_events_max_retries_reached() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:9999").unwrap();
    let dialer = Arc::new(FailingDialer::new(url));

    let handle = alice
        .dial(
            BackoffConfig {
                initial_delay: Duration::from_millis(10),
                max_delay: Duration::from_millis(50),
                max_retries: Some(1),
            },
            dialer.clone(),
        )
        .unwrap();

    let mut events = handle.events();

    // Collect events until MaxRetriesReached
    let found_max_retries = tokio::time::timeout(Duration::from_secs(10), async {
        while let Some(event) = events.next().await {
            if matches!(event, DialerEvent::MaxRetriesReached) {
                return true;
            }
        }
        false
    })
    .await
    .expect("event stream timed out");

    assert!(
        found_max_retries,
        "should have received MaxRetriesReached event"
    );

    alice.stop().await;
}

#[tokio::test]
async fn dial_recovers_after_initial_failures() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();

    // Fail 2 times, then succeed
    let dialer = FailThenSucceedDialer::new(url, acceptor, 2);

    let handle = alice
        .dial(
            BackoffConfig {
                initial_delay: Duration::from_millis(10),
                max_delay: Duration::from_millis(100),
                max_retries: None, // unlimited retries
            },
            Arc::new(dialer),
        )
        .unwrap();

    let peer_info = tokio::time::timeout(Duration::from_secs(10), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed — should have recovered");

    assert_eq!(peer_info.peer_id, PeerId::from("bob"));

    handle.close();
    alice.stop().await;
    bob.stop().await;
}

// =============================================================================
// Lifecycle / cleanup tests
// =============================================================================

#[tokio::test]
async fn remove_connector_by_handle() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor);

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed");

    assert!(handle.is_connected());

    // Close the dialer — this removes the connector internally
    handle.close();

    // Repo should still stop cleanly after closing a connector
    tokio::time::timeout(Duration::from_secs(5), alice.stop())
        .await
        .expect("alice.stop() timed out");
    bob.stop().await;
}

#[tokio::test]
async fn stop_repo_with_active_connectors() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();
    let dialer = MockDialer::new(url, acceptor.clone());

    let handle = alice
        .dial(BackoffConfig::default(), Arc::new(dialer))
        .unwrap();

    tokio::time::timeout(Duration::from_secs(5), handle.established())
        .await
        .expect("established timed out")
        .expect("established failed");

    // Stop both repos — should not panic
    tokio::time::timeout(Duration::from_secs(5), alice.stop())
        .await
        .expect("alice.stop() timed out");

    tokio::time::timeout(Duration::from_secs(5), bob.stop())
        .await
        .expect("bob.stop() timed out");
}

#[tokio::test]
async fn dial_on_stopped_repo_returns_error() {
    init_logging();
    let alice = Repo::build_tokio()
        .with_peer_id(PeerId::from("alice"))
        .load()
        .await;

    let bob = Repo::build_tokio()
        .with_peer_id(PeerId::from("bob"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = bob.make_acceptor(url.clone()).unwrap();

    alice.stop().await;

    let dialer = MockDialer::new(url, acceptor);
    let result = alice.dial(BackoffConfig::default(), Arc::new(dialer));
    assert!(result.is_err(), "dial on stopped repo should return Err");

    bob.stop().await;
}

// =============================================================================
// Multi-peer sync via server relay
// =============================================================================

#[tokio::test]
async fn multi_peer_sync_via_server() {
    init_logging();
    let server = Repo::build_tokio()
        .with_peer_id(PeerId::from("server"))
        .load()
        .await;

    let client_a = Repo::build_tokio()
        .with_peer_id(PeerId::from("client-a"))
        .load()
        .await;

    let client_b = Repo::build_tokio()
        .with_peer_id(PeerId::from("client-b"))
        .load()
        .await;

    let url = Url::parse("ws://localhost:8080").unwrap();
    let acceptor = server.make_acceptor(url.clone()).unwrap();

    // Both clients dial the server
    let dialer_a = MockDialer::new(url.clone(), acceptor.clone());
    let handle_a = client_a
        .dial(BackoffConfig::default(), Arc::new(dialer_a))
        .unwrap();

    let dialer_b = MockDialer::new(url, acceptor);
    let handle_b = client_b
        .dial(BackoffConfig::default(), Arc::new(dialer_b))
        .unwrap();

    // Wait for both to connect
    tokio::time::timeout(Duration::from_secs(5), handle_a.established())
        .await
        .expect("client_a established timed out")
        .expect("client_a established failed");

    tokio::time::timeout(Duration::from_secs(5), handle_b.established())
        .await
        .expect("client_b established timed out")
        .expect("client_b established failed");

    // Client A creates a document
    let doc_a = client_a.create(Automerge::new()).await.unwrap();
    doc_a.with_document(|am| {
        use automerge::{AutomergeError, ROOT};
        am.transact::<_, _, AutomergeError>(|tx| {
            use automerge::transaction::Transactable;
            tx.put(ROOT, "author", "client-a")?;
            Ok(())
        })
        .unwrap();
    });

    // Client B should eventually find it (via server relay)
    let _b_finds_doc = tokio::time::timeout(Duration::from_secs(10), async {
        loop {
            if let Some(doc) = client_b.find(doc_a.document_id().clone()).await.unwrap() {
                return doc;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("client_b never found client_a's document");

    // Finding the document proves it was relayed through the server.
    // Content sync timing is tested in dial_and_accept_sync_documents.

    handle_a.close();
    handle_b.close();
    server.stop().await;
    client_a.stop().await;
    client_b.stop().await;
}