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
data/sig/kino.rbs CHANGED
@@ -1,7 +1,6 @@
1
- # Public interfaces only. Internals (Kino::Worker, Kino::RactorSupervisor,
2
- # Kino::Input, Kino::NullInput, Kino::ErrorsStream, Kino::Stream,
3
- # Kino::Native) are deliberately unsigned: they are implementation detail
4
- # and may change without notice.
1
+ # Public interfaces only. Internals, everything marked @private and the
2
+ # extension's Kino::Native, are deliberately unsigned: they are
3
+ # implementation detail and may change without notice.
5
4
  module Kino
6
5
  VERSION: String
7
6
 
@@ -17,12 +16,19 @@ module Kino
17
16
  class UnshareableAppError < Error
18
17
  end
19
18
 
19
+ # Raised by a streaming body's write once its client has gone.
20
+ class ClientGone < IOError
21
+ end
22
+
20
23
  # High-resolution sleep on the OS clock with the GVL released.
21
24
  def self.sleep: (Numeric seconds) -> nil
22
25
 
23
26
  # CPUs this process may use (affinity mask and cgroup quota); never below 1.
24
27
  def self.available_parallelism: () -> Integer
25
28
 
29
+ # RUBY_MAX_CPU as Ruby reads it: 8 when unset or not an integer.
30
+ def self.ruby_max_cpu: () -> Integer
31
+
26
32
  class Server
27
33
  attr_reader port: Integer?
28
34
  attr_reader control_port: Integer?
@@ -49,17 +55,19 @@ module Kino
49
55
  # Graceful shutdown: drain to the deadline, then abort stragglers.
50
56
  def shutdown: (?timeout: Numeric?) -> nil
51
57
 
52
- def wait: () -> untyped
58
+ # Block until a shutdown has ended; raises its error if it failed.
59
+ def wait: () -> void
53
60
 
54
61
  # Live snapshot: config echo plus native counters (queued, in_flight,
55
- # served, rejected, timeouts, respawns, lane_depths when lanes are on).
62
+ # served, rejected, timeouts, respawns, ...), in the order /stats lists
63
+ # them; :responses_cut and :websockets cover the whole process.
56
64
  def stats: () -> stats_hash
57
65
 
58
66
  # Production entry point: build the server and #run it.
59
- def self.run: (rack_app app, **untyped opts) -> Server
67
+ def self.run: (rack_app app, ?credits: bool, ?on_ready: (^() -> void)?, **untyped opts) -> Server
60
68
 
61
69
  # Serve until shut down: start, banner, signal traps, block until done.
62
- def run: () -> self
70
+ def run: (?credits: bool, ?on_ready: (^() -> void)?) -> self
63
71
 
64
72
  # INT/TERM drain gracefully (second signal force-exits); USR1 prints stats.
65
73
  def self.trap_signals: (Server server) -> void
@@ -120,16 +128,25 @@ module Kino
120
128
  def max_connections: (int count) -> untyped
121
129
  def max_body_size: (int? bytes) -> untyped
122
130
  def batch: (int count) -> untyped
131
+ # Per-worker lanes (default: on with a worker_loop, else off); native WebSockets and wake
132
+ # hooks need them.
123
133
  def lanes: (boolish enabled) -> untyped
134
+ # Largest message a client may send (default 1 MiB); past it, 1009.
135
+ def websocket_max_message: (int bytes) -> untyped
136
+ # Most native sockets open at once (default nil: no cap of its own).
137
+ def websocket_max: (int? count) -> untyped
138
+ # Seconds of silence before a ping (default 30); nil or 0: no pings.
139
+ def websocket_ping_interval: (Numeric? seconds) -> untyped
124
140
  def log_requests: (boolish enabled) -> untyped
125
141
  def on_error: (?^(Exception, Hash[String, untyped]) -> void handler) ?{ (Exception, Hash[String, untyped]) -> void } -> untyped
126
142
  def after_boot: (?^() -> void handler) ?{ () -> void } -> untyped
127
143
  def after_worker_boot: (?^(Integer) -> void handler) ?{ (Integer) -> void } -> untyped
128
144
  def after_request_complete: (?^(Hash[String, untyped], Integer) -> void handler) ?{ (Hash[String, untyped], Integer) -> void } -> untyped
