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
@@ -0,0 +1,600 @@
1
+ //! A socket's connection task: it reads the client's messages into the
2
+ //! worker's inbox as credit allows, writes what is queued, pings a silent
3
+ //! client, and says the drain's goodbye.
4
+
5
+ use std::future::Future;
6
+ use std::io;
7
+ use std::pin::Pin;
8
+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
+ use std::sync::Arc;
10
+ use std::task::{Context, Poll};
11
+ use std::time::Duration;
12
+
13
+ use bytes::Bytes;
14
+ use hyper_util::rt::TokioIo;
15
+ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf};
16
+ use tokio::sync::mpsc;
17
+ use tungstenite::Message;
18
+
19
+ use super::codec::{close_frame, encode, Opcode, Reader};
20
+ use super::handshake::Accepted;
21
+ use super::socket::{Abort, Out};
22
+ use super::stats::{Cause, WsCount, COUNTS};
23
+ use super::{handled, shutdown_ran, WsEvent, CLOSE_TIMEOUT, GOING_AWAY};
24
+ use crate::slot::WorkerSlot;
25
+
26
+ /// Hand `event` to the owner's worker, waiting while its inbox is full; whether a worker will
27
+ /// take it. An abandoned slot drops it once it lands, which frees room for the next reader.
28
+ async fn emit(owner: &WorkerSlot, event: WsEvent) -> bool {
29
+ let Some(tx) = owner.lane.ws_tx.as_ref() else {
30
+ return false;
31
+ };
32
+ let sent = tx.send_async(event).await.is_ok();
33
+ landed(owner, sent)
34
+ }
35
+
36
+ /// emit, but never waiting: the event back when `owner`'s inbox is full,
37
+ /// else whether a worker will take it.
38
+ fn try_emit(owner: &WorkerSlot, event: WsEvent) -> Result<bool, WsEvent> {
39
+ let Some(tx) = owner.lane.ws_tx.as_ref() else {
40
+ return Ok(false);
41
+ };
42
+ match tx.try_send(event) {
43
+ Err(flume::TrySendError::Full(event)) => Err(event),
44
+ sent => Ok(landed(owner, sent.is_ok())),
45
+ }
46
+ }
47
+
48
+ /// After an event went to `owner`'s inbox, or failed to: ring the worker, or on an abandoned
49
+ /// slot drop what landed. Whether a worker will take it.
50
+ fn landed(owner: &WorkerSlot, sent: bool) -> bool {
51
+ if owner.sockets.abandoned() {
52
+ drain_inbox(owner);
53
+ return false;
54
+ }
55
+ if sent {
56
+ owner.notify();
57
+ }
58
+ sent
59
+ }
60
+
61
+ /// Drop the events waiting in `slot`'s inbox: their sockets get the
62
+ /// credit back, and the drain does not wait for their on_shutdown.
63
+ pub(super) fn drain_inbox(slot: &WorkerSlot) {
64
+ if let Some(rx) = slot.lane.ws_rx.as_ref() {
65
+ while let Ok(event) = rx.try_recv() {
66
+ match event {
67
+ WsEvent::Message { id, .. } => handled(id),
68
+ WsEvent::Shutdown { id } => shutdown_ran(id),
69
+ WsEvent::Drained { .. } | WsEvent::Close { .. } => {}
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ /// When a socket's client was last heard from: any bytes it sent, or a write that got through
76
+ /// after the connection made it wait (room only the client's reading frees). A reader waiting
77
+ /// on its worker reads nothing, but then the worker is behind, not the client. Also the last ping.
78
+ pub(super) struct Liveness {
79
+ start: tokio::time::Instant,
80
+ heard_us: AtomicU64,
81
+ waiting: AtomicBool,
82
+ /// When the last ping was written, plus one; 0: never.
83
+ ping_written_us: AtomicU64,
84
+ }
85
+
86
+ impl Liveness {
87
+ fn new() -> Self {
88
+ Liveness {
89
+ start: tokio::time::Instant::now(),
90
+ heard_us: AtomicU64::new(0),
91
+ waiting: AtomicBool::new(false),
92
+ ping_written_us: AtomicU64::new(0),
93
+ }
94
+ }
95
+
96
+ fn now_us(&self) -> u64 {
97
+ self.start.elapsed().as_micros() as u64
98
+ }
99
+
100
+ fn heard(&self) {
101
+ self.heard_us.store(self.now_us(), Ordering::SeqCst);
102
+ }
103
+
104
+ fn ping_written(&self) {
105
+ self.ping_written_us
106
+ .store(self.now_us() + 1, Ordering::SeqCst);
107
+ }
108
+
109
+ /// How long the socket has been open, when its client was last heard from (now, while the
110
+ /// reader waits on its worker), and when the last ping was written.
111
+ fn state(&self) -> (Duration, Duration, Option<Duration>) {
112
+ let now = self.start.elapsed();
113
+ let heard = if self.waiting.load(Ordering::SeqCst) {
114
+ now
115
+ } else {
116
+ Duration::from_micros(self.heard_us.load(Ordering::SeqCst))
117
+ };
118
+ let ping = match self.ping_written_us.load(Ordering::SeqCst) {
119
+ 0 => None,
120
+ written => Some(Duration::from_micros(written - 1)),
121
+ };
122
+ (now, heard, ping)
123
+ }
124
+
125
+ /// The reader waits on its worker for `wait`; the client's silence
126
+ /// counts again from its end.
127
+ pub(super) async fn on_worker<T>(&self, wait: impl Future<Output = T>) -> T {
128
+ self.waiting.store(true, Ordering::SeqCst);
129
+ let out = wait.await;
130
+ self.heard();
131
+ self.waiting.store(false, Ordering::SeqCst);
132
+ out
133
+ }
134
+ }
135
+
136
+ /// A socket's stream, telling its Liveness of a read that brings bytes, or a write that gets
137
+ /// through after the stream made it wait (the client read, freeing room).
138
+ struct Tap<S> {
139
+ io: S,
140
+ liveness: Arc<Liveness>,
141
+ waited: bool,
142
+ }
143
+
144
+ impl<S> Tap<S> {
145
+ fn read(&mut self, n: usize) {
146
+ if n > 0 {
147
+ self.liveness.heard();
148
+ COUNTS.add_n(WsCount::ReceivedBytes, n as u64);
149
+ }
150
+ }
151
+
152
+ /// A write or flush polled; `progress` says whether a done one moved
153
+ /// anything.
154
+ fn wrote<T>(
155
+ &mut self,
156
+ polled: Poll<io::Result<T>>,
157
+ progress: impl Fn(&T) -> bool,
158
+ ) -> Poll<io::Result<T>> {
159
+ match &polled {
160
+ Poll::Pending => self.waited = true,
161
+ Poll::Ready(Ok(done)) if self.waited && progress(done) => {
162
+ self.waited = false;
163
+ self.liveness.heard();
164
+ }
165
+ Poll::Ready(_) => {}
166
+ }
167
+ polled
168
+ }
169
+ }
170
+
171
+ impl<S: AsyncRead + Unpin> AsyncRead for Tap<S> {
172
+ fn poll_read(
173
+ self: Pin<&mut Self>,
174
+ cx: &mut Context<'_>,
175
+ buf: &mut ReadBuf<'_>,
176
+ ) -> Poll<io::Result<()>> {
177
+ let this = self.get_mut();
178
+ let before = buf.filled().len();
179
+ let polled = Pin::new(&mut this.io).poll_read(cx, buf);
180
+ this.read(buf.filled().len() - before);
181
+ polled
182
+ }
183
+ }
184
+
185
+ impl<S: AsyncWrite + Unpin> AsyncWrite for Tap<S> {
186
+ fn poll_write(
187
+ self: Pin<&mut Self>,
188
+ cx: &mut Context<'_>,
189
+ buf: &[u8],
190
+ ) -> Poll<io::Result<usize>> {
191
+ let this = self.get_mut();
192
+ let polled = Pin::new(&mut this.io).poll_write(cx, buf);
193
+ this.wrote(polled, |written| *written > 0)
194
+ }
195
+
196
+ fn poll_write_vectored(
197
+ self: Pin<&mut Self>,
198
+ cx: &mut Context<'_>,
199
+ bufs: &[io::IoSlice<'_>],
200
+ ) -> Poll<io::Result<usize>> {
201
+ let this = self.get_mut();
202
+ let polled = Pin::new(&mut this.io).poll_write_vectored(cx, bufs);
203
+ this.wrote(polled, |written| *written > 0)
204
+ }
205
+
206
+ fn is_write_vectored(&self) -> bool {
207
+ self.io.is_write_vectored()
208
+ }
209
+
210
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
211
+ let this = self.get_mut();
212
+ let polled = Pin::new(&mut this.io).poll_flush(cx);
213
+ this.wrote(polled, |_| true)
214
+ }
215
+
216
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
217
+ Pin::new(&mut self.get_mut().io).poll_shutdown(cx)
218
+ }
219
+ }
220
+
221
+ /// Pings a client silent for `interval`, once per silence, and resolves
222
+ /// once it has been silent for two, and for one since the ping was
223
+ /// written: a dead peer. Zero: never.
224
+ async fn keepalive(liveness: &Liveness, interval: Duration, abort: &Abort, out: mpsc::Sender<Out>) {
225
+ if interval.is_zero() {
226
+ return std::future::pending().await;
227
+ }
228
+ // When the client was last heard from as of the last ping.
229
+ let mut pinged = None;
230
+ loop {
231
+ let (now, heard, ping_written) = liveness.state();
232
+ let silence = now.saturating_sub(heard);
233
+ if silence < interval {
234
+ tokio::time::sleep(interval - silence).await;
235
+ continue;
236
+ }
237
+ let mut deadline = heard + interval * 2;
238
+ if let Some(written) = ping_written.filter(|written| *written >= heard) {
239
+ deadline = deadline.max(written + interval);
240
+ }
241
+ if now >= deadline {
242
+ return;
243
+ }
244
+ let mut check_in = deadline - now;
245
+ // Nothing may follow a close frame; a full queue takes the ping a
246
+ // little later.
247
+ if pinged != Some(heard) && !abort.closing.load(Ordering::SeqCst) {
248
+ if out.try_send(Out::Ping(encode(Opcode::Ping, b""))).is_ok() {
249
+ pinged = Some(heard);
250
+ } else {
251
+ check_in = check_in.min(interval / 8);
252
+ }
253
+ }
254
+ tokio::time::sleep(check_in).await;
255
+ }
256
+ }
257
+
258
+ /// The drain's goodbye (leave_all): once told to leave, the worker runs its on_shutdown, if
259
+ /// any, and the 1001 follows that and the socket's turn in the spread. Resolves only when the
260
+ /// 1001 cannot queue (a full queue): the socket is dropped instead.
261
+ async fn going_away(id: u64, owner: &WorkerSlot, abort: &Abort, out: mpsc::Sender<Out>) {
262
+ abort.leave.notified().await;
263
+ let turn = Duration::from_micros(abort.leave_after_us.load(Ordering::SeqCst));
264
+ let goodbye = async {
265
+ if abort.on_shutdown.load(Ordering::SeqCst) && emit(owner, WsEvent::Shutdown { id }).await {
266
+ abort.goodbye.notified().await;
267
+ }
268
+ };
269
+ tokio::join!(tokio::time::sleep(turn), goodbye);
270
+ if abort.close(&out, GOING_AWAY, Cause::GoingAway) {
271
+ std::future::pending::<()>().await;
272
+ }
273
+ }
274
+
275
+ /// The connection task once the app accepted (upgrade::settle): waits for
276
+ /// hyper to hand over the upgraded connection, then frames it.
277
+ pub(crate) async fn drive(on_upgrade: hyper::upgrade::OnUpgrade, accepted: Accepted) {
278
+ let Accepted {
279
+ registration,
280
+ out_rx,
281
+ reply,
282
+ switched,
283
+ } = accepted;
284
+ let (id, owner) = (registration.id, &registration.owner);
285
+ let (limits, abort) = (registration.limits.clone(), registration.abort.clone());
286
+ let mut flushing = None;
287
+ // Only a 101 hands the connection over: after any other answer hyper
288
+ // keeps the upgrade pending until the client hangs up.
289
+ let upgraded = match switched.await {
290
+ Ok(()) => {
291
+ abort.switched.store(true, Ordering::SeqCst);
292
+ let upgraded = on_upgrade.await.ok();
293
+ if upgraded.is_none() {
294
+ abort.end_as(Cause::ClientGone);
295
+ }
296
+ upgraded
297
+ }
298
+ Err(_) => {
299
+ drop(on_upgrade);
300
+ // Whatever ended it first, the client never got the socket.
301
+ abort
302
+ .cause
303
+ .store(Cause::HandshakeFailed as u8, Ordering::SeqCst);
304
+ None
305
+ }
306
+ };
307
+ if let Some(upgraded) = upgraded {
308
+ let liveness = Arc::new(Liveness::new());
309
+ let (rd, wr) = tokio::io::split(Tap {
310
+ io: TokioIo::new(upgraded),
311
+ liveness: liveness.clone(),
312
+ waited: false,
313
+ });
314
+ let socket = Socket {
315
+ id,
316
+ owner: owner.clone(),
317
+ abort: abort.clone(),
318
+ liveness: liveness.clone(),
319
+ };
320
+ let writer = tokio::spawn(write_loop(wr, out_rx, socket));
321
+ let messages = Reader::new(rd, limits.max_message);
322
+ let (pinger, leaver) = (reply.clone(), reply.clone());
323
+ // An abort wins even over a reader parked on a full inbox or out of credit; what the
324
+ // client already sent (a pong) is read before its silence is judged. The arms' senders
325
+ // go with them, so the writer ends once unregister drops the socket's own. An abort or
326
+ // a close recorded its cause when asked for.
327
+ let (aborted, cause) = tokio::select! {
328
+ biased;
329
+ _ = abort.notify.notified() => (true, None),
330
+ _ = abort.close_expired() => (true, None),
331
+ cause = read_loop(messages, id, owner, reply, &abort, &liveness) => (false, Some(cause)),
332
+ () = keepalive(&liveness, limits.ping_interval, &abort, pinger) => (true, Some(Cause::DeadPeer)),
333
+ () = going_away(id, owner, &abort, leaver) => (true, Some(Cause::GoingAway)),
334
+ };
335
+ if let Some(cause) = cause {
336
+ abort.end_as(cause);
337
+ }
338
+ if aborted {
339
+ // The writer may be stuck on a client that stopped reading.
340
+ writer.abort();
341
+ } else {
342
+ // It flushes what is queued (a close echo included) and ends
343
+ // once unregister drops the last senders.
344
+ flushing = Some(writer);
345
+ }
346
+ }
347
+ registration.unregister();
348
+ emit(owner, WsEvent::Close { id }).await;
349
+ registration.uncount();
350
+ if let Some(mut writer) = flushing {
351
+ // A client that stopped reading would keep it waiting forever.
352
+ if tokio::time::timeout(CLOSE_TIMEOUT, &mut writer)
353
+ .await
354
+ .is_err()
355
+ {
356
+ writer.abort();
357
+ }
358
+ }
359
+ }
360
+
361
+ /// Frames a socket's writer gathers into one vectored write.
362
+ const WRITE_BATCH: usize = 64;
363
+
364
+ /// What a socket's writer needs besides its queue.
365
+ struct Socket {
366
+ id: u64,
367
+ owner: Arc<WorkerSlot>,
368
+ abort: Arc<Abort>,
369
+ liveness: Arc<Liveness>,
370
+ }
371
+
372
+ /// Drains a socket's queue: what is queued goes out together, in vectored writes straight from
373
+ /// the frames, so a socket holds no write buffer. Data frames leave the budgets once written;
374
+ /// when that empties a queue that refused something, the worker hears, without the writer waiting.
375
+ async fn write_loop<W: AsyncWrite + Unpin>(mut wr: W, mut rx: mpsc::Receiver<Out>, socket: Socket) {
376
+ let Socket {
377
+ id,
378
+ owner,
379
+ abort: budget,
380
+ liveness,
381
+ } = socket;
382
+ while let Some(first) = rx.recv().await {
383
+ let mut frames = Vec::new();
384
+ let (mut charged, mut data) = (0, 0);
385
+ let mut ping = false;
386
+ let mut close = None;
387
+ let mut next = Some(first);
388
+ while let Some(out) = next.take() {
389
+ match out {
390
+ // An empty write would read as a closed stream.
391
+ Out::Frame(bytes) if bytes.is_empty() => data += 1,
392
+ Out::Control(bytes) if bytes.is_empty() => {}
393
+ Out::Frame(bytes) => {
394
+ charged += bytes.len();
395
+ data += 1;
396
+ frames.push(bytes);
397
+ }
398
+ Out::Control(bytes) => frames.push(bytes),
399
+ Out::Ping(bytes) => {
400
+ ping = true;
401
+ frames.push(bytes);
402
+ }
403
+ Out::Close(bytes) => {
404
+ close = Some(bytes);
405
+ break;
406
+ }
407
+ }
408
+ if frames.len() < WRITE_BATCH {
409
+ next = rx.try_recv().ok();
410
+ }
411
+ }
412
+ let bytes: usize = frames.iter().map(Bytes::len).sum();
413
+ if write_frames(&mut wr, frames).await.is_err() {
414
+ return;
415
+ }
416
+ budget.queued_bytes.fetch_sub(charged, Ordering::SeqCst);
417
+ budget.queued_frames.fetch_sub(data, Ordering::SeqCst);
418
+ COUNTS.add_n(WsCount::MessagesSent, data as u64);
419
+ COUNTS.add_n(WsCount::SentBytes, bytes as u64);
420
+ if ping {
421
+ liveness.ping_written();
422
+ }
423
+ if let Some(bytes) = close {
424
+ if wr.write_all(&bytes).await.is_ok() {
425
+ COUNTS.add_n(WsCount::SentBytes, bytes.len() as u64);
426
+ }
427
+ let _ = wr.flush().await;
428
+ let _ = wr.shutdown().await;
429
+ return;
430
+ }
431
+ if wr.flush().await.is_err() {
432
+ return;
433
+ }
434
+ // A socket on its way out has nothing left to resume.
435
+ if !budget.closing.load(Ordering::SeqCst) && budget.drained() {
436
+ hand_off(&owner, WsEvent::Drained { id });
437
+ }
438
+ }
439
+ let _ = wr.shutdown().await;
440
+ }
441
+
442
+ /// emit for a task that must not wait on the worker: a full inbox gets
443
+ /// the event from a task of its own.
444
+ fn hand_off(owner: &Arc<WorkerSlot>, event: WsEvent) {
445
+ if let Err(event) = try_emit(owner, event) {
446
+ let owner = owner.clone();
447
+ tokio::spawn(async move { emit(&owner, event).await });
448
+ }
449
+ }
450
+
451
+ /// Write `frames` whole and in order, as few writes as the stream takes.
452
+ async fn write_frames<W: AsyncWrite + Unpin>(wr: &mut W, mut frames: Vec<Bytes>) -> io::Result<()> {
453
+ let mut first = 0;
454
+ while first < frames.len() {
455
+ let slices: Vec<_> = frames[first..]
456
+ .iter()
457
+ .map(|frame| io::IoSlice::new(frame))
458
+ .collect();
459
+ let mut written = wr.write_vectored(&slices).await?;
460
+ drop(slices);
461
+ if written == 0 {
462
+ return Err(io::ErrorKind::WriteZero.into());
463
+ }
464
+ while written > 0 {
465
+ let frame = &mut frames[first];
466
+ if written < frame.len() {
467
+ bytes::Buf::advance(frame, written);
468
+ break;
469
+ }
470
+ written -= frame.len();
471
+ first += 1;
472
+ }
473
+ }
474
+ Ok(())
475
+ }
476
+
477
+ /// Reads a socket's messages into its worker's inbox, each once it has
478
+ /// the credit for it: with `Limits::inbound` unhandled, nothing more
479
+ /// is read, and TCP pushes back on the client. Returns why reading
480
+ /// ended.
481
+ async fn read_loop<R: AsyncRead + Unpin>(
482
+ mut messages: Reader<R>,
483
+ id: u64,
484
+ owner: &WorkerSlot,
485
+ reply: mpsc::Sender<Out>,
486
+ credit: &Abort,
487
+ liveness: &Liveness,
488
+ ) -> Cause {
489
+ loop {
490
+ credit.take_credit(owner, liveness).await;
491
+ let (data, text) = loop {
492
+ match messages.next().await {
493
+ Ok(Message::Text(data)) => break (data.into(), true),
494
+ Ok(Message::Binary(data)) => break (data, false),
495
+ Ok(Message::Ping(payload)) => {
496
+ let _ = reply.try_send(Out::Control(encode(Opcode::Pong, &payload)));
497
+ }
498
+ Ok(_) => {}
499
+ Err(ended) => {
500
+ if let Some(code) = ended.code {
501
+ let _ = reply.try_send(Out::Close(close_frame(code)));
502
+ }
503
+ return ended.cause;
504
+ }
505
+ }
506
+ };
507
+ COUNTS.add(WsCount::MessagesReceived);
508
+ let message = WsEvent::Message { id, data, text };
509
+ if let Err(message) = try_emit(owner, message) {
510
+ liveness.on_worker(emit(owner, message)).await;
511
+ }
512
+ }
513
+ }
514
+
515
+ #[cfg(test)]
516
+ mod tests {
517
+ use tokio::io::AsyncReadExt;
518
+
519
+ use super::*;
520
+ use crate::ws::QUEUE_FRAMES;
521
+
522
+ #[tokio::test]
523
+ async fn queued_frames_reach_a_slow_client_whole_and_in_order() {
524
+ // Its writes count in the process-wide counters socket tests read.
525
+ let _serial = crate::testing::SERIAL.lock().await;
526
+ let (client, conn) = tokio::io::duplex(1000);
527
+ let (tx, rx) = mpsc::channel(QUEUE_FRAMES);
528
+ let budget = Arc::new(Abort::default());
529
+ let socket = Socket {
530
+ id: 1,
531
+ owner: Arc::new(WorkerSlot::new(true, 1, None, false)),
532
+ abort: budget.clone(),
533
+ liveness: Arc::new(Liveness::new()),
534
+ };
535
+ let writer = tokio::spawn(write_loop(conn, rx, socket));
536
+ let small = |n: usize| encode(Opcode::Text, n.to_string().as_bytes());
537
+ let mut frames: Vec<Bytes> = (0..50).map(small).collect();
538
+ frames.push(encode(Opcode::Binary, &vec![7; 300_000]));
539
+ frames.extend((50..100).map(small));
540
+ let reading = tokio::spawn(async move {
541
+ let mut received = Vec::new();
542
+ let mut client = client;
543
+ client.read_to_end(&mut received).await.map(|_| received)
544
+ });
545
+
546
+ for frame in &frames {
547
+ budget.queued_bytes.fetch_add(frame.len(), Ordering::SeqCst);
548
+ budget.queued_frames.fetch_add(1, Ordering::SeqCst);
549
+ tx.send(Out::Frame(frame.clone()))
550
+ .await
551
+ .expect("the writer stopped taking frames");
552
+ }
553
+ drop(tx);
554
+ writer.await.expect("writer");
555
+ assert_eq!(
556
+ budget.queued_bytes.load(Ordering::SeqCst),
557
+ 0,
558
+ "written frames must leave the byte budget"
559
+ );
560
+ assert_eq!(budget.pending(), 0, "written frames are no longer pending");
561
+
562
+ let received = reading.await.expect("join").expect("client read");
563
+ assert!(
564
+ received == frames.concat(),
565
+ "the client got {} bytes, {} were queued, or they came out of order",
566
+ received.len(),
567
+ frames.concat().len()
568
+ );
569
+ }
570
+
571
+ #[tokio::test(start_paused = true)]
572
+ async fn a_client_has_an_interval_to_answer_from_when_its_ping_went_out_and_none_with_pings_off(
573
+ ) {
574
+ let interval = Duration::from_secs(2);
575
+ let (liveness, abort) = (Liveness::new(), Abort::default());
576
+ let (tx, mut queued) = mpsc::channel(4);
577
+ let dead = keepalive(&liveness, interval, &abort, tx);
578
+ tokio::pin!(dead);
579
+ // Silent since it opened: a ping is queued after an interval, and
580
+ // the writer gets it out only at 3.5 s, behind other frames.
581
+ let early = tokio::time::timeout(Duration::from_millis(3500), &mut dead);
582
+ assert!(early.await.is_err());
583
+ assert!(matches!(queued.try_recv(), Ok(Out::Ping(_))));
584
+ liveness.ping_written();
585
+
586
+ let late = tokio::time::timeout(Duration::from_millis(1999), &mut dead);
587
+ assert!(
588
+ late.await.is_err(),
589
+ "two intervals of silence, but not one since the ping went out"
590
+ );
591
+ let due = tokio::time::timeout(Duration::from_millis(2), &mut dead);
592
+ assert!(due.await.is_ok());
593
+
594
+ // Zero: no pings, and no client is ever dropped for its silence.
595
+ let (tx, mut queued) = mpsc::channel(4);
596
+ let off = keepalive(&liveness, Duration::ZERO, &abort, tx);
597
+ assert!(tokio::time::timeout(interval * 100, off).await.is_err());
598
+ assert!(queued.try_recv().is_err(), "no ping");
599
+ }
600
+ }