distributed-topic-tracker 0.3.2

automagically find peers interested in a topic + iroh-gossip integration
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
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
use std::time::Duration;

/// Timeout settings for gossip operations.
#[derive(Debug, Clone)]
pub struct TimeoutConfig {
    join_peer_timeout: Duration,
    broadcast_timeout: Duration,
    broadcast_neighbors_timeout: Duration,
}

impl TimeoutConfig {
    /// Create a new `TimeoutConfigBuilder` with default values.
    pub fn builder() -> TimeoutConfigBuilder {
        TimeoutConfigBuilder {
            timeouts: TimeoutConfig::default(),
        }
    }

    /// How long to wait when joining a peer.
    ///
    /// Default: 5s.
    pub fn join_peer_timeout(&self) -> Duration {
        self.join_peer_timeout
    }

    /// How long to wait when broadcasting messages.
    ///
    /// Default: 5s.
    pub fn broadcast_timeout(&self) -> Duration {
        self.broadcast_timeout
    }

    /// How long to wait when broadcasting to neighbors.
    ///
    /// Default: 5s.
    pub fn broadcast_neighbors_timeout(&self) -> Duration {
        self.broadcast_neighbors_timeout
    }
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            join_peer_timeout: Duration::from_secs(5),
            broadcast_timeout: Duration::from_secs(5),
            broadcast_neighbors_timeout: Duration::from_secs(5),
        }
    }
}

/// Builder for `TimeoutConfig`.
#[derive(Debug)]
pub struct TimeoutConfigBuilder {
    timeouts: TimeoutConfig,
}

impl TimeoutConfigBuilder {
    /// How long to wait when joining a peer.
    ///
    /// Default: 5s.
    pub fn join_peer_timeout(mut self, timeout: Duration) -> Self {
        self.timeouts.join_peer_timeout = timeout;
        self
    }

    /// How long to wait when broadcasting messages.
    ///
    /// Default: 5s.
    pub fn broadcast_timeout(mut self, timeout: Duration) -> Self {
        self.timeouts.broadcast_timeout = timeout;
        self
    }

    /// How long to wait when broadcasting to neighbors.
    ///
    /// Default: 5s.
    pub fn broadcast_neighbors_timeout(mut self, timeout: Duration) -> Self {
        self.timeouts.broadcast_neighbors_timeout = timeout;
        self
    }

    /// Build the `TimeoutConfig`.
    pub fn build(self) -> TimeoutConfig {
        self.timeouts
    }
}

/// DHT operation settings including retry logic and timeouts.
#[derive(Debug, Clone)]
pub struct DhtConfig {
    retries: usize,
    base_retry_interval: Duration,
    max_retry_jitter: Duration,
    put_timeout: Duration,
    get_timeout: Duration,
}

/// Builder for `DhtConfig`.
#[derive(Debug, Clone)]
pub struct DhtConfigBuilder {
    config: DhtConfig,
}

impl DhtConfigBuilder {
    /// Number of retries after the initial attempt.
    ///
    /// Total attempts = 1 + retries.
    ///
    /// Default: 3.
    pub fn retries(mut self, retries: usize) -> Self {
        self.config.retries = retries;
        self
    }

    /// Base delay between retries. No-op if `interval` is `Duration::ZERO`.
    ///
    /// If `base_retry_interval` is called only once with `Duration::ZERO`, default value prevails.
    /// If `base_retry_interval` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 5s.
    pub fn base_retry_interval(mut self, interval: Duration) -> Self {
        if interval > Duration::ZERO {
            self.config.base_retry_interval = interval;
        }
        self
    }

    /// Max random jitter added to retry interval.
    ///
    /// Default: 10s.
    pub fn max_retry_jitter(mut self, jitter: Duration) -> Self {
        self.config.max_retry_jitter = jitter;
        self
    }

    /// Timeout for DHT put operations. No-op if `timeout` is `Duration::ZERO`.
    ///
    /// If `put_timeout` is called only once with `Duration::ZERO`, default value prevails.
    /// If `put_timeout` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 10s.
    pub fn put_timeout(mut self, timeout: Duration) -> Self {
        if timeout > Duration::ZERO {
            self.config.put_timeout = timeout;
        }
        self
    }

