Skip to main content

rings_node/extension/protocols/
relay.rs

1//! Generic transport-relay protocol — one pure server-side state machine for TCP and UDP.
2//!
3//! The pure model is generic over the **target** `T` a service resolves to; the native
4//! interpreter `NativeRelay` resolves it to a `SocketAddr` and runs the effects over OS
5//! sockets. TCP and UDP share the same `step`, state, duplicate-`Open` rejection and
6//! owner-rejection: they are one relay.
7//!
8//! Every session is identified by the **owner-scoped key** `(from, namespace, session,
9//! initiator)` ([`SessionKey`]). `from` is the authenticated sender (owner rejection: a peer
10//! can only name keys whose `from` is itself), and `initiator` records which end opened it —
11//! so a session a peer opened never collides with one we opened that got the same id
12//! (bidirectional-open safety). A frame's `from_opener` flips to our `initiator`.
13//!
14//! The reducer is the **sole authority** over the session set: `Data`/`Shutdown`/`Close`
15//! emit an effect only for a session in `sessions` (the engine never adjudicates liveness).
16//! The order of a TCP direction's segments and its FIN is the session task's, which owns the
17//! socket they are written to (`engine::reorder`): a repeated FIN, or a segment past its count,
18//! resets the session there.
19//!
20//! ```text
21//!   S = (services : Name ⇀ T, sessions : ℘ SessionKey, next : ℕ)
22//!   k = (from, namespace, session, init)        init = Remote if from_opener else Local
23//!   step (Command(Register n t))                ↦ (S[services∪{n↦t}], ε)
24//!   step (Command(Accepted tok peer svc))       ↦ (S[sessions∪{kₗ}, next+1], [OpenAccepted tok kₗ svc])
25//!                                                   where kₗ=(peer,ns,next,Local)   ← core mints the id
26//!   step (Command(Untrack k))                   ↦ (S[sessions∖{k}], ε)
27//!   step (Frame(from, Open s n)) | k∈sessions   ↦ (S, ε)                  (live duplicate)
28//!                                | n∈services    ↦ (S∪{k}, [Connect k t kind])
29//!                                | otherwise     ↦ (S, [SendClose s])
30//!   step (Frame(from, Data s q b))   | TCP ∧ k∈sessions ↦ (S, [Write k q b])        else (S, ε)
31//!   step (Frame(from, FIN s n))      | TCP ∧ k∈sessions ↦ (S, [Shutdown k n])       else (S, ε)
32//!   step (Frame(from, Datagram s b)) | UDP ∧ k∈sessions ↦ (S, [SendDatagram k b])   else (S, ε)
33//!   step (Frame(from, Close s))  | k∈sessions          ↦ (S∖{k}, [Close k]) else (S, ε)
34//!   invariant                    |sessions| ≤ 1024 ∧ ∀peer. sessions(peer) ≤ 64
35//! ```
36
37use std::collections::HashMap;
38use std::collections::HashSet;
39use std::sync::Arc;
40
41use bytes::Bytes;
42use rings_core::dht::Did;
43use rings_runtime::MaybeSendSync;
44use serde::de::DeserializeOwned;
45use serde::Deserialize;
46use serde::Serialize;
47
48use crate::extension::ext::Ctx;
49use crate::extension::ext::EffectScope;
50use crate::extension::ext::Interpret;
51use crate::extension::ext::Protocol;
52use crate::extension::ext::Reject;
53use crate::extension::ext::Scope;
54use crate::extension::ext::Transition;
55use crate::extension::ext::Wire;
56use crate::extension::transport::engine::Outbound;
57use crate::extension::transport::EffectEnqueue;
58use crate::extension::transport::Frame;
59use crate::extension::transport::Initiator;
60use crate::extension::transport::RelaySessionId;
61use crate::extension::transport::SessionKey;
62use crate::extension::transport::TransportKind;
63use crate::peer_quota::PeerQuota;
64
65mod control_outbox;
66use self::control_outbox::ControlOutbox;
67#[cfg(test)]
68pub(crate) use self::control_outbox::ControlSendTestHook;
69
70/// Namespace for the TCP relay.
71pub const TCP: &str = "tcp";
72/// Namespace for the UDP relay.
73pub const UDP: &str = "udp";
74
75/// Hard per-namespace live-session bound. The reducer owns admission, so both native and
76/// browser interpreters inherit the same resource ceiling.
77pub(crate) const MAX_RELAY_SESSIONS: usize = 1_024;
78/// A single authenticated peer cannot consume the entire relay-session budget.
79pub(crate) const MAX_RELAY_SESSIONS_PER_PEER: usize = 64;
80/// A local control command, re-injected by the provider (provenance = self; never sent by
81/// peers). Generic over the service target `T`.
82#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
83pub enum RelayCommand<T> {
84    /// Map a service name to a local target that `Open` may dial.
85    RegisterService {
86        /// Service name.
87        name: String,
88        /// Local target (a `SocketAddr` for the native interpreter).
89        target: T,
90    },
91    /// Engine→protocol feedback: a local connection/datagram-flow was accepted, pending
92    /// under engine-local `token`, destined for `peer`'s `service`. The pure `step` mints
93    /// the session id (so id allocation lives in the core, not the shell), records it, and
94    /// replies with [`RelayEffect::OpenAccepted`] to bind the pending resource. The engine
95    /// never mints or decides identity — it only reports the raw accept and executes effects.
96    Accepted {
97        /// Engine-local handle for the pending (not-yet-bound) connection/flow.
98        token: u64,
99        /// The remote peer this session is tunnelled to.
100        peer: Did,
101        /// The remote service to open.
102        service: String,
103    },
104    /// Engine→protocol feedback: a session was torn down by the engine (any side); forget
105    /// it. The single point through which every teardown reaches the pure state.
106    Untrack {
107        /// The remote peer of the session.
108        peer: Did,
109        /// The session id.
110        session: RelaySessionId,
111        /// Which end opened it (so the right key is removed).
112        initiator: Initiator,
113    },
114    /// Engine→protocol feedback: the current backend failed under an ordered
115    /// effect. Forget it and emit exactly one peer-facing `Close`.
116    Abort {
117        /// The remote peer of the session.
118        peer: Did,
119        /// The session id.
120        session: RelaySessionId,
121        /// Which end opened it.
122        initiator: Initiator,
123    },
124}
125
126/// The relay's typed input: a self-injected [`RelayCommand`] or an authenticated peer
127/// [`Frame`]. The `from == me` split is resolved in [`Relay::decode`].
128pub enum RelayEvent<T> {
129    /// Runtime service registration (provenance = self).
130    Command(RelayCommand<T>),
131    /// A network frame from an authenticated peer.
132    Frame {
133        /// Authenticated sender.
134        from: Did,
135        /// The frame.
136        frame: Frame,
137    },
138}
139
140/// The relay's own effect algebra (interpreted by `NativeRelay`).
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub enum RelayEffect<T> {
143    /// Open a local backend session to `target` and relay it (peer opened a session).
144    Connect {
145        /// Owner-scoped delegatee key.
146        key: SessionKey,
147        /// Local target to dial.
148        target: T,
149        /// Stream (TCP) or datagram (UDP).
150        kind: TransportKind,
151    },
152    /// Write a peer segment to a session's local stream, in its `seq` order.
153    Write {
154        /// Target session.
155        key: SessionKey,
156        /// The segment's position in the peer's direction.
157        seq: u64,
158        /// Bytes.
159        bytes: Bytes,
160    },
161    /// Send a peer datagram on a flow's local socket.
162    SendDatagram {
163        /// Target flow.
164        key: SessionKey,
165        /// The datagram.
166        bytes: Bytes,
167    },
168    /// Half-close a session's local write side once the peer's `sent` segments are written
169    /// (peer FIN).
170    Shutdown {
171        /// Target session.
172        key: SessionKey,
173        /// How many segments the peer sent this direction.
174        sent: u64,
175    },
176    /// Close a session (full teardown).
177    Close {
178        /// Target session.
179        key: SessionKey,
180    },
181    /// Reply a `Frame::Close` to a peer that opened an unknown service. The reply goes out under
182    /// the interpreter's own namespace (its [`Scope`]), so the effect carries no namespace of
183    /// its own.
184    SendClose {
185        /// Peer to reply to.
186        to: Did,
187        /// Relay session identifier to close.
188        session: RelaySessionId,
189        /// Whether *we* opened the session (false: the peer did).
190        from_opener: bool,
191    },
192    /// Bind a pending accepted connection/flow (engine-local `token`) to the session `key`
193    /// the pure `step` just minted, then open it to the peer and start relaying. The reply
194    /// to [`RelayCommand::Accepted`] — this is how a step-minted id reaches the engine.
195    OpenAccepted {
196        /// Engine-local handle for the pending connection/flow.
197        token: u64,
198        /// The delegatee key minted by the pure step.
199        key: SessionKey,
200        /// The remote service to open.
201        service: String,
202    },
203    /// Drop an accepted local resource when the pure session-id space is exhausted.
204    RejectAccepted {
205        /// Engine-local handle whose resource must be released.
206        token: u64,
207    },
208}
209
210/// Relay state: the service registry and the set of live sessions in both directions. The live
211/// OS resources are the interpreter's engine table; this is the protocol's view
212/// used for admission, ownership checks, and duplicate-`Open` rejection.
213#[derive(Clone)]
214pub struct RelayState<T> {
215    services: Arc<HashMap<String, T>>,
216    /// Persistent live-session index. Cloning a pure state for a data-frame transition is O(1);
217    /// session lifecycle steps copy on write.
218    sessions: Arc<HashSet<SessionKey>>,
219    /// Exact cached cardinality of `sessions` projected by authenticated peer.
220    ///
221    /// Invariant: `session_quota.peer_total(p) = |{ k \in sessions : k.peer = p }|`; zero entries are
222    /// absent. Keeping the projection in the pure state makes admission O(1) without giving the
223    /// interpreter a second source of truth.
224    session_quota: Arc<PeerQuota>,
225    /// Monotonic allocator for client-side session ids. Lives in the **pure** state so the
226    /// core (not the engine) mints session identities — `Event → step → Effect` is the sole
227    /// authority for both the session set and its ids.
228    next_session: u64,
229}
230
231impl<T> Default for RelayState<T> {
232    fn default() -> Self {
233        Self {
234            services: Arc::new(HashMap::new()),
235            sessions: Arc::new(HashSet::new()),
236            session_quota: Arc::new(PeerQuota::new(
237                MAX_RELAY_SESSIONS,
238                MAX_RELAY_SESSIONS_PER_PEER,
239            )),
240            next_session: 0,
241        }
242    }
243}
244
245impl<T> RelayState<T> {
246    fn can_admit_session(&self, key: &SessionKey) -> bool {
247        self.session_quota.can_reserve(key.peer).is_ok()
248    }
249
250    fn insert_session(&mut self, key: SessionKey) -> bool {
251        if self.sessions.contains(&key) {
252            return false;
253        }
254        if Arc::make_mut(&mut self.session_quota)
255            .reserve(key.peer)
256            .is_err()
257        {
258            return false;
259        }
260        let peer = key.peer;
261        if Arc::make_mut(&mut self.sessions).insert(key) {
262            true
263        } else {
264            let rolled_back = Arc::make_mut(&mut self.session_quota).release(peer);
265            debug_assert!(rolled_back);
266            false
267        }
268    }
269
270    fn remove_session(&mut self, key: &SessionKey) -> bool {
271        if !self.sessions.contains(key) {
272            return false;
273        }
274        if !Arc::make_mut(&mut self.session_quota).release(key.peer) {
275            debug_assert!(false, "session quota missing admitted peer {}", key.peer);
276            return false;
277        }
278        let removed = Arc::make_mut(&mut self.sessions).remove(key);
279        debug_assert!(removed);
280        removed
281    }
282}
283
284/// Transport relay protocol (server side), generic over the service target `T`.
285#[derive(Clone)]
286pub struct Relay<T> {
287    namespace: String,
288    kind: TransportKind,
289    /// Target type carried by the protocol algebra. Runtime registration is the sole source of
290    /// service mappings, so construction owns no second map.
291    marker: std::marker::PhantomData<fn() -> T>,
292}
293
294impl<T> Relay<T> {
295    /// Build a TCP relay with an initially empty runtime service registry.
296    pub fn tcp() -> Self {
297        Self {
298            namespace: TCP.to_string(),
299            kind: TransportKind::Tcp,
300            marker: std::marker::PhantomData,
301        }
302    }
303
304    /// Build a UDP relay with an initially empty runtime service registry.
305    pub fn udp() -> Self {
306        Self {
307            namespace: UDP.to_string(),
308            kind: TransportKind::Udp,
309            marker: std::marker::PhantomData,
310        }
311    }
312}
313
314impl<T> Protocol for Relay<T>
315where T: Clone + DeserializeOwned + Serialize + MaybeSendSync + 'static
316{
317    type State = RelayState<T>;
318    type Event = RelayEvent<T>;
319    type Effect = RelayEffect<T>;
320
321    fn namespace(&self) -> &str {
322        self.namespace.as_str()
323    }
324
325    fn init(&self) -> RelayState<T> {
326        RelayState::default()
327    }
328
329    fn decode(&self, wire: Wire<'_>) -> Result<RelayEvent<T>, Reject> {
330        if wire.from == wire.me {
331            let command = rings_codec::deserialize::<RelayCommand<T>>(wire.payload)
332                .map_err(|e| Reject(format!("bad relay command: {e}")))?;
333            Ok(RelayEvent::Command(command))
334        } else {
335            let frame = rings_codec::deserialize::<Frame>(wire.payload)
336                .map_err(|e| Reject(format!("bad relay frame: {e}")))?;
337            Ok(RelayEvent::Frame {
338                from: wire.from,
339                frame,
340            })
341        }
342    }
343
344    fn step(
345        &self,
346        ctx: Ctx<'_, RelayState<T>>,
347        event: RelayEvent<T>,
348    ) -> Transition<RelayState<T>, RelayEffect<T>> {
349        match event {
350            RelayEvent::Command(command) => {
351                step_command(self.namespace.as_str(), ctx.state, command)
352            }
353            RelayEvent::Frame { from, frame } => {
354                step_frame(self.kind, self.namespace.as_str(), ctx.state, from, frame)
355            }
356        }
357    }
358}
359
360/// Apply a local [`RelayCommand`]. Pure. `Accepted`/`Untrack` are the engine→protocol
361/// feedback that make `step` the sole authority over the session set **and its ids**: the
362/// core mints the id on `Accepted` (the engine reported only a local token) and forgets the
363/// session on `Untrack`.
364fn step_command<T: Clone>(
365    namespace: &str,
366    state: &RelayState<T>,
367    command: RelayCommand<T>,
368) -> Transition<RelayState<T>, RelayEffect<T>> {
369    let mut next = state.clone();
370    match command {
371        RelayCommand::RegisterService { name, target } => {
372            Arc::make_mut(&mut next.services).insert(name, target);
373            Transition::pure(next)
374        }
375        RelayCommand::Accepted {
376            token,
377            peer,
378            service,
379        } => {
380            // The core mints the session id (the engine reported only its local token), so
381            // id allocation is part of the pure state transition, not a shell decision.
382            let session = RelaySessionId(next.next_session);
383            let key = SessionKey::new(peer, namespace, session, Initiator::Local);
384            if !next.can_admit_session(&key) {
385                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
386            }
387            let Some(next_session) = next.next_session.checked_add(1) else {
388                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
389            };
390            next.next_session = next_session;
391            // A locally-accepted tunnel: we are the initiator.
392            if !next.insert_session(key.clone()) {
393                return Transition::with(next, vec![RelayEffect::RejectAccepted { token }]);
394            }
395            Transition::with(next, vec![RelayEffect::OpenAccepted {
396                token,
397                key,
398                service,
399            }])
400        }
401        RelayCommand::Untrack {
402            peer,
403            session,
404            initiator,
405        } => {
406            next.remove_session(&SessionKey::new(peer, namespace, session, initiator));
407            Transition::pure(next)
408        }
409        RelayCommand::Abort {
410            peer,
411            session,
412            initiator,
413        } => {
414            let key = SessionKey::new(peer, namespace, session, initiator);
415            if next.remove_session(&key) {
416                Transition::with(next, vec![RelayEffect::SendClose {
417                    to: peer,
418                    session,
419                    from_opener: matches!(initiator, Initiator::Local),
420                }])
421            } else {
422                Transition::pure(next)
423            }
424        }
425    }
426}
427
428/// Apply a network [`Frame`]. Pure; emits relay effects scoped to the authenticated `from`.
429fn step_frame<T: Clone>(
430    kind: TransportKind,
431    namespace: &str,
432    state: &RelayState<T>,
433    from: Did,
434    frame: Frame,
435) -> Transition<RelayState<T>, RelayEffect<T>> {
436    match frame {
437        // `Open` is always sent by the opener, so from our side the peer is the initiator.
438        Frame::Open { session, service } => {
439            let key = SessionKey::new(from, namespace, session, Initiator::Remote);
440            // A duplicate for a live session is silent. Rejected opens are not retained in pure
441            // state: the bounded interpreter outbox owns control-plane resource admission, so a
442            // historical failure cannot permanently consume protocol capacity.
443            if state.sessions.contains(&key) {
444                return Transition::pure(state.clone());
445            }
446            match state.services.get(service.as_str()) {
447                Some(target) => {
448                    let mut next = state.clone();
449                    if !next.can_admit_session(&key) {
450                        return rejected_open(next, key);
451                    }
452                    let target = target.clone();
453                    if !next.insert_session(key.clone()) {
454                        return rejected_open(next, key);
455                    }
456                    Transition::with(next, vec![RelayEffect::Connect { key, target, kind }])
457                }
458                None => rejected_open(state.clone(), key),
459            }
460        }
461        // Data/Shutdown/Close are guarded on the authoritative session set: the *reducer*
462        // decides whether the effect happens, not the engine table. `from_opener` (the
463        // sender opened it) flips to our initiator.
464        Frame::Data {
465            session,
466            from_opener,
467            seq,
468            bytes,
469        } => {
470            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
471            to_live_session(state, kind, TransportKind::Tcp, key, |key| {
472                RelayEffect::Write { key, seq, bytes }
473            })
474        }
475        Frame::Shutdown {
476            session,
477            from_opener,
478            sent,
479        } => {
480            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
481            to_live_session(state, kind, TransportKind::Tcp, key, |key| {
482                RelayEffect::Shutdown { key, sent }
483            })
484        }
485        Frame::Datagram {
486            session,
487            from_opener,
488            bytes,
489        } => {
490            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
491            to_live_session(state, kind, TransportKind::Udp, key, |key| {
492                RelayEffect::SendDatagram { key, bytes }
493            })
494        }
495        Frame::Close {
496            session,
497            from_opener,
498        } => {
499            let key = SessionKey::new(from, namespace, session, opener_to_initiator(from_opener));
500            if state.sessions.contains(&key) {
501                let mut next = state.clone();
502                next.remove_session(&key);
503                Transition::with(next, vec![RelayEffect::Close { key }])
504            } else {
505                Transition::pure(state.clone())
506            }
507        }
508    }
509}
510
511/// Reject a peer-opened session without allocating live-session or interpreter state.
512fn rejected_open<T>(
513    state: RelayState<T>,
514    key: SessionKey,
515) -> Transition<RelayState<T>, RelayEffect<T>> {
516    Transition::with(state, vec![RelayEffect::SendClose {
517        to: key.peer,
518        session: key.session,
519        // The peer opened it; this endpoint did not.
520        from_opener: false,
521    }])
522}
523
524/// Hand the session `key` its `effect` iff the relay's `kind` is the frame's `carrier` and the
525/// session is live; any other frame changes nothing.
526fn to_live_session<T: Clone>(
527    state: &RelayState<T>,
528    kind: TransportKind,
529    carrier: TransportKind,
530    key: SessionKey,
531    effect: impl FnOnce(SessionKey) -> RelayEffect<T>,
532) -> Transition<RelayState<T>, RelayEffect<T>> {
533    if kind == carrier && state.sessions.contains(&key) {
534        Transition::with(state.clone(), vec![effect(key)])
535    } else {
536        Transition::pure(state.clone())
537    }
538}
539
540/// Map a frame's `from_opener` (the **sender** opened the session) to our own [`Initiator`].
541fn opener_to_initiator(from_opener: bool) -> Initiator {
542    if from_opener {
543        Initiator::Remote
544    } else {
545        Initiator::Local
546    }
547}
548
549/// Encode a `Frame::Close` as bytes for an overlay send. `from_opener` is whether *we* (the
550/// sender of this close) opened the session.
551pub(crate) fn close_frame(
552    session: RelaySessionId,
553    from_opener: bool,
554) -> crate::error::Result<Bytes> {
555    let frame = Frame::Close {
556        session,
557        from_opener,
558    };
559    rings_codec::serialize(&frame)
560        .map(Bytes::from)
561        .map_err(|_| crate::error::Error::EncodeError)
562}
563
564// ── Native interpreter (OS sockets) ───────────────────────────────────────────────────
565
566/// Native relay interpreter: runs [`RelayEffect`]s over the OS-socket engine it owns. The
567/// engine uses the namespace-scoped [`Scope`] capability for both overlay sends and lifecycle
568/// feedback (`Accepted`/`Untrack`), so the engine has no `Processor` of its own.
569pub(crate) struct NativeRelay {
570    engine: Arc<crate::extension::transport::engine::TransportSessions>,
571    control_outbox: ControlOutbox,
572}
573
574impl NativeRelay {
575    /// Build over a shared engine.
576    pub(crate) fn new(engine: Arc<crate::extension::transport::engine::TransportSessions>) -> Self {
577        Self {
578            engine,
579            control_outbox: ControlOutbox::default(),
580        }
581    }
582
583    #[cfg(test)]
584    pub(crate) fn new_with_control_send_test_hook(
585        engine: Arc<crate::extension::transport::engine::TransportSessions>,
586        hook: Arc<ControlSendTestHook>,
587    ) -> Self {
588        Self {
589            engine,
590            control_outbox: ControlOutbox::with_test_hook(hook),
591        }
592    }
593}
594
595impl NativeRelay {
596    /// Deliver `outbound` to the session `key`'s local socket, as the reducer's feedback.
597    fn deliver(&self, key: SessionKey, outbound: Outbound) -> crate::error::Result<Vec<Bytes>> {
598        let admission = self.engine.deliver(&key, outbound);
599        enqueue_feedback::<std::net::SocketAddr>(key, admission)
600    }
601}
602
603#[async_trait::async_trait]
604impl Interpret for NativeRelay {
605    type Effect = RelayEffect<std::net::SocketAddr>;
606
607    async fn run(
608        &self,
609        scope: &EffectScope,
610        effect: RelayEffect<std::net::SocketAddr>,
611    ) -> crate::error::Result<Vec<Bytes>> {
612        match effect {
613            RelayEffect::Connect { key, target, kind } => {
614                let admission =
615                    self.engine
616                        .clone()
617                        .connect(scope.lifecycle(), key.clone(), target, kind);
618                return enqueue_feedback::<std::net::SocketAddr>(key, admission);
619            }
620            RelayEffect::Write { key, seq, bytes } => {
621                return self.deliver(key, Outbound::Segment { seq, bytes });
622            }
623            RelayEffect::SendDatagram { key, bytes } => {
624                return self.deliver(key, Outbound::Datagram(bytes));
625            }
626            RelayEffect::Shutdown { key, sent } => {
627                return self.deliver(key, Outbound::Shutdown { sent });
628            }
629            RelayEffect::Close { key } => {
630                self.engine.close_for_effect(&key);
631            }
632            RelayEffect::SendClose {
633                to,
634                session,
635                from_opener,
636            } => {
637                self.control_outbox.enqueue(
638                    scope.lifecycle(),
639                    to,
640                    close_frame(session, from_opener)?,
641                )?;
642            }
643            RelayEffect::OpenAccepted {
644                token,
645                key,
646                service,
647            } => {
648                let feedback =
649                    self.engine
650                        .clone()
651                        .bind_accepted(scope.lifecycle(), token, key, service);
652                return feedback
653                    .map(untrack_feedback::<std::net::SocketAddr>)
654                    .transpose()
655                    .map(|feedback| feedback.into_iter().collect());
656            }
657            RelayEffect::RejectAccepted { token } => {
658                self.engine.evict_pending_for_effect(token);
659            }
660        }
661        Ok(Vec::new())
662    }
663}
664
665/// Encode an engine teardown as the relay's synchronous, ordered feedback path.
666fn untrack_feedback<T: Serialize>(key: SessionKey) -> crate::error::Result<Bytes> {
667    let command = RelayCommand::<T>::Untrack {
668        peer: key.peer,
669        session: key.session,
670        initiator: key.initiator,
671    };
672    rings_codec::serialize(&command)
673        .map(Bytes::from)
674        .map_err(|_| crate::error::Error::EncodeError)
675}
676
677/// Encode a synchronous engine failure so the pure reducer owns both state
678/// removal and the exactly-once peer-facing terminal effect.
679fn abort_feedback<T: Serialize>(key: SessionKey) -> crate::error::Result<Bytes> {
680    let command = RelayCommand::<T>::Abort {
681        peer: key.peer,
682        session: key.session,
683        initiator: key.initiator,
684    };
685    rings_codec::serialize(&command)
686        .map(Bytes::from)
687        .map_err(|_| crate::error::Error::EncodeError)
688}
689
690/// Map backend admission into the relay reducer's ordered feedback algebra.
691fn enqueue_feedback<T: Serialize>(
692    key: SessionKey,
693    admission: EffectEnqueue,
694) -> crate::error::Result<Vec<Bytes>> {
695    match admission {
696        EffectEnqueue::Enqueued | EffectEnqueue::AlreadyPresent => Ok(Vec::new()),
697        EffectEnqueue::Missing => untrack_feedback::<T>(key).map(|feedback| vec![feedback]),
698        EffectEnqueue::Failed => abort_feedback::<T>(key).map(|feedback| vec![feedback]),
699    }
700}
701
702// ── Client-side relay handle ──────────────────────────────────────────────────────────
703
704/// Client-facing handle to the relay extension's live engine: open local tunnels and register
705/// local services. This is the relay extension's *own* surface — the relay owns its engine and
706/// installs itself ([`install`](RelayHandle::install)), so nothing about it leaks into the
707/// generic [`Provider`](crate::provider::Provider).
708/// Cloneable; every clone drives the same shared engine and pure [`Relay`] state.
709/// Holds the two per-namespace scoped capabilities (`tcp` / `udp`); each method picks one and
710/// can only act within it, so the handle cannot address an arbitrary namespace even internally.
711#[derive(Clone)]
712pub struct RelayHandle {
713    engine: Arc<crate::extension::transport::engine::TransportSessions>,
714    tcp: Scope,
715    udp: Scope,
716}
717
718impl RelayHandle {
719    /// Install the relay into an extension registry: register the TCP and UDP interpreters
720    /// over a fresh, relay-owned OS-socket engine and return the client handle. Errors if the
721    /// `tcp`/`udp` namespaces are already taken. Call once per node, after constructing the
722    /// provider — the relay is opt-in, not a `Provider` invariant.
723    pub fn install(extensions: &crate::extension::ext::Extensions) -> crate::error::Result<Self> {
724        let engine = Arc::new(crate::extension::transport::engine::TransportSessions::new());
725        // Atomic: both namespaces register together, or neither (no half-installed relay).
726        extensions.register_many(vec![
727            (Relay::tcp(), NativeRelay::new(engine.clone())),
728            (Relay::udp(), NativeRelay::new(engine.clone())),
729        ])?;
730        let core = extensions.core();
731        Ok(Self {
732            engine,
733            tcp: Scope::new(core.clone(), TCP.to_string()),
734            udp: Scope::new(core, UDP.to_string()),
735        })
736    }
737
738    /// Open a local **TCP** tunnel: bind `local_addr` and relay each accepted connection to
739    /// `peer`'s `service` (client side, forward proxy).
740    pub async fn open_tcp_tunnel(
741        &self,
742        local_addr: std::net::SocketAddr,
743        peer: Did,
744        service: String,
745    ) -> crate::error::Result<()> {
746        self.open_tunnel(&self.tcp, local_addr, peer, service, TransportKind::Tcp)
747            .await
748    }
749
750    /// Relay one already-accepted **TCP** stream to `peer`'s `service`. Returns once the relay
751    /// has taken the stream; the session runs on.
752    pub async fn relay_tcp_stream(
753        &self,
754        stream: tokio::net::TcpStream,
755        peer: Did,
756        service: String,
757    ) -> crate::error::Result<()> {
758        self.engine
759            .clone()
760            .relay_tcp_stream(self.tcp.clone(), stream, peer, service, Bytes::new(), None)
761            .await;
762        Ok(())
763    }
764
765    /// Relay one already-accepted **TCP** stream to `peer`'s `service`, `preamble` first, and
766    /// return once the relay is done with it: its session ended, or it was refused or never
767    /// opened. A caller that bounds its live connections holds its slot for this call.
768    pub async fn carry_tcp_stream(
769        &self,
770        stream: tokio::net::TcpStream,
771        peer: Did,
772        service: String,
773        preamble: Bytes,
774    ) -> crate::error::Result<()> {
775        let (hold, released) = crate::extension::transport::engine::StreamHold::new();
776        self.engine
777            .clone()
778            .relay_tcp_stream(
779                self.tcp.clone(),
780                stream,
781                peer,
782                service,
783                preamble,
784                Some(hold),
785            )
786            .await;
787        released.wait().await;
788        Ok(())
789    }
790
791    /// Open a local **UDP** tunnel: bind `local_addr` and relay each datagram flow to `peer`'s
792    /// `service` (client side, forward proxy).
793    pub async fn open_udp_tunnel(
794        &self,
795        local_addr: std::net::SocketAddr,
796        peer: Did,
797        service: String,
798    ) -> crate::error::Result<()> {
799        self.open_tunnel(&self.udp, local_addr, peer, service, TransportKind::Udp)
800            .await
801    }
802
803    async fn open_tunnel(
804        &self,
805        scope: &Scope,
806        local_addr: std::net::SocketAddr,
807        peer: Did,
808        service: String,
809        kind: TransportKind,
810    ) -> crate::error::Result<()> {
811        // Bind a local listener on the relay engine with this namespace's scope. Each accepted
812        // connection is reported back through the pure relay (`Accepted`), so
813        // `RelayState.sessions` stays the sole authority.
814        self.engine
815            .clone()
816            .listen(scope.clone(), local_addr, peer, service, kind)
817            .await
818    }
819
820    /// Register (at runtime) a local service the **TCP** relay may dial (`name` → `addr`).
821    pub async fn register_tcp_service(
822        &self,
823        name: String,
824        addr: std::net::SocketAddr,
825    ) -> crate::error::Result<()> {
826        register_service(&self.tcp, name, addr).await
827    }
828
829    /// Register (at runtime) a local service the **UDP** relay may dial (`name` → `addr`).
830    pub async fn register_udp_service(
831        &self,
832        name: String,
833        addr: std::net::SocketAddr,
834    ) -> crate::error::Result<()> {
835        register_service(&self.udp, name, addr).await
836    }
837}
838
839/// Map a service `name` → `target` by self-injecting a `RegisterService` command into the
840/// scope's own namespace (provenance = self).
841async fn register_service<T>(scope: &Scope, name: String, target: T) -> crate::error::Result<()>
842where T: Serialize {
843    let command = RelayCommand::RegisterService { name, target };
844    let payload = rings_codec::serialize(&command).map_err(|_| crate::error::Error::EncodeError)?;
845    scope.inject(Bytes::from(payload)).await
846}
847
848#[cfg(test)]
849mod test_relay;