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.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +281 -0
- data/Cargo.lock +164 -95
- data/README.md +269 -438
- data/doc/README.md +27 -2
- data/doc/architecture.md +862 -43
- data/doc/benchmarks.md +444 -214
- data/doc/configuration.md +215 -0
- data/doc/operations.md +258 -0
- data/doc/rails-on-ractors.md +161 -49
- data/doc/streaming.md +52 -0
- data/doc/websockets.md +469 -0
- data/doc/why-kino.md +6 -6
- data/doc/worker-loop.md +462 -0
- data/ext/kino/Cargo.toml +17 -1
- data/ext/kino/build.rs +32 -1
- data/ext/kino/clippy.toml +10 -0
- data/ext/kino/src/access_log.rs +70 -92
- data/ext/kino/src/control.rs +26 -685
- data/ext/kino/src/counters.rs +132 -0
- data/ext/kino/src/cpus.rs +1 -18
- data/ext/kino/src/dispatch/tests.rs +731 -0
- data/ext/kino/src/dispatch.rs +276 -0
- data/ext/kino/src/doorbell.rs +108 -0
- data/ext/kino/src/env_strings.rs +26 -30
- data/ext/kino/src/framing.rs +110 -0
- data/ext/kino/src/gvl.rs +292 -66
- data/ext/kino/src/hijack/tests.rs +416 -0
- data/ext/kino/src/hijack.rs +471 -0
- data/ext/kino/src/inline/answer.rs +488 -0
- data/ext/kino/src/inline/conn.rs +1124 -0
- data/ext/kino/src/inline/deadline.rs +421 -0
- data/ext/kino/src/inline/encode.rs +119 -0
- data/ext/kino/src/inline/io.rs +487 -0
- data/ext/kino/src/inline/mod.rs +766 -0
- data/ext/kino/src/inline/parity.rs +862 -0
- data/ext/kino/src/inline/parse.rs +131 -0
- data/ext/kino/src/inline/spin.rs +428 -0
- data/ext/kino/src/inline/testing.rs +628 -0
- data/ext/kino/src/io_shards.rs +240 -192
- data/ext/kino/src/lane_room.rs +99 -0
- data/ext/kino/src/lib.rs +139 -77
- data/ext/kino/src/listen.rs +180 -12
- data/ext/kino/src/log.rs +12 -47
- data/ext/kino/src/logsink.rs +3 -9
- data/ext/kino/src/mono.rs +12 -17
- data/ext/kino/src/pin.rs +3 -3
- data/ext/kino/src/queue/mod.rs +54 -0
- data/ext/kino/src/queue/take.rs +503 -0
- data/ext/kino/src/queue/testing.rs +107 -0
- data/ext/kino/src/queue/tests.rs +581 -0
- data/ext/kino/src/queue/worker.rs +501 -0
- data/ext/kino/src/registry.rs +168 -379
- data/ext/kino/src/request.rs +834 -235
- data/ext/kino/src/response.rs +532 -94
- data/ext/kino/src/server/accept.rs +322 -0
- data/ext/kino/src/server/config.rs +138 -0
- data/ext/kino/src/server/handle.rs +247 -0
- data/ext/kino/src/server/intake.rs +217 -0
- data/ext/kino/src/server/mod.rs +157 -0
- data/ext/kino/src/server/natives.rs +223 -0
- data/ext/kino/src/server/serve/intake_tests.rs +458 -0
- data/ext/kino/src/server/serve.rs +436 -0
- data/ext/kino/src/server/tests.rs +532 -0
- data/ext/kino/src/shared_gvl.rs +50 -0
- data/ext/kino/src/slot/lane.rs +138 -0
- data/ext/kino/src/slot/life.rs +111 -0
- data/ext/kino/src/slot/load.rs +193 -0
- data/ext/kino/src/slot/mod.rs +494 -0
- data/ext/kino/src/slot/park.rs +82 -0
- data/ext/kino/src/stats.rs +936 -0
- data/ext/kino/src/symbols.rs +66 -0
- data/ext/kino/src/test_support.rs +24 -14
- data/ext/kino/src/testing.rs +409 -0
- data/ext/kino/src/ticker.rs +87 -0
- data/ext/kino/src/timer.rs +4 -7
- data/ext/kino/src/tls.rs +101 -131
- data/ext/kino/src/typed_data.rs +131 -0
- data/ext/kino/src/upgrade.rs +77 -0
- data/ext/kino/src/ws/codec.rs +470 -0
- data/ext/kino/src/ws/drive.rs +600 -0
- data/ext/kino/src/ws/handshake.rs +267 -0
- data/ext/kino/src/ws/mod.rs +317 -0
- data/ext/kino/src/ws/server_tests.rs +759 -0
- data/ext/kino/src/ws/socket.rs +279 -0
- data/ext/kino/src/ws/stats.rs +88 -0
- data/ext/kino/src/ws/testing.rs +156 -0
- data/ext/kino/src/ws/topics.rs +550 -0
- data/lib/kino/cli.rb +100 -9
- data/lib/kino/configuration.rb +32 -10
- data/lib/kino/crash_backoff.rb +56 -0
- data/lib/kino/input.rb +36 -17
- data/lib/kino/log.rb +8 -1
- data/lib/kino/monitor.rb +1 -1
- data/lib/kino/pool.rb +169 -0
- data/lib/kino/pool_scaler.rb +12 -13
- data/lib/kino/quarantine_monitor.rb +3 -3
- data/lib/kino/ractor_supervisor.rb +201 -161
- data/lib/kino/server.rb +291 -185
- data/lib/kino/slot_bank.rb +21 -9
- data/lib/kino/stream.rb +2 -2
- data/lib/kino/teardown.rb +33 -0
- data/lib/kino/templates/kino.rb.tt +41 -6
- data/lib/kino/threaded_pool.rb +87 -102
- data/lib/kino/version.rb +1 -1
- data/lib/kino/web_socket.rb +125 -0
- data/lib/kino/worker/loop.rb +319 -0
- data/lib/kino/worker.rb +345 -79
- data/lib/kino/worker_hooks.rb +7 -1
- data/lib/kino/worker_row.rb +15 -0
- data/lib/kino.rb +27 -3
- data/lib/rackup/handler/kino.rb +1 -1
- data/sig/kino.rbs +93 -10
- metadata +66 -3
- data/ext/kino/src/queue.rs +0 -333
- data/ext/kino/src/server.rs +0 -1785
data/doc/worker-loop.md
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
# Fibers inside Kino workers: `worker_loop` (experimental)
|
|
2
|
+
|
|
3
|
+
Kino's own loop runs one request at a time on each worker thread, so a
|
|
4
|
+
request that waits (on a database permit, an upstream API, a slow
|
|
5
|
+
client) holds its worker until it is done. `worker_loop` lets your app
|
|
6
|
+
run its own fiber scheduler on every Kino worker thread, in both modes.
|
|
7
|
+
Kino hands the scheduler each request as a job: a request that waits
|
|
8
|
+
suspends only its fiber, and the worker takes the next one meanwhile.
|
|
9
|
+
Kino keeps the Ractors, the threads, dispatch and all of HTTP. It ships
|
|
10
|
+
no scheduler and depends on none: Async is the example on this page,
|
|
11
|
+
and any `Fiber::Scheduler` works. How it works inside is in
|
|
12
|
+
[architecture.md](architecture.md#worker-loops).
|
|
13
|
+
|
|
14
|
+
Turn it on when your requests spend their time waiting and you want
|
|
15
|
+
many of them on one worker, or when your app is fiber-native already.
|
|
16
|
+
For requests that never wait, Kino's own loop stays the leaner path
|
|
17
|
+
(see [Per-request cost](#per-request-cost)). A request on an
|
|
18
|
+
[inline connection](#inline-connections) gets no fiber of its own: its
|
|
19
|
+
connection's job runs it.
|
|
20
|
+
|
|
21
|
+
## Setting it up
|
|
22
|
+
|
|
23
|
+
```ruby
|
|
24
|
+
# kino.rb
|
|
25
|
+
require "async"
|
|
26
|
+
|
|
27
|
+
threads 1
|
|
28
|
+
worker_loop Ractor.shareable_proc { |worker|
|
|
29
|
+
Sync do |task|
|
|
30
|
+
# This worker's own background tasks, if any, start here as
|
|
31
|
+
# transient tasks (see "Background work" below).
|
|
32
|
+
worker.serve(concurrency: 32) { |job| task.async { job.call } }
|
|
33
|
+
end
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or pass `worker_loop:` to `Kino::Server.new`. The sample config that
|
|
38
|
+
`kino --init` writes has the same example, commented out.
|
|
39
|
+
|
|
40
|
+
- Kino calls the proc once on each worker thread, after
|
|
41
|
+
`after_worker_boot`, with that worker's `Kino::Worker::Loop`. In
|
|
42
|
+
`:ractor` mode it runs inside the worker Ractor, so build it with
|
|
43
|
+
`Ractor.shareable_proc`: with a plain block, `:auto` mode falls back
|
|
44
|
+
to `:threaded` with a warning, and `mode :ractor` refuses to start.
|
|
45
|
+
- `worker.serve(concurrency:) { |job| ... }` is Kino's loop, written for
|
|
46
|
+
a scheduler: without one on the thread it raises `ArgumentError`.
|
|
47
|
+
`concurrency` is a positive Integer, the most requests the worker
|
|
48
|
+
runs at once.
|
|
49
|
+
- The block starts each job on the scheduler, and must run it at once
|
|
50
|
+
until it first waits, as `task.async { job.call }` does under Async
|
|
51
|
+
(and `Fiber.schedule { job.call }` under any scheduler); see
|
|
52
|
+
[Dispatch](#dispatch). Jobs must run on the worker thread, as fibers
|
|
53
|
+
of its scheduler: never hand one to another thread or a thread pool.
|
|
54
|
+
- `serve` returns `nil` once the worker is drained (the server shuts
|
|
55
|
+
down, or the elastic pool retires the worker) and every job has
|
|
56
|
+
finished. Let the proc return only after `serve` has: Kino treats an
|
|
57
|
+
earlier return as a crash (`Kino::Error`, "worker_loop returned
|
|
58
|
+
before its worker was drained"), and a new worker takes its place.
|
|
59
|
+
- `worker_loop` turns `lanes` on; `lanes false` with a `worker_loop`
|
|
60
|
+
raises `ArgumentError`. `batch` has no effect, and Kino warns when it
|
|
61
|
+
is set.
|
|
62
|
+
- `threads 1` is the natural setting: the fibers are the concurrency.
|
|
63
|
+
For parallelism, raise `workers` in `:ractor` mode; in `:threaded`
|
|
64
|
+
mode every loop shares the GVL.
|
|
65
|
+
|
|
66
|
+
## What runs where
|
|
67
|
+
|
|
68
|
+
Everything on a worker still runs on its one thread, so nothing on it
|
|
69
|
+
runs in parallel; requests, WebSocket callbacks and the wake hook
|
|
70
|
+
interleave wherever one of them waits. State they share across a wait
|
|
71
|
+
needs the care any fiber-concurrent code needs.
|
|
72
|
+
|
|
73
|
+
### Requests
|
|
74
|
+
|
|
75
|
+
Each request that comes through the worker's lane is one job (an inline
|
|
76
|
+
connection's requests run on its job instead: see
|
|
77
|
+
[Inline connections](#inline-connections)), which does what Kino's own
|
|
78
|
+
loop does for a request, from the env to `after_request_complete`. A job
|
|
79
|
+
raises into your scheduler only when Kino's own handling failed, after
|
|
80
|
+
the client got its 500. Stopping a request's job from outside aborts its
|
|
81
|
+
request (a 500, or a cut connection mid-stream) and frees its slot.
|
|
82
|
+
|
|
83
|
+
`concurrency` counts a request from the moment the loop takes it until
|
|
84
|
+
its job ends, `after_request_complete` included. A native WebSocket
|
|
85
|
+
handshake is a request like any other; the socket's events then go to
|
|
86
|
+
a job of their own (below). A request stops counting before its job
|
|
87
|
+
ends only when the app takes its connection over: a full `rack.hijack`,
|
|
88
|
+
or a 101 answered with a callable (a partial hijack, or a Rack 3
|
|
89
|
+
streaming body). A partial hijack with any other status is a streamed
|
|
90
|
+
response and counts until it ends. With `concurrency` requests running,
|
|
91
|
+
the loop takes no more requests, though it keeps taking socket events
|
|
92
|
+
and wakes.
|
|
93
|
+
|
|
94
|
+
### What carries over between requests
|
|
95
|
+
|
|
96
|
+
Requests run on fibers that outlive them: every request a worker takes
|
|
97
|
+
in Kino's own loop runs on its thread, every request of an
|
|
98
|
+
[inline connection](#inline-connections) on that connection's job, and
|
|
99
|
+
under the [runner recipe](#per-request-cost) every request a runner
|
|
100
|
+
takes on that runner. So fiber-local state one request sets
|
|
101
|
+
(`Thread.current[]`, `Fiber[]`, task-local state) is still there for a
|
|
102
|
+
later one, which can be another client's (on an inline connection,
|
|
103
|
+
behind a proxy that reuses its connections to Kino). Kino resets none
|
|
104
|
+
of it: reset what you set, per request, as on any server that reuses
|
|
105
|
+
threads; Rails' executor resets its own state. Only a request on a new
|
|
106
|
+
task (each lane request under the spawn block above; under the recipe,
|
|
107
|
+
one that starts a runner or finds every runner busy) begins with a
|
|
108
|
+
fiber of its own, its `Fiber[]` a copy of the loop's.
|
|
109
|
+
|
|
110
|
+
### WebSockets
|
|
111
|
+
|
|
112
|
+
- Each socket's events run one at a time and in order, on a job of
|
|
113
|
+
their own while the socket has any. Different sockets' callbacks run
|
|
114
|
+
concurrently: an `on_message` that waits holds up only its own
|
|
115
|
+
socket. Socket jobs do not count toward `concurrency`.
|
|
116
|
+
- `on_open` runs on the handshake's job, before the client gets the
|
|
117
|
+
101. Events that arrive meanwhile wait behind it, even when the
|
|
118
|
+
handshake timed out (`request_timeout`) while `on_open` ran.
|
|
119
|
+
`on_close` is the socket's last event.
|
|
120
|
+
- A worker's loop holds at most 64 socket events and wakes it has taken
|
|
121
|
+
and not yet done. At that many it takes only requests until some are
|
|
122
|
+
done, and Kino pushes back on the sockets' clients meanwhile. At most
|
|
123
|
+
16 of one socket's messages wait or run at once, so one flooding
|
|
124
|
+
socket never fills the backlog alone.
|
|
125
|
+
- A callback that raises is handled as in Kino's own loop, and the
|
|
126
|
+
events behind it keep running.
|
|
127
|
+
|
|
128
|
+
Everything else in [websockets.md](websockets.md) holds under a
|
|
129
|
+
`worker_loop` too: flow control, topics, limits, pings and the drain's
|
|
130
|
+
goodbye.
|
|
131
|
+
|
|
132
|
+
### The wake hook
|
|
133
|
+
|
|
134
|
+
`Kino::Worker.on_wake` works as in Kino's own loop: register it in
|
|
135
|
+
`after_worker_boot`, or in the `worker_loop` proc before `serve`. Its
|
|
136
|
+
runs go on a job of their own, alongside requests and socket callbacks
|
|
137
|
+
rather than between them, and never two at once: wakes that come while
|
|
138
|
+
it runs fold into one more run. The wake job does not count toward
|
|
139
|
+
`concurrency`.
|
|
140
|
+
|
|
141
|
+
### Background work
|
|
142
|
+
|
|
143
|
+
Background work that belongs to a worker can run as tasks on its
|
|
144
|
+
scheduler, started inside the `Sync` block before `serve`. Start them
|
|
145
|
+
transient, or stop them once `serve` has returned:
|
|
146
|
+
|
|
147
|
+
```ruby
|
|
148
|
+
Sync do |task|
|
|
149
|
+
task.async(transient: true) { loop { MyApp.flush; sleep 1 } }
|
|
150
|
+
worker.serve(concurrency: 32) { |job| task.async { job.call } }
|
|
151
|
+
end
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`Sync` waits for every task that is not transient, so a periodic task
|
|
155
|
+
started with a plain `task.async` would keep the worker from returning
|
|
156
|
+
after a drain: shutdown would wait out `shutdown_timeout`, and a
|
|
157
|
+
retired worker would never leave. Kino logs a warning for each worker
|
|
158
|
+
whose `worker_loop` still runs a second after its `serve` returned.
|
|
159
|
+
|
|
160
|
+
### Jobs your scheduler stops
|
|
161
|
+
|
|
162
|
+
A socket's job and the wake job carry events Kino has already taken
|
|
163
|
+
from the worker's queues. When your scheduler stops one of them before
|
|
164
|
+
its events are done, nothing else would run those events, so `serve`
|
|
165
|
+
raises `Kino::Error` ("a worker_loop job ended before its socket events
|
|
166
|
+
or wakes were done"), and the worker crashes and is replaced.
|
|
167
|
+
|
|
168
|
+
## Waiting the right way
|
|
169
|
+
|
|
170
|
+
Whatever waits through the scheduler suspends only its fiber:
|
|
171
|
+
|
|
172
|
+
- `sleep`, Ruby's socket and pipe I/O, `Thread::Queue#pop`, `Mutex`, and
|
|
173
|
+
the scheduler's own primitives;
|
|
174
|
+
- Kino's body I/O: `rack.input` reads, and the writes of a streamed
|
|
175
|
+
response (an enumerable body, or a Rack 3 stream). On a request that
|
|
176
|
+
came through hyper, while the client is slower than the app, the fiber
|
|
177
|
+
waits on a descriptor and costs no wake-ups meanwhile. Each such
|
|
178
|
+
request holds up to four descriptors that `max_connections` does not
|
|
179
|
+
count: near the open-file limit, many slow clients can run the process
|
|
180
|
+
out of descriptors, and a wait then raises an `IOError` in the app.
|
|
181
|
+
Leave room for them in `ulimit -n`. On an
|
|
182
|
+
[inline connection](#inline-connections), Kino reads the body whole
|
|
183
|
+
before the app runs, so `rack.input` never waits, and a streamed write
|
|
184
|
+
waits on the connection's own socket.
|
|
185
|
+
|
|
186
|
+
Whatever blocks the thread instead holds every fiber on the worker:
|
|
187
|
+
|
|
188
|
+
- `Kino.sleep`, which waits on the OS clock: use `sleep` under a
|
|
189
|
+
`worker_loop`;
|
|
190
|
+
- a C extension call that blocks without going through the scheduler
|
|
191
|
+
(some database drivers do);
|
|
192
|
+
- CPU-bound work, and anything inside `Fiber.blocking { }`.
|
|
193
|
+
|
|
194
|
+
Body I/O otherwise behaves as in Kino's own loop. A write raises
|
|
195
|
+
`Kino::ClientGone` once the client has gone or Kino has cut the stream
|
|
196
|
+
(see [Streaming responses](streaming.md#streaming-responses)), and a
|
|
197
|
+
body read still waiting on its client when shutdown passes its deadline
|
|
198
|
+
raises `RuntimeError` ("Kino: request interrupted during shutdown").
|
|
199
|
+
Beyond that:
|
|
200
|
+
|
|
201
|
+
- While a thread of the app's own waits to read a request's body, the
|
|
202
|
+
connection cannot change hands under that read: `rack.hijack` raises
|
|
203
|
+
an `IOError`, and a native WebSocket handshake or a 101 with a
|
|
204
|
+
callable gets a 500. A fiber's wait on the body holds nothing.
|
|
205
|
+
- A request's reader and its writer wait apart, so a full-duplex body
|
|
206
|
+
can read on one fiber while it writes on another. Two fibers that
|
|
207
|
+
wait on the same side of one request can take each other's wake-up,
|
|
208
|
+
and one then waits for the next change.
|
|
209
|
+
|
|
210
|
+
These waits work under any scheduler: an app on Kino's own loop that
|
|
211
|
+
reads `rack.input` inside `Sync { }` gets them too. There an enumerable
|
|
212
|
+
body is written after the app returned, outside its scheduler, the
|
|
213
|
+
blocking way.
|
|
214
|
+
|
|
215
|
+
## Shutdown and retirement
|
|
216
|
+
|
|
217
|
+
When the server drains, or the elastic pool retires the worker, the loop
|
|
218
|
+
takes nothing more and `serve` waits for every job: suspended requests,
|
|
219
|
+
work in `after_request_complete`, jobs serving switched connections,
|
|
220
|
+
inline connections' jobs, and each socket's remaining events up to its
|
|
221
|
+
`on_close`. How each inline connection ends then is in
|
|
222
|
+
[architecture.md](architecture.md#inline-connections). A drain waits up
|
|
223
|
+
to `shutdown_timeout` for that, and past it gives up on what still runs
|
|
224
|
+
as it does on a stuck handler: clients still waiting get a 500 or a cut
|
|
225
|
+
connection, and body reads still waiting raise.
|
|
226
|
+
|
|
227
|
+
A drain closes connections that switched protocols once requests have
|
|
228
|
+
drained, so the jobs serving them read EOF and can end. A hijacked
|
|
229
|
+
request the app has not answered yet, such as a long poll held on its
|
|
230
|
+
fiber, stays open until the workers have stopped, so its job holds the
|
|
231
|
+
drain until it answers, up to `shutdown_timeout` (see
|
|
232
|
+
[websockets.md](websockets.md#rackhijack-and-action-cable)).
|
|
233
|
+
|
|
234
|
+
## Stuck workers and quarantine
|
|
235
|
+
|
|
236
|
+
A `worker_loop`'s requests may wait for seconds by design, so Kino
|
|
237
|
+
judges the thread, not the requests: a worker is busy while its thread
|
|
238
|
+
stays away from its loop and there is work for it. A worker whose
|
|
239
|
+
fibers only wait reads at most about 50 ms of `busy_ms`; a job that
|
|
240
|
+
computes without waiting adds its own run time. Keep
|
|
241
|
+
`quarantine_timeout` well above that: a quarantined worker's inline
|
|
242
|
+
connections end as
|
|
243
|
+
[architecture.md](architecture.md#inline-connections) says. A fiber that spins while the
|
|
244
|
+
worker has no work at all, or after the loop got its end (a drain or a
|
|
245
|
+
retirement), is not seen: that worker reads 0. `request_timeout` works
|
|
246
|
+
as usual: the client gets its 504 while the job runs on, holding its
|
|
247
|
+
slot until it ends.
|
|
248
|
+
|
|
249
|
+
## Dispatch
|
|
250
|
+
|
|
251
|
+
Requests that come through hyper reach a worker by
|
|
252
|
+
[lane dispatch](architecture.md#lane-dispatch), which counts what a
|
|
253
|
+
worker has open: a worker whose fibers all wait counts as idle, one with
|
|
254
|
+
`concurrency` requests open gets no more, and with every worker full a
|
|
255
|
+
request waits its turn, in the order requests came, up to
|
|
256
|
+
`queue_timeout`, then gets a 503. While a sibling sits idle, a worker
|
|
257
|
+
holding a request it has not answered yet is passed over, so a few
|
|
258
|
+
clients spread over the workers. A request on an
|
|
259
|
+
[inline connection](#inline-connections) never passes through it: it
|
|
260
|
+
runs on the worker its connection was placed on.
|
|
261
|
+
|
|
262
|
+
What the app controls is when a job starts: dispatch sees a worker's
|
|
263
|
+
loop, not its fibers. A job left queued (on a `Thread::Queue`, or on
|
|
264
|
+
Async's `Queue`, `Condition` or `Notification`) starts only after the
|
|
265
|
+
loop told dispatch that the worker is idle, so requests wait behind it
|
|
266
|
+
while idle siblings get none. Start each job at once, as `task.async`
|
|
267
|
+
does.
|
|
268
|
+
|
|
269
|
+
`concurrency` counts a request until its job ends, so a worker whose
|
|
270
|
+
answered requests still run (in `after_request_complete`, or past a
|
|
271
|
+
`request_timeout` 504) can be sent a request it has no room for yet. It
|
|
272
|
+
waits in the worker's lane until a job ends, or until an idle sibling
|
|
273
|
+
takes it, within 50 ms.
|
|
274
|
+
|
|
275
|
+
## Inline connections
|
|
276
|
+
|
|
277
|
+
Over plain TCP or a `unix://` bind, a `worker_loop` server serves
|
|
278
|
+
HTTP/1.1 connections on its worker threads, with nothing to turn on.
|
|
279
|
+
Kino places each connection it accepts on a worker with room for it,
|
|
280
|
+
and that worker's loop runs the connection as a job of its own: Kino's
|
|
281
|
+
Rust code reads each request on the worker's thread, the app runs on
|
|
282
|
+
that job, and Kino writes the answer straight to the socket, with no
|
|
283
|
+
hand-off between threads, no wake of the loop and no task per request.
|
|
284
|
+
There is no setting: a server with TLS serves nothing inline. How it works inside, the deadlines, and how each connection
|
|
285
|
+
ends at a drain, a retirement, a quarantine or a crash are in
|
|
286
|
+
[architecture.md](architecture.md#inline-connections).
|
|
287
|
+
|
|
288
|
+
### What an app sees
|
|
289
|
+
|
|
290
|
+
- A connection's requests run one after another on its job, each
|
|
291
|
+
counting toward `concurrency` while it runs, and a worker takes at
|
|
292
|
+
most `concurrency` connections. Between requests the job waits on the
|
|
293
|
+
socket through your scheduler, after stepping aside once (the
|
|
294
|
+
scheduler's `yield`, else `kernel_sleep(0)`) when another inline
|
|
295
|
+
connection shares the worker. The requests share the job's fiber and
|
|
296
|
+
task (see [What carries over](#what-carries-over-between-requests));
|
|
297
|
+
stopping that task ends the connection.
|
|
298
|
+
- A worker serves its inline connections in turn: a request that holds
|
|
299
|
+
the thread (computing, or blocking outside your scheduler) delays the
|
|
300
|
+
worker's other connections, and none of them moves to another worker.
|
|
301
|
+
A lower `concurrency` leaves fewer connections behind each slow
|
|
302
|
+
request; more workers spread them.
|
|
303
|
+
- Kino reads a request's body whole before the app runs, so
|
|
304
|
+
`rack.input` never waits.
|
|
305
|
+
- A streamed answer goes out as through hyper. What the socket does not
|
|
306
|
+
take yet waits on the job, never on the worker's thread, so a slow
|
|
307
|
+
reader holds back its own connection only.
|
|
308
|
+
- Answers, deadlines and the drain follow hyper's, with a few
|
|
309
|
+
[recorded differences](architecture.md#recorded-differences) over
|
|
310
|
+
headers an app should not set, a first head's deadline and the drain.
|
|
311
|
+
- The only inline connection on a worker with nothing else to do spins
|
|
312
|
+
at its socket for up to 100 µs, with the GVL released, before its job
|
|
313
|
+
waits, so a client that sends its next request at once is served
|
|
314
|
+
without a wake. A client whose requests mostly come later backs it off
|
|
315
|
+
to one spin in 32 requests; nothing spins on a process that may use
|
|
316
|
+
one CPU.
|
|
317
|
+
|
|
318
|
+
### What goes to hyper
|
|
319
|
+
|
|
320
|
+
hyper, on Kino's I/O threads, serves everything else, as on a server
|
|
321
|
+
without a `worker_loop`:
|
|
322
|
+
|
|
323
|
+
- TLS and HTTP/2 (an h2c preface included);
|
|
324
|
+
- every request outside a strict subset of HTTP/1.1 (no HTTP/1.0, an
|
|
325
|
+
origin-form target, a body of at most 64 KiB and `max_body_size` by one
|
|
326
|
+
`Content-Length`, no `Transfer-Encoding`, `Expect` or upgrade, a head
|
|
327
|
+
of at most 16 KiB and 100 headers), handed back before the app sees
|
|
328
|
+
it with the bytes read replayed, and a request read whole while its
|
|
329
|
+
worker has no room, which waits for room in the lanes up to
|
|
330
|
+
`queue_timeout`;
|
|
331
|
+
- connections no worker takes at accept, and those of a worker that
|
|
332
|
+
retires, crashes or is quarantined.
|
|
333
|
+
|
|
334
|
+
A connection never goes to hyper in the middle of an answer, and in the
|
|
335
|
+
middle of a request body only as its worker retires, with what was
|
|
336
|
+
read. Behind nginx, connections stay inline while nginx speaks
|
|
337
|
+
HTTP/1.1 to Kino and keeps its connections open, as it does by default
|
|
338
|
+
since 1.29.7; an older nginx needs `proxy_http_version 1.1`,
|
|
339
|
+
`proxy_set_header Connection ""` and an upstream `keepalive` pool. One
|
|
340
|
+
that speaks HTTP/1.0 has every request handed back.
|
|
341
|
+
|
|
342
|
+
## Per-request cost
|
|
343
|
+
|
|
344
|
+
This section is about requests that reach a worker through its lane:
|
|
345
|
+
everything hyper serves, such as TLS, HTTP/2 and hand-backs. A request
|
|
346
|
+
on an
|
|
347
|
+
[inline connection](#inline-connections) pays neither Kino's wake nor a
|
|
348
|
+
task and fiber of its own: its connection's job waits on the socket
|
|
349
|
+
through the scheduler, and runs the request itself. The numbers here
|
|
350
|
+
were measured before Kino served connections inline.
|
|
351
|
+
|
|
352
|
+
A request that reaches an idle `worker_loop` worker costs more than in
|
|
353
|
+
Kino's own loop, which answers one request and takes the next in a
|
|
354
|
+
single native call: one wake-up of the scheduler (none while work
|
|
355
|
+
waits, so nothing under load), and a task and a fiber per request, the
|
|
356
|
+
larger part. For requests that wait on a database or another service
|
|
357
|
+
none of this shows; for an app whose requests do almost nothing, these
|
|
358
|
+
are its levers:
|
|
359
|
+
|
|
360
|
+
- **A task per request**, as above. This is the default for good
|
|
361
|
+
reason: each request has a task and a fiber of its own, so its fiber
|
|
362
|
+
storage and task-local state are its own, stopping its task aborts it
|
|
363
|
+
alone, and a job that raises ends nothing else.
|
|
364
|
+
- **`RUBY_SHARED_FIBER_POOL_FREE_STACKS=0`** in the environment Ruby
|
|
365
|
+
starts with keeps a finished fiber's stack where Ruby would hand its
|
|
366
|
+
memory back, one system call per request; every stack a worker has
|
|
367
|
+
used then stays in memory, up to `concurrency` per worker plus those
|
|
368
|
+
of its socket and wake jobs.
|
|
369
|
+
- **A fixed set of job fibers (runners), each job handed straight to
|
|
370
|
+
an idle one**: no task and no fiber per request. It looks like
|
|
371
|
+
this:
|
|
372
|
+
|
|
373
|
+
<!-- spec/worker_loop_spec.rb and spec/inline_io_spec.rb run this block as a kino.rb. -->
|
|
374
|
+
|
|
375
|
+
```ruby
|
|
376
|
+
worker_loop Ractor.shareable_proc { |worker|
|
|
377
|
+
Sync do |task|
|
|
378
|
+
concurrency = 32 # requests at once, and as many runners
|
|
379
|
+
scheduler = Fiber.scheduler
|
|
380
|
+
idle = []
|
|
381
|
+
done = false
|
|
382
|
+
concurrency.times do
|
|
383
|
+
# Transient, so Sync never waits for a runner.
|
|
384
|
+
task.async(transient: true) do
|
|
385
|
+
runner = Fiber.current
|
|
386
|
+
loop do
|
|
387
|
+
idle << runner
|
|
388
|
+
# A job, or nil once serve has returned: any other wake-up is
|
|
389
|
+
# not a hand-off, and the runner waits on.
|
|
390
|
+
job = scheduler.transfer until done || job.respond_to?(:call)
|
|
391
|
+
break unless job.respond_to?(:call)
|
|
392
|
+
job.call
|
|
393
|
+
end
|
|
394
|
+
end
|
|
395
|
+
end
|
|
396
|
+
worker.serve(concurrency:) do |job|
|
|
397
|
+
if (runner = idle.pop)
|
|
398
|
+
# Runs the job now, until it first waits, as task.async would.
|
|
399
|
+
scheduler.resume(runner, job)
|
|
400
|
+
else
|
|
401
|
+
# Socket and wake jobs, and requests whose connection switched,
|
|
402
|
+
# hold runners outside concurrency: every runner can be busy.
|
|
403
|
+
task.async { job.call }
|
|
404
|
+
end
|
|
405
|
+
end
|
|
406
|
+
done = true
|
|
407
|
+
scheduler.resume(idle.pop, nil) until idle.empty?
|
|
408
|
+
end
|
|
409
|
+
}
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
The hand-off uses two methods of Async's scheduler that io-event's
|
|
413
|
+
selectors implement: `scheduler.transfer` gives control to the event
|
|
414
|
+
loop, so an idle runner wakes only when resumed, and
|
|
415
|
+
`scheduler.resume(runner, job)` switches to the runner at once, as
|
|
416
|
+
`task.async` starts a task. Neither is part of Ruby's
|
|
417
|
+
`Fiber::Scheduler` interface, so check the recipe again after an Async
|
|
418
|
+
or io-event upgrade (it was written against async 2.46 and io-event
|
|
419
|
+
1.22). Feeding the runners through a queue instead would start each job
|
|
420
|
+
too late (see [Dispatch](#dispatch)).
|
|
421
|
+
|
|
422
|
+
What a task per request guarantees no longer holds: requests share the
|
|
423
|
+
runners' fibers, so fiber storage and task-local state carry over, and
|
|
424
|
+
a wake-up that comes late for one request's wait can end a later wait
|
|
425
|
+
of its runner early. Stopping a runner stops its request and the runner
|
|
426
|
+
with it, a job that raises ends its runner too, and the pool does not
|
|
427
|
+
refill: once no runner is idle, jobs get tasks of their own.
|
|
428
|
+
|
|
429
|
+
## Stats and logs
|
|
430
|
+
|
|
431
|
+
- `worker_status[].in_flight` counts the requests the worker has open.
|
|
432
|
+
Socket callbacks and wake hook runs do not count, while in Kino's own
|
|
433
|
+
loop a running callback or hook counts as one.
|
|
434
|
+
- `worker_status[].busy_ms` is how long the worker's thread has stayed
|
|
435
|
+
away from its loop while there is work for it (see
|
|
436
|
+
[Stuck workers](#stuck-workers-and-quarantine)).
|
|
437
|
+
- `wakes` counts each wake the loop takes, also one that folds into a
|
|
438
|
+
run already waiting, so it can be higher than the hook's runs.
|
|
439
|
+
- The access log leaves out the GC and allocation figures, as requests
|
|
440
|
+
interleave: the breakdown is `(ruby; kino; wait)`.
|
|
441
|
+
- `stats[:inline]` (`"inline"` in `/stats`, `null` on a server that
|
|
442
|
+
serves nothing inline) counts [inline serving](#inline-connections):
|
|
443
|
+
- `connections`: served inline now (`kino_inline_connections`);
|
|
444
|
+
- `requests`: served inline (`kino_inline_requests_total`), counted in
|
|
445
|
+
`served`, their worker's row, `timeouts` and `responses_cut` too, as
|
|
446
|
+
hyper's are;
|
|
447
|
+
- `declined`: connections left with hyper at accept, as no worker
|
|
448
|
+
could take one (`kino_inline_declined_total`);
|
|
449
|
+
- `handbacks` (`kino_inline_handbacks_total`): connections handed
|
|
450
|
+
back to hyper, whatever for
|
|
451
|
+
([What goes to hyper](#what-goes-to-hyper));
|
|
452
|
+
- `closed` (`kino_inline_closed_total`): the connections Kino cut
|
|
453
|
+
off, at a deadline, a crash, the shutdown's deadline or a
|
|
454
|
+
quarantine. One its client or an answer closed never counts, nor
|
|
455
|
+
does one a `request_timeout` 504 ended (in `timeouts`);
|
|
456
|
+
- `spins` (`kino_inline_spins_total`): the spins of a lone
|
|
457
|
+
connection's job for its next request, whatever they caught.
|
|
458
|
+
- `worker_status[].inline_connections` counts the connections the
|
|
459
|
+
worker serves inline now (`kino_worker_inline_connections`).
|
|
460
|
+
- An inline request is logged as hyper logs one, with `wait 0.0ms`, as
|
|
461
|
+
it waits in no queue (nor counts in `queue_time`); one handed back is
|
|
462
|
+
logged by hyper alone.
|
data/ext/kino/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "kino"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.8.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
authors = ["Yaroslav Markin <yaroslav@markin.net>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -25,6 +25,8 @@ hyper = { version = "1.6", features = ["http1", "http2", "server"] }
|
|
|
25
25
|
hyper-util = { version = "0.1", features = ["server", "server-auto", "tokio", "http1", "http2"] }
|
|
26
26
|
http = "1"
|
|
27
27
|
http-body-util = "0.1"
|
|
28
|
+
# Parses a hijacked app's response head; already in the tree via hyper.
|
|
29
|
+
httparse = "1.10"
|
|
28
30
|
bytes = "1"
|
|
29
31
|
# Local-time stamps for the access log: the system zone only (no bundled
|
|
30
32
|
# tzdb, no serde), which keeps the dependency tree to jiff itself.
|
|
@@ -33,7 +35,20 @@ jiff = { version = "0.2", default-features = false, features = ["std", "tz-syste
|
|
|
33
35
|
# cross-compiles cleanly in rb-sys-dock containers, while aws-lc-sys wants
|
|
34
36
|
# cmake and a per-target C toolchain.
|
|
35
37
|
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "logging", "tls12"] }
|
|
38
|
+
# Either, one stream type for TCP, unix and TLS connections; already in
|
|
39
|
+
# the tree via h2.
|
|
40
|
+
tokio-util = { version = "0.7", default-features = false }
|
|
36
41
|
rustls-pemfile = "2.2"
|
|
42
|
+
# SHA-1 for the WebSocket handshake key; already in the tree via rustls.
|
|
43
|
+
ring = "0.17"
|
|
44
|
+
# Reads WebSocket client frames into messages; Kino writes its own frames.
|
|
45
|
+
tungstenite = { version = "0.30", default-features = false }
|
|
46
|
+
# EPROTO, which std has no ErrorKind for; already in the tree via tokio.
|
|
47
|
+
libc = "0.2"
|
|
48
|
+
# Socket calls std lacks: hijack bridge reads without tokio, a unix bind's
|
|
49
|
+
# nonblocking live-socket check, the intake's recv, and StdConn, the
|
|
50
|
+
# inline connections' socket; already in the tree via tokio.
|
|
51
|
+
socket2 = "0.6"
|
|
37
52
|
|
|
38
53
|
# musl's loader rejects initial-exec TLS in dlopen'd libraries ("initial-exec
|
|
39
54
|
# TLS resolves to dynamic definition"); build the same mimalloc with the
|
|
@@ -54,3 +69,4 @@ rb-sys = { version = "0.9", features = ["link-ruby"] }
|
|
|
54
69
|
# enables both only for `cargo test`.
|
|
55
70
|
hyper = { version = "1.6", features = ["client"] }
|
|
56
71
|
tokio = { version = "1.45", features = ["test-util"] }
|
|
72
|
+
proptest = { version = "1", default-features = false, features = ["std"] }
|
data/ext/kino/build.rs
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
2
|
-
let
|
|
2
|
+
let env = rb_sys_env::activate()?;
|
|
3
|
+
|
|
4
|
+
// cfg(kino_thread_safe_free) where this Ruby's headers declare the flag (src/typed_data.rs).
|
|
5
|
+
println!("cargo:rustc-check-cfg=cfg(kino_thread_safe_free)");
|
|
6
|
+
// Rerun when this script, the header or where it is changes, or with rb-sys's build (a new
|
|
7
|
+
// Ruby); not on every edit of the crate's sources.
|
|
8
|
+
println!("cargo:rerun-if-changed=build.rs");
|
|
9
|
+
println!("cargo:rerun-if-env-changed=RBCONFIG_rubyhdrdir");
|
|
10
|
+
// The header directory as rb-sys itself looks it up: the rb_sys gem's environment first,
|
|
11
|
+
// which is all a cross build has, then what rb-sys read from the Ruby it ran.
|
|
12
|
+
let header = std::env::var("RBCONFIG_rubyhdrdir")
|
|
13
|
+
.ok()
|
|
14
|
+
.or_else(|| env.get_rbconfig_value("RUBYHDRDIR").map(String::from))
|
|
15
|
+
.map(|dir| format!("{}/ruby/internal/core/rtypeddata.h", dir.trim()));
|
|
16
|
+
let declared = header.as_ref().is_some_and(|header| {
|
|
17
|
+
println!("cargo:rerun-if-changed={header}");
|
|
18
|
+
std::fs::read_to_string(header)
|
|
19
|
+
.is_ok_and(|text| text.contains("RUBY_TYPED_THREAD_SAFE_FREE"))
|
|
20
|
+
});
|
|
21
|
+
if declared {
|
|
22
|
+
println!("cargo:rustc-cfg=kino_thread_safe_free");
|
|
23
|
+
} else if env.ruby_major_minor() >= (4, 1) {
|
|
24
|
+
// A warning, not an error: without the flag Kino is slower on this Ruby, not broken.
|
|
25
|
+
let looked = header.map_or_else(
|
|
26
|
+
|| "no header directory from rb-sys".to_string(),
|
|
27
|
+
|header| format!("not in '{header}'"),
|
|
28
|
+
);
|
|
29
|
+
println!(
|
|
30
|
+
"cargo:warning=no RUBY_TYPED_THREAD_SAFE_FREE ({looked}): this Ruby frees Kino's \
|
|
31
|
+
native objects in batches under a VM barrier"
|
|
32
|
+
);
|
|
33
|
+
}
|
|
3
34
|
|
|
4
35
|
Ok(())
|
|
5
36
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# The GVL is released through gvl::call alone and passed through gvl::pass
|
|
2
|
+
# alone: gvl.rs runs the VM's interrupts in protected calls, so a raise
|
|
3
|
+
# never jumps over Rust frames. A release or a pass anywhere else would.
|
|
4
|
+
disallowed-methods = [
|
|
5
|
+
{ path = "rb_sys::rb_thread_call_without_gvl", reason = "release the GVL through crate::gvl" },
|
|
6
|
+
{ path = "rb_sys::rb_thread_call_without_gvl2", reason = "release the GVL through crate::gvl" },
|
|
7
|
+
{ path = "rb_sys::rb_nogvl", reason = "release the GVL through crate::gvl" },
|
|
8
|
+
{ path = "rb_sys::rb_thread_schedule", reason = "pass the GVL through crate::gvl::pass" },
|
|
9
|
+
{ path = "magnus::Ruby::thread_schedule", reason = "pass the GVL through crate::gvl::pass" },
|
|
10
|
+
]
|