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
@@ -1,8 +1,10 @@
1
1
  //! The response half of a request's lifecycle. A `Responder` is shared
2
- //! between the Ruby-held `Request` handle and (via `Weak`) the worker slot,
3
- //! so exactly one of three parties can answer the client: the app (normal
4
- //! path), the supervisor (`abort_inflight` after a ractor crash), or the
2
+ //! between the Ruby-held `Request` handle and the worker slot's in-flight
3
+ //! list, so exactly one of three parties can answer the client: the app
4
+ //! (normal path), Kino (`abort_inflight` after a ractor crash, or a
5
+ //! worker's next take, `let_go`, for what it left unanswered), or the
5
6
  //! `RequestCtx` Drop backstop. The `responded` flag makes the race benign.
7
+ //! An inline request is answered on its own socket (Sink::Inline), under its connection's lock.
6
8
  //!
7
9
  //! Two response shapes: `send_response` (complete, one shot) and
8
10
  //! `send_stream_head` + a bounded frame channel (streaming bodies). The
@@ -10,131 +12,539 @@
10
12
  //! makes `write_chunk` block in Ruby, with the GVL released.
11
13
 
12
14
  use std::io;
15
+ use std::pin::Pin;
13
16
  use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
17
+ use std::sync::{Arc, Weak};
18
+ use std::task::{Context, Poll};
14
19
 
15
20
  use bytes::Bytes;
16
21
  use http_body_util::{Either, Full, StreamBody};
17
22
  use parking_lot::Mutex;
23
+ use tokio::sync::oneshot;
24
+
25
+ use crate::counters::{tallied, Tallied, Tally};
26
+ use crate::doorbell::Doorbell;
27
+ use crate::framing::{usable_length, Bodiless};
18
28
 
19
29
  pub type BodyFrame = hyper::body::Frame<Bytes>;
20
30
  pub type FrameResult = Result<BodyFrame, io::Error>;
21
31
  /// Both response shapes as one concrete type: no per-response Box or
22
32
  /// vtable, unlike BoxBody. Either erases the two error types itself.
23
- pub type ResponseBody =
24
- Either<Full<Bytes>, StreamBody<flume::r#async::RecvStream<'static, FrameResult>>>;
33
+ pub type ResponseBody = Either<Full<Bytes>, Streamed>;
25
34
  pub type HyperResponse = hyper::Response<ResponseBody>;
26
35
 
27
36
  const STREAM_BUFFER: usize = 8;
28
37
 