129
145
  def on_worker_exit: (?^(Integer, Exception?) -> void handler) ?{ (Integer, Exception?) -> void } -> untyped
146
+ def worker_loop: (?^(Worker::Loop) -> void handler) ?{ (Worker::Loop) -> void } -> untyped
130
147
  def shutdown_timeout: (Numeric seconds) -> untyped
131
148
  def io_shards: (?boolish enabled) -> untyped
132
- def io_threads: (int? count) -> untyped
149
+ def io_threads: (int count) -> untyped
133
150
  def tokio_threads: (int count) -> untyped
134
151
  def tls: (cert: String, key: String) -> untyped
135
152
  def http2: (?boolish enabled) -> untyped
@@ -143,6 +160,72 @@ module Kino
143
160
  end
144
161
  end
145
162
 
163
+ # A handle to a native WebSocket, handed to the callbacks of the handler an app sets as
164
+ # env["rack.upgrade"]: frozen, shareable, and usable from any thread or Ractor.
165
+ class WebSocket
166
+ attr_reader id: Integer
167
+
168
+ # The socket with this id; nil once it is gone.
169
+ def self.[]: (Integer id) -> WebSocket?
170
+
171
+ def ==: (untyped other) -> bool
172
+
173
+ def eql?: (untyped other) -> bool
174
+
175
+ def hash: () -> Integer
176
+
177
+ # One text frame.
178
+ def write: (String data) -> bool
179
+
180
+ # One binary frame.
181
+ def write_binary: (String data) -> bool
182
+
183
+ # Bytes that already form complete frames.
184
+ def write_raw: (String frames) -> bool
185
+
186
+ # A close frame after what is queued (5 s to answer); the first close stands, on_close
187
+ # follows. False on a full queue; ArgumentError for a code no endpoint may send.
188
+ def close: (?Integer code) -> bool
189
+
190
+ # Drop the connection now; on_close follows.
191
+ def abort: () -> bool
192
+
193
+ # Data frames queued and not yet written; 0 once the socket is gone.
194
+ def pending: () -> Integer
195
+
196
+ # Receive `topic`'s publishes as `prefix + body + suffix` frames; a full queue drops the
197
+ # socket (:close) or skips the message (:skip). False once gone.
198
+ def subscribe: (String topic, ?prefix: String, ?suffix: String, ?when_full: :close | :skip) -> bool
199
+
200
+ # End every subscription to `topic`, or those made with `prefix`; false if none.
201
+ def unsubscribe: (String topic, ?prefix: String?) -> bool
202
+
203
+ # Queue `body` for `topic`'s subscribers from any Ractor, as text (UTF-8) or binary; false
204
+ # only when the fan-out queue is full.
205
+ def self.publish: (String topic, String body, ?binary: boolish) -> bool
206
+ end
207
+
208
+ # The worker's wake hook: work on the worker's own thread (::on_wake). Needs lanes.
209
+ class Worker
210
+ # Register (or replace) this worker thread's hook; ArgumentError off a worker thread.
211
+ def self.on_wake: () { () -> void } -> Waker
212
+
213
+ # Wakes one worker, from any thread or Ractor (frozen, shareable).
214
+ class Waker
215
+ # The hook runs soon; wakes before it coalesce. False once the worker has exited or is
216
+ # retiring, or without lanes.
217
+ def wake: () -> bool
218
+ end
219
+
220
+ # What a worker_loop gets: Kino's loop, for the app's fiber scheduler to run.
221
+ class Loop
222
+ # Serve the worker's requests as jobs the block starts, at most `concurrency` at a time;
223
+ # each socket's events, and the wakes, run in order on jobs of their own. Returns once the
224
+ # worker is drained. An inline connection runs on its own job, its requests counting too.
225
+ def serve: (concurrency: Integer) { (^() -> void job) -> void } -> nil
226
+ end
227
+ end
228
+
146
229
  # The `kino` executable plus startup presentation shared with Server.run.
147
230
  module CLI
148
231
  MOTD: String
@@ -163,7 +246,7 @@ module Kino
163
246
 
164
247
  def self.red: (String text, ?io: IO) -> String
165
248
 
166
- # The banner with a vertical grayscale gradient.
249
+ # The banner with its three-tone shading.
167
250
  def self.motd: (?color: bool) -> String
