kino 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +286 -0
  4. data/Cargo.lock +209 -132
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +19 -3
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
data/doc/architecture.md CHANGED
@@ -11,13 +11,19 @@ tokio (Rust threads) Ruby
11
11
  └──────────────────────────┘ └────────────────────────────┘
12
12
  ```
13
13
 
14
- All network I/O lives in Rust on tokio runtimes; hyper parses HTTP/1.1 and
15
- handles keep-alive; rustls terminates TLS. The default is Tokio's
16
- multi-thread runtime. With `io_shards true`, one current-thread runtime
17
- accepts connections and assigns them to current-thread I/O shards, where
18
- each connection stays for its lifetime. Ruby never touches a socket. Each
19
- request becomes a Rust-side `RequestCtx` pushed to a bounded flume MPMC
20
- queue; Ruby workers pull from it.
14
+ All network I/O lives in Rust. On tokio runtimes, hyper parses HTTP/1.1
15
+ and handles keep-alive, and rustls terminates TLS. The default is
16
+ Tokio's multi-thread runtime. With `io_shards true`, one current-thread
17
+ runtime accepts connections and assigns them to current-thread I/O
18
+ shards, where each connection stays for its lifetime. Each request
19
+ becomes a Rust-side `RequestCtx` pushed to a bounded flume MPMC queue;
20
+ Ruby workers pull from it. On a `worker_loop` server, plain HTTP/1.1
21
+ connections are served inline instead: Kino's Rust code reads and writes
22
+ them on the worker threads, whose fibers wait on their descriptors
23
+ through the app's scheduler (see
24
+ [Inline connections](#inline-connections)). Ruby never reads, writes or
25
+ closes a client's socket: an app that hijacks a request gets a socket of
26
+ its own, which Kino bridges to the client's.
21
27
 
22
28
  ## Topology
23
29
 
@@ -42,8 +48,94 @@ Puma-style two-level: `workers × threads`.
42
48
  slot table never grows with churn. Both pools (the ractor supervisor
43
49
  and the threaded pool) expose the same grow/retire/groups seam.
44
50
  - Experimental `lanes true` replaces the one shared queue with a small
45
- private queue per worker slot (awake-preferring dispatch, work
46
- stealing); see [benchmarks](benchmarks.md#lane-dispatch-experimental-lanes-true).
51
+ private queue per worker slot (see [Lane dispatch](#lane-dispatch) and
52
+ [benchmarks](benchmarks.md#lane-dispatch-experimental-lanes-true)).
53
+ Native WebSockets need it: a lane also carries the bell that wakes its
54
+ worker for its sockets' events (see [WebSockets](#websockets)).
55
+ - `worker_loop` hands each worker thread to the app's own fiber
56
+ scheduler, which runs many requests at once there through Kino's
57
+ nonblocking takes (see [Worker loops](#worker-loops)). It runs on
58
+ lanes and turns them on.
59
+
60
+ ## Lane dispatch
61
+
62
+ With `lanes true` each worker slot has a lane of at most 4 requests,
63
+ or for a `worker_loop` worker as many as it has room for (its
64
+ `concurrency` less the requests it has open) when that is more, and
65
+ the tokio side picks one for each request:
66
+
67
+ 1. An awake lane with room (its worker is not parked), round-robin, so
68
+ a hot worker keeps taking without paying a futex wake; this step
69
+ fills a lane only to 4 requests, however deep it is. While a sibling
70
+ sits idle, a classic worker 100 µs or more into its current item (a
71
+ request, a socket event, a wake hook) is passed over: fast handlers
72
+ keep their hot lane, and past that, waking the sibling (tens of
73
+ microseconds) beats waiting out the rest. A `worker_loop` worker is
74
+ passed over while it holds a request at all: one it has not answered
75
+ yet (or a socket event, a wake hook), or one waiting in its lane.
76
+ What it runs after its answer, and its fibers that only wait, do not
77
+ count, so one client's requests in turn keep their hot lane. This
78
+ spreads a few clients over the workers instead of stacking them on
79
+ one, a trade: with four clients a page endpoint served about a fifth
80
+ more requests with a median about 15% lower, for a 99th percentile
81
+ about 40% higher and about a third more CPU per request (more
82
+ workers awake); at one client and at sixteen nothing moved.
83
+ 2. Else the idle worker with the fewest requests open, and of those the
84
+ one that parked last, whose caches are still warm. A classic worker
85
+ idles with none open; a `worker_loop` worker idles while its fibers
86
+ wait, so requests that wait spread over the workers instead of
87
+ piling onto the one that parked last. Only an empty lane qualifies,
88
+ so a burst into an idle server spreads instead of queueing behind
89
+ one worker.
90
+ 3. Else any lane with room, round-robin. A `worker_loop` lane fills
91
+ past 4 only here.
92
+
93
+ A `worker_loop` worker takes a request whenever its thread comes back
94
+ to its loop with a job slot free, so its lane may hold as many as it
95
+ has room for: a lane of 4 turned requests away from a worker with room
96
+ for them while its thread ran a job. A lane deeper than the room left
97
+ would hold requests its worker cannot start yet, behind long polls or
98
+ slow clients, while a sibling could. Dispatch reads the worker's loop,
99
+ not its fibers: a job the app leaves queued starts only once the loop
100
+ has parked the worker, which then reads idle and is sent requests that
101
+ wait behind those jobs. In a chat app on 8 workers, requests then
102
+ waited 2.0 ms in the scheduler before they started, against 0.02-0.03
103
+ ms when each job started at once.
104
+
105
+ With every lane full, on a `worker_loop` server, a request waits its
106
+ turn for room behind those that came before it, and gets a 503 if none
107
+ comes within `queue_timeout`. Only the first in line dispatches: a
108
+ worker that takes a request from a lane, parks, or drops below its
109
+ `concurrency` tells it to look again, and once it has gone in, the next
110
+ in line looks; a lane that gains room any other way (it deepens as its
111
+ worker answers below its `concurrency`) is seen at the next look, 50 ms
112
+ later at most. A newcomer lines up behind those waiting, so requests
113
+ that waited go in the order they came. While nobody waits, the signal
114
+ costs a worker's take one load. `queued` in the stats counts the
115
+ requests in line too. Without a `worker_loop` a request retries every
116
+ 500 µs instead, in whatever order the retries fall; requests retrying
117
+ do not count in `queued`. Measured against that retry on a
118
+ `worker_loop` server with every lane full, the line served the same
119
+ throughput with a 99th percentile 3 to 10 times lower and, with
120
+ hundreds waiting, less CPU; at 64 clients its median was higher.
121
+
122
+ Retired slots, and a crashed worker's slot until it is recycled, take
123
+ nothing. Workers steal from a sibling's lane before they park and on
124
+ every 50 ms tick while parked, so a request that reached a worker just
125
+ before its item turned slow waits for a sibling that runs out of work
126
+ of its own, at most until the next steal of an idle one. A worker that
127
+ a tick woke leaves a lane whose own worker idles on it, as the send
128
+ woke that one: taking its request would move one client's requests in
129
+ turn to a cold worker. (A `worker_loop` worker whose doorbell wait is a
130
+ tick overdue is away on a job, and its lane is not left to it.) A
131
+ WebSocket handshake tries the workers that own the fewest open sockets
132
+ first, in the same order.
133
+
134
+ In `:threaded` mode every worker shares one GVL, so passing a CPU-bound
135
+ request to an idle thread spreads the wait rather than shortening it:
136
+ with a 0.6 ms CPU-bound handler, 8 threads and 4 clients, throughput
137
+ and mean latency are unchanged, the median rises from 1.2 to 2.4 ms
138
+ and the 99th percentile falls from 56 to 3 ms.
47
139
 
48
140
  ## The Rust ↔ Ruby boundary
49
141
 
@@ -54,24 +146,74 @@ Puma-style two-level: `workers × threads`.
54
146
  (`Kino::Native::Request`, a TypedData object) is created *inside* the
55
147
  worker ractor by the take calls (`take_one`/`take_batch`), so its
56
148
  ownership is correct by construction.
57
- - **Blocking discipline:** every blocking native call goes through
58
- `rb_thread_call_without_gvl` (rb-sys; magnus doesn't wrap it) so a
59
- blocked worker holds no VM lock. Waits poll an atomic interrupt flag
60
- between bounded `recv_timeout` ticks; the unblock function (UBF) just
61
- sets the flag. `flume::Selector` lost wakeups under sustained load
149
+ - **Thread-safe frees:** on a Ruby with per-Ractor GC (4.1 and later), a
150
+ free not declared thread-safe waits in a process-wide batch run under
151
+ a VM barrier, and Kino frees a Request per request. So Kino's native
152
+ types (`Request`, `Conn`, `Worker` and `PinKeeper`, listed in
153
+ `typed_data.rs`) declare `RUBY_TYPED_THREAD_SAFE_FREE` where the Ruby
154
+ has it: their frees may run on any thread, without the VM lock, beside
155
+ other frees and Ractors. Each calls no Ruby API, reads no Ruby object,
156
+ touches only `Send` and `Sync` state, takes no lock held across a Ruby
157
+ call or a GVL release (whose holder may sweep right there, or wait on
158
+ a barrier for the free's thread), never panics, and never blocks or
159
+ waits (no join, no blocking send, no runtime dropped). A change to
160
+ those drops or to what they reach (`ServerInner`, `WorkerSlot`,
161
+ `InlineIo`, `Responder`, and the calls they make: `Doorbell::ring`,
162
+ `Logged::completion`, `serve_handed_back`) re-checks this;
163
+ `ws::Registration`'s drop may release the GVL, so it must never become
164
+ reachable from them.
165
+ - **Blocking discipline:** every blocking native call releases the GVL
166
+ through `rb_thread_call_without_gvl2` (rb-sys; magnus doesn't wrap it,
167
+ and a lint bars every other release or pass of the GVL, which would
168
+ raise past Rust frames) so a blocked worker holds no VM lock. Waits
169
+ poll an atomic interrupt flag between bounded `recv_timeout` ticks;
170
+ the unblock function (UBF) just sets the flag. A worker waiting for
171
+ its next request, and a request waiting on its client (a body read, a
172
+ streamed write), tell the shutdown, which raises the slot's halted
173
+ flag, from the VM's own unblocking (`Thread#wakeup`, `#run`, `#raise`,
174
+ `#kill`), which raises a flag of the wait's own:
175
+ then the wait runs its thread's pending interrupts in a protected call
176
+ and waits again, or raises what they raised, so no jump crosses Rust
177
+ frames and every borrow of the request is released on the way out. A
178
+ request a worker's wait took as the unblock function fired goes back
179
+ (to the shared queue, or the worker's lane) before those interrupts
180
+ run, so a raise cannot beat it to Ruby and lose it; one with no room
181
+ to go back is held while they run, and a raise answers it with a 500
182
+ at once. A WebSocket event goes to the worker as taken, and a raise
183
+ fires at Ruby's first interrupt check, before the event's callback,
184
+ so that event is lost (a message keeps its inbound credit, a shutdown
185
+ or close event never runs its callback); the socket's later events
186
+ keep their order.
187
+ `flume::Selector` lost wakeups under sustained load
62
188
  (workers went permanently deaf to a non-empty queue after ~100k
63
189
  requests) and is not used anywhere.
64
190
  - **Fast path:** when a request is already queued, `take_one` takes it
65
191
  with `try_recv` while still holding the GVL—the release/reacquire pair
66
192
  (two scheduler round-trips) is skipped entirely. Under load this is the
67
193
  common case.
194
+ - **Passing the GVL:** where worker threads share a GVL (every worker in
195
+ `:threaded` mode, a Ractor's `threads` past one), a worker that keeps
196
+ finding work would hold it until Ruby's 100 ms timer preempts it, most
197
+ often mid-request; under a backlog that request then waits for every
198
+ other worker's 100 ms (2.3 s with 8 × 3 threads), and a request handed
199
+ to a parked worker waits as long. So between two items a worker passes
200
+ the GVL, as `Thread.pass` does, once it has held it for 1 ms (2 or 5 ms
201
+ cost more throughput, for a longer wait); with no thread waiting, the
202
+ pass returns at once. A take judges the hold at its last item's start,
203
+ a clock read the slot already keeps (one of its own cost 1-2.5% of
204
+ throughput), so a worker holds the GVL for 1 ms plus an item, a batch
205
+ passes only before it, and a take that rides an answer takes nothing
206
+ when a pass is due, so the answered body closes first. A
207
+ `worker_loop`'s takes and an inline connection's next request read the
208
+ clock, and its hold runs from its last pass: its scheduler's waits go
209
+ unseen, so after one it may pass at once and wait a round of the line.
68
210
  - **Fused crossing:** the common complete-body response rides
69
211
  `respond_and_take_one`: answer the previous request and take the next in
70
212
  one FFI call, ~one crossing per request once the loop is warm. The env
71
213
  Hash carries the request handle under `env["kino.request"]`, so no
72
214
  per-request pair array exists either.
73
215
  - **Env construction:** one FFI call builds the full CGI side of the Rack
74
- env as a real Hash. Static keys, common methods/protocols and 44 common
216
+ env as a real Hash. Static keys, common methods/protocols and 46 common
75
217
  `HTTP_*` header names come from a frozen (and therefore Ractor-shareable)
76
218
  string cache built once at init on the main ractor. Frozen keys also
77
219
  skip the dup that `Hash#[]=` performs on unfrozen string keys. Only
@@ -81,15 +223,405 @@ Puma-style two-level: `workers × threads`.
81
223
  in place from rooted Ruby strings (safe: GVL held, hyper copies
82
224
  immediately). Single-chunk bodies skip the join copy.
83
225
 
226
+ ## Worker loops
227
+
228
+ What an app sees is in [worker-loop.md](worker-loop.md); this is how
229
+ it works inside.
230
+
231
+ A `worker_loop` worker's `serve` is Kino's loop written for the app's
232
+ fiber scheduler. It never blocks in native code: its takes do not wait,
233
+ and with nothing to take it waits on the worker's readiness descriptor,
234
+ which the scheduler turns into a fiber wait. A request's job runs the
235
+ classic loop's own code (the env, the app call, the response path,
236
+ upgrades, hijacks, hooks); jobs end in any order, so the fused
237
+ respond-and-take is not used. Apps without a `worker_loop` keep the
238
+ classic loop as it was.
239
+
240
+ **Readiness doorbell.** Each slot of a `worker_loop` server has a
241
+ doorbell: a nonblocking Unix socket pair and an armed flag. A take that
242
+ finds nothing arms it and looks once more, so a send that raced the arm
243
+ is taken now. Every lane send, the lane's close, and a socket event or
244
+ wake for a worker too full to read its lane ring it: a ring loads the
245
+ flag and, only if it is armed, swaps it off and writes one byte. A busy
246
+ worker never arms, so a send to it costs no syscall; an idle one costs
247
+ one write per wake-up, as a futex wake does in the classic loop. The
248
+ wait has no timeout, so the scheduler keeps no timer for it: one ticker
249
+ thread per server rings every armed doorbell each 50 ms, and the take
250
+ that answers is the lane tick a parked classic worker gets (a retired
251
+ worker's exit, a deferred wake, a steal).
252
+
253
+ **Takes.** The loop takes what it has room for: anything, in the
254
+ classic take's order; with every job slot busy, only socket events and
255
+ wakes (a full worker does not park, so dispatch does not read it as
256
+ idle); with its backlog of 64 taken events full, only requests, so the
257
+ inbox fills and pushes back on the sockets' readers. With room for one
258
+ kind only and none of it ready, the loop waits on its doorbell, which a
259
+ job that frees a slot or a backlog that drains also rings. Every take
260
+ also takes the inline connections placed on the worker (see
261
+ [Inline connections](#inline-connections)), so one placed just before
262
+ the worker filled up hands its first request to hyper rather than
263
+ wait for a job to end; with room for neither events nor requests,
264
+ the loop takes the placed connections alone, back every tick.
265
+
266
+ **Open requests.** A take with room prunes the slot's list of open
267
+ requests instead of resetting it, and answering a request prunes it
268
+ too, so dispatch sees the worker's load at once. A slot at its
269
+ `concurrency` is the exception: only its next take with room lowers the
270
+ count, as that take is what tells the request first in line for lane
271
+ room.
272
+
273
+ **Jobs.** Each request taken from the lane is a job, and so is each
274
+ inline connection, whose job runs its requests itself (see
275
+ [Inline connections](#inline-connections)). Socket events and wakes
276
+ queue in Ruby, per socket and for the wake hook: the first event of a queue starts a job that drains it in
277
+ order, and a socket's `on_open` holds its queue on the handshake's job.
278
+ At most one wake run waits beside the running one. Jobs report their
279
+ end through a queue the scheduler waits on: a request's job frees its
280
+ slot, and a socket's or the wake job that ended with events left fails
281
+ `serve`.
282
+
283
+ **Heartbeat.** Each time the thread comes back to its loop, the slot is
284
+ stamped with the time; going to wait on the doorbell stamps it one tick
285
+ ahead, as that wait is time in the loop until it is overdue. A worker
286
+ is busy while it has a request open or something waits for it, and its
287
+ `busy_ms` is the stamp's age. Whether the thread holds something right
288
+ now, which dispatch's pass-over reads, is a flag of its own: raised by
289
+ a take that hands it something, lowered as it answers that request or
290
+ comes back to its loop.
291
+
292
+ **Per-request bells.** Under any fiber scheduler, `rack.input` reads
293
+ and streamed writes take steps that never block: each returns its
294
+ result, or a descriptor to wait on. A request has two bells of the
295
+ doorbell's kind, opened by their first wait: one for the next body
296
+ chunk or the body's end, one for room in the response stream or its
297
+ end. A step arms its bell and looks once more before it hands out the
298
+ descriptor. The body forwarder rings the first after each chunk and
299
+ when it stops, and the response body rings the second each time hyper
300
+ takes a frame or drops it, so a read and a write of one request can
301
+ wait at once. The bells close when the job ends, or once the last wait
302
+ on them is back. Past the shutdown deadline a step that would wait
303
+ fails as interrupted, and what already waits is rung. An inline request
304
+ needs no bell: Kino reads its body whole before the app runs, and a streamed write that has to wait is
305
+ handed its connection's own descriptor (*Serving*, 3, under
306
+ [Inline connections](#inline-connections)).
307
+
308
+ ## Inline connections
309
+
310
+ What an app sees is in
311
+ [worker-loop.md](worker-loop.md#inline-connections); this is how it
312
+ works inside.
313
+
314
+ **Placement.** At accept, on the I/O thread, a plain TCP connection to a
315
+ `worker_loop` server, or one on its `unix://` bind, goes to a worker
316
+ picked under one lock, so two I/O threads never both take the least
317
+ loaded. A server with TLS has no inline side. Of the
318
+ workers whose `serve` started, with an open lane, fewer inline
319
+ connections than their `concurrency` and room for another request,
320
+ placement takes the one with the fewest inline connections, then the
321
+ fewest requests open, then the one that parked last, so a client that
322
+ connects anew for each request finds the worker that served its last
323
+ one. A worker at capacity, by the slot's count (see *Many requests per
324
+ slot* under [Worker loops](#worker-loops)), takes none, so with every
325
+ worker full a connection stays with hyper from accept, whose lanes line
326
+ its request up for room until `queue_timeout`, as they line up any
327
+ other. That counts as `declined`, and so does a connection whose worker
328
+ turns it down as it is sent (it retired, was quarantined or left its
329
+ slot, or its lane closed meanwhile). The connections a worker counts as
330
+ open leave out those whose answer is out until their job looks for the
331
+ next request, or steps aside just before (*Serving*, 4). The connection
332
+ reaches its worker through an inbox of its own beside the lane, which
333
+ no sibling's steal reads, ringing the worker's doorbell, and its socket
334
+ leaves tokio for the worker's scheduler.
335
+
336
+ A connection stays on its worker for its life unless it goes to hyper
337
+ (*Hand-back*): nothing moves one off a worker busy with slow requests.
338
+ Handing such a worker's connections to hyper was tried and did worse at
339
+ the 99th percentile, at 5 ms and at 20 ms of CPU a request, as the
340
+ requests it moved waited behind the slow ones in the lanes. Against the
341
+ lanes, inline cost 2-4% of the requests a second on pages of 270-850 µs
342
+ of CPU, as the lanes let whichever worker is free take the next request.
343
+ These and the measurements below ran in Docker, in an arm64 Linux VM on
344
+ an M1 Pro, with the server (4 workers) on 4 pinned CPUs.
345
+
346
+ A unix-socket connection is placed, served, timed and handed back as a
347
+ TCP one is. Rust peeks at it with `recv` and `MSG_PEEK` (std's peek for
348
+ a unix stream is not stable), a hand-back registers it with tokio as a
349
+ unix stream, and its env has the addresses hyper gives one:
350
+ `REMOTE_ADDR` 127.0.0.1, and `SERVER_PORT` 80 unless its Host names a
351
+ port.
352
+
353
+ **Serving.** A request on an inline connection crosses no thread:
354
+
355
+ 1. The worker's take hands Ruby the connection as a
356
+ `Kino::Native::Conn`, and the loop starts a job for it.
357
+ 2. The job asks `Conn#next_request(room)`. Rust first flushes what the
358
+ last answer left in the connection's buffer, then reads what the
359
+ socket has, nonblocking (but see 4), parses a head in the strict
360
+ subset, reads its body whole, and admits the request as hyper's are
361
+ admitted (the same `RequestCtx`, env and in-flight guard). With
362
+ nothing more to read or flush yet, it answers `:readable` or
363
+ `:writable`, and the job waits on the socket through the scheduler,
364
+ on an IO that never closes the descriptor.
365
+ 3. The app runs on the job. Its answer is encoded and written to the
366
+ socket nonblocking under the connection's lock, from whichever
367
+ thread answers: a complete one at once, a streamed one chunk by
368
+ chunk. What the socket does not take stays in the connection's
369
+ buffer for the job's next look, and a streamed write that finds the
370
+ socket still holding the last one hands its fiber the descriptor to
371
+ wait on (`[:writable, fd]`).
372
+ 4. The job looks for the next request, and the connection's state
373
+ decides whether it goes on, ends, or goes to hyper. Before its first
374
+ look after a request, if the answer went out whole, nothing of the
375
+ next request was read and another inline connection shares the
376
+ worker, the job steps aside once (`:yield`): the scheduler's `yield`
377
+ (io-event's selectors put the fiber on the ready list for the next
378
+ pass), else `kernel_sleep(0)`. Every fiber already ready runs first,
379
+ as async-http's server yields after each response. The step counts
380
+ as the look, for placement and as an idle wait (`Idle`, below), lest
381
+ a busy worker read emptier than it is during a burst of accepts. Then
382
+ that first look reads nothing and answers `:readable`, so a request
383
+ that came while the worker finished the last one runs behind the
384
+ worker's connections whose requests came first: io-event's kqueue
385
+ selector arms a socket anew as its job waits, and the step makes its
386
+ epoll selector, which keeps a socket registered level-triggered
387
+ within the wake-up that resumed it, re-register it too. A pipelined
388
+ request runs at once. The only inline connection on its worker skips
389
+ the step (there it cost 2.6% of the requests a second, for nothing),
390
+ as does an answer still going out. On requests that do almost
391
+ nothing, the step costs about 3% more CPU at 16 to 64 connections,
392
+ and took their 99th percentile at 64 connections down by 15%. While
393
+ the server drains, or once the worker is quarantined, the look reads
394
+ first, as either ends an idle connection unless a request came; a
395
+ retired worker's connection goes to hyper at that look.
396
+
397
+ **Spin.** The look's wait parks the worker's thread until the client's
398
+ next request wakes it, and waking a thread whose CPU went idle costs
399
+ tens of microseconds in a VM, on every request of a client that sends
400
+ its next at once. So the only inline connection on a worker with
401
+ nothing else to do first `poll`s its socket, waiting for nothing, for up
402
+ to 100 µs, with the GVL released (see
403
+ [The Rust ↔ Ruby boundary](#the-rust--ruby-boundary)). It runs under a
404
+ gate (at most half the CPUs' worth of requests in flight, as each keeps
405
+ up to two threads busy; no drain; a process that may use two CPUs or
406
+ more), with nothing open on
407
+ the worker or waiting for it, the worker neither retired nor
408
+ quarantined, and fewer connections spinning server-wide than the gate
409
+ lets requests be in flight; all of it is read again on every pass (the
410
+ lane and the inboxes, behind locks, every 8th). The VM's unblock
411
+ function stops a spin too, and what it saw is left to the job's wait,
412
+ where a `Thread#raise` meets it. A connection spins once per request it
413
+ read and once as it opens, never while an answer is owed, before the
414
+ look's lock, waiting on nothing as the drain and a quarantine see it.
415
+ A worker with `concurrency: 1` never spins: at capacity, it counts its
416
+ last request open until its next take.
417
+
418
+ A request the spin catches skips the job's wait, and so a pass of the
419
+ scheduler: the worker's other fibers wait. So a job reads at most 16
420
+ requests in a row through its spins, and for at most 1 ms from its last
421
+ wait; past either, a catch is left to the job's wait, on a socket that
422
+ reads ready already, with no park and no wake. A lone keep-alive client
423
+ got 22% more requests a second on a trivial route and 7% on a page,
424
+ every percentile better or tied, for about 8% more CPU per request; at
425
+ 16 connections nothing changed.
426
+
427
+ A spin that runs out costs its whole budget, so each connection backs
428
+ off on its own, with no timer, on its recent share of requests that came
429
+ within the spin (`inline::spin::Backoff`), an average
430
+ that weighs each chance 1/8: it spins while that share is at least
431
+ 9/16, and once in 32 chances otherwise, so a client that keeps coming
432
+ late pays one spin in 32 requests, about 3 µs of CPU per request. A
433
+ chance it skips counts by when its request was read: within 100 µs as
434
+ caught (the gap from that chance is the client's plus the wake), past
435
+ 200 µs as missed, between not at all, as the wake alone may have taken
436
+ it past; without that band, a client whose wake makes its gap look past
437
+ the budget would never come back. A lone client pausing 500 µs between
438
+ requests paid 1.6% more CPU per request, one with random gaps averaging
439
+ 500 µs 2.3%, and one pausing 5 ms tied. A skipped chance costs two clock
440
+ reads.
441
+
442
+ **Hand-back.** Anything outside the subset goes to hyper as its head is
443
+ parsed, before the app sees it; so does a request whose worker has no
444
+ room for it once it is read whole (reading a body takes none), and
445
+ every connection of a retired worker at its job's next look. The job
446
+ lets go of the socket, which is registered with tokio again on the I/O
447
+ runtime that accepted the connection, and hyper serves it from then on,
448
+ every byte read so far replayed to its codec first, so the request goes
449
+ through lane dispatch as any other. One handed over with too little
450
+ read for hyper-util's version sniff waits out what is left of its
451
+ header time (see [Intake deadlines](#intake-deadlines)), and one already
452
+ cut off is closed instead: hyper must not serve what was cut. Each
453
+ hand-back counts once, in one total, whatever sent it: a head outside
454
+ the subset ([worker-loop.md](worker-loop.md#what-goes-to-hyper) lists
455
+ it) or one httparse or the `http` crate refuse; a request read whole
456
+ while its worker runs `concurrency` requests; a retired worker's
457
+ connection; one placed on a worker that never took it (it crashed, was
458
+ quarantined or left its slot, or the queues closed); or one waiting idle
459
+ for its next request as its worker crashed or its job ended. An nginx
460
+ that speaks HTTP/1.0 to Kino, every request handed back, cost 13% of the
461
+ requests a second, for 23% more CPU, against hyper serving them all.
462
+
463
+ **Timeouts.** Nothing is timed per request: no timer in the app's
464
+ scheduler, no clock read. Each connection keeps its deadline in one
465
+ atomic, set from the server's inline clock, a microsecond stamp the
466
+ ticker moves on each TICK (50 ms), so a deadline costs a load and a
467
+ store and falls up to 50 ms either side of its mark: 15 s after the
468
+ accept or an answer's last byte, for the next head, and 30 s after a
469
+ body's last bytes. Each TICK the ticker reads the deadlines off every
470
+ worker's list and, once it let go of the lists, shuts down the socket of
471
+ a connection past its deadline that still waits on its client, which
472
+ wakes its job to close it: the client reads the end, and the app never
473
+ sees the request. One serving a request or writing an answer waits on
474
+ no client and is looked at again 15 s on; but on a worker that leaves
475
+ (retired, or quarantined), an answer's deadline moves on only as the
476
+ socket takes some of it, so a client that stopped reading cannot keep
477
+ the worker. While its worker is not quarantined, one whose client's
478
+ bytes wait unread, or whose job holds a whole request read, is passed
479
+ over until its job reads them. A cut between the job's read of a
480
+ request and its admission is found under the lock the request is
481
+ admitted under, as if it came first. With `request_timeout` set,
482
+ admission sets the deadline from a clock read instead (the one cost on
483
+ the request path), so the 504 is never early; the ticker claims the
484
+ unanswered request under the connection's lock and writes hyper's 504
485
+ with `connection: close`, now or never. The app runs on; its answer
486
+ goes nowhere, and a stream it starts ends at its first write.
487
+
488
+ **Lifecycle.** Only a connection's job, or the last write waiting on
489
+ it, closes its descriptor, until hyper takes the connection over; any
490
+ other thread at most shuts its socket down, which wakes the job, or
491
+ hands an idle connection of a crashed worker to hyper. A write that has
492
+ to wait on the socket (from any of the app's fibers or threads) is
493
+ handed the descriptor and counted out until its wait is back, and a job
494
+ that lets go meanwhile leaves the close to the last such wait, so no
495
+ wait meets a closed or reused descriptor. Either close puts the FIN
496
+ behind what the socket still holds of an answer and first reads off
497
+ what the client sent that nothing will read (up to 64 KiB): a close
498
+ with such bytes unread resets the connection, dropping the rest of the
499
+ answer. A connection's seat on its worker, its answered mark and its
500
+ `max_connections` permit are given back once, under its lock, by its
501
+ job or by the slot's abandonment. A connection joins its worker's list
502
+ only as `send_placed` hands it over, under the lane lock a crash
503
+ retires the slot under, so a crash never cuts one it would refuse. A
504
+ worker's handle, let go as it leaves its slot by any path, takes the
505
+ slot's capacity with it and hands what was placed and never taken to
506
+ hyper; a slot is recycled only once no inline connection counts on it.
507
+
508
+ **Events.** What an event does to a connection turns on what its job
509
+ last told the connection's lock it waits for (`Waits`): `Idle` while it
510
+ waits for a next request with nothing of it read, or steps aside just
511
+ before; `MidHead` while a kept-alive connection waits for the rest of
512
+ its next head; `Other` otherwise. The drain shuts down the sockets of
513
+ `Idle` and `MidHead` connections whose clients' bytes do not wait
514
+ unread, and a quarantine those of `Idle` ones, whatever came; a job
515
+ about to wait checks for both under the same lock. Every other
516
+ connection meets either at its job's next look. A retirement's look
517
+ comes as the worker's loop, its take loop over, closes the IO each job
518
+ waits on, which wakes a waiting fiber under a scheduler with
519
+ `fiber_interrupt` (Async has it; under one without, the job looks when
520
+ its client next sends, or at the idle deadline). A crash or the shutdown
521
+ deadline (`abandon_slot`) waits for no look: it answers every request
522
+ held, flushes each connection as far as the socket takes it and shuts it
523
+ down. A worker whose thread is killed crashes as one that raised does.
524
+ The table says what happens to each connection, and what it counts
525
+ where it is handed back (`handbacks`) or cut off (`closed`):
526
+
527
+ | The connection is | Drain | Retirement | Quarantine | Crash | Its job ends | Shutdown deadline |
528
+ |---|---|---|---|---|---|---|
529
+ | Placed, not taken yet | served at its job's first look if a request came, else closed; or to hyper as the queues close (`handbacks`) | to hyper (`handbacks`) | to hyper (`handbacks`) | to hyper (`handbacks`) | no job yet | to hyper (`handbacks`) |
530
+ | Waiting for a request, nothing of it read: new, between requests, or stepping aside | closed, unless its client's bytes came, which it reads first and serves if they make a request | to hyper at its job's next look (`handbacks`) | shut at once (`closed`) | to hyper, which serves a request just sent (`handbacks`) | to hyper (`handbacks`) | closed (`closed`) |
531
+ | Part of a request read: a head or a body | a first head or a body reads on and is served; a next head closes, unless more of it came, which it reads first and serves if that completes a request | to hyper at its job's next look, with what was read (`handbacks`) | reads on and is served, or is cut at its deadline (`closed`) | closed (`closed`) | closed (`closed`) | closed (`closed`) |
532
+ | Serving a request: the app runs, or its answer goes out | answered, then closed | answered, then to hyper with what came of the next request (`handbacks`) | answered, then closed (`closed` if its answer began before the quarantine) | a 500 or its stream cut, then closed (`closed`) | a 500 or its stream cut, then closed (`closed`) | a 500 or its stream cut, then closed (`closed`) |
533
+ | Answer out whole, its job not back yet | at its job's next look, a request that came is served, else closed | to hyper at its job's next look (`handbacks`) | at its job's next look, a request that came is served, else closed (`closed`) | closed (`closed`) | closed (`closed`) | closed (`closed`) |
534
+
535
+ A quarantine shuts a waiting connection with whatever its client sent
536
+ just then, a race a client that reuses a kept-alive connection meets
537
+ anyway, and retries. On a worker both retired and quarantined, the
538
+ quarantine's column holds only where it shuts a connection or ends an
539
+ answer; the rest go to hyper. A connection that is to go to
540
+ hyper while a write still waits on its socket is closed instead, and
541
+ counts as cut off.
542
+
543
+ **Counters.** A request served inline counts on its worker's slot, as
544
+ `served` does, and so do the spins its jobs end and the connections cut
545
+ off (`closed`, one total); a stats read sums the slots, whose counts
546
+ never start over. Hand-backs and `declined` are the server's, counted
547
+ once per connection. A cut counts once, by whichever look ends the
548
+ connection first, and not when it was ending already (an answer that
549
+ closes it, a 504) or is no longer its worker's. The access log writes an inline
550
+ request's arrival line as its job admits it, under the connection's
551
+ lock, so it comes before any completion line, and its completion line
552
+ where its answer begins, through the same nonblocking sink as hyper's
553
+ (a 504 or a give-up's 500 with no breakdown); with the log off, each end
554
+ costs one branch.
555
+
556
+ ### Recorded differences
557
+
558
+ Inline answers go out as hyper writes them, interim statuses, framing
559
+ refusals and lengths included, but for three differences, each over a
560
+ header an app should not set and all but the last on a streamed answer:
561
+
562
+ - A streamed answer's own `Transfer-Encoding` is dropped and Kino frames
563
+ the body itself, where hyper passes it on (`gzip, chunked`): the
564
+ framing is the server's to choose, and `Content-Encoding` goes out as
565
+ the app set it. On a complete answer both drop it.
566
+ - A streamed answer to a HEAD with both a `Content-Length` and a
567
+ `Transfer-Encoding` goes out with its length, where hyper, in one of
568
+ the two orders, refuses it and closes the connection.
569
+ - A `Connection` value that names `close` among bytes outside ASCII
570
+ closes the connection after the answer, where hyper cannot read it and
571
+ keeps the connection open.
572
+
573
+ A connection's first head is due 15 s after the accept, where hyper
574
+ gives 15 s for a first byte and 15 more for the head; a head over 16 KiB
575
+ goes to hyper part read and gets hyper's 15 s afresh. A client that ends
576
+ its side once its request is sent is answered inline (see
577
+ [Intake deadlines](#intake-deadlines)). The drain differs four ways:
578
+ a connection whose answer was whole before the drain, its job not back
579
+ yet, ends at its job's next look, where hyper ends it at once; one
580
+ placed and not taken yet ends at its job's first look or goes to hyper
581
+ as the queues close, where hyper ends it unless its client's bytes are
582
+ there; a new connection holding only a start of the h2 preface (or the
583
+ `P` of a `POST`) reads its head on, where hyper closes it; and a next
584
+ head past 16 KiB on a kept-alive connection ends unanswered, where
585
+ hyper reads it on. Only the last loses a request.
586
+
84
587
  ## Backpressure, in both directions
85
588
 
589
+ - The kernel's accept queue, ahead of all of Kino's own. The client
590
+ listener (TCP or unix) asks for the largest backlog there is, which
591
+ the kernel clamps, as Kino listens, to `net.core.somaxconn` on Linux
592
+ (4096 by default since 5.4; a container's own counts) or
593
+ `kern.ipc.somaxconn` on macOS (128), where Rust's standard library
594
+ alone would leave 128 and Linux would drop the SYNs of a connect
595
+ burst past it, their clients retrying a second later. While Kino is
596
+ not accepting (at `max_connections`, or with its accept loop held up),
597
+ up to that many clients finish their handshake and wait: overload
598
+ shows as a slow first byte rather than a slow connect, a health check
599
+ that only opens a TCP connection passes for longer, and the drain
600
+ resets every connection still in the queue. The control plane's TCP
601
+ listener keeps a queue of 128, so a probe of a stuck control thread
602
+ fails at connect.
86
603
  - Bounded request queue between tokio and Ruby. When it stays full past
87
604
  `queue_timeout`, the client gets an immediate 503 rather than waiting.
88
605
  - Request bodies stream through a bounded(8) channel: hyper is only polled
89
606
  as fast as Ruby consumes (inbound backpressure costs nothing extra).
90
607
  Bodyless requests (most GETs) spawn no forwarder task at all.
91
608
  - Response bodies stream through a bounded(8) channel the other way: a
92
- slow client makes `write_chunk` block—with the GVL released.
609
+ slow client makes `write_chunk` block—with the GVL released. A gone
610
+ client (hyper dropped the body: the client hung up, the connection
611
+ broke, an h2 stream was reset) disconnects the channel, and the next
612
+ write raises `Kino::ClientGone`, which the worker loop takes as the
613
+ normal end of the request.
614
+ - Giving up on a stream (a body that raised, a crashed worker, shutdown
615
+ past its deadline) never waits for room in that channel: the error
616
+ frame goes in if it fits, and either way a flag on the `Responder`
617
+ makes the body end in an error once hyper drains it, so a client that
618
+ stopped reading holds no thread. Only a body that returned finishes
619
+ its stream, so a truncated response never ends cleanly. A write still
620
+ waiting for room sees the flag within a tick and raises
621
+ `Kino::ClientGone`. The abort borrows the request handle no more than
622
+ a waiting write or read on another thread does, so it runs beside
623
+ them; only what needs the handle to itself (a hijack, accepting or
624
+ switching a WebSocket) raises then instead of panicking.
93
625
 
94
626
  ## Failure handling
95
627
 
@@ -98,11 +630,44 @@ first-claimant-wins flag on the per-request `Responder`:
98
630
 
99
631
  1. The app, via the worker loop (normal path; `StandardError` is rescued
100
632
  in Ruby and becomes a clean 500).
101
- 2. The supervisor: each worker ractor has a supervisor thread blocked in
102
- `Ractor#value`. A hard crash (any `Exception`) wakes it; it immediately
103
- 500s the crashed ractor's in-flight requests via a `Weak<Responder>`
104
- side table—not when GC eventually notices—and respawns the ractor
105
- with fresh slots.
633
+ 2. The crash path: a worker thread that dies of a hard crash (any
634
+ `Exception`, a `StandardError` that `Thread#raise` sends into it
635
+ while it waits for its next request, or its thread killed, which
636
+ no rescue sees but its loop's `ensure` does) 500s its in-flight
637
+ requests on its way out, via the
638
+ slot's in-flight list—not when GC eventually notices—and closes
639
+ its WebSockets with 1011. The requests that waited in its lane go to the
640
+ other workers' lanes, or, with no room in any, wait for some on the
641
+ I/O runtime as a new arrival does (up to `queue_timeout`, then the
642
+ 503 a new arrival gets, counted in `rejected`). That wait starts
643
+ `queue_timeout` over, by design, so behind workers that keep crashing
644
+ a client can wait longer than `queue_timeout`. Its inline connections
645
+ end as [Inline connections](#inline-connections) says. Only the
646
+ threads Kino kills itself, past the shutdown deadline, and those the
647
+ process kills as it exits, end no crash. Then it is replaced on a
648
+ slot from the pool's bank while its siblings serve on: in `:threaded`
649
+ mode by the pool, in `:ractor` mode by its ractor's main thread,
650
+ which asks the ractor's supervisor thread (on the main ractor) for
651
+ the slot. The supervisor reads those reports and `Ractor#monitor`'s
652
+ end notice from one port (a report has a class of its own: the notice
653
+ is a Symbol up to Ruby 4.0 and an Array from 4.1), and respawns a
654
+ ractor that dies as a whole. A worker that keeps crashing within a
655
+ second of starting, before it served a request, is respawned with a
656
+ doubling delay (0.1 s up to 5 s), each thread paced by its own
657
+ crashes.
658
+
659
+ A crashed worker's slot is retired under its lane lock (neither the
660
+ dispatcher nor inline placement picks it) and goes back to the bank,
661
+ which hands it to a later worker only once it is quiet: no socket
662
+ still owed its close, no hijacked or inline connection open, its last
663
+ worker's handle let go of it (so a late end never touches its
664
+ successor), not quarantined. Crashes
665
+ therefore do not grow the slot table, and with lanes a request that
666
+ arrives while the replacement starts waits for a worker, up to
667
+ `queue_timeout`. Each slot carries a
668
+ generation that moves on whenever a worker leaves it, and a waker, a
669
+ retirement or a quarantine names the generation it meant, so none of
670
+ them can reach the worker that took the slot over.
106
671
  3. A `Drop` guard on `RequestCtx` as the universal backstop (GC of an
107
672
  abandoned handle, teardown races). The Drop path never touches the Ruby
108
673
  API, so it is safe from any thread.
@@ -122,31 +687,129 @@ plain decrement after an `.await` would never run).
122
687
  `stop_accepting` → every live connection switches to graceful shutdown
123
688
  (finish the in-flight request, answer with `Connection: close` on
124
689
  HTTP/1 or GOAWAY on h2, take nothing new—so drains converge instead
125
- of chasing chatty keep-alive clients) → drain until queue + in-flight
126
- reach zero or the deadline passes → `close_queue` (idle workers see
127
- Disconnected and exit) →
128
- join workers → past deadline: abort remaining clients (a 500, or a
129
- connection abort mid-stream), interrupt blocked workers, reap
130
- stragglers → tear down the tokio runtime. Idempotent;
131
- a second INT/TERM force-exits.
690
+ of chasing chatty keep-alive clients) → say goodbye to every native
691
+ WebSocket (its worker runs `on_shutdown`, then a 1001 follows, the
692
+ sockets taking turns over a second) → drain until
693
+ queue + in-flight reach zero and every socket's `on_close` has reached
694
+ its worker, or the deadline passes → `close_queue` (idle workers see
695
+ Disconnected and exit; the bridges of hijacked connections that
696
+ switched protocols close, so an app serving one on its worker reads
697
+ EOF) → join workers (a crash they died of is not raised again) → past
698
+ deadline: abort remaining clients (a 500, or a connection abort
699
+ mid-stream), interrupt blocked workers, reap stragglers → close the
700
+ other hijack bridges (a long poll still unanswered gets a 503, and
701
+ shutdown waits up to 100 ms for the bridges to end and hyper to take
702
+ their answers) → tear down the tokio runtime → stop the control plane
703
+ → remove the pidfile. Idempotent, and one at a time: a call made
704
+ during a shutdown waits for it. A second INT/TERM force-exits.
705
+ `Server.run` (and so the `kino` executable and the Rack handler)
706
+ returns only once the shutdown has ended, and raises its error if a
707
+ step failed, so the process exits non-zero.
708
+
709
+ Process exit can then take about a second more, in Ruby's VM teardown,
710
+ when an app Ractor's main thread and another of its threads are both
711
+ blocked at exit (an event loop and a thread feeding it), or a worker
712
+ Ractor is still stuck past the deadline. Ending such app loops in an
713
+ `at_exit` hook avoids it.
714
+
715
+ ## Unix sockets
716
+
717
+ A `unix://` bind, the client listener's or the control plane's, tells a
718
+ live socket from a stale one by a connect that never waits. One that is
719
+ answered, or on Linux turned away by a full accept queue, refuses the
720
+ boot with "socket is in use"; one that is refused means a crashed
721
+ server left the file, which is unlinked and bound over. A path that
722
+ holds anything but a socket is refused, never unlinked. Shutdown removes
723
+ the socket file.
724
+
725
+ Nothing locks the path, which leaves two limits. On macOS a connect to
726
+ a full accept queue is refused as one to a stale file is, so a second
727
+ server booted on the path of a live one whose queue is full takes the
728
+ path over (on Linux it is refused). And two servers booted at the same
729
+ instant on a stale path may both bind it, the first left serving a
730
+ socket no path names. A `pidfile` the two share refuses the second boot
731
+ in both cases.
732
+
733
+ ## Intake deadlines
734
+
735
+ Before hyper serves a connection, Kino waits for enough of its client's
736
+ first bytes for hyper to choose a codec, as hyper-util's version sniff
737
+ has no timer: it waits for good on a connection that sends nothing, or
738
+ stops inside the 24-byte h2 preface. On TCP and unix connections that is
739
+ a nonblocking `recv` with `MSG_PEEK` of up to 24 bytes, enough once they
740
+ part from the preface (HTTP/1) or hold all of it (h2), or once the
741
+ connection ends. It is due 15 s after the accept, and past that the
742
+ connection closes unanswered (no 408), as at hyper's header timeout;
743
+ once the drain begins it closes at once unless enough is there. Then
744
+ hyper's own timer gives the head 15 s from when hyper starts reading it,
745
+ so a head is whole at most 30 s after the accept. That holds with
746
+ `http2 false` too, where the wait is what lets the drain close a fresh
747
+ connection at once: hyper's HTTP/1 codec keeps one to its header timeout.
748
+
749
+ A TLS handshake is due 10 s after the accept, and one whose client has
750
+ sent nothing closes at the drain. Then Kino serves the codec the client
751
+ chose by ALPN, with no sniff: for `http/1.1` the first byte is due 15 s
752
+ after the accept; for `h2`, whose codec has no preface timer either,
753
+ Kino reads the 24-byte preface itself within those 15 s and replays it.
754
+ Without ALPN it reads until the bytes tell HTTP/1 from h2. With
755
+ `http2 false` only HTTP/1 is offered. A client must speak what it
756
+ negotiated: the codec ends one that chose h2 and sends HTTP/1, or the
757
+ reverse, serving it nothing. An inline connection handed back with too
758
+ little read for the sniff waits out what is left of its header time the
759
+ same way, and what came is read onto what the worker read (a `recv` of
760
+ at most 24 bytes), so hyper starts with it: hyper's own first read of a
761
+ handed-back socket waits for tokio to report it readable, by when a
762
+ drain may have cancelled the sniff. A connection placed on a worker that
763
+ turned it down goes to hyper the same way, with nothing read.
764
+
765
+ A connection whose first bytes are in by the accept, as they mostly
766
+ are, pays one peek; one whose are not pays a timer and the readiness
767
+ wait hyper's first read would have made. Once hyper serves an h2
768
+ connection, the pings under [HTTP/2](#http2) take over.
769
+
770
+ A client that ends its side (a FIN, `shutdown(SHUT_WR)`) once its
771
+ request is sent is taken as gone, as nginx takes one (its 499): hyper's
772
+ HTTP/1 codecs keep half-close off, so an end read while a request is
773
+ served closes the connection unanswered and drops the request's future,
774
+ and a request still waiting for room in the queue or a lane leaves it.
775
+ One already queued runs, and its answer goes nowhere; an answer written
776
+ before hyper reads the end still goes out. A connection that ends
777
+ before a whole request closes at once with no app call. Inline, a whole
778
+ request then an end is answered and the connection closes after it, as
779
+ seeing the end before the app runs would take a peek per request.
132
780
 
133
781
  ## HTTP/2
134
782
 
135
- One connection builder serves every protocol: hyper-util's auto builder
136
- picks h2 by ALPN on TLS connections, by the 24-byte preface sniff on
137
- plaintext (prior-knowledge h2c), and HTTP/1.x otherwise; `http2 false`
138
- pins the HTTP/1 codec and skips the sniff entirely. Streams multiplex
139
- into the same bounded queue as keep-alive requests, so h2 concurrency
140
- is bounded by workers × threads exactly as h1's is, and the bounded
141
- body channels give per-stream backpressure for free: while the
142
- forwarder blocks, hyper withholds WINDOW_UPDATE and the client stalls.
783
+ Plaintext connections that hyper serves go through hyper-util's auto
784
+ builder, which picks h2 by the 24-byte preface sniff (prior-knowledge
785
+ h2c) and HTTP/1.x otherwise; TLS connections get the codec ALPN chose,
786
+ or without ALPN the one the preface tells (see
787
+ [Intake deadlines](#intake-deadlines)); `http2 false` pins the HTTP/1
788
+ codec and skips the sniff entirely. Streams multiplex into the same
789
+ bounded queue as keep-alive requests, so h2 concurrency is bounded by
790
+ workers × threads exactly as h1's is, and the bounded body channels give
791
+ per-stream backpressure for free: while the forwarder blocks, hyper
792
+ withholds WINDOW_UPDATE and the client stalls.
793
+
794
+ **Pings.** hyper's h2 side has no idle timer, so a peer that is gone (a
795
+ phone off the network, a dropped NAT mapping) would hold its connection
796
+ and its `max_connections` permit for good. Kino turns on hyper's
797
+ keep-alive: a connection that has sent no request and no request body
798
+ for 30 s gets a PING, and one that leaves it unanswered for 20 s is
799
+ closed, its open streams with it, during a drain too. A client that
800
+ answers keeps its connection, with or without a stream open: unlike an
801
+ idle HTTP/1 connection, which hyper closes at its 15 s header deadline,
802
+ an idle HTTP/2 one stays as long as its client likes, bounded by
803
+ `max_connections` or by a fronting proxy's own idle timeout.
143
804
 
144
805
  The env bridge fills SERVER_NAME/SERVER_PORT/HTTP_HOST from the request
145
806
  URI's `:authority` (h2 requests carry no Host header), through the same
146
- host LRU the Host-header path uses, keyed by the authority bytes;
147
- SERVER_PROTOCOL is the interned "HTTP/2". h2 trailer frames are dropped
148
- (Rack has no trailer surface), and the h2 codec itself rejects
149
- connection-ish headers before they can reach the env.
807
+ host LRU the Host-header path uses, keyed by the authority bytes and,
808
+ when they name no port, the local port, which becomes SERVER_PORT (a
809
+ process may serve a host on several ports); SERVER_PROTOCOL is the
810
+ interned "HTTP/2". h2 trailer frames are dropped (Rack has no trailer
811
+ surface), and the h2 codec itself rejects connection-ish headers before
812
+ they can reach the env.
150
813
 
151
814
  The upload path needed one h2-shaped fix: `read_body` drains every
152
815
  already-queued chunk in a single native call (one GVL round-trip and
@@ -176,6 +839,162 @@ Deferred until benchmarks justify it: slot-aware flow-control window
176
839
  grants (a memory/abuse lever, not a throughput one—the knob sweep
177
840
  showed windows don't gate upload throughput).
178
841
 
842
+ ## WebSockets
843
+
844
+ What an app sees, with every limit and close code, is in
845
+ [websockets.md](websockets.md); this is how it works inside.
846
+
847
+ **Claiming the connection.** hyper hands out one upgrade per request.
848
+ For an HTTP/1.1 request with an `Upgrade` header, the request's handler
849
+ takes it and spawns a task that holds it until the app claims the
850
+ connection, as a native socket or through `rack.hijack`, or answers
851
+ plainly (the task then ends); every other request pays one header
852
+ lookup.
853
+
854
+ **One worker per socket.** A native socket belongs to the worker slot
855
+ that accepted it: its callbacks run on that worker's thread, in order,
856
+ between its requests, so per-worker app state needs no lock. Each
857
+ socket runs as two tokio tasks. The reader hands the stream to
858
+ tungstenite's `WebSocketContext` (read side only, a 4 KiB read
859
+ buffer), which unmasks, joins fragments and enforces the message cap;
860
+ Kino answers pings and echoes closes itself and maps how reading ended
861
+ to its close code and cause. The writer drains the socket's queue,
862
+ bounded in frames and in bytes (counted from the write that queues a
863
+ data frame until the writer has written it), in vectored writes
864
+ straight from the queued frames, so a socket holds no write buffer.
865
+ Ruby holds only the socket's Integer id, so no TypedData crosses a
866
+ ractor, and a write is a lookup in one id-to-socket table.
867
+
868
+ **Inbox and bell.** A worker blocks on one queue only (waiting on two
869
+ would need a select, which loses wakeups), so its lane carries two kinds
870
+ of item: a request, or a bell. A socket's messages go into its worker's
871
+ bounded inbox, and one deduplicated bell goes into the lane to wake the
872
+ worker if it is parked. The take loop reads its inbox first, then a due
873
+ wake, then its lane, then steals. After eight events in a row, or one
874
+ wake, the worker owes its lane a look, so a socket that keeps sending
875
+ cannot hold requests or the wake hook up. A stealer that finds a
876
+ sibling's bell rings it again for its owner, so events never change
877
+ workers. A bell that meets a full lane is dropped: that worker is busy,
878
+ and it checks its inbox on every take and every 50 ms tick while
879
+ parked. A full inbox holds up the readers that feed it.
880
+
881
+ **Inbound credit.** The inbox is one FIFO per worker, so each socket
882
+ counts its unhandled messages: the reader takes a credit before it
883
+ reads a message and gets it back when Ruby is done with it (once
884
+ `on_message` returns or raises) or when an abandoned worker's inbox
885
+ drops it. Out of credit, the reader waits. The reader of a socket whose
886
+ worker was abandoned never waits, so it still reads the client's answer
887
+ to the 1011.
888
+
889
+ **Pings.** Each socket keeps the time its client was last heard from:
890
+ the reader's stream stamps it whenever a read brings bytes, and the
891
+ writer's when a write gets through after the connection made it wait
892
+ (only the client reading frees that room). A timer in the socket's task
893
+ queues each ping as a control frame outside the byte budget, and the
894
+ socket is dropped like an abort once the client has been silent for two
895
+ intervals and for one since the ping was written. A reader waiting on
896
+ its worker counts its client as heard from, and the task polls its
897
+ reader before its timer, so a pong that arrived as the deadline came
898
+ still counts.
899
+
900
+ **Flow control.** Each socket also counts its data frames from queue to
901
+ write (`ws.pending`). What the full queue refuses sets a flag bit in
902
+ that same counter; whoever sees the count at zero with the bit set
903
+ clears it and tells the worker: the writer after a batch, or the
904
+ refuser, which wakes the writer with an empty frame when the queue
905
+ emptied in between. One atomic holds both, so exactly one of them sees
906
+ the other. The writer never waits on the worker: a full inbox gets the
907
+ event from a task of its own.
908
+
909
+ **Handshakes.** A handshake goes to the live worker with the fewest
910
+ open sockets (ties keep the hot-lane order). Accepting registers the
911
+ socket and holds its 101 while `on_open` runs; the 101 then goes out
912
+ with the frames `on_open` queued behind it. Any other answer to an
913
+ accepted handshake (a 500, a `request_timeout` 504, the Drop backstop's
914
+ 500) ends the socket and closes the connection.
915
+
916
+ **Topics and the fan-out thread.** `publish` copies topic and body into
917
+ a queue bounded at 65,536 publishes and 64 MiB, and returns. One native
918
+ thread takes publishes in order and, under the topic registry's read
919
+ lock, builds one frame per distinct envelope and queues refcounted
920
+ clones of it to every subscriber, never waiting for room: a full
921
+ subscriber is skipped or dropped through an out-of-band abort, never
922
+ through its own queue. The socket table and the topic registry are
923
+ never locked together, so a write never waits behind a fan-out. A
924
+ subscribe marks its socket subscribed under the registry lock and then
925
+ checks it is not gone; an unregistering socket marks itself gone and
926
+ then forgets its subscriptions only if it is subscribed. One of the two
927
+ sees the other's mark, so a racing subscribe gives up or is undone, and
928
+ a socket that never subscribed closes without the registry lock. A
929
+ Ruby thread that changes the registry while a fan-out holds it waits
930
+ with the GVL released: one blocked with the GVL held would stop its
931
+ ractor's other threads and, unable to reach a VM barrier, every ractor
932
+ at the next GC.
933
+
934
+ **The wake hook.** It rides the same bell: a wake sets a flag on the
935
+ slot and rings, so wakes before the hook runs coalesce into one take.
936
+ The waker names its slot's generation, so it wakes nothing once its
937
+ worker has left the slot. A park right after a wake-only take keeps the
938
+ worker's place in the hot-lane order, so periodic wakes do not reorder
939
+ dispatch.
940
+
941
+ **The hijack bridge.** A full hijack creates a Unix socket pair: Ruby
942
+ gets one end as a real IO, the bridge keeps the other. The bridge reads
943
+ the app's response head (httparse; at most 16 KiB and 100 headers, else
944
+ a 502) and replays it through hyper, which keeps TLS working. On a 101
945
+ it waits for hyper's upgrade and copies bytes both ways; any other head
946
+ must carry a Content-Length (all digits; repeated values must agree),
947
+ and the bridge streams that many bytes as the body, with
948
+ `Connection: close`. An answer that has no body (a 204, a 304, the
949
+ answer to a HEAD) needs no Content-Length. A hijacked request leaves
950
+ `in_flight` when the app takes it over: the hijack and the end of the
951
+ request's handler race on one flag on the responder, so the count drops
952
+ once. A 101 answered with a callable takes the same bridge, its head
953
+ handed over rather than written.
954
+
955
+ The drain closes the bridges in two steps, through one level on the
956
+ server that only rises. A switched bridge closes with the queues: its
957
+ exchange is over, and an app serving it on its worker must see EOF for
958
+ that worker to stop. Every other bridge closes once the workers have
959
+ stopped, so an app still on its worker gets to answer, and one still
960
+ unanswered then gets a 503. So does one whose app's end closes without
961
+ a word once requests have drained: a leaving worker Ractor's objects
962
+ are collected as it ends (on Ruby 4.1 at once, on 4.0 by the next GC).
963
+ Before that, such a close gets a 502. Once the workers have stopped,
964
+ the runtime may not have seen what an app wrote, so the bridge reads it
965
+ straight from the socket: an answer whose head had not gone out goes
966
+ out from memory if it is whole within the first MiB read, else the
967
+ request gets the 503; a body under way takes what is there, and is cut
968
+ if that falls short. Each bridge counts as running until hyper has
969
+ taken its answer (the count rides in the response's extensions and in a
970
+ streamed body, which hyper drops in the poll that writes them), and
971
+ teardown waits up to 100 ms for the count to reach zero. The
972
+ `max_connections` permit, and on an I/O shard the connection's load
973
+ count, travel inside the connection's stream wrapper, so an upgraded
974
+ connection keeps both for as long as it lives.
975
+
976
+ **Lifecycle.** Each slot counts the sockets whose `on_close` its worker
977
+ is still owed; the drain waits for those counts to reach zero. The
978
+ drain's goodbye runs in each socket's own task: told to leave with its
979
+ turn in the spread (evenly spaced by socket id), it hands the worker a
980
+ shutdown event when the handler has `on_shutdown`, waits for the
981
+ worker's word that it ran (or for the slot to be abandoned), and queues
982
+ the 1001 once both that and its turn have come. An abandoned slot's
983
+ events are dropped from then on; a slot handed to a new worker closes
984
+ whatever the last one left. A retirement that races a new socket closes
985
+ it, and the worker stays until that close has reached it.
986
+
987
+ **Counters.** The WebSocket counters are process-wide relaxed atomics
988
+ on paths sockets take anyway: the writer adds each batch's frames and
989
+ bytes, the reader's stream each read's bytes. Each socket keeps why it
990
+ ends in one atomic, and the first cause recorded stands: whoever asks
991
+ for the end records it before waking the socket's task, and the task
992
+ records what it saw itself. The registration counts the close under
993
+ that cause as it unregisters, then stops counting it open, so a
994
+ snapshot that reads none open has read every close. A streamed response
995
+ counts as cut once, on its responder's cut flag, unless its head says
996
+ it carries no body or never went out because Kino had answered first.
997
+
179
998
  ## Timer waits: `Kino.sleep`
180
999
 
181
1000
  MRI's `sleep` parks the thread on the VM timer, whose wakeups inside
@@ -211,9 +1030,9 @@ at the interrupt tick so `Thread#kill` and shutdown stay responsive.
211
1030
  feature-flag spike if the Linux plaintext ceiling ever matters
212
1031
  competitively.
213
1032
  - **io_uring path**: tokio ships in-tree io_uring as an unstable feature
214
- (file ops as of 1.52; network expected to follow). `server.rs` isolates
215
- the runtime, so adopting it later is a contained change—and would
216
- deliver most of ntex/neon's win without the type seam.
1033
+ (file ops as of 1.52; network expected to follow). The `server` module
1034
+ isolates the runtime, so adopting it later is a contained change—and
1035
+ would deliver most of ntex/neon's win without the type seam.
217
1036
 
218
1037
  ## Versioning of risky dependencies
219
1038