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
@@ -4,50 +4,15 @@
4
4
  //! the least-loaded shard. Each shard then owns that connection for its
5
5
  //! lifetime, avoiding the shared Tokio worker pool on hot HTTP paths.
6
6
 
7
- use std::net::SocketAddr;
8
7
  use std::sync::atomic::{AtomicUsize, Ordering};
9
8
  use std::sync::Arc;
10
9
  use std::thread::JoinHandle;
11
10
 
11
+ use crate::counters::Counted;
12
12
  use crate::listen::Listener;
13
13
  use crate::log::{self, Level};
14
- use crate::registry::{ServerInner, STATE_DRAINING};
15
- use crate::server::{serve_conn, AsyncListener, Conn};
16
-
17
- /// A connection in transit from the acceptor to its shard. Tokio streams
18
- /// are bound to the runtime that registered them, so the handoff carries
19
- /// the std stream and the shard re-registers it on arrival.
20
- enum StdConn {
21
- Tcp(std::net::TcpStream),
22
- Unix(std::os::unix::net::UnixStream),
23
- }
24
-
25
- impl StdConn {
26
- /// Register with the calling (shard) runtime.
27
- fn into_tokio(self) -> std::io::Result<Conn> {
28
- Ok(match self {
29
- StdConn::Tcp(stream) => Conn::Tcp(tokio::net::TcpStream::from_std(stream)?),
30
- StdConn::Unix(stream) => Conn::Unix(tokio::net::UnixStream::from_std(stream)?),
31
- })
32
- }
33
- }
34
-
35
- /// Detach an accepted stream from the acceptor's runtime for the handoff.
36
- fn into_std(conn: Conn) -> std::io::Result<StdConn> {
37
- Ok(match conn {
38
- Conn::Tcp(stream) => StdConn::Tcp(stream.into_std()?),
39
- Conn::Unix(stream) => StdConn::Unix(stream.into_std()?),
40
- })
41
- }
42
-
43
- /// One accepted connection en route to a shard: the detached stream, the
44
- /// addresses hyper reports, and the slot it holds against max_connections.
45
- struct Accepted {
46
- conn: StdConn,
47
- remote_addr: SocketAddr,
48
- local_addr: SocketAddr,
49
- permit: tokio::sync::OwnedSemaphorePermit,
50
- }
14
+ use crate::registry::ServerInner;
15
+ use crate::server::{next_accept, serve_conn, Accepted, AsyncListener, StdConn};
51
16
 
52
17
  /// Shard count: an explicit `io_threads` wins; the default is half the
53
18
  /// available CPUs. Framing requests is cheap next to running the app, so
@@ -129,20 +94,29 @@ fn join_all(handles: Vec<JoinHandle<()>>) {
129
94
  }
130
95
  }
131
96
 
132
- fn current_thread_runtime() -> std::io::Result<tokio::runtime::Runtime> {
133
- tokio::runtime::Builder::new_current_thread()
134
- .enable_all()
135
- .build()
136
- }
97
+ /// What an I/O thread reports once its runtime is up, or what kept it
98
+ /// from coming up.
99
+ type Ready = std::sync::mpsc::SyncSender<std::io::Result<()>>;
137
100
 
