kino 0.7.2 → 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.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +281 -0
  4. data/Cargo.lock +164 -95
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +17 -1
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
@@ -0,0 +1,628 @@
1
+ //! The inline tests' harness: servers that serve inline or leave every
2
+ //! connection to hyper, loopback clients connected to an inline
3
+ //! connection or to one the accept loop serves, the app's and hyper's
4
+ //! sides of a request, and a client that reads what comes back (Wire,
5
+ //! Event).
6
+
7
+ use std::io::{ErrorKind, Read, Write};
8
+ use std::net::{TcpListener, TcpStream};
9
+ use std::os::fd::{AsFd, RawFd};
10
+ use std::sync::atomic::{AtomicUsize, Ordering};
11
+ use std::sync::Arc;
12
+ use std::time::{Duration, Instant};
13
+
14
+ use bytes::Bytes;
15
+ use tokio_util::either::Either;
16
+
17
+ use super::{InlineConn, Next};
18
+ use crate::registry::{BoxedCtx, ServerInner};
19
+ use crate::request::RequestCtx;
20
+ use crate::server::testing::hyper_body_of;
21
+ use crate::server::{Accepted, Held, Peer};
22
+ use crate::slot::WorkerSlot;
23
+ use crate::testing::{eventually, eventually_blocking, permit, slot, TestServer};
24
+
25
+ /// A classic (queue) server with inline serving on and one worker slot;
26
+ /// hyper's requests land in its queue, and hand-backs run on the
27
+ /// caller's runtime.
28
+ pub fn server() -> Arc<ServerInner> {
29
+ configured_server(|_| {})
30
+ }
31
+
32
+ /// server(), as `set` changes its config.
33
+ pub fn configured_server(set: impl FnOnce(&mut crate::server::ServerConfig)) -> Arc<ServerInner> {
34
+ let test = TestServer::shared_queue().workers(1).with(|c| {
35
+ c.queue_depth = 8;
36
+ c.inline = true;
37
+ set(c);
38
+ });
39
+ let server = test.build();
40
+ let _ = server.io_runtime.set(tokio::runtime::Handle::current());
41
+ server
42
+ }
43
+
44
+ /// A worker_loop server serving inline, with `workers` workers that each
45
+ /// run up to `capacity` requests at once (their serve started).
46
+ pub fn inline_loop_server(workers: usize, capacity: usize) -> Arc<ServerInner> {
47
+ loop_server_as(workers, capacity, |test| test)
48
+ }
49
+
50
+ /// inline_loop_server, as `adjust` changes its TestServer.
51
+ pub fn loop_server_as(
52
+ workers: usize,
53
+ capacity: usize,
54
+ adjust: impl FnOnce(TestServer) -> TestServer,
55
+ ) -> Arc<ServerInner> {
56
+ let test = TestServer::worker_loop()
57
+ .workers(workers)
58
+ .capacity(capacity);
59
+ let test = test.with(|c| {
60
+ c.queue_depth = 8;
61
+ c.inline = true;
62
+ });
63
+ let server = adjust(test).build();
64
+ let _ = server.io_runtime.set(tokio::runtime::Handle::current());
65
+ server
66
+ }
67
+
68
+ /// A client connected over loopback, and the server's end.
69
+ fn pair() -> (TcpStream, TcpStream) {
70
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
71
+ let client = TcpStream::connect(listener.local_addr().expect("addr")).expect("connect");
72
+ let (stream, _) = listener.accept().expect("accept");
73
+ (client, stream)
74
+ }
75
+
76
+ /// Both ends as a test and a server need them: a `client` read that
77
+ /// hangs fails five seconds on, so its test fails instead, and `stream`
78
+ /// never blocks. The connection's addresses, as its server sees them.
79
+ fn ready(client: &TcpStream, stream: &TcpStream) -> Peer {
80
+ client
81
+ .set_read_timeout(Some(Duration::from_secs(5)))
82
+ .expect("read timeout");
83
+ stream.set_nonblocking(true).expect("nonblocking");
84
+ Peer {
85
+ remote: stream.peer_addr().expect("remote addr"),
86
+ local: stream.local_addr().expect("local addr"),
87
+ }
88
+ }
89
+
90
+ /// A connection as an accept loop has it, registered with the caller's
91
+ /// runtime and ready to place or serve, and its client.
92
+ pub fn accepted() -> (TcpStream, Accepted) {
93
+ let (client, stream) = pair();
94
+ let peer = ready(&client, &stream);
95
+ let stream = tokio::net::TcpStream::from_std(stream).expect("registered");
96
+ let (conn, held) = (Either::Left(stream), Held::new(permit(), None));
97
+ (client, Accepted { conn, peer, held })
98
+ }
99
+
100
+ /// One connection placed on `server` as the accept loop places it: its
101
+ /// client.
102
+ pub fn placed(server: &Arc<ServerInner>) -> TcpStream {
103
+ let (client, Accepted { conn, peer, held }) = accepted();
104
+ assert!(super::place(server, conn, held, peer).is_ok());
105
+ client
106
+ }
107
+
108
+ /// placed(), on the first worker: its siblings have no room meanwhile.
109
+ pub fn placed_on_first(server: &Arc<ServerInner>) -> TcpStream {
110
+ let siblings = server.slots.read()[1..].to_vec();
111
+ let room = |slot: &Arc<WorkerSlot>| slot.load.capacity.swap(0, Ordering::Relaxed);
112
+ let rooms: Vec<usize> = siblings.iter().map(room).collect();
113
+ let client = placed(server);
114
+ for (slot, room) in siblings.iter().zip(rooms) {
115
+ slot.load.capacity.store(room, Ordering::Relaxed);
116
+ }
117
+ client
118
+ }
119
+
120
+ /// `slot`'s worker is given up on as wedged.
121
+ pub fn wedge(slot: &WorkerSlot) {
122
+ assert!(slot.quarantine_at(slot.life.generation.load(Ordering::SeqCst)));
123
+ }
124
+
125
+ /// A connected client, and the server end as an inline connection of the
126
+ /// first worker slot, accepted on the caller's runtime.
127
+ pub fn loopback(server: &Arc<ServerInner>) -> (TcpStream, Box<InlineConn>) {
128
+ loopback_holding(server, permit())
129
+ }
130
+
131
+ /// loopback, the connection holding `permit` as its max_connections one.
132
+ pub fn loopback_holding(
133
+ server: &Arc<ServerInner>,
134
+ permit: tokio::sync::OwnedSemaphorePermit,
135
+ ) -> (TcpStream, Box<InlineConn>) {
136
+ let (client, stream) = pair();
137
+ inline_conn(server, permit, client, stream)
138
+ }
139
+
140
+ /// loopback, with the socket buffers between the client and the
141
+ /// connection narrowed to 4 KiB, so an answer of any size waits on its
142
+ /// client's reads. Narrowed before the handshake for Linux, which keeps
143
+ /// the window and segment size it set up (narrowed later, an answer
144
+ /// crawls out a window probe at a time), and again after it for macOS,
145
+ /// which sizes both buffers anew at the handshake.
146
+ pub fn narrowed(server: &Arc<ServerInner>) -> (TcpStream, Box<InlineConn>) {
147
+ use socket2::{Domain, SockRef, Socket, Type};
148
+
149
+ let sends = |socket: SockRef<'_>| socket.set_send_buffer_size(4096).expect("narrowed");
150
+ let reads = |socket: SockRef<'_>| socket.set_recv_buffer_size(4096).expect("narrowed");
151
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
152
+ // The connection's socket, once accepted, takes the listener's.
153
+ sends(SockRef::from(&listener));
154
+ let socket = Socket::new(Domain::IPV4, Type::STREAM, None).expect("a socket");
155
+ reads(SockRef::from(&socket));
156
+ socket
157
+ .connect(&listener.local_addr().expect("addr").into())
158
+ .expect("connect");
159
+ let client = TcpStream::from(socket);
160
+ let (stream, _) = listener.accept().expect("accept");
161
+ reads(SockRef::from(&client));
162
+ sends(SockRef::from(&stream));
163
+ inline_conn(server, permit(), client, stream)
164
+ }
165
+
166
+ /// `client`'s connection, the server's end `stream`, as an inline
167
+ /// connection of the first worker slot holding `permit`.
168
+ fn inline_conn(
169
+ server: &Arc<ServerInner>,
170
+ permit: tokio::sync::OwnedSemaphorePermit,
171
+ client: TcpStream,
172
+ stream: TcpStream,
173
+ ) -> (TcpStream, Box<InlineConn>) {
174
+ let peer = ready(&client, &stream);
175
+ let (seat, held) = (super::take_seat(&slot(server, 0)), Held::new(permit, None));
176
+ let home = tokio::runtime::Handle::current();
177
+ let conn = InlineConn::new(server, seat, stream.into(), held, peer, home);
178
+ conn.list();
179
+ (client, conn)
180
+ }
181
+
182
+ impl From<TcpStream> for crate::server::StdConn {
183
+ fn from(stream: TcpStream) -> Self {
184
+ let (socket, unix) = (stream.into(), false);
185
+ crate::server::StdConn { socket, unix }
186
+ }
187
+ }
188
+
189
+ /// What tests read of a connection past its job's looks.
190
+ impl InlineConn {
191
+ /// Whether its client's bytes have arrived, for a look that must
192
+ /// find them.
193
+ pub fn readable(&self) -> bool {
194
+ self.io.state.lock().unread()
195
+ }
196
+
197
+ /// The size of its write buffer.
198
+ pub fn write_buffered(&self) -> usize {
199
+ self.io.state.lock().out.buf.len()
200
+ }
201
+
202
+ /// What its write buffer holds that the socket did not take yet.
203
+ pub fn unsent(&self) -> usize {
204
+ let state = self.io.state.lock();
205
+ state.out.buf.len() - state.out.pos
206
+ }
207
+ }
208
+
209
+ /// inline_loop_server, its spin on, a lone connection's job spinning
210
+ /// for up to `budget`, in runs as long.
211
+ pub fn spinning_server(workers: usize, budget: Duration) -> Arc<ServerInner> {
212
+ let mut server = inline_loop_server(workers, 8);
213
+ let own = Arc::get_mut(&mut server).and_then(|server| server.inline.as_mut());
214
+ let inline = own.and_then(Arc::get_mut).expect("a server of its own");
215
+ (inline.spin_budget, inline.spin_run) = (budget, budget);
216
+ *inline.spin_on.get_mut() = true;
217
+ server
218
+ }
219
+
220
+ /// `client` sends each write at once, and closes abortively: neither
221
+ /// end waits in TIME_WAIT, so the many connections tests open never run
222
+ /// the host out of ports. Without the first, a client's second small
223
+ /// write waits for its first's ack, which Linux delays.
224
+ pub fn abortive(client: &TcpStream) {
225
+ client.set_nodelay(true).expect("nodelay");
226
+ let socket = socket2::SockRef::from(client);
227
+ socket.set_linger(Some(Duration::ZERO)).expect("linger off");
228
+ }
229
+
230
+ /// Everything `client` reads until the server ends the connection.
231
+ pub fn read_to_end(client: &TcpStream) -> Vec<u8> {
232
+ let mut read = Vec::new();
233
+ match (&*client).read_to_end(&mut read) {
234
+ Ok(_) => read,
235
+ // Shut down with bytes of its own unread, the server resets.
236
+ Err(e) if e.kind() == ErrorKind::ConnectionReset => read,
237
+ Err(e) => panic!("the end never came: {e}"),
238
+ }
239
+ }
240
+
241
+ /// `client` sends a GET of `path`, asking the connection to end after
242
+ /// its answer when `close` is set.
243
+ pub fn send_get(client: &TcpStream, path: &str, close: bool) {
244
+ let close = if close { "connection: close\r\n" } else { "" };
245
+ let head = format!("GET {path} HTTP/1.1\r\nhost: x\r\n{close}\r\n");
246
+ (&*client).write_all(head.as_bytes()).unwrap();
247
+ }
248
+
249
+ /// A request for `target` with a body of `length` bytes, the body's
250
+ /// first `sent` bytes included.
251
+ pub fn with_body(target: &str, length: usize, sent: usize) -> Vec<u8> {
252
+ let head = format!("POST {target} HTTP/1.1\r\nhost: x\r\ncontent-length: {length}\r\n\r\n");
253
+ let mut request = head.into_bytes();
254
+ request.extend((0..sent).map(|i| b'a' + (i % 26) as u8));
255
+ request
256
+ }
257
+
258
+ /// What `conn`'s job sees once the answer it wrote last is out, past
259
+ /// the looks that wait for its client to take it.
260
+ pub fn once_written(conn: &mut InlineConn) -> Next {
261
+ let deadline = Instant::now() + Duration::from_secs(10);
262
+ loop {
263
+ match conn.next(true) {
264
+ Next::Writable => {
265
+ assert!(Instant::now() < deadline, "the answer never went out");
266
+ if let Some(fd) = conn.fd() {
267
+ super::await_writable(fd, Duration::from_millis(10));
268
+ }
269
+ }
270
+ next => return next,
271
+ }
272
+ }
273
+ }
274
+
275
+ /// What `conn`'s job finds as it looks with what its client sent by now
276
+ /// in hand: past a look that waits on a socket that reads ready already,
277
+ /// as the first look after a request waits its turn before it reads, and
278
+ /// the app's scheduler then wakes the job at once.
279
+ pub fn look(conn: &mut InlineConn, room: bool) -> Next {
280
+ let deadline = Instant::now() + Duration::from_secs(10);
281
+ loop {
282
+ match conn.next(room) {
283
+ Next::Readable if conn.fd().is_some_and(|fd| reads_within(fd, 0)) => {
284
+ assert!(
285
+ Instant::now() < deadline,
286
+ "the job never read its socket's bytes"
287
+ );
288
+ }
289
+ next => return next,
290
+ }
291
+ }
292
+ }
293
+
294
+ /// Whether socket `fd` reads ready (bytes, or its peer's end) within `ms`
295
+ /// (0: now).
296
+ pub fn reads_within(fd: RawFd, ms: libc::c_int) -> bool {
297
+ super::io::poll_for(fd, libc::POLLIN, ms).is_some()
298
+ }
299
+
300
+ /// `server`'s inline clock, `by` further on: its connections' deadlines
301
+ /// come due as if that long had passed. From there its ticker's looks
302
+ /// (tick) run on with real time.
303
+ pub fn advance(server: &ServerInner, by: Duration) {
304
+ let inline = server.inline.as_ref().expect("inline on");
305
+ let by = u64::try_from(by.as_micros()).expect("a test's span");
306
+ let clock = inline.clock.0.fetch_add(by, Ordering::Relaxed) + by;
307
+ let ahead = clock.saturating_sub(crate::mono::mono_us());
308
+ inline.ahead.store(ahead, Ordering::Relaxed);
309
+ }
310
+
311
+ /// The ticker's look at `server`'s inline connections (inline::tick),
312
+ /// once `by` more has passed on its inline clock.
313
+ pub fn elapse(server: &ServerInner, by: Duration) {
314
+ advance(server, by);
315
+ super::tick(server);
316
+ }
317
+
318
+ /// Waits until `conn`'s client's bytes have arrived.
319
+ pub fn await_bytes(conn: &InlineConn) {
320
+ eventually_blocking("the client's bytes", || conn.readable().then_some(()));
321
+ }
322
+
323
+ /// The body an inline request carries, all of it there before the app
324
+ /// runs: its chunks, then the end.
325
+ pub fn body_of(ctx: &RequestCtx) -> Vec<u8> {
326
+ let Some(body_rx) = &ctx.body_rx else {
327
+ return Vec::new();
328
+ };
329
+ let mut body = Vec::new();
330
+ loop {
331
+ match body_rx.try_recv() {
332
+ Ok(chunk) => body.extend_from_slice(&chunk),
333
+ Err(flume::TryRecvError::Disconnected) => return body,
334
+ Err(flume::TryRecvError::Empty) => panic!("the app would wait for the body's end"),
335
+ }
336
+ }
337
+ }
338
+
339
+ /// Whether an answer's `headers` (Wire's lines) end its connection.
340
+ pub fn closes(headers: &[String]) -> bool {
341
+ headers.iter().any(|line| line == "connection: close")
342
+ }
343
+
344
+ /// The next request on `conn`, waiting for its bytes.
345
+ pub fn next_request(conn: &mut InlineConn) -> BoxedCtx {
346
+ eventually_blocking("the next request", || match conn.next(true) {
347
+ Next::Request(ctx) => Some(ctx),
348
+ Next::Readable => None,
349
+ Next::Writable => panic!("a response is still going out"),
350
+ Next::Closed => panic!("the connection ended before a request"),
351
+ })
352
+ }
353
+
354
+ /// Answers `ctx` inline, as InlineIo::respond writes it: a 200 with `body`.
355
+ pub fn answer(ctx: &RequestCtx, body: &[u8]) {
356
+ let io = ctx.inline.as_deref().expect("an inline request");
357
+ let answered = io.respond(
358
+ &ctx.responder,
359
+ http::StatusCode::OK,
360
+ &http::HeaderMap::new(),
361
+ body,
362
+ );
363
+ assert!(answered, "something answered {} first", ctx.uri);
364
+ }
365
+
366
+ /// Hyper's side of a hand-back on a worker_loop server: the requests for
367
+ /// `paths` that hyper sent to the workers' lanes, each answered with a
368
+ /// 200 once its body is read, its body naming it: "hyper:<path>", then
369
+ /// ":<body>" if it had one. What else the lanes hold is taken and
370
+ /// dropped.
371
+ pub async fn answer_dispatched(server: &Arc<ServerInner>, paths: &[&str]) {
372
+ let slots = server.slots.read().clone();
373
+ let mut left = paths.to_vec();
374
+ while !left.is_empty() {
375
+ let ctx = eventually(format!("hyper sending {left:?} to a lane"), || {
376
+ slots.iter().find_map(|slot| loop {
377
+ match crate::queue::Taker::new(server, slot).ready() {
378
+ crate::queue::Take::Item(crate::queue::Item::Ctx(ctx)) => return Some(ctx),
379
+ crate::queue::Take::Item(_) => {}
380
+ crate::queue::Take::Closed | crate::queue::Take::Nothing => return None,
381
+ }
382
+ })
383
+ });
384
+ let ctx: BoxedCtx = ctx.await;
385
+ let Some(at) = left.iter().position(|path| *path == ctx.uri.path()) else {
386
+ continue;
387
+ };
388
+ left.swap_remove(at);
389
+ let body = hyper_body_of(ctx.body_rx.as_ref()).await;
390
+ let mut text = format!("hyper:{}", ctx.uri.path()).into_bytes();
391
+ if !body.is_empty() {
392
+ text.push(b':');
393
+ text.extend(body);
394
+ }
395
+ let body = crate::response::full_body(Bytes::from(text));
396
+ let response = hyper::Response::builder().body(body).expect("a response");
397
+ assert!(ctx.responder.send_response(response), "answered first");
398
+ }
399
+ }
400
+
401
+ /// How many connections `server` handed back to hyper.
402
+ pub fn handbacks(server: &ServerInner) -> u64 {
403
+ server.inline.as_ref().expect("inline on").handbacks()
404
+ }
405
+
406
+ /// `server`'s inline stats now.
407
+ pub fn inline_stats(server: &ServerInner) -> crate::stats::InlineSnapshot {
408
+ crate::stats::Snapshot::take(server)
409
+ .inline
410
+ .expect("inline on")
411
+ }
412
+
413
+ /// How many inline connections `server` cut off.
414
+ pub fn cut_offs(server: &ServerInner) -> u64 {
415
+ inline_stats(server).closed
416
+ }
417
+
418
+ /// How much of its answers a client read so far (Wire counts it).
419
+ #[derive(Clone, Default)]
420
+ pub struct Taken(pub Arc<AtomicUsize>);
421
+
422
+ /// What a client reads.
423
+ #[derive(Clone, Debug, PartialEq, Eq)]
424
+ pub enum Event {
425
+ /// An answer: its status line, its header lines (lower-case names,
426
+ /// sorted, no date) and its body as framed.
427
+ Answer {
428
+ status: String,
429
+ headers: Vec<String>,
430
+ body: Vec<u8>,
431
+ },
432
+ /// An answer whose body was cut off: its head, and what came of the
433
+ /// body.
434
+ Cut {
435
+ status: String,
436
+ headers: Vec<String>,
437
+ body: Vec<u8>,
438
+ },
439
+ /// Bytes that are no whole HTTP/1 head, up to the end.
440
+ Raw(Vec<u8>),
441
+ /// The follow-up request was answered: the connection stayed open.
442
+ Open,
443
+ /// The server ended the connection.
444
+ Closed,
445
+ /// The server reset the connection (Wire::end; elsewhere a reset is
446
+ /// Closed).
447
+ Reset,
448
+ /// Nothing came for the client's read timeout.
449
+ Hung,
450
+ }
451
+
452
+ /// Why a read stopped: the end, or a pause.
453
+ struct Stop;
454
+
455
+ /// A client's end (TCP or unix), read ahead, its reads counted in
456
+ /// `taken`.
457
+ pub struct Wire {
458
+ stream: socket2::Socket,
459
+ buf: Vec<u8>,
460
+ pub taken: Taken,
461
+ hung: bool,
462
+ reset: bool,
463
+ }
464
+
465
+ impl Wire {
466
+ pub fn of(client: &impl AsFd) -> Wire {
467
+ let stream = client.as_fd().try_clone_to_owned().expect("a clone");
468
+ Wire {
469
+ stream: stream.into(),
470
+ buf: Vec::new(),
471
+ taken: Taken::default(),
472
+ hung: false,
473
+ reset: false,
474
+ }
475
+ }
476
+
477
+ /// The next answer, whole: its status line, header lines and body.
478
+ pub fn response(&mut self) -> (String, Vec<String>, Vec<u8>) {
479
+ match self.answer(false) {
480
+ Event::Answer {
481
+ status,
482
+ headers,
483
+ body,
484
+ ..
485
+ } => (status, headers, body),
486
+ other => panic!("no whole answer: {other:?}"),
487
+ }
488
+ }
489
+
490
+ /// More bytes, or the end (a reset too: closed with bytes of the
491
+ /// client's unread), or a pause past the client's read timeout (hung).
492
+ fn more(&mut self) -> Result<(), Stop> {
493
+ let mut chunk = [0u8; 64 * 1024];
494
+ let read = loop {
495
+ match (&self.stream).read(&mut chunk) {
496
+ Err(e) if e.kind() == ErrorKind::Interrupted => {}
497
+ read => break read,
498
+ }
499
+ };
500
+ let paused =
501
+ |e: &std::io::Error| matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut);
502
+ self.hung = read.as_ref().is_err_and(paused);
503
+ self.reset = read
504
+ .as_ref()
505
+ .is_err_and(|e| e.kind() == ErrorKind::ConnectionReset);
506
+ let n = read.unwrap_or(0);
507
+ self.buf.extend_from_slice(&chunk[..n]);
508
+ self.taken.0.fetch_add(n, Ordering::Relaxed);
509
+ if n > 0 {
510
+ Ok(())
511
+ } else {
512
+ Err(Stop)
513
+ }
514
+ }
515
+
516
+ /// What comes after the answers read, as answer() has it, but a reset
517
+ /// is Reset: Closed is the server's end alone.
518
+ pub fn end(&mut self) -> Event {
519
+ match self.answer(false) {
520
+ Event::Closed if self.reset => Event::Reset,
521
+ event => event,
522
+ }
523
+ }
524
+
525
+ /// The offset just past the first `needle` read ahead from `from`.
526
+ fn find(&mut self, from: usize, needle: &[u8]) -> Result<usize, Stop> {
527
+ loop {
528
+ let mut ahead = self.buf[from.min(self.buf.len())..].windows(needle.len());
529
+ if let Some(at) = ahead.position(|window| window == needle) {
530
+ return Ok(from + at + needle.len());
531
+ }
532
+ self.more()?;
533
+ }
534
+ }
535
+
536
+ /// At least `n` bytes read ahead, then the first `n` taken.
537
+ fn take(&mut self, n: usize) -> Result<Vec<u8>, Stop> {
538
+ while self.buf.len() < n {
539
+ self.more()?;
540
+ }
541
+ Ok(self.buf.drain(..n).collect())
542
+ }
543
+
544
+ /// The next answer, to a HEAD if `head_only`, past any interim ones.
545
+ pub fn answer(&mut self, head_only: bool) -> Event {
546
+ loop {
547
+ if self.buf.is_empty() && self.more().is_err() {
548
+ return if self.hung {
549
+ Event::Hung
550
+ } else {
551
+ Event::Closed
552
+ };
553
+ }
554
+ let seen = self.buf.len().min(7);
555
+ let Ok(end) = self.find(0, b"\r\n\r\n") else {
556
+ return Event::Raw(std::mem::take(&mut self.buf));
557
+ };
558
+ if self.buf[..seen] != b"HTTP/1."[..seen] {
559
+ while self.more().is_ok() {}
560
+ return Event::Raw(std::mem::take(&mut self.buf));
561
+ }
562
+ let head = String::from_utf8_lossy(&self.buf[..end - 4]).into_owned();
563
+ self.buf.drain(..end);
564
+ let mut head_lines = head.split("\r\n");
565
+ let status = head_lines.next().unwrap_or_default().to_string();
566
+ let mut headers: Vec<String> = head_lines
567
+ .map(|line| match line.split_once(':') {
568
+ Some((name, value)) => format!("{}:{value}", name.to_ascii_lowercase()),
569
+ None => line.to_string(),
570
+ })
571
+ .filter(|line| !line.starts_with("date:"))
572
+ .collect();
573
+ headers.sort();
574
+ let code: u16 = status.get(9..12).and_then(|c| c.parse().ok()).unwrap_or(0);
575
+ if (100..200).contains(&code) && code != 101 {
576
+ continue;
577
+ }
578
+ let header = |name: &str| {
579
+ let value = headers.iter().find_map(|line| line.strip_prefix(name));
580
+ value.map(str::trim)
581
+ };
582
+ let chunked = header("transfer-encoding:").is_some_and(|te| te.ends_with("chunked"));
583
+ let length = header("content-length:").and_then(|cl| cl.parse::<usize>().ok());
584
+ let body = if head_only || [101, 204, 304].contains(&code) {
585
+ Ok(Vec::new())
586
+ } else if chunked {
587
+ self.chunked()
588
+ } else if let Some(length) = length {
589
+ self.take(length)
590
+ } else {
591
+ // Framed by its end.
592
+ while self.more().is_ok() {}
593
+ Ok(std::mem::take(&mut self.buf))
594
+ };
595
+ return match body {
596
+ Ok(body) => Event::Answer {
597
+ status,
598
+ headers,
599
+ body,
600
+ },
601
+ Err(Stop) => Event::Cut {
602
+ status,
603
+ headers,
604
+ body: std::mem::take(&mut self.buf),
605
+ },
606
+ };
607
+ }
608
+ }
609
+
610
+ /// A chunked body, as framed.
611
+ fn chunked(&mut self) -> Result<Vec<u8>, Stop> {
612
+ let mut at = 0;
613
+ loop {
614
+ let line_end = self.find(at, b"\r\n")?;
615
+ let line = String::from_utf8_lossy(&self.buf[at..line_end - 2]).into_owned();
616
+ let size = line.split(';').next().unwrap_or("").trim();
617
+ let size = usize::from_str_radix(size, 16).unwrap_or(0);
618
+ if size == 0 {
619
+ let end = self.find(line_end - 2, b"\r\n\r\n")?;
620
+ return self.take(end);
621
+ }
622
+ at = line_end + size + 2;
623
+ while self.buf.len() < at {
624
+ self.more()?;
625
+ }
626
+ }
627
+ }
628
+ }