kino 0.7.2-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.
data/lib/kino/worker.rb CHANGED
@@ -1,59 +1,197 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "socket"
4
+
3
5
  module Kino
4
- # @private
5
- # The request loop. Identical for threaded and ractor modes.
6
- #
7
- # The default (batch 1) hot path allocates one Hash per request: the env
8
- # arrives with the native request handle embedded under "kino.request",
9
- # and the common complete-body response rides the fused
10
- # respond_and_take_one call: ~one FFI crossing per request, no arrays.
11
- #
12
- # batch > 1 trades fairness for throughput: a worker grabs up to that
13
- # many already-queued requests per crossing, adding head-of-line blocking
14
- # behind slow handlers and stretching effective queue depth.
15
- module Worker
6
+ module Native
7
+ # @private
8
+ # The request handle is its own rack.hijack callable: calling it takes the connection over.
9
+ class Request
10
+ def call = UNIXSocket.for_fd(hijack).tap { Kino::Worker::Loop.switched(self) }
11
+
12
+ # Up to `max` bytes of the body, nil at its end; cooperative under a fiber scheduler.
13
+ def read_some(max) = Fiber.current_scheduler ? cooperatively { read_body_nonblock(max) } : read_body(max)
14
+
15
+ # All of `chunk`, onto the response stream, the way read_some waits.
16
+ def write_all(chunk) = Fiber.current_scheduler ? cooperatively { write_chunk_nonblock(chunk) } : write_chunk(chunk)
17
+
18
+ # Off a scheduler an inline write waits a TICK at a time, so a Thread#raise reaches it here.
19
+ def write_chunk(chunk)
20
+ nil while write_chunk_or_wait(chunk)
21
+ end
22
+
23
+ private
24
+
25
+ # Every request's fiber shares the thread: never block it. While the client is slower than
26
+ # the app, wait until the native side rings the descriptor it handed out.
27
+ # An inline request waits for its socket to take more ([:writable, fd]).
28
+ def cooperatively
29
+ loop do
30
+ case (step = yield)
31
+ when Integer then wait_until_rung(step)
32
+ when Array then wait_until_writable(step.last)
33
+ else return step
34
+ end
35
+ end
36
+ end
37
+
38
+ # The request's descriptor, open until #waited: this IO must never close it, and is made
39
+ # afresh each wait, as the number may change.
40
+ def wait_until_rung(fd)
41
+ IO.for_fd(fd, autoclose: false).wait_readable
42
+ ensure
43
+ waited
44
+ end
45
+
46
+ # The connection's descriptor, open until #waited_writable: this IO must never close it.
47
+ def wait_until_writable(fd)
48
+ IO.for_fd(fd, autoclose: false).wait_writable
49
+ ensure
50
+ waited_writable
51
+ end
52
+ end
53
+ end
54
+
55
+ # A worker's wake hook: work on the worker's own thread (::on_wake). Needs lanes.
56
+ # An instance is one worker thread's request loop (private API).
57
+ class Worker
16
58
  RACK_INPUT = "rack.input"
59
+ RACK_UPGRADE = "rack.upgrade"
60
+ RACK_HIJACK_OFFERED = "rack.hijack?"
61
+ RACK_HIJACK = "rack.hijack"
17
62
  KINO_REQUEST = "kino.request"
63
+ # Thread variables, so fibers on the thread see them: the native handle, the wake hook, the Loop.
64
+ HANDLE = :kino_worker
65
+ HOOK = :kino_wake_hook
66
+ CUSTOM_LOOP = :kino_worker_loop
67
+ WAKE = :wake
68
+ WAKE_ENV = Ractor.make_shareable({"kino.callback" => "on_wake"})
69
+ # What a worker without hooks runs with.
70
+ NO_HOOKS = Ractor.make_shareable(
71
+ WorkerHooks.new(on_error: nil, after_worker_boot: nil, after_request_complete: nil, worker_loop: nil,
72
+ access_timing: false)
73
+ )
74
+ private_constant :RACK_INPUT, :RACK_UPGRADE, :RACK_HIJACK_OFFERED, :RACK_HIJACK, :KINO_REQUEST, :HANDLE, :HOOK,
75
+ :CUSTOM_LOOP, :WAKE, :WAKE_ENV, :NO_HOOKS
76
+
77
+ # Wakes one worker's hook, from any thread or Ractor (frozen, shareable); returns at once.
78
+ class Waker
79
+ # @private
80
+ def initialize(server_id, worker_id, generation)
81
+ @server_id = server_id
82
+ @worker_id = worker_id
83
+ @generation = generation
84
+ freeze
85
+ end
86
+
87
+ # @return [Boolean] false once the worker has exited or is retiring, or without lanes
88
+ def wake = Native.wake_worker(@server_id, @worker_id, @generation)
89
+ end
18
90
 
