rings-node 1.0.0-pre.8

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.
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
//! Generic transport-relay protocol — one pure server-side state machine for TCP and UDP.
//!
//! The pure model is generic over the **target** `T` a service resolves to; the native
//! interpreter `NativeRelay` resolves it to a `SocketAddr` and runs the effects over OS
//! sockets. TCP and UDP share the same `step`, state, duplicate-`Open` rejection and
//! owner-rejection: they are one relay.
//!
//! Every session is identified by the **owner-scoped key** `(from, namespace, session,
//! initiator)` ([`SessionKey`]). `from` is the authenticated sender (owner rejection: a peer
//! can only name keys whose `from` is itself), and `initiator` records which end opened it —
//! so a session a peer opened never collides with one we opened that got the same id
//! (bidirectional-open safety). A frame's `from_opener` flips to our `initiator`.
//!
//! The reducer is the **sole authority** over the session set: `Data`/`Shutdown`/`Close`
//! emit an effect only for a session in `sessions` (the engine never adjudicates liveness).
//! The order of a TCP direction's segments and its FIN is the session task's, which owns the
//! socket they are written to (`engine::reorder`): a repeated FIN, or a segment past its count,
//! resets the session there.
//!
//! ```text
//!   S = (services : Name ⇀ T, sessions : ℘ SessionKey, next : ℕ)
//!   k = (from, namespace, session, init)        init = Remote if from_opener else Local
//!   step (Command(Register n t))                ↦ (S[services∪{n↦t}], ε)
//!   step (Command(Accepted tok peer svc))       ↦ (S[sessions∪{kₗ}, next+1], [OpenAccepted tok kₗ svc])
//!                                                   where kₗ=(peer,ns,next,Local)   ← core mints the id
//!   step (Command(Untrack k))                   ↦ (S[sessions∖{k}], ε)
//!   step (Frame(from, Open s n)) | k∈sessions   ↦ (S, ε)                  (live duplicate)
//!                                | n∈services    ↦ (S∪{k}, [Connect k t kind])
//!                                | otherwise     ↦ (S, [SendClose s])
//!   step (Frame(from, Data s q b))   | TCP ∧ k∈sessions ↦ (S, [Write k q b])        else (S, ε)
//!   step (Frame(from, FIN s n))      | TCP ∧ k∈sessions ↦ (S, [Shutdown k n])       else (S, ε)
//!   step (Frame(from, Datagram s b)) | UDP ∧ k∈sessions ↦ (S, [SendDatagram k b])   else (S, ε)
//!   step (Frame(from, Close s))  | k∈sessions          ↦ (S∖{k}, [Close k]) else (S, ε)
//!   invariant                    |sessions| ≤ 1024 ∧ ∀peer. sessions(peer) ≤ 64
//! ```

use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;

use bytes::Bytes;
use rings_core::dht::Did;
use rings_runtime::MaybeSendSync;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;

use crate::extension::ext::Ctx;
use crate::extension::ext::EffectScope;
use crate::extension::ext::Interpret;
use crate::extension::ext::Protocol;
use crate::extension::ext::Reject;
use crate::extension::ext::Scope;
use crate::extension::ext::Transition;
use crate::extension::ext::Wire;
use crate::extension::transport::engine::Outbound;
use crate::extension::transport::EffectEnqueue;
use crate::extension::transport::Frame;
use crate::extension::transport::Initiator;
use crate::extension::transport::RelaySessionId;
use crate::extension::transport::SessionKey;
use crate::extension::transport::TransportKind;
use crate::peer_quota::PeerQuota;

mod control_outbox;
use self::control_outbox::ControlOutbox;
#[cfg(test)]
pub(crate) use self::control_outbox::ControlSendTestHook;

/// Namespace for the TCP relay.
pub const TCP: &str = "tcp";
/// Namespace for the UDP relay.
pub const UDP: &str = "udp";

