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.
@@ -0,0 +1,1206 @@
1
+ //! Driver state and connection admission.
2
+ //!
3
+ //! Pooled HTTP/2: one admitting connection per origin. A connection whose
4
+ //! dispatcher ended (GOAWAY, error, close) stops admitting and drains its
5
+ //! streams on its own while the next caller dials a new one.
6
+ //!
7
+ //! Pool dials, as grpc-go's channel dials: an origin has at most one shared
8
+ //! HTTP/2 dial at a time, a task the driver owns. Its outcome is decided only
9
+ //! by the dial and by `close`, never by a caller, and every caller that waited
10
+ //! for it gets the same outcome: a pooled connection to check out (a waiter
11
+ //! that finds it ended before the server's HTTP/2 preface, and nothing else
12
+ //! usable, fails as that connection would have), HTTP/1.1 (the clean
13
+ //! connection is parked idle; each waiter then uses a usable pooled or idle
14
+ //! connection, else dials its own), or the failure. A caller decides to use
15
+ //! a connection, or else to join or start the dial, under one lock. It waits
16
+ //! under its own deadline, cancellation and interrupts, and leaving changes
17
+ //! nothing about the dial, whose per-address budget splits `connect_timeout`
18
+ //! alone. A dial still running when its transport is garbage collected ends
19
+ //! within `connect_timeout`.
20
+ //!
21
+ //! Unshared dials run inside one call, bounded by the earlier of
22
+ //! `connect_timeout` and the call deadline: per-call mode, `http2: false`
23
+ //! (one HTTP/1.1 connection serves one call at a time, so connections dial
24
+ //! in parallel, as Go net/http dials them), callers after an HTTP/1.1
25
+ //! outcome and a retry from a pooled connection that still admits. A second
26
+ //! HTTP/2 connection never replaces a usable pooled one: it serves only the
27
+ //! call that dialed it. Idle connections close after
28
+ //! `idle_timeout`; the reaper claims the exact checkout generation it
29
+ //! observed idle, read under the lock checkouts count with. At most two idle
30
+ //! HTTP/1.1 keep-alive connections per origin; only a connection whose request
31
+ //! and response both completed cleanly returns, and each idle connection has
32
+ //! one idle timer, cancelled when a call takes it.
33
+ //!
34
+ //! Closing: waiters of a pool dial fail with the closed phrase and the dial
35
+ //! ends. An admitted call's own unshared dial still proceeds within the
36
+ //! grace, but a connection dialed after admission closed is never pooled.
37
+ //! Teardown runs as a runtime task, so it ends however closers are
38
+ //! interrupted, and every closer gets its published outcome.
39
+ use std::collections::HashMap;
40
+ use std::future::Future;
41
+ use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
42
+ use std::sync::{Arc, Mutex, Weak};
43
+ use std::time::{Duration, Instant};
44
+
45
+ use hyper::client::conn::{http1, http2};
46
+ use tokio::sync::Notify;
47
+
48
+ use crate::body::CallBody;
49
+ use crate::conn::{self, Connected, Handshake, Origin, Settings};
50
+ use crate::failure::{Failure, TlsFault};
51
+ use crate::gvl::Signal;
52
+ use crate::holds::Holds;
53
+ use crate::runtime::{self, Task, Tracker};
54
+ use crate::tls::{TlsInputs, native_roots};
55
+ use crate::wire::{Mark, Wire};
56
+
57
+ /// Go's DefaultMaxIdleConnsPerHost.
58
+ const MAX_IDLE_H1: usize = 2;
59
+ /// core's GRPCProtocol::FIELD_LIMIT.
60
+ const GRPC_FIELD_LIMIT: usize = 65_536;
61
+
62
+ type TlsConfigs = (Arc<rustls::ClientConfig>, Arc<rustls::ClientConfig>);
63
+
64
+ pub struct Config {
65
+ pub pooled: bool,
66
+ pub idle_timeout: Option<Duration>,
67
+ pub connect_timeout: Duration,
68
+ pub settings: Settings,
69
+ pub tls: TlsInputs,
70
+ }
71
+
72
+ pub struct DriverCore {
73
+ pub config: Config,
74
+ tls_configs: tokio::sync::OnceCell<TlsConfigs>,
75
+ pub tracker: Arc<Tracker>,
76
+ origins: Mutex<HashMap<Origin, Arc<OriginEntry>>>,
77
+ closing: AtomicBool,
78
+ /// Fires when admission closes: wakes the waiters of a pool dial.
79
+ pub closed: Arc<Signal>,
80
+ /// Fires on forced teardown: ends every wait of every call.
81
+ pub shutdown: Arc<Signal>,
82
+ teardown: AtomicBool,
83
+ /// The teardown result: unknown, false or true (0, 1, 2).
84
+ outcome: AtomicU8,
85
+ /// Fires once `outcome` is published.
86
+ torn_down: Arc<Signal>,
87
+ inflight: AtomicUsize,
88
+ drained: Notify,
89
+ opened: AtomicUsize,
90
+ next_id: AtomicU64,
91
+ pub holds: Arc<Holds>,
92
+ }
93
+
94
+ #[derive(Default)]
95
+ pub struct OriginEntry {
96
+ state: Mutex<OriginState>,
97
+ }
98
+
99
+ #[derive(Default)]
100
+ struct OriginState {
101
+ h2: Option<Arc<H2Conn>>,
102
+ /// The pool dial in progress.
103
+ dialing: Option<Arc<Dial>>,
104
+ idle_h1: Vec<IdleH1>,
105
+ }
106
+
107
+ /// A pool dial's outcome, shared by everyone who waited for it.
108
+ #[derive(Default)]
109
+ struct Dial {
110
+ outcome: Mutex<Option<Outcome>>,
111
+ done: Signal,
112
+ }
113
+
114
+ #[derive(Clone)]
115
+ enum Outcome {
116
+ /// The pool has a usable HTTP/2 connection: check it out. It names the
117
+ /// connection this dial pooled, if the pool kept it.
118
+ Pooled(Option<Dialed>),
119
+ /// TLS negotiated HTTP/1.1. The connection is parked idle, if it fits;
120
+ /// waiters claim again without sharing a dial.
121
+ Http1,
122
+ /// The dial failed: every waiter fails the same way.
123
+ Failed(Failure),
124
+ /// Close ended the dial, or its task ended without an outcome.
125
+ Ended,
126
+ }
127
+
128
+ impl Dial {
129
+ async fn wait(&self) -> Outcome {
130
+ self.done.wait().await;
131
+ self.outcome
132
+ .lock()
133
+ .unwrap_or_else(|e| e.into_inner())
134
+ .clone()
135
+ .unwrap_or(Outcome::Ended)
136
+ }
137
+ }
138
+
139
+ /// Publishes a pool dial's outcome when dropped, so every exit of its task
140
+ /// (an outcome, close, abort, refusal by a sealed tracker or a panic) ends
141
+ /// the dial for its waiters. Clearing `dialing` comes first, so a caller
142
+ /// woken by the outcome finds either the pooled connection or no dial.
143
+ struct Publish {
144
+ entry: Arc<OriginEntry>,
145
+ dial: Arc<Dial>,
146
+ outcome: Option<Outcome>,
147
+ }
148
+
149
+ impl Publish {
150
+ fn finish(mut self, outcome: Outcome) {
151
+ self.outcome = Some(outcome);
152
+ }
153
+ }
154
+
155
+ impl Drop for Publish {
156
+ fn drop(&mut self) {
157
+ {
158
+ let mut state = self.entry.state.lock().unwrap_or_else(|e| e.into_inner());
159
+ if state
160
+ .dialing
161
+ .as_ref()
162
+ .is_some_and(|current| Arc::ptr_eq(current, &self.dial))
163
+ {
164
+ state.dialing = None;
165
+ }
166
+ }
167
+ *self.dial.outcome.lock().unwrap_or_else(|e| e.into_inner()) = self.outcome.take();
168
+ self.dial.done.fire();
169
+ }
170
+ }
171
+
172
+ /// What one look at an origin's state gives a caller.
173
+ enum Claim {
174
+ /// A pooled connection; a parked HTTP/1.1 one still needs `ready`.
175
+ Lease(Lease),
176
+ /// Dial a connection for this call only.
177
+ Dial,
178
+ /// Wait for the pool dial; `start` when this caller created it.
179
+ Wait { dial: Arc<Dial>, start: bool },
180
+ }
181
+
182
+ struct H2Conn {
183
+ sender: http2::SendRequest<CallBody>,
184
+ shared: Arc<ConnShared>,
185
+ local_port: u16,
186
+ wire: Arc<Wire>,
187
+ fault: Arc<TlsFault>,
188
+ }
189
+
190
+ impl H2Conn {
191
+ /// A GOAWAY read on the socket retires the connection at once, before
192
+ /// hyper's dispatcher notices it, so retries do not each dial past it.
193
+ fn usable(&self) -> bool {
194
+ !self.sender.is_closed() && !self.shared.closed.fired() && !self.wire.going_away()
195
+ }
196
+ }
197
+
198
+ struct ConnShared {
199
+ id: u64,
200
+ active: AtomicUsize,
201
+ generation: AtomicU64,
202
+ idle: Notify,
203
+ closed: Arc<Signal>,
204
+ /// The pool evicted it as unusable. hyper may close its sender before
205
+ /// `closed` fires; this keeps that verdict for `Dialed`, which has none.
206
+ retired: AtomicBool,
207
+ /// The idle reaper evicted it: its end is the pool's doing, not a failed
208
+ /// connection attempt, even before the server's preface arrived.
209
+ reaped: AtomicBool,
210
+ }
211
+
212
+ /// A connection the pool kept, without its hyper sender: an outcome a slow
213
+ /// waiter has yet to claim must not keep an evicted connection open (the
214
+ /// idle reaper relies on the pool's sender being the last one).
215
+ #[derive(Clone)]
216
+ struct Dialed {
217
+ shared: Arc<ConnShared>,
218
+ wire: Arc<Wire>,
219
+ fault: Arc<TlsFault>,
220
+ }
221
+
222
+ impl Dialed {
223
+ /// The connection's failure when it closed or stopped admitting before
224
+ /// the server's HTTP/2 preface (its SETTINGS): a failed connection
225
+ /// attempt, as grpc-go treats a transport that never received the server
226
+ /// preface. None while it admits or once the server started HTTP/2.
227
+ fn failure(&self) -> Option<Failure> {
228
+ // Ended first: a preface read, or an idle eviction made, before the
229
+ // end is then always seen.
230
+ let ended = self.shared.retired.load(Ordering::SeqCst)
231
+ || self.shared.closed.fired()
232
+ || self.wire.going_away();
233
+ let failed =
234
+ ended && !self.shared.reaped.load(Ordering::SeqCst) && !self.wire.server_started();
235
+ failed.then(|| self.fault.resolve(Failure::closed()))
236
+ }
237
+ }
238
+
239
+ struct IdleH1 {
240
+ /// Unique per park, so a timer only ever claims the park it started for.
241
+ park: u64,
242
+ conn: H1Conn,
243
+ _timer: Option<IdleTimer>,
244
+ }
245
+
246
+ /// An idle connection's timer task, aborted when the connection leaves the
247
+ /// idle list (checkout, close or expiry).
248
+ struct IdleTimer(Task);
249
+
250
+ impl Drop for IdleTimer {
251
+ fn drop(&mut self) {
252
+ self.0.abort();
253
+ }
254
+ }
255
+
256
+ pub struct H1Conn {
257
+ pub sender: http1::SendRequest<CallBody>,
258
+ task: Task,
259
+ /// Fires once hyper's dispatcher has ended and been dropped.
260
+ closed: Arc<Signal>,
261
+ id: u64,
262
+ pub local_port: u16,
263
+ fault: Arc<TlsFault>,
264
+ }
265
+
266
+ impl H1Conn {
267
+ /// Closes the socket now, whatever was in flight.
268
+ fn abort(self) {
269
+ self.task.abort();
270
+ }
271
+ }
272
+
273
+ /// One call's hold on a connection.
274
+ pub enum Lease {
275
+ H2 {
276
+ sender: http2::SendRequest<CallBody>,
277
+ local_port: u16,
278
+ id: u64,
279
+ wire: Arc<Wire>,
280
+ fault: Arc<TlsFault>,
281
+ /// Fires once hyper's dispatcher has ended and been dropped.
282
+ closed: Arc<Signal>,
283
+ _active: Option<Active>,
284
+ },
285
+ H1 {
286
+ conn: Option<H1Conn>,
287
+ entry: Option<Arc<OriginEntry>>,
288
+ },
289
+ }
290
+
291
+ impl Lease {
292
+ pub fn id(&self) -> u64 {
293
+ match self {
294
+ Lease::H2 { id, .. } => *id,
295
+ Lease::H1 { conn, .. } => conn.as_ref().map_or(0, |c| c.id),
296
+ }
297
+ }
298
+
299
+ pub fn local_port(&self) -> u16 {
300
+ match self {
301
+ Lease::H2 { local_port, .. } => *local_port,
302
+ Lease::H1 { conn, .. } => conn.as_ref().map_or(0, |c| c.local_port),
303
+ }
304
+ }
305
+
306
+ pub fn is_h2(&self) -> bool {
307
+ matches!(self, Lease::H2 { .. })
308
+ }
309
+
310
+ /// A mark for the next request on an HTTP/2 connection.
311
+ pub fn mark(&self) -> Option<Arc<Mark>> {
312
+ match self {
313
+ Lease::H2 { wire, .. } => Some(Mark::new(wire.clone())),
314
+ Lease::H1 { .. } => None,
315
+ }
316
+ }
317
+
318
+ /// The connection's TLS failure record; None once an HTTP/1.1 lease
319
+ /// released its connection.
320
+ pub fn fault(&self) -> Option<&Arc<TlsFault>> {
321
+ match self {
322
+ Lease::H2 { fault, .. } => Some(fault),
323
+ Lease::H1 { conn, .. } => conn.as_ref().map(|c| &c.fault),
324
+ }
325
+ }
326
+
327
+ /// A call failure for `error` on this lease's connection, reporting a
328
+ /// TLS failure that ended the connection as such.
329
+ pub fn failure(&self, error: &hyper::Error) -> Failure {
330
+ match self.fault() {
331
+ Some(fault) => fault.failure(error),
332
+ None => Failure::from_hyper(error),
333
+ }
334
+ }
335
+
336
+ /// The failure of a request that its connection ended without answering
337
+ /// (see `call::send`): the connection's TLS failure, or a closed one.
338
+ pub fn closed_failure(&self) -> Failure {
339
+ match self.fault() {
340
+ Some(fault) => fault.resolve(Failure::closed()),
341
+ None => Failure::closed(),
342
+ }
343
+ }
344
+
345
+ /// The signal that fires once the connection's dispatcher has ended and
346
+ /// been dropped; None once an HTTP/1.1 lease released its connection.
347
+ pub fn closed(&self) -> Option<&Arc<Signal>> {
348
+ match self {
349
+ Lease::H2 { closed, .. } => Some(closed),
350
+ Lease::H1 { conn, .. } => conn.as_ref().map(|c| &c.closed),
351
+ }
352
+ }
353
+
354
+ pub fn disable_wire(&self) {
355
+ if let Lease::H2 { wire, .. } = self {
356
+ wire.disable();
357
+ }
358
+ }
359
+ }
360
+
361
+ impl Drop for Lease {
362
+ fn drop(&mut self) {
363
+ // A lease dropped without a clean release closes an HTTP/1.1 socket:
364
+ // its request or response may be incomplete.
365
+ if let Lease::H1 { conn, .. } = self {
366
+ if let Some(conn) = conn.take() {
367
+ conn.abort();
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ /// Counts a call on a pooled HTTP/2 connection; dropping it may start the
374
+ /// idle clock.
375
+ pub struct Active {
376
+ shared: Arc<ConnShared>,
377
+ }
378
+
379
+ impl Drop for Active {
380
+ fn drop(&mut self) {
381
+ if self.shared.active.fetch_sub(1, Ordering::AcqRel) == 1 {
382
+ self.shared.idle.notify_waiters();
383
+ }
384
+ }
385
+ }
386
+
387
+ /// Holds a call in the driver's in-flight count until released.
388
+ pub struct Inflight {
389
+ core: Weak<DriverCore>,
390
+ }
391
+
392
+ impl Drop for Inflight {
393
+ fn drop(&mut self) {
394
+ if let Some(core) = self.core.upgrade() {
395
+ if core.inflight.fetch_sub(1, Ordering::AcqRel) == 1 {
396
+ core.drained.notify_waiters();
397
+ }
398
+ }
399
+ }
400
+ }
401
+
402
+ /// The parts of a request that survive a retry.
403
+ pub struct RequestSpec {
404
+ pub method: http::Method,
405
+ pub uri: http::Uri,
406
+ pub origin: Origin,
407
+ pub headers: Vec<(http::HeaderName, http::HeaderValue)>,
408
+ pub timeout_header: Option<TimeoutHeader>,
409
+ pub grpc: bool,
410
+ }
411
+
412
+ #[derive(Clone, Copy)]
413
+ pub enum TimeoutHeader {
414
+ Grpc,
415
+ Connect,
416
+ }
417
+
418
+ /// core's GRPCProtocol.timeout.
419
+ fn grpc_timeout(seconds: f64) -> String {
420
+ const UNITS: [(&str, f64); 6] = [
421
+ ("n", 1e-9),
422
+ ("u", 1e-6),
423
+ ("m", 0.001),
424
+ ("S", 1.0),
425
+ ("M", 60.0),
426
+ ("H", 3600.0),
427
+ ];
428
+ for (unit, scale) in UNITS {
429
+ let scaled = seconds / scale;
430
+ if scaled.is_finite() && scaled <= 99_999_999.0 {
431
+ let amount = scaled.ceil();
432
+ if amount <= 99_999_999.0 {
433
+ return format!("{}{unit}", amount.max(1.0) as u64);
434
+ }
435
+ }
436
+ }
437
+ "99999999H".to_string()
438
+ }
439
+
440
+ /// core's Deadline#timeout_ms.
441
+ fn connect_timeout_ms(seconds: f64) -> String {
442
+ let millis = (seconds * 1000.0).min(9_999_999_999.0).ceil();
443
+ (millis as u64).clamp(1, 9_999_999_999).to_string()
444
+ }
445
+
446
+ impl RequestSpec {
447
+ /// Builds the request at dispatch: the wire timeout reflects the deadline
448
+ /// remaining now, after connection setup.
449
+ pub fn build(
450
+ &self,
451
+ body: CallBody,
452
+ deadline: Option<Instant>,
453
+ h2: bool,
454
+ ) -> Result<hyper::Request<CallBody>, Failure> {
455
+ let mut builder = hyper::Request::builder().method(self.method.clone());
456
+ builder = if h2 {
457
+ builder.uri(self.uri.clone())
458
+ } else {
459
+ let authority = self
460
+ .uri
461
+ .authority()
462
+ .map_or(self.origin.host.as_str(), |a| a.as_str());
463
+ // A forwarding proxy takes the absolute form and its credentials;
464
+ // an origin, direct or through a tunnel, takes the origin form.
465
+ let builder = match self
466
+ .origin
467
+ .proxy
468
+ .as_ref()
469
+ .filter(|_| self.origin.forwarded())
470
+ {
471
+ Some(route) => {
472
+ let builder = builder.uri(self.uri.clone());
473
+ match &route.authorization {
474
+ Some(value) => {
475
+ builder.header(http::header::PROXY_AUTHORIZATION, value.clone())
476
+ }
477
+ None => builder,
478
+ }
479
+ }
480
+ None => builder.uri(self.uri.path_and_query().map_or("/", |p| p.as_str())),
481
+ };
482
+ builder.header(http::header::HOST, authority)
483
+ };
484
+ let mut request = builder
485
+ .body(body)
486
+ .map_err(|_| Failure::new("request", "invalid request"))?;
487
+ let headers = request.headers_mut();
488
+ for (name, value) in &self.headers {
489
+ headers.append(name.clone(), value.clone());
490
+ }
491
+ if let (Some(kind), Some(deadline)) = (self.timeout_header, deadline) {
492
+ let remaining = deadline
493
+ .saturating_duration_since(Instant::now())
494
+ .as_secs_f64();
495
+ if remaining <= 0.0 {
496
+ return Err(Failure::new("timeout", "deadline expired before dispatch"));
497
+ }
498
+ let (name, value) = match kind {
499
+ TimeoutHeader::Grpc => ("grpc-timeout", grpc_timeout(remaining)),
500
+ TimeoutHeader::Connect => ("connect-timeout-ms", connect_timeout_ms(remaining)),
501
+ };
502
+ let value = http::HeaderValue::from_str(&value).expect("timeout header is ASCII");
503
+ headers.insert(http::HeaderName::from_static(name), value);
504
+ }
505
+ if self.grpc {
506
+ // core's GRPCProtocol.check_fields!, on the fields actually sent.
507
+ let size: usize = headers
508
+ .iter()
509
+ .filter(|(name, _)| *name != http::header::HOST)
510
+ .map(|(name, value)| name.as_str().len() + value.len() + 32)
511
+ .sum();
512
+ if size > GRPC_FIELD_LIMIT {
513
+ return Err(Failure::new(
514
+ "field_limit",
515
+ "gRPC field block exceeds byte limit",
516
+ ));
517
+ }
518
+ }
519
+ Ok(request)
520
+ }
521
+ }
522
+
523
+ impl DriverCore {
524
+ pub fn new(config: Config, tracker: Arc<Tracker>) -> Arc<Self> {
525
+ Arc::new(Self {
526
+ config,
527
+ tls_configs: tokio::sync::OnceCell::new(),
528
+ tracker,
529
+ origins: Mutex::new(HashMap::new()),
530
+ closing: AtomicBool::new(false),
531
+ closed: Signal::new(),
532
+ shutdown: Signal::new(),
533
+ teardown: AtomicBool::new(false),
534
+ outcome: AtomicU8::new(0),
535
+ torn_down: Signal::new(),
536
+ inflight: AtomicUsize::new(0),
537
+ drained: Notify::new(),
538
+ opened: AtomicUsize::new(0),
539
+ next_id: AtomicU64::new(1),
540
+ holds: Arc::default(),
541
+ })
542
+ }
543
+
544
+ pub fn opened(&self) -> usize {
545
+ self.opened.load(Ordering::SeqCst)
546
+ }
547
+
548
+ /// Idle pooled HTTP/1.1 connections across origins.
549
+ pub fn idle_h1(&self) -> usize {
550
+ let origins = self.origins.lock().unwrap_or_else(|e| e.into_inner());
551
+ origins
552
+ .values()
553
+ .map(|entry| {
554
+ entry
555
+ .state
556
+ .lock()
557
+ .unwrap_or_else(|e| e.into_inner())
558
+ .idle_h1
559
+ .len()
560
+ })
561
+ .sum()
562
+ }
563
+
564
+ pub fn inflight(&self) -> usize {
565
+ self.inflight.load(Ordering::SeqCst)
566
+ }
567
+
568
+ pub fn is_closing(&self) -> bool {
569
+ self.closing.load(Ordering::SeqCst)
570
+ }
571
+
572
+ pub fn admit(self: &Arc<Self>) -> Result<Inflight, Failure> {
573
+ self.inflight.fetch_add(1, Ordering::AcqRel);
574
+ let guard = Inflight {
575
+ core: Arc::downgrade(self),
576
+ };
577
+ if self.is_closing() {
578
+ return Err(Failure::admission());
579
+ }
580
+ Ok(guard)
581
+ }
582
+
583
+ fn entry(&self, origin: &Origin) -> Arc<OriginEntry> {
584
+ let mut origins = self.origins.lock().unwrap_or_else(|e| e.into_inner());
585
+ origins.entry(origin.clone()).or_default().clone()
586
+ }
587
+
588
+ async fn tls_config(&self, h2: bool) -> Result<Arc<rustls::ClientConfig>, Failure> {
589
+ let (with_h2, h1_only) = self
590
+ .tls_configs
591
+ .get_or_try_init(|| async {
592
+ let native = tokio::task::spawn_blocking(native_roots)
593
+ .await
594
+ .map_err(|_| Failure::new("tls", "trust store load failed"))?;
595
+ self.config.tls.configs(&native)
596
+ })
597
+ .await?;
598
+ Ok(if h2 { with_h2.clone() } else { h1_only.clone() })
599
+ }
600
+
601
+ /// Dials within `connect_timeout`. As Go's dialer does, each address
602
+ /// attempt gets a share of what is left before the earlier of
603
+ /// `connect_timeout` and `deadline`: the call deadline for an unshared
604
+ /// dial, none for a pool dial. The call deadline itself still ends the
605
+ /// call as the caller's expiry.
606
+ async fn dial(
607
+ self: &Arc<Self>,
608
+ origin: &Origin,
609
+ deadline: Option<Instant>,
610
+ ) -> Result<Connected, Failure> {
611
+ let limit = self.config.connect_timeout;
612
+ let mut budget = tokio::time::Instant::now() + limit;
613
+ if let Some(deadline) = deadline {
614
+ budget = budget.min(tokio::time::Instant::from_std(deadline));
615
+ }
616
+ let work = async {
617
+ let tls = if origin.https {
618
+ Some(self.tls_config(self.config.settings.http2).await?)
619
+ } else {
620
+ None
621
+ };
622
+ conn::connect(
623
+ &self.config.settings,
624
+ tls,
625
+ origin,
626
+ &self.tracker,
627
+ &self.holds,
628
+ budget,
629
+ )
630
+ .await
631
+ };
632
+ let connected = tokio::time::timeout(limit, work)
633
+ .await
634
+ .map_err(|_| Failure::new("connect_timeout", "connection setup timed out"))??;
635
+ self.opened.fetch_add(1, Ordering::SeqCst);
636
+ Ok(connected)
637
+ }
638
+
639
+ fn next_id(&self) -> u64 {
640
+ self.next_id.fetch_add(1, Ordering::SeqCst)
641
+ }
642
+
643
+ /// A connection for one call ending at `deadline`. `exclude` names a
644
+ /// connection that just refused or handed back a request: a retry never
645
+ /// reuses it, and never evicts it while it still admits other calls. A
646
+ /// call admitted before close keeps its own unshared dial; new calls and
647
+ /// waiters of a pool dial fail with the closed phrase.
648
+ pub async fn acquire(
649
+ self: &Arc<Self>,
650
+ origin: &Origin,
651
+ require_h2: bool,
652
+ exclude: Option<u64>,
653
+ deadline: Option<Instant>,
654
+ ) -> Result<Lease, Failure> {
655
+ if self.is_closing() {
656
+ return Err(Failure::admission());
657
+ }
658
+ if !self.config.pooled {
659
+ let connected = self.dial(origin, deadline).await?;
660
+ return self.fresh_lease(connected, None, require_h2);
661
+ }
662
+ let entry = self.entry(origin);
663
+ // HTTP/1.1 connections cannot be shared, so neither are their dials,
664
+ // nor dials after a pool dial negotiated HTTP/1.1.
665
+ let mut share = self.config.settings.http2;
666
+ // The connection the pool dial this caller waited for pooled. One that
667
+ // ended before the server's HTTP/2 preface fails the caller instead
668
+ // of starting another dial (see `claim`), so a server that rejects
669
+ // every connection cannot keep it dialing.
670
+ let mut waited = None;
671
+ loop {
672
+ let dial = match self.claim(&entry, require_h2, exclude, share, waited.take())? {
673
+ Claim::Lease(lease) => match self.ready(lease).await? {
674
+ Some(lease) => return Ok(lease),
675
+ None => continue,
676
+ },
677
+ Claim::Dial => {
678
+ let connected = self.dial(origin, deadline).await?;
679
+ return self.fresh_lease(connected, Some(&entry), require_h2);
680
+ }
681
+ Claim::Wait { dial, start } => {
682
+ if start {
683
+ self.tracker.spawn(self.clone().pool_dial(
684
+ entry.clone(),
685
+ origin.clone(),
686
+ dial.clone(),
687
+ ));
688
+ // Spec hold point: armed with a zero bound, it counts
689
+ // the pool dials started.
690
+ self.holds.reach("dial:started").await;
691
+ }
692
+ // Spec hold point: armed with a zero bound, it counts the
693
+ // callers that will get a pool dial's outcome. A thread
694
+ // parked in a native wait may not have claimed yet.
695
+ self.holds.reach("dial:joined").await;
696
+ dial
697
+ }
698
+ };
699
+ let outcome = tokio::select! {
700
+ outcome = dial.wait() => outcome,
701
+ _ = self.closed.wait() => return Err(Failure::admission()),
702
+ };
703
+ if self.is_closing() {
704
+ return Err(Failure::admission());
705
+ }
706
+ match outcome {
707
+ Outcome::Pooled(conn) => waited = conn,
708
+ // The origin speaks HTTP/1.1; dialing again would not change it.
709
+ Outcome::Http1 if require_h2 => {
710
+ return Err(Failure::new("alpn", "HTTP/2 was not negotiated"));
711
+ }
712
+ Outcome::Http1 => share = false,
713
+ Outcome::Failed(failure) => return Err(failure),
714
+ Outcome::Ended => return Err(Failure::new("closed", "connection setup ended")),
715
+ }
716
+ }
717
+ }
718
+
719
+ /// A pool dial: its own task, bounded by `connect_timeout` alone and
720
+ /// ended by close. `Publish` exists before the task does, so dropping the
721
+ /// task unpolled (refused by a sealed tracker or aborted) publishes too.
722
+ fn pool_dial(
723
+ self: Arc<Self>,
724
+ entry: Arc<OriginEntry>,
725
+ origin: Origin,
726
+ dial: Arc<Dial>,
727
+ ) -> impl Future<Output = ()> + Send + 'static {
728
+ let publish = Publish {
729
+ entry,
730
+ dial,
731
+ outcome: None,
732
+ };
733
+ async move {
734
+ let connected = tokio::select! {
735
+ connected = self.dial(&origin, None) => connected,
736
+ _ = self.closed.wait() => return,
737
+ };
738
+ let outcome = match connected {
739
+ Err(failure) => Outcome::Failed(failure),
740
+ Ok(connected) => match connected.handshake {
741
+ Handshake::H2 {
742
+ sender,
743
+ closed,
744
+ wire,
745
+ } => {
746
+ let id = self.next_id();
747
+ let port = connected.local_port;
748
+ let fault = connected.fault;
749
+ let pooled =
750
+ self.pool_h2(&publish.entry, sender, closed, wire, fault, port, id, 0);
751
+ if pooled.is_none() && self.is_closing() {
752
+ return;
753
+ }
754
+ // Pooled, or an unshared dial pooled a usable
755
+ // connection first and this one closes unused.
756
+ self.holds.reach("dial:pooled").await;
757
+ Outcome::Pooled(pooled)
758
+ }
759
+ Handshake::H1 {
760
+ sender,
761
+ task,
762
+ closed,
763
+ } => {
764
+ let conn = H1Conn {
765
+ sender,
766
+ task,
767
+ closed,
768
+ id: self.next_id(),
769
+ local_port: connected.local_port,
770
+ fault: connected.fault,
771
+ };
772
+ self.park_h1(publish.entry.clone(), conn);
773
+ if self.is_closing() {
774
+ return;
775
+ }
776
+ Outcome::Http1
777
+ }
778
+ },
779
+ };
780
+ publish.finish(outcome);
781
+ }
782
+ }
783
+
784
+ /// A parked HTTP/1.1 connection once hyper reports it ready, or None if
785
+ /// it closed meanwhile; any other lease as it is.
786
+ async fn ready(self: &Arc<Self>, mut lease: Lease) -> Result<Option<Lease>, Failure> {
787
+ let ready = match &mut lease {
788
+ Lease::H1 {
789
+ conn: Some(conn), ..
790
+ } => tokio::select! {
791
+ ready = conn.sender.ready() => ready.is_ok(),
792
+ _ = self.closed.wait() => return Err(Failure::admission()),
793
+ },
794
+ _ => true,
795
+ };
796
+ Ok(ready.then_some(lease))
797
+ }
798
+
799
+ /// One look at the origin under its lock: a usable connection, or else
800
+ /// the pool dial to join or start. Deciding both under one lock means a
801
+ /// caller never misses a connection pooled between its look and its join.
802
+ /// The caller spawns a dial it started after the lock is released: a
803
+ /// sealed tracker drops the task at once, and its `Publish` takes this
804
+ /// lock.
805
+ ///
806
+ /// `waited` is the connection the pool dial this caller waited for
807
+ /// pooled. If it ended before the server's HTTP/2 preface and nothing
808
+ /// else here is usable, the caller fails as that connection would have
809
+ /// failed its call, instead of dialing again: grpc-go treats a transport
810
+ /// that never received the server preface as a failed connection
811
+ /// attempt, and a server that ends every connection right after its
812
+ /// handshake (a TLS 1.3 server rejecting a missing client certificate)
813
+ /// would otherwise keep a caller dialing until its deadline. One that
814
+ /// drains or closes after the preface was a working connection: as
815
+ /// grpc-go re-picks, the caller joins or starts another dial, as do
816
+ /// callers that did not wait for that dial.
817
+ fn claim(
818
+ self: &Arc<Self>,
819
+ entry: &Arc<OriginEntry>,
820
+ require_h2: bool,
821
+ exclude: Option<u64>,
822
+ share: bool,
823
+ waited: Option<Dialed>,
824
+ ) -> Result<Claim, Failure> {
825
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
826
+ if let Some(conn) = state.h2.as_ref() {
827
+ let usable = conn.usable();
828
+ if usable && exclude == Some(conn.shared.id) {
829
+ // A retry from a connection that still admits: it stays pooled
830
+ // for its other calls, and the retry gets a connection of its
831
+ // own, which pool_h2 then leaves unpooled.
832
+ return Ok(Claim::Dial);
833
+ }
834
+ if usable {
835
+ // Under the state lock, so the reaper's claim sees it.
836
+ conn.shared.active.fetch_add(1, Ordering::AcqRel);
837
+ conn.shared.generation.fetch_add(1, Ordering::AcqRel);
838
+ return Ok(Claim::Lease(Lease::H2 {
839
+ sender: conn.sender.clone(),
840
+ local_port: conn.local_port,
841
+ id: conn.shared.id,
842
+ wire: conn.wire.clone(),
843
+ fault: conn.fault.clone(),
844
+ closed: conn.shared.closed.clone(),
845
+ _active: Some(Active {
846
+ shared: conn.shared.clone(),
847
+ }),
848
+ }));
849
+ }
850
+ // Stops admitting; its in-flight streams drain on their own.
851
+ conn.shared.retired.store(true, Ordering::SeqCst);
852
+ state.h2 = None;
853
+ }
854
+ // Taking a connection out of the idle list drops its timer.
855
+ while let Some(idle) = state.idle_h1.pop() {
856
+ if idle.conn.sender.is_closed() {
857
+ continue;
858
+ }
859
+ if require_h2 {
860
+ // The origin negotiated HTTP/1.1; keep the clean socket.
861
+ state.idle_h1.push(idle);
862
+ return Err(Failure::new("alpn", "HTTP/2 was not negotiated"));
863
+ }
864
+ return Ok(Claim::Lease(Lease::H1 {
865
+ conn: Some(idle.conn),
866
+ entry: Some(entry.clone()),
867
+ }));
868
+ }
869
+ if let Some(failure) = waited.and_then(|conn| conn.failure()) {
870
+ return Err(failure);
871
+ }
872
+ if !share {
873
+ return Ok(Claim::Dial);
874
+ }
875
+ if let Some(dial) = &state.dialing {
876
+ return Ok(Claim::Wait {
877
+ dial: dial.clone(),
878
+ start: false,
879
+ });
880
+ }
881
+ let dial = Arc::new(Dial::default());
882
+ state.dialing = Some(dial.clone());
883
+ Ok(Claim::Wait { dial, start: true })
884
+ }
885
+
886
+ fn fresh_lease(
887
+ self: &Arc<Self>,
888
+ connected: Connected,
889
+ entry: Option<&Arc<OriginEntry>>,
890
+ require_h2: bool,
891
+ ) -> Result<Lease, Failure> {
892
+ let id = self.next_id();
893
+ let local_port = connected.local_port;
894
+ let fault = connected.fault;
895
+ match connected.handshake {
896
+ // Without an entry (per-call mode) it serves only this call.
897
+ Handshake::H2 {
898
+ sender,
899
+ closed,
900
+ wire,
901
+ } => {
902
+ let active = entry
903
+ .and_then(|entry| {
904
+ let (sender, closed) = (sender.clone(), closed.clone());
905
+ let (wire, fault) = (wire.clone(), fault.clone());
906
+ self.pool_h2(entry, sender, closed, wire, fault, local_port, id, 1)
907
+ })
908
+ .map(|conn| Active {
909
+ shared: conn.shared,
910
+ });
911
+ Ok(Lease::H2 {
912
+ sender,
913
+ local_port,
914
+ id,
915
+ wire,
916
+ fault,
917
+ closed,
918
+ _active: active,
919
+ })
920
+ }
921
+ Handshake::H1 {
922
+ sender,
923
+ task,
924
+ closed,
925
+ } => {
926
+ let conn = H1Conn {
927
+ sender,
928
+ task,
929
+ closed,
930
+ id,
931
+ local_port,
932
+ fault,
933
+ };
934
+ if require_h2 {
935
+ // ALPN chose HTTP/1.1: fail before any request is queued.
936
+ // The untouched socket stays available to unary calls.
937
+ if let Some(entry) = entry {
938
+ self.park_h1(entry.clone(), conn);
939
+ }
940
+ return Err(Failure::new("alpn", "HTTP/2 was not negotiated"));
941
+ }
942
+ Ok(Lease::H1 {
943
+ conn: Some(conn),
944
+ entry: entry.cloned(),
945
+ })
946
+ }
947
+ }
948
+ }
949
+
950
+ /// Pools an HTTP/2 connection already held by `active` calls and starts
951
+ /// its reaper; returns its sender-free record, or None when it was not
952
+ /// pooled.
953
+ /// Checked under the lock begin_close clears the pool with: a connection
954
+ /// dialed for a call admitted before close serves only that call, then
955
+ /// closes with it. So does one dialed while a usable connection is pooled
956
+ /// (an unshared dial after an HTTP/1.1 outcome may still get h2 from TLS,
957
+ /// and a retry dials past a connection that still admits): replacing it
958
+ /// would retire a working connection with streams in flight.
959
+ #[allow(clippy::too_many_arguments)]
960
+ fn pool_h2(
961
+ self: &Arc<Self>,
962
+ entry: &Arc<OriginEntry>,
963
+ sender: http2::SendRequest<CallBody>,
964
+ closed: Arc<Signal>,
965
+ wire: Arc<Wire>,
966
+ fault: Arc<TlsFault>,
967
+ local_port: u16,
968
+ id: u64,
969
+ active: usize,
970
+ ) -> Option<Dialed> {
971
+ let shared = Arc::new(ConnShared {
972
+ id,
973
+ active: AtomicUsize::new(active),
974
+ generation: AtomicU64::new(1),
975
+ idle: Notify::new(),
976
+ closed,
977
+ retired: AtomicBool::new(false),
978
+ reaped: AtomicBool::new(false),
979
+ });
980
+ let dialed = Dialed {
981
+ shared: shared.clone(),
982
+ wire: wire.clone(),
983
+ fault: fault.clone(),
984
+ };
985
+ {
986
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
987
+ let pooled = state.h2.as_ref().is_some_and(|current| current.usable());
988
+ if self.is_closing() || pooled {
989
+ return None;
990
+ }
991
+ let replaced = state.h2.replace(Arc::new(H2Conn {
992
+ sender,
993
+ shared: shared.clone(),
994
+ local_port,
995
+ wire,
996
+ fault,
997
+ }));
998
+ if let Some(replaced) = replaced {
999
+ replaced.shared.retired.store(true, Ordering::SeqCst);
1000
+ }
1001
+ }
1002
+ if let Some(timeout) = self.config.idle_timeout {
1003
+ self.tracker.spawn(reap(
1004
+ Arc::downgrade(entry),
1005
+ shared.clone(),
1006
+ timeout,
1007
+ self.closed.clone(),
1008
+ self.holds.clone(),
1009
+ ));
1010
+ }
1011
+ Some(dialed)
1012
+ }
1013
+
1014
+ /// Returns an HTTP/1.1 connection once hyper reports it ready for the
1015
+ /// next request, within the idle cap. Called only after a clean exchange.
1016
+ pub fn release_h1(self: &Arc<Self>, lease: &mut Lease) {
1017
+ if let Lease::H1 { conn, entry } = lease {
1018
+ match (conn.take(), entry.take()) {
1019
+ (Some(conn), Some(entry)) if !self.is_closing() => self.park_h1(entry, conn),
1020
+ // Per-call or closing: dropping the sender closes it gracefully.
1021
+ (Some(conn), _) => drop(conn.sender),
1022
+ _ => {}
1023
+ }
1024
+ }
1025
+ }
1026
+
1027
+ /// Parks a clean HTTP/1.1 connection at once; the next checkout waits for
1028
+ /// hyper to report it ready before reusing it. Beyond the cap, dropping
1029
+ /// the sender closes it gracefully. Each park starts one idle timer,
1030
+ /// which the checkout that takes the connection aborts, so the
1031
+ /// connection closes only after a full `idle_timeout` of idleness.
1032
+ fn park_h1(self: &Arc<Self>, entry: Arc<OriginEntry>, conn: H1Conn) {
1033
+ let park = self.next_id();
1034
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1035
+ if self.is_closing() || state.idle_h1.len() >= MAX_IDLE_H1 {
1036
+ return;
1037
+ }
1038
+ let timer = self.config.idle_timeout.map(|timeout| {
1039
+ let closed = self.closed.clone();
1040
+ let entry = Arc::downgrade(&entry);
1041
+ IdleTimer(self.tracker.spawn(async move {
1042
+ tokio::select! {
1043
+ _ = tokio::time::sleep(timeout) => {}
1044
+ _ = closed.wait() => {}
1045
+ }
1046
+ // Claims this exact park; a connection checked out and parked
1047
+ // again has a new park id and its own timer.
1048
+ let Some(entry) = entry.upgrade() else { return };
1049
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1050
+ state.idle_h1.retain(|idle| idle.park != park);
1051
+ }))
1052
+ });
1053
+ state.idle_h1.push(IdleH1 {
1054
+ park,
1055
+ conn,
1056
+ _timer: timer,
1057
+ });
1058
+ }
1059
+
1060
+ /// Stops admission: later calls, dial waiters and lazy exchanges fail
1061
+ /// with the closed phrase. Idle connections close now.
1062
+ pub fn begin_close(&self) {
1063
+ self.closing.store(true, Ordering::SeqCst);
1064
+ self.closed.fire();
1065
+ let origins = self.origins.lock().unwrap_or_else(|e| e.into_inner());
1066
+ for entry in origins.values() {
1067
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1068
+ state.h2 = None;
1069
+ state.idle_h1.clear();
1070
+ }
1071
+ }
1072
+
1073
+ pub async fn wait_drained(&self) {
1074
+ loop {
1075
+ let drained = self.drained.notified();
1076
+ tokio::pin!(drained);
1077
+ drained.as_mut().enable();
1078
+ if self.inflight.load(Ordering::SeqCst) == 0 {
1079
+ return;
1080
+ }
1081
+ drained.await;
1082
+ }
1083
+ }
1084
+
1085
+ /// Starts teardown once: stops admission, lets in-flight calls finish
1086
+ /// within `grace`, then forces the rest and waits for every owned task.
1087
+ /// It is a runtime task outside the tracker, which `force` seals and waits
1088
+ /// for, so no closer's interruption ends it part way. Every call returns
1089
+ /// the signal that fires once the outcome is published.
1090
+ pub fn start_teardown(self: &Arc<Self>, grace: Duration) -> Arc<Signal> {
1091
+ if !self.teardown.swap(true, Ordering::SeqCst) {
1092
+ self.begin_close();
1093
+ let core = self.clone();
1094
+ runtime::handle().spawn(async move {
1095
+ let expires = tokio::time::Instant::now() + grace;
1096
+ let drained = tokio::time::timeout_at(expires, core.wait_drained())
1097
+ .await
1098
+ .is_ok();
1099
+ let quiet = drained
1100
+ && tokio::time::timeout_at(expires, core.tracker.wait_empty())
1101
+ .await
1102
+ .is_ok();
1103
+ core.force().await;
1104
+ core.outcome
1105
+ .store(if quiet { 2 } else { 1 }, Ordering::SeqCst);
1106
+ core.torn_down.fire();
1107
+ });
1108
+ }
1109
+ self.torn_down.clone()
1110
+ }
1111
+
1112
+ /// The published teardown result: true when everything drained within
1113
+ /// the grace, false after forced teardown, None before it ended.
1114
+ pub fn close_outcome(&self) -> Option<bool> {
1115
+ match self.outcome.load(Ordering::SeqCst) {
1116
+ 0 => None,
1117
+ outcome => Some(outcome == 2),
1118
+ }
1119
+ }
1120
+
1121
+ /// Ends every call's waits and every owned task, then waits for the
1122
+ /// tasks. Sealing first means a call mid-poll registers no task later.
1123
+ /// The order does not choose a call's phrase: a call already mid-poll
1124
+ /// sees a task's abort before `shutdown` in either order, so each site
1125
+ /// that observes one maps it to the shutdown or closed phrase itself.
1126
+ pub async fn force(&self) {
1127
+ self.tracker.seal();
1128
+ self.shutdown.fire();
1129
+ // Spec hold point: a spec armed with a zero bound observes the seal.
1130
+ self.holds.reach("force:sealed").await;
1131
+ self.tracker.wait_empty().await;
1132
+ }
1133
+ }
1134
+
1135
+ impl Drop for DriverCore {
1136
+ fn drop(&mut self) {
1137
+ // No call holds the driver any more; stop its owned tasks.
1138
+ self.closed.fire();
1139
+ self.tracker.abort_all();
1140
+ }
1141
+ }
1142
+
1143
+ /// Closes a pooled HTTP/2 connection after `timeout` without calls, claiming
1144
+ /// the checkout generation it observed idle so a racing checkout wins.
1145
+ async fn reap(
1146
+ entry: Weak<OriginEntry>,
1147
+ shared: Arc<ConnShared>,
1148
+ timeout: Duration,
1149
+ closed: Arc<Signal>,
1150
+ holds: Arc<Holds>,
1151
+ ) {
1152
+ loop {
1153
+ let generation = loop {
1154
+ let idle = shared.idle.notified();
1155
+ tokio::pin!(idle);
1156
+ idle.as_mut().enable();
1157
+ if shared.closed.fired() || closed.fired() {
1158
+ return;
1159
+ }
1160
+ let Some(origin) = entry.upgrade() else {
1161
+ return;
1162
+ };
1163
+ let observed = {
1164
+ // One snapshot under the lock checkouts count calls with, so
1165
+ // a checkout between the two reads cannot pass for idleness.
1166
+ let _state = origin.state.lock().unwrap_or_else(|e| e.into_inner());
1167
+ (shared.active.load(Ordering::Acquire) == 0).then(|| {
1168
+ holds.block("reap:idle");
1169
+ shared.generation.load(Ordering::Acquire)
1170
+ })
1171
+ };
1172
+ drop(origin);
1173
+ if let Some(generation) = observed {
1174
+ break generation;
1175
+ }
1176
+ tokio::select! {
1177
+ _ = idle => {}
1178
+ _ = shared.closed.wait() => return,
1179
+ _ = closed.wait() => return,
1180
+ }
1181
+ };
1182
+ tokio::select! {
1183
+ _ = tokio::time::sleep(timeout) => {}
1184
+ _ = shared.closed.wait() => return,
1185
+ _ = closed.wait() => return,
1186
+ }
1187
+ let Some(entry) = entry.upgrade() else { return };
1188
+ let mut state = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1189
+ let current = state
1190
+ .h2
1191
+ .as_ref()
1192
+ .is_some_and(|conn| conn.shared.id == shared.id);
1193
+ if !current {
1194
+ return;
1195
+ }
1196
+ if shared.active.load(Ordering::Acquire) == 0
1197
+ && shared.generation.load(Ordering::Acquire) == generation
1198
+ {
1199
+ // Dropping the pool's sender lets hyper close the connection.
1200
+ // Marked first, so a dial waiter yet to claim it redials.
1201
+ shared.reaped.store(true, Ordering::SeqCst);
1202
+ state.h2 = None;
1203
+ return;
1204
+ }
1205
+ }
1206
+ }