    /// Timeout for DHT get operations. No-op if `timeout` is `Duration::ZERO`.
    ///
    /// If `get_timeout` is called only once with `Duration::ZERO`, default value prevails.
    /// If `get_timeout` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 10s.
    pub fn get_timeout(mut self, timeout: Duration) -> Self {
        if timeout > Duration::ZERO {
            self.config.get_timeout = timeout;
        }
        self
    }

    /// Build the `DhtConfig`.
    pub fn build(self) -> DhtConfig {
        self.config
    }
}

impl DhtConfig {
    /// Create a new `DhtConfigBuilder` with default values.
    pub fn builder() -> DhtConfigBuilder {
        DhtConfigBuilder {
            config: DhtConfig::default(),
        }
    }

    /// Number of retries after the initial attempt.
    ///
    /// Total attempts = 1 + retries.
    ///
    /// Default: 3.
    pub fn retries(&self) -> usize {
        self.retries
    }

    /// Base delay between retries.
    ///
    /// Default: 5s.
    pub fn base_retry_interval(&self) -> Duration {
        self.base_retry_interval
    }

    /// Max random jitter added to retry interval.
    ///
    /// Default: 10s.
    pub fn max_retry_jitter(&self) -> Duration {
        self.max_retry_jitter
    }

    /// Timeout for DHT put operations.
    ///
    /// Default: 10s.
    pub fn put_timeout(&self) -> Duration {
        self.put_timeout
    }

    /// Timeout for DHT get operations.
    ///
    /// Default: 10s.
    pub fn get_timeout(&self) -> Duration {
        self.get_timeout
    }
}

impl Default for DhtConfig {
    fn default() -> Self {
        Self {
            retries: 3,
            base_retry_interval: Duration::from_secs(5),
            max_retry_jitter: Duration::from_secs(10),
            put_timeout: Duration::from_secs(10),
            get_timeout: Duration::from_secs(10),
        }
    }
}

/// Bubble merge strategy config for detecting and healing split-brain scenarios by joining small clusters with peers advertised in DHT that are not our neighbors.
#[derive(Debug, Clone)]
pub enum BubbleMergeConfig {
    Enabled(BubbleMergeConfigInner),
    Disabled,
}

#[derive(Debug, Clone)]
pub struct BubbleMergeConfigInner {
    initial_interval: Duration,
    base_interval: Duration,
    max_jitter: Duration,
    min_neighbors: usize,
    fail_topic_creation_on_merge_startup_failure: bool,
    max_join_peers: usize,
}

#[derive(Debug, Clone)]
pub struct BubbleMergeConfigBuilder {
    config: BubbleMergeConfigInner,
}

impl Default for BubbleMergeConfig {
    fn default() -> Self {
        Self::Enabled(BubbleMergeConfigInner::default())
    }
}

impl Default for BubbleMergeConfigInner {
    fn default() -> Self {
        Self {
            initial_interval: Duration::from_secs(30),
            base_interval: Duration::from_secs(60),
            max_jitter: Duration::from_secs(120),
            min_neighbors: 4,
            fail_topic_creation_on_merge_startup_failure: true,
            max_join_peers: 2,
        }
    }
}

impl BubbleMergeConfig {
    /// Create a new `BubbleMergeConfigBuilder` with default values.
    pub fn builder() -> BubbleMergeConfigBuilder {
        BubbleMergeConfigBuilder {
            config: BubbleMergeConfigInner::default(),
        }
    }
}

impl BubbleMergeConfigInner {
    /// Initial delay before starting bubble merge attempts.
    ///
    /// Default: 30s.
    pub fn initial_interval(&self) -> Duration {
        self.initial_interval
    }

    /// Base interval for bubble merge attempts.
    ///
    /// `base_interval` > Duration::ZERO
    ///
    /// Default: 60s.
    pub fn base_interval(&self) -> Duration {
        self.base_interval
    }

    /// Max random jitter added to bubble merge interval.
    ///
    /// Default: 120s.
    pub fn max_jitter(&self) -> Duration {
        self.max_jitter
    }

    /// Minimum number of neighbors required to attempt a bubble merge.
    ///
    /// Default: 4.
    pub fn min_neighbors(&self) -> usize {
        self.min_neighbors
    }

    /// Whether to fail topic creation
    ///
    /// If a bubble merge startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_merge_startup_failure(&self) -> bool {
        self.fail_topic_creation_on_merge_startup_failure
    }

    /// Max number of peers to join during a bubble merge attempt.
    ///
    /// Default: 2.
    pub fn max_join_peers(&self) -> usize {
        self.max_join_peers
    }
}