168
251
 
169
252
  # One-line stats dump (the SIGUSR1 handler's output).
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kino
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.2
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yaroslav Markin
@@ -183,37 +183,95 @@ files:
183
183
  - doc/README.md
184
184
  - doc/architecture.md
185
185
  - doc/benchmarks.md
186
+ - doc/configuration.md
187
+ - doc/operations.md
186
188
  - doc/rails-on-ractors.md
189
+ - doc/streaming.md
190
+ - doc/websockets.md
187
191
  - doc/why-kino.md
192
+ - doc/worker-loop.md
188
193
  - exe/kino
189
194
  - ext/kino/Cargo.toml
190
195
  - ext/kino/build.rs
196
+ - ext/kino/clippy.toml
191
197
  - ext/kino/extconf.rb
192
198
  - ext/kino/src/access_log.rs
193
199
  - ext/kino/src/control.rs
200
+ - ext/kino/src/counters.rs
194
201
  - ext/kino/src/cpus.rs
202
+ - ext/kino/src/dispatch.rs
203
+ - ext/kino/src/dispatch/tests.rs
204
+ - ext/kino/src/doorbell.rs
195
205
  - ext/kino/src/env_strings.rs
206
+ - ext/kino/src/framing.rs
196
207
  - ext/kino/src/gvl.rs
208
+ - ext/kino/src/hijack.rs
209
+ - ext/kino/src/hijack/tests.rs
210
+ - ext/kino/src/inline/answer.rs
211
+ - ext/kino/src/inline/conn.rs
212
+ - ext/kino/src/inline/deadline.rs
213
+ - ext/kino/src/inline/encode.rs
214
+ - ext/kino/src/inline/io.rs
215
+ - ext/kino/src/inline/mod.rs
216
+ - ext/kino/src/inline/parity.rs
217
+ - ext/kino/src/inline/parse.rs
218
+ - ext/kino/src/inline/spin.rs
219
+ - ext/kino/src/inline/testing.rs
197
220
  - ext/kino/src/io_shards.rs
221
+ - ext/kino/src/lane_room.rs
198
222
  - ext/kino/src/lib.rs
199
223
  - ext/kino/src/listen.rs
200
224
  - ext/kino/src/log.rs
201
225
  - ext/kino/src/logsink.rs
202
226
  - ext/kino/src/mono.rs
203
227
  - ext/kino/src/pin.rs
204
- - ext/kino/src/queue.rs
228
+ - ext/kino/src/queue/mod.rs
229
+ - ext/kino/src/queue/take.rs
230
+ - ext/kino/src/queue/testing.rs
231
+ - ext/kino/src/queue/tests.rs
232
+ - ext/kino/src/queue/worker.rs
205
233
  - ext/kino/src/registry.rs
206
234
  - ext/kino/src/request.rs
207
235
  - ext/kino/src/response.rs
208
- - ext/kino/src/server.rs
236
+ - ext/kino/src/server/accept.rs
237
+ - ext/kino/src/server/config.rs
238
+ - ext/kino/src/server/handle.rs
239
+ - ext/kino/src/server/intake.rs
240
+ - ext/kino/src/server/mod.rs
241
+ - ext/kino/src/server/natives.rs
242
+ - ext/kino/src/server/serve.rs
243
+ - ext/kino/src/server/serve/intake_tests.rs
244
+ - ext/kino/src/server/tests.rs
245
+ - ext/kino/src/shared_gvl.rs
246
+ - ext/kino/src/slot/lane.rs
247
+ - ext/kino/src/slot/life.rs
248
+ - ext/kino/src/slot/load.rs
249
+ - ext/kino/src/slot/mod.rs
250
+ - ext/kino/src/slot/park.rs
251
+ - ext/kino/src/stats.rs
209
252
  - ext/kino/src/style.rs
253
+ - ext/kino/src/symbols.rs
210
254
  - ext/kino/src/test_support.rs
255
+ - ext/kino/src/testing.rs
256
+ - ext/kino/src/ticker.rs
211
257
  - ext/kino/src/timer.rs
212
258
  - ext/kino/src/tls.rs
