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
//! Transport relay — one abstraction for TCP, HTTP and (future) UDP.
//!
//! # Why these are *not* three protocols
//!
//! The rings overlay (DHT + swarm + backend envelopes) provides an **authenticated,
//! bidirectional message channel between two DIDs** — call it the *virtual circuit*. It is
//! best effort: a full application inbox or namespace queue drops a message, counted, and a
//! frame held on an unresolved delegation reference may be overtaken by later frames of its
//! stream. A relay that promises a reliable byte stream therefore sequences its frames and
//! resets the stream on a loss it cannot repair (see [`Frame::Data`]). TCP / HTTP / UDP
//! "services" are all the **same thing**: a *relay* that maps a local I/O resource (a
//! socket) onto that virtual circuit. They differ only in the shape of the local resource,
//! along three axes:
//!
//! ```text
//! axis TCP HTTP UDP
//! ---------------------- ----------------- --------------------- ------------------
//! session cardinality ω (endless stream) 1 (one req/resp, 0 (no session,
//! affine: Req ⊸ Resp) datagrams)
//! framing byte stream HTTP messages datagrams
//! lifecycle open → data* → close open → 1×req → 1×resp none
//! → close
//! ordering / reliability ordered, reliable ordered, reliable unordered, lossy
//! (semantics chosen
//! when tunnelled)
//! ```
//!
//! Categorically they are one structure at three points of a single "session
//! cardinality" axis:
//!
//! - **TCP** = a bidirectional byte **stream** — the cofree stream / a long-lived
//! process; cardinality **ω**.
//! - **HTTP** = the **affine** degeneration of TCP: exactly one exchange
//! `Request ⊸ Response` (a use-once session); cardinality **1**.
//! - **UDP** = the **0-session** degeneration: `Datagram → [Datagram]`, a discrete
//! transducer with no lifecycle; cardinality **0**.
//!
//! So adding UDP later is not a fourth subsystem — it is this axis taken to 0.
//!
//! # How it sits on the effect base (`backend::ext`)
//!
//! Pure/effect separation is preserved:
//!
//! - The **interpreter owns the live resources** (the `TcpStream` / `UdpSocket`), keyed
//! by [`RelaySessionId`], in a resource table. These are non-purifiable OS handles and so
//! live only in the imperative shell — never in a protocol's state.
//! - A protocol's **pure `step`** holds only session *metadata* (which `RelaySessionId` maps
//! to which peer/service, framing state, counters) — never a live socket.
//! - Generic transport **effects** (run by the interpreter): stream ops
//! `Connect` / `Write` / `Close`; datagram ops `Bind` / `SendTo`.
//! - Local reads / accepts **re-inject** [`Frame`]s as events (the event trace of the
//! effect monad): the read task feeds `Data` / `Close` / `Datagram` back through the
//! router → `step` → an `Effect::Send` over the virtual circuit.
//!
//! TCP / HTTP / UDP are then thin instances over this one relay: TCP uses the stream
//! ops with an ω session; HTTP adds "one request → one response → close" session logic
//! (expressible purely in `step`); UDP uses only the datagram ops with no session.
// The relay's imperative resource tables are private to the relay interpreter — not a public
// API. Reachable in-crate by the relay extension only.
pub
use AtomicU64;
use Ordering;
use Duration;
use Bytes;
use Did;
use Deserialize;
use Serialize;
/// Maximum silence before an abandoned local socket/flow is reclaimed.
pub const RELAY_IDLE_TIMEOUT: Duration = from_secs;
/// Allocate one counter value without ever wrapping back to a live ABA-equivalent value.
pub
/// Identifier assigned by the opener to a relayed stream or datagram flow (a virtual circuit
/// ↔ local socket pairing). This relay identifier is distinct from delegated-signing identity.
///
/// TCP uses it for a connection; UDP uses it for a *flow* (a NAT-like mapping that
/// routes responses back to the right local client) — see [`TransportKind`].
;
/// Which end **opened** a relay session, from the perspective of the node holding the key.
///
/// Necessary because two nodes that simultaneously open a tunnel to each other both mint
/// `RelaySessionId(0)`: without an initiator, "the session I opened to peer B" and "the session B
/// opened to me" would collide on `(peer=B, namespace, session=0)`, and a wire `Data(0)`
/// would be ambiguous. The initiator splits the id space into two halves per `(peer,
/// namespace)`.
/// Result of applying one ordered peer-to-local transport effect without
/// waiting for backend backpressure.
pub
/// Result of trying to reserve one unique backend slot.
pub
/// A relay session's full identity — the unit used to key live sessions and to address
/// transport effects.
///
/// A bare [`RelaySessionId`] is **not** a valid address: the id on the wire is assigned by the
/// opener, so two ends can both pick `RelaySessionId(0)`. The key scopes a session by `(peer,
/// namespace, session, initiator)`, where `peer` is the **authenticated** other end
/// (`event.from`, the verified signer) and `initiator` records which end opened it. Because a
/// peer cannot forge `event.from`, it can only ever address sessions whose `peer` is itself
/// (owner rejection); and `initiator` keeps a peer's session distinct from one of ours that
/// happened to get the same id (bidirectional-open safety).
/// Which local socket a relay session is backed by.
///
/// Both kinds share the same [`Frame`] vocabulary (`Open`/`Data`/`Close`); only the
/// socket differs. UDP is *flow*-based rather than truly sessionless because a relayed
/// datagram still needs a return path to the originating local client, so each flow
/// carries a [`RelaySessionId`] just like a TCP connection. `Data` preserves message
/// boundaries (one datagram per frame) for UDP.
/// The relay's overlay wire message — the payload carried under a transport namespace.
///
/// One vocabulary for both kinds (TCP connections and UDP flows), differing only in how the
/// bytes travel:
///
/// ```text
/// TCP Open(session, service) → Data(session, seq, bytes)* → Shutdown(session, sent)
/// → Close(session)
/// UDP Open(session, service) → Datagram(session, bytes)* → Close(session)
/// ```
///
/// Law (no silent gap). A TCP direction's `Data` frames carry `seq = 0, 1, 2, …` and its
/// `Shutdown` carries the number `sent` of them. The receiver writes bytes to its local socket
/// in `seq` order only, reordering at most [`REORDER_WINDOW`] frames ahead, so the local
/// stream is always a prefix of what the peer sent. A frame missing for [`REORDER_DEADLINE`] is
/// past the delivery bounds of its path, and one more than the window behind can never arrive
/// (the replay window refuses it), so either way the receiver resets the session: the peer gets
/// `Close`, and the local socket an abortive close. A `Shutdown` is applied only once every one
/// of its `sent` frames was written, so a lost last frame is a reset, never a clean end of
/// stream.
///
/// [`REORDER_WINDOW`]: rings_core::message::REORDER_WINDOW
/// [`REORDER_DEADLINE`]: rings_core::message::REORDER_DEADLINE
///
/// `Open` is always sent by the session's opener. `Data`/`Shutdown`/`Close` flow in both
/// directions over the *same* opener-assigned id, so they carry `from_opener` — whether the
/// **sender** of this frame opened the session. The receiver flips it to recover its own
/// [`Initiator`], so a peer's session never collides with one of ours sharing the same id.