connectrpc-hyper 0.3.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 +7 -0
- data/Cargo.lock +927 -0
- data/Cargo.toml +8 -0
- data/LICENSE +21 -0
- data/README.md +475 -0
- data/THIRD_PARTY_NOTICES.md +3886 -0
- data/ext/connectrpc_hyper/Cargo.toml +31 -0
- data/ext/connectrpc_hyper/extconf.rb +9 -0
- data/ext/connectrpc_hyper/src/body.rs +142 -0
- data/ext/connectrpc_hyper/src/call.rs +659 -0
- data/ext/connectrpc_hyper/src/conn.rs +825 -0
- data/ext/connectrpc_hyper/src/failure.rs +247 -0
- data/ext/connectrpc_hyper/src/gvl.rs +414 -0
- data/ext/connectrpc_hyper/src/holds.rs +241 -0
- data/ext/connectrpc_hyper/src/lib.rs +652 -0
- data/ext/connectrpc_hyper/src/pool.rs +1206 -0
- data/ext/connectrpc_hyper/src/runtime.rs +352 -0
- data/ext/connectrpc_hyper/src/tls.rs +114 -0
- data/ext/connectrpc_hyper/src/unary.rs +120 -0
- data/ext/connectrpc_hyper/src/wire.rs +513 -0
- data/lib/connectrpc/hyper/errors.rb +79 -0
- data/lib/connectrpc/hyper/exchange.rb +89 -0
- data/lib/connectrpc/hyper/tls.rb +110 -0
- data/lib/connectrpc/hyper/transport.rb +369 -0
- data/lib/connectrpc/hyper/version.rb +7 -0
- data/lib/connectrpc/hyper.rb +27 -0
- data/sig/connectrpc-hyper.rbs +23 -0
- data/sig/manifest.yaml +3 -0
- metadata +107 -0
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
//! The process runtime, fork guards, the fork-safe socket registry and the
|
|
2
|
+
//! task tracker every driver spawns through.
|
|
3
|
+
//!
|
|
4
|
+
//! Fork: a child has none of the parent's runtime threads, and any lock or
|
|
5
|
+
//! waker may have been mid-update at fork time. Nothing created by the parent
|
|
6
|
+
//! runtime is ever dropped or used in a child: `ForkGuard` leaks it, the Ruby
|
|
7
|
+
//! transport builds a new driver, and the runtime slot is replaced. No state
|
|
8
|
+
//! here is guarded by a lock a fork can inherit.
|
|
9
|
+
use std::collections::HashMap;
|
|
10
|
+
use std::future::Future;
|
|
11
|
+
use std::mem::ManuallyDrop;
|
|
12
|
+
use std::pin::Pin;
|
|
13
|
+
use std::ptr;
|
|
14
|
+
use std::sync::atomic::{AtomicPtr, Ordering};
|
|
15
|
+
use std::sync::{Arc, Mutex};
|
|
16
|
+
use std::task::{Context, Poll};
|
|
17
|
+
|
|
18
|
+
use tokio::runtime::{Builder, Handle, Runtime};
|
|
19
|
+
use tokio::sync::Notify;
|
|
20
|
+
use tokio::task::AbortHandle;
|
|
21
|
+
|
|
22
|
+
pub fn pid() -> u32 {
|
|
23
|
+
std::process::id()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
struct Slot {
|
|
27
|
+
pid: u32,
|
|
28
|
+
runtime: Runtime,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// The current process's runtime, or a leaked parent's, or null.
|
|
32
|
+
static RUNTIME: AtomicPtr<Slot> = AtomicPtr::new(ptr::null_mut());
|
|
33
|
+
|
|
34
|
+
/// The process runtime, created on first use (never when a transport is
|
|
35
|
+
/// built) and recreated in a forked child. Concurrent cold callers each build
|
|
36
|
+
/// one; the compare-and-swap elects a winner and losers shut theirs down.
|
|
37
|
+
pub fn handle() -> Handle {
|
|
38
|
+
let me = pid();
|
|
39
|
+
let mut current = RUNTIME.load(Ordering::Acquire);
|
|
40
|
+
loop {
|
|
41
|
+
// SAFETY: a published slot is never freed: slots are leaked for the
|
|
42
|
+
// life of the process, including inherited ones in a child.
|
|
43
|
+
if let Some(slot) = unsafe { current.as_ref() } {
|
|
44
|
+
if slot.pid == me {
|
|
45
|
+
return slot.runtime.handle().clone();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
let runtime = Builder::new_multi_thread()
|
|
49
|
+
.worker_threads(2)
|
|
50
|
+
.thread_name("hyper-runtime")
|
|
51
|
+
.enable_all()
|
|
52
|
+
.build()
|
|
53
|
+
.expect("tokio runtime");
|
|
54
|
+
let fresh = Box::into_raw(Box::new(Slot { pid: me, runtime }));
|
|
55
|
+
match RUNTIME.compare_exchange(current, fresh, Ordering::AcqRel, Ordering::Acquire) {
|
|
56
|
+
// An inherited slot, if any, is leaked: its threads do not exist here.
|
|
57
|
+
Ok(_) => {
|
|
58
|
+
// SAFETY: `fresh` was just published and is never freed.
|
|
59
|
+
return unsafe { &*fresh }.runtime.handle().clone();
|
|
60
|
+
}
|
|
61
|
+
Err(actual) => {
|
|
62
|
+
// SAFETY: `fresh` was never published, so this thread owns it.
|
|
63
|
+
let lost = unsafe { Box::from_raw(fresh) };
|
|
64
|
+
lost.runtime.shutdown_background();
|
|
65
|
+
current = actual;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// A process-scoped value in a lock-free slot: the parent's value is leaked
|
|
72
|
+
/// in a child, and concurrent initialisers elect one value.
|
|
73
|
+
pub struct PidCell<T: 'static> {
|
|
74
|
+
slot: AtomicPtr<(u32, T)>,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
impl<T: 'static> PidCell<T> {
|
|
78
|
+
pub const fn new() -> Self {
|
|
79
|
+
Self {
|
|
80
|
+
slot: AtomicPtr::new(ptr::null_mut()),
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// `init` may run more than once when callers race; one result wins.
|
|
85
|
+
pub fn get_or_init(&'static self, init: impl Fn() -> T) -> &'static T {
|
|
86
|
+
let me = pid();
|
|
87
|
+
let mut current = self.slot.load(Ordering::Acquire);
|
|
88
|
+
loop {
|
|
89
|
+
// SAFETY: published values are leaked, never freed.
|
|
90
|
+
if let Some((owner, value)) = unsafe { current.as_ref() } {
|
|
91
|
+
if *owner == me {
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let fresh = Box::into_raw(Box::new((me, init())));
|
|
96
|
+
match self
|
|
97
|
+
.slot
|
|
98
|
+
.compare_exchange(current, fresh, Ordering::AcqRel, Ordering::Acquire)
|
|
99
|
+
{
|
|
100
|
+
// SAFETY: published and leaked.
|
|
101
|
+
Ok(_) => return &unsafe { &*fresh }.1,
|
|
102
|
+
Err(actual) => {
|
|
103
|
+
// SAFETY: never published; this thread owns it.
|
|
104
|
+
drop(unsafe { Box::from_raw(fresh) });
|
|
105
|
+
current = actual;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Wraps values owned by the parent process's runtime and leaks them when
|
|
113
|
+
/// dropped in a forked child.
|
|
114
|
+
pub struct ForkGuard<T> {
|
|
115
|
+
pid: u32,
|
|
116
|
+
value: ManuallyDrop<T>,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
impl<T> ForkGuard<T> {
|
|
120
|
+
pub fn new(value: T) -> Self {
|
|
121
|
+
Self {
|
|
122
|
+
pid: pid(),
|
|
123
|
+
value: ManuallyDrop::new(value),
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
pub fn inherited(&self) -> bool {
|
|
128
|
+
self.pid != pid()
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
impl<T> std::ops::Deref for ForkGuard<T> {
|
|
133
|
+
type Target = T;
|
|
134
|
+
fn deref(&self) -> &T {
|
|
135
|
+
&self.value
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
impl<T> Drop for ForkGuard<T> {
|
|
140
|
+
fn drop(&mut self) {
|
|
141
|
+
if !self.inherited() {
|
|
142
|
+
// SAFETY: dropped exactly once, here, in the owning process.
|
|
143
|
+
unsafe { ManuallyDrop::drop(&mut self.value) }
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/// Fork-safe registry of connection sockets. A slot holds an fd only while
|
|
149
|
+
/// that fd is open as one of our sockets: a socket registers after it is
|
|
150
|
+
/// connected and deregisters before it closes. A forked child closes (never
|
|
151
|
+
/// shuts down, which would affect the parent's shared socket) every
|
|
152
|
+
/// registered fd in a `pthread_atfork` child handler, before any child code
|
|
153
|
+
/// runs. Sockets still connecting at fork time are not registered and stay
|
|
154
|
+
/// open in the child until it exits.
|
|
155
|
+
#[cfg(unix)]
|
|
156
|
+
pub mod sockets {
|
|
157
|
+
use std::sync::Once;
|
|
158
|
+
use std::sync::atomic::{AtomicI32, Ordering};
|
|
159
|
+
|
|
160
|
+
const SLOTS: usize = 4096;
|
|
161
|
+
static FDS: [AtomicI32; SLOTS] = [const { AtomicI32::new(-1) }; SLOTS];
|
|
162
|
+
static INSTALL: Once = Once::new();
|
|
163
|
+
|
|
164
|
+
extern "C" fn close_inherited() {
|
|
165
|
+
for slot in &FDS {
|
|
166
|
+
let fd = slot.swap(-1, Ordering::AcqRel);
|
|
167
|
+
if fd >= 0 {
|
|
168
|
+
// SAFETY: async-signal-safe; the fd is an inherited copy of a
|
|
169
|
+
// registered socket (see the module invariant).
|
|
170
|
+
unsafe { libc::close(fd) };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
pub fn install() {
|
|
176
|
+
INSTALL.call_once(|| {
|
|
177
|
+
// SAFETY: registers a handler that only touches atomics and close(2).
|
|
178
|
+
unsafe { libc::pthread_atfork(None, None, Some(close_inherited)) };
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/// Returns the slot index, or None when the registry is full.
|
|
183
|
+
pub fn register(fd: i32) -> Option<usize> {
|
|
184
|
+
FDS.iter().position(|slot| {
|
|
185
|
+
slot.compare_exchange(-1, fd, Ordering::AcqRel, Ordering::Acquire)
|
|
186
|
+
.is_ok()
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
pub fn deregister(index: usize) {
|
|
191
|
+
FDS[index].store(-1, Ordering::Release);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
#[cfg(not(unix))]
|
|
196
|
+
pub mod sockets {
|
|
197
|
+
pub fn install() {}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// Every task a driver starts, including hyper's connection, body and
|
|
201
|
+
/// response tasks, so a closing transport can abort them and wait for them
|
|
202
|
+
/// to end: no detached tasks outlive `close`. Once sealed it refuses new
|
|
203
|
+
/// tasks, so a call still mid-poll when teardown starts cannot register one
|
|
204
|
+
/// after `close` observed the set empty.
|
|
205
|
+
pub struct Tracker {
|
|
206
|
+
tasks: Mutex<TrackerState>,
|
|
207
|
+
emptied: Notify,
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#[derive(Default)]
|
|
211
|
+
struct TrackerState {
|
|
212
|
+
next: u64,
|
|
213
|
+
sealed: bool,
|
|
214
|
+
running: HashMap<u64, AbortHandle>,
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/// A tracked task's handle; empty when a sealed tracker refused the task.
|
|
218
|
+
pub struct Task(Option<AbortHandle>);
|
|
219
|
+
|
|
220
|
+
impl Task {
|
|
221
|
+
pub fn abort(&self) {
|
|
222
|
+
if let Some(task) = &self.0 {
|
|
223
|
+
task.abort();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
struct Finished {
|
|
229
|
+
tracker: Arc<Tracker>,
|
|
230
|
+
id: u64,
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// A tracked future and its registration. Fields drop in declaration order,
|
|
234
|
+
/// so the future, and every socket or task it owns, is gone before the
|
|
235
|
+
/// registration leaves the set: whether the task completed, panicked, or was
|
|
236
|
+
/// aborted before or during a poll. An `async` block holding both would drop
|
|
237
|
+
/// its captures in capture order when aborted before its first poll, removing
|
|
238
|
+
/// the registration first.
|
|
239
|
+
struct Tracked {
|
|
240
|
+
future: Pin<Box<dyn Future<Output = ()> + Send>>,
|
|
241
|
+
_finished: Finished,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
impl Future for Tracked {
|
|
245
|
+
type Output = ();
|
|
246
|
+
|
|
247
|
+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
|
248
|
+
self.future.as_mut().poll(cx)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
impl Drop for Finished {
|
|
253
|
+
fn drop(&mut self) {
|
|
254
|
+
let mut state = self.tracker.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
255
|
+
state.running.remove(&self.id);
|
|
256
|
+
if state.running.is_empty() {
|
|
257
|
+
self.tracker.emptied.notify_waiters();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
impl Tracker {
|
|
263
|
+
/// Binds the process runtime at the first spawn, not at construction.
|
|
264
|
+
pub fn new() -> Arc<Self> {
|
|
265
|
+
Arc::new(Self {
|
|
266
|
+
tasks: Mutex::new(TrackerState::default()),
|
|
267
|
+
emptied: Notify::new(),
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
pub fn spawn<F>(self: &Arc<Self>, future: F) -> Task
|
|
272
|
+
where
|
|
273
|
+
F: Future<Output = ()> + Send + 'static,
|
|
274
|
+
{
|
|
275
|
+
// The lock spans the spawn, so a task that ends at once removes an
|
|
276
|
+
// entry that already exists, and `seal` waits for a registration in
|
|
277
|
+
// progress, then aborts it.
|
|
278
|
+
let mut state = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
279
|
+
if state.sealed {
|
|
280
|
+
drop(state);
|
|
281
|
+
// Dropped outside the lock: dropping it may release the last
|
|
282
|
+
// driver reference, whose teardown takes this lock.
|
|
283
|
+
drop(future);
|
|
284
|
+
return Task(None);
|
|
285
|
+
}
|
|
286
|
+
state.next += 1;
|
|
287
|
+
let id = state.next;
|
|
288
|
+
let finished = Finished {
|
|
289
|
+
tracker: self.clone(),
|
|
290
|
+
id,
|
|
291
|
+
};
|
|
292
|
+
let join = handle().spawn(Tracked {
|
|
293
|
+
future: Box::pin(future),
|
|
294
|
+
_finished: finished,
|
|
295
|
+
});
|
|
296
|
+
let abort = join.abort_handle();
|
|
297
|
+
state.running.insert(id, abort.clone());
|
|
298
|
+
Task(Some(abort))
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/// Refuses every later spawn and aborts every registered task.
|
|
302
|
+
pub fn seal(&self) {
|
|
303
|
+
let mut state = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
304
|
+
state.sealed = true;
|
|
305
|
+
for task in state.running.values() {
|
|
306
|
+
task.abort();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
pub fn abort_all(&self) {
|
|
311
|
+
let state = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
312
|
+
for task in state.running.values() {
|
|
313
|
+
task.abort();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
pub fn len(&self) -> usize {
|
|
318
|
+
let state = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
319
|
+
state.running.len()
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
pub fn is_empty(&self) -> bool {
|
|
323
|
+
let state = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
|
324
|
+
state.running.is_empty()
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
pub async fn wait_empty(&self) {
|
|
328
|
+
loop {
|
|
329
|
+
let emptied = self.emptied.notified();
|
|
330
|
+
tokio::pin!(emptied);
|
|
331
|
+
emptied.as_mut().enable();
|
|
332
|
+
if self.is_empty() {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
emptied.await;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/// hyper's executor: every connection, body pipe and response task it
|
|
341
|
+
/// spawns is tracked by the driver.
|
|
342
|
+
#[derive(Clone)]
|
|
343
|
+
pub struct TrackedExec(pub Arc<Tracker>);
|
|
344
|
+
|
|
345
|
+
impl<F> hyper::rt::Executor<F> for TrackedExec
|
|
346
|
+
where
|
|
347
|
+
F: Future<Output = ()> + Send + 'static,
|
|
348
|
+
{
|
|
349
|
+
fn execute(&self, future: F) {
|
|
350
|
+
self.0.spawn(future);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
//! rustls client configuration: aws-lc-rs with post-quantum key exchange
|
|
2
|
+
//! preferred, TLS 1.2 minimum, no session resumption, native roots (loaded
|
|
3
|
+
//! once per process, honouring SSL_CERT_FILE/SSL_CERT_DIR at first use) plus
|
|
4
|
+
//! the transport's appended `ca_file` certificates. Ruby validates inputs with
|
|
5
|
+
//! OpenSSL and passes DER.
|
|
6
|
+
use std::sync::Arc;
|
|
7
|
+
|
|
8
|
+
use rustls::client::Resumption;
|
|
9
|
+
use rustls::crypto::CryptoProvider;
|
|
10
|
+
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
|
11
|
+
use rustls::sign::CertifiedKey;
|
|
12
|
+
use rustls::{ClientConfig, RootCertStore};
|
|
13
|
+
|
|
14
|
+
use crate::failure::Failure;
|
|
15
|
+
use crate::runtime::PidCell;
|
|
16
|
+
|
|
17
|
+
static NATIVE_ROOTS: PidCell<Arc<RootCertStore>> = PidCell::new();
|
|
18
|
+
|
|
19
|
+
fn provider() -> Arc<CryptoProvider> {
|
|
20
|
+
Arc::new(rustls::crypto::aws_lc_rs::default_provider())
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// The platform trust store, or SSL_CERT_FILE/SSL_CERT_DIR when set, loaded
|
|
24
|
+
/// once per process. Blocking file I/O: call from a blocking context.
|
|
25
|
+
pub fn native_roots() -> Arc<RootCertStore> {
|
|
26
|
+
NATIVE_ROOTS
|
|
27
|
+
.get_or_init(|| {
|
|
28
|
+
let mut roots = RootCertStore::empty();
|
|
29
|
+
roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
|
|
30
|
+
Arc::new(roots)
|
|
31
|
+
})
|
|
32
|
+
.clone()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Validated TLS inputs; construction fails with the name of the input.
|
|
36
|
+
pub struct TlsInputs {
|
|
37
|
+
extra_roots: Vec<CertificateDer<'static>>,
|
|
38
|
+
identity: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
impl TlsInputs {
|
|
42
|
+
pub fn new(
|
|
43
|
+
roots: Vec<Vec<u8>>,
|
|
44
|
+
chain: Option<Vec<Vec<u8>>>,
|
|
45
|
+
key: Option<Vec<u8>>,
|
|
46
|
+
) -> Result<Self, &'static str> {
|
|
47
|
+
let extra_roots: Vec<CertificateDer<'static>> =
|
|
48
|
+
roots.into_iter().map(CertificateDer::from).collect();
|
|
49
|
+
// Every appended certificate must become a trust anchor.
|
|
50
|
+
let mut check = RootCertStore::empty();
|
|
51
|
+
for root in &extra_roots {
|
|
52
|
+
check.add(root.clone()).map_err(|_| "ca_file")?;
|
|
53
|
+
}
|
|
54
|
+
let identity = match (chain, key) {
|
|
55
|
+
(Some(chain), Some(key)) => {
|
|
56
|
+
let chain: Vec<CertificateDer<'static>> =
|
|
57
|
+
chain.into_iter().map(CertificateDer::from).collect();
|
|
58
|
+
let provider = provider();
|
|
59
|
+
// Imports the key into the provider: a key OpenSSL accepts but
|
|
60
|
+
// aws-lc-rs cannot sign with (Ed448) fails here.
|
|
61
|
+
let key: PrivateKeyDer<'static> = PrivatePkcs8KeyDer::from(key).into();
|
|
62
|
+
let signing = provider
|
|
63
|
+
.key_provider
|
|
64
|
+
.load_private_key(key.clone_key())
|
|
65
|
+
.map_err(|_| "private_key")?;
|
|
66
|
+
let certified = CertifiedKey::new(chain.clone(), signing);
|
|
67
|
+
match certified.keys_match() {
|
|
68
|
+
Ok(()) => {}
|
|
69
|
+
Err(rustls::Error::InconsistentKeys(rustls::InconsistentKeys::Unknown)) => {}
|
|
70
|
+
Err(rustls::Error::InconsistentKeys(_)) => {
|
|
71
|
+
return Err("private_key");
|
|
72
|
+
}
|
|
73
|
+
Err(_) => return Err("certificate_chain"),
|
|
74
|
+
}
|
|
75
|
+
Some((chain, key))
|
|
76
|
+
}
|
|
77
|
+
(None, None) => None,
|
|
78
|
+
(Some(_), None) => return Err("private_key"),
|
|
79
|
+
(None, Some(_)) => return Err("certificate_chain"),
|
|
80
|
+
};
|
|
81
|
+
Ok(Self {
|
|
82
|
+
extra_roots,
|
|
83
|
+
identity,
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/// Builds the h2 (ALPN h2, http/1.1) and HTTP/1.1-only configurations.
|
|
88
|
+
pub fn configs(
|
|
89
|
+
&self,
|
|
90
|
+
native: &RootCertStore,
|
|
91
|
+
) -> Result<(Arc<ClientConfig>, Arc<ClientConfig>), Failure> {
|
|
92
|
+
let mut roots = native.clone();
|
|
93
|
+
for root in &self.extra_roots {
|
|
94
|
+
roots
|
|
95
|
+
.add(root.clone())
|
|
96
|
+
.map_err(|_| Failure::new("tls", "invalid trust anchor"))?;
|
|
97
|
+
}
|
|
98
|
+
let builder = ClientConfig::builder_with_provider(provider())
|
|
99
|
+
.with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])
|
|
100
|
+
.map_err(|_| Failure::new("tls", "unsupported protocol versions"))?
|
|
101
|
+
.with_root_certificates(roots);
|
|
102
|
+
let mut config = match &self.identity {
|
|
103
|
+
Some((chain, key)) => builder
|
|
104
|
+
.with_client_auth_cert(chain.clone(), key.clone_key())
|
|
105
|
+
.map_err(|_| Failure::new("tls", "client identity rejected"))?,
|
|
106
|
+
None => builder.with_no_client_auth(),
|
|
107
|
+
};
|
|
108
|
+
config.resumption = Resumption::disabled();
|
|
109
|
+
let mut h1 = config.clone();
|
|
110
|
+
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
|
111
|
+
h1.alpn_protocols = vec![b"http/1.1".to_vec()];
|
|
112
|
+
Ok((Arc::new(config), Arc::new(h1)))
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
//! The Connect unary fast path: connect or reuse, send, head and the whole
|
|
2
|
+
//! body under the response limit as one operation, so a call releases the
|
|
3
|
+
//! GVL once.
|
|
4
|
+
use std::sync::Arc;
|
|
5
|
+
use std::time::Instant;
|
|
6
|
+
|
|
7
|
+
use bytes::{Bytes, BytesMut};
|
|
8
|
+
use http_body_util::BodyExt;
|
|
9
|
+
|
|
10
|
+
use crate::body::CallBody;
|
|
11
|
+
use crate::call::{Unanswered, send};
|
|
12
|
+
use crate::failure::Failure;
|
|
13
|
+
use crate::pool::{DriverCore, RequestSpec};
|
|
14
|
+
|
|
15
|
+
pub struct Unary {
|
|
16
|
+
pub status: u16,
|
|
17
|
+
pub headers: http::HeaderMap,
|
|
18
|
+
pub body: Bytes,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
fn content_length(headers: &http::HeaderMap) -> Option<u64> {
|
|
22
|
+
headers
|
|
23
|
+
.get(http::header::CONTENT_LENGTH)
|
|
24
|
+
.and_then(|value| value.to_str().ok())
|
|
25
|
+
.and_then(|value| value.trim().parse().ok())
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// Retries once, on a fresh connection and with a refreshed wire timeout: a
|
|
29
|
+
/// request hyper hands back unsent or that its connection stranded (see
|
|
30
|
+
/// `send`), or, before response headers, a stream the server refused with
|
|
31
|
+
/// REFUSED_STREAM or that its GOAWAY says it never processed (a stream id
|
|
32
|
+
/// above the last stream id). Nothing else is replayed.
|
|
33
|
+
pub async fn unary(
|
|
34
|
+
core: Arc<DriverCore>,
|
|
35
|
+
spec: RequestSpec,
|
|
36
|
+
payload: Option<Bytes>,
|
|
37
|
+
limit: usize,
|
|
38
|
+
deadline: Option<Instant>,
|
|
39
|
+
) -> Result<Unary, Failure> {
|
|
40
|
+
let mut exclude = None;
|
|
41
|
+
loop {
|
|
42
|
+
let mut lease = core.acquire(&spec.origin, false, exclude, deadline).await?;
|
|
43
|
+
let body = match &payload {
|
|
44
|
+
Some(bytes) => CallBody::full(bytes.clone()),
|
|
45
|
+
None => CallBody::empty(),
|
|
46
|
+
};
|
|
47
|
+
let request = spec.build(body, deadline, lease.is_h2())?;
|
|
48
|
+
// Spec hold point: parks the call before it hands its request to
|
|
49
|
+
// hyper, while the runtime keeps driving the connection.
|
|
50
|
+
core.holds.reach("request:send").await;
|
|
51
|
+
let (sent, mark) = send(&mut lease, request, &core.holds);
|
|
52
|
+
// Spec hold point: armed with a zero bound, it counts the requests
|
|
53
|
+
// handed to hyper.
|
|
54
|
+
core.holds.block("request:queued");
|
|
55
|
+
let response = match sent.await {
|
|
56
|
+
Ok(response) => response,
|
|
57
|
+
Err(Unanswered::Stranded) => {
|
|
58
|
+
// Never taken by hyper, so never sent: as unsent below.
|
|
59
|
+
core.holds.reach("retry:unsent").await;
|
|
60
|
+
if exclude.is_none() {
|
|
61
|
+
exclude = Some(lease.id());
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
return Err(lease.closed_failure());
|
|
65
|
+
}
|
|
66
|
+
Err(Unanswered::Failed(mut error)) => {
|
|
67
|
+
let unsent = error.take_message().is_some();
|
|
68
|
+
if unsent {
|
|
69
|
+
// Spec hold point: it parks, or with a zero bound counts,
|
|
70
|
+
// the requests hyper handed back unsent.
|
|
71
|
+
core.holds.reach("retry:unsent").await;
|
|
72
|
+
}
|
|
73
|
+
// Its stream is above a GOAWAY's last stream id and either h2
|
|
74
|
+
// failed it for that GOAWAY or it never reached the socket.
|
|
75
|
+
let unprocessed = !unsent
|
|
76
|
+
&& mark.as_ref().is_some_and(|mark| {
|
|
77
|
+
mark.unprocessed()
|
|
78
|
+
&& (Failure::remote_go_away(error.error()) || mark.unsent())
|
|
79
|
+
});
|
|
80
|
+
let replayable = unsent || unprocessed || Failure::refused_stream(error.error());
|
|
81
|
+
if replayable && exclude.is_none() {
|
|
82
|
+
if unprocessed {
|
|
83
|
+
// Spec hold point: it parks, or with a zero bound
|
|
84
|
+
// counts, the requests replayed after a GOAWAY.
|
|
85
|
+
core.holds.reach("retry:unprocessed").await;
|
|
86
|
+
}
|
|
87
|
+
exclude = Some(lease.id());
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
return Err(lease.failure(error.error()));
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
let (parts, mut incoming) = response.into_parts();
|
|
94
|
+
if content_length(&parts.headers).is_some_and(|length| length > limit as u64) {
|
|
95
|
+
return Err(Failure::new(
|
|
96
|
+
"response_limit",
|
|
97
|
+
"response exceeds byte limit",
|
|
98
|
+
));
|
|
99
|
+
}
|
|
100
|
+
let mut body = BytesMut::new();
|
|
101
|
+
while let Some(frame) = incoming.frame().await {
|
|
102
|
+
let frame = frame.map_err(|error| lease.failure(&error))?;
|
|
103
|
+
if let Ok(data) = frame.into_data() {
|
|
104
|
+
if body.len() + data.len() > limit {
|
|
105
|
+
return Err(Failure::new(
|
|
106
|
+
"response_limit",
|
|
107
|
+
"response exceeds byte limit",
|
|
108
|
+
));
|
|
109
|
+
}
|
|
110
|
+
body.extend_from_slice(&data);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
core.release_h1(&mut lease);
|
|
114
|
+
return Ok(Unary {
|
|
115
|
+
status: parts.status.as_u16(),
|
|
116
|
+
headers: parts.headers,
|
|
117
|
+
body: body.freeze(),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|