19
- module_function
91
+ # Run `block` on this worker's thread, between requests and socket events, whenever the
92
+ # returned Waker is used; wakes coalesce, a self-waking hook alternates with waiting requests,
93
+ # and calling again replaces the hook. A raising hook goes to on_error, as on_wake's callback.
94
+ # Under a worker_loop it runs as a job of its own, alongside requests, one run at a time.
95
+ # @raise [ArgumentError] off a worker thread, or without a block
96
+ # @return [Waker] wakes this worker
97
+ def self.on_wake(&block)
98
+ thread = Thread.current
99
+ worker = thread.thread_variable_get(HANDLE)
100
+ raise ArgumentError, "Kino::Worker.on_wake must be called on a worker thread" unless worker
101
+ raise ArgumentError, "Kino::Worker.on_wake needs a block" unless block
20
102
 
21
- def run(server_id, worker_id, app, batch_size = 1, hooks = nil)
22
- fire_after_worker_boot(hooks, worker_id)
103
+ Log.warn(WAKE_WARNING) if !worker.lanes? && worker.claim_warning(WAKE_WARNING)
104
+ thread.thread_variable_set(HOOK, block)
105
+ Waker.new(*worker.identity)
106
+ end
107
+
108
+ # @private
109
+ # The request loop, the same in both modes. At batch 1 a request costs one Hash and about one
110
+ # FFI crossing (respond_and_take_one); batch > 1 trades fairness for fewer crossings.
111
+ # With no request waiting, the answer's body closes before the worker waits (take_one).
112
+ def self.run(server_id, worker_id, app, batch_size, hooks)
113
+ new(server_id, worker_id, app, batch_size, hooks).run
114
+ end
115
+
116
+ # @private
117
+ def initialize(server_id, worker_id, app, batch_size, hooks)
118
+ @server_id = server_id
119
+ @worker_id = worker_id
120
+ @app = app
121
+ @batch_size = batch_size
122
+ @hooks = hooks || NO_HOOKS
123
+ end
124
+
125
+ # @private
126
+ def run
23
127
  # One resolution of (server, worker) into a native handle; every take
24
128
  # after this skips the registry lookup. nil = server already gone.
25
- worker = Native.worker(server_id, worker_id)
26
- return unless worker
27
- if batch_size <= 1
28
- env = worker.take_one
29
- env = handle_one(env, worker, app, hooks) while env
30
- else
31
- batch = worker.take_batch(batch_size)
32
- batch = process(batch, worker, app, batch_size, hooks) while batch
33
- end
129
+ # Resolved before after_worker_boot, so that hook can call on_wake.
130
+ @worker = Native.worker(@server_id, @worker_id)
131
+ Thread.current.thread_variable_set(HANDLE, @worker)
132
+ HookFire.fire(@hooks.after_worker_boot, "after_worker_boot", @worker_id)
133
+ take_until_drained if @worker
134
+ ended = true
135
+ ensure
136
+ # Short of its loop's end the worker crashed, by an exception or a kill no rescue sees.
137
+ # Nothing waits on a dead worker: its clients get a 500 now, its sockets a 1011.
138
+ @worker&.crashed unless ended
139
+ # The worker loop is over: its wakers report false from now on.
140
+ @worker&.release
141
+ Thread.current.thread_variable_set(HANDLE, nil)
142
+ Thread.current.thread_variable_set(HOOK, nil)
143
+ Thread.current.thread_variable_set(CUSTOM_LOOP, nil)
34
144
  end
35
145
 
36
146
  # serve() returns this when the response did NOT ride a fused
37
147
  # respond-and-take (streaming body or app error) and the caller must