38
+ tallied! {
39
+ /// Why a streamed response ended before the app finished it.
40
+ pub enum Cut {
41
+ ClientGone => "client_gone",
42
+ /// The drain's deadline passed with the stream still going.
43
+ Shutdown => "shutdown",
44
+ /// Its worker crashed, the app raised mid-stream, or the request was dropped.
45
+ Crash => "crash",
46
+ }
47
+ }
48
+
49
+ static CUT: Tally<Cut, { Cut::ALL.len() }> = Tally::new();
50
+
51
+ pub fn responses_cut() -> [(&'static str, u64); Cut::ALL.len()] {
52
+ Cut::named(CUT.read())
53
+ }
54
+
29
55
  /// Why the body forwarder stopped pulling a request body: read_body turns
30
56
  /// these into raised errors instead of a (truncated) clean EOF.
31
57
  #[derive(Clone, Copy, PartialEq, Eq, Debug)]
58
+ #[repr(u8)]
32
59
  pub enum BodyAbandon {
33
- Oversize,
34
- TimedOut,
60
+ Oversize = 1,
61
+ TimedOut = 2,
62
+ /// The forwarder went with the runtime mid-body (shutdown).
63
+ Interrupted = 3,
35
64
  }
36
65
 
66
+ impl TryFrom<u8> for BodyAbandon {
67
+ type Error = u8;
68
+
69
+ fn try_from(code: u8) -> Result<Self, u8> {
70
+ match code {
71
+ 1 => Ok(BodyAbandon::Oversize),
72
+ 2 => Ok(BodyAbandon::TimedOut),
73
+ 3 => Ok(BodyAbandon::Interrupted),
74
+ none => Err(none),
75
+ }
76
+ }
77
+ }
78
+
79
+ /// hyper's side of the answer: the head's oneshot, then a streamed body's channel.
80
+ #[derive(Default)]
81
+ struct HyperSink {
82
+ head: Mutex<Option<oneshot::Sender<HyperResponse>>>,
83
+ body: Mutex<Option<flume::Sender<FrameResult>>>,
84
+ /// An accepted handshake's 101, held until on_open ran, with what tells the socket's
85
+ /// task it went out; dropped unsent, the task learns it never will.
86
+ held_101: Mutex<Option<(oneshot::Sender<()>, Box<HyperResponse>)>>,
87
+ }
88
+
89
+ /// Where a request's answer goes: hyper's connection, or the one it was read on inline.
90
+ enum Sink {
91
+ Hyper(HyperSink),
92
+ Inline(Weak<crate::inline::InlineIo>),
93
+ }
94
+
95
+ impl Default for Sink {
96
+ fn default() -> Self {
97
+ Sink::Hyper(HyperSink::default())
98
+ }
99
+ }
100
+
101
+ /// How a request's answer reaches its connection. Dropped and given up in a thread-safe free:
102
+ /// what it holds and what give_up calls keep typed_data.rs's promise.
103
+ #[derive(Default)]
37
104
  pub struct Responder {
105
+ sink: Sink,
106
+ /// An inline stream is going out, from its head until its end.
107
+ streaming: AtomicBool,
108
+ /// A stream started, inline or not: whether it is still open is let_go's to look.
109
+ streamed: AtomicBool,
38
110
  responded: AtomicBool,
39
111
  /// The forwarder's abandonment flag rides in the one per-request shared
40
- /// allocation rather than its own Arc. 0 = none, 1/2 = BodyAbandon.
112
+ /// allocation rather than its own Arc. 0 = none, else a BodyAbandon.
41
113
  body_abandoned: AtomicU8,
42
- head_tx: Mutex<Option<tokio::sync::oneshot::Sender<HyperResponse>>>,
43
- body_tx: Mutex<Option<flume::Sender<FrameResult>>>,
114
+ /// Out of in_flight: once hijacked or once handle_request ended, whichever came first.
115
+ left_in_flight: AtomicBool,
116
+ /// Cut short (the client left, or it was given up): it ends in an error even when its
117
+ /// error frame found no room; counted once, for the first cause.
118
+ stream_cut: AtomicBool,
119
+ /// No cut counts: a bodiless answer, or a head that never went out (answered_first).
120
+ uncounted: AtomicBool,
121
+ /// Body I/O under a fiber scheduler waits on these: the next chunk or the body's end rings
122
+ /// `body_bell`, room in the response stream or its end `room_bell`.
123
+ pub body_bell: Doorbell,
124
+ pub room_bell: Doorbell,
44
125
  }
45
126
 
46
127
  impl Responder {
47
- pub fn new(head_tx: tokio::sync::oneshot::Sender<HyperResponse>) -> Self {
128
+ pub fn new(head_tx: oneshot::Sender<HyperResponse>) -> Self {
129
+ let head = Mutex::new(Some(head_tx));
130
+ Responder {
131
+ sink: Sink::Hyper(HyperSink {
132
+ head,
133
+ ..HyperSink::default()
134
+ }),
135
+ ..Responder::default()
136
+ }
137
+ }
138
+
139
+ pub fn inline(io: Weak<crate::inline::InlineIo>) -> Self {
48
140
  Responder {
49
- responded: AtomicBool::new(false),
50
- body_abandoned: AtomicU8::new(0),
51
- head_tx: Mutex::new(Some(head_tx)),
52
- body_tx: Mutex::new(None),
141
+ sink: Sink::Inline(io),
142
+ ..Responder::default()
143
+ }
144
+ }
145
+
146
+ fn hyper(&self) -> Option<&HyperSink> {
147
+ match &self.sink {
148
+ Sink::Hyper(hyper) => Some(hyper),
149
+ Sink::Inline(_) => None,
53
150
  }
54
151
  }
55
152
 
153
+ /// True for the first caller only, which owes in_flight its decrement.
154
+ pub fn leave_in_flight(&self) -> bool {
155
+ !self.left_in_flight.swap(true, Ordering::AcqRel)
156
+ }
157
+
158
+ pub fn ring_bells(&self) {
159
+ self.body_bell.ring();
160
+ self.room_bell.ring();
161
+ }
162
+
163
+ pub fn close_bells(&self) {
164
+ self.body_bell.release();
165
+ self.room_bell.release();
166
+ }
167
+
56
168
  /// Record why the body forwarder gave up; the store happens before the
57
169
  /// sender drops, so a reader that saw Disconnected sees the flag too.
58
170
  pub fn abandon_body(&self, why: BodyAbandon) {
59
- let code = match why {
60
- BodyAbandon::Oversize => 1,
61
- BodyAbandon::TimedOut => 2,
62
- };
63
- self.body_abandoned.store(code, Ordering::Relaxed);
171
+ self.body_abandoned.store(why as u8, Ordering::Relaxed);
64
172
  }
65
173
 
66
174
  /// Whether (and why) the forwarder abandoned the request body.
67
175
  pub fn body_abandoned(&self) -> Option<BodyAbandon> {
68
- match self.body_abandoned.load(Ordering::Relaxed) {
69
- 1 => Some(BodyAbandon::Oversize),
70
- 2 => Some(BodyAbandon::TimedOut),
71
- _ => None,
176
+ BodyAbandon::try_from(self.body_abandoned.load(Ordering::Relaxed)).ok()
177
+ }
178
+
179
+ /// The app still owes its answer, or the rest of a stream that was not cut.
180
+ pub fn open(&self) -> bool {
181
+ !self.responded.load(Ordering::SeqCst)
182
+ || (!self.stream_cut()
183
+ && (self.streaming.load(Ordering::SeqCst)
184
+ || self.hyper().is_some_and(|h| h.body.lock().is_some())))
185
+ }
186
+
187
+ pub(crate) fn set_streaming(&self, streaming: bool) {
188
+ if streaming {
189
+ self.streamed.store(true, Ordering::Relaxed);
72
190
  }
191
+ self.streaming.store(streaming, Ordering::SeqCst);
73
192
  }
74
193
 
75
194
  /// Claim the right to respond. First caller wins; everyone else gets None.
76
- fn claim(&self) -> Option<tokio::sync::oneshot::Sender<HyperResponse>> {
195
+ /// An inline request's is claimed on its connection instead (claim_inline).
196
+ fn claim(&self) -> Option<oneshot::Sender<HyperResponse>> {
197
+ let hyper = self.hyper()?;
77
198
  if self.responded.swap(true, Ordering::SeqCst) {
78
199
  return None;
79
200
  }
80
- self.head_tx.lock().take()
201
+ hyper.head.lock().take()
202
+ }
203
+
204
+ /// Under the connection's lock. First caller wins.
205
+ pub fn claim_inline(&self) -> bool {
206
+ !self.responded.swap(true, Ordering::SeqCst)
207
+ }
208
+
209
+ /// Whether the app's answer, its stream's head or Kino's own claimed the request.
210
+ pub fn claimed(&self) -> bool {
211
+ self.responded.load(Ordering::SeqCst)
81
212
  }
82
213
 
83
214
  /// Complete response in one shot.
84
215
  pub fn send_response(&self, response: HyperResponse) -> bool {
85
- match self.claim() {
86
- Some(tx) => tx.send(response).is_ok(),
87
- None => false,
216
+ self.claim().is_some_and(|head| head.send(response).is_ok())
217
+ }
218
+
219
+ /// Hold a handshake's 101 for `switch`; `switched` hears when it goes out, and is dropped
220
+ /// when anything else answers. hyper keeps a connection open for an upgrade after any
221
+ /// answer but a 101, so the socket must not wait on hyper.
222
+ pub fn hold_for_switch(&self, switched: oneshot::Sender<()>, response: HyperResponse) {
223
+ debug_assert!(self.hyper().is_some(), "inline serves no protocol switch");
224
+ if let Some(hyper) = self.hyper() {
225
+ *hyper.held_101.lock() = Some((switched, Box::new(response)));
226
+ }
227
+ }
228
+
229
+ /// False when nothing is held, or something else answered first (a 500, a 504).
230
+ pub fn switch(&self) -> bool {
231
+ let Some(hyper) = self.hyper() else {
232
+ return false;
233
+ };
234
+ let mut held = hyper.held_101.lock();
235
+ let Some((switched, response)) = held.take() else {
236
+ return false;
237
+ };
238
+ let sent = self.send_response(*response);
239
+ if sent {
240
+ let _ = switched.send(());
88
241
  }
242
+ sent
243
+ }
244
+
245
+ pub fn cancel_switch(&self) -> bool {
246
+ self.hyper()
247
+ .is_some_and(|h| h.held_101.lock().take().is_some())
248
+ }
249
+
250
+ /// A stream's claim on the answer, with hyper's sink; None, the stream reading as cut, when
251
+ /// Kino answered first.
252
+ fn claim_stream(&self) -> Option<(&HyperSink, oneshot::Sender<HyperResponse>)> {
253
+ let (Some(hyper), Some(head)) = (self.hyper(), self.claim()) else {
254
+ // A request starts its stream once: an open one is its own.
255
+ if self.hyper().is_none_or(|h| h.body.lock().is_none()) {
256
+ self.answered_first();
257
+ }
258
+ return None;
259
+ };
260
+ // Closed when a request_timeout 504 went out instead, or the request is gone.
261
+ if head.is_closed() {
262
+ self.answered_first();
263
+ return None;
264
+ }
265
+ Some((hyper, head))
266
+ }
267
+
268
+ /// A streamed answer's head where HTTP allows no body: it goes out with an empty one, its
269
+ /// first Content-Length kept; one hyper would refuse keeps an unknown-length body, for hyper
270
+ /// to refuse. False when Kino answered first.
271
+ pub fn send_bodiless_head(
272
+ &self,
273
+ mut builder: hyper::http::response::Builder,
274
+ bodiless: Bodiless,
275
+ ) -> Result<bool, http::Error> {
276
+ let Some((_, head)) = self.claim_stream() else {
277
+ return Ok(false);
278
+ };
279
+ if let Some(headers) = builder.headers_mut() {
280
+ bodiless.drop_forbidden_length(headers);
281
+ }
282
+ let usable = builder.headers_ref().is_none_or(usable_length);
283
+ let body = if usable {
284
+ if let Some(headers) = builder.headers_mut() {
285
+ bodiless.keep_length(headers, 0);
286
+ }
287
+ full_body(Bytes::new())
288
+ } else {
289
+ let (_, frames) = flume::bounded::<FrameResult>(1);
290
+ Either::Right(Streamed::new(frames, None, None))
291
+ };
292
+ let sent = head.send(builder.body(body)?).is_ok();
293
+ self.answered_first();
294
+ Ok(sent)
89
295
  }
90
296
 
91
297
  /// Start a streaming response from a prepared head: send it now, return
92
- /// chunks later through the frame channel. Returns false if someone
93
- /// already responded.
298
+ /// chunks later; false when Kino answered first.
94
299
  pub fn send_stream_head(
95
- &self,
300
+ self: &Arc<Self>,
96
301
  builder: hyper::http::response::Builder,
97
302
  ) -> Result<bool, http::Error> {
98
- let Some(tx) = self.claim() else {
303
+ let Some((hyper, head)) = self.claim_stream() else {
99
304
  return Ok(false);
100
305
  };
101
- let (body_tx, body_rx) = flume::bounded::<FrameResult>(STREAM_BUFFER);
102
- let response = builder.body(Either::Right(StreamBody::new(body_rx.into_stream())))?;
103
- *self.body_tx.lock() = Some(body_tx);
104
- let _ = tx.send(response);
306
+ let (body, frames) = flume::bounded(STREAM_BUFFER);
307
+ let streamed = Streamed::new(frames, Some(self.clone()), None);
308
+ let response = builder.body(Either::Right(streamed))?;
309
+ self.streamed.store(true, Ordering::Relaxed);
310
+ *hyper.body.lock() = Some(body);
311
+ if head.send(response).is_err() {
312
+ self.answered_first();
313
+ return Ok(false);
314
+ }
105
315
  Ok(true)
106
316
  }
107
317
 
318
+ /// Kino answered first (a 504 or a give-up's 500), the request is gone, or its head allows no
319
+ /// body: the stream reads as cut, so the next write ends it, but no cut counts.
320
+ pub(crate) fn answered_first(&self) {
321
+ self.uncounted.store(true, Ordering::Relaxed);
322
+ if let Some(hyper) = self.hyper() {
323
+ hyper.body.lock().take();
324
+ }
325
+ self.stream_cut.store(true, Ordering::SeqCst);
326
+ }
327
+
328
+ /// Hand the answer to a hijack's bridge; everyone else then finds it answered.
329
+ pub fn hijack(&self) -> Option<oneshot::Sender<HyperResponse>> {
330
+ self.claim()
331
+ }
332
+
108
333
  /// Clone of the live frame sender, if a stream is open. The clone lets
109
334
  /// `write_chunk` block on a full channel without holding the lock.
110
335
  pub fn body_sender(&self) -> Option<flume::Sender<FrameResult>> {
111
- self.body_tx.lock().clone()
336
+ self.hyper().and_then(|hyper| hyper.body.lock().clone())
337
+ }
338
+
339
+ pub fn stream_cut(&self) -> bool {
340
+ self.stream_cut.load(Ordering::SeqCst)
112
341
  }
113
342
 
114
343
  /// Clean end of stream: dropping the sender ends the hyper body.
115
344
  pub fn finish_stream(&self) {
116
- self.body_tx.lock().take();
345
+ match &self.sink {
346
+ Sink::Hyper(hyper) => {
347
+ hyper.body.lock().take();
348
+ self.room_bell.ring();
349
+ }
350
+ Sink::Inline(io) => {
351
+ if let Some(io) = io.upgrade() {
352
+ io.finish_stream(self);
353
+ }
354
+ }
355
+ }
356
+ }
357
+
358
+ pub fn cut_stream(&self, why: Cut) {
359
+ if !self.stream_cut.swap(true, Ordering::SeqCst) && !self.uncounted.load(Ordering::Relaxed)
360
+ {
361
+ CUT.add(why);
362
+ }
363
+ }
364
+
365
+ /// The worker let go of the request (Load::let_go): one never answered gets a give-up's 500
366
+ /// and an open stream is cut, but a hijack or a 101 waiting for on_open is left to the app.
367
+ /// One answered whole costs two loads.
368
+ pub fn let_go(&self) {
369
+ if self.claimed() && !self.streamed.load(Ordering::Relaxed) {
370
+ return;
371
+ }
372
+ if !self.open() || self.hyper().is_some_and(|h| h.held_101.lock().is_some()) {
373
+ return;
374
+ }
375
+ self.give_up(Cut::Crash);
117
376
  }
118
377
 
119
378
  /// The "the app will never answer" path. Before the head: canned 500.
120
379
  /// Mid-stream: error frame, which makes hyper abort the connection
121
380
  /// rather than fake a clean end. Never touches the Ruby API: callable
122
- /// from Drop, tokio threads, and the supervisor.
123
- pub fn respond_500_if_unsent(&self) {
381
+ /// from Drop, tokio threads, and the supervisor. Never waits either.
382
+ /// An inline request's goes out on its connection (InlineIo::give_up), else is only claimed.
383
+ pub fn give_up(&self, why: Cut) {
384
+ let hyper = match &self.sink {
385
+ Sink::Hyper(hyper) => hyper,
386
+ Sink::Inline(io) => {
387
+ match io.upgrade() {
388
+ Some(io) => io.give_up(self, why),
389
+ None => _ = self.claim_inline(),
390
+ }
391
+ return;
392
+ }
393
+ };
124
394
  if let Some(tx) = self.claim() {
125
- let _ = tx.send(plain_response(500, "Internal Server Error\n"));
395
+ let mut response = plain_response(500, "Internal Server Error\n");
396
+ if self.cancel_switch() {
397
+ close_connection(&mut response);
398
+ }
399
+ let _ = tx.send(response);
126
400
  return;
127
401
  }
128
- if let Some(body_tx) = self.body_tx.lock().take() {
129
- let _ = body_tx.send(Err(io::Error::other("Kino: response abandoned mid-stream")));
402
+ if let Some(body_tx) = hyper.body.lock().take() {
403
+ // Flagged before the send: without room for the frame, hyper fails it once drained.
404
+ self.cut_stream(why);
405
+ let _ = body_tx.try_send(Err(abandoned()));
406
+ // A write waiting for room fails now, not once the client reads.
407
+ self.room_bell.ring();
130
408
  }
131
409
  }
132
410
  }
133
411
 
412
+ fn abandoned() -> io::Error {
413
+ io::Error::other("Kino: response abandoned mid-stream")
414
+ }
415
+
134
416
  pub fn full_body(bytes: Bytes) -> ResponseBody {
135
417
  Either::Left(Full::new(bytes))
136
418
  }
137
419
 
420
+ /// Holds `held` until hyper drops the body, in the poll that writes its last frame.
421
+ pub fn stream_body_holding(
422
+ frames: flume::Receiver<FrameResult>,
423
+ held: Arc<dyn Send + Sync>,
424
+ ) -> ResponseBody {
425
+ Either::Right(Streamed::new(frames, None, Some(held)))
426
+ }
427
+
428
+ pub struct Streamed {
429
+ frames: Option<StreamBody<flume::r#async::RecvStream<'static, FrameResult>>>,
430
+ /// A worker's stream's; each frame hyper takes, and the body's drop, rings its room bell.
431
+ responder: Option<Arc<Responder>>,
432
+ _held: Option<Arc<dyn Send + Sync>>,
433
+ /// hyper took something (the head, then data) since the body last made it wait.
434
+ taken_since_wait: bool,
435
+ failed: Option<io::Error>,
436
+ }
437
+
438
+ impl Streamed {
439
+ fn new(
440
+ frames: flume::Receiver<FrameResult>,
441
+ responder: Option<Arc<Responder>>,
442
+ held: Option<Arc<dyn Send + Sync>>,
443
+ ) -> Streamed {
444
+ Streamed {
445
+ frames: Some(StreamBody::new(frames.into_stream())),
446
+ responder,
447
+ _held: held,
448
+ taken_since_wait: true,
449
+ failed: None,
450
+ }
451
+ }
452
+ }
453
+
454
+ impl hyper::body::Body for Streamed {
455
+ type Data = Bytes;
456
+ type Error = io::Error;
457
+
458
+ fn poll_frame(
459
+ self: Pin<&mut Self>,
460
+ cx: &mut Context<'_>,
461
+ ) -> Poll<Option<Result<hyper::body::Frame<Bytes>, io::Error>>> {
462
+ let this = self.get_mut();
463
+ if let Some(error) = this.failed.take() {
464
+ return Poll::Ready(Some(Err(error)));
465
+ }
466
+ let Some(frames) = this.frames.as_mut() else {
467
+ return Poll::Ready(None);
468
+ };
469
+ let mut polled = Pin::new(frames).poll_frame(cx);
470
+ if let Some(responder) = &this.responder {
471
+ if polled.is_ready() {
472
+ responder.room_bell.ring();
473
+ }
474
+ if matches!(polled, Poll::Ready(None)) && responder.stream_cut() {
475
+ polled = Poll::Ready(Some(Err(abandoned())));
476
+ }
477
+ }
478
+ match polled {
479
+ // Once a body fails, hyper drops what it took but has not written (h1: the
480
+ // write buffer, head included; h2: the reset stream's frames): wait once first.
481
+ // h2 writing before this task runs again rests on tokio's order, not on hyper.
482
+ Poll::Ready(Some(Err(error))) if this.taken_since_wait => {
483
+ this.taken_since_wait = false;
484
+ this.failed = Some(error);
485
+ cx.waker().wake_by_ref();
486
+ Poll::Pending
487
+ }
488
+ Poll::Ready(Some(Ok(frame))) => {
489
+ this.taken_since_wait = true;
490
+ Poll::Ready(Some(Ok(frame)))
491
+ }
492
+ Poll::Pending => {
493
+ this.taken_since_wait = false;
494
+ Poll::Pending
495
+ }
496
+ polled => polled,
497
+ }
498
+ }
499
+
500
+ fn is_end_stream(&self) -> bool {
501
+ self.frames
502
+ .as_ref()
503
+ .is_none_or(|frames| frames.is_end_stream())
504
+ }
505
+
506
+ fn size_hint(&self) -> hyper::body::SizeHint {
507
+ self.frames.as_ref().map_or_else(
508
+ || hyper::body::SizeHint::with_exact(0),
509
+ |frames| frames.size_hint(),
510
+ )
511
+ }
512
+ }
513
+
514
+ impl Drop for Streamed {
515
+ /// The channel closes before the ring, so the writer it wakes finds it closed.
516
+ fn drop(&mut self) {
517
+ self.frames.take();
518
+ if let Some(responder) = &self.responder {
519
+ responder.room_bell.ring();
520
+ }
521
+ }
522
+ }
523
+
524
+ /// A request that asked to switch and did not: hyper would keep it for an upgrade.
525
+ pub fn close_connection<B>(response: &mut hyper::Response<B>) {
526
+ response.headers_mut().insert(
527
+ http::header::CONNECTION,
528
+ http::HeaderValue::from_static("close"),
529
+ );
530
+ }
531
+
532
+ /// `response` with no body where HTTP allows none (a HEAD, a 1xx, a 204, a 304), as hyper over h2
533
+ /// would send it as DATA; a HEAD keeps its body's length, a 1xx or a 204 has none. A streamed
534
+ /// body stays: its head decided (send_stream_head).
535
+ pub fn without_forbidden_body(mut response: HyperResponse, head: bool) -> HyperResponse {
536
+ let Some(bodiless) = Bodiless::of(response.status().as_u16(), head) else {
537
+ return response;
538
+ };
539
+ let len = match response.body() {
540
+ Either::Left(full) => hyper::body::Body::size_hint(full).exact().unwrap_or(0),
541
+ Either::Right(_) => return response,
542
+ };
543
+ bodiless.settle(response.headers_mut(), len as usize);
544
+ *response.body_mut() = full_body(Bytes::new());
545
+ response
546
+ }
547
+
138
548
  /// Canned plain-text response, built entirely on the Rust side (used for
139
549
  /// the 500/503/504 paths that never reach Ruby).
140
550
  pub fn plain_response(status: u16, message: &'static str) -> HyperResponse {
@@ -149,72 +559,70 @@ pub fn plain_response(status: u16, message: &'static str) -> HyperResponse {
149
559
  mod tests {
150
560
  use super::*;
151
561
 
152
- fn pair() -> (Responder, tokio::sync::oneshot::Receiver<HyperResponse>) {
153
- let (head_tx, head_rx) = tokio::sync::oneshot::channel();
154
- (Responder::new(head_tx), head_rx)
155
- }
562
+ /// A responder, and hyper's end of its head.
563
+ type Pair = (Arc<Responder>, oneshot::Receiver<HyperResponse>);
156
564
 
157
- #[test]
158
- fn first_claimant_wins() {
159
- let (responder, mut head_rx) = pair();
160
-
161
- assert!(responder.send_response(plain_response(200, "first")));
162
- assert!(!responder.send_response(plain_response(201, "second")));
163
- assert_eq!(head_rx.try_recv().expect("head sent").status(), 200);
565
+ fn pair() -> Pair {
566
+ let (head_tx, head_rx) = oneshot::channel();
567
+ (Arc::new(Responder::new(head_tx)), head_rx)
164
568
  }
165
569
 
166
570
  #[test]
167
571
  fn backstop_sends_500_when_unsent_and_is_idempotent() {
168
572
  let (responder, mut head_rx) = pair();
169
573
 
170
- responder.respond_500_if_unsent();
171
- responder.respond_500_if_unsent(); // second call must be a no-op
574
+ responder.give_up(Cut::Crash);
575
+ responder.give_up(Cut::Crash); // second call must be a no-op
172
576
 
173
577
  assert_eq!(head_rx.try_recv().expect("head sent").status(), 500);
174
578
  assert!(!responder.send_response(plain_response(200, "late")));
175
579
  }
176
580
 
177
- #[test]
178
- fn stream_head_claims_and_opens_the_frame_channel() {
179
- let (responder, mut head_rx) = pair();
180
-
181
- let started = responder
581
+ /// A response whose stream has started.
582
+ fn streaming() -> Pair {
583
+ let (responder, head_rx) = pair();
584
+ assert!(responder
182
585
  .send_stream_head(hyper::Response::builder().status(200))
183
- .expect("valid head");
184
- assert!(started);
185
- assert_eq!(head_rx.try_recv().expect("head sent").status(), 200);
186
-
187
- // A second stream start loses the claim.
188
- let again = responder
189
- .send_stream_head(hyper::Response::builder().status(201))
190
- .expect("valid head");
191
- assert!(!again);
192
-
193
- // The frame channel is open until finish_stream closes it.
194
- assert!(responder.body_sender().is_some());
195
- responder.finish_stream();
196
- assert!(responder.body_sender().is_none());
586
+ .expect("valid head"));
587
+ (responder, head_rx)
197
588
  }
198
589
 
199
590
  #[test]
200
- fn backstop_mid_stream_closes_the_frame_channel() {
201
- let (responder, _head_rx) = pair();
202
-
203
- responder
204
- .send_stream_head(hyper::Response::builder().status(200))
205
- .expect("valid head");
206
- assert!(responder.body_sender().is_some());
207
-
208
- // Mid-stream abandonment: the error frame goes to hyper (which
209
- // aborts the connection) and the channel is closed for the app.
210
- responder.respond_500_if_unsent();
211
- assert!(responder.body_sender().is_none());
591
+ fn a_stream_cut_counts_once_for_what_cut_it_first() {
592
+ // The counts are process-wide; the other tests that cut a stream
593
+ // take the lock too.
594
+ let _serial = crate::testing::SERIAL.blocking_lock();
595
+ let before = responses_cut();
596
+
597
+ let (gone, _gone) = streaming();
598
+ gone.cut_stream(Cut::ClientGone);
599
+ gone.give_up(Cut::Crash); // the app raised once its client left
600
+ let (stopped, _stopped) = streaming();
601
+ stopped.give_up(Cut::Shutdown);
602
+ stopped.give_up(Cut::Shutdown);
603
+ let (raised, _raised) = streaming();
604
+ raised.give_up(Cut::Crash);
605
+ let (finished, _finished) = streaming();
606
+ finished.finish_stream();
607
+ finished.give_up(Cut::Crash);
608
+ let (unstarted, _unstarted) = pair();
609
+ unstarted.give_up(Cut::Crash);
610
+
611
+ let cut: Vec<_> = responses_cut()
612
+ .into_iter()
613
+ .zip(before)
614
+ .map(|((cause, now), (_, then))| (cause, now - then))
615
+ .collect();
616
+ assert_eq!(
617
+ cut,
618
+ [("client_gone", 1), ("shutdown", 1), ("crash", 1)],
619
+ "a finished stream and an unstarted response are not cut"
620
+ );
212
621
  }
213
622
 
214
623
  #[test]
215
624
  fn concurrent_claimants_yield_exactly_one_winner() {
216
625
  let (responder, mut head_rx) = pair();
217
- let responder = std::sync::Arc::new(responder);
218
626
 
219
627
  let winners: usize = std::thread::scope(|scope| {
220
628
  (0..16)
@@ -233,13 +641,43 @@ mod tests {
233
641
  }
234
642
 
235
643
  #[test]
236
- fn plain_response_sets_status_and_content_type() {
237
- let response = plain_response(503, "Service Unavailable\n");
644
+ fn a_let_go_cuts_a_stream_left_open_and_leaves_a_finished_one() {
645
+ let _serial = crate::testing::SERIAL.blocking_lock();
646
+ let (open, _head_rx) = streaming();
647
+ open.let_go();
648
+ assert!(open.stream_cut(), "a stream left open is cut");
649
+ assert!(open.body_sender().is_none(), "nothing more goes out on it");
650
+
651
+ let (finished, _head_rx) = streaming();
652
+ finished.finish_stream();
653
+ finished.let_go();
654
+ assert!(!finished.stream_cut(), "a finished stream is no cut");
655
+ }
238
656
 
239
- assert_eq!(response.status(), 503);
657
+ #[test]
658
+ fn a_let_go_leaves_a_hijacked_request_and_a_held_101_alone() {
659
+ let (hijacked, mut head_rx) = pair();
660
+ let bridge = hijacked.hijack().expect("the claim");
661
+ hijacked.let_go();
662
+ assert!(
663
+ head_rx.try_recv().is_err(),
664
+ "the app answers on the connection"
665
+ );
666
+ drop(bridge);
667
+
668
+ let (handshake, mut head_rx) = pair();
669
+ let (switched, mut told) = oneshot::channel();
670
+ handshake.hold_for_switch(switched, plain_response(101, ""));
671
+ handshake.let_go();
672
+ assert!(
673
+ head_rx.try_recv().is_err(),
674
+ "the socket's 101 waits for its on_open"
675
+ );
676
+ let held = told.try_recv();
240
677
  assert_eq!(
241
- response.headers().get("content-type").unwrap(),
242
- "text/plain"
678
+ held,
679
+ Err(oneshot::error::TryRecvError::Empty),
680
+ "the 101 is held"
243
681
  );
244
682
  }
245
683
  }