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
data/ext/kino/src/tls.rs
CHANGED
|
@@ -18,12 +18,6 @@ fn pem_bytes(input: &str) -> Result<Vec<u8>, String> {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
pub fn build_acceptor(cert: &str, key: &str, http2: bool) -> Result<TlsAcceptor, String> {
|
|
21
|
-
Ok(TlsAcceptor::from(Arc::new(server_config(
|
|
22
|
-
cert, key, http2,
|
|
23
|
-
)?)))
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
fn server_config(cert: &str, key: &str, http2: bool) -> Result<ServerConfig, String> {
|
|
27
21
|
let cert_pem = pem_bytes(cert)?;
|
|
28
22
|
let key_pem = pem_bytes(key)?;
|
|
29
23
|
|
|
@@ -49,14 +43,25 @@ fn server_config(cert: &str, key: &str, http2: bool) -> Result<ServerConfig, Str
|
|
|
49
43
|
} else {
|
|
50
44
|
vec![b"http/1.1".to_vec()]
|
|
51
45
|
};
|
|
52
|
-
Ok(config)
|
|
46
|
+
Ok(TlsAcceptor::from(Arc::new(config)))
|
|
53
47
|
}
|
|
54
48
|
|
|
49
|
+
/// A TLS server and client for tests: an acceptor for a fixture cert,
|
|
50
|
+
/// and a connector that takes any certificate (the fixture is CA-flagged,
|
|
51
|
+
/// which webpki refuses as an end-entity cert).
|
|
55
52
|
#[cfg(test)]
|
|
56
|
-
mod
|
|
57
|
-
use
|
|
53
|
+
pub(crate) mod testing {
|
|
54
|
+
use std::sync::Arc;
|
|
55
|
+
|
|
56
|
+
use tokio_rustls::rustls::client::danger::{
|
|
57
|
+
HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,
|
|
58
|
+
};
|
|
59
|
+
use tokio_rustls::rustls::crypto::WebPkiSupportedAlgorithms;
|
|
60
|
+
use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName, UnixTime};
|
|
61
|
+
use tokio_rustls::rustls::{ClientConfig, DigitallySignedStruct, Error, SignatureScheme};
|
|
62
|
+
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
|
58
63
|
|
|
59
|
-
const CERT: &str = "-----BEGIN CERTIFICATE-----
|
|
64
|
+
pub const CERT: &str = "-----BEGIN CERTIFICATE-----
|
|
60
65
|
MIIBfjCCASWgAwIBAgIUTs9+cVJSzJjy4TSi9YLEd+i4KiIwCgYIKoZIzj0EAwIw
|
|
61
66
|
FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MDYxMDE3MjUzNVoYDzIxMjYwNTE3
|
|
62
67
|
MTcyNTM1WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO
|
|
@@ -68,146 +73,111 @@ vdrY8C5A0QufP/Y1Bm0OrgIgQz+pJX47iTdoINM49gX/6ekLZgmfjwzilJK37E4z
|
|
|
68
73
|
gw8=
|
|
69
74
|
-----END CERTIFICATE-----";
|
|
70
75
|
|
|
71
|
-
const KEY: &str = "-----BEGIN PRIVATE KEY-----
|
|
76
|
+
pub const KEY: &str = "-----BEGIN PRIVATE KEY-----
|
|
72
77
|
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgSlcfB39H6lv5IqYe
|
|
73
78
|
Q+daLGVt9Bf/i5bf+OnLUKcaZYahRANCAAQCgKc2l0PwJW5CAWzp8uW8iIIaGaPk
|
|
74
79
|
WJ2lRijROyX9v7f8aSQlb6kEwKhI8kG8SbeUc+zbKkzGgRXNaZHY/mAa
|
|
75
80
|
-----END PRIVATE KEY-----";
|
|
76
81
|
|
|
77
|
-
|
|
78
|
-
fn
|
|
79
|
-
|
|
82
|
+
/// An acceptor for the fixture cert, offering h2 when `http2` is.
|
|
83
|
+
pub fn acceptor(http2: bool) -> TlsAcceptor {
|
|
84
|
+
super::build_acceptor(CERT, KEY, http2).expect("valid PEM")
|
|
80
85
|
}
|
|
81
86
|
|
|
82
|
-
|
|
83
|
-
fn
|
|
84
|
-
let
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
87
|
+
/// A connector that offers `alpn` and trusts any server.
|
|
88
|
+
pub fn connector(alpn: &[&[u8]]) -> TlsConnector {
|
|
89
|
+
let provider = tokio_rustls::rustls::crypto::ring::default_provider();
|
|
90
|
+
let verifier = AcceptAny(provider.signature_verification_algorithms);
|
|
91
|
+
let mut client = ClientConfig::builder()
|
|
92
|
+
.dangerous()
|
|
93
|
+
.with_custom_certificate_verifier(Arc::new(verifier))
|
|
94
|
+
.with_no_client_auth();
|
|
95
|
+
client.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect();
|
|
96
|
+
TlsConnector::from(Arc::new(client))
|
|
88
97
|
}
|
|
89
98
|
|
|
90
|
-
|
|
91
|
-
fn
|
|
92
|
-
|
|
93
|
-
.err()
|
|
94
|
-
.expect("a key is not a cert");
|
|
95
|
-
assert!(err.contains("no certificates found"));
|
|
99
|
+
/// The fixture's name.
|
|
100
|
+
pub fn localhost() -> ServerName<'static> {
|
|
101
|
+
ServerName::try_from("localhost").expect("server name")
|
|
96
102
|
}
|
|
97
103
|
|
|
98
|
-
#[
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
104
|
+
#[derive(Debug)]
|
|
105
|
+
struct AcceptAny(WebPkiSupportedAlgorithms);
|
|
106
|
+
|
|
107
|
+
impl ServerCertVerifier for AcceptAny {
|
|
108
|
+
fn verify_server_cert(
|
|
109
|
+
&self,
|
|
110
|
+
_end_entity: &CertificateDer<'_>,
|
|
111
|
+
_intermediates: &[CertificateDer<'_>],
|
|
112
|
+
_server_name: &ServerName<'_>,
|
|
113
|
+
_ocsp_response: &[u8],
|
|
114
|
+
_now: UnixTime,
|
|
115
|
+
) -> Result<ServerCertVerified, Error> {
|
|
116
|
+
Ok(ServerCertVerified::assertion())
|
|
117
|
+
}
|
|
105
118
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
.expect("garbage key");
|
|
115
|
-
assert!(!err.is_empty());
|
|
116
|
-
}
|
|
119
|
+
fn verify_tls12_signature(
|
|
120
|
+
&self,
|
|
121
|
+
_message: &[u8],
|
|
122
|
+
_cert: &CertificateDer<'_>,
|
|
123
|
+
_dss: &DigitallySignedStruct,
|
|
124
|
+
) -> Result<HandshakeSignatureValid, Error> {
|
|
125
|
+
Ok(HandshakeSignatureValid::assertion())
|
|
126
|
+
}
|
|
117
127
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
128
|
+
fn verify_tls13_signature(
|
|
129
|
+
&self,
|
|
130
|
+
_message: &[u8],
|
|
131
|
+
_cert: &CertificateDer<'_>,
|
|
132
|
+
_dss: &DigitallySignedStruct,
|
|
133
|
+
) -> Result<HandshakeSignatureValid, Error> {
|
|
134
|
+
Ok(HandshakeSignatureValid::assertion())
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
|
138
|
+
self.0.supported_schemes()
|
|
139
|
+
}
|
|
125
140
|
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#[cfg(test)]
|
|
144
|
+
mod tests {
|
|
145
|
+
use super::build_acceptor;
|
|
146
|
+
use super::testing::{acceptor, connector, localhost, CERT, KEY};
|
|
126
147
|
|
|
127
148
|
#[test]
|
|
128
|
-
fn
|
|
129
|
-
let
|
|
130
|
-
|
|
149
|
+
fn pem_that_cannot_make_an_acceptor_is_refused_saying_why() {
|
|
150
|
+
let garbage = "-----BEGIN PRIVATE KEY-----\ngarbage\n-----END PRIVATE KEY-----";
|
|
151
|
+
#[rustfmt::skip] // One row per refused cert and key.
|
|
152
|
+
let refused = [
|
|
153
|
+
("/nonexistent/cert.pem", "/nonexistent/key.pem", "cannot read"),
|
|
154
|
+
(KEY, KEY, "no certificates found"),
|
|
155
|
+
(CERT, CERT, "no private key found"),
|
|
156
|
+
(CERT, garbage, "TLS config rejected"),
|
|
157
|
+
];
|
|
158
|
+
for (cert, key, says) in refused {
|
|
159
|
+
let error = build_acceptor(cert, key, true).err();
|
|
160
|
+
let error = error.unwrap_or_else(|| panic!("{says}: built"));
|
|
161
|
+
assert!(error.contains(says), "{says}: {error}");
|
|
162
|
+
}
|
|
131
163
|
}
|
|
132
164
|
|
|
133
|
-
/// A real rustls handshake over an in-memory pipe:
|
|
134
|
-
///
|
|
135
|
-
///
|
|
136
|
-
/// certificate verification (the fixture cert is CA-flagged, which
|
|
137
|
-
/// webpki refuses as an end-entity cert): ALPN is under test here,
|
|
138
|
-
/// not the trust chain.
|
|
165
|
+
/// A real rustls handshake over an in-memory pipe, its client offering HTTP/1.1 first: the
|
|
166
|
+
/// server's order chooses, so h2 while http2 is on. The client skips certificate
|
|
167
|
+
/// verification: ALPN is under test here, not the trust chain.
|
|
139
168
|
#[tokio::test]
|
|
140
|
-
async fn
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
struct AcceptAny(WebPkiSupportedAlgorithms);
|
|
153
|
-
|
|
154
|
-
impl ServerCertVerifier for AcceptAny {
|
|
155
|
-
fn verify_server_cert(
|
|
156
|
-
&self,
|
|
157
|
-
_end_entity: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
|
|
158
|
-
_intermediates: &[tokio_rustls::rustls::pki_types::CertificateDer<'_>],
|
|
159
|
-
_server_name: &ServerName<'_>,
|
|
160
|
-
_ocsp_response: &[u8],
|
|
161
|
-
_now: tokio_rustls::rustls::pki_types::UnixTime,
|
|
162
|
-
) -> Result<ServerCertVerified, tokio_rustls::rustls::Error> {
|
|
163
|
-
Ok(ServerCertVerified::assertion())
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
fn verify_tls12_signature(
|
|
167
|
-
&self,
|
|
168
|
-
_message: &[u8],
|
|
169
|
-
_cert: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
|
|
170
|
-
_dss: &tokio_rustls::rustls::DigitallySignedStruct,
|
|
171
|
-
) -> Result<HandshakeSignatureValid, tokio_rustls::rustls::Error> {
|
|
172
|
-
Ok(HandshakeSignatureValid::assertion())
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
fn verify_tls13_signature(
|
|
176
|
-
&self,
|
|
177
|
-
_message: &[u8],
|
|
178
|
-
_cert: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
|
|
179
|
-
_dss: &tokio_rustls::rustls::DigitallySignedStruct,
|
|
180
|
-
) -> Result<HandshakeSignatureValid, tokio_rustls::rustls::Error> {
|
|
181
|
-
Ok(HandshakeSignatureValid::assertion())
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
fn supported_verify_schemes(&self) -> Vec<tokio_rustls::rustls::SignatureScheme> {
|
|
185
|
-
self.0.supported_schemes()
|
|
186
|
-
}
|
|
169
|
+
async fn the_handshake_chooses_h2_over_http11_only_while_http2_is_on() {
|
|
170
|
+
for (http2, chosen) in [(true, &b"h2"[..]), (false, &b"http/1.1"[..])] {
|
|
171
|
+
let acceptor = acceptor(http2);
|
|
172
|
+
let (client_io, server_io) = tokio::io::duplex(16 * 1024);
|
|
173
|
+
let server = tokio::spawn(async move { acceptor.accept(server_io).await });
|
|
174
|
+
let client = connector(&[b"http/1.1", b"h2"])
|
|
175
|
+
.connect(localhost(), client_io)
|
|
176
|
+
.await
|
|
177
|
+
.expect("client handshake");
|
|
178
|
+
let server = server.await.expect("join").expect("server handshake");
|
|
179
|
+
assert_eq!(client.get_ref().1.alpn_protocol(), Some(chosen), "{http2}");
|
|
180
|
+
assert_eq!(server.get_ref().1.alpn_protocol(), Some(chosen), "{http2}");
|
|
187
181
|
}
|
|
188
|
-
|
|
189
|
-
let acceptor =
|
|
190
|
-
TlsAcceptor::from(Arc::new(server_config(CERT, KEY, true).expect("valid PEM")));
|
|
191
|
-
|
|
192
|
-
let provider = tokio_rustls::rustls::crypto::ring::default_provider();
|
|
193
|
-
let verifier = AcceptAny(provider.signature_verification_algorithms);
|
|
194
|
-
let mut client = ClientConfig::builder()
|
|
195
|
-
.dangerous()
|
|
196
|
-
.with_custom_certificate_verifier(Arc::new(verifier))
|
|
197
|
-
.with_no_client_auth();
|
|
198
|
-
client.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
|
199
|
-
let connector = TlsConnector::from(Arc::new(client));
|
|
200
|
-
|
|
201
|
-
let (client_io, server_io) = tokio::io::duplex(16 * 1024);
|
|
202
|
-
let server = tokio::spawn(async move { acceptor.accept(server_io).await });
|
|
203
|
-
let domain = ServerName::try_from("localhost").expect("server name");
|
|
204
|
-
let client_stream = connector
|
|
205
|
-
.connect(domain, client_io)
|
|
206
|
-
.await
|
|
207
|
-
.expect("client handshake");
|
|
208
|
-
let server_stream = server.await.expect("join").expect("server handshake");
|
|
209
|
-
|
|
210
|
-
assert_eq!(client_stream.get_ref().1.alpn_protocol(), Some(&b"h2"[..]));
|
|
211
|
-
assert_eq!(server_stream.get_ref().1.alpn_protocol(), Some(&b"h2"[..]));
|
|
212
182
|
}
|
|
213
183
|
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
//! Kino's native types as Ruby sees them: wrapped as `#[magnus::wrap]` wraps, with their frees
|
|
2
|
+
//! declared thread-safe where the Ruby built against has the flag (build.rs). A Ruby with
|
|
3
|
+
//! per-Ractor GC then frees them in their Ractor's own sweep, not in a process-wide batch under a
|
|
4
|
+
//! VM barrier.
|
|
5
|
+
//!
|
|
6
|
+
//! The flag is a promise each type listed here keeps (doc/architecture.md). Its drop, and the
|
|
7
|
+
//! drop of all it owns or reaches, may run on any thread, a Ruby thread or not, beside other frees
|
|
8
|
+
//! and running Ractors: no Ruby API and no read of a Ruby object, only Send and Sync state, no
|
|
9
|
+
//! lock that anything holds across a Ruby call or a GVL release, no panic, and nothing that
|
|
10
|
+
//! blocks or waits (no join, no blocking send, no runtime dropped).
|
|
11
|
+
|
|
12
|
+
use magnus::typed_data::DataTypeBuilder;
|
|
13
|
+
use magnus::value::{Lazy, ReprValue};
|
|
14
|
+
use magnus::{Class, DataType, RClass, Ruby, TypedData};
|
|
15
|
+
use rb_sys::{rb_data_type_t, VALUE};
|
|
16
|
+
|
|
17
|
+
use crate::inline::ConnHandle;
|
|
18
|
+
use crate::pin::PinKeeper;
|
|
19
|
+
use crate::queue::Worker;
|
|
20
|
+
use crate::request::Request;
|
|
21
|
+
|
|
22
|
+
/// RUBY_TYPED_THREAD_SAFE_FREE, or no bit where Ruby has no such flag.
|
|
23
|
+
#[cfg(kino_thread_safe_free)]
|
|
24
|
+
const THREAD_SAFE_FREE: VALUE =
|
|
25
|
+
rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_THREAD_SAFE_FREE as VALUE;
|
|
26
|
+
#[cfg(not(kino_thread_safe_free))]
|
|
27
|
+
const THREAD_SAFE_FREE: VALUE = 0;
|
|
28
|
+
|
|
29
|
+
/// `built` with THREAD_SAFE_FREE, which magnus's builder cannot set; all else as it was built.
|
|
30
|
+
const fn thread_safe_free(built: DataType) -> DataType {
|
|
31
|
+
// SAFETY: DataType is #[repr(transparent)] over rb_data_type_t, so it is the same value
|
|
32
|
+
// either way. A magnus whose DataType changes size fails to build here.
|
|
33
|
+
unsafe {
|
|
34
|
+
let mut raw = std::mem::transmute::<DataType, rb_data_type_t>(built);
|
|
35
|
+
raw.flags |= THREAD_SAFE_FREE;
|
|
36
|
+
std::mem::transmute::<rb_data_type_t, DataType>(raw)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// `magnus::TypedData` for each `$ty` as `#[magnus::wrap(class = $class, $flag, ...)]` derives
|
|
41
|
+
/// it, but for the DataType, which goes through thread_safe_free.
|
|
42
|
+
macro_rules! native_types {
|
|
43
|
+
($($ty:ty: $class:literal $(, $flag:ident)*;)*) => {
|
|
44
|
+
$(
|
|
45
|
+
// SAFETY: magnus's own derive for these attributes, plus a flag whose promise the
|
|
46
|
+
// type's drop keeps (module docs).
|
|
47
|
+
unsafe impl TypedData for $ty {
|
|
48
|
+
fn class(ruby: &Ruby) -> RClass {
|
|
49
|
+
static CLASS: Lazy<RClass> = Lazy::new(|ruby| {
|
|
50
|
+
let name = $class.to_str().expect("an ASCII class name");
|
|
51
|
+
let class: RClass =
|
|
52
|
+
ruby.class_object().funcall("const_get", (name,)).unwrap();
|
|
53
|
+
class.undef_default_alloc_func();
|
|
54
|
+
class
|
|
55
|
+
});
|
|
56
|
+
ruby.get_inner(&CLASS)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
fn data_type() -> &'static DataType {
|
|
60
|
+
static DATA_TYPE: DataType = thread_safe_free(
|
|
61
|
+
DataTypeBuilder::<$ty>::new($class)$(.$flag())*.build(),
|
|
62
|
+
);
|
|
63
|
+
&DATA_TYPE
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
)*
|
|
67
|
+
|
|
68
|
+
/// Resolves every class now, on the main Ractor: magnus resolves one lazily at its first
|
|
69
|
+
/// wrap, and two worker Ractors must never race that.
|
|
70
|
+
pub fn resolve_classes(ruby: &Ruby) {
|
|
71
|
+
$(let _ = <$ty>::class(ruby);)*
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Why each drop keeps the promise is in its type's docs.
|
|
77
|
+
native_types! {
|
|
78
|
+
Request: c"Kino::Native::Request", free_immediately;
|
|
79
|
+
ConnHandle: c"Kino::Native::Conn", free_immediately;
|
|
80
|
+
Worker: c"Kino::Native::Worker", free_immediately;
|
|
81
|
+
PinKeeper: c"Kino::Native::PinKeeper", mark, free_immediately;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
#[cfg(test)]
|
|
85
|
+
mod tests {
|
|
86
|
+
use std::ffi::CStr;
|
|
87
|
+
|
|
88
|
+
use magnus::DataTypeFunctions;
|
|
89
|
+
|
|
90
|
+
use super::*;
|
|
91
|
+
|
|
92
|
+
/// What Ruby reads of `data_type`.
|
|
93
|
+
fn raw(data_type: &DataType) -> rb_data_type_t {
|
|
94
|
+
// SAFETY: as thread_safe_free, here a bitwise copy of pointers and integers.
|
|
95
|
+
unsafe { std::mem::transmute_copy(data_type) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// `T` is `class` as magnus builds it freed immediately with `attrs`, plus the flag.
|
|
99
|
+
fn wrapped<T: TypedData + DataTypeFunctions>(
|
|
100
|
+
class: &'static CStr,
|
|
101
|
+
attrs: fn(DataTypeBuilder<T>) -> DataTypeBuilder<T>,
|
|
102
|
+
) {
|
|
103
|
+
let ours = raw(T::data_type());
|
|
104
|
+
let magnus = raw(&attrs(DataTypeBuilder::new(class))
|
|
105
|
+
.free_immediately()
|
|
106
|
+
.build());
|
|
107
|
+
// SAFETY: native_types! names a type with a C string literal.
|
|
108
|
+
let name = unsafe { CStr::from_ptr(ours.wrap_struct_name) };
|
|
109
|
+
assert_eq!(name, class);
|
|
110
|
+
assert_eq!(
|
|
111
|
+
(ours.function.dmark.is_some(), ours.function.dfree.is_some()),
|
|
112
|
+
(magnus.function.dmark.is_some(), true),
|
|
113
|
+
"{class:?}: whether it has a mark and a free function"
|
|
114
|
+
);
|
|
115
|
+
assert_eq!(
|
|
116
|
+
ours.flags,
|
|
117
|
+
magnus.flags | THREAD_SAFE_FREE,
|
|
118
|
+
"{class:?}: flags other than magnus's, plus thread-safe free where Ruby has it \
|
|
119
|
+
(cfg kino_thread_safe_free: {})",
|
|
120
|
+
cfg!(kino_thread_safe_free)
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
#[test]
|
|
125
|
+
fn native_types_are_wrapped_as_magnus_wraps_them_plus_a_thread_safe_free_where_ruby_has_it() {
|
|
126
|
+
wrapped::<Request>(c"Kino::Native::Request", |plain| plain);
|
|
127
|
+
wrapped::<ConnHandle>(c"Kino::Native::Conn", |plain| plain);
|
|
128
|
+
wrapped::<Worker>(c"Kino::Native::Worker", |plain| plain);
|
|
129
|
+
wrapped::<PinKeeper>(c"Kino::Native::PinKeeper", DataTypeBuilder::mark);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
//! Who gets a connection that asks to switch protocols: hyper hands out one upgrade per request,
|
|
2
|
+
//! so a task holds it until the app claims it (ws::accept, hijack::take) or answers plainly.
|
|
3
|
+
|
|
4
|
+
use std::sync::Arc;
|
|
5
|
+
|
|
6
|
+
use hyper::upgrade::OnUpgrade;
|
|
7
|
+
use tokio::sync::oneshot;
|
|
8
|
+
|
|
9
|
+
use crate::hijack::Bridge;
|
|
10
|
+
use crate::registry::ServerInner;
|
|
11
|
+
use crate::ws;
|
|
12
|
+
|
|
13
|
+
/// Claiming it hands the connection over; dropping it (a plain answer) ends the holding task.
|
|
14
|
+
pub struct Upgrade {
|
|
15
|
+
claim: oneshot::Sender<Claim>,
|
|
16
|
+
websocket: Option<ws::Offer>,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
impl Upgrade {
|
|
20
|
+
pub fn websocket(&self) -> Option<&ws::Offer> {
|
|
21
|
+
self.websocket.as_ref()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// False when nothing holds it any more (the runtime is shutting down).
|
|
25
|
+
pub(crate) fn claim(self, claim: Claim) -> bool {
|
|
26
|
+
self.claim.send(claim).is_ok()
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
pub(crate) enum Claim {
|
|
31
|
+
WebSocket(ws::Accepted),
|
|
32
|
+
Hijack(Bridge),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pub fn capture(
|
|
36
|
+
req: &mut hyper::Request<hyper::body::Incoming>,
|
|
37
|
+
server: &Arc<ServerInner>,
|
|
38
|
+
) -> Option<Upgrade> {
|
|
39
|
+
if req.version() != http::Version::HTTP_11 || !req.headers().contains_key(http::header::UPGRADE)
|
|
40
|
+
{
|
|
41
|
+
return None;
|
|
42
|
+
}
|
|
43
|
+
let websocket = ws::offer(req, server);
|
|
44
|
+
let (claim, claimed) = oneshot::channel();
|
|
45
|
+
tokio::spawn(settle(hyper::upgrade::on(req), claimed, server.clone()));
|
|
46
|
+
Some(Upgrade { claim, websocket })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// A WebSocket handshake as `server` hands it to dispatch, with no
|
|
50
|
+
/// connection behind it.
|
|
51
|
+
#[cfg(test)]
|
|
52
|
+
pub fn test_handshake(server: &ServerInner) -> crate::registry::BoxedCtx {
|
|
53
|
+
let request = ws::testing::handshake()
|
|
54
|
+
.body(())
|
|
55
|
+
.expect("handshake request");
|
|
56
|
+
let (claim, _claimed) = oneshot::channel();
|
|
57
|
+
let mut ctx = crate::request::test_ctx();
|
|
58
|
+
ctx.headers = request.headers().clone();
|
|
59
|
+
ctx.upgrade = Some(Upgrade {
|
|
60
|
+
claim,
|
|
61
|
+
websocket: ws::offer(&request, server),
|
|
62
|
+
});
|
|
63
|
+
assert!(ctx.offers_websocket(), "only a lanes server offers sockets");
|
|
64
|
+
ctx
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async fn settle(
|
|
68
|
+
on_upgrade: OnUpgrade,
|
|
69
|
+
claimed: oneshot::Receiver<Claim>,
|
|
70
|
+
server: Arc<ServerInner>,
|
|
71
|
+
) {
|
|
72
|
+
match claimed.await {
|
|
73
|
+
Ok(Claim::WebSocket(accepted)) => ws::drive(on_upgrade, accepted).await,
|
|
74
|
+
Ok(Claim::Hijack(bridge)) => bridge.run(on_upgrade, &server).await,
|
|
75
|
+
Err(_) => {} // the app answered plainly
|
|
76
|
+
}
|
|
77
|
+
}
|