kino 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +286 -0
- data/Cargo.lock +209 -132
- data/README.md +269 -438
- data/doc/README.md +27 -2
- data/doc/architecture.md +862 -43
- data/doc/benchmarks.md +444 -214
- data/doc/configuration.md +215 -0
- data/doc/operations.md +258 -0
- data/doc/rails-on-ractors.md +161 -49
- data/doc/streaming.md +52 -0
- data/doc/websockets.md +469 -0
- data/doc/why-kino.md +6 -6
- data/doc/worker-loop.md +462 -0
- data/ext/kino/Cargo.toml +19 -3
- data/ext/kino/build.rs +32 -1
- data/ext/kino/clippy.toml +10 -0
- data/ext/kino/src/access_log.rs +70 -92
- data/ext/kino/src/control.rs +26 -685
- data/ext/kino/src/counters.rs +132 -0
- data/ext/kino/src/cpus.rs +1 -18
- data/ext/kino/src/dispatch/tests.rs +731 -0
- data/ext/kino/src/dispatch.rs +276 -0
- data/ext/kino/src/doorbell.rs +108 -0
- data/ext/kino/src/env_strings.rs +26 -30
- data/ext/kino/src/framing.rs +110 -0
- data/ext/kino/src/gvl.rs +292 -66
- data/ext/kino/src/hijack/tests.rs +416 -0
- data/ext/kino/src/hijack.rs +471 -0
- data/ext/kino/src/inline/answer.rs +488 -0
- data/ext/kino/src/inline/conn.rs +1124 -0
- data/ext/kino/src/inline/deadline.rs +421 -0
- data/ext/kino/src/inline/encode.rs +119 -0
- data/ext/kino/src/inline/io.rs +487 -0
- data/ext/kino/src/inline/mod.rs +766 -0
- data/ext/kino/src/inline/parity.rs +862 -0
- data/ext/kino/src/inline/parse.rs +131 -0
- data/ext/kino/src/inline/spin.rs +428 -0
- data/ext/kino/src/inline/testing.rs +628 -0
- data/ext/kino/src/io_shards.rs +240 -192
- data/ext/kino/src/lane_room.rs +99 -0
- data/ext/kino/src/lib.rs +139 -77
- data/ext/kino/src/listen.rs +180 -12
- data/ext/kino/src/log.rs +12 -47
- data/ext/kino/src/logsink.rs +3 -9
- data/ext/kino/src/mono.rs +12 -17
- data/ext/kino/src/pin.rs +3 -3
- data/ext/kino/src/queue/mod.rs +54 -0
- data/ext/kino/src/queue/take.rs +503 -0
- data/ext/kino/src/queue/testing.rs +107 -0
- data/ext/kino/src/queue/tests.rs +581 -0
- data/ext/kino/src/queue/worker.rs +501 -0
- data/ext/kino/src/registry.rs +168 -379
- data/ext/kino/src/request.rs +834 -235
- data/ext/kino/src/response.rs +532 -94
- data/ext/kino/src/server/accept.rs +322 -0
- data/ext/kino/src/server/config.rs +138 -0
- data/ext/kino/src/server/handle.rs +247 -0
- data/ext/kino/src/server/intake.rs +217 -0
- data/ext/kino/src/server/mod.rs +157 -0
- data/ext/kino/src/server/natives.rs +223 -0
- data/ext/kino/src/server/serve/intake_tests.rs +458 -0
- data/ext/kino/src/server/serve.rs +436 -0
- data/ext/kino/src/server/tests.rs +532 -0
- data/ext/kino/src/shared_gvl.rs +50 -0
- data/ext/kino/src/slot/lane.rs +138 -0
- data/ext/kino/src/slot/life.rs +111 -0
- data/ext/kino/src/slot/load.rs +193 -0
- data/ext/kino/src/slot/mod.rs +494 -0
- data/ext/kino/src/slot/park.rs +82 -0
- data/ext/kino/src/stats.rs +936 -0
- data/ext/kino/src/symbols.rs +66 -0
- data/ext/kino/src/test_support.rs +24 -14
- data/ext/kino/src/testing.rs +409 -0
- data/ext/kino/src/ticker.rs +87 -0
- data/ext/kino/src/timer.rs +4 -7
- data/ext/kino/src/tls.rs +101 -131
- data/ext/kino/src/typed_data.rs +131 -0
- data/ext/kino/src/upgrade.rs +77 -0
- data/ext/kino/src/ws/codec.rs +470 -0
- data/ext/kino/src/ws/drive.rs +600 -0
- data/ext/kino/src/ws/handshake.rs +267 -0
- data/ext/kino/src/ws/mod.rs +317 -0
- data/ext/kino/src/ws/server_tests.rs +759 -0
- data/ext/kino/src/ws/socket.rs +279 -0
- data/ext/kino/src/ws/stats.rs +88 -0
- data/ext/kino/src/ws/testing.rs +156 -0
- data/ext/kino/src/ws/topics.rs +550 -0
- data/lib/kino/cli.rb +100 -9
- data/lib/kino/configuration.rb +32 -10
- data/lib/kino/crash_backoff.rb +56 -0
- data/lib/kino/input.rb +36 -17
- data/lib/kino/log.rb +8 -1
- data/lib/kino/monitor.rb +1 -1
- data/lib/kino/pool.rb +169 -0
- data/lib/kino/pool_scaler.rb +12 -13
- data/lib/kino/quarantine_monitor.rb +3 -3
- data/lib/kino/ractor_supervisor.rb +201 -161
- data/lib/kino/server.rb +291 -185
- data/lib/kino/slot_bank.rb +21 -9
- data/lib/kino/stream.rb +2 -2
- data/lib/kino/teardown.rb +33 -0
- data/lib/kino/templates/kino.rb.tt +41 -6
- data/lib/kino/threaded_pool.rb +87 -102
- data/lib/kino/version.rb +1 -1
- data/lib/kino/web_socket.rb +125 -0
- data/lib/kino/worker/loop.rb +319 -0
- data/lib/kino/worker.rb +345 -79
- data/lib/kino/worker_hooks.rb +7 -1
- data/lib/kino/worker_row.rb +15 -0
- data/lib/kino.rb +27 -3
- data/lib/rackup/handler/kino.rb +1 -1
- data/sig/kino.rbs +93 -10
- metadata +66 -3
- data/ext/kino/src/queue.rs +0 -333
- data/ext/kino/src/server.rs +0 -1785
|
@@ -0,0 +1,1124 @@
|
|
|
1
|
+
//! An inline connection's reader: its socket, its read buffer and its looks for the next request.
|
|
2
|
+
|
|
3
|
+
use std::io::{ErrorKind, Read};
|
|
4
|
+
use std::os::fd::{AsRawFd, RawFd};
|
|
5
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
6
|
+
use std::sync::Arc;
|
|
7
|
+
use std::time::Duration;
|
|
8
|
+
|
|
9
|
+
use bytes::Bytes;
|
|
10
|
+
use parking_lot::Mutex;
|
|
11
|
+
|
|
12
|
+
use super::answer::Current;
|
|
13
|
+
use super::io::{close, forget, micros, Deadline, InlineIo, IoState, Listed, Origin, Seat, Waits};
|
|
14
|
+
use super::parse::{parse_head, Head, Parsed, HEAD_MAX};
|
|
15
|
+
use super::spin::{Backoff, Release, Run, Spin};
|
|
16
|
+
use super::INLINE_BODY_MAX;
|
|
17
|
+
use crate::access_log::Logged;
|
|
18
|
+
use crate::registry::{BoxedCtx, ServerInner};
|
|
19
|
+
use crate::request::RequestCtx;
|
|
20
|
+
use crate::response::{Cut, Responder};
|
|
21
|
+
use crate::server::{Held, InFlight, Peer, StdConn, BODY_READ_TIMEOUT, HEADER_READ_TIMEOUT};
|
|
22
|
+
use crate::slot::WorkerSlot;
|
|
23
|
+
|
|
24
|
+
/// A plain TCP or unix connection served inline, owned by its worker's job.
|
|
25
|
+
pub struct InlineConn {
|
|
26
|
+
pub(super) io: Arc<InlineIo>,
|
|
27
|
+
/// Read and not consumed yet; HEAD_MAX long except while a longer body is read (read_body).
|
|
28
|
+
buf: Box<[u8]>,
|
|
29
|
+
len: usize,
|
|
30
|
+
pending: Option<Head>,
|
|
31
|
+
/// IoState::unparsed as its job last set it: a look locks to clear it only if set.
|
|
32
|
+
unparsed: bool,
|
|
33
|
+
/// It ran a request, so its next head is not its first (the drain ends it mid-head).
|
|
34
|
+
served: bool,
|
|
35
|
+
/// A request went to the app since its job last looked: that look waits its turn (wait_turn).
|
|
36
|
+
after_request: bool,
|
|
37
|
+
/// Likewise: that look decides whether the job steps aside first (yield_turn).
|
|
38
|
+
yield_due: bool,
|
|
39
|
+
/// It may spin for its next request (spin_for_next): as it opens and after each request.
|
|
40
|
+
spin_due: bool,
|
|
41
|
+
/// The spin's budget (InlineServer::spin_budget), read once at accept.
|
|
42
|
+
budget: Duration,
|
|
43
|
+
backoff: Backoff,
|
|
44
|
+
/// Its last look ended in a wait on the app's scheduler, or it has not looked yet: the next
|
|
45
|
+
/// look starts a new run (spin::Run).
|
|
46
|
+
waited: bool,
|
|
47
|
+
run: Run,
|
|
48
|
+
server: Arc<ServerInner>,
|
|
49
|
+
/// Counts it (InlineSeats::conns) while it holds its seat, until it closes or goes to hyper.
|
|
50
|
+
slot: Arc<WorkerSlot>,
|
|
51
|
+
/// Tests: run once, as a request is read whole and before it is
|
|
52
|
+
/// admitted or handed back, as another thread may cut the connection
|
|
53
|
+
/// short then.
|
|
54
|
+
#[cfg(test)]
|
|
55
|
+
pub(crate) on_whole: Option<Box<dyn FnOnce() + Send>>,
|
|
56
|
+
/// Tests: run once, as a look that read all there was is about to
|
|
57
|
+
/// wait, as its client's bytes and the drain may come then.
|
|
58
|
+
#[cfg(test)]
|
|
59
|
+
pub(crate) on_wait: Option<Box<dyn FnOnce() + Send>>,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
enum Got {
|
|
63
|
+
/// Bytes, or an interrupted read: look again.
|
|
64
|
+
More,
|
|
65
|
+
Nothing,
|
|
66
|
+
/// Its client closed its side, or the socket failed or is gone.
|
|
67
|
+
End,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pub enum Next {
|
|
71
|
+
Request(BoxedCtx),
|
|
72
|
+
Readable,
|
|
73
|
+
Writable,
|
|
74
|
+
/// Closed, or handed back to hyper.
|
|
75
|
+
Closed,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
impl InlineConn {
|
|
79
|
+
/// `stream` (nonblocking), accepted on `home`; it holds `held` while open, here or on hyper.
|
|
80
|
+
pub(crate) fn new(
|
|
81
|
+
server: &Arc<ServerInner>,
|
|
82
|
+
seat: Seat,
|
|
83
|
+
stream: StdConn,
|
|
84
|
+
held: Held,
|
|
85
|
+
peer: Peer,
|
|
86
|
+
home: tokio::runtime::Handle,
|
|
87
|
+
) -> Box<InlineConn> {
|
|
88
|
+
let slot = seat.owner().clone();
|
|
89
|
+
let io = Arc::new(InlineIo {
|
|
90
|
+
deadline: Deadline::new(super::now(server) + micros(HEADER_READ_TIMEOUT)),
|
|
91
|
+
origin: Origin {
|
|
92
|
+
server: server.clone(),
|
|
93
|
+
home,
|
|
94
|
+
peer,
|
|
95
|
+
},
|
|
96
|
+
slot: slot.clone(),
|
|
97
|
+
state: Mutex::new(IoState {
|
|
98
|
+
stream: Some(stream),
|
|
99
|
+
seat: Some(seat),
|
|
100
|
+
held: Some(held),
|
|
101
|
+
..IoState::default()
|
|
102
|
+
}),
|
|
103
|
+
});
|
|
104
|
+
Box::new(InlineConn {
|
|
105
|
+
io,
|
|
106
|
+
buf: vec![0; HEAD_MAX].into_boxed_slice(),
|
|
107
|
+
len: 0,
|
|
108
|
+
pending: None,
|
|
109
|
+
unparsed: false,
|
|
110
|
+
served: false,
|
|
111
|
+
after_request: false,
|
|
112
|
+
yield_due: false,
|
|
113
|
+
spin_due: true,
|
|
114
|
+
budget: server
|
|
115
|
+
.inline
|
|
116
|
+
.as_ref()
|
|
117
|
+
.map_or(super::spin::BUDGET, |inline| inline.spin_budget),
|
|
118
|
+
backoff: Backoff::default(),
|
|
119
|
+
waited: true,
|
|
120
|
+
run: Run::default(),
|
|
121
|
+
server: server.clone(),
|
|
122
|
+
slot,
|
|
123
|
+
#[cfg(test)]
|
|
124
|
+
on_whole: None,
|
|
125
|
+
#[cfg(test)]
|
|
126
|
+
on_wait: None,
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// Listed under the lane lock as send_placed accepts it, so the drain, the deadlines and a
|
|
131
|
+
/// crash find it before its worker takes it; one a crash missed goes to hyper whole.
|
|
132
|
+
pub(crate) fn list(&self) {
|
|
133
|
+
self.slot.inline.ios.lock().push(Listed {
|
|
134
|
+
deadline: self.io.deadline.clone(),
|
|
135
|
+
io: Arc::downgrade(&self.io),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
pub(crate) fn server(&self) -> &Arc<ServerInner> {
|
|
140
|
+
&self.server
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pub(crate) fn slot(&self) -> &Arc<WorkerSlot> {
|
|
144
|
+
&self.slot
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
pub fn fd(&self) -> Option<RawFd> {
|
|
148
|
+
self.io.state.lock().stream.as_ref().map(AsRawFd::as_raw_fd)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Its worker counts it no more, and its socket closes (io::close), if still here.
|
|
152
|
+
pub(crate) fn let_go(&mut self) {
|
|
153
|
+
self.release(false);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// let_go for hyper: out come its socket and what it holds, if still here. None, the socket
|
|
157
|
+
/// closed, if it was cut short (past its deadline or the shutdown's), as hyper must not serve
|
|
158
|
+
/// what was cut.
|
|
159
|
+
pub(crate) fn let_go_to_hyper(&mut self) -> Option<(StdConn, Held)> {
|
|
160
|
+
self.release(true)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
fn release(&mut self, to_hyper: bool) -> Option<(StdConn, Held)> {
|
|
164
|
+
let (stream, seat, held, cut) = {
|
|
165
|
+
let mut state = self.io.state.lock();
|
|
166
|
+
state.looked(&self.slot);
|
|
167
|
+
// Its job ends a connection as it looks (next): a close here is a shutdown's.
|
|
168
|
+
let cut = to_hyper && state.closing;
|
|
169
|
+
let stream = if state.lent > 0 {
|
|
170
|
+
// A write still waits on it: shut down to end that wait; the last back closes it.
|
|
171
|
+
if to_hyper {
|
|
172
|
+
state.ends(&self.slot);
|
|
173
|
+
}
|
|
174
|
+
state.shutdown();
|
|
175
|
+
state.released = true;
|
|
176
|
+
None
|
|
177
|
+
} else {
|
|
178
|
+
state.stream.take()
|
|
179
|
+
};
|
|
180
|
+
(stream, state.seat.take(), state.held.take(), cut)
|
|
181
|
+
};
|
|
182
|
+
if seat.is_some() {
|
|
183
|
+
forget(&self.slot, &self.io);
|
|
184
|
+
}
|
|
185
|
+
drop(seat);
|
|
186
|
+
match (stream, held) {
|
|
187
|
+
(Some(stream), Some(held)) if to_hyper && !cut => Some((stream, held)),
|
|
188
|
+
(stream, _) => {
|
|
189
|
+
if let Some(stream) = stream {
|
|
190
|
+
close(stream);
|
|
191
|
+
}
|
|
192
|
+
None
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// One its worker never took, to hyper on its accepting runtime with nothing read, counted
|
|
198
|
+
/// as handed back (or else as declined): its client keeps what is left of its header time.
|
|
199
|
+
pub(crate) fn send_to_hyper(&mut self, handed_back: bool) {
|
|
200
|
+
if let Some((stream, held)) = self.let_go_to_hyper() {
|
|
201
|
+
self.io.to_hyper(stream, held, Bytes::new(), handed_back);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// At its job's first look after a request: whether the job steps aside behind the fibers
|
|
206
|
+
/// already ready on the app's scheduler, as async-http's server yields after each response.
|
|
207
|
+
/// Only when the answer went out whole, nothing of the next request was read and another
|
|
208
|
+
/// inline connection shares the worker. The step counts as the look, for placement
|
|
209
|
+
/// (IoState::looked) and as an idle wait (Waits::Idle), so a crash, a quarantine or the drain
|
|
210
|
+
/// treats the connection as idle meanwhile.
|
|
211
|
+
pub fn yield_turn(&mut self) -> bool {
|
|
212
|
+
if !std::mem::take(&mut self.yield_due) || self.len > 0 {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
if self.slot.inline.conns.load(Ordering::Relaxed) <= 1 {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
let mut state = self.io.state.lock();
|
|
219
|
+
let due = state.out.sent() && state.current.is_none() && !state.closing;
|
|
220
|
+
if due {
|
|
221
|
+
state.looked(&self.slot);
|
|
222
|
+
state.waits = Waits::Idle;
|
|
223
|
+
self.waited = true;
|
|
224
|
+
}
|
|
225
|
+
due
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/// The next request once the last answer is out, its body whole. One outside the subset, or
|
|
229
|
+
/// with no `room` on its worker, goes to hyper with the connection, as does the connection
|
|
230
|
+
/// once its worker retired. Alone on its worker, the job may spin for it first.
|
|
231
|
+
pub fn next(&mut self, room: bool) -> Next {
|
|
232
|
+
self.next_with(room, &mut super::spin::released)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// next, with the spin's release passed in: tests spin in place.
|
|
236
|
+
pub(crate) fn next_with(&mut self, room: bool, release: &mut Release) -> Next {
|
|
237
|
+
if std::mem::take(&mut self.waited) {
|
|
238
|
+
self.run.waited(&self.server, &self.slot);
|
|
239
|
+
}
|
|
240
|
+
let next = self.look_for(room, release);
|
|
241
|
+
self.waited = matches!(next, Next::Readable | Next::Writable);
|
|
242
|
+
next
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
fn look_for(&mut self, room: bool, release: &mut Release) -> Next {
|
|
246
|
+
self.give_up_owed();
|
|
247
|
+
{
|
|
248
|
+
let mut state = self.io.state.lock();
|
|
249
|
+
state.waits = Waits::Other;
|
|
250
|
+
state.taken = true;
|
|
251
|
+
state.looked(&self.slot);
|
|
252
|
+
let unsent = !state.out.sent();
|
|
253
|
+
let from = state.out.pos;
|
|
254
|
+
match state.flush() {
|
|
255
|
+
Ok(true) => {}
|
|
256
|
+
Ok(false) => {
|
|
257
|
+
// Its client took some: the answer's deadline moves on.
|
|
258
|
+
if state.out.pos > from {
|
|
259
|
+
self.io.deadline.due_in(&self.server, HEADER_READ_TIMEOUT);
|
|
260
|
+
}
|
|
261
|
+
return Next::Writable;
|
|
262
|
+
}
|
|
263
|
+
Err(_) => {
|
|
264
|
+
drop(state);
|
|
265
|
+
return self.end();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if state.closing {
|
|
269
|
+
drop(state);
|
|
270
|
+
return self.end();
|
|
271
|
+
}
|
|
272
|
+
// The last answer just went out whole: as hyper decides once it flushes, the
|
|
273
|
+
// connection ends now if the drain began or its worker was quarantined.
|
|
274
|
+
if unsent {
|
|
275
|
+
let draining = self.server.is_draining();
|
|
276
|
+
if draining || self.slot.life.quarantined() {
|
|
277
|
+
if !draining {
|
|
278
|
+
state.ends(&self.slot);
|
|
279
|
+
}
|
|
280
|
+
drop(state);
|
|
281
|
+
return self.end();
|
|
282
|
+
}
|
|
283
|
+
self.io.deadline.due_in(&self.server, HEADER_READ_TIMEOUT);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
// Once the drain began, a request that came is still served, then the connection closes;
|
|
287
|
+
// a kept-alive one mid-head ends, as hyper's does; a fresh one reads its first head on.
|
|
288
|
+
let draining = self.server.is_draining();
|
|
289
|
+
if !draining && self.slot.life.seems_retired() {
|
|
290
|
+
return self.hand_back();
|
|
291
|
+
}
|
|
292
|
+
if let Some(head) = self.pending.take() {
|
|
293
|
+
return self.read_body(head, room, false);
|
|
294
|
+
}
|
|
295
|
+
if std::mem::take(&mut self.after_request) && self.len == 0 {
|
|
296
|
+
if let Some(next) = self.wait_turn(release) {
|
|
297
|
+
return next;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
loop {
|
|
301
|
+
match parse_head(&self.buf[..self.len]) {
|
|
302
|
+
Parsed::Head(head) if head.content_length > self.body_max() => {
|
|
303
|
+
return self.hand_back()
|
|
304
|
+
}
|
|
305
|
+
// Ready to run: no room is why it goes.
|
|
306
|
+
Parsed::Head(head) if head.content_length == 0 && !room => return self.hand_back(),
|
|
307
|
+
Parsed::Head(head) => return self.read_body(head, room, true),
|
|
308
|
+
Parsed::Refused => return self.hand_back(),
|
|
309
|
+
Parsed::Partial if self.len == self.buf.len() && draining && self.served => {
|
|
310
|
+
return self.end()
|
|
311
|
+
}
|
|
312
|
+
Parsed::Partial if self.len == self.buf.len() => return self.hand_back(),
|
|
313
|
+
Parsed::Partial => match self.read_more() {
|
|
314
|
+
Got::More => self.backoff.observed(self.budget),
|
|
315
|
+
Got::Nothing => {
|
|
316
|
+
if let Some(next) = self.wait(release) {
|
|
317
|
+
return next;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
Got::End => return self.end(),
|
|
321
|
+
},
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// INLINE_BODY_MAX, or max_body_size (0: none) if lower, past which hyper answers 413.
|
|
327
|
+
fn body_max(&self) -> u64 {
|
|
328
|
+
match self.server.config.max_body_size as u64 {
|
|
329
|
+
0 => INLINE_BODY_MAX,
|
|
330
|
+
cap => cap.min(INLINE_BODY_MAX),
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/// `head`'s request once its body is whole, waiting on the socket up to BODY_READ_TIMEOUT
|
|
335
|
+
/// from the head (`fresh`) or the last bytes. A body past the buffer grows it, doubling, for
|
|
336
|
+
/// this request alone; `room` counts only once the app is to run.
|
|
337
|
+
fn read_body(&mut self, head: Head, room: bool, fresh: bool) -> Next {
|
|
338
|
+
let end = head.len + head.content_length as usize;
|
|
339
|
+
let mut came = fresh;
|
|
340
|
+
while self.len < end {
|
|
341
|
+
if self.len == self.buf.len() {
|
|
342
|
+
self.grow((self.len * 2).min(end));
|
|
343
|
+
}
|
|
344
|
+
match self.read_more() {
|
|
345
|
+
Got::More => came = true,
|
|
346
|
+
Got::Nothing => {
|
|
347
|
+
if came {
|
|
348
|
+
self.io.deadline.due_in(&self.server, BODY_READ_TIMEOUT);
|
|
349
|
+
}
|
|
350
|
+
self.pending = Some(head);
|
|
351
|
+
self.parsed();
|
|
352
|
+
return Next::Readable;
|
|
353
|
+
}
|
|
354
|
+
Got::End => return self.end(),
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if !room {
|
|
358
|
+
return self.hand_back();
|
|
359
|
+
}
|
|
360
|
+
self.request(head, end)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/// Nothing to parse until the socket reads ready. Idle, a drain or a quarantine may shut the
|
|
364
|
+
/// connection; mid-head on a kept-alive one, a drain may. Should the drain have begun since
|
|
365
|
+
/// the look, it ends now, unless its client's bytes came meanwhile (or the spin saw them):
|
|
366
|
+
/// the look reads those first (None), as hyper reads what came before it heeds the drain.
|
|
367
|
+
fn wait(&mut self, release: &mut Release) -> Option<Next> {
|
|
368
|
+
#[cfg(test)]
|
|
369
|
+
if let Some(meanwhile) = self.on_wait.take() {
|
|
370
|
+
meanwhile();
|
|
371
|
+
}
|
|
372
|
+
if self.len > 0 && !self.served {
|
|
373
|
+
self.parsed();
|
|
374
|
+
return Some(Next::Readable);
|
|
375
|
+
}
|
|
376
|
+
if self.len == 0 && self.spin_for_next(release) {
|
|
377
|
+
return self.retired_meanwhile();
|
|
378
|
+
}
|
|
379
|
+
let mut state = self.io.state.lock();
|
|
380
|
+
if self.server.is_draining() {
|
|
381
|
+
if state.unread() {
|
|
382
|
+
return None;
|
|
383
|
+
}
|
|
384
|
+
drop(state);
|
|
385
|
+
return Some(self.end());
|
|
386
|
+
}
|
|
387
|
+
if self.len == 0 {
|
|
388
|
+
if self.slot.life.quarantined() {
|
|
389
|
+
state.ends(&self.slot);
|
|
390
|
+
drop(state);
|
|
391
|
+
return Some(self.end());
|
|
392
|
+
}
|
|
393
|
+
state.waits = Waits::Idle;
|
|
394
|
+
// Nothing is left unparsed: a request() consumed what it left.
|
|
395
|
+
return Some(Next::Readable);
|
|
396
|
+
}
|
|
397
|
+
state.waits = Waits::MidHead;
|
|
398
|
+
state.unparsed = false;
|
|
399
|
+
self.unparsed = false;
|
|
400
|
+
Some(Next::Readable)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/// The first look after a request, nothing of the next read: the job waits on the socket
|
|
404
|
+
/// before it reads, so a request that came meanwhile runs behind the worker's connections
|
|
405
|
+
/// whose requests came first; a pipelined one runs at once. None, to read first, once the
|
|
406
|
+
/// drain began or the worker was quarantined (read under the lock their passes take), or once
|
|
407
|
+
/// the spin saw the next request, as then no other connection shares the worker.
|
|
408
|
+
fn wait_turn(&mut self, release: &mut Release) -> Option<Next> {
|
|
409
|
+
if self.spin_for_next(release) {
|
|
410
|
+
return self.retired_meanwhile();
|
|
411
|
+
}
|
|
412
|
+
let mut state = self.io.state.lock();
|
|
413
|
+
if self.server.is_draining() || self.slot.life.quarantined() {
|
|
414
|
+
return None;
|
|
415
|
+
}
|
|
416
|
+
state.waits = Waits::Idle;
|
|
417
|
+
Some(Next::Readable)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/// Whether its job reads the next request now, having spun for it up to the budget instead of
|
|
421
|
+
/// parking on the socket: once per request read and as it opens, nothing owed, within the
|
|
422
|
+
/// server-wide gate and the back-off. A stop by the VM's unblock function does not count, and
|
|
423
|
+
/// a catch past the job's run (spin::Run) is left to the job's wait, so the app's scheduler
|
|
424
|
+
/// gets its pass. The descriptor stays the job's: nothing takes it to hyper while the job
|
|
425
|
+
/// waits on nothing.
|
|
426
|
+
fn spin_for_next(&mut self, release: &mut Release) -> bool {
|
|
427
|
+
if !std::mem::take(&mut self.spin_due) || !super::spin::may_spin(&self.server, &self.slot) {
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
let Some(inline) = self.server.inline.as_deref() else {
|
|
431
|
+
return false;
|
|
432
|
+
};
|
|
433
|
+
let fd = {
|
|
434
|
+
let state = self.io.state.lock();
|
|
435
|
+
match &state.stream {
|
|
436
|
+
Some(stream) if state.current.is_none() && state.out.sent() && !state.closing => {
|
|
437
|
+
stream.as_raw_fd()
|
|
438
|
+
}
|
|
439
|
+
_ => return false,
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
// No room in the server-wide count leaves the back-off as it was: a due probe waits for a
|
|
443
|
+
// chance that can spin.
|
|
444
|
+
let Some(spinning) = inline.spinners.join(inline.spin_in_flight) else {
|
|
445
|
+
return false;
|
|
446
|
+
};
|
|
447
|
+
if !self.backoff.chance() {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
let budget = self.budget;
|
|
451
|
+
let (server, slot) = (&self.server, &self.slot);
|
|
452
|
+
let woken = AtomicBool::new(false);
|
|
453
|
+
let spun = release(&woken, &mut || {
|
|
454
|
+
super::spin::poll(fd, budget, &woken, server, slot)
|
|
455
|
+
});
|
|
456
|
+
drop(spinning);
|
|
457
|
+
let Some(spun) = spun else {
|
|
458
|
+
return false;
|
|
459
|
+
};
|
|
460
|
+
let spun = if woken.load(Ordering::Relaxed) {
|
|
461
|
+
Spin::Stopped
|
|
462
|
+
} else {
|
|
463
|
+
spun
|
|
464
|
+
};
|
|
465
|
+
slot.inline.spins.fetch_add(1, Ordering::Relaxed);
|
|
466
|
+
self.backoff.record(spun) && self.run.reads(inline.spin_run)
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/// After a spin's catch: None for the look to read it, unless the worker retired meanwhile,
|
|
470
|
+
/// when the connection goes to hyper as at the look's start.
|
|
471
|
+
fn retired_meanwhile(&mut self) -> Option<Next> {
|
|
472
|
+
let draining = self.server.is_draining();
|
|
473
|
+
(!draining && self.slot.life.seems_retired()).then(|| self.hand_back())
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/// Parsed short of a request: no whole one waits in the buffer (IoState::unparsed).
|
|
477
|
+
fn parsed(&mut self) {
|
|
478
|
+
if self.unparsed {
|
|
479
|
+
self.io.state.lock().unparsed = false;
|
|
480
|
+
self.unparsed = false;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/// The request being served got no answer by the job's next look: a 500, then it ends.
|
|
485
|
+
fn give_up_owed(&self) {
|
|
486
|
+
let owed = self
|
|
487
|
+
.io
|
|
488
|
+
.state
|
|
489
|
+
.lock()
|
|
490
|
+
.current
|
|
491
|
+
.as_ref()
|
|
492
|
+
.map(|c| c.responder.clone());
|
|
493
|
+
if let Some(responder) = owed {
|
|
494
|
+
self.io.give_up(&responder, Cut::Crash);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
fn grow(&mut self, to: usize) {
|
|
499
|
+
let mut buf = std::mem::take(&mut self.buf).into_vec();
|
|
500
|
+
buf.reserve_exact(to - buf.len());
|
|
501
|
+
buf.resize(to, 0);
|
|
502
|
+
self.buf = buf.into_boxed_slice();
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/// The first `end` bytes were a request's: the rest moves to a usual-size buffer's front.
|
|
506
|
+
fn consume(&mut self, end: usize) {
|
|
507
|
+
self.buf.copy_within(end..self.len, 0);
|
|
508
|
+
self.len -= end;
|
|
509
|
+
if self.buf.len() > HEAD_MAX {
|
|
510
|
+
let mut buf = std::mem::take(&mut self.buf).into_vec();
|
|
511
|
+
buf.truncate(HEAD_MAX.max(self.len));
|
|
512
|
+
self.buf = buf.into_boxed_slice();
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
fn read_more(&mut self) -> Got {
|
|
517
|
+
let state = self.io.state.lock();
|
|
518
|
+
let Some(stream) = state.stream.as_ref() else {
|
|
519
|
+
return Got::End;
|
|
520
|
+
};
|
|
521
|
+
match (&stream.socket).read(&mut self.buf[self.len..]) {
|
|
522
|
+
Ok(0) => Got::End,
|
|
523
|
+
Ok(n) => {
|
|
524
|
+
self.len += n;
|
|
525
|
+
Got::More
|
|
526
|
+
}
|
|
527
|
+
Err(e) if e.kind() == ErrorKind::WouldBlock => Got::Nothing,
|
|
528
|
+
Err(e) if e.kind() == ErrorKind::Interrupted => Got::More,
|
|
529
|
+
Err(_) => Got::End,
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
fn end(&mut self) -> Next {
|
|
534
|
+
self.let_go();
|
|
535
|
+
Next::Closed
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/// Hyper serves the connection from here on, reading what was read here first.
|
|
539
|
+
fn hand_back(&mut self) -> Next {
|
|
540
|
+
#[cfg(test)]
|
|
541
|
+
if let Some(cut) = self.on_whole.take() {
|
|
542
|
+
cut();
|
|
543
|
+
}
|
|
544
|
+
let Some((stream, held)) = self.let_go_to_hyper() else {
|
|
545
|
+
return Next::Closed;
|
|
546
|
+
};
|
|
547
|
+
let prefix = Bytes::copy_from_slice(&self.buf[..self.len]);
|
|
548
|
+
self.len = 0;
|
|
549
|
+
self.pending = None;
|
|
550
|
+
self.io.to_hyper(stream, held, prefix, true);
|
|
551
|
+
Next::Closed
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/// The request read whole, the first `end` bytes of the buffer.
|
|
555
|
+
fn request(&mut self, head: Head, end: usize) -> Next {
|
|
556
|
+
#[cfg(test)]
|
|
557
|
+
if let Some(cut) = self.on_whole.take() {
|
|
558
|
+
cut();
|
|
559
|
+
}
|
|
560
|
+
// The header values and the body share one copy.
|
|
561
|
+
let bytes = Bytes::copy_from_slice(&self.buf[..end]);
|
|
562
|
+
let (uri, headers) = match head.parts(&bytes) {
|
|
563
|
+
Some(parts) => parts,
|
|
564
|
+
None => return self.hand_back(),
|
|
565
|
+
};
|
|
566
|
+
self.consume(end);
|
|
567
|
+
// All of it, then the end: the app's reads never wait.
|
|
568
|
+
let body_rx = (end > head.len).then(|| {
|
|
569
|
+
let (body_tx, body_rx) = flume::bounded(1);
|
|
570
|
+
let _ = body_tx.send(bytes.slice(head.len..));
|
|
571
|
+
body_rx
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
let mut state = self.io.state.lock();
|
|
575
|
+
// Cut short since its job looked: it ends unanswered and the app never runs it.
|
|
576
|
+
if state.closing {
|
|
577
|
+
drop(state);
|
|
578
|
+
return self.end();
|
|
579
|
+
}
|
|
580
|
+
self.served = true;
|
|
581
|
+
self.after_request = true;
|
|
582
|
+
self.yield_due = true;
|
|
583
|
+
self.spin_due = true;
|
|
584
|
+
let server = &self.server;
|
|
585
|
+
// Under the lock, so its arrival line comes before any thread's completion line.
|
|
586
|
+
let logged = server.access_log.as_ref().map(|log| {
|
|
587
|
+
let from = self.io.origin.peer.remote.ip();
|
|
588
|
+
Box::new(Logged::arrival(log, &head.method, &uri, from))
|
|
589
|
+
});
|
|
590
|
+
state.unparsed = self.len > 0;
|
|
591
|
+
self.unparsed = state.unparsed;
|
|
592
|
+
// A 504 unless its answer begins by then, on the clock read now: hyper's never comes
|
|
593
|
+
// early.
|
|
594
|
+
if server.config.request_timeout_ms > 0 {
|
|
595
|
+
let timeout = server.config.request_timeout_ms.saturating_mul(1000);
|
|
596
|
+
self.io
|
|
597
|
+
.deadline
|
|
598
|
+
.set(super::real_now(server).saturating_add(timeout));
|
|
599
|
+
}
|
|
600
|
+
let responder = Arc::new(Responder::inline(Arc::downgrade(&self.io)));
|
|
601
|
+
// It offers no hijack: nothing takes it out of the count early.
|
|
602
|
+
let in_flight = InFlight::enter(server.clone(), None);
|
|
603
|
+
self.slot.inline.requests.fetch_add(1, Ordering::Relaxed);
|
|
604
|
+
state.dropped = 0;
|
|
605
|
+
state.current = Some(Current {
|
|
606
|
+
responder: responder.clone(),
|
|
607
|
+
head_only: head.method == http::Method::HEAD,
|
|
608
|
+
close: head.close,
|
|
609
|
+
_in_flight: in_flight,
|
|
610
|
+
stream: None,
|
|
611
|
+
logged,
|
|
612
|
+
});
|
|
613
|
+
drop(state);
|
|
614
|
+
// Never https inline; unix connections get hyper's addresses
|
|
615
|
+
// (server::UNIX_PEER).
|
|
616
|
+
let mut ctx = RequestCtx::queued(
|
|
617
|
+
server,
|
|
618
|
+
head.method,
|
|
619
|
+
uri,
|
|
620
|
+
http::Version::HTTP_11,
|
|
621
|
+
headers,
|
|
622
|
+
self.io.origin.peer,
|
|
623
|
+
responder,
|
|
624
|
+
);
|
|
625
|
+
ctx.body_rx = body_rx;
|
|
626
|
+
ctx.slot = Some(self.slot.clone());
|
|
627
|
+
ctx.inline = Some(self.io.clone());
|
|
628
|
+
Next::Request(Box::new(ctx))
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
impl Drop for InlineConn {
|
|
633
|
+
/// No Ruby API, so it may run in a free. Let go while still its worker's, the connection was
|
|
634
|
+
/// cut off by whatever ended the job; one waiting idle goes to hyper instead
|
|
635
|
+
/// (InlineIo::abandon).
|
|
636
|
+
fn drop(&mut self) {
|
|
637
|
+
if let Some(seat) = self.io.to_hyper_if_idle() {
|
|
638
|
+
forget(&self.slot, &self.io);
|
|
639
|
+
drop(seat);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
self.io.state.lock().ends(&self.slot);
|
|
643
|
+
self.give_up_owed();
|
|
644
|
+
self.let_go();
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
#[cfg(test)]
|
|
649
|
+
mod tests {
|
|
650
|
+
use std::io::Write;
|
|
651
|
+
use std::sync::atomic::Ordering;
|
|
652
|
+
use std::time::Duration;
|
|
653
|
+
|
|
654
|
+
use super::*;
|
|
655
|
+
use crate::inline::testing::{
|
|
656
|
+
advance, answer, answer_dispatched, await_bytes, body_of, closes, configured_server,
|
|
657
|
+
cut_offs, handbacks, inline_loop_server, look, loop_server_as, loopback, loopback_holding,
|
|
658
|
+
narrowed, next_request, once_written, read_to_end, reads_within, send_get, server,
|
|
659
|
+
with_body, Event, Wire,
|
|
660
|
+
};
|
|
661
|
+
use crate::inline::Wrote;
|
|
662
|
+
use crate::testing::{eventually_blocking, slot};
|
|
663
|
+
|
|
664
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
665
|
+
async fn a_body_past_max_body_size_goes_to_hyper_for_its_413() {
|
|
666
|
+
// As long as max_body_size, read inline; a byte past it (though
|
|
667
|
+
// short enough to read inline), hyper's 413, as without inline
|
|
668
|
+
// serving.
|
|
669
|
+
let server = configured_server(|c| c.max_body_size = 1024);
|
|
670
|
+
let (client, mut conn) = loopback(&server);
|
|
671
|
+
(&client)
|
|
672
|
+
.write_all(&with_body("/form", 1024, 1024))
|
|
673
|
+
.unwrap();
|
|
674
|
+
let ctx = next_request(&mut conn);
|
|
675
|
+
assert_eq!(body_of(&ctx).len(), 1024);
|
|
676
|
+
answer(&ctx, b"stored");
|
|
677
|
+
drop(ctx);
|
|
678
|
+
let mut wire = Wire::of(&client);
|
|
679
|
+
assert_eq!(wire.response().0, "HTTP/1.1 200 OK");
|
|
680
|
+
(&client).write_all(&with_body("/form", 1025, 10)).unwrap();
|
|
681
|
+
await_bytes(&conn);
|
|
682
|
+
assert!(matches!(look(&mut conn, true), Next::Closed), "read inline");
|
|
683
|
+
assert_eq!(wire.response().0, "HTTP/1.1 413 Payload Too Large");
|
|
684
|
+
assert_eq!(handbacks(&server), 1);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
688
|
+
async fn a_drain_closes_idle_and_half_read_connections_and_serves_with_a_close_what_was_sent() {
|
|
689
|
+
let server = server();
|
|
690
|
+
let (idle_client, mut idle) = loopback(&server);
|
|
691
|
+
assert!(matches!(idle.next(true), Next::Readable));
|
|
692
|
+
// Placed, and not looked at yet by its job: one silent, one whose
|
|
693
|
+
// client's request is in.
|
|
694
|
+
let (fresh_client, mut fresh) = loopback(&server);
|
|
695
|
+
let (sent_client, mut sent) = loopback(&server);
|
|
696
|
+
send_get(&sent_client, "/sent", false);
|
|
697
|
+
await_bytes(&sent);
|
|
698
|
+
let (busy_client, mut busy) = loopback(&server);
|
|
699
|
+
send_get(&busy_client, "/busy", false);
|
|
700
|
+
let ctx = next_request(&mut busy);
|
|
701
|
+
// Kept alive, and part of its next head read, the rest still to
|
|
702
|
+
// come.
|
|
703
|
+
let (part_client, mut part) = loopback(&server);
|
|
704
|
+
send_get(&part_client, "/first", false);
|
|
705
|
+
answer(&next_request(&mut part), b"first");
|
|
706
|
+
assert_eq!(Wire::of(&part_client).response().2, b"first");
|
|
707
|
+
(&part_client)
|
|
708
|
+
.write_all(b"GET /part HTTP/1.1\r\nho")
|
|
709
|
+
.unwrap();
|
|
710
|
+
await_bytes(&part);
|
|
711
|
+
while part.readable() {
|
|
712
|
+
assert!(matches!(part.next(true), Next::Readable));
|
|
713
|
+
}
|
|
714
|
+
server.stop_accepting();
|
|
715
|
+
|
|
716
|
+
// The idle one's client reads the end before its job looks again.
|
|
717
|
+
assert_eq!(read_to_end(&idle_client), b"");
|
|
718
|
+
for conn in [&mut idle, &mut fresh] {
|
|
719
|
+
assert!(matches!(conn.next(true), Next::Closed));
|
|
720
|
+
}
|
|
721
|
+
assert_eq!(read_to_end(&fresh_client), b"");
|
|
722
|
+
assert_eq!(
|
|
723
|
+
read_to_end(&part_client),
|
|
724
|
+
b"",
|
|
725
|
+
"a half-read head was answered"
|
|
726
|
+
);
|
|
727
|
+
assert!(matches!(part.next(true), Next::Closed));
|
|
728
|
+
|
|
729
|
+
let sent_ctx = next_request(&mut sent);
|
|
730
|
+
for (ctx, client, conn) in [
|
|
731
|
+
(ctx, &busy_client, &mut busy),
|
|
732
|
+
(sent_ctx, &sent_client, &mut sent),
|
|
733
|
+
] {
|
|
734
|
+
answer(&ctx, b"done");
|
|
735
|
+
drop(ctx);
|
|
736
|
+
let mut wire = Wire::of(client);
|
|
737
|
+
let (status, headers, body) = wire.response();
|
|
738
|
+
assert!(
|
|
739
|
+
status == "HTTP/1.1 200 OK" && body == b"done" && closes(&headers),
|
|
740
|
+
"{headers:?}"
|
|
741
|
+
);
|
|
742
|
+
assert!(matches!(conn.next(true), Next::Closed));
|
|
743
|
+
assert_eq!(wire.answer(false), Event::Closed);
|
|
744
|
+
}
|
|
745
|
+
assert_eq!(slot(&server, 0).inline.conns.load(Ordering::Relaxed), 0);
|
|
746
|
+
assert_eq!(cut_offs(&server), 0, "a drain's closes count as cut off");
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
750
|
+
async fn a_request_that_comes_as_the_drain_begins_is_answered_and_its_connection_ends() {
|
|
751
|
+
// The job had read none of it, or part of its head, and waited
|
|
752
|
+
// for the rest, which came before its next look, or during it,
|
|
753
|
+
// after it read all there was and before it waited.
|
|
754
|
+
let second = b"GET /2 HTTP/1.1\r\nhost: x\r\n\r\n";
|
|
755
|
+
for (before, during) in [(0, false), (19, false), (0, true), (19, true)] {
|
|
756
|
+
let shown = format!("{before} bytes read, the rest during the look {during}");
|
|
757
|
+
let server = server();
|
|
758
|
+
let _accepting = server.shutdown_tx.subscribe();
|
|
759
|
+
let (client, mut conn) = loopback(&server);
|
|
760
|
+
send_get(&client, "/1", false);
|
|
761
|
+
answer(&next_request(&mut conn), b"one");
|
|
762
|
+
let mut wire = Wire::of(&client);
|
|
763
|
+
assert_eq!(wire.response().2, b"one");
|
|
764
|
+
let fd = conn.fd().expect("an open connection");
|
|
765
|
+
if before > 0 {
|
|
766
|
+
(&client).write_all(&second[..before]).unwrap();
|
|
767
|
+
assert!(reads_within(fd, 5_000), "the bytes never came");
|
|
768
|
+
}
|
|
769
|
+
assert!(matches!(look(&mut conn, true), Next::Readable), "{shown}");
|
|
770
|
+
let rest = second[before..].to_vec();
|
|
771
|
+
if during {
|
|
772
|
+
let (sender, draining) = (client.try_clone().expect("a clone"), server.clone());
|
|
773
|
+
conn.on_wait = Some(Box::new(move || {
|
|
774
|
+
(&sender).write_all(&rest).unwrap();
|
|
775
|
+
assert!(reads_within(fd, 5_000), "the rest never came");
|
|
776
|
+
draining.stop_accepting();
|
|
777
|
+
}));
|
|
778
|
+
} else {
|
|
779
|
+
(&client).write_all(&rest).unwrap();
|
|
780
|
+
await_bytes(&conn);
|
|
781
|
+
server.stop_accepting();
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
let ctx = next_request(&mut conn);
|
|
785
|
+
assert_eq!(ctx.uri.path(), "/2", "{shown}");
|
|
786
|
+
answer(&ctx, b"two");
|
|
787
|
+
drop(ctx);
|
|
788
|
+
let (_, headers, body) = wire.response();
|
|
789
|
+
assert!(body == b"two" && closes(&headers), "{shown}: {headers:?}");
|
|
790
|
+
assert!(matches!(conn.next(true), Next::Closed), "{shown}");
|
|
791
|
+
assert_eq!(wire.answer(false), Event::Closed, "{shown}");
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
796
|
+
async fn a_request_handed_to_hyper_as_the_drain_begins_is_answered() {
|
|
797
|
+
/// The drain begins as `conn`'s next look reads a request whole,
|
|
798
|
+
/// before that request goes anywhere.
|
|
799
|
+
fn drain_on_whole(server: &Arc<ServerInner>, conn: &mut InlineConn) {
|
|
800
|
+
let draining = server.clone();
|
|
801
|
+
conn.on_whole = Some(Box::new(move || draining.stop_accepting()));
|
|
802
|
+
}
|
|
803
|
+
type Hand = fn(&Arc<ServerInner>, &std::net::TcpStream, &mut InlineConn) -> &'static str;
|
|
804
|
+
// Outside the subset; read whole on a worker with no room; read a
|
|
805
|
+
// byte at a time, a start of the h2 preface, then whole, as its
|
|
806
|
+
// worker retires: it goes to hyper with too little for its sniff.
|
|
807
|
+
let causes: [Hand; 3] = [
|
|
808
|
+
|server, client, conn| {
|
|
809
|
+
let chunked = "POST /chunked HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n";
|
|
810
|
+
(&*client).write_all(chunked.as_bytes()).unwrap();
|
|
811
|
+
await_bytes(conn);
|
|
812
|
+
drain_on_whole(server, conn);
|
|
813
|
+
assert!(matches!(conn.next(true), Next::Closed));
|
|
814
|
+
"/chunked"
|
|
815
|
+
},
|
|
816
|
+
|server, client, conn| {
|
|
817
|
+
send_get(client, "/full", false);
|
|
818
|
+
await_bytes(conn);
|
|
819
|
+
drain_on_whole(server, conn);
|
|
820
|
+
assert!(matches!(conn.next(false), Next::Closed));
|
|
821
|
+
"/full"
|
|
822
|
+
},
|
|
823
|
+
|server, client, conn| {
|
|
824
|
+
send_get(client, "/1", false);
|
|
825
|
+
answer(&next_request(conn), b"one");
|
|
826
|
+
assert_eq!(Wire::of(client).response().2, b"one");
|
|
827
|
+
let next = b"POST /retired HTTP/1.1\r\nhost: x\r\ncontent-length: 2\r\n\r\nhi";
|
|
828
|
+
(&*client).write_all(&next[..1]).unwrap();
|
|
829
|
+
await_bytes(conn);
|
|
830
|
+
assert!(matches!(look(conn, true), Next::Readable));
|
|
831
|
+
(&*client).write_all(&next[1..]).unwrap();
|
|
832
|
+
await_bytes(conn);
|
|
833
|
+
let slot = slot(server, 0);
|
|
834
|
+
slot.retire();
|
|
835
|
+
drain_on_whole(server, conn);
|
|
836
|
+
assert!(matches!(conn.next(true), Next::Closed));
|
|
837
|
+
"/retired"
|
|
838
|
+
},
|
|
839
|
+
];
|
|
840
|
+
// Eight times over: which of the two hyper looked at first, the
|
|
841
|
+
// request or the drain, is a coin's toss (fewer rounds let a hand-back
|
|
842
|
+
// that drops what the worker read pass now and then). With either
|
|
843
|
+
// builder: the HTTP/1 one closes a connection it read nothing of at
|
|
844
|
+
// the drain, as the auto one cancels its sniff.
|
|
845
|
+
for _ in 0..8 {
|
|
846
|
+
for http2 in [true, false] {
|
|
847
|
+
for (i, hand) in causes.iter().enumerate() {
|
|
848
|
+
let server = loop_server_as(2, 8, |t| t.with(|c| c.http2 = http2));
|
|
849
|
+
let _accepting = server.shutdown_tx.subscribe();
|
|
850
|
+
let (client, mut conn) = loopback(&server);
|
|
851
|
+
let path = hand(&server, &client, &mut conn);
|
|
852
|
+
let shown = format!("cause {i} ({path}), http2 {http2}");
|
|
853
|
+
let paths = [path];
|
|
854
|
+
let answered = answer_dispatched(&server, &paths);
|
|
855
|
+
let answered = tokio::time::timeout(Duration::from_secs(3), answered);
|
|
856
|
+
assert!(answered.await.is_ok(), "{shown}: never dispatched");
|
|
857
|
+
let (status, headers, _) = Wire::of(&client).response();
|
|
858
|
+
assert!(
|
|
859
|
+
status == "HTTP/1.1 200 OK" && closes(&headers),
|
|
860
|
+
"{shown}: {status} {headers:?}"
|
|
861
|
+
);
|
|
862
|
+
assert_eq!(read_to_end(&client), b"", "{shown}");
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
869
|
+
async fn a_streamed_chunk_waits_while_the_socket_still_holds_the_last() {
|
|
870
|
+
let server = server();
|
|
871
|
+
let (client, mut conn) = narrowed(&server);
|
|
872
|
+
send_get(&client, "/s", true);
|
|
873
|
+
let ctx = next_request(&mut conn);
|
|
874
|
+
let io = ctx.inline.clone().expect("an inline request");
|
|
875
|
+
let responder = &ctx.responder;
|
|
876
|
+
assert!(io.start_stream(responder, http::StatusCode::OK, &http::HeaderMap::new()));
|
|
877
|
+
let chunk = vec![b'x'; 1 << 20];
|
|
878
|
+
// The chunk and its frame, and no more, wait for the client.
|
|
879
|
+
let bound = chunk.len() + b"100000\r\n\r\n".len();
|
|
880
|
+
let buffered = |conn: &InlineConn| {
|
|
881
|
+
assert!(
|
|
882
|
+
conn.write_buffered() <= bound,
|
|
883
|
+
"{} bytes buffered",
|
|
884
|
+
conn.write_buffered()
|
|
885
|
+
);
|
|
886
|
+
};
|
|
887
|
+
assert_eq!(io.write_chunk(responder, &chunk), Wrote::Done);
|
|
888
|
+
buffered(&conn);
|
|
889
|
+
match io.write_chunk(responder, &chunk) {
|
|
890
|
+
Wrote::Wait(fd) => assert_eq!(Some(fd), conn.fd(), "a wait on another descriptor"),
|
|
891
|
+
wrote => {
|
|
892
|
+
panic!("the stream took another chunk while its client read nothing: {wrote:?}")
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
buffered(&conn);
|
|
896
|
+
|
|
897
|
+
// The socket takes the first chunk 4 KiB at a time, as its
|
|
898
|
+
// client reads: each wait is a blocking write's, for the socket
|
|
899
|
+
// to take more, however long its client takes over a read.
|
|
900
|
+
let reader = std::thread::spawn(move || read_to_end(&client));
|
|
901
|
+
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
|
902
|
+
while let Wrote::Wait(fd) = io.write_chunk(responder, &chunk) {
|
|
903
|
+
buffered(&conn);
|
|
904
|
+
assert!(
|
|
905
|
+
std::time::Instant::now() < deadline,
|
|
906
|
+
"the client's reads never made room"
|
|
907
|
+
);
|
|
908
|
+
crate::inline::await_writable(fd, Duration::from_secs(1));
|
|
909
|
+
}
|
|
910
|
+
io.finish_stream(responder);
|
|
911
|
+
assert!(matches!(once_written(&mut conn), Next::Closed));
|
|
912
|
+
let read = reader.join().expect("the client");
|
|
913
|
+
assert_eq!(read.iter().filter(|&&b| b == b'x').count(), 2 * chunk.len());
|
|
914
|
+
assert!(read.ends_with(b"\r\n0\r\n\r\n"), "the body never ended");
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
918
|
+
async fn a_connection_handed_to_hyper_with_too_little_read_keeps_its_header_deadline() {
|
|
919
|
+
let server = server();
|
|
920
|
+
let ends_soon = |client: &std::net::TcpStream, within: Duration, what: &str| {
|
|
921
|
+
let handed = std::time::Instant::now();
|
|
922
|
+
assert_eq!(read_to_end(client), b"", "{what}");
|
|
923
|
+
assert!(
|
|
924
|
+
handed.elapsed() < within,
|
|
925
|
+
"{what}: closed {:?} after",
|
|
926
|
+
handed.elapsed()
|
|
927
|
+
);
|
|
928
|
+
};
|
|
929
|
+
// Its client silent: it closes once its header time is up, 100 ms
|
|
930
|
+
// on, as it would have inline.
|
|
931
|
+
let (silent_client, mut silent) = loopback(&server);
|
|
932
|
+
advance(&server, HEADER_READ_TIMEOUT - Duration::from_millis(100));
|
|
933
|
+
silent.send_to_hyper(true);
|
|
934
|
+
ends_soon(&silent_client, Duration::from_secs(2), "silent");
|
|
935
|
+
|
|
936
|
+
// One whose client stopped inside the h2 preface, on which hyper's
|
|
937
|
+
// sniff would wait, closes at its header time too.
|
|
938
|
+
let (stalled_client, mut stalled) = loopback(&server);
|
|
939
|
+
(&stalled_client).write_all(b"P").unwrap();
|
|
940
|
+
await_bytes(&stalled);
|
|
941
|
+
assert!(matches!(stalled.next(true), Next::Readable));
|
|
942
|
+
advance(&server, HEADER_READ_TIMEOUT - Duration::from_millis(100));
|
|
943
|
+
assert!(matches!(stalled.hand_back(), Next::Closed));
|
|
944
|
+
ends_soon(
|
|
945
|
+
&stalled_client,
|
|
946
|
+
Duration::from_secs(2),
|
|
947
|
+
"inside the preface",
|
|
948
|
+
);
|
|
949
|
+
|
|
950
|
+
// Once the drain began, a silent one closes at once.
|
|
951
|
+
let _accepting = server.shutdown_tx.subscribe();
|
|
952
|
+
server.stop_accepting();
|
|
953
|
+
let (silent_client, mut silent) = loopback(&server);
|
|
954
|
+
silent.send_to_hyper(true);
|
|
955
|
+
ends_soon(
|
|
956
|
+
&silent_client,
|
|
957
|
+
Duration::from_millis(500),
|
|
958
|
+
"silent, the drain begun",
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
#[test]
|
|
963
|
+
fn a_connection_handed_to_hyper_inside_the_h2_preface_that_then_ends_closes_at_once() {
|
|
964
|
+
// Its job read a start of the preface or nothing, then its client
|
|
965
|
+
// sent more of it and ended its side, or reset: what hyper reads
|
|
966
|
+
// first comes from the worker, the socket, or both.
|
|
967
|
+
for (read, then) in [(&b"P"[..], &b"R"[..]), (b"", b"P")] {
|
|
968
|
+
for reset in [false, true] {
|
|
969
|
+
let end = if reset { "RST" } else { "FIN" };
|
|
970
|
+
let what = format!(
|
|
971
|
+
"{:?} read, {:?} then a {end}",
|
|
972
|
+
read.escape_ascii().to_string(),
|
|
973
|
+
then.escape_ascii().to_string()
|
|
974
|
+
);
|
|
975
|
+
let shown = what.clone();
|
|
976
|
+
crate::testing::on_own_runtime(what, Duration::from_secs(3), async move {
|
|
977
|
+
let server = server();
|
|
978
|
+
let permits = Arc::new(tokio::sync::Semaphore::new(1));
|
|
979
|
+
let permit = permits.clone().try_acquire_owned().expect("a permit");
|
|
980
|
+
let (client, mut conn) = loopback_holding(&server, permit);
|
|
981
|
+
if !read.is_empty() {
|
|
982
|
+
(&client).write_all(read).unwrap();
|
|
983
|
+
await_bytes(&conn);
|
|
984
|
+
}
|
|
985
|
+
assert!(matches!(conn.next(true), Next::Readable));
|
|
986
|
+
(&client).write_all(then).unwrap();
|
|
987
|
+
let client = if reset {
|
|
988
|
+
crate::inline::testing::abortive(&client);
|
|
989
|
+
drop(client);
|
|
990
|
+
None
|
|
991
|
+
} else {
|
|
992
|
+
client.shutdown(std::net::Shutdown::Write).unwrap();
|
|
993
|
+
client.set_nonblocking(true).unwrap();
|
|
994
|
+
Some(tokio::net::TcpStream::from_std(client).expect("a client"))
|
|
995
|
+
};
|
|
996
|
+
assert!(matches!(conn.hand_back(), Next::Closed));
|
|
997
|
+
// Hyper reads all its client sent, and the end, and
|
|
998
|
+
// closes: a close with some of it unread would reset.
|
|
999
|
+
if let Some(mut client) = client {
|
|
1000
|
+
let mut rest = Vec::new();
|
|
1001
|
+
let read = tokio::io::AsyncReadExt::read_to_end(&mut client, &mut rest);
|
|
1002
|
+
tokio::time::timeout(Duration::from_secs(1), read)
|
|
1003
|
+
.await
|
|
1004
|
+
.unwrap_or_else(|_| panic!("{shown}: still open a second on"))
|
|
1005
|
+
.unwrap_or_else(|e| panic!("{shown}: the end: {e}"));
|
|
1006
|
+
}
|
|
1007
|
+
// Its task ends, which gives its permit back.
|
|
1008
|
+
let ended = tokio::time::timeout(Duration::from_secs(1), permits.acquire());
|
|
1009
|
+
assert!(
|
|
1010
|
+
ended.await.is_ok(),
|
|
1011
|
+
"{shown}: still served a second after its hand-back"
|
|
1012
|
+
);
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
1019
|
+
async fn a_request_whose_client_then_ends_its_side_is_answered_inline_where_hyper_closes_it() {
|
|
1020
|
+
let server = inline_loop_server(1, 8);
|
|
1021
|
+
let get = &b"GET /hello HTTP/1.1\r\nhost: x\r\n\r\n"[..];
|
|
1022
|
+
// The job reads a request whole and looks at the socket again only
|
|
1023
|
+
// for the next: it answers, then reads the end.
|
|
1024
|
+
let (client, mut conn) = loopback(&server);
|
|
1025
|
+
(&client).write_all(get).unwrap();
|
|
1026
|
+
client.shutdown(std::net::Shutdown::Write).unwrap();
|
|
1027
|
+
answer(&next_request(&mut conn), b"inline");
|
|
1028
|
+
assert!(
|
|
1029
|
+
reads_within(conn.fd().expect("open"), 5_000),
|
|
1030
|
+
"the end never came"
|
|
1031
|
+
);
|
|
1032
|
+
assert!(
|
|
1033
|
+
matches!(look(&mut conn, true), Next::Closed),
|
|
1034
|
+
"kept open past its client's end"
|
|
1035
|
+
);
|
|
1036
|
+
let read = read_to_end(&client);
|
|
1037
|
+
assert!(read.starts_with(b"HTTP/1.1 200 OK\r\n") && read.ends_with(b"\r\n\r\ninline"));
|
|
1038
|
+
// Part of a head, or nothing: it closes, and no app sees a request.
|
|
1039
|
+
for bytes in [&b"GET /hello HT"[..], b""] {
|
|
1040
|
+
let (client, mut conn) = loopback(&server);
|
|
1041
|
+
(&client).write_all(bytes).unwrap();
|
|
1042
|
+
client.shutdown(std::net::Shutdown::Write).unwrap();
|
|
1043
|
+
eventually_blocking("the close", || match conn.next(true) {
|
|
1044
|
+
Next::Closed => Some(()),
|
|
1045
|
+
Next::Readable => None,
|
|
1046
|
+
_ => panic!(
|
|
1047
|
+
"{:?} then the end: a request",
|
|
1048
|
+
bytes.escape_ascii().to_string()
|
|
1049
|
+
),
|
|
1050
|
+
});
|
|
1051
|
+
assert_eq!(read_to_end(&client), b"");
|
|
1052
|
+
}
|
|
1053
|
+
// Handed back whole, as its worker has no room: hyper reads the end
|
|
1054
|
+
// before any answer and closes, as on its own connections.
|
|
1055
|
+
let (client, mut conn) = loopback(&server);
|
|
1056
|
+
(&client).write_all(get).unwrap();
|
|
1057
|
+
client.shutdown(std::net::Shutdown::Write).unwrap();
|
|
1058
|
+
await_bytes(&conn);
|
|
1059
|
+
assert!(matches!(conn.next(false), Next::Closed));
|
|
1060
|
+
assert_eq!(read_to_end(&client), b"", "handed back: answered");
|
|
1061
|
+
assert_eq!(handbacks(&server), 1);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
1065
|
+
async fn a_connection_a_write_still_waits_on_is_cut_rather_than_handed_to_hyper() {
|
|
1066
|
+
let server = inline_loop_server(2, 8);
|
|
1067
|
+
let slot = slot(&server, 0);
|
|
1068
|
+
let (client, mut conn) = narrowed(&server);
|
|
1069
|
+
send_get(&client, "/s", false);
|
|
1070
|
+
let ctx = next_request(&mut conn);
|
|
1071
|
+
let io = ctx.inline.clone().expect("an inline request");
|
|
1072
|
+
assert!(io.start_stream(
|
|
1073
|
+
&ctx.responder,
|
|
1074
|
+
http::StatusCode::OK,
|
|
1075
|
+
&http::HeaderMap::new()
|
|
1076
|
+
));
|
|
1077
|
+
let chunk = vec![b'x'; 1 << 20];
|
|
1078
|
+
// A helper's write that waits on the socket, while the stream
|
|
1079
|
+
// ends; then its worker retires.
|
|
1080
|
+
loop {
|
|
1081
|
+
match io.write_chunk(&ctx.responder, &chunk) {
|
|
1082
|
+
Wrote::Done => {}
|
|
1083
|
+
Wrote::Wait(_) => break,
|
|
1084
|
+
wrote => panic!("the stream ended: {wrote:?}"),
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
io.finish_stream(&ctx.responder);
|
|
1088
|
+
slot.retire();
|
|
1089
|
+
let reader = std::thread::spawn(move || read_to_end(&client));
|
|
1090
|
+
|
|
1091
|
+
// Its answer out, its job would hand it to hyper: the descriptor
|
|
1092
|
+
// is the wait's, so the connection ends instead.
|
|
1093
|
+
assert!(matches!(once_written(&mut conn), Next::Closed));
|
|
1094
|
+
let read = reader.join().expect("the client");
|
|
1095
|
+
assert!(
|
|
1096
|
+
read.ends_with(b"0\r\n\r\n"),
|
|
1097
|
+
"the answer did not go out whole"
|
|
1098
|
+
);
|
|
1099
|
+
let counts = (handbacks(&server), cut_offs(&server));
|
|
1100
|
+
assert_eq!(counts, (0, 1));
|
|
1101
|
+
io.waited();
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
1105
|
+
async fn a_connection_whose_job_ends_while_it_waits_idle_goes_to_hyper_with_its_clients_request(
|
|
1106
|
+
) {
|
|
1107
|
+
let server = inline_loop_server(2, 8);
|
|
1108
|
+
let (client, mut conn) = loopback(&server);
|
|
1109
|
+
send_get(&client, "/first", false);
|
|
1110
|
+
answer(&next_request(&mut conn), b"inline");
|
|
1111
|
+
let mut wire = Wire::of(&client);
|
|
1112
|
+
assert_eq!(wire.response().2, b"inline");
|
|
1113
|
+
assert!(matches!(conn.next(true), Next::Readable));
|
|
1114
|
+
send_get(&client, "/sent", false);
|
|
1115
|
+
await_bytes(&conn);
|
|
1116
|
+
|
|
1117
|
+
// Its job ends (its task stopped, its thread killed) as it waits.
|
|
1118
|
+
drop(conn);
|
|
1119
|
+
|
|
1120
|
+
answer_dispatched(&server, &["/sent"]).await;
|
|
1121
|
+
assert_eq!(wire.response().2, b"hyper:/sent");
|
|
1122
|
+
assert_eq!((handbacks(&server), cut_offs(&server)), (1, 0));
|
|
1123
|
+
}
|
|
1124
|
+
}
|