kino 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +281 -0
  4. data/Cargo.lock +164 -95
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +17 -1
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
@@ -0,0 +1,494 @@
1
+ //! A worker slot: one per worker thread, known to Ruby by its index. Dispatch,
2
+ //! the take loop, the pool and the drain meet here. Each part owns its state: the lane
3
+ //! (lane.rs), the park flag (park.rs), what is in flight (load.rs), and who is on the slot
4
+ //! (life.rs).
5
+
6
+ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
7
+ use std::sync::Arc;
8
+
9
+ use parking_lot::Mutex;
10
+
11
+ use crate::doorbell::Doorbell;
12
+ use crate::inline::InlineConn;
13
+ use crate::registry::{BoxedCtx, LaneItem, ServerInner};
14
+ use crate::response::{Cut, Responder};
15
+
16
+ mod lane;
17
+ mod life;
18
+ mod load;
19
+ mod park;
20
+
21
+ pub use lane::Lane;
22
+ pub use life::Life;
23
+ pub use load::{Load, HOLDING_ITEM};
24
+ pub use park::Park;
25
+
26
+ /// Small, so a slow handler delays at most this many neighbors (stealing rescues them).
27
+ pub const LANE_DEPTH: usize = 4;
28
+
29
+ /// A full inbox stops the sockets' readers; each socket's share is lower (ws::INBOUND_CREDIT).
30
+ pub const WS_INBOX: usize = 1024;
31
+
32
+ /// A held lane lock: retire, quarantine and recycle check the generation under it.
33
+ type LaneGuard<'a> = parking_lot::MutexGuard<'a, Option<flume::Sender<LaneItem>>>;
34
+
35
+ /// Its last Arc may go in a thread-safe free, so what it holds keeps typed_data.rs's promise.
36
+ /// Park, Load, Life, the lane lock and the Arc's count sit on cache lines of their own (128 bytes,
37
+ /// as inline's Spinners): dispatch locks the lane and reads Park and Load for every request while
38
+ /// the worker writes them, and a field added anywhere moves none of them onto another's line.
39
+ #[derive(Default)]
40
+ pub struct WorkerSlot {
41
+ pub lane: Lane,
42
+ pub park: Park,
43
+ pub load: Load,
44
+ pub life: Life,
45
+ /// Lane mode only: the WebSockets this worker accepted.
46
+ pub sockets: crate::ws::SlotSockets,
47
+ /// Open hijack bridges of this worker's requests. In :ractor mode the app serves them
48
+ /// from the worker's Ractor, so a worker holding any is not idle.
49
+ pub hijacked: AtomicUsize,
50
+ pub inline: InlineSeats,
51
+ }
52
+
53
+ /// worker_loop serving inline: its open connections and their sockets, those answered whose job
54
+ /// has not looked since (placement skips them), and counters never reset.
55
+ #[derive(Default)]
56
+ pub struct InlineSeats {
57
+ pub conns: AtomicUsize,
58
+ pub ios: Mutex<Vec<crate::inline::Listed>>,
59
+ pub answered: AtomicUsize,
60
+ pub requests: AtomicU64,
61
+ /// Connections Kino cut off, whatever for (IoState::ends).
62
+ pub closed: AtomicU64,
63
+ /// Spins its connections' jobs ended, whatever they caught.
64
+ pub spins: AtomicU64,
65
+ }
66
+
67
+ impl WorkerSlot {
68
+ pub fn new(lanes: bool, inbox: usize, doorbell: Option<Doorbell>, inline: bool) -> Self {
69
+ WorkerSlot {
70
+ lane: Lane::new(lanes, inbox, doorbell, inline),
71
+ ..WorkerSlot::default()
72
+ }
73
+ }
74
+
75
+ pub fn generation(&self) -> u64 {
76
+ self.life.generation()
77
+ }
78
+
79
+ /// Every lane send comes here, ringing a waiting worker_loop doorbell. Full at lane_depth, and
80
+ /// for a request once the worker retired or is at capacity.
81
+ #[inline]
82
+ pub fn send_lane(&self, item: LaneItem) -> Result<(), flume::TrySendError<LaneItem>> {
83
+ self.send_lane_upto(item, usize::MAX)
84
+ }
85
+
86
+ /// With a worker_loop lane full at `depth` when that is less than its lane_depth.
87
+ #[inline]
88
+ pub fn send_lane_upto(
89
+ &self,
90
+ item: LaneItem,
91
+ depth: usize,
92
+ ) -> Result<(), flume::TrySendError<LaneItem>> {
93
+ let lane = self.lane.tx.lock();
94
+ let Some(tx) = lane.as_ref() else {
95
+ return Err(flume::TrySendError::Disconnected(item));
96
+ };
97
+ let request = matches!(item, LaneItem::Request(_));
98
+ // Under the lane lock, as WorkerSlot::retire_at orders it.
99
+ if request && self.life.retired() {
100
+ return Err(flume::TrySendError::Full(item));
101
+ }
102
+ let Some(doorbell) = &self.lane.doorbell else {
103
+ debug_assert!(depth >= LANE_DEPTH, "a classic lane is LANE_DEPTH deep");
104
+ return tx.try_send(item);
105
+ };
106
+ if request && self.load.at_capacity() {
107
+ return Err(flume::TrySendError::Full(item));
108
+ }
109
+ // The channel is unbounded: every send takes the lane lock, so the
110
+ // count cannot grow between this look and the send.
111
+ if tx.len() >= depth.min(self.lane_depth()) {
112
+ return Err(flume::TrySendError::Full(item));
113
+ }
114
+ tx.try_send(item)?;
115
+ drop(lane);
116
+ doorbell.ring();
117
+ Ok(())
118
+ }
119
+
120
+ /// For a worker_loop worker, the room it has left when more than LANE_DEPTH: it takes a
121
+ /// request whenever its thread comes back with a job slot free, so its lane holds that many.
122
+ pub fn lane_depth(&self) -> usize {
123
+ match self.lane.is_worker_loop() {
124
+ true => self.load.room().max(LANE_DEPTH),
125
+ false => LANE_DEPTH,
126
+ }
127
+ }
128
+
129
+ /// A worker_loop worker answered the request (Load::answered); nothing to any other.
130
+ /// The thread that served an `inline` one goes back to its loop's doorbell wait or a job.
131
+ pub fn answered(&self, responder: &Arc<Responder>, inline: bool) {
132
+ if !self.lane.is_worker_loop() {
133
+ return;
134
+ }
135
+ self.load.answered(responder);
136
+ if inline {
137
+ let now = crate::mono::mono_us();
138
+ if self.park.parked.load(Ordering::Relaxed) {
139
+ self.load.waits_on_doorbell(now);
140
+ } else {
141
+ self.load.last_started_us.store(now, Ordering::Relaxed);
142
+ }
143
+ }
144
+ }
145
+
146
+ /// When the work its thread is away on started (mono us), for the stats; None while it has
147
+ /// none. A worker_loop worker is judged by its thread's time away from its loop while
148
+ /// anything is open or waits, not by how long its requests wait.
149
+ pub fn busy_since(&self) -> Option<u64> {
150
+ if !self.lane.is_worker_loop() {
151
+ return self.load.busy_since();
152
+ }
153
+ let in_flight = self.load.in_flight();
154
+ let away = self.load.away_since()?;
155
+ (in_flight > 0 || self.lane.has_waiting()).then_some(away)
156
+ }
157
+
158
+ /// Hand a placed connection to this worker_loop worker and ring its doorbell; back if its
159
+ /// lane is closed or it retired, was quarantined or left its slot, checked under the lane
160
+ /// lock.
161
+ pub fn send_placed(&self, conn: Box<InlineConn>) -> Result<(), Box<InlineConn>> {
162
+ let lane = self.lane.tx.lock();
163
+ let (Some(_), Some(placed), Some(doorbell)) =
164
+ (lane.as_ref(), &self.lane.placed_tx, &self.lane.doorbell)
165
+ else {
166
+ return Err(conn);
167
+ };
168
+ if self.life.retired()
169
+ || self.life.quarantined.load(Ordering::SeqCst)
170
+ || self.load.capacity.load(Ordering::Relaxed) == 0
171
+ {
172
+ return Err(conn);
173
+ }
174
+ // Listed under the lane lock, under which a crash retires the slot before it gives up the
175
+ // slot's connections: one it would refuse is never among them.
176
+ conn.list();
177
+ placed.send(conn).map_err(|refused| refused.into_inner())?;
178
+ drop(lane);
179
+ doorbell.ring();
180
+ Ok(())
181
+ }
182
+
183
+ pub fn close_lane(&self) {
184
+ self.lane.tx.lock().take();
185
+ self.lane.ring_doorbell();
186
+ }
187
+
188
+ /// One bell in the lane at a time, for what reached the inbox or a due wake; a full lane's
189
+ /// worker is busy and checks its inbox on every take. A busy worker_loop worker may read
190
+ /// only its inbox, so its own doorbell rings either way.
191
+ pub fn notify(&self) {
192
+ if self.lane.bell_pending.swap(true, Ordering::SeqCst) {
193
+ self.lane.ring_doorbell();
194
+ return;
195
+ }
196
+ if self.send_lane(LaneItem::Bell).is_err() {
197
+ self.lane.took_bell();
198
+ self.lane.ring_doorbell();
199
+ }
200
+ }
201
+
202
+ /// The next take hands `:wake` before any request; wakes until then coalesce. False
203
+ /// without lanes.
204
+ pub fn wake(&self) -> bool {
205
+ if !self.lane.exists() {
206
+ return false;
207
+ }
208
+ if !self.lane.wake_pending.swap(true, Ordering::SeqCst) {
209
+ self.notify();
210
+ }
211
+ true
212
+ }
213
+
214
+ /// Send the worker home once idle, if still at `generation`. Raised under the lane lock
215
+ /// the dispatcher holds while it checks and sends, so every dispatch that saw "not
216
+ /// retired" is in the lane before the worker drains it. The sockets close with 1001
217
+ /// first, so a later worker on the slot cannot inherit the close.
218
+ /// Its inline connections go to hyper at their jobs' next look, their clients keeping them.
219
+ pub fn retire_at(&self, generation: u64) -> bool {
220
+ let lane = self.lane.tx.lock();
221
+ let current = self.generation() == generation;
222
+ if current {
223
+ self.retire_under(&lane);
224
+ }
225
+ current
226
+ }
227
+
228
+ fn retire_under(&self, _lane: &LaneGuard<'_>) {
229
+ crate::ws::close_slot(self, crate::ws::GOING_AWAY, crate::ws::Cause::GoingAway);
230
+ self.life.retired.store(true, Ordering::SeqCst);
231
+ }
232
+
233
+ /// Give the slot up as wedged if still at `generation` (the sample may predate a crash):
234
+ /// its sockets' events are dropped and they close with 1011.
235
+ /// Its idle inline connections close and unplaced ones go to hyper (flag set under the lane
236
+ /// lock).
237
+ pub fn quarantine_at(&self, generation: u64) -> bool {
238
+ {
239
+ let _lane = self.lane.tx.lock();
240
+ if self.generation() != generation {
241
+ return false;
242
+ }
243
+ self.life.quarantined.store(true, Ordering::SeqCst);
244
+ }
245
+ crate::ws::give_up_slot(self);
246
+ crate::inline::quarantine(self);
247
+ true
248
+ }
249
+
250
+ /// Hand the slot to a new worker once quiet: no socket of the last worker counts on it,
251
+ /// no hijacked or inline connection is open, its last worker's handle let go (Life::holder),
252
+ /// and it is not quarantined (its worker may come back).
253
+ /// Slots are never removed. Returns the new generation.
254
+ pub fn recycle(&self) -> Option<u64> {
255
+ let lane = self.lane.tx.lock();
256
+ let quiet = self.sockets.open() == 0
257
+ && self.hijacked.load(Ordering::SeqCst) == 0
258
+ && self.inline.conns.load(Ordering::SeqCst) == 0
259
+ && !self.life.is_held()
260
+ && !self.life.quarantined.load(Ordering::SeqCst);
261
+ if !quiet {
262
+ return None;
263
+ }
264
+ crate::ws::hand_over(self);
265
+ self.reset_under(&lane);
266
+ Some(self.generation())
267
+ }
268
+
269
+ /// Retire the slot first, so neither dispatch nor placement picks the dead worker, then 500
270
+ /// or cut (for `why`) what it was serving. Out come the requests that waited in its lane.
271
+ pub fn abort(&self, why: Cut) -> Vec<BoxedCtx> {
272
+ self.retire_dead();
273
+ crate::inline::giving_up(self, Cut::Crash);
274
+ for responder in self.load.current.lock().drain(..) {
275
+ responder.close_bells();
276
+ responder.give_up(why);
277
+ }
278
+ self.clear_dead(Cut::Crash)
279
+ }
280
+
281
+ /// The worker may still run, so its requests stay listed for interrupt_all_workers.
282
+ /// Its lane's requests get their 500 as they drop.
283
+ pub fn abort_held(&self) {
284
+ crate::inline::giving_up(self, Cut::Shutdown);
285
+ for responder in self.load.current.lock().iter() {
286
+ responder.give_up(Cut::Shutdown);
287
+ }
288
+ self.interrupt();
289
+ self.retire_dead();
290
+ drop(self.clear_dead(Cut::Shutdown));
291
+ }
292
+
293
+ /// Retired under the lane lock as in retire_at, so neither dispatch nor placement reaches the
294
+ /// dead worker; the lane and a worker_loop doorbell stay for the slot's next worker.
295
+ fn retire_dead(&self) {
296
+ {
297
+ let _lane = self.lane.tx.lock();
298
+ self.life.retired.store(true, Ordering::SeqCst);
299
+ }
300
+ self.lane.ring_doorbell();
301
+ self.park.parked.store(true, Ordering::Relaxed);
302
+ }
303
+
304
+ /// What the dead worker left: its sensors reset, its lane's requests out for the caller to
305
+ /// dispatch again or drop, its inline connections ended for `why`.
306
+ fn clear_dead(&self, why: Cut) -> Vec<BoxedCtx> {
307
+ self.load.clear();
308
+ let queued = self.lane.rx.as_ref().map_or_else(Vec::new, |rx| {
309
+ rx.try_iter()
310
+ .filter_map(|item| match item {
311
+ LaneItem::Request(ctx) => Some(ctx),
312
+ LaneItem::Bell => None,
313
+ })
314
+ .collect()
315
+ });
316
+ // Unplaced connections go to hyper with nothing read; served ones end here whatever their
317
+ // jobs do next, but for those a crash finds idle, which go to hyper too.
318
+ crate::inline::unplace(self);
319
+ crate::inline::abandon_slot(self, why);
320
+ queued
321
+ }
322
+
323
+ /// Abort, and close its sockets with 1011 (their handlers died with it); how many.
324
+ /// Its lane's requests go to the other workers as new arrivals would (dispatch::redispatch).
325
+ pub fn crash(&self, server: &ServerInner) -> usize {
326
+ for ctx in self.abort(Cut::Crash) {
327
+ crate::dispatch::redispatch(server, ctx);
328
+ }
329
+ crate::ws::give_up_slot(self)
330
+ }
331
+
332
+ /// Body I/O under a fiber scheduler waits on its requests' bells, rung after the halt.
333
+ /// Inline connections not serving a request (reading one, or still writing an answer) close.
334
+ pub fn interrupt(&self) {
335
+ self.halt();
336
+ for responder in self.load.current.lock().iter() {
337
+ responder.ring_bells();
338
+ }
339
+ crate::inline::shut_unserved(self);
340
+ }
341
+
342
+ pub fn halt(&self) {
343
+ self.life.halt();
344
+ }
345
+
346
+ /// Its worker leaves: the wakers it handed out stop waking.
347
+ pub fn release(&self) {
348
+ self.life.generation.fetch_add(1, Ordering::SeqCst);
349
+ self.life.drained.lock().take();
350
+ }
351
+
352
+ /// Fresh for a new worker; the lane channel and the quarantine mark stay.
353
+ fn reset_under(&self, _lane: &LaneGuard<'_>) {
354
+ self.load.current.lock().clear();
355
+ self.life.retired.store(false, Ordering::SeqCst);
356
+ self.life.reset_halt();
357
+ self.park.parked.store(false, Ordering::SeqCst);
358
+ self.park.parked_at.store(0, Ordering::Relaxed);
359
+ self.lane.wake_pending.store(false, Ordering::SeqCst);
360
+ // A crashed worker's lane was drained without taking its doorbell.
361
+ self.lane.bell_pending.store(false, Ordering::SeqCst);
362
+ if let Some(doorbell) = &self.lane.doorbell {
363
+ // Nor its worker_loop doorbell: the next worker starts with none armed, none rung.
364
+ doorbell.disarm();
365
+ if let Some(sockets) = doorbell.sockets() {
366
+ sockets.drain();
367
+ }
368
+ }
369
+ self.life.generation.fetch_add(1, Ordering::SeqCst);
370
+ self.sockets.reset();
371
+ self.park.own_run.store(0, Ordering::Relaxed);
372
+ self.park.woke.store(false, Ordering::Relaxed);
373
+ self.load.served.store(0, Ordering::Relaxed);
374
+ self.load.clear();
375
+ // Until the new worker's serve sets its own, its lane holds LANE_DEPTH.
376
+ self.load.capacity.store(0, Ordering::Relaxed);
377
+ self.load.holding.store(0, Ordering::Relaxed);
378
+ self.life.drained.lock().take();
379
+ }
380
+ }
381
+
382
+ #[cfg(test)]
383
+ mod tests {
384
+ use std::sync::atomic::Ordering::{Relaxed, SeqCst};
385
+ use std::sync::Arc;
386
+ use std::time::Duration;
387
+
388
+ use super::*;
389
+ use crate::testing::{slot, TestServer};
390
+
391
+ impl WorkerSlot {
392
+ /// `retire_at` the slot's current generation.
393
+ pub(crate) fn retire(&self) {
394
+ let lane = self.lane.tx.lock();
395
+ self.retire_under(&lane);
396
+ }
397
+
398
+ /// Return the slot to its fresh state, quiet or not (recycle checks).
399
+ pub(crate) fn reset(&self) {
400
+ let lane = self.lane.tx.lock();
401
+ self.reset_under(&lane);
402
+ }
403
+ }
404
+
405
+ fn lanes_slot() -> Arc<WorkerSlot> {
406
+ slot(&TestServer::lanes().workers(1).build(), 0)
407
+ }
408
+
409
+ #[test]
410
+ fn a_reset_slot_is_fresh_for_its_next_worker_but_for_its_lane_and_a_quarantine_mark() {
411
+ let slot = lanes_slot();
412
+ slot.park.parked.store(true, Relaxed);
413
+ slot.life.halt();
414
+ slot.life.quarantined.store(true, Relaxed);
415
+ slot.lane.wake_pending.store(true, Relaxed);
416
+ slot.load.served.store(5, Relaxed);
417
+ slot.load.in_flight.store(1, Relaxed);
418
+ slot.load.last_started_us.store(9, Relaxed);
419
+ slot.load.current.lock().push(Arc::default());
420
+ slot.load.capacity.store(16, Relaxed);
421
+
422
+ slot.retire();
423
+ slot.reset();
424
+ let flags = [
425
+ slot.life.retired.load(Relaxed),
426
+ slot.park.parked.load(Relaxed),
427
+ slot.life.is_halted(),
428
+ slot.lane.wake_pending.load(Relaxed),
429
+ ];
430
+ assert_eq!(
431
+ flags, [false; 4],
432
+ "the last occupant's wake is not the next one's"
433
+ );
434
+ let load = (
435
+ slot.load.served.load(Relaxed),
436
+ slot.load.in_flight.load(Relaxed),
437
+ slot.load.last_started_us.load(Relaxed),
438
+ slot.load.current.lock().len(),
439
+ slot.load.capacity.load(Relaxed),
440
+ );
441
+ assert_eq!(load, (0, 0, 0, 0, 0));
442
+ // A wedged slot stays flagged, should it ever come back around, and
443
+ // the next occupant takes from the same lane.
444
+ assert!(slot.life.quarantined.load(Relaxed) && slot.lane.tx.lock().is_some());
445
+ }
446
+
447
+ #[test]
448
+ fn a_slot_is_recycled_once_its_last_worker_left_nothing_open_unless_it_was_quarantined() {
449
+ // Its socket counts in the process-wide counts socket tests read.
450
+ let _serial = crate::testing::serial_blocking();
451
+ let slot = lanes_slot();
452
+ slot.retire();
453
+ slot.hijacked.store(1, SeqCst);
454
+ let socket =
455
+ crate::ws::testing::QueuedSocket::with_limits(slot.clone(), Default::default());
456
+
457
+ assert!(slot.recycle().is_none(), "a hijacked connection is open");
458
+ let why = "a refused recycle changes nothing";
459
+ assert!(slot.life.retired.load(SeqCst), "{why}");
460
+ slot.hijacked.store(0, SeqCst);
461
+ assert!(slot.recycle().is_none(), "a socket is open");
462
+ socket.close();
463
+ assert!(slot.recycle().is_some());
464
+ assert!(!slot.life.retired.load(SeqCst));
465
+
466
+ slot.life.quarantined.store(true, SeqCst);
467
+ slot.retire();
468
+ assert!(
469
+ slot.recycle().is_none(),
470
+ "a quarantined slot is never recycled"
471
+ );
472
+ }
473
+
474
+ #[test]
475
+ fn retire_waits_for_a_dispatcher_holding_the_lane_lock() {
476
+ let slot = lanes_slot();
477
+
478
+ // A dispatcher that has already read "not retired" and is sending.
479
+ let sending = slot.lane.tx.lock();
480
+ let retiring = std::thread::spawn({
481
+ let slot = slot.clone();
482
+ move || slot.retire()
483
+ });
484
+ std::thread::sleep(Duration::from_millis(30));
485
+ assert!(
486
+ !slot.life.retired.load(SeqCst),
487
+ "the flag must not go up under a dispatcher's lock"
488
+ );
489
+
490
+ drop(sending);
491
+ retiring.join().expect("retire thread");
492
+ assert!(slot.life.retired.load(SeqCst));
493
+ }
494
+ }
@@ -0,0 +1,82 @@
1
+ //! Whether a slot's worker is parked, and since when.
2
+
3
+ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
4
+
5
+ use crate::doorbell::Doorbell;
6
+ use crate::queue::Item;
7
+ use crate::registry::ServerInner;
8
+
9
+ /// The dispatcher prefers awake lanes, so a hot worker never pays a futex wake.
10
+ #[derive(Default)]
11
+ #[repr(align(128))]
12
+ pub struct Park {
13
+ pub parked: AtomicBool,
14
+ /// ServerInner::park_seq at its last park (0 = never); among idle workers the last is warmest.
15
+ pub parked_at: AtomicU64,
16
+ /// Only wakes were taken since parked_at was stamped, so the next park keeps it. Owner only.
17
+ pub woke: AtomicBool,
18
+ /// Socket events since a take last looked at the lane, a wake counting as a whole run
19
+ /// (queue::OWN_RUN), so neither a flooding socket nor a self-waking hook starves requests.
20
+ pub own_run: AtomicU32,
21
+ /// Owner only: when it last got the GVL back from a park or a pass (mono us), for shared_gvl.
22
+ gvl_since_us: AtomicU64,
23
+ }
24
+
25
+ impl Park {
26
+ /// A worker that has taken only wakes since its parked_at was stamped
27
+ /// keeps it: periodic wakes must not reorder the hot-lane dispatch.
28
+ /// On a worker_loop server, the first request waiting for room looks again.
29
+ pub fn park(&self, server: &ServerInner) {
30
+ if !self.woke.load(Ordering::Relaxed) {
31
+ let seq = server.park_seq.fetch_add(1, Ordering::Relaxed) + 1;
32
+ self.parked_at.store(seq, Ordering::Relaxed);
33
+ }
34
+ self.woke.store(true, Ordering::Relaxed);
35
+ self.parked.store(true, Ordering::SeqCst);
36
+ if server.config.worker_loop {
37
+ server.lane_room.notify();
38
+ }
39
+ }
40
+
41
+ pub fn unpark(&self) {
42
+ self.parked.store(false, Ordering::SeqCst);
43
+ }
44
+
45
+ /// A worker_loop worker found work: a parked one disarms its doorbell.
46
+ pub fn awake(&self, doorbell: &Doorbell) {
47
+ if self.parked.load(Ordering::Relaxed) {
48
+ doorbell.disarm();
49
+ self.unpark();
50
+ }
51
+ }
52
+
53
+ /// Its worker got a shared GVL back, from a park or a pass, at `now` (mono us).
54
+ #[inline]
55
+ pub fn got_gvl(&self, now: u64) {
56
+ self.gvl_since_us.store(now, Ordering::Relaxed);
57
+ }
58
+
59
+ /// Since when its worker has held a shared GVL (mono us).
60
+ #[inline]
61
+ pub fn held_gvl_since(&self) -> u64 {
62
+ self.gvl_since_us.load(Ordering::Relaxed)
63
+ }
64
+
65
+ #[inline]
66
+ pub fn took(&self, item: Option<&Item>) {
67
+ let only_wakes = self.woke.load(Ordering::Relaxed) && matches!(item, Some(Item::Wake));
68
+ self.woke.store(only_wakes, Ordering::Relaxed);
69
+ }
70
+
71
+ /// Advisory: the dispatcher's look.
72
+ #[inline]
73
+ pub fn is_parked(&self) -> bool {
74
+ self.parked.load(Ordering::Relaxed)
75
+ }
76
+
77
+ /// Its place in the hot-lane order: the later it parked, the warmer.
78
+ #[inline]
79
+ pub fn parked_at(&self) -> u64 {
80
+ self.parked_at.load(Ordering::Relaxed)
81
+ }
82
+ }