38
- # take the next request itself. Frozen: worker ractors read it.
39
- NOT_FUSED = Object.new.freeze
148
+ # take the next request itself, or when nothing waited for a fused take.
149
+ NOT_FUSED = false
150
+ private_constant :NOT_FUSED
151
+
152
+ private
40
153
 
41
- # Handle one request; returns the next env (fused take) or nil.
42
- def handle_one(env, worker, app, hooks)
43
- result = serve(env, app, hooks) do |request, status, headers, chunks|
44
- request.respond_and_take_one(worker, status, headers, chunks)
154
+ # The worker's loop, Kino's or the app's (worker_loop), until its queues close or it retires.
155
+ def take_until_drained
156
+ if (custom = @hooks.worker_loop)
157
+ served = Loop.new(self, @worker)
158
+ Thread.current.thread_variable_set(CUSTOM_LOOP, served)
159
+ custom.call(served)
160
+ # Its lane would stay open to dispatch with no one taking.
161
+ raise Error, "worker_loop returned before its worker was drained" unless served.drained?
162
+ elsif @batch_size <= 1
163
+ env = @worker.take_one
164
+ env = handle_one(env) while env
165
+ else
166
+ batch = @worker.take_batch(@batch_size)
167
+ batch = process(batch) while batch
45
168
  end
46
- result.equal?(NOT_FUSED) ? worker.take_one : result
47
169
  end
48
170
 
49
- # Handle every env in the batch; returns the next batch (the last
50
- # simple response rides the fused respond_and_take) or nil on shutdown.
51
- def process(batch, worker, app, batch_size, hooks)
171
+ # Handle one take; returns the next env (fused take) or nil.
172
+ def handle_one(env)
173
+ unless env.is_a?(Hash)
174
+ dispatch(env)
175
+ return @worker.take_one
176
+ end
177
+ result = serve(env) do |request, status, headers, chunks|
178
+ request.respond_and_take_one(@worker, status, headers, chunks)
179
+ end
180
+ result.equal?(NOT_FUSED) ? @worker.take_one : result
181
+ end
182
+
183
+ # Handle every take in the batch; returns the next batch (the last simple response
184
+ # rides the fused respond_and_take) or nil on shutdown.
185
+ def process(batch)
52
186
  last = batch.size - 1
53
187
  batch.each_with_index do |env, index|
54
- result = serve(env, app, hooks) do |request, status, headers, chunks|
188
+ unless env.is_a?(Hash)
189
+ dispatch(env)
190
+ next
191
+ end
192
+ result = serve(env) do |request, status, headers, chunks|
55
193
  if index == last
56
- request.respond_and_take(worker, batch_size, status, headers, chunks)
194
+ request.respond_and_take(@worker, @batch_size, status, headers, chunks)
57
195
  else
58
196
  request.send_simple(status, headers, chunks)
59
197
  NOT_FUSED
@@ -61,7 +199,18 @@ module Kino
61
199
  end
62
200
  return result if index == last && !result.equal?(NOT_FUSED)
63
201
  end
64
- worker.take_batch(batch_size)
202
+ @worker.take_batch(@batch_size)
203
+ end
204
+
205
+ def dispatch(item)
206
+ item.equal?(WAKE) ? run_wake_hook : WebSocket::Events.dispatch(item, @hooks.on_error)
207
+ end
208
+
209
+ def run_wake_hook
210
+ Thread.current.thread_variable_get(HOOK)&.call
211
+ rescue => e
212
+ Log.failure("on_wake hook", e)
213
+ HookFire.fire(@hooks.on_error, "on_error", e, WAKE_ENV)
65
214
  end
66
215
 
67
216
  # Run one request through the app. Complete bodies are yielded so the
@@ -70,40 +219,41 @@ module Kino
70
219
  # here and return NOT_FUSED. App errors must never kill the worker;
71
220
  # hard crashes (Exception) are the supervisor's job; and `abort` does
72
221
  # the right thing whether or not the response head already went out.
73
- def serve(env, app, hooks)
222
+ def serve(env)
74
223
  request = env[KINO_REQUEST]
75
224
  env[RACK_INPUT] ||= Input.new(request)
76
- if hooks&.access_timing
225
+ if @hooks.access_timing
77
226
  # The access log's breakdown: the VM's cumulative GC time and