impl BubbleMergeConfigBuilder {
    /// Initial delay before starting bubble merge attempts.
    ///
    /// Default: 30s.
    pub fn initial_interval(mut self, interval: Duration) -> Self {
        self.config.initial_interval = interval;
        self
    }

    /// Base interval for bubble merge attempts. No-op if `interval` is `Duration::ZERO`.
    ///
    /// If `base_interval` is called only once with `Duration::ZERO`, default value prevails.
    /// If `base_interval` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 60s.
    pub fn base_interval(mut self, interval: Duration) -> Self {
        if interval > Duration::ZERO {
            self.config.base_interval = interval;
        }
        self
    }

    /// Max random jitter added to bubble merge interval.
    ///
    /// Default: 120s
    pub fn max_jitter(mut self, jitter: Duration) -> Self {
        self.config.max_jitter = jitter;
        self
    }

    /// Minimum number of neighbors required to attempt a bubble merge.
    ///
    /// Default: 4.
    pub fn min_neighbors(mut self, min_neighbors: usize) -> Self {
        self.config.min_neighbors = min_neighbors;
        self
    }

    /// Whether to fail topic creation
    ///
    /// If a bubble merge startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_merge_startup_failure(mut self, fail: bool) -> Self {
        self.config.fail_topic_creation_on_merge_startup_failure = fail;
        self
    }

    /// Max number of peers to join during a bubble merge attempt. No-op if `max_join_peers` is zero.
    ///
    /// If `max_join_peers` is called only once with zero, default value prevails.
    /// If `max_join_peers` is first called with a > zero, and then again with zero, the first set value is kept.
    ///
    /// Default: 2.
    pub fn max_join_peers(mut self, max_join_peers: usize) -> Self {
        if max_join_peers > 0 {
            self.config.max_join_peers = max_join_peers;
        }
        self
    }

    /// Build the `BubbleMergeConfig`.
    pub fn build(self) -> BubbleMergeConfig {
        BubbleMergeConfig::Enabled(self.config)
    }
}

/// Message overlap merge strategy config for detecting and healing split-brain scenarios by checking for overlapping message hashes with other cluster peers.
#[derive(Debug, Clone)]
pub enum MessageOverlapMergeConfig {
    Enabled(MessageOverlapMergeConfigInner),
    Disabled,
}

#[derive(Debug, Clone)]
pub struct MessageOverlapMergeConfigInner {
    initial_interval: Duration,
    base_interval: Duration,
    max_jitter: Duration,
    fail_topic_creation_on_merge_startup_failure: bool,
    max_join_peers: usize,
}

#[derive(Debug, Clone)]
pub struct MessageOverlapMergeConfigBuilder {
    config: MessageOverlapMergeConfigInner,
}

impl Default for MessageOverlapMergeConfigInner {
    fn default() -> Self {
        Self {
            initial_interval: Duration::from_secs(30),
            base_interval: Duration::from_secs(60),
            max_jitter: Duration::from_secs(120),
            fail_topic_creation_on_merge_startup_failure: true,
            max_join_peers: 2,
        }
    }
}

impl Default for MessageOverlapMergeConfig {
    fn default() -> Self {
        Self::Enabled(MessageOverlapMergeConfigInner::default())
    }
}

impl MessageOverlapMergeConfig {
    /// Create a new `MessageOverlapMergeConfigBuilder` with default values.
    pub fn builder() -> MessageOverlapMergeConfigBuilder {
        MessageOverlapMergeConfigBuilder {
            config: MessageOverlapMergeConfigInner::default(),
        }
    }
}

impl MessageOverlapMergeConfigInner {
    /// Initial delay before starting message overlap merge attempts.
    ///
    /// Default: 30s.
    pub fn initial_interval(&self) -> Duration {
        self.initial_interval
    }

    /// Base interval for message overlap merge attempts.
    ///
    /// `base_interval` > Duration::ZERO
    ///
    /// Default: 60s.
    pub fn base_interval(&self) -> Duration {
        self.base_interval
    }

    /// Max random jitter added to message overlap merge interval.
    ///
    /// Default: 120s.
    pub fn max_jitter(&self) -> Duration {
        self.max_jitter
    }