/// Hard per-namespace live-session bound. The reducer owns admission, so both native and
/// browser interpreters inherit the same resource ceiling.
pub(crate) const MAX_RELAY_SESSIONS: usize = 1_024;
/// A single authenticated peer cannot consume the entire relay-session budget.
pub(crate) const MAX_RELAY_SESSIONS_PER_PEER: usize = 64;
/// A local control command, re-injected by the provider (provenance = self; never sent by
/// peers). Generic over the service target `T`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum RelayCommand<T> {
    /// Map a service name to a local target that `Open` may dial.
    RegisterService {
        /// Service name.
        name: String,
        /// Local target (a `SocketAddr` for the native interpreter).
        target: T,
    },
    /// Engine→protocol feedback: a local connection/datagram-flow was accepted, pending
    /// under engine-local `token`, destined for `peer`'s `service`. The pure `step` mints
    /// the session id (so id allocation lives in the core, not the shell), records it, and
    /// replies with [`RelayEffect::OpenAccepted`] to bind the pending resource. The engine
    /// never mints or decides identity — it only reports the raw accept and executes effects.
    Accepted {
        /// Engine-local handle for the pending (not-yet-bound) connection/flow.
        token: u64,
        /// The remote peer this session is tunnelled to.
        peer: Did,
        /// The remote service to open.
        service: String,
    },
    /// Engine→protocol feedback: a session was torn down by the engine (any side); forget
    /// it. The single point through which every teardown reaches the pure state.
    Untrack {
        /// The remote peer of the session.
        peer: Did,
        /// The session id.
        session: RelaySessionId,
        /// Which end opened it (so the right key is removed).
        initiator: Initiator,
    },
    /// Engine→protocol feedback: the current backend failed under an ordered
    /// effect. Forget it and emit exactly one peer-facing `Close`.
    Abort {
        /// The remote peer of the session.
        peer: Did,
        /// The session id.
        session: RelaySessionId,
        /// Which end opened it.
        initiator: Initiator,
    },
}

/// The relay's typed input: a self-injected [`RelayCommand`] or an authenticated peer
/// [`Frame`]. The `from == me` split is resolved in [`Relay::decode`].
pub enum RelayEvent<T> {
    /// Runtime service registration (provenance = self).
    Command(RelayCommand<T>),
    /// A network frame from an authenticated peer.
    Frame {
        /// Authenticated sender.
        from: Did,
        /// The frame.
        frame: Frame,
    },
}

/// The relay's own effect algebra (interpreted by `NativeRelay`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RelayEffect<T> {
    /// Open a local backend session to `target` and relay it (peer opened a session).
    Connect {
        /// Owner-scoped delegatee key.
        key: SessionKey,
        /// Local target to dial.
        target: T,
        /// Stream (TCP) or datagram (UDP).
        kind: TransportKind,
    },
    /// Write a peer segment to a session's local stream, in its `seq` order.
    Write {
        /// Target session.
        key: SessionKey,
        /// The segment's position in the peer's direction.
        seq: u64,
        /// Bytes.
        bytes: Bytes,
    },
    /// Send a peer datagram on a flow's local socket.
    SendDatagram {
        /// Target flow.
        key: SessionKey,
        /// The datagram.
        bytes: Bytes,
    },
    /// Half-close a session's local write side once the peer's `sent` segments are written
    /// (peer FIN).
    Shutdown {
        /// Target session.
        key: SessionKey,
        /// How many segments the peer sent this direction.
        sent: u64,
    },
    /// Close a session (full teardown).
    Close {
        /// Target session.
        key: SessionKey,
    },
    /// Reply a `Frame::Close` to a peer that opened an unknown service. The reply goes out under
    /// the interpreter's own namespace (its [`Scope`]), so the effect carries no namespace of
    /// its own.
    SendClose {
        /// Peer to reply to.
        to: Did,
        /// Relay session identifier to close.
        session: RelaySessionId,
        /// Whether *we* opened the session (false: the peer did).
        from_opener: bool,
    },
    /// Bind a pending accepted connection/flow (engine-local `token`) to the session `key`
    /// the pure `step` just minted, then open it to the peer and start relaying. The reply
    /// to [`RelayCommand::Accepted`] — this is how a step-minted id reaches the engine.
    OpenAccepted {
        /// Engine-local handle for the pending connection/flow.
        token: u64,
        /// The delegatee key minted by the pure step.
        key: SessionKey,
        /// The remote service to open.
        service: String,
    },
    /// Drop an accepted local resource when the pure session-id space is exhausted.
    RejectAccepted {
        /// Engine-local handle whose resource must be released.
        token: u64,
    },
}

