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,66 @@
|
|
|
1
|
+
//! The Symbols natives tell apart or hand Ruby on hot paths, made once at init on the main
|
|
2
|
+
//! Ractor. An interned Symbol is one VALUE, the same in every Ractor for the process's life, so
|
|
3
|
+
//! telling one apart is a compare and handing one to Ruby allocates nothing, where reading a
|
|
4
|
+
//! Symbol's name takes the VM-wide lock once more than one Ractor exists and Ruby::to_symbol
|
|
5
|
+
//! allocates a String.
|
|
6
|
+
|
|
7
|
+
use std::sync::OnceLock;
|
|
8
|
+
|
|
9
|
+
use magnus::rb_sys::{AsRawValue, FromRawValue};
|
|
10
|
+
use magnus::{Ruby, Value};
|
|
11
|
+
|
|
12
|
+
#[derive(Clone, Copy)]
|
|
13
|
+
pub(crate) struct Sym(rb_sys::VALUE);
|
|
14
|
+
|
|
15
|
+
impl Sym {
|
|
16
|
+
pub(crate) fn is(self, value: Value) -> bool {
|
|
17
|
+
value.as_raw() == self.0
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
pub(crate) fn value(self) -> Value {
|
|
21
|
+
// SAFETY: an interned Symbol's VALUE stays valid in every Ractor for the process's life.
|
|
22
|
+
unsafe { Value::from_raw(self.0) }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
pub(crate) struct Symbols {
|
|
27
|
+
/// The rooms Kino::Native::Worker#take_nonblock narrows to.
|
|
28
|
+
pub(crate) events: Sym,
|
|
29
|
+
pub(crate) requests: Sym,
|
|
30
|
+
pub(crate) connections: Sym,
|
|
31
|
+
pub(crate) wake: Sym,
|
|
32
|
+
pub(crate) message: Sym,
|
|
33
|
+
pub(crate) shutdown: Sym,
|
|
34
|
+
pub(crate) drained: Sym,
|
|
35
|
+
pub(crate) close: Sym,
|
|
36
|
+
/// What an inline job or a write waits for or does next.
|
|
37
|
+
pub(crate) readable: Sym,
|
|
38
|
+
pub(crate) writable: Sym,
|
|
39
|
+
pub(crate) step_aside: Sym,
|
|
40
|
+
pub(crate) websocket: Sym,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static SYMBOLS: OnceLock<Symbols> = OnceLock::new();
|
|
44
|
+
|
|
45
|
+
/// At init, on the main Ractor, before any native that reads them runs.
|
|
46
|
+
pub(crate) fn init(ruby: &Ruby) {
|
|
47
|
+
let sym = |name: &str| Sym(ruby.sym_new(name).as_raw());
|
|
48
|
+
let _ = SYMBOLS.set(Symbols {
|
|
49
|
+
events: sym("events"),
|
|
50
|
+
requests: sym("requests"),
|
|
51
|
+
connections: sym("connections"),
|
|
52
|
+
wake: sym("wake"),
|
|
53
|
+
message: sym("message"),
|
|
54
|
+
shutdown: sym("shutdown"),
|
|
55
|
+
drained: sym("drained"),
|
|
56
|
+
close: sym("close"),
|
|
57
|
+
readable: sym("readable"),
|
|
58
|
+
writable: sym("writable"),
|
|
59
|
+
step_aside: sym("yield"),
|
|
60
|
+
websocket: sym("websocket"),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
pub(crate) fn get() -> &'static Symbols {
|
|
65
|
+
SYMBOLS.get().expect("Kino's Symbols are made at init")
|
|
66
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//! Test-only natives
|
|
2
|
-
//!
|
|
1
|
+
//! Test-only natives for the specs of the crate's primitives: blocking channel takes with the
|
|
2
|
+
//! GVL released, a panic in a release, and the env caches under parallel Ractors.
|
|
3
3
|
//! Exposed as `Kino::Native::_test_*`; not part of the public API.
|
|
4
4
|
|
|
5
5
|
use std::collections::HashMap;
|
|
@@ -65,14 +65,20 @@ pub fn take(ruby: &magnus::Ruby, id: u64) -> Result<Option<String>, magnus::Erro
|
|
|
65
65
|
let chan = lookup(ruby, id)?;
|
|
66
66
|
chan.interrupted.store(false, Ordering::SeqCst);
|
|
67
67
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
68
|
+
// One tick at a time, until the channel yields or closes, or the VM's unblock function
|
|
69
|
+
// raises the flag.
|
|
70
|
+
let taken = gvl::released(
|
|
71
|
+
|| loop {
|
|
72
|
+
if chan.interrupted.load(Ordering::SeqCst) {
|
|
73
|
+
return None;
|
|
74
|
+
}
|
|
75
|
+
if let Some(taken) = crate::queue::recv_tick(&chan.rx) {
|
|
76
|
+
return taken;
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
Some(&chan.interrupted),
|
|
80
|
+
)?;
|
|
81
|
+
Ok(taken)
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
/// Panic inside a GVL-released block: proves it surfaces as a Ruby
|
|
@@ -82,7 +88,7 @@ pub fn take(ruby: &magnus::Ruby, id: u64) -> Result<Option<String>, magnus::Erro
|
|
|
82
88
|
pub fn panic_in_release() -> Result<(), magnus::Error> {
|
|
83
89
|
let hook = std::panic::take_hook();
|
|
84
90
|
std::panic::set_hook(Box::new(|_| {}));
|
|
85
|
-
let result = gvl::
|
|
91
|
+
let result = gvl::released(|| panic!("intentional test panic"), None);
|
|
86
92
|
std::panic::set_hook(hook);
|
|
87
93
|
result
|
|
88
94
|
}
|
|
@@ -107,7 +113,7 @@ pub fn env_probe(
|
|
|
107
113
|
user_agent: String,
|
|
108
114
|
) -> Result<magnus::RHash, magnus::Error> {
|
|
109
115
|
use crate::env_strings;
|
|
110
|
-
use crate::request::split_host_port;
|
|
116
|
+
use crate::request::{host_key, named_port, split_host_port};
|
|
111
117
|
|
|
112
118
|
let ip: std::net::IpAddr = ip.parse().map_err(|e| {
|
|
113
119
|
magnus::Error::new(ruby.exception_arg_error(), format!("bad ip {ip:?}: {e}"))
|
|
@@ -116,10 +122,14 @@ pub fn env_probe(
|
|
|
116
122
|
env_strings::set_addr_env(ruby, env, ip)?;
|
|
117
123
|
match &authority {
|
|
118
124
|
Some(authority) => {
|
|
119
|
-
|
|
125
|
+
let key = host_key(authority.as_bytes(), named_port(authority).is_some(), 80);
|
|
126
|
+
env_strings::set_authority_env(ruby, env, &key, authority, || {
|
|
127
|
+
split_host_port(authority, 80)
|
|
128
|
+
})?
|
|
120
129
|
}
|
|
121
130
|
None => {
|
|
122
|
-
|
|
131
|
+
let key = host_key(host.as_bytes(), named_port(&host).is_some(), 80);
|
|
132
|
+
env_strings::set_host_env(ruby, env, &key, || split_host_port(&host, 80))?
|
|
123
133
|
}
|
|
124
134
|
}
|
|
125
135
|
let strings = env_strings::get();
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
//! What the crate's tests share: the one test server, a client for the
|
|
2
|
+
//! connections it serves, the lock that runs the tests reading
|
|
3
|
+
//! process-wide counters one at a time, and polling for what another
|
|
4
|
+
//! thread or task does.
|
|
5
|
+
|
|
6
|
+
use std::fmt::Display;
|
|
7
|
+
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|
8
|
+
use std::sync::atomic::AtomicBool;
|
|
9
|
+
use std::sync::Arc;
|
|
10
|
+
use std::time::Duration;
|
|
11
|
+
|
|
12
|
+
use bytes::Bytes;
|
|
13
|
+
use http_body_util::Full;
|
|
14
|
+
use hyper::client::conn::http1::SendRequest;
|
|
15
|
+
use hyper_util::rt::TokioIo;
|
|
16
|
+
use tokio::io::{AsyncRead, AsyncReadExt};
|
|
17
|
+
|
|
18
|
+
use crate::doorbell::Doorbell;
|
|
19
|
+
use crate::gvl::Parker;
|
|
20
|
+
use crate::registry::{BoxedCtx, ServerInner};
|
|
21
|
+
use crate::server::{Peer, ServerConfig, Topology};
|
|
22
|
+
use crate::slot::{WorkerSlot, WS_INBOX};
|
|
23
|
+
|
|
24
|
+
/// Tests that read process-wide counters (sockets, bridges, cut
|
|
25
|
+
/// streams) run one at a time.
|
|
26
|
+
pub static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
|
27
|
+
|
|
28
|
+
/// The peer of a connection no socket carries: a client port on loopback, Kino's default port.
|
|
29
|
+
pub const PEER: Peer = Peer {
|
|
30
|
+
remote: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 40000),
|
|
31
|
+
local: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 9292),
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/// How long `eventually` keeps polling before the test fails.
|
|
35
|
+
const PATIENCE: Duration = Duration::from_secs(5);
|
|
36
|
+
|
|
37
|
+
/// Poll `ready` every millisecond, the way a worker keeps coming back to
|
|
38
|
+
/// its queue, until it yields; panics naming `what` after five seconds,
|
|
39
|
+
/// of the runtime's clock (a paused one advances while this sleeps).
|
|
40
|
+
/// `what` is rendered only then, so a `fmt::from_fn` can show what the
|
|
41
|
+
/// test last saw.
|
|
42
|
+
pub async fn eventually<T>(what: impl Display, mut ready: impl FnMut() -> Option<T>) -> T {
|
|
43
|
+
let deadline = tokio::time::Instant::now() + PATIENCE;
|
|
44
|
+
loop {
|
|
45
|
+
if let Some(value) = ready() {
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
assert!(
|
|
49
|
+
tokio::time::Instant::now() < deadline,
|
|
50
|
+
"timed out waiting for {what}"
|
|
51
|
+
);
|
|
52
|
+
tokio::time::sleep(Duration::from_millis(1)).await;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// `eventually`, for a condition.
|
|
57
|
+
pub async fn until(what: impl Display, mut done: impl FnMut() -> bool) {
|
|
58
|
+
eventually(what, || done().then_some(())).await
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// `eventually` outside a runtime: the calling thread sleeps between
|
|
62
|
+
/// polls.
|
|
63
|
+
pub fn eventually_blocking<T>(what: impl Display, mut ready: impl FnMut() -> Option<T>) -> T {
|
|
64
|
+
let deadline = std::time::Instant::now() + PATIENCE;
|
|
65
|
+
loop {
|
|
66
|
+
if let Some(value) = ready() {
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
assert!(
|
|
70
|
+
std::time::Instant::now() < deadline,
|
|
71
|
+
"timed out waiting for {what}"
|
|
72
|
+
);
|
|
73
|
+
std::thread::sleep(Duration::from_millis(1));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/// What `work` returns, run on its own thread; fails naming `what` if it has not returned
|
|
78
|
+
/// within the patience. A call that blocks a runtime thread cannot be cut short by
|
|
79
|
+
/// `tokio::time::timeout`; this can. A stuck thread is left behind, the test fails.
|
|
80
|
+
pub fn finishes_in_time<T: Send + 'static>(
|
|
81
|
+
what: &str,
|
|
82
|
+
work: impl FnOnce() -> T + Send + 'static,
|
|
83
|
+
) -> T {
|
|
84
|
+
let (done, finished) = std::sync::mpsc::channel();
|
|
85
|
+
std::thread::spawn(move || {
|
|
86
|
+
let _ = done.send(work());
|
|
87
|
+
});
|
|
88
|
+
finished
|
|
89
|
+
.recv_timeout(PATIENCE)
|
|
90
|
+
.unwrap_or_else(|_| panic!("{what} blocked for over {PATIENCE:?}"))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// SERIAL, taken outside a runtime once no socket of an earlier test is
|
|
94
|
+
/// open (its runtime may still be dropping them).
|
|
95
|
+
pub fn serial_blocking() -> tokio::sync::MutexGuard<'static, ()> {
|
|
96
|
+
let serial = SERIAL.blocking_lock();
|
|
97
|
+
eventually_blocking("the sockets of earlier tests to end", || {
|
|
98
|
+
(crate::ws::snapshot().open == 0).then_some(())
|
|
99
|
+
});
|
|
100
|
+
serial
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// The worker slot at `index` of `server`.
|
|
104
|
+
pub fn slot(server: &ServerInner, index: usize) -> Arc<WorkerSlot> {
|
|
105
|
+
server.slots.read()[index].clone()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// The dispatcher's part: a request lands in `slot`'s lane, ringing
|
|
109
|
+
/// its doorbell if a worker_loop worker armed it.
|
|
110
|
+
pub fn assign(slot: &WorkerSlot) {
|
|
111
|
+
let request = crate::registry::LaneItem::Request(crate::request::test_ctx());
|
|
112
|
+
assert!(slot.send_lane(request).is_ok(), "lane open, with room");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// The Parker of tests, which have no VM: a worker's wait runs through
|
|
116
|
+
/// `release`, handed the flag the VM's unblock function raises and the
|
|
117
|
+
/// wait, which it runs or not, and `interrupts` stands for the VM's
|
|
118
|
+
/// pending interrupts.
|
|
119
|
+
pub struct InPlace<R, I> {
|
|
120
|
+
pub release: R,
|
|
121
|
+
pub interrupts: I,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
impl<R, I> Parker for InPlace<R, I>
|
|
125
|
+
where
|
|
126
|
+
R: FnMut(&AtomicBool, &mut dyn FnMut()),
|
|
127
|
+
I: FnMut() -> Result<(), &'static str>,
|
|
128
|
+
{
|
|
129
|
+
type Error = &'static str;
|
|
130
|
+
|
|
131
|
+
fn release<T>(
|
|
132
|
+
&mut self,
|
|
133
|
+
woken: &AtomicBool,
|
|
134
|
+
f: impl FnOnce() -> T,
|
|
135
|
+
) -> Result<Option<T>, Self::Error> {
|
|
136
|
+
let (mut f, mut ran) = (Some(f), None);
|
|
137
|
+
(self.release)(woken, &mut || ran = f.take().map(|f| f()));
|
|
138
|
+
Ok(ran)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
fn check_ints(&mut self) -> Result<(), Self::Error> {
|
|
142
|
+
(self.interrupts)()
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// A ServerInner with no runtime of its own: lane dispatch or the shared
|
|
147
|
+
/// queue, 4 deep, a 10 ms queue timeout, and `workers` worker slots.
|
|
148
|
+
/// Ids are unique, so tests that register theirs can run in parallel.
|
|
149
|
+
pub struct TestServer {
|
|
150
|
+
config: ServerConfig,
|
|
151
|
+
workers: usize,
|
|
152
|
+
inbox: usize,
|
|
153
|
+
capacity: usize,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
impl TestServer {
|
|
157
|
+
/// Requests go to each worker's lane.
|
|
158
|
+
pub fn lanes() -> Self {
|
|
159
|
+
Self::new(true)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/// Requests wait in the shared queue.
|
|
163
|
+
pub fn shared_queue() -> Self {
|
|
164
|
+
Self::new(false)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// Lanes, each worker running its own loop: its slot has a doorbell.
|
|
168
|
+
pub fn worker_loop() -> Self {
|
|
169
|
+
Self::new(true).with(|c| c.worker_loop = true)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
fn new(lanes: bool) -> Self {
|
|
173
|
+
TestServer {
|
|
174
|
+
config: ServerConfig {
|
|
175
|
+
queue_depth: 4,
|
|
176
|
+
queue_timeout_ms: 10,
|
|
177
|
+
http2: true,
|
|
178
|
+
lanes,
|
|
179
|
+
topology: Topology {
|
|
180
|
+
mode: "threaded".to_string(),
|
|
181
|
+
batch: 1,
|
|
182
|
+
..Topology::default()
|
|
183
|
+
},
|
|
184
|
+
..ServerConfig::default()
|
|
185
|
+
},
|
|
186
|
+
workers: 0,
|
|
187
|
+
inbox: WS_INBOX,
|
|
188
|
+
capacity: 0,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
pub fn workers(mut self, count: usize) -> Self {
|
|
193
|
+
self.workers = count;
|
|
194
|
+
self
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// Each worker_loop worker runs up to `jobs` requests at once, as its serve sets it.
|
|
198
|
+
pub fn capacity(mut self, jobs: usize) -> Self {
|
|
199
|
+
self.capacity = jobs;
|
|
200
|
+
self
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// Each worker's WebSocket inbox holds `events`.
|
|
204
|
+
pub fn inbox(mut self, events: usize) -> Self {
|
|
205
|
+
self.inbox = events;
|
|
206
|
+
self
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/// The WebSocket budgets, as `set` changes the defaults.
|
|
210
|
+
pub fn ws(mut self, set: impl FnOnce(&mut crate::ws::Limits)) -> Self {
|
|
211
|
+
let mut limits = crate::ws::Limits::default();
|
|
212
|
+
set(&mut limits);
|
|
213
|
+
self.config.ws = Arc::new(limits);
|
|
214
|
+
self
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/// Any other setting.
|
|
218
|
+
pub fn with(mut self, set: impl FnOnce(&mut ServerConfig)) -> Self {
|
|
219
|
+
set(&mut self.config);
|
|
220
|
+
self
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
pub fn build(self) -> Arc<ServerInner> {
|
|
224
|
+
let (lanes, worker_loop) = (self.config.lanes, self.config.worker_loop);
|
|
225
|
+
let server = Arc::new(ServerInner::new(self.config));
|
|
226
|
+
for _ in 0..self.workers {
|
|
227
|
+
let doorbell = worker_loop.then(|| Doorbell::new().expect("a doorbell"));
|
|
228
|
+
let slot = WorkerSlot::new(lanes, self.inbox, doorbell, server.inline.is_some());
|
|
229
|
+
slot.load.set_capacity(self.capacity);
|
|
230
|
+
server.slots.write().push(Arc::new(slot));
|
|
231
|
+
}
|
|
232
|
+
server
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// Built for a test that serves connections, once no socket of an
|
|
236
|
+
/// earlier one is open (its runtime may still be dropping them), and
|
|
237
|
+
/// registered as a running server is, its bridges on this test's
|
|
238
|
+
/// runtime.
|
|
239
|
+
pub async fn running(self) -> (Arc<ServerInner>, Running) {
|
|
240
|
+
let serial = SERIAL.lock().await;
|
|
241
|
+
until("the sockets of earlier tests to end", || {
|
|
242
|
+
crate::ws::snapshot().open == 0
|
|
243
|
+
})
|
|
244
|
+
.await;
|
|
245
|
+
let server = self.build();
|
|
246
|
+
crate::registry::insert(server.clone());
|
|
247
|
+
let id = server.id;
|
|
248
|
+
(
|
|
249
|
+
server,
|
|
250
|
+
Running {
|
|
251
|
+
_serial: serial,
|
|
252
|
+
id,
|
|
253
|
+
},
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/// What a test serving connections holds until it ends: the lock that
|
|
259
|
+
/// keeps other such tests out, as they read process-wide counts, and its
|
|
260
|
+
/// server's registration.
|
|
261
|
+
pub struct Running {
|
|
262
|
+
_serial: tokio::sync::MutexGuard<'static, ()>,
|
|
263
|
+
id: u64,
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
impl Drop for Running {
|
|
267
|
+
fn drop(&mut self) {
|
|
268
|
+
crate::registry::remove(self.id);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/// A client's response, still on its way.
|
|
273
|
+
pub type Pending = tokio::task::JoinHandle<hyper::Result<hyper::Response<hyper::body::Incoming>>>;
|
|
274
|
+
|
|
275
|
+
/// A GET of `path` with no body.
|
|
276
|
+
pub fn get(path: &str) -> hyper::Request<Full<Bytes>> {
|
|
277
|
+
hyper::Request::get(path)
|
|
278
|
+
.header(http::header::HOST, "kino.test")
|
|
279
|
+
.body(Full::new(Bytes::new()))
|
|
280
|
+
.expect("request")
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/// An HTTP/2 GET of `path`: no Host header, its authority in the URI.
|
|
284
|
+
pub fn h2_get(path: &str) -> hyper::Request<Full<Bytes>> {
|
|
285
|
+
let uri = format!("http://kino.test:8443{path}");
|
|
286
|
+
hyper::Request::get(uri)
|
|
287
|
+
.body(Full::new(Bytes::new()))
|
|
288
|
+
.expect("request")
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/// A request asking to switch to a protocol Kino knows nothing about.
|
|
292
|
+
pub fn upgrade_request() -> hyper::Request<Full<Bytes>> {
|
|
293
|
+
hyper::Request::get("/chat")
|
|
294
|
+
.header(http::header::HOST, "kino.test")
|
|
295
|
+
.header(http::header::UPGRADE, "chat")
|
|
296
|
+
.header(http::header::CONNECTION, "Upgrade")
|
|
297
|
+
.body(Full::new(Bytes::new()))
|
|
298
|
+
.expect("upgrade request")
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/// An app's hijacked answer switching to that protocol.
|
|
302
|
+
pub const SWITCHED: &[u8] =
|
|
303
|
+
b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: chat\r\nConnection: Upgrade\r\n\r\n";
|
|
304
|
+
|
|
305
|
+
/// An HTTP/1.1 client connection to `server`, served the production way.
|
|
306
|
+
pub async fn connect(server: &Arc<ServerInner>) -> SendRequest<Full<Bytes>> {
|
|
307
|
+
let io = TokioIo::new(crate::server::testing::spawn_conn(server.clone()));
|
|
308
|
+
let (sender, conn) = hyper::client::conn::http1::handshake(io)
|
|
309
|
+
.await
|
|
310
|
+
.expect("h1 handshake");
|
|
311
|
+
tokio::spawn(conn.with_upgrades());
|
|
312
|
+
sender
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/// A prior-knowledge HTTP/2 client on `io`: hyper's, which answers the server's PINGs.
|
|
316
|
+
pub async fn h2_client(
|
|
317
|
+
io: tokio::io::DuplexStream,
|
|
318
|
+
) -> hyper::client::conn::http2::SendRequest<Full<Bytes>> {
|
|
319
|
+
let executor = hyper_util::rt::TokioExecutor::new();
|
|
320
|
+
let (sender, conn) = hyper::client::conn::http2::handshake(executor, TokioIo::new(io))
|
|
321
|
+
.await
|
|
322
|
+
.expect("h2 handshake");
|
|
323
|
+
tokio::spawn(conn);
|
|
324
|
+
sender
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// A client sends `request` on a connection of its own.
|
|
328
|
+
pub async fn send(server: &Arc<ServerInner>, request: hyper::Request<Full<Bytes>>) -> Pending {
|
|
329
|
+
let mut sender = connect(server).await;
|
|
330
|
+
tokio::spawn(async move { sender.send_request(request).await })
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// The next request in the shared queue, as a worker takes it.
|
|
334
|
+
pub async fn take_ctx(server: &ServerInner) -> BoxedCtx {
|
|
335
|
+
server.req_rx.recv_async().await.expect("a queued request")
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/// The response `pending` waits for; panics after five seconds.
|
|
339
|
+
pub async fn response_to(pending: Pending) -> hyper::Response<hyper::body::Incoming> {
|
|
340
|
+
tokio::time::timeout(PATIENCE, pending)
|
|
341
|
+
.await
|
|
342
|
+
.expect("no response within 5s")
|
|
343
|
+
.expect("join")
|
|
344
|
+
.expect("a response")
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/// An HTTP/1 head off the wire, up to its blank line; panics after five
|
|
348
|
+
/// seconds.
|
|
349
|
+
pub async fn read_head(io: &mut (impl AsyncRead + Unpin)) -> String {
|
|
350
|
+
let mut head = Vec::new();
|
|
351
|
+
let read = async {
|
|
352
|
+
while !head.ends_with(b"\r\n\r\n") {
|
|
353
|
+
head.push(io.read_u8().await.expect("the rest of a head"));
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
tokio::time::timeout(PATIENCE, read)
|
|
357
|
+
.await
|
|
358
|
+
.expect("no head within 5s");
|
|
359
|
+
String::from_utf8(head).expect("an ASCII head")
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/// Everything until the other end closes; panics naming `what` if it
|
|
363
|
+
/// stays open past five seconds.
|
|
364
|
+
pub async fn read_to_close(io: &mut (impl AsyncRead + Unpin + ?Sized), what: &str) -> Vec<u8> {
|
|
365
|
+
let mut bytes = Vec::new();
|
|
366
|
+
tokio::time::timeout(PATIENCE, io.read_to_end(&mut bytes))
|
|
367
|
+
.await
|
|
368
|
+
.unwrap_or_else(|_| panic!("{what}: still open after 5s"))
|
|
369
|
+
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
|
370
|
+
bytes
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/// A max_connections permit of a connection's own, for a test that does
|
|
374
|
+
/// not count them.
|
|
375
|
+
pub fn permit() -> tokio::sync::OwnedSemaphorePermit {
|
|
376
|
+
let permits = Arc::new(tokio::sync::Semaphore::new(1));
|
|
377
|
+
permits.try_acquire_owned().expect("a permit")
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/// `scenario` on a runtime of its own, which must finish `within`, as
|
|
381
|
+
/// the calling thread's clock tells: a task that spins a worker then
|
|
382
|
+
/// fails the test, where the runtime's timers could stall (the other
|
|
383
|
+
/// worker asleep, none driving them), and dropping it would wait on the
|
|
384
|
+
/// spinning thread for good.
|
|
385
|
+
pub fn on_own_runtime(
|
|
386
|
+
what: impl Display,
|
|
387
|
+
within: Duration,
|
|
388
|
+
scenario: impl std::future::Future<Output = ()> + Send + 'static,
|
|
389
|
+
) {
|
|
390
|
+
let runtime = tokio::runtime::Builder::new_multi_thread()
|
|
391
|
+
.worker_threads(2)
|
|
392
|
+
.enable_all()
|
|
393
|
+
.build()
|
|
394
|
+
.expect("a runtime");
|
|
395
|
+
let scenario = runtime.spawn(scenario);
|
|
396
|
+
let deadline = std::time::Instant::now() + within;
|
|
397
|
+
while !scenario.is_finished() && std::time::Instant::now() < deadline {
|
|
398
|
+
std::thread::sleep(Duration::from_millis(5));
|
|
399
|
+
}
|
|
400
|
+
if !scenario.is_finished() {
|
|
401
|
+
runtime.shutdown_background();
|
|
402
|
+
panic!("{what}: not done {within:?} on");
|
|
403
|
+
}
|
|
404
|
+
let done = runtime.block_on(scenario);
|
|
405
|
+
runtime.shutdown_background();
|
|
406
|
+
if let Err(failed) = done {
|
|
407
|
+
std::panic::resume_unwind(failed.into_panic());
|
|
408
|
+
}
|
|
409
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
//! worker_loop's lane tick. A doorbell wait has no timeout, which would cost the app's scheduler
|
|
2
|
+
//! a timer per wait: instead one thread per server rings every armed doorbell each TICK, and
|
|
3
|
+
//! the take that answers (queue::Taker::nonblock) does what a parked classic worker's tick does.
|
|
4
|
+
//! The same look cuts off inline connections past their deadline (inline::tick).
|
|
5
|
+
|
|
6
|
+
use std::sync::{Arc, Weak};
|
|
7
|
+
use std::time::Instant;
|
|
8
|
+
|
|
9
|
+
use crate::queue::TICK;
|
|
10
|
+
use crate::registry::ServerInner;
|
|
11
|
+
|
|
12
|
+
pub struct Ticker {
|
|
13
|
+
/// Never sent on: the thread runs until this goes.
|
|
14
|
+
stop: flume::Sender<()>,
|
|
15
|
+
thread: std::thread::JoinHandle<()>,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
impl Ticker {
|
|
19
|
+
pub fn start(server: &Arc<ServerInner>) -> std::io::Result<Ticker> {
|
|
20
|
+
let (stop, stopped) = flume::bounded(0);
|
|
21
|
+
let server = Arc::downgrade(server);
|
|
22
|
+
let thread = std::thread::Builder::new()
|
|
23
|
+
.name("kino-ticker".to_string())
|
|
24
|
+
.spawn(move || run(&server, &stopped))?;
|
|
25
|
+
Ok(Ticker { stop, thread })
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
pub fn stop(self) {
|
|
29
|
+
drop(self.stop);
|
|
30
|
+
let _ = self.thread.join();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// A tick that fell behind (the process was suspended) starts over from now, not catching up.
|
|
35
|
+
fn run(server: &Weak<ServerInner>, stopped: &flume::Receiver<()>) {
|
|
36
|
+
let mut next = Instant::now() + TICK;
|
|
37
|
+
while let Err(flume::RecvTimeoutError::Timeout) = stopped.recv_deadline(next) {
|
|
38
|
+
let Some(server) = server.upgrade() else {
|
|
39
|
+
return;
|
|
40
|
+
};
|
|
41
|
+
for slot in server.slots.read().iter() {
|
|
42
|
+
slot.lane.ring_doorbell();
|
|
43
|
+
}
|
|
44
|
+
crate::inline::tick(&server);
|
|
45
|
+
next += TICK;
|
|
46
|
+
let now = Instant::now();
|
|
47
|
+
if next <= now {
|
|
48
|
+
next = now + TICK;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
#[cfg(test)]
|
|
54
|
+
mod tests {
|
|
55
|
+
use std::time::Duration;
|
|
56
|
+
|
|
57
|
+
use super::*;
|
|
58
|
+
use crate::server::HEADER_READ_TIMEOUT;
|
|
59
|
+
|
|
60
|
+
/// Long enough for a ring due within a TICK on a loaded CI runner, which
|
|
61
|
+
/// can be 100 ms late. A cut that never comes fails at the client's 5 s
|
|
62
|
+
/// read timeout.
|
|
63
|
+
const A_FEW_TICKS: Duration = Duration::from_millis(10 * TICK.as_millis() as u64);
|
|
64
|
+
|
|
65
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
66
|
+
async fn it_cuts_off_an_inline_connection_within_a_tick_of_its_deadline() {
|
|
67
|
+
let server = crate::inline::testing::inline_loop_server(1, 8);
|
|
68
|
+
let (client, _conn) = crate::inline::testing::loopback(&server);
|
|
69
|
+
let ticker = Ticker::start(&server).expect("the ticker thread");
|
|
70
|
+
|
|
71
|
+
// Its deadline is 100 ms off: the ticker's clock runs on to it.
|
|
72
|
+
let left = Duration::from_millis(100);
|
|
73
|
+
crate::inline::testing::advance(&server, HEADER_READ_TIMEOUT - left);
|
|
74
|
+
let advanced = Instant::now();
|
|
75
|
+
assert_eq!(
|
|
76
|
+
crate::inline::testing::read_to_end(&client),
|
|
77
|
+
b"",
|
|
78
|
+
"a connection that sent nothing got an answer"
|
|
79
|
+
);
|
|
80
|
+
assert!(
|
|
81
|
+
advanced.elapsed() < left + A_FEW_TICKS,
|
|
82
|
+
"cut off {:?} after its deadline",
|
|
83
|
+
advanced.elapsed().saturating_sub(left)
|
|
84
|
+
);
|
|
85
|
+
ticker.stop();
|
|
86
|
+
}
|
|
87
|
+
}
|
data/ext/kino/src/timer.rs
CHANGED
|
@@ -7,14 +7,14 @@
|
|
|
7
7
|
//! Only one bounded chunk is slept per call: the caller (Kino.sleep in
|
|
8
8
|
//! Ruby) loops, so pending VM interrupts are processed between chunks and
|
|
9
9
|
//! Thread#kill / shutdown stay responsive within one tick.
|
|
10
|
+
//! What one raises comes back as an error from the chunk (gvl::released).
|
|
10
11
|
|
|
11
|
-
use std::ffi::c_void;
|
|
12
12
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
13
13
|
use std::time::{Duration, Instant};
|
|
14
14
|
|
|
15
15
|
use magnus::{Error, Ruby};
|
|
16
16
|
|
|
17
|
-
use crate::gvl
|
|
17
|
+
use crate::gvl;
|
|
18
18
|
|
|
19
19
|
/// Sleep up to `seconds` (capped at one interrupt tick), GVL released.
|
|
20
20
|
/// Returns the seconds actually remaining after this chunk (0.0 = done),
|
|
@@ -32,7 +32,7 @@ pub fn sleep_chunk(ruby: &Ruby, seconds: f64) -> Result<f64, Error> {
|
|
|
32
32
|
let deadline = Instant::now() + chunk;
|
|
33
33
|
|
|
34
34
|
let interrupted = AtomicBool::new(false);
|
|
35
|
-
gvl::
|
|
35
|
+
gvl::released(
|
|
36
36
|
|| {
|
|
37
37
|
// std::thread::sleep retries on EINTR, so the UBF can't cut a
|
|
38
38
|
// sleep short: the flag is only observed once the chunk ends.
|
|
@@ -46,10 +46,7 @@ pub fn sleep_chunk(ruby: &Ruby, seconds: f64) -> Result<f64, Error> {
|
|
|
46
46
|
std::thread::sleep(deadline - now);
|
|
47
47
|
}
|
|
48
48
|
},
|
|
49
|
-
Some(
|
|
50
|
-
func: gvl::ubf_interrupt,
|
|
51
|
-
data: &interrupted as *const _ as *mut c_void,
|
|
52
|
-
}),
|
|
49
|
+
Some(&interrupted),
|
|
53
50
|
)?;
|
|
54
51
|
|
|
55
52
|
let remaining = requested.saturating_sub(chunk);
|