78
227
  # allocation count, differenced around the app call.
79
228
  gc_before = GC.total_time
80
229
  allocated_before = GC.stat(:total_allocated_objects)
81
- status, headers, body = app.call(env)
230
+ status, headers, body = @app.call(env)
82
231
  request.timing(GC.total_time - gc_before, GC.stat(:total_allocated_objects) - allocated_before)
83
232
  else
84
- status, headers, body = app.call(env)
85
- end
86
-
87
- if body.respond_to?(:to_ary)
88
- chunks = join_chunks(body.to_ary)
89
- if hooks&.after_request_complete
90
- # Hook set: do not fuse. Send the complete response, fire the hook
91
- # after it is out, then signal the caller to take the next request
92
- # separately (so the hook never waits on the next request).
93
- request.send_simple(status.to_i, headers, chunks)
94
- body.close if body.respond_to?(:close)
95
- fire_after_request_complete(hooks, env, status.to_i)
96
- NOT_FUSED
97
- else
98
- # No hook: fused fast path, unchanged, zero cost.
99
- result = yield(request, status.to_i, headers, chunks)
100
- body.close if body.respond_to?(:close)
101
- result
233
+ status, headers, body = @app.call(env)
234
+ end
235
+ if env[RACK_HIJACK_OFFERED]
236
+ return NOT_FUSED if serve_hijacked(request, status, headers, body, env)
237
+ end
238
+ if (handler = env[RACK_UPGRADE])
239
+ return NOT_FUSED if serve_upgrade(request, headers, body, handler, env)
240
+ end
241
+
242
+ if body.respond_to?(:to_ary) && !@hooks.after_request_complete
243
+ # No hook: fused fast path, zero cost (an ensure runs inline). The body closes whatever the
244
+ # fused call raised; a failed close is reported here, and what the take brought is served.
245
+ begin
246
+ yield(request, status.to_i, headers, join_chunks(body.to_ary))
247
+ ensure
248
+ begin
249
+ body.close if body.respond_to?(:close)
250
+ rescue => e
251
+ Log.exception(e, env)
252
+ HookFire.fire(@hooks.on_error, "on_error", e, env)
253
+ end
102
254
  end
103
255
  else
104
- deliver_streaming(request, status.to_i, headers, body, env[RACK_INPUT])
105
- fire_after_request_complete(hooks, env, status.to_i)
106
- NOT_FUSED
256
+ deliver_unfused(request, status.to_i, headers, body, env)
107
257
  end
108
258
  rescue => e
109
259
  # Abort before the hook: the client's 500 must never wait on a
@@ -113,34 +263,153 @@ module Kino
113
263
  # because nothing may escape this block and kill the worker.
114
264
  Log.exception(e, env)
115
265
  request.abort
116
- HookFire.fire(hooks&.on_error, "on_error", e, env)
266
+ HookFire.fire(@hooks.on_error, "on_error", e, env)
117
267
  NOT_FUSED
118
268
  end
119
269
 