259
+ - ext/kino/src/typed_data.rs
260
+ - ext/kino/src/upgrade.rs
261
+ - ext/kino/src/ws/codec.rs
262
+ - ext/kino/src/ws/drive.rs
263
+ - ext/kino/src/ws/handshake.rs
264
+ - ext/kino/src/ws/mod.rs
265
+ - ext/kino/src/ws/server_tests.rs
266
+ - ext/kino/src/ws/socket.rs
267
+ - ext/kino/src/ws/stats.rs
268
+ - ext/kino/src/ws/testing.rs
269
+ - ext/kino/src/ws/topics.rs
213
270
  - lib/kino.rb
214
271
  - lib/kino/check.rb
215
272
  - lib/kino/cli.rb
216
273
  - lib/kino/configuration.rb
274
+ - lib/kino/crash_backoff.rb
217
275
  - lib/kino/errors_stream.rb
218
276
  - lib/kino/hook_fire.rb
219
277
  - lib/kino/input.rb
@@ -221,17 +279,22 @@ files:
221
279
  - lib/kino/logger.rb
222
280
  - lib/kino/monitor.rb
223
281
  - lib/kino/null_input.rb
282
+ - lib/kino/pool.rb
224
283
  - lib/kino/pool_scaler.rb
225
284
  - lib/kino/quarantine_monitor.rb
226
285
  - lib/kino/ractor_supervisor.rb
227
286
  - lib/kino/server.rb
228
287
  - lib/kino/slot_bank.rb
229
288
  - lib/kino/stream.rb
289
+ - lib/kino/teardown.rb
230
290
  - lib/kino/templates/kino.rb.tt
231
291
  - lib/kino/threaded_pool.rb
232
292
  - lib/kino/version.rb
293
+ - lib/kino/web_socket.rb
233
294
  - lib/kino/worker.rb
295
+ - lib/kino/worker/loop.rb
234
296
  - lib/kino/worker_hooks.rb
297
+ - lib/kino/worker_row.rb
235
298
  - lib/rackup/handler/kino.rb
236
299
  - sig/kino.rbs
237
300
  homepage: https://github.com/yaroslav/kino
