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.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +286 -0
  4. data/Cargo.lock +209 -132
  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 +19 -3
  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,862 @@
1
+ //! Inline serving against hyper. Each request of a corpus goes to a
2
+ //! connection hyper serves and to an inline one, both answered by one
3
+ //! app: what their clients read must agree, and the inline connection
4
+ //! goes back to hyper for the reason its row names, or serves it all
5
+ //! itself where the row names none. Then the subset parser is fuzzed: it
6
+ //! never panics, and what it accepts httparse, the http crate and hyper
7
+ //! read the same way.
8
+
9
+ use std::io::Write;
10
+ use std::net::TcpStream;
11
+ use std::sync::atomic::Ordering;
12
+ use std::sync::Arc;
13
+ use std::time::{Duration, Instant};
14
+
15
+ use bytes::Bytes;
16
+ use http::StatusCode;
17
+
18
+ use super::testing::{abortive, accepted, body_of, loopback, server, Event, Taken, Wire};
19
+ use super::{InlineConn, Next, Wrote};
20
+ use crate::registry::{BoxedCtx, ServerInner};
21
+ use crate::request::RequestCtx;
22
+ use crate::response::{BodyFrame, Cut};
23
+ use crate::server::testing::hyper_body_of;
24
+
25
+ /// How the app answers each request of a row.
26
+ #[derive(Clone, Copy)]
27
+ struct Reply {
28
+ status: u16,
29
+ headers: &'static [(&'static str, &'static str)],
30
+ body: Body,
31
+ }
32
+
33
+ #[derive(Clone, Copy)]
34
+ enum Body {
35
+ Full(&'static [u8]),
36
+ /// A stream: its head, these writes, then its end.
37
+ Stream(&'static [&'static [u8]]),
38
+ /// A stream the app raises out of after these writes.
39
+ Raise(&'static [&'static [u8]]),
40
+ /// A stream that ends after these writes, short of the app's length.
41
+ Stops(&'static [&'static [u8]]),
42
+ }
43
+
44
+ const TEXT: &[(&str, &str)] = &[("content-type", "text/plain")];
45
+ const CL: (&str, &str) = ("content-length", "5");
46
+ const TE: (&str, &str) = ("transfer-encoding", "chunked");
47
+ const LENGTH_FIVE: &[(&str, &str)] = &[CL];
48
+ const HELLO: Reply = full(200, TEXT, b"hello");
49
+
50
+ const fn full(
51
+ status: u16,
52
+ headers: &'static [(&'static str, &'static str)],
53
+ body: &'static [u8],
54
+ ) -> Reply {
55
+ Reply {
56
+ status,
57
+ headers,
58
+ body: Body::Full(body),
59
+ }
60
+ }
61
+
62
+ const fn streamed(
63
+ status: u16,
64
+ headers: &'static [(&'static str, &'static str)],
65
+ writes: &'static [&'static [u8]],
66
+ ) -> Reply {
67
+ Reply {
68
+ status,
69
+ headers,
70
+ body: Body::Stream(writes),
71
+ }
72
+ }
73
+
74
+ /// How long an app waits on its client's reads.
75
+ const PATIENCE: Duration = Duration::from_secs(5);
76
+
77
+ /// Once the client `taken` counts for read past `seen` (or a few seconds
78
+ /// on): how much. hyper drops what it holds of a stream that ends early
79
+ /// at once, and writes it out when the stream's next write is not there
80
+ /// yet: an app whose stream ends so goes on only once its client read
81
+ /// what it sent.
82
+ fn past(taken: &Taken, seen: usize) -> usize {
83
+ let deadline = Instant::now() + PATIENCE;
84
+ while taken.0.load(Ordering::Relaxed) <= seen && Instant::now() < deadline {
85
+ std::thread::sleep(Duration::from_millis(1));
86
+ }
87
+ taken.0.load(Ordering::Relaxed)
88
+ }
89
+
90
+ async fn past_async(taken: &Taken, seen: usize) -> usize {
91
+ let deadline = Instant::now() + PATIENCE;
92
+ while taken.0.load(Ordering::Relaxed) <= seen && Instant::now() < deadline {
93
+ tokio::time::sleep(Duration::from_millis(1)).await;
94
+ }
95
+ taken.0.load(Ordering::Relaxed)
96
+ }
97
+
98
+ /// The app's answer to `ctx` (a follow-up's is HELLO), its headers with
99
+ /// what the app saw of the request (x-saw): the request line as parsed,
100
+ /// its headers in order, and its body.
101
+ fn answer_for(ctx: &RequestCtx, body: &[u8], reply: Reply) -> (Reply, http::HeaderMap) {
102
+ let reply = if ctx.uri.path() == "/follow-up" {
103
+ HELLO
104
+ } else {
105
+ reply
106
+ };
107
+ let mut headers = http::HeaderMap::new();
108
+ for (name, value) in reply.headers {
109
+ let name = http::HeaderName::from_bytes(name.as_bytes()).expect("a name");
110
+ headers.append(
111
+ name,
112
+ http::HeaderValue::from_bytes(value.as_bytes()).expect("a value"),
113
+ );
114
+ }
115
+ let mut saw = format!("{} {} {:?}", ctx.method, ctx.uri, ctx.version);
116
+ for (name, value) in &ctx.headers {
117
+ saw.push_str(&format!(" {name}={}", value.as_bytes().escape_ascii()));
118
+ }
119
+ let shown = &body[..body.len().min(32)];
120
+ saw.push_str(&format!(" body={}:{}", body.len(), shown.escape_ascii()));
121
+ headers.append(
122
+ "x-saw",
123
+ http::HeaderValue::from_str(&saw).expect("an escaped value"),
124
+ );
125
+ (reply, headers)
126
+ }
127
+
128
+ /// The app answers an inline request, as request.rs writes it. A stream
129
+ /// that ends early goes on only once its client read what it sent, as
130
+ /// hyper drops what it holds of such a stream at once.
131
+ fn answer_inline(ctx: &RequestCtx, reply: Reply, taken: &Taken) {
132
+ let io = ctx.inline.as_deref().expect("an inline request");
133
+ let (reply, headers) = answer_for(ctx, &body_of(ctx), reply);
134
+ let status = StatusCode::from_u16(reply.status).expect("a status");
135
+ let (writes, waits) = match reply.body {
136
+ Body::Full(body) => {
137
+ io.respond(&ctx.responder, status, &headers, body);
138
+ return;
139
+ }
140
+ Body::Stream(writes) => (writes, false),
141
+ Body::Raise(writes) | Body::Stops(writes) => (writes, true),
142
+ };
143
+ let mut seen = taken.0.load(Ordering::Relaxed);
144
+ if !io.start_stream(&ctx.responder, status, &headers) {
145
+ return;
146
+ }
147
+ if waits {
148
+ seen = past(taken, seen);
149
+ }
150
+ 'writes: for data in writes {
151
+ loop {
152
+ match io.write_chunk(&ctx.responder, data) {
153
+ Wrote::Done => break,
154
+ Wrote::Wait(fd) => {
155
+ super::await_writable(fd, Duration::from_millis(10));
156
+ io.waited();
157
+ }
158
+ Wrote::Gone | Wrote::Closed => break 'writes,
159
+ }
160
+ }
161
+ if waits {
162
+ seen = past(taken, seen);
163
+ }
164
+ }
165
+ match reply.body {
166
+ Body::Raise(_) => ctx.responder.give_up(Cut::Crash),
167
+ _ => io.finish_stream(&ctx.responder),
168
+ }
169
+ }
170
+
171
+ /// The app answers a request hyper read, as request.rs sends it.
172
+ async fn answer_hyper(ctx: BoxedCtx, reply: Reply, taken: &Taken) {
173
+ let body = hyper_body_of(ctx.body_rx.as_ref()).await;
174
+ let (reply, headers) = answer_for(&ctx, &body, reply);
175
+ let mut builder = hyper::Response::builder().status(reply.status);
176
+ for (name, value) in &headers {
177
+ builder = builder.header(name, value);
178
+ }
179
+ let (writes, waits) = match reply.body {
180
+ Body::Full(body) => {
181
+ let sent = crate::request::frame_by_length(
182
+ &mut builder,
183
+ reply.status,
184
+ &ctx.method,
185
+ body.len(),
186
+ );
187
+ let body = if sent {
188
+ Bytes::from_static(body)
189
+ } else {
190
+ Bytes::new()
191
+ };
192
+ let response = builder
193
+ .body(crate::response::full_body(body))
194
+ .expect("a response");
195
+ ctx.responder.send_response(response);
196
+ return;
197
+ }
198
+ Body::Stream(writes) => (writes, false),
199
+ Body::Raise(writes) | Body::Stops(writes) => (writes, true),
200
+ };
201
+ let mut seen = taken.0.load(Ordering::Relaxed);
202
+ let head = ctx.method == http::Method::HEAD;
203
+ let sent = match crate::framing::Bodiless::of(reply.status, head) {
204
+ Some(bodiless) => ctx.responder.send_bodiless_head(builder, bodiless),
205
+ None => ctx.responder.send_stream_head(builder),
206
+ };
207
+ if !matches!(sent, Ok(true)) {
208
+ return;
209
+ }
210
+ if waits {
211
+ seen = past_async(taken, seen).await;
212
+ }
213
+ if let Some(frames) = ctx.responder.body_sender() {
214
+ for data in writes {
215
+ if frames
216
+ .send_async(Ok(BodyFrame::data(Bytes::from_static(data))))
217
+ .await
218
+ .is_err()
219
+ {
220
+ break;
221
+ }
222
+ if waits {
223
+ seen = past_async(taken, seen).await;
224
+ }
225
+ }
226
+ }
227
+ match reply.body {
228
+ Body::Raise(_) => ctx.responder.give_up(Cut::Crash),
229
+ _ => ctx.responder.finish_stream(),
230
+ }
231
+ }
232
+
233
+ /// `server`'s app for what hyper reads: each request its queue gets,
234
+ /// answered with `reply`, until aborted.
235
+ fn app(server: &Arc<ServerInner>, reply: Reply, taken: Taken) -> tokio::task::JoinHandle<()> {
236
+ let server = server.clone();
237
+ tokio::spawn(async move {
238
+ while let Ok(ctx) = server.req_rx.recv_async().await {
239
+ answer_hyper(ctx, reply, &taken).await;
240
+ }
241
+ })
242
+ }
243
+
244
+ /// An inline connection's job: each request it reads answered with
245
+ /// `reply`, until it closes or goes back to hyper, or ten seconds pass
246
+ /// with nothing to run. The requests it ran, as "METHOD target".
247
+ fn job(
248
+ mut conn: Box<InlineConn>,
249
+ reply: Reply,
250
+ taken: Taken,
251
+ ) -> std::thread::JoinHandle<Vec<String>> {
252
+ std::thread::spawn(move || {
253
+ let mut ran = Vec::new();
254
+ let deadline = Instant::now() + Duration::from_secs(10);
255
+ loop {
256
+ match conn.next(true) {
257
+ Next::Request(ctx) => {
258
+ ran.push(format!("{} {}", ctx.method, ctx.uri));
259
+ answer_inline(&ctx, reply, &taken);
260
+ }
261
+ Next::Readable | Next::Writable if Instant::now() < deadline => {
262
+ std::thread::sleep(Duration::from_millis(1));
263
+ }
264
+ Next::Readable | Next::Writable => {
265
+ ran.push("(the job gave up waiting)".to_string());
266
+ return ran;
267
+ }
268
+ Next::Closed => return ran,
269
+ }
270
+ }
271
+ })
272
+ }
273
+
274
+ /// A raw exchange: what the client sends, in pieces `pause` apart, and
275
+ /// the answers it reads, true for each to a HEAD.
276
+ #[derive(Clone)]
277
+ struct Row {
278
+ name: &'static str,
279
+ sent: Vec<Vec<u8>>,
280
+ pause: Duration,
281
+ reads: Vec<bool>,
282
+ reply: Reply,
283
+ /// A recorded deviation, named: what the inline client reads instead
284
+ /// (lines, x-saw aside).
285
+ deviation: Option<(&'static str, Vec<&'static str>)>,
286
+ /// Why an inline connection hands it back to hyper, if it does (the
287
+ /// server counts a total: the reason is the reader's).
288
+ handed_back: Option<&'static str>,
289
+ }
290
+
291
+ fn row(name: &'static str, sent: impl Into<Vec<u8>>) -> Row {
292
+ Row {
293
+ name,
294
+ sent: vec![sent.into()],
295
+ pause: Duration::ZERO,
296
+ reads: vec![false],
297
+ reply: HELLO,
298
+ deviation: None,
299
+ handed_back: None,
300
+ }
301
+ }
302
+
303
+ impl Row {
304
+ fn reads(mut self, reads: &[bool]) -> Self {
305
+ self.reads = reads.to_vec();
306
+ self
307
+ }
308
+
309
+ fn reply(mut self, reply: Reply) -> Self {
310
+ self.reply = reply;
311
+ self
312
+ }
313
+
314
+ /// What it sends goes in pieces of `size` bytes, `pause` apart.
315
+ fn pieces(mut self, size: usize, pause: Duration) -> Self {
316
+ let sent = self.sent.concat();
317
+ self.sent = sent.chunks(size).map(<[u8]>::to_vec).collect();
318
+ self.pause = pause;
319
+ self
320
+ }
321
+
322
+ fn handed_back(mut self, why: &'static str) -> Self {
323
+ self.handed_back = Some(why);
324
+ self
325
+ }
326
+
327
+ fn deviation(mut self, why: &'static str, inline: &[&'static str]) -> Self {
328
+ self.deviation = Some((why, inline.to_vec()));
329
+ self
330
+ }
331
+ }
332
+
333
+ /// What `client` reads of `row`, its reads counted in `taken`: it sends
334
+ /// the row, reads its answers, then, unless the connection ended, a
335
+ /// follow-up's (Event::Open if answered).
336
+ fn view(client: TcpStream, row: &Row, taken: &Taken) -> Vec<Event> {
337
+ let mut wire = Wire::of(&client);
338
+ wire.taken = taken.clone();
339
+ for (i, piece) in row.sent.iter().enumerate() {
340
+ if i > 0 {
341
+ std::thread::sleep(row.pause);
342
+ }
343
+ if (&client).write_all(piece).is_err() {
344
+ break;
345
+ }
346
+ }
347
+ let mut events = Vec::new();
348
+ for &head_only in &row.reads {
349
+ let event = wire.answer(head_only);
350
+ let answered = matches!(event, Event::Answer { .. });
351
+ let cut = matches!(event, Event::Raw(_) | Event::Cut { .. });
352
+ events.push(event);
353
+ if !answered {
354
+ if cut {
355
+ events.push(wire.answer(false));
356
+ }
357
+ return events;
358
+ }
359
+ }
360
+ if (&client)
361
+ .write_all(b"GET /follow-up HTTP/1.1\r\nhost: x\r\n\r\n")
362
+ .is_err()
363
+ {
364
+ events.push(Event::Closed);
365
+ return events;
366
+ }
367
+ events.push(match wire.answer(false) {
368
+ Event::Answer { headers, .. }
369
+ if headers
370
+ .iter()
371
+ .any(|line| line.starts_with("x-saw: GET /follow-up")) =>
372
+ {
373
+ Event::Open
374
+ }
375
+ other => other,
376
+ });
377
+ events
378
+ }
379
+
380
+ /// What a client of a connection hyper serves reads of `row`.
381
+ async fn hyper_view(row: &Row) -> Vec<Event> {
382
+ let test = crate::testing::TestServer::shared_queue().workers(1);
383
+ let server = test.with(|c| (c.queue_depth, c.http2) = (8, true)).build();
384
+ let taken = Taken::default();
385
+ let app = app(&server, row.reply, taken.clone());
386
+ let (client, accepted) = accepted();
387
+ abortive(&client);
388
+ tokio::spawn(crate::server::serve_conn(accepted, None, server.clone()));
389
+ let events = tokio::task::block_in_place(|| view(client, row, &taken));
390
+ app.abort();
391
+ events
392
+ }
393
+
394
+ /// `events` as lines: each answer's status, headers (x-saw only if
395
+ /// `saw`) and body, and how the connection ended.
396
+ fn lines(events: &[Event], saw: bool) -> Vec<String> {
397
+ let shown = |bytes: &[u8]| match bytes.len() {
398
+ 0..=96 => bytes.escape_ascii().to_string(),
399
+ n => format!("{}... ({n} bytes)", bytes[..96].escape_ascii()),
400
+ };
401
+ let mut lines = Vec::new();
402
+ for event in events {
403
+ let (cut, status, headers, body) = match event {
404
+ Event::Answer {
405
+ status,
406
+ headers,
407
+ body,
408
+ } => ("", status, headers, body),
409
+ Event::Cut {
410
+ status,
411
+ headers,
412
+ body,
413
+ } => ("cut short: ", status, headers, body),
414
+ other => {
415
+ lines.push(format!("{other:?}").to_lowercase());
416
+ continue;
417
+ }
418
+ };
419
+ lines.push(format!("{cut}{status}"));
420
+ let kept = headers
421
+ .iter()
422
+ .filter(|line| saw || !line.starts_with("x-saw:"));
423
+ lines.extend(kept.cloned());
424
+ lines.push(format!("body: {}", shown(body)));
425
+ }
426
+ lines
427
+ }
428
+
429
+ /// What a client of an inline connection reads of `row`, the requests
430
+ /// its job ran, and whether it went back to hyper.
431
+ async fn inline_view(row: &Row) -> (Vec<Event>, Vec<String>, bool) {
432
+ let server = server();
433
+ let taken = Taken::default();
434
+ let app = app(&server, row.reply, taken.clone());
435
+ let (client, conn) = loopback(&server);
436
+ abortive(&client);
437
+ let job = job(conn, row.reply, taken.clone());
438
+ let (events, ran) = tokio::task::block_in_place(|| {
439
+ let events = view(client, row, &taken);
440
+ (events, job.join().expect("the job"))
441
+ });
442
+ app.abort();
443
+ (events, ran, super::testing::handbacks(&server) > 0)
444
+ }
445
+
446
+ /// A request for `target` with `headers` (each line's end included).
447
+ fn get(target: &str, headers: &str) -> Vec<u8> {
448
+ format!("GET {target} HTTP/1.1\r\nhost: x\r\n{headers}\r\n").into_bytes()
449
+ }
450
+
451
+ /// A POST of `body`, framed by its length.
452
+ fn post(body: &[u8]) -> Vec<u8> {
453
+ let head = format!(
454
+ "POST /up HTTP/1.1\r\nhost: x\r\ncontent-length: {}\r\n\r\n",
455
+ body.len()
456
+ );
457
+ [head.as_bytes(), body].concat()
458
+ }
459
+
460
+ /// The corpus: raw requests, and how the app answers them. A row marks a
461
+ /// boundary where inline serving and hyper take different code: framing,
462
+ /// why a connection goes back to hyper, whether it stays open, a stream
463
+ /// cut short, and the recorded differences (doc/architecture.md).
464
+ #[rustfmt::skip] // One row per line: a table of exchanges.
465
+ fn corpus() -> Vec<Row> {
466
+ let many_headers = |n: usize| (0..n).map(|i| format!("x-h{i}: v\r\n")).collect::<String>();
467
+ // Heads of 16 KiB, the inline cap, and a byte past it (within hyper's).
468
+ let head_of = |len: usize| {
469
+ let filler = len - get("/", "x-fill: \r\n").len();
470
+ get("/", &format!("x-fill: {}\r\n", "f".repeat(filler)))
471
+ };
472
+ let (at_cap, past_cap) = (head_of(16 * 1024), head_of(16 * 1024 + 1));
473
+ let head = "HEAD / HTTP/1.1\r\nhost: x\r\n\r\n";
474
+ let chunked_put = "PUT /2 HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n";
475
+
476
+ vec![
477
+ // Requests served inline, and whether the connection stays open.
478
+ row("a GET that closes", get("/", "connection: close\r\n")),
479
+ row("a POST", post(b"hello")),
480
+ row("100 headers", get("/", &many_headers(99))),
481
+ row("a head of 16 KiB", at_cap),
482
+ row("three at once, sent a byte at a time", [get("/1", ""), post(b"2"), get("/3", "")].concat()).reads(&[false; 3]).pieces(1, Duration::ZERO),
483
+ // The app's answers, buffered.
484
+ row("a HEAD answered as Rack::Head answers it", head).reads(&[true]).reply(full(200, LENGTH_FIVE, b"")),
485
+ row("a 304 with the app's length and a body", get("/", "")).reply(full(304, LENGTH_FIVE, b"hello")),
486
+ row("the app's connection: close", get("/", "")).reply(full(200, &[("connection", "close")], b"bye")),
487
+ row("an app length shorter than its body", get("/", "")).reply(full(200, &[("content-length", "2")], b"hello")),
488
+ row("the app's transfer-encoding on a buffered body", get("/", "")).reply(full(200, &[TE], b"hello")),
489
+ // The app's answers, streamed, and cut short.
490
+ row("a streamed answer", get("/", "")).reply(streamed(200, TEXT, &[b"hel", b"lo"])),
491
+ row("a streamed answer to a HEAD", head).reads(&[true]).reply(streamed(200, TEXT, &[b"hello"])),
492
+ row("a 204 streamed with the app's length", get("/", "")).reply(streamed(204, LENGTH_FIVE, &[b"hello"])),
493
+ row("a streamed answer past the app's length in two writes", get("/", "")).reply(streamed(200, LENGTH_FIVE, &[b"hel", b"lo!!"])),
494
+ row("a streamed answer with the app's length not a number", get("/", "")).reply(streamed(200, &[("content-length", "five")], &[b"hello"])),
495
+ row("a streamed length cut short", get("/", "")).reply(Reply { status: 200, headers: &[("content-length", "10")], body: Body::Stops(&[b"hello"]) }),
496
+ row("a stream the app raises out of", get("/", "")).reply(Reply { status: 200, headers: TEXT, body: Body::Raise(&[b"hel"]) }),
497
+ // The recorded differences.
498
+ row("the app's transfer-encoding on a stream", get("/", "")).reply(streamed(200, &[("transfer-encoding", "gzip")], &[b"hello"]))
499
+ .deviation("inline drops an app's transfer-encoding and frames the body itself",
500
+ &["HTTP/1.1 200 OK", "server: Kino", "transfer-encoding: chunked", "body: 5\\r\\nhello\\r\\n0\\r\\n\\r\\n", "open"]),
501
+ row("a streamed answer to a HEAD with the app's length, then its encoding", head).reads(&[true]).reply(streamed(200, &[CL, TE], &[b"hello"]))
502
+ .deviation("inline writes the length, where hyper's refusal depends on the order",
503
+ &["HTTP/1.1 200 OK", "content-length: 5", "server: Kino", "body: ", "open"]),
504
+ row("the app's close in a value past ASCII", get("/", "")).reply(full(200, &[("connection", "close, caf\u{e9}")], b"hello"))
505
+ .deviation("inline ends the connection on a close hyper cannot read in a value past ASCII",
506
+ &["HTTP/1.1 200 OK", "connection: close, caf\u{e9}", "content-length: 5", "server: Kino", "body: hello", "closed"]),
507
+ // Handed back, a row a reason, the bytes read replayed to hyper.
508
+ row("a POST past 64 KiB", post(&vec![b'b'; 64 * 1024 + 1])).handed_back("body"),
509
+ row("a GET, a chunked PUT, then a GET that closes", [&get("/1", "")[..], chunked_put.as_bytes(), &get("/3", "connection: close\r\n")].concat()).reads(&[false; 3]).handed_back("chunked"),
510
+ row("HTTP/1.0", "GET / HTTP/1.0\r\n\r\n").handed_back("version"),
511
+ row("101 headers", get("/", &many_headers(100))).handed_back("malformed"),
512
+ row("a head of 16 KiB and a byte", past_cap.clone()).handed_back("too_large"),
513
+ row("a slow head past 16 KiB", past_cap).pieces(1024, Duration::from_millis(2)).handed_back("too_large"),
514
+ row("absolute-form", get("http://x.test/a?b=1", "")).handed_back("target"),
515
+ row("expect: 100-continue", "POST /up HTTP/1.1\r\nhost: x\r\nexpect: 100-continue\r\ncontent-length: 5\r\n\r\nhello").handed_back("expect"),
516
+ row("upgrade", get("/", "upgrade: websocket\r\n")).handed_back("upgrade"),
517
+ // hyper answers a CONNECT with no body and ends the connection:
518
+ // what follows it is a tunnel's, never a request.
519
+ row("a CONNECT with a request behind it", "CONNECT /x HTTP/1.1\r\nhost: x\r\n\r\nGET /y HTTP/1.1\r\nhost: x\r\n\r\n").handed_back("upgrade"),
520
+ ]
521
+ }
522
+
523
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
524
+ async fn inline_and_hyper_answer_the_corpus_the_same() {
525
+ // Some rows cut streams, which tests of the process-wide counts see.
526
+ let _serial = crate::testing::SERIAL.lock().await;
527
+ let rows = corpus();
528
+ let mut mismatches = Vec::new();
529
+ for row in &rows {
530
+ let hyper = hyper_view(row).await;
531
+ let (inline, ran, handed) = inline_view(row).await;
532
+ let sent = row.sent.concat();
533
+ let show = || {
534
+ format!(
535
+ "{}\n sent: {}\n ran inline: {ran:?}, handed back: {handed}\n inline: {:#?}\n hyper: {:#?}",
536
+ row.name,
537
+ sent[..sent.len().min(400)].escape_ascii(),
538
+ lines(&inline, true),
539
+ lines(&hyper, true),
540
+ )
541
+ };
542
+ if handed != row.handed_back.is_some() {
543
+ mismatches.push(format!("{} (handed back: {:?})", show(), row.handed_back));
544
+ continue;
545
+ }
546
+ match &row.deviation {
547
+ None if inline == hyper => {}
548
+ None => mismatches.push(show()),
549
+ Some((deviation, pinned)) if lines(&inline, false) != *pinned => {
550
+ mismatches.push(format!("{} ({deviation})", show()));
551
+ }
552
+ Some(_) => {}
553
+ }
554
+ }
555
+ assert!(
556
+ mismatches.is_empty(),
557
+ "{} of {} rows differ:\n\n{}",
558
+ mismatches.len(),
559
+ rows.len(),
560
+ mismatches.join("\n\n")
561
+ );
562
+ }
563
+
564
+ /// The subset parser, fuzzed.
565
+ mod parser {
566
+ use std::convert::Infallible;
567
+ use std::sync::Arc;
568
+ use std::time::Duration;
569
+
570
+ use bytes::Bytes;
571
+ use parking_lot::Mutex;
572
+ use proptest::collection::vec;
573
+ use proptest::prelude::*;
574
+ use proptest::sample::{select, Index};
575
+
576
+ use crate::inline::parse::{parse_head, Parsed};
577
+
578
+ const TCHAR: &[u8] =
579
+ b"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
580
+
581
+ fn token(max: usize) -> impl Strategy<Value = Vec<u8>> {
582
+ vec(select(TCHAR), 1..=max)
583
+ }
584
+
585
+ fn method() -> impl Strategy<Value = Vec<u8>> {
586
+ prop_oneof![
587
+ 8 => select(&[
588
+ "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "CONNECT", "TRACE",
589
+ ][..])
590
+ .prop_map(|m| m.as_bytes().to_vec()),
591
+ 1 => token(8),
592
+ ]
593
+ }
594
+
595
+ fn target() -> impl Strategy<Value = Vec<u8>> {
596
+ // Unreserved, sub-delims, ':' '@' '%' '/' '?'; now and then one
597
+ // that needs escaping, or a byte past ASCII.
598
+ let path_byte = prop_oneof![
599
+ 20 => select(&b"abcxyzABC0189-._~!$&'()*+,;=:@%/?"[..]),
600
+ 1 => select(&b"[]{}|\\^`\"<>\x7f\xc3\xa9#"[..]),
601
+ ];
602
+ prop_oneof![
603
+ 12 => vec(path_byte, 0..24).prop_map(|rest| [&b"/"[..], &rest].concat()),
604
+ 1 => Just(b"*".to_vec()),
605
+ 1 => Just(b"http://x.test/a?b".to_vec()),
606
+ 1 => Just(b"x.test:443".to_vec()),
607
+ ]
608
+ }
609
+
610
+ fn value() -> impl Strategy<Value = Vec<u8>> {
611
+ let byte = prop_oneof![
612
+ 8 => 0x21u8..0x7f,
613
+ 2 => Just(b' '),
614
+ 1 => Just(b'\t'),
615
+ 1 => 0x80u8..=0xff,
616
+ ];
617
+ vec(byte, 0..16)
618
+ }
619
+
620
+ fn header() -> impl Strategy<Value = (Vec<u8>, Vec<u8>)> {
621
+ let named = |names: &'static [&'static str]| {
622
+ select(names).prop_map(|name| name.as_bytes().to_vec())
623
+ };
624
+ let length = prop_oneof![
625
+ 3 => (0u64..100_000).prop_map(|n| n.to_string().into_bytes()),
626
+ 1 => select(
627
+ &[
628
+ "05", "+5", " 5 ", "5, 5", "", "5 5", "18446744073709551614",
629
+ "18446744073709551615", "18446744073709551616", "-1", "0x5",
630
+ ][..],
631
+ )
632
+ .prop_map(|v| v.as_bytes().to_vec()),
633
+ ];
634
+ let connection = vec(
635
+ select(
636
+ &[
637
+ "close",
638
+ "Close",
639
+ "keep-alive",
640
+ "upgrade",
641
+ "te",
642
+ "caf\u{e9}",
643
+ "",
644
+ " close ",
645
+ ][..],
646
+ ),
647
+ 1..4,
648
+ )
649
+ .prop_map(|tokens| tokens.join(",").into_bytes());
650
+ prop_oneof![
651
+ 12 => (
652
+ prop_oneof![named(&["host", "accept", "cookie", "x-a", "user-agent"]), token(12)],
653
+ value(),
654
+ ),
655
+ 3 => (named(&["content-length", "Content-Length", "CONTENT-LENGTH"]), length),
656
+ 4 => (named(&["connection", "Connection"]), connection),
657
+ 1 => (
658
+ named(&[
659
+ "transfer-encoding", "expect", "upgrade", "http2-settings", "te", "trailer",
660
+ ]),
661
+ value(),
662
+ ),
663
+ ]
664
+ }
665
+
666
+ /// What a mutation does to a head.
667
+ #[derive(Clone, Debug)]
668
+ enum Mutation {
669
+ /// One of CR, LF, NUL, space or colon, at a point.
670
+ Insert(Index, u8),
671
+ Duplicate(Index),
672
+ Version(&'static str),
673
+ Truncate(Index),
674
+ }
675
+
676
+ fn mutation() -> impl Strategy<Value = Mutation> {
677
+ const VERSIONS: [&str; 6] = [
678
+ "HTTP/1.0",
679
+ "HTTP/2.0",
680
+ "HTTP/1.2",
681
+ "HTTP/0.9",
682
+ "HTTP/1.10",
683
+ "http/1.1",
684
+ ];
685
+ prop_oneof![
686
+ (any::<Index>(), select(&b"\r\n\0 :"[..])).prop_map(|(at, b)| Mutation::Insert(at, b)),
687
+ any::<Index>().prop_map(Mutation::Duplicate),
688
+ select(&VERSIONS[..]).prop_map(Mutation::Version),
689
+ any::<Index>().prop_map(Mutation::Truncate),
690
+ ]
691
+ }
692
+
693
+ /// A valid head from method, target and header generators, then up
694
+ /// to three mutations.
695
+ fn head_strategy() -> impl Strategy<Value = Vec<u8>> {
696
+ let line_end = prop_oneof![9 => Just(&b"\r\n"[..]), 1 => Just(&b"\n"[..])];
697
+ let space = prop_oneof![4 => Just(&b" "[..]), 1 => Just(&b""[..]), 1 => Just(&b"\t"[..])];
698
+ (
699
+ method(),
700
+ target(),
701
+ vec((header(), space), 0..8),
702
+ line_end,
703
+ prop_oneof![4 => Just(0), 2 => Just(1), 1 => Just(2), 1 => Just(3)]
704
+ .prop_flat_map(|n| vec(mutation(), n)),
705
+ )
706
+ .prop_map(|(method, target, mut headers, eol, mutations)| {
707
+ let mut version = "HTTP/1.1";
708
+ for mutation in &mutations {
709
+ match mutation {
710
+ Mutation::Duplicate(at) if !headers.is_empty() => {
711
+ let line = headers[at.index(headers.len())].clone();
712
+ headers.insert(at.index(headers.len()), line);
713
+ }
714
+ Mutation::Version(other) => version = other,
715
+ _ => {}
716
+ }
717
+ }
718
+ let mut head = [&method[..], b" ", &target, b" ", version.as_bytes(), eol].concat();
719
+ for ((name, value), space) in &headers {
720
+ head.extend([&name[..], b":", space, value, eol].concat());
721
+ }
722
+ head.extend_from_slice(eol);
723
+ for mutation in &mutations {
724
+ match mutation {
725
+ Mutation::Insert(at, byte) => head.insert(at.index(head.len() + 1), *byte),
726
+ Mutation::Truncate(at) => head.truncate(at.index(head.len() + 1)),
727
+ _ => {}
728
+ }
729
+ }
730
+ head
731
+ })
732
+ }
733
+
734
+ /// A head_strategy head with up to seven bytes flipped.
735
+ fn flipped() -> impl Strategy<Value = Vec<u8>> {
736
+ let flips = vec((any::<Index>(), any::<u8>()), 1..8);
737
+ (head_strategy(), flips).prop_map(|(mut head, flips)| {
738
+ for (at, byte) in flips {
739
+ if !head.is_empty() {
740
+ let at = at.index(head.len());
741
+ head[at] = byte;
742
+ }
743
+ }
744
+ head
745
+ })
746
+ }
747
+
748
+ /// What hyper makes of a request head: its parts, its body's length,
749
+ /// and whether its answer closes the connection.
750
+ #[derive(Debug, PartialEq)]
751
+ struct Read {
752
+ method: http::Method,
753
+ uri: http::Uri,
754
+ headers: http::HeaderMap,
755
+ length: Option<u64>,
756
+ close: bool,
757
+ }
758
+
759
+ /// `head`, read by hyper's HTTP/1 server; None where hyper refuses it.
760
+ async fn hyper_reads(head: &[u8]) -> Option<Read> {
761
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
762
+
763
+ let (mut client, server) = tokio::io::duplex(64 * 1024);
764
+ let seen = Arc::new(Mutex::new(None));
765
+ let service = {
766
+ let seen = seen.clone();
767
+ hyper::service::service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
768
+ let length = hyper::body::Body::size_hint(req.body()).exact();
769
+ // Its body kept, unread: hyper closes a connection whose
770
+ // request body was let go of.
771
+ let (parts, body) = req.into_parts();
772
+ *seen.lock() = Some((parts.method, parts.uri, parts.headers, length, body));
773
+ async {
774
+ Ok::<_, Infallible>(hyper::Response::new(http_body_util::Empty::<Bytes>::new()))
775
+ }
776
+ })
777
+ };
778
+ let served = tokio::spawn(
779
+ hyper::server::conn::http1::Builder::new()
780
+ .serve_connection(hyper_util::rt::TokioIo::new(server), service),
781
+ );
782
+ client.write_all(head).await.ok()?;
783
+ let mut answer = Vec::new();
784
+ let mut chunk = [0; 4096];
785
+ while !answer.windows(4).any(|w| w == b"\r\n\r\n") {
786
+ match tokio::time::timeout(Duration::from_secs(2), client.read(&mut chunk)).await {
787
+ Ok(Ok(0) | Err(_)) => break,
788
+ Ok(Ok(n)) => answer.extend_from_slice(&chunk[..n]),
789
+ Err(_) => panic!("hyper neither answered nor ended {:?}", head.escape_ascii()),
790
+ }
791
+ }
792
+ served.abort();
793
+ let (method, uri, headers, length, _body) = seen.lock().take()?;
794
+ let answer = String::from_utf8_lossy(&answer).to_ascii_lowercase();
795
+ Some(Read {
796
+ method,
797
+ uri,
798
+ headers,
799
+ length,
800
+ close: answer.contains("\r\nconnection: close\r\n"),
801
+ })
802
+ }
803
+
804
+ /// One runtime for the cases' hyper.
805
+ fn runtime() -> &'static tokio::runtime::Runtime {
806
+ static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
807
+ RUNTIME.get_or_init(|| {
808
+ let mut builder = tokio::runtime::Builder::new_current_thread();
809
+ builder.enable_all().build().expect("a runtime")
810
+ })
811
+ }
812
+
813
+ proptest! {
814
+ // Nothing written into the tree: a failure prints its case.
815
+ #![proptest_config(ProptestConfig { cases: 2_000, failure_persistence: None, ..ProptestConfig::default() })]
816
+
817
+ /// Accepted: the subset parser takes the head, and its parts
818
+ /// convert (InlineConn::request hands back a head whose parts do
819
+ /// not). A head, a head with bytes flipped, or random bytes: it
820
+ /// never panics.
821
+ #[test]
822
+ fn the_subset_parser_never_panics_nor_accepts_what_httparse_and_http_refuse(
823
+ head in prop_oneof![3 => head_strategy(), 1 => flipped(), 1 => vec(any::<u8>(), 0..20_000)]
824
+ ) {
825
+ let Parsed::Head(parsed) = parse_head(&head) else {
826
+ return Ok(());
827
+ };
828
+ let bytes = Bytes::copy_from_slice(&head[..parsed.len]);
829
+ let Some((uri, headers)) = parsed.parts(&bytes) else {
830
+ return Ok(());
831
+ };
832
+ let shown = head.escape_ascii().to_string();
833
+
834
+ let mut slots = [httparse::EMPTY_HEADER; 100];
835
+ let mut req = httparse::Request::new(&mut slots);
836
+ prop_assert_eq!(
837
+ req.parse(&head),
838
+ Ok(httparse::Status::Complete(parsed.len)),
839
+ "httparse: {}", shown
840
+ );
841
+ let method = req.method.unwrap_or("").as_bytes();
842
+ prop_assert!(http::Method::from_bytes(method).is_ok(), "method: {}", shown);
843
+ prop_assert!(http::Uri::try_from(req.path.unwrap_or("")).is_ok(), "target: {}", shown);
844
+ for header in req.headers.iter() {
845
+ let name = http::HeaderName::from_bytes(header.name.as_bytes());
846
+ prop_assert!(name.is_ok(), "name: {}", shown);
847
+ let value = http::HeaderValue::from_bytes(header.value);
848
+ prop_assert!(value.is_ok(), "value: {}", shown);
849
+ }
850
+
851
+ let hyper = runtime().block_on(hyper_reads(&head[..parsed.len]));
852
+ let inline = Read {
853
+ method: parsed.method.clone(),
854
+ uri,
855
+ headers,
856
+ length: Some(parsed.content_length),
857
+ close: parsed.close,
858
+ };
859
+ prop_assert_eq!(Some(inline), hyper, "hyper: {}", shown);
860
+ }
861
+ }
862
+ }