/// Relay state: the service registry and the set of live sessions in both directions. The live
/// OS resources are the interpreter's engine table; this is the protocol's view
/// used for admission, ownership checks, and duplicate-`Open` rejection.
#[derive(Clone)]
pub struct RelayState<T> {
    services: Arc<HashMap<String, T>>,
    /// Persistent live-session index. Cloning a pure state for a data-frame transition is O(1);
    /// session lifecycle steps copy on write.
    sessions: Arc<HashSet<SessionKey>>,
    /// Exact cached cardinality of `sessions` projected by authenticated peer.
    ///
    /// Invariant: `session_quota.peer_total(p) = |{ k \in sessions : k.peer = p }|`; zero entries are
    /// absent. Keeping the projection in the pure state makes admission O(1) without giving the
    /// interpreter a second source of truth.
    session_quota: Arc<PeerQuota>,
    /// Monotonic allocator for client-side session ids. Lives in the **pure** state so the
    /// core (not the engine) mints session identities — `Event → step → Effect` is the sole
    /// authority for both the session set and its ids.
    next_session: u64,
}

impl<T> Default for RelayState<T> {
    fn default() -> Self {
        Self {
            services: Arc::new(HashMap::new()),
            sessions: Arc::new(HashSet::new()),
            session_quota: Arc::new(PeerQuota::new(
                MAX_RELAY_SESSIONS,
                MAX_RELAY_SESSIONS_PER_PEER,
            )),
            next_session: 0,
        }
    }
}

impl<T> RelayState<T> {
    fn can_admit_session(&self, key: &SessionKey) -> bool {
        self.session_quota.can_reserve(key.peer).is_ok()
    }

    fn insert_session(&mut self, key: SessionKey) -> bool {
        if self.sessions.contains(&key) {
            return false;
        }
        if Arc::make_mut(&mut self.session_quota)
            .reserve(key.peer)
            .is_err()
        {
            return false;
        }
        let peer = key.peer;
        if Arc::make_mut(&mut self.sessions).insert(key) {
            true
        } else {
            let rolled_back = Arc::make_mut(&mut self.session_quota).release(peer);
            debug_assert!(rolled_back);
            false
        }
    }

    fn remove_session(&mut self, key: &SessionKey) -> bool {
        if !self.sessions.contains(key) {
            return false;
        }
        if !Arc::make_mut(&mut self.session_quota).release(key.peer) {
            debug_assert!(false, "session quota missing admitted peer {}", key.peer);
            return false;
        }
        let removed = Arc::make_mut(&mut self.sessions).remove(key);
        debug_assert!(removed);
        removed
    }
}

/// Transport relay protocol (server side), generic over the service target `T`.
#[derive(Clone)]
pub struct Relay<T> {
    namespace: String,
    kind: TransportKind,
    /// Target type carried by the protocol algebra. Runtime registration is the sole source of
    /// service mappings, so construction owns no second map.
    marker: std::marker::PhantomData<fn() -> T>,
}

impl<T> Relay<T> {
    /// Build a TCP relay with an initially empty runtime service registry.
    pub fn tcp() -> Self {
        Self {
            namespace: TCP.to_string(),
            kind: TransportKind::Tcp,
            marker: std::marker::PhantomData,
        }
    }

    /// Build a UDP relay with an initially empty runtime service registry.
    pub fn udp() -> Self {
        Self {
            namespace: UDP.to_string(),
            kind: TransportKind::Udp,
            marker: std::marker::PhantomData,
        }
    }
}

impl<T> Protocol for Relay<T>
where T: Clone + DeserializeOwned + Serialize + MaybeSendSync + 'static
{
    type State = RelayState<T>;
    type Event = RelayEvent<T>;
    type Effect = RelayEffect<T>;

    fn namespace(&self) -> &str {
        self.namespace.as_str()
    }

    fn init(&self) -> RelayState<T> {
        RelayState::default()
    }

    fn decode(&self, wire: Wire<'_>) -> Result<RelayEvent<T>, Reject> {
        if wire.from == wire.me {
            let command = rings_codec::deserialize::<RelayCommand<T>>(wire.payload)
                .map_err(|e| Reject(format!("bad relay command: {e}")))?;
            Ok(RelayEvent::Command(command))
        } else {
            let frame = rings_codec::deserialize::<Frame>(wire.payload)
                .map_err(|e| Reject(format!("bad relay frame: {e}")))?;
            Ok(RelayEvent::Frame {
                from: wire.from,
                frame,
            })
        }
    }

    fn step(
        &self,
        ctx: Ctx<'_, RelayState<T>>,
        event: RelayEvent<T>,
    ) -> Transition<RelayState<T>, RelayEffect<T>> {
        match event {
            RelayEvent::Command(command) => {
                step_command(self.namespace.as_str(), ctx.state, command)
            }
            RelayEvent::Frame { from, frame } => {
                step_frame(self.kind, self.namespace.as_str(), ctx.state, from, frame)
            }
        }
    }
}

