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.
@@ -0,0 +1,462 @@
1
+ # Fibers inside Kino workers: `worker_loop` (experimental)
2
+
3
+ Kino's own loop runs one request at a time on each worker thread, so a
4
+ request that waits (on a database permit, an upstream API, a slow
5
+ client) holds its worker until it is done. `worker_loop` lets your app
6
+ run its own fiber scheduler on every Kino worker thread, in both modes.
7
+ Kino hands the scheduler each request as a job: a request that waits
8
+ suspends only its fiber, and the worker takes the next one meanwhile.
9
+ Kino keeps the Ractors, the threads, dispatch and all of HTTP. It ships
10
+ no scheduler and depends on none: Async is the example on this page,
11
+ and any `Fiber::Scheduler` works. How it works inside is in
12
+ [architecture.md](architecture.md#worker-loops).
13
+
14
+ Turn it on when your requests spend their time waiting and you want
15
+ many of them on one worker, or when your app is fiber-native already.
16
+ For requests that never wait, Kino's own loop stays the leaner path
17
+ (see [Per-request cost](#per-request-cost)). A request on an
18
+ [inline connection](#inline-connections) gets no fiber of its own: its
19
+ connection's job runs it.
20
+
21
+ ## Setting it up
22
+
23
+ ```ruby
24
+ # kino.rb
25
+ require "async"
26
+
27
+ threads 1
28
+ worker_loop Ractor.shareable_proc { |worker|
29
+ Sync do |task|
30
+ # This worker's own background tasks, if any, start here as
31
+ # transient tasks (see "Background work" below).
32
+ worker.serve(concurrency: 32) { |job| task.async { job.call } }
33
+ end
34
+ }
35
+ ```
36
+
37
+ Or pass `worker_loop:` to `Kino::Server.new`. The sample config that
38
+ `kino --init` writes has the same example, commented out.
39
+
40
+ - Kino calls the proc once on each worker thread, after
41
+ `after_worker_boot`, with that worker's `Kino::Worker::Loop`. In
42
+ `:ractor` mode it runs inside the worker Ractor, so build it with
43
+ `Ractor.shareable_proc`: with a plain block, `:auto` mode falls back
44
+ to `:threaded` with a warning, and `mode :ractor` refuses to start.
45
+ - `worker.serve(concurrency:) { |job| ... }` is Kino's loop, written for
46
+ a scheduler: without one on the thread it raises `ArgumentError`.
47
+ `concurrency` is a positive Integer, the most requests the worker
48
+ runs at once.
49
+ - The block starts each job on the scheduler, and must run it at once
50
+ until it first waits, as `task.async { job.call }` does under Async
51
+ (and `Fiber.schedule { job.call }` under any scheduler); see
52
+ [Dispatch](#dispatch). Jobs must run on the worker thread, as fibers
53
+ of its scheduler: never hand one to another thread or a thread pool.
54
+ - `serve` returns `nil` once the worker is drained (the server shuts
55
+ down, or the elastic pool retires the worker) and every job has
56
+ finished. Let the proc return only after `serve` has: Kino treats an
57
+ earlier return as a crash (`Kino::Error`, "worker_loop returned
58
+ before its worker was drained"), and a new worker takes its place.
59
+ - `worker_loop` turns `lanes` on; `lanes false` with a `worker_loop`
60
+ raises `ArgumentError`. `batch` has no effect, and Kino warns when it
61
+ is set.
62
+ - `threads 1` is the natural setting: the fibers are the concurrency.
63
+ For parallelism, raise `workers` in `:ractor` mode; in `:threaded`
64
+ mode every loop shares the GVL.
65
+
66
+ ## What runs where
67
+
68
+ Everything on a worker still runs on its one thread, so nothing on it
69
+ runs in parallel; requests, WebSocket callbacks and the wake hook
70
+ interleave wherever one of them waits. State they share across a wait
71
+ needs the care any fiber-concurrent code needs.
72
+
73
+ ### Requests
74
+
75
+ Each request that comes through the worker's lane is one job (an inline
76
+ connection's requests run on its job instead: see
77
+ [Inline connections](#inline-connections)), which does what Kino's own
78
+ loop does for a request, from the env to `after_request_complete`. A job
79
+ raises into your scheduler only when Kino's own handling failed, after
80
+ the client got its 500. Stopping a request's job from outside aborts its
81
+ request (a 500, or a cut connection mid-stream) and frees its slot.
82
+
83
+ `concurrency` counts a request from the moment the loop takes it until
84
+ its job ends, `after_request_complete` included. A native WebSocket
85
+ handshake is a request like any other; the socket's events then go to
86
+ a job of their own (below). A request stops counting before its job
87
+ ends only when the app takes its connection over: a full `rack.hijack`,
88
+ or a 101 answered with a callable (a partial hijack, or a Rack 3
89
+ streaming body). A partial hijack with any other status is a streamed
90
+ response and counts until it ends. With `concurrency` requests running,
91
+ the loop takes no more requests, though it keeps taking socket events
92
+ and wakes.
93
+
94
+ ### What carries over between requests
95
+
96
+ Requests run on fibers that outlive them: every request a worker takes
97
+ in Kino's own loop runs on its thread, every request of an
98
+ [inline connection](#inline-connections) on that connection's job, and
99
+ under the [runner recipe](#per-request-cost) every request a runner
100
+ takes on that runner. So fiber-local state one request sets
101
+ (`Thread.current[]`, `Fiber[]`, task-local state) is still there for a
102
+ later one, which can be another client's (on an inline connection,
103
+ behind a proxy that reuses its connections to Kino). Kino resets none
104
+ of it: reset what you set, per request, as on any server that reuses
105
+ threads; Rails' executor resets its own state. Only a request on a new
106
+ task (each lane request under the spawn block above; under the recipe,
107
+ one that starts a runner or finds every runner busy) begins with a
108
+ fiber of its own, its `Fiber[]` a copy of the loop's.
109
+
110
+ ### WebSockets
111
+
112
+ - Each socket's events run one at a time and in order, on a job of
113
+ their own while the socket has any. Different sockets' callbacks run
114
+ concurrently: an `on_message` that waits holds up only its own
115
+ socket. Socket jobs do not count toward `concurrency`.
116
+ - `on_open` runs on the handshake's job, before the client gets the
117
+ 101. Events that arrive meanwhile wait behind it, even when the
118
+ handshake timed out (`request_timeout`) while `on_open` ran.
119
+ `on_close` is the socket's last event.
120
+ - A worker's loop holds at most 64 socket events and wakes it has taken
121
+ and not yet done. At that many it takes only requests until some are
122
+ done, and Kino pushes back on the sockets' clients meanwhile. At most
123
+ 16 of one socket's messages wait or run at once, so one flooding
124
+ socket never fills the backlog alone.
125
+ - A callback that raises is handled as in Kino's own loop, and the
126
+ events behind it keep running.
127
+
128
+ Everything else in [websockets.md](websockets.md) holds under a
129
+ `worker_loop` too: flow control, topics, limits, pings and the drain's
130
+ goodbye.
131
+
132
+ ### The wake hook
133
+
134
+ `Kino::Worker.on_wake` works as in Kino's own loop: register it in
135
+ `after_worker_boot`, or in the `worker_loop` proc before `serve`. Its
136
+ runs go on a job of their own, alongside requests and socket callbacks
137
+ rather than between them, and never two at once: wakes that come while
138
+ it runs fold into one more run. The wake job does not count toward
139
+ `concurrency`.
140
+
141
+ ### Background work
142
+
143
+ Background work that belongs to a worker can run as tasks on its
144
+ scheduler, started inside the `Sync` block before `serve`. Start them
145
+ transient, or stop them once `serve` has returned:
146
+
147
+ ```ruby
148
+ Sync do |task|
149
+ task.async(transient: true) { loop { MyApp.flush; sleep 1 } }
150
+ worker.serve(concurrency: 32) { |job| task.async { job.call } }
151
+ end
152
+ ```
153
+
154
+ `Sync` waits for every task that is not transient, so a periodic task
155
+ started with a plain `task.async` would keep the worker from returning
156
+ after a drain: shutdown would wait out `shutdown_timeout`, and a
157
+ retired worker would never leave. Kino logs a warning for each worker
158
+ whose `worker_loop` still runs a second after its `serve` returned.
159
+
160
+ ### Jobs your scheduler stops
161
+
162
+ A socket's job and the wake job carry events Kino has already taken
163
+ from the worker's queues. When your scheduler stops one of them before
164
+ its events are done, nothing else would run those events, so `serve`
165
+ raises `Kino::Error` ("a worker_loop job ended before its socket events
166
+ or wakes were done"), and the worker crashes and is replaced.
167
+
168
+ ## Waiting the right way
169
+
170
+ Whatever waits through the scheduler suspends only its fiber:
171
+
172
+ - `sleep`, Ruby's socket and pipe I/O, `Thread::Queue#pop`, `Mutex`, and
173
+ the scheduler's own primitives;
174
+ - Kino's body I/O: `rack.input` reads, and the writes of a streamed
175
+ response (an enumerable body, or a Rack 3 stream). On a request that
176
+ came through hyper, while the client is slower than the app, the fiber
177
+ waits on a descriptor and costs no wake-ups meanwhile. Each such
178
+ request holds up to four descriptors that `max_connections` does not
179
+ count: near the open-file limit, many slow clients can run the process
180
+ out of descriptors, and a wait then raises an `IOError` in the app.
181
+ Leave room for them in `ulimit -n`. On an
182
+ [inline connection](#inline-connections), Kino reads the body whole
183
+ before the app runs, so `rack.input` never waits, and a streamed write
184
+ waits on the connection's own socket.
185
+
186
+ Whatever blocks the thread instead holds every fiber on the worker:
187
+
188
+ - `Kino.sleep`, which waits on the OS clock: use `sleep` under a
189
+ `worker_loop`;
190
+ - a C extension call that blocks without going through the scheduler
191
+ (some database drivers do);
192
+ - CPU-bound work, and anything inside `Fiber.blocking { }`.
193
+
194
+ Body I/O otherwise behaves as in Kino's own loop. A write raises
195
+ `Kino::ClientGone` once the client has gone or Kino has cut the stream
196
+ (see [Streaming responses](streaming.md#streaming-responses)), and a
197
+ body read still waiting on its client when shutdown passes its deadline
198
+ raises `RuntimeError` ("Kino: request interrupted during shutdown").
199
+ Beyond that:
200
+
201
+ - While a thread of the app's own waits to read a request's body, the
202
+ connection cannot change hands under that read: `rack.hijack` raises
203
+ an `IOError`, and a native WebSocket handshake or a 101 with a
204
+ callable gets a 500. A fiber's wait on the body holds nothing.
205
+ - A request's reader and its writer wait apart, so a full-duplex body
206
+ can read on one fiber while it writes on another. Two fibers that
207
+ wait on the same side of one request can take each other's wake-up,
208
+ and one then waits for the next change.
209
+
210
+ These waits work under any scheduler: an app on Kino's own loop that
211
+ reads `rack.input` inside `Sync { }` gets them too. There an enumerable
212
+ body is written after the app returned, outside its scheduler, the
213
+ blocking way.
214
+
215
+ ## Shutdown and retirement
216
+
217
+ When the server drains, or the elastic pool retires the worker, the loop
218
+ takes nothing more and `serve` waits for every job: suspended requests,
219
+ work in `after_request_complete`, jobs serving switched connections,
220
+ inline connections' jobs, and each socket's remaining events up to its
221
+ `on_close`. How each inline connection ends then is in
222
+ [architecture.md](architecture.md#inline-connections). A drain waits up
223
+ to `shutdown_timeout` for that, and past it gives up on what still runs
224
+ as it does on a stuck handler: clients still waiting get a 500 or a cut
225
+ connection, and body reads still waiting raise.
226
+
227
+ A drain closes connections that switched protocols once requests have
228
+ drained, so the jobs serving them read EOF and can end. A hijacked
229
+ request the app has not answered yet, such as a long poll held on its
230
+ fiber, stays open until the workers have stopped, so its job holds the
231
+ drain until it answers, up to `shutdown_timeout` (see
232
+ [websockets.md](websockets.md#rackhijack-and-action-cable)).
233
+
234
+ ## Stuck workers and quarantine
235
+
236
+ A `worker_loop`'s requests may wait for seconds by design, so Kino
237
+ judges the thread, not the requests: a worker is busy while its thread
238
+ stays away from its loop and there is work for it. A worker whose
239
+ fibers only wait reads at most about 50 ms of `busy_ms`; a job that
240
+ computes without waiting adds its own run time. Keep
241
+ `quarantine_timeout` well above that: a quarantined worker's inline
242
+ connections end as
243
+ [architecture.md](architecture.md#inline-connections) says. A fiber that spins while the
244
+ worker has no work at all, or after the loop got its end (a drain or a
245
+ retirement), is not seen: that worker reads 0. `request_timeout` works
246
+ as usual: the client gets its 504 while the job runs on, holding its
247
+ slot until it ends.
248
+
249
+ ## Dispatch
250
+
251
+ Requests that come through hyper reach a worker by
252
+ [lane dispatch](architecture.md#lane-dispatch), which counts what a
253
+ worker has open: a worker whose fibers all wait counts as idle, one with
254
+ `concurrency` requests open gets no more, and with every worker full a
255
+ request waits its turn, in the order requests came, up to
256
+ `queue_timeout`, then gets a 503. While a sibling sits idle, a worker
257
+ holding a request it has not answered yet is passed over, so a few
258
+ clients spread over the workers. A request on an
259
+ [inline connection](#inline-connections) never passes through it: it
260
+ runs on the worker its connection was placed on.
261
+
262
+ What the app controls is when a job starts: dispatch sees a worker's
263
+ loop, not its fibers. A job left queued (on a `Thread::Queue`, or on
264
+ Async's `Queue`, `Condition` or `Notification`) starts only after the
265
+ loop told dispatch that the worker is idle, so requests wait behind it
266
+ while idle siblings get none. Start each job at once, as `task.async`
267
+ does.
268
+
269
+ `concurrency` counts a request until its job ends, so a worker whose
270
+ answered requests still run (in `after_request_complete`, or past a
271
+ `request_timeout` 504) can be sent a request it has no room for yet. It
272
+ waits in the worker's lane until a job ends, or until an idle sibling
273
+ takes it, within 50 ms.
274
+
275
+ ## Inline connections
276
+
277
+ Over plain TCP or a `unix://` bind, a `worker_loop` server serves
278
+ HTTP/1.1 connections on its worker threads, with nothing to turn on.
279
+ Kino places each connection it accepts on a worker with room for it,
280
+ and that worker's loop runs the connection as a job of its own: Kino's
281
+ Rust code reads each request on the worker's thread, the app runs on
282
+ that job, and Kino writes the answer straight to the socket, with no
283
+ hand-off between threads, no wake of the loop and no task per request.
284
+ There is no setting: a server with TLS serves nothing inline. How it works inside, the deadlines, and how each connection
285
+ ends at a drain, a retirement, a quarantine or a crash are in
286
+ [architecture.md](architecture.md#inline-connections).
287
+
288
+ ### What an app sees
289
+
290
+ - A connection's requests run one after another on its job, each
291
+ counting toward `concurrency` while it runs, and a worker takes at
292
+ most `concurrency` connections. Between requests the job waits on the
293
+ socket through your scheduler, after stepping aside once (the
294
+ scheduler's `yield`, else `kernel_sleep(0)`) when another inline
295
+ connection shares the worker. The requests share the job's fiber and
296
+ task (see [What carries over](#what-carries-over-between-requests));
297
+ stopping that task ends the connection.
298
+ - A worker serves its inline connections in turn: a request that holds
299
+ the thread (computing, or blocking outside your scheduler) delays the
300
+ worker's other connections, and none of them moves to another worker.
301
+ A lower `concurrency` leaves fewer connections behind each slow
302
+ request; more workers spread them.
303
+ - Kino reads a request's body whole before the app runs, so
304
+ `rack.input` never waits.
305
+ - A streamed answer goes out as through hyper. What the socket does not
306
+ take yet waits on the job, never on the worker's thread, so a slow
307
+ reader holds back its own connection only.
308
+ - Answers, deadlines and the drain follow hyper's, with a few
309
+ [recorded differences](architecture.md#recorded-differences) over
310
+ headers an app should not set, a first head's deadline and the drain.
311
+ - The only inline connection on a worker with nothing else to do spins
312
+ at its socket for up to 100 µs, with the GVL released, before its job
313
+ waits, so a client that sends its next request at once is served
314
+ without a wake. A client whose requests mostly come later backs it off
315
+ to one spin in 32 requests; nothing spins on a process that may use
316
+ one CPU.
317
+
318
+ ### What goes to hyper
319
+
320
+ hyper, on Kino's I/O threads, serves everything else, as on a server
321
+ without a `worker_loop`:
322
+
323
+ - TLS and HTTP/2 (an h2c preface included);
324
+ - every request outside a strict subset of HTTP/1.1 (no HTTP/1.0, an
325
+ origin-form target, a body of at most 64 KiB and `max_body_size` by one
326
+ `Content-Length`, no `Transfer-Encoding`, `Expect` or upgrade, a head
327
+ of at most 16 KiB and 100 headers), handed back before the app sees
328
+ it with the bytes read replayed, and a request read whole while its
329
+ worker has no room, which waits for room in the lanes up to
330
+ `queue_timeout`;
331
+ - connections no worker takes at accept, and those of a worker that
332
+ retires, crashes or is quarantined.
333
+
334
+ A connection never goes to hyper in the middle of an answer, and in the
335
+ middle of a request body only as its worker retires, with what was
336
+ read. Behind nginx, connections stay inline while nginx speaks
337
+ HTTP/1.1 to Kino and keeps its connections open, as it does by default
338
+ since 1.29.7; an older nginx needs `proxy_http_version 1.1`,
339
+ `proxy_set_header Connection ""` and an upstream `keepalive` pool. One
340
+ that speaks HTTP/1.0 has every request handed back.
341
+
342
+ ## Per-request cost
343
+
344
+ This section is about requests that reach a worker through its lane:
345
+ everything hyper serves, such as TLS, HTTP/2 and hand-backs. A request
346
+ on an
347
+ [inline connection](#inline-connections) pays neither Kino's wake nor a
348
+ task and fiber of its own: its connection's job waits on the socket
349
+ through the scheduler, and runs the request itself. The numbers here
350
+ were measured before Kino served connections inline.
351
+
352
+ A request that reaches an idle `worker_loop` worker costs more than in
353
+ Kino's own loop, which answers one request and takes the next in a
354
+ single native call: one wake-up of the scheduler (none while work
355
+ waits, so nothing under load), and a task and a fiber per request, the
356
+ larger part. For requests that wait on a database or another service
357
+ none of this shows; for an app whose requests do almost nothing, these
358
+ are its levers:
359
+
360
+ - **A task per request**, as above. This is the default for good
361
+ reason: each request has a task and a fiber of its own, so its fiber
362
+ storage and task-local state are its own, stopping its task aborts it
363
+ alone, and a job that raises ends nothing else.
364
+ - **`RUBY_SHARED_FIBER_POOL_FREE_STACKS=0`** in the environment Ruby
365
+ starts with keeps a finished fiber's stack where Ruby would hand its
366
+ memory back, one system call per request; every stack a worker has
367
+ used then stays in memory, up to `concurrency` per worker plus those
368
+ of its socket and wake jobs.
369
+ - **A fixed set of job fibers (runners), each job handed straight to
370
+ an idle one**: no task and no fiber per request. It looks like
371
+ this:
372
+
373
+ <!-- spec/worker_loop_spec.rb and spec/inline_io_spec.rb run this block as a kino.rb. -->
374
+
375
+ ```ruby
376
+ worker_loop Ractor.shareable_proc { |worker|
377
+ Sync do |task|
378
+ concurrency = 32 # requests at once, and as many runners
379
+ scheduler = Fiber.scheduler
380
+ idle = []
381
+ done = false
382
+ concurrency.times do
383
+ # Transient, so Sync never waits for a runner.
384
+ task.async(transient: true) do
385
+ runner = Fiber.current
386
+ loop do
387
+ idle << runner
388
+ # A job, or nil once serve has returned: any other wake-up is
389
+ # not a hand-off, and the runner waits on.
390
+ job = scheduler.transfer until done || job.respond_to?(:call)
391
+ break unless job.respond_to?(:call)
392
+ job.call
393
+ end
394
+ end
395
+ end
396
+ worker.serve(concurrency:) do |job|
397
+ if (runner = idle.pop)
398
+ # Runs the job now, until it first waits, as task.async would.
399
+ scheduler.resume(runner, job)
400
+ else
401
+ # Socket and wake jobs, and requests whose connection switched,
402
+ # hold runners outside concurrency: every runner can be busy.
403
+ task.async { job.call }
404
+ end
405
+ end
406
+ done = true
407
+ scheduler.resume(idle.pop, nil) until idle.empty?
408
+ end
409
+ }
410
+ ```
411
+
412
+ The hand-off uses two methods of Async's scheduler that io-event's
413
+ selectors implement: `scheduler.transfer` gives control to the event
414
+ loop, so an idle runner wakes only when resumed, and
415
+ `scheduler.resume(runner, job)` switches to the runner at once, as
416
+ `task.async` starts a task. Neither is part of Ruby's
417
+ `Fiber::Scheduler` interface, so check the recipe again after an Async
418
+ or io-event upgrade (it was written against async 2.46 and io-event
419
+ 1.22). Feeding the runners through a queue instead would start each job
420
+ too late (see [Dispatch](#dispatch)).
421
+
422
+ What a task per request guarantees no longer holds: requests share the
423
+ runners' fibers, so fiber storage and task-local state carry over, and
424
+ a wake-up that comes late for one request's wait can end a later wait
425
+ of its runner early. Stopping a runner stops its request and the runner
426
+ with it, a job that raises ends its runner too, and the pool does not
427
+ refill: once no runner is idle, jobs get tasks of their own.
428
+
429
+ ## Stats and logs
430
+
431
+ - `worker_status[].in_flight` counts the requests the worker has open.
432
+ Socket callbacks and wake hook runs do not count, while in Kino's own
433
+ loop a running callback or hook counts as one.
434
+ - `worker_status[].busy_ms` is how long the worker's thread has stayed
435
+ away from its loop while there is work for it (see
436
+ [Stuck workers](#stuck-workers-and-quarantine)).
437
+ - `wakes` counts each wake the loop takes, also one that folds into a
438
+ run already waiting, so it can be higher than the hook's runs.
439
+ - The access log leaves out the GC and allocation figures, as requests
440
+ interleave: the breakdown is `(ruby; kino; wait)`.
441
+ - `stats[:inline]` (`"inline"` in `/stats`, `null` on a server that
442
+ serves nothing inline) counts [inline serving](#inline-connections):
443
+ - `connections`: served inline now (`kino_inline_connections`);
444
+ - `requests`: served inline (`kino_inline_requests_total`), counted in
445
+ `served`, their worker's row, `timeouts` and `responses_cut` too, as
446
+ hyper's are;
447
+ - `declined`: connections left with hyper at accept, as no worker
448
+ could take one (`kino_inline_declined_total`);
449
+ - `handbacks` (`kino_inline_handbacks_total`): connections handed
450
+ back to hyper, whatever for
451
+ ([What goes to hyper](#what-goes-to-hyper));
452
+ - `closed` (`kino_inline_closed_total`): the connections Kino cut
453
+ off, at a deadline, a crash, the shutdown's deadline or a
454
+ quarantine. One its client or an answer closed never counts, nor
455
+ does one a `request_timeout` 504 ended (in `timeouts`);
456
+ - `spins` (`kino_inline_spins_total`): the spins of a lone
457
+ connection's job for its next request, whatever they caught.
458
+ - `worker_status[].inline_connections` counts the connections the
459
+ worker serves inline now (`kino_worker_inline_connections`).
460
+ - An inline request is logged as hyper logs one, with `wait 0.0ms`, as
461
+ it waits in no queue (nor counts in `queue_time`); one handed back is
462
+ logged by hyper alone.
@@ -0,0 +1,10 @@
1
+ # The GVL is released through gvl::call alone and passed through gvl::pass
2
+ # alone: gvl.rs runs the VM's interrupts in protected calls, so a raise
3
+ # never jumps over Rust frames. A release or a pass anywhere else would.
4
+ disallowed-methods = [
5
+ { path = "rb_sys::rb_thread_call_without_gvl", reason = "release the GVL through crate::gvl" },
6
+ { path = "rb_sys::rb_thread_call_without_gvl2", reason = "release the GVL through crate::gvl" },
7
+ { path = "rb_sys::rb_nogvl", reason = "release the GVL through crate::gvl" },
8
+ { path = "rb_sys::rb_thread_schedule", reason = "pass the GVL through crate::gvl::pass" },
9
+ { path = "magnus::Ruby::thread_schedule", reason = "pass the GVL through crate::gvl::pass" },
10
+ ]
data/lib/kino/cli.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "optparse"
4
+ require "tempfile"
4
5
  require_relative "version"
5
6
 
6
7
  module Kino
@@ -112,7 +113,8 @@ module Kino
112
113
 
113
114
  # The two banner halves around Server#start: credits before, the ready
114
115
  # block plus a bold "Action!" after, once mode and port are known.
115
- # Server.run is the one caller; the kino CLI funnels into it.
116
+ # Server#run calls it unless the kino CLI already did, ahead of loading
117
+ # the app.
116
118
  # @return [void]
117
119
  def opening_credits
118
120
  puts motd
@@ -184,13 +186,28 @@ module Kino
184
186
 
185
187
  ENV["RACK_ENV"] ||= config[:environment] if config[:environment]
186
188
 
187
- app = Rack::Builder.parse_file(rackup_file)
188
- app = app.first if app.is_a?(Array) # rack < 3 compat
189
+ return check(rackup_file) if options[:check]
190
+
191
+ $stdout.sync = true
192
+ opening_credits
193
+ # The app's boot output is held back and shown under "Action!".
194
+ capture = OutputCapture.new
195
+ app = capture.during { load_app(rackup_file) }
196
+ begin
197
+ serve(app, config, capture)
198
+ ensure
199
+ capture.replay
200
+ end
201
+ 0
202
+ end
189
203
 
190
- return Check.print_report(app) ? 0 : 1 if options[:check]
204
+ def load_app(rackup_file)
205
+ app = Rack::Builder.parse_file(rackup_file)
206
+ app.is_a?(Array) ? app.first : app # rack < 3 compat
207
+ end
191
208
 
192
- serve(app, config)
193
- 0
209
+ def check(rackup_file)
210
+ Check.print_report(load_app(rackup_file)) ? 0 : 1
194
211
  end
195
212
 
196
213
  # Bun-style colored help, generated from the parser's own switch list
@@ -266,11 +283,85 @@ module Kino
266
283
  config
267
284
  end
268
285
 
269
- def serve(app, config)
270
- Server.run(app, **config.server_options)
286
+ def serve(app, config, capture)
287
+ Server.run(app, credits: false, on_ready: -> { capture.replay },
288
+ **config.server_options)
289
+ end
290
+
291
+ # Holds fd 1 and 2 output in temp files while the app loads. The same
292
+ # IO objects stay in place (reopened onto the files and back), so
293
+ # loggers that captured $stdout or $stderr keep working afterwards.
294
+ class OutputCapture
295
+ def initialize
296
+ @files = []
297
+ end
298
+
299
+ # Run the block with output captured; on any exception (SystemExit
300
+ # included) restore and show what was captured before re-raising.
301
+ def during
302
+ begin_capture
303
+ yield
304
+ rescue Exception # rubocop:disable Lint/RescueException
305
+ end_capture
306
+ replay
307
+ raise
308
+ ensure
309
+ end_capture
310
+ end
311
+
312
+ # Write the captured output to the real streams, once.
313
+ def replay
314
+ files, @files = @files, []
315
+ @ios.zip(files).each do |io, file|
316
+ next unless file
317
+
318
+ file.rewind
319
+ content = file.read
320
+ io.write(content) unless content.empty?
321
+ io.flush
322
+ rescue IOError, SystemCallError
323
+ nil # a closed pipe must not take the server down
324
+ ensure
325
+ file&.close!
326
+ end
327
+ end
328
+
329
+ private
330
+
331
+ def begin_capture
332
+ @ios = [$stdout, $stderr]
333
+ @ios.each(&:flush)
334
+ @saved = @ios.map(&:dup)
335
+ @files = [Tempfile.new("kino-out"), Tempfile.new("kino-err")]
336
+ @ios.zip(@files).each { |io, file| io.reopen(file) }
337
+ end
338
+
339
+ def end_capture
340
+ return unless @saved
341
+
342
+ failure = flush_rails_logger
343
+ @ios.zip(@saved).each do |io, saved|
344
+ io.flush
345
+ io.reopen(saved)
346
+ io.sync = true
347
+ saved.close
348
+ end
349
+ @saved = nil
350
+ warn "kino: flushing Rails.logger failed: #{failure.message}" if failure
351
+ end
352
+
353
+ # Returns the error instead of raising: the fds must be restored.
354
+ def flush_rails_logger
355
+ logger = defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
356
+ logger.flush if logger.respond_to?(:flush)
357
+ nil
358
+ rescue => e
359
+ e
360
+ end
271
361
  end
362
+ private_constant :OutputCapture
272
363
 
273
364
  private_class_method :print_help, :option_parser, :write_sample,
274
- :resolve_config, :serve, :count
365
+ :resolve_config, :serve, :count, :load_app, :check
275
366
  end
276
367
  end