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
@@ -0,0 +1,276 @@
1
+ //! Handing a request to a worker: its lane, in hot-lane order, or the shared queue.
2
+
3
+ use std::ops::ControlFlow;
4
+ use std::sync::atomic::Ordering;
5
+ use std::sync::Arc;
6
+ use std::time::Duration;
7
+
8
+ use crate::registry::{BoxedCtx, LaneItem, ServerInner};
9
+ use crate::request::RequestCtx;
10
+ use crate::response::plain_response;
11
+ use crate::slot::{WorkerSlot, LANE_DEPTH};
12
+
13
+ #[cfg(test)]
14
+ mod tests;
15
+
16
+ /// One dispatch attempt: Break once it is over, sent (Ok) or handed back with every lane closed
17
+ /// (Err); Continue hands the request back, every open lane full, for another attempt.
18
+ type Attempt = ControlFlow<Result<(), BoxedCtx>, BoxedCtx>;
19
+
20
+ /// A send down a list of lanes: Break once a lane took the request, Continue with it back.
21
+ type Unsent = ControlFlow<(), BoxedCtx>;
22
+
23
+ fn try_dispatch(server: &ServerInner, ctx: BoxedCtx) -> Attempt {
24
+ let slots = server.slots.read();
25
+ if slots.is_empty() {
26
+ return Attempt::Continue(ctx);
27
+ }
28
+ let start = server.lane_cursor.fetch_add(1, Ordering::Relaxed);
29
+ // A request can wait in a lane only while another is in flight (bar a rare given-up one).
30
+ let others = server.config.worker_loop && server.counters.in_flight.load(Ordering::Relaxed) > 1;
31
+ let pass = Pass { start, others };
32
+ let mut any_open = false;
33
+ match send(&slots, pass, &mut any_open, ctx) {
34
+ Unsent::Break(()) => Attempt::Break(Ok(())),
35
+ Unsent::Continue(ctx) if any_open => Attempt::Continue(ctx), // overload: every open lane is full
36
+ Unsent::Continue(ctx) => Attempt::Break(Err(ctx)), // draining: all lanes closed
37
+ }
38
+ }
39
+
40
+ /// An awake lane with room (a hot worker never pays a futex wake), unless another worker idles
41
+ /// and this one is passed over for it: a worker_loop worker that holds a request, a classic
42
+ /// one deep in its item (see send_hot_first). Then the idle worker with the fewest open, of
43
+ /// those the one that parked last (warmest caches); then any lane with room. A handshake goes
44
+ /// first to the workers with the fewest sockets, as a socket stays with the worker that
45
+ /// accepts it.
46
+ fn send(slots: &[Arc<WorkerSlot>], pass: Pass, any_open: &mut bool, mut ctx: BoxedCtx) -> Unsent {
47
+ if ctx.offers_websocket() {
48
+ if let Some(fewest) = fewest_sockets(slots) {
49
+ let least_loaded =
50
+ |slot: &WorkerSlot| slot.sockets.open() == fewest && takes_sockets(slot);
51
+ ctx = send_hot_first(slots, pass, any_open, ctx, least_loaded)?;
52
+ }
53
+ }
54
+ send_hot_first(slots, pass, any_open, ctx, |_| true)
55
+ }
56
+
57
+ /// In the pool, and its sockets not being closed.
58
+ fn takes_sockets(slot: &WorkerSlot) -> bool {
59
+ !slot.life.seems_retired() && slot.sockets.accepting()
60
+ }
61
+
62
+ fn fewest_sockets(slots: &[Arc<WorkerSlot>]) -> Option<usize> {
63
+ slots
64
+ .iter()
65
+ .filter(|slot| takes_sockets(slot))
66
+ .map(|slot| slot.sockets.open())
67
+ .min()
68
+ }
69
+
70
+ /// `others`: requests besides this one are in flight, so one may wait in a worker_loop lane.
71
+ #[derive(Clone, Copy)]
72
+ struct Pass {
73
+ start: usize,
74
+ others: bool,
75
+ }
76
+
77
+ /// In hot-lane order among the slots `eligible` picks; back when no lane has room.
78
+ fn send_hot_first(
79
+ slots: &[Arc<WorkerSlot>],
80
+ pass: Pass,
81
+ any_open: &mut bool,
82
+ mut ctx: BoxedCtx,
83
+ eligible: impl Fn(&WorkerSlot) -> bool,
84
+ ) -> Unsent {
85
+ let Pass { start, others } = pass;
86
+ let n = slots.len();
87
+ // A lane with no room for a request (full, retired, its worker at capacity) is still open;
88
+ // `depth` caps how full a worker_loop lane may already be.
89
+ let mut try_lane = |slot: &WorkerSlot, ctx: BoxedCtx, depth: usize| -> Unsent {
90
+ let Err(refused) = slot.send_lane_upto(LaneItem::Request(ctx), depth) else {
91
+ return Unsent::Break(());
92
+ };
93
+ *any_open |= matches!(refused, flume::TrySendError::Full(_));
94
+ match refused.into_inner() {
95
+ LaneItem::Request(ctx) => Unsent::Continue(ctx),
96
+ LaneItem::Bell => unreachable!("only requests are dispatched"),
97
+ }
98
+ };
99
+
100
+ // Only an empty lane: a burst into an idle server must spread, not queue behind one hot
101
+ // worker. A crashed worker's slot stays parked and retired until it is recycled.
102
+ // A worker_loop worker's inline request runs while its loop stays parked: holding one, it is
103
+ // not idle.
104
+ let find_hottest = || {
105
+ slots
106
+ .iter()
107
+ .filter(|slot| slot.park.is_parked())
108
+ .filter(|slot| !slot.load.is_holding())
109
+ .filter(|slot| !slot.life.seems_retired())
110
+ .filter(|slot| eligible(slot) && !slot.load.at_capacity())
111
+ .filter(|slot| slot.lane.open_and_empty())
112
+ .max_by_key(|slot| {
113
+ let fewer_open = std::cmp::Reverse(slot.load.in_flight());
114
+ (fewer_open, slot.park.parked_at())
115
+ })
116
+ };
117
+ let mut hottest = None;
118
+ let mut now = None;
119
+ for k in 0..n {
120
+ let slot = &slots[(start + k) % n];
121
+ if slot.park.is_parked() || !eligible(slot) {
122
+ continue;
123
+ }
124
+ // Passed over only for an idle sibling; with none, any busy worker will do.
125
+ // A worker_loop worker while it holds a request at all, a classic one once deep in its
126
+ // item; once find_hottest found no idle sibling, a worker_loop hold needs no look.
127
+ let passed_over = match slot.lane.is_worker_loop() {
128
+ true => !matches!(hottest, Some(None)) && holds_request(slot, others),
129
+ false => deep_in_work(slot, &mut now),
130
+ };
131
+ if passed_over && hottest.get_or_insert_with(find_hottest).is_some() {
132
+ continue;
133
+ }
134
+ // A hot lane fills only as far as a classic one: past that an idle worker goes first.
135
+ ctx = try_lane(slot, ctx, LANE_DEPTH)?;
136
+ }
137
+ if let Some(slot) = hottest.unwrap_or_else(find_hottest) {
138
+ ctx = try_lane(slot, ctx, usize::MAX)?;
139
+ }
140
+ // Any lane with room, round-robin; this also tells a full lane from a closed one.
141
+ for k in 0..n {
142
+ let slot = &slots[(start + k) % n];
143
+ if eligible(slot) {
144
+ ctx = try_lane(slot, ctx, usize::MAX)?;
145
+ }
146
+ }
147
+ Unsent::Continue(ctx)
148
+ }
149
+
150
+ /// A request unanswered on its thread (Load::holding), or one in its lane (only with `others`).
151
+ fn holds_request(slot: &WorkerSlot, others: bool) -> bool {
152
+ slot.load.is_holding() || others && slot.lane.holds_items()
153
+ }
154
+
155
+ /// How far into its item a busy worker stops counting as hot while a sibling idles: past it,
156
+ /// waking the sibling (tens of microseconds) beats waiting out the rest.
157
+ const DEEP_US: u64 = 100;
158
+
159
+ /// A classic worker's rule. `now` is read on first need, for a busy worker only.
160
+ fn deep_in_work(slot: &WorkerSlot, now: &mut Option<u64>) -> bool {
161
+ let Some(started) = slot.load.busy_since() else {
162
+ return false;
163
+ };
164
+ let now = *now.get_or_insert_with(crate::mono::mono_us);
165
+ now.saturating_sub(started) >= DEEP_US
166
+ }
167
+
168
+ /// A take from a lane, a park and a drop below capacity tell the first in line; a lane that
169
+ /// deepens as its worker answers below capacity tells nobody, and this bounds that wait, and
170
+ /// a missed signal.
171
+ const LANE_ROOM_RECHECK: Duration = crate::queue::TICK;
172
+
173
+ /// Without a worker_loop, how often a request looks again while every lane is full.
174
+ const LANE_RETRY: Duration = Duration::from_micros(500);
175
+
176
+ /// In a lane, waiting for room while all are full, or on the shared queue; false (a 503) when every
177
+ /// queue is closed or still full at queue_timeout.
178
+ pub(crate) async fn enqueue(server: &ServerInner, ctx: BoxedCtx) -> bool {
179
+ let timeout = Duration::from_millis(server.config.queue_timeout_ms);
180
+ if server.config.lanes {
181
+ return matches!(to_lane(server, ctx, timeout).await, Attempt::Break(Ok(())));
182
+ }
183
+ // Cloned per request, so a keep-alive connection cannot hold the queue open during drain.
184
+ let Some(tx) = server.req_tx.lock().clone() else {
185
+ return false;
186
+ };
187
+ // try_send first: room is the common case, and it skips a tokio timer.
188
+ match tx.try_send(ctx) {
189
+ Ok(()) => true,
190
+ Err(flume::TrySendError::Disconnected(_)) => false,
191
+ // Timed out or closed mid-send: ctx was dropped unsent either way.
192
+ Err(flume::TrySendError::Full(ctx)) => matches!(
193
+ tokio::time::timeout(timeout, tx.send_async(ctx)).await,
194
+ Ok(Ok(()))
195
+ ),
196
+ }
197
+ }
198
+
199
+ /// Into a lane, waiting for room as the server's kind of loop does.
200
+ async fn to_lane(server: &ServerInner, ctx: BoxedCtx, timeout: Duration) -> Attempt {
201
+ match server.config.worker_loop {
202
+ true => wait_in_line(server, ctx, timeout).await,
203
+ false => retry_for_lane_room(server, ctx, timeout).await,
204
+ }
205
+ }
206
+
207
+ /// A worker_loop server's dispatch: with every lane full, the request waits its turn in
208
+ /// LaneRoom, and only the first in line looks again. Continue: no room within `timeout`.
209
+ async fn wait_in_line(server: &ServerInner, mut ctx: BoxedCtx, timeout: Duration) -> Attempt {
210
+ if server.lane_room.waiting() == 0 {
211
+ ctx = try_dispatch(server, ctx)?;
212
+ }
213
+ let deadline = tokio::time::Instant::now() + timeout;
214
+ let place = server.lane_room.line_up();
215
+ loop {
216
+ if place.is_first() {
217
+ ctx = try_dispatch(server, ctx)?;
218
+ }
219
+ let now = tokio::time::Instant::now();
220
+ if now >= deadline {
221
+ return Attempt::Continue(ctx);
222
+ }
223
+ let wake = deadline.min(now + LANE_ROOM_RECHECK);
224
+ let _ = tokio::time::timeout_at(wake, place.turn()).await;
225
+ }
226
+ }
227
+
228
+ /// A classic lanes server's: it looks again every LANE_RETRY. Continue: no room within `timeout`.
229
+ async fn retry_for_lane_room(
230
+ server: &ServerInner,
231
+ mut ctx: BoxedCtx,
232
+ timeout: Duration,
233
+ ) -> Attempt {
234
+ let deadline = tokio::time::Instant::now() + timeout;
235
+ loop {
236
+ ctx = try_dispatch(server, ctx)?;
237
+ if tokio::time::Instant::now() >= deadline {
238
+ return Attempt::Continue(ctx);
239
+ }
240
+ tokio::time::sleep(LANE_RETRY).await;
241
+ }
242
+ }
243
+
244
+ /// A crashed worker's request that waited in its lane goes to the other workers' lanes, or waits
245
+ /// for room as a new arrival would, and is turned away as one is.
246
+ pub(crate) fn redispatch(server: &ServerInner, ctx: BoxedCtx) {
247
+ match try_dispatch(server, ctx) {
248
+ Attempt::Break(Ok(())) => {}
249
+ Attempt::Break(Err(ctx)) => turn_away(server, &ctx),
250
+ Attempt::Continue(ctx) => wait_for_lane_room(server, ctx),
251
+ }
252
+ }
253
+
254
+ /// Waits for lane room on the server's I/O runtime (the crash path must not wait), up to
255
+ /// queue_timeout; with no runtime running yet, its client gets its 500 now.
256
+ fn wait_for_lane_room(server: &ServerInner, ctx: BoxedCtx) {
257
+ let serving = crate::registry::try_get(server.id).zip(server.io_runtime.get());
258
+ if let Some((server, runtime)) = serving {
259
+ runtime.spawn(async move {
260
+ let timeout = Duration::from_millis(server.config.queue_timeout_ms);
261
+ let (Attempt::Break(Err(ctx)) | Attempt::Continue(ctx)) =
262
+ to_lane(&server, ctx, timeout).await
263
+ else {
264
+ return;
265
+ };
266
+ turn_away(&server, &ctx);
267
+ });
268
+ }
269
+ }
270
+
271
+ /// The 503 a turned-away arrival gets, counted as rejected.
272
+ fn turn_away(server: &ServerInner, ctx: &RequestCtx) {
273
+ server.counters.rejected.fetch_add(1, Ordering::Relaxed);
274
+ ctx.responder
275
+ .send_response(plain_response(503, "Service Unavailable\n"));
276
+ }
@@ -0,0 +1,108 @@
1
+ //! The readiness signal a worker_loop worker's fiber scheduler waits on.
2
+
3
+ use std::io::{Read, Write};
4
+ use std::os::fd::{AsRawFd, RawFd};
5
+ use std::os::unix::net::UnixStream;
6
+ use std::sync::atomic::{AtomicBool, Ordering};
7
+ use std::sync::Arc;
8
+
9
+ use parking_lot::Mutex;
10
+
11
+ /// Armed by a worker that finds nothing to take; the next lane send or close disarms it and
12
+ /// writes one byte, so a send to a busy worker makes no syscall and takes no lock.
13
+ #[derive(Default)]
14
+ pub struct Doorbell {
15
+ armed: AtomicBool,
16
+ /// A ring writes under this lock, so never to a closed descriptor or a reused number.
17
+ sockets: Mutex<Option<Arc<DoorbellSockets>>>,
18
+ /// Runs once, between a look that found nothing and the arm, where tests send.
19
+ #[cfg(test)]
20
+ before_arm: Mutex<Option<Box<dyn FnOnce() + Send>>>,
21
+ }
22
+
23
+ pub struct DoorbellSockets {
24
+ rx: UnixStream,
25
+ tx: UnixStream,
26
+ }
27
+
28
+ impl DoorbellSockets {
29
+ fn pair() -> std::io::Result<Arc<Self>> {
30
+ let (rx, tx) = UnixStream::pair()?;
31
+ rx.set_nonblocking(true)?;
32
+ tx.set_nonblocking(true)?;
33
+ Ok(Arc::new(DoorbellSockets { rx, tx }))
34
+ }
35
+
36
+ pub fn fd(&self) -> RawFd {
37
+ self.rx.as_raw_fd()
38
+ }
39
+
40
+ pub fn drain(&self) {
41
+ let mut rings = [0u8; 64];
42
+ while matches!((&self.rx).read(&mut rings), Ok(n) if n > 0) {}
43
+ }
44
+
45
+ /// One read: a ring writes one byte as it disarms; any left over cost one empty wake-up.
46
+ pub fn take_rings(&self) {
47
+ let _ = (&self.rx).read(&mut [0u8; 64]);
48
+ }
49
+ }
50
+
51
+ impl Doorbell {
52
+ pub fn new() -> std::io::Result<Self> {
53
+ let bell = Doorbell::default();
54
+ bell.open()?;
55
+ Ok(bell)
56
+ }
57
+
58
+ pub fn sockets(&self) -> Option<Arc<DoorbellSockets>> {
59
+ self.sockets.lock().clone()
60
+ }
61
+
62
+ /// The descriptor to wait on, emptied of past rings; made on first use.
63
+ pub fn open(&self) -> std::io::Result<RawFd> {
64
+ let mut sockets = self.sockets.lock();
65
+ Ok(match sockets.as_ref() {
66
+ Some(open) => {
67
+ open.drain();
68
+ open.fd()
69
+ }
70
+ None => sockets.insert(DoorbellSockets::pair()?).fd(),
71
+ })
72
+ }
73
+
74
+ pub fn release(&self) {
75
+ self.sockets.lock().take();
76
+ }
77
+
78
+ /// The worker must look once more after arming: a send just before it found no arm.
79
+ pub fn arm(&self) {
80
+ #[cfg(test)]
81
+ {
82
+ let hook = self.before_arm.lock().take();
83
+ hook.into_iter().for_each(|hook| hook());
84
+ }
85
+ self.armed.store(true, Ordering::SeqCst);
86
+ }
87
+
88
+ #[cfg(test)]
89
+ pub fn before_arm(&self, hook: impl FnOnce() + Send + 'static) {
90
+ *self.before_arm.lock() = Some(Box::new(hook));
91
+ }
92
+
93
+ pub fn disarm(&self) {
94
+ self.armed.store(false, Ordering::SeqCst);
95
+ }
96
+
97
+ /// The load keeps a busy worker's sends off the flag; a full socket means a ring already
98
+ /// waits.
99
+ /// A thread-safe free may run it (a request given up), so it keeps typed_data.rs's promise:
100
+ /// one write that never waits, under a lock nothing holds across a Ruby call.
101
+ pub fn ring(&self) {
102
+ if self.armed.load(Ordering::SeqCst) && self.armed.swap(false, Ordering::SeqCst) {
103
+ if let Some(sockets) = self.sockets.lock().as_ref() {
104
+ let _ = (&sockets.tx).write(&[1]);
105
+ }
106
+ }
107
+ }
108
+ }
@@ -63,6 +63,8 @@ pub struct EnvStrings {
63
63
  pub rack_input: Opaque<RString>,
64
64
  pub rack_errors: Opaque<RString>,
65
65
  pub kino_request: Opaque<RString>,
66
+ pub rack_hijack_offered: Opaque<RString>,
67
+ pub rack_hijack: Opaque<RString>,
66
68
  // values
67
69
  pub empty: Opaque<RString>,
68
70
  pub http: Opaque<RString>,
@@ -77,7 +79,8 @@ pub struct EnvStrings {
77
79
  /// module docs); a cache entry owns its slots and clears them when
78
80
  /// it is evicted.
79
81
  pub slab: Arc<PinSlab>,
80
- /// Host-header or :authority bytes -> frozen host values, and peer
82
+ /// Host-header or :authority bytes (with the local port, when they
83
+ /// name none: request::host_key) -> frozen host values, and peer
81
84
  /// IP -> frozen REMOTE_ADDR value. Real traffic has low cardinality
82
85
  /// on both, so these kill 3 string allocations per request.
83
86
  /// LRU-bounded, so a rotating-host attack recycles cache slots
@@ -370,6 +373,8 @@ pub fn init(ruby: &Ruby) {
370
373
  rack_input: frozen(ruby, "rack.input"),
371
374
  rack_errors: frozen(ruby, "rack.errors"),
372
375
  kino_request: frozen(ruby, "kino.request"),
376
+ rack_hijack_offered: frozen(ruby, "rack.hijack?"),
377
+ rack_hijack: frozen(ruby, "rack.hijack"),
373
378
  empty: frozen(ruby, ""),
374
379
  http: frozen(ruby, "http"),
375
380
  https: frozen(ruby, "https"),
@@ -460,20 +465,20 @@ where
460
465
  pub fn set_host_env(
461
466
  ruby: &Ruby,
462
467
  env: magnus::RHash,
463
- host: &[u8],
468
+ key: &[u8],
464
469
  make: impl FnOnce() -> (String, u16),
465
470
  ) -> Result<(), magnus::Error> {
466
471
  let s = get();
467
472
  let (name, port) = get_or_insert(
468
473
  &s.hosts,
469
- host,
474
+ key,
470
475
  |entry| entry.name_port(ruby),
471
476
  || {
472
477
  let (name, port) = make();
473
478
  (frozen_str(ruby, &name), frozen_str(ruby, &port.to_string()))
474
479
  },
475
480
  |&(name, port)| HostEntry::root(&s.slab, name, port, None),
476
- || host.to_vec(),
481
+ || key.to_vec(),
477
482
  );
478
483
  env.aset(ruby.get_inner(s.server_name), name)?;
479
484
  env.aset(ruby.get_inner(s.server_port), port)?;
@@ -489,11 +494,11 @@ pub fn set_host_env(
489
494
  pub fn set_authority_env(
490
495
  ruby: &Ruby,
491
496
  env: magnus::RHash,
497
+ key: &[u8],
492
498
  authority: &str,
493
499
  make: impl FnOnce() -> (String, u16),
494
500
  ) -> Result<(), magnus::Error> {
495
501
  let s = get();
496
- let key = authority.as_bytes();
497
502
  let read = |entry: &HostEntry| {
498
503
  let (name, port) = entry.name_port(ruby);
499
504
  (name, port, entry.host.as_ref().map(|host| host.get(ruby)))
@@ -581,7 +586,7 @@ pub fn set_addr_env(ruby: &Ruby, env: magnus::RHash, ip: IpAddr) -> Result<(), m
581
586
 
582
587
  #[cfg(test)]
583
588
  mod tests {
584
- use super::{cgi_name, COMMON_HEADERS, COMMON_METHODS};
589
+ use super::{cgi_name, COMMON_HEADERS, COMMON_METHODS, INTERNABLE_VALUES};
585
590
 
586
591
  #[test]
587
592
  fn cgi_names() {
@@ -591,31 +596,22 @@ mod tests {
591
596
  assert_eq!(cgi_name("sec-ch-ua"), "HTTP_SEC_CH_UA");
592
597
  }
593
598
 
594
- // The cache is keyed by hyper's lowercase wire form; one uppercase
595
- // entry would silently never hit.
599
+ // The caches are keyed by hyper's wire forms, lowercase names and uppercase methods; an
600
+ // entry in another case would silently never hit.
596
601
  #[test]
597
- fn common_headers_are_lowercase_and_unique() {
598
- let mut seen = std::collections::HashSet::new();
599
- for header in COMMON_HEADERS {
600
- assert_eq!(
601
- *header,
602
- header.to_ascii_lowercase(),
603
- "{header} must be lowercase"
604
- );
605
- assert!(seen.insert(*header), "{header} listed twice");
606
- }
607
- }
608
-
609
- #[test]
610
- fn common_methods_are_uppercase_and_unique() {
611
- let mut seen = std::collections::HashSet::new();
612
- for method in COMMON_METHODS {
613
- assert_eq!(
614
- *method,
615
- method.to_ascii_uppercase(),
616
- "{method} must be uppercase"
617
- );
618
- assert!(seen.insert(*method), "{method} listed twice");
602
+ fn the_cached_names_are_listed_once_each_in_their_wire_case() {
603
+ type WireCase = fn(&str) -> String;
604
+ let lists: [(&[&str], WireCase); 3] = [
605
+ (COMMON_HEADERS, str::to_ascii_lowercase),
606
+ (INTERNABLE_VALUES, str::to_ascii_lowercase),
607
+ (COMMON_METHODS, str::to_ascii_uppercase),
608
+ ];
609
+ for (list, wire_case) in lists {
610
+ let mut seen = std::collections::HashSet::new();
611
+ for &name in list {
612
+ assert_eq!(name, wire_case(name), "{name} is not in its wire case");
613
+ assert!(seen.insert(name), "{name} listed twice");
614
+ }
619
615
  }
620
616
  }
621
617
  }
@@ -0,0 +1,110 @@
1
+ //! HTTP/1 framing as hyper reads it: bodiless and lengthless answers, lengths, header lists.
2
+
3
+ use http::header::CONTENT_LENGTH;
4
+
5
+ /// As hyper's default: the most headers a head may have.
6
+ pub const MAX_HEADERS: usize = 100;
7
+
8
+ /// No body whatever the head declares (RFC 9110 6.4.1): a 1xx, 204 or 304, or a HEAD answer.
9
+ pub fn bodiless(status: u16, head_request: bool) -> bool {
10
+ head_request || matches!(status, 100..=199 | 204 | 304)
11
+ }
12
+
13
+ /// A 1xx or a 204: no Content-Length, which RFC 9110 forbids and h2 clients reject.
14
+ pub fn lengthless(status: u16) -> bool {
15
+ matches!(status, 100..=199 | 204)
16
+ }
17
+
18
+ /// An answer that sends no body, and the one rule for what its head keeps of a Content-Length,
19
+ /// whichever way the answer goes out (whole from the worker, streamed, or canned by Kino).
20
+ #[derive(Clone, Copy)]
21
+ pub struct Bodiless {
22
+ /// By its status alone, whatever the request's method.
23
+ by_status: bool,
24
+ /// A 1xx or a 204: no Content-Length, which RFC 9110 forbids and h2 clients reject.
25
+ lengthless: bool,
26
+ }
27
+
28
+ impl Bodiless {
29
+ /// None for an answer whose body goes out.
30
+ #[inline]
31
+ pub fn of(status: u16, head_request: bool) -> Option<Bodiless> {
32
+ let by_status = bodiless(status, false);
33
+ if !head_request && !by_status {
34
+ return None;
35
+ }
36
+ Some(Bodiless {
37
+ by_status,
38
+ lengthless: lengthless(status),
39
+ })
40
+ }
41
+
42
+ /// For a whole body of `len` bytes that stays behind: keep_length unless it is empty, then
43
+ /// drop_forbidden_length. keep_length leaves one Content-Length where the head repeated
44
+ /// it, which loses nothing: a worker's answer comes with one, and a hijack bridge's
45
+ /// answer whose lengths differ was refused with a 502, so only equal ones meet here.
46
+ pub fn settle(&self, headers: &mut http::HeaderMap, len: usize) {
47
+ if len > 0 {
48
+ self.keep_length(headers, len);
49
+ }
50
+ self.drop_forbidden_length(headers);
51
+ }
52
+
53
+ /// The app's first Content-Length stays, alone; without one a HEAD's answer gets its body's
54
+ /// `len`, unless that is 0 or its status alone forbids the body (a 304).
55
+ pub fn keep_length(&self, headers: &mut http::HeaderMap, len: usize) {
56
+ match headers.get(CONTENT_LENGTH).cloned() {
57
+ Some(first) => {
58
+ headers.insert(CONTENT_LENGTH, first);
59
+ }
60
+ None if !self.by_status && len > 0 => {
61
+ headers.insert(CONTENT_LENGTH, len.into());
62
+ }
63
+ None => {}
64
+ }
65
+ }
66
+
67
+ pub fn drop_forbidden_length(&self, headers: &mut http::HeaderMap) {
68
+ if self.lengthless {
69
+ headers.remove(CONTENT_LENGTH);
70
+ }
71
+ }
72
+ }
73
+
74
+ /// A Content-Length value: digits only, as hyper reads it.
75
+ pub fn digits(value: &[u8]) -> Option<u64> {
76
+ if value.is_empty() {
77
+ return None;
78
+ }
79
+ value.iter().try_fold(0u64, |n, &b| {
80
+ if !b.is_ascii_digit() {
81
+ return None;
82
+ }
83
+ n.checked_mul(10)?.checked_add(u64::from(b - b'0'))
84
+ })
85
+ }
86
+
87
+ /// The first Content-Length's value; None when it is absent or not digits.
88
+ pub fn content_length(headers: &http::HeaderMap) -> Option<u64> {
89
+ digits(headers.get(CONTENT_LENGTH)?.as_bytes())
90
+ }
91
+
92
+ /// No Content-Length, or values all digits and equal: what hyper takes beside an unknown length.
93
+ pub fn usable_length(headers: &http::HeaderMap) -> bool {
94
+ let values = headers.get_all(CONTENT_LENGTH);
95
+ let mut lengths = values.iter().map(|value| digits(value.as_bytes()));
96
+ match lengths.next() {
97
+ None => true,
98
+ Some(first) => first.is_some() && lengths.all(|next| next == first),
99
+ }
100
+ }
101
+
102
+ /// The items of a comma-separated header value, trimmed.
103
+ pub fn tokens(value: &[u8]) -> impl DoubleEndedIterator<Item = &[u8]> {
104
+ value.split(|&b| b == b',').map(<[u8]>::trim_ascii)
105
+ }
106
+
107
+ /// Whether a list header's `value` names `token`, in any case.
108
+ pub fn has_token(value: &[u8], token: &[u8]) -> bool {
109
+ tokens(value).any(|t| t.eq_ignore_ascii_case(token))
110
+ }