    /// Whether to fail topic creation
    ///
    /// If a message overlap merge startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_merge_startup_failure(&self) -> bool {
        self.fail_topic_creation_on_merge_startup_failure
    }

    /// Max number of peers to join during a message overlap merge attempt.
    ///
    /// Default: 2.
    pub fn max_join_peers(&self) -> usize {
        self.max_join_peers
    }
}

impl MessageOverlapMergeConfigBuilder {
    /// Initial delay before starting message overlap merge attempts.
    ///
    /// Default: 30s.
    pub fn initial_interval(mut self, interval: Duration) -> Self {
        self.config.initial_interval = interval;
        self
    }

    /// Base interval for message overlap merge attempts. No-op if `interval` is `Duration::ZERO`.
    ///
    /// If `base_interval` is called only once with `Duration::ZERO`, default value prevails.
    /// If `base_interval` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 60s.
    pub fn base_interval(mut self, interval: Duration) -> Self {
        if interval > Duration::ZERO {
            self.config.base_interval = interval;
        }
        self
    }

    /// Max random jitter added to message overlap merge interval.
    ///
    /// Default: 120s. Minimum is 0s.
    pub fn max_jitter(mut self, jitter: Duration) -> Self {
        self.config.max_jitter = jitter;
        self
    }

    /// Whether to fail topic creation
    ///
    /// If a message overlap merge startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_merge_startup_failure(mut self, fail: bool) -> Self {
        self.config.fail_topic_creation_on_merge_startup_failure = fail;
        self
    }

    /// Max number of peers to join during a message overlap merge attempt. No-op if `max_join_peers` is zero.
    ///
    /// If `max_join_peers` is called only once with zero, default value prevails.
    /// If `max_join_peers` is first called with a > zero, and then again with zero, the first set value is kept.
    ///
    /// Default: 2.
    pub fn max_join_peers(mut self, max_join_peers: usize) -> Self {
        if max_join_peers > 0 {
            self.config.max_join_peers = max_join_peers;
        }
        self
    }

    /// Build the `MessageOverlapMergeConfig`.
    pub fn build(self) -> MessageOverlapMergeConfig {
        MessageOverlapMergeConfig::Enabled(self.config)
    }
}

/// Publisher strategy config for publishing bootstrap records to DHT for peer discovery.
#[derive(Debug, Clone)]
pub enum PublisherConfig {
    Enabled(PublisherConfigInner),
    Disabled,
}

#[derive(Debug, Clone)]
pub struct PublisherConfigInner {
    initial_delay: Duration,
    base_interval: Duration,
    max_jitter: Duration,
    fail_topic_creation_on_publishing_startup_failure: bool,
}

#[derive(Debug, Clone)]
pub struct PublisherConfigBuilder {
    config: PublisherConfigInner,
}

impl Default for PublisherConfigInner {
    fn default() -> Self {
        Self {
            initial_delay: Duration::from_secs(10),
            base_interval: Duration::from_secs(10),
            max_jitter: Duration::from_secs(50),
            fail_topic_creation_on_publishing_startup_failure: true,
        }
    }
}

impl Default for PublisherConfig {
    fn default() -> Self {
        Self::Enabled(PublisherConfigInner::default())
    }
}

impl PublisherConfig {
    /// Create a new `PublisherConfigBuilder` with default values.
    pub fn builder() -> PublisherConfigBuilder {
        PublisherConfigBuilder {
            config: PublisherConfigInner::default(),
        }
    }
}

impl PublisherConfigInner {
    /// Initial delay before starting publisher.
    ///
    /// Default: 10s.
    pub fn initial_delay(&self) -> Duration {
        self.initial_delay
    }

    /// Base interval for publisher attempts.
    ///
    /// `base_interval` > Duration::ZERO
    ///
    /// Default: 10s.
    pub fn base_interval(&self) -> Duration {
        self.base_interval
    }

    /// Max random jitter added to publisher interval.
    ///
    /// Default: 50s.
    pub fn max_jitter(&self) -> Duration {
        self.max_jitter
    }

    /// Whether to fail topic creation
    ///
    /// If a publisher startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_publishing_startup_failure(&self) -> bool {
        self.fail_topic_creation_on_publishing_startup_failure
    }
}

impl PublisherConfigBuilder {
    /// Initial delay before starting publisher.
    ///
    /// Default: 10s.
    pub fn initial_delay(mut self, delay: Duration) -> Self {
        self.config.initial_delay = delay;
        self
    }

