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,471 @@
1
+ //! Full `rack.hijack` (Rack 3) on HTTP/1: the app gets one end of a Unix
2
+ //! socket pair and writes its own response there. The bridge on the other
3
+ //! end replays the head through hyper (so TLS works), then joins the two
4
+ //! connections (101) or streams the Content-Length body behind it. An
5
+ //! answer that has no body (a 204, a 304, the answer to a HEAD) needs no
6
+ //! Content-Length; any other framing gets a 502. Only a request that asked
7
+ //! to upgrade is offered one: its bridge runs on the task holding the
8
+ //! upgrade (upgrade::settle).
9
+
10
+ use std::fmt;
11
+ use std::future::Future;
12
+ use std::io;
13
+ use std::os::unix::net::UnixStream;
14
+ use std::pin::Pin;
15
+ use std::sync::atomic::Ordering;
16
+ use std::sync::Arc;
17
+ use std::task::{Context, Poll};
18
+
19
+ use bytes::{Buf, Bytes, BytesMut};
20
+ use http::header::TRANSFER_ENCODING;
21
+ use http::StatusCode;
22
+ use hyper::upgrade::OnUpgrade;
23
+ use hyper_util::rt::TokioIo;
24
+ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, ReadBuf};
25
+ use tokio::sync::oneshot;
26
+
27
+ use crate::counters::Counted;
28
+ use crate::framing;
29
+ use crate::registry::ServerInner;
30
+ use crate::request::RequestCtx;
31
+ use crate::response::{
32
+ close_connection, full_body, plain_response, stream_body_holding, FrameResult, HyperResponse,
33
+ };
34
+ use crate::slot::WorkerSlot;
35
+ use crate::upgrade::Claim;
36
+
37
+ /// Longest response head the app may write; past it, the client gets 502.
38
+ const MAX_HEAD: usize = 16 * 1024;
39
+ const READ_CHUNK: usize = 16 * 1024;
40
+ /// Body frames that may wait for a slow client, as for streamed responses.
41
+ const BODY_FRAMES: usize = 8;
42
+ /// Most read at once after the workers stopped; an answer not whole by then gets 503.
43
+ const AT_DRAIN_MAX: usize = 1024 * 1024;
44
+
45
+ /// A hijacked connection's Rust side: its end of the pair, and the answer the app's head becomes.
46
+ pub(crate) struct Bridge {
47
+ io: UnixStream,
48
+ answer: oneshot::Sender<HyperResponse>,
49
+ /// The 101 the app answered with, when it did not write one.
50
+ head: Option<HyperResponse>,
51
+ /// Counts against the hijacked worker's slot until the bridge ends, so the pool keeps it.
52
+ open: Option<Counted<WorkerSlot>>,
53
+ head_request: bool,
54
+ }
55
+
56
+ #[derive(Debug, PartialEq, Eq)]
57
+ pub enum Refused {
58
+ NotOffered,
59
+ AlreadyHijacked,
60
+ /// Answered meanwhile (a request timeout's 504).
61
+ Answered,
62
+ Busy,
63
+ Gone,
64
+ Socket(io::ErrorKind),
65
+ }
66
+
67
+ impl fmt::Display for Refused {
68
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69
+ match self {
70
+ Refused::NotOffered => f.write_str(
71
+ "offered on HTTP/1.1 requests with an Upgrade header, and not once a native \
72
+ WebSocket took the connection",
73
+ ),
74
+ Refused::AlreadyHijacked => f.write_str("the connection is already hijacked"),
75
+ Refused::Answered => f.write_str("the request was already answered"),
76
+ Refused::Busy => f.write_str(crate::request::BUSY),
77
+ Refused::Gone => f.write_str("the server is shutting down"),
78
+ Refused::Socket(kind) => write!(f, "no socket pair: {kind}"),
79
+ }
80
+ }
81
+ }
82
+
83
+ /// An HTTP/1.1 request that asked to upgrade, until something claims its connection.
84
+ pub fn offered(ctx: &RequestCtx) -> bool {
85
+ ctx.upgrade.is_some()
86
+ }
87
+
88
+ /// rack.hijack: the app's end of a fresh socket pair; the bridge answers with what it writes
89
+ /// there. With `head`, the 101 an app answered with a callable, the bridge joins at once.
90
+ pub fn take(ctx: &mut RequestCtx, head: Option<HyperResponse>) -> Result<UnixStream, Refused> {
91
+ if ctx.hijacked {
92
+ return Err(Refused::AlreadyHijacked);
93
+ }
94
+ // A native WebSocket took the upgrade with it. After a 500 the claim below
95
+ // finds the request answered, and after a 504 the bridge lets go at once.
96
+ if !offered(ctx) {
97
+ return Err(Refused::NotOffered);
98
+ }
99
+ // First, so running out of file descriptors leaves the hijack offered.
100
+ let (app, io) = UnixStream::pair().map_err(|e| Refused::Socket(e.kind()))?;
101
+ let answer = ctx.responder.hijack().ok_or(Refused::Answered)?;
102
+ // The request is the app's now, so a drain does not wait for it.
103
+ if let Some(server) = crate::registry::try_get(ctx.server_id) {
104
+ if ctx.responder.leave_in_flight() {
105
+ server.counters.in_flight.fetch_sub(1, Ordering::Relaxed);
106
+ }
107
+ }
108
+ let bridge = Bridge {
109
+ io,
110
+ answer,
111
+ head,
112
+ open: ctx
113
+ .slot
114
+ .as_ref()
115
+ .map(|slot| Counted::on(slot, |slot| &slot.hijacked)),
116
+ head_request: ctx.method == http::Method::HEAD,
117
+ };
118
+ let upgrade = ctx.upgrade.take().ok_or(Refused::NotOffered)?;
119
+ if !upgrade.claim(Claim::Hijack(bridge)) {
120
+ return Err(Refused::Gone);
121
+ }
122
+ ctx.hijacked = true;
123
+ Ok(app)
124
+ }
125
+
126
+ /// How far a drain has closed the bridges; it only rises.
127
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
128
+ pub enum Closed {
129
+ Nothing,
130
+ /// Requests have drained: a switched connection is the app's alone and
131
+ /// closes now; an app's end that closes silently gets All's 503 from here.
132
+ Switched,
133
+ /// The workers have stopped: every bridge closes; an unanswered request gets 503.
134
+ All,
135
+ }
136
+
137
+ /// Never reopens a bridge.
138
+ pub(crate) fn close(server: &ServerInner, closed: Closed) {
139
+ server.bridges_closed.send_if_modified(|now| {
140
+ let rises = *now < closed;
141
+ if rises {
142
+ *now = closed;
143
+ }
144
+ rises
145
+ });
146
+ }
147
+
148
+ async fn closing(server: &ServerInner, closed: Closed) {
149
+ let mut bridges = server.bridges_closed.subscribe();
150
+ let _ = bridges.wait_for(|now| *now >= closed).await;
151
+ }
152
+
153
+ /// Kino's own answer: it closes the connection, which is the app's now.
154
+ fn own_answer(status: u16, message: &'static str) -> HyperResponse {
155
+ let mut response = plain_response(status, message);
156
+ close_connection(&mut response);
157
+ response
158
+ }
159
+
160
+ fn unanswered() -> HyperResponse {
161
+ own_answer(503, "Service Unavailable\n")
162
+ }
163
+
164
+ fn bad_gateway() -> HyperResponse {
165
+ own_answer(502, "Bad Gateway\n")
166
+ }
167
+
168
+ /// Why the bridge has no head from the app.
169
+ enum NoHead {
170
+ /// The app closed its end without writing a byte.
171
+ Silent,
172
+ /// Malformed, past MAX_HEAD or cut short; or the read failed.
173
+ Bad,
174
+ }
175
+
176
+ impl Bridge {
177
+ /// Answer with the head the app writes, then carry the rest: both ways
178
+ /// once switched (101), else as the body.
179
+ pub(crate) async fn run(self, on_upgrade: OnUpgrade, server: &ServerInner) {
180
+ // Held by the bridge and its answer until hyper takes it; close_bridges waits.
181
+ let running = BridgeHold(Arc::new(Counted::hold(&server.bridges_running, 1)));
182
+ let Bridge {
183
+ io,
184
+ mut answer,
185
+ head,
186
+ open: _open,
187
+ head_request,
188
+ } = self;
189
+ // The answer that leaves nothing to carry: Kino's own, or one the app wrote whole in time.
190
+ let last = 'last: {
191
+ let Ok(mut io) = into_tokio(io) else {
192
+ break 'last bad_gateway();
193
+ };
194
+ let mut buf = BytesMut::new();
195
+ // Whether the head was read after the workers stopped.
196
+ let mut at_drain = false;
197
+ let head = match head {
198
+ Some(head) => Ok(head.map(drop)),
199
+ // A head the app wrote goes out even when the drain is over.
200
+ None => tokio::select! {
201
+ biased;
202
+ head = read_head(&mut io, &mut buf) => head,
203
+ // Answered meanwhile (a request timeout's 504), or the client left.
204
+ () = answer.closed() => return,
205
+ // The runtime may not have seen what the app wrote before its worker
206
+ // stopped: read the socket; no whole head by then gets a 503.
207
+ () = closing(server, Closed::All) => {
208
+ read_written(&io, &mut buf);
209
+ let Ok(Some(head)) = parse_head(&mut buf) else {
210
+ break 'last unanswered();
211
+ };
212
+ at_drain = true;
213
+ Ok(head)
214
+ }
215
+ },
216
+ };
217
+ let mut head = match head {
218
+ Ok(head) => head,
219
+ // Past Switched, a worker Ractor's objects (a long poll's IO) go with it:
220
+ // a silent close then is an unanswered request, not a failed app.
221
+ Err(NoHead::Silent) if *server.bridges_closed.borrow() >= Closed::Switched => {
222
+ break 'last unanswered();
223
+ }
224
+ Err(_) => break 'last bad_gateway(),
225
+ };
226
+
227
+ if head.status() == StatusCode::SWITCHING_PROTOCOLS {
228
+ let response = head.map(|()| full_body(Bytes::new()));
229
+ if answer.send(held(response, &running)).is_err() {
230
+ return; // the client is gone
231
+ }
232
+ // The connection is the app's now: it closes once requests drain, not at All.
233
+ tokio::select! {
234
+ () = switch(on_upgrade, buf, io) => {}
235
+ () = closing(server, Closed::Switched) => {}
236
+ }
237
+ return;
238
+ }
239
+
240
+ let Some(length) = body_length(&head, head_request) else {
241
+ break 'last bad_gateway();
242
+ };
243
+ close_connection(&mut head);
244
+ let (frames, body) = flume::bounded(BODY_FRAMES);
245
+ // The body holds the bridge counted too, until hyper has its tail.
246
+ let response = head.map(|()| stream_body_holding(body, running.0.clone()));
247
+ if at_drain {
248
+ // Nothing went out and nothing more comes: its body goes from memory
249
+ // if it is all there; else 503.
250
+ let whole = usize::try_from(length).ok();
251
+ let Some(length) = whole.filter(|&length| buf.len() >= length) else {
252
+ break 'last unanswered();
253
+ };
254
+ if length > 0 {
255
+ buf.truncate(length);
256
+ let _ = frames.try_send(Ok(hyper::body::Frame::data(buf.freeze())));
257
+ }
258
+ break 'last response;
259
+ }
260
+ if answer.send(held(response, &running)).is_err() {
261
+ return;
262
+ }
263
+ let mut app = UntilDrained {
264
+ io: &mut io,
265
+ drained: Some(Box::pin(closing(server, Closed::All))),
266
+ };
267
+ if let Err(error) = forward(&mut app, buf, length, &frames).await {
268
+ // The error frame makes hyper abort, so a cut body cannot pass for whole.
269
+ let _ = frames.send_async(Err(error)).await;
270
+ }
271
+ return;
272
+ };
273
+ let _ = answer.send(held(last, &running));
274
+ }
275
+ }
276
+
277
+ /// What the app wrote behind its 101 goes first, then bytes go both ways.
278
+ async fn switch(on_upgrade: OnUpgrade, behind: BytesMut, app: tokio::net::UnixStream) {
279
+ let Ok(upgraded) = on_upgrade.await else {
280
+ return;
281
+ };
282
+ let mut client = TokioIo::new(upgraded);
283
+ if client.write_all(&behind).await.is_err() || client.flush().await.is_err() {
284
+ return;
285
+ }
286
+ join(client, app).await;
287
+ }
288
+
289
+ /// The client closing its side reaches the app as EOF; the app closing its
290
+ /// end closes the client outright, so a client cannot keep the bridge.
291
+ async fn join(client: TokioIo<hyper::upgrade::Upgraded>, mut app: tokio::net::UnixStream) {
292
+ let (mut client_rd, mut client_wr) = tokio::io::split(client);
293
+ let (mut app_rd, mut app_wr) = app.split();
294
+ let to_client = async {
295
+ let _ = tokio::io::copy(&mut app_rd, &mut client_wr).await;
296
+ let _ = client_wr.shutdown().await;
297
+ };
298
+ let to_app = async {
299
+ let _ = tokio::io::copy(&mut client_rd, &mut app_wr).await;
300
+ let _ = app_wr.shutdown().await;
301
+ // The app may still answer before it closes its end.
302
+ std::future::pending::<()>().await
303
+ };
304
+ tokio::select! {
305
+ () = to_client => {}
306
+ () = to_app => {}
307
+ }
308
+ }
309
+
310
+ /// A response extension of its own type, so no other count can replace it.
311
+ #[derive(Clone)]
312
+ struct BridgeHold(Arc<Counted>);
313
+
314
+ /// hyper drops a response's extensions as it encodes the head, ending the hold.
315
+ fn held(mut response: HyperResponse, running: &BridgeHold) -> HyperResponse {
316
+ response.extensions_mut().insert(running.clone());
317
+ response
318
+ }
319
+
320
+ fn into_tokio(io: UnixStream) -> io::Result<tokio::net::UnixStream> {
321
+ io.set_nonblocking(true)?;
322
+ tokio::net::UnixStream::from_std(io)
323
+ }
324
+
325
+ /// Straight from the socket: the runtime's readiness can trail a write by a
326
+ /// scheduling slice. WouldBlock when nothing is there.
327
+ fn read_now(io: &tokio::net::UnixStream, into: &mut [u8]) -> io::Result<usize> {
328
+ crate::server::recv_now(&socket2::SockRef::from(io), into, 0)
329
+ }
330
+
331
+ /// What the app wrote, up to AT_DRAIN_MAX (past it by less than a read).
332
+ fn read_written(io: &tokio::net::UnixStream, buf: &mut BytesMut) {
333
+ let mut chunk = [0; READ_CHUNK];
334
+ while buf.len() < AT_DRAIN_MAX {
335
+ match read_now(io, &mut chunk) {
336
+ Ok(n) if n > 0 => buf.extend_from_slice(&chunk[..n]),
337
+ _ => break,
338
+ }
339
+ }
340
+ }
341
+
342
+ /// Through the runtime until the workers stop, then from the socket; what is missing cuts the body.
343
+ struct UntilDrained<'a> {
344
+ io: &'a mut tokio::net::UnixStream,
345
+ drained: Option<Pin<Box<dyn Future<Output = ()> + Send + 'a>>>,
346
+ }
347
+
348
+ impl AsyncRead for UntilDrained<'_> {
349
+ fn poll_read(
350
+ mut self: Pin<&mut Self>,
351
+ cx: &mut Context<'_>,
352
+ into: &mut ReadBuf<'_>,
353
+ ) -> Poll<io::Result<()>> {
354
+ let this = &mut *self;
355
+ if let Some(drained) = this.drained.as_mut() {
356
+ if let Poll::Ready(read) = Pin::new(&mut *this.io).poll_read(cx, into) {
357
+ return Poll::Ready(read);
358
+ }
359
+ if drained.as_mut().poll(cx).is_pending() {
360
+ return Poll::Pending;
361
+ }
362
+ this.drained = None;
363
+ }
364
+ Poll::Ready(match read_now(this.io, into.initialize_unfilled()) {
365
+ Ok(n) => {
366
+ into.advance(n);
367
+ Ok(())
368
+ }
369
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
370
+ Err(io::Error::other("the server shut down mid-body"))
371
+ }
372
+ Err(error) => Err(error),
373
+ })
374
+ }
375
+ }
376
+
377
+ /// The app's response head, leaving what follows it in `buf`.
378
+ async fn read_head(
379
+ io: &mut tokio::net::UnixStream,
380
+ buf: &mut BytesMut,
381
+ ) -> Result<hyper::Response<()>, NoHead> {
382
+ loop {
383
+ if let Some(head) = parse_head(buf).map_err(|()| NoHead::Bad)? {
384
+ return Ok(head);
385
+ }
386
+ if buf.len() >= MAX_HEAD {
387
+ return Err(NoHead::Bad);
388
+ }
389
+ buf.reserve(READ_CHUNK);
390
+ if io.read_buf(buf).await.map_err(|_| NoHead::Bad)? == 0 {
391
+ return Err(if buf.is_empty() {
392
+ NoHead::Silent
393
+ } else {
394
+ NoHead::Bad
395
+ });
396
+ }
397
+ }
398
+ }
399
+
400
+ /// Takes a whole head off `buf`; Ok(None) while it is partial.
401
+ fn parse_head(buf: &mut BytesMut) -> Result<Option<hyper::Response<()>>, ()> {
402
+ let mut slots = [httparse::EMPTY_HEADER; framing::MAX_HEADERS];
403
+ let mut parsed = httparse::Response::new(&mut slots);
404
+ let length = match parsed.parse(buf) {
405
+ Ok(httparse::Status::Complete(length)) if length <= MAX_HEAD => length,
406
+ Ok(httparse::Status::Partial) => return Ok(None),
407
+ _ => return Err(()),
408
+ };
409
+ let mut head = hyper::Response::builder().status(parsed.code.ok_or(())?);
410
+ for header in parsed.headers.iter() {
411
+ head = head.header(header.name, header.value);
412
+ }
413
+ let head = head.body(()).map_err(drop)?;
414
+ // hyper sends one final head; of the 1xx, only a switch is final.
415
+ let status = head.status();
416
+ if status.is_informational() && status != StatusCode::SWITCHING_PROTOCOLS {
417
+ return Err(());
418
+ }
419
+ buf.advance(length);
420
+ Ok(Some(head))
421
+ }
422
+
423
+ /// The Content-Length of the body behind a head; None for a body framed any
424
+ /// other way (chunked, or by the close), which the bridge does not carry, and
425
+ /// for a Content-Length hyper's encoder refuses by dropping the connection
426
+ /// unanswered: a value that is not all ASCII digits (a sign, a list, a number
427
+ /// past u64), or two values that differ. A bodiless answer has no body
428
+ /// whatever its head declares, which is what hyper sends of it.
429
+ fn body_length(head: &hyper::Response<()>, head_request: bool) -> Option<u64> {
430
+ if !framing::usable_length(head.headers()) {
431
+ return None;
432
+ }
433
+ if framing::bodiless(head.status().as_u16(), head_request) {
434
+ return Some(0);
435
+ }
436
+ // A transfer coding voids any length (RFC 9112 6.3).
437
+ if head.headers().contains_key(TRANSFER_ENCODING) {
438
+ return None;
439
+ }
440
+ framing::content_length(head.headers())
441
+ }
442
+
443
+ /// The body's `length` bytes as frames, from `buf` first, then from the app.
444
+ async fn forward(
445
+ app: &mut UntilDrained<'_>,
446
+ mut buf: BytesMut,
447
+ mut length: u64,
448
+ frames: &flume::Sender<FrameResult>,
449
+ ) -> io::Result<()> {
450
+ while length > 0 {
451
+ if buf.is_empty() {
452
+ buf.reserve(READ_CHUNK);
453
+ if app.read_buf(&mut buf).await? == 0 {
454
+ return Err(io::Error::new(
455
+ io::ErrorKind::UnexpectedEof,
456
+ "the app closed its hijacked connection mid-body",
457
+ ));
458
+ }
459
+ }
460
+ let n = buf.len().min(usize::try_from(length).unwrap_or(usize::MAX));
461
+ let data = hyper::body::Frame::data(buf.split_to(n).freeze());
462
+ // Fails once the client is gone.
463
+ let sent = frames.send_async(Ok(data)).await;
464
+ sent.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?;
465
+ length -= n as u64;
466
+ }
467
+ Ok(())
468
+ }
469
+
470
+ #[cfg(test)]
471
+ mod tests;