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.
@@ -0,0 +1,319 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kino
4
+ class Worker
5
+ # What a `worker_loop` gets on its worker thread: Kino's loop, for the app's scheduler (#serve).
6
+ class Loop
7
+ # Seconds between lane ticks: the native ticker rings a doorbell wait, and a job wait ends, as often.
8
+ TICK = Native::TICK_SECONDS
9
+ # The most socket events and wakes taken and not yet done: with this many the loop takes requests
10
+ # only, and the native inbox, filling, pushes back on the sockets.
11
+ BACKLOG = 64
12
+ JOB_LOST = "a worker_loop job ended before its socket events or wakes were done"
13
+ LINGER = 1.0
14
+ LINGERING = "the worker_loop is still running #{LINGER} s after its serve returned; most likely " \
15
+ "a task that is not transient keeps its scheduler, and so the worker, from finishing".freeze
16
+ private_constant :TICK, :BACKLOG, :JOB_LOST, :LINGER, :LINGERING
17
+
18
+ # @private
19
+ # `serving` is the Kino::Worker whose requests and events the jobs run, `worker` its native handle.
20
+ def initialize(serving, worker)
21
+ @serving = serving
22
+ @worker = worker
23
+ # The descriptor is the native worker's; this IO must never close it.
24
+ @ready = IO.for_fd(worker.ready_fd, autoclose: false)
25
+ # Wakes for the loop: a job freed its slot, the backlog drained, a job ended while the loop
26
+ # drains, or a socket's (or the wakes') job ended before its events were done.
27
+ @done = Thread::Queue.new
28
+ # Each request job's request: true while it holds a slot, false once its connection switched.
29
+ @requests = {}.compare_by_identity
30
+ # Each socket's events not yet done, in order, the first running; the wakes under WAKE.
31
+ @pending = {}
32
+ # Each inline connection on a job, with the IO its job waits on.
33
+ @conns = {}.compare_by_identity
34
+ @running = 0
35
+ @backlog = 0
36
+ @waiting = @backlogged = @draining = @lost = @drained = false
37
+ end
38
+
39
+ # @private
40
+ def drained? = @drained
41
+
42
+ # @private
43
+ # Warns once per drain about each loop still running LINGER after its serve returned.
44
+ def self.warn_lingering(server_id)
45
+ Native.lingering_loops(server_id, LINGER).each { |label| Native.log_line("warn", label, LINGERING) }
46
+ end
47
+
48
+ # @private
49
+ # `request`'s connection switched (rack.hijack, or a 101 with a callable): its job frees its slot.
50
+ def self.switched(request) = current&.switched(request)
51
+
52
+ # @private
53
+ # A socket's on_open, on its request's job: the socket's later events wait, then get a job.
54
+ def self.opening(id, &on_open)
55
+ custom = current
56
+ custom ? custom.opening(id, &on_open) : yield
57
+ end
58
+
59
+ # The loop serving on this thread, if a worker_loop runs it.
60
+ def self.current = Thread.current.thread_variable_get(CUSTOM_LOOP)
61
+ private_class_method :current
62
+
63
+ # @private
64
+ def opening(id)
65
+ pending = @pending[id] ||= []
66
+ yield
67
+ ensure
68
+ pending.empty? ? @pending.delete(id) : start_pending(id, pending)
69
+ end
70
+
71
+ # @private
72
+ def switched(request)
73
+ return unless @requests[request]
74
+
75
+ @requests[request] = false
76
+ free_slot(always: true)
77
+ end
78
+
79
+ # Serve this worker's requests, at most `concurrency` at a time, each as a job the block starts
80
+ # on the thread's fiber scheduler (`task.async { job.call }` under Async) and runs until it first
81
+ # waits, lest dispatch read the worker as idle. Each WebSocket's events, and the wakes, run in
82
+ # order on jobs of their own. Returns once the worker is drained and every job has finished.
83
+ # A connection served inline runs on a job of its own, each request counting toward
84
+ # `concurrency`, and may step aside once after an answer (`yield`, else `kernel_sleep(0)`).
85
+ # @param concurrency [Integer] the most requests running at once; one whose connection
86
+ # switched counts no more
87
+ # @yieldparam job [#call] runs one request, a socket's events, or the wakes
88
+ # @return [nil]
89
+ # @raise [ArgumentError] without a fiber scheduler on this thread
90
+ # @raise [Kino::Error] when a socket's job, or the wakes', ends before its events were done
91
+ def serve(concurrency:, &spawn)
92
+ raise ArgumentError, "worker.serve needs a fiber scheduler on this thread" unless Fiber.current_scheduler
93
+ raise ArgumentError, "worker.serve needs a block that starts each job" unless spawn
94
+ concurrency = Integer(concurrency)
95
+ raise ArgumentError, "concurrency must be positive (got #{concurrency})" unless concurrency.positive?
96
+
97
+ @worker.capacity = concurrency
98
+ @spawn = spawn
99
+ @concurrency = concurrency
100
+ loop do
101
+ @done.clear
102
+ raise Error, JOB_LOST if @lost
103
+ room = room?
104
+ @backlogged = @backlog >= BACKLOG
105
+ case (item = take(room))
106
+ when Hash
107
+ @running += 1
108
+ # Kept from here on: the app may replace the env's entry.
109
+ request = item[KINO_REQUEST]
110
+ @requests[request] = true
111
+ spawn.call(-> { run_request(item, request) })
112
+ when Native::Conn
113
+ @conns[item] = nil
114
+ spawn.call(-> { run_conn(item) })
115
+ when Array, WAKE then queue(item)
116
+ when nil then break
117
+ end
118
+ end
119
+ @draining = true
120
+ # Each connection's job looks once more, so a retired worker's go to hyper: closing the IO it
121
+ # waits on wakes it (under a scheduler with fiber_interrupt) and leaves the descriptor open.
122
+ @conns.each_value { it&.close }
123
+ @done.pop until @requests.empty? && @pending.empty? && @conns.empty?
124
+ raise Error, JOB_LOST if @lost
125
+ @drained = true
126
+ @worker.drained(Log.source)
127
+ nil
128
+ end
129
+
130
+ private
131
+
132
+ # Takes what there is room for (Native::Worker#take_nonblock), else waits; false: take again.
133
+ def take(room)
134
+ only = if room
135
+ :requests if @backlogged
136
+ else
137
+ @backlogged ? :connections : :events
138
+ end
139
+ item = only ? @worker.take_nonblock(only) : @worker.take_nonblock
140
+ return item unless item == false
141
+
142
+ case only
143
+ when nil then idle
144
+ when :connections then full
145
+ else busy(only)
146
+ end
147
+ end
148
+
149
+ # Neither fits: wait for a job or the backlog, back every TICK so the worker never reads stuck.
150
+ # A connection placed meanwhile is taken then.
151
+ def full
152
+ @worker.woke unless @done.pop(timeout: TICK)
153
+ false
154
+ end
155
+
156
+ # No timeout, so no scheduler timer: the ticker rings a waiting doorbell every TICK (a lane tick).
157
+ def idle
158
+ @ready.wait_readable
159
+ return @worker.take_woken if room?
160
+
161
+ @worker.woke
162
+ false
163
+ end
164
+
165
+ # A job that ended, the backlog drained or inline requests taking the room change what fits.
166
+ def busy(only)
167
+ @waiting = true
168
+ @ready.wait_readable if @done.empty?
169
+ return @worker.take_woken(only) if @done.empty? && (only == :events || room?)
170
+
171
+ @worker.woke
172
+ false
173
+ ensure
174
+ @waiting = false
175
+ end
176
+
177
+ def room? = @running < @concurrency
178
+
179
+ # An inline connection's requests, one at a time while the worker has room; between them the
180
+ # job waits on the socket, which only the native side reads, writes and closes.
181
+ def run_conn(conn)
182
+ io = watch(conn)
183
+ loop do
184
+ case (got = conn.next_request(room?))
185
+ when Hash then run_inline(got)
186
+ when :yield then yield_turn
187
+ when :readable, :writable
188
+ begin
189
+ (got == :readable) ? io.wait_readable : io.wait_writable
190
+ rescue IOError
191
+ raise unless io.closed?
192
+ io = watch(conn)
193
+ end
194
+ else break
195
+ end
196
+ end
197
+ ensure
198
+ conn.close
199
+ @conns.delete(conn)
200
+ @done << 0 if @draining
201
+ end
202
+
203
+ # Every fiber already ready runs before the job looks again, as async-http yields after each
204
+ # response: the scheduler's own yield where it has one, else kernel_sleep(0).
205
+ def yield_turn
206
+ scheduler = Fiber.current_scheduler or return
207
+ scheduler.respond_to?(:yield) ? scheduler.yield : scheduler.kernel_sleep(0)
208
+ end
209
+
210
+ # The IO the loop closes to wake the job; the descriptor is the connection's, never this IO's.
211
+ def watch(conn)
212
+ fd = conn.fd
213
+ @conns[conn] = fd && IO.for_fd(fd, autoclose: false)
214
+ end
215
+
216
+ # No rescue: whatever unwinds the job, the connection's close (run_conn) answers with a 500.
217
+ # Worker#serve straight from the job: a method between would cost a Ruby call per request.
218
+ def run_inline(env)
219
+ @running += 1
220
+ request = env[KINO_REQUEST]
221
+ @serving.serve(env) do |_request, status, headers, chunks|
222
+ request.send_simple(status, headers, chunks)
223
+ end
224
+ ensure
225
+ request&.close_waits
226
+ free_slot(always: false)
227
+ end
228
+
229
+ def run_request(env, request)
230
+ @serving.serve(env) do |_request, status, headers, chunks|
231
+ request.send_simple(status, headers, chunks)
232
+ end
233
+ rescue Exception # rubocop:disable Lint/RescueException -- the job's failure is the app's scheduler's to see
234
+ # Kino's own rescue failed: the client must not wait for the handle to be collected.
235
+ request.abort
236
+ raise
237
+ ensure
238
+ request.close_waits
239
+ if @requests.delete(request)
240
+ free_slot(always: true)
241
+ elsif @draining
242
+ @done << 0
243
+ end
244
+ end
245
+
246
+ # The count drops at once, for a connection's job that resumes first. The loop hears of it from a
247
+ # request job, or when the worker was full, which dispatch counts until its loop's next take.
248
+ def free_slot(always:)
249
+ was_full = !room?
250
+ @running -= 1
251
+ @done << 0 if always || was_full
252
+ @worker.ring if @waiting || was_full
253
+ end
254
+
255
+ # An event waits on its socket's job, or starts one; a wake folds into one waiting to run.
256
+ def queue(item)
257
+ key = item.equal?(WAKE) ? WAKE : item.first
258
+ pending = @pending[key]
259
+ return if pending && key.equal?(WAKE) && pending.size > 1
260
+
261
+ @backlog += 1
262
+ return pending << item if pending
263
+
264
+ start_pending(key, @pending[key] = [item])
265
+ end
266
+
267
+ # A scheduler that refuses the job (a closing one raises) loses its events: the loop hears so.
268
+ def start_pending(key, pending)
269
+ @spawn.call(-> { run_pending(key, pending) })
270
+ rescue Exception # rubocop:disable Lint/RescueException -- the events are lost, whatever was raised
271
+ @pending.delete(key)
272
+ lose_events
273
+ raise
274
+ end
275
+
276
+ def run_pending(key, pending)
277
+ until pending.empty?
278
+ run_event(pending.first)
279
+ pending.shift
280
+ @backlog -= 1
281
+ relieve if @backlogged && @backlog < BACKLOG
282
+ end
283
+ ensure
284
+ @pending.delete(key)
285
+ if pending.empty?
286
+ @done << 0 if @draining
287
+ else
288
+ # The app's scheduler stopped it.
289
+ lose_events
290
+ end
291
+ end
292
+
293
+ # Events will never run: serve raises once it hears.
294
+ def lose_events
295
+ @lost = true
296
+ @done << 0
297
+ @worker.ring
298
+ end
299
+
300
+ def relieve
301
+ @backlogged = false
302
+ @done << 0
303
+ @worker.ring if @waiting
304
+ end
305
+
306
+ # A failed report must not end the job either; its socket is dropped all the same, as a crash.
307
+ def run_event(item)
308
+ @serving.dispatch(item)
309
+ rescue => e
310
+ Native.ws_fail(item.first) if item.is_a?(Array)
311
+ begin
312
+ Log.failure("worker_loop event", e)
313
+ rescue
314
+ Log.error("worker_loop event · #{e.class} (its report failed too)")
315
+ end
316
+ end
317
+ end
318
+ end
319
+ end