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
//! Stream Demultiplexer
//!
//! Routes incoming packets to their target streams based on `stream_id`
//! extracted from `PhantomPacket` headers. Replaces the old smoltcp-based
//! multiplexer with a lightweight, zero-copy routing table.
use crate::transport::types::SequenceNumber;
use bytes::Bytes;
use dashmap::DashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use tokio::sync::mpsc;
/// Messages routed to a stream by the demultiplexer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamMessage {
/// Normal data payload
Data(Bytes),
/// Acknowledgment of a specific sequence number
Ack(SequenceNumber),
/// Stream closure signal
Close,
}
/// A lightweight stream demultiplexer that routes packets to registered streams.
///
/// # Design
///
/// ```text
/// UDP Socket → StreamDemultiplexer → Stream[0] (reliable)
/// → Stream[1] (reliable)
/// → Stream[2] (unreliable)
/// → control channel
/// ```
///
/// Each stream is identified by a `u32` stream ID extracted from the packet header.
/// Unrecognized stream IDs are dropped (with a log warning).
pub struct StreamDemultiplexer {
/// Active stream senders: stream_id → sender channel
streams: DashMap<u32, mpsc::Sender<StreamMessage>>,
/// Control channel for session-level messages (stream_id = 0)
control_tx: mpsc::Sender<Bytes>,
/// Next stream ID to allocate
next_stream_id: AtomicU32,
}
/// Handle returned when a stream is registered with the demultiplexer.
pub struct StreamHandle {
/// The stream ID assigned to this stream
pub stream_id: u32,
/// Receiver end for incoming packets
pub rx: mpsc::Receiver<StreamMessage>,
}
impl StreamDemultiplexer {
/// Create a new demultiplexer with a control channel.
///
/// The control channel (stream_id = 0) receives session-level packets
/// such as keepalives, migration signals, and stream management.
pub fn new(control_buffer: usize) -> (Self, mpsc::Receiver<Bytes>) {
let (control_tx, control_rx) = mpsc::channel(control_buffer);
let mux = Self {
streams: DashMap::new(),
control_tx,
next_stream_id: AtomicU32::new(2), // 0 = control, 1 = raw-app session channel
};
(mux, control_rx)
}
/// Register a new stream and get back a handle with the assigned ID.
///
/// `buffer_size` controls the depth of the per-stream receive buffer.
pub fn open_stream(&self, buffer_size: usize) -> StreamHandle {
let stream_id = self.next_stream_id.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::channel(buffer_size);
self.streams.insert(stream_id, tx);
StreamHandle { stream_id, rx }
}
/// Register a stream with a specific ID (e.g., for accepting remote-initiated streams).
pub fn register_stream(&self, stream_id: u32, buffer_size: usize) -> StreamHandle {
let (tx, rx) = mpsc::channel(buffer_size);
self.streams.insert(stream_id, tx);
// Update next_stream_id if necessary to avoid collisions
let _ = self
.next_stream_id
.fetch_max(stream_id + 1, Ordering::Relaxed);
StreamHandle { stream_id, rx }
}
/// Remove a stream from the routing table.
pub fn close_stream(&self, stream_id: u32) {
self.streams.remove(&stream_id);
}
/// Route data payload to the appropriate stream.
///
/// Returns `true` if the packet was successfully delivered,
/// `false` if the stream was not found or the buffer was full.
pub fn route_data(&self, stream_id: u32, payload: Bytes) -> bool {
if stream_id == 0 {
// Control channel
return self.control_tx.try_send(payload).is_ok();
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.try_send(StreamMessage::Data(payload)).is_ok()
} else {
log::warn!(
"StreamDemultiplexer: dropping data for unknown stream_id={}",
stream_id
);
false
}
}
/// Route data asynchronously (waits if buffer is full).
pub async fn route_data_async(&self, stream_id: u32, payload: Bytes) -> bool {
if stream_id == 0 {
return self.control_tx.send(payload).await.is_ok();
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.send(StreamMessage::Data(payload)).await.is_ok()
} else {
log::warn!(
"StreamDemultiplexer: dropping data for unknown stream_id={}",
stream_id
);
false
}
}
/// Route an ACK signal to a stream **without blocking**. Returns
/// `false` if the stream is unknown or its buffer is full — the recv pump
/// uses this on its never-block path, where a vestigial/absent stream
/// consumer must not stall inbound ACK/control processing.
pub fn route_ack(&self, stream_id: u32, seq: SequenceNumber) -> bool {
if stream_id == 0 {
return false;
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.try_send(StreamMessage::Ack(seq)).is_ok()
} else {
false
}
}
/// Route a stream-closure signal **without blocking** (see [`Self::route_ack`]).
pub fn route_close(&self, stream_id: u32) -> bool {
if stream_id == 0 {
return false;
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.try_send(StreamMessage::Close).is_ok()
} else {
false
}
}
/// Route an ACK signal to a stream asynchronously.
pub async fn route_ack_async(&self, stream_id: u32, seq: SequenceNumber) -> bool {
if stream_id == 0 {
return false;
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.send(StreamMessage::Ack(seq)).await.is_ok()
} else {
log::warn!(
"StreamDemultiplexer: dropping ACK for unknown stream_id={}",
stream_id
);
false
}
}
/// Route a stream closure signal asynchronously.
pub async fn route_close_async(&self, stream_id: u32) -> bool {
if stream_id == 0 {
return false;
}
if let Some(sender) = self.streams.get(&stream_id) {
sender.send(StreamMessage::Close).await.is_ok()
} else {
log::warn!(
"StreamDemultiplexer: dropping CLOSE for unknown stream_id={}",
stream_id
);
false
}
}
/// Number of active streams (excluding control channel).
pub fn active_stream_count(&self) -> usize {
self.streams.len()
}
/// Check if a stream is registered.
pub fn has_stream(&self, stream_id: u32) -> bool {
self.streams.contains_key(&stream_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_demux_open_and_route() {
let (demux, _ctrl_rx) = StreamDemultiplexer::new(16);
let handle = demux.open_stream(16);
let sid = handle.stream_id;
let mut rx = handle.rx;
assert!(demux.has_stream(sid));
assert_eq!(demux.active_stream_count(), 1);
// Route a packet
let data = Bytes::from_static(b"hello stream");
assert!(demux.route_data(sid, data.clone()));
// Receive it
let received = rx.recv().await.unwrap();
assert_eq!(received, StreamMessage::Data(data));
}
#[tokio::test]
async fn test_demux_control_channel() {
let (demux, mut ctrl_rx) = StreamDemultiplexer::new(16);
let data = Bytes::from_static(b"control msg");
assert!(demux.route_data(0, data.clone()));
let received = ctrl_rx.recv().await.unwrap();
assert_eq!(received, data);
}
#[tokio::test]
async fn test_demux_unknown_stream() {
let (demux, _ctrl_rx) = StreamDemultiplexer::new(16);
// Route to non-existent stream
let data = Bytes::from_static(b"lost");
assert!(!demux.route_data(999, data));
}
#[tokio::test]
async fn test_demux_close_stream() {
let (demux, _ctrl_rx) = StreamDemultiplexer::new(16);
let handle = demux.open_stream(16);
let sid = handle.stream_id;
assert!(demux.has_stream(sid));
demux.close_stream(sid);
assert!(!demux.has_stream(sid));
assert_eq!(demux.active_stream_count(), 0);
}
#[tokio::test]
async fn test_demux_multiple_streams() {
let (demux, _ctrl_rx) = StreamDemultiplexer::new(16);
let h1 = demux.open_stream(16);
let h2 = demux.open_stream(16);
let h3 = demux.open_stream(16);
assert_ne!(h1.stream_id, h2.stream_id);
assert_ne!(h2.stream_id, h3.stream_id);
assert_eq!(demux.active_stream_count(), 3);
}
}