rings-node 1.0.0-pre.5

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
//! Supervisor shell tests over a scripted port under tokio's paused clock, plus target
//! validation and evidence-record tests.
//!
//! Every timing assertion below is in paused virtual time: the runtime advances the clock only
//! when no task can make progress, so attempt instants are exact, not approximate.

use std::collections::BTreeMap;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

use rings_core::dht::Did;
use tokio::sync::futures::Notified;
use tokio::sync::oneshot::error::TryRecvError;
use tokio::sync::Notify;
use tokio::time::Instant;

use super::evidence::Admissions;
use super::evidence::ReachabilityEvidence;
use super::schedule::duration_ms;
use super::schedule::is_one_slow_delay_after;
use super::BootstrapPort;
use super::BootstrapSupervisor;
use super::BootstrapTargets;
use super::DialFailure;
use crate::error::Error;
use crate::native::config::BootstrapConfig;
use crate::prelude::StopSource;
use crate::seed::SeedPeer;
use crate::seed::SeedPeerError;
use crate::seed::ValidatedSeedPeer;
use crate::test_support::TestTask;

/// Fixed jitter seed so slow-cadence instants replay identically.
const JITTER_SEED: u64 = 7;
/// DID of the node under test; never a target.
const LOCAL: u32 = 0xFFFF;

/// Scripted dial behaviour for one attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DialScript {
    /// The handshake completes and the target becomes reachable.
    Succeed,
    /// The handshake fails.
    Fail,
    /// The core reports a handshake to the target already in flight.
    InFlight,
    /// The handshake never returns; only cancellation ends it.
    Hang,
    /// The handshake completes after the given virtual milliseconds.
    SucceedAfter(u64),
}

/// One recorded port call.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CallKind {
    /// A reachability assessment.
    Probe,
    /// A dial.
    Dial,
}

/// One recorded port call with its virtual instant.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Call {
    at_ms: u64,
    target: Did,
    kind: CallKind,
}

/// Scripted state: reachability per target, queued dial scripts, the call log, and the count
/// of dials currently hanging.
#[derive(Default)]
struct PortState {
    reachable: BTreeMap<Did, bool>,
    dials: BTreeMap<Did, VecDeque<DialScript>>,
    log: Vec<Call>,
    hanging: usize,
}

/// A [`BootstrapPort`] driven entirely by the test.
struct ScriptedPort {
    origin: Instant,
    state: Mutex<PortState>,
    hang_released: Notify,
}

/// Counts a hanging dial while its future is alive and announces its cancellation, so the
/// shutdown test waits for the event rather than for a scheduler pass.
struct HangGuard<'port> {
    port: &'port ScriptedPort,
}

impl<'port> HangGuard<'port> {
    /// Register one hanging dial.
    fn new(port: &'port ScriptedPort) -> Self {
        port.state().hanging += 1;
        Self { port }
    }
}

impl Drop for HangGuard<'_> {
    /// Unregister the hanging dial and announce it, also when its future is dropped.
    fn drop(&mut self) {
        self.port.state().hanging -= 1;
        self.port.hang_released.notify_one();
    }
}

impl ScriptedPort {
    /// A port whose log clock starts now.
    fn new() -> Arc<Self> {
        Arc::new(Self {
            origin: Instant::now(),
            state: Mutex::new(PortState::default()),
            hang_released: Notify::new(),
        })
    }

    /// Virtual milliseconds since the port was created.
    fn now_ms(&self) -> u64 {
        duration_ms(self.origin.elapsed())
    }

    /// Lock the scripted state.
    fn state(&self) -> std::sync::MutexGuard<'_, PortState> {
        self.state.lock().unwrap()
    }

    /// Set whether `target` currently answers as reachable.
    fn set_reachable(&self, target: Did, reachable: bool) {
        self.state().reachable.insert(target, reachable);
    }

    /// Queue dial scripts for `target`; an exhausted queue fails.
    fn script_dials(&self, target: Did, scripts: impl IntoIterator<Item = DialScript>) {
        self.state()
            .dials
            .entry(target)
            .or_default()
            .extend(scripts);
    }

    /// Instants of every call of `kind` on `target`, in order.
    fn call_times(&self, target: Did, kind: CallKind) -> Vec<u64> {
        self.state()
            .log
            .iter()
            .filter(|call| call.target == target && call.kind == kind)
            .map(|call| call.at_ms)
            .collect()
    }

    /// Dials whose future is currently alive and hanging.
    fn hanging(&self) -> usize {
        self.state().hanging
    }

    /// Resolves once a hanging dial's future is dropped.
    fn released(&self) -> Notified<'_> {
        self.hang_released.notified()
    }
}

