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,279 @@
1
+ //! A socket as its writers see it: the outgoing queue and its budgets, inbound credit, and closing.
2
+
3
+ use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU64, AtomicU8, AtomicUsize, Ordering};
4
+ use std::sync::Arc;
5
+
6
+ use bytes::Bytes;
7
+ use tokio::sync::{mpsc, Notify};
8
+
9
+ use super::codec::close_frame;
10
+ use super::drive::Liveness;
11
+ use super::stats::{Cause, WsCount, COUNTS};
12
+ use super::CLOSE_TIMEOUT;
13
+ use crate::slot::WorkerSlot;
14
+
15
+ /// Move `counter` to what `next` makes of it: Ok with the old value, Err with the refused
16
+ /// one. Not std's fetch_update: it is deprecated, and its successor needs Rust 1.95.
17
+ pub(super) fn update(
18
+ counter: &AtomicUsize,
19
+ next: impl Fn(usize) -> Option<usize>,
20
+ ) -> Result<usize, usize> {
21
+ let mut seen = counter.load(Ordering::SeqCst);
22
+ loop {
23
+ let to = next(seen).ok_or(seen)?;
24
+ match counter.compare_exchange_weak(seen, to, Ordering::SeqCst, Ordering::SeqCst) {
25
+ Ok(_) => return Ok(seen),
26
+ Err(now) => seen = now,
27
+ }
28
+ }
29
+ }
30
+
31
+ /// Add `len` to `queued` unless that passes `cap`; anything fits when nothing is queued.
32
+ pub(super) fn charge(queued: &AtomicUsize, cap: usize, len: usize) -> bool {
33
+ update(queued, |held| {
34
+ (held == 0 || held.saturating_add(len) <= cap).then_some(held + len)
35
+ })
36
+ .is_ok()
37
+ }
38
+
39
+ pub(super) enum Out {
40
+ /// Counted against the byte budget until written.
41
+ Frame(Bytes),
42
+ /// Kino's own (a pong), outside the byte budget.
43
+ Control(Bytes),
44
+ /// Kino's ping: the client's time to answer starts once it is written.
45
+ Ping(Bytes),
46
+ Close(Bytes),
47
+ }
48
+
49
+ #[derive(Clone)]
50
+ pub struct Conn {
51
+ pub(super) tx: mpsc::Sender<Out>,
52
+ pub(super) abort: Arc<Abort>,
53
+ pub(super) owner: Arc<WorkerSlot>,
54
+ }
55
+
56
+ /// What a socket's writers share with its connection task.
57
+ #[derive(Default)]
58
+ pub(super) struct Abort {
59
+ /// Drops the connection even when its queue is full (a slow client).
60
+ pub(super) notify: Notify,
61
+ /// Set at unregister, before its subscriptions go; see Conn::subscribing.
62
+ pub(super) gone: AtomicBool,
63
+ pub(super) subscribed: AtomicBool,
64
+ /// Set by the first close queued; `close_queued` starts the client's CLOSE_TIMEOUT.
65
+ pub(super) closing: AtomicBool,
66
+ pub(super) close_queued: Notify,
67
+ pub(super) queued_bytes: AtomicUsize,
68
+ pub(super) queue_bytes: usize,
69
+ /// Data frames not yet written, with REFUSED set by a refused write: whoever sees the
70
+ /// count reach zero with it set clears it and tells the worker.
71
+ pub(super) queued_frames: AtomicUsize,
72
+ /// Messages with the worker, counting one being read; `credit` wakes a reader waiting for room.
73
+ pub(super) unhandled: AtomicUsize,
74
+ pub(super) inbound: usize,
75
+ pub(super) credit: Notify,
76
+ /// The drain's goodbye: `leave` after `leave_after_us`, after on_shutdown (`goodbye`) if any.
77
+ pub(super) leave: Notify,
78
+ pub(super) leave_after_us: AtomicU64,
79
+ pub(super) on_shutdown: AtomicBool,
80
+ pub(super) goodbye: Notify,
81
+ pub(super) cause: AtomicU8,
82
+ pub(super) switched: AtomicBool,
83
+ }
84
+
85
+ pub(super) const REFUSED: usize = 1 << (usize::BITS - 1);
86
+
87
+ impl Abort {
88
+ pub(super) fn end_as(&self, cause: Cause) {
89
+ let _ = self
90
+ .cause
91
+ .compare_exchange(0, cause as u8, Ordering::SeqCst, Ordering::SeqCst);
92
+ }
93
+
94
+ pub(super) fn cause(&self) -> Option<Cause> {
95
+ Cause::of(self.cause.load(Ordering::SeqCst))
96
+ }
97
+
98
+ pub(super) async fn close_expired(&self) {
99
+ self.close_queued.notified().await;
100
+ tokio::time::sleep(CLOSE_TIMEOUT).await;
101
+ }
102
+
103
+ /// Waits while `inbound` are unhandled; a slot whose events are dropped has room.
104
+ pub(super) async fn take_credit(&self, owner: &WorkerSlot, liveness: &Liveness) {
105
+ let mut paused = false;
106
+ loop {
107
+ let taken = update(&self.unhandled, |unhandled| {
108
+ (unhandled < self.inbound).then_some(unhandled + 1)
109
+ })
110
+ .is_ok();
111
+ if taken || owner.sockets.abandoned() {
112
+ return;
113
+ }
114
+ if !paused {
115
+ paused = true;
116
+ COUNTS.add(WsCount::InboundPauses);
117
+ }
118
+ liveness.on_worker(self.credit.notified()).await;
119
+ }
120
+ }
121
+
122
+ pub(super) fn return_credit(&self) {
123
+ let returned = update(&self.unhandled, |unhandled| unhandled.checked_sub(1));
124
+ if returned.is_ok_and(|before| before >= self.inbound) {
125
+ self.credit.notify_one();
126
+ }
127
+ }
128
+
129
+ pub(super) fn pending(&self) -> usize {
130
+ self.queued_frames.load(Ordering::SeqCst) & !REFUSED
131
+ }
132
+
133
+ /// The queue emptied since a refused write; true once, for the caller that tells the worker.
134
+ pub(super) fn drained(&self) -> bool {
135
+ self.queued_frames.load(Ordering::SeqCst) == REFUSED
136
+ && self
137
+ .queued_frames
138
+ .compare_exchange(REFUSED, 0, Ordering::SeqCst, Ordering::SeqCst)
139
+ .is_ok()
140
+ }
141
+
142
+ /// After what is queued, ending for `cause`; the first close stands. False on a full queue.
143
+ pub(super) fn close(&self, tx: &mpsc::Sender<Out>, code: u16, cause: Cause) -> bool {
144
+ if self.closing.swap(true, Ordering::SeqCst) {
145
+ return true;
146
+ }
147
+ if tx.try_send(Out::Close(close_frame(code))).is_err() {
148
+ self.closing.store(false, Ordering::SeqCst);
149
+ return false;
150
+ }
151
+ self.end_as(cause);
152
+ self.close_queued.notify_one();
153
+ true
154
+ }
155
+
156
+ pub(super) fn drop_as(&self, cause: Cause) {
157
+ self.end_as(cause);
158
+ self.notify.notify_one();
159
+ }
160
+ }
161
+
162
+ #[derive(Default)]
163
+ pub struct SlotSockets {
164
+ /// Not closed yet as the worker knows: their close event has not reached its inbox.
165
+ pub(super) open: AtomicUsize,
166
+ /// The code its sockets were closed with (0: none); handshakes are refused from then.
167
+ pub(super) close_code: AtomicU16,
168
+ /// No worker takes the slot's events (it crashed, or is wedged): they are dropped.
169
+ pub(super) abandoned: AtomicBool,
170
+ }
171
+
172
+ impl SlotSockets {
173
+ pub fn open(&self) -> usize {
174
+ self.open.load(Ordering::SeqCst)
175
+ }
176
+
177
+ pub fn accepting(&self) -> bool {
178
+ self.close_code.load(Ordering::Relaxed) == 0 && !self.abandoned()
179
+ }
180
+
181
+ pub fn reset(&self) {
182
+ self.close_code.store(0, Ordering::SeqCst);
183
+ self.abandoned.store(false, Ordering::SeqCst);
184
+ }
185
+
186
+ pub(super) fn abandoned(&self) -> bool {
187
+ self.abandoned.load(Ordering::SeqCst)
188
+ }
189
+ }
190
+
191
+ impl Conn {
192
+ /// Mark the socket as subscribing, under the topic lock; false if it was unregistered
193
+ /// meanwhile. unregister marks it gone, then forgets subscriptions only if it sees this
194
+ /// mark: one sees the other's, so either the subscribe gives up or the forget waits for it.
195
+ pub(super) fn subscribing(&self) -> bool {
196
+ self.abort.subscribed.store(true, Ordering::SeqCst);
197
+ !self.abort.gone.load(Ordering::SeqCst)
198
+ }
199
+
200
+ /// Without waiting: full at `Limits::queue` frames or past `Limits::queue_bytes`.
201
+ fn push(&self, frame: Bytes) -> Push {
202
+ let len = frame.len();
203
+ if !charge(&self.abort.queued_bytes, self.abort.queue_bytes, len) {
204
+ // A writer that ended leaves the bytes of what it never wrote.
205
+ return if self.tx.is_closed() {
206
+ Push::Gone
207
+ } else {
208
+ Push::Full
209
+ };
210
+ }
211
+ // Counted first: the writer may write it before try_send returns.
212
+ self.abort.queued_frames.fetch_add(1, Ordering::SeqCst);
213
+ match self.tx.try_send(Out::Frame(frame)) {
214
+ Ok(()) => Push::Queued,
215
+ Err(refused) => {
216
+ self.abort.queued_bytes.fetch_sub(len, Ordering::SeqCst);
217
+ self.abort.queued_frames.fetch_sub(1, Ordering::SeqCst);
218
+ match refused {
219
+ mpsc::error::TrySendError::Full(_) => Push::Full,
220
+ mpsc::error::TrySendError::Closed(_) => Push::Gone,
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ /// A publish; false only when the queue is full (a client too slow to keep up).
227
+ pub(super) fn offer(&self, frame: Bytes) -> bool {
228
+ !matches!(self.push(frame), Push::Full)
229
+ }
230
+
231
+ pub(super) fn drop_slow(&self) {
232
+ self.abort.drop_as(Cause::Slow);
233
+ }
234
+
235
+ /// An app write; a refusal by the full queue is marked, so on_drained follows.
236
+ pub(super) fn write(&self, frame: Bytes) -> bool {
237
+ match self.push(frame) {
238
+ Push::Queued => true,
239
+ Push::Full => {
240
+ self.refused_write();
241
+ false
242
+ }
243
+ Push::Gone => false,
244
+ }
245
+ }
246
+
247
+ /// The app's close; a full queue refuses it as it does a write.
248
+ pub(super) fn close(&self, code: u16) -> bool {
249
+ let queued = self.abort.close(&self.tx, code, Cause::Normal);
250
+ if !queued && !self.tx.is_closed() {
251
+ self.refused_write();
252
+ }
253
+ queued
254
+ }
255
+
256
+ pub(super) fn owned_by(&self, slot: &WorkerSlot) -> bool {
257
+ std::ptr::eq(&*self.owner, slot)
258
+ }
259
+
260
+ fn refused_write(&self) {
261
+ self.refused();
262
+ COUNTS.add(WsCount::WritesRefused);
263
+ }
264
+
265
+ /// The worker hears once the queue empties; one that emptied meanwhile is sent an
266
+ /// empty frame, so its writer sees the mark.
267
+ pub(super) fn refused(&self) {
268
+ let before = self.abort.queued_frames.fetch_or(REFUSED, Ordering::SeqCst);
269
+ if before & !REFUSED == 0 {
270
+ let _ = self.tx.try_send(Out::Control(Bytes::new()));
271
+ }
272
+ }
273
+ }
274
+
275
+ enum Push {
276
+ Queued,
277
+ Full,
278
+ Gone,
279
+ }
@@ -0,0 +1,88 @@
1
+ //! The process's WebSocket counters: closes by cause, refused handshakes, and what moved.
2
+
3
+ use std::sync::atomic::{AtomicU64, Ordering};
4
+
5
+ use crate::counters::{tallied, Tallied, Tally};
6
+
7
+ tallied! {
8
+ /// Why a socket ended; the first cause recorded stands. From 1: Abort::cause holds 0 for none.
9
+ pub enum Cause {
10
+ /// A close frame from either side, or the app's abort.
11
+ Normal = 1 => "normal",
12
+ /// Kino's 1001: the server drained, or the worker retired.
13
+ GoingAway => "going_away",
14
+ Protocol => "protocol",
15
+ TooBig => "too_big",
16
+ Slow => "slow",
17
+ DeadPeer => "dead_peer",
18
+ ClientGone => "client_gone",
19
+ /// Kino's 1011 (its worker crashed or was given up on), or a callback raised.
20
+ Crash => "crash",
21
+ /// The 101 never went out: the client never got the socket.
22
+ HandshakeFailed => "handshake_failed",
23
+ }
24
+ }
25
+
26
+ impl Cause {
27
+ pub(super) fn of(code: u8) -> Option<Cause> {
28
+ Cause::ALL.get(usize::from(code).checked_sub(1)?).copied()
29
+ }
30
+ }
31
+
32
+ tallied! {
33
+ /// Why Kino answered a handshake the app accepted with a 503.
34
+ pub enum Refusal {
35
+ WebsocketMax => "websocket_max",
36
+ Draining => "draining",
37
+ WorkerClosing => "worker_closing",
38
+ }
39
+ }
40
+
41
+ tallied! {
42
+ /// What moved on the process's sockets, in the order /stats lists it.
43
+ pub enum WsCount {
44
+ Opened => "opened",
45
+ MessagesReceived => "messages_received",
46
+ /// Data frames written, one per write_raw however many frames it held.
47
+ MessagesSent => "messages_sent",
48
+ /// One per subscriber per publish left out; one dropped instead counts as closed slow.
49
+ MessagesSkipped => "messages_skipped",
50
+ WritesRefused => "writes_refused",
51
+ PublishesRefused => "publishes_refused",
52
+ InboundPauses => "inbound_pauses",
53
+ /// Frame headers and control frames included.
54
+ ReceivedBytes => "received_bytes",
55
+ SentBytes => "sent_bytes",
56
+ }
57
+ }
58
+
59
+ // Process-wide, Relaxed and advisory, read through `snapshot`.
60
+ pub(super) static OPEN: AtomicU64 = AtomicU64::new(0);
61
+ pub(super) static COUNTS: Tally<WsCount, { WsCount::ALL.len() }> = Tally::new();
62
+ pub(super) static CLOSED: Tally<Cause, { Cause::ALL.len() }> = Tally::new();
63
+ pub(super) static HANDSHAKES_REFUSED: Tally<Refusal, { Refusal::ALL.len() }> = Tally::new();
64
+
65
+ /// Every socket opened is open, or closed once under its cause.
66
+ #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
67
+ pub struct WsSnapshot {
68
+ pub open: u64,
69
+ /// Indexed as WsCount::ALL.
70
+ pub counts: [u64; WsCount::ALL.len()],
71
+ pub closed: [u64; Cause::ALL.len()],
72
+ pub handshakes_refused: [u64; Refusal::ALL.len()],
73
+ }
74
+
75
+ impl WsSnapshot {
76
+ pub fn count(&self, count: WsCount) -> u64 {
77
+ self.counts[count.index()]
78
+ }
79
+ }
80
+
81
+ pub fn snapshot() -> WsSnapshot {
82
+ WsSnapshot {
83
+ open: OPEN.load(Ordering::Acquire),
84
+ counts: COUNTS.read(),
85
+ closed: CLOSED.read(),
86
+ handshakes_refused: HANDSHAKES_REFUSED.read(),
87
+ }
88
+ }
@@ -0,0 +1,156 @@
1
+ //! What the WebSocket tests share: client frames and handshakes, counts of
2
+ //! closes and refusals, and sockets with no connection behind them.
3
+
4
+ use std::future::Future;
5
+ use std::task::{Context, Waker};
6
+
7
+ use tokio::sync::mpsc::{self, error::TryRecvError};
8
+
9
+ use super::handshake::{register, Registration};
10
+ use super::socket::{Abort, Out};
11
+ use super::topics::{subscribe_with, Wait, WhenFull};
12
+ use super::*;
13
+ use crate::counters::Tallied;
14
+
15
+ pub use super::codec::encode;
16
+
17
+ /// A masked client frame (RFC 6455 5.3), the only kind a client may
18
+ /// send: `first` is the FIN bit and opcode.
19
+ pub fn client_frame(first: u8, payload: &[u8]) -> Vec<u8> {
20
+ const MASK: [u8; 4] = [0x37, 0xfa, 0x21, 0x3d];
21
+ let mut out = vec![first];
22
+ match payload.len() {
23
+ n if n < 126 => out.push(0x80 | n as u8),
24
+ n if n < 65_536 => {
25
+ out.push(0x80 | 126);
26
+ out.extend_from_slice(&(n as u16).to_be_bytes());
27
+ }
28
+ n => {
29
+ out.push(0x80 | 127);
30
+ out.extend_from_slice(&(n as u64).to_be_bytes());
31
+ }
32
+ }
33
+ out.extend_from_slice(&MASK);
34
+ out.extend(payload.iter().enumerate().map(|(i, b)| b ^ MASK[i & 3]));
35
+ out
36
+ }
37
+
38
+ /// A client's opening handshake (RFC 6455 4.1) with the RFC's sample
39
+ /// key.
40
+ pub fn handshake() -> http::request::Builder {
41
+ hyper::Request::get("/ws")
42
+ .header(http::header::HOST, "kino.test")
43
+ .header(http::header::UPGRADE, "websocket")
44
+ .header(http::header::CONNECTION, "Upgrade")
45
+ .header(http::header::SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==")
46
+ .header(http::header::SEC_WEBSOCKET_VERSION, "13")
47
+ }
48
+
49
+ /// Sockets closed since `before`, by cause.
50
+ pub fn closes_since(before: &WsSnapshot) -> Vec<(&'static str, u64)> {
51
+ moved(Cause::named(snapshot().closed), Cause::named(before.closed))
52
+ }
53
+
54
+ /// Handshakes refused since `before`, by cause.
55
+ pub fn refusals_since(before: &WsSnapshot) -> Vec<(&'static str, u64)> {
56
+ let refused = |snapshot: &WsSnapshot| Refusal::named(snapshot.handshakes_refused);
57
+ moved(refused(&snapshot()), refused(before))
58
+ }
59
+
60
+ fn moved<const N: usize>(
61
+ now: [(&'static str, u64); N],
62
+ then: [(&'static str, u64); N],
63
+ ) -> Vec<(&'static str, u64)> {
64
+ let since = now.into_iter().zip(then);
65
+ let since = since.map(|((cause, now), (_, then))| (cause, now - then));
66
+ since.filter(|(_, count)| *count > 0).collect()
67
+ }
68
+
69
+ /// A registered socket with no connection behind it: the test reads
70
+ /// its queue of outgoing frames, as its writer would. Dropping it
71
+ /// ends the socket.
72
+ pub struct QueuedSocket {
73
+ pub id: u64,
74
+ out: mpsc::Receiver<Out>,
75
+ abort: Arc<Abort>,
76
+ registration: Registration,
77
+ }
78
+
79
+ impl QueuedSocket {
80
+ /// A socket whose queue holds `queue` frames.
81
+ pub fn new(queue: usize) -> Self {
82
+ let limits = Limits {
83
+ queue,
84
+ ..Limits::default()
85
+ };
86
+ Self::with_limits(Arc::new(WorkerSlot::new(true, 1, None, false)), limits)
87
+ }
88
+
89
+ /// A socket the worker on `owner` accepted, with these budgets.
90
+ pub fn with_limits(owner: Arc<WorkerSlot>, limits: Limits) -> Self {
91
+ // Its `reply` sender goes: nothing reads from this socket.
92
+ let (_, switched) = tokio::sync::oneshot::channel();
93
+ let (id, mut accepted) =
94
+ register(owner, &Arc::new(limits), switched).expect("no websocket_max");
95
+ accepted.registration.open();
96
+ QueuedSocket {
97
+ id,
98
+ out: accepted.out_rx,
99
+ abort: accepted.registration.abort.clone(),
100
+ registration: accepted.registration,
101
+ }
102
+ }
103
+
104
+ /// The next frame queued for it, which leaves the byte budget as
105
+ /// once written; panics after five seconds.
106
+ pub fn next_frame(&mut self) -> Bytes {
107
+ let what = format!("a frame queued for socket {}", self.id);
108
+ crate::testing::eventually_blocking(&what, || match self.out.try_recv() {
109
+ Ok(Out::Frame(frame)) => {
110
+ self.abort
111
+ .queued_bytes
112
+ .fetch_sub(frame.len(), Ordering::SeqCst);
113
+ self.abort.queued_frames.fetch_sub(1, Ordering::SeqCst);
114
+ Some(frame)
115
+ }
116
+ Ok(Out::Control(frame) | Out::Ping(frame)) => Some(frame),
117
+ Ok(Out::Close(_)) => panic!("socket {} got a close frame", self.id),
118
+ Err(TryRecvError::Disconnected) => {
119
+ panic!("socket {} ended with nothing queued", self.id)
120
+ }
121
+ Err(TryRecvError::Empty) => None,
122
+ })
123
+ }
124
+
125
+ /// Whether something asked its connection to drop.
126
+ pub fn aborted(&self) -> bool {
127
+ let notified = std::pin::pin!(self.abort.notify.notified());
128
+ notified
129
+ .poll(&mut Context::from_waker(Waker::noop()))
130
+ .is_ready()
131
+ }
132
+
133
+ /// Whether nothing can queue frames to it any more: its writer
134
+ /// would flush and end.
135
+ pub fn released(&self) -> bool {
136
+ self.out.is_closed()
137
+ }
138
+
139
+ /// End it, as its connection task does when the client goes.
140
+ pub fn close(&self) {
141
+ self.registration.unregister();
142
+ self.registration.uncount();
143
+ }
144
+ }
145
+
146
+ /// Whether socket `id` is unregistered; None while CONNS is held or
147
+ /// awaited, so a test can poll it without queuing on the lock.
148
+ pub fn unregistered(id: u64) -> Option<bool> {
149
+ CONNS.try_read().map(|conns| !conns.contains_key(&id))
150
+ }
151
+
152
+ /// `subscribe_with`, waiting for the lock.
153
+ pub fn subscribe(id: u64, topic: &[u8], prefix: &[u8], suffix: &[u8], when_full: WhenFull) -> bool {
154
+ let [topic, prefix, suffix] = [topic, prefix, suffix].map(Bytes::copy_from_slice);
155
+ subscribe_with(Wait::Block, id, &topic, &prefix, &suffix, when_full).unwrap_or(false)
156
+ }