270
+ # A complete answer sent apart from the take (a hook is set, which never waits on the next
271
+ # request), or a streamed one.
272
+ def deliver_unfused(request, status, headers, body, env)
273
+ closing_reported(body, request, env) do
274
+ if body.respond_to?(:to_ary)
275
+ request.send_simple(status, headers, join_chunks(body.to_ary))
276
+ else
277
+ deliver_streaming(request, status, headers, body, env[RACK_INPUT])
278
+ end
279
+ end
280
+ after_request_complete(env, status)
281
+ NOT_FUSED
282
+ end
283
+
284
+ # What an app offered rack.hijack did with it: true once it took the connection over, in full
285
+ # or with a callable; nil when it answers as any other request.
286
+ def serve_hijacked(request, status, headers, body, env)
287
+ # Taken over with rack.hijack: the app answers on the connection, and its triple is
288
+ # ignored (Rack 3). The body still closes: middleware cleans up there.
289
+ return closing(body) { true } if request.hijacked?
290
+ partial = headers&.[](RACK_HIJACK)
291
+ if status.to_i == 101 && (partial || (!env[RACK_UPGRADE] && streaming_body?(body)))
292
+ closing(body) { switch_hijacked(request, headers, partial || body, body, env) }
293
+ elsif partial
294
+ closing(body) { hijack_partially(request, status, headers, partial, env) }
295
+ end
296
+ end
297
+
298
+ # A native WebSocket for `handler`: true once Kino answered the handshake (its 101, a 500
299
+ # or a 503), false when it cannot accept one and the app's response goes out.
300
+ def serve_upgrade(request, headers, body, handler, env)
301
+ id = accept_upgrade(request, headers, body, handler.respond_to?(:on_shutdown))
302
+ if id
303
+ # The 101 goes out only after on_open, so what it writes and subscribes is in place;
304
+ # if on_open raised, the client gets a 500 before on_error hears of it.
305
+ if (failure = Loop.opening(id) { WebSocket::Events.open(id, handler) })
306
+ request.abort
307
+ WebSocket::Events.report(failure, id, "on_open", @hooks.on_error)
308
+ elsif request.switch_protocols
309
+ after_request_complete(env, 101)
310
+ end
311
+ end
312
+ return true unless id.nil?
313
+
314
+ # Once per server, from the first worker that meets the cause.
315
+ Log.warn(UPGRADE_WARNING) if !@worker.lanes? && @worker.claim_warning(UPGRADE_WARNING)
316
+ false
317
+ end
318
+
319
+ # Accept a handshake, its 101 held for switch_protocols with the app's headers, and close
320
+ # the body. Nil when Kino cannot (no handshake, no lanes): the app's response goes out.
321
+ # False for Kino's 503 refusal. A body that fails to close drops the new socket (a 500).
322
+ def accept_upgrade(request, headers, body, on_shutdown)
323
+ id = request.upgrade_websocket(headers || {}, on_shutdown)
324
+ closing(body) unless id.nil?
325
+ id
326
+ rescue
327
+ closing(body) if id.nil?
328
+ Native.ws_abort(id) if id
329
+ raise
330
+ end
331
+
332
+ # Partial hijack (Rack 3): the rack.hijack callable gets the response stream after the head.
333
+ def hijack_partially(request, status, headers, callable, env)
334
+ deliver_streaming(request, status.to_i, headers.except(RACK_HIJACK), callable, env[RACK_INPUT])
335
+ after_request_complete(env, status.to_i)
336
+ true
337
+ end
338
+
339
+ # A 101 with a callable (a partial hijack, or a Rack 3 streaming body): the callable gets
340
+ # the switched connection as a socket. Kino closes it once a streaming body returns.
341
+ def switch_hijacked(request, headers, callable, body, env)
342
+ io = UNIXSocket.for_fd(request.hijack_switched(headers.except(RACK_HIJACK)))
343
+ Loop.switched(request)
344
+ begin
345
+ callable.call(io)
346
+ rescue
347
+ io.close
348
+ raise
349
+ end
350
+ io.close if callable.equal?(body) && !io.closed?
351
+ after_request_complete(env, 101)
352
+ true
353
+ end
354
+
355
+ # Runs the block, if any, then closes `body` however it ended.
356
+ def closing(body)
357
+ yield if block_given?
358
+ ensure
359
+ body.close if body.respond_to?(:close)
360
+ end
361
+
362
+ # The block, then `body` closed however it ended. A failed close raises into serve's rescue
363
+ # after a block that returned; after one that raised, it is reported here, its 500 first.
364
+ def closing_reported(body, request, env)
365
+ yield
366
+ done = true
367
+ ensure
368
+ begin
369
+ body.close if body.respond_to?(:close)
370
+ rescue => e
371
+ raise if done
372
+ request.abort
373
+ Log.exception(e, env)
374
+ HookFire.fire(@hooks.on_error, "on_error", e, env)
375
+ end
376
+ end
377
+
378
+ def streaming_body?(body) = body.respond_to?(:call) && !body.respond_to?(:each)
379
+
380
+ UPGRADE_WARNING = "the app set rack.upgrade, but native WebSockets need `lanes true`; " \
381
+ "sending its own response instead"
382
+ WAKE_WARNING = "the app registered a Kino::Worker.on_wake hook, but wakes need `lanes true`; " \
383
+ "the hook will never run"
384
+ private_constant :UPGRADE_WARNING, :WAKE_WARNING
385
+
386
+ # Sends the head, then what `body` streams; closing the body is its caller's (Rack).
120
387
  def deliver_streaming(request, status, headers, body, input)