/// Apply a local [`RelayCommand`]. Pure. `Accepted`/`Untrack` are the engine→protocol
/// feedback that make `step` the sole authority over the session set **and its ids**: the
/// core mints the id on `Accepted` (the engine reported only a local token) and forgets the
/// session on `Untrack`.
fn step_command<T: Clone>(
    namespace: &str,
    state: &RelayState<T>,
    command: RelayCommand<T>,
) -> Transition<RelayState<T>, RelayEffect<T>> {
    let mut next = state.clone();
    match command {
        RelayCommand::RegisterService { name, target } => {
            Arc::make_mut(&mut next.services).insert(name, target);
            Transition::pure(next)
        }
        RelayCommand::Accepted {
            token,
            peer,
            service,
        } => {
            // The core mints the session id (the engine reported only its local token), so
            // id allocation is part of the pure state transition, not a shell decision.
            let session = RelaySessionId(next.next_session);
            let key = SessionKey::new(peer, namespace, session, Initiator::Local);
            if !next.can_admit_session(&key) {
                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
            }
            let Some(next_session) = next.next_session.checked_add(1) else {
                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
            };
            next.next_session = next_session;
            // A locally-accepted tunnel: we are the initiator.
            if !next.insert_session(key.clone()) {
                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
            }
            Transition::with(next, vec![RelayEffect::OpenAccepted {
                token,
                key,
                service,
            }])
        }
        RelayCommand::Untrack {
            peer,
            session,
            initiator,
        } => {
            next.remove_session(&SessionKey::new(peer, namespace, session, initiator));
            Transition::pure(next)
        }
        RelayCommand::Abort {
            peer,
            session,
            initiator,
        } => {
            let key = SessionKey::new(peer, namespace, session, initiator);
            if next.remove_session(&key) {
                Transition::with(next, vec![RelayEffect::SendClose {
                    to: peer,
                    session,
                    from_opener: matches!(initiator, Initiator::Local),
                }])
            } else {
                Transition::pure(next)
            }
        }
    }
}

/// Apply a network [`Frame`]. Pure; emits relay effects scoped to the authenticated `from`.
fn step_frame<T: Clone>(
    kind: TransportKind,
    namespace: &str,
    state: &RelayState<T>,
    from: Did,
    frame: Frame,
) -> Transition<RelayState<T>, RelayEffect<T>> {
    match frame {
        // `Open` is always sent by the opener, so from our side the peer is the initiator.
        Frame::Open { session, service } => {
            let key = SessionKey::new(from, namespace, session, Initiator::Remote);
            // A duplicate for a live session is silent. Rejected opens are not retained in pure
            // state: the bounded interpreter outbox owns control-plane resource admission, so a
            // historical failure cannot permanently consume protocol capacity.
            if state.sessions.contains(&key) {
                return Transition::pure(state.clone());
            }
            match state.services.get(service.as_str()) {
                Some(target) => {
                    let mut next = state.clone();
                    if !next.can_admit_session(&key) {
                        return rejected_open(next, key);
                    }
                    let target = target.clone();
                    if !next.insert_session(key.clone()) {
                        return rejected_open(next, key);
                    }
                    Transition::with(next, vec![RelayEffect::Connect { key, target, kind }])
                }
                None => rejected_open(state.clone(), key),
            }
        }
        // Data/Shutdown/Close are guarded on the authoritative session set: the *reducer*
        // decides whether the effect happens, not the engine table. `from_opener` (the
        // sender opened it) flips to our initiator.
        Frame::Data {
            session,
            from_opener,
            seq,
            bytes,
        } => {
            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
            to_live_session(state, kind, TransportKind::Tcp, key, |key| {
                RelayEffect::Write { key, seq, bytes }
            })
        }
        Frame::Shutdown {
            session,
            from_opener,
            sent,
        } => {
            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
            to_live_session(state, kind, TransportKind::Tcp, key, |key| {
                RelayEffect::Shutdown { key, sent }
            })
        }
        Frame::Datagram {
            session,
            from_opener,
            bytes,
        } => {
            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
            to_live_session(state, kind, TransportKind::Udp, key, |key| {
                RelayEffect::SendDatagram { key, bytes }
            })
        }
        Frame::Close {
            session,
            from_opener,
        } => {
            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
            if state.sessions.contains(&key) {
                let mut next = state.clone();
                next.remove_session(&key);
                Transition::with(next, vec![RelayEffect::Close { key }])
            } else {
                Transition::pure(state.clone())
            }
        }
    }
}

