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,10 +1,10 @@
1
1
  //! `Kino::Native::Request`: the opaque per-request handle. Created INSIDE
2
- //! the worker ractor by the take calls (queue.rs), so the wrapping Ruby
2
+ //! the worker ractor by the take calls (queue/worker.rs), so the wrapping Ruby
3
3
  //! object is owned by the ractor that will use it, and never crosses
4
4
  //! ractor boundaries.
5
5
 
6
- use std::cell::RefCell;
7
- use std::net::SocketAddr;
6
+ use std::cell::{Cell, RefCell, RefMut};
7
+ use std::os::fd::RawFd;
8
8
  use std::sync::Arc;
9
9
 
10
10
  use bytes::Bytes;
@@ -12,16 +12,22 @@ use magnus::r_hash::ForEach;
12
12
  use magnus::value::ReprValue;
13
13
  use magnus::{Error, RArray, RHash, RString, Ruby, Value};
14
14
 
15
+ use crate::doorbell::Doorbell;
16
+ use crate::env_strings::{self, EnvStrings};
17
+ use crate::framing::Bodiless;
15
18
  use crate::gvl;
16
- use crate::response::{full_body, BodyFrame, Responder};
19
+ use crate::pin::PinSlab;
20
+ use crate::registry::ServerInner;
21
+ use crate::response::{full_body, BodyFrame, Cut, FrameResult, Responder};
22
+ use crate::server::Peer;
23
+ use crate::slot::WorkerSlot;
17
24
 