121
388
  request.send_headers(status, headers)
122
- if body.respond_to?(:call) && !body.respond_to?(:each)
389
+ if streaming_body?(body)
123
390
  # Rack 3 streaming body: the app drives a full-duplex stream whose
124
391
  # read side is the request's existing rack.input (a fresh Input
125
392
  # here would strand anything the app already buffered from it).
393
+ # Its write side closes only on success; a raising body is cut by serve's abort.
126
394
  stream = Stream.new(request, input)
127
395
  begin
128
396
  body.call(stream)
129
- ensure
130
- stream.close
397
+ rescue
398
+ stream.close_read
399
+ raise
131
400
  end
401
+ stream.close
132
402
  else
133
403
  # Enumerable body: chunked transfer unless the app set content-length.
134
404
  # finish only on success: a body that raised must abort the
135
405
  # connection (serve's rescue), not fake a clean end of stream that
136
406
  # the client cannot tell from a complete response.
137
- begin
138
- body.each { |chunk| request.write_chunk(chunk) }
139
- request.finish
140
- ensure
141
- body.close if body.respond_to?(:close)
142
- end
407
+ body.each { |chunk| request.write_all(chunk) }
408
+ request.finish
143
409
  end
410
+ rescue ClientGone
411
+ # The client left mid-stream: the request is over, and nothing failed.
412
+ nil
144
413
  end
145
414
 
146
415
  def join_chunks(chunks)
@@ -153,15 +422,12 @@ module Kino
153
422
  joined
154
423
  end
155
424
 
156
- def fire_after_worker_boot(hooks, worker_id)
157
- HookFire.fire(hooks&.after_worker_boot, "after_worker_boot", worker_id)
158
- end
159
-
160
- def fire_after_request_complete(hooks, env, status)
161
- HookFire.fire(hooks&.after_request_complete, "after_request_complete", env, status)
425
+ def after_request_complete(env, status)
426
+ HookFire.fire(@hooks.after_request_complete, "after_request_complete", env, status)
162
427
  end
163
428
 
164
- private_class_method :handle_one, :process, :serve, :deliver_streaming,
165
- :join_chunks, :fire_after_worker_boot, :fire_after_request_complete
429
+ # @private
430
+ # A worker_loop's jobs run these (Worker::Loop).
431
+ public :serve, :dispatch
166
432
  end
167
433
  end
@@ -1,13 +1,19 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kino
4
+ # The hooks that run in worker context and so must be shareable (after_boot and
5
+ # on_worker_exit run on the main thread).
6
+ WORKER_HOOKS = %i[on_error after_worker_boot after_request_complete worker_loop].freeze
7
+ private_constant :WORKER_HOOKS
8
+
4
9
  # @private
5
10
  # The worker-context lifecycle hooks, bundled so one frozen, shareable
6
11
  # value crosses into each worker (a ractor in :ractor mode) instead of
7
12
  # several bare procs. Any member may be nil. A Data instance is frozen,
8
13
  # so it is Ractor.shareable? exactly when its members are (nil, or a
9
14
  # Ractor.shareable_proc), letting it ride the ractor boundary like the app.
15
+ # `worker_loop`, when set, runs the worker's loop in place of Kino's.
10
16
  # `access_timing` rides along: whether the worker measures the GC pause
11
17
  # and allocations around each app call for the access log's breakdown.
12
- WorkerHooks = Data.define(:on_error, :after_worker_boot, :after_request_complete, :access_timing)
18
+ WorkerHooks = Data.define(*WORKER_HOOKS, :access_timing)
13
19
  end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kino
4
+ # @private
5
+ # One slot's row of Native.worker_stats, by name; `slot` is the :index of a Server#stats
6
+ # worker_status row.
7
+ WorkerRow = Struct.new(:slot, :served, :in_flight, :busy_ms, :quarantined, :retired,
8
+ :websockets_open, :hijacked_connections, :generation) do
9
+ # Every slot's row; none once the server is gone.
10
+ def self.all(server_id) = Native.worker_stats(server_id).map { |row| new(*row) }
11
+
12
+ # Whether the slot holds a request, an open WebSocket or a hijacked connection.
13
+ def occupied? = in_flight.positive? || websockets_open.positive? || hijacked_connections.positive?
14
+ end
15
+ end
data/lib/kino.rb CHANGED
@@ -9,15 +9,21 @@ require "kino/kino"
9
9
  # Ractor-shareable.