/// Reject a peer-opened session without allocating live-session or interpreter state.
fn rejected_open<T>(
    state: RelayState<T>,
    key: SessionKey,
) -> Transition<RelayState<T>, RelayEffect<T>> {
    Transition::with(state, vec![RelayEffect::SendClose {
        to: key.peer,
        session: key.session,
        // The peer opened it; this endpoint did not.
        from_opener: false,
    }])
}

/// Hand the session `key` its `effect` iff the relay's `kind` is the frame's `carrier` and the
/// session is live; any other frame changes nothing.
fn to_live_session<T: Clone>(
    state: &RelayState<T>,
    kind: TransportKind,
    carrier: TransportKind,
    key: SessionKey,
    effect: impl FnOnce(SessionKey) -> RelayEffect<T>,
) -> Transition<RelayState<T>, RelayEffect<T>> {
    if kind == carrier && state.sessions.contains(&key) {
        Transition::with(state.clone(), vec![effect(key)])
    } else {
        Transition::pure(state.clone())
    }
}

/// Map a frame's `from_opener` (the **sender** opened the session) to our own [`Initiator`].
fn opener_to_initiator(from_opener: bool) -> Initiator {
    if from_opener {
        Initiator::Remote
    } else {
        Initiator::Local
    }
}

/// Encode a `Frame::Close` as bytes for an overlay send. `from_opener` is whether *we* (the
/// sender of this close) opened the session.
pub(crate) fn close_frame(
    session: RelaySessionId,
    from_opener: bool,
) -> crate::error::Result<Bytes> {
    let frame = Frame::Close {
        session,
        from_opener,
    };
    rings_codec::serialize(&frame)
        .map(Bytes::from)
        .map_err(|_| crate::error::Error::EncodeError)
}

// ── Native interpreter (OS sockets) ───────────────────────────────────────────────────

/// Native relay interpreter: runs [`RelayEffect`]s over the OS-socket engine it owns. The
/// engine uses the namespace-scoped [`Scope`] capability for both overlay sends and lifecycle
/// feedback (`Accepted`/`Untrack`), so the engine has no `Processor` of its own.
pub(crate) struct NativeRelay {
    engine: Arc<crate::extension::transport::engine::TransportSessions>,
    control_outbox: ControlOutbox,
}

impl NativeRelay {
    /// Build over a shared engine.
    pub(crate) fn new(engine: Arc<crate::extension::transport::engine::TransportSessions>) -> Self {
        Self {
            engine,
            control_outbox: ControlOutbox::default(),
        }
    }

    #[cfg(test)]
    pub(crate) fn new_with_control_send_test_hook(
        engine: Arc<crate::extension::transport::engine::TransportSessions>,
        hook: Arc<ControlSendTestHook>,
    ) -> Self {
        Self {
            engine,
            control_outbox: ControlOutbox::with_test_hook(hook),
        }
    }
}

impl NativeRelay {
    /// Deliver `outbound` to the session `key`'s local socket, as the reducer's feedback.
    fn deliver(&self, key: SessionKey, outbound: Outbound) -> crate::error::Result<Vec<Bytes>> {
        let admission = self.engine.deliver(&key, outbound);
        enqueue_feedback::<std::net::SocketAddr>(key, admission)
    }
}

#[async_trait::async_trait]
impl Interpret for NativeRelay {
    type Effect = RelayEffect<std::net::SocketAddr>;

