kino 0.7.1-aarch64-linux → 0.8.0-aarch64-linux
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 +286 -0
- 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/clippy.toml +10 -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/kino.so +0 -0
- 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 +14 -2
data/lib/kino/slot_bank.rb
CHANGED
|
@@ -3,29 +3,41 @@
|
|
|
3
3
|
module Kino
|
|
4
4
|
# @private
|
|
5
5
|
# Dispatch slots for a worker pool: fresh ones from the native registry,
|
|
6
|
-
# or ones
|
|
7
|
-
#
|
|
8
|
-
# keeps
|
|
9
|
-
#
|
|
10
|
-
# abandoned (stale interrupt kicks and dead weak refs go down with
|
|
11
|
-
# them).
|
|
6
|
+
# or ones retired or crashed workers handed back, reset once quiet. The
|
|
7
|
+
# native side never removes a slot, so recycling keeps the table from
|
|
8
|
+
# growing. The bank keeps each slot's generation as it handed it out, so
|
|
9
|
+
# an id read for one worker never acts on a later one.
|
|
12
10
|
class SlotBank
|
|
13
11
|
def initialize(server_id)
|
|
14
12
|
@server_id = server_id
|
|
15
13
|
@free = []
|
|
14
|
+
@generations = {}
|
|
16
15
|
@lock = Mutex.new
|
|
17
16
|
end
|
|
18
17
|
|
|
19
18
|
def claim
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
@lock.synchronize do
|
|
20
|
+
@free.each_with_index do |id, index|
|
|
21
|
+
next unless (generation = Native.reset_slot(@server_id, id))
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
@free.delete_at(index)
|
|
24
|
+
@generations[id] = generation
|
|
25
|
+
return id
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
id = Native.register_worker(@server_id)
|
|
29
|
+
@lock.synchronize { @generations[id] = 0 }
|
|
24
30
|
id
|
|
25
31
|
end
|
|
26
32
|
|
|
33
|
+
# The generation slot `id` had when this bank handed it out.
|
|
34
|
+
def generation(id) = @lock.synchronize { @generations.fetch(id) }
|
|
35
|
+
|
|
27
36
|
def release(ids)
|
|
28
37
|
@lock.synchronize { @free.concat(ids) }
|
|
29
38
|
end
|
|
39
|
+
|
|
40
|
+
# Whether the workers on slots `ids` have taken a request since they got them.
|
|
41
|
+
def served_any?(ids) = WorkerRow.all(@server_id).any? { |row| ids.include?(row.slot) && row.served.positive? }
|
|
30
42
|
end
|
|
31
43
|
end
|
data/lib/kino/stream.rb
CHANGED
|
@@ -4,7 +4,7 @@ module Kino
|
|
|
4
4
|
# @private
|
|
5
5
|
# The stream handed to Rack 3 streaming bodies (`body.call(stream)`).
|
|
6
6
|
# Rack 3 requires it to be full-duplex: writes go to the native response
|
|
7
|
-
# channel (a slow client blocks the writer
|
|
7
|
+
# channel (a slow client blocks the writer, or suspends its fiber under a scheduler), reads
|
|
8
8
|
# pull the remaining request body through the request's own rack.input.
|
|
9
9
|
class Stream
|
|
10
10
|
def initialize(request, input)
|
|
@@ -23,7 +23,7 @@ module Kino
|
|
|
23
23
|
def write(chunk)
|
|
24
24
|
raise IOError, "stream is closed for writing" if @write_closed
|
|
25
25
|
|
|
26
|
-
@request.
|
|
26
|
+
@request.write_all(chunk)
|
|
27
27
|
chunk.bytesize
|
|
28
28
|
end
|
|
29
29
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Kino
|
|
4
|
+
# @private
|
|
5
|
+
module Teardown
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
# Thread#join(limit), minus the re-raise of the crash the thread died
|
|
9
|
+
# of: that was reported when it happened, and must not cut a shutdown
|
|
10
|
+
# short.
|
|
11
|
+
# @return [Thread, nil] the thread once it has ended, nil on timeout
|
|
12
|
+
def join(thread, limit)
|
|
13
|
+
thread.join(limit)
|
|
14
|
+
rescue Exception # rubocop:disable Lint/RescueException -- the joined thread's crash, reported already
|
|
15
|
+
raise if thread.alive? # not its crash: one aimed at the caller
|
|
16
|
+
|
|
17
|
+
thread
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Join each thread the block lists within `timeout` seconds (then 10 ms each), then any it
|
|
21
|
+
# lists afresh: a joined thread may have added one (a crashed worker's replacement).
|
|
22
|
+
def join_all(timeout)
|
|
23
|
+
deadline = Kino.monotonic + timeout
|
|
24
|
+
joined = {}
|
|
25
|
+
until (pending = yield.reject { |thread| joined.key?(thread) }).empty?
|
|
26
|
+
pending.each do |thread|
|
|
27
|
+
join(thread, [deadline - Kino.monotonic, 0.01].max)
|
|
28
|
+
joined[thread] = true
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
@@ -30,7 +30,9 @@
|
|
|
30
30
|
# How many workers to run. Each worker handles requests independently;
|
|
31
31
|
# in :ractor mode every worker runs Ruby in parallel on its own core.
|
|
32
32
|
# Default: the CPUs this process may use (Kino.available_parallelism:
|
|
33
|
-
# the affinity mask and, in a container, the cgroup CPU quota).
|
|
33
|
+
# the affinity mask and, in a container, the cgroup CPU quota). In
|
|
34
|
+
# :ractor mode that is capped at RUBY_MAX_CPU (8 unless set), because
|
|
35
|
+
# Ruby runs at most that many ractors' Ruby code at once.
|
|
34
36
|
# workers 8
|
|
35
37
|
|
|
36
38
|
# Threads inside each worker. More threads help when your app spends
|
|
@@ -53,6 +55,7 @@
|
|
|
53
55
|
# max_workers 32
|
|
54
56
|
|
|
55
57
|
# Seconds an extra worker must sit idle before it is retired.
|
|
58
|
+
# A worker with open WebSockets or hijacked connections counts as busy.
|
|
56
59
|
# scale_down_after 30
|
|
57
60
|
|
|
58
61
|
## Dispatch mode
|
|
@@ -95,6 +98,8 @@
|
|
|
95
98
|
|
|
96
99
|
# Experimental dispatcher that gives each worker its own line. Faster
|
|
97
100
|
# for quick handlers; behavior under heavy overload differs slightly.
|
|
101
|
+
# Native WebSockets and Kino::Worker.on_wake hooks need it.
|
|
102
|
+
# A worker_loop (below) turns it on.
|
|
98
103
|
# lanes false
|
|
99
104
|
|
|
100
105
|
# Log every request to stdout: an arrival line before the app runs and a
|
|
@@ -131,9 +136,37 @@
|
|
|
131
136
|
# error). error is the crash cause, or nil on a clean exit. In :ractor
|
|
132
137
|
# mode worker_index identifies the exited ractor (0..workers - 1), a
|
|
133
138
|
# different number space than after_worker_boot's slot id: do not
|
|
134
|
-
# correlate boot and exit by that number in :ractor mode.
|
|
139
|
+
# correlate boot and exit by that number in :ractor mode. It also fires
|
|
140
|
+
# for each worker thread that crashed.
|
|
135
141
|
# on_worker_exit { |worker_index, error| }
|
|
136
142
|
|
|
143
|
+
# Run each worker's loop under your own fiber scheduler: called on the
|
|
144
|
+
# worker thread with the worker, whose serve(concurrency:) hands your
|
|
145
|
+
# scheduler each request as a job. With it, Kino also serves plain
|
|
146
|
+
# HTTP/1.1 connections inline, on the worker threads themselves, with no
|
|
147
|
+
# hand-off between threads (inline serving). In :ractor mode pass a
|
|
148
|
+
# Ractor.shareable_proc (a do...end block is never shareable). Needs the
|
|
149
|
+
# async gem; see doc/worker-loop.md in the Kino repository.
|
|
150
|
+
# require "async"
|
|
151
|
+
# worker_loop Ractor.shareable_proc { |worker|
|
|
152
|
+
# Sync { |task| worker.serve(concurrency: 32) { |job| task.async { job.call } } }
|
|
153
|
+
# }
|
|
154
|
+
|
|
155
|
+
## WebSockets (experimental)
|
|
156
|
+
#
|
|
157
|
+
# Native WebSockets need `lanes true`; rack.hijack (Action Cable) works in both modes.
|
|
158
|
+
|
|
159
|
+
# Largest message a client may send, in bytes; a bigger one closes the
|
|
160
|
+
# socket with 1009. Default: 1 MiB.
|
|
161
|
+
# websocket_max_message 1024 * 1024
|
|
162
|
+
|
|
163
|
+
# Most native WebSockets open at once (default: only max_connections); past it, a 503.
|
|
164
|
+
# websocket_max 10_000
|
|
165
|
+
|
|
166
|
+
# Ping a client silent for this many seconds, and drop one silent for
|
|
167
|
+
# twice that. nil or 0 sends no pings.
|
|
168
|
+
# websocket_ping_interval 30
|
|
169
|
+
|
|
137
170
|
## Lifecycle
|
|
138
171
|
|
|
139
172
|
# On shutdown, give in-flight requests this many seconds to finish.
|
|
@@ -176,7 +209,9 @@
|
|
|
176
209
|
# quarantined for good (in :ractor mode the ractor itself leaks until
|
|
177
210
|
# process exit, since a wedged ractor cannot be safely interrupted). Off
|
|
178
211
|
# unless set; set it above your slowest legitimate endpoint, and above
|
|
179
|
-
# request_timeout.
|
|
212
|
+
# request_timeout. A WebSocket callback or wake hook counts as a request;
|
|
213
|
+
# the slot's sockets close with 1011. Under a worker_loop, a worker is
|
|
214
|
+
# stuck once its thread stays away from its loop that long.
|
|
180
215
|
# quarantine_timeout 60
|
|
181
216
|
|
|
182
217
|
# Cap on the total number of replacement events over the process
|
|
@@ -207,6 +242,6 @@
|
|
|
207
242
|
# - Set the database pool to at least workers x threads.
|
|
208
243
|
# - Send logs to stdout or another thread-safe destination.
|
|
209
244
|
#
|
|
210
|
-
#
|
|
211
|
-
#
|
|
212
|
-
#
|
|
245
|
+
# Rails main partially runs on Ractors via `Rails.application.ractorize!`;
|
|
246
|
+
# see doc/rails-on-ractors.md in the Kino repository. Most apps still
|
|
247
|
+
# need :threaded.
|
data/lib/kino/threaded_pool.rb
CHANGED
|
@@ -2,39 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
module Kino
|
|
4
4
|
# @private
|
|
5
|
-
# The :threaded-mode
|
|
6
|
-
#
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class ThreadedPool
|
|
12
|
-
def initialize(server_id, app, threads:, batch: 1, hooks: nil, on_worker_exit: nil)
|
|
13
|
-
@server_id = server_id
|
|
14
|
-
@app = app
|
|
15
|
-
@threads = threads
|
|
16
|
-
@batch = batch
|
|
17
|
-
@hooks = hooks
|
|
18
|
-
@on_worker_exit = on_worker_exit
|
|
19
|
-
@lock = Mutex.new
|
|
20
|
-
# index => {slots:, threads:}; the groups asked to leave; quarantine
|
|
21
|
-
# replacements (one thread each, standing in for a wedged slot:
|
|
22
|
-
# neither counted nor retired, so the wedged group keeps counting as
|
|
23
|
-
# the capacity it still is). Retired groups hand their slots back to
|
|
24
|
-
# the bank.
|
|
5
|
+
# The :threaded-mode Pool: `workers` groups of `threads` Threads, a group being one Ractor's
|
|
6
|
+
# worth of capacity; a crashed thread is replaced in its group, paced by a CrashBackoff.
|
|
7
|
+
class ThreadedPool < Pool
|
|
8
|
+
def initialize(...)
|
|
9
|
+
super
|
|
10
|
+
# index => its threads; quarantine replacements (one thread each: not counted, not retired).
|
|
25
11
|
@groups = {}
|
|
26
|
-
@slot_to_group = {}
|
|
27
|
-
@retiring = {}
|
|
28
|
-
@bank = SlotBank.new(server_id)
|
|
29
12
|
@replacements = {}
|
|
30
13
|
@wedged = {}
|
|
31
|
-
@
|
|
32
|
-
end
|
|
33
|
-
|
|
34
|
-
def start(workers)
|
|
35
|
-
workers.times { spawn_group }
|
|
36
|
-
report_active
|
|
37
|
-
self
|
|
14
|
+
@stragglers_killed = false
|
|
38
15
|
end
|
|
39
16
|
|
|
40
17
|
# Groups that are staying: quarantine replacements aside, and minus
|
|
@@ -52,125 +29,137 @@ module Kino
|
|
|
52
29
|
def groups
|
|
53
30
|
reap
|
|
54
31
|
@lock.synchronize do
|
|
55
|
-
@
|
|
56
|
-
.reject { |index, _| @retiring.key?(index) || @wedged.key?(index) || @replacements.key?(index) }
|
|
57
|
-
.transform_values { |group| group[:slots].dup }
|
|
32
|
+
@slots.reject { |index, _| @retiring.key?(index) || @wedged.key?(index) || @replacements.key?(index) }
|
|
58
33
|
end
|
|
59
34
|
end
|
|
60
35
|
|
|
61
|
-
#
|
|
36
|
+
# Retiring groups that have left are reaped first.
|
|
62
37
|
def grow
|
|
63
38
|
reap
|
|
64
|
-
|
|
65
|
-
report_active
|
|
66
|
-
index
|
|
39
|
+
super
|
|
67
40
|
end
|
|
68
41
|
|
|
69
|
-
#
|
|
70
|
-
#
|
|
71
|
-
#
|
|
72
|
-
def
|
|
73
|
-
|
|
74
|
-
next
|
|
42
|
+
# The quarantine replacer for slot `worker_id` at `generation`: mark the slot (a crash
|
|
43
|
+
# meanwhile gets no second replacement), spawn a replacement on a bank slot (a ThreadError
|
|
44
|
+
# unmarks it), then quarantine. False for a slot that moved on since the sample.
|
|
45
|
+
def replace(worker_id, generation)
|
|
46
|
+
marked = @lock.synchronize do
|
|
47
|
+
next false if @quarantined.key?(worker_id) || !@owner.key?(worker_id)
|
|
48
|
+
next false unless @bank.generation(worker_id) == generation
|
|
75
49
|
|
|
76
|
-
@
|
|
77
|
-
@groups[index][:slots]
|
|
50
|
+
@quarantined[worker_id] = true
|
|
78
51
|
end
|
|
79
|
-
return false unless
|
|
80
|
-
|
|
81
|
-
slots.each { |id| Native.retire_slot(@server_id, id) }
|
|
82
|
-
true
|
|
83
|
-
end
|
|
52
|
+
return false unless marked
|
|
84
53
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
@lock.synchronize do
|
|
91
|
-
wedged = @slot_to_group[worker_id]
|
|
92
|
-
@wedged[wedged] = true if wedged
|
|
54
|
+
begin
|
|
55
|
+
spawn_group(slots: 1, replacement: true)
|
|
56
|
+
rescue
|
|
57
|
+
unmark([worker_id])
|
|
58
|
+
raise
|
|
93
59
|
end
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
# Join every thread up to the (numeric) deadline.
|
|
98
|
-
def shutdown(timeout)
|
|
99
|
-
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
100
|
-
all_threads.each do |thread|
|
|
101
|
-
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
102
|
-
thread.join([remaining, 0.01].max)
|
|
60
|
+
if quarantine(worker_id, generation)
|
|
61
|
+
@lock.synchronize { @wedged[@owner[worker_id]] = true if @owner.key?(worker_id) }
|
|
103
62
|
end
|
|
63
|
+
true
|
|
104
64
|
end
|
|
105
65
|
|
|
106
|
-
|
|
107
|
-
all_threads.none?(&:alive?)
|
|
108
|
-
end
|
|
109
|
-
|
|
110
|
-
# Block until every thread exits on its own (drain elsewhere).
|
|
111
|
-
def join
|
|
112
|
-
all_threads.each(&:join)
|
|
113
|
-
end
|
|
114
|
-
|
|
66
|
+
# Threads the shutdown kills end no crash: their clients were freed by abort_all_inflight.
|
|
115
67
|
def kill_stragglers
|
|
116
|
-
|
|
68
|
+
@stragglers_killed = true
|
|
69
|
+
join_set.each { |thread| thread.kill if thread.alive? }
|
|
117
70
|
end
|
|
118
71
|
|
|
119
72
|
private
|
|
120
73
|
|
|
121
|
-
def
|
|
122
|
-
|
|
123
|
-
|
|
74
|
+
def add_worker = spawn_group
|
|
75
|
+
|
|
76
|
+
def join_set = @lock.synchronize { @groups.values.flatten }
|
|
77
|
+
|
|
78
|
+
def member?(index) = @groups.key?(index)
|
|
124
79
|
|
|
125
80
|
# The group is in the table before its first thread starts, so a
|
|
126
81
|
# ThreadError partway through leaves nothing untracked for shutdown.
|
|
127
82
|
def spawn_group(slots: @threads, replacement: false)
|
|
128
|
-
|
|
83
|
+
threads = []
|
|
129
84
|
index = @lock.synchronize do
|
|
130
85
|
@next_index += 1
|
|
131
|
-
@groups[@next_index] =
|
|
86
|
+
@groups[@next_index] = threads
|
|
87
|
+
@slots[@next_index] = []
|
|
132
88
|
@replacements[@next_index] = true if replacement
|
|
133
89
|
@next_index
|
|
134
90
|
end
|
|
135
|
-
slots.times do
|
|
91
|
+
slots.times do |position|
|
|
136
92
|
id = @bank.claim
|
|
137
|
-
@lock.synchronize
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
end
|
|
141
|
-
thread = spawn_thread(id)
|
|
142
|
-
@lock.synchronize { group[:threads] << thread }
|
|
93
|
+
@lock.synchronize { map_slot(index, id) }
|
|
94
|
+
thread = spawn_thread(index, id, CrashBackoff.for(index, position, slots))
|
|
95
|
+
@lock.synchronize { threads << thread }
|
|
143
96
|
end
|
|
144
97
|
index
|
|
145
98
|
end
|
|
146
99
|
|
|
147
|
-
def spawn_thread(worker_id)
|
|
100
|
+
def spawn_thread(index, worker_id, backoff)
|
|
148
101
|
Thread.new do
|
|
149
102
|
# Named so log lines from inside say which worker spoke.
|
|
150
103
|
Thread.current.name = "worker-#{worker_id}"
|
|
151
|
-
|
|
104
|
+
backoff.started
|
|
105
|
+
error = crashed_at = nil
|
|
106
|
+
ended = false
|
|
152
107
|
begin
|
|
153
108
|
Worker.run(@server_id, worker_id, @app, @batch, @hooks)
|
|
154
|
-
|
|
109
|
+
ended = true
|
|
110
|
+
rescue Exception => e # rubocop:disable Lint/RescueException -- a crash, cleaned up after by Worker.run
|
|
155
111
|
error = e
|
|
156
|
-
|
|
112
|
+
crashed_at = Kino.monotonic
|
|
157
113
|
ensure
|
|
158
|
-
|
|
114
|
+
# Neither its end nor an exception: killed, a crash unless by the shutdown or the VM's exit.
|
|
115
|
+
unless ended || error || @stragglers_killed || !Thread.main.alive?
|
|
116
|
+
error = Error.new(KILLED)
|
|
117
|
+
crashed_at = Kino.monotonic
|
|
118
|
+
end
|
|
119
|
+
worker_exited(worker_id, error)
|
|
120
|
+
# Here, as a killed thread runs only its ensure.
|
|
121
|
+
replace_crashed(index, worker_id, backoff, error, crashed_at) if error
|
|
159
122
|
end
|
|
160
123
|
end
|
|
161
124
|
end
|
|
162
125
|
|
|
126
|
+
# A crashed thread's last act, as its replacement's supervisor: release its slot, then after
|
|
127
|
+
# the backoff spawn a fresh thread, unless the group is leaving, the slot wedged, or draining.
|
|
128
|
+
def replace_crashed(index, dead_id, backoff, error, crashed_at)
|
|
129
|
+
Thread.current.name = "supervisor-#{index}"
|
|
130
|
+
return unless recover(index, [dead_id], error, backoff, crashed_at)
|
|
131
|
+
|
|
132
|
+
id = claim_slot(index) { draining? || @retiring.key?(index) }
|
|
133
|
+
return unless id
|
|
134
|
+
|
|
135
|
+
Native.record_respawn(@server_id)
|
|
136
|
+
thread = spawn_thread(index, id, backoff)
|
|
137
|
+
@lock.synchronize { @groups[index].keep_if(&:alive?) << thread }
|
|
138
|
+
rescue => e
|
|
139
|
+
replacement_failed(index, e)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Unmap the group's slots of `ids`; returns the releasable ones, wedged, and leaving.
|
|
143
|
+
def forget_slots(index, ids)
|
|
144
|
+
@lock.synchronize do
|
|
145
|
+
forgotten = unmap(index, ids)
|
|
146
|
+
released = releasable(forgotten)
|
|
147
|
+
[released, released.size < forgotten.size, !@groups.key?(index) || @retiring.key?(index)]
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
163
151
|
# Retiring groups whose threads have all exited give their slots back
|
|
164
152
|
# and leave the table. Runs before every pool decision, so the count
|
|
165
153
|
# the control plane sees never lags by more than a scaler tick.
|
|
166
154
|
def reap
|
|
167
155
|
freed = @lock.synchronize do
|
|
168
|
-
done = @retiring.keys.select { |index| @groups[index]
|
|
156
|
+
done = @retiring.keys.select { |index| @groups[index].none?(&:alive?) }
|
|
169
157
|
done.flat_map do |index|
|
|
170
|
-
|
|
158
|
+
@groups.delete(index)
|
|
171
159
|
@retiring.delete(index)
|
|
172
|
-
|
|
173
|
-
|
|
160
|
+
slots = @slots.delete(index)
|
|
161
|
+
slots.each { |id| @owner.delete(id) }
|
|
162
|
+
releasable(slots)
|
|
174
163
|
end
|
|
175
164
|
end
|
|
176
165
|
return if freed.empty?
|
|
@@ -178,9 +167,5 @@ module Kino
|
|
|
178
167
|
@bank.release(freed)
|
|
179
168
|
report_active
|
|
180
169
|
end
|
|
181
|
-
|
|
182
|
-
def report_active
|
|
183
|
-
Native.set_active_workers(@server_id, active_count)
|
|
184
|
-
end
|
|
185
170
|
end
|
|
186
171
|
end
|
data/lib/kino/version.rb
CHANGED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Kino
|
|
4
|
+
# A native WebSocket (experimental): set `env["rack.upgrade"]` to a handler
|
|
5
|
+
# when `env["rack.upgrade?"]` is `:websocket`. Its callbacks (on_open,
|
|
6
|
+
# on_message, on_drained, on_shutdown, on_close; each optional) run on the
|
|
7
|
+
# worker that accepted the socket, one event at a time. A handle is frozen
|
|
8
|
+
# and shareable, and works from any thread or Ractor. Needs `lanes true`;
|
|
9
|
+
# doc/websockets.md is the guide.
|
|
10
|
+
class WebSocket
|
|
11
|
+
# @return [Integer] the socket's id, unique in the process
|
|
12
|
+
attr_reader :id
|
|
13
|
+
|
|
14
|
+
# The socket with this id, from any thread or Ractor; nil once it is gone.
|
|
15
|
+
def self.[](id) = (new(id) if Native.ws_registered(id))
|
|
16
|
+
|
|
17
|
+
private_class_method :new
|
|
18
|
+
|
|
19
|
+
def initialize(id)
|
|
20
|
+
@id = id
|
|
21
|
+
freeze
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def ==(other) = other.is_a?(WebSocket) && other.id == @id
|
|
25
|
+
|
|
26
|
+
alias_method :eql?, :==
|
|
27
|
+
|
|
28
|
+
def hash = @id.hash
|
|
29
|
+
|
|
30
|
+
# Send a text message; false once the socket is gone or its queue is full.
|
|
31
|
+
def write(data) = Native.ws_write(@id, data)
|
|
32
|
+
|
|
33
|
+
# Send a binary message; false as for #write.
|
|
34
|
+
def write_binary(data) = Native.ws_write_binary(@id, data)
|
|
35
|
+
|
|
36
|
+
# Send bytes that already form complete WebSocket frames.
|
|
37
|
+
def write_raw(frames) = Native.ws_write_raw(@id, frames)
|
|
38
|
+
|
|
39
|
+
# Close after what is queued; on_close follows, and the client has 5 seconds
|
|
40
|
+
# to answer. The first close stands. False once gone, or on a full queue (then #abort).
|
|
41
|
+
# @raise [ArgumentError] for a code outside 1000-1003, 1007-1011 and 3000-4999
|
|
42
|
+
def close(code = 1000) = Native.ws_close(@id, code)
|
|
43
|
+
|
|
44
|
+
# Drop the connection without a close frame; on_close follows.
|
|
45
|
+
def abort = Native.ws_abort(@id)
|
|
46
|
+
|
|
47
|
+
# Data frames queued and not yet written (a #write_raw counts once); 0 once gone.
|
|
48
|
+
def pending = Native.ws_pending(@id)
|
|
49
|
+
|
|
50
|
+
# Receive `topic`'s publishes as `prefix + body + suffix` frames; a full queue drops the
|
|
51
|
+
# socket (`when_full: :close`) or skips the message (`:skip`). False once the socket is gone.
|
|
52
|
+
# @raise [ArgumentError] for a `when_full` other than :close or :skip
|
|
53
|
+
def subscribe(topic, prefix: "", suffix: "", when_full: :close)
|
|
54
|
+
unless %i[close skip].include?(when_full)
|
|
55
|
+
raise ArgumentError, "when_full must be :close or :skip, not #{when_full.inspect}"
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
Native.ws_subscribe(@id, topic, prefix, suffix, when_full == :skip)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Every subscription to `topic`, or those made with `prefix`; false if none.
|
|
62
|
+
def unsubscribe(topic, prefix: nil) = Native.ws_unsubscribe(@id, topic, prefix)
|
|
63
|
+
|
|
64
|
+
# Send `body` to `topic`'s subscribers from any thread or Ractor, as text (valid UTF-8) or
|
|
65
|
+
# with `binary: true`; asynchronous, false only when the fan-out queue is full.
|
|
66
|
+
# @raise [ArgumentError] for a text `body` that is not UTF-8
|
|
67
|
+
def self.publish(topic, body, binary: false) = Native.ws_publish(topic, body, binary)
|
|
68
|
+
|
|
69
|
+
# @private
|
|
70
|
+
module Events
|
|
71
|
+
HANDLERS = :kino_websockets
|
|
72
|
+
CALLBACKS = Ractor.make_shareable({message: "on_message", drained: "on_drained",
|
|
73
|
+
shutdown: "on_shutdown", close: "on_close"})
|
|
74
|
+
|
|
75
|
+
module_function
|
|
76
|
+
|
|
77
|
+
# Kept in a thread variable of the accepting worker thread; returns what on_open raised.
|
|
78
|
+
def open(id, handler)
|
|
79
|
+
ws = WebSocket.__send__(:new, id)
|
|
80
|
+
thread = Thread.current
|
|
81
|
+
sockets = thread.thread_variable_get(HANDLERS) || thread.thread_variable_set(HANDLERS, {})
|
|
82
|
+
sockets[id] = [handler, ws]
|
|
83
|
+
handler.on_open(ws) if handler.respond_to?(:on_open)
|
|
84
|
+
nil
|
|
85
|
+
rescue => e
|
|
86
|
+
failed(e, id, "on_open")
|
|
87
|
+
e
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# A handled message returns its credit; a finished on_shutdown lets the drain close it.
|
|
91
|
+
def dispatch(event, on_error)
|
|
92
|
+
id, kind, data = event
|
|
93
|
+
sockets = Thread.current.thread_variable_get(HANDLERS) or return
|
|
94
|
+
if kind == :message
|
|
95
|
+
handler, ws = sockets[id]
|
|
96
|
+
handler.on_message(ws, data) if handler.respond_to?(:on_message)
|
|
97
|
+
else
|
|
98
|
+
# The socket's last event, on_close, forgets its handler.
|
|
99
|
+
handler, ws = (kind == :close) ? sockets.delete(id) : sockets[id]
|
|
100
|
+
callback = CALLBACKS.fetch(kind)
|
|
101
|
+
handler.public_send(callback, ws) if handler.respond_to?(callback)
|
|
102
|
+
end
|
|
103
|
+
rescue => e
|
|
104
|
+
callback = CALLBACKS.fetch(kind)
|
|
105
|
+
failed(e, id, callback)
|
|
106
|
+
report(e, id, callback, on_error)
|
|
107
|
+
ensure
|
|
108
|
+
case kind
|
|
109
|
+
when :message then Native.ws_handled(id)
|
|
110
|
+
when :shutdown then Native.ws_shutdown_ran(id)
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Logged with its backtrace; the socket is dropped (on_close follows), counted as a crash.
|
|
115
|
+
def failed(error, id, callback)
|
|
116
|
+
Log.failure("websocket ##{id} #{callback}", error)
|
|
117
|
+
Native.ws_fail(id)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def report(error, id, callback, on_error)
|
|
121
|
+
HookFire.fire(on_error, "on_error", error, {"kino.callback" => callback, "kino.websocket" => id}.freeze)
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|