10
10
  #
11
11
  # The public API is {Kino::Server}, {Kino::Configuration}, {Kino::Check},
12
- # {Kino::Logger}, and {Kino.sleep}; the `kino` executable is implemented
13
- # by {Kino::CLI}.
12
+ # {Kino::Logger}, {Kino::WebSocket}, {Kino::Worker.on_wake},
13
+ # {Kino::Worker::Loop} (what a `worker_loop` serves with), and
14
+ # {Kino.sleep}; the `kino` executable is implemented by {Kino::CLI}.
14
15
  module Kino
15
- # Base class for all errors raised by Kino.
16
+ # Base class for the errors Kino raises (ClientGone aside).
16
17
  class Error < StandardError; end
17
18
 
18
19
  # Raised when mode: :ractor is forced but the app is not Ractor-shareable.
19
20
  class UnshareableAppError < Error; end
20
21
 
22
+ # Raised by a streaming body's write once nothing reaches the client: it left, Kino cut the
23
+ # response, or the response has no body (HEAD, 204, 304, a request_timeout 504). An IOError,
24
+ # so a body that stops on IOError needs no change; Kino ends the request quietly.
25
+ class ClientGone < IOError; end
26
+
21
27
  # High-resolution sleep that bypasses the VM timer (whose wakeups inside
22
28
  # non-main ractors are coarse: ~+2.5ms on Linux). Sleeps on the OS clock
23
29
  # with the GVL released; chunked so Thread#kill and shutdown interrupts
@@ -43,6 +49,18 @@ module Kino
43
49
  def self.available_parallelism
44
50
  Native.available_parallelism
45
51
  end
52
+
53
+ # @private
54
+ # Seconds on the monotonic clock; callable from any Ractor.
55
+ def self.monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
56
+
57
+ # How many ractors Ruby runs at once: RUBY_MAX_CPU, 8 when unset or
58
+ # not an integer.
59
+ #
60
+ # @return [Integer]
61
+ def self.ruby_max_cpu
62
+ Integer(ENV.fetch("RUBY_MAX_CPU", "8"), exception: false) || 8
63
+ end
46
64
  end
47
65
 
48
66
  require_relative "kino/cli"
@@ -53,11 +71,17 @@ require_relative "kino/input"
53
71
  require_relative "kino/null_input"
54
72
  require_relative "kino/errors_stream"
55
73
  require_relative "kino/stream"
74
+ require_relative "kino/web_socket"
56
75
  require_relative "kino/configuration"
57
76
  require_relative "kino/hook_fire"
77
+ require_relative "kino/teardown"
58
78
  require_relative "kino/worker_hooks"
59
79
  require_relative "kino/worker"
80
+ require_relative "kino/worker/loop"
81
+ require_relative "kino/worker_row"
60
82
  require_relative "kino/slot_bank"
83
+ require_relative "kino/crash_backoff"
84
+ require_relative "kino/pool"
61
85
  require_relative "kino/ractor_supervisor"
62
86
  require_relative "kino/threaded_pool"
63
87
  require_relative "kino/monitor"
@@ -40,7 +40,7 @@ module Rackup
40
40
  {
41
41
  "Host=HOST" => "Address to bind (default: 127.0.0.1)",
42
42
  "Port=PORT" => "Port to listen on (default: 9292)",
43
- "Workers=COUNT" => "Workers: ractors in :ractor mode, thread groups in :threaded (default: one per CPU)",
43
+ "Workers=COUNT" => "Workers: ractors in :ractor mode, thread groups in :threaded (default: one per CPU; in :ractor mode, at most RUBY_MAX_CPU)",
44
44
  "Threads=COUNT" => "Threads per worker (default: 1 in :ractor, 3 in :threaded)",
45
45
  "Mode=MODE" => "auto | ractor | threaded (default: auto)",
46
46
  "Config=PATH" => "Kino config file (default: kino.rb, then config/kino.rb)"