#[async_trait::async_trait]
impl BootstrapPort for ScriptedPort {
    /// Answer from the scripted reachability table (unknown targets are unreachable) and log it.
    async fn reachable(&self, target: Did) -> bool {
        let at_ms = self.now_ms();
        let mut state = self.state();
        let reachable = state.reachable.get(&target).copied().unwrap_or(false);
        state.log.push(Call {
            at_ms,
            target,
            kind: CallKind::Probe,
        });
        reachable
    }

    /// Follow the next queued script for the target (an exhausted queue fails) and log it.
    async fn dial(&self, target: &ValidatedSeedPeer) -> std::result::Result<(), DialFailure> {
        let at_ms = self.now_ms();
        let script = {
            let mut state = self.state();
            let script = state
                .dials
                .get_mut(&target.did())
                .and_then(VecDeque::pop_front)
                .unwrap_or(DialScript::Fail);
            state.log.push(Call {
                at_ms,
                target: target.did(),
                kind: CallKind::Dial,
            });
            script
        };
        match script {
            DialScript::Succeed => {
                self.set_reachable(target.did(), true);
                Ok(())
            }
            DialScript::Fail => Err(DialFailure::Failed(Error::AdmissionTimedOut {
                peer: target.did(),
            })),
            DialScript::InFlight => Err(DialFailure::InFlight),
            DialScript::Hang => {
                let _guard = HangGuard::new(self);
                std::future::pending().await
            }
            DialScript::SucceedAfter(delay_ms) => {
                tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                self.set_reachable(target.did(), true);
                Ok(())
            }
        }
    }
}

/// A seed entry for the numbered peer.
fn peer(n: u32) -> SeedPeer {
    SeedPeer {
        did: Did::from(n).to_string(),
        url: format!("https://peer{n}.example.com:50001/"),
        api_token: None,
    }
}

/// Validated targets for `peers`, for a local node that is none of them.
fn targets(peers: Vec<SeedPeer>) -> BootstrapTargets {
    BootstrapTargets::from_config(BootstrapConfig { peers }, Did::from(LOCAL))
        .expect("test targets must validate")
}

/// The error `peers` are rejected with.
fn rejection(peers: Vec<SeedPeer>) -> Error {
    match BootstrapTargets::from_config(BootstrapConfig { peers }, Did::from(LOCAL)) {
        Err(error) => error,
        Ok(targets) => panic!("peers must be rejected, got {targets:?}"),
    }
}

/// A running supervisor over a scripted port.
struct Running {
    port: Arc<ScriptedPort>,
    evidence: Arc<ReachabilityEvidence>,
    stop: StopSource,
    task: TestTask<()>,
}

impl Running {
    /// Spawn a supervisor over `peers` with `port` already scripted.
    fn spawn(port: Arc<ScriptedPort>, peers: Vec<SeedPeer>) -> Self {
        let evidence = Arc::new(ReachabilityEvidence::default());
        let stop = StopSource::new();
        let supervisor =
            BootstrapSupervisor::new(targets(peers), port.clone(), evidence.clone(), JITTER_SEED);
        let task = TestTask::spawn(supervisor.run(stop.token()));
        Self {
            port,
            evidence,
            stop,
            task,
        }
    }

    /// Report that `target` left the local DHT and make it unreachable.
    fn lose(&self, target: Did) {
        self.port.set_reachable(target, false);
        self.evidence
            .losses()
            .observe(target)
            .expect("losses must accept a retirement");
    }

    /// Request stop and wait for the run to return.
    async fn shutdown(self) {
        self.stop.request_stop();
        tokio::time::timeout(Duration::from_secs(1), self.task)
            .await
            .expect("run must return promptly after stop")
            .expect("run task must not panic");
    }
}

/// An unreachable target from start-up is dialed at 0, 2, 4, 6, 8 s and then once per slow delay.
#[tokio::test(start_paused = true)]
async fn initial_failure_bursts_then_falls_back_to_the_slow_cadence() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(9_000)).await;
    assert_eq!(port.call_times(target, CallKind::Dial), vec![
        0, 2_000, 4_000, 6_000, 8_000
    ]);

    tokio::time::sleep(Duration::from_millis(340_000)).await;
    let dials = port.call_times(target, CallKind::Dial);
    assert_eq!(dials.len(), 6, "exactly one slow attempt follows the burst");
    assert!(is_one_slow_delay_after(8_000, dials[5]));

    tokio::time::sleep(Duration::from_millis(340_000)).await;
    let dials = port.call_times(target, CallKind::Dial);
    assert_eq!(dials.len(), 7);
    assert!(is_one_slow_delay_after(dials[5], dials[6]));
    running.shutdown().await;
}