18
25
  pub struct RequestCtx {
19
26
  pub method: http::Method,
20
27
  pub uri: http::Uri,
21
28
  pub version: http::Version,
22
29
  pub headers: http::HeaderMap,
23
- pub remote_addr: SocketAddr,
24
- pub local_addr: SocketAddr,
30
+ pub peer: Peer,
25
31
  pub https: bool,
26
32
  /// Request body, streamed from hyper through a bounded channel: hyper is
27
33
  /// only polled as Ruby consumes, so inbound backpressure is free. None
@@ -29,37 +35,270 @@ pub struct RequestCtx {
29
35
  /// channel allocation entirely.
30
36
  pub body_rx: Option<flume::Receiver<Bytes>>,
31
37
  /// When a frame is bigger than read_body's max_len, the rest waits here.
32
- pub leftover: Option<Bytes>,
33
- /// The owning worker slot (set at admit time, queue.rs); its interrupt
34
- /// flag makes blocked body reads/writes interruptible like the queue pop.
35
- pub slot: Option<Arc<crate::registry::WorkerSlot>>,
38
+ pub leftover: Cell<Option<Bytes>>,
39
+ /// The owning worker slot (set at admit time, queue/worker.rs); its halted flag ends
40
+ /// blocked body reads/writes at the shutdown, as it ends a park.
41
+ pub slot: Option<Arc<WorkerSlot>>,
36
42
  /// The server's zero-copy roots: large response bodies are pinned
37
43
  /// here and ride to hyper without a copy (pin.rs).
38
44
  pub pin_slab: Arc<crate::pin::PinSlab>,
39
45
  pub responder: Arc<Responder>,
40
46
  /// When this request entered the queue, for the queue-wait histogram.
41
- /// Stamped at ctx creation; read once at admit (queue.rs).
47
+ /// Stamped at ctx creation; read once at admit (queue/worker.rs).
42
48
  pub enqueued_at: std::time::Instant,
43
49
  /// Whether the access log wants timing: decided at intake, read on
44
50
  /// the way out, so an idle log costs nothing per request.
45
51
  pub timed: bool,
46
- /// Queue wait, stamped at admit (queue.rs): the log's `wait`.
52
+ /// Queue wait, stamped at admit (queue/worker.rs): the log's `wait`.
47
53
  pub wait: std::time::Duration,
48
54
  /// When a worker took the request; elapsed at the response head it is
49
55
  /// the log's `ruby`.
50
56
  pub admitted_at: std::time::Instant,
51
57
  /// GC pause and objects allocated during the app call, when the
52
- /// worker measured them (Request#timing).
53
- pub gc: Option<(std::time::Duration, u64)>,
58
+ /// worker measured them (Request#timing). A Cell: another thread may wait.
59
+ pub gc: Cell<Option<(std::time::Duration, u64)>>,
60
+ /// HTTP/1.1 with an Upgrade header: ws::accept or rack.hijack claims the connection.
61
+ pub upgrade: Option<crate::upgrade::Upgrade>,
62
+ pub hijacked: bool,
63
+ /// Whose in-flight count a hijack leaves.
64
+ pub server_id: u64,
65
+ pub waits: Waits,
66
+ /// Served inline: its connection, held as long as the request is, so a write's wait on its
67
+ /// socket outlives its job (InlineIo::waited); its responder holds it weakly.
68
+ pub inline: Option<Arc<crate::inline::InlineIo>>,
69
+ }
70
+
71
+ /// Whether a wait opened the bells, how many waits are out (Request#waited), and whether the
72
+ /// bells close once none is. Cells, so each native takes the handle's shared borrow: a blocking
73
+ /// write_chunk holds one across its wait while another thread closes the stream.
74
+ #[derive(Default)]
75
+ pub struct Waits {
76
+ opened: Cell<bool>,
77
+ out: Cell<u32>,
78
+ closing: Cell<bool>,
79
+ }
80
+
81
+ /// One step under a fiber scheduler: done, or the descriptor to wait on before the next.
82
+ #[derive(Debug, PartialEq, Eq)]
83
+ pub enum Step<T> {
84
+ Done(T),
85
+ Wait(RawFd),
86
+ }
87
+
88
+ #[derive(Debug)]
89
+ pub enum WaitError {
90
+ /// The response stream was not started, or already finished.
91
+ Closed,
92
+ /// Nothing written reaches anyone (client gone, stream given up): Kino::ClientGone.
93
+ Gone,
94
+ Interrupted,
95
+ /// No descriptor to wait on (out of file descriptors).
96
+ Io(std::io::Error),
97
+ }
98
+
99
+ impl Waits {
100
+ /// `attempt`, else `bell` armed and `attempt` once more, so a change just before the arm
101
+ /// still rings. The bell stays armed after a find, for other fibers on it: a stray ring costs
102
+ /// a look. Past the shutdown deadline (a halted slot) a wait fails as interrupted.
103
+ fn step<T>(
104
+ &self,
105
+ slot: Option<&WorkerSlot>,
106
+ bell: &Doorbell,
107
+ mut attempt: impl FnMut() -> Option<T>,
108
+ ) -> Result<Step<T>, WaitError> {
109
+ if let Some(done) = attempt() {
110
+ return Ok(Step::Done(done));
111
+ }
112
+ let fd = bell.open().map_err(WaitError::Io)?;
113
+ self.opened.set(true);
114
+ bell.arm();
115
+ if let Some(done) = attempt() {
116
+ return Ok(Step::Done(done));
117
+ }
118
+ // After the arm, as the shutdown rings after raising the flag.
119
+ if slot.is_some_and(|slot| slot.life.is_halted()) {
120
+ return Err(WaitError::Interrupted);
121
+ }
122
+ self.out.set(self.out.get() + 1);
123
+ Ok(Step::Wait(fd))
124
+ }
54
125
  }
55
126
 
56
127
  impl RequestCtx {
128
+ /// A request as it joins the queue: its wait starts now.
129
+ pub fn new(
130
+ parts: http::request::Parts,
131
+ peer: Peer,
132
+ server: &crate::registry::ServerInner,
133
+ responder: Arc<Responder>,
134
+ body_rx: Option<flume::Receiver<Bytes>>,
135
+ upgrade: Option<crate::upgrade::Upgrade>,
136
+ ) -> crate::registry::BoxedCtx {
137
+ let mut ctx = RequestCtx::queued(
138
+ server,
139
+ parts.method,
140
+ parts.uri,
141
+ parts.version,
142
+ parts.headers,
143
+ peer,
144
+ responder,
145
+ );
146
+ ctx.body_rx = body_rx;
147
+ ctx.upgrade = upgrade;
148
+ Box::new(ctx)
149
+ }
150
+
151
+ /// Queued now, with no body, worker or switch yet: the caller sets what its request has.
152
+ #[inline]
153
+ pub fn queued(
154
+ server: &ServerInner,
155
+ method: http::Method,
156
+ uri: http::Uri,
157
+ version: http::Version,
158
+ headers: http::HeaderMap,
159
+ peer: Peer,
160
+ responder: Arc<Responder>,
161
+ ) -> Self {
162
+ let now = std::time::Instant::now();
163
+ RequestCtx {
164
+ method,
165
+ uri,
166
+ version,
167
+ headers,
168
+ peer,
169
+ https: server.config.tls.is_some(),
170
+ body_rx: None,
171
+ leftover: Cell::new(None),
172
+ slot: None,
173
+ pin_slab: server.pin_slab.clone(),
174
+ responder,
175
+ enqueued_at: now,
176
+ timed: server.access_log.is_some(),
177
+ wait: std::time::Duration::ZERO,
178
+ admitted_at: now,
179
+ gc: Cell::new(None),
180
+ upgrade: None,
181
+ hijacked: false,
182
+ server_id: server.id,
183
+ waits: Waits::default(),
184
+ inline: None,
185
+ }
186
+ }
187
+
188
+ /// Done(None) at the body's end (or abandonment, see body_ended), when its waits close too.
189
+ pub fn read_nonblock(&self) -> Result<Step<Option<Bytes>>, WaitError> {
190
+ let Some(body_rx) = self.body_rx.as_ref() else {
191
+ return Ok(Step::Done(None));
192
+ };
193
+ let step =
194
+ self.waits.step(
195
+ self.slot.as_deref(),
196
+ &self.responder.body_bell,
197
+ || match body_rx.try_recv() {
198
+ Ok(bytes) => Some(Some(bytes)),
199
+ Err(flume::TryRecvError::Empty) => None,
200
+ Err(flume::TryRecvError::Disconnected) => Some(None),
201
+ },
202
+ )?;
203
+ if step == Step::Done(None) {
204
+ self.close_waits();
205
+ }
206
+ Ok(step)
207
+ }
208
+
209
+ /// One data frame without blocking; `make` makes its bytes once there is room. Gone once the
210
+ /// client is gone or the stream was cut, as write_chunk raises, also for a write that waited.
211
+ pub fn write_nonblock(
212
+ &self,
213
+ make: impl FnOnce(&Arc<PinSlab>) -> Bytes,
214
+ ) -> Result<Step<()>, WaitError> {
215
+ let Some(sender) = self.responder.body_sender() else {
216
+ if self.responder.stream_cut() {
217
+ return Err(WaitError::Gone);
218
+ }
219
+ return Err(WaitError::Closed);
220
+ };
221
+ let pin_slab = &self.pin_slab;
222
+ let mut make = Some(make);
223
+ let mut frame: Option<FrameResult> = None;
224
+ let step = self
225
+ .waits
226
+ .step(self.slot.as_deref(), &self.responder.room_bell, || {
227
+ if sender.is_disconnected() {
228
+ return Some(false);
229
+ }
230
+ if sender.is_full() {
231
+ // As a blocking write's wait: a stream given up while
232
+ // its client stalls never drains.
233
+ return self.responder.stream_cut().then_some(false);
234
+ }
235
+ let next = frame.take().unwrap_or_else(|| {
236
+ let make = make.take().expect("bytes made once");
237
+ Ok(BodyFrame::data(make(pin_slab)))
238
+ });
239
+ match sender.try_send(next) {
240
+ Ok(()) => Some(true),
241
+ Err(flume::TrySendError::Disconnected(_)) => Some(false),
242
+ Err(flume::TrySendError::Full(back)) => {
243
+ frame = Some(back);
244
+ None
245
+ }
246
+ }
247
+ })?;
248
+ match step {
249
+ Step::Done(true) => Ok(Step::Done(())),
250
+ Step::Done(false) => Err(WaitError::Gone),
251
+ Step::Wait(fd) => Ok(Step::Wait(fd)),
252
+ }
253
+ }
254
+
255
+ pub fn waited(&self) {
256
+ self.waits.out.set(self.waits.out.get().saturating_sub(1));
257
+ if self.waits.closing.get() {
258
+ self.close_waits();
259
+ }
260
+ }
261
+
262
+ /// Now if no wait is out, else once the last is back, so no fiber waits on a closed descriptor.
263
+ pub fn close_waits(&self) {
264
+ if !self.waits.opened.get() {
265
+ return;
266
+ }
267
+ if self.waits.out.get() > 0 {
268
+ self.waits.closing.set(true);
269
+ return;
270
+ }
271
+ self.waits.opened.set(false);
272
+ self.waits.closing.set(false);
273
+ self.responder.close_bells();
274
+ }
275
+
276
+ /// Its waits close, and the worker that took it hears (WorkerSlot::answered).
277
+ fn answered(&self) {
278
+ self.close_waits();
279
+ if let Some(slot) = &self.slot {
280
+ slot.answered(&self.responder, self.inline.is_some());
281
+ }
282
+ }
283
+
284
+ /// A plain answer: the task holding the connection for a claim ends now, not at GC.
285
+ pub fn decline_upgrade(&mut self) {
286
+ self.upgrade = None;
287
+ }
288
+
289
+ pub fn offers_websocket(&self) -> bool {
290
+ self.upgrade
291
+ .as_ref()
292
+ .and_then(crate::upgrade::Upgrade::websocket)
293
+ .is_some()
294
+ }
295
+
57
296
  /// The timing this request carries to the access log.
58
297
  fn timing(&self) -> crate::access_log::Timing {
59
298
  crate::access_log::Timing {
60
299
  wait: self.wait,
61
300
  ruby: self.admitted_at.elapsed(),
62
- gc: self.gc,
301
+ gc: self.gc.get(),
63
302
  }
64
303
  }
65
304
  }
@@ -83,65 +322,130 @@ impl Drop for RequestCtx {
83
322
  /// the client gets a 500/abort instead of a hung connection. Never
84
323
  /// touches the Ruby API: safe under `free_immediately`.
85
324
  fn drop(&mut self) {
86
- self.responder.respond_500_if_unsent();
325
+ self.responder.give_up(Cut::Crash);
87
326
  }
88
327
  }
89
328
 
90
- /// Block on a channel operation with the GVL released, waking on the
91
- /// slot's interrupt flag. `attempt` performs one bounded tick and returns
92
- /// Some when done; None on timeout. Ok(None) = interrupted. Every Ruby
93
- /// handle is created by `admit` (queue.rs), which always sets the slot.
329
+ /// Block on a channel operation with the GVL released, as the worker parks (gvl::park):
330
+ /// `attempt` runs one bounded tick, Some when done; Ok(None) once the slot is halted. A raise
331
+ /// comes back as Err, a chunk read or written as it came staying the app's. Every Ruby handle
332
+ /// is created by `admit` (queue/worker.rs), which always sets the slot.
94
333
  fn block_on<T>(
95
- slot: &Option<Arc<crate::registry::WorkerSlot>>,
334
+ slot: &Option<Arc<WorkerSlot>>,
96
335
  attempt: impl FnMut() -> Option<T>,
97
336
  ) -> Result<Option<T>, Error> {
98
337
  let slot = slot.as_ref().expect("slot set by admit");
99
- gvl::interruptible(&slot.interrupted, attempt)
338
+ gvl::park(
339
+ &mut gvl::Released,
340
+ slot.life.halted(),
341
+ attempt,
342
+ gvl::Back::HandedOver,
343
+ )
344
+ }
345
+
346
+ fn runtime_error(ruby: &Ruby, message: impl Into<std::borrow::Cow<'static, str>>) -> Error {
347
+ Error::new(ruby.exception_runtime_error(), message)
100
348
  }
101
349
 
350
+ const INTERRUPTED: &str = "Kino: request interrupted during shutdown";
351
+
102
352
  fn interrupted_error(ruby: &Ruby) -> Error {
103
- Error::new(
104
- ruby.exception_runtime_error(),
105
- "Kino: request interrupted during shutdown",
106
- )
353
+ runtime_error(ruby, INTERRUPTED)
107
354
  }
108
355
 
109
- fn body_too_large_error(ruby: &Ruby) -> Error {
110
- Error::new(
111
- ruby.exception_runtime_error(),
112
- "Kino: request body exceeded max_body_size",
113
- )
356
+ /// A write nothing reaches any more (hyper dropped the body, or Kino gave the stream
357
+ /// up): Kino::ClientGone, an IOError, ends the body's write loop.
358
+ fn client_gone_error(ruby: &Ruby) -> Error {
359
+ use magnus::Module;
360
+
361
+ let class = ruby
362
+ .class_object()
363
+ .const_get::<_, magnus::RModule>("Kino")
364
+ .and_then(|kino| kino.const_get::<_, magnus::ExceptionClass>("ClientGone"))
365
+ .unwrap_or_else(|_| ruby.exception_io_error());
366
+ Error::new(class, "Kino: the response stream is closed")
114
367
  }
115
368
 
116
- fn body_timeout_error(ruby: &Ruby) -> Error {
117
- Error::new(
118
- ruby.exception_runtime_error(),
119
- "Kino: request body read timed out",
369
+ /// Why what needs the request to itself cannot happen now.
370
+ pub(crate) const BUSY: &str =
371
+ "another of the app's threads is waiting on this request (reading its body or writing its response)";
372
+
373
+ fn busy_error(ruby: &Ruby) -> Error {
374
+ runtime_error(ruby, format!("Kino: {BUSY}"))
375
+ }
376
+
377
+ /// ClientGone once Kino gave the stream up, else it was never started or is already finished.
378
+ fn stream_closed_error(ruby: &Ruby, responder: &Responder) -> Error {
379
+ if responder.stream_cut() {
380
+ return client_gone_error(ruby);
381
+ }
382
+ runtime_error(
383
+ ruby,
384
+ "Kino: response stream not started or already finished",
120
385
  )
121
386
  }
122
387
 
388
+ fn wait_error(ruby: &Ruby, responder: &Responder, error: WaitError) -> Error {
389
+ match error {
390
+ WaitError::Closed => stream_closed_error(ruby, responder),
391
+ WaitError::Gone => {
392
+ // Counted once, unless Kino cut it first (counted then).
393
+ responder.cut_stream(crate::response::Cut::ClientGone);
394
+ client_gone_error(ruby)
395
+ }
396
+ WaitError::Interrupted => interrupted_error(ruby),
397
+ WaitError::Io(e) => Error::new(
398
+ ruby.exception_io_error(),
399
+ format!("Kino: no descriptor to wait on the client with: {e}"),
400
+ ),
401
+ }
402
+ }
403
+
123
404
  fn invalid_response(ruby: &Ruby, e: impl std::fmt::Display) -> Error {
124
- Error::new(
125
- ruby.exception_runtime_error(),
126
- format!("invalid response: {e}"),
127
- )
405
+ runtime_error(ruby, format!("invalid response: {e}"))
128
406
  }
129
407
 
130
- #[magnus::wrap(class = "Kino::Native::Request", free_immediately)]
408
+ /// Kino::Native::Request, wrapped in typed_data.rs, whose promise its drop keeps: RequestCtx's
409
+ /// gives the request up through atomics, Kino's own locks, channels and a socket write.
410
+ #[derive(magnus::DataTypeFunctions)]
131
411
  pub struct Request(pub RefCell<RequestCtx>);
132
412
 
413
+ impl Request {
414
+ /// None while another thread holds the request shared, waiting with the GVL released
415
+ /// in read_body or write_chunk, where borrow_mut would panic.
416
+ fn exclusive(&self) -> Option<RefMut<'_, RequestCtx>> {
417
+ self.0.try_borrow_mut().ok()
418
+ }
419
+
420
+ /// While another thread waits on the request, the upgrade is declined at GC instead.
421
+ fn decline_upgrade(&self) {
422
+ if let Some(mut ctx) = self.exclusive() {
423
+ ctx.decline_upgrade();
424
+ }
425
+ }
426
+ }
427
+
133
428
  /// Build the complete Rack env for a request. Static keys and common
134
429
  /// values come from the frozen, Ractor-shareable cache (env_strings);
135
430
  /// only genuinely dynamic strings are allocated. Called by `admit`
136
- /// (queue.rs) with the GVL held, before the ctx is wrapped.
431
+ /// (queue/worker.rs) with the GVL held, before the ctx is wrapped.
137
432
  pub fn build_env(ruby: &Ruby, ctx: &RequestCtx) -> Result<RHash, Error> {
138
- use crate::env_strings;
139
-
140
433
  let s = env_strings::get();
141
434
  // Pre-sized: a dozen static keys plus one per header lands near 30
142
435
  // entries, which a default Hash reaches only via the ar-to-st
143
436
  // migration and a rehash per doubling.
144
437
  let env = ruby.hash_new_capa(32);
438
+ set_request_env(ruby, env, s, ctx)?;
439
+ set_headers_env(ruby, env, s, ctx)?;
440
+ // After the headers, so an authority-derived HTTP_HOST wins over a literal host header
441
+ // a proxy forwarded.
442
+ set_server_env(ruby, env, ctx)?;
443
+ Ok(env)
444
+ }
445
+
446
+ /// The request line, the peer, the scheme, and the rack.* streams.
447
+ #[inline(always)]
448
+ fn set_request_env(ruby: &Ruby, env: RHash, s: &EnvStrings, ctx: &RequestCtx) -> Result<(), Error> {
145
449
  // Opaque -> live RString for this thread's Ruby handle.
146
450
  let live = |o: magnus::value::Opaque<RString>| ruby.get_inner(o);
147
451
 
@@ -166,7 +470,7 @@ pub fn build_env(ruby: &Ruby, ctx: &RequestCtx) -> Result<RHash, Error> {
166
470
  _ => s.http11,
167
471
  };
168
472
  env.aset(live(s.server_protocol), live(protocol))?;
169
- env_strings::set_addr_env(ruby, env, ctx.remote_addr.ip())?;
473
+ env_strings::set_addr_env(ruby, env, ctx.peer.remote.ip())?;
170
474
  // The scheme is the transport's to know, not the app config's.
171
475
  let scheme = if ctx.https { s.https } else { s.http };
172
476
  env.aset(live(s.rack_url_scheme), live(scheme))?;
@@ -182,7 +486,13 @@ pub fn build_env(ruby: &Ruby, ctx: &RequestCtx) -> Result<RHash, Error> {
182
486
  env.aset(live(s.rack_input), ruby.get_inner(null_input))?;
183
487
  }
184
488
  }
489
+ Ok(())
490
+ }
185
491
 
492
+ /// One HTTP_* entry per header name, its values joined.
493
+ #[inline(always)]
494
+ fn set_headers_env(ruby: &Ruby, env: RHash, s: &EnvStrings, ctx: &RequestCtx) -> Result<(), Error> {
495
+ let live = |o: magnus::value::Opaque<RString>| ruby.get_inner(o);
186
496
  for name in ctx.headers.keys() {
187
497
  let key = if *name == http::header::CONTENT_TYPE {
188
498
  live(s.content_type)
@@ -222,65 +532,106 @@ pub fn build_env(ruby: &Ruby, ctx: &RequestCtx) -> Result<RHash, Error> {
222
532
  }
223
533
  }
224
534
  }
535
+ Ok(())
536
+ }
225
537
 
226
- // SERVER_NAME/SERVER_PORT/HTTP_HOST, best source first: the request
227
- // URI's authority (every h2 request via :authority; also h1
228
- // absolute-form, where it beats Host per RFC 9112), then the Host
229
- // header (HTTP/1.1 requires it), then the accepted socket's local
230
- // address. Runs after the header loop so an authority-derived
231
- // HTTP_HOST wins over a literal host header a proxy forwarded.
538
+ /// SERVER_NAME/SERVER_PORT/HTTP_HOST, best source first: the request
539
+ /// URI's authority (every h2 request via :authority; also h1
540
+ /// absolute-form, where it beats Host per RFC 9112), then the Host
541
+ /// header (HTTP/1.1 requires it), then the accepted socket's local
542
+ /// address.
543
+ #[inline(always)]
544
+ fn set_server_env(ruby: &Ruby, env: RHash, ctx: &RequestCtx) -> Result<(), Error> {
545
+ let local_port = ctx.peer.local.port();
232
546
  if let Some(authority) = ctx.uri.authority() {
233
- let local_port = ctx.local_addr.port();
234
- env_strings::set_authority_env(ruby, env, authority.as_str(), || {
235
- (
236
- authority.host().to_string(),
237
- authority.port_u16().unwrap_or(local_port),
238
- )
239
- })?;
240
- } else {
241
- match ctx.headers.get(http::header::HOST) {
242
- Some(host) => {
243
- let local_port = ctx.local_addr.port();
244
- env_strings::set_host_env(
245
- ruby,
246
- env,
247
- host.as_bytes(),
248
- || match std::str::from_utf8(host.as_bytes()) {
249
- Ok(h) => split_host_port(h, local_port),
250
- Err(_) => (
251
- String::from_utf8_lossy(host.as_bytes()).into_owned(),
252
- local_port,
253
- ),
254
- },
255
- )?;
256
- }
257
- None => {
258
- let ip = ctx.local_addr.ip();
259
- let port = ctx.local_addr.port();
260
- env_strings::set_host_env(ruby, env, format!("\0{ip}:{port}").as_bytes(), || {
261
- (ip.to_string(), port)
262
- })?;
263
- }
547
+ let port = authority.port_u16();
548
+ let key = host_key(authority.as_str().as_bytes(), port.is_some(), local_port);
549
+ return env_strings::set_authority_env(ruby, env, &key, authority.as_str(), || {
550
+ (authority.host().to_string(), port.unwrap_or(local_port))
551
+ });
552
+ }
553
+ match ctx.headers.get(http::header::HOST) {
554
+ Some(host) => {
555
+ let (bytes, text) = (host.as_bytes(), std::str::from_utf8(host.as_bytes()));
556
+ let names_port = text.is_ok_and(|text| named_port(text).is_some());
557
+ env_strings::set_host_env(ruby, env, &host_key(bytes, names_port, local_port), || {
558
+ match text {
559
+ Ok(text) => split_host_port(text, local_port),
560
+ Err(_) => (String::from_utf8_lossy(bytes).into_owned(), local_port),
561
+ }
562
+ })
563
+ }
564
+ None => {
565
+ let ip = ctx.peer.local.ip();
566
+ let key = format!("\0{ip}:{local_port}");
567
+ env_strings::set_host_env(ruby, env, key.as_bytes(), || (ip.to_string(), local_port))
264
568
  }
265
569
  }
266
-
267
- Ok(env)
268
570
  }
269
571
 
270
572
  /// Bodyless requests carry no channel at all; a present channel that is
271
573
  /// disconnected and empty (EOF already reached) also has nothing left.
272
574
  fn body_possible(ctx: &RequestCtx) -> bool {
273
- ctx.leftover.is_some()
274
- || ctx
275
- .body_rx
276
- .as_ref()
277
- .is_some_and(|rx| !(rx.is_empty() && rx.is_disconnected()))
575
+ let leftover = ctx.leftover.take();
576
+ let left = leftover.is_some();
577
+ ctx.leftover.set(leftover);
578
+ left || ctx
579
+ .body_rx
580
+ .as_ref()
581
+ .is_some_and(|rx| !(rx.is_empty() && rx.is_disconnected()))
582
+ }
583
+
584
+ /// The body channel disconnected: a clean EOF, unless the forwarder
585
+ /// abandoned the body (too large, or the client stalled).
586
+ fn body_ended(ruby: &Ruby, ctx: &RequestCtx) -> Result<(), Error> {
587
+ use crate::response::BodyAbandon;
588
+ let why = match ctx.responder.body_abandoned() {
589
+ None => return Ok(()),
590
+ Some(BodyAbandon::Oversize) => "Kino: request body exceeded max_body_size",
591
+ Some(BodyAbandon::TimedOut) => "Kino: request body read timed out",
592
+ Some(BodyAbandon::Interrupted) => INTERRUPTED,
593
+ };
594
+ Err(runtime_error(ruby, why))
595
+ }
596
+
597
+ /// `chunk`, up to `max_len` bytes (the rest waits in leftover), topped up with what arrived.
598
+ fn body_chunk(ruby: &Ruby, ctx: &RequestCtx, mut chunk: Bytes, max_len: usize) -> RString {
599
+ let max_len = max_len.max(1);
600
+ if chunk.len() > max_len {
601
+ ctx.leftover.set(Some(chunk.split_off(max_len)));
602
+ return ruby.str_from_slice(&chunk);
603
+ }
604
+
605
+ // Greedy drain: what the forwarder already queued rides out in this crossing, up to max_len,
606
+ // so a body of small DATA frames (HTTP/2's 16 KB default) costs one GVL round-trip and one
607
+ // Ruby string, not one per frame. What has not come yet, EOF included, is the next read's.
608
+ let mut assembled: Option<RString> = None;
609
+ if let Some(body_rx) = ctx.body_rx.clone() {
610
+ let mut total = chunk.len();
611
+ while total < max_len {
612
+ let Ok(mut more) = body_rx.try_recv() else {
613
+ break;
614
+ };
615
+ if more.len() > max_len - total {
616
+ ctx.leftover.set(Some(more.split_off(max_len - total)));
617
+ }
618
+ total += more.len();
619
+ let out = *assembled.get_or_insert_with(|| {
620
+ let out = ruby.str_buf_new(max_len);
621
+ out.cat(&chunk[..]);
622
+ out
623
+ });
624
+ out.cat(&more[..]);
625
+ }
626
+ }
627
+ assembled.unwrap_or_else(|| ruby.str_from_slice(&chunk))
278
628
  }
279
629
 
280
630
  /// Complete response in one shot: status, the Rack headers Hash (iterated
281
631
  /// here, no intermediate array on the Ruby side), full body. Free function
282
632
  /// shared by the `send_simple` binding and the fused respond_and_take path
283
- /// (queue.rs).
633
+ /// (queue/worker.rs).
634
+ /// An inline request's answer is written on its connection here and now.
284
635
  pub fn respond_simple(
285
636
  ruby: &Ruby,
286
637
  request: &Request,
@@ -288,31 +639,144 @@ pub fn respond_simple(
288
639
  headers: RHash,
289
640
  body: RString,
290
641
  ) -> Result<bool, Error> {
642
+ request.decline_upgrade();
291
643
  let ctx = request.0.borrow();
292
- let builder = timed(&ctx, build_head(status, headers)?);
293
- let bytes = body_bytes(&ctx, body);
644
+ if let Some(io) = &ctx.inline {
645
+ let head = head_parts(ruby, status, headers)?;
646
+ // No copy: the GVL is held until the write returns, which copies what the socket leaves.
647
+ // SAFETY: `body` is an RString on this frame's stack (the GC neither frees nor moves it),
648
+ // and no Ruby runs nor is the GVL released before the slice's last use, in respond.
649
+ let body = unsafe { body.as_slice() };
650
+ let sent = io.respond(&ctx.responder, head.status, &head.headers, body);
651
+ ctx.answered();
652
+ return Ok(sent);
653
+ }
654
+ let mut builder = timed(&ctx, build_head(status, headers)?);
655
+ let bytes = if frame_by_length(&mut builder, status, &ctx.method, body.len()) {
656
+ body_bytes(&ctx.pin_slab, body)
657
+ } else {
658
+ Bytes::new()
659
+ };
294
660
  let response = builder
295
661
  .body(full_body(bytes))
296
662
  .map_err(|e| invalid_response(ruby, e))?;
297
- Ok(ctx.responder.send_response(response))
663
+ let sent = ctx.responder.send_response(response);
664
+ ctx.answered();
665
+ Ok(sent)
666
+ }
667
+
668
+ /// A buffered answer is framed by its body, as the inline writer frames it: hyper trusts a
669
+ /// Content-Length it is given, so the app's is dropped (a wrong one would misframe what follows),
670
+ /// as is its Transfer-Encoding (beside a length, hyper ends the connection unanswered). A HEAD
671
+ /// sends no body (over h2 it would go as DATA) and keeps the app's first Content-Length, else its
672
+ /// body's (`len`) unless 304; a 304 to another method, a 1xx and a 204 send none either. True
673
+ /// when the body goes out.
674
+ pub(crate) fn frame_by_length(
675
+ builder: &mut hyper::http::response::Builder,
676
+ status: u16,
677
+ method: &http::Method,
678
+ len: usize,
679
+ ) -> bool {
680
+ let bodiless = Bodiless::of(status, *method == http::Method::HEAD);
681
+ if let Some(headers) = builder.headers_mut() {
682
+ headers.remove(http::header::TRANSFER_ENCODING);
683
+ match bodiless {
684
+ None => drop(headers.remove(http::header::CONTENT_LENGTH)),
685
+ Some(bodiless) => bodiless.settle(headers, len),
686
+ }
687
+ }
688
+ bodiless.is_none()
298
689
  }
299
690
 
300
691
  /// Body bytes for hyper: large bodies are pinned in place (zero-copy),
301
692
  /// everything else is copied out of the Ruby string, which may be
302
693
  /// mutated or collected the moment we return.
303
- fn body_bytes(ctx: &RequestCtx, body: RString) -> Bytes {
304
- if let Some(bytes) = crate::pin::pinned_bytes(&ctx.pin_slab, body) {
694
+ fn body_bytes(pin_slab: &Arc<PinSlab>, body: RString) -> Bytes {
695
+ if let Some(bytes) = crate::pin::pinned_bytes(pin_slab, body) {
305
696
  return bytes;
306
697
  }
307
698
  Bytes::copy_from_slice(unsafe { body.as_slice() })
308
699
  }
309
700
 
310
701
  impl Request {
702
+ /// Accept a handshake (ws::accept), its 101 carrying `headers` for switch_protocols: the
703
+ /// socket id, false for Kino's 503 refusal, nil when it is no handshake or there are no lanes.
704
+ pub fn upgrade_websocket(
705
+ ruby: &Ruby,
706
+ rb_self: &Request,
707
+ headers: RHash,
708
+ on_shutdown: bool,
709
+ ) -> Result<magnus::Value, Error> {
710
+ let head = head_parts(ruby, 101, headers)?;
711
+ let extra: Vec<_> = head
712
+ .headers
713
+ .iter()
714
+ .map(|(name, value)| (name.clone(), value.clone()))
715
+ .collect();
716
+ let mut ctx = rb_self.exclusive().ok_or_else(|| busy_error(ruby))?;
717
+ Ok(match crate::ws::accept(&mut ctx, &extra, on_shutdown) {
718
+ crate::ws::Accept::Opened(id) => ruby.into_value(id),
719
+ crate::ws::Accept::Refused => ruby.qfalse().as_value(),
720
+ crate::ws::Accept::Declined => ruby.qnil().as_value(),
721
+ })
722
+ }
723
+
724
+ /// The accepted handshake's 101, once on_open ran; false when the request was answered
725
+ /// otherwise first, which closes the connection.
726
+ pub fn switch_protocols(ruby: &Ruby, rb_self: &Request) -> Result<bool, Error> {
727
+ let ctx = rb_self.exclusive().ok_or_else(|| busy_error(ruby))?;
728
+ Ok(ctx.responder.switch())
729
+ }
730
+
731
+ /// rack.hijack: the fd of the app's end of the bridge.
732
+ pub fn hijack(ruby: &Ruby, rb_self: &Request) -> Result<i32, Error> {
733
+ rb_self.hijacked_fd(ruby, None)
734
+ }
735
+
736
+ /// A 101 with a callable (a partial hijack, or a Rack 3 streaming body): sends it with
737
+ /// `headers` and takes the connection over; the fd of the app's end.
738
+ pub fn hijack_switched(ruby: &Ruby, rb_self: &Request, headers: RHash) -> Result<i32, Error> {
739
+ let head = build_head(101, headers)?
740
+ .body(full_body(Bytes::new()))
741
+ .map_err(|e| invalid_response(ruby, e))?;
742
+ rb_self.hijacked_fd(ruby, Some(head))
743
+ }
744
+
745
+ /// The fd of the app's end of a bridge that took the connection over (hijack::take).
746
+ fn hijacked_fd(
747
+ &self,
748
+ ruby: &Ruby,
749
+ head: Option<crate::response::HyperResponse>,
750
+ ) -> Result<i32, Error> {
751
+ use std::os::fd::IntoRawFd;
752
+
753
+ let taken = match self.exclusive() {
754
+ Some(mut ctx) => {
755
+ let taken = crate::hijack::take(&mut ctx, head);
756
+ ctx.close_waits();
757
+ taken
758
+ }
759
+ None => Err(crate::hijack::Refused::Busy),
760
+ };
761
+ let io = taken.map_err(|refused| {
762
+ Error::new(
763
+ ruby.exception_io_error(),
764
+ format!("Kino: rack.hijack failed: {refused}"),
765
+ )
766
+ })?;
767
+ Ok(io.into_raw_fd())
768
+ }
769
+
770
+ pub fn hijacked(_ruby: &Ruby, rb_self: &Request) -> bool {
771
+ rb_self.0.borrow().hijacked
772
+ }
773
+
311
774
  /// The worker's measurements around the app call, for the access log's
312
775
  /// breakdown: the GC pause in nanoseconds and the objects allocated.
313
776
  /// Called only when the access log is on.
314
777
  pub fn set_timing(_ruby: &Ruby, rb_self: &Request, gc_nanos: u64, allocs: u64) {
315
- rb_self.0.borrow_mut().gc = Some((std::time::Duration::from_nanos(gc_nanos), allocs));
778
+ let gc = std::time::Duration::from_nanos(gc_nanos);
779
+ rb_self.0.borrow().gc.set(Some((gc, allocs)));
316
780
  }
317
781
 
318
782
  /// Next chunk of the request body, at most `max_len` bytes; nil at EOF.
@@ -322,108 +786,101 @@ impl Request {
322
786
  rb_self: &Request,
323
787
  max_len: usize,
324
788
  ) -> Result<Option<RString>, Error> {
325
- let mut ctx = rb_self.0.borrow_mut();
326
- let max_len = max_len.max(1);
327
-
328
- let mut chunk = match ctx.leftover.take() {
789
+ // Shared across the wait: other threads may abort or answer the request meanwhile.
790
+ let ctx = rb_self.0.borrow();
791
+ let chunk = match ctx.leftover.take() {
329
792
  Some(bytes) => bytes,
330
793
  None => {
331
794
  let Some(body_rx) = ctx.body_rx.clone() else {
332
795
  return Ok(None); // bodyless request: EOF from the start
333
796
  };
334
- let outcome = block_on(&ctx.slot, || {
335
- match body_rx.recv_timeout(crate::queue::TICK) {
336
- Ok(bytes) => Some(Some(bytes)),
337
- Err(flume::RecvTimeoutError::Timeout) => None,
338
- Err(flume::RecvTimeoutError::Disconnected) => Some(None),
339
- }
340
- })?;
341
- match outcome {
797
+ match block_on(&ctx.slot, || crate::queue::recv_tick(&body_rx))? {
342
798
  Some(Some(bytes)) => bytes,
343
- Some(None) => {
344
- // Disconnected: a clean EOF, unless the forwarder
345
- // abandoned the body (too large, or the client stalled).
346
- use crate::response::BodyAbandon;
347
- return match ctx.responder.body_abandoned() {
348
- Some(BodyAbandon::Oversize) => Err(body_too_large_error(ruby)),
349
- Some(BodyAbandon::TimedOut) => Err(body_timeout_error(ruby)),
350
- None => Ok(None), // EOF
351
- };
352
- }
799
+ Some(None) => return body_ended(ruby, &ctx).map(|()| None),
353
800
  None => return Err(interrupted_error(ruby)),
354
801
  }
355
802
  }
356
803
  };
804
+ Ok(Some(body_chunk(ruby, &ctx, chunk, max_len)))
805
+ }
357
806
 
358
- if chunk.len() > max_len {
359
- ctx.leftover = Some(chunk.split_off(max_len));
360
- return Ok(Some(ruby.str_from_slice(&chunk)));
361
- }
362
-
363
- // Greedy drain: whatever the forwarder has already queued rides
364
- // out in this same crossing, up to max_len. A body arriving as
365
- // small DATA frames (HTTP/2 caps them at 16 KB unless negotiated
366
- // higher) then costs one GVL round-trip and one Ruby string, not
367
- // one per frame. Non-blocking: a chunk that has not arrived yet
368
- // is next call's business, as are EOF and abandonment (try_recv's
369
- // Disconnected included; the recv above maps them to errors).
370
- let mut assembled: Option<RString> = None;
371
- if let Some(body_rx) = ctx.body_rx.clone() {
372
- let mut total = chunk.len();
373
- while total < max_len {
374
- let Ok(mut more) = body_rx.try_recv() else {
375
- break;
376
- };
377
- if more.len() > max_len - total {
378
- ctx.leftover = Some(more.split_off(max_len - total));
807
+ /// read_body for a fiber scheduler: while no chunk has come, the descriptor to wait on.
808
+ pub fn read_body_nonblock(
809
+ ruby: &Ruby,
810
+ rb_self: &Request,
811
+ max_len: usize,
812
+ ) -> Result<Value, Error> {
813
+ let ctx = rb_self.0.borrow();
814
+ let chunk = match ctx.leftover.take() {
815
+ Some(bytes) => bytes,
816
+ None => match ctx
817
+ .read_nonblock()
818
+ .map_err(|e| wait_error(ruby, &ctx.responder, e))?
819
+ {
820
+ Step::Done(Some(bytes)) => bytes,
821
+ Step::Done(None) => {
822
+ body_ended(ruby, &ctx)?;
823
+ return Ok(ruby.qnil().as_value());
379
824
  }
380
- total += more.len();
381
- let out = *assembled.get_or_insert_with(|| {
382
- let out = ruby.str_buf_new(max_len);
383
- out.cat(&chunk[..]);
384
- out
385
- });
386
- out.cat(&more[..]);
387
- }
388
- }
389
- Ok(Some(match assembled {
390
- Some(out) => out,
391
- None => ruby.str_from_slice(&chunk),
392
- }))
825
+ Step::Wait(fd) => return Ok(ruby.into_value(fd)),
826
+ },
827
+ };
828
+ Ok(body_chunk(ruby, &ctx, chunk, max_len).as_value())
393
829
  }
394
830
 
395
831
  /// Start a streaming response: head goes out now, chunks follow via
396
- /// write_chunk, terminated by finish.
832
+ /// write_chunk, terminated by finish. Once Kino answered, the first write ends the body.
833
+ /// An inline request's head is written on its connection (InlineIo::start_stream).
397
834
  pub fn send_headers(
398
835
  ruby: &Ruby,
399
836
  rb_self: &Request,
400
837
  status: u16,
401
838
  headers: RHash,
402
839
  ) -> Result<bool, Error> {
840
+ rb_self.decline_upgrade();
403
841
  let ctx = rb_self.0.borrow();
842
+ if let Some(io) = &ctx.inline {
843
+ let head = head_parts(ruby, status, headers)?;
844
+ return Ok(io.start_stream(&ctx.responder, head.status, &head.headers));
845
+ }
404
846
  let builder = timed(&ctx, build_head(status, headers)?);
405
- ctx.responder
406
- .send_stream_head(builder)
407
- .map_err(|e| invalid_response(ruby, e))
847
+ let sent = match Bodiless::of(status, ctx.method == http::Method::HEAD) {
848
+ Some(bodiless) => ctx.responder.send_bodiless_head(builder, bodiless),
849
+ None => ctx.responder.send_stream_head(builder),
850
+ };
851
+ sent.map_err(|e| invalid_response(ruby, e))
408
852
  }
409
853
 
410
854
  /// One body chunk. Blocks (GVL released) when the client is slower than
411
- /// the app: this is the outbound backpressure.
412
- pub fn write_chunk(ruby: &Ruby, rb_self: &Request, chunk: RString) -> Result<(), Error> {
855
+ /// client is gone or Kino gave the stream up.
856
+ /// False once the chunk is on its way. An inline write waits a TICK at most for its socket,
857
+ /// then returns true to be made again, so a pending Thread#raise reaches the thread in Ruby.
858
+ pub fn write_chunk(ruby: &Ruby, rb_self: &Request, chunk: RString) -> Result<bool, Error> {
413
859
  let ctx = rb_self.0.borrow();
860
+ if let Some(io) = &ctx.inline {
861
+ let Step::Wait(fd) = write_inline(ruby, &ctx, io, chunk)? else {
862
+ return Ok(false);
863
+ };
864
+ let unread = std::sync::atomic::AtomicBool::new(false);
865
+ let wait = || crate::inline::await_writable(fd, crate::queue::TICK);
866
+ let waited = gvl::Parker::release(&mut gvl::Released, &unread, wait);
867
+ io.waited();
868
+ waited?;
869
+ return Ok(true);
870
+ }
414
871
  let Some(sender) = ctx.responder.body_sender() else {
415
- return Err(Error::new(
416
- ruby.exception_runtime_error(),
417
- "Kino: response stream not started or already finished",
418
- ));
872
+ return Err(stream_closed_error(ruby, &ctx.responder));
419
873
  };
420
- let bytes = body_bytes(&ctx, chunk);
874
+ let bytes = body_bytes(&ctx.pin_slab, chunk);
421
875
  let mut pending = Some(Ok(BodyFrame::data(bytes)));
422
876
 
423
877
  let outcome = block_on(&ctx.slot, || {
424
878
  let frame = pending.take().expect("frame consumed twice");
425
879
  match sender.send_timeout(frame, crate::queue::TICK) {
426
880
  Ok(()) => Some(true),
881
+ Err(flume::SendTimeoutError::Timeout(_)) if ctx.responder.stream_cut() => {
882
+ Some(false)
883
+ }
427
884
  Err(flume::SendTimeoutError::Timeout(frame)) => {
428
885
  pending = Some(frame); // client slow; keep waiting
429
886
  None
@@ -432,27 +889,115 @@ impl Request {
432
889
  }
433
890
  })?;
434
891
  match outcome {
435
- // Receiver dropped = client went away; the app keeps writing
436
- // into the void harmlessly (Rack has no error contract here).
437
- Some(_) => Ok(()),
892
+ Some(true) => Ok(false),
893
+ // Gone, or given up (and counted then).
894
+ Some(false) => {
895
+ ctx.responder.cut_stream(crate::response::Cut::ClientGone);
896
+ Err(client_gone_error(ruby))
897
+ }
438
898
  None => Err(interrupted_error(ruby)),
439
899
  }
440
900
  }
441
901
 
902
+ /// write_chunk for a fiber scheduler: true once on its way, else the descriptor to wait on.
903
+ /// An inline request's is [:writable, fd].
904
+ pub fn write_chunk_nonblock(
905
+ ruby: &Ruby,
906
+ rb_self: &Request,
907
+ chunk: RString,
908
+ ) -> Result<Value, Error> {
909
+ let ctx = rb_self.0.borrow();
910
+ if let Some(io) = &ctx.inline {
911
+ return Ok(match write_inline(ruby, &ctx, io, chunk)? {
912
+ Step::Done(()) => ruby.qtrue().as_value(),
913
+ Step::Wait(fd) => {
914
+ let writable = crate::symbols::get().writable.value();
915
+ let wait = ruby.ary_new_from_values(&[writable, ruby.into_value(fd)]);
916
+ wait.as_value()
917
+ }
918
+ });
919
+ }
920
+ let step = ctx.write_nonblock(|pin_slab| body_bytes(pin_slab, chunk));
921
+ Ok(
922
+ match step.map_err(|e| wait_error(ruby, &ctx.responder, e))? {
923
+ Step::Done(()) => ruby.qtrue().as_value(),
924
+ Step::Wait(fd) => ruby.into_value(fd),
925
+ },
926
+ )
927
+ }
928
+
929
+ /// A wait on a descriptor read_body_nonblock or write_chunk_nonblock handed out is over.
930
+ pub fn waited(_ruby: &Ruby, rb_self: &Request) {
931
+ rb_self.0.borrow().waited();
932
+ }
933
+
934
+ /// The [:writable, fd] wait write_chunk_nonblock handed out is over: the descriptor may
935
+ /// close.
936
+ pub fn waited_writable(_ruby: &Ruby, rb_self: &Request) {
937
+ if let Some(io) = &rb_self.0.borrow().inline {
938
+ io.waited();
939
+ }
940
+ }
941
+
942
+ /// The request's job is over: its waits' descriptors close (RequestCtx::close_waits).
943
+ pub fn close_waits(_ruby: &Ruby, rb_self: &Request) {
944
+ rb_self.0.borrow().close_waits();
945
+ }
946
+
442
947
  /// Clean end of a streaming response.
443
948
  pub fn finish(_ruby: &Ruby, rb_self: &Request) -> Result<(), Error> {
444
- rb_self.0.borrow().responder.finish_stream();
949
+ let ctx = rb_self.0.borrow();
950
+ ctx.responder.finish_stream();
951
+ ctx.answered();
445
952
  Ok(())
446
953
  }
447
954
 
448
955
  /// Give up on this request: canned 500 if the head wasn't sent, abort
449
- /// the connection if mid-stream. Used by the worker's rescue path.
956
+ /// the connection if mid-stream. Used by the worker's rescue path. It
957
+ /// borrows no more than threads waiting on the request do, so a waiting write fails.
450
958
  pub fn abort(_ruby: &Ruby, rb_self: &Request) -> Result<(), Error> {
451
- rb_self.0.borrow().responder.respond_500_if_unsent();
959
+ rb_self.decline_upgrade();
960
+ if let Ok(ctx) = rb_self.0.try_borrow() {
961
+ ctx.responder.give_up(Cut::Crash);
962
+ ctx.answered();
963
+ }
452
964
  Ok(())
453
965
  }
454
966
  }
455
967
 
968
+ /// A head's status and headers alone: what an inline answer is encoded from (inline/encode.rs),
969
+ /// and what a handshake's 101 adds to Kino's own.
970
+ #[inline]
971
+ fn head_parts(ruby: &Ruby, status: u16, headers: RHash) -> Result<http::response::Parts, Error> {
972
+ let response = build_head(status, headers)?.body(());
973
+ Ok(response
974
+ .map_err(|e| invalid_response(ruby, e))?
975
+ .into_parts()
976
+ .0)
977
+ }
978
+
979
+ /// One chunk of an inline request's stream, written now with the GVL held, or the socket to wait
980
+ /// on first (InlineIo::write_chunk); ClientGone once nothing reaches the client.
981
+ fn write_inline(
982
+ ruby: &Ruby,
983
+ ctx: &RequestCtx,
984
+ io: &crate::inline::InlineIo,
985
+ chunk: RString,
986
+ ) -> Result<Step<()>, Error> {
987
+ use crate::inline::Wrote;
988
+
989
+ // SAFETY: `chunk` is an RString on this frame's stack (the GC neither frees nor moves it),
990
+ // and no Ruby runs nor is the GVL released before write_chunk, which copies what the socket
991
+ // does not take.
992
+ let data = unsafe { chunk.as_slice() };
993
+ match io.write_chunk(&ctx.responder, data) {
994
+ Wrote::Done => Ok(Step::Done(())),
995
+ Wrote::Wait(fd) => Ok(Step::Wait(fd)),
996
+ Wrote::Gone => Err(wait_error(ruby, &ctx.responder, WaitError::Gone)),
997
+ Wrote::Closed => Err(stream_closed_error(ruby, &ctx.responder)),
998
+ }
999
+ }
1000
+
456
1001
  /// Build the response head straight from the Rack headers Hash.
457
1002
  /// Values are Strings or Arrays of Strings (Rack 3); each Array element
458
1003
  /// becomes a repeated header. Name/value bytes are borrowed in place from
@@ -493,39 +1038,57 @@ fn coerce_str(value: Value) -> Result<RString, Error> {
493
1038
  }
494
1039
 
495
1040
  pub(crate) fn split_host_port(host: &str, default_port: u16) -> (String, u16) {
1041
+ match named_port(host) {
1042
+ Some((name, port)) => (name.to_string(), port),
1043
+ None => (host.to_string(), default_port),
1044
+ }
1045
+ }
1046
+
1047
+ /// `host`'s name and port, when it ends in a colon and a port that parses.
1048
+ pub(crate) fn named_port(host: &str) -> Option<(&str, u16)> {
496
1049
  match host.rsplit_once(':') {
497
- Some((name, port)) if !name.is_empty() => match port.parse() {
498
- Ok(p) => (name.to_string(), p),
499
- Err(_) => (host.to_string(), default_port),
500
- },
501
- _ => (host.to_string(), default_port),
1050
+ Some((name, port)) if !name.is_empty() => port.parse().ok().map(|port| (name, port)),
1051
+ _ => None,
1052
+ }
1053
+ }
1054
+
1055
+ /// The host cache's key for `host` (a Host header or an authority) on a connection to
1056
+ /// `local_port`: the bytes alone when they name a port, else the bytes, a NUL and that port, as
1057
+ /// it becomes SERVER_PORT and a process may serve a host on several ports. Up to 256 bytes stay
1058
+ /// on the stack.
1059
+ pub(crate) fn host_key(
1060
+ host: &[u8],
1061
+ names_port: bool,
1062
+ local_port: u16,
1063
+ ) -> smallvec::SmallVec<[u8; 256]> {
1064
+ let mut key = smallvec::SmallVec::from_slice(host);
1065
+ if !names_port {
1066
+ key.push(0);
1067
+ key.extend_from_slice(&local_port.to_be_bytes());
502
1068
  }
1069
+ key
503
1070
  }
504
1071
 
505
1072
  /// A minimal ctx for pure-Rust tests (no Ruby involved). Dropping it
506
1073
  /// fires the Drop-500 backstop into a dropped receiver, which is a no-op.
507
1074
  #[cfg(test)]
508
1075
  pub fn test_ctx() -> crate::registry::BoxedCtx {
509
- let (head_tx, _head_rx) = tokio::sync::oneshot::channel();
510
- Box::new(RequestCtx {
511
- method: http::Method::GET,
512
- uri: "/".parse().expect("static uri"),
513
- version: http::Version::HTTP_11,
514
- headers: http::HeaderMap::new(),
515
- remote_addr: "127.0.0.1:40000".parse().expect("static addr"),
516
- local_addr: "127.0.0.1:9292".parse().expect("static addr"),
517
- https: false,
518
- body_rx: None,
519
- leftover: None,
520
- slot: None,
521
- pin_slab: Arc::new(crate::pin::PinSlab::for_responses(false)),
522
- responder: Arc::new(Responder::new(head_tx)),
523
- enqueued_at: std::time::Instant::now(),
524
- timed: false,
525
- wait: std::time::Duration::ZERO,
526
- admitted_at: std::time::Instant::now(),
527
- gc: None,
528
- })
1076
+ test_ctx_with_client().0
1077
+ }
1078
+
1079
+ /// A test_ctx whose client still waits for its answer, as long as the
1080
+ /// caller keeps the returned receiver of its response head.
1081
+ #[cfg(test)]
1082
+ pub fn test_ctx_with_client() -> (
1083
+ crate::registry::BoxedCtx,
1084
+ tokio::sync::oneshot::Receiver<crate::response::HyperResponse>,
1085
+ ) {
1086
+ let (head_tx, head_rx) = tokio::sync::oneshot::channel();
1087
+ let (parts, ()) = http::Request::new(()).into_parts();
1088
+ let server = crate::testing::TestServer::shared_queue().build();
1089
+ let responder = Arc::new(Responder::new(head_tx));
1090
+ let ctx = RequestCtx::new(parts, crate::testing::PEER, &server, responder, None, None);
1091
+ (ctx, head_rx)
529
1092
  }
530
1093
 
531
1094
  #[cfg(test)]
@@ -533,57 +1096,93 @@ mod tests {
533
1096
  use super::*;
534
1097
 
535
1098
  #[test]
536
- fn host_port_split() {
1099
+ fn a_host_splits_into_its_name_and_port_else_stays_whole_with_the_default_port() {
1100
+ let rows = [
1101
+ ("example.com:8080", "example.com", 8080),
1102
+ ("example.com", "example.com", 80),
1103
+ // Bracketed IPv6 (the RFC-correct Host form) keeps the brackets.
1104
+ ("[::1]:8080", "[::1]", 8080),
1105
+ // An out-of-range or missing port, or an empty name: whole.
1106
+ ("example.com:99999", "example.com:99999", 80),
1107
+ ("example.com:", "example.com:", 80),
1108
+ (":8080", ":8080", 80),
1109
+ ];
1110
+ for (host, name, port) in rows {
1111
+ let split = split_host_port(host, 80);
1112
+ assert_eq!(split, (name.to_string(), port), "{host}");
1113
+ }
1114
+ }
1115
+
1116
+ #[test]
1117
+ fn a_chunk_that_arrives_as_the_read_arms_is_read_not_waited_for() {
1118
+ let (body_tx, body_rx) = flume::bounded(1);
1119
+ let mut ctx = test_ctx();
1120
+ ctx.body_rx = Some(body_rx);
1121
+ let responder = ctx.responder.clone();
1122
+
1123
+ // As the forwarder sends: the chunk, then a ring, which finds the
1124
+ // bell not armed yet.
1125
+ ctx.responder.body_bell.before_arm(move || {
1126
+ body_tx.send(Bytes::from_static(b"late")).expect("open");
1127
+ responder.body_bell.ring();
1128
+ });
537
1129
  assert_eq!(
538
- split_host_port("example.com:8080", 80),
539
- ("example.com".into(), 8080)
1130
+ ctx.read_nonblock().expect("a read"),
1131
+ Step::Done(Some(Bytes::from_static(b"late")))
540
1132
  );
541
- assert_eq!(
542
- split_host_port("example.com", 80),
543
- ("example.com".into(), 80)
1133
+ }
1134
+
1135
+ #[test]
1136
+ fn a_wait_fails_as_interrupted_once_its_slot_is_halted_though_what_came_is_still_read() {
1137
+ let (body_tx, body_rx) = flume::bounded::<Bytes>(1);
1138
+ let slot = Arc::new(WorkerSlot::new(true, 1, None, false));
1139
+ let mut ctx = test_ctx();
1140
+ ctx.body_rx = Some(body_rx);
1141
+ ctx.slot = Some(slot.clone());
1142
+
1143
+ slot.halt();
1144
+ assert!(matches!(ctx.read_nonblock(), Err(WaitError::Interrupted)));
1145
+ body_tx.send(Bytes::from_static(b"sent")).expect("open");
1146
+ assert!(
1147
+ matches!(ctx.read_nonblock(), Ok(Step::Done(Some(_)))),
1148
+ "what already came is read"
544
1149
  );
545
1150
  }
546
1151
 
547
1152
  #[test]
548
- fn host_port_split_edge_cases() {
549
- // Bracketed IPv6 (the RFC-correct Host form) keeps the brackets.
550
- assert_eq!(split_host_port("[::1]:8080", 80), ("[::1]".into(), 8080));
551
- // Out-of-range or non-numeric port: whole input + default port.
1153
+ fn closing_waits_holds_their_descriptor_until_the_last_wait_is_back() {
1154
+ let (body_tx, body_rx) = flume::bounded::<Bytes>(1);
1155
+ let mut ctx = test_ctx();
1156
+ ctx.body_rx = Some(body_rx);
1157
+ let first = ctx.read_nonblock().expect("a read");
1158
+ let second = ctx.read_nonblock().expect("a read");
1159
+ let Step::Wait(fd) = first else {
1160
+ panic!("expected to wait, got {first:?}");
1161
+ };
552
1162
  assert_eq!(
553
- split_host_port("example.com:99999", 80),
554
- ("example.com:99999".into(), 80)
1163
+ second,
1164
+ Step::Wait(fd),
1165
+ "waits share the request's descriptor"
555
1166
  );
1167
+
1168
+ ctx.close_waits();
1169
+ ctx.waited();
556
1170
  assert_eq!(
557
- split_host_port("example.com:", 80),
558
- ("example.com:".into(), 80)
1171
+ ctx.responder.body_bell.sockets().map(|s| s.fd()),
1172
+ Some(fd),
1173
+ "a wait is still out"
559
1174
  );
560
- // Empty name (":8080") falls back whole.
561
- assert_eq!(split_host_port(":8080", 80), (":8080".into(), 80));
562
- }
1175
+ ctx.waited();
1176
+ assert!(ctx.responder.body_bell.sockets().is_none());
563
1177
 
564
- #[test]
565
- fn authority_host_port_derivation() {
566
- // The same derivation build_env applies to a URI authority (the
567
- // h2 :authority pseudo-header): http::uri does the split, the
568
- // socket's local port fills a missing port.
569
- let with_port: http::Uri = "https://example.com:8443/x".parse().expect("uri");
570
- let authority = with_port.authority().expect("authority");
571
- assert_eq!(authority.host(), "example.com");
572
- assert_eq!(authority.port_u16(), Some(8443));
573
- assert_eq!(authority.as_str(), "example.com:8443");
574
-
575
- let bare: http::Uri = "https://example.com/x".parse().expect("uri");
576
- let authority = bare.authority().expect("authority");
577
- assert_eq!(authority.host(), "example.com");
578
- assert_eq!(authority.port_u16().unwrap_or(9292), 9292);
579
-
580
- // Bracketed IPv6: host() keeps the brackets, matching the h1
581
- // split_host_port convention for SERVER_NAME.
582
- let v6: http::Uri = "https://[::1]:8443/x".parse().expect("uri");
583
- let authority = v6.authority().expect("authority");
584
- assert_eq!(authority.host(), "[::1]");
585
- assert_eq!(authority.port_u16(), Some(8443));
586
- assert_eq!(authority.as_str(), "[::1]:8443");
1178
+ assert!(
1179
+ matches!(ctx.read_nonblock(), Ok(Step::Wait(_))),
1180
+ "a later wait opens it again"
1181
+ );
1182
+ ctx.waited();
1183
+ ctx.close_waits();
1184
+ assert!(ctx.responder.body_bell.sockets().is_none());
1185
+ drop(body_tx);
587
1186
  }
588
1187
 
589
1188
  #[test]
@@ -593,8 +1192,8 @@ mod tests {
593
1192
  assert!(!body_possible(&ctx));
594
1193
 
595
1194
  // A leftover chunk means there is still body to read.
596
- let mut ctx = test_ctx();
597
- ctx.leftover = Some(bytes::Bytes::from_static(b"tail"));
1195
+ let ctx = test_ctx();
1196
+ ctx.leftover.set(Some(bytes::Bytes::from_static(b"tail")));
598
1197
  assert!(body_possible(&ctx));
599
1198
 
600
1199
  // A live sender means bytes may still arrive.