@@ -1,333 +0,0 @@
1
- //! The worker-side bridge: batched request intake and the fused
2
- //! respond-and-take call. This is where FFI crossings per request went
3
- //! from three in early designs (take, env, respond) to amortized ~one.
4
- //!
5
- //! Blocking discipline (everywhere in this crate): bounded `recv_timeout`
6
- //! ticks + an AtomicBool interrupt flag. No flume::Selector: it loses
7
- //! wakeups under churn, observed as workers going permanently deaf to a
8
- //! non-empty queue after ~100k requests.
9
-
10
- use std::cell::RefCell;
11
- use std::sync::atomic::Ordering;
12
- use std::sync::Arc;
13
- use std::time::Duration;
14
-
15
- use magnus::prelude::*;
16
- use magnus::{Error, RArray, RHash, RString, Ruby};
17
-
18
- use crate::gvl;
19
- use crate::registry::{self, BoxedCtx, ServerInner, WorkerSlot};
20
- use crate::request::Request;
21
-
22
- pub const TICK: Duration = Duration::from_millis(50);
23
-
24
- /// None = shutdown (queue closed or interrupted); the caller can't tell
25
- /// the difference and doesn't need to.
26
- type Taken = Option<BoxedCtx>;
27
-
28
- /// What a take does when its bounded wait times out: keep waiting (None),
29
- /// or end the loop because the pool scaler retired this slot. A retired
30
- /// lane worker first empties its own lane, one item per timeout: the
31
- /// dispatcher stopped feeding it when the flag went up (see
32
- /// registry::WorkerSlot::retire for the ordering), so whatever is
33
- /// still there is the last of it, and nothing already assigned is
34
- /// orphaned. Only reached with the queue momentarily empty, so the fast
35
- /// path pays nothing for it.
36
- fn after_timeout(slot: &WorkerSlot) -> Option<Taken> {
37
- if !slot.retired.load(Ordering::SeqCst) {
38
- return None;
39
- }
40
- Some(slot.lane_rx.as_ref().and_then(|rx| rx.try_recv().ok()))
41
- }
42
-
43
- /// Block until one request arrives (GVL released, interruptible).
44
- /// No busy-poll before parking, deliberately: the wake-per-request futex
45
- /// cost is real (~20% of cycles at saturation, per perf), but a measured
46
- /// 20µs spin made things WORSE on oversubscribed cores: spinners steal
47
- /// exactly the CPU the tokio threads need.
48
- fn block_take(server: &ServerInner, slot: &Arc<WorkerSlot>) -> Result<Taken, Error> {
49
- if slot.lane_rx.is_some() {
50
- return lane_take(server, slot);
51
- }
52
- let req_rx = &server.req_rx;
53
-
54
- // Fast path: a request is already queued (the common case under load).
55
- // try_recv never blocks, so the whole GVL release/reacquire (two
56
- // scheduler round-trips per request) is skipped entirely.
57
- match req_rx.try_recv() {
58
- Ok(ctx) => Ok(Some(ctx)),
59
- Err(flume::TryRecvError::Disconnected) => Ok(None),
60
- Err(flume::TryRecvError::Empty) => {
61
- let taken =
62
- gvl::interruptible(&slot.interrupted, || match req_rx.recv_timeout(TICK) {
63
- Ok(ctx) => Some(Some(ctx)),
64
- Err(flume::RecvTimeoutError::Timeout) => after_timeout(slot),
65
- Err(flume::RecvTimeoutError::Disconnected) => Some(None),
66
- })?;
67
- Ok(taken.flatten())
68
- }
69
- }
70
- }
71
-
72
- /// Lane-mode take: own lane first (no wake needed while the dispatcher
73
- /// keeps feeding an awake lane), then steal from siblings, then park on
74
- /// the own lane with the parked flag raised so the dispatcher avoids it.
75
- fn lane_take(server: &ServerInner, slot: &Arc<WorkerSlot>) -> Result<Taken, Error> {
76
- let lane_rx = slot.lane_rx.as_ref().expect("lane_take without lane");
77
-
78
- let steal = || -> Option<BoxedCtx> {
79
- let slots = server.slots.read();
80
- for other in slots.iter() {
81
- if Arc::ptr_eq(other, slot) {
82
- continue;
83
- }
84
- if let Some(rx) = other.lane_rx.as_ref() {
85
- if let Ok(ctx) = rx.try_recv() {
86
- return Some(ctx);
87
- }
88
- }
89
- }
90
- None
91
- };
92
-
93
- // Hot path, GVL still held: own lane, then a steal sweep.
94
- match lane_rx.try_recv() {
95
- Ok(ctx) => return Ok(Some(ctx)),
96
- Err(flume::TryRecvError::Disconnected) => return Ok(None),
97
- Err(flume::TryRecvError::Empty) => {}
98
- }
99
- if let Some(ctx) = steal() {
100
- return Ok(Some(ctx));
101
- }
102
-
103
- // Park. The flag-then-recheck order closes the race with a dispatcher
104
- // that read parked=false just before we set it: anything it sent lands
105
- // in the lane, and recv_timeout checks the queue before sleeping.
106
- slot.parked.store(true, Ordering::SeqCst);
107
- let taken = gvl::interruptible(&slot.interrupted, || {
108
- match lane_rx.recv_timeout(TICK) {
109
- Ok(ctx) => Some(Some(ctx)),
110
- // Periodic steal so a backlog behind a slow sibling can't
111
- // outlive a tick; a retired worker leaves instead.
112
- Err(flume::RecvTimeoutError::Timeout) => {
113
- after_timeout(slot).or_else(|| steal().map(Some))
114
- }
115
- Err(flume::RecvTimeoutError::Disconnected) => Some(None),
116
- }
117
- });
118
- // Unpark before propagating any panic, or the dispatcher shuns this
119
- // lane for good.
120
- slot.parked.store(false, Ordering::SeqCst);
121
- Ok(taken?.flatten())
122
- }
123
-
124
- /// Wrap a ctx into its env Hash, with the Ruby request handle embedded
125
- /// under the frozen "kino.request" key (one Hash carries everything, no
126
- /// per-request pair array). Registered in the slot's in-flight list;
127
- /// created inside the calling ractor, so handle ownership is correct by
128
- /// construction.
129
- fn admit(
130
- ruby: &Ruby,
131
- server: &ServerInner,
132
- slot: &Arc<WorkerSlot>,
133
- mut ctx: BoxedCtx,
134
- ) -> Result<RHash, Error> {
135
- server.served.fetch_add(1, Ordering::Relaxed);
136
- slot.served.fetch_add(1, Ordering::Relaxed);
137
- slot.last_started_ms
138
- .store(crate::mono::mono_ms(), Ordering::Relaxed);
139
- slot.in_flight.fetch_add(1, Ordering::Relaxed);
140
- // One clock read serves the histogram and, for the access log, the
141
- // request's queue wait and the start of its time in Ruby.
142
- let now = std::time::Instant::now();
143
- let wait = now.duration_since(ctx.enqueued_at);
144
- server.queue_histogram.record(wait.as_micros() as u64);
145
- ctx.wait = wait;
146
- ctx.admitted_at = now;
147
- slot.current.lock().push(Arc::downgrade(&ctx.responder));
148
- // Wire the slot into the request so blocked body reads/writes are
149
- // interruptible the same way the queue pop is.
150
- ctx.slot = Some(slot.clone());
151
- let env = crate::request::build_env(ruby, &ctx)?;
152
- let request = ruby.obj_wrap(Request(RefCell::new(*ctx)));
153
- let key = ruby.get_inner(crate::env_strings::get().kino_request);
154
- env.aset(key, request.as_value())?;
155
- Ok(env)
156
- }
157
-
158
- /// Per-worker native handle: the registry lookup and slot resolution are
159
- /// paid once at worker boot instead of on every take. Created inside the
160
- /// worker thread/ractor that uses it (like Request handles), so ownership
161
- /// is correct by construction. Holds the server weakly: after teardown the
162
- /// upgrade fails, which is the same clean shutdown signal the per-take
163
- /// registry lookup used to give.
164
- #[magnus::wrap(class = "Kino::Native::Worker", free_immediately)]
165
- pub struct Worker {
166
- server: std::sync::Weak<ServerInner>,
167
- slot: Arc<WorkerSlot>,
168
- }
169
-
170
- /// Resolve a (server, worker) pair into a Worker handle; nil when the
171
- /// server is already gone (the caller treats that as shutdown).
172
- pub fn worker(ruby: &Ruby, server_id: u64, worker_id: usize) -> Result<Option<Worker>, Error> {
173
- let Some(server) = registry::try_get(server_id) else {
174
- return Ok(None);
175
- };
176
- let slot = server.slot(ruby, worker_id)?;
177
- Ok(Some(Worker {
178
- server: Arc::downgrade(&server),
179
- slot,
180
- }))
181
- }
182
-
183
- impl Worker {
184
- fn checkout(&self) -> Result<Option<(Arc<ServerInner>, BoxedCtx)>, Error> {
185
- let Some(server) = self.server.upgrade() else {
186
- return Ok(None); // server torn down → clean shutdown signal
187
- };
188
-
189
- // The previous batch is fully answered once the worker comes back.
190
- self.slot.current.lock().clear();
191
- self.slot.in_flight.store(0, Ordering::Relaxed);
192
- self.slot.interrupted.store(false, Ordering::SeqCst);
193
-
194
- Ok(block_take(&server, &self.slot)?.map(|ctx| (server, ctx)))
195
- }
196
-
197
- /// Take one request; returns its env Hash (request handle inside under
198
- /// "kino.request") or nil on shutdown. The batch-of-one hot path: no
199
- /// arrays allocated at all.
200
- pub fn take_one(ruby: &Ruby, rb_self: &Worker) -> Result<Option<RHash>, Error> {
201
- match rb_self.checkout()? {
202
- Some((server, ctx)) => Ok(Some(admit(ruby, &server, &rb_self.slot, ctx)?)),
203
- None => Ok(None),
204
- }
205
- }
206
-
207
- /// Take up to `max` requests: block for the first, drain the rest
208
- /// non-blocking (they only batch when the queue is already deep).
209
- /// Returns nil on shutdown; otherwise an Array of env Hashes.
210
- pub fn take_batch(ruby: &Ruby, rb_self: &Worker, max: usize) -> Result<Option<RArray>, Error> {
211
- let Some((server, first)) = rb_self.checkout()? else {
212
- return Ok(None);
213
- };
214
-
215
- let batch = ruby.ary_new_capa(max.max(1));
216
- batch.push(admit(ruby, &server, &rb_self.slot, first)?)?;
217
- for _ in 1..max {
218
- match server.req_rx.try_recv() {
219
- Ok(ctx) => batch.push(admit(ruby, &server, &rb_self.slot, ctx)?)?,
220
- Err(_) => break,
221
- }
222
- }
223
- Ok(Some(batch))
224
- }
225
- }
226
-
227
- /// The fused hot path: answer `request` (complete response in one shot)
228
- /// and immediately take the next request. One FFI crossing per request
229
- /// once the loop is warm.
230
- pub fn respond_and_take_one(
231
- ruby: &Ruby,
232
- request: &Request,
233
- worker: magnus::typed_data::Obj<Worker>,
234
- status: u16,
235
- headers: RHash,
236
- body: RString,
237
- ) -> Result<Option<RHash>, Error> {
238
- crate::request::respond_simple(ruby, request, status, headers, body)?;
239
- Worker::take_one(ruby, &worker)
240
- }
241
-
242
- /// Batch variant of the fused call.
243
- pub fn respond_and_take(
244
- ruby: &Ruby,
245
- request: &Request,
246
- worker: magnus::typed_data::Obj<Worker>,
247
- max: usize,
248
- status: u16,
249
- headers: RHash,
250
- body: RString,
251
- ) -> Result<Option<RArray>, Error> {
252
- crate::request::respond_simple(ruby, request, status, headers, body)?;
253
- Worker::take_batch(ruby, &worker, max)
254
- }
255
-
256
- #[cfg(test)]
257
- mod tests {
258
- use super::*;
259
- use crate::registry::test_server;
260
- use crate::request::test_ctx;
261
-
262
- #[test]
263
- fn a_take_keeps_waiting_after_a_timeout_unless_the_slot_is_retired() {
264
- let server = test_server(false, 4);
265
- server.register_worker();
266
- let slot = server.slots.read()[0].clone();
267
-
268
- assert!(after_timeout(&slot).is_none());
269
- }
270
-
271
- #[test]
272
- fn a_retired_shared_queue_worker_ends_its_loop_at_the_next_timeout() {
273
- let server = test_server(false, 4);
274
- server.register_worker();
275
- server.slots.read()[0].retire();
276
- let slot = server.slots.read()[0].clone();
277
-
278
- assert!(matches!(after_timeout(&slot), Some(None)));
279
- }
280
-
281
- #[test]
282
- fn a_retired_lane_worker_drains_its_own_lane_before_leaving() {
283
- let server = test_server(true, 4);
284
- server.register_worker();
285
- let slot = server.slots.read()[0].clone();
286
- slot.lane_tx
287
- .lock()
288
- .as_ref()
289
- .expect("lane open")
290
- .send(test_ctx())
291
- .expect("lane has room");
292
- server.slots.read()[0].retire();
293
-
294
- // One item still assigned to this lane: serve it, not orphan it.
295
- assert!(matches!(after_timeout(&slot), Some(Some(_))));
296
- // Lane empty now: leave.
297
- assert!(matches!(after_timeout(&slot), Some(None)));
298
- }
299
-
300
- #[test]
301
- fn a_retired_lane_worker_drains_every_item_one_per_timeout() {
302
- let server = test_server(true, 4);
303
- server.register_worker();
304
- let slot = server.slots.read()[0].clone();
305
- for _ in 0..3 {
306
- slot.lane_tx
307
- .lock()
308
- .as_ref()
309
- .expect("lane open")
310
- .send(test_ctx())
311
- .expect("lane has room");
312
- }
313
- server.slots.read()[0].retire();
314
-
315
- for _ in 0..3 {
316
- assert!(matches!(after_timeout(&slot), Some(Some(_))));
317
- }
318
- assert!(matches!(after_timeout(&slot), Some(None)));
319
- }
320
-
321
- #[test]
322
- fn a_reset_slot_keeps_waiting_again() {
323
- let server = test_server(false, 4);
324
- server.register_worker();
325
- let slot = server.slots.read()[0].clone();
326
- slot.retire();
327
- assert!(matches!(after_timeout(&slot), Some(None)));
328
-
329
- slot.reset();
330
-
331
- assert!(after_timeout(&slot).is_none());
332
- }
333
- }