    async fn run(
        &self,
        scope: &EffectScope,
        effect: RelayEffect<std::net::SocketAddr>,
    ) -> crate::error::Result<Vec<Bytes>> {
        match effect {
            RelayEffect::Connect { key, target, kind } => {
                let admission =
                    self.engine
                        .clone()
                        .connect(scope.lifecycle(), key.clone(), target, kind);
                return enqueue_feedback::<std::net::SocketAddr>(key, admission);
            }
            RelayEffect::Write { key, seq, bytes } => {
                return self.deliver(key, Outbound::Segment { seq, bytes });
            }
            RelayEffect::SendDatagram { key, bytes } => {
                return self.deliver(key, Outbound::Datagram(bytes));
            }
            RelayEffect::Shutdown { key, sent } => {
                return self.deliver(key, Outbound::Shutdown { sent });
            }
            RelayEffect::Close { key } => {
                self.engine.close_for_effect(&key);
            }
            RelayEffect::SendClose {
                to,
                session,
                from_opener,
            } => {
                self.control_outbox.enqueue(
                    scope.lifecycle(),
                    to,
                    close_frame(session, from_opener)?,
                )?;
            }
            RelayEffect::OpenAccepted {
                token,
                key,
                service,
            } => {
                let feedback =
                    self.engine
                        .clone()
                        .bind_accepted(scope.lifecycle(), token, key, service);
                return feedback
                    .map(untrack_feedback::<std::net::SocketAddr>)
                    .transpose()
                    .map(|feedback| feedback.into_iter().collect());
            }
            RelayEffect::RejectAccepted { token } => {
                self.engine.evict_pending_for_effect(token);
            }
        }
        Ok(Vec::new())
    }
}

/// Encode an engine teardown as the relay's synchronous, ordered feedback path.
fn untrack_feedback<T: Serialize>(key: SessionKey) -> crate::error::Result<Bytes> {
    let command = RelayCommand::<T>::Untrack {
        peer: key.peer,
        session: key.session,
        initiator: key.initiator,
    };
    rings_codec::serialize(&command)
        .map(Bytes::from)
        .map_err(|_| crate::error::Error::EncodeError)
}

/// Encode a synchronous engine failure so the pure reducer owns both state
/// removal and the exactly-once peer-facing terminal effect.
fn abort_feedback<T: Serialize>(key: SessionKey) -> crate::error::Result<Bytes> {
    let command = RelayCommand::<T>::Abort {
        peer: key.peer,
        session: key.session,
        initiator: key.initiator,
    };
    rings_codec::serialize(&command)
        .map(Bytes::from)
        .map_err(|_| crate::error::Error::EncodeError)
}

/// Map backend admission into the relay reducer's ordered feedback algebra.
fn enqueue_feedback<T: Serialize>(
    key: SessionKey,
    admission: EffectEnqueue,
) -> crate::error::Result<Vec<Bytes>> {
    match admission {
        EffectEnqueue::Enqueued | EffectEnqueue::AlreadyPresent => Ok(Vec::new()),
        EffectEnqueue::Missing => untrack_feedback::<T>(key).map(|feedback| vec![feedback]),
        EffectEnqueue::Failed => abort_feedback::<T>(key).map(|feedback| vec![feedback]),
    }
}

// ── Client-side relay handle ──────────────────────────────────────────────────────────

/// Client-facing handle to the relay extension's live engine: open local tunnels and register
/// local services. This is the relay extension's *own* surface — the relay owns its engine and
/// installs itself ([`install`](RelayHandle::install)), so nothing about it leaks into the
/// generic [`Provider`](crate::provider::Provider).
/// Cloneable; every clone drives the same shared engine and pure [`Relay`] state.
/// Holds the two per-namespace scoped capabilities (`tcp` / `udp`); each method picks one and
/// can only act within it, so the handle cannot address an arbitrary namespace even internally.
#[derive(Clone)]
pub struct RelayHandle {
    engine: Arc<crate::extension::transport::engine::TransportSessions>,
    tcp: Scope,
    udp: Scope,
}

