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
data/ext/kino/src/server.rs
DELETED
|
@@ -1,1785 +0,0 @@
|
|
|
1
|
-
//! tokio + hyper front-end: owns the listener, the runtime, and request
|
|
2
|
-
//! intake. Ruby is never on these threads; the only contact points are the
|
|
3
|
-
//! flume queue (in) and each request's Responder (out).
|
|
4
|
-
|
|
5
|
-
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|
6
|
-
use std::sync::atomic::Ordering;
|
|
7
|
-
use std::sync::Arc;
|
|
8
|
-
use std::time::Duration;
|
|
9
|
-
|
|
10
|
-
use http_body_util::BodyExt;
|
|
11
|
-
use hyper::service::service_fn;
|
|
12
|
-
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
|
|
13
|
-
use hyper_util::server::conn::auto;
|
|
14
|
-
use magnus::{Error, Ruby};
|
|
15
|
-
use parking_lot::{Mutex, RwLock};
|
|
16
|
-
|
|
17
|
-
use crate::listen::Listener;
|
|
18
|
-
use crate::registry::{self, BoxedCtx, RuntimeHandle, ServerInner, WorkerSlot};
|
|
19
|
-
use crate::request::RequestCtx;
|
|
20
|
-
use crate::response::{plain_response, HyperResponse, Responder};
|
|
21
|
-
|
|
22
|
-
fn io_error(ruby: &Ruby, what: &str, e: std::io::Error) -> Error {
|
|
23
|
-
Error::new(ruby.exception_runtime_error(), format!("{what}: {e}"))
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/// Required key from the boot-config Hash.
|
|
27
|
-
fn cfg<T: magnus::TryConvert>(ruby: &Ruby, config: magnus::RHash, key: &str) -> Result<T, Error> {
|
|
28
|
-
cfg_opt::<T>(ruby, config, key)?.ok_or_else(|| {
|
|
29
|
-
Error::new(
|
|
30
|
-
ruby.exception_arg_error(),
|
|
31
|
-
format!("server_start: missing config key :{key}"),
|
|
32
|
-
)
|
|
33
|
-
})
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/// Optional key from the boot-config Hash (absent or nil → None).
|
|
37
|
-
fn cfg_opt<T: magnus::TryConvert>(
|
|
38
|
-
ruby: &Ruby,
|
|
39
|
-
config: magnus::RHash,
|
|
40
|
-
key: &str,
|
|
41
|
-
) -> Result<Option<T>, Error> {
|
|
42
|
-
config.lookup(ruby.to_symbol(key))
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/// Bind + spawn the accept loop. Takes one config Hash: this runs once
|
|
46
|
-
/// at boot, so Hash-lookup cost is irrelevant and the interface stays
|
|
47
|
-
/// extensible. Binding is synchronous so address errors raise in Ruby at
|
|
48
|
-
/// `start` time; returns the actual port for `port: 0`. TLS config errors
|
|
49
|
-
/// (bad cert/key) also raise here, before any traffic. The third element
|
|
50
|
-
/// of the return tuple is the control-plane port (nil unless control_bind
|
|
51
|
-
/// is configured).
|
|
52
|
-
pub fn server_start(ruby: &Ruby, config: magnus::RHash) -> Result<(u64, u16, Option<u16>), Error> {
|
|
53
|
-
let bind: String = cfg(ruby, config, "bind")?;
|
|
54
|
-
let port: u16 = cfg(ruby, config, "port")?;
|
|
55
|
-
let queue_depth: usize = cfg(ruby, config, "queue_depth")?;
|
|
56
|
-
let queue_timeout_ms: u64 = cfg(ruby, config, "queue_timeout_ms")?;
|
|
57
|
-
let request_timeout_ms: u64 = cfg_opt::<u64>(ruby, config, "request_timeout_ms")?.unwrap_or(0);
|
|
58
|
-
let max_body_size: usize = cfg_opt::<usize>(ruby, config, "max_body_size")?.unwrap_or(0);
|
|
59
|
-
let max_connections: usize = cfg_opt::<usize>(ruby, config, "max_connections")?.unwrap_or(1024);
|
|
60
|
-
let io_shards: bool = cfg_opt(ruby, config, "io_shards")?.unwrap_or(false);
|
|
61
|
-
let io_threads: usize = cfg_opt::<usize>(ruby, config, "io_threads")?.unwrap_or(0);
|
|
62
|
-
let tokio_threads: usize = cfg_opt::<usize>(ruby, config, "tokio_threads")?.unwrap_or(0);
|
|
63
|
-
let tls_cert: Option<String> = cfg_opt(ruby, config, "tls_cert")?;
|
|
64
|
-
let tls_key: Option<String> = cfg_opt(ruby, config, "tls_key")?;
|
|
65
|
-
let lanes: bool = cfg_opt(ruby, config, "lanes")?.unwrap_or(false);
|
|
66
|
-
// Default true guards embedders calling the native layer directly.
|
|
67
|
-
let http2: bool = cfg_opt(ruby, config, "http2")?.unwrap_or(true);
|
|
68
|
-
let log_requests: bool = cfg_opt(ruby, config, "log_requests")?.unwrap_or(false);
|
|
69
|
-
let mode: String = cfg_opt(ruby, config, "mode")?.unwrap_or_else(|| "threaded".to_string());
|
|
70
|
-
let workers: usize = cfg_opt(ruby, config, "workers")?.unwrap_or(0);
|
|
71
|
-
// Absent or below the floor means a fixed pool.
|
|
72
|
-
let max_workers: usize = cfg_opt::<usize>(ruby, config, "max_workers")?
|
|
73
|
-
.unwrap_or(workers)
|
|
74
|
-
.max(workers);
|
|
75
|
-
let threads: usize = cfg_opt(ruby, config, "threads")?.unwrap_or(0);
|
|
76
|
-
let batch: usize = cfg_opt(ruby, config, "batch")?.unwrap_or(1);
|
|
77
|
-
let acceptor = match (&tls_cert, &tls_key) {
|
|
78
|
-
(Some(cert), Some(key)) => Some(
|
|
79
|
-
crate::tls::build_acceptor(cert, key, http2)
|
|
80
|
-
.map_err(|e| Error::new(ruby.exception_runtime_error(), format!("TLS: {e}")))?,
|
|
81
|
-
),
|
|
82
|
-
(None, None) => None,
|
|
83
|
-
_ => {
|
|
84
|
-
return Err(Error::new(
|
|
85
|
-
ruby.exception_arg_error(),
|
|
86
|
-
"TLS requires both cert and key",
|
|
87
|
-
))
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
let listener = Listener::bind(&bind, port).map_err(|e| io_error(ruby, "bind failed", e))?;
|
|
92
|
-
// Ruby refuses this combination up front; this guards embedders
|
|
93
|
-
// calling the native layer directly.
|
|
94
|
-
if acceptor.is_some() && matches!(listener, Listener::Unix(..)) {
|
|
95
|
-
return Err(Error::new(
|
|
96
|
-
ruby.exception_arg_error(),
|
|
97
|
-
"TLS is not supported on a unix socket bind",
|
|
98
|
-
));
|
|
99
|
-
}
|
|
100
|
-
let local_port = listener
|
|
101
|
-
.port()
|
|
102
|
-
.map_err(|e| io_error(ruby, "listener setup failed", e))?;
|
|
103
|
-
let unix_path = match &listener {
|
|
104
|
-
Listener::Unix(_, path) => Some(path.clone()),
|
|
105
|
-
Listener::Tcp(_) => None,
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
let control_bind_addr: Option<String> = cfg_opt(ruby, config, "control_bind")?;
|
|
109
|
-
let control_token: Option<String> = cfg_opt(ruby, config, "control_token")?;
|
|
110
|
-
let control_bind = control_bind_addr
|
|
111
|
-
.as_deref()
|
|
112
|
-
.map(|addr| {
|
|
113
|
-
crate::control::bind_control(addr).map_err(|e| io_error(ruby, "control bind failed", e))
|
|
114
|
-
})
|
|
115
|
-
.transpose()?;
|
|
116
|
-
|
|
117
|
-
let (req_tx, req_rx) = flume::bounded(queue_depth);
|
|
118
|
-
let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
|
|
119
|
-
|
|
120
|
-
let pin_slab = Arc::new(crate::pin::PinSlab::for_responses(mode == "ractor"));
|
|
121
|
-
let server = Arc::new(ServerInner {
|
|
122
|
-
id: registry::next_server_id(),
|
|
123
|
-
req_tx: Mutex::new(Some(req_tx)),
|
|
124
|
-
req_rx,
|
|
125
|
-
shutdown_tx,
|
|
126
|
-
runtime: Mutex::new(RuntimeHandle::None),
|
|
127
|
-
slots: RwLock::new(Vec::new()),
|
|
128
|
-
in_flight: std::sync::atomic::AtomicUsize::new(0),
|
|
129
|
-
served: std::sync::atomic::AtomicU64::new(0),
|
|
130
|
-
rejected: std::sync::atomic::AtomicU64::new(0),
|
|
131
|
-
queue_timeout_ms,
|
|
132
|
-
request_timeout_ms,
|
|
133
|
-
max_body_size,
|
|
134
|
-
timeouts: std::sync::atomic::AtomicU64::new(0),
|
|
135
|
-
state: std::sync::atomic::AtomicU8::new(registry::STATE_BOOTING),
|
|
136
|
-
respawns: std::sync::atomic::AtomicU64::new(0),
|
|
137
|
-
quarantine_replacements: std::sync::atomic::AtomicU64::new(0),
|
|
138
|
-
active_workers: std::sync::atomic::AtomicUsize::new(workers),
|
|
139
|
-
scale_ups: std::sync::atomic::AtomicU64::new(0),
|
|
140
|
-
scale_downs: std::sync::atomic::AtomicU64::new(0),
|
|
141
|
-
topology: registry::Topology {
|
|
142
|
-
mode,
|
|
143
|
-
workers,
|
|
144
|
-
max_workers,
|
|
145
|
-
threads,
|
|
146
|
-
batch,
|
|
147
|
-
},
|
|
148
|
-
https: acceptor.is_some(),
|
|
149
|
-
http2,
|
|
150
|
-
unix_path,
|
|
151
|
-
access_log: log_requests.then(|| crate::logsink::Sink::new(std::io::stdout())),
|
|
152
|
-
lanes,
|
|
153
|
-
lane_cursor: std::sync::atomic::AtomicUsize::new(0),
|
|
154
|
-
pin_slab,
|
|
155
|
-
queue_histogram: registry::QueueHistogram::new(),
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
if io_shards {
|
|
159
|
-
// The shards keep serving accepted connections while the acceptor
|
|
160
|
-
// drains on `shutdown_rx`; this second signal stops them only at
|
|
161
|
-
// final teardown.
|
|
162
|
-
let (runtime_shutdown_tx, runtime_shutdown_rx) = tokio::sync::watch::channel(false);
|
|
163
|
-
let threads = crate::io_shards::spawn(
|
|
164
|
-
listener,
|
|
165
|
-
acceptor,
|
|
166
|
-
server.clone(),
|
|
167
|
-
max_connections,
|
|
168
|
-
shutdown_rx,
|
|
169
|
-
runtime_shutdown_rx,
|
|
170
|
-
crate::io_shards::thread_count(io_threads),
|
|
171
|
-
)
|
|
172
|
-
.map_err(|e| io_error(ruby, "sharded runtime failed", e))?;
|
|
173
|
-
*server.runtime.lock() = RuntimeHandle::Shards {
|
|
174
|
-
shutdown_tx: runtime_shutdown_tx,
|
|
175
|
-
threads,
|
|
176
|
-
};
|
|
177
|
-
} else {
|
|
178
|
-
let mut builder = tokio::runtime::Builder::new_multi_thread();
|
|
179
|
-
builder.enable_all().thread_name("kino-tokio");
|
|
180
|
-
if tokio_threads > 0 {
|
|
181
|
-
builder.worker_threads(tokio_threads);
|
|
182
|
-
}
|
|
183
|
-
let runtime = builder
|
|
184
|
-
.build()
|
|
185
|
-
.map_err(|e| io_error(ruby, "tokio runtime failed", e))?;
|
|
186
|
-
let tokio_listener = {
|
|
187
|
-
let _guard = runtime.enter();
|
|
188
|
-
AsyncListener::from_std(listener)
|
|
189
|
-
.map_err(|e| io_error(ruby, "listener setup failed", e))?
|
|
190
|
-
};
|
|
191
|
-
runtime.spawn(accept_loop(
|
|
192
|
-
tokio_listener,
|
|
193
|
-
acceptor,
|
|
194
|
-
server.clone(),
|
|
195
|
-
max_connections,
|
|
196
|
-
shutdown_rx,
|
|
197
|
-
));
|
|
198
|
-
*server.runtime.lock() = RuntimeHandle::MultiThread(runtime);
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
let id = server.id;
|
|
202
|
-
let control_port = match control_bind {
|
|
203
|
-
// Not yet in the registry: on failure Ruby never learns this id, so
|
|
204
|
-
// nothing could ever reach it to shut it down. The accept loop's
|
|
205
|
-
// task holds its own Arc back to `server` (stored inside its own
|
|
206
|
-
// `runtime` field), so just dropping our handle would leak the
|
|
207
|
-
// runtime forever; take it out and stop it explicitly instead.
|
|
208
|
-
// Safe to block here: this is the plain Ruby thread, no async
|
|
209
|
-
// context above it.
|
|
210
|
-
Some(bind) => match crate::control::start(bind, server.clone(), control_token) {
|
|
211
|
-
Ok(port) => port,
|
|
212
|
-
Err(e) => {
|
|
213
|
-
// Nothing is serving yet, so the bound only matters for a
|
|
214
|
-
// wedged shard thread; the default runtime just cancels
|
|
215
|
-
// its one idle accept task.
|
|
216
|
-
let _ = server.shutdown_tx.send(true);
|
|
217
|
-
std::mem::take(&mut *server.runtime.lock()).shutdown(Duration::from_millis(1_000));
|
|
218
|
-
return Err(io_error(ruby, "control start failed", e));
|
|
219
|
-
}
|
|
220
|
-
},
|
|
221
|
-
None => None,
|
|
222
|
-
};
|
|
223
|
-
registry::insert(server);
|
|
224
|
-
Ok((id, local_port, control_port))
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/// Slowloris guard for TLS: a client that completes the TCP connect but then
|
|
228
|
-
/// stalls the handshake would otherwise hold a connection slot indefinitely
|
|
229
|
-
/// (the per-request and header-read deadlines only start once hyper is
|
|
230
|
-
/// serving, i.e. after the handshake). A handshake is a few round trips, so
|
|
231
|
-
/// this is generous even for a high-latency client. Fixed, like the header
|
|
232
|
-
/// timeout: not a knob.
|
|
233
|
-
const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
|
|
234
|
-
|
|
235
|
-
/// What a unix-socket connection reports as its addresses. The peer is
|
|
236
|
-
/// local by definition (REMOTE_ADDR 127.0.0.1), and a socket has no port,
|
|
237
|
-
/// so SERVER_PORT falls back to http's default when the Host header names
|
|
238
|
-
/// none, the way Puma reports unix-socket requests.
|
|
239
|
-
const UNIX_PEER: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
|
|
240
|
-
const UNIX_LOCAL: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 80);
|
|
241
|
-
|
|
242
|
-
/// The accept loop's listener: TCP (optionally behind TLS), or a unix
|
|
243
|
-
/// socket, which carries plain HTTP only.
|
|
244
|
-
pub(crate) enum AsyncListener {
|
|
245
|
-
Tcp(tokio::net::TcpListener),
|
|
246
|
-
Unix(tokio::net::UnixListener),
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/// One accepted connection, before the protocol layer sees it.
|
|
250
|
-
pub(crate) enum Conn {
|
|
251
|
-
Tcp(tokio::net::TcpStream),
|
|
252
|
-
Unix(tokio::net::UnixStream),
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
impl AsyncListener {
|
|
256
|
-
/// Register the bound listener with the current runtime.
|
|
257
|
-
pub(crate) fn from_std(listener: Listener) -> std::io::Result<AsyncListener> {
|
|
258
|
-
Ok(match listener {
|
|
259
|
-
Listener::Tcp(listener) => {
|
|
260
|
-
AsyncListener::Tcp(tokio::net::TcpListener::from_std(listener)?)
|
|
261
|
-
}
|
|
262
|
-
Listener::Unix(listener, _) => {
|
|
263
|
-
AsyncListener::Unix(tokio::net::UnixListener::from_std(listener)?)
|
|
264
|
-
}
|
|
265
|
-
})
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/// The next connection with its (peer, local) addresses.
|
|
269
|
-
pub(crate) async fn accept(&self) -> std::io::Result<(Conn, SocketAddr, SocketAddr)> {
|
|
270
|
-
match self {
|
|
271
|
-
AsyncListener::Tcp(listener) => {
|
|
272
|
-
let (stream, remote_addr) = listener.accept().await?;
|
|
273
|
-
// Small responses must not wait on Nagle + delayed ACK.
|
|
274
|
-
let _ = stream.set_nodelay(true);
|
|
275
|
-
let local_addr = stream
|
|
276
|
-
.local_addr()
|
|
277
|
-
.unwrap_or_else(|_| SocketAddr::from(([0, 0, 0, 0], 0)));
|
|
278
|
-
Ok((Conn::Tcp(stream), remote_addr, local_addr))
|
|
279
|
-
}
|
|
280
|
-
AsyncListener::Unix(listener) => {
|
|
281
|
-
let (stream, _) = listener.accept().await?;
|
|
282
|
-
Ok((Conn::Unix(stream), UNIX_PEER, UNIX_LOCAL))
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
async fn accept_loop(
|
|
289
|
-
listener: AsyncListener,
|
|
290
|
-
acceptor: Option<tokio_rustls::TlsAcceptor>,
|
|
291
|
-
server: Arc<ServerInner>,
|
|
292
|
-
max_connections: usize,
|
|
293
|
-
mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
|
|
294
|
-
) {
|
|
295
|
-
// Bound concurrent connections: unbounded, a flood spawns a task and holds
|
|
296
|
-
// a socket per connection until file descriptors or memory run out. One
|
|
297
|
-
// permit per live connection; acquiring BEFORE accept leaves the excess in
|
|
298
|
-
// the kernel backlog (backpressure) rather than accepting then dropping.
|
|
299
|
-
let conn_limit = Arc::new(tokio::sync::Semaphore::new(max_connections));
|
|
300
|
-
loop {
|
|
301
|
-
let permit = tokio::select! {
|
|
302
|
-
_ = shutdown_rx.changed() => break,
|
|
303
|
-
permit = conn_limit.clone().acquire_owned() => match permit {
|
|
304
|
-
Ok(permit) => permit,
|
|
305
|
-
Err(_) => break, // semaphore closed
|
|
306
|
-
},
|
|
307
|
-
};
|
|
308
|
-
let (conn, remote_addr, local_addr) = tokio::select! {
|
|
309
|
-
_ = shutdown_rx.changed() => break,
|
|
310
|
-
accepted = listener.accept() => match accepted {
|
|
311
|
-
Ok(accepted) => accepted,
|
|
312
|
-
Err(_) => continue, // transient accept error; permit drops, retry
|
|
313
|
-
},
|
|
314
|
-
};
|
|
315
|
-
let server = server.clone();
|
|
316
|
-
let acceptor = acceptor.clone();
|
|
317
|
-
tokio::spawn(async move {
|
|
318
|
-
// Held for the connection's lifetime; dropping it frees a slot.
|
|
319
|
-
let _permit = permit;
|
|
320
|
-
serve_conn(conn, acceptor, server, remote_addr, local_addr).await;
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/// Everything between an accepted connection and hyper: the optional TLS
|
|
326
|
-
/// handshake, then the protocol layer. Shared by the default accept loop
|
|
327
|
-
/// and the sharded one, so connection policy exists exactly once.
|
|
328
|
-
pub(crate) async fn serve_conn(
|
|
329
|
-
conn: Conn,
|
|
330
|
-
acceptor: Option<tokio_rustls::TlsAcceptor>,
|
|
331
|
-
server: Arc<ServerInner>,
|
|
332
|
-
remote_addr: SocketAddr,
|
|
333
|
-
local_addr: SocketAddr,
|
|
334
|
-
) {
|
|
335
|
-
match (conn, acceptor) {
|
|
336
|
-
(Conn::Tcp(stream), Some(acceptor)) => {
|
|
337
|
-
// Handshake failures (port scans, plain HTTP to a TLS
|
|
338
|
-
// port) and stalled handshakes (slowloris) just drop the
|
|
339
|
-
// connection; the timeout bounds the latter.
|
|
340
|
-
let handshake = tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, acceptor.accept(stream));
|
|
341
|
-
let Ok(Ok(tls)) = handshake.await else { return };
|
|
342
|
-
serve_connection(tls, server, remote_addr, local_addr).await;
|
|
343
|
-
}
|
|
344
|
-
(Conn::Tcp(stream), None) => {
|
|
345
|
-
serve_connection(stream, server, remote_addr, local_addr).await
|
|
346
|
-
}
|
|
347
|
-
// TLS over a unix socket is refused at bind time.
|
|
348
|
-
(Conn::Unix(stream), _) => serve_connection(stream, server, remote_addr, local_addr).await,
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
/// Slowloris guard: drop a connection that has not sent its complete request
|
|
353
|
-
/// headers within this window. Long enough never to trip a real client (even
|
|
354
|
-
/// on a slow mobile link), short enough to reap a stalled one. Deliberately a
|
|
355
|
-
/// constant, not a config knob: fine-tuning intake limits is the fronting
|
|
356
|
-
/// proxy's job; the actual hazard was having no default at all. Guards the
|
|
357
|
-
/// HTTP/1 side only: h2 intake is bounded by the TLS-handshake timeout and
|
|
358
|
-
/// the h2 codec's own SETTINGS handling.
|
|
359
|
-
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(15);
|
|
360
|
-
|
|
361
|
-
/// The connection builder every data-plane connection is served with,
|
|
362
|
-
/// in both accept topologies. `http2: true` is the protocol-auto shape:
|
|
363
|
-
/// ALPN-negotiated h2 over TLS, prior-knowledge h2c on plaintext (the
|
|
364
|
-
/// builder sniffs the 24-byte preface once per connection), HTTP/1.x
|
|
365
|
-
/// for everything else. `http2: false` pins the HTTP/1 codec: no sniff,
|
|
366
|
-
/// same wire behavior as a server built without h2.
|
|
367
|
-
///
|
|
368
|
-
/// No auto Date header on either protocol: it costs a clock read per
|
|
369
|
-
/// response (together with timer reads, ~7% of tokio-side cycles in the
|
|
370
|
-
/// profile); it's a SHOULD not a MUST, and apps that need it can set it
|
|
371
|
-
/// themselves.
|
|
372
|
-
///
|
|
373
|
-
/// The http1 timer is installed so header_read_timeout actually fires:
|
|
374
|
-
/// hyper's slow-header guard is inert without one. It arms only while
|
|
375
|
-
/// the request head is being read, so it adds no per-response cost on
|
|
376
|
-
/// the hot path. The h2 side gets a timer too so its own timed
|
|
377
|
-
/// machinery (keep-alive, shutdown deadlines) can fire if ever enabled.
|
|
378
|
-
/// SETTINGS_MAX_CONCURRENT_STREAMS, derived from worker-slot capacity
|
|
379
|
-
/// (workers × threads) instead of hyper's flat 200. Two jobs: an
|
|
380
|
-
/// h2-aware balancer sees the server's real admission and spreads
|
|
381
|
-
/// streams across upstream connections instead of queueing blind, and a
|
|
382
|
-
/// hostile client can't multiply one connection into 200 queued
|
|
383
|
-
/// requests. The floor keeps tiny topologies browser-friendly (one
|
|
384
|
-
/// page's fetches still parallelize; excess streams just queue), the
|
|
385
|
-
/// cap bounds per-connection bookkeeping, and an unknown topology (an
|
|
386
|
-
/// embedder passing zeros) keeps hyper's default.
|
|
387
|
-
fn advertised_streams(workers: usize, threads: usize) -> u32 {
|
|
388
|
-
let slots = workers.saturating_mul(threads);
|
|
389
|
-
if slots == 0 {
|
|
390
|
-
return 200;
|
|
391
|
-
}
|
|
392
|
-
slots.clamp(8, 1024) as u32
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
/// The pool can grow to its ceiling to meet what an h2 balancer sends, so
|
|
396
|
-
/// the ceiling is the admission to advertise (the floor for a fixed pool).
|
|
397
|
-
fn stream_capacity(topology: ®istry::Topology) -> u32 {
|
|
398
|
-
advertised_streams(topology.max_workers, topology.threads)
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
fn conn_builder(http2: bool, max_streams: u32) -> auto::Builder<TokioExecutor> {
|
|
402
|
-
let mut builder = auto::Builder::new(TokioExecutor::new());
|
|
403
|
-
builder
|
|
404
|
-
.http1()
|
|
405
|
-
.timer(TokioTimer::new())
|
|
406
|
-
.header_read_timeout(HEADER_READ_TIMEOUT)
|
|
407
|
-
.auto_date_header(false);
|
|
408
|
-
// Beyond the stream cap, hyper's h2 defaults (16 KB frames, 1 MB
|
|
409
|
-
// windows) stay: a knob sweep (frame size 64K/256K, adaptive
|
|
410
|
-
// windows, 4/8 MB windows) moved the upload lane nowhere or slightly
|
|
411
|
-
// down once read_body coalesced its channel drain: the crossings
|
|
412
|
-
// were the cost, not the codec. The codec's abuse bounds also ship
|
|
413
|
-
// as defaults: 16 KB header lists, 20 pending remote resets then
|
|
414
|
-
// GOAWAY (rapid reset), reset-churn and empty-frame budgets.
|
|
415
|
-
builder
|
|
416
|
-
.http2()
|
|
417
|
-
.timer(TokioTimer::new())
|
|
418
|
-
.auto_date_header(false)
|
|
419
|
-
.max_concurrent_streams(max_streams);
|
|
420
|
-
if http2 {
|
|
421
|
-
builder
|
|
422
|
-
} else {
|
|
423
|
-
builder.http1_only()
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
async fn serve_connection<I>(
|
|
428
|
-
io: I,
|
|
429
|
-
server: Arc<ServerInner>,
|
|
430
|
-
remote_addr: SocketAddr,
|
|
431
|
-
local_addr: SocketAddr,
|
|
432
|
-
) where
|
|
433
|
-
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
|
434
|
-
{
|
|
435
|
-
let http2 = server.http2;
|
|
436
|
-
let max_streams = stream_capacity(&server.topology);
|
|
437
|
-
let mut drain = server.shutdown_tx.subscribe();
|
|
438
|
-
let service =
|
|
439
|
-
service_fn(move |req| handle_request(server.clone(), remote_addr, local_addr, req));
|
|
440
|
-
let builder = conn_builder(http2, max_streams);
|
|
441
|
-
let conn = builder.serve_connection(TokioIo::new(io), service);
|
|
442
|
-
let mut conn = std::pin::pin!(conn);
|
|
443
|
-
// Serve until done, or switch to graceful shutdown when the drain
|
|
444
|
-
// signal fires (stop_accepting): the in-flight request finishes and
|
|
445
|
-
// the connection then closes (`Connection: close` on HTTP/1,
|
|
446
|
-
// GOAWAY on h2), so a balancer moves on instead of feeding a
|
|
447
|
-
// draining server, and teardown never cuts a response mid-stream.
|
|
448
|
-
// A connection that outlives the drain deadline is still cut by the
|
|
449
|
-
// runtime teardown, as before.
|
|
450
|
-
tokio::select! {
|
|
451
|
-
_ = conn.as_mut() => {}
|
|
452
|
-
_ = drain_signal(&mut drain) => {
|
|
453
|
-
conn.as_mut().graceful_shutdown();
|
|
454
|
-
let _ = conn.as_mut().await;
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/// Resolve when the server starts draining. A connection accepted just
|
|
460
|
-
/// before the signal may subscribe just after it, and `changed()` alone
|
|
461
|
-
/// would miss that edge, so the current value is checked first; a
|
|
462
|
-
/// dropped sender (teardown) counts as draining too.
|
|
463
|
-
async fn drain_signal(rx: &mut tokio::sync::watch::Receiver<bool>) {
|
|
464
|
-
if !*rx.borrow_and_update() {
|
|
465
|
-
let _ = rx.changed().await;
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
/// The 503 every rejection path returns; counted for stats. Branding
|
|
470
|
-
/// happens at handle_request's single exit.
|
|
471
|
-
fn unavailable(server: &ServerInner) -> HyperResponse {
|
|
472
|
-
server.rejected.fetch_add(1, Ordering::Relaxed);
|
|
473
|
-
plain_response(503, "Service Unavailable\n")
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
/// Every response carries `Server: kino` unless the app set its own.
|
|
477
|
-
fn branded(mut response: HyperResponse) -> HyperResponse {
|
|
478
|
-
response
|
|
479
|
-
.headers_mut()
|
|
480
|
-
.entry(http::header::SERVER)
|
|
481
|
-
.or_insert(http::HeaderValue::from_static("Kino"));
|
|
482
|
-
response
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/// A single valid Content-Length as a byte count. hyper has already rejected
|
|
486
|
-
/// conflicting/duplicate values, so the first is authoritative; anything
|
|
487
|
-
/// unparseable yields None and the streaming cap still applies.
|
|
488
|
-
fn content_length(headers: &http::HeaderMap) -> Option<u64> {
|
|
489
|
-
headers
|
|
490
|
-
.get(http::header::CONTENT_LENGTH)?
|
|
491
|
-
.to_str()
|
|
492
|
-
.ok()?
|
|
493
|
-
.trim()
|
|
494
|
-
.parse()
|
|
495
|
-
.ok()
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
/// Idle deadline between request-body frames. A client that stalls mid-body
|
|
499
|
-
/// would otherwise hold a worker slot indefinitely (the worker blocks in
|
|
500
|
-
/// read_body). Generous: a real upload sends steadily and resets this each
|
|
501
|
-
/// frame, so only a silent client trips it. Fixed, like the header timeout.
|
|
502
|
-
const BODY_READ_TIMEOUT: Duration = Duration::from_secs(30);
|
|
503
|
-
|
|
504
|
-
async fn handle_request(
|
|
505
|
-
server: Arc<ServerInner>,
|
|
506
|
-
remote_addr: SocketAddr,
|
|
507
|
-
local_addr: SocketAddr,
|
|
508
|
-
req: hyper::Request<hyper::body::Incoming>,
|
|
509
|
-
) -> Result<HyperResponse, std::convert::Infallible> {
|
|
510
|
-
let (parts, body) = req.into_parts();
|
|
511
|
-
|
|
512
|
-
// Access-log metadata is captured only when logging is on: one Instant
|
|
513
|
-
// read plus two small Strings per request. The arrival record is
|
|
514
|
-
// queued now, before the app sees the request, so a hang shows as an
|
|
515
|
-
// arrow with no answer; the completion record follows the response.
|
|
516
|
-
let log_meta = server.access_log.as_ref().map(|log| {
|
|
517
|
-
let target = match parts.uri.query() {
|
|
518
|
-
Some(q) => format!("{}?{}", parts.uri.path(), q),
|
|
519
|
-
None => parts.uri.path().to_string(),
|
|
520
|
-
};
|
|
521
|
-
let method = parts.method.to_string();
|
|
522
|
-
log.write_line(crate::access_log::arrival(
|
|
523
|
-
&method,
|
|
524
|
-
&target,
|
|
525
|
-
remote_addr.ip(),
|
|
526
|
-
));
|
|
527
|
-
(std::time::Instant::now(), method, target)
|
|
528
|
-
});
|
|
529
|
-
|
|
530
|
-
// Body-size guard: an honestly-declared oversize body is refused with a
|
|
531
|
-
// 413 below, before any worker runs. Chunked or lying clients are caught
|
|
532
|
-
// by the forwarder, which caps cumulative bytes and flags an overflow so
|
|
533
|
-
// read_body raises instead of letting the app buffer without bound.
|
|
534
|
-
let max_body = server.max_body_size;
|
|
535
|
-
let oversize =
|
|
536
|
-
max_body > 0 && content_length(&parts.headers).is_some_and(|len| len > max_body as u64);
|
|
537
|
-
|
|
538
|
-
let (head_tx, head_rx) = tokio::sync::oneshot::channel();
|
|
539
|
-
let responder = Arc::new(Responder::new(head_tx));
|
|
540
|
-
|
|
541
|
-
// Stream the request body through a bounded channel: hyper is polled
|
|
542
|
-
// only as fast as the Ruby side consumes (inbound backpressure), and the
|
|
543
|
-
// forwarder dropping the sender is EOF. Bodyless requests (most GETs)
|
|
544
|
-
// skip the channel and the forwarder task entirely: no channel IS the EOF.
|
|
545
|
-
let body_rx = if oversize || hyper::body::Body::is_end_stream(&body) {
|
|
546
|
-
None
|
|
547
|
-
} else {
|
|
548
|
-
let (body_tx, body_rx) = flume::bounded::<bytes::Bytes>(8);
|
|
549
|
-
let responder = responder.clone();
|
|
550
|
-
tokio::spawn(async move {
|
|
551
|
-
let mut body = body;
|
|
552
|
-
let mut total: u64 = 0;
|
|
553
|
-
loop {
|
|
554
|
-
// Idle deadline between frames: a client that stalls mid-body
|
|
555
|
-
// would otherwise pin a worker blocked in read_body. Only the
|
|
556
|
-
// client's silence trips this; a slow APP blocks the forwarder
|
|
557
|
-
// in send_async below instead, which is not timed.
|
|
558
|
-
let frame = match tokio::time::timeout(BODY_READ_TIMEOUT, body.frame()).await {
|
|
559
|
-
Ok(Some(Ok(frame))) => frame,
|
|
560
|
-
Ok(Some(Err(_))) | Ok(None) => break, // body error or clean EOF
|
|
561
|
-
Err(_) => {
|
|
562
|
-
responder.abandon_body(crate::response::BodyAbandon::TimedOut);
|
|
563
|
-
break;
|
|
564
|
-
}
|
|
565
|
-
};
|
|
566
|
-
// Non-data frames (h2 trailers) are dropped by design:
|
|
567
|
-
// Rack has no trailer surface. DATA frames around them
|
|
568
|
-
// still forward, and hyper reports EOF right after.
|
|
569
|
-
if let Ok(data) = frame.into_data() {
|
|
570
|
-
total += data.len() as u64;
|
|
571
|
-
if max_body > 0 && total > max_body as u64 {
|
|
572
|
-
// Past the cap: flag it and stop pulling. Dropping the
|
|
573
|
-
// sender unblocks read_body, which then raises.
|
|
574
|
-
responder.abandon_body(crate::response::BodyAbandon::Oversize);
|
|
575
|
-
break;
|
|
576
|
-
}
|
|
577
|
-
if body_tx.send_async(data).await.is_err() {
|
|
578
|
-
break; // request handle dropped; stop pulling
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
});
|
|
583
|
-
Some(body_rx)
|
|
584
|
-
};
|
|
585
|
-
|
|
586
|
-
let now = std::time::Instant::now();
|
|
587
|
-
let ctx = Box::new(RequestCtx {
|
|
588
|
-
method: parts.method,
|
|
589
|
-
uri: parts.uri,
|
|
590
|
-
version: parts.version,
|
|
591
|
-
headers: parts.headers,
|
|
592
|
-
remote_addr,
|
|
593
|
-
local_addr,
|
|
594
|
-
https: server.https,
|
|
595
|
-
body_rx,
|
|
596
|
-
leftover: None,
|
|
597
|
-
slot: None,
|
|
598
|
-
pin_slab: server.pin_slab.clone(),
|
|
599
|
-
responder,
|
|
600
|
-
enqueued_at: now,
|
|
601
|
-
timed: server.access_log.is_some(),
|
|
602
|
-
wait: Duration::ZERO,
|
|
603
|
-
admitted_at: now,
|
|
604
|
-
gc: None,
|
|
605
|
-
});
|
|
606
|
-
|
|
607
|
-
// Drop guard, not manual decrement: when a client aborts mid-request,
|
|
608
|
-
// hyper DROPS this future at the next await point: a plain decrement
|
|
609
|
-
// after the await would never run, leaking in_flight upward and making
|
|
610
|
-
// shutdown's drain wait its full deadline (observed as a Ctrl-C "hang").
|
|
611
|
-
struct InFlight(Arc<ServerInner>);
|
|
612
|
-
impl Drop for InFlight {
|
|
613
|
-
fn drop(&mut self) {
|
|
614
|
-
self.0.in_flight.fetch_sub(1, Ordering::Relaxed);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
server.in_flight.fetch_add(1, Ordering::Relaxed);
|
|
618
|
-
let _in_flight = InFlight(server.clone());
|
|
619
|
-
|
|
620
|
-
// Single exit point so the access log sees every outcome, 503s included.
|
|
621
|
-
let response: HyperResponse = 'resp: {
|
|
622
|
-
if oversize {
|
|
623
|
-
break 'resp plain_response(413, "Payload Too Large\n");
|
|
624
|
-
}
|
|
625
|
-
if server.lanes {
|
|
626
|
-
if !dispatch_to_lane(&server, ctx).await {
|
|
627
|
-
break 'resp unavailable(&server);
|
|
628
|
-
}
|
|
629
|
-
} else {
|
|
630
|
-
// Clone the sender per request (not per connection) so a
|
|
631
|
-
// long-lived keep-alive connection can't hold the queue open
|
|
632
|
-
// during drain.
|
|
633
|
-
let Some(tx) = server.req_tx.lock().clone() else {
|
|
634
|
-
break 'resp unavailable(&server);
|
|
635
|
-
};
|
|
636
|
-
|
|
637
|
-
// try_send first: when the queue has room (the overwhelmingly
|
|
638
|
-
// common case) this skips registering a tokio timer + its
|
|
639
|
-
// clock reads. Only a genuinely full queue pays for the timed
|
|
640
|
-
// wait before the 503.
|
|
641
|
-
match tx.try_send(ctx) {
|
|
642
|
-
Ok(()) => {}
|
|
643
|
-
Err(flume::TrySendError::Disconnected(_)) => {
|
|
644
|
-
break 'resp unavailable(&server);
|
|
645
|
-
}
|
|
646
|
-
Err(flume::TrySendError::Full(ctx)) => {
|
|
647
|
-
let timeout = Duration::from_millis(server.queue_timeout_ms);
|
|
648
|
-
let enqueued = tokio::time::timeout(timeout, tx.send_async(ctx)).await;
|
|
649
|
-
if !matches!(enqueued, Ok(Ok(()))) {
|
|
650
|
-
// Timed out or queue closed mid-send; ctx was
|
|
651
|
-
// dropped unsent either way.
|
|
652
|
-
break 'resp unavailable(&server);
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
// request_timeout: the response head must arrive within the
|
|
659
|
-
// deadline or the client gets an immediate 504; the worker keeps
|
|
660
|
-
// running and its eventual response is dropped harmlessly (the
|
|
661
|
-
// responder's first-claimant race makes the late send a no-op).
|
|
662
|
-
// Caveat by design: a CPU-stuck handler still occupies its slot
|
|
663
|
-
// until it finishes; interrupting arbitrary Ruby would require
|
|
664
|
-
// Thread#raise-style unsafety.
|
|
665
|
-
if server.request_timeout_ms > 0 {
|
|
666
|
-
let deadline = Duration::from_millis(server.request_timeout_ms);
|
|
667
|
-
match tokio::time::timeout(deadline, head_rx).await {
|
|
668
|
-
Ok(result) => {
|
|
669
|
-
result.unwrap_or_else(|_| plain_response(500, "Internal Server Error\n"))
|
|
670
|
-
}
|
|
671
|
-
Err(_elapsed) => {
|
|
672
|
-
server.timeouts.fetch_add(1, Ordering::Relaxed);
|
|
673
|
-
plain_response(504, "Gateway Timeout\n")
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
} else {
|
|
677
|
-
head_rx
|
|
678
|
-
.await
|
|
679
|
-
.unwrap_or_else(|_| plain_response(500, "Internal Server Error\n"))
|
|
680
|
-
}
|
|
681
|
-
};
|
|
682
|
-
|
|
683
|
-
if let (Some(log), Some((start, method, target))) = (server.access_log.as_ref(), log_meta) {
|
|
684
|
-
// The worker attached its timing to the response head; a 503 or
|
|
685
|
-
// 504 never reached a worker and carries none.
|
|
686
|
-
let timing = response
|
|
687
|
-
.extensions()
|
|
688
|
-
.get::<crate::access_log::Timing>()
|
|
689
|
-
.copied();
|
|
690
|
-
log.write_line(crate::access_log::completion(
|
|
691
|
-
response.status().as_u16(),
|
|
692
|
-
&method,
|
|
693
|
-
&target,
|
|
694
|
-
start.elapsed(),
|
|
695
|
-
timing,
|
|
696
|
-
));
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
Ok(branded(response))
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
/// One dispatch attempt's outcome; `Full` hands the ctx back for a retry.
|
|
703
|
-
enum Dispatch {
|
|
704
|
-
Sent,
|
|
705
|
-
Full(BoxedCtx),
|
|
706
|
-
Closed,
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
/// Lane dispatch: prefer an awake (non-parked) lane with room (a hot
|
|
710
|
-
/// worker keeps taking without ever paying a futex wake), then any lane
|
|
711
|
-
/// with room. All lanes full = genuine overload: retry briefly up to
|
|
712
|
-
/// queue_timeout, then give up (caller 503s).
|
|
713
|
-
fn try_dispatch(server: &ServerInner, mut ctx: BoxedCtx) -> Dispatch {
|
|
714
|
-
let slots = server.slots.read();
|
|
715
|
-
let n = slots.len();
|
|
716
|
-
if n == 0 {
|
|
717
|
-
return Dispatch::Full(ctx);
|
|
718
|
-
}
|
|
719
|
-
let start = server.lane_cursor.fetch_add(1, Ordering::Relaxed);
|
|
720
|
-
let mut any_open = false;
|
|
721
|
-
for pass in 0..2 {
|
|
722
|
-
for k in 0..n {
|
|
723
|
-
let slot = &slots[(start + k) % n];
|
|
724
|
-
if pass == 0 && slot.parked.load(Ordering::Relaxed) {
|
|
725
|
-
continue;
|
|
726
|
-
}
|
|
727
|
-
let guard = slot.lane_tx.lock();
|
|
728
|
-
let Some(tx) = guard.as_ref() else { continue };
|
|
729
|
-
any_open = true;
|
|
730
|
-
// Checked under the lane lock, which WorkerSlot::retire also
|
|
731
|
-
// takes: see there for the ordering.
|
|
732
|
-
if slot.retired.load(Ordering::SeqCst) {
|
|
733
|
-
continue;
|
|
734
|
-
}
|
|
735
|
-
match tx.try_send(ctx) {
|
|
736
|
-
Ok(()) => return Dispatch::Sent,
|
|
737
|
-
Err(flume::TrySendError::Full(c)) | Err(flume::TrySendError::Disconnected(c)) => {
|
|
738
|
-
ctx = c;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if any_open {
|
|
744
|
-
Dispatch::Full(ctx) // overload: every open lane is full
|
|
745
|
-
} else {
|
|
746
|
-
Dispatch::Closed // draining: all lanes closed
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
async fn dispatch_to_lane(server: &Arc<ServerInner>, ctx: BoxedCtx) -> bool {
|
|
751
|
-
let mut pending = ctx;
|
|
752
|
-
let deadline = tokio::time::Instant::now() + Duration::from_millis(server.queue_timeout_ms);
|
|
753
|
-
loop {
|
|
754
|
-
match try_dispatch(server, pending) {
|
|
755
|
-
Dispatch::Sent => return true,
|
|
756
|
-
Dispatch::Closed => return false,
|
|
757
|
-
Dispatch::Full(ctx) => {
|
|
758
|
-
if tokio::time::Instant::now() >= deadline {
|
|
759
|
-
return false;
|
|
760
|
-
}
|
|
761
|
-
pending = ctx;
|
|
762
|
-
tokio::time::sleep(Duration::from_micros(500)).await;
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
// --- lifecycle natives ---
|
|
769
|
-
// All tolerant of an already-removed server: shutdown must be idempotent and
|
|
770
|
-
// late-waking workers must see "gone" as a no-op, never an exception.
|
|
771
|
-
|
|
772
|
-
pub fn register_worker(ruby: &Ruby, server_id: u64) -> Result<usize, Error> {
|
|
773
|
-
Ok(registry::get(ruby, server_id)?.register_worker())
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
pub fn stop_accepting(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
777
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
778
|
-
server
|
|
779
|
-
.state
|
|
780
|
-
.store(registry::STATE_DRAINING, Ordering::Relaxed);
|
|
781
|
-
let _ = server.shutdown_tx.send(true);
|
|
782
|
-
}
|
|
783
|
-
Ok(())
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/// Ruby reports the worker pool up; /ready starts answering 200.
|
|
787
|
-
pub fn control_ready(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
788
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
789
|
-
server.state.store(registry::STATE_READY, Ordering::Relaxed);
|
|
790
|
-
}
|
|
791
|
-
Ok(())
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
/// One worker respawn, recorded by the Ruby supervisor.
|
|
795
|
-
pub fn record_respawn(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
796
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
797
|
-
server.respawns.fetch_add(1, Ordering::Relaxed);
|
|
798
|
-
}
|
|
799
|
-
Ok(())
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
pub fn close_queue(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
803
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
804
|
-
server.req_tx.lock().take();
|
|
805
|
-
for slot in server.slots.read().iter() {
|
|
806
|
-
slot.lane_tx.lock().take();
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
Ok(())
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
pub fn queue_stats(_ruby: &Ruby, server_id: u64) -> Result<(usize, usize), Error> {
|
|
813
|
-
match registry::try_get(server_id) {
|
|
814
|
-
Some(server) => Ok((server.queued(), server.in_flight.load(Ordering::Relaxed))),
|
|
815
|
-
None => Ok((0, 0)),
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
fn abort_slot(slot: &WorkerSlot) {
|
|
820
|
-
for weak in slot.current.lock().drain(..) {
|
|
821
|
-
if let Some(responder) = weak.upgrade() {
|
|
822
|
-
responder.respond_500_if_unsent();
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
// A dead worker holds nothing: every request it had is answered above
|
|
826
|
-
// (or already was), so the slot is quiescent from here on. Without
|
|
827
|
-
// this, a crashed worker's slot reports in_flight>=1 forever (the
|
|
828
|
-
// supervisor never reuses a slot after a crash), wedging /stats,
|
|
829
|
-
// /metrics and server.stats with a phantom busy worker.
|
|
830
|
-
slot.in_flight.store(0, Ordering::Relaxed);
|
|
831
|
-
// Lane mode: this worker is dead. Close its lane so the dispatcher
|
|
832
|
-
// skips it, and drain anything queued; dropping each ctx fires the
|
|
833
|
-
// Drop-500 backstop so those clients aren't left hanging.
|
|
834
|
-
slot.lane_tx.lock().take();
|
|
835
|
-
slot.parked.store(true, Ordering::Relaxed);
|
|
836
|
-
if let Some(rx) = slot.lane_rx.as_ref() {
|
|
837
|
-
while rx.try_recv().is_ok() {}
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
pub fn abort_inflight(ruby: &Ruby, server_id: u64, worker_id: usize) -> Result<(), Error> {
|
|
842
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
843
|
-
let slot = server.slot(ruby, worker_id)?;
|
|
844
|
-
abort_slot(&slot);
|
|
845
|
-
}
|
|
846
|
-
Ok(())
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
pub fn abort_all_inflight(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
850
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
851
|
-
for slot in server.slots.read().iter() {
|
|
852
|
-
abort_slot(slot);
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
Ok(())
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
pub fn interrupt_all_workers(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
859
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
860
|
-
for slot in server.slots.read().iter() {
|
|
861
|
-
slot.interrupted.store(true, Ordering::SeqCst);
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
Ok(())
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
pub fn shutdown_runtime(_ruby: &Ruby, server_id: u64, timeout_ms: u64) -> Result<(), Error> {
|
|
868
|
-
if let Some(server) = registry::remove(server_id) {
|
|
869
|
-
let _ = server.shutdown_tx.send(true);
|
|
870
|
-
std::mem::take(&mut *server.runtime.lock()).shutdown(Duration::from_millis(timeout_ms));
|
|
871
|
-
// The listener is closed with the runtime; its socket file is not.
|
|
872
|
-
if let Some(path) = &server.unix_path {
|
|
873
|
-
crate::listen::cleanup_unix(path);
|
|
874
|
-
}
|
|
875
|
-
}
|
|
876
|
-
Ok(())
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
/// The GC anchor for this server's zero-copy pins: the Ruby Server holds
|
|
880
|
-
/// it for its lifetime, so pinned buffers survive worker-ractor crashes.
|
|
881
|
-
pub fn pin_keeper(
|
|
882
|
-
ruby: &Ruby,
|
|
883
|
-
server_id: u64,
|
|
884
|
-
) -> Result<magnus::typed_data::Obj<crate::pin::PinKeeper>, Error> {
|
|
885
|
-
let server = registry::get(ruby, server_id)?;
|
|
886
|
-
Ok(ruby.obj_wrap(crate::pin::PinKeeper(server.pin_slab.clone())))
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
/// Full stats snapshot: [queued, in_flight, served, rejected, timeouts,
|
|
890
|
-
/// respawns, lane_depths]. lane_depths is nil unless lane dispatch is on.
|
|
891
|
-
#[allow(clippy::type_complexity)]
|
|
892
|
-
pub fn server_stats(
|
|
893
|
-
_ruby: &Ruby,
|
|
894
|
-
server_id: u64,
|
|
895
|
-
) -> Result<(usize, usize, u64, u64, u64, u64, Option<Vec<usize>>), Error> {
|
|
896
|
-
let Some(server) = registry::try_get(server_id) else {
|
|
897
|
-
return Ok((0, 0, 0, 0, 0, 0, None));
|
|
898
|
-
};
|
|
899
|
-
let lane_depths = server.lane_depths();
|
|
900
|
-
let queued = server.req_rx.len() + lane_depths.as_ref().map_or(0, |d| d.iter().sum::<usize>());
|
|
901
|
-
Ok((
|
|
902
|
-
queued,
|
|
903
|
-
server.in_flight.load(Ordering::Relaxed),
|
|
904
|
-
server.served.load(Ordering::Relaxed),
|
|
905
|
-
server.rejected.load(Ordering::Relaxed),
|
|
906
|
-
server.timeouts.load(Ordering::Relaxed),
|
|
907
|
-
server.respawns.load(Ordering::Relaxed),
|
|
908
|
-
lane_depths,
|
|
909
|
-
))
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
/// Queue-wait count and summed seconds for Server#stats parity. Zeros when
|
|
913
|
-
/// the server is gone.
|
|
914
|
-
pub fn queue_time(_ruby: &Ruby, server_id: u64) -> Result<(u64, f64), Error> {
|
|
915
|
-
let Some(server) = registry::try_get(server_id) else {
|
|
916
|
-
return Ok((0, 0.0));
|
|
917
|
-
};
|
|
918
|
-
let h = server.queue_histogram.snapshot();
|
|
919
|
-
Ok((h.count, h.sum_seconds()))
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
/// One worker slot's [index, served, in_flight, busy_ms, quarantined] row.
|
|
923
|
-
pub type WorkerStatRow = (usize, u64, usize, u64, bool, bool);
|
|
924
|
-
|
|
925
|
-
/// Per-slot rows for Server#stats parity: [index, served, in_flight,
|
|
926
|
-
/// busy_ms, quarantined] each. Empty when the server is gone.
|
|
927
|
-
pub fn worker_stats(_ruby: &Ruby, server_id: u64) -> Result<Vec<WorkerStatRow>, Error> {
|
|
928
|
-
let Some(server) = registry::try_get(server_id) else {
|
|
929
|
-
return Ok(Vec::new());
|
|
930
|
-
};
|
|
931
|
-
Ok(crate::control::collect_worker_status(&server)
|
|
932
|
-
.into_iter()
|
|
933
|
-
.map(|w| {
|
|
934
|
-
(
|
|
935
|
-
w.index,
|
|
936
|
-
w.served,
|
|
937
|
-
w.in_flight,
|
|
938
|
-
w.busy_ms,
|
|
939
|
-
w.quarantined,
|
|
940
|
-
w.retired,
|
|
941
|
-
)
|
|
942
|
-
})
|
|
943
|
-
.collect())
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
/// Mark a slot quarantined (the monitor has abandoned it as wedged).
|
|
947
|
-
pub fn quarantine_slot(ruby: &Ruby, server_id: u64, worker_id: usize) -> Result<(), Error> {
|
|
948
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
949
|
-
let slot = server.slot(ruby, worker_id)?;
|
|
950
|
-
slot.quarantined.store(true, Ordering::Relaxed);
|
|
951
|
-
}
|
|
952
|
-
Ok(())
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
/// Send a slot's worker home once idle (pool scale-down); see
|
|
956
|
-
/// registry::WorkerSlot::retire. An unknown id is a caller bug: raise.
|
|
957
|
-
pub fn retire_slot(ruby: &Ruby, server_id: u64, worker_id: usize) -> Result<(), Error> {
|
|
958
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
959
|
-
server.slot(ruby, worker_id)?.retire();
|
|
960
|
-
}
|
|
961
|
-
Ok(())
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
/// Hand a retired slot to a new worker (pool scale-up reusing a slot).
|
|
965
|
-
pub fn reset_slot(ruby: &Ruby, server_id: u64, worker_id: usize) -> Result<(), Error> {
|
|
966
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
967
|
-
server.slot(ruby, worker_id)?.reset();
|
|
968
|
-
}
|
|
969
|
-
Ok(())
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
/// The Ruby pool reports how many workers are alive and serving.
|
|
973
|
-
pub fn set_active_workers(_ruby: &Ruby, server_id: u64, count: usize) -> Result<(), Error> {
|
|
974
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
975
|
-
server.active_workers.store(count, Ordering::Relaxed);
|
|
976
|
-
}
|
|
977
|
-
Ok(())
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
/// One worker added by the pool scaler.
|
|
981
|
-
pub fn record_scale_up(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
982
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
983
|
-
server.scale_ups.fetch_add(1, Ordering::Relaxed);
|
|
984
|
-
}
|
|
985
|
-
Ok(())
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
/// One worker retired by the pool scaler.
|
|
989
|
-
pub fn record_scale_down(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
990
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
991
|
-
server.scale_downs.fetch_add(1, Ordering::Relaxed);
|
|
992
|
-
}
|
|
993
|
-
Ok(())
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
/// [active_workers, max_workers, scale_ups, scale_downs] for Server#stats.
|
|
997
|
-
/// Zeros when the server is gone.
|
|
998
|
-
pub fn pool_stats(_ruby: &Ruby, server_id: u64) -> Result<(usize, usize, u64, u64), Error> {
|
|
999
|
-
let Some(server) = registry::try_get(server_id) else {
|
|
1000
|
-
return Ok((0, 0, 0, 0));
|
|
1001
|
-
};
|
|
1002
|
-
Ok((
|
|
1003
|
-
server.active_workers.load(Ordering::Relaxed),
|
|
1004
|
-
server.topology.max_workers,
|
|
1005
|
-
server.scale_ups.load(Ordering::Relaxed),
|
|
1006
|
-
server.scale_downs.load(Ordering::Relaxed),
|
|
1007
|
-
))
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
/// One replacement spawned by the quarantine monitor.
|
|
1011
|
-
pub fn record_quarantine_replacement(_ruby: &Ruby, server_id: u64) -> Result<(), Error> {
|
|
1012
|
-
if let Some(server) = registry::try_get(server_id) {
|
|
1013
|
-
server
|
|
1014
|
-
.quarantine_replacements
|
|
1015
|
-
.fetch_add(1, Ordering::Relaxed);
|
|
1016
|
-
}
|
|
1017
|
-
Ok(())
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
#[cfg(test)]
|
|
1021
|
-
mod tests {
|
|
1022
|
-
use super::*;
|
|
1023
|
-
use crate::registry::{test_server, LANE_DEPTH};
|
|
1024
|
-
use crate::request::test_ctx;
|
|
1025
|
-
|
|
1026
|
-
/// Serve one real connection through the production `serve_connection`
|
|
1027
|
-
/// over an in-memory pipe, against a queue the test consumes itself (a
|
|
1028
|
-
/// stand-in for the Ruby worker). Returns the client end.
|
|
1029
|
-
fn spawn_conn(server: Arc<ServerInner>) -> tokio::io::DuplexStream {
|
|
1030
|
-
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
|
|
1031
|
-
tokio::spawn(serve_connection(
|
|
1032
|
-
server_io,
|
|
1033
|
-
server,
|
|
1034
|
-
"127.0.0.1:40000".parse().expect("static addr"),
|
|
1035
|
-
"127.0.0.1:9292".parse().expect("static addr"),
|
|
1036
|
-
));
|
|
1037
|
-
client_io
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
async fn take_ctx(server: &Arc<ServerInner>) -> BoxedCtx {
|
|
1041
|
-
server.req_rx.recv_async().await.expect("a queued request")
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
/// Read the request body the way a worker does: leftover first, then
|
|
1045
|
-
/// the forwarder channel until the sender drops (EOF).
|
|
1046
|
-
async fn drain_body(ctx: &mut RequestCtx) -> Vec<u8> {
|
|
1047
|
-
let mut out = Vec::new();
|
|
1048
|
-
if let Some(leftover) = ctx.leftover.take() {
|
|
1049
|
-
out.extend_from_slice(&leftover);
|
|
1050
|
-
}
|
|
1051
|
-
if let Some(rx) = &ctx.body_rx {
|
|
1052
|
-
while let Ok(chunk) = rx.recv_async().await {
|
|
1053
|
-
out.extend_from_slice(&chunk);
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
out
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
#[tokio::test]
|
|
1060
|
-
async fn h2c_prior_knowledge_reaches_the_queue_as_http2() {
|
|
1061
|
-
use http_body_util::{BodyExt, Full};
|
|
1062
|
-
|
|
1063
|
-
let server = test_server(false, 4);
|
|
1064
|
-
let client_io = spawn_conn(server.clone());
|
|
1065
|
-
|
|
1066
|
-
let worker = tokio::spawn(async move {
|
|
1067
|
-
let ctx = take_ctx(&server).await;
|
|
1068
|
-
assert_eq!(ctx.version, http::Version::HTTP_2);
|
|
1069
|
-
// The :authority pseudo-header arrives in the URI, where
|
|
1070
|
-
// build_env picks it up; no Host header exists on h2.
|
|
1071
|
-
assert_eq!(
|
|
1072
|
-
ctx.uri.authority().map(|a| a.as_str()),
|
|
1073
|
-
Some("kino.test:8443")
|
|
1074
|
-
);
|
|
1075
|
-
assert!(ctx.headers.get(http::header::HOST).is_none());
|
|
1076
|
-
assert!(ctx.responder.send_response(plain_response(200, "ok\n")));
|
|
1077
|
-
});
|
|
1078
|
-
|
|
1079
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1080
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1081
|
-
TokioIo::new(client_io),
|
|
1082
|
-
)
|
|
1083
|
-
.await
|
|
1084
|
-
.expect("h2c prior-knowledge handshake");
|
|
1085
|
-
tokio::spawn(conn);
|
|
1086
|
-
let request = hyper::Request::builder()
|
|
1087
|
-
.uri("http://kino.test:8443/")
|
|
1088
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1089
|
-
.expect("request");
|
|
1090
|
-
let response = sender.send_request(request).await.expect("h2 response");
|
|
1091
|
-
assert_eq!(response.status(), 200);
|
|
1092
|
-
assert_eq!(
|
|
1093
|
-
response.headers().get("server").expect("branded"),
|
|
1094
|
-
"Kino",
|
|
1095
|
-
"responses stay branded over h2"
|
|
1096
|
-
);
|
|
1097
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1098
|
-
assert_eq!(&body.to_bytes()[..], b"ok\n");
|
|
1099
|
-
worker.await.expect("worker assertions");
|
|
1100
|
-
}
|
|
1101
|
-
|
|
1102
|
-
#[tokio::test]
|
|
1103
|
-
async fn h1_is_still_served_by_the_auto_builder() {
|
|
1104
|
-
use http_body_util::{BodyExt, Full};
|
|
1105
|
-
|
|
1106
|
-
let server = test_server(false, 4);
|
|
1107
|
-
let client_io = spawn_conn(server.clone());
|
|
1108
|
-
|
|
1109
|
-
let worker = tokio::spawn(async move {
|
|
1110
|
-
let ctx = take_ctx(&server).await;
|
|
1111
|
-
assert_eq!(ctx.version, http::Version::HTTP_11);
|
|
1112
|
-
assert!(ctx.responder.send_response(plain_response(200, "h1\n")));
|
|
1113
|
-
});
|
|
1114
|
-
|
|
1115
|
-
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(client_io))
|
|
1116
|
-
.await
|
|
1117
|
-
.expect("h1 handshake");
|
|
1118
|
-
tokio::spawn(conn);
|
|
1119
|
-
let request = hyper::Request::builder()
|
|
1120
|
-
.uri("/")
|
|
1121
|
-
.header("host", "kino.test")
|
|
1122
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1123
|
-
.expect("request");
|
|
1124
|
-
let response = sender.send_request(request).await.expect("h1 response");
|
|
1125
|
-
assert_eq!(response.status(), 200);
|
|
1126
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1127
|
-
assert_eq!(&body.to_bytes()[..], b"h1\n");
|
|
1128
|
-
worker.await.expect("worker assertions");
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
#[tokio::test]
|
|
1132
|
-
async fn http2_off_refuses_the_preface_but_serves_h1() {
|
|
1133
|
-
use http_body_util::{BodyExt, Full};
|
|
1134
|
-
use hyper::service::service_fn;
|
|
1135
|
-
|
|
1136
|
-
// Driven at the builder seam: conn_builder(false) is what a
|
|
1137
|
-
// ServerInner with http2 off serves every connection with.
|
|
1138
|
-
let stub = || {
|
|
1139
|
-
service_fn(|_req: hyper::Request<hyper::body::Incoming>| async {
|
|
1140
|
-
Ok::<_, std::convert::Infallible>(plain_response(200, "pinned\n"))
|
|
1141
|
-
})
|
|
1142
|
-
};
|
|
1143
|
-
|
|
1144
|
-
// An h2 prior-knowledge client must fail: the pinned h1 codec
|
|
1145
|
-
// reads the preface as a malformed request line.
|
|
1146
|
-
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
|
|
1147
|
-
tokio::spawn(async move {
|
|
1148
|
-
let _ = conn_builder(false, 200)
|
|
1149
|
-
.serve_connection(TokioIo::new(server_io), stub())
|
|
1150
|
-
.await;
|
|
1151
|
-
});
|
|
1152
|
-
let refused = async {
|
|
1153
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1154
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1155
|
-
TokioIo::new(client_io),
|
|
1156
|
-
)
|
|
1157
|
-
.await?;
|
|
1158
|
-
tokio::spawn(conn);
|
|
1159
|
-
let request = hyper::Request::builder()
|
|
1160
|
-
.uri("http://kino.test/")
|
|
1161
|
-
.body(Full::new(bytes::Bytes::new()))?;
|
|
1162
|
-
sender.send_request(request).await?;
|
|
1163
|
-
Ok::<_, Box<dyn std::error::Error>>(())
|
|
1164
|
-
}
|
|
1165
|
-
.await;
|
|
1166
|
-
assert!(refused.is_err(), "h2 must not be served when pinned to h1");
|
|
1167
|
-
|
|
1168
|
-
// The same pinned builder serves a plain h1 client.
|
|
1169
|
-
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
|
|
1170
|
-
tokio::spawn(async move {
|
|
1171
|
-
let _ = conn_builder(false, 200)
|
|
1172
|
-
.serve_connection(TokioIo::new(server_io), stub())
|
|
1173
|
-
.await;
|
|
1174
|
-
});
|
|
1175
|
-
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(client_io))
|
|
1176
|
-
.await
|
|
1177
|
-
.expect("h1 handshake");
|
|
1178
|
-
tokio::spawn(conn);
|
|
1179
|
-
let request = hyper::Request::builder()
|
|
1180
|
-
.uri("/")
|
|
1181
|
-
.header("host", "kino.test")
|
|
1182
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1183
|
-
.expect("request");
|
|
1184
|
-
let response = sender.send_request(request).await.expect("h1 response");
|
|
1185
|
-
assert_eq!(response.status(), 200);
|
|
1186
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1187
|
-
assert_eq!(&body.to_bytes()[..], b"pinned\n");
|
|
1188
|
-
}
|
|
1189
|
-
|
|
1190
|
-
#[tokio::test]
|
|
1191
|
-
async fn h2_upload_forwards_data_and_drops_trailers() {
|
|
1192
|
-
use http_body_util::{BodyExt, StreamBody};
|
|
1193
|
-
use hyper::body::Frame;
|
|
1194
|
-
|
|
1195
|
-
let server = test_server(false, 4);
|
|
1196
|
-
let client_io = spawn_conn(server.clone());
|
|
1197
|
-
|
|
1198
|
-
let worker = tokio::spawn(async move {
|
|
1199
|
-
let mut ctx = take_ctx(&server).await;
|
|
1200
|
-
assert_eq!(ctx.version, http::Version::HTTP_2);
|
|
1201
|
-
let body = drain_body(&mut ctx).await;
|
|
1202
|
-
assert_eq!(&body[..], b"hello world");
|
|
1203
|
-
assert!(
|
|
1204
|
-
ctx.responder.body_abandoned().is_none(),
|
|
1205
|
-
"a trailer frame must not abort the body read"
|
|
1206
|
-
);
|
|
1207
|
-
let response = hyper::Response::builder()
|
|
1208
|
-
.status(200)
|
|
1209
|
-
.body(crate::response::full_body(bytes::Bytes::from(
|
|
1210
|
-
body.len().to_string(),
|
|
1211
|
-
)))
|
|
1212
|
-
.expect("response");
|
|
1213
|
-
assert!(ctx.responder.send_response(response));
|
|
1214
|
-
});
|
|
1215
|
-
|
|
1216
|
-
let (frames_tx, frames_rx) =
|
|
1217
|
-
flume::bounded::<Result<Frame<bytes::Bytes>, std::io::Error>>(4);
|
|
1218
|
-
frames_tx
|
|
1219
|
-
.send(Ok(Frame::data(bytes::Bytes::from_static(b"hello "))))
|
|
1220
|
-
.expect("frame");
|
|
1221
|
-
frames_tx
|
|
1222
|
-
.send(Ok(Frame::data(bytes::Bytes::from_static(b"world"))))
|
|
1223
|
-
.expect("frame");
|
|
1224
|
-
let mut trailers = http::HeaderMap::new();
|
|
1225
|
-
trailers.insert("x-checksum", "ignored".parse().expect("value"));
|
|
1226
|
-
frames_tx
|
|
1227
|
-
.send(Ok(Frame::trailers(trailers)))
|
|
1228
|
-
.expect("frame");
|
|
1229
|
-
drop(frames_tx); // EOS
|
|
1230
|
-
|
|
1231
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1232
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1233
|
-
TokioIo::new(client_io),
|
|
1234
|
-
)
|
|
1235
|
-
.await
|
|
1236
|
-
.expect("h2 handshake");
|
|
1237
|
-
tokio::spawn(conn);
|
|
1238
|
-
let request = hyper::Request::builder()
|
|
1239
|
-
.method("POST")
|
|
1240
|
-
.uri("http://kino.test/upload")
|
|
1241
|
-
.body(StreamBody::new(frames_rx.into_stream()))
|
|
1242
|
-
.expect("request");
|
|
1243
|
-
let response = sender.send_request(request).await.expect("h2 response");
|
|
1244
|
-
assert_eq!(response.status(), 200);
|
|
1245
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1246
|
-
assert_eq!(&body.to_bytes()[..], b"11");
|
|
1247
|
-
worker.await.expect("worker assertions");
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
#[tokio::test]
|
|
1251
|
-
async fn h2_streaming_response_arrives_chunked() {
|
|
1252
|
-
use http_body_util::{BodyExt, Full};
|
|
1253
|
-
|
|
1254
|
-
let server = test_server(false, 4);
|
|
1255
|
-
let client_io = spawn_conn(server.clone());
|
|
1256
|
-
|
|
1257
|
-
let worker = tokio::spawn(async move {
|
|
1258
|
-
let ctx = take_ctx(&server).await;
|
|
1259
|
-
let started = ctx
|
|
1260
|
-
.responder
|
|
1261
|
-
.send_stream_head(hyper::Response::builder().status(200))
|
|
1262
|
-
.expect("valid head");
|
|
1263
|
-
assert!(started);
|
|
1264
|
-
let frames = ctx.responder.body_sender().expect("open stream");
|
|
1265
|
-
for chunk in [&b"alpha "[..], &b"beta "[..], &b"gamma"[..]] {
|
|
1266
|
-
frames
|
|
1267
|
-
.send_async(Ok(hyper::body::Frame::data(bytes::Bytes::from_static(
|
|
1268
|
-
chunk,
|
|
1269
|
-
))))
|
|
1270
|
-
.await
|
|
1271
|
-
.expect("chunk accepted");
|
|
1272
|
-
}
|
|
1273
|
-
ctx.responder.finish_stream();
|
|
1274
|
-
});
|
|
1275
|
-
|
|
1276
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1277
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1278
|
-
TokioIo::new(client_io),
|
|
1279
|
-
)
|
|
1280
|
-
.await
|
|
1281
|
-
.expect("h2 handshake");
|
|
1282
|
-
tokio::spawn(conn);
|
|
1283
|
-
let request = hyper::Request::builder()
|
|
1284
|
-
.uri("http://kino.test/stream")
|
|
1285
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1286
|
-
.expect("request");
|
|
1287
|
-
let response = sender.send_request(request).await.expect("h2 response");
|
|
1288
|
-
assert_eq!(response.status(), 200);
|
|
1289
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1290
|
-
assert_eq!(&body.to_bytes()[..], b"alpha beta gamma");
|
|
1291
|
-
worker.await.expect("worker assertions");
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
#[tokio::test]
|
|
1295
|
-
async fn h2_multiplexes_concurrent_streams_into_the_queue() {
|
|
1296
|
-
use http_body_util::{BodyExt, Full};
|
|
1297
|
-
|
|
1298
|
-
let server = test_server(false, 4);
|
|
1299
|
-
let client_io = spawn_conn(server.clone());
|
|
1300
|
-
|
|
1301
|
-
// Both streams must be queued before either is answered: that is
|
|
1302
|
-
// multiplexing observable at the worker boundary; and answering
|
|
1303
|
-
// them in reverse order proves stream completion is not FIFO.
|
|
1304
|
-
let worker = tokio::spawn(async move {
|
|
1305
|
-
let first = take_ctx(&server).await;
|
|
1306
|
-
let second = take_ctx(&server).await;
|
|
1307
|
-
let order = [second.uri.path().to_string(), first.uri.path().to_string()];
|
|
1308
|
-
assert!(second.responder.send_response(plain_response(200, "two\n")));
|
|
1309
|
-
assert!(first.responder.send_response(plain_response(200, "one\n")));
|
|
1310
|
-
order
|
|
1311
|
-
});
|
|
1312
|
-
|
|
1313
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1314
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1315
|
-
TokioIo::new(client_io),
|
|
1316
|
-
)
|
|
1317
|
-
.await
|
|
1318
|
-
.expect("h2 handshake");
|
|
1319
|
-
tokio::spawn(conn);
|
|
1320
|
-
let req = |path: &str| {
|
|
1321
|
-
hyper::Request::builder()
|
|
1322
|
-
.uri(format!("http://kino.test{path}"))
|
|
1323
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1324
|
-
.expect("request")
|
|
1325
|
-
};
|
|
1326
|
-
let (one, two) = tokio::join!(
|
|
1327
|
-
sender.send_request(req("/one")),
|
|
1328
|
-
sender.send_request(req("/two"))
|
|
1329
|
-
);
|
|
1330
|
-
let one = one.expect("first stream");
|
|
1331
|
-
let two = two.expect("second stream");
|
|
1332
|
-
assert_eq!(one.status(), 200);
|
|
1333
|
-
assert_eq!(two.status(), 200);
|
|
1334
|
-
let one = one.into_body().collect().await.expect("body").to_bytes();
|
|
1335
|
-
let two = two.into_body().collect().await.expect("body").to_bytes();
|
|
1336
|
-
assert_eq!(&one[..], b"one\n");
|
|
1337
|
-
assert_eq!(&two[..], b"two\n");
|
|
1338
|
-
let order = worker.await.expect("worker assertions");
|
|
1339
|
-
assert_eq!(order, ["/two".to_string(), "/one".to_string()]);
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
#[tokio::test]
|
|
1343
|
-
async fn drain_finishes_the_in_flight_h2_stream_then_goaways() {
|
|
1344
|
-
use http_body_util::{BodyExt, Full};
|
|
1345
|
-
|
|
1346
|
-
let server = test_server(false, 4);
|
|
1347
|
-
let client_io = spawn_conn(server.clone());
|
|
1348
|
-
|
|
1349
|
-
let (sender, conn) = hyper::client::conn::http2::handshake(
|
|
1350
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1351
|
-
TokioIo::new(client_io),
|
|
1352
|
-
)
|
|
1353
|
-
.await
|
|
1354
|
-
.expect("h2 handshake");
|
|
1355
|
-
tokio::spawn(conn);
|
|
1356
|
-
|
|
1357
|
-
let mut in_flight_sender = sender.clone();
|
|
1358
|
-
let in_flight = tokio::spawn(async move {
|
|
1359
|
-
let request = hyper::Request::builder()
|
|
1360
|
-
.uri("http://kino.test/inflight")
|
|
1361
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1362
|
-
.expect("request");
|
|
1363
|
-
in_flight_sender.send_request(request).await
|
|
1364
|
-
});
|
|
1365
|
-
|
|
1366
|
-
// The request is with the worker when the drain fires; its
|
|
1367
|
-
// response must still reach the client through the shutdown.
|
|
1368
|
-
let ctx = take_ctx(&server).await;
|
|
1369
|
-
let _ = server.shutdown_tx.send(true);
|
|
1370
|
-
tokio::time::sleep(Duration::from_millis(20)).await;
|
|
1371
|
-
assert!(ctx.responder.send_response(plain_response(200, "late\n")));
|
|
1372
|
-
|
|
1373
|
-
let response = in_flight.await.expect("join").expect("in-flight served");
|
|
1374
|
-
assert_eq!(response.status(), 200);
|
|
1375
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1376
|
-
assert_eq!(&body.to_bytes()[..], b"late\n");
|
|
1377
|
-
|
|
1378
|
-
// The connection is now GOAWAY'd: a new stream must fail.
|
|
1379
|
-
let mut sender = sender;
|
|
1380
|
-
let request = hyper::Request::builder()
|
|
1381
|
-
.uri("http://kino.test/after")
|
|
1382
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1383
|
-
.expect("request");
|
|
1384
|
-
assert!(
|
|
1385
|
-
sender.send_request(request).await.is_err(),
|
|
1386
|
-
"a drained connection must not accept new streams"
|
|
1387
|
-
);
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
#[tokio::test]
|
|
1391
|
-
async fn drain_closes_an_h1_connection_after_its_response() {
|
|
1392
|
-
use http_body_util::Full;
|
|
1393
|
-
|
|
1394
|
-
let server = test_server(false, 4);
|
|
1395
|
-
let client_io = spawn_conn(server.clone());
|
|
1396
|
-
|
|
1397
|
-
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(client_io))
|
|
1398
|
-
.await
|
|
1399
|
-
.expect("h1 handshake");
|
|
1400
|
-
tokio::spawn(conn);
|
|
1401
|
-
|
|
1402
|
-
// h1's SendRequest is not Clone: one task drives both requests;
|
|
1403
|
-
// the in-flight one, then (once it completed, so the drain has
|
|
1404
|
-
// been seen) the keep-alive follow-up that must be refused.
|
|
1405
|
-
let req = |path: &str| {
|
|
1406
|
-
hyper::Request::builder()
|
|
1407
|
-
.uri(path.to_string())
|
|
1408
|
-
.header("host", "kino.test")
|
|
1409
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1410
|
-
.expect("request")
|
|
1411
|
-
};
|
|
1412
|
-
let client = tokio::spawn(async move {
|
|
1413
|
-
let first = sender.send_request(req("/inflight")).await;
|
|
1414
|
-
let second_failed = sender.send_request(req("/after")).await.is_err();
|
|
1415
|
-
(first, second_failed)
|
|
1416
|
-
});
|
|
1417
|
-
|
|
1418
|
-
let ctx = take_ctx(&server).await;
|
|
1419
|
-
let _ = server.shutdown_tx.send(true);
|
|
1420
|
-
tokio::time::sleep(Duration::from_millis(20)).await;
|
|
1421
|
-
assert!(ctx.responder.send_response(plain_response(200, "late\n")));
|
|
1422
|
-
|
|
1423
|
-
let (first, second_failed) = client.await.expect("join");
|
|
1424
|
-
assert_eq!(first.expect("in-flight served").status(), 200);
|
|
1425
|
-
assert!(
|
|
1426
|
-
second_failed,
|
|
1427
|
-
"a drained keep-alive connection must close after its response"
|
|
1428
|
-
);
|
|
1429
|
-
}
|
|
1430
|
-
|
|
1431
|
-
#[test]
|
|
1432
|
-
fn advertised_streams_tracks_slot_capacity() {
|
|
1433
|
-
// Slot capacity, floored for tiny topologies and capped.
|
|
1434
|
-
assert_eq!(advertised_streams(8, 3), 24);
|
|
1435
|
-
assert_eq!(advertised_streams(2, 1), 8, "floor");
|
|
1436
|
-
assert_eq!(advertised_streams(64, 32), 1024, "cap");
|
|
1437
|
-
// Unknown topology (embedder passing zeros): hyper's default.
|
|
1438
|
-
assert_eq!(advertised_streams(0, 0), 200);
|
|
1439
|
-
assert_eq!(advertised_streams(8, 0), 200);
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
#[test]
|
|
1443
|
-
fn stream_capacity_is_advertised_from_the_pool_ceiling() {
|
|
1444
|
-
// An elastic pool grows to meet load an h2 balancer sends, so the
|
|
1445
|
-
// ceiling, not the floor, is the admission to advertise.
|
|
1446
|
-
let topology = registry::Topology {
|
|
1447
|
-
mode: "ractor".to_string(),
|
|
1448
|
-
workers: 2,
|
|
1449
|
-
max_workers: 8,
|
|
1450
|
-
threads: 3,
|
|
1451
|
-
batch: 1,
|
|
1452
|
-
};
|
|
1453
|
-
assert_eq!(stream_capacity(&topology), 24);
|
|
1454
|
-
}
|
|
1455
|
-
|
|
1456
|
-
#[test]
|
|
1457
|
-
fn stream_capacity_of_a_fixed_pool_is_its_slot_count() {
|
|
1458
|
-
let topology = registry::Topology {
|
|
1459
|
-
mode: "threaded".to_string(),
|
|
1460
|
-
workers: 4,
|
|
1461
|
-
max_workers: 4,
|
|
1462
|
-
threads: 3,
|
|
1463
|
-
batch: 1,
|
|
1464
|
-
};
|
|
1465
|
-
assert_eq!(stream_capacity(&topology), 12);
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
#[tokio::test]
|
|
1469
|
-
async fn streams_beyond_the_advertised_cap_queue_instead_of_failing() {
|
|
1470
|
-
use http_body_util::Full;
|
|
1471
|
-
use hyper::service::service_fn;
|
|
1472
|
-
|
|
1473
|
-
// Cap of 2: six concurrent requests must all complete; the h2
|
|
1474
|
-
// client holds excess streams locally until the server frees a
|
|
1475
|
-
// slot; nothing is refused or reset.
|
|
1476
|
-
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
|
|
1477
|
-
tokio::spawn(async move {
|
|
1478
|
-
let stub = service_fn(|_req: hyper::Request<hyper::body::Incoming>| async {
|
|
1479
|
-
Ok::<_, std::convert::Infallible>(plain_response(200, "capped\n"))
|
|
1480
|
-
});
|
|
1481
|
-
let _ = conn_builder(true, 2)
|
|
1482
|
-
.serve_connection(TokioIo::new(server_io), stub)
|
|
1483
|
-
.await;
|
|
1484
|
-
});
|
|
1485
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1486
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1487
|
-
TokioIo::new(client_io),
|
|
1488
|
-
)
|
|
1489
|
-
.await
|
|
1490
|
-
.expect("h2 handshake");
|
|
1491
|
-
tokio::spawn(conn);
|
|
1492
|
-
let mut requests = Vec::new();
|
|
1493
|
-
for i in 0..6 {
|
|
1494
|
-
let request = hyper::Request::builder()
|
|
1495
|
-
.uri(format!("http://kino.test/{i}"))
|
|
1496
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1497
|
-
.expect("request");
|
|
1498
|
-
requests.push(sender.send_request(request));
|
|
1499
|
-
}
|
|
1500
|
-
for request in requests {
|
|
1501
|
-
let response = request.await.expect("queued stream served");
|
|
1502
|
-
assert_eq!(response.status(), 200);
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
#[tokio::test]
|
|
1507
|
-
async fn rapid_stream_resets_do_not_wedge_the_pipeline() {
|
|
1508
|
-
use http_body_util::{BodyExt, Full};
|
|
1509
|
-
|
|
1510
|
-
let server = test_server(false, 64);
|
|
1511
|
-
let client_io = spawn_conn(server.clone());
|
|
1512
|
-
|
|
1513
|
-
// A worker that answers everything it sees until told to stop;
|
|
1514
|
-
// answers to already-reset streams just vanish, as in production.
|
|
1515
|
-
let worker = tokio::spawn(async move {
|
|
1516
|
-
loop {
|
|
1517
|
-
let Ok(ctx) = server.req_rx.recv_async().await else {
|
|
1518
|
-
break;
|
|
1519
|
-
};
|
|
1520
|
-
let done = ctx.uri.path() == "/done";
|
|
1521
|
-
ctx.responder.send_response(plain_response(200, "ok\n"));
|
|
1522
|
-
if done {
|
|
1523
|
-
break;
|
|
1524
|
-
}
|
|
1525
|
-
}
|
|
1526
|
-
});
|
|
1527
|
-
|
|
1528
|
-
let (mut sender, conn) = hyper::client::conn::http2::handshake(
|
|
1529
|
-
hyper_util::rt::TokioExecutor::new(),
|
|
1530
|
-
TokioIo::new(client_io),
|
|
1531
|
-
)
|
|
1532
|
-
.await
|
|
1533
|
-
.expect("h2 handshake");
|
|
1534
|
-
tokio::spawn(conn);
|
|
1535
|
-
|
|
1536
|
-
// Fire-and-cancel: dropping the response future resets the
|
|
1537
|
-
// stream. The codec bounds reset churn; the server must keep
|
|
1538
|
-
// serving afterwards.
|
|
1539
|
-
for i in 0..40 {
|
|
1540
|
-
let request = hyper::Request::builder()
|
|
1541
|
-
.uri(format!("http://kino.test/cancel/{i}"))
|
|
1542
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1543
|
-
.expect("request");
|
|
1544
|
-
drop(sender.send_request(request));
|
|
1545
|
-
}
|
|
1546
|
-
let request = hyper::Request::builder()
|
|
1547
|
-
.uri("http://kino.test/done")
|
|
1548
|
-
.body(Full::new(bytes::Bytes::new()))
|
|
1549
|
-
.expect("request");
|
|
1550
|
-
let response = sender.send_request(request).await.expect("still served");
|
|
1551
|
-
assert_eq!(response.status(), 200);
|
|
1552
|
-
let body = response.into_body().collect().await.expect("body");
|
|
1553
|
-
assert_eq!(&body.to_bytes()[..], b"ok\n");
|
|
1554
|
-
worker.await.expect("worker loop");
|
|
1555
|
-
}
|
|
1556
|
-
|
|
1557
|
-
#[tokio::test(start_paused = true)]
|
|
1558
|
-
async fn header_read_timeout_still_fires_through_the_auto_builder() {
|
|
1559
|
-
use hyper::service::service_fn;
|
|
1560
|
-
use tokio::io::AsyncWriteExt;
|
|
1561
|
-
|
|
1562
|
-
let (mut client_io, server_io) = tokio::io::duplex(64 * 1024);
|
|
1563
|
-
let conn = tokio::spawn(async move {
|
|
1564
|
-
let _ = conn_builder(true, 200)
|
|
1565
|
-
.serve_connection(
|
|
1566
|
-
TokioIo::new(server_io),
|
|
1567
|
-
service_fn(|_req: hyper::Request<hyper::body::Incoming>| async {
|
|
1568
|
-
Ok::<_, std::convert::Infallible>(plain_response(200, "never\n"))
|
|
1569
|
-
}),
|
|
1570
|
-
)
|
|
1571
|
-
.await;
|
|
1572
|
-
});
|
|
1573
|
-
// A partial h1 request line, then silence: the slow-header guard
|
|
1574
|
-
// must reap the connection (paused clock auto-advances past 15s).
|
|
1575
|
-
client_io
|
|
1576
|
-
.write_all(b"GET / HT")
|
|
1577
|
-
.await
|
|
1578
|
-
.expect("partial write");
|
|
1579
|
-
tokio::time::timeout(Duration::from_secs(60), conn)
|
|
1580
|
-
.await
|
|
1581
|
-
.expect("connection reaped by header_read_timeout")
|
|
1582
|
-
.expect("serve task join");
|
|
1583
|
-
}
|
|
1584
|
-
|
|
1585
|
-
#[test]
|
|
1586
|
-
fn dispatch_with_no_slots_reports_full() {
|
|
1587
|
-
let server = test_server(true, 4);
|
|
1588
|
-
|
|
1589
|
-
assert!(matches!(
|
|
1590
|
-
try_dispatch(&server, test_ctx()),
|
|
1591
|
-
Dispatch::Full(_)
|
|
1592
|
-
));
|
|
1593
|
-
}
|
|
1594
|
-
|
|
1595
|
-
#[test]
|
|
1596
|
-
fn dispatch_sends_to_an_open_lane() {
|
|
1597
|
-
let server = test_server(true, 4);
|
|
1598
|
-
server.register_worker();
|
|
1599
|
-
|
|
1600
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1601
|
-
assert_eq!(server.lane_depths(), Some(vec![1]));
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
#[test]
|
|
1605
|
-
fn dispatch_hands_the_ctx_back_when_every_lane_is_full() {
|
|
1606
|
-
let server = test_server(true, 4);
|
|
1607
|
-
server.register_worker();
|
|
1608
|
-
|
|
1609
|
-
for _ in 0..LANE_DEPTH {
|
|
1610
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1611
|
-
}
|
|
1612
|
-
// The overload path must return the ctx for the timed retry loop.
|
|
1613
|
-
assert!(matches!(
|
|
1614
|
-
try_dispatch(&server, test_ctx()),
|
|
1615
|
-
Dispatch::Full(_)
|
|
1616
|
-
));
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
#[test]
|
|
1620
|
-
fn dispatch_reports_closed_when_lanes_are_draining() {
|
|
1621
|
-
let server = test_server(true, 4);
|
|
1622
|
-
server.register_worker();
|
|
1623
|
-
server.slots.read()[0].lane_tx.lock().take();
|
|
1624
|
-
|
|
1625
|
-
assert!(matches!(
|
|
1626
|
-
try_dispatch(&server, test_ctx()),
|
|
1627
|
-
Dispatch::Closed
|
|
1628
|
-
));
|
|
1629
|
-
}
|
|
1630
|
-
|
|
1631
|
-
#[test]
|
|
1632
|
-
fn branded_adds_the_server_header_unless_the_app_set_one() {
|
|
1633
|
-
let response = branded(plain_response(200, "x"));
|
|
1634
|
-
assert_eq!(response.headers().get("server").unwrap(), "Kino");
|
|
1635
|
-
|
|
1636
|
-
let mut custom = plain_response(200, "x");
|
|
1637
|
-
custom.headers_mut().insert(
|
|
1638
|
-
http::header::SERVER,
|
|
1639
|
-
http::HeaderValue::from_static("custom"),
|
|
1640
|
-
);
|
|
1641
|
-
assert_eq!(branded(custom).headers().get("server").unwrap(), "custom");
|
|
1642
|
-
}
|
|
1643
|
-
|
|
1644
|
-
#[test]
|
|
1645
|
-
fn unavailable_counts_rejections_and_returns_503() {
|
|
1646
|
-
let server = test_server(false, 1);
|
|
1647
|
-
|
|
1648
|
-
let response = unavailable(&server);
|
|
1649
|
-
assert_eq!(response.status(), 503);
|
|
1650
|
-
assert_eq!(server.rejected.load(Ordering::Relaxed), 1);
|
|
1651
|
-
}
|
|
1652
|
-
|
|
1653
|
-
#[test]
|
|
1654
|
-
fn dispatch_round_robins_across_awake_lanes() {
|
|
1655
|
-
let server = test_server(true, 4);
|
|
1656
|
-
server.register_worker();
|
|
1657
|
-
server.register_worker();
|
|
1658
|
-
|
|
1659
|
-
for _ in 0..4 {
|
|
1660
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1661
|
-
}
|
|
1662
|
-
// The rotating cursor spreads load instead of pinning one lane.
|
|
1663
|
-
assert_eq!(server.lane_depths(), Some(vec![2, 2]));
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
#[test]
|
|
1667
|
-
fn dispatch_skips_parked_lanes_when_an_awake_one_has_room() {
|
|
1668
|
-
let server = test_server(true, 4);
|
|
1669
|
-
server.register_worker();
|
|
1670
|
-
server.register_worker();
|
|
1671
|
-
server.slots.read()[0].parked.store(true, Ordering::Relaxed);
|
|
1672
|
-
|
|
1673
|
-
// Both dispatches land on the awake lane (slot 1), regardless of
|
|
1674
|
-
// where the rotating cursor starts.
|
|
1675
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1676
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1677
|
-
assert_eq!(server.lane_depths(), Some(vec![0, 2]));
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
#[test]
|
|
1681
|
-
fn dispatch_skips_retired_lanes() {
|
|
1682
|
-
let server = test_server(true, 4);
|
|
1683
|
-
server.register_worker();
|
|
1684
|
-
server.register_worker();
|
|
1685
|
-
server.slots.read()[0].retire();
|
|
1686
|
-
|
|
1687
|
-
// A retiring worker gets nothing new: both land on slot 1.
|
|
1688
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1689
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1690
|
-
assert_eq!(server.lane_depths(), Some(vec![0, 2]));
|
|
1691
|
-
}
|
|
1692
|
-
|
|
1693
|
-
#[test]
|
|
1694
|
-
fn dispatch_retries_rather_than_closing_when_only_retired_lanes_remain() {
|
|
1695
|
-
let server = test_server(true, 4);
|
|
1696
|
-
server.register_worker();
|
|
1697
|
-
server.slots.read()[0].retire();
|
|
1698
|
-
|
|
1699
|
-
// Retired is not draining: the caller keeps retrying until the
|
|
1700
|
-
// queue timeout, so a replacement worker can still pick this up.
|
|
1701
|
-
assert!(matches!(
|
|
1702
|
-
try_dispatch(&server, test_ctx()),
|
|
1703
|
-
Dispatch::Full(_)
|
|
1704
|
-
));
|
|
1705
|
-
}
|
|
1706
|
-
|
|
1707
|
-
#[test]
|
|
1708
|
-
fn dispatch_skips_a_retired_lane_even_when_it_is_the_only_awake_one() {
|
|
1709
|
-
let server = test_server(true, 4);
|
|
1710
|
-
server.register_worker();
|
|
1711
|
-
server.register_worker();
|
|
1712
|
-
server.slots.read()[0].retire();
|
|
1713
|
-
server.slots.read()[1].parked.store(true, Ordering::Relaxed);
|
|
1714
|
-
|
|
1715
|
-
// The second pass (parked lanes allowed) still skips the retired one.
|
|
1716
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1717
|
-
assert_eq!(server.lane_depths(), Some(vec![0, 1]));
|
|
1718
|
-
}
|
|
1719
|
-
|
|
1720
|
-
#[test]
|
|
1721
|
-
fn dispatch_keeps_retrying_when_the_other_lanes_are_closed() {
|
|
1722
|
-
let server = test_server(true, 4);
|
|
1723
|
-
server.register_worker();
|
|
1724
|
-
server.register_worker();
|
|
1725
|
-
server.slots.read()[0].lane_tx.lock().take(); // a crashed worker's lane
|
|
1726
|
-
server.slots.read()[1].retire();
|
|
1727
|
-
|
|
1728
|
-
assert!(matches!(
|
|
1729
|
-
try_dispatch(&server, test_ctx()),
|
|
1730
|
-
Dispatch::Full(_)
|
|
1731
|
-
));
|
|
1732
|
-
}
|
|
1733
|
-
|
|
1734
|
-
#[test]
|
|
1735
|
-
fn a_reset_lane_receives_dispatches_again() {
|
|
1736
|
-
let server = test_server(true, 4);
|
|
1737
|
-
server.register_worker();
|
|
1738
|
-
server.register_worker();
|
|
1739
|
-
server.slots.read()[0].retire();
|
|
1740
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1741
|
-
assert_eq!(server.lane_depths(), Some(vec![0, 1]));
|
|
1742
|
-
|
|
1743
|
-
server.slots.read()[0].reset();
|
|
1744
|
-
for _ in 0..2 {
|
|
1745
|
-
assert!(matches!(try_dispatch(&server, test_ctx()), Dispatch::Sent));
|
|
1746
|
-
}
|
|
1747
|
-
// Back in the round-robin.
|
|
1748
|
-
assert_eq!(server.lane_depths(), Some(vec![1, 2]));
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
|
-
#[test]
|
|
1752
|
-
fn nothing_lands_in_a_lane_after_its_retirement_and_final_drain() {
|
|
1753
|
-
let server = test_server(true, 4);
|
|
1754
|
-
server.register_worker();
|
|
1755
|
-
server.register_worker();
|
|
1756
|
-
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
|
1757
|
-
let dispatcher = std::thread::spawn({
|
|
1758
|
-
let server = server.clone();
|
|
1759
|
-
let stop = stop.clone();
|
|
1760
|
-
move || {
|
|
1761
|
-
while !stop.load(Ordering::Relaxed) {
|
|
1762
|
-
let _ = try_dispatch(&server, test_ctx());
|
|
1763
|
-
// Lane 1 keeps draining, so dispatch never stalls on Full.
|
|
1764
|
-
let slots = server.slots.read();
|
|
1765
|
-
if let Some(rx) = slots[1].lane_rx.as_ref() {
|
|
1766
|
-
while rx.try_recv().is_ok() {}
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
});
|
|
1771
|
-
std::thread::sleep(Duration::from_millis(20));
|
|
1772
|
-
|
|
1773
|
-
// The scaler retires slot 0; its worker then drains what it holds.
|
|
1774
|
-
let slot = server.slots.read()[0].clone();
|
|
1775
|
-
slot.retire();
|
|
1776
|
-
if let Some(rx) = slot.lane_rx.as_ref() {
|
|
1777
|
-
while rx.try_recv().is_ok() {}
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
std::thread::sleep(Duration::from_millis(50));
|
|
1781
|
-
stop.store(true, Ordering::Relaxed);
|
|
1782
|
-
dispatcher.join().expect("dispatcher thread");
|
|
1783
|
-
assert_eq!(server.lane_depths(), Some(vec![0, 0]));
|
|
1784
|
-
}
|
|
1785
|
-
}
|