kino 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +281 -0
  4. data/Cargo.lock +164 -95
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +17 -1
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
@@ -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 that retired workers handed back, reset for their next
7
- # occupant. The native side never removes a slot, so recycling is what
8
- # keeps the slot table from growing as an elastic pool breathes. Only
9
- # cleanly exited workers return slots; a crashed worker's slots are
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
- id = @lock.synchronize { @free.pop }
21
- return Native.register_worker(@server_id) unless id
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
- Native.reset_slot(@server_id, id)
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 with the GVL released), reads
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.write_chunk(chunk)
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
- # Ractor mode cannot run Rails yet; the blockers are upstream in Rails.
211
- # Once `Ractor.make_shareable(Rails.application)` works, switching to
212
- # `mode :ractor` here is all you will need.
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.
@@ -2,39 +2,16 @@
2
2
 
3
3
  module Kino
4
4
  # @private
5
- # The :threaded-mode worker pool: `workers` groups of `threads` plain
6
- # Threads, each thread on its own dispatch slot. A group is one ractor's
7
- # worth of capacity, so `workers` and `max_workers` mean the same thing
8
- # in both modes. Behind PoolScaler here (`grow`, `retire`, `groups`,
9
- # `active_count`), the quarantine monitor's replacer (`replace`), and
10
- # the join/kill sweeps Server#shutdown runs.
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
- @next_index = -1
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
- @groups
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
- # Add one group; returns its index.
36
+ # Retiring groups that have left are reaped first.
62
37
  def grow
63
38
  reap
64
- index = spawn_group
65
- report_active
66
- index
39
+ super
67
40
  end
68
41
 
69
- # Send a group home: its slots stop receiving work now, each thread
70
- # finishes what it holds and leaves at its next idle tick, and the
71
- # slots come back to the free list once every thread has exited.
72
- def retire(index)
73
- slots = @lock.synchronize do
74
- next nil unless @groups.key?(index) && !@retiring.key?(index)
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
- @retiring[index] = true
77
- @groups[index][:slots]
50
+ @quarantined[worker_id] = true
78
51
  end
79
- return false unless slots
80
-
81
- slots.each { |id| Native.retire_slot(@server_id, id) }
82
- true
83
- end
52
+ return false unless marked
84
53
 
85
- # The quarantine replacer: spawn a replacement thread on a fresh slot
86
- # FIRST (may raise ThreadError), then quarantine the wedged slot.
87
- def replace(worker_id)
88
- spawn_group(slots: 1, replacement: true)
89
- Native.quarantine_slot(@server_id, worker_id)
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
- true
95
- end
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
- def done?
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
- all_threads.each { |thread| thread.kill if thread.alive? }
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 all_threads
122
- @lock.synchronize { @groups.values.flat_map { |group| group[:threads] } }
123
- end
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
- group = {slots: [], threads: []}
83
+ threads = []
129
84
  index = @lock.synchronize do
130
85
  @next_index += 1
131
- @groups[@next_index] = group
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 do
138
- group[:slots] << id
139
- @slot_to_group[id] = index
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
- error = nil
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
- rescue Exception => e # rubocop:disable Lint/RescueException -- a hard crash in a threaded worker thread
109
+ ended = true
110
+ rescue Exception => e # rubocop:disable Lint/RescueException -- a crash, cleaned up after by Worker.run
155
111
  error = e
156
- raise
112
+ crashed_at = Kino.monotonic
157
113
  ensure
158
- HookFire.fire(@on_worker_exit, "on_worker_exit", worker_id, error)
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][:threads].none?(&:alive?) }
156
+ done = @retiring.keys.select { |index| @groups[index].none?(&:alive?) }
169
157
  done.flat_map do |index|
170
- group = @groups.delete(index)
158
+ @groups.delete(index)
171
159
  @retiring.delete(index)
172
- group[:slots].each { |id| @slot_to_group.delete(id) }
173
- group[:slots]
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
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Kino
4
4
  # The gem version (single source of truth; ext/kino/Cargo.toml syncs).
5
- VERSION = "0.7.2"
5
+ VERSION = "0.8.0"
6
6
  end
@@ -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