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,416 @@
1
+ //! rack.hijack through a served connection: a test plays the client and
2
+ //! the app, which writes its response on its end of the bridge as a Rack
3
+ //! app would.
4
+
5
+ use std::time::Duration;
6
+
7
+ use http::header::CONNECTION;
8
+ use http::HeaderValue;
9
+ use http_body_util::{BodyExt, Full};
10
+
11
+ use super::*;
12
+ use crate::registry::{BoxedCtx, ServerInner};
13
+ use crate::request::RequestCtx;
14
+ use crate::response::{full_body, plain_response};
15
+ use crate::server::ServerConfig;
16
+ use crate::testing::{
17
+ read_to_close, response_to, send, slot, take_ctx, until, upgrade_request, Pending, Running,
18
+ TestServer, SWITCHED,
19
+ };
20
+
21
+ /// The app's end of a hijacked connection.
22
+ type AppEnd = tokio::net::UnixStream;
23
+ /// How the app takes the connection over.
24
+ type End = fn(&mut RequestCtx) -> AppEnd;
25
+
26
+ /// A server without lanes (a hijack needs none), running.
27
+ async fn hijack_server(set: impl FnOnce(&mut ServerConfig)) -> (Arc<ServerInner>, Running) {
28
+ TestServer::shared_queue().with(set).running().await
29
+ }
30
+
31
+ fn registered(io: UnixStream) -> AppEnd {
32
+ io.set_nonblocking(true).expect("nonblocking app end");
33
+ AppEnd::from_std(io).expect("app end registered")
34
+ }
35
+
36
+ /// Take `ctx`'s connection over, as rack.hijack does.
37
+ fn app_end(ctx: &mut RequestCtx) -> AppEnd {
38
+ registered(take(ctx, None).expect("an Upgrade request can be hijacked"))
39
+ }
40
+
41
+ /// The app's 101 to the chat protocol, answered with a callable.
42
+ fn chat_switch() -> crate::response::HyperResponse {
43
+ hyper::Response::builder()
44
+ .status(101)
45
+ .header(http::header::UPGRADE, "chat")
46
+ .header(CONNECTION, "Upgrade")
47
+ .body(full_body(Bytes::new()))
48
+ .expect("101 head")
49
+ }
50
+
51
+ /// A client sends `request`, and the app takes its connection over by
52
+ /// `end`: the client's pending response, the request as its worker
53
+ /// holds it, and the app's end.
54
+ async fn hijacked_request(
55
+ server: &Arc<ServerInner>,
56
+ request: hyper::Request<Full<Bytes>>,
57
+ end: End,
58
+ ) -> (Pending, BoxedCtx, AppEnd) {
59
+ let pending = send(server, request).await;
60
+ let mut ctx = take_ctx(server).await;
61
+ let app = end(&mut ctx);
62
+ (pending, ctx, app)
63
+ }
64
+
65
+ /// hijacked_request, for an Upgrade request taken over as rack.hijack does.
66
+ async fn hijacked(server: &Arc<ServerInner>) -> (Pending, BoxedCtx, AppEnd) {
67
+ hijacked_request(server, upgrade_request(), app_end).await
68
+ }
69
+
70
+ /// The client's end, once its Upgrade request got the chat 101.
71
+ async fn switched_client(pending: Pending) -> TokioIo<hyper::upgrade::Upgraded> {
72
+ let response = response_to(pending).await;
73
+ assert_eq!(response.status(), 101);
74
+ assert_eq!(
75
+ response.headers()[http::header::UPGRADE],
76
+ "chat",
77
+ "the app's headers reach the client"
78
+ );
79
+ TokioIo::new(hyper::upgrade::on(response).await.expect("client upgrade"))
80
+ }
81
+
82
+ /// Kino answered a hijacked request itself, with `status`, and closed the
83
+ /// connection, which is the app's.
84
+ async fn kino_answered(pending: Pending, status: u16, what: &str) {
85
+ let response = response_to(pending).await;
86
+ assert_eq!(response.status(), status, "{what}");
87
+ assert_eq!(
88
+ response.headers().get(CONNECTION),
89
+ Some(&HeaderValue::from_static("close")),
90
+ "{what}: a hijacked connection must not serve another request"
91
+ );
92
+ }
93
+
94
+ #[tokio::test]
95
+ async fn any_other_answer_with_a_content_length_goes_out_whole_or_not_at_all_then_closes() {
96
+ let (server, _running) = hijack_server(|_| {}).await;
97
+ // The app keeps its end open, or closes it short of the body, which
98
+ // aborts the connection.
99
+ let cases: [(&str, &[u8], bool); 2] = [
100
+ ("content-length", b"content-length: 5\r\n\r\nhello", true),
101
+ ("cut short", b"content-length: 10\r\n\r\nhello", false),
102
+ ];
103
+ for (framing, rest, whole) in cases {
104
+ let (pending, _ctx, mut app) = hijacked(&server).await;
105
+ let head = b"HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n";
106
+ app.write_all(&[head, rest].concat())
107
+ .await
108
+ .expect("app write");
109
+ if !whole {
110
+ app.shutdown().await.expect("app closes its end");
111
+ // The abort may come before or after the head reaches the client.
112
+ let received = tokio::time::timeout(Duration::from_secs(5), async {
113
+ pending.await.expect("join")?.into_body().collect().await
114
+ });
115
+ let received = received.await.expect("the response ended within 5s");
116
+ assert!(
117
+ received.is_err(),
118
+ "{framing}: must not reach the client as complete"
119
+ );
120
+ continue;
121
+ }
122
+
123
+ let response = response_to(pending).await;
124
+ assert_eq!(response.status(), 400, "{framing}");
125
+ assert_eq!(response.headers()[http::header::CONTENT_TYPE], "text/plain");
126
+ assert_eq!(
127
+ response.headers()[CONNECTION],
128
+ "close",
129
+ "{framing}: the connection must close after the answer"
130
+ );
131
+ let body = tokio::time::timeout(Duration::from_secs(5), response.into_body().collect())
132
+ .await
133
+ .unwrap_or_else(|_| panic!("{framing}: the body did not end within 5s"))
134
+ .expect("body");
135
+ assert_eq!(body.to_bytes(), "hello", "{framing}");
136
+ // The bridge lets go of the app's end once the body is through.
137
+ let what = format!("{framing}: the app's end");
138
+ assert_eq!(read_to_close(&mut app, &what).await, b"", "{framing}");
139
+ }
140
+ }
141
+
142
+ /// A hijack of `request` whose bridge waits for the app, the app's end
143
+ /// able to take a whole answer at once: a write never yields to the
144
+ /// runtime, which would let it see the bytes (a macOS socket holds 8 KiB
145
+ /// by default).
146
+ async fn waiting_hijack(
147
+ server: &Arc<ServerInner>,
148
+ request: hyper::Request<Full<Bytes>>,
149
+ ) -> (Pending, BoxedCtx, AppEnd) {
150
+ let hijack = hijacked_request(server, request, app_end).await;
151
+ socket2::SockRef::from(&hijack.2)
152
+ .set_send_buffer_size(1 << 20)
153
+ .expect("app end send buffer");
154
+ until("the bridge to wait for the app", || {
155
+ server.bridges_running.load(Ordering::SeqCst) == 1
156
+ })
157
+ .await;
158
+ hijack
159
+ }
160
+
161
+ /// What the client gets for `request` when its app writes `written`
162
+ /// and, if `closes`, closes its end, and the workers then stop before
163
+ /// the runtime has seen any of it (the drain wakes the bridge first):
164
+ /// the status and body, or what went wrong.
165
+ async fn answer_at_drain(
166
+ request: hyper::Request<Full<Bytes>>,
167
+ written: &[u8],
168
+ closes: bool,
169
+ ) -> Result<(u16, Bytes), String> {
170
+ let (server, _running) = hijack_server(|_| {}).await;
171
+ let (pending, _ctx, mut app) = waiting_hijack(&server, request).await;
172
+ app.write_all(written).await.expect("app write");
173
+ let _open = (!closes).then_some(app);
174
+ close(&server, Closed::All);
175
+ let response = tokio::time::timeout(Duration::from_secs(5), pending)
176
+ .await
177
+ .map_err(|_| "no response within 5s".to_string())?
178
+ .expect("join")
179
+ .map_err(|e| format!("no answer at all ({e})"))?;
180
+ let status = response.status().as_u16();
181
+ let body = response.into_body().collect().await;
182
+ let body = body.map_err(|e| format!("the body was cut ({e})"))?;
183
+ Ok((status, body.to_bytes()))
184
+ }
185
+
186
+ /// An answer the app writes: what it is, its bytes, whether the app's end
187
+ /// then closes, and the status and body the client gets.
188
+ type Answer<'a> = (&'a str, &'a [u8], bool, u16, &'a [u8]);
189
+
190
+ #[tokio::test]
191
+ async fn an_answer_the_app_wrote_before_the_workers_stopped_goes_out_if_whole_else_the_503() {
192
+ let long = [
193
+ b"HTTP/1.1 200 OK\r\ncontent-length: 65536\r\n\r\n".as_slice(),
194
+ &[b'x'; 65536],
195
+ ]
196
+ .concat();
197
+ let unavailable: &[u8] = b"Service Unavailable\n";
198
+ // One row per case; rustfmt would split each row field by field.
199
+ #[rustfmt::skip]
200
+ let cases: [Answer<'_>; 8] = [
201
+ ("a content-length", b"HTTP/1.1 200 OK\r\ncontent-length: 8\r\n\r\nanswered", false, 200,
202
+ b"answered"),
203
+ ("a content-length of 64 KiB", &long, true, 200, &[b'x'; 65536]),
204
+ ("half a content-length", b"HTTP/1.1 200 OK\r\ncontent-length: 16\r\n\r\nanswered", true,
205
+ 503, unavailable),
206
+ ("part of a head", b"HTTP/1.1 2", false, 503, unavailable),
207
+ // No body, whatever the head declares.
208
+ ("a 204 with a content-length", b"HTTP/1.1 204 No Content\r\ncontent-length: 8\r\n\r\n",
209
+ false, 204, b""),
210
+ ("a 304 with a content-length", b"HTTP/1.1 304 Not Modified\r\ncontent-length: 8\r\n\r\n",
211
+ false, 304, b""),
212
+ ("a 204 without a content-length", b"HTTP/1.1 204 No Content\r\n\r\n", false, 204, b""),
213
+ ("the same content-length twice",
214
+ b"HTTP/1.1 200 OK\r\ncontent-length: 8\r\ncontent-length: 8\r\n\r\nanswered", false, 200,
215
+ b"answered"),
216
+ ];
217
+ for (answer, written, closes, status, body) in cases {
218
+ let (got_status, got) = answer_at_drain(upgrade_request(), written, closes)
219
+ .await
220
+ .unwrap_or_else(|e| panic!("{answer}: {e}"));
221
+ assert_eq!(got_status, status, "{answer}");
222
+ assert!(
223
+ got == body,
224
+ "{answer}: a body of {} bytes, not the {} expected",
225
+ got.len(),
226
+ body.len()
227
+ );
228
+ }
229
+
230
+ // An answer to a HEAD has no body either, whatever its head declares.
231
+ let mut head = upgrade_request();
232
+ *head.method_mut() = http::Method::HEAD;
233
+ let written = b"HTTP/1.1 200 OK\r\ncontent-length: 8\r\n\r\n";
234
+ let got = answer_at_drain(head, written, false).await;
235
+ let got = got.unwrap_or_else(|e| panic!("a HEAD request: {e}"));
236
+ assert_eq!(got, (200, Bytes::new()), "a HEAD request");
237
+ }
238
+
239
+ #[tokio::test]
240
+ async fn a_body_the_app_finished_before_the_workers_stopped_goes_out_and_one_it_did_not_is_cut() {
241
+ // The body, the head that goes out the usual way, and the rest, which
242
+ // the app then writes before the workers stop, unseen by the runtime;
243
+ // whether the app's end closes, and whether the body is whole.
244
+ // One row per case; rustfmt would split each row field by field.
245
+ #[rustfmt::skip]
246
+ let cases: [(&str, &[u8], bool, bool); 2] = [
247
+ ("a content-length", b"HTTP/1.1 200 OK\r\ncontent-length: 8\r\n\r\n", true, true),
248
+ ("half its length", b"HTTP/1.1 200 OK\r\ncontent-length: 16\r\n\r\n", false, false),
249
+ ];
250
+ for (body, head, closes, whole) in cases {
251
+ let (server, _running) = hijack_server(|_| {}).await;
252
+ let (pending, _ctx, mut app) = waiting_hijack(&server, upgrade_request()).await;
253
+ app.write_all(head).await.expect("app head");
254
+ let response = response_to(pending).await;
255
+ assert_eq!(response.status(), 200, "{body}");
256
+ app.write_all(b"answered").await.expect("app rest");
257
+ let _open = (!closes).then_some(app);
258
+ close(&server, Closed::All);
259
+
260
+ let got = response.into_body().collect().await;
261
+ if whole {
262
+ let got = got.unwrap_or_else(|e| panic!("{body}: the body was cut ({e})"));
263
+ assert_eq!(got.to_bytes(), "answered", "{body}");
264
+ } else {
265
+ assert!(
266
+ got.is_err(),
267
+ "{body}: a body short of its length must be cut"
268
+ );
269
+ }
270
+ }
271
+ }
272
+
273
+ #[tokio::test]
274
+ async fn a_101_the_app_wrote_before_the_workers_stopped_goes_out_and_its_connection_closes() {
275
+ let (server, _running) = hijack_server(|_| {}).await;
276
+ let (pending, _ctx, mut app) = waiting_hijack(&server, upgrade_request()).await;
277
+ app.write_all(&[SWITCHED, b"welcome"].concat())
278
+ .await
279
+ .expect("app write");
280
+ close(&server, Closed::All);
281
+
282
+ // Requests drained before the workers stopped, so the switched
283
+ // connection, the app's alone, closes as the 101 goes out.
284
+ let mut client = switched_client(pending).await;
285
+ read_to_close(&mut client, "the client after the 101").await;
286
+ }
287
+
288
+ #[tokio::test]
289
+ async fn once_requests_drain_switched_bridges_close_and_unanswered_ones_wait_for_the_workers() {
290
+ let (server, _running) = hijack_server(|_| {}).await;
291
+ let (pending, _ctx, mut written_app) = hijacked(&server).await;
292
+ written_app.write_all(SWITCHED).await.expect("app write");
293
+ let mut written_client = switched_client(pending).await;
294
+ // The app answers with chat_switch, whose callable gets this end.
295
+ let callable_end =
296
+ |ctx: &mut RequestCtx| registered(take(ctx, Some(chat_switch())).expect("switched"));
297
+ let (pending, _ctx, mut callable) =
298
+ hijacked_request(&server, upgrade_request(), callable_end).await;
299
+ let mut callable_client = switched_client(pending).await;
300
+ let (unanswered, _ctx, mut answering) = hijacked(&server).await;
301
+ let (long_poll, _ctx, _polling) = hijacked(&server).await;
302
+
303
+ close(&server, Closed::Switched);
304
+
305
+ let ends: [(&str, &mut (dyn AsyncRead + Unpin)); 4] = [
306
+ ("the app's end after its own 101", &mut written_app),
307
+ ("the client of the app's own 101", &mut written_client),
308
+ ("a callable's end", &mut callable),
309
+ ("the client of a callable's 101", &mut callable_client),
310
+ ];
311
+ for (what, end) in ends {
312
+ assert_eq!(read_to_close(end, what).await, b"", "{what}");
313
+ }
314
+ let answer = b"HTTP/1.1 200 OK\r\ncontent-length: 8\r\n\r\nanswered";
315
+ answering.write_all(answer).await.expect("app write");
316
+ let response = response_to(unanswered).await;
317
+ assert_eq!(response.status(), 200, "the app's own answer, not a 503");
318
+ let body = response.into_body().collect().await.expect("body");
319
+ assert_eq!(body.to_bytes(), "answered");
320
+ assert!(
321
+ !long_poll.is_finished(),
322
+ "a hijack the app has not answered waits past the switched ones closing"
323
+ );
324
+
325
+ close(&server, Closed::All);
326
+ kino_answered(long_poll, 503, "a hijack unanswered once the workers stop").await;
327
+ }
328
+
329
+ #[tokio::test]
330
+ async fn a_hijack_counts_against_its_worker_and_server_until_its_bridge_ends() {
331
+ let (server, _running) = hijack_server(|_| {}).await;
332
+ server.register_worker().expect("a worker slot");
333
+ let pending = send(&server, upgrade_request()).await;
334
+ let mut ctx = take_ctx(&server).await;
335
+ ctx.slot = Some(slot(&server, 0));
336
+ let app = app_end(&mut ctx);
337
+ let counted = || {
338
+ let worker = slot(&server, 0).hijacked.load(Ordering::SeqCst);
339
+ let stats = crate::stats::Snapshot::take(&server);
340
+ (worker, stats.hijacked_connections)
341
+ };
342
+ assert_eq!(counted(), (1, 1), "counted from the hijack on");
343
+
344
+ drop(app);
345
+ kino_answered(pending, 502, "an app's end closed unanswered").await;
346
+ until("the bridge to stop counting", || counted() == (0, 0)).await;
347
+ }
348
+
349
+ #[tokio::test]
350
+ async fn a_head_the_bridge_cannot_read_or_whose_body_has_no_content_length_answers_502() {
351
+ let (server, _running) = hijack_server(|_| {}).await;
352
+ let padding = "x".repeat(16 * 1024);
353
+ let oversized = format!("HTTP/1.1 200 OK\r\nx-padding: {padding}\r\n\r\n");
354
+ let informational = b"HTTP/1.1 103 Early Hints\r\nlink: </style.css>\r\n\r\n";
355
+ // One row per case; rustfmt would split the long rows.
356
+ #[rustfmt::skip]
357
+ let cases: [(&str, &[u8]); 10] = [
358
+ ("a chunked body", b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n"),
359
+ ("a body until close", b"HTTP/1.1 200 OK\r\n\r\nhello"),
360
+ ("a content-length that is no number", b"HTTP/1.1 200 OK\r\ncontent-length: five\r\n\r\nhello"),
361
+ ("a signed content-length", b"HTTP/1.1 200 OK\r\ncontent-length: +5\r\n\r\nhello"),
362
+ ("two content-lengths that differ", b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\ncontent-length: 50\r\n\r\nhello"),
363
+ ("a bodiless answer with a signed content-length", b"HTTP/1.1 204 No Content\r\ncontent-length: +5\r\n\r\n"),
364
+ ("cut short by the app closing", b"HTTP/1.1 101 Swi"),
365
+ ("longer than 16 KiB", oversized.as_bytes()),
366
+ ("not an HTTP response", b"hello\r\n\r\n"),
367
+ ("an informational head", informational),
368
+ ];
369
+
370
+ for (head, written) in cases {
371
+ let (pending, _ctx, mut app) = hijacked(&server).await;
372
+ let written = written.to_vec();
373
+ // The bridge may stop reading before all of it is written.
374
+ tokio::spawn(async move {
375
+ let _ = app.write_all(&written).await;
376
+ let _ = app.shutdown().await;
377
+ });
378
+ kino_answered(pending, 502, head).await;
379
+ }
380
+ }
381
+
382
+ #[tokio::test]
383
+ async fn once_hijacked_only_the_app_answers() {
384
+ let (server, _running) = hijack_server(|_| {}).await;
385
+ let (pending, mut ctx, mut app) = hijacked(&server).await;
386
+
387
+ assert_eq!(
388
+ take(&mut ctx, None).map(drop),
389
+ Err(Refused::AlreadyHijacked),
390
+ "a connection is hijacked once"
391
+ );
392
+ let triple = plain_response(200, "the app's triple\n");
393
+ assert!(
394
+ !ctx.responder.send_response(triple),
395
+ "the request handle can no longer answer"
396
+ );
397
+ // The Drop backstop, as when Ruby collects the request handle before
398
+ // the app has written anything.
399
+ drop(ctx);
400
+ app.write_all(SWITCHED).await.expect("app write");
401
+ assert_eq!(response_to(pending).await.status(), 101);
402
+ }
403
+
404
+ #[tokio::test]
405
+ async fn a_bridge_lets_go_once_its_request_is_answered_without_it() {
406
+ let (server, _running) = hijack_server(|config| config.request_timeout_ms = 50).await;
407
+ let (pending, _ctx, mut app) = hijacked(&server).await;
408
+
409
+ kino_answered(pending, 504, "a hijacked request past its deadline").await;
410
+ assert_eq!(
411
+ read_to_close(&mut app, "the app's end after a 504").await,
412
+ b""
413
+ );
414
+ let in_flight = server.counters.in_flight.load(Ordering::Relaxed);
415
+ assert_eq!(in_flight, 0, "counted out once, when hijacked");
416
+ }