138
- /// Wait for a just spawned I/O thread to report its runtime up, so a
139
- /// startup failure becomes the boot error Ruby sees instead of a silently
140
- /// dead thread.
141
- fn await_ready(
142
- handle: JoinHandle<()>,
143
- ready_rx: std::sync::mpsc::Receiver<std::io::Result<()>>,
101
+ /// Spawn thread `name` (the `what` thread) on a current-thread runtime of its own, running
102
+ /// `run`, and wait for it to report ready, so a startup failure becomes Ruby's boot error.
103
+ fn spawn_io_thread(
104
+ name: String,
144
105
  what: &str,
106
+ run: impl FnOnce(tokio::runtime::Runtime, Ready) + Send + 'static,
145
107
  ) -> std::io::Result<JoinHandle<()>> {
108
+ let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
109
+ let handle = std::thread::Builder::new().name(name).spawn(move || {
110
+ match tokio::runtime::Builder::new_current_thread()
111
+ .enable_all()
112
+ .build()
113
+ {
114
+ Ok(runtime) => run(runtime, ready_tx),
115
+ Err(error) => {
116
+ let _ = ready_tx.send(Err(error));
117
+ }
118
+ }
119
+ })?;
146
120
  match ready_rx.recv() {
147
121
  Ok(Ok(())) => Ok(handle),
148
122
  Ok(Err(error)) => {
@@ -157,27 +131,22 @@ fn await_ready(
157
131
 
158
132
  fn spawn_shard(
159
133
  index: usize,
160
- rx: tokio::sync::mpsc::UnboundedReceiver<Accepted>,
134
+ rx: tokio::sync::mpsc::UnboundedReceiver<Accepted<StdConn>>,
161
135
  acceptor: Option<tokio_rustls::TlsAcceptor>,
162
136
  server: Arc<ServerInner>,
163
137
  load: Arc<AtomicUsize>,
164
138
  mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
165
139
  ) -> std::io::Result<JoinHandle<()>> {
166
- let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
167
- let handle = std::thread::Builder::new()
168
- .name(format!("kino-io-{index}"))
169
- .spawn(move || {
170
- let runtime = match current_thread_runtime() {
171
- Ok(runtime) => runtime,
172
- Err(error) => {
173
- let _ = ready_tx.send(Err(error));
174
- return;
175
- }
176
- };
140
+ spawn_io_thread(
141
+ format!("kino-io-{index}"),
142
+ "shard",
143
+ move |runtime, ready_tx| {
144
+ // Shards run until final teardown, unlike the acceptor.
145
+ let _ = server.io_runtime.set(runtime.handle().clone());
177
146
  let _ = ready_tx.send(Ok(()));
178
147
  runtime.block_on(shard_loop(rx, acceptor, server, load, &mut shutdown_rx));
179
- })?;
180
- await_ready(handle, ready_rx, "shard")
148
+ },
149
+ )
181
150
  }
182
151
 
183
152
  fn spawn_acceptor(
@@ -185,20 +154,13 @@ fn spawn_acceptor(
185
154
  server: Arc<ServerInner>,
186
155
  max_connections: usize,
187
156
  shutdown_rx: tokio::sync::watch::Receiver<bool>,
188
- shard_txs: Vec<tokio::sync::mpsc::UnboundedSender<Accepted>>,
157
+ shard_txs: Vec<tokio::sync::mpsc::UnboundedSender<Accepted<StdConn>>>,
189
158
  loads: Vec<Arc<AtomicUsize>>,
190
159
  ) -> std::io::Result<JoinHandle<()>> {
191
- let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
192
- let handle = std::thread::Builder::new()
193
- .name("kino-accept".to_string())
194
- .spawn(move || {
195
- let runtime = match current_thread_runtime() {
196
- Ok(runtime) => runtime,
197
- Err(error) => {
198
- let _ = ready_tx.send(Err(error));
199
- return;
200
- }
201
- };
160
+ spawn_io_thread(
161
+ "kino-accept".to_string(),
162
+ "accept",
163
+ move |runtime, ready_tx| {
202
164
  runtime.block_on(async move {
203
165
  // Registration must happen on this runtime; a failure is
204
166
  // routed through the same ready channel as a build error.
@@ -220,16 +182,15 @@ fn spawn_acceptor(
220
182
  )
221
183
  .await;
222
184
  });
223
- })?;
224
- await_ready(handle, ready_rx, "accept")
185
+ },
186
+ )
225
187
  }
226
188
 
227
189
  /// Serve handed-over connections until the acceptor is gone, then let the
228
- /// remaining ones finish. The final teardown signal cuts either phase
229
- /// short: dropping the runtime cancels connection tasks at their next
230
- /// await point.
190
+ /// remaining ones run until the final teardown signal: dropping the
191
+ /// runtime cancels connection tasks at their next await point.
231
192
  async fn shard_loop(
232
- mut rx: tokio::sync::mpsc::UnboundedReceiver<Accepted>,
193
+ mut rx: tokio::sync::mpsc::UnboundedReceiver<Accepted<StdConn>>,
233
194
  acceptor: Option<tokio_rustls::TlsAcceptor>,
234
195
  server: Arc<ServerInner>,
235
196
  load: Arc<AtomicUsize>,
@@ -243,117 +204,76 @@ async fn shard_loop(
243
204
  let Some(accepted) = accepted else { break };
244
205
  let acceptor = acceptor.clone();
245
206
  let server = server.clone();
246
- let guard = LoadGuard(load.clone());
247
- connections.spawn(async move {
248
- let _guard = guard;
249
- serve_accepted(accepted, acceptor, server).await;
250
- });
207
+ // The acceptor counted it.
208
+ let load = Counted::adopt(load.clone(), 1);
209
+ connections.spawn(serve_accepted(accepted, load, acceptor, server));
251
210
  }
252
211
  // Reap closed connections so the set stays small.
253
212
  Some(_) = connections.join_next(), if !connections.is_empty() => {}
254
213
  }
255
214
  }
256
- // The acceptor is gone: drain. Every join is one connection closing.
257
- while !connections.is_empty() {
258
- tokio::select! {
259
- _ = shutdown_rx.changed() => return,
260
- _ = connections.join_next() => {}
261
- }
262
- }
263
- }
264
-
265
- /// Keeps the shard's connection count honest whichever way the task ends:
266
- /// return, panic, or cancellation at teardown. A plain decrement after the
267
- /// await would never run on the last two.
268
- struct LoadGuard(Arc<AtomicUsize>);
269
-
270
- impl Drop for LoadGuard {
271
- fn drop(&mut self) {
272
- self.0.fetch_sub(1, Ordering::Relaxed);
273
- }
215
+ // The acceptor is gone. Upgraded connections (hijacked bridges, native
216
+ // WebSockets) run in tasks outside the set, so the runtime stays up
217
+ // until teardown even once every connection in it has closed.
218
+ let _ = shutdown_rx.changed().await;
219
+ drop(connections);
274
220
  }
275
221
 
276
222
  /// The shard's half of the handoff: re-register the stream on this
277
223
  /// runtime, then run the shared connection pipeline (TLS handshake,
278
224
  /// protocol layer) exactly as the default runtime would.
279
225
  async fn serve_accepted(
280
- accepted: Accepted,
226
+ Accepted {
227
+ conn,
228
+ peer,
229
+ mut held,
230
+ }: Accepted<StdConn>,
231
+ load: Counted,
281
232
  acceptor: Option<tokio_rustls::TlsAcceptor>,
282
233
  server: Arc<ServerInner>,
283
234
  ) {
284
- // Held for the connection's lifetime; dropping it frees a slot.
285
- let _permit = accepted.permit;
286
- let conn = match accepted.conn.into_tokio() {
287
- Ok(conn) => conn,
288
- Err(_) => {
289
- log::emit(
290
- Level::Warn,
291
- "tokio",
292
- "failed to register a stream on an I/O shard",
293
- );
294
- return;
295
- }
235
+ // Tokio streams are bound to the runtime that registered them: the shard registers the
236
+ // handed-over std stream anew.
237
+ let Ok(conn) = conn.into_tokio() else {
238
+ log::emit(
239
+ Level::Warn,
240
+ "tokio",
241
+ "failed to register a stream on an I/O shard",
242
+ );
243
+ return;
296
244
  };
297
- serve_conn(
298
- conn,
299
- acceptor,
300
- server,
301
- accepted.remote_addr,
302
- accepted.local_addr,
303
- )
304
- .await;
245
+ held.shard_load = Some(load);
246
+ serve_conn(Accepted { conn, peer, held }, acceptor, server).await;
305
247
  }
306
248
 
307
- /// The sharded accept loop. Same backpressure as the default loop: the
308
- /// permit is acquired before accept, so past max_connections the excess
309
- /// waits in the kernel backlog instead of being accepted and dropped.
310
- /// A shard whose channel is gone is marked dead and routed around; with
311
- /// no shard left the loop stops accepting and flips the server to
312
- /// draining, so the control plane stops reporting ready.
249
+ /// The sharded accept loop, with the default loop's backpressure
250
+ /// (next_accept). A shard whose channel is gone is marked dead and
251
+ /// routed around; with no shard left the loop stops accepting and flips
252
+ /// the server to draining, so the control plane stops reporting ready.
313
253
  async fn accept_loop(
314
254
  listener: AsyncListener,
315
255
  server: Arc<ServerInner>,
316
256
  max_connections: usize,
317
257
  mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
318
- shard_txs: Vec<tokio::sync::mpsc::UnboundedSender<Accepted>>,
258
+ shard_txs: Vec<tokio::sync::mpsc::UnboundedSender<Accepted<StdConn>>>,
319
259
  loads: Vec<Arc<AtomicUsize>>,
320
- ready_tx: std::sync::mpsc::SyncSender<std::io::Result<()>>,
260
+ ready_tx: Ready,
321
261
  ) {
322
262
  let conn_limit = Arc::new(tokio::sync::Semaphore::new(max_connections));
323
263
  let mut live = vec![true; shard_txs.len()];
324
264
  let _ = ready_tx.send(Ok(()));
325
- 'accept: loop {
326
- let permit = tokio::select! {
327
- _ = shutdown_rx.changed() => break,
328
- permit = conn_limit.clone().acquire_owned() => match permit {
329
- Ok(permit) => permit,
330
- Err(_) => break,
331
- },
332
- };
333
- let (conn, remote_addr, local_addr) = tokio::select! {
334
- _ = shutdown_rx.changed() => break,
335
- accepted = listener.accept() => match accepted {
336
- Ok(accepted) => accepted,
337
- Err(_) => continue,
338
- },
339
- };
340
- let conn = match into_std(conn) {
341
- Ok(conn) => conn,
342
- Err(_) => {
343
- log::emit(
344
- Level::Warn,
345
- "tokio",
346
- "failed to detach an accepted stream; connection dropped",
347
- );
348
- continue;
349
- }
350
- };
351
- let mut accepted = Accepted {
352
- conn,
353
- remote_addr,
354
- local_addr,
355
- permit,
265
+ 'accept: while let Some(Accepted { conn, peer, held }) =
266
+ next_accept(&listener, &conn_limit, &mut shutdown_rx).await
267
+ {
268
+ let Ok(conn) = StdConn::detach(conn) else {
269
+ log::emit(
270
+ Level::Warn,
271
+ "tokio",
272
+ "failed to detach an accepted stream; connection dropped",
273
+ );
274
+ continue;
356
275
  };
276
+ let mut accepted = Accepted { conn, peer, held };
357
277
  loop {
358
278
  let Some(index) = least_loaded(&loads, &live) else {
359
279
  log::emit(
@@ -361,7 +281,8 @@ async fn accept_loop(
361
281
  "tokio",
362
282
  "all I/O shards are down; not accepting connections",
363
283
  );
364
- server.state.store(STATE_DRAINING, Ordering::Relaxed);
284
+ // As a drain begins: idle inline connections close, and none spins.
285
+ server.stop_accepting();
365
286
  break 'accept;
366
287
  };
367
288
  loads[index].fetch_add(1, Ordering::Relaxed);
@@ -390,48 +311,175 @@ fn least_loaded(loads: &[Arc<AtomicUsize>], live: &[bool]) -> Option<usize> {
390
311
 
391
312
  #[cfg(test)]
392
313
  mod tests {
393
- use super::{default_thread_count, least_loaded, thread_count, Arc, AtomicUsize};
314
+ use super::*;
315
+ use crate::testing::{upgrade_request, SWITCHED};
316
+ use hyper_util::rt::TokioIo;
317
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
394
318
 
395
- fn loads(counts: &[usize]) -> Vec<Arc<AtomicUsize>> {
396
- counts
319
+ /// A client connects to `port`, and the app (the test, playing the
320
+ /// worker) takes the connection over and switches it to another
321
+ /// protocol; once a byte went through, returns both ends.
322
+ async fn upgraded(
323
+ server: &ServerInner,
324
+ port: u16,
325
+ ) -> (TokioIo<hyper::upgrade::Upgraded>, tokio::net::UnixStream) {
326
+ let tcp = tokio::net::TcpStream::connect(("127.0.0.1", port))
327
+ .await
328
+ .expect("connect");
329
+ let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tcp))
330
+ .await
331
+ .expect("h1 handshake");
332
+ tokio::spawn(conn.with_upgrades());
333
+ let pending = tokio::spawn(async move { sender.send_request(upgrade_request()).await });
334
+ let mut ctx = server.req_rx.recv_async().await.expect("the request");
335
+ let app = crate::hijack::take(&mut ctx, None).expect("an Upgrade request can be hijacked");
336
+ app.set_nonblocking(true).expect("nonblocking app end");
337
+ let mut app = tokio::net::UnixStream::from_std(app).expect("app end registered");
338
+ app.write_all(SWITCHED).await.expect("app write");
339
+ let response = pending.await.expect("join").expect("the 101");
340
+ assert_eq!(response.status(), 101);
341
+ let mut client = TokioIo::new(hyper::upgrade::on(response).await.expect("client upgrade"));
342
+ client.write_all(b"x").await.expect("client write");
343
+ app.read_u8().await.expect("the byte through the bridge");
344
+ (client, app)
345
+ }
346
+
347
+ fn counts(loads: &[Arc<AtomicUsize>]) -> Vec<usize> {
348
+ loads
397
349
  .iter()
398
- .map(|&n| Arc::new(AtomicUsize::new(n)))
350
+ .map(|load| load.load(Ordering::Relaxed))
399
351
  .collect()
400
352
  }
401
353
 
402
- #[test]
403
- fn explicit_io_threads_win() {
404
- assert_eq!(thread_count(3), 3);
405
- }
354
+ #[tokio::test]
355
+ async fn sequential_upgraded_connections_spread_across_shards() {
356
+ // Runs one at a time with the socket and bridge tests, as they do.
357
+ let _serial = crate::testing::SERIAL.lock().await;
358
+ let server = crate::testing::TestServer::shared_queue().build();
359
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
360
+ listener
361
+ .set_nonblocking(true)
362
+ .expect("nonblocking listener");
363
+ let port = listener.local_addr().expect("local addr").port();
364
+ let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
365
+ let loads = vec![Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))];
366
+ let mut handles = Vec::new();
367
+ let mut shard_txs = Vec::new();
368
+ for (index, load) in loads.iter().enumerate() {
369
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
370
+ let shard = spawn_shard(
371
+ index,
372
+ rx,
373
+ None,
374
+ server.clone(),
375
+ load.clone(),
376
+ shutdown_rx.clone(),
377
+ );
378
+ handles.push(shard.expect("shard"));
379
+ shard_txs.push(tx);
380
+ }
381
+ let listener = Listener::Tcp(listener);
382
+ let acceptor = spawn_acceptor(
383
+ listener,
384
+ server.clone(),
385
+ 16,
386
+ shutdown_rx,
387
+ shard_txs,
388
+ loads.clone(),
389
+ );
390
+ handles.push(acceptor.expect("acceptor"));
391
+
392
+ let first = upgraded(&server, port).await;
393
+ let second = upgraded(&server, port).await;
406
394
 
407
- #[test]
408
- fn least_loaded_picks_the_emptiest_live_shard() {
409
395
  assert_eq!(
410
- least_loaded(&loads(&[3, 0, 1]), &[true, true, true]),
411
- Some(1)
396
+ counts(&loads),
397
+ [1, 1],
398
+ "two open upgraded connections must count on different shards"
412
399
  );
400
+ drop((first, second));
401
+ let still = std::fmt::from_fn(|f| {
402
+ write!(
403
+ f,
404
+ "closed upgraded connections to stop counting (shard loads {:?})",
405
+ counts(&loads)
406
+ )
407
+ });
408
+ crate::testing::until(still, || counts(&loads) == [0, 0]).await;
409
+ shutdown_tx.send(true).expect("shards listening");
410
+ tokio::task::spawn_blocking(|| join_all(handles))
411
+ .await
412
+ .expect("join");
413
413
  }
414
414
 
415
- #[test]
416
- fn least_loaded_routes_around_dead_shards() {
417
- // The dead shard's count is frozen at 0; it must not win anyway.
418
- assert_eq!(
419
- least_loaded(&loads(&[3, 0, 1]), &[true, false, true]),
420
- Some(2)
421
- );
415
+ fn loads(counts: &[usize]) -> Vec<Arc<AtomicUsize>> {
416
+ counts
417
+ .iter()
418
+ .map(|&n| Arc::new(AtomicUsize::new(n)))
419
+ .collect()
420
+ }
421
+
422
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
423
+ async fn with_every_shard_down_the_acceptor_begins_the_drain_which_ends_idle_inline_connections(
424
+ ) {
425
+ use crate::inline::testing::{inline_loop_server, loopback, read_to_end};
426
+
427
+ let server = inline_loop_server(1, 8);
428
+ let (idle_client, mut idle) = loopback(&server);
429
+ assert!(matches!(idle.next(true), crate::inline::Next::Readable));
430
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
431
+ .await
432
+ .expect("bind");
433
+ let addr = listener.local_addr().expect("addr");
434
+ // Its one shard is gone: its channel's other end dropped.
435
+ let (shard_tx, shard_rx) = tokio::sync::mpsc::unbounded_channel();
436
+ drop(shard_rx);
437
+ let (_stop, shutdown_rx) = tokio::sync::watch::channel(false);
438
+ let (ready_tx, _ready) = std::sync::mpsc::sync_channel(1);
439
+ let accepting = tokio::spawn(accept_loop(
440
+ AsyncListener::Tcp(listener),
441
+ server.clone(),
442
+ 8,
443
+ shutdown_rx,
444
+ vec![shard_tx],
445
+ loads(&[0]),
446
+ ready_tx,
447
+ ));
448
+
449
+ let _refused = std::net::TcpStream::connect(addr).expect("connect");
450
+ let stopped = tokio::time::timeout(std::time::Duration::from_secs(5), accepting);
451
+ stopped
452
+ .await
453
+ .expect("it stops accepting")
454
+ .expect("the loop");
455
+ assert!(server.is_draining());
456
+ // Shut by the drain, before its job looks again or any deadline.
457
+ assert_eq!(read_to_end(&idle_client), b"");
458
+ assert!(matches!(idle.next(true), crate::inline::Next::Closed));
422
459
  }
423
460
 
424
461
  #[test]
425
- fn least_loaded_reports_when_no_shard_is_left() {
426
- assert_eq!(least_loaded(&loads(&[0, 0]), &[false, false]), None);
462
+ fn a_connection_goes_to_the_live_shard_with_the_fewest_open() {
463
+ let rows: [(&[usize], &[bool], Option<usize>); 3] = [
464
+ (&[3, 0, 1], &[true, true, true], Some(1)),
465
+ // A dead shard's count is frozen at 0; it must not win anyway.
466
+ (&[3, 0, 1], &[true, false, true], Some(2)),
467
+ (&[0, 0], &[false, false], None),
468
+ ];
469
+ for (counts, live, picked) in rows {
470
+ assert_eq!(
471
+ least_loaded(&loads(counts), live),
472
+ picked,
473
+ "{counts:?} {live:?}"
474
+ );
475
+ }
427
476
  }
428
477
 
429
478
  #[test]
430
- fn default_is_half_the_cpus() {
431
- assert_eq!(default_thread_count(1), 1);
432
- assert_eq!(default_thread_count(2), 1);
433
- assert_eq!(default_thread_count(3), 2);
434
- assert_eq!(default_thread_count(12), 6);
435
- assert_eq!(default_thread_count(128), 64);
479
+ fn io_threads_sets_the_shard_count_else_it_is_half_the_cpus() {
480
+ assert_eq!(thread_count(3), 3);
481
+ for (cpus, shards) in [(1, 1), (2, 1), (3, 2), (12, 6), (128, 64)] {
482
+ assert_eq!(default_thread_count(cpus), shards, "{cpus} CPUs");
483
+ }
436
484
  }
437
485
  }
@@ -0,0 +1,99 @@
1
+ //! The line of requests that found no lane with room on a worker_loop server: they go in
2
+ //! first come first served, and only the first in line dispatches.
3
+
4
+ use std::collections::VecDeque;
5
+ use std::sync::atomic::{fence, AtomicUsize, Ordering};
6
+ use std::sync::Arc;
7
+
8
+ use parking_lot::Mutex;
9
+ use tokio::sync::Notify;
10
+
11
+ /// While nobody waits, a take pays one load for it.
12
+ #[derive(Default)]
13
+ pub struct LaneRoom {
14
+ waiting: AtomicUsize,
15
+ line: Mutex<VecDeque<Arc<Notify>>>,
16
+ }
17
+
18
+ impl LaneRoom {
19
+ pub fn waiting(&self) -> usize {
20
+ self.waiting.load(Ordering::Relaxed)
21
+ }
22
+
23
+ /// After a lane may have gained room (a worker parked, a full worker went below its
24
+ /// capacity, lanes closed). The fence pairs with line_up's: either the newcomer's first
25
+ /// look sees the change, or this sees the newcomer.
26
+ pub fn notify(&self) {
27
+ fence(Ordering::SeqCst);
28
+ self.notify_taken();
29
+ }
30
+
31
+ /// notify after a take from a lane, with no fence: that lane's channel lock orders the
32
+ /// take and a newcomer's look at it, and the newcomer lined up before it looked.
33
+ pub fn notify_taken(&self) {
34
+ if self.waiting.load(Ordering::Relaxed) != 0 {
35
+ self.wake_first();
36
+ }
37
+ }
38
+
39
+ fn wake_first(&self) {
40
+ let first = self.line.lock().front().cloned();
41
+ if let Some(first) = first {
42
+ first.notify_one();
43
+ }
44
+ }
45
+
46
+ /// The place leaves the line when dropped, handing the turn on if it was first.
47
+ pub fn line_up(&self) -> Place<'_> {
48
+ let turn = Arc::new(Notify::new());
49
+ {
50
+ let mut line = self.line.lock();
51
+ line.push_back(turn.clone());
52
+ self.waiting.store(line.len(), Ordering::Relaxed);
53
+ }
54
+ fence(Ordering::SeqCst);
55
+ Place { room: self, turn }
56
+ }
57
+ }
58
+
59
+ pub struct Place<'a> {
60
+ room: &'a LaneRoom,
61
+ /// A notification before the wait is kept for it.
62
+ turn: Arc<Notify>,
63
+ }
64
+
65
+ impl Place<'_> {
66
+ pub fn is_first(&self) -> bool {
67
+ self.room
68
+ .line
69
+ .lock()
70
+ .front()
71
+ .is_some_and(|first| Arc::ptr_eq(first, &self.turn))
72
+ }
73
+
74
+ /// May resolve for nothing (a notification the last look acted on): look again.
75
+ pub async fn turn(&self) {
76
+ self.turn.notified().await;
77
+ }
78
+ }
79
+
80
+ impl Drop for Place<'_> {
81
+ fn drop(&mut self) {
82
+ let next = {
83
+ let mut line = self.room.line.lock();
84
+ let Some(at) = line.iter().position(|place| Arc::ptr_eq(place, &self.turn)) else {
85
+ return;
86
+ };
87
+ line.remove(at);
88
+ self.room.waiting.store(line.len(), Ordering::Relaxed);
89
+ if at == 0 {
90
+ line.front().cloned()
91
+ } else {
92
+ None
93
+ }
94
+ };
95
+ if let Some(next) = next {
96
+ next.notify_one();
97
+ }
98
+ }
99
+ }