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,247 @@
|
|
|
1
|
+
//! One request through hyper: body forwarding, the queue, the answer and the access log.
|
|
2
|
+
|
|
3
|
+
use std::ops::Deref;
|
|
4
|
+
use std::sync::atomic::Ordering;
|
|
5
|
+
use std::sync::Arc;
|
|
6
|
+
use std::time::Duration;
|
|
7
|
+
|
|
8
|
+
use http_body_util::BodyExt;
|
|
9
|
+
|
|
10
|
+
use super::accept::Peer;
|
|
11
|
+
use crate::access_log::{Logged, Timing};
|
|
12
|
+
use crate::framing::content_length;
|
|
13
|
+
use crate::registry::ServerInner;
|
|
14
|
+
use crate::request::RequestCtx;
|
|
15
|
+
use crate::response::{plain_response, HyperResponse, Responder};
|
|
16
|
+
|
|
17
|
+
fn branded(mut response: HyperResponse) -> HyperResponse {
|
|
18
|
+
response
|
|
19
|
+
.headers_mut()
|
|
20
|
+
.entry(http::header::SERVER)
|
|
21
|
+
.or_insert(http::HeaderValue::from_static("Kino"));
|
|
22
|
+
response
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Idle deadline between body frames, so a silent client cannot pin a worker in read_body.
|
|
26
|
+
pub(crate) const BODY_READ_TIMEOUT: Duration = Duration::from_secs(30);
|
|
27
|
+
|
|
28
|
+
/// A request counted in Counters::in_flight while this lives. hyper's borrows its connection's
|
|
29
|
+
/// server, keeping the server's Arc count, which every worker take moves, off the I/O threads;
|
|
30
|
+
/// an inline request's holds an Arc.
|
|
31
|
+
/// A Drop guard: hyper drops this future at an await when the client aborts, and a
|
|
32
|
+
/// plain decrement after it would never run.
|
|
33
|
+
pub(crate) struct InFlight<S: Deref<Target = ServerInner> = Arc<ServerInner>> {
|
|
34
|
+
server: S,
|
|
35
|
+
/// A switching request's responder, which leaves the count when the app takes it over.
|
|
36
|
+
switching: Option<Arc<Responder>>,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
impl<S: Deref<Target = ServerInner>> InFlight<S> {
|
|
40
|
+
pub(crate) fn enter(server: S, switching: Option<Arc<Responder>>) -> Self {
|
|
41
|
+
server.counters.in_flight.fetch_add(1, Ordering::Relaxed);
|
|
42
|
+
InFlight { server, switching }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
impl<S: Deref<Target = ServerInner>> Drop for InFlight<S> {
|
|
47
|
+
fn drop(&mut self) {
|
|
48
|
+
// A hijacked request left the count when the app took it over.
|
|
49
|
+
if self.switching.as_ref().is_none_or(|r| r.leave_in_flight()) {
|
|
50
|
+
self.server
|
|
51
|
+
.counters
|
|
52
|
+
.in_flight
|
|
53
|
+
.fetch_sub(1, Ordering::Relaxed);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pub(super) async fn handle_request(
|
|
59
|
+
server: &Arc<ServerInner>,
|
|
60
|
+
peer: Peer,
|
|
61
|
+
mut req: hyper::Request<hyper::body::Incoming>,
|
|
62
|
+
) -> Result<HyperResponse, std::convert::Infallible> {
|
|
63
|
+
// A task holds a switching request's connection until the app claims it.
|
|
64
|
+
let upgrade = crate::upgrade::capture(&mut req, server);
|
|
65
|
+
let (parts, body) = req.into_parts();
|
|
66
|
+
let head = parts.method == http::Method::HEAD;
|
|
67
|
+
// Only when logging.
|
|
68
|
+
let logged = server.access_log.as_ref().map(|log| {
|
|
69
|
+
let logged = Logged::arrival(log, &parts.method, &parts.uri, peer.remote.ip());
|
|
70
|
+
(log, logged)
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// A declared oversize body gets a 413 before any worker runs; the forwarder caps
|
|
74
|
+
// chunked or lying clients, and read_body raises.
|
|
75
|
+
let max_body = server.config.max_body_size as u64;
|
|
76
|
+
let oversize = max_body > 0 && content_length(&parts.headers).is_some_and(|len| len > max_body);
|
|
77
|
+
|
|
78
|
+
let (head_tx, mut head_rx) = tokio::sync::oneshot::channel();
|
|
79
|
+
let responder = Arc::new(Responder::new(head_tx));
|
|
80
|
+
// A request that asks to switch can be hijacked: it keeps its responder for the request
|
|
81
|
+
// timeout and the in-flight count.
|
|
82
|
+
let switching = upgrade.is_some().then(|| responder.clone());
|
|
83
|
+
// No channel is a bodyless EOF.
|
|
84
|
+
let bodyless = oversize || hyper::body::Body::is_end_stream(&body);
|
|
85
|
+
let body_rx = (!bodyless).then(|| forward_body(body, &responder, max_body));
|
|
86
|
+
let ctx = RequestCtx::new(parts, peer, server, responder, body_rx, upgrade);
|
|
87
|
+
|
|
88
|
+
let in_flight = InFlight::enter(&**server, switching);
|
|
89
|
+
|
|
90
|
+
// One exit, so the access log sees every outcome, 503s included.
|
|
91
|
+
let response = if oversize {
|
|
92
|
+
plain_response(413, "Payload Too Large\n")
|
|
93
|
+
} else if !crate::dispatch::enqueue(server, ctx).await {
|
|
94
|
+
server.counters.rejected.fetch_add(1, Ordering::Relaxed);
|
|
95
|
+
plain_response(503, "Service Unavailable\n")
|
|
96
|
+
} else {
|
|
97
|
+
await_head(server, in_flight.switching.as_deref(), &mut head_rx).await
|
|
98
|
+
};
|
|
99
|
+
if let Some((log, logged)) = logged {
|
|
100
|
+
// A 503 or 504 never reached a worker and carries no timing.
|
|
101
|
+
let timing = response.extensions().get::<Timing>().copied();
|
|
102
|
+
let total = logged.elapsed();
|
|
103
|
+
logged.completion(log, response.status().as_u16(), total, timing);
|
|
104
|
+
}
|
|
105
|
+
Ok(branded(crate::response::without_forbidden_body(
|
|
106
|
+
response, head,
|
|
107
|
+
)))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// The request's body, forwarded by a task of its own through a bounded channel, so hyper is
|
|
111
|
+
/// polled only as fast as Ruby reads.
|
|
112
|
+
fn forward_body(
|
|
113
|
+
mut body: hyper::body::Incoming,
|
|
114
|
+
responder: &Arc<Responder>,
|
|
115
|
+
max_body: u64,
|
|
116
|
+
) -> flume::Receiver<bytes::Bytes> {
|
|
117
|
+
let (body_tx, body_rx) = flume::bounded::<bytes::Bytes>(8);
|
|
118
|
+
let feed = BodyFeed {
|
|
119
|
+
tx: Some(body_tx),
|
|
120
|
+
responder: responder.clone(),
|
|
121
|
+
ended: false,
|
|
122
|
+
};
|
|
123
|
+
tokio::spawn(async move {
|
|
124
|
+
let mut total: u64 = 0;
|
|
125
|
+
loop {
|
|
126
|
+
// Only the client's silence trips this; a slow app blocks send_async, untimed.
|
|
127
|
+
let frame = match tokio::time::timeout(BODY_READ_TIMEOUT, body.frame()).await {
|
|
128
|
+
Ok(Some(Ok(frame))) => frame,
|
|
129
|
+
Ok(Some(Err(_))) | Ok(None) => break, // body error or clean EOF
|
|
130
|
+
Err(_) => {
|
|
131
|
+
feed.responder
|
|
132
|
+
.abandon_body(crate::response::BodyAbandon::TimedOut);
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
// Non-data frames (h2 trailers) are dropped: Rack has no trailer surface.
|
|
137
|
+
if let Ok(data) = frame.into_data() {
|
|
138
|
+
total += data.len() as u64;
|
|
139
|
+
if max_body > 0 && total > max_body {
|
|
140
|
+
// Past the cap: dropping the sender unblocks read_body, which raises.
|
|
141
|
+
feed.responder
|
|
142
|
+
.abandon_body(crate::response::BodyAbandon::Oversize);
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
if !feed.send(data).await {
|
|
146
|
+
break; // request handle dropped; stop pulling
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
feed.end();
|
|
151
|
+
});
|
|
152
|
+
body_rx
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// The head must arrive in time or the client gets a 504; the worker runs on, and its late
|
|
156
|
+
/// answer goes nowhere (the first claim won). A CPU-stuck handler keeps its slot.
|
|
157
|
+
async fn await_head(
|
|
158
|
+
server: &ServerInner,
|
|
159
|
+
switching: Option<&Responder>,
|
|
160
|
+
head_rx: &mut tokio::sync::oneshot::Receiver<HyperResponse>,
|
|
161
|
+
) -> HyperResponse {
|
|
162
|
+
let dropped = |_| plain_response(500, "Internal Server Error\n");
|
|
163
|
+
if server.config.request_timeout_ms == 0 {
|
|
164
|
+
return head_rx.await.unwrap_or_else(dropped);
|
|
165
|
+
}
|
|
166
|
+
let deadline = Duration::from_millis(server.config.request_timeout_ms);
|
|
167
|
+
match tokio::time::timeout(deadline, &mut *head_rx).await {
|
|
168
|
+
Ok(result) => result.unwrap_or_else(dropped),
|
|
169
|
+
Err(_elapsed) => timed_out(server, switching, head_rx),
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/// The forwarder's end of a request body: each chunk, and the body's end however it comes,
|
|
174
|
+
/// rings a reader waiting on the request's body bell.
|
|
175
|
+
struct BodyFeed {
|
|
176
|
+
tx: Option<flume::Sender<bytes::Bytes>>,
|
|
177
|
+
responder: Arc<Responder>,
|
|
178
|
+
/// Dropped before its loop ended, the forwarder went with the runtime: no end at all.
|
|
179
|
+
ended: bool,
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
impl BodyFeed {
|
|
183
|
+
/// False once the request's handle is gone.
|
|
184
|
+
async fn send(&self, data: bytes::Bytes) -> bool {
|
|
185
|
+
let Some(tx) = &self.tx else {
|
|
186
|
+
return false;
|
|
187
|
+
};
|
|
188
|
+
let sent = tx.send_async(data).await.is_ok();
|
|
189
|
+
self.responder.body_bell.ring();
|
|
190
|
+
sent
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
fn end(mut self) {
|
|
194
|
+
self.ended = true;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
impl Drop for BodyFeed {
|
|
199
|
+
/// The channel closes before the ring, so the reader it wakes finds
|
|
200
|
+
/// the body's end; a body cut by the shutdown reads as interrupted.
|
|
201
|
+
fn drop(&mut self) {
|
|
202
|
+
if !self.ended {
|
|
203
|
+
self.responder
|
|
204
|
+
.abandon_body(crate::response::BodyAbandon::Interrupted);
|
|
205
|
+
}
|
|
206
|
+
self.tx.take();
|
|
207
|
+
self.responder.body_bell.ring();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/// A 504. For a request that asked to switch (`switching`, its responder) it closes the
|
|
212
|
+
/// connection, and a held 101 is given up unless it went out as the deadline passed.
|
|
213
|
+
fn timed_out(
|
|
214
|
+
server: &ServerInner,
|
|
215
|
+
switching: Option<&Responder>,
|
|
216
|
+
head_rx: &mut tokio::sync::oneshot::Receiver<HyperResponse>,
|
|
217
|
+
) -> HyperResponse {
|
|
218
|
+
if let Some(responder) = switching {
|
|
219
|
+
if !responder.cancel_switch() {
|
|
220
|
+
if let Ok(response) = head_rx.try_recv() {
|
|
221
|
+
return response;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
server.counters.timeouts.fetch_add(1, Ordering::Relaxed);
|
|
226
|
+
let mut response = plain_response(504, "Gateway Timeout\n");
|
|
227
|
+
if switching.is_some() {
|
|
228
|
+
crate::response::close_connection(&mut response);
|
|
229
|
+
}
|
|
230
|
+
response
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
#[cfg(test)]
|
|
234
|
+
mod tests {
|
|
235
|
+
use super::*;
|
|
236
|
+
|
|
237
|
+
#[test]
|
|
238
|
+
fn branded_adds_the_server_header_unless_the_app_set_one() {
|
|
239
|
+
let response = branded(plain_response(200, "x"));
|
|
240
|
+
assert_eq!(response.headers()[http::header::SERVER], "Kino");
|
|
241
|
+
|
|
242
|
+
let mut custom = plain_response(200, "x");
|
|
243
|
+
let server = http::HeaderValue::from_static("custom");
|
|
244
|
+
custom.headers_mut().insert(http::header::SERVER, server);
|
|
245
|
+
assert_eq!(branded(custom).headers()[http::header::SERVER], "custom");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
//! A connection's intake before hyper serves it: by when its client must have begun (Intake), and
|
|
2
|
+
//! how it began, told as hyper-util's sniff tells HTTP/1 from h2 (Sniff).
|
|
3
|
+
|
|
4
|
+
use std::io::ErrorKind;
|
|
5
|
+
use std::time::Duration;
|
|
6
|
+
|
|
7
|
+
use bytes::Bytes;
|
|
8
|
+
use socket2::{SockRef, Socket};
|
|
9
|
+
use tokio::io::{AsyncReadExt, Interest};
|
|
10
|
+
use tokio::net::{TcpStream, UnixStream};
|
|
11
|
+
use tokio_util::either::Either;
|
|
12
|
+
|
|
13
|
+
use crate::registry::ServerInner;
|
|
14
|
+
|
|
15
|
+
/// Slowloris guard for HTTP/1 heads; fixed, as tuning intake is the fronting proxy's job.
|
|
16
|
+
/// hyper times the head once it reads; first_bytes (or preface, over TLS) what comes before.
|
|
17
|
+
pub(crate) const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(15);
|
|
18
|
+
|
|
19
|
+
/// hyper's HTTP/2 keep-alive: a client silent this long gets a PING, and is closed unless it
|
|
20
|
+
/// answers within H2_PING_TIMEOUT. It reaps a peer that is gone; an idle client that answers
|
|
21
|
+
/// keeps its connection (max_connections, or a fronting proxy, bounds those).
|
|
22
|
+
pub(super) const H2_PING_EVERY: Duration = Duration::from_secs(30);
|
|
23
|
+
pub(super) const H2_PING_TIMEOUT: Duration = Duration::from_secs(20);
|
|
24
|
+
|
|
25
|
+
/// What a client opening HTTP/2 without ALPN sends first (RFC 9113 3.4).
|
|
26
|
+
pub(super) const H2_PREFACE: &[u8; 24] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
|
|
27
|
+
|
|
28
|
+
/// By when a client must have begun, from its accept: its TLS handshake done and its first byte
|
|
29
|
+
/// sent (first_bytes).
|
|
30
|
+
#[derive(Clone, Copy)]
|
|
31
|
+
pub(super) struct Intake {
|
|
32
|
+
pub(super) handshake: Duration,
|
|
33
|
+
pub(super) first_byte: Duration,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
impl Intake {
|
|
37
|
+
pub(super) const KINO: Intake = Intake {
|
|
38
|
+
// Slowloris guard for TLS: the header deadline starts only once hyper serves.
|
|
39
|
+
handshake: Duration::from_secs(10),
|
|
40
|
+
first_byte: HEADER_READ_TIMEOUT,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// How a client began, as hyper's sniff tells: the h2 preface, or anything else (its end too).
|
|
45
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
46
|
+
pub(super) enum Began {
|
|
47
|
+
H2,
|
|
48
|
+
Other,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
pub(super) type Plain<'a> = Either<&'a TcpStream, &'a UnixStream>;
|
|
52
|
+
|
|
53
|
+
fn socket<'a>(plain: &Plain<'a>) -> SockRef<'a> {
|
|
54
|
+
match *plain {
|
|
55
|
+
Either::Left(stream) => SockRef::from(stream),
|
|
56
|
+
Either::Right(stream) => SockRef::from(stream),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// What a client sent first, up to what tells HTTP/1 from h2 (a byte off the preface, or all of
|
|
61
|
+
/// it); the sniff waits for it with no timer.
|
|
62
|
+
#[derive(Clone, Copy)]
|
|
63
|
+
struct Sniff {
|
|
64
|
+
first: [u8; H2_PREFACE.len()],
|
|
65
|
+
have: usize,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
impl Sniff {
|
|
69
|
+
fn after(read: &[u8]) -> Sniff {
|
|
70
|
+
let mut first = [0; H2_PREFACE.len()];
|
|
71
|
+
let have = read.len().min(first.len());
|
|
72
|
+
first[..have].copy_from_slice(&read[..have]);
|
|
73
|
+
Sniff { first, have }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fn began(&self) -> Option<Began> {
|
|
77
|
+
let first = &self.first[..self.have];
|
|
78
|
+
if first == H2_PREFACE {
|
|
79
|
+
Some(Began::H2)
|
|
80
|
+
} else if !H2_PREFACE.starts_with(first) {
|
|
81
|
+
Some(Began::Other)
|
|
82
|
+
} else {
|
|
83
|
+
None
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fn recv(&mut self, socket: &Socket, flags: libc::c_int) -> std::io::Result<usize> {
|
|
88
|
+
let n = recv_now(socket, &mut self.first[self.have..], flags)?;
|
|
89
|
+
self.have += n;
|
|
90
|
+
Ok(n)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// How `socket`'s client began, by what it sent and what waits unread (a peek that waits for
|
|
94
|
+
/// nothing); Other once its connection ended or failed, all of it hyper's to read.
|
|
95
|
+
fn peek(mut self, socket: &Socket) -> Option<Began> {
|
|
96
|
+
if let Some(began) = self.began() {
|
|
97
|
+
return Some(began);
|
|
98
|
+
}
|
|
99
|
+
match self.recv(socket, libc::MSG_PEEK) {
|
|
100
|
+
Ok(0) => Some(Began::Other),
|
|
101
|
+
Ok(_) => self.began(),
|
|
102
|
+
Err(e) => (e.kind() != ErrorKind::WouldBlock).then_some(Began::Other),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// How a connection whose client sent (past `read`) too little for hyper's sniff began, once it
|
|
108
|
+
/// has: the sniff never times out a client that sends nothing or stops inside the h2 preface.
|
|
109
|
+
/// None, and it closes unanswered, when nothing more comes `within`, or once the drain began with
|
|
110
|
+
/// nothing there, as hyper closes an idle connection. Mostly the bytes are in by the accept: one
|
|
111
|
+
/// peek.
|
|
112
|
+
pub(super) async fn first_bytes(
|
|
113
|
+
plain: Plain<'_>,
|
|
114
|
+
read: &[u8],
|
|
115
|
+
within: Duration,
|
|
116
|
+
server: &ServerInner,
|
|
117
|
+
) -> Option<Began> {
|
|
118
|
+
let (sniff, sock) = (Sniff::after(read), socket(&plain));
|
|
119
|
+
if let Some(began) = sniff.peek(&sock) {
|
|
120
|
+
return Some(began);
|
|
121
|
+
}
|
|
122
|
+
let mut drain = server.shutdown_tx.subscribe();
|
|
123
|
+
let sent = async {
|
|
124
|
+
// tokio assumes a just-accepted socket ready; the peek tells, and forgets a readiness
|
|
125
|
+
// that was not. One whose client ended its side is hyper's to read: tokio never forgets
|
|
126
|
+
// that readiness, so waiting on would spin.
|
|
127
|
+
loop {
|
|
128
|
+
let ready = match &plain {
|
|
129
|
+
Either::Left(stream) => stream.ready(Interest::READABLE).await,
|
|
130
|
+
Either::Right(stream) => stream.ready(Interest::READABLE).await,
|
|
131
|
+
};
|
|
132
|
+
match ready {
|
|
133
|
+
Ok(ready) if ready.is_read_closed() => return Some(Began::Other),
|
|
134
|
+
Ok(_) => {}
|
|
135
|
+
Err(_) => return None,
|
|
136
|
+
}
|
|
137
|
+
let peek = || sniff.peek(&sock).ok_or(ErrorKind::WouldBlock.into());
|
|
138
|
+
let looked = match &plain {
|
|
139
|
+
Either::Left(stream) => stream.try_io(Interest::READABLE, peek),
|
|
140
|
+
Either::Right(stream) => stream.try_io(Interest::READABLE, peek),
|
|
141
|
+
};
|
|
142
|
+
if let Ok(began) = looked {
|
|
143
|
+
return Some(began);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
tokio::select! {
|
|
148
|
+
biased;
|
|
149
|
+
sent = tokio::time::timeout(within, sent) => sent.ok().flatten(),
|
|
150
|
+
() = drain_signal(&mut drain) => None,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/// `read`, with what its client sent past it taken off `plain`, up to what tells HTTP/1 from h2,
|
|
155
|
+
/// the end, or nothing more: hyper's sniff starts with it, as hyper's own first read of a
|
|
156
|
+
/// handed-back socket waits for a readiness a drain may cancel. Each read takes some or stops.
|
|
157
|
+
pub(super) fn took_first(plain: Plain<'_>, read: Bytes) -> Bytes {
|
|
158
|
+
let mut sniff = Sniff::after(&read);
|
|
159
|
+
if sniff.began().is_some() {
|
|
160
|
+
return read;
|
|
161
|
+
}
|
|
162
|
+
let sock = socket(&plain);
|
|
163
|
+
while sniff.began().is_none() && matches!(sniff.recv(&sock, 0), Ok(1..)) {}
|
|
164
|
+
Bytes::copy_from_slice(&sniff.first[..sniff.have])
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// How a TLS client began, read off `tls` until that tells within `within`, and those bytes for
|
|
168
|
+
/// hyper to read again; None, and it closes, past that, at a drain with too little there, or at
|
|
169
|
+
/// its end.
|
|
170
|
+
pub(super) async fn preface(
|
|
171
|
+
tls: &mut tokio_rustls::server::TlsStream<TcpStream>,
|
|
172
|
+
within: Duration,
|
|
173
|
+
server: &ServerInner,
|
|
174
|
+
) -> Option<(Began, Bytes)> {
|
|
175
|
+
let mut sniff = Sniff::after(&[]);
|
|
176
|
+
let mut drain = server.shutdown_tx.subscribe();
|
|
177
|
+
let read = async {
|
|
178
|
+
loop {
|
|
179
|
+
if let Some(began) = sniff.began() {
|
|
180
|
+
return Some(began);
|
|
181
|
+
}
|
|
182
|
+
match tls.read(&mut sniff.first[sniff.have..]).await {
|
|
183
|
+
Ok(0) | Err(_) => return None,
|
|
184
|
+
Ok(n) => sniff.have += n,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
let began = tokio::select! {
|
|
189
|
+
biased;
|
|
190
|
+
began = tokio::time::timeout(within, read) => began.ok().flatten(),
|
|
191
|
+
() = drain_signal(&mut drain) => None,
|
|
192
|
+
};
|
|
193
|
+
Some((began?, Bytes::copy_from_slice(&sniff.first[..sniff.have])))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// recv(2) on `socket` into `buf` with `flags`, waiting for nothing; again if interrupted.
|
|
197
|
+
pub(crate) fn recv_now(
|
|
198
|
+
socket: &Socket,
|
|
199
|
+
buf: &mut [u8],
|
|
200
|
+
flags: libc::c_int,
|
|
201
|
+
) -> std::io::Result<usize> {
|
|
202
|
+
// SAFETY: recv(2) writes only initialised bytes, as socket2's own Read for &Socket relies on.
|
|
203
|
+
let buf = unsafe { &mut *(buf as *mut [u8] as *mut [std::mem::MaybeUninit<u8>]) };
|
|
204
|
+
loop {
|
|
205
|
+
match socket.recv_with_flags(buf, flags | libc::MSG_DONTWAIT) {
|
|
206
|
+
Err(e) if e.kind() == ErrorKind::Interrupted => {}
|
|
207
|
+
got => return got,
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// The value first: a connection may subscribe just after the signal. A dropped sender counts.
|
|
213
|
+
pub(super) async fn drain_signal(rx: &mut tokio::sync::watch::Receiver<bool>) {
|
|
214
|
+
if !*rx.borrow_and_update() {
|
|
215
|
+
let _ = rx.changed().await;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
//! The tokio + hyper front-end: listener, runtime and intake. Ruby never runs on these
|
|
2
|
+
//! threads; it meets them at the queue (in) and at each request's Responder (out).
|
|
3
|
+
|
|
4
|
+
mod accept;
|
|
5
|
+
mod config;
|
|
6
|
+
mod handle;
|
|
7
|
+
mod intake;
|
|
8
|
+
mod natives;
|
|
9
|
+
mod serve;
|
|
10
|
+
#[cfg(test)]
|
|
11
|
+
mod tests;
|
|
12
|
+
|
|
13
|
+
use std::sync::Arc;
|
|
14
|
+
use std::time::Duration;
|
|
15
|
+
|
|
16
|
+
use magnus::{Error, Ruby};
|
|
17
|
+
|
|
18
|
+
use crate::listen::Listener;
|
|
19
|
+
use crate::registry::{self, RuntimeHandle, ServerInner};
|
|
20
|
+
|
|
21
|
+
use accept::accept_loop;
|
|
22
|
+
#[cfg(test)]
|
|
23
|
+
pub(crate) use accept::UNIX_PEER;
|
|
24
|
+
pub(crate) use accept::{next_accept, Accepted, AsyncListener, Conn, Held, Peer, StdConn};
|
|
25
|
+
pub use config::{ServerConfig, Topology};
|
|
26
|
+
pub(crate) use handle::{InFlight, BODY_READ_TIMEOUT};
|
|
27
|
+
pub(crate) use intake::{recv_now, HEADER_READ_TIMEOUT};
|
|
28
|
+
pub use natives::*;
|
|
29
|
+
#[cfg(test)]
|
|
30
|
+
pub(crate) use serve::testing;
|
|
31
|
+
pub(crate) use serve::{serve_conn, serve_handed_back};
|
|
32
|
+
|
|
33
|
+
fn io_error(ruby: &Ruby, what: &str, e: std::io::Error) -> Error {
|
|
34
|
+
Error::new(ruby.exception_runtime_error(), format!("{what}: {e}"))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// Bind and spawn the accept loop, synchronously so bind and TLS errors raise at `start`.
|
|
38
|
+
/// Returns the id, the bound port (for `port: 0`) and the control port, if any.
|
|
39
|
+
pub fn server_start(ruby: &Ruby, config: magnus::RHash) -> Result<(u64, u16, Option<u16>), Error> {
|
|
40
|
+
let mut config = ServerConfig::try_from(config)?;
|
|
41
|
+
let acceptor = config
|
|
42
|
+
.tls
|
|
43
|
+
.as_ref()
|
|
44
|
+
.map(|(cert, key)| {
|
|
45
|
+
crate::tls::build_acceptor(cert, key, config.http2)
|
|
46
|
+
.map_err(|e| Error::new(ruby.exception_runtime_error(), format!("TLS: {e}")))
|
|
47
|
+
})
|
|
48
|
+
.transpose()?;
|
|
49
|
+
|
|
50
|
+
let listener =
|
|
51
|
+
Listener::bind(&config.bind, config.port).map_err(|e| io_error(ruby, "bind failed", e))?;
|
|
52
|
+
// Ruby refuses this up front; this guards embedders calling the native layer directly.
|
|
53
|
+
if acceptor.is_some() && matches!(listener, Listener::Unix(..)) {
|
|
54
|
+
return Err(Error::new(
|
|
55
|
+
ruby.exception_arg_error(),
|
|
56
|
+
"TLS is not supported on a unix socket bind",
|
|
57
|
+
));
|
|
58
|
+
}
|
|
59
|
+
let local_port = listener
|
|
60
|
+
.port()
|
|
61
|
+
.map_err(|e| io_error(ruby, "listener setup failed", e))?;
|
|
62
|
+
if let Listener::Unix(_, path) = &listener {
|
|
63
|
+
config.unix_path = Some(path.clone());
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let control_bind = config
|
|
67
|
+
.control_bind
|
|
68
|
+
.as_deref()
|
|
69
|
+
.map(|addr| {
|
|
70
|
+
crate::control::bind_control(addr).map_err(|e| io_error(ruby, "control bind failed", e))
|
|
71
|
+
})
|
|
72
|
+
.transpose()?;
|
|
73
|
+
|
|
74
|
+
let server = Arc::new(ServerInner::new(config));
|
|
75
|
+
// Before the runtime, as a server that fails here has nothing running yet.
|
|
76
|
+
if server.config.worker_loop {
|
|
77
|
+
let ticker = crate::ticker::Ticker::start(&server)
|
|
78
|
+
.map_err(|e| io_error(ruby, "worker_loop ticker failed", e))?;
|
|
79
|
+
*server.ticker.lock() = Some(ticker);
|
|
80
|
+
}
|
|
81
|
+
let runtime =
|
|
82
|
+
start_runtime(&server, listener, acceptor).map_err(|(what, e)| io_error(ruby, what, e))?;
|
|
83
|
+
*server.runtime.lock() = runtime;
|
|
84
|
+
|
|
85
|
+
let id = server.id;
|
|
86
|
+
let control_port = match control_bind {
|
|
87
|
+
Some(bind) => {
|
|
88
|
+
start_control(&server, bind).map_err(|e| io_error(ruby, "control start failed", e))?
|
|
89
|
+
}
|
|
90
|
+
None => None,
|
|
91
|
+
};
|
|
92
|
+
registry::insert(server);
|
|
93
|
+
Ok((id, local_port, control_port))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/// The I/O threads, accepting from `listener`: the shards, or tokio's multi-thread runtime.
|
|
97
|
+
/// An error comes with what failed.
|
|
98
|
+
fn start_runtime(
|
|
99
|
+
server: &Arc<ServerInner>,
|
|
100
|
+
listener: Listener,
|
|
101
|
+
acceptor: Option<tokio_rustls::TlsAcceptor>,
|
|
102
|
+
) -> Result<RuntimeHandle, (&'static str, std::io::Error)> {
|
|
103
|
+
let config = &server.config;
|
|
104
|
+
let shutdown_rx = server.shutdown_tx.subscribe();
|
|
105
|
+
if config.io_shards {
|
|
106
|
+
// The shards serve on while the acceptor drains; this signal stops them at final teardown.
|
|
107
|
+
let (runtime_shutdown_tx, runtime_shutdown_rx) = tokio::sync::watch::channel(false);
|
|
108
|
+
let threads = crate::io_shards::spawn(
|
|
109
|
+
listener,
|
|
110
|
+
acceptor,
|
|
111
|
+
server.clone(),
|
|
112
|
+
config.max_connections,
|
|
113
|
+
shutdown_rx,
|
|
114
|
+
runtime_shutdown_rx,
|
|
115
|
+
crate::io_shards::thread_count(config.io_threads),
|
|
116
|
+
)
|
|
117
|
+
.map_err(|e| ("sharded runtime failed", e))?;
|
|
118
|
+
return Ok(RuntimeHandle::Shards {
|
|
119
|
+
shutdown_tx: runtime_shutdown_tx,
|
|
120
|
+
threads,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
let mut builder = tokio::runtime::Builder::new_multi_thread();
|
|
124
|
+
builder.enable_all().thread_name("kino-tokio");
|
|
125
|
+
if config.tokio_threads > 0 {
|
|
126
|
+
builder.worker_threads(config.tokio_threads);
|
|
127
|
+
}
|
|
128
|
+
let runtime = builder.build().map_err(|e| ("tokio runtime failed", e))?;
|
|
129
|
+
let tokio_listener = {
|
|
130
|
+
let _guard = runtime.enter();
|
|
131
|
+
AsyncListener::from_std(listener).map_err(|e| ("listener setup failed", e))?
|
|
132
|
+
};
|
|
133
|
+
let _ = server.io_runtime.set(runtime.handle().clone());
|
|
134
|
+
runtime.spawn(accept_loop(
|
|
135
|
+
tokio_listener,
|
|
136
|
+
acceptor,
|
|
137
|
+
server.clone(),
|
|
138
|
+
config.max_connections,
|
|
139
|
+
shutdown_rx,
|
|
140
|
+
));
|
|
141
|
+
Ok(RuntimeHandle::MultiThread(runtime))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/// The control plane's port, if it listens on one. On failure the runtime stops here: not
|
|
145
|
+
/// registered yet, nothing else could shut it down, and the accept task's Arc keeps it alive
|
|
146
|
+
/// (a plain Ruby thread, safe to block).
|
|
147
|
+
fn start_control(
|
|
148
|
+
server: &Arc<ServerInner>,
|
|
149
|
+
bind: crate::control::ControlBind,
|
|
150
|
+
) -> std::io::Result<Option<u16>> {
|
|
151
|
+
let token = server.config.control_token.clone();
|
|
152
|
+
crate::control::start(bind, server.clone(), token).inspect_err(|_| {
|
|
153
|
+
// Nothing serves yet: the bound matters only for a wedged shard thread.
|
|
154
|
+
let _ = server.shutdown_tx.send(true);
|
|
155
|
+
std::mem::take(&mut *server.runtime.lock()).shutdown(Duration::from_millis(1_000));
|
|
156
|
+
})
|
|
157
|
+
}
|