/// A successful dial ends the burst; the target is then only probed, one slow delay later.
#[tokio::test(start_paused = true)]
async fn recovery_resets_the_burst_and_rechecks_without_dialing() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    port.script_dials(target, [
        DialScript::Fail,
        DialScript::Fail,
        DialScript::Succeed,
    ]);
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(400_000)).await;
    assert_eq!(port.call_times(target, CallKind::Dial), vec![
        0, 2_000, 4_000
    ]);
    let probes = port.call_times(target, CallKind::Probe);
    assert_eq!(
        probes.len(),
        4,
        "three failing turns plus one periodic recheck"
    );
    assert!(is_one_slow_delay_after(4_000, probes[3]));
    running.shutdown().await;
}

/// A retirement triggers an immediate probe and dial; a second loss restarts from the short delay.
#[tokio::test(start_paused = true)]
async fn a_loss_reassesses_at_once_and_a_second_loss_restarts_the_burst() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    port.set_reachable(target, true);
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(10_000)).await;
    assert!(port.call_times(target, CallKind::Dial).is_empty());
    running.lose(target);
    port.script_dials(target, [
        DialScript::Fail,
        DialScript::Fail,
        DialScript::Succeed,
    ]);
    tokio::time::sleep(Duration::from_millis(10_000)).await;
    assert_eq!(port.call_times(target, CallKind::Dial), vec![
        10_000, 12_000, 14_000
    ]);

    tokio::time::sleep(Duration::from_millis(80_000)).await;
    running.lose(target);
    port.script_dials(target, [DialScript::Fail, DialScript::Succeed]);
    tokio::time::sleep(Duration::from_millis(10_000)).await;
    assert_eq!(
        port.call_times(target, CallKind::Dial),
        vec![10_000, 12_000, 14_000, 100_000, 102_000],
        "the second loss starts a fresh burst from the short delay"
    );
    running.shutdown().await;
}

/// A loss recorded while a target waits in the slow cadence restarts its burst at once.
#[tokio::test(start_paused = true)]
async fn a_loss_wakes_a_target_sleeping_to_its_slow_deadline() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(20_000)).await;
    assert_eq!(port.call_times(target, CallKind::Dial).len(), 5);
    running.lose(target);
    tokio::time::sleep(Duration::from_millis(9_000)).await;
    assert_eq!(
        port.call_times(target, CallKind::Dial),
        vec![0, 2_000, 4_000, 6_000, 8_000, 20_000, 22_000, 24_000, 26_000, 28_000],
        "the slow wait is abandoned for a fresh burst"
    );
    running.shutdown().await;
}

/// A dial refused because the target's slot is owned by another attempt is a miss like a failed
/// one: it consumes a burst turn, so a handshake the peer keeps in flight cannot hold the target
/// in the rapid cadence.
#[tokio::test(start_paused = true)]
async fn a_refused_dial_consumes_a_burst_turn() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    port.script_dials(target, [
        DialScript::Fail,
        DialScript::InFlight,
        DialScript::InFlight,
        DialScript::InFlight,
        DialScript::InFlight,
        DialScript::InFlight,
    ]);
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(9_000)).await;
    assert_eq!(
        port.call_times(target, CallKind::Dial),
        vec![0, 2_000, 4_000, 6_000, 8_000],
        "refusals and failures share the burst"
    );
    tokio::time::sleep(Duration::from_millis(340_000)).await;
    let dials = port.call_times(target, CallKind::Dial);
    assert_eq!(dials.len(), 6);
    assert!(
        is_one_slow_delay_after(8_000, dials[5]),
        "the fifth miss enters the slow cadence"
    );
    running.shutdown().await;
}

