openrtc 2.8.8

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
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
//! Shared iroh connection install/replacement policy.
//!
//! Browser and native nodes both see the same symmetric-dial and post-restart
//! races. Keeping this decision table target-neutral prevents wasm/native
//! behavior from drifting as each wrapper evolves.

use crate::lifecycle_reason::{
    REASON_DUPLICATE_ACCEPT_SUPERSEDED, REASON_DUPLICATE_DIAL_SUPERSEDED,
};

/// Briefly let the canonical initiator establish the shared physical leg before
/// the noncanonical endpoint falls back to its own dial. This prevents the two
/// independent QUIC connections from closing each other during symmetric
/// reconnect while still allowing a one-sided caller to make progress.
pub(crate) const NONCANONICAL_OUTBOUND_DIAL_GRACE_MS: u64 = 250;

/// Decide whether a custom Iroh carrier may be prepared over the current
/// physical path. Initial upgrades may start from relay/unknown, while an
/// atomic policy switch may prepare the opposite custom carrier over the live
/// incumbent. Same-carrier replacement is reserved for an explicitly bounded
/// stale-generation retry.
#[cfg(any(test, feature = "transport-webrtc", feature = "transport-moq"))]
pub(crate) fn custom_carrier_base_allows(
    path: crate::client::IrohPathKind,
    target: crate::client::IrohPathKind,
    allow_same_carrier_retry: bool,
) -> bool {
    use crate::client::IrohPathKind;

    matches!(path, IrohPathKind::Relay | IrohPathKind::Unknown)
        || matches!(
            (path, target),
            (IrohPathKind::WebRtc, IrohPathKind::Moq) | (IrohPathKind::Moq, IrohPathKind::WebRtc)
        )
        || (allow_same_carrier_retry && path == target)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IrohConnectionDirection {
    Inbound,
    Outbound,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ExistingConnectionState {
    pub same_stable_id: bool,
    pub alive: bool,
    pub direction: IrohConnectionDirection,
    pub age_ms: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IrohConnectionInstallDecision {
    /// Adopt the fresh connection into the endpoint map.
    Install,
    /// Adopt the fresh connection and retire the non-canonical existing leg.
    /// Endpoint-id ordering makes both peers select opposite halves of the
    /// same physical dial instead of each keeping its own outbound connection.
    ReplaceExisting { close_existing_reason: &'static str },
    /// Keep the existing endpoint map entry and close the fresh connection.
    KeepExisting { close_fresh_reason: &'static str },
}

pub(crate) fn should_start_outbound_dial(
    existing: Option<(bool, IrohConnectionDirection)>,
    local_prefers_outbound: bool,
) -> bool {
    let Some((alive, direction)) = existing else {
        return true;
    };
    !alive || (local_prefers_outbound && direction != IrohConnectionDirection::Outbound)
}

pub(crate) fn should_wait_for_canonical_inbound(
    existing: Option<(bool, IrohConnectionDirection)>,
    local_prefers_outbound: bool,
) -> bool {
    if local_prefers_outbound {
        return false;
    }
    match existing {
        None => true,
        Some((alive, _)) => !alive,
    }
}

pub(crate) fn decide_inbound_install(
    existing: Option<ExistingConnectionState>,
    local_prefers_outbound: bool,
) -> IrohConnectionInstallDecision {
    decide_install(
        existing,
        IrohConnectionDirection::Inbound,
        local_prefers_outbound,
    )
}

pub(crate) fn decide_outbound_install(
    existing: Option<ExistingConnectionState>,
    local_prefers_outbound: bool,
) -> IrohConnectionInstallDecision {
    decide_install(
        existing,
        IrohConnectionDirection::Outbound,
        local_prefers_outbound,
    )
}

fn replace_existing_decision(
    fresh_direction: IrohConnectionDirection,
) -> IrohConnectionInstallDecision {
    IrohConnectionInstallDecision::ReplaceExisting {
        close_existing_reason: match fresh_direction {
            IrohConnectionDirection::Inbound => {
                crate::lifecycle_reason::REASON_REPLACED_BY_NEW_INBOUND
            }
            IrohConnectionDirection::Outbound => {
                crate::lifecycle_reason::REASON_REPLACED_BY_NEW_OUTBOUND
            }
        },
    }
}

fn decide_install(
    existing: Option<ExistingConnectionState>,
    fresh_direction: IrohConnectionDirection,
    local_prefers_outbound: bool,
) -> IrohConnectionInstallDecision {
    let Some(existing) = existing else {
        return IrohConnectionInstallDecision::Install;
    };
    if existing.same_stable_id || !existing.alive {
        return IrohConnectionInstallDecision::Install;
    }
    let canonical_direction = if local_prefers_outbound {
        IrohConnectionDirection::Outbound
    } else {
        IrohConnectionDirection::Inbound
    };
    if fresh_direction != canonical_direction {
        return IrohConnectionInstallDecision::KeepExisting {
            close_fresh_reason: match fresh_direction {
                IrohConnectionDirection::Inbound => REASON_DUPLICATE_ACCEPT_SUPERSEDED,
                IrohConnectionDirection::Outbound => REASON_DUPLICATE_DIAL_SUPERSEDED,
            },
        };
    }
    // Direction resolves symmetric dials immediately. A live same-direction
    // leg remains authoritative regardless of age: elapsed time alone is not
    // evidence that a QUIC connection is stale. Replacing it on every later
    // canonical dial makes admission proofs alternate between two physical
    // generations and can prevent bilateral settlement forever. Restart
    // recovery is driven by close/heartbeat evidence (existing.alive=false),
    // while explicit custom-transport replacement has its own fenced path.
    if existing.direction != canonical_direction {
        return replace_existing_decision(fresh_direction);
    }
    IrohConnectionInstallDecision::KeepExisting {
        close_fresh_reason: match fresh_direction {
            IrohConnectionDirection::Inbound => REASON_DUPLICATE_ACCEPT_SUPERSEDED,
            IrohConnectionDirection::Outbound => REASON_DUPLICATE_DIAL_SUPERSEDED,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn custom_carrier_admission_is_symmetric_and_fail_closed() {
        use crate::client::IrohPathKind;

        for target in [IrohPathKind::WebRtc, IrohPathKind::Moq] {
            assert!(custom_carrier_base_allows(
                IrohPathKind::Relay,
                target,
                false,
            ));
            assert!(custom_carrier_base_allows(
                IrohPathKind::Unknown,
                target,
                false,
            ));
            assert!(!custom_carrier_base_allows(target, target, false));
            for rejected in [
                IrohPathKind::DirectQuic,
                IrohPathKind::DirectLan,
                IrohPathKind::Ble,
            ] {
                assert!(!custom_carrier_base_allows(rejected, target, false));
            }
        }
        assert!(custom_carrier_base_allows(
            IrohPathKind::WebRtc,
            IrohPathKind::Moq,
            false,
        ));
        assert!(custom_carrier_base_allows(
            IrohPathKind::Moq,
            IrohPathKind::WebRtc,
            false,
        ));
        assert!(custom_carrier_base_allows(
            IrohPathKind::Moq,
            IrohPathKind::Moq,
            true,
        ));
    }

    #[test]
    fn install_without_existing_or_for_same_stable_id() {
        assert_eq!(
            decide_inbound_install(None, false),
            IrohConnectionInstallDecision::Install
        );
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: true,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: 0,
                }),
                true
            ),
            IrohConnectionInstallDecision::Install
        );
    }

    #[test]
    fn install_over_dead_existing_connection() {
        assert_eq!(
            decide_inbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: false,
                    direction: IrohConnectionDirection::Outbound,
                    age_ms: 0,
                }),
                false
            ),
            IrohConnectionInstallDecision::Install
        );
    }

    #[test]
    fn recent_same_direction_canonical_duplicate_keeps_existing_connection() {
        assert_eq!(
            decide_inbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: 1_999,
                }),
                false
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_ACCEPT_SUPERSEDED,
            }
        );
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Outbound,
                    age_ms: 0,
                }),
                true
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_DIAL_SUPERSEDED,
            }
        );
    }

    #[test]
    fn elapsed_time_cannot_replace_a_live_same_direction_connection() {
        assert_eq!(
            decide_inbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: u64::MAX,
                }),
                false
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_ACCEPT_SUPERSEDED,
            }
        );
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Outbound,
                    age_ms: u64::MAX,
                }),
                true
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_DIAL_SUPERSEDED,
            }
        );
    }

    #[test]
    fn canonical_fresh_leg_replaces_the_non_canonical_live_leg() {
        assert_eq!(
            decide_inbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Outbound,
                    age_ms: 0,
                }),
                false
            ),
            IrohConnectionInstallDecision::ReplaceExisting {
                close_existing_reason: crate::lifecycle_reason::REASON_REPLACED_BY_NEW_INBOUND,
            }
        );
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: 0,
                }),
                true
            ),
            IrohConnectionInstallDecision::ReplaceExisting {
                close_existing_reason: crate::lifecycle_reason::REASON_REPLACED_BY_NEW_OUTBOUND,
            }
        );
    }

    #[test]
    fn noncanonical_fresh_leg_cannot_replace_an_existing_live_leg() {
        assert_eq!(
            decide_inbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Outbound,
                    age_ms: u64::MAX,
                }),
                true
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_ACCEPT_SUPERSEDED,
            }
        );
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: u64::MAX,
                }),
                false
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_DIAL_SUPERSEDED,
            }
        );
    }

    #[test]
    fn connection_age_never_overrides_noncanonical_direction() {
        assert_eq!(
            decide_outbound_install(
                Some(ExistingConnectionState {
                    same_stable_id: false,
                    alive: true,
                    direction: IrohConnectionDirection::Inbound,
                    age_ms: u64::MAX,
                }),
                false,
            ),
            IrohConnectionInstallDecision::KeepExisting {
                close_fresh_reason: REASON_DUPLICATE_DIAL_SUPERSEDED,
            }
        );
    }

    #[test]
    fn outbound_precheck_is_idempotent_and_repairs_only_noncanonical_live_legs() {
        assert!(should_start_outbound_dial(None, true));
        assert!(should_start_outbound_dial(
            Some((false, IrohConnectionDirection::Outbound)),
            true,
        ));
        assert!(!should_start_outbound_dial(
            Some((true, IrohConnectionDirection::Outbound)),
            true,
        ));
        assert!(should_start_outbound_dial(
            Some((true, IrohConnectionDirection::Inbound)),
            true,
        ));
        assert!(!should_start_outbound_dial(
            Some((true, IrohConnectionDirection::Outbound)),
            false,
        ));
    }

    #[test]
    fn noncanonical_endpoint_waits_only_when_no_live_leg_exists() {
        assert!(should_wait_for_canonical_inbound(None, false));
        assert!(should_wait_for_canonical_inbound(
            Some((false, IrohConnectionDirection::Outbound)),
            false,
        ));
        assert!(!should_wait_for_canonical_inbound(
            Some((true, IrohConnectionDirection::Inbound)),
            false,
        ));
        assert!(!should_wait_for_canonical_inbound(None, true));
    }
}