    /// Base interval for publisher attempts. No-op if `interval` is `Duration::ZERO`.
    ///
    /// If `base_interval` is called only once with `Duration::ZERO`, default value prevails.
    /// If `base_interval` is first called with a > `Duration::ZERO`, and then again with `Duration::ZERO`, the first set value is kept.
    ///
    /// Default: 10s.
    pub fn base_interval(mut self, interval: Duration) -> Self {
        if interval > Duration::ZERO {
            self.config.base_interval = interval;
        }
        self
    }

    /// Max random jitter added to publisher interval.
    ///
    /// Default: 50s.
    pub fn max_jitter(mut self, jitter: Duration) -> Self {
        self.config.max_jitter = jitter;
        self
    }

    /// Whether to fail topic creation
    ///
    /// If a publisher startup check fails (ret Err()) or just log and run topic without.
    ///
    /// Default: true.
    pub fn fail_topic_creation_on_publishing_startup_failure(mut self, fail: bool) -> Self {
        self.config
            .fail_topic_creation_on_publishing_startup_failure = fail;
        self
    }

    /// Build the `PublisherConfig`.
    pub fn build(self) -> PublisherConfig {
        PublisherConfig::Enabled(self.config)
    }
}

/// Merge strategies run periodically in the background and attempt to merge split clusters by joining peers in DHT records
/// and message hashes for bubble detection and merging, and by joining peers in DHT records with overlapping message hashes
/// for message overlap detection and merging.
#[derive(Debug, Clone, Default)]
pub struct MergeConfig {
    bubble_merge: BubbleMergeConfig,
    message_overlap_merge: MessageOverlapMergeConfig,
}

/// Builder for `MergeConfig`.
#[derive(Debug, Clone)]
pub struct MergeConfigBuilder {
    config: MergeConfig,
}

impl MergeConfig {
    /// Create a new `MergeConfigBuilder` with default values.
    pub fn builder() -> MergeConfigBuilder {
        MergeConfigBuilder {
            config: MergeConfig::default(),
        }
    }

    /// Bubble merge strategy config.
    ///
    /// Default: BubbleMergeConfig::default()
    pub fn bubble_merge(&self) -> &BubbleMergeConfig {
        &self.bubble_merge
    }

    /// Message overlap merge strategy config.
    ///
    /// Default: MessageOverlapMergeConfig::default()
    pub fn message_overlap_merge(&self) -> &MessageOverlapMergeConfig {
        &self.message_overlap_merge
    }
}

impl MergeConfigBuilder {
    /// Bubble merge strategy config.
    ///
    /// Default: BubbleMergeConfig::default()
    pub fn bubble_merge(mut self, bubble_merge: BubbleMergeConfig) -> Self {
        self.config.bubble_merge = bubble_merge;
        self
    }

    /// Message overlap merge strategy config.
    ///
    /// Default: MessageOverlapMergeConfig::default()
    pub fn message_overlap_merge(
        mut self,
        message_overlap_merge: MessageOverlapMergeConfig,
    ) -> Self {
        self.config.message_overlap_merge = message_overlap_merge;
        self
    }

    /// Build the `MergeConfig`.
    pub fn build(self) -> MergeConfig {
        self.config
    }
}

/// Bootstrap process settings for peer discovery.
#[derive(Debug, Clone)]
pub struct BootstrapConfig {
    max_bootstrap_records: usize,
    no_peers_retry_interval: Duration,
    per_peer_join_settle_time: Duration,
    join_confirmation_wait_time: Duration,
    discovery_poll_interval: Duration,
    publish_record_on_startup: bool,
    check_older_records_first_on_startup: bool,
}

impl Default for BootstrapConfig {
    fn default() -> Self {
        Self {
            max_bootstrap_records: 5,
            no_peers_retry_interval: Duration::from_millis(1500),
            per_peer_join_settle_time: Duration::from_millis(100),
            join_confirmation_wait_time: Duration::from_millis(500),
            discovery_poll_interval: Duration::from_millis(2000),
            publish_record_on_startup: true,
            check_older_records_first_on_startup: false,
        }
    }
}

/// Builder for `BootstrapConfig`.
#[derive(Debug)]
pub struct BootstrapConfigBuilder {
    config: BootstrapConfig,
}

