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.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +286 -0
- data/Cargo.lock +209 -132
- data/README.md +269 -438
- data/doc/README.md +27 -2
- data/doc/architecture.md +862 -43
- data/doc/benchmarks.md +444 -214
- data/doc/configuration.md +215 -0
- data/doc/operations.md +258 -0
- data/doc/rails-on-ractors.md +161 -49
- data/doc/streaming.md +52 -0
- data/doc/websockets.md +469 -0
- data/doc/why-kino.md +6 -6
- data/doc/worker-loop.md +462 -0
- data/ext/kino/Cargo.toml +19 -3
- data/ext/kino/build.rs +32 -1
- data/ext/kino/clippy.toml +10 -0
- data/ext/kino/src/access_log.rs +70 -92
- data/ext/kino/src/control.rs +26 -685
- data/ext/kino/src/counters.rs +132 -0
- data/ext/kino/src/cpus.rs +1 -18
- data/ext/kino/src/dispatch/tests.rs +731 -0
- data/ext/kino/src/dispatch.rs +276 -0
- data/ext/kino/src/doorbell.rs +108 -0
- data/ext/kino/src/env_strings.rs +26 -30
- data/ext/kino/src/framing.rs +110 -0
- data/ext/kino/src/gvl.rs +292 -66
- data/ext/kino/src/hijack/tests.rs +416 -0
- data/ext/kino/src/hijack.rs +471 -0
- data/ext/kino/src/inline/answer.rs +488 -0
- data/ext/kino/src/inline/conn.rs +1124 -0
- data/ext/kino/src/inline/deadline.rs +421 -0
- data/ext/kino/src/inline/encode.rs +119 -0
- data/ext/kino/src/inline/io.rs +487 -0
- data/ext/kino/src/inline/mod.rs +766 -0
- data/ext/kino/src/inline/parity.rs +862 -0
- data/ext/kino/src/inline/parse.rs +131 -0
- data/ext/kino/src/inline/spin.rs +428 -0
- data/ext/kino/src/inline/testing.rs +628 -0
- data/ext/kino/src/io_shards.rs +240 -192
- data/ext/kino/src/lane_room.rs +99 -0
- data/ext/kino/src/lib.rs +139 -77
- data/ext/kino/src/listen.rs +180 -12
- data/ext/kino/src/log.rs +12 -47
- data/ext/kino/src/logsink.rs +3 -9
- data/ext/kino/src/mono.rs +12 -17
- data/ext/kino/src/pin.rs +3 -3
- data/ext/kino/src/queue/mod.rs +54 -0
- data/ext/kino/src/queue/take.rs +503 -0
- data/ext/kino/src/queue/testing.rs +107 -0
- data/ext/kino/src/queue/tests.rs +581 -0
- data/ext/kino/src/queue/worker.rs +501 -0
- data/ext/kino/src/registry.rs +168 -379
- data/ext/kino/src/request.rs +834 -235
- data/ext/kino/src/response.rs +532 -94
- data/ext/kino/src/server/accept.rs +322 -0
- data/ext/kino/src/server/config.rs +138 -0
- data/ext/kino/src/server/handle.rs +247 -0
- data/ext/kino/src/server/intake.rs +217 -0
- data/ext/kino/src/server/mod.rs +157 -0
- data/ext/kino/src/server/natives.rs +223 -0
- data/ext/kino/src/server/serve/intake_tests.rs +458 -0
- data/ext/kino/src/server/serve.rs +436 -0
- data/ext/kino/src/server/tests.rs +532 -0
- data/ext/kino/src/shared_gvl.rs +50 -0
- data/ext/kino/src/slot/lane.rs +138 -0
- data/ext/kino/src/slot/life.rs +111 -0
- data/ext/kino/src/slot/load.rs +193 -0
- data/ext/kino/src/slot/mod.rs +494 -0
- data/ext/kino/src/slot/park.rs +82 -0
- data/ext/kino/src/stats.rs +936 -0
- data/ext/kino/src/symbols.rs +66 -0
- data/ext/kino/src/test_support.rs +24 -14
- data/ext/kino/src/testing.rs +409 -0
- data/ext/kino/src/ticker.rs +87 -0
- data/ext/kino/src/timer.rs +4 -7
- data/ext/kino/src/tls.rs +101 -131
- data/ext/kino/src/typed_data.rs +131 -0
- data/ext/kino/src/upgrade.rs +77 -0
- data/ext/kino/src/ws/codec.rs +470 -0
- data/ext/kino/src/ws/drive.rs +600 -0
- data/ext/kino/src/ws/handshake.rs +267 -0
- data/ext/kino/src/ws/mod.rs +317 -0
- data/ext/kino/src/ws/server_tests.rs +759 -0
- data/ext/kino/src/ws/socket.rs +279 -0
- data/ext/kino/src/ws/stats.rs +88 -0
- data/ext/kino/src/ws/testing.rs +156 -0
- data/ext/kino/src/ws/topics.rs +550 -0
- data/lib/kino/cli.rb +100 -9
- data/lib/kino/configuration.rb +32 -10
- data/lib/kino/crash_backoff.rb +56 -0
- data/lib/kino/input.rb +36 -17
- data/lib/kino/log.rb +8 -1
- data/lib/kino/monitor.rb +1 -1
- data/lib/kino/pool.rb +169 -0
- data/lib/kino/pool_scaler.rb +12 -13
- data/lib/kino/quarantine_monitor.rb +3 -3
- data/lib/kino/ractor_supervisor.rb +201 -161
- data/lib/kino/server.rb +291 -185
- data/lib/kino/slot_bank.rb +21 -9
- data/lib/kino/stream.rb +2 -2
- data/lib/kino/teardown.rb +33 -0
- data/lib/kino/templates/kino.rb.tt +41 -6
- data/lib/kino/threaded_pool.rb +87 -102
- data/lib/kino/version.rb +1 -1
- data/lib/kino/web_socket.rb +125 -0
- data/lib/kino/worker/loop.rb +319 -0
- data/lib/kino/worker.rb +345 -79
- data/lib/kino/worker_hooks.rb +7 -1
- data/lib/kino/worker_row.rb +15 -0
- data/lib/kino.rb +27 -3
- data/lib/rackup/handler/kino.rb +1 -1
- data/sig/kino.rbs +93 -10
- metadata +66 -3
- data/ext/kino/src/queue.rs +0 -333
- data/ext/kino/src/server.rs +0 -1785
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
//! Taking a handshake natively: the offer, the app's accept, registration and the held 101.
|
|
2
|
+
|
|
3
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
4
|
+
use std::sync::Arc;
|
|
5
|
+
|
|
6
|
+
use bytes::Bytes;
|
|
7
|
+
use http::{HeaderName, HeaderValue};
|
|
8
|
+
use tokio::sync::mpsc;
|
|
9
|
+
|
|
10
|
+
use super::codec::accept_key;
|
|
11
|
+
use super::socket::{Abort, Out};
|
|
12
|
+
use super::stats::{Cause, Refusal, WsCount, CLOSED, COUNTS, HANDSHAKES_REFUSED, OPEN};
|
|
13
|
+
use super::{unregister, Conn, Limits, CONNS, NEXT_ID};
|
|
14
|
+
use crate::framing;
|
|
15
|
+
use crate::registry::ServerInner;
|
|
16
|
+
use crate::request::RequestCtx;
|
|
17
|
+
use crate::slot::WorkerSlot;
|
|
18
|
+
use crate::upgrade::Claim;
|
|
19
|
+
|
|
20
|
+
/// What ws::accept needs, held with the request's upgrade until the app claims it.
|
|
21
|
+
#[derive(Clone)]
|
|
22
|
+
pub struct Offer {
|
|
23
|
+
limits: Arc<Limits>,
|
|
24
|
+
/// A draining server opens no sockets.
|
|
25
|
+
draining: tokio::sync::watch::Receiver<bool>,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
#[derive(Debug, PartialEq, Eq)]
|
|
29
|
+
pub enum Accept {
|
|
30
|
+
Opened(u64),
|
|
31
|
+
/// Draining, the worker's sockets closed, or `websocket_max` open: a 503 that closes.
|
|
32
|
+
Refused,
|
|
33
|
+
/// Not a handshake Kino can take (or answered, or hijacked): the app's response goes out.
|
|
34
|
+
Declined,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// What the connection task needs once the app accepted.
|
|
38
|
+
pub(crate) struct Accepted {
|
|
39
|
+
pub(super) registration: Registration,
|
|
40
|
+
pub(super) out_rx: mpsc::Receiver<Out>,
|
|
41
|
+
/// For pongs and close echoes.
|
|
42
|
+
pub(super) reply: mpsc::Sender<Out>,
|
|
43
|
+
/// Resolves once the 101 went out; fails when answered otherwise (hold_for_switch).
|
|
44
|
+
pub(super) switched: tokio::sync::oneshot::Receiver<()>,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// A socket's entry in CONNS and its place in the open counts (server, worker, process):
|
|
48
|
+
/// dropping it gives up what is left, so every end, a runtime teardown included, forgets it.
|
|
49
|
+
pub(crate) struct Registration {
|
|
50
|
+
pub(super) id: u64,
|
|
51
|
+
pub(super) owner: Arc<WorkerSlot>,
|
|
52
|
+
pub(super) limits: Arc<Limits>,
|
|
53
|
+
pub(super) abort: Arc<Abort>,
|
|
54
|
+
registered: AtomicBool,
|
|
55
|
+
counted: AtomicBool,
|
|
56
|
+
opened: bool,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
impl Registration {
|
|
60
|
+
pub(super) fn open(&mut self) {
|
|
61
|
+
self.opened = true;
|
|
62
|
+
OPEN.fetch_add(1, Ordering::Relaxed);
|
|
63
|
+
COUNTS.add(WsCount::Opened);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Out of CONNS and its topics, and the open counts. An opened socket counts as closed under
|
|
67
|
+
/// its cause; one with none went with its task: GoingAway once switched, else HandshakeFailed.
|
|
68
|
+
pub(super) fn unregister(&self) {
|
|
69
|
+
if self.registered.swap(false, Ordering::SeqCst) {
|
|
70
|
+
unregister(self.id);
|
|
71
|
+
self.limits.open.fetch_sub(1, Ordering::SeqCst);
|
|
72
|
+
if self.opened {
|
|
73
|
+
// Closed first: a snapshot that reads none open reads every close.
|
|
74
|
+
let cause = self.abort.cause().unwrap_or_else(|| {
|
|
75
|
+
if self.abort.switched.load(Ordering::SeqCst) {
|
|
76
|
+
Cause::GoingAway
|
|
77
|
+
} else {
|
|
78
|
+
Cause::HandshakeFailed
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
CLOSED.add(cause);
|
|
82
|
+
OPEN.fetch_sub(1, Ordering::Release);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/// Its close is in the worker's inbox, or no worker will take it: no on_close is owed.
|
|
88
|
+
pub(super) fn uncount(&self) {
|
|
89
|
+
if self.counted.swap(false, Ordering::SeqCst) {
|
|
90
|
+
self.owner.sockets.open.fetch_sub(1, Ordering::SeqCst);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
impl Drop for Registration {
|
|
96
|
+
fn drop(&mut self) {
|
|
97
|
+
self.unregister();
|
|
98
|
+
self.uncount();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// RFC 6455 4.2.1: an HTTP/1.1 GET upgrading to version 13, with a key.
|
|
103
|
+
fn is_upgrade<B>(req: &hyper::Request<B>) -> bool {
|
|
104
|
+
let has_token = |name, token: &[u8]| {
|
|
105
|
+
let mut values = req.headers().get_all(name).iter();
|
|
106
|
+
values.any(|v| v.to_str().is_ok() && framing::has_token(v.as_bytes(), token))
|
|
107
|
+
};
|
|
108
|
+
req.method() == http::Method::GET
|
|
109
|
+
&& req.version() == http::Version::HTTP_11
|
|
110
|
+
&& has_token(http::header::UPGRADE, b"websocket")
|
|
111
|
+
&& has_token(http::header::CONNECTION, b"upgrade")
|
|
112
|
+
&& req.headers().contains_key(http::header::SEC_WEBSOCKET_KEY)
|
|
113
|
+
&& req
|
|
114
|
+
.headers()
|
|
115
|
+
.get(http::header::SEC_WEBSOCKET_VERSION)
|
|
116
|
+
.is_some_and(|v| v == "13")
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// Only on a lanes server: without lanes, a socket's events have no route to its worker.
|
|
120
|
+
pub(crate) fn offer<B>(req: &hyper::Request<B>, server: &ServerInner) -> Option<Offer> {
|
|
121
|
+
(server.config.lanes && is_upgrade(req)).then(|| Offer {
|
|
122
|
+
limits: server.config.ws.clone(),
|
|
123
|
+
draining: server.shutdown_tx.subscribe(),
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// Give the socket to the slot that took the request, and hold its 101 with the app's `extra`
|
|
128
|
+
/// headers for `switch`: on_open runs in between, so what it writes and subscribes is in place
|
|
129
|
+
/// when the client sees the socket. With `on_shutdown`, the drain's 1001 waits for it.
|
|
130
|
+
pub fn accept(
|
|
131
|
+
ctx: &mut RequestCtx,
|
|
132
|
+
extra: &[(HeaderName, HeaderValue)],
|
|
133
|
+
on_shutdown: bool,
|
|
134
|
+
) -> Accept {
|
|
135
|
+
open(ctx, extra, on_shutdown).unwrap_or(Accept::Declined)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fn open(
|
|
139
|
+
ctx: &mut RequestCtx,
|
|
140
|
+
extra: &[(HeaderName, HeaderValue)],
|
|
141
|
+
on_shutdown: bool,
|
|
142
|
+
) -> Option<Accept> {
|
|
143
|
+
let owner = ctx.slot.clone().filter(|slot| slot.lane.ws_tx.is_some())?;
|
|
144
|
+
let key = ctx.headers.get(http::header::SEC_WEBSOCKET_KEY)?;
|
|
145
|
+
let accept = HeaderValue::try_from(accept_key(key.as_bytes())).ok()?;
|
|
146
|
+
let upgrade = ctx
|
|
147
|
+
.upgrade
|
|
148
|
+
.take_if(|upgrade| upgrade.websocket().is_some())?;
|
|
149
|
+
let offer = upgrade.websocket()?.clone();
|
|
150
|
+
|
|
151
|
+
let (switch_tx, switched) = tokio::sync::oneshot::channel();
|
|
152
|
+
let Some((id, mut accepted)) = register(owner.clone(), &offer.limits, switched) else {
|
|
153
|
+
// A drain or a closing worker would have refused it anyway.
|
|
154
|
+
let why = refusal(&owner, &offer.draining).unwrap_or(Refusal::WebsocketMax);
|
|
155
|
+
return Some(refuse(ctx, why));
|
|
156
|
+
};
|
|
157
|
+
// Checked once registered: a close that begins later finds the socket.
|
|
158
|
+
if let Some(why) = refusal(&owner, &offer.draining) {
|
|
159
|
+
drop(accepted);
|
|
160
|
+
return Some(refuse(ctx, why));
|
|
161
|
+
}
|
|
162
|
+
accepted.registration.open();
|
|
163
|
+
let abort = &accepted.registration.abort;
|
|
164
|
+
abort.on_shutdown.store(on_shutdown, Ordering::SeqCst);
|
|
165
|
+
// The connection task is gone (runtime shutdown); the claim dropped the registration.
|
|
166
|
+
if !upgrade.claim(Claim::WebSocket(accepted)) {
|
|
167
|
+
return None;
|
|
168
|
+
}
|
|
169
|
+
ctx.responder
|
|
170
|
+
.hold_for_switch(switch_tx, switching_protocols(accept, extra));
|
|
171
|
+
Some(Accept::Opened(id))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/// A 503 for `why` that closes the connection.
|
|
175
|
+
fn refuse(ctx: &mut RequestCtx, why: Refusal) -> Accept {
|
|
176
|
+
let mut refusal = crate::response::plain_response(503, "Service Unavailable\n");
|
|
177
|
+
crate::response::close_connection(&mut refusal);
|
|
178
|
+
ctx.responder.send_response(refusal);
|
|
179
|
+
HANDSHAKES_REFUSED.add(why);
|
|
180
|
+
Accept::Refused
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
fn switching_protocols(
|
|
184
|
+
accept: HeaderValue,
|
|
185
|
+
extra: &[(HeaderName, HeaderValue)],
|
|
186
|
+
) -> crate::response::HyperResponse {
|
|
187
|
+
let mut response = hyper::Response::new(crate::response::full_body(Bytes::new()));
|
|
188
|
+
*response.status_mut() = http::StatusCode::SWITCHING_PROTOCOLS;
|
|
189
|
+
let headers = response.headers_mut();
|
|
190
|
+
for (name, value) in extra {
|
|
191
|
+
headers.append(name.clone(), value.clone());
|
|
192
|
+
}
|
|
193
|
+
headers.insert(http::header::UPGRADE, HeaderValue::from_static("websocket"));
|
|
194
|
+
headers.insert(
|
|
195
|
+
http::header::CONNECTION,
|
|
196
|
+
HeaderValue::from_static("Upgrade"),
|
|
197
|
+
);
|
|
198
|
+
headers.insert(http::header::SEC_WEBSOCKET_ACCEPT, accept);
|
|
199
|
+
response
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/// The server drains, or the slot's sockets are being closed.
|
|
203
|
+
fn refusal(owner: &WorkerSlot, draining: &tokio::sync::watch::Receiver<bool>) -> Option<Refusal> {
|
|
204
|
+
if *draining.borrow() {
|
|
205
|
+
return Some(Refusal::Draining);
|
|
206
|
+
}
|
|
207
|
+
(owner.sockets.close_code.load(Ordering::SeqCst) != 0).then_some(Refusal::WorkerClosing)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// None when `websocket_max` sockets are open.
|
|
211
|
+
pub(super) fn register(
|
|
212
|
+
owner: Arc<WorkerSlot>,
|
|
213
|
+
limits: &Arc<Limits>,
|
|
214
|
+
switched: tokio::sync::oneshot::Receiver<()>,
|
|
215
|
+
) -> Option<(u64, Accepted)> {
|
|
216
|
+
if !limits.open_one() {
|
|
217
|
+
return None;
|
|
218
|
+
}
|
|
219
|
+
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
|
220
|
+
let (tx, out_rx) = mpsc::channel(limits.queue);
|
|
221
|
+
let abort = Arc::new(Abort {
|
|
222
|
+
queue_bytes: limits.queue_bytes,
|
|
223
|
+
inbound: limits.inbound,
|
|
224
|
+
..Abort::default()
|
|
225
|
+
});
|
|
226
|
+
owner.sockets.open.fetch_add(1, Ordering::SeqCst);
|
|
227
|
+
CONNS.write().insert(
|
|
228
|
+
id,
|
|
229
|
+
Conn {
|
|
230
|
+
tx: tx.clone(),
|
|
231
|
+
abort: abort.clone(),
|
|
232
|
+
owner: owner.clone(),
|
|
233
|
+
},
|
|
234
|
+
);
|
|
235
|
+
let accepted = Accepted {
|
|
236
|
+
registration: Registration {
|
|
237
|
+
id,
|
|
238
|
+
owner,
|
|
239
|
+
limits: limits.clone(),
|
|
240
|
+
abort,
|
|
241
|
+
registered: AtomicBool::new(true),
|
|
242
|
+
counted: AtomicBool::new(true),
|
|
243
|
+
opened: false,
|
|
244
|
+
},
|
|
245
|
+
out_rx,
|
|
246
|
+
reply: tx,
|
|
247
|
+
switched,
|
|
248
|
+
};
|
|
249
|
+
Some((id, accepted))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
#[cfg(test)]
|
|
253
|
+
mod tests {
|
|
254
|
+
use super::*;
|
|
255
|
+
|
|
256
|
+
#[test]
|
|
257
|
+
fn only_protocol_version_13_is_a_handshake() {
|
|
258
|
+
let mut request = crate::ws::testing::handshake().body(()).expect("request");
|
|
259
|
+
assert!(is_upgrade(&request));
|
|
260
|
+
|
|
261
|
+
request.headers_mut().insert(
|
|
262
|
+
http::header::SEC_WEBSOCKET_VERSION,
|
|
263
|
+
http::HeaderValue::from_static("8"),
|
|
264
|
+
);
|
|
265
|
+
assert!(!is_upgrade(&request), "version 8 must not be upgraded");
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
//! Native WebSockets: the id-keyed API over the socket registry. A socket belongs to the
|
|
2
|
+
//! slot that accepted it: its messages land in that slot's inbox in order, reading pauses
|
|
3
|
+
//! at its inbound credit, and writes never block Ruby (a full queue returns false).
|
|
4
|
+
|
|
5
|
+
mod codec;
|
|
6
|
+
mod drive;
|
|
7
|
+
mod handshake;
|
|
8
|
+
#[cfg(test)]
|
|
9
|
+
mod server_tests;
|
|
10
|
+
mod socket;
|
|
11
|
+
mod stats;
|
|
12
|
+
#[cfg(test)]
|
|
13
|
+
pub mod testing;
|
|
14
|
+
pub mod topics;
|
|
15
|
+
|
|
16
|
+
use std::collections::HashMap;
|
|
17
|
+
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
|
18
|
+
use std::sync::{Arc, LazyLock};
|
|
19
|
+
use std::time::Duration;
|
|
20
|
+
|
|
21
|
+
use bytes::Bytes;
|
|
22
|
+
use magnus::prelude::*;
|
|
23
|
+
use magnus::{Error, RString, Ruby};
|
|
24
|
+
use parking_lot::RwLock;
|
|
25
|
+
|
|
26
|
+
pub(crate) use codec::Opcode;
|
|
27
|
+
use drive::drain_inbox;
|
|
28
|
+
pub(crate) use drive::drive;
|
|
29
|
+
pub use handshake::{accept, Accept, Offer};
|
|
30
|
+
pub(crate) use handshake::{offer, Accepted};
|
|
31
|
+
use socket::update;
|
|
32
|
+
use socket::Conn;
|
|
33
|
+
pub use socket::SlotSockets;
|
|
34
|
+
pub use stats::{snapshot, Cause, Refusal, WsCount, WsSnapshot};
|
|
35
|
+
|
|
36
|
+
use crate::registry::ServerInner;
|
|
37
|
+
use crate::slot::WorkerSlot;
|
|
38
|
+
|
|
39
|
+
/// Outgoing frames a socket may have queued; past this, writes fail.
|
|
40
|
+
const QUEUE_FRAMES: usize = 256;
|
|
41
|
+
/// Bytes of outgoing frames a socket may have queued; whichever budget fills first counts.
|
|
42
|
+
const QUEUE_BYTES: usize = 4 << 20;
|
|
43
|
+
/// Messages of a socket its worker may have waiting or in a callback.
|
|
44
|
+
pub const INBOUND_CREDIT: usize = 16;
|
|
45
|
+
/// Largest message, all fragments together (`websocket_max_message`).
|
|
46
|
+
pub const DEFAULT_MAX_MESSAGE: usize = 1 << 20;
|
|
47
|
+
/// Silence before a ping; silent for two, the client is dropped (`websocket_ping_interval`).
|
|
48
|
+
pub const DEFAULT_PING_INTERVAL: Duration = Duration::from_secs(30);
|
|
49
|
+
|
|
50
|
+
/// A server's WebSocket budgets and its open count; the queue and inbound budgets are fixed.
|
|
51
|
+
pub struct Limits {
|
|
52
|
+
pub max_message: usize,
|
|
53
|
+
pub queue: usize,
|
|
54
|
+
pub queue_bytes: usize,
|
|
55
|
+
pub inbound: usize,
|
|
56
|
+
/// Zero: no pings, and no client is dropped for its silence.
|
|
57
|
+
pub ping_interval: Duration,
|
|
58
|
+
/// Most sockets open at once (`websocket_max`); 0: no cap.
|
|
59
|
+
pub max: usize,
|
|
60
|
+
pub(crate) open: AtomicUsize,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
impl Default for Limits {
|
|
64
|
+
fn default() -> Self {
|
|
65
|
+
Limits {
|
|
66
|
+
max_message: DEFAULT_MAX_MESSAGE,
|
|
67
|
+
queue: QUEUE_FRAMES,
|
|
68
|
+
queue_bytes: QUEUE_BYTES,
|
|
69
|
+
inbound: INBOUND_CREDIT,
|
|
70
|
+
ping_interval: DEFAULT_PING_INTERVAL,
|
|
71
|
+
max: 0,
|
|
72
|
+
open: AtomicUsize::new(0),
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
impl Limits {
|
|
78
|
+
fn open_one(&self) -> bool {
|
|
79
|
+
update(&self.open, |open| {
|
|
80
|
+
(self.max == 0 || open < self.max).then_some(open + 1)
|
|
81
|
+
})
|
|
82
|
+
.is_ok()
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// How long a client has to answer Kino's close, and a writer to flush, before the drop.
|
|
87
|
+
const CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
|
|
88
|
+
|
|
89
|
+
/// The longest a drain spreads its 1001s over, so clients do not all reconnect at once.
|
|
90
|
+
const CLOSE_SPREAD: Duration = Duration::from_secs(1);
|
|
91
|
+
|
|
92
|
+
/// Half the drain's `left` seconds, at most CLOSE_SPREAD (unbounded: all of it; past or NaN: none).
|
|
93
|
+
pub fn close_spread(left: f64) -> Duration {
|
|
94
|
+
if left > 0.0 {
|
|
95
|
+
Duration::try_from_secs_f64(left / 2.0).map_or(CLOSE_SPREAD, |half| half.min(CLOSE_SPREAD))
|
|
96
|
+
} else {
|
|
97
|
+
Duration::ZERO
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
pub const GOING_AWAY: u16 = 1001;
|
|
102
|
+
pub const SERVER_ERROR: u16 = 1011;
|
|
103
|
+
|
|
104
|
+
/// What a socket hands its worker: a message, on_shutdown's turn, on_drained, or its end.
|
|
105
|
+
#[derive(Debug, PartialEq, Eq)]
|
|
106
|
+
pub enum WsEvent {
|
|
107
|
+
Message { id: u64, data: Bytes, text: bool },
|
|
108
|
+
Shutdown { id: u64 },
|
|
109
|
+
Drained { id: u64 },
|
|
110
|
+
Close { id: u64 },
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
impl WsEvent {
|
|
114
|
+
pub fn into_ruby(self, ruby: &Ruby) -> Result<magnus::Value, Error> {
|
|
115
|
+
let symbols = crate::symbols::get();
|
|
116
|
+
let ary = ruby.ary_new_capa(3);
|
|
117
|
+
let (id, kind) = match self {
|
|
118
|
+
WsEvent::Message { id, data, text } => {
|
|
119
|
+
ary.push(id)?;
|
|
120
|
+
ary.push(symbols.message.value())?;
|
|
121
|
+
let s = ruby.str_from_slice(&data);
|
|
122
|
+
if text {
|
|
123
|
+
s.enc_associate(ruby.utf8_encindex())?;
|
|
124
|
+
}
|
|
125
|
+
ary.push(s)?;
|
|
126
|
+
return Ok(ary.as_value());
|
|
127
|
+
}
|
|
128
|
+
WsEvent::Shutdown { id } => (id, symbols.shutdown),
|
|
129
|
+
WsEvent::Drained { id } => (id, symbols.drained),
|
|
130
|
+
WsEvent::Close { id } => (id, symbols.close),
|
|
131
|
+
};
|
|
132
|
+
ary.push(id)?;
|
|
133
|
+
ary.push(kind.value())?;
|
|
134
|
+
Ok(ary.as_value())
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
|
139
|
+
static CONNS: LazyLock<RwLock<HashMap<u64, Conn>>> = LazyLock::new(Default::default);
|
|
140
|
+
|
|
141
|
+
/// Forget a socket and its subscriptions. CONNS is released before the topic lock: a
|
|
142
|
+
/// fan-out holds that one a while, and writes to every other socket need CONNS meanwhile.
|
|
143
|
+
/// A socket that never subscribed skips the topic lock.
|
|
144
|
+
fn unregister(id: u64) {
|
|
145
|
+
let mut conns = CONNS.write();
|
|
146
|
+
let removed = conns.remove(&id);
|
|
147
|
+
if let Some(conn) = &removed {
|
|
148
|
+
conn.abort.gone.store(true, Ordering::SeqCst);
|
|
149
|
+
}
|
|
150
|
+
drop(conns);
|
|
151
|
+
if removed.is_some_and(|conn| conn.abort.subscribed.load(Ordering::SeqCst)) {
|
|
152
|
+
topics::forget(id);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
pub fn registered(id: u64) -> bool {
|
|
157
|
+
CONNS.read().contains_key(&id)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/// `then` on socket `id` under the registry's read lock.
|
|
161
|
+
fn with<T>(id: u64, then: impl FnOnce(&Conn) -> T) -> Option<T> {
|
|
162
|
+
CONNS.read().get(&id).map(then)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/// A callback returned, or the message was dropped: the reader may read another.
|
|
166
|
+
pub fn handled(id: u64) {
|
|
167
|
+
with(id, |conn| conn.abort.return_credit());
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// on_shutdown ran, or will not: the drain may send its 1001.
|
|
171
|
+
pub fn shutdown_ran(id: u64) {
|
|
172
|
+
with(id, |conn| conn.abort.goodbye.notify_one());
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
pub fn pending(id: u64) -> usize {
|
|
176
|
+
with(id, |conn| conn.abort.pending()).unwrap_or(0)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// False once the socket is gone or its queue is full; the socket stays open either way.
|
|
180
|
+
pub fn write(id: u64, opcode: Opcode, payload: &[u8]) -> bool {
|
|
181
|
+
let frame = codec::encode(opcode, payload);
|
|
182
|
+
with(id, |conn| conn.write(frame)).unwrap_or(false)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/// Complete frames as they are (server frames are unmasked, so one suits every socket).
|
|
186
|
+
pub fn write_raw(id: u64, frames: &[u8]) -> bool {
|
|
187
|
+
if frames.is_empty() {
|
|
188
|
+
return registered(id);
|
|
189
|
+
}
|
|
190
|
+
let frames = Bytes::copy_from_slice(frames);
|
|
191
|
+
with(id, |conn| conn.write(frames)).unwrap_or(false)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/// After what is queued; the client has CLOSE_TIMEOUT to answer. The first close stands.
|
|
195
|
+
pub fn close(id: u64, code: u16) -> bool {
|
|
196
|
+
with(id, |conn| conn.close(code)).unwrap_or(false)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// `code` to each of `slot`'s sockets (dropped on a full queue); handshakes refused until reset.
|
|
200
|
+
pub fn close_slot(slot: &WorkerSlot, code: u16, cause: Cause) -> usize {
|
|
201
|
+
slot.sockets.close_code.store(code, Ordering::SeqCst);
|
|
202
|
+
let conns = CONNS.read();
|
|
203
|
+
let mut had = 0;
|
|
204
|
+
for conn in conns.values().filter(|conn| conn.owned_by(slot)) {
|
|
205
|
+
if !conn.abort.close(&conn.tx, code, cause) {
|
|
206
|
+
conn.abort.drop_as(cause);
|
|
207
|
+
}
|
|
208
|
+
had += 1;
|
|
209
|
+
}
|
|
210
|
+
had
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/// The drain's goodbye: refuse handshakes, run each on_shutdown, then its 1001, the sockets'
|
|
214
|
+
/// turns spread over `spread`, oldest first. How many there were.
|
|
215
|
+
pub fn leave_all(server: &ServerInner, spread: Duration) -> usize {
|
|
216
|
+
let slots = server.slots.read().clone();
|
|
217
|
+
for slot in &slots {
|
|
218
|
+
slot.sockets.close_code.store(GOING_AWAY, Ordering::SeqCst);
|
|
219
|
+
}
|
|
220
|
+
let mut leaving: Vec<(u64, Arc<socket::Abort>)> = CONNS
|
|
221
|
+
.read()
|
|
222
|
+
.iter()
|
|
223
|
+
.filter(|(_, conn)| slots.iter().any(|slot| conn.owned_by(slot)))
|
|
224
|
+
.map(|(id, conn)| (*id, conn.abort.clone()))
|
|
225
|
+
.collect();
|
|
226
|
+
leaving.sort_unstable_by_key(|(id, _)| *id);
|
|
227
|
+
let count = leaving.len();
|
|
228
|
+
for (turn, (_, abort)) in leaving.iter().enumerate() {
|
|
229
|
+
let after = spread.mul_f64(turn as f64 / count as f64);
|
|
230
|
+
abort
|
|
231
|
+
.leave_after_us
|
|
232
|
+
.store(after.as_micros() as u64, Ordering::SeqCst);
|
|
233
|
+
abort.leave.notify_one();
|
|
234
|
+
}
|
|
235
|
+
count
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/// No worker takes `slot`'s events any more: drop them, waiting ones too, so no socket waits on
|
|
239
|
+
/// an unread inbox, on credit a stuck callback holds, or on an on_shutdown that never returns.
|
|
240
|
+
pub fn abandon(slot: &WorkerSlot) {
|
|
241
|
+
slot.sockets.abandoned.store(true, Ordering::SeqCst);
|
|
242
|
+
drain_inbox(slot);
|
|
243
|
+
for conn in CONNS.read().values().filter(|conn| conn.owned_by(slot)) {
|
|
244
|
+
conn.abort.credit.notify_one();
|
|
245
|
+
conn.abort.goodbye.notify_one();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/// Crashed or wedged: abandon the events and close with 1011, the handlers gone. How many.
|
|
250
|
+
pub fn give_up_slot(slot: &WorkerSlot) -> usize {
|
|
251
|
+
abandon(slot);
|
|
252
|
+
close_slot(slot, SERVER_ERROR, Cause::Crash)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/// Before a new worker: the last one's sockets lost their handlers, so close them with 1011.
|
|
256
|
+
pub fn hand_over(slot: &WorkerSlot) {
|
|
257
|
+
close_slot(slot, SERVER_ERROR, Cause::Crash);
|
|
258
|
+
drain_inbox(slot);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/// Drop the connection now, queued frames and all; works on a full queue.
|
|
262
|
+
pub fn abort(id: u64) -> bool {
|
|
263
|
+
drop_as(id, Cause::Normal)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/// `abort` for a socket whose callback raised: it counts as a crash.
|
|
267
|
+
pub fn fail(id: u64) -> bool {
|
|
268
|
+
drop_as(id, Cause::Crash)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
fn drop_as(id: u64, cause: Cause) -> bool {
|
|
272
|
+
with(id, |conn| conn.abort.drop_as(cause)).is_some()
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
pub fn ws_write(id: u64, data: RString) -> bool {
|
|
276
|
+
write(id, Opcode::Text, unsafe { data.as_slice() })
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
pub fn ws_write_binary(id: u64, data: RString) -> bool {
|
|
280
|
+
write(id, Opcode::Binary, unsafe { data.as_slice() })
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
pub fn ws_write_raw(id: u64, frames: RString) -> bool {
|
|
284
|
+
write_raw(id, unsafe { frames.as_slice() })
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/// ArgumentError for a code no endpoint may send.
|
|
288
|
+
pub fn ws_close(ruby: &Ruby, id: u64, code: i64) -> Result<bool, Error> {
|
|
289
|
+
match u16::try_from(code) {
|
|
290
|
+
Ok(code) if codec::valid_close_code(code) => Ok(close(id, code)),
|
|
291
|
+
_ => Err(Error::new(
|
|
292
|
+
ruby.exception_arg_error(),
|
|
293
|
+
format!("invalid close code {code}: send 1000-1003, 1007-1011 or 3000-4999"),
|
|
294
|
+
)),
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
#[cfg(test)]
|
|
299
|
+
mod tests {
|
|
300
|
+
use super::*;
|
|
301
|
+
|
|
302
|
+
#[test]
|
|
303
|
+
fn a_drain_spreads_its_closes_over_half_what_is_left_up_to_a_second() {
|
|
304
|
+
let ms = Duration::from_millis;
|
|
305
|
+
for (left, spread) in [
|
|
306
|
+
(f64::INFINITY, CLOSE_SPREAD),
|
|
307
|
+
(1e30, CLOSE_SPREAD),
|
|
308
|
+
(2.0, CLOSE_SPREAD),
|
|
309
|
+
(0.4, ms(200)),
|
|
310
|
+
(0.0, Duration::ZERO),
|
|
311
|
+
(f64::NEG_INFINITY, Duration::ZERO),
|
|
312
|
+
(f64::NAN, Duration::ZERO),
|
|
313
|
+
] {
|
|
314
|
+
assert_eq!(close_spread(left), spread, "{left} s left");
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|