kino 0.7.1 → 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 +286 -0
  4. data/Cargo.lock +209 -132
  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 +19 -3
  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
@@ -1,380 +1,20 @@
1
1
  //! Read-only control plane: stats, metrics and probes served off-runtime;
2
- //! see also server.rs for the data plane.
2
+ //! the data plane is server/, and what the endpoints report is stats.rs.
3
3
 
4
4
  use std::collections::HashMap;
5
- use std::sync::atomic::Ordering;
6
5
  use std::sync::{Arc, OnceLock};
7
6
  use std::time::Duration;
8
7
 
9
8
  use parking_lot::Mutex;
10
9
 
11
- use crate::registry::{ServerInner, STATE_DRAINING, STATE_READY};
12
-
13
- /// One dispatch slot's sensors, captured for a response. busy_ms is the
14
- /// age of the current in-flight work (0 when idle), the wedge signal.
15
- pub struct WorkerStat {
16
- pub index: usize,
17
- pub served: u64,
18
- pub in_flight: usize,
19
- pub busy_ms: u64,
20
- pub quarantined: bool,
21
- /// Sent home by the pool scaler; leaves at its next idle tick.
22
- pub retired: bool,
23
- }
24
-
25
- /// Read every slot's per-worker sensors in one pass under the slots read
26
- /// lock (the same lock lane_depths uses), computing busy_ms against one
27
- /// "now". No Ruby, so it is safe on the control thread and below the GVL.
28
- pub fn collect_worker_status(server: &ServerInner) -> Vec<WorkerStat> {
29
- let now = crate::mono::mono_ms();
30
- server
31
- .slots
32
- .read()
33
- .iter()
34
- .enumerate()
35
- .map(|(index, slot)| {
36
- let quarantined = slot.quarantined.load(Ordering::Relaxed);
37
- let in_flight = slot.in_flight.load(Ordering::Relaxed);
38
- let started = slot.last_started_ms.load(Ordering::Relaxed);
39
- WorkerStat {
40
- index,
41
- served: slot.served.load(Ordering::Relaxed),
42
- in_flight,
43
- // A quarantined slot is a known, handled wedge: report 0 so
44
- // it never re-trips detection or reads as a live wedge.
45
- busy_ms: if quarantined || in_flight == 0 {
46
- 0
47
- } else {
48
- now.saturating_sub(started)
49
- },
50
- quarantined,
51
- retired: slot.retired.load(Ordering::Relaxed),
52
- }
53
- })
54
- .collect()
55
- }
56
-
57
- /// Everything the endpoints report, captured in one pass so a response
58
- /// is internally consistent.
59
- pub struct StatsSnapshot {
60
- pub mode: String,
61
- pub lanes: bool,
62
- pub workers: usize,
63
- pub threads: usize,
64
- pub batch: usize,
65
- pub respawns: u64,
66
- pub queued: usize,
67
- pub in_flight: usize,
68
- pub served: u64,
69
- pub rejected: u64,
70
- pub timeouts: u64,
71
- pub lane_depths: Option<Vec<usize>>,
72
- pub state: u8,
73
- pub worker_status: Vec<WorkerStat>,
74
- pub quarantined_count: usize,
75
- pub quarantine_replacements: u64,
76
- pub max_workers: usize,
77
- pub active_workers: usize,
78
- pub scale_ups: u64,
79
- pub scale_downs: u64,
80
- pub queue_histogram: crate::registry::QueueHistogramSnapshot,
81
- }
82
-
83
- impl StatsSnapshot {
84
- pub fn take(server: &ServerInner) -> Self {
85
- let worker_status = collect_worker_status(server);
86
- let quarantined_count = worker_status.iter().filter(|w| w.quarantined).count();
87
- StatsSnapshot {
88
- mode: server.topology.mode.clone(),
89
- lanes: server.lanes,
90
- workers: server.topology.workers,
91
- threads: server.topology.threads,
92
- batch: server.topology.batch,
93
- respawns: server.respawns.load(Ordering::Relaxed),
94
- queued: server.queued(),
95
- in_flight: server.in_flight.load(Ordering::Relaxed),
96
- served: server.served.load(Ordering::Relaxed),
97
- rejected: server.rejected.load(Ordering::Relaxed),
98
- timeouts: server.timeouts.load(Ordering::Relaxed),
99
- lane_depths: server.lane_depths(),
100
- state: server.state.load(Ordering::Relaxed),
101
- worker_status,
102
- quarantined_count,
103
- quarantine_replacements: server.quarantine_replacements.load(Ordering::Relaxed),
104
- max_workers: server.topology.max_workers,
105
- active_workers: server.active_workers.load(Ordering::Relaxed),
106
- scale_ups: server.scale_ups.load(Ordering::Relaxed),
107
- scale_downs: server.scale_downs.load(Ordering::Relaxed),
108
- queue_histogram: server.queue_histogram.snapshot(),
109
- }
110
- }
111
-
112
- pub fn state_name(&self) -> &'static str {
113
- match self.state {
114
- STATE_READY => "ready",
115
- STATE_DRAINING => "draining",
116
- _ => "booting",
117
- }
118
- }
119
- }
120
-
121
- /// Same vocabulary as Server#stats (plus state and version); mode and
122
- /// state are fixed identifiers, so no JSON escaping is needed.
123
- pub fn stats_json(s: &StatsSnapshot) -> String {
124
- use std::fmt::Write;
125
- let mut out = String::with_capacity(256);
126
- write!(
127
- out,
128
- r#"{{"mode":"{}","lanes":{},"workers":{},"threads":{},"batch":{},"respawns":{},"queued":{},"in_flight":{},"served":{},"rejected":{},"timeouts":{},"max_workers":{},"active_workers":{},"scale_ups":{},"scale_downs":{}"#,
129
- s.mode, s.lanes, s.workers, s.threads, s.batch, s.respawns,
130
- s.queued, s.in_flight, s.served, s.rejected, s.timeouts,
131
- s.max_workers, s.active_workers, s.scale_ups, s.scale_downs
132
- )
133
- .expect("writing to a String cannot fail");
134
- if let Some(depths) = &s.lane_depths {
135
- let list = depths
136
- .iter()
137
- .map(|d| d.to_string())
138
- .collect::<Vec<_>>()
139
- .join(",");
140
- write!(out, r#","lane_depths":[{list}]"#).expect("writing to a String cannot fail");
141
- }
142
- out.push_str(r#","worker_status":["#);
143
- for (i, w) in s.worker_status.iter().enumerate() {
144
- if i > 0 {
145
- out.push(',');
146
- }
147
- write!(
148
- out,
149
- r#"{{"index":{},"served":{},"in_flight":{},"busy_ms":{},"quarantined":{},"retired":{}}}"#,
150
- w.index, w.served, w.in_flight, w.busy_ms, w.quarantined, w.retired
151
- )
152
- .expect("writing to a String cannot fail");
153
- }
154
- out.push(']');
155
- write!(
156
- out,
157
- r#","queue_time":{{"count":{},"sum_seconds":{}}}"#,
158
- s.queue_histogram.count,
159
- s.queue_histogram.sum_seconds()
160
- )
161
- .expect("writing to a String cannot fail");
162
- write!(
163
- out,
164
- r#","quarantined":{},"state":"{}","version":"{}"}}"#,
165
- s.quarantined_count,
166
- s.state_name(),
167
- env!("CARGO_PKG_VERSION")
168
- )
169
- .expect("writing to a String cannot fail");
170
- out
171
- }
172
-
173
- /// One HELP/TYPE/sample triple for a single-value metric.
174
- fn metric(out: &mut String, name: &str, kind: &str, help: &str, value: impl std::fmt::Display) {
175
- use std::fmt::Write;
176
- writeln!(
177
- out,
178
- "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {value}"
179
- )
180
- .expect("writing to a String cannot fail");
181
- }
182
-
183
- /// One HELP/TYPE header followed by one `name{label="key"} value` line per
184
- /// row, for the labeled per-lane and per-worker series.
185
- fn series<K: std::fmt::Display, V: std::fmt::Display>(
186
- out: &mut String,
187
- name: &str,
188
- kind: &str,
189
- help: &str,
190
- label: &str,
191
- rows: impl Iterator<Item = (K, V)>,
192
- ) {
193
- use std::fmt::Write;
194
- writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}")
195
- .expect("writing to a String cannot fail");
196
- for (key, value) in rows {
197
- writeln!(out, "{name}{{{label}=\"{key}\"}} {value}")
198
- .expect("writing to a String cannot fail");
199
- }
200
- }
201
-
202
- /// Prometheus text exposition (version 0.0.4) for every stat in `s`.
203
- pub fn metrics_text(s: &StatsSnapshot) -> String {
204
- use std::fmt::Write;
205
- let mut out = String::with_capacity(1024);
206
- metric(
207
- &mut out,
208
- "kino_requests_served_total",
209
- "counter",
210
- "Requests handed to Ruby workers.",
211
- s.served,
212
- );
213
- metric(
214
- &mut out,
215
- "kino_requests_rejected_total",
216
- "counter",
217
- "Requests rejected with a 503.",
218
- s.rejected,
219
- );
220
- metric(
221
- &mut out,
222
- "kino_request_timeouts_total",
223
- "counter",
224
- "Responses past the request timeout (client got a 504).",
225
- s.timeouts,
226
- );
227
- metric(
228
- &mut out,
229
- "kino_worker_respawns_total",
230
- "counter",
231
- "Crashed workers respawned by the supervisor.",
232
- s.respawns,
233
- );
234
- metric(
235
- &mut out,
236
- "kino_queue_depth",
237
- "gauge",
238
- "Requests waiting for a worker.",
239
- s.queued,
240
- );
241
- metric(
242
- &mut out,
243
- "kino_requests_in_flight",
244
- "gauge",
245
- "Requests currently inside Ruby workers.",
246
- s.in_flight,
247
- );
248
- metric(
249
- &mut out,
250
- "kino_workers",
251
- "gauge",
252
- "Configured worker count.",
253
- s.workers,
254
- );
255
- metric(
256
- &mut out,
257
- "kino_threads_per_worker",
258
- "gauge",
259
- "Configured threads per worker.",
260
- s.threads,
261
- );
262
- metric(
263
- &mut out,
264
- "kino_max_workers",
265
- "gauge",
266
- "Worker pool ceiling (equals kino_workers for a fixed pool).",
267
- s.max_workers,
268
- );
269
- metric(
270
- &mut out,
271
- "kino_active_workers",
272
- "gauge",
273
- "Workers currently alive and serving.",
274
- s.active_workers,
275
- );
276
- metric(
277
- &mut out,
278
- "kino_scale_ups_total",
279
- "counter",
280
- "Workers added by the pool scaler.",
281
- s.scale_ups,
282
- );
283
- metric(
284
- &mut out,
285
- "kino_scale_downs_total",
286
- "counter",
287
- "Idle workers retired by the pool scaler.",
288
- s.scale_downs,
289
- );
290
- metric(
291
- &mut out,
292
- "kino_ready",
293
- "gauge",
294
- "1 when serving, 0 while booting or draining.",
295
- if s.state == STATE_READY { "1" } else { "0" },
296
- );
297
- if let Some(depths) = &s.lane_depths {
298
- series(
299
- &mut out,
300
- "kino_lane_depth",
301
- "gauge",
302
- "Queued requests in each worker lane.",
303
- "lane",
304
- depths
305
- .iter()
306
- .enumerate()
307
- .map(|(lane, depth)| (lane, *depth)),
308
- );
309
- }
310
- series(
311
- &mut out,
312
- "kino_worker_requests_served_total",
313
- "counter",
314
- "Requests handed to each dispatch slot.",
315
- "worker",
316
- s.worker_status.iter().map(|w| (w.index, w.served)),
317
- );
318
- series(
319
- &mut out,
320
- "kino_worker_in_flight",
321
- "gauge",
322
- "Requests executing in each dispatch slot.",
323
- "worker",
324
- s.worker_status.iter().map(|w| (w.index, w.in_flight)),
325
- );
326
- series(
327
- &mut out,
328
- "kino_worker_busy_ms",
329
- "gauge",
330
- "Age in ms of the current in-flight request per slot (0 when idle).",
331
- "worker",
332
- s.worker_status.iter().map(|w| (w.index, w.busy_ms)),
333
- );
334
- metric(
335
- &mut out,
336
- "kino_quarantined_workers",
337
- "gauge",
338
- "Dispatch slots abandoned as wedged.",
339
- s.quarantined_count,
340
- );
341
- metric(
342
- &mut out,
343
- "kino_quarantine_replacements_total",
344
- "counter",
345
- "Replacement workers spawned after a wedge.",
346
- s.quarantine_replacements,
347
- );
348
- let h = &s.queue_histogram;
349
- out.push_str("# HELP kino_request_queue_seconds Seconds requests waited in the queue before a worker admitted them.\n# TYPE kino_request_queue_seconds histogram\n");
350
- let mut cumulative = 0u64;
351
- for (i, bound_us) in crate::registry::QUEUE_BOUNDS_US.iter().enumerate() {
352
- cumulative += h.buckets[i];
353
- let le = *bound_us as f64 / 1_000_000.0;
354
- writeln!(
355
- out,
356
- "kino_request_queue_seconds_bucket{{le=\"{le}\"}} {cumulative}"
357
- )
358
- .expect("writing to a String cannot fail");
359
- }
360
- let total = cumulative + h.overflow;
361
- writeln!(
362
- out,
363
- "kino_request_queue_seconds_bucket{{le=\"+Inf\"}} {total}"
364
- )
365
- .expect("writing to a String cannot fail");
366
- writeln!(out, "kino_request_queue_seconds_sum {}", h.sum_seconds())
367
- .expect("writing to a String cannot fail");
368
- writeln!(out, "kino_request_queue_seconds_count {total}")
369
- .expect("writing to a String cannot fail");
370
- out
371
- }
10
+ use crate::registry::{ServerInner, STATE_READY};
11
+ use crate::stats::Snapshot;
372
12
 
373
13
  /// Constant-time comparison against "Bearer <token>": the length check is
374
14
  /// not part of the secret, so it may return early; once the lengths match,
375
15
  /// every byte of both strings is visited regardless of where they first
376
16
  /// differ.
377
- pub fn token_ok(expected: &str, authorization: Option<&str>) -> bool {
17
+ fn token_ok(expected: &str, authorization: Option<&str>) -> bool {
378
18
  let presented = authorization
379
19
  .and_then(|h| h.strip_prefix("Bearer "))
380
20
  .unwrap_or("");
@@ -390,19 +30,18 @@ pub fn token_ok(expected: &str, authorization: Option<&str>) -> bool {
390
30
  diff == 0
391
31
  }
392
32
 
393
- /// (status, content type, body). The token, when configured, guards the
394
- /// data endpoints only; orchestrator probes must never need credentials.
395
- pub fn route(
33
+ /// (status, content type, body) for a request to `path`, the URI's path alone. The token, when
34
+ /// configured, guards the data endpoints only; orchestrator probes must never need credentials.
35
+ fn route(
396
36
  method: &str,
397
37
  path: &str,
398
38
  authorization: Option<&str>,
399
39
  token: Option<&str>,
400
- snapshot: &StatsSnapshot,
40
+ snapshot: &Snapshot,
401
41
  ) -> (u16, &'static str, String) {
402
42
  if method != "GET" && method != "HEAD" {
403
43
  return (405, "text/plain", "method not allowed\n".to_string());
404
44
  }
405
- let path = path.split('?').next().unwrap_or(path);
406
45
  match path {
407
46
  "/live" => (200, "text/plain", "ok\n".to_string()),
408
47
  "/ready" => {
@@ -419,9 +58,9 @@ pub fn route(
419
58
  }
420
59
  }
421
60
  if path == "/stats" {
422
- (200, "application/json", stats_json(snapshot))
61
+ (200, "application/json", snapshot.json())
423
62
  } else {
424
- (200, "text/plain; version=0.0.4", metrics_text(snapshot))
63
+ (200, "text/plain; version=0.0.4", snapshot.metrics())
425
64
  }
426
65
  }
427
66
  _ => (404, "text/plain", "not found\n".to_string()),
@@ -437,6 +76,11 @@ const CONTROL_DEADLINE: Duration = Duration::from_secs(5);
437
76
  /// Concurrent monitoring connections; probes and scrapers need a
438
77
  /// handful, connections past the cap are dropped at accept.
439
78
  const CONTROL_MAX_CONNECTIONS: usize = 16;
79
+ /// The TCP control listener's accept queue, pinned at std's 128: monitors connect a few at a
80
+ /// time, and past it, at a stuck control thread, a probe fails at connect rather than wait on a
81
+ /// handshake nobody answers. A unix control socket keeps the kernel's maximum: on Linux a full
82
+ /// unix queue holds a blocking connect rather than fail it.
83
+ const CONTROL_BACKLOG: libc::c_int = 128;
440
84
 
441
85
  /// A bound control listener: TCP with its resolved port, or a unix socket
442
86
  /// with its path.
@@ -453,6 +97,7 @@ pub fn bind_control(addr: &str) -> std::io::Result<ControlBind> {
453
97
  Ok(ControlBind::Unix(listener, path.to_path_buf()))
454
98
  } else {
455
99
  let listener = std::net::TcpListener::bind(addr)?;
100
+ let _ = crate::listen::set_backlog(&listener, CONTROL_BACKLOG);
456
101
  listener.set_nonblocking(true)?;
457
102
  let port = listener.local_addr()?.port();
458
103
  Ok(ControlBind::Tcp(listener, port))
@@ -635,7 +280,7 @@ fn handle(
635
280
  .headers()
636
281
  .get(hyper::header::AUTHORIZATION)
637
282
  .and_then(|v| v.to_str().ok());
638
- let snapshot = StatsSnapshot::take(server);
283
+ let snapshot = Snapshot::take(server);
639
284
  let (status, content_type, body) = route(
640
285
  req.method().as_str(),
641
286
  req.uri().path(),
@@ -663,135 +308,6 @@ fn handle(
663
308
  mod tests {
664
309
  use super::*;
665
310
 
666
- fn snapshot(state: u8) -> StatsSnapshot {
667
- StatsSnapshot {
668
- mode: "ractor".to_string(),
669
- lanes: false,
670
- workers: 8,
671
- threads: 1,
672
- batch: 1,
673
- respawns: 2,
674
- queued: 3,
675
- in_flight: 4,
676
- served: 100,
677
- rejected: 5,
678
- timeouts: 6,
679
- lane_depths: None,
680
- state,
681
- worker_status: vec![],
682
- quarantined_count: 0,
683
- quarantine_replacements: 0,
684
- max_workers: 32,
685
- active_workers: 12,
686
- scale_ups: 3,
687
- scale_downs: 1,
688
- queue_histogram: crate::registry::QueueHistogramSnapshot {
689
- buckets: [0; crate::registry::QUEUE_BOUNDS_US.len()],
690
- overflow: 0,
691
- sum_us: 0,
692
- count: 0,
693
- },
694
- }
695
- }
696
-
697
- #[test]
698
- fn stats_json_reports_every_field_and_the_state_name() {
699
- let json = stats_json(&snapshot(crate::registry::STATE_READY));
700
- for needle in [
701
- r#""mode":"ractor""#,
702
- r#""lanes":false"#,
703
- r#""workers":8"#,
704
- r#""threads":1"#,
705
- r#""batch":1"#,
706
- r#""respawns":2"#,
707
- r#""queued":3"#,
708
- r#""in_flight":4"#,
709
- r#""served":100"#,
710
- r#""rejected":5"#,
711
- r#""timeouts":6"#,
712
- r#""max_workers":32"#,
713
- r#""active_workers":12"#,
714
- r#""scale_ups":3"#,
715
- r#""scale_downs":1"#,
716
- r#""state":"ready""#,
717
- r#""version":""#,
718
- ] {
719
- assert!(json.contains(needle), "missing {needle} in {json}");
720
- }
721
- assert!(!json.contains("lane_depths"));
722
- }
723
-
724
- #[test]
725
- fn stats_json_includes_lane_depths_when_lanes_are_on() {
726
- let mut s = snapshot(crate::registry::STATE_READY);
727
- s.lane_depths = Some(vec![1, 0]);
728
- assert!(stats_json(&s).contains(r#""lane_depths":[1,0]"#));
729
- }
730
-
731
- #[test]
732
- fn metrics_text_is_prometheus_shaped() {
733
- let text = metrics_text(&snapshot(crate::registry::STATE_READY));
734
- assert!(text.contains("# TYPE kino_requests_served_total counter"));
735
- assert!(text.contains("kino_requests_served_total 100"));
736
- assert!(text.contains("kino_ready 1"));
737
- let draining = metrics_text(&snapshot(crate::registry::STATE_DRAINING));
738
- assert!(draining.contains("kino_ready 0"));
739
- }
740
-
741
- #[test]
742
- fn metrics_text_reports_the_elastic_pool() {
743
- let text = metrics_text(&snapshot(crate::registry::STATE_READY));
744
- assert!(text.contains("# TYPE kino_max_workers gauge"));
745
- assert!(text.contains("kino_max_workers 32"));
746
- assert!(text.contains("# TYPE kino_active_workers gauge"));
747
- assert!(text.contains("kino_active_workers 12"));
748
- assert!(text.contains("# TYPE kino_scale_ups_total counter"));
749
- assert!(text.contains("kino_scale_ups_total 3"));
750
- assert!(text.contains("# TYPE kino_scale_downs_total counter"));
751
- assert!(text.contains("kino_scale_downs_total 1"));
752
- }
753
-
754
- #[test]
755
- fn worker_status_reports_retired_slots() {
756
- let server = crate::registry::test_server(false, 4);
757
- server.register_worker();
758
- server.register_worker();
759
- server.slots.read()[1].retire();
760
-
761
- let status = collect_worker_status(&server);
762
-
763
- assert_eq!(
764
- status.iter().map(|w| w.retired).collect::<Vec<_>>(),
765
- vec![false, true]
766
- );
767
- assert!(status.iter().all(|w| w.busy_ms == 0));
768
- }
769
-
770
- #[test]
771
- fn snapshot_reads_the_pool_counters() {
772
- let server = crate::registry::test_server(false, 4);
773
- server.active_workers.store(3, Ordering::Relaxed);
774
- server.scale_ups.fetch_add(2, Ordering::Relaxed);
775
- server.scale_downs.fetch_add(1, Ordering::Relaxed);
776
-
777
- let s = StatsSnapshot::take(&server);
778
-
779
- assert_eq!(s.active_workers, 3);
780
- assert_eq!(s.max_workers, server.topology.max_workers);
781
- assert_eq!((s.scale_ups, s.scale_downs), (2, 1));
782
- }
783
-
784
- #[test]
785
- fn metrics_text_includes_lane_depth_samples_when_lanes_are_on() {
786
- let mut s = snapshot(crate::registry::STATE_READY);
787
- s.lane_depths = Some(vec![2, 0]);
788
- let text = metrics_text(&s);
789
- assert!(text.contains("# HELP kino_lane_depth Queued requests in each worker lane."));
790
- assert!(text.contains("# TYPE kino_lane_depth gauge"));
791
- assert!(text.contains(r#"kino_lane_depth{lane="0"} 2"#));
792
- assert!(text.contains(r#"kino_lane_depth{lane="1"} 0"#));
793
- }
794
-
795
311
  #[test]
796
312
  fn token_check_wants_the_exact_bearer_token() {
797
313
  assert!(token_ok("s3cret", Some("Bearer s3cret")));
@@ -812,194 +328,19 @@ mod tests {
812
328
  assert!(!token_ok("s3cret", Some("Bearer s3cret\0")));
813
329
  }
814
330
 
331
+ // The rest of the routes, the probes' states and the token's guard: spec/control_plane_spec.rb.
815
332
  #[test]
816
- fn routing_matrix() {
817
- let ready = snapshot(crate::registry::STATE_READY);
818
- assert_eq!(route("GET", "/live", None, None, &ready).0, 200);
333
+ fn a_head_is_routed_as_a_get_and_the_token_guards_the_metrics_too() {
334
+ let ready = Snapshot {
335
+ state: STATE_READY,
336
+ ..Snapshot::default()
337
+ };
819
338
  assert_eq!(route("HEAD", "/live", None, None, &ready).0, 200);
820
- assert_eq!(route("GET", "/ready", None, None, &ready).0, 200);
821
- assert_eq!(route("GET", "/stats", None, None, &ready).0, 200);
822
- assert_eq!(route("GET", "/metrics", None, None, &ready).0, 200);
823
- assert_eq!(route("GET", "/nope", None, None, &ready).0, 404);
824
- assert_eq!(route("POST", "/stats", None, None, &ready).0, 405);
825
- assert_eq!(route("GET", "/stats?x=1", None, None, &ready).0, 200);
826
-
827
- let booting = snapshot(crate::registry::STATE_BOOTING);
828
- let (code, _, body) = route("GET", "/ready", None, None, &booting);
829
- assert_eq!((code, body.as_str()), (503, "booting\n"));
830
-
831
- // The token guards stats and metrics; the probes stay open.
832
- assert_eq!(route("GET", "/stats", None, Some("t"), &ready).0, 401);
339
+ let token = Some("t");
340
+ assert_eq!(route("GET", "/metrics", None, token, &ready).0, 401);
833
341
  assert_eq!(
834
- route("GET", "/metrics", Some("Bearer t"), Some("t"), &ready).0,
342
+ route("GET", "/metrics", Some("Bearer t"), token, &ready).0,
835
343
  200
836
344
  );
837
- assert_eq!(route("GET", "/ready", None, Some("t"), &ready).0, 200);
838
- assert_eq!(route("GET", "/live", None, Some("t"), &ready).0, 200);
839
- }
840
-
841
- #[test]
842
- fn stats_json_emits_worker_status_array() {
843
- let mut s = snapshot(crate::registry::STATE_READY);
844
- s.worker_status = vec![
845
- WorkerStat {
846
- index: 0,
847
- served: 10,
848
- in_flight: 1,
849
- busy_ms: 4,
850
- quarantined: false,
851
- retired: false,
852
- },
853
- WorkerStat {
854
- index: 1,
855
- served: 7,
856
- in_flight: 0,
857
- busy_ms: 0,
858
- quarantined: false,
859
- retired: true,
860
- },
861
- ];
862
- let json = stats_json(&s);
863
- assert!(json.contains(r#""worker_status":[{"index":0,"served":10,"in_flight":1,"busy_ms":4,"quarantined":false,"retired":false},{"index":1,"served":7,"in_flight":0,"busy_ms":0,"quarantined":false,"retired":true}]"#), "got {json}");
864
- }
865
-
866
- #[test]
867
- fn stats_json_worker_status_is_empty_array_with_no_slots() {
868
- let s = snapshot(crate::registry::STATE_READY);
869
- assert!(stats_json(&s).contains(r#""worker_status":[]"#));
870
- }
871
-
872
- #[test]
873
- fn metrics_text_emits_per_worker_series() {
874
- let mut s = snapshot(crate::registry::STATE_READY);
875
- s.worker_status = vec![
876
- WorkerStat {
877
- index: 0,
878
- served: 10,
879
- in_flight: 1,
880
- busy_ms: 4,
881
- quarantined: false,
882
- retired: false,
883
- },
884
- WorkerStat {
885
- index: 1,
886
- served: 7,
887
- in_flight: 0,
888
- busy_ms: 0,
889
- quarantined: false,
890
- retired: true,
891
- },
892
- ];
893
- let text = metrics_text(&s);
894
- assert!(text.contains("# TYPE kino_worker_requests_served_total counter"));
895
- assert!(text.contains(r#"kino_worker_requests_served_total{worker="0"} 10"#));
896
- assert!(text.contains(r#"kino_worker_in_flight{worker="1"} 0"#));
897
- assert!(text.contains("# TYPE kino_worker_busy_ms gauge"));
898
- assert!(text.contains(r#"kino_worker_busy_ms{worker="0"} 4"#));
899
- }
900
-
901
- #[test]
902
- fn quarantined_slot_reports_zero_busy_ms() {
903
- let server = crate::registry::test_server(false, 4);
904
- server.register_worker();
905
- {
906
- let slots = server.slots.read();
907
- slots[0]
908
- .in_flight
909
- .store(1, std::sync::atomic::Ordering::Relaxed);
910
- slots[0]
911
- .last_started_ms
912
- .store(0, std::sync::atomic::Ordering::Relaxed);
913
- slots[0]
914
- .quarantined
915
- .store(true, std::sync::atomic::Ordering::Relaxed);
916
- }
917
- let rows = collect_worker_status(&server);
918
- assert!(rows[0].quarantined);
919
- assert_eq!(rows[0].busy_ms, 0);
920
- }
921
-
922
- #[test]
923
- fn stats_json_reports_quarantine() {
924
- let mut s = snapshot(crate::registry::STATE_READY);
925
- s.quarantined_count = 1;
926
- s.worker_status = vec![
927
- WorkerStat {
928
- index: 0,
929
- served: 3,
930
- in_flight: 1,
931
- busy_ms: 0,
932
- quarantined: true,
933
- retired: false,
934
- },
935
- WorkerStat {
936
- index: 1,
937
- served: 9,
938
- in_flight: 1,
939
- busy_ms: 5,
940
- quarantined: false,
941
- retired: false,
942
- },
943
- ];
944
- let json = stats_json(&s);
945
- assert!(
946
- json.contains(r#""quarantined":1"#),
947
- "top-level count: {json}"
948
- );
949
- assert!(
950
- json.contains(r#"{"index":0,"served":3,"in_flight":1,"busy_ms":0,"quarantined":true,"retired":false}"#),
951
- "{json}"
952
- );
953
- assert!(json.contains(r#""quarantined":false"#));
954
- }
955
-
956
- #[test]
957
- fn metrics_text_reports_quarantine() {
958
- let mut s = snapshot(crate::registry::STATE_READY);
959
- s.quarantined_count = 2;
960
- s.quarantine_replacements = 7;
961
- let text = metrics_text(&s);
962
- assert!(text.contains("# TYPE kino_quarantined_workers gauge"));
963
- assert!(text.contains("kino_quarantined_workers 2"));
964
- assert!(text.contains("# TYPE kino_quarantine_replacements_total counter"));
965
- assert!(text.contains("kino_quarantine_replacements_total 7"));
966
- }
967
-
968
- #[test]
969
- fn metrics_text_emits_a_cumulative_queue_histogram() {
970
- let mut s = snapshot(crate::registry::STATE_READY);
971
- let mut buckets = [0u64; crate::registry::QUEUE_BOUNDS_US.len()];
972
- buckets[0] = 3; // <= 0.0005s
973
- buckets[2] = 1; // <= 0.0025s
974
- s.queue_histogram = crate::registry::QueueHistogramSnapshot {
975
- buckets,
976
- overflow: 1,
977
- sum_us: 3 * 100 + 2_000 + 20_000_000,
978
- count: 5,
979
- };
980
- let text = metrics_text(&s);
981
- assert!(text.contains("# TYPE kino_request_queue_seconds histogram"));
982
- assert!(text.contains(r#"kino_request_queue_seconds_bucket{le="0.0005"} 3"#));
983
- // cumulative: le=0.0025 includes buckets 0..=2 = 3 + 0 + 1 = 4
984
- assert!(text.contains(r#"kino_request_queue_seconds_bucket{le="0.0025"} 4"#));
985
- assert!(text.contains(r#"kino_request_queue_seconds_bucket{le="+Inf"} 5"#));
986
- assert!(text.contains("kino_request_queue_seconds_count 5"));
987
- assert!(text.contains("kino_request_queue_seconds_sum "));
988
- }
989
-
990
- #[test]
991
- fn stats_json_reports_queue_time() {
992
- let mut s = snapshot(crate::registry::STATE_READY);
993
- s.queue_histogram = crate::registry::QueueHistogramSnapshot {
994
- buckets: [0; crate::registry::QUEUE_BOUNDS_US.len()],
995
- overflow: 0,
996
- sum_us: 1_500_000,
997
- count: 2,
998
- };
999
- let json = stats_json(&s);
1000
- assert!(
1001
- json.contains(r#""queue_time":{"count":2,"sum_seconds":1.5}"#),
1002
- "{json}"
1003
- );
1004
345
  }
1005
346
  }