impl BootstrapConfigBuilder {
    /// Max bootstrap records per topic per minute slot.
    ///
    /// If zero, we don't publish (PublisherConfig will be set to Disabled).
    ///
    /// Default: 5.
    pub fn max_bootstrap_records(mut self, max_records: usize) -> Self {
        self.config.max_bootstrap_records = max_records;
        self
    }

    /// How long to wait when no peers are found before retrying.
    ///
    /// Default: 1500ms.
    pub fn no_peers_retry_interval(mut self, interval: Duration) -> Self {
        self.config.no_peers_retry_interval = interval;
        self
    }

    /// How long to wait after joining a peer before attempting to join another.
    ///
    /// Default: 100ms.
    pub fn per_peer_join_settle_time(mut self, interval: Duration) -> Self {
        self.config.per_peer_join_settle_time = interval;
        self
    }

    /// How long to wait after joining a peer before checking if joined successfully.
    ///
    /// Default: 500ms.
    pub fn join_confirmation_wait_time(mut self, interval: Duration) -> Self {
        self.config.join_confirmation_wait_time = interval;
        self
    }

    /// How long to wait between DHT discovery attempts.
    ///
    /// Default: 2000ms.
    pub fn discovery_poll_interval(mut self, interval: Duration) -> Self {
        self.config.discovery_poll_interval = interval;
        self
    }

    /// Whether to publish a bootstrap record unconditionally on startup before dht get.
    ///
    /// Default: true.
    pub fn publish_record_on_startup(mut self, publish: bool) -> Self {
        self.config.publish_record_on_startup = publish;
        self
    }

    /// Whether to check `unix_minute` and `unix_minute-1` or `unix_minute-1` and `unix_minute-2` on startup.
    ///
    /// If this is enabled, we first fetch `unix_minute-1` and `unix_minute-2`.
    ///  
    /// If joining longer running, existing topics is priority, set to true.
    /// If minimizing bootstrap time for cluster cold starts (2+ nodes starting roughly
    /// at the same time into a topic without peers), set to false.
    ///
    /// Default: false.
    pub fn check_older_records_first_on_startup(mut self, check: bool) -> Self {
        self.config.check_older_records_first_on_startup = check;
        self
    }

    /// Build the `BootstrapConfig`.
    pub fn build(self) -> BootstrapConfig {
        self.config
    }
}

impl BootstrapConfig {
    /// Create a new `BootstrapConfigBuilder` with default values.
    pub fn builder() -> BootstrapConfigBuilder {
        BootstrapConfigBuilder {
            config: BootstrapConfig::default(),
        }
    }

    /// Max bootstrap records per topic per minute slot.
    ///
    /// If zero, we don't publish (PublisherConfig will be set to Disabled).
    ///
    /// Default: 5.
    pub fn max_bootstrap_records(&self) -> usize {
        self.max_bootstrap_records
    }

    /// How long to wait when no peers are found before retrying.
    ///
    /// Default: 1500ms.
    pub fn no_peers_retry_interval(&self) -> Duration {
        self.no_peers_retry_interval
    }

    /// How long to wait after joining a peer before attempting to join another.
    ///
    /// Default: 100ms.
    pub fn per_peer_join_settle_time(&self) -> Duration {
        self.per_peer_join_settle_time
    }

    /// How long to wait after joining a peer before checking if joined successfully.
    ///
    /// Default: 500ms.
    pub fn join_confirmation_wait_time(&self) -> Duration {
        self.join_confirmation_wait_time
    }

    /// How long to wait between DHT discovery attempts.
    ///
    /// Default: 2000ms.
    pub fn discovery_poll_interval(&self) -> Duration {
        self.discovery_poll_interval
    }

    /// Whether to publish a bootstrap record unconditionally on startup before dht get.
    ///
    /// Default: true.
    pub fn publish_record_on_startup(&self) -> bool {
        self.publish_record_on_startup
    }

    /// Whether to check `unix_minute` and `unix_minute-1` or `unix_minute-1` and `unix_minute-2` on startup.
    ///
    /// If this is enabled, we first fetch `unix_minute-1` and `unix_minute-2`.  
    ///  
    /// If joining longer running, existing topics is priority, set to true.
    /// If minimizing bootstrap time for cluster cold starts (2+ nodes starting roughly
    /// at the same time into a topic without peers), set to false.
    ///
    /// Default: false.
    pub fn check_older_records_first_on_startup(&self) -> bool {
        self.check_older_records_first_on_startup
    }
}