/// A hanging dial is never dialed again while busy, and does not delay another target's burst.
#[tokio::test(start_paused = true)]
async fn targets_retry_independently_and_never_overlap() {
    let hanging = Did::from(1);
    let failing = Did::from(2);
    let port = ScriptedPort::new();
    port.script_dials(hanging, [DialScript::Hang]);
    let running = Running::spawn(port.clone(), vec![peer(1), peer(2)]);

    tokio::time::sleep(Duration::from_millis(9_000)).await;
    assert_eq!(port.call_times(hanging, CallKind::Dial), vec![0]);
    assert_eq!(port.call_times(failing, CallKind::Dial), vec![
        0, 2_000, 4_000, 6_000, 8_000
    ]);
    assert_eq!(port.hanging(), 1);
    running.shutdown().await;
}

/// Requesting stop returns the run promptly and drops the hanging dial future.
#[tokio::test(start_paused = true)]
async fn shutdown_cancels_an_in_flight_dial() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    port.script_dials(target, [DialScript::Hang]);
    let running = Running::spawn(port.clone(), vec![peer(1)]);

    tokio::time::sleep(Duration::from_millis(1_000)).await;
    assert_eq!(port.hanging(), 1);
    let released = port.released();
    running.shutdown().await;
    tokio::time::timeout(Duration::from_secs(1), released)
        .await
        .expect("dropping the run cancels its turns");
    assert_eq!(port.hanging(), 0);
}

/// A loss that races a slow dial is reassessed the instant that dial settles, not one slow
/// delay later.
#[tokio::test(start_paused = true)]
async fn a_loss_during_a_turn_is_reassessed_as_soon_as_the_turn_settles() {
    let target = Did::from(1);
    let port = ScriptedPort::new();
    port.script_dials(target, [DialScript::SucceedAfter(5_000)]);
    let running = Running::spawn(port.clone(), vec![peer(1)]);
    tokio::time::sleep(Duration::from_millis(1_000)).await;

    running.lose(target);
    tokio::time::sleep(Duration::from_millis(10_000)).await;
    assert_eq!(port.call_times(target, CallKind::Dial), vec![0]);
    assert_eq!(
        port.call_times(target, CallKind::Probe),
        vec![0, 5_000],
        "reassessed at the instant the raced turn settled"
    );
    running.shutdown().await;
}

/// Target validation accepts distinct public peers, reports a seed entry's own refusal
/// unchanged (the set laws are tested with the seed module), and skips the node itself.
#[test]
fn targets_validate_as_a_seed_set_and_skip_self() {
    let local = Did::from(LOCAL);
    assert_eq!(targets(vec![peer(1), peer(2)]).len(), 2);
    assert!(matches!(
        rejection(vec![SeedPeer {
            did: "not-a-did".to_string(),
            ..peer(1)
        }]),
        Error::SeedPeer(SeedPeerError::NotADid(did)) if did == "not-a-did"
    ));
    assert_eq!(
        targets(vec![peer(1), peer(2), peer(LOCAL)]).len(),
        2,
        "the node itself is skipped, not refused"
    );
    assert!(
        BootstrapTargets::from_config(BootstrapConfig::default(), local)
            .expect("an empty section validates")
            .is_empty()
    );
}

/// The admission rendezvous resolves a registered waiter and drops an admission observed before
/// any; a later waiter for the same peer replaces the earlier one, whose drop leaves the
/// replacement registered; a dropped waiter forgets its own registration.
#[tokio::test]
async fn test_admissions_resolve_registered_waiters_replace_and_forget() {
    let admissions = Admissions::default();

    admissions.observe(Did::from(1)).unwrap();
    assert_eq!(
        admissions.len().unwrap(),
        0,
        "an unawaited admission is dropped"
    );
    let mut late = admissions.wait_for(Did::from(1)).unwrap();
    assert!(
        matches!(late.try_recv(), Err(TryRecvError::Empty)),
        "a waiter never sees an admission observed before it"
    );
    admissions.observe(Did::from(1)).unwrap();
    assert_eq!(late.await, Ok(()));

    let mut stale = admissions.wait_for(Did::from(2)).unwrap();
    let waiter = admissions.wait_for(Did::from(2)).unwrap();
    assert!(
        matches!(stale.try_recv(), Err(TryRecvError::Closed)),
        "the replaced waiter is closed"
    );
    drop(stale);
    admissions.observe(Did::from(2)).unwrap();
    assert_eq!(
        waiter.await,
        Ok(()),
        "dropping the replaced waiter leaves the replacement registered"
    );

    let waiter = admissions.wait_for(Did::from(3)).unwrap();
    assert_eq!(admissions.len().unwrap(), 1);
    drop(waiter);
    assert_eq!(
        admissions.len().unwrap(),
        0,
        "a dropped waiter forgets its registration"
    );
}