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/websockets.md
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
# WebSockets (experimental)
|
|
2
|
+
|
|
3
|
+
Kino serves WebSockets two ways:
|
|
4
|
+
|
|
5
|
+
- **Native WebSockets** run the protocol in Rust: the handshake,
|
|
6
|
+
framing, pings, the close handshake and topic fan-out. Your handler's
|
|
7
|
+
callbacks run on the worker that accepted the socket. An idle socket
|
|
8
|
+
costs Ruby nothing: no thread, no fiber. Needs `lanes true`.
|
|
9
|
+
- **`rack.hijack`** hands the connection to libraries that bring their
|
|
10
|
+
own WebSocket stack, such as Action Cable. Works in both modes, with
|
|
11
|
+
or without lanes.
|
|
12
|
+
|
|
13
|
+
This guide covers what an app sees; [architecture.md](architecture.md#websockets)
|
|
14
|
+
explains how it works inside.
|
|
15
|
+
|
|
16
|
+
## Native WebSockets
|
|
17
|
+
|
|
18
|
+
### Accepting a handshake
|
|
19
|
+
|
|
20
|
+
Lane dispatch routes each socket's events to its own worker, so turn it
|
|
21
|
+
on:
|
|
22
|
+
|
|
23
|
+
```ruby
|
|
24
|
+
# kino.rb
|
|
25
|
+
lanes true
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
An app accepts a handshake by setting `env["rack.upgrade"]` to a handler
|
|
29
|
+
when `env["rack.upgrade?"]` is `:websocket` (the env keys and callback
|
|
30
|
+
names iodine and Agoo use):
|
|
31
|
+
|
|
32
|
+
```ruby
|
|
33
|
+
module Chat
|
|
34
|
+
def self.on_open(ws) = ws.subscribe("chat")
|
|
35
|
+
def self.on_message(ws, data) = Kino::WebSocket.publish("chat", data)
|
|
36
|
+
def self.on_close(ws) = nil
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
app = Ractor.shareable_proc do |env|
|
|
40
|
+
if env["rack.upgrade?"] == :websocket
|
|
41
|
+
env["rack.upgrade"] = Chat
|
|
42
|
+
[101, {}, []]
|
|
43
|
+
else
|
|
44
|
+
[200, {"content-type" => "text/plain"}, ["hello"]]
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Kino answers with a 101 that carries the response's headers (a
|
|
50
|
+
subprotocol, cookies); the status is ignored. `after_request_complete`
|
|
51
|
+
fires once the 101 is out, with status 101. `rack.upgrade?` is set only
|
|
52
|
+
on a valid handshake (HTTP/1.1, version 13) to a server with lanes;
|
|
53
|
+
anywhere else, whatever the app returns goes out as is, so answer 426
|
|
54
|
+
or 404 there. Compare it to `:websocket` rather than testing it for
|
|
55
|
+
truth: the convention has other values (iodine sets `:sse`), and a later
|
|
56
|
+
Kino may set them too.
|
|
57
|
+
|
|
58
|
+
Kino does not check `Origin`. A browser lets any page open a WebSocket
|
|
59
|
+
to your server and sends your cookies along, so accept handshakes only
|
|
60
|
+
from the origins you serve (Action Cable checks for you):
|
|
61
|
+
|
|
62
|
+
```ruby
|
|
63
|
+
if env["rack.upgrade?"] == :websocket && ALLOWED_ORIGINS.include?(env["HTTP_ORIGIN"])
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Callbacks
|
|
67
|
+
|
|
68
|
+
The handler is any object with `on_open(ws)`, `on_message(ws, data)`,
|
|
69
|
+
`on_drained(ws)`, `on_shutdown(ws)` and `on_close(ws)`, each optional:
|
|
70
|
+
a module that serves every socket, or an object per socket that keeps
|
|
71
|
+
its own state (`env["rack.upgrade"] = ChatSession.new(user)`). The
|
|
72
|
+
handler stays on the worker that accepted the socket, so in `:ractor`
|
|
73
|
+
mode it need not be shareable, and it may change its state without a
|
|
74
|
+
lock.
|
|
75
|
+
|
|
76
|
+
- Callbacks run on the worker thread that accepted the socket, one
|
|
77
|
+
event at a time and in order, between that worker's requests, never
|
|
78
|
+
alongside them. New sockets go to the worker that owns the fewest, and
|
|
79
|
+
a socket stays on its worker. That affinity is how Kino runs sockets
|
|
80
|
+
today, not a promise for every mode it may add: keep a socket's state
|
|
81
|
+
in its handler, and reach other sockets through their handles rather
|
|
82
|
+
than through one worker's globals.
|
|
83
|
+
- Under a `worker_loop` they run alongside the worker's requests and
|
|
84
|
+
other sockets' callbacks instead, each socket's still in order (see
|
|
85
|
+
[worker-loop.md](worker-loop.md#websockets)).
|
|
86
|
+
- A busy socket cannot hold up its worker: after eight events in a row,
|
|
87
|
+
a waiting request goes next, then a due wake. Nor can it hold up the
|
|
88
|
+
worker's other sockets: Kino reads at most 16 of a socket's messages
|
|
89
|
+
ahead of its worker, so another socket's message waits behind at most
|
|
90
|
+
16 of the busy one's.
|
|
91
|
+
- `data` is a UTF-8 String for a text message and a binary String for
|
|
92
|
+
a binary one.
|
|
93
|
+
- `on_open` runs before the client gets the 101, so what it writes or
|
|
94
|
+
subscribes to is in place when the client sees the socket open. It
|
|
95
|
+
counts toward `request_timeout`.
|
|
96
|
+
- `on_drained` runs once the socket's outgoing queue has emptied after
|
|
97
|
+
it was too full for something (see [Flow control](#flow-control)).
|
|
98
|
+
- `on_shutdown` runs when the server starts to drain, before Kino closes
|
|
99
|
+
the socket with 1001: what it writes reaches the client first. Use it
|
|
100
|
+
to tell a client where to reconnect, or for a protocol's own goodbye.
|
|
101
|
+
The drain waits for it, so keep it short.
|
|
102
|
+
- `on_close` runs once for each socket that opened, on its worker,
|
|
103
|
+
whatever ended the socket, unless the worker itself is gone (see
|
|
104
|
+
[Lifecycle](#lifecycle-and-close-codes)). It gets no close code or
|
|
105
|
+
reason.
|
|
106
|
+
- A callback that raises is logged and its socket is dropped (its
|
|
107
|
+
`on_close` follows, unless `on_close` itself raised); the worker keeps
|
|
108
|
+
serving. When `on_open` raises, the client gets a 500 instead of the
|
|
109
|
+
101. So does a handshake whose request body another of the app's
|
|
110
|
+
threads is still reading when Kino accepts it or sends its 101. Action
|
|
111
|
+
Cable keeps a connection open when a channel raises; to get that,
|
|
112
|
+
rescue inside the callback. The log line names the socket and the
|
|
113
|
+
callback:
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
kino[4213] worker-2: websocket #42 on_message · RuntimeError: boom (chat.rb:7:in 'Chat.on_message')
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The `on_error` hook gets the exception too (for `on_open`, once the
|
|
120
|
+
client has its 500), with a frozen Hash in place of the Rack env:
|
|
121
|
+
`{"kino.callback" => "on_message", "kino.websocket" => 42}`. It is not
|
|
122
|
+
a Rack env, so an error tracker should check for `"kino.callback"`
|
|
123
|
+
before building a `Rack::Request` from it.
|
|
124
|
+
|
|
125
|
+
### The socket
|
|
126
|
+
|
|
127
|
+
`ws` is a handle to the socket: frozen, shareable across Ractors, and
|
|
128
|
+
equal (`==`, `eql?`, `hash`) to every other handle with the same id. Its
|
|
129
|
+
methods work from any thread or Ractor, not only inside the socket's
|
|
130
|
+
callbacks, and each returns at once. Being frozen, a handle takes no
|
|
131
|
+
instance variables; keep per-socket state in the handler, or in a Hash
|
|
132
|
+
keyed by `ws`. `Kino::WebSocket[id]` returns the handle for socket `id`,
|
|
133
|
+
or nil once the socket is gone (by the time its `on_close` runs, it is).
|
|
134
|
+
|
|
135
|
+
- `ws.write(text)` and `ws.write_binary(bytes)` queue one frame. They
|
|
136
|
+
return false once the socket is gone, or when its queue is full
|
|
137
|
+
([Limits](#limits)); the socket stays open, and what to do about a
|
|
138
|
+
slow client is the app's call.
|
|
139
|
+
- `ws.write_raw(frames)` queues bytes that already form complete
|
|
140
|
+
frames. Server frames are not masked, so a frame built once can go to
|
|
141
|
+
many sockets.
|
|
142
|
+
- `ws.close(code = 1000)` queues a close frame after what is already
|
|
143
|
+
queued; the client has 5 seconds to answer it. The first close
|
|
144
|
+
stands, and closing again returns true. It returns false, and queues
|
|
145
|
+
no close, once the socket is gone or while its queue is full. A code
|
|
146
|
+
no endpoint may send (anything but 1000-1003, 1007-1011 and
|
|
147
|
+
3000-4999) raises `ArgumentError`.
|
|
148
|
+
- `ws.abort` drops the connection now, queued frames and all.
|
|
149
|
+
- `ws.pending` is how many data frames (writes and publishes) are queued
|
|
150
|
+
and not yet written, a `ws.write_raw` counting once; 0 once the socket
|
|
151
|
+
is gone.
|
|
152
|
+
- `ws.id` is an Integer, unique in the process.
|
|
153
|
+
|
|
154
|
+
### Flow control
|
|
155
|
+
|
|
156
|
+
A write never waits: when the client reads too slowly and the queue is
|
|
157
|
+
full, `ws.write` returns false and the frame is not sent. An app that
|
|
158
|
+
streams more than a client can take (a log tail, a file, an LLM's tokens
|
|
159
|
+
to a slow phone) pauses there and resumes in `on_drained`:
|
|
160
|
+
|
|
161
|
+
```ruby
|
|
162
|
+
class Download
|
|
163
|
+
def initialize(chunks) = @chunks = chunks # Strings to send, in order
|
|
164
|
+
|
|
165
|
+
def on_open(ws) = on_drained(ws)
|
|
166
|
+
|
|
167
|
+
# Writes until the queue is full; on_drained comes back once the
|
|
168
|
+
# client has caught up, also to retry a close the full queue refused.
|
|
169
|
+
def on_drained(ws)
|
|
170
|
+
while (chunk = @chunks.first)
|
|
171
|
+
return unless ws.write_binary(chunk)
|
|
172
|
+
|
|
173
|
+
@chunks.shift
|
|
174
|
+
end
|
|
175
|
+
ws.close
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`on_drained` follows a refused write or close, or a publish skipped
|
|
181
|
+
under `when_full: :skip`; it runs once per streak, however many were
|
|
182
|
+
refused, and not on a socket that is closing. `ws.pending` reads the
|
|
183
|
+
queue without waiting, for apps that would rather slow down first.
|
|
184
|
+
|
|
185
|
+
## Topics
|
|
186
|
+
|
|
187
|
+
`Kino::WebSocket.publish(topic, body, binary: false)` sends `body` to
|
|
188
|
+
every socket subscribed to `topic`, from any Ractor or thread, and
|
|
189
|
+
returns at once. One native fan-out thread takes publishes in order and
|
|
190
|
+
builds one frame per distinct envelope, shared by every subscriber that
|
|
191
|
+
uses it: publishing to ten thousand sockets costs Ruby one call.
|
|
192
|
+
|
|
193
|
+
```ruby
|
|
194
|
+
ws.subscribe("room:7") # each message as is
|
|
195
|
+
ws.subscribe("room:7", prefix: %({"identifier":"room-7","message":), suffix: "}")
|
|
196
|
+
ws.subscribe("ticker", when_full: :skip) # a slow client misses ticks
|
|
197
|
+
ws.unsubscribe("room:7", prefix: %({"identifier":"room-7","message":)) # that envelope
|
|
198
|
+
ws.unsubscribe("room:7") # every envelope
|
|
199
|
+
Kino::WebSocket.publish("room:7", %({"text":"hi"}))
|
|
200
|
+
Kino::WebSocket.publish("quotes", packed, binary: true) # a binary frame
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- A subscriber gets `prefix + body + suffix` in one frame. Subscribing
|
|
204
|
+
again with the same envelope keeps one subscription and takes the new
|
|
205
|
+
`when_full`; a socket's subscriptions end with it. A subscription made
|
|
206
|
+
in `on_open` gets every publish made after the client sees the socket
|
|
207
|
+
open.
|
|
208
|
+
- `binary: true` decides the frame, never the String's encoding. A text
|
|
209
|
+
publish raises `ArgumentError` unless `body` is valid UTF-8, and skips
|
|
210
|
+
envelopes that are not; in a binary publish, body and envelope are
|
|
211
|
+
bytes.
|
|
212
|
+
- `ws.unsubscribe(topic)` ends every subscription the socket has to
|
|
213
|
+
`topic`; with `prefix:`, only those made with that prefix. It returns
|
|
214
|
+
false when there was none.
|
|
215
|
+
- When a publish finds a subscriber's queue full, `when_full` decides:
|
|
216
|
+
`:close`, the default, drops the socket as too slow (its `on_close`
|
|
217
|
+
runs); `:skip` leaves that message out for that socket only and its
|
|
218
|
+
`on_drained` runs once the queue has emptied. Skip suits tickers and
|
|
219
|
+
dashboards, close suits protocols that cannot lose a message. Either
|
|
220
|
+
way the fan-out never waits for a socket.
|
|
221
|
+
- `publish` returns false only when the fan-out queue is full (65,536
|
|
222
|
+
messages, or 64 MiB); the message is not sent and nothing waits for
|
|
223
|
+
room, so log it, drop it, or try again later.
|
|
224
|
+
- A subscribe or unsubscribe made during a fan-out waits for it, but
|
|
225
|
+
lets the caller's other threads, and other Ractors, run meanwhile.
|
|
226
|
+
- Publishing is asynchronous: a `ws.write` made after a publish can
|
|
227
|
+
reach the client first, and an unsubscribe right after it can keep it
|
|
228
|
+
from the socket.
|
|
229
|
+
|
|
230
|
+
## Background work on a worker
|
|
231
|
+
|
|
232
|
+
Socket handlers often need work that no client message starts: deliver
|
|
233
|
+
an update a receiver thread fetched, flush a buffer.
|
|
234
|
+
`Kino::Worker.on_wake` runs a block on the worker's own thread, between
|
|
235
|
+
its requests and socket events and never alongside them, so the block
|
|
236
|
+
can use what the worker's handlers use without a lock:
|
|
237
|
+
|
|
238
|
+
```ruby
|
|
239
|
+
# kino.rb
|
|
240
|
+
lanes true
|
|
241
|
+
after_worker_boot Ractor.shareable_proc { |_worker_id|
|
|
242
|
+
updates = Thread::Queue.new
|
|
243
|
+
waker = Kino::Worker.on_wake { MyApp.deliver(updates.pop) until updates.empty? }
|
|
244
|
+
Thread.new do
|
|
245
|
+
loop do
|
|
246
|
+
updates << MyApp.next_update # blocks on a port, a socket, a queue
|
|
247
|
+
waker.wake
|
|
248
|
+
end
|
|
249
|
+
end
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
- Call `on_wake` on a worker thread, in `after_worker_boot` or while
|
|
254
|
+
serving. It sets that worker's hook (replacing an earlier one) and
|
|
255
|
+
returns a `Kino::Worker::Waker`.
|
|
256
|
+
- `waker.wake` returns at once and works from any thread or Ractor (a
|
|
257
|
+
Waker is frozen and shareable). Wakes that arrive before the hook runs
|
|
258
|
+
coalesce. It returns false once the worker has exited or is retiring,
|
|
259
|
+
and always without lanes; a later worker on the same slot is not woken
|
|
260
|
+
by the old Waker.
|
|
261
|
+
- A hook that raises is logged and the worker keeps serving; `on_error`
|
|
262
|
+
gets `{"kino.callback" => "on_wake"}` in place of the Rack env. A hook
|
|
263
|
+
that wakes its own worker alternates with waiting requests, so it
|
|
264
|
+
cannot starve them.
|
|
265
|
+
- Under a `worker_loop` it runs alongside requests and socket
|
|
266
|
+
callbacks, never twice at once (see
|
|
267
|
+
[worker-loop.md](worker-loop.md#the-wake-hook)).
|
|
268
|
+
- Without lanes Kino warns once and the hook never runs. There is no
|
|
269
|
+
worker-side timer: for periodic work, start a thread that sleeps and
|
|
270
|
+
calls `waker.wake`.
|
|
271
|
+
|
|
272
|
+
## Limits
|
|
273
|
+
|
|
274
|
+
- `websocket_max_message` (default 1 MiB) is the largest message a
|
|
275
|
+
client may send, all fragments together; a bigger one closes the
|
|
276
|
+
socket with 1009. A fragmented message can hold about twice that
|
|
277
|
+
while a slow sender trickles it in.
|
|
278
|
+
- A socket may have 256 outgoing frames waiting, or 4 MiB, whichever
|
|
279
|
+
fills first. Past either, writes return false and a publish drops or
|
|
280
|
+
skips the socket, as its `when_full` says. A frame of any size fits
|
|
281
|
+
an empty queue.
|
|
282
|
+
- A socket's worker may have 16 of its messages waiting or in
|
|
283
|
+
`on_message`; at that many Kino stops reading the socket until a
|
|
284
|
+
callback returns, and TCP pushes back on that client. A worker's
|
|
285
|
+
sockets share an inbox of 1,024 events, which holds up their reading
|
|
286
|
+
the same way when it fills. Nothing is dropped.
|
|
287
|
+
- `websocket_max` (default none) is how many native sockets may be open
|
|
288
|
+
at once; a handshake past it gets a 503. Without it, only
|
|
289
|
+
`max_connections` bounds sockets, and they can take every connection
|
|
290
|
+
slot from plain requests.
|
|
291
|
+
- `websocket_ping_interval` (default 30 seconds) is how long a client
|
|
292
|
+
may be silent before Kino pings it; one silent for twice that is
|
|
293
|
+
dropped and its `on_close` runs. Any frame from the client breaks the
|
|
294
|
+
silence, and so does a client taking what Kino writes; a client held
|
|
295
|
+
up by its own slow worker never counts as silent. On macOS, which
|
|
296
|
+
wakes blocked writers in batches, an interval below about half a
|
|
297
|
+
second can drop a client that only reads, slowly. `nil` or 0 turns
|
|
298
|
+
pings off. Kino answers the client's pings itself.
|
|
299
|
+
- Upgraded connections, native or hijacked, keep their
|
|
300
|
+
`max_connections` slot while they stay open.
|
|
301
|
+
|
|
302
|
+
## Lifecycle and close codes
|
|
303
|
+
|
|
304
|
+
- A graceful drain says goodbye to every native socket when it starts:
|
|
305
|
+
each socket's worker runs `on_shutdown` (if the handler has one), then
|
|
306
|
+
Kino closes the socket with 1001, spread over a second (never more
|
|
307
|
+
than half the drain's deadline) so clients do not all reconnect at
|
|
308
|
+
once. The drain then waits, within `shutdown_timeout`, for each
|
|
309
|
+
`on_close`; a socket still open at the deadline is cut without it.
|
|
310
|
+
- When a worker crashes, or is quarantined as wedged, its sockets close
|
|
311
|
+
with 1011 and their `on_close` does not run: the handlers went with
|
|
312
|
+
the worker. A request or handshake that arrives while the replacement
|
|
313
|
+
starts waits for a worker, up to `queue_timeout`. A worker stuck in a
|
|
314
|
+
callback or its wake hook reads as busy in `worker_status`, so
|
|
315
|
+
`quarantine_timeout` covers it (under a `worker_loop`, by how long its
|
|
316
|
+
thread stays away from its loop: see
|
|
317
|
+
[worker-loop.md](worker-loop.md#stuck-workers-and-quarantine)).
|
|
318
|
+
- The elastic pool does not retire a worker that owns open sockets, so
|
|
319
|
+
with long-lived sockets a pool that grew rarely shrinks back. A socket
|
|
320
|
+
that opens on a worker the pool has just decided to retire is closed
|
|
321
|
+
with 1001, and its `on_close` runs before the worker leaves.
|
|
322
|
+
- A client that vanished without closing (a dropped network, a laptop
|
|
323
|
+
gone to sleep) is dropped after two silent ping intervals, without a
|
|
324
|
+
close frame, so it does not keep its socket or its connection slot.
|
|
325
|
+
- Handshakes that arrive while the server drains, that reach a worker
|
|
326
|
+
whose sockets are being closed, or that would pass `websocket_max`
|
|
327
|
+
get a 503 with `connection: close`, and `on_open` does not run.
|
|
328
|
+
|
|
329
|
+
The close codes Kino sends:
|
|
330
|
+
|
|
331
|
+
- 1000: `ws.close` without a code.
|
|
332
|
+
- 1001: the server drains, or the socket's worker retires.
|
|
333
|
+
- 1002: the client broke the protocol (an unmasked frame, a bad opcode).
|
|
334
|
+
- 1007: a text message that is not valid UTF-8.
|
|
335
|
+
- 1009: a message larger than `websocket_max_message`.
|
|
336
|
+
- 1011: the socket's worker crashed or was quarantined.
|
|
337
|
+
|
|
338
|
+
When the client closes first, Kino echoes its code (1000 if it sent
|
|
339
|
+
none, 1002 for one no endpoint may send).
|
|
340
|
+
|
|
341
|
+
## `rack.hijack` and Action Cable
|
|
342
|
+
|
|
343
|
+
On HTTP/1.1 requests that carry an `Upgrade` header, in both modes and
|
|
344
|
+
with or without lanes, the env has `rack.hijack?` set to true and a
|
|
345
|
+
`rack.hijack` callable (Rack 3). No other request has them; an HTTP/2
|
|
346
|
+
request never does: h2 multiplexes streams on one connection, so no
|
|
347
|
+
request has a connection of its own to hand over.
|
|
348
|
+
|
|
349
|
+
- **Full hijack**: `env["rack.hijack"].call` returns a real socket (one
|
|
350
|
+
end of a Unix socket pair), which nio4r can watch. The app writes its
|
|
351
|
+
own response there, from any thread, now or later; Kino replays it
|
|
352
|
+
through hyper, so TLS keeps working. On a 101 it then joins the two
|
|
353
|
+
connections. Any other answer must carry a Content-Length (a
|
|
354
|
+
handshake a library rejects with its own 400, say), unless it has no
|
|
355
|
+
body (a 204, a 304, the answer to a HEAD): Kino sends it and closes
|
|
356
|
+
the connection. One whose body is chunked, or runs until the close,
|
|
357
|
+
or whose Content-Length is not one plain number, gets a 502 instead.
|
|
358
|
+
The request body stays in `rack.input`, to read before or after the
|
|
359
|
+
hijack. While another of the app's threads waits to read the body,
|
|
360
|
+
the call raises an `IOError`. The returned triple is ignored, and its
|
|
361
|
+
body is still closed. Kino does not set `rack.hijack_io` (Rack 2).
|
|
362
|
+
`after_request_complete` does not fire.
|
|
363
|
+
- **Partial hijack**: a callable in the `rack.hijack` response header
|
|
364
|
+
gets the response stream once the head is out, as a Rack 3 streaming
|
|
365
|
+
body does, and `after_request_complete` fires once it returns. As for
|
|
366
|
+
any [streamed response](streaming.md#streaming-responses), a write
|
|
367
|
+
raises `Kino::ClientGone` once the client has gone.
|
|
368
|
+
- **A 101 with a callable**: a 101 answered with a partial hijack, or
|
|
369
|
+
with a Rack 3 streaming body (`[101, headers, ->(io) { }]`), goes out
|
|
370
|
+
with the response's headers, and the callable gets the switched
|
|
371
|
+
connection as a socket. A partial hijack closes it when done (Rack
|
|
372
|
+
leaves that to the app); a streaming body's is closed once the body
|
|
373
|
+
returns.
|
|
374
|
+
|
|
375
|
+
Each hijacked connection keeps its `max_connections` slot and holds
|
|
376
|
+
three descriptors: the client's socket and both ends of the pair. With
|
|
377
|
+
many open, the process runs out of descriptors at about a third of
|
|
378
|
+
`ulimit -n` connections, before the default `max_connections` (80% of
|
|
379
|
+
it): raise the open-file limit, or set `max_connections` to a third of
|
|
380
|
+
it. Out of descriptors, a hijack raises an `IOError` in the app.
|
|
381
|
+
|
|
382
|
+
A worker whose hijacked connections are still open is not retired by
|
|
383
|
+
the elastic pool. A graceful drain does not wait for hijacked
|
|
384
|
+
connections: a switched one closes once requests and native sockets
|
|
385
|
+
are done, so an app serving it on its worker thread reads EOF and can
|
|
386
|
+
let the worker stop; the others close once the workers have stopped, so
|
|
387
|
+
an app still on its worker can answer first. A long poll still
|
|
388
|
+
unanswered then gets a 503. `request_timeout`, when set, also bounds
|
|
389
|
+
how long a hijacked request may take to write its head: keep it above
|
|
390
|
+
your long poll's interval.
|
|
391
|
+
|
|
392
|
+
Action Cable runs on Kino unmodified this way, in `:threaded` mode
|
|
393
|
+
(lanes not needed):
|
|
394
|
+
|
|
395
|
+
```ruby
|
|
396
|
+
# config/kino.rb
|
|
397
|
+
mode :threaded
|
|
398
|
+
threads 5
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
It does not run inside Ractors yet (see [Rails on
|
|
402
|
+
Ractors](rails-on-ractors.md#live-posts), whose example streams new
|
|
403
|
+
posts over native WebSockets instead).
|
|
404
|
+
|
|
405
|
+
## Stats
|
|
406
|
+
|
|
407
|
+
The WebSocket counters cover the whole process, as topics do. In
|
|
408
|
+
`server.stats` and `GET /stats` they sit under `websockets`, and
|
|
409
|
+
`GET /metrics` has each one as the series in parentheses.
|
|
410
|
+
|
|
411
|
+
- `open` (`kino_websockets_open`, a gauge): native WebSockets open now.
|
|
412
|
+
- `opened` (`kino_websockets_opened_total`): handshakes the app accepted
|
|
413
|
+
that Kino took as sockets.
|
|
414
|
+
- `closed` (`kino_websockets_closed_total{cause="..."}`): sockets
|
|
415
|
+
closed, by why. Every socket opened closes once, under the first
|
|
416
|
+
cause recorded:
|
|
417
|
+
- `normal`: a close frame from either side, or the app's `ws.abort`.
|
|
418
|
+
- `going_away`: Kino's 1001 (a drain, a retiring worker), or a socket
|
|
419
|
+
still open when the server stopped.
|
|
420
|
+
- `protocol`: the client broke the protocol (1002, or 1007).
|
|
421
|
+
- `too_big`: a message past `websocket_max_message` (1009).
|
|
422
|
+
- `slow`: dropped because a publish found its queue full.
|
|
423
|
+
- `dead_peer`: silent for two `websocket_ping_interval`s.
|
|
424
|
+
- `client_gone`: the connection ended without a close frame.
|
|
425
|
+
- `crash`: Kino's 1011, or a callback raised.
|
|
426
|
+
- `handshake_failed`: the 101 never went out (`on_open` raised, or the
|
|
427
|
+
request was answered otherwise first).
|
|
428
|
+
- `handshakes_refused`
|
|
429
|
+
(`kino_websocket_handshakes_refused_total{cause="..."}`): accepted
|
|
430
|
+
handshakes Kino answered with a 503, by why: `websocket_max`,
|
|
431
|
+
`draining` (counted so even when `websocket_max` was reached too) or
|
|
432
|
+
`worker_closing`. These never count as opened.
|
|
433
|
+
- `messages_received` and `messages_sent`
|
|
434
|
+
(`kino_websocket_messages_received_total`,
|
|
435
|
+
`kino_websocket_messages_sent_total`): messages from and to clients;
|
|
436
|
+
a `ws.write_raw` counts once, and pings, pongs and closes not at all.
|
|
437
|
+
- `messages_skipped` (`kino_websocket_messages_skipped_total`):
|
|
438
|
+
publishes left out under `when_full: :skip`, one per subscriber.
|
|
439
|
+
- `writes_refused` (`kino_websocket_writes_refused_total`): the app's
|
|
440
|
+
writes and closes refused by a full queue.
|
|
441
|
+
- `publishes_refused` (`kino_websocket_publishes_refused_total`):
|
|
442
|
+
publishes refused by a full fan-out queue.
|
|
443
|
+
- `inbound_pauses` (`kino_websocket_inbound_pauses_total`): times a
|
|
444
|
+
socket's reading paused at 16 messages ahead of its worker.
|
|
445
|
+
- `received_bytes` and `sent_bytes`
|
|
446
|
+
(`kino_websocket_received_bytes_total`,
|
|
447
|
+
`kino_websocket_sent_bytes_total`): bytes read and written, frame
|
|
448
|
+
headers and control frames included.
|
|
449
|
+
|
|
450
|
+
These are the server's own, at the top level:
|
|
451
|
+
|
|
452
|
+
- `hijacked_connections` (`kino_hijacked_connections`, a gauge):
|
|
453
|
+
connections taken over by a full hijack, or switched by a 101 with a
|
|
454
|
+
callable, and still open. A request leaves `in_flight` when the app
|
|
455
|
+
takes it over and counts here instead.
|
|
456
|
+
- `wakes` (`kino_wakes_total`): wake hook runs handed to workers (under
|
|
457
|
+
a `worker_loop`, every wake its loop takes).
|
|
458
|
+
- Each `worker_status` row has `websockets_open`
|
|
459
|
+
(`kino_worker_websockets_open{worker="N"}`) and `hijacked_connections`
|
|
460
|
+
(`kino_worker_hijacked_connections{worker="N"}`) for its slot.
|
|
461
|
+
|
|
462
|
+
## Not supported
|
|
463
|
+
|
|
464
|
+
- WebSockets over HTTP/2 (RFC 8441). Browsers open WebSockets over
|
|
465
|
+
HTTP/1.1, also when the page itself came over h2.
|
|
466
|
+
- permessage-deflate compression.
|
|
467
|
+
- `rack.hijack` on HTTP/2. For plain streaming, return a Rack 3
|
|
468
|
+
streaming body, which works on both protocols.
|
|
469
|
+
- Action Cable in `:ractor` mode.
|
data/doc/why-kino.md
CHANGED
|
@@ -15,8 +15,8 @@ deep-copies it, and sockets cannot cross at all.
|
|
|
15
15
|
|
|
16
16
|
We measured what the "obvious" workaround costs. The ractor-pool wrapper
|
|
17
17
|
experiment (reduce the env to a shareable subset, copy it to a worker
|
|
18
|
-
over a `Ractor::Port`, copy the response back) runs at **
|
|
19
|
-
where Kino does
|
|
18
|
+
over a `Ractor::Port`, copy the response back) runs at **40.7k req/s
|
|
19
|
+
where Kino does 413k** on the same hardware—see the
|
|
20
20
|
[wrapper comparison](benchmarks.md#the-ractor-pool-wrapper-comparison).
|
|
21
21
|
Copying at the Rack layer eats the entire ractor dividend. Dispatch has
|
|
22
22
|
to live below the Rack contract.
|
|
@@ -78,10 +78,10 @@ objects; Rust sees one queue and one registry.
|
|
|
78
78
|
|
|
79
79
|
With the dispatch cost eliminated, Ractors deliver the thing they were
|
|
80
80
|
built for—a lock per ractor instead of one GVL—and each layer is
|
|
81
|
-
visible in the [benchmarks](benchmarks.md): `/cpu` at
|
|
82
|
-
ractor mode vs **
|
|
83
|
-
fork cluster's CPU parallelism by +
|
|
84
|
-
the cluster's ~1,
|
|
81
|
+
visible in the [benchmarks](benchmarks.md): `/cpu` at 118.1k req/s in
|
|
82
|
+
ractor mode vs **20.2k threaded (5.8×, the GVL ceiling)**, beating the
|
|
83
|
+
fork cluster's CPU parallelism by +14% while holding **~167 MB against
|
|
84
|
+
the cluster's ~1,171 MB** (by PSS, on the bench app), because eight
|
|
85
85
|
ractors share one VM, one Rust front-end, one queue, and one JIT, where
|
|
86
86
|
eight forks each pay full price.
|
|
87
87
|
|