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
use std::collections::HashMap;
use std::sync::Arc;
use bytes::Bytes;
use tokio::sync::{
mpsc,
oneshot,
};
use tokio_util::sync::CancellationToken;
use super::commands::{
MuxCommand,
StreamRegistration,
};
use super::window::SendWindow;
use super::{
RST_STATUS_CANCEL,
RST_STATUS_FLOW_CONTROL,
RST_STATUS_INVALID_STREAM,
};
use crate::codec::Frame;
use crate::error::Error;
/// Per-stream state owned exclusively by one frame worker.
pub(super) struct StreamState {
/// Data sender. `None` after remote FIN (half-close).
data_tx: Option<mpsc::Sender<Bytes>>,
send_window: Arc<SendWindow>,
/// Bytes delivered to the per-stream channel since the last
/// WINDOW_UPDATE was sent.
consumed_since_update: u64,
}
/// Owns a shard of streams partitioned by `stream_id % FRAME_WORKERS`.
/// No shared mutable state across workers.
///
/// Drains `close_reg_rx` (close registrations) before `reg_rx` (open
/// registrations) so teardown is never blocked by a burst of opens.
#[allow(clippy::too_many_arguments)]
pub(super) async fn run_frame_worker(
worker_id: usize, mut frame_rx: mpsc::Receiver<Frame>,
mut reg_rx: mpsc::Receiver<StreamRegistration>,
mut close_reg_rx: mpsc::Receiver<StreamRegistration>, control_tx: mpsc::Sender<MuxCommand>,
window_tx: mpsc::Sender<MuxCommand>, cancel: CancellationToken, initial_window_size: u32,
) {
let mut streams: HashMap<u32, StreamState> = HashMap::new();
let mut pending_replies: HashMap<u32, oneshot::Sender<Result<(), Error>>> = HashMap::new();
loop {
// drain close registrations first (non-blocking, priority).
while let Ok(reg) = close_reg_rx.try_recv() {
apply_registration(reg, &mut streams, &mut pending_replies, &control_tx);
}
// drain any pending open registrations (non-blocking) to ensure
// Open registrations are applied before any frames for that stream.
while let Ok(reg) = reg_rx.try_recv() {
apply_registration(reg, &mut streams, &mut pending_replies, &control_tx);
}
tokio::select! {
biased;
() = cancel.cancelled() => break,
// close registrations have priority over opens.
reg = close_reg_rx.recv() => match reg {
Some(r) => apply_registration(r, &mut streams, &mut pending_replies, &control_tx),
None => break,
},
// open registrations checked before frames.
reg = reg_rx.recv() => match reg {
Some(r) => apply_registration(r, &mut streams, &mut pending_replies, &control_tx),
None => break,
},
frame = frame_rx.recv() => match frame {
Some(f) => dispatch_frame_in_worker(
f, &mut streams, &mut pending_replies,
&control_tx, &window_tx, initial_window_size,
),
None => break,
},
}
}
// shutdown: fail all pending replies, poison all send windows.
let orphaned_streams = streams.len();
let orphaned_replies = pending_replies.len();
if orphaned_streams > 0 || orphaned_replies > 0 {
tracing::debug!(
worker_id,
orphaned_streams,
orphaned_replies,
"worker shutting down with in-flight streams"
);
}
for (_, reply_tx) in pending_replies.drain() {
let _ = reply_tx.send(Err(Error::MuxClosed));
}
for (_, state) in streams.drain() {
state.send_window.close();
}
}
/// Dispatches a decoded SPDY frame within a worker. Handles only stream-keyed
/// frames. Entirely synchronous and never blocks.
pub(super) fn dispatch_frame_in_worker(
frame: Frame, streams: &mut HashMap<u32, StreamState>,
pending_replies: &mut HashMap<u32, oneshot::Sender<Result<(), Error>>>,
cmd_tx: &mpsc::Sender<MuxCommand>, window_tx: &mpsc::Sender<MuxCommand>,
initial_window_size: u32,
) {
match frame {
Frame::Data {
stream_id,
payload,
fin,
} => {
if !payload.is_empty() {
let payload_len = payload.len() as u64;
// session-level recv window is tracked by the reader (not here).
let mut remove = false;
if let Some(state) = streams.get_mut(&stream_id) {
// Only send data if the data_tx is still open (not half-closed)
if let Some(ref data_tx) = state.data_tx {
match data_tx.try_send(payload) {
Ok(()) => {
// track consumed bytes since last per-stream WINDOW_UPDATE.
state.consumed_since_update += payload_len;
if state.consumed_since_update >= (initial_window_size / 2) as u64 {
let delta = state.consumed_since_update as u32;
// only reset on success; if the channel is full,
// accumulate and retry on the next DATA frame.
if window_tx
.try_send(MuxCommand::EncodeWindowUpdate {
stream_id,
delta,
})
.is_ok()
{
state.consumed_since_update = 0;
}
}
}
Err(mpsc::error::TrySendError::Full(_)) => {
// on buffer-full: do NOT send RST_STREAM. Stop draining frame_rx
// instead; the reader backs up, TCP
// applies backpressure to the peer, the peer slows down. The frame
// is "lost" for this try, but the per-stream recv window is not
// replenished (no WINDOW_UPDATE),
// so the peer naturally pauses sending to this
// stream.
tracing::debug!(
stream_id,
"SPDY stream buffer full, applying backpressure (not RST)"
);
}
Err(mpsc::error::TrySendError::Closed(_)) => {
remove = true;
}
}
}
// if data_tx is None (half-closed), silently ignore. The
// stream entry is kept for WINDOW_UPDATE processing.
} else {
// trace level: routinely fires during connection teardown when
// late DATA frames arrive for streams we've already closed.
// the RST_STREAM response is correct per SPDY spec; only the
// log noise is undesirable at DEBUG.
tracing::trace!(
stream_id,
"SPDY DATA for unknown stream, sending RST_STREAM"
);
let _ = cmd_tx.try_send(MuxCommand::CloseStream {
stream_id,
status: RST_STATUS_INVALID_STREAM,
});
}
if remove {
streams.remove(&stream_id);
let _ = cmd_tx.try_send(MuxCommand::CloseStream {
stream_id,
status: RST_STATUS_FLOW_CONTROL,
});
return;
}
}
// half-close: remote FIN means peer is done sending. Close our data Sender so
// the consumer reads EOF, but keep the stream entry alive for
// outgoing WINDOW_UPDATE processing. Full cleanup happens when
// StreamGuard fires Close.
if fin {
if let Some(state) = streams.get_mut(&stream_id) {
tracing::debug!(stream_id, "SPDY DATA FIN received, half-closing read side");
state.data_tx = None;
}
}
}
Frame::SynReply {
stream_id,
headers,
fin,
} => {
tracing::debug!(
stream_id,
num_headers = headers.len(),
fin,
"SPDY SYN_REPLY received"
);
if let Some(reply_tx) = pending_replies.remove(&stream_id) {
let _ = reply_tx.send(Ok(()));
} else if !streams.contains_key(&stream_id) {
let _ = cmd_tx.try_send(MuxCommand::CloseStream {
stream_id,
status: RST_STATUS_INVALID_STREAM,
});
}
// half-close on SYN_REPLY with FIN
if fin {
if let Some(state) = streams.get_mut(&stream_id) {
state.data_tx = None;
}
}
}
Frame::RstStream { stream_id, status } => {
// poison the send window so any in-progress poll_write on this
// stream returns BrokenPipe immediately. Critical for the
// no-SYN_REPLY-wait path: if the server rejects the stream
// via RST_STREAM, the caller learns through the poisoned window,
// not through an awaited oneshot.
tracing::debug!(stream_id, status, "SPDY RST_STREAM received");
if let Some(state) = streams.remove(&stream_id) {
state.send_window.close();
}
if let Some(reply_tx) = pending_replies.remove(&stream_id) {
let _ = reply_tx.send(Err(Error::StreamReset(stream_id, status)));
}
}
Frame::WindowUpdate {
stream_id,
delta_window_size,
} => {
// only per-stream WINDOW_UPDATEs reach workers (stream_id == 0
// is handled by the reader directly).
if let Some(state) = streams.get(&stream_id) {
state.send_window.replenish(delta_window_size);
}
// else: stream already closed, harmless.
}
// other frame types should not reach workers.
_ => {}
}
}
pub(super) fn apply_registration(
reg: StreamRegistration, streams: &mut HashMap<u32, StreamState>,
pending_replies: &mut HashMap<u32, oneshot::Sender<Result<(), Error>>>,
cmd_tx: &mpsc::Sender<MuxCommand>,
) {
match reg {
StreamRegistration::Open {
stream_id,
data_tx,
reply_tx,
send_window,
} => {
streams.insert(
stream_id,
StreamState {
data_tx: Some(data_tx),
send_window,
consumed_since_update: 0,
},
);
pending_replies.insert(stream_id, reply_tx);
}
StreamRegistration::Close { stream_id } => {
if let Some(state) = streams.remove(&stream_id) {
state.send_window.close();
}
pending_replies.remove(&stream_id);
}
StreamRegistration::SettingsWindowDelta { delta } => {
for state in streams.values() {
state.send_window.apply_delta(delta);
}
}
StreamRegistration::GoAway {
last_good_stream_id,
status,
} => {
// clean up streams with id > last_good_stream_id in this shard.
let bad_ids: Vec<u32> = streams
.keys()
.filter(|&&id| id > last_good_stream_id)
.copied()
.collect();
for id in bad_ids {
if let Some(state) = streams.remove(&id) {
state.send_window.close();
}
if let Some(reply_tx) = pending_replies.remove(&id) {
let _ = reply_tx.send(Err(Error::GoAway {
last_good_stream_id,
status,
}));
}
let _ = cmd_tx.try_send(MuxCommand::CloseStream {
stream_id: id,
status: RST_STATUS_CANCEL,
});
}
}
}
}