/// Top-level configuration combining all settings.
#[derive(Debug, Clone)]
pub struct Config {
    bootstrap_config: BootstrapConfig,
    publisher_config: PublisherConfig,
    dht_config: DhtConfig,

    merge_config: MergeConfig,

    max_join_peer_count: usize,
    timeouts: TimeoutConfig,
}

impl Config {
    /// Create a new `ConfigBuilder` with default values.
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder {
            config: Config::default(),
        }
    }

    /// Publisher strategy config.
    ///
    /// Default: PublisherConfig::default().
    pub fn publisher_config(&self) -> &PublisherConfig {
        &self.publisher_config
    }

    /// DHT operation settings.
    ///
    /// Default: DhtConfig::default().
    pub fn dht_config(&self) -> &DhtConfig {
        &self.dht_config
    }

    /// Bootstrap strategy settings.
    ///
    /// Default: BootstrapConfig::default().
    pub fn bootstrap_config(&self) -> &BootstrapConfig {
        &self.bootstrap_config
    }

    /// Max peers to join simultaneously.
    ///
    /// Minimum is 1.
    ///
    /// Default: 4.
    pub fn max_join_peer_count(&self) -> usize {
        self.max_join_peer_count
    }

    /// Timeout settings.
    ///
    /// Default: TimeoutConfig::default().
    pub fn timeouts(&self) -> &TimeoutConfig {
        &self.timeouts
    }

    /// Merge strategy settings.
    ///
    /// Default: bubble and overlap merges enabled.
    pub fn merge_config(&self) -> &MergeConfig {
        &self.merge_config
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            merge_config: MergeConfig::default(),
            bootstrap_config: BootstrapConfig::default(),
            publisher_config: PublisherConfig::default(),
            dht_config: DhtConfig::default(),
            max_join_peer_count: 4,
            timeouts: TimeoutConfig::default(),
        }
    }
}

/// Builder for `Config`.
#[derive(Debug)]
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    /// Merge strategy settings.
    ///
    /// Default: MergeConfig::default().
    pub fn merge_config(mut self, merge_config: MergeConfig) -> Self {
        self.config.merge_config = merge_config;
        self
    }

    /// Publisher strategy config.
    ///
    /// Default: PublisherConfig::default().
    pub fn publisher_config(mut self, publisher_config: PublisherConfig) -> Self {
        self.config.publisher_config = publisher_config;
        self
    }

    /// DHT operation settings.
    ///
    /// Default: DhtConfig::default().
    pub fn dht_config(mut self, dht_config: DhtConfig) -> Self {
        self.config.dht_config = dht_config;
        self
    }

    /// Bootstrap strategy settings.
    ///
    /// Default: BootstrapConfig::default().
    pub fn bootstrap_config(mut self, bootstrap_config: BootstrapConfig) -> Self {
        self.config.bootstrap_config = bootstrap_config;
        self
    }

    /// Max peers to join simultaneously. No-op if `max_join_peer_count` is zero.
    ///
    /// If `max_join_peer_count` is called only once with zero, default value prevails.
    /// If `max_join_peer_count` is first called with a non-zero value, and then again with zero, the first set value is kept.
    ///
    /// Default: 4.
    pub fn max_join_peer_count(mut self, max_peers: usize) -> Self {
        if max_peers > 0 {
            self.config.max_join_peer_count = max_peers;
        }
        self
    }

    /// Timeout settings.
    ///
    /// Default: TimeoutConfig::default().
    pub fn timeouts(mut self, timeouts: TimeoutConfig) -> Self {
        self.config.timeouts = timeouts;
        self
    }

    /// Build the `Config`.
    ///
    /// If `max_bootstrap_records` is zero, `PublisherConfig` is set to `Disabled`.
    pub fn build(self) -> Config {
        let mut config = self.config;
        if config.bootstrap_config.max_bootstrap_records == 0
            && matches!(config.publisher_config, PublisherConfig::Enabled(_))
        {
            // if max_bootstrap_records is zero, we don't publish, so disable publisher to avoid confusion
            tracing::warn!(
                "Publisher is enabled via PublisherConfig::Enabled(_) but BootstrapConfig.max_bootstrap_records is set to 0 (we effectively never publish). Overriding PublisherConfig to PublisherConfig::Disabled."
            );
            config.publisher_config = PublisherConfig::Disabled;
        }

        config
    }
}