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,131 @@
|
|
|
1
|
+
//! The request heads served inline: a strict subset of HTTP/1.1, read with httparse. Anything
|
|
2
|
+
//! else goes back to hyper, whose own rules then decide.
|
|
3
|
+
|
|
4
|
+
use bytes::Bytes;
|
|
5
|
+
use smallvec::SmallVec;
|
|
6
|
+
|
|
7
|
+
use crate::framing::{digits, tokens, MAX_HEADERS};
|
|
8
|
+
|
|
9
|
+
/// The longest head served inline; a longer one goes back to hyper.
|
|
10
|
+
pub const HEAD_MAX: usize = 16 * 1024;
|
|
11
|
+
/// The longest request body hyper frames by its length.
|
|
12
|
+
const LENGTH_MAX: u64 = u64::MAX - 2;
|
|
13
|
+
|
|
14
|
+
pub type Span = (usize, usize);
|
|
15
|
+
|
|
16
|
+
/// A complete head the subset covers, as offsets into its buffer.
|
|
17
|
+
pub struct Head {
|
|
18
|
+
/// Its length in bytes, the empty line included.
|
|
19
|
+
pub len: usize,
|
|
20
|
+
pub method: http::Method,
|
|
21
|
+
pub path: Span,
|
|
22
|
+
pub headers: SmallVec<[(Span, Span); 24]>,
|
|
23
|
+
pub close: bool,
|
|
24
|
+
/// Its body's length: Content-Length, or 0 without one.
|
|
25
|
+
pub content_length: u64,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// On the stack, one per look: boxing the head would allocate per request.
|
|
29
|
+
#[allow(clippy::large_enum_variant)]
|
|
30
|
+
pub enum Parsed {
|
|
31
|
+
Partial,
|
|
32
|
+
/// Outside the subset: hyper's to read.
|
|
33
|
+
Refused,
|
|
34
|
+
Head(Head),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// The head at the start of `buf`, if complete and in the subset: HTTP/1.1, origin-form, no
|
|
38
|
+
/// Transfer-Encoding, Expect or protocol switch (CONNECT included), at most one all-digits
|
|
39
|
+
/// Content-Length up to LENGTH_MAX, and at most MAX_HEADERS headers.
|
|
40
|
+
pub fn parse_head(buf: &[u8]) -> Parsed {
|
|
41
|
+
let mut slots = [httparse::EMPTY_HEADER; MAX_HEADERS];
|
|
42
|
+
let mut req = httparse::Request::new(&mut slots);
|
|
43
|
+
let len = match req.parse(buf) {
|
|
44
|
+
Ok(httparse::Status::Complete(len)) => len,
|
|
45
|
+
Ok(httparse::Status::Partial) => return Parsed::Partial,
|
|
46
|
+
Err(_) => return Parsed::Refused,
|
|
47
|
+
};
|
|
48
|
+
let (Some(method), Some(path), Some(version)) = (req.method, req.path, req.version) else {
|
|
49
|
+
return Parsed::Refused;
|
|
50
|
+
};
|
|
51
|
+
let Ok(method) = http::Method::from_bytes(method.as_bytes()) else {
|
|
52
|
+
return Parsed::Refused;
|
|
53
|
+
};
|
|
54
|
+
let base = buf.as_ptr() as usize;
|
|
55
|
+
let at = |part: &[u8]| {
|
|
56
|
+
let start = part.as_ptr() as usize - base;
|
|
57
|
+
(start, start + part.len())
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
let (mut chunked, mut expect, mut close) = (false, false, false);
|
|
61
|
+
// hyper holds a CONNECT's connection for a tunnel, as an Upgrade's.
|
|
62
|
+
let mut upgrade = method == http::Method::CONNECT;
|
|
63
|
+
let mut lengths = 0;
|
|
64
|
+
let mut content_length = Some(0);
|
|
65
|
+
let mut headers = SmallVec::new();
|
|
66
|
+
for header in req.headers.iter() {
|
|
67
|
+
let (name, value) = (header.name, header.value);
|
|
68
|
+
if name.eq_ignore_ascii_case("transfer-encoding") {
|
|
69
|
+
chunked = true;
|
|
70
|
+
} else if name.eq_ignore_ascii_case("content-length") {
|
|
71
|
+
lengths += 1;
|
|
72
|
+
content_length = digits(value).filter(|&length| length <= LENGTH_MAX);
|
|
73
|
+
} else if name.eq_ignore_ascii_case("expect") {
|
|
74
|
+
expect = true;
|
|
75
|
+
} else if name.eq_ignore_ascii_case("upgrade")
|
|
76
|
+
|| name.eq_ignore_ascii_case("http2-settings")
|
|
77
|
+
{
|
|
78
|
+
upgrade = true;
|
|
79
|
+
} else if name.eq_ignore_ascii_case("connection") {
|
|
80
|
+
for token in tokens(value) {
|
|
81
|
+
// hyper reads no close in a value that is not visible ASCII.
|
|
82
|
+
close |= token.eq_ignore_ascii_case(b"close") && value.is_ascii();
|
|
83
|
+
upgrade |= token.eq_ignore_ascii_case(b"upgrade");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
headers.push((at(name.as_bytes()), at(value)));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Every header was looked at; the first refusal in this order wins.
|
|
90
|
+
if version != 1 {
|
|
91
|
+
return Parsed::Refused;
|
|
92
|
+
}
|
|
93
|
+
if !path.starts_with('/') {
|
|
94
|
+
return Parsed::Refused;
|
|
95
|
+
}
|
|
96
|
+
if chunked {
|
|
97
|
+
return Parsed::Refused;
|
|
98
|
+
}
|
|
99
|
+
let (0..=1, Some(content_length)) = (lengths, content_length) else {
|
|
100
|
+
return Parsed::Refused;
|
|
101
|
+
};
|
|
102
|
+
if expect {
|
|
103
|
+
return Parsed::Refused;
|
|
104
|
+
}
|
|
105
|
+
if upgrade {
|
|
106
|
+
return Parsed::Refused;
|
|
107
|
+
}
|
|
108
|
+
Parsed::Head(Head {
|
|
109
|
+
len,
|
|
110
|
+
method,
|
|
111
|
+
path: at(path.as_bytes()),
|
|
112
|
+
headers,
|
|
113
|
+
close,
|
|
114
|
+
content_length,
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
impl Head {
|
|
119
|
+
/// Its target and headers, from a copy of the bytes `head` was parsed from, which the values
|
|
120
|
+
/// share. The http crate's own checks refuse what httparse let through.
|
|
121
|
+
pub fn parts(&self, head: &Bytes) -> Option<(http::Uri, http::HeaderMap)> {
|
|
122
|
+
let uri = http::Uri::from_maybe_shared(head.slice(self.path.0..self.path.1)).ok()?;
|
|
123
|
+
let mut headers = http::HeaderMap::with_capacity(self.headers.len());
|
|
124
|
+
for &((n0, n1), (v0, v1)) in &self.headers {
|
|
125
|
+
let name = http::HeaderName::from_bytes(&head[n0..n1]).ok()?;
|
|
126
|
+
let value = http::HeaderValue::from_maybe_shared(head.slice(v0..v1)).ok()?;
|
|
127
|
+
headers.append(name, value);
|
|
128
|
+
}
|
|
129
|
+
Some((uri, headers))
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
//! The inline spin: once its answer is out, the job of a connection alone on its worker looks at
|
|
2
|
+
//! the socket for up to BUDGET, GVL released, before it waits on the app's scheduler, so a next
|
|
3
|
+
//! request sent at once is read without a park and a wake. Catch runs are bounded (Run), and a
|
|
4
|
+
//! client that keeps coming late backs the spin off (Backoff). See doc/architecture.md.
|
|
5
|
+
|
|
6
|
+
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
7
|
+
use std::time::{Duration, Instant};
|
|
8
|
+
|
|
9
|
+
use crate::gvl::Parker;
|
|
10
|
+
use crate::registry::ServerInner;
|
|
11
|
+
use crate::slot::WorkerSlot;
|
|
12
|
+
|
|
13
|
+
/// Past this many requests in flight server-wide a spinner would hold a CPU the busy threads
|
|
14
|
+
/// need: each keeps up to two threads busy, so half the CPUs' worth leave CPUs for the spinners.
|
|
15
|
+
pub(super) fn in_flight_limit(cpus: usize) -> usize {
|
|
16
|
+
(cpus / 2).max(1)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ONE: u16 = 1024;
|
|
20
|
+
|
|
21
|
+
/// 9/16: a spinner whose waits alternate quick and late peaks at 547 just after a quick one,
|
|
22
|
+
/// and backs off; at 1/2 it would spin before each late one only.
|
|
23
|
+
const SPIN_AT: u16 = ONE * 9 / 16;
|
|
24
|
+
|
|
25
|
+
const PROBE: u8 = 32;
|
|
26
|
+
|
|
27
|
+
const SEEN_MISS: u32 = 2;
|
|
28
|
+
|
|
29
|
+
/// How a spin ended.
|
|
30
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
31
|
+
pub(crate) enum Spin {
|
|
32
|
+
/// Its client's bytes or close came within the budget.
|
|
33
|
+
Hit,
|
|
34
|
+
Miss,
|
|
35
|
+
/// The gate shut, or the VM's unblock function fired.
|
|
36
|
+
Stopped,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// When a connection's spins pay: it spins while its share of hits (in 1/ONE, each chance
|
|
40
|
+
/// weighing 1/8) is at least SPIN_AT, else once in PROBE chances. A skipped chance is judged by
|
|
41
|
+
/// when what it waited for came (observed): within the budget a hit, past SEEN_MISS budgets a
|
|
42
|
+
/// miss. Its connection's job alone reads and writes it.
|
|
43
|
+
pub(crate) struct Backoff {
|
|
44
|
+
share: u16,
|
|
45
|
+
skipped: u8,
|
|
46
|
+
/// When its last skipped chance was, in mono µs; 0 once judged.
|
|
47
|
+
skipped_at: u64,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
impl Default for Backoff {
|
|
51
|
+
fn default() -> Self {
|
|
52
|
+
Backoff {
|
|
53
|
+
share: ONE,
|
|
54
|
+
skipped: 0,
|
|
55
|
+
skipped_at: 0,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
impl Backoff {
|
|
61
|
+
/// Whether this chance spins; one it skips is stamped, for observed.
|
|
62
|
+
pub(crate) fn chance(&mut self) -> bool {
|
|
63
|
+
if self.share >= SPIN_AT || self.skipped + 1 >= PROBE {
|
|
64
|
+
(self.skipped, self.skipped_at) = (0, 0);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
self.skipped += 1;
|
|
68
|
+
self.skipped_at = crate::mono::mono_us().max(1);
|
|
69
|
+
false
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/// Whether the spin that ended as `spun` caught what it waited for; a stop counts neither
|
|
73
|
+
/// way.
|
|
74
|
+
pub(crate) fn record(&mut self, spun: Spin) -> bool {
|
|
75
|
+
if spun != Spin::Stopped {
|
|
76
|
+
self.share = counted(self.share, spun == Spin::Hit);
|
|
77
|
+
}
|
|
78
|
+
spun == Spin::Hit
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
pub(crate) fn observed(&mut self, budget: Duration) {
|
|
82
|
+
if self.skipped_at != 0 {
|
|
83
|
+
let seen = crate::mono::mono_us().saturating_sub(self.skipped_at);
|
|
84
|
+
let seen = Duration::from_micros(seen);
|
|
85
|
+
if seen <= budget {
|
|
86
|
+
self.share = counted(self.share, true);
|
|
87
|
+
} else if seen > budget * SEEN_MISS {
|
|
88
|
+
self.share = counted(self.share, false);
|
|
89
|
+
}
|
|
90
|
+
self.skipped_at = 0;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// The eighth is rounded to the nearest unit, so rounding favours neither side.
|
|
96
|
+
fn counted(hits: u16, hit: bool) -> u16 {
|
|
97
|
+
hits - (hits + 4) / 8 + if hit { ONE / 8 } else { 0 }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// Whether the server's inline connections may spin at all: on (ServerConfig::inline_spin) and
|
|
101
|
+
/// not draining.
|
|
102
|
+
fn on(server: &ServerInner) -> bool {
|
|
103
|
+
let inline = server.inline.as_ref();
|
|
104
|
+
inline.is_some_and(|inline| inline.spin_on.load(Ordering::Relaxed))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// Whether a spin may go on: on, and the server lightly loaded.
|
|
108
|
+
#[inline]
|
|
109
|
+
fn lightly_loaded(server: &ServerInner) -> bool {
|
|
110
|
+
server.inline.as_ref().is_some_and(|inline| {
|
|
111
|
+
inline.spin_on.load(Ordering::Relaxed)
|
|
112
|
+
&& server.counters.in_flight.load(Ordering::Relaxed) <= inline.spin_in_flight
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
pub(crate) const BUDGET: Duration = Duration::from_micros(100);
|
|
117
|
+
|
|
118
|
+
/// Past this many reads in a row through spins, or this long since the job's last wait, a catch
|
|
119
|
+
/// is left to the job's wait: the bound on how long the worker's other fibers wait for a pass.
|
|
120
|
+
const RUN_HITS: u32 = 16;
|
|
121
|
+
pub(crate) const RUN: Duration = Duration::from_millis(1);
|
|
122
|
+
|
|
123
|
+
/// The gate's costlier checks (WorkerSlot::has_waiting) run once in this many passes.
|
|
124
|
+
const WAITING_EVERY: u32 = 8;
|
|
125
|
+
|
|
126
|
+
#[derive(Default)]
|
|
127
|
+
pub(super) struct Run {
|
|
128
|
+
/// From the job's return from that wait if a spin could follow then, else its first hit.
|
|
129
|
+
since: Option<Instant>,
|
|
130
|
+
hits: u32,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
impl Run {
|
|
134
|
+
/// The job came back from a wait; the clock is read only where a spin may follow.
|
|
135
|
+
pub(super) fn waited(&mut self, server: &ServerInner, slot: &WorkerSlot) {
|
|
136
|
+
self.hits = 0;
|
|
137
|
+
self.since =
|
|
138
|
+
(slot.inline.conns.load(Ordering::Relaxed) == 1 && on(server)).then(Instant::now);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// A spin caught the next request: whether the job reads it now or leaves it to its wait.
|
|
142
|
+
pub(super) fn reads(&mut self, run: Duration) -> bool {
|
|
143
|
+
let since = *self.since.get_or_insert_with(Instant::now);
|
|
144
|
+
self.hits += 1;
|
|
145
|
+
self.hits <= RUN_HITS && since.elapsed() < run
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// At most spin_in_flight; on its own cache line, as each spin changes it twice.
|
|
150
|
+
#[derive(Default)]
|
|
151
|
+
#[repr(align(128))]
|
|
152
|
+
pub(crate) struct Spinners(AtomicUsize);
|
|
153
|
+
|
|
154
|
+
impl Spinners {
|
|
155
|
+
/// One more spinning, while fewer than `most` do: held until it drops.
|
|
156
|
+
pub(crate) fn join(&self, most: usize) -> Option<Spinning<'_>> {
|
|
157
|
+
if self.0.fetch_add(1, Ordering::Relaxed) >= most {
|
|
158
|
+
self.0.fetch_sub(1, Ordering::Relaxed);
|
|
159
|
+
return None;
|
|
160
|
+
}
|
|
161
|
+
Some(Spinning(&self.0))
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
pub(crate) struct Spinning<'a>(&'a AtomicUsize);
|
|
166
|
+
|
|
167
|
+
impl Drop for Spinning<'_> {
|
|
168
|
+
fn drop(&mut self) {
|
|
169
|
+
self.0.fetch_sub(1, Ordering::Relaxed);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/// Runs the spin it is given, the unblock function raising the flag; None if it did not run.
|
|
174
|
+
pub(crate) type Release<'a> = dyn FnMut(&AtomicBool, &mut dyn FnMut() -> Spin) -> Option<Spin> + 'a;
|
|
175
|
+
|
|
176
|
+
/// With the GVL released, so other Ruby threads run and the VM's barriers never wait on it; not
|
|
177
|
+
/// at all with an interrupt pending. A panic reads as no spin.
|
|
178
|
+
pub(crate) fn released(woken: &AtomicBool, spin: &mut dyn FnMut() -> Spin) -> Option<Spin> {
|
|
179
|
+
crate::gvl::Released.release(woken, spin).ok().flatten()
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
pub(super) fn poll(
|
|
183
|
+
fd: std::os::fd::RawFd,
|
|
184
|
+
budget: Duration,
|
|
185
|
+
woken: &AtomicBool,
|
|
186
|
+
server: &ServerInner,
|
|
187
|
+
slot: &WorkerSlot,
|
|
188
|
+
) -> Spin {
|
|
189
|
+
let start = Instant::now();
|
|
190
|
+
for pass in 1u32.. {
|
|
191
|
+
if super::io::poll_for(fd, libc::POLLIN, 0).is_some() {
|
|
192
|
+
return Spin::Hit;
|
|
193
|
+
}
|
|
194
|
+
if start.elapsed() >= budget {
|
|
195
|
+
return Spin::Miss;
|
|
196
|
+
}
|
|
197
|
+
// `woken` is the release's own flag, for the VM's unblock function; the slot's halt is
|
|
198
|
+
// Kino's alone, read beside it.
|
|
199
|
+
if woken.load(Ordering::Relaxed)
|
|
200
|
+
|| slot.life.halted().load(Ordering::Relaxed)
|
|
201
|
+
|| !going(server, slot)
|
|
202
|
+
|| (pass.is_multiple_of(WAITING_EVERY) && slot.lane.has_waiting())
|
|
203
|
+
{
|
|
204
|
+
return Spin::Stopped;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
Spin::Miss
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// The connection is alone on `slot`'s worker, which has nothing open or waiting and is neither
|
|
211
|
+
/// retired nor quarantined, and the server is lightly loaded.
|
|
212
|
+
pub(super) fn may_spin(server: &ServerInner, slot: &WorkerSlot) -> bool {
|
|
213
|
+
going(server, slot) && !slot.lane.has_waiting()
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
fn going(server: &ServerInner, slot: &WorkerSlot) -> bool {
|
|
217
|
+
slot.inline.conns.load(Ordering::Relaxed) == 1
|
|
218
|
+
&& lightly_loaded(server)
|
|
219
|
+
&& slot.load.in_flight.load(Ordering::Relaxed) == 0
|
|
220
|
+
&& !slot.lane.wake_pending.load(Ordering::Relaxed)
|
|
221
|
+
&& !slot.life.seems_retired()
|
|
222
|
+
&& !slot.life.quarantined()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#[cfg(test)]
|
|
226
|
+
mod tests {
|
|
227
|
+
use std::net::TcpStream;
|
|
228
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
229
|
+
use std::sync::Arc;
|
|
230
|
+
use std::time::{Duration, Instant};
|
|
231
|
+
|
|
232
|
+
use super::Spin;
|
|
233
|
+
use crate::inline::testing::{
|
|
234
|
+
answer, answer_dispatched, await_bytes, handbacks, loopback, placed, send_get,
|
|
235
|
+
spinning_server, wedge, Wire,
|
|
236
|
+
};
|
|
237
|
+
use crate::inline::{InlineConn, Next};
|
|
238
|
+
use crate::registry::{BoxedCtx, ServerInner};
|
|
239
|
+
use crate::slot::WorkerSlot;
|
|
240
|
+
use crate::testing::{eventually_blocking, slot};
|
|
241
|
+
|
|
242
|
+
/// The spin's switch, as boot and the drain set it.
|
|
243
|
+
fn spin_on(server: &ServerInner, on: bool) {
|
|
244
|
+
let inline = server.inline.as_ref().expect("an inline server");
|
|
245
|
+
inline.spin_on.store(on, Ordering::Relaxed);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/// Far longer than any test waits: a look still spinning when a test
|
|
249
|
+
/// checks fails it.
|
|
250
|
+
const LONG: Duration = Duration::from_secs(20);
|
|
251
|
+
/// How soon a spin must let go once it has to.
|
|
252
|
+
const PROMPTLY: Duration = Duration::from_secs(1);
|
|
253
|
+
|
|
254
|
+
/// A spin's release in place, as on a thread with no GVL to release.
|
|
255
|
+
fn in_place(_: &AtomicBool, spin: &mut dyn FnMut() -> Spin) -> Option<Spin> {
|
|
256
|
+
Some(spin())
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/// How many spins `server`'s connections ended since `before`; None
|
|
260
|
+
/// for all so far.
|
|
261
|
+
fn spun_since(server: &ServerInner, before: Option<u64>) -> u64 {
|
|
262
|
+
crate::inline::testing::inline_stats(server).spins - before.unwrap_or(0)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/// The request `conn`'s job reads once its client's bytes are there,
|
|
266
|
+
/// its looks spinning in place.
|
|
267
|
+
fn request_on(conn: &mut InlineConn) -> BoxedCtx {
|
|
268
|
+
await_bytes(conn);
|
|
269
|
+
eventually_blocking("the request", || {
|
|
270
|
+
match conn.next_with(true, &mut in_place) {
|
|
271
|
+
Next::Request(ctx) => Some(ctx),
|
|
272
|
+
Next::Readable => None,
|
|
273
|
+
Next::Writable | Next::Closed => panic!("no request came"),
|
|
274
|
+
}
|
|
275
|
+
})
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/// `ctx` answered, and its answer read by `client`.
|
|
279
|
+
fn answered(ctx: &BoxedCtx, client: &TcpStream) {
|
|
280
|
+
let path = ctx.uri.path().to_string();
|
|
281
|
+
answer(ctx, path.as_bytes());
|
|
282
|
+
assert_eq!(Wire::of(client).response().2, path.as_bytes());
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// A server of `workers` workers whose connections' jobs spin for
|
|
286
|
+
/// LONG, the spin's gate open, and a connection alone on its
|
|
287
|
+
/// worker that has served a request: its job's next look spins.
|
|
288
|
+
fn alone_after_a_request(workers: usize) -> (Arc<ServerInner>, TcpStream, Box<InlineConn>) {
|
|
289
|
+
let server = spinning_server(workers, LONG);
|
|
290
|
+
let (client, mut conn) = loopback(&server);
|
|
291
|
+
send_get(&client, "/first", false);
|
|
292
|
+
answered(&request_on(&mut conn), &client);
|
|
293
|
+
(server, client, conn)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
297
|
+
async fn a_lone_connections_job_waits_through_the_scheduler_every_16_requests() {
|
|
298
|
+
// Requests that are there as each look spins: the job reads 16
|
|
299
|
+
// in a row through its spins, then the 17th waits, its request
|
|
300
|
+
// unread, for the scheduler to resume the job, which reads it.
|
|
301
|
+
let (server, client, mut conn) = alone_after_a_request(1);
|
|
302
|
+
let mut caught = 0;
|
|
303
|
+
for i in 0..40 {
|
|
304
|
+
send_get(&client, &format!("/{i}"), false);
|
|
305
|
+
await_bytes(&conn);
|
|
306
|
+
let before = Some(spun_since(&server, None));
|
|
307
|
+
let ctx = match conn.next_with(true, &mut in_place) {
|
|
308
|
+
Next::Request(ctx) => {
|
|
309
|
+
caught += 1;
|
|
310
|
+
assert!(caught <= 16, "{caught} requests read without a wait");
|
|
311
|
+
ctx
|
|
312
|
+
}
|
|
313
|
+
Next::Readable => {
|
|
314
|
+
assert_eq!(caught, 16, "request {i} waited after {caught}");
|
|
315
|
+
assert!(conn.readable(), "request {i} was read before the wait");
|
|
316
|
+
caught = 0;
|
|
317
|
+
request_on(&mut conn)
|
|
318
|
+
}
|
|
319
|
+
_ => panic!("the connection ended"),
|
|
320
|
+
};
|
|
321
|
+
let spun = spun_since(&server, before);
|
|
322
|
+
assert_eq!(spun, 1, "request {i} came with no spin");
|
|
323
|
+
answered(&ctx, &client);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
328
|
+
async fn a_lone_connections_job_spins_only_while_its_worker_has_nothing_else_to_do() {
|
|
329
|
+
type Set = fn(&Arc<ServerInner>, &Arc<WorkerSlot>) -> Box<dyn std::any::Any>;
|
|
330
|
+
type Then = fn(&Next) -> bool;
|
|
331
|
+
let readable: Then = |next| matches!(next, Next::Readable);
|
|
332
|
+
let closed: Then = |next| matches!(next, Next::Closed);
|
|
333
|
+
// What holds as the look begins, so that it never spins; or what
|
|
334
|
+
// comes as it spins, which stops it, and what the look then finds.
|
|
335
|
+
#[rustfmt::skip] // One row per line: a table of conditions.
|
|
336
|
+
let rows: [(&str, bool, Set, Then); 7] = [
|
|
337
|
+
("another connection on its worker", false, |server, _| Box::new(loopback(server)), readable),
|
|
338
|
+
("a request open on its worker", false, |server, slot| {
|
|
339
|
+
crate::testing::assign(slot);
|
|
340
|
+
Box::new(crate::queue::testing::admit_next(server, slot))
|
|
341
|
+
}, readable),
|
|
342
|
+
("the spin off, as on one CPU", false, |server, _| {
|
|
343
|
+
spin_on(server, false);
|
|
344
|
+
Box::new(())
|
|
345
|
+
}, readable),
|
|
346
|
+
("a second connection placed on its worker", true, |server, _| Box::new(placed(server)), readable),
|
|
347
|
+
("a request sent to its worker", true, |_, slot| { crate::testing::assign(slot); Box::new(()) }, readable),
|
|
348
|
+
("the drain", true, |server, _| { server.stop_accepting(); Box::new(()) }, closed),
|
|
349
|
+
("its worker given up on as wedged", true, |_, slot| {
|
|
350
|
+
wedge(slot);
|
|
351
|
+
Box::new(())
|
|
352
|
+
}, closed),
|
|
353
|
+
];
|
|
354
|
+
for (what, during, set, then) in rows {
|
|
355
|
+
let (server, _client, conn) = alone_after_a_request(1);
|
|
356
|
+
let slot = slot(&server, 0);
|
|
357
|
+
let before = Some(spun_since(&server, None));
|
|
358
|
+
let (started, spinning) = std::sync::mpsc::channel();
|
|
359
|
+
let held = (!during).then(|| set(&server, &slot));
|
|
360
|
+
let look = std::thread::spawn(move || {
|
|
361
|
+
let mut conn = conn;
|
|
362
|
+
let begun = Instant::now();
|
|
363
|
+
let next = conn.next_with(true, &mut |_, spin| {
|
|
364
|
+
let _ = started.send(());
|
|
365
|
+
Some(spin())
|
|
366
|
+
});
|
|
367
|
+
(next, begun.elapsed())
|
|
368
|
+
});
|
|
369
|
+
let spun = spinning.recv_timeout(PROMPTLY).is_ok();
|
|
370
|
+
assert_eq!(spun, during, "{what}: spun {spun}");
|
|
371
|
+
let _held = held.or_else(|| Some(set(&server, &slot)));
|
|
372
|
+
let (next, took) = look.join().expect("the look");
|
|
373
|
+
assert!(took < PROMPTLY, "{what}: still spun for {took:?}");
|
|
374
|
+
assert!(then(&next), "{what}: the look went on as without a spin");
|
|
375
|
+
assert_eq!(spun_since(&server, before), u64::from(during), "{what}");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
380
|
+
async fn a_request_a_spin_catches_as_its_worker_retires_goes_to_hyper_with_the_connection() {
|
|
381
|
+
// Two workers: hyper sends the request to the one that stays.
|
|
382
|
+
let (server, client, mut conn) = alone_after_a_request(2);
|
|
383
|
+
let slot = slot(&server, 0);
|
|
384
|
+
send_get(&client, "/second", false);
|
|
385
|
+
await_bytes(&conn);
|
|
386
|
+
|
|
387
|
+
// The retirement lands as the spin starts, which then catches the
|
|
388
|
+
// request at its first look, before it reads the gate again.
|
|
389
|
+
let next = conn.next_with(true, &mut |_, spin| {
|
|
390
|
+
slot.retire();
|
|
391
|
+
Some(spin())
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
assert!(
|
|
395
|
+
matches!(next, Next::Closed),
|
|
396
|
+
"the retiring worker served it inline"
|
|
397
|
+
);
|
|
398
|
+
assert_eq!(handbacks(&server), 1);
|
|
399
|
+
answer_dispatched(&server, &["/second"]).await;
|
|
400
|
+
assert_eq!(Wire::of(&client).response().2, b"hyper:/second");
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
404
|
+
async fn a_request_a_lone_connections_spin_sees_as_its_thread_is_unblocked_waits_for_the_jobs_wait(
|
|
405
|
+
) {
|
|
406
|
+
let (server, client, mut conn) = alone_after_a_request(1);
|
|
407
|
+
send_get(&client, "/second", false);
|
|
408
|
+
await_bytes(&conn);
|
|
409
|
+
let before = Some(spun_since(&server, None));
|
|
410
|
+
|
|
411
|
+
// The VM's unblock function fires as the spin starts (a
|
|
412
|
+
// Thread#raise, say): the job waits, where the raise meets it, as
|
|
413
|
+
// without a spin, rather than run a request first.
|
|
414
|
+
let next = conn.next_with(true, &mut |woken, spin| {
|
|
415
|
+
woken.store(true, Ordering::SeqCst);
|
|
416
|
+
Some(spin())
|
|
417
|
+
});
|
|
418
|
+
assert!(
|
|
419
|
+
matches!(next, Next::Readable),
|
|
420
|
+
"the spin took the request past its unblock"
|
|
421
|
+
);
|
|
422
|
+
assert_eq!(spun_since(&server, before), 1, "the spin never ran");
|
|
423
|
+
let Next::Request(ctx) = conn.next_with(true, &mut in_place) else {
|
|
424
|
+
panic!("the wait's look missed the request");
|
|
425
|
+
};
|
|
426
|
+
assert_eq!(ctx.uri.path(), "/second");
|
|
427
|
+
}
|
|
428
|
+
}
|