kino 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +286 -0
- data/Cargo.lock +209 -132
- data/README.md +269 -438
- data/doc/README.md +27 -2
- data/doc/architecture.md +862 -43
- data/doc/benchmarks.md +444 -214
- data/doc/configuration.md +215 -0
- data/doc/operations.md +258 -0
- data/doc/rails-on-ractors.md +161 -49
- data/doc/streaming.md +52 -0
- data/doc/websockets.md +469 -0
- data/doc/why-kino.md +6 -6
- data/doc/worker-loop.md +462 -0
- data/ext/kino/Cargo.toml +19 -3
- data/ext/kino/build.rs +32 -1
- data/ext/kino/clippy.toml +10 -0
- data/ext/kino/src/access_log.rs +70 -92
- data/ext/kino/src/control.rs +26 -685
- data/ext/kino/src/counters.rs +132 -0
- data/ext/kino/src/cpus.rs +1 -18
- data/ext/kino/src/dispatch/tests.rs +731 -0
- data/ext/kino/src/dispatch.rs +276 -0
- data/ext/kino/src/doorbell.rs +108 -0
- data/ext/kino/src/env_strings.rs +26 -30
- data/ext/kino/src/framing.rs +110 -0
- data/ext/kino/src/gvl.rs +292 -66
- data/ext/kino/src/hijack/tests.rs +416 -0
- data/ext/kino/src/hijack.rs +471 -0
- data/ext/kino/src/inline/answer.rs +488 -0
- data/ext/kino/src/inline/conn.rs +1124 -0
- data/ext/kino/src/inline/deadline.rs +421 -0
- data/ext/kino/src/inline/encode.rs +119 -0
- data/ext/kino/src/inline/io.rs +487 -0
- data/ext/kino/src/inline/mod.rs +766 -0
- data/ext/kino/src/inline/parity.rs +862 -0
- data/ext/kino/src/inline/parse.rs +131 -0
- data/ext/kino/src/inline/spin.rs +428 -0
- data/ext/kino/src/inline/testing.rs +628 -0
- data/ext/kino/src/io_shards.rs +240 -192
- data/ext/kino/src/lane_room.rs +99 -0
- data/ext/kino/src/lib.rs +139 -77
- data/ext/kino/src/listen.rs +180 -12
- data/ext/kino/src/log.rs +12 -47
- data/ext/kino/src/logsink.rs +3 -9
- data/ext/kino/src/mono.rs +12 -17
- data/ext/kino/src/pin.rs +3 -3
- data/ext/kino/src/queue/mod.rs +54 -0
- data/ext/kino/src/queue/take.rs +503 -0
- data/ext/kino/src/queue/testing.rs +107 -0
- data/ext/kino/src/queue/tests.rs +581 -0
- data/ext/kino/src/queue/worker.rs +501 -0
- data/ext/kino/src/registry.rs +168 -379
- data/ext/kino/src/request.rs +834 -235
- data/ext/kino/src/response.rs +532 -94
- data/ext/kino/src/server/accept.rs +322 -0
- data/ext/kino/src/server/config.rs +138 -0
- data/ext/kino/src/server/handle.rs +247 -0
- data/ext/kino/src/server/intake.rs +217 -0
- data/ext/kino/src/server/mod.rs +157 -0
- data/ext/kino/src/server/natives.rs +223 -0
- data/ext/kino/src/server/serve/intake_tests.rs +458 -0
- data/ext/kino/src/server/serve.rs +436 -0
- data/ext/kino/src/server/tests.rs +532 -0
- data/ext/kino/src/shared_gvl.rs +50 -0
- data/ext/kino/src/slot/lane.rs +138 -0
- data/ext/kino/src/slot/life.rs +111 -0
- data/ext/kino/src/slot/load.rs +193 -0
- data/ext/kino/src/slot/mod.rs +494 -0
- data/ext/kino/src/slot/park.rs +82 -0
- data/ext/kino/src/stats.rs +936 -0
- data/ext/kino/src/symbols.rs +66 -0
- data/ext/kino/src/test_support.rs +24 -14
- data/ext/kino/src/testing.rs +409 -0
- data/ext/kino/src/ticker.rs +87 -0
- data/ext/kino/src/timer.rs +4 -7
- data/ext/kino/src/tls.rs +101 -131
- data/ext/kino/src/typed_data.rs +131 -0
- data/ext/kino/src/upgrade.rs +77 -0
- data/ext/kino/src/ws/codec.rs +470 -0
- data/ext/kino/src/ws/drive.rs +600 -0
- data/ext/kino/src/ws/handshake.rs +267 -0
- data/ext/kino/src/ws/mod.rs +317 -0
- data/ext/kino/src/ws/server_tests.rs +759 -0
- data/ext/kino/src/ws/socket.rs +279 -0
- data/ext/kino/src/ws/stats.rs +88 -0
- data/ext/kino/src/ws/testing.rs +156 -0
- data/ext/kino/src/ws/topics.rs +550 -0
- data/lib/kino/cli.rb +100 -9
- data/lib/kino/configuration.rb +32 -10
- data/lib/kino/crash_backoff.rb +56 -0
- data/lib/kino/input.rb +36 -17
- data/lib/kino/log.rb +8 -1
- data/lib/kino/monitor.rb +1 -1
- data/lib/kino/pool.rb +169 -0
- data/lib/kino/pool_scaler.rb +12 -13
- data/lib/kino/quarantine_monitor.rb +3 -3
- data/lib/kino/ractor_supervisor.rb +201 -161
- data/lib/kino/server.rb +291 -185
- data/lib/kino/slot_bank.rb +21 -9
- data/lib/kino/stream.rb +2 -2
- data/lib/kino/teardown.rb +33 -0
- data/lib/kino/templates/kino.rb.tt +41 -6
- data/lib/kino/threaded_pool.rb +87 -102
- data/lib/kino/version.rb +1 -1
- data/lib/kino/web_socket.rb +125 -0
- data/lib/kino/worker/loop.rb +319 -0
- data/lib/kino/worker.rb +345 -79
- data/lib/kino/worker_hooks.rb +7 -1
- data/lib/kino/worker_row.rb +15 -0
- data/lib/kino.rb +27 -3
- data/lib/rackup/handler/kino.rb +1 -1
- data/sig/kino.rbs +93 -10
- metadata +66 -3
- data/ext/kino/src/queue.rs +0 -333
- data/ext/kino/src/server.rs +0 -1785
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
//! Accepting connections: the listeners, what a connection holds, and the accept loop's backoff.
|
|
2
|
+
|
|
3
|
+
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|
4
|
+
use std::os::fd::{AsRawFd, RawFd};
|
|
5
|
+
use std::pin::Pin;
|
|
6
|
+
use std::sync::Arc;
|
|
7
|
+
use std::task::{Context, Poll};
|
|
8
|
+
use std::time::Duration;
|
|
9
|
+
|
|
10
|
+
use bytes::Bytes;
|
|
11
|
+
use socket2::Socket;
|
|
12
|
+
use tokio::io::{AsyncRead, AsyncWrite};
|
|
13
|
+
use tokio::net::{TcpListener, TcpStream, UnixListener, UnixStream};
|
|
14
|
+
use tokio_util::either::Either;
|
|
15
|
+
|
|
16
|
+
use super::serve_conn;
|
|
17
|
+
use crate::counters::Counted;
|
|
18
|
+
use crate::listen::Listener;
|
|
19
|
+
use crate::registry::ServerInner;
|
|
20
|
+
|
|
21
|
+
#[derive(Clone, Copy)]
|
|
22
|
+
pub(crate) struct Peer {
|
|
23
|
+
pub remote: SocketAddr,
|
|
24
|
+
pub local: SocketAddr,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// A unix socket's peer is local (127.0.0.1) and has no port, so SERVER_PORT falls back
|
|
28
|
+
/// to 80 when the Host header names none.
|
|
29
|
+
pub(crate) const UNIX_PEER: Peer = Peer {
|
|
30
|
+
remote: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
|
31
|
+
local: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 80),
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/// TCP (optionally behind TLS), or a unix socket for plain HTTP.
|
|
35
|
+
pub(crate) enum AsyncListener {
|
|
36
|
+
Tcp(TcpListener),
|
|
37
|
+
Unix(UnixListener),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// An accepted stream, before the protocol layer sees it.
|
|
41
|
+
pub(crate) type Conn = Either<TcpStream, UnixStream>;
|
|
42
|
+
|
|
43
|
+
/// An accepted connection off any runtime, nonblocking: bound for an I/O shard or a worker.
|
|
44
|
+
pub(crate) struct StdConn {
|
|
45
|
+
pub(crate) socket: Socket,
|
|
46
|
+
pub(crate) unix: bool,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
impl StdConn {
|
|
50
|
+
/// Off the runtime that registered `conn`, to which a tokio stream is bound.
|
|
51
|
+
pub(crate) fn detach(conn: Conn) -> std::io::Result<StdConn> {
|
|
52
|
+
let unix = matches!(conn, Either::Right(_));
|
|
53
|
+
let socket = match conn {
|
|
54
|
+
Either::Left(stream) => stream.into_std()?.into(),
|
|
55
|
+
Either::Right(stream) => stream.into_std()?.into(),
|
|
56
|
+
};
|
|
57
|
+
Ok(StdConn { socket, unix })
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
pub(crate) fn into_tokio(self) -> std::io::Result<Conn> {
|
|
61
|
+
Ok(if self.unix {
|
|
62
|
+
Either::Right(UnixStream::from_std(self.socket.into())?)
|
|
63
|
+
} else {
|
|
64
|
+
Either::Left(TcpStream::from_std(self.socket.into())?)
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// What the client sent and nothing read yet, left there (recv_now).
|
|
69
|
+
pub(crate) fn peek(&self, buf: &mut [u8]) -> std::io::Result<usize> {
|
|
70
|
+
super::intake::recv_now(&self.socket, buf, libc::MSG_PEEK)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// send(2), for what an inline answer's first write left (WriteBuf::flush); on Linux TCP with
|
|
74
|
+
/// MSG_NOSIGNAL, as std's sends, so a closed peer is EPIPE, not SIGPIPE. That first write
|
|
75
|
+
/// (WriteBuf::write, a sendmsg) sets no flag.
|
|
76
|
+
pub(crate) fn send(&self, buf: &[u8]) -> std::io::Result<usize> {
|
|
77
|
+
#[cfg(target_os = "linux")]
|
|
78
|
+
let flags = if self.unix { 0 } else { libc::MSG_NOSIGNAL };
|
|
79
|
+
#[cfg(not(target_os = "linux"))]
|
|
80
|
+
let flags = 0;
|
|
81
|
+
self.socket.send_with_flags(buf, flags)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
impl AsRawFd for StdConn {
|
|
86
|
+
fn as_raw_fd(&self) -> RawFd {
|
|
87
|
+
self.socket.as_raw_fd()
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
pub(crate) struct Accepted<C = Conn> {
|
|
92
|
+
pub conn: C,
|
|
93
|
+
pub peer: Peer,
|
|
94
|
+
pub held: Held,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
impl AsyncListener {
|
|
98
|
+
pub(crate) fn from_std(listener: Listener) -> std::io::Result<AsyncListener> {
|
|
99
|
+
Ok(match listener {
|
|
100
|
+
Listener::Tcp(listener) => AsyncListener::Tcp(TcpListener::from_std(listener)?),
|
|
101
|
+
Listener::Unix(listener, _) => AsyncListener::Unix(UnixListener::from_std(listener)?),
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async fn accept(&self) -> std::io::Result<(Conn, Peer)> {
|
|
106
|
+
match self {
|
|
107
|
+
AsyncListener::Tcp(listener) => {
|
|
108
|
+
let (stream, remote) = listener.accept().await?;
|
|
109
|
+
// Small responses must not wait on Nagle + delayed ACK.
|
|
110
|
+
let _ = stream.set_nodelay(true);
|
|
111
|
+
let local = stream
|
|
112
|
+
.local_addr()
|
|
113
|
+
.unwrap_or_else(|_| SocketAddr::from(([0, 0, 0, 0], 0)));
|
|
114
|
+
Ok((Either::Left(stream), Peer { remote, local }))
|
|
115
|
+
}
|
|
116
|
+
AsyncListener::Unix(listener) => {
|
|
117
|
+
let (stream, _) = listener.accept().await?;
|
|
118
|
+
Ok((Either::Right(stream), UNIX_PEER))
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// Its max_connections permit and, on an I/O shard, its count in the shard's load; an
|
|
125
|
+
/// upgraded connection keeps both after hyper lets go of it.
|
|
126
|
+
pub(crate) struct Held {
|
|
127
|
+
_permit: tokio::sync::OwnedSemaphorePermit,
|
|
128
|
+
pub(crate) shard_load: Option<Counted>,
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
impl Held {
|
|
132
|
+
pub(crate) fn new(
|
|
133
|
+
permit: tokio::sync::OwnedSemaphorePermit,
|
|
134
|
+
shard_load: Option<Counted>,
|
|
135
|
+
) -> Self {
|
|
136
|
+
Held {
|
|
137
|
+
_permit: permit,
|
|
138
|
+
shard_load,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// The stream with what it holds, through hyper and past an upgrade: `prefix`, read off it before
|
|
144
|
+
/// hyper, is read first.
|
|
145
|
+
pub(super) struct ConnIo<I> {
|
|
146
|
+
io: I,
|
|
147
|
+
_held: Held,
|
|
148
|
+
prefix: Bytes,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
impl<I> ConnIo<I> {
|
|
152
|
+
pub(super) fn new(io: I, held: Held, prefix: Bytes) -> Self {
|
|
153
|
+
ConnIo {
|
|
154
|
+
io,
|
|
155
|
+
_held: held,
|
|
156
|
+
prefix,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/// Only a connection whose first bytes were read before hyper (handed back, or sniffed after
|
|
161
|
+
/// a TLS handshake) has a prefix, read first; later reads pay one branch.
|
|
162
|
+
#[cold]
|
|
163
|
+
fn read_prefix(&mut self, buf: &mut tokio::io::ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
|
164
|
+
let n = self.prefix.len().min(buf.remaining());
|
|
165
|
+
buf.put_slice(&self.prefix.split_to(n));
|
|
166
|
+
Poll::Ready(Ok(()))
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
impl<I: AsyncRead + Unpin> AsyncRead for ConnIo<I> {
|
|
171
|
+
fn poll_read(
|
|
172
|
+
self: Pin<&mut Self>,
|
|
173
|
+
cx: &mut Context<'_>,
|
|
174
|
+
buf: &mut tokio::io::ReadBuf<'_>,
|
|
175
|
+
) -> Poll<std::io::Result<()>> {
|
|
176
|
+
let this = self.get_mut();
|
|
177
|
+
if !this.prefix.is_empty() {
|
|
178
|
+
return this.read_prefix(buf);
|
|
179
|
+
}
|
|
180
|
+
Pin::new(&mut this.io).poll_read(cx, buf)
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
impl<I: AsyncWrite + Unpin> AsyncWrite for ConnIo<I> {
|
|
185
|
+
fn poll_write(
|
|
186
|
+
self: Pin<&mut Self>,
|
|
187
|
+
cx: &mut Context<'_>,
|
|
188
|
+
buf: &[u8],
|
|
189
|
+
) -> Poll<std::io::Result<usize>> {
|
|
190
|
+
Pin::new(&mut self.get_mut().io).poll_write(cx, buf)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
fn poll_write_vectored(
|
|
194
|
+
self: Pin<&mut Self>,
|
|
195
|
+
cx: &mut Context<'_>,
|
|
196
|
+
bufs: &[std::io::IoSlice<'_>],
|
|
197
|
+
) -> Poll<std::io::Result<usize>> {
|
|
198
|
+
Pin::new(&mut self.get_mut().io).poll_write_vectored(cx, bufs)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
fn is_write_vectored(&self) -> bool {
|
|
202
|
+
self.io.is_write_vectored()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
|
206
|
+
Pin::new(&mut self.get_mut().io).poll_flush(cx)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
|
210
|
+
Pin::new(&mut self.get_mut().io).poll_shutdown(cx)
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// The wait after an accept that failed for want of a resource.
|
|
215
|
+
const ACCEPT_BACKOFF: Duration = Duration::from_millis(10);
|
|
216
|
+
|
|
217
|
+
/// A connection that failed on its own (aborted, reset, unreachable, or EPROTO, which Linux
|
|
218
|
+
/// reports from accept) or an interrupted call frees the next accept. Anything else (EMFILE,
|
|
219
|
+
/// ENFILE, out of memory) would fail again at once and spin a runtime thread: wait first.
|
|
220
|
+
async fn accept_failed(error: &std::io::Error) {
|
|
221
|
+
use std::io::ErrorKind::{
|
|
222
|
+
ConnectionAborted, ConnectionReset, HostUnreachable, Interrupted, NetworkDown,
|
|
223
|
+
NetworkUnreachable,
|
|
224
|
+
};
|
|
225
|
+
let consumed = matches!(
|
|
226
|
+
error.kind(),
|
|
227
|
+
ConnectionAborted
|
|
228
|
+
| ConnectionReset
|
|
229
|
+
| Interrupted
|
|
230
|
+
| NetworkDown
|
|
231
|
+
| NetworkUnreachable
|
|
232
|
+
| HostUnreachable
|
|
233
|
+
) || error.raw_os_error() == Some(libc::EPROTO);
|
|
234
|
+
if !consumed {
|
|
235
|
+
tokio::time::sleep(ACCEPT_BACKOFF).await;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/// The next connection with its `conn_limit` permit; None once the drain began. The permit
|
|
240
|
+
/// comes first, so a flood waits in the kernel backlog instead of holding a task and a socket.
|
|
241
|
+
pub(crate) async fn next_accept(
|
|
242
|
+
listener: &AsyncListener,
|
|
243
|
+
conn_limit: &Arc<tokio::sync::Semaphore>,
|
|
244
|
+
shutdown_rx: &mut tokio::sync::watch::Receiver<bool>,
|
|
245
|
+
) -> Option<Accepted> {
|
|
246
|
+
loop {
|
|
247
|
+
let permit = tokio::select! {
|
|
248
|
+
_ = shutdown_rx.changed() => return None,
|
|
249
|
+
permit = conn_limit.clone().acquire_owned() => permit.ok()?, // closed
|
|
250
|
+
};
|
|
251
|
+
tokio::select! {
|
|
252
|
+
_ = shutdown_rx.changed() => return None,
|
|
253
|
+
accepted = listener.accept() => match accepted {
|
|
254
|
+
Ok((conn, peer)) => {
|
|
255
|
+
let held = Held::new(permit, None);
|
|
256
|
+
return Some(Accepted { conn, peer, held });
|
|
257
|
+
}
|
|
258
|
+
Err(error) => {
|
|
259
|
+
drop(permit);
|
|
260
|
+
accept_failed(&error).await;
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
pub(super) async fn accept_loop(
|
|
268
|
+
listener: AsyncListener,
|
|
269
|
+
acceptor: Option<tokio_rustls::TlsAcceptor>,
|
|
270
|
+
server: Arc<ServerInner>,
|
|
271
|
+
max_connections: usize,
|
|
272
|
+
mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
|
|
273
|
+
) {
|
|
274
|
+
let conn_limit = Arc::new(tokio::sync::Semaphore::new(max_connections));
|
|
275
|
+
while let Some(accepted) = next_accept(&listener, &conn_limit, &mut shutdown_rx).await {
|
|
276
|
+
tokio::spawn(serve_conn(accepted, acceptor.clone(), server.clone()));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
#[cfg(test)]
|
|
281
|
+
mod tests {
|
|
282
|
+
use std::io::{Error, ErrorKind};
|
|
283
|
+
|
|
284
|
+
use super::*;
|
|
285
|
+
|
|
286
|
+
#[tokio::test(start_paused = true)]
|
|
287
|
+
async fn a_failed_accept_waits_before_the_next_unless_only_its_connection_failed() {
|
|
288
|
+
let waited = async |error: Error| {
|
|
289
|
+
let started = tokio::time::Instant::now();
|
|
290
|
+
accept_failed(&error).await;
|
|
291
|
+
started.elapsed()
|
|
292
|
+
};
|
|
293
|
+
// EMFILE and ENFILE, the same numbers on Linux and macOS.
|
|
294
|
+
for errno in [24, 23] {
|
|
295
|
+
let out_of_descriptors = Error::from_raw_os_error(errno);
|
|
296
|
+
assert!(
|
|
297
|
+
waited(out_of_descriptors).await >= ACCEPT_BACKOFF,
|
|
298
|
+
"errno {errno}"
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
let consumed = [
|
|
302
|
+
ErrorKind::ConnectionAborted,
|
|
303
|
+
ErrorKind::ConnectionReset,
|
|
304
|
+
ErrorKind::Interrupted,
|
|
305
|
+
ErrorKind::NetworkDown,
|
|
306
|
+
ErrorKind::NetworkUnreachable,
|
|
307
|
+
ErrorKind::HostUnreachable,
|
|
308
|
+
];
|
|
309
|
+
for error in consumed
|
|
310
|
+
.map(Error::from)
|
|
311
|
+
.into_iter()
|
|
312
|
+
.chain([Error::from_raw_os_error(libc::EPROTO)])
|
|
313
|
+
{
|
|
314
|
+
let what = format!("{error:?}");
|
|
315
|
+
assert_eq!(
|
|
316
|
+
waited(error).await,
|
|
317
|
+
Duration::ZERO,
|
|
318
|
+
"{what}: the next may go at once"
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
//! What a server is built from: the boot-config Hash Ruby hands server_start, read once.
|
|
2
|
+
|
|
3
|
+
use std::sync::Arc;
|
|
4
|
+
use std::time::Duration;
|
|
5
|
+
|
|
6
|
+
use magnus::{Error, RHash, Ruby, TryConvert};
|
|
7
|
+
|
|
8
|
+
/// Echoed by /stats; `mode` is resolved: "ractor" or "threaded", never "auto".
|
|
9
|
+
#[derive(Clone)]
|
|
10
|
+
#[cfg_attr(test, derive(Default))]
|
|
11
|
+
pub struct Topology {
|
|
12
|
+
pub mode: String,
|
|
13
|
+
/// The pool floor.
|
|
14
|
+
pub workers: usize,
|
|
15
|
+
/// The pool ceiling (`workers` for a fixed pool), which HTTP/2 admission is advertised from.
|
|
16
|
+
pub max_workers: usize,
|
|
17
|
+
pub threads: usize,
|
|
18
|
+
pub batch: usize,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
#[cfg_attr(test, derive(Default))]
|
|
22
|
+
pub struct ServerConfig {
|
|
23
|
+
pub bind: String,
|
|
24
|
+
pub port: u16,
|
|
25
|
+
pub queue_depth: usize,
|
|
26
|
+
pub queue_timeout_ms: u64,
|
|
27
|
+
/// 0: none; else the head must arrive within this many ms or the client gets a 504.
|
|
28
|
+
pub request_timeout_ms: u64,
|
|
29
|
+
/// 0: unlimited; else a 413 for a truthful Content-Length, or a mid-stream abort.
|
|
30
|
+
pub max_body_size: usize,
|
|
31
|
+
pub max_connections: usize,
|
|
32
|
+
pub io_shards: bool,
|
|
33
|
+
pub io_threads: usize,
|
|
34
|
+
pub tokio_threads: usize,
|
|
35
|
+
/// The TLS cert and key, both or neither.
|
|
36
|
+
pub tls: Option<(String, String)>,
|
|
37
|
+
pub lanes: bool,
|
|
38
|
+
/// Each worker runs its own loop under the app's fiber scheduler (lanes only).
|
|
39
|
+
pub worker_loop: bool,
|
|
40
|
+
/// Worker threads share a GVL (:threaded mode, or `threads` past one in a Ractor), which each
|
|
41
|
+
/// passes between items once it has held it long (shared_gvl.rs).
|
|
42
|
+
pub shared_gvl: bool,
|
|
43
|
+
/// False pins every connection to HTTP/1.
|
|
44
|
+
pub http2: bool,
|
|
45
|
+
/// Serve plain HTTP/1.1 connections on worker_loop workers' threads (inline/), as resolved.
|
|
46
|
+
pub inline: bool,
|
|
47
|
+
/// An inline connection alone on its worker may spin at its socket (inline/spin.rs); Ruby
|
|
48
|
+
/// turns it off on a process that may use one CPU.
|
|
49
|
+
pub inline_spin: bool,
|
|
50
|
+
pub log_requests: bool,
|
|
51
|
+
pub topology: Topology,
|
|
52
|
+
pub ws: Arc<crate::ws::Limits>,
|
|
53
|
+
pub control_bind: Option<String>,
|
|
54
|
+
pub control_token: Option<String>,
|
|
55
|
+
/// The socket file of a `unix://` bind, removed at shutdown; set by binding, not a key.
|
|
56
|
+
pub unix_path: Option<std::path::PathBuf>,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
impl TryFrom<RHash> for ServerConfig {
|
|
60
|
+
type Error = Error;
|
|
61
|
+
|
|
62
|
+
/// A missing key or half a TLS pair is an ArgumentError; a wrong type raises in its conversion.
|
|
63
|
+
fn try_from(hash: RHash) -> Result<Self, Error> {
|
|
64
|
+
let mut config = ServerConfig {
|
|
65
|
+
bind: required(hash, "bind")?,
|
|
66
|
+
port: required(hash, "port")?,
|
|
67
|
+
queue_depth: required(hash, "queue_depth")?,
|
|
68
|
+
queue_timeout_ms: required(hash, "queue_timeout_ms")?,
|
|
69
|
+
request_timeout_ms: optional(hash, "request_timeout_ms")?.unwrap_or(0),
|
|
70
|
+
max_body_size: optional(hash, "max_body_size")?.unwrap_or(0),
|
|
71
|
+
max_connections: optional(hash, "max_connections")?.unwrap_or(1024),
|
|
72
|
+
io_shards: optional(hash, "io_shards")?.unwrap_or(false),
|
|
73
|
+
io_threads: optional(hash, "io_threads")?.unwrap_or(0),
|
|
74
|
+
tokio_threads: optional(hash, "tokio_threads")?.unwrap_or(0),
|
|
75
|
+
tls: match (optional(hash, "tls_cert")?, optional(hash, "tls_key")?) {
|
|
76
|
+
(Some(cert), Some(key)) => Some((cert, key)),
|
|
77
|
+
(None, None) => None,
|
|
78
|
+
_ => return Err(arg_error(hash, "TLS requires both cert and key")),
|
|
79
|
+
},
|
|
80
|
+
lanes: optional(hash, "lanes")?.unwrap_or(false),
|
|
81
|
+
worker_loop: optional(hash, "worker_loop")?.unwrap_or(false),
|
|
82
|
+
shared_gvl: false,
|
|
83
|
+
// Default true guards embedders calling the native layer directly.
|
|
84
|
+
http2: optional(hash, "http2")?.unwrap_or(true),
|
|
85
|
+
inline: optional(hash, "inline")?.unwrap_or(true),
|
|
86
|
+
inline_spin: optional(hash, "inline_spin")?.unwrap_or(false),
|
|
87
|
+
log_requests: optional(hash, "log_requests")?.unwrap_or(false),
|
|
88
|
+
topology: Topology {
|
|
89
|
+
mode: optional(hash, "mode")?.unwrap_or_else(|| "threaded".to_string()),
|
|
90
|
+
workers: optional(hash, "workers")?.unwrap_or(0),
|
|
91
|
+
max_workers: optional(hash, "max_workers")?.unwrap_or(0),
|
|
92
|
+
threads: optional(hash, "threads")?.unwrap_or(0),
|
|
93
|
+
batch: optional(hash, "batch")?.unwrap_or(1),
|
|
94
|
+
},
|
|
95
|
+
ws: Arc::new(crate::ws::Limits {
|
|
96
|
+
max_message: optional(hash, "websocket_max_message")?
|
|
97
|
+
.unwrap_or(crate::ws::DEFAULT_MAX_MESSAGE),
|
|
98
|
+
ping_interval: optional(hash, "websocket_ping_interval_ms")?
|
|
99
|
+
.map_or(crate::ws::DEFAULT_PING_INTERVAL, Duration::from_millis),
|
|
100
|
+
max: optional(hash, "websocket_max")?.unwrap_or(0),
|
|
101
|
+
..crate::ws::Limits::default()
|
|
102
|
+
}),
|
|
103
|
+
control_bind: optional(hash, "control_bind")?,
|
|
104
|
+
control_token: optional(hash, "control_token")?,
|
|
105
|
+
unix_path: None,
|
|
106
|
+
};
|
|
107
|
+
// Ruby refuses this up front: a queue of none would turn every request away.
|
|
108
|
+
if config.queue_depth == 0 {
|
|
109
|
+
let error = "queue_depth must be a positive Integer (got 0)";
|
|
110
|
+
return Err(arg_error(hash, error));
|
|
111
|
+
}
|
|
112
|
+
// Guards embedders calling the native layer directly; Ruby refuses this up front.
|
|
113
|
+
if config.worker_loop && !config.lanes {
|
|
114
|
+
return Err(arg_error(hash, "worker_loop needs lanes"));
|
|
115
|
+
}
|
|
116
|
+
// Absent or below the floor means a fixed pool.
|
|
117
|
+
let topology = &mut config.topology;
|
|
118
|
+
topology.max_workers = topology.max_workers.max(topology.workers);
|
|
119
|
+
config.shared_gvl = topology.mode == "threaded" || topology.threads > 1;
|
|
120
|
+
// TLS serves through hyper alone.
|
|
121
|
+
config.inline &= config.worker_loop && config.tls.is_none();
|
|
122
|
+
Ok(config)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fn required<T: TryConvert>(hash: RHash, key: &str) -> Result<T, Error> {
|
|
127
|
+
let missing = || arg_error(hash, format!("server_start: missing config key :{key}"));
|
|
128
|
+
optional(hash, key)?.ok_or_else(missing)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
fn arg_error(hash: RHash, message: impl Into<std::borrow::Cow<'static, str>>) -> Error {
|
|
132
|
+
Error::new(Ruby::get_with(hash).exception_arg_error(), message)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Absent or nil: None.
|
|
136
|
+
fn optional<T: TryConvert>(hash: RHash, key: &str) -> Result<Option<T>, Error> {
|
|
137
|
+
hash.lookup(Ruby::get_with(hash).to_symbol(key))
|
|
138
|
+
}
|