impl RelayHandle {
    /// Install the relay into an extension registry: register the TCP and UDP interpreters
    /// over a fresh, relay-owned OS-socket engine and return the client handle. Errors if the
    /// `tcp`/`udp` namespaces are already taken. Call once per node, after constructing the
    /// provider — the relay is opt-in, not a `Provider` invariant.
    pub fn install(extensions: &crate::extension::ext::Extensions) -> crate::error::Result<Self> {
        let engine = Arc::new(crate::extension::transport::engine::TransportSessions::new());
        // Atomic: both namespaces register together, or neither (no half-installed relay).
        extensions.register_many(vec![
            (Relay::tcp(), NativeRelay::new(engine.clone())),
            (Relay::udp(), NativeRelay::new(engine.clone())),
        ])?;
        let core = extensions.core();
        Ok(Self {
            engine,
            tcp: Scope::new(core.clone(), TCP.to_string()),
            udp: Scope::new(core, UDP.to_string()),
        })
    }

    /// Open a local **TCP** tunnel: bind `local_addr` and relay each accepted connection to
    /// `peer`'s `service` (client side, forward proxy).
    pub async fn open_tcp_tunnel(
        &self,
        local_addr: std::net::SocketAddr,
        peer: Did,
        service: String,
    ) -> crate::error::Result<()> {
        self.open_tunnel(&self.tcp, local_addr, peer, service, TransportKind::Tcp)
            .await
    }

    /// Relay one already-accepted **TCP** stream to `peer`'s `service`. Returns once the relay
    /// has taken the stream; the session runs on.
    pub async fn relay_tcp_stream(
        &self,
        stream: tokio::net::TcpStream,
        peer: Did,
        service: String,
    ) -> crate::error::Result<()> {
        self.engine
            .clone()
            .relay_tcp_stream(self.tcp.clone(), stream, peer, service, Bytes::new(), None)
            .await;
        Ok(())
    }

    /// Relay one already-accepted **TCP** stream to `peer`'s `service`, `preamble` first, and
    /// return once the relay is done with it: its session ended, or it was refused or never
    /// opened. A caller that bounds its live connections holds its slot for this call.
    pub async fn carry_tcp_stream(
        &self,
        stream: tokio::net::TcpStream,
        peer: Did,
        service: String,
        preamble: Bytes,
    ) -> crate::error::Result<()> {
        let (hold, released) = crate::extension::transport::engine::StreamHold::new();
        self.engine
            .clone()
            .relay_tcp_stream(
                self.tcp.clone(),
                stream,
                peer,
                service,
                preamble,
                Some(hold),
            )
            .await;
        released.wait().await;
        Ok(())
    }

    /// Open a local **UDP** tunnel: bind `local_addr` and relay each datagram flow to `peer`'s
    /// `service` (client side, forward proxy).
    pub async fn open_udp_tunnel(
        &self,
        local_addr: std::net::SocketAddr,
        peer: Did,
        service: String,
    ) -> crate::error::Result<()> {
        self.open_tunnel(&self.udp, local_addr, peer, service, TransportKind::Udp)
            .await
    }

    async fn open_tunnel(
        &self,
        scope: &Scope,
        local_addr: std::net::SocketAddr,
        peer: Did,
        service: String,
        kind: TransportKind,
    ) -> crate::error::Result<()> {
        // Bind a local listener on the relay engine with this namespace's scope. Each accepted
        // connection is reported back through the pure relay (`Accepted`), so
        // `RelayState.sessions` stays the sole authority.
        self.engine
            .clone()
            .listen(scope.clone(), local_addr, peer, service, kind)
            .await
    }

    /// Register (at runtime) a local service the **TCP** relay may dial (`name` → `addr`).
    pub async fn register_tcp_service(
        &self,
        name: String,
        addr: std::net::SocketAddr,
    ) -> crate::error::Result<()> {
        register_service(&self.tcp, name, addr).await
    }

    /// Register (at runtime) a local service the **UDP** relay may dial (`name` → `addr`).
    pub async fn register_udp_service(
        &self,
        name: String,
        addr: std::net::SocketAddr,
    ) -> crate::error::Result<()> {
        register_service(&self.udp, name, addr).await
    }
}

/// Map a service `name` → `target` by self-injecting a `RegisterService` command into the
/// scope's own namespace (provenance = self).
async fn register_service<T>(scope: &Scope, name: String, target: T) -> crate::error::Result<()>
where T: Serialize {
    let command = RelayCommand::RegisterService { name, target };
    let payload = rings_codec::serialize(&command).map_err(|_| crate::error::Error::EncodeError)?;
    scope.inject(Bytes::from(payload)).await
}

#[cfg(test)]
mod test_relay;