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.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +281 -0
- data/Cargo.lock +164 -95
- 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 +17 -1
- 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,550 @@
|
|
|
1
|
+
//! WebSocket topics: a socket subscribes with an envelope (a prefix and a suffix). A publish,
|
|
2
|
+
//! from any Ractor, only queues for one fan-out thread, which builds one frame per envelope
|
|
3
|
+
//! and queues the same bytes to every socket that shares it.
|
|
4
|
+
|
|
5
|
+
use std::collections::HashMap;
|
|
6
|
+
use std::sync::atomic::AtomicUsize;
|
|
7
|
+
use std::sync::{Arc, LazyLock};
|
|
8
|
+
|
|
9
|
+
use bytes::Bytes;
|
|
10
|
+
use magnus::{Error, RString, Ruby};
|
|
11
|
+
use parking_lot::{RwLock, RwLockWriteGuard};
|
|
12
|
+
|
|
13
|
+
use super::codec::{encode_parts, Opcode};
|
|
14
|
+
use super::socket::charge;
|
|
15
|
+
use super::stats::{WsCount, COUNTS};
|
|
16
|
+
use super::Conn;
|
|
17
|
+
use crate::counters::Counted;
|
|
18
|
+
|
|
19
|
+
/// Publishes waiting for the fan-out thread, and their bytes: past either, publish fails
|
|
20
|
+
/// rather than block. Anything fits an empty queue.
|
|
21
|
+
const FANOUT_QUEUE: usize = 65_536;
|
|
22
|
+
const FANOUT_BYTES: usize = 64 << 20;
|
|
23
|
+
|
|
24
|
+
/// What a publish that finds a subscriber's queue full does to it.
|
|
25
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
26
|
+
pub enum WhenFull {
|
|
27
|
+
/// Drop the socket as too slow.
|
|
28
|
+
Close,
|
|
29
|
+
/// Leave this message out for that socket only.
|
|
30
|
+
Skip,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
struct Subscriber {
|
|
34
|
+
conn: Conn,
|
|
35
|
+
when_full: WhenFull,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
struct Envelope {
|
|
39
|
+
prefix: Bytes,
|
|
40
|
+
suffix: Bytes,
|
|
41
|
+
/// Both parts are UTF-8, so text publishes can use it.
|
|
42
|
+
text: bool,
|
|
43
|
+
sockets: HashMap<u64, Subscriber>,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
impl Envelope {
|
|
47
|
+
fn new(prefix: Bytes, suffix: Bytes) -> Self {
|
|
48
|
+
let text = std::str::from_utf8(&prefix).is_ok() && std::str::from_utf8(&suffix).is_ok();
|
|
49
|
+
Envelope {
|
|
50
|
+
prefix,
|
|
51
|
+
suffix,
|
|
52
|
+
text,
|
|
53
|
+
sockets: HashMap::new(),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// None for a text publish through an envelope that is not UTF-8.
|
|
58
|
+
fn frame(&self, opcode: Opcode, body: &[u8]) -> Option<Bytes> {
|
|
59
|
+
(opcode == Opcode::Binary || self.text)
|
|
60
|
+
.then(|| encode_parts(opcode, &[&self.prefix, body, &self.suffix]))
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
#[derive(Default)]
|
|
65
|
+
struct Registry {
|
|
66
|
+
topics: HashMap<Bytes, Vec<Envelope>>,
|
|
67
|
+
/// Each socket's topics, so forgetting it touches only those.
|
|
68
|
+
by_socket: HashMap<u64, Vec<Bytes>>,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// Never held together with CONNS: a fan-out holds it for reading while it queues to
|
|
72
|
+
/// every subscriber. A Ruby thread never waits for it with the GVL held
|
|
73
|
+
/// (`without_waiting_on_gvl`).
|
|
74
|
+
static REGISTRY: LazyLock<RwLock<Registry>> = LazyLock::new(Default::default);
|
|
75
|
+
|
|
76
|
+
/// How a change to the registry takes its lock.
|
|
77
|
+
#[derive(Clone, Copy)]
|
|
78
|
+
pub(super) enum Wait {
|
|
79
|
+
Block,
|
|
80
|
+
Try,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
fn lock(wait: Wait) -> Option<RwLockWriteGuard<'static, Registry>> {
|
|
84
|
+
match wait {
|
|
85
|
+
Wait::Block => Some(REGISTRY.write()),
|
|
86
|
+
Wait::Try => REGISTRY.try_write(),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
impl Registry {
|
|
91
|
+
fn add(&mut self, id: u64, topic: Bytes, envelope: Envelope, subscriber: Subscriber) {
|
|
92
|
+
let envelopes = self.topics.entry(topic.clone()).or_default();
|
|
93
|
+
let index = envelopes
|
|
94
|
+
.iter()
|
|
95
|
+
.position(|e| e.prefix == envelope.prefix && e.suffix == envelope.suffix)
|
|
96
|
+
.unwrap_or_else(|| {
|
|
97
|
+
envelopes.push(envelope);
|
|
98
|
+
envelopes.len() - 1
|
|
99
|
+
});
|
|
100
|
+
envelopes[index].sockets.insert(id, subscriber);
|
|
101
|
+
let topics = self.by_socket.entry(id).or_default();
|
|
102
|
+
if !topics.contains(&topic) {
|
|
103
|
+
topics.push(topic);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// Out of the envelopes of `topic` that `matches` selects; true if it was in one.
|
|
108
|
+
fn remove(&mut self, id: u64, topic: &[u8], matches: impl Fn(&Envelope) -> bool) -> bool {
|
|
109
|
+
let Some(envelopes) = self.topics.get_mut(topic) else {
|
|
110
|
+
return false;
|
|
111
|
+
};
|
|
112
|
+
let (mut removed, mut still) = (false, false);
|
|
113
|
+
envelopes.retain_mut(|envelope| {
|
|
114
|
+
if matches(envelope) {
|
|
115
|
+
removed |= envelope.sockets.remove(&id).is_some();
|
|
116
|
+
}
|
|
117
|
+
still |= envelope.sockets.contains_key(&id);
|
|
118
|
+
!envelope.sockets.is_empty()
|
|
119
|
+
});
|
|
120
|
+
if envelopes.is_empty() {
|
|
121
|
+
self.topics.remove(topic);
|
|
122
|
+
}
|
|
123
|
+
if !still {
|
|
124
|
+
if let Some(topics) = self.by_socket.get_mut(&id) {
|
|
125
|
+
topics.retain(|t| t != topic);
|
|
126
|
+
if topics.is_empty() {
|
|
127
|
+
self.by_socket.remove(&id);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
removed
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Deliver `topic`'s publishes to socket `id` as `prefix + body + suffix` frames; the same
|
|
136
|
+
/// envelope again keeps one subscription with the new `when_full`. False once the socket is
|
|
137
|
+
/// gone; None when `wait` is Try and the lock is held.
|
|
138
|
+
pub(super) fn subscribe_with(
|
|
139
|
+
wait: Wait,
|
|
140
|
+
id: u64,
|
|
141
|
+
topic: &Bytes,
|
|
142
|
+
prefix: &Bytes,
|
|
143
|
+
suffix: &Bytes,
|
|
144
|
+
when_full: WhenFull,
|
|
145
|
+
) -> Option<bool> {
|
|
146
|
+
let Some(conn) = super::with(id, Conn::clone) else {
|
|
147
|
+
return Some(false);
|
|
148
|
+
};
|
|
149
|
+
let envelope = Envelope::new(prefix.clone(), suffix.clone());
|
|
150
|
+
let mut registry = lock(wait)?;
|
|
151
|
+
if !conn.subscribing() {
|
|
152
|
+
return Some(false);
|
|
153
|
+
}
|
|
154
|
+
registry.add(id, topic.clone(), envelope, Subscriber { conn, when_full });
|
|
155
|
+
Some(true)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/// Those made with `prefix` (any suffix), or all; false if none, None as for subscribe_with.
|
|
159
|
+
fn unsubscribe_with(wait: Wait, id: u64, topic: &[u8], prefix: Option<&[u8]>) -> Option<bool> {
|
|
160
|
+
Some(lock(wait)?.remove(id, topic, |e| {
|
|
161
|
+
prefix.is_none_or(|prefix| e.prefix == prefix)
|
|
162
|
+
}))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/// At once while the lock is free, else waiting with the GVL released: waiting with it held
|
|
166
|
+
/// would stop the Ractor's other threads, and under Ractors every GC, for a whole fan-out.
|
|
167
|
+
/// `change` must not touch Ruby.
|
|
168
|
+
/// A Ruby interrupt's raise comes back as Err (gvl::released), the change made or not.
|
|
169
|
+
fn without_waiting_on_gvl<T>(change: impl Fn(Wait) -> Option<T>) -> Result<T, Error> {
|
|
170
|
+
waiting_released(change, |wait| crate::gvl::released(wait, None))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/// without_waiting_on_gvl with its release passed in: tests stand in for the VM.
|
|
174
|
+
fn waiting_released<T, E>(
|
|
175
|
+
change: impl Fn(Wait) -> Option<T>,
|
|
176
|
+
release: impl FnOnce(&dyn Fn() -> T) -> Result<T, E>,
|
|
177
|
+
) -> Result<T, E> {
|
|
178
|
+
if let Some(done) = change(Wait::Try) {
|
|
179
|
+
return Ok(done);
|
|
180
|
+
}
|
|
181
|
+
release(&|| change(Wait::Block).expect("a blocking lock always comes"))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/// Every subscription of socket `id`, from its unregister once it was marked gone. On a Ruby
|
|
185
|
+
/// thread (a handshake refused once registered) it waits as subscribe does.
|
|
186
|
+
/// With an interrupt pending it waits GVL held (gvl::released_or_held): the subscriptions must go.
|
|
187
|
+
pub fn forget(id: u64) {
|
|
188
|
+
let change = |wait| {
|
|
189
|
+
let mut registry = lock(wait)?;
|
|
190
|
+
for topic in registry.by_socket.remove(&id).unwrap_or_default() {
|
|
191
|
+
registry.remove(id, &topic, |_| true);
|
|
192
|
+
}
|
|
193
|
+
Some(())
|
|
194
|
+
};
|
|
195
|
+
if Ruby::get().is_ok() {
|
|
196
|
+
if change(Wait::Try).is_none() {
|
|
197
|
+
// Only a panic fails it, and the panic hook has reported that.
|
|
198
|
+
let _ = crate::gvl::released_or_held(|| change(Wait::Block));
|
|
199
|
+
}
|
|
200
|
+
} else {
|
|
201
|
+
change(Wait::Block);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
struct Message {
|
|
206
|
+
topic: Bytes,
|
|
207
|
+
body: Bytes,
|
|
208
|
+
opcode: Opcode,
|
|
209
|
+
/// Its bytes in the queue, given back once it is fanned out or refused.
|
|
210
|
+
_queued: Counted,
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
struct Fanout {
|
|
214
|
+
queue: flume::Sender<Message>,
|
|
215
|
+
bytes: Arc<AtomicUsize>,
|
|
216
|
+
max_bytes: usize,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
impl Fanout {
|
|
220
|
+
fn bounded(capacity: usize, max_bytes: usize) -> (Fanout, flume::Receiver<Message>) {
|
|
221
|
+
let (queue, published) = flume::bounded(capacity);
|
|
222
|
+
let fanout = Fanout {
|
|
223
|
+
queue,
|
|
224
|
+
bytes: Arc::default(),
|
|
225
|
+
max_bytes,
|
|
226
|
+
};
|
|
227
|
+
(fanout, published)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
fn publish(&self, topic: &[u8], body: &[u8], opcode: Opcode) -> bool {
|
|
231
|
+
let len = topic.len() + body.len();
|
|
232
|
+
// A refused message gives its bytes back as it drops.
|
|
233
|
+
let queued = charge(&self.bytes, self.max_bytes, len)
|
|
234
|
+
&& self
|
|
235
|
+
.queue
|
|
236
|
+
.try_send(Message {
|
|
237
|
+
topic: Bytes::copy_from_slice(topic),
|
|
238
|
+
body: Bytes::copy_from_slice(body),
|
|
239
|
+
opcode,
|
|
240
|
+
_queued: Counted::adopt(self.bytes.clone(), len),
|
|
241
|
+
})
|
|
242
|
+
.is_ok();
|
|
243
|
+
if !queued {
|
|
244
|
+
COUNTS.add(WsCount::PublishesRefused);
|
|
245
|
+
}
|
|
246
|
+
queued
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
static FANOUT: LazyLock<Fanout> = LazyLock::new(|| {
|
|
251
|
+
let (fanout, published) = Fanout::bounded(FANOUT_QUEUE, FANOUT_BYTES);
|
|
252
|
+
std::thread::Builder::new()
|
|
253
|
+
.name("kino-ws-fanout".into())
|
|
254
|
+
.spawn(move || {
|
|
255
|
+
for message in published.iter() {
|
|
256
|
+
fan_out(&message);
|
|
257
|
+
}
|
|
258
|
+
})
|
|
259
|
+
.expect("spawn the WebSocket fan-out thread");
|
|
260
|
+
fanout
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
/// UTF-8 `body` as a text frame to `topic`'s UTF-8 envelopes; false only when the fan-out
|
|
264
|
+
/// queue is full.
|
|
265
|
+
pub fn publish(topic: &[u8], body: &[u8]) -> bool {
|
|
266
|
+
FANOUT.publish(topic, body, Opcode::Text)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/// A binary frame, to every subscriber.
|
|
270
|
+
pub fn publish_binary(topic: &[u8], body: &[u8]) -> bool {
|
|
271
|
+
FANOUT.publish(topic, body, Opcode::Binary)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
fn fan_out(message: &Message) {
|
|
275
|
+
let registry = REGISTRY.read();
|
|
276
|
+
let Some(envelopes) = registry.topics.get(&message.topic) else {
|
|
277
|
+
return;
|
|
278
|
+
};
|
|
279
|
+
for envelope in envelopes {
|
|
280
|
+
let Some(frame) = envelope.frame(message.opcode, &message.body) else {
|
|
281
|
+
continue;
|
|
282
|
+
};
|
|
283
|
+
for subscriber in envelope.sockets.values() {
|
|
284
|
+
if subscriber.conn.offer(frame.clone()) {
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
match subscriber.when_full {
|
|
288
|
+
WhenFull::Skip => {
|
|
289
|
+
COUNTS.add(WsCount::MessagesSkipped);
|
|
290
|
+
// The app may resync it once its queue has emptied.
|
|
291
|
+
subscriber.conn.refused();
|
|
292
|
+
}
|
|
293
|
+
WhenFull::Close => subscriber.conn.drop_slow(),
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/// `skip` stands for WhenFull::Skip.
|
|
300
|
+
pub fn ws_subscribe(
|
|
301
|
+
id: u64,
|
|
302
|
+
topic: RString,
|
|
303
|
+
prefix: RString,
|
|
304
|
+
suffix: RString,
|
|
305
|
+
skip: bool,
|
|
306
|
+
) -> Result<bool, Error> {
|
|
307
|
+
// Copied while the GVL is held: the change may run without it.
|
|
308
|
+
let [topic, prefix, suffix] =
|
|
309
|
+
[topic, prefix, suffix].map(|string| Bytes::copy_from_slice(unsafe { string.as_slice() }));
|
|
310
|
+
let when_full = if skip {
|
|
311
|
+
WhenFull::Skip
|
|
312
|
+
} else {
|
|
313
|
+
WhenFull::Close
|
|
314
|
+
};
|
|
315
|
+
without_waiting_on_gvl(|wait| subscribe_with(wait, id, &topic, &prefix, &suffix, when_full))
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
pub fn ws_unsubscribe(id: u64, topic: RString, prefix: Option<RString>) -> Result<bool, Error> {
|
|
319
|
+
let topic = unsafe { topic.as_slice() }.to_vec();
|
|
320
|
+
let prefix = prefix.map(|prefix| unsafe { prefix.as_slice() }.to_vec());
|
|
321
|
+
without_waiting_on_gvl(|wait| unsubscribe_with(wait, id, &topic, prefix.as_deref()))
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/// Callable from any Ractor; ArgumentError for a text body that is not UTF-8.
|
|
325
|
+
pub fn ws_publish(ruby: &Ruby, topic: RString, body: RString, binary: bool) -> Result<bool, Error> {
|
|
326
|
+
let (topic, body) = unsafe { (topic.as_slice(), body.as_slice()) };
|
|
327
|
+
if binary {
|
|
328
|
+
return Ok(publish_binary(topic, body));
|
|
329
|
+
}
|
|
330
|
+
if std::str::from_utf8(body).is_err() {
|
|
331
|
+
return Err(Error::new(
|
|
332
|
+
ruby.exception_arg_error(),
|
|
333
|
+
"a text publish needs a UTF-8 body; publish bytes with binary: true",
|
|
334
|
+
));
|
|
335
|
+
}
|
|
336
|
+
Ok(publish(topic, body))
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
#[cfg(test)]
|
|
340
|
+
mod tests {
|
|
341
|
+
use std::sync::Arc;
|
|
342
|
+
use std::time::Duration;
|
|
343
|
+
|
|
344
|
+
use super::*;
|
|
345
|
+
use crate::testing::{eventually_blocking, serial_blocking};
|
|
346
|
+
use crate::ws::testing::{closes_since, subscribe, unregistered, QueuedSocket};
|
|
347
|
+
use crate::ws::{self, snapshot};
|
|
348
|
+
|
|
349
|
+
/// A frame as it should be queued (Bytes print readably).
|
|
350
|
+
fn frame(wire: &'static [u8]) -> Bytes {
|
|
351
|
+
Bytes::from_static(wire)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
#[test]
|
|
355
|
+
fn a_full_subscriber_is_dropped_others_still_get_it() {
|
|
356
|
+
let _serial = serial_blocking();
|
|
357
|
+
let topic = b"a_full_subscriber_is_dropped_others_still_get_it";
|
|
358
|
+
let slow = QueuedSocket::new(1);
|
|
359
|
+
let mut fast = QueuedSocket::new(8);
|
|
360
|
+
assert!(subscribe(slow.id, topic, b"", b"", WhenFull::Close));
|
|
361
|
+
assert!(subscribe(fast.id, topic, b"", b"", WhenFull::Close));
|
|
362
|
+
let before = snapshot();
|
|
363
|
+
|
|
364
|
+
// The first fills the slow socket's queue; the others find it full.
|
|
365
|
+
for body in [b"1", b"2", b"3", b"4"] {
|
|
366
|
+
assert!(publish(topic, body));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
for wire in [b"\x81\x011", b"\x81\x012", b"\x81\x013", b"\x81\x014"] {
|
|
370
|
+
assert_eq!(fast.next_frame(), frame(wire), "the socket keeping up");
|
|
371
|
+
}
|
|
372
|
+
assert!(slow.aborted(), "a socket too slow for a publish is dropped");
|
|
373
|
+
slow.close();
|
|
374
|
+
assert_eq!(
|
|
375
|
+
closes_since(&before),
|
|
376
|
+
[("slow", 1)],
|
|
377
|
+
"a slow socket closes once as slow, however many publishes find it full"
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
#[test]
|
|
382
|
+
fn a_full_subscriber_that_skips_misses_only_what_found_it_full() {
|
|
383
|
+
let _serial = serial_blocking();
|
|
384
|
+
let topic = b"a_full_subscriber_that_skips";
|
|
385
|
+
let mut slow = QueuedSocket::new(1);
|
|
386
|
+
let mut fast = QueuedSocket::new(8);
|
|
387
|
+
assert!(subscribe(slow.id, topic, b"", b"", WhenFull::Skip));
|
|
388
|
+
assert!(subscribe(fast.id, topic, b"", b"", WhenFull::Close));
|
|
389
|
+
let before = snapshot();
|
|
390
|
+
|
|
391
|
+
// The first fills the slow socket's queue; the next two find it full.
|
|
392
|
+
for body in [b"1", b"2", b"3"] {
|
|
393
|
+
assert!(publish(topic, body));
|
|
394
|
+
}
|
|
395
|
+
eventually_blocking("the slow socket to be found full", || {
|
|
396
|
+
(snapshot().count(WsCount::MessagesSkipped)
|
|
397
|
+
== before.count(WsCount::MessagesSkipped) + 2)
|
|
398
|
+
.then_some(())
|
|
399
|
+
});
|
|
400
|
+
assert_eq!(slow.next_frame(), frame(b"\x81\x011"));
|
|
401
|
+
assert!(publish(topic, b"4"));
|
|
402
|
+
|
|
403
|
+
let next = slow.next_frame();
|
|
404
|
+
assert_eq!(next, frame(b"\x81\x014"), "room again, so it gets the next");
|
|
405
|
+
assert!(!slow.aborted(), "a socket that skips is kept");
|
|
406
|
+
for wire in [b"\x81\x011", b"\x81\x012", b"\x81\x013", b"\x81\x014"] {
|
|
407
|
+
assert_eq!(fast.next_frame(), frame(wire), "the socket keeping up");
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
#[test]
|
|
412
|
+
fn a_closed_socket_leaves_every_topic() {
|
|
413
|
+
let _serial = serial_blocking();
|
|
414
|
+
let socket = QueuedSocket::new(8);
|
|
415
|
+
let topics: [&[u8]; 2] = [b"a_closed_socket/1", b"a_closed_socket/2"];
|
|
416
|
+
for topic in topics {
|
|
417
|
+
assert!(subscribe(socket.id, topic, b"<", b">", WhenFull::Close));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
socket.close();
|
|
421
|
+
|
|
422
|
+
assert!(
|
|
423
|
+
socket.released(),
|
|
424
|
+
"a subscription outlived its socket and keeps its writer waiting"
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
#[test]
|
|
429
|
+
fn during_a_fan_out_writes_and_closes_go_on_and_a_subscribe_that_waited_out_a_close_fails() {
|
|
430
|
+
let _serial = serial_blocking();
|
|
431
|
+
let socket = Arc::new(QueuedSocket::new(8));
|
|
432
|
+
let mut bystander = QueuedSocket::new(8);
|
|
433
|
+
// A long fan-out in progress holds the registry for reading; the
|
|
434
|
+
// socket subscribes, which found it, then waits while it closes.
|
|
435
|
+
let fan_out = REGISTRY.read();
|
|
436
|
+
let subscriber = std::thread::spawn({
|
|
437
|
+
let id = socket.id;
|
|
438
|
+
move || subscribe(id, b"during_a_fan_out", b"", b"", WhenFull::Close)
|
|
439
|
+
});
|
|
440
|
+
// A writer waiting for the lock bars new readers; it also goes
|
|
441
|
+
// first once the fan-out ends, ahead of the forget.
|
|
442
|
+
eventually_blocking("the subscribe to reach the topic lock", || {
|
|
443
|
+
REGISTRY.try_read().is_none().then_some(())
|
|
444
|
+
});
|
|
445
|
+
let closer = std::thread::spawn({
|
|
446
|
+
let socket = socket.clone();
|
|
447
|
+
move || socket.close()
|
|
448
|
+
});
|
|
449
|
+
eventually_blocking("the close to leave CONNS during the fan-out", || {
|
|
450
|
+
(unregistered(socket.id) == Some(true)).then_some(())
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
// Another socket's write goes through, and one that never subscribed
|
|
454
|
+
// closes, with nothing to forget.
|
|
455
|
+
let (done, finished) = std::sync::mpsc::channel();
|
|
456
|
+
let (bystander_id, quiet) = (bystander.id, QueuedSocket::new(8));
|
|
457
|
+
std::thread::spawn(move || {
|
|
458
|
+
let _ = done.send(ws::write(bystander_id, Opcode::Text, b"meanwhile"));
|
|
459
|
+
quiet.close();
|
|
460
|
+
let _ = done.send(true);
|
|
461
|
+
});
|
|
462
|
+
for what in [
|
|
463
|
+
"a write to another socket",
|
|
464
|
+
"a close of one never subscribed",
|
|
465
|
+
] {
|
|
466
|
+
let finished = finished.recv_timeout(Duration::from_secs(5));
|
|
467
|
+
assert!(finished.unwrap_or_else(|_| panic!("{what} waited for the fan-out")));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
drop(fan_out);
|
|
471
|
+
closer.join().expect("closer thread");
|
|
472
|
+
let subscribed = subscriber.join().expect("subscriber thread");
|
|
473
|
+
assert!(!subscribed, "the socket closed before it subscribed");
|
|
474
|
+
assert!(
|
|
475
|
+
socket.released(),
|
|
476
|
+
"a subscription outlived its socket and keeps its writer waiting"
|
|
477
|
+
);
|
|
478
|
+
assert_eq!(bystander.next_frame(), frame(b"\x81\x09meanwhile"));
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
#[test]
|
|
482
|
+
fn a_publish_past_the_fan_out_queues_frames_or_bytes_is_refused_until_its_thread_takes_some() {
|
|
483
|
+
let _serial = serial_blocking();
|
|
484
|
+
let (fanout, queue) = Fanout::bounded(2, 10);
|
|
485
|
+
let before = snapshot().count(WsCount::PublishesRefused);
|
|
486
|
+
|
|
487
|
+
// A publish costs its topic and body.
|
|
488
|
+
let bodies: [&[u8]; 4] = [b"12345", b"123456", b"12", b""];
|
|
489
|
+
let published = bodies.map(|body| fanout.publish(b"t", body, Opcode::Text));
|
|
490
|
+
assert_eq!(
|
|
491
|
+
published,
|
|
492
|
+
[true, false, true, false],
|
|
493
|
+
"13 bytes would pass the budget, and a third publish the frames"
|
|
494
|
+
);
|
|
495
|
+
assert_eq!(snapshot().count(WsCount::PublishesRefused), before + 2);
|
|
496
|
+
for _ in 0..2 {
|
|
497
|
+
drop(queue.recv().expect("a queued publish"));
|
|
498
|
+
}
|
|
499
|
+
assert!(
|
|
500
|
+
fanout.publish(b"t", &[b'x'; 100], Opcode::Text),
|
|
501
|
+
"fanned out, the publishes give their bytes back, and any publish fits an empty queue"
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
#[test]
|
|
506
|
+
fn a_raise_into_a_subscribe_waiting_on_a_fan_out_comes_back_and_leaves_the_topics_free() {
|
|
507
|
+
let _serial = serial_blocking();
|
|
508
|
+
let mut socket = QueuedSocket::new(8);
|
|
509
|
+
let topic = Bytes::from_static(b"a_raise_into_a_waiting_subscribe");
|
|
510
|
+
let fan_out = REGISTRY.read();
|
|
511
|
+
let id = socket.id;
|
|
512
|
+
let subscriber = std::thread::spawn({
|
|
513
|
+
let topic = topic.clone();
|
|
514
|
+
move || {
|
|
515
|
+
let empty = Bytes::new();
|
|
516
|
+
let change =
|
|
517
|
+
|wait| subscribe_with(wait, id, &topic, &empty, &empty, WhenFull::Close);
|
|
518
|
+
// In place of the VM: a Thread#raise came as it waited.
|
|
519
|
+
let mut vm = crate::testing::InPlace {
|
|
520
|
+
release: |_: &std::sync::atomic::AtomicBool, wait: &mut dyn FnMut()| wait(),
|
|
521
|
+
interrupts: || Err("Thread#raise"),
|
|
522
|
+
};
|
|
523
|
+
waiting_released(change, |wait| {
|
|
524
|
+
crate::gvl::released_by(&mut vm, &false.into(), wait)
|
|
525
|
+
})
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
eventually_blocking("the subscribe to wait for the fan-out", || {
|
|
529
|
+
REGISTRY.try_read().is_none().then_some(())
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
drop(fan_out);
|
|
533
|
+
let subscribed = subscriber.join().expect("subscriber thread");
|
|
534
|
+
|
|
535
|
+
assert_eq!(subscribed, Err("Thread#raise"));
|
|
536
|
+
assert!(
|
|
537
|
+
REGISTRY.try_write().is_some(),
|
|
538
|
+
"the raise must leave the topics' lock free"
|
|
539
|
+
);
|
|
540
|
+
assert!(
|
|
541
|
+
publish(&topic, b"after"),
|
|
542
|
+
"the next take of the lock goes through"
|
|
543
|
+
);
|
|
544
|
+
assert_eq!(
|
|
545
|
+
socket.next_frame(),
|
|
546
|
+
frame(b"\x81\x05after"),
|
|
547
|
+
"the change made before the raise stands"
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
}
|
data/lib/kino/cli.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "optparse"
|
|
4
|
+
require "tempfile"
|
|
4
5
|
require_relative "version"
|
|
5
6
|
|
|
6
7
|
module Kino
|
|
@@ -112,7 +113,8 @@ module Kino
|
|
|
112
113
|
|
|
113
114
|
# The two banner halves around Server#start: credits before, the ready
|
|
114
115
|
# block plus a bold "Action!" after, once mode and port are known.
|
|
115
|
-
# Server
|
|
116
|
+
# Server#run calls it unless the kino CLI already did, ahead of loading
|
|
117
|
+
# the app.
|
|
116
118
|
# @return [void]
|
|
117
119
|
def opening_credits
|
|
118
120
|
puts motd
|
|
@@ -184,13 +186,28 @@ module Kino
|
|
|
184
186
|
|
|
185
187
|
ENV["RACK_ENV"] ||= config[:environment] if config[:environment]
|
|
186
188
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
+
return check(rackup_file) if options[:check]
|
|
190
|
+
|
|
191
|
+
$stdout.sync = true
|
|
192
|
+
opening_credits
|
|
193
|
+
# The app's boot output is held back and shown under "Action!".
|
|
194
|
+
capture = OutputCapture.new
|
|
195
|
+
app = capture.during { load_app(rackup_file) }
|
|
196
|
+
begin
|
|
197
|
+
serve(app, config, capture)
|
|
198
|
+
ensure
|
|
199
|
+
capture.replay
|
|
200
|
+
end
|
|
201
|
+
0
|
|
202
|
+
end
|
|
189
203
|
|
|
190
|
-
|
|
204
|
+
def load_app(rackup_file)
|
|
205
|
+
app = Rack::Builder.parse_file(rackup_file)
|
|
206
|
+
app.is_a?(Array) ? app.first : app # rack < 3 compat
|
|
207
|
+
end
|
|
191
208
|
|
|
192
|
-
|
|
193
|
-
0
|
|
209
|
+
def check(rackup_file)
|
|
210
|
+
Check.print_report(load_app(rackup_file)) ? 0 : 1
|
|
194
211
|
end
|
|
195
212
|
|
|
196
213
|
# Bun-style colored help, generated from the parser's own switch list
|
|
@@ -266,11 +283,85 @@ module Kino
|
|
|
266
283
|
config
|
|
267
284
|
end
|
|
268
285
|
|
|
269
|
-
def serve(app, config)
|
|
270
|
-
Server.run(app,
|
|
286
|
+
def serve(app, config, capture)
|
|
287
|
+
Server.run(app, credits: false, on_ready: -> { capture.replay },
|
|
288
|
+
**config.server_options)
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
# Holds fd 1 and 2 output in temp files while the app loads. The same
|
|
292
|
+
# IO objects stay in place (reopened onto the files and back), so
|
|
293
|
+
# loggers that captured $stdout or $stderr keep working afterwards.
|
|
294
|
+
class OutputCapture
|
|
295
|
+
def initialize
|
|
296
|
+
@files = []
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
# Run the block with output captured; on any exception (SystemExit
|
|
300
|
+
# included) restore and show what was captured before re-raising.
|
|
301
|
+
def during
|
|
302
|
+
begin_capture
|
|
303
|
+
yield
|
|
304
|
+
rescue Exception # rubocop:disable Lint/RescueException
|
|
305
|
+
end_capture
|
|
306
|
+
replay
|
|
307
|
+
raise
|
|
308
|
+
ensure
|
|
309
|
+
end_capture
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
# Write the captured output to the real streams, once.
|
|
313
|
+
def replay
|
|
314
|
+
files, @files = @files, []
|
|
315
|
+
@ios.zip(files).each do |io, file|
|
|
316
|
+
next unless file
|
|
317
|
+
|
|
318
|
+
file.rewind
|
|
319
|
+
content = file.read
|
|
320
|
+
io.write(content) unless content.empty?
|
|
321
|
+
io.flush
|
|
322
|
+
rescue IOError, SystemCallError
|
|
323
|
+
nil # a closed pipe must not take the server down
|
|
324
|
+
ensure
|
|
325
|
+
file&.close!
|
|
326
|
+
end
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
private
|
|
330
|
+
|
|
331
|
+
def begin_capture
|
|
332
|
+
@ios = [$stdout, $stderr]
|
|
333
|
+
@ios.each(&:flush)
|
|
334
|
+
@saved = @ios.map(&:dup)
|
|
335
|
+
@files = [Tempfile.new("kino-out"), Tempfile.new("kino-err")]
|
|
336
|
+
@ios.zip(@files).each { |io, file| io.reopen(file) }
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
def end_capture
|
|
340
|
+
return unless @saved
|
|
341
|
+
|
|
342
|
+
failure = flush_rails_logger
|
|
343
|
+
@ios.zip(@saved).each do |io, saved|
|
|
344
|
+
io.flush
|
|
345
|
+
io.reopen(saved)
|
|
346
|
+
io.sync = true
|
|
347
|
+
saved.close
|
|
348
|
+
end
|
|
349
|
+
@saved = nil
|
|
350
|
+
warn "kino: flushing Rails.logger failed: #{failure.message}" if failure
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
# Returns the error instead of raising: the fds must be restored.
|
|
354
|
+
def flush_rails_logger
|
|
355
|
+
logger = defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
|
|
356
|
+
logger.flush if logger.respond_to?(:flush)
|
|
357
|
+
nil
|
|
358
|
+
rescue => e
|
|
359
|
+
e
|
|
360
|
+
end
|
|
271
361
|
end
|
|
362
|
+
private_constant :OutputCapture
|
|
272
363
|
|
|
273
364
|
private_class_method :print_help, :option_parser, :write_sample,
|
|
274
|
-
:resolve_config, :serve, :count
|
|
365
|
+
:resolve_config, :serve, :count, :load_app, :check
|
|
275
366
|
end
|
|
276
367
|
end
|