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,659 @@
|
|
|
1
|
+
//! One streaming exchange. Opening waits for nothing: the first `write` or
|
|
2
|
+
//! `response_head` connects and dispatches. The send and receive halves are
|
|
3
|
+
//! independent (core allows one reader and one writer at once), each taken
|
|
4
|
+
//! out of its lock for the duration of an operation. `abort` fires a signal
|
|
5
|
+
//! that every wait and the request body observe, so it wins over busy
|
|
6
|
+
//! operations instead of waiting for them.
|
|
7
|
+
use std::future::Future;
|
|
8
|
+
use std::pin::{Pin, pin};
|
|
9
|
+
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
|
10
|
+
use std::sync::{Arc, Mutex};
|
|
11
|
+
use std::task::Poll;
|
|
12
|
+
use std::time::Instant;
|
|
13
|
+
|
|
14
|
+
use bytes::Bytes;
|
|
15
|
+
use http_body_util::BodyExt;
|
|
16
|
+
use hyper::body::Incoming;
|
|
17
|
+
use hyper::client::conn::TrySendError;
|
|
18
|
+
use tokio::sync::{mpsc, oneshot};
|
|
19
|
+
|
|
20
|
+
use crate::body::CallBody;
|
|
21
|
+
use crate::failure::{Failure, TlsFault};
|
|
22
|
+
use crate::gvl::Signal;
|
|
23
|
+
use crate::holds::Holds;
|
|
24
|
+
use crate::pool::{DriverCore, Inflight, Lease, RequestSpec};
|
|
25
|
+
use crate::wire::Mark;
|
|
26
|
+
|
|
27
|
+
/// Why a request got no response head.
|
|
28
|
+
pub enum Unanswered<E> {
|
|
29
|
+
/// hyper's failure, which carries the request if hyper handed it back.
|
|
30
|
+
Failed(E),
|
|
31
|
+
/// The connection's dispatcher ended without ever taking the request.
|
|
32
|
+
Stranded,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Response = hyper::Response<Incoming>;
|
|
36
|
+
type HyperError = TrySendError<hyper::Request<CallBody>>;
|
|
37
|
+
type Promise = Pin<Box<dyn Future<Output = Result<Response, HyperError>> + Send>>;
|
|
38
|
+
pub type Sent = Pin<Box<dyn Future<Output = Result<Response, Unanswered<HyperError>>> + Send>>;
|
|
39
|
+
|
|
40
|
+
/// Enqueues the request on the leased connection now; the returned future
|
|
41
|
+
/// resolves with the response head, hands back an unsent request, or reports
|
|
42
|
+
/// it stranded. On HTTP/2 the mark learns the request's stream id (see
|
|
43
|
+
/// wire.rs).
|
|
44
|
+
///
|
|
45
|
+
/// Stranded: tokio's unbounded `send` checks that the channel is open, then
|
|
46
|
+
/// pushes, while the receiver's drop closes the channel, then drains what it
|
|
47
|
+
/// can read (tokio-rs/tokio#7714). A request pushed between the two is
|
|
48
|
+
/// neither drained nor ever received, and its envelope, whose drop would
|
|
49
|
+
/// answer the caller, lives until the connection's last sender drops: the
|
|
50
|
+
/// lease, the pool and sibling leases hold those. Since hyper 1.13.0
|
|
51
|
+
/// (hyperium/hyper#4222, #4242) a dispatcher that shuts down closes its
|
|
52
|
+
/// channel and waits for such a push before its future completes, so this
|
|
53
|
+
/// guards a future dropped unfinished (an aborted task), an HTTP/1.1 upgrade,
|
|
54
|
+
/// which completes without that drain, and any other path to that race. The
|
|
55
|
+
/// answer races the connection's `closed` signal, which fires only after
|
|
56
|
+
/// hyper's dispatcher was dropped and so answered every request it held (see
|
|
57
|
+
/// `conn::Dispatcher`).
|
|
58
|
+
pub fn send(
|
|
59
|
+
lease: &mut Lease,
|
|
60
|
+
request: hyper::Request<CallBody>,
|
|
61
|
+
holds: &Holds,
|
|
62
|
+
) -> (Sent, Option<Arc<Mark>>) {
|
|
63
|
+
if request.method() == http::Method::CONNECT {
|
|
64
|
+
// hyper may drop a CONNECT request after taking its index.
|
|
65
|
+
lease.disable_wire();
|
|
66
|
+
}
|
|
67
|
+
let mark = lease.mark();
|
|
68
|
+
let closed = lease
|
|
69
|
+
.closed()
|
|
70
|
+
.expect("a lease holds its connection")
|
|
71
|
+
.clone();
|
|
72
|
+
let http1 = !lease.is_h2();
|
|
73
|
+
// Spec hold point: armed, it counts the request and keeps it, body
|
|
74
|
+
// included, until the point is released, never handing it to hyper, as a
|
|
75
|
+
// stranded envelope stays in the channel while a sender lives. The kept
|
|
76
|
+
// request carries no mark: nothing indexes it, and a mark would tie the
|
|
77
|
+
// driver's holds to themselves (mark, wire, holds) if the driver were
|
|
78
|
+
// dropped while the point is armed.
|
|
79
|
+
let promise: Promise = match holds.keep("request:strand", request) {
|
|
80
|
+
None => Box::pin(std::future::pending()),
|
|
81
|
+
Some(mut request) => {
|
|
82
|
+
request.body_mut().set_mark(mark.clone());
|
|
83
|
+
match lease {
|
|
84
|
+
Lease::H2 { sender, .. } => Box::pin(sender.try_send_request(request)),
|
|
85
|
+
Lease::H1 { conn, .. } => {
|
|
86
|
+
let conn = conn.as_mut().expect("HTTP/1.1 lease holds its connection");
|
|
87
|
+
Box::pin(conn.sender.try_send_request(request))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
let taken = mark.clone();
|
|
93
|
+
// hyper's HTTP/1.1 dispatcher answers every request it took when it is
|
|
94
|
+
// dropped. hyper's HTTP/2 dispatcher indexes each request it takes before
|
|
95
|
+
// passing it to h2 (wire.rs), and an indexed request belongs to h2 and its
|
|
96
|
+
// response task, which may still answer it (a graceful GOAWAY drains).
|
|
97
|
+
let stranded = move || http1 || !taken.as_ref().is_some_and(|mark| mark.indexed());
|
|
98
|
+
(Box::pin(answered(promise, closed, stranded)), mark)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// `promise`'s answer, or `Stranded` when `closed` has fired, `promise` is
|
|
102
|
+
/// still pending and `stranded` says nobody else can answer it.
|
|
103
|
+
async fn answered<T, E>(
|
|
104
|
+
promise: impl Future<Output = Result<T, E>>,
|
|
105
|
+
closed: Arc<Signal>,
|
|
106
|
+
stranded: impl FnOnce() -> bool,
|
|
107
|
+
) -> Result<T, Unanswered<E>> {
|
|
108
|
+
let mut promise = pin!(promise);
|
|
109
|
+
tokio::select! {
|
|
110
|
+
biased;
|
|
111
|
+
answer = promise.as_mut() => return answer.map_err(Unanswered::Failed),
|
|
112
|
+
() = closed.wait() => {}
|
|
113
|
+
}
|
|
114
|
+
// The dispatcher answered every request it held before `closed` fired
|
|
115
|
+
// (SeqCst), so such an answer is ready now. Polled again because the first
|
|
116
|
+
// poll may have come before it, and unconstrained because tokio's oneshot
|
|
117
|
+
// checks the task's cooperative budget before its state: an exhausted
|
|
118
|
+
// budget must not read as pending.
|
|
119
|
+
let again = tokio::task::unconstrained(std::future::poll_fn(|cx| {
|
|
120
|
+
Poll::Ready(promise.as_mut().poll(cx))
|
|
121
|
+
}))
|
|
122
|
+
.await;
|
|
123
|
+
if let Poll::Ready(answer) = again {
|
|
124
|
+
return answer.map_err(Unanswered::Failed);
|
|
125
|
+
}
|
|
126
|
+
if stranded() {
|
|
127
|
+
return Err(Unanswered::Stranded);
|
|
128
|
+
}
|
|
129
|
+
promise.await.map_err(Unanswered::Failed)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
type Delivered = Result<(hyper::Response<Incoming>, Lease), Failure>;
|
|
133
|
+
|
|
134
|
+
enum Dispatch {
|
|
135
|
+
Pending,
|
|
136
|
+
Dispatched(Option<oneshot::Receiver<Delivered>>),
|
|
137
|
+
Failed(Failure),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
pub struct Head {
|
|
141
|
+
pub status: u16,
|
|
142
|
+
pub headers: http::HeaderMap,
|
|
143
|
+
pub end_stream: bool,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#[derive(Default)]
|
|
147
|
+
pub struct RecvHalf {
|
|
148
|
+
pending: Option<oneshot::Receiver<Delivered>>,
|
|
149
|
+
pub head: Option<Head>,
|
|
150
|
+
body: Option<Incoming>,
|
|
151
|
+
buffer: Bytes,
|
|
152
|
+
pub trailers: Option<http::HeaderMap>,
|
|
153
|
+
done: bool,
|
|
154
|
+
/// The response's connection's TLS failure record, for body errors.
|
|
155
|
+
fault: Arc<TlsFault>,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
pub struct SendHalf {
|
|
159
|
+
tx: Option<mpsc::Sender<Bytes>>,
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
pub struct CallState {
|
|
163
|
+
core: Arc<DriverCore>,
|
|
164
|
+
spec: Arc<RequestSpec>,
|
|
165
|
+
require_h2: bool,
|
|
166
|
+
pub deadline: Option<Instant>,
|
|
167
|
+
pub cancel: Arc<Signal>,
|
|
168
|
+
pub abort: Arc<Signal>,
|
|
169
|
+
/// Fires when the request was stranded: its body, which owns the upload
|
|
170
|
+
/// channel's receiver, may stay alive, so a blocked `write` returns.
|
|
171
|
+
stranded: Arc<Signal>,
|
|
172
|
+
aborted: AtomicBool,
|
|
173
|
+
finished: AtomicBool,
|
|
174
|
+
failed: AtomicBool,
|
|
175
|
+
ended: Arc<AtomicBool>,
|
|
176
|
+
body: Mutex<Option<mpsc::Receiver<Bytes>>>,
|
|
177
|
+
dispatch: tokio::sync::Mutex<Dispatch>,
|
|
178
|
+
pub send: Mutex<Option<SendHalf>>,
|
|
179
|
+
pub recv: Mutex<Option<RecvHalf>>,
|
|
180
|
+
lease: Mutex<Option<Lease>>,
|
|
181
|
+
inflight: Mutex<Option<Inflight>>,
|
|
182
|
+
local_port: AtomicU16,
|
|
183
|
+
h2: AtomicBool,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
impl CallState {
|
|
187
|
+
pub fn new(
|
|
188
|
+
core: Arc<DriverCore>,
|
|
189
|
+
spec: RequestSpec,
|
|
190
|
+
require_h2: bool,
|
|
191
|
+
deadline: Option<Instant>,
|
|
192
|
+
cancel: Arc<Signal>,
|
|
193
|
+
inflight: Inflight,
|
|
194
|
+
) -> Arc<Self> {
|
|
195
|
+
let (tx, rx) = mpsc::channel(1);
|
|
196
|
+
Arc::new(Self {
|
|
197
|
+
core,
|
|
198
|
+
spec: Arc::new(spec),
|
|
199
|
+
require_h2,
|
|
200
|
+
deadline,
|
|
201
|
+
cancel,
|
|
202
|
+
abort: Signal::new(),
|
|
203
|
+
stranded: Signal::new(),
|
|
204
|
+
aborted: AtomicBool::new(false),
|
|
205
|
+
finished: AtomicBool::new(false),
|
|
206
|
+
failed: AtomicBool::new(false),
|
|
207
|
+
ended: Arc::new(AtomicBool::new(false)),
|
|
208
|
+
body: Mutex::new(Some(rx)),
|
|
209
|
+
dispatch: tokio::sync::Mutex::new(Dispatch::Pending),
|
|
210
|
+
send: Mutex::new(Some(SendHalf { tx: Some(tx) })),
|
|
211
|
+
recv: Mutex::new(Some(RecvHalf::default())),
|
|
212
|
+
lease: Mutex::new(None),
|
|
213
|
+
inflight: Mutex::new(Some(inflight)),
|
|
214
|
+
local_port: AtomicU16::new(0),
|
|
215
|
+
h2: AtomicBool::new(false),
|
|
216
|
+
})
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
pub fn shutdown(&self) -> &Arc<Signal> {
|
|
220
|
+
&self.core.shutdown
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
pub fn local_port(&self) -> u16 {
|
|
224
|
+
self.local_port.load(Ordering::SeqCst)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
pub fn is_h2(&self) -> bool {
|
|
228
|
+
self.h2.load(Ordering::SeqCst)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
pub fn is_finished(&self) -> bool {
|
|
232
|
+
self.finished.load(Ordering::SeqCst) || self.aborted.load(Ordering::SeqCst)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// Returns a half after an operation, unless the call was aborted
|
|
236
|
+
/// meanwhile; then the half is dropped here instead.
|
|
237
|
+
pub fn restore<T>(&self, slot: &Mutex<Option<T>>, half: T) {
|
|
238
|
+
let mut guard = slot.lock().unwrap_or_else(|e| e.into_inner());
|
|
239
|
+
if !self.aborted.load(Ordering::SeqCst) {
|
|
240
|
+
*guard = Some(half);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
pub fn mark_failed(&self) {
|
|
245
|
+
self.failed.store(true, Ordering::SeqCst);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async fn dispatch(self: &Arc<Self>) -> Result<(), Failure> {
|
|
249
|
+
let mut state = self.dispatch.lock().await;
|
|
250
|
+
match &*state {
|
|
251
|
+
Dispatch::Pending => {}
|
|
252
|
+
Dispatch::Dispatched(_) => return Ok(()),
|
|
253
|
+
Dispatch::Failed(failure) => return Err(failure.clone()),
|
|
254
|
+
}
|
|
255
|
+
let mut lease = match self
|
|
256
|
+
.core
|
|
257
|
+
.acquire(&self.spec.origin, self.require_h2, None, self.deadline)
|
|
258
|
+
.await
|
|
259
|
+
{
|
|
260
|
+
Ok(lease) => lease,
|
|
261
|
+
Err(failure) => {
|
|
262
|
+
*state = Dispatch::Failed(failure.clone());
|
|
263
|
+
return Err(failure);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
if self.aborted.load(Ordering::SeqCst) {
|
|
267
|
+
return Err(Failure::new("aborted", "exchange aborted"));
|
|
268
|
+
}
|
|
269
|
+
// From here to the end nothing awaits: the request is queued exactly
|
|
270
|
+
// once, even if this operation is woken and resumed.
|
|
271
|
+
let rx = self
|
|
272
|
+
.body
|
|
273
|
+
.lock()
|
|
274
|
+
.unwrap_or_else(|e| e.into_inner())
|
|
275
|
+
.take()
|
|
276
|
+
.expect("request body is dispatched once");
|
|
277
|
+
let (home, homed) = oneshot::channel();
|
|
278
|
+
let body = CallBody::stream(rx, self.ended.clone(), self.abort.clone(), home);
|
|
279
|
+
let request = match self.spec.build(body, self.deadline, lease.is_h2()) {
|
|
280
|
+
Ok(request) => request,
|
|
281
|
+
Err(failure) => {
|
|
282
|
+
*state = Dispatch::Failed(failure.clone());
|
|
283
|
+
return Err(failure);
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
self.local_port.store(lease.local_port(), Ordering::SeqCst);
|
|
287
|
+
self.h2.store(lease.is_h2(), Ordering::SeqCst);
|
|
288
|
+
let (sent, mark) = send(&mut lease, request, &self.core.holds);
|
|
289
|
+
// Spec hold point: armed with a zero bound, it counts the requests
|
|
290
|
+
// handed to hyper. `block` keeps this section free of awaits.
|
|
291
|
+
self.core.holds.block("request:queued");
|
|
292
|
+
let (deliver, delivered) = oneshot::channel();
|
|
293
|
+
self.core.tracker.spawn(respond(
|
|
294
|
+
self.core.clone(),
|
|
295
|
+
self.spec.clone(),
|
|
296
|
+
Attempt {
|
|
297
|
+
require_h2: self.require_h2,
|
|
298
|
+
deadline: self.deadline,
|
|
299
|
+
ended: self.ended.clone(),
|
|
300
|
+
lease,
|
|
301
|
+
sent,
|
|
302
|
+
mark,
|
|
303
|
+
homed,
|
|
304
|
+
},
|
|
305
|
+
self.abort.clone(),
|
|
306
|
+
self.cancel.clone(),
|
|
307
|
+
self.stranded.clone(),
|
|
308
|
+
deliver,
|
|
309
|
+
));
|
|
310
|
+
*state = Dispatch::Dispatched(Some(delivered));
|
|
311
|
+
Ok(())
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
pub async fn head(self: &Arc<Self>, recv: &mut RecvHalf) -> Result<(), Failure> {
|
|
315
|
+
if recv.head.is_some() {
|
|
316
|
+
return Ok(());
|
|
317
|
+
}
|
|
318
|
+
if recv.pending.is_none() {
|
|
319
|
+
self.dispatch().await?;
|
|
320
|
+
let mut state = self.dispatch.lock().await;
|
|
321
|
+
if let Dispatch::Dispatched(delivered) = &mut *state {
|
|
322
|
+
recv.pending = delivered.take();
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
let pending = recv
|
|
326
|
+
.pending
|
|
327
|
+
.as_mut()
|
|
328
|
+
.ok_or_else(|| Failure::new("state", "response head already taken"))?;
|
|
329
|
+
let delivered = pending.await;
|
|
330
|
+
recv.pending = None;
|
|
331
|
+
// `respond` ends without delivering only on this call's abort, or
|
|
332
|
+
// when forced teardown aborted it or a sealed tracker refused it.
|
|
333
|
+
let (response, lease) = delivered.map_err(|_| {
|
|
334
|
+
if self.abort.fired() {
|
|
335
|
+
Failure::new("aborted", "exchange aborted")
|
|
336
|
+
} else {
|
|
337
|
+
Failure::shutdown()
|
|
338
|
+
}
|
|
339
|
+
})??;
|
|
340
|
+
{
|
|
341
|
+
// abort sets `aborted` before it takes the lease, so checking under
|
|
342
|
+
// the lease lock means an abort that already ran drops the lease
|
|
343
|
+
// here instead of leaving it held until the call is collected.
|
|
344
|
+
let mut slot = self.lease.lock().unwrap_or_else(|e| e.into_inner());
|
|
345
|
+
if self.aborted.load(Ordering::SeqCst) {
|
|
346
|
+
drop(lease);
|
|
347
|
+
return Err(Failure::new("aborted", "exchange aborted"));
|
|
348
|
+
}
|
|
349
|
+
if let Some(fault) = lease.fault() {
|
|
350
|
+
recv.fault = fault.clone();
|
|
351
|
+
}
|
|
352
|
+
*slot = Some(lease);
|
|
353
|
+
}
|
|
354
|
+
let (parts, body) = response.into_parts();
|
|
355
|
+
// HEADERS carried END_STREAM: a gRPC trailers-only response. h2 keeps
|
|
356
|
+
// trailers that arrived right behind the head in its queue, so this is
|
|
357
|
+
// false when the status came in a separate trailing HEADERS frame.
|
|
358
|
+
let end_stream = http_body::Body::is_end_stream(&body);
|
|
359
|
+
recv.done = end_stream;
|
|
360
|
+
recv.head = Some(Head {
|
|
361
|
+
status: parts.status.as_u16(),
|
|
362
|
+
headers: parts.headers,
|
|
363
|
+
end_stream,
|
|
364
|
+
});
|
|
365
|
+
recv.body = Some(body);
|
|
366
|
+
Ok(())
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
pub async fn read(
|
|
370
|
+
self: &Arc<Self>,
|
|
371
|
+
recv: &mut RecvHalf,
|
|
372
|
+
max: usize,
|
|
373
|
+
) -> Result<Option<Bytes>, Failure> {
|
|
374
|
+
self.head(recv).await?;
|
|
375
|
+
loop {
|
|
376
|
+
if !recv.buffer.is_empty() {
|
|
377
|
+
let take = max.max(1).min(recv.buffer.len());
|
|
378
|
+
return Ok(Some(recv.buffer.split_to(take)));
|
|
379
|
+
}
|
|
380
|
+
if recv.done {
|
|
381
|
+
return Ok(None);
|
|
382
|
+
}
|
|
383
|
+
let body = recv.body.as_mut().expect("body after head");
|
|
384
|
+
match body.frame().await {
|
|
385
|
+
None => recv.done = true,
|
|
386
|
+
Some(Ok(frame)) => match frame.into_data() {
|
|
387
|
+
Ok(data) => recv.buffer = data,
|
|
388
|
+
Err(frame) => {
|
|
389
|
+
if let Ok(trailers) = frame.into_trailers() {
|
|
390
|
+
recv.trailers = Some(trailers);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
Some(Err(error)) => return Err(recv.fault.failure(&error)),
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/// Queues `bytes` once, then returns when hyper has pulled them, which it
|
|
400
|
+
/// does only while the stream has send window: a peer that does not read
|
|
401
|
+
/// blocks the writer.
|
|
402
|
+
pub async fn write(self: &Arc<Self>, send: &mut SendHalf, bytes: Bytes) -> Result<(), Failure> {
|
|
403
|
+
self.dispatch().await?;
|
|
404
|
+
let Some(tx) = send.tx.as_ref() else {
|
|
405
|
+
return Err(Failure::new("state", "request body already closed"));
|
|
406
|
+
};
|
|
407
|
+
// A closed channel means hyper dropped the request body: the stream
|
|
408
|
+
// ended or was reset, and the response side reports why. So does a
|
|
409
|
+
// stranded request, whose body may never be dropped or read.
|
|
410
|
+
let reserved = tokio::select! {
|
|
411
|
+
reserved = tx.reserve() => reserved,
|
|
412
|
+
() = self.stranded.wait() => return Ok(()),
|
|
413
|
+
};
|
|
414
|
+
match reserved {
|
|
415
|
+
Ok(permit) => permit.send(bytes),
|
|
416
|
+
Err(_) => return Ok(()),
|
|
417
|
+
}
|
|
418
|
+
tokio::select! {
|
|
419
|
+
_ = tx.reserve() => {}
|
|
420
|
+
() = self.stranded.wait() => {}
|
|
421
|
+
}
|
|
422
|
+
Ok(())
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
pub fn close_send(&self) {
|
|
426
|
+
if let Some(half) = self.send.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
|
427
|
+
half.tx = None;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
pub async fn drain(self: &Arc<Self>, recv: &mut RecvHalf) -> Result<(), Failure> {
|
|
432
|
+
while self.read(recv, 64 * 1024).await?.is_some() {}
|
|
433
|
+
Ok(())
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/// After a clean drain: an HTTP/1.1 socket returns to the pool only when
|
|
437
|
+
/// the request body also ended cleanly.
|
|
438
|
+
pub fn complete(&self) {
|
|
439
|
+
if self.finished.swap(true, Ordering::SeqCst) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
let lease = self.lease.lock().unwrap_or_else(|e| e.into_inner()).take();
|
|
443
|
+
if let Some(mut lease) = lease {
|
|
444
|
+
if self.ended.load(Ordering::SeqCst) && !self.failed.load(Ordering::SeqCst) {
|
|
445
|
+
self.core.release_h1(&mut lease);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
drop(self.send.lock().unwrap_or_else(|e| e.into_inner()).take());
|
|
449
|
+
// The head and trailers stay readable; the h2 stream handle goes, so
|
|
450
|
+
// nothing holds the connection open after the call.
|
|
451
|
+
if let Some(recv) = self.recv.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
|
452
|
+
recv.body = None;
|
|
453
|
+
recv.pending = None;
|
|
454
|
+
}
|
|
455
|
+
drop(
|
|
456
|
+
self.inflight
|
|
457
|
+
.lock()
|
|
458
|
+
.unwrap_or_else(|e| e.into_inner())
|
|
459
|
+
.take(),
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/// Drops the stream: RST_STREAM(CANCEL) on HTTP/2, a closed socket on
|
|
464
|
+
/// HTTP/1.1. Never waits, so it is safe in a masked ensure.
|
|
465
|
+
pub fn abort(&self) {
|
|
466
|
+
if self.finished.load(Ordering::SeqCst) || self.aborted.swap(true, Ordering::SeqCst) {
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
// Signal first: the request body then fails with CANCEL instead of
|
|
470
|
+
// ending cleanly when its sender drops below.
|
|
471
|
+
self.abort.fire();
|
|
472
|
+
drop(self.send.lock().unwrap_or_else(|e| e.into_inner()).take());
|
|
473
|
+
drop(self.recv.lock().unwrap_or_else(|e| e.into_inner()).take());
|
|
474
|
+
drop(self.lease.lock().unwrap_or_else(|e| e.into_inner()).take());
|
|
475
|
+
drop(
|
|
476
|
+
self.inflight
|
|
477
|
+
.lock()
|
|
478
|
+
.unwrap_or_else(|e| e.into_inner())
|
|
479
|
+
.take(),
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/// The first dispatch of a streaming call, as `respond` retries it.
|
|
485
|
+
struct Attempt {
|
|
486
|
+
require_h2: bool,
|
|
487
|
+
deadline: Option<Instant>,
|
|
488
|
+
ended: Arc<AtomicBool>,
|
|
489
|
+
lease: Lease,
|
|
490
|
+
sent: Sent,
|
|
491
|
+
mark: Option<Arc<Mark>>,
|
|
492
|
+
/// The request body's receiver, back if hyper dropped the body unread.
|
|
493
|
+
homed: oneshot::Receiver<mpsc::Receiver<Bytes>>,
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/// Owns the response future so an unsent request can be retried once on a
|
|
497
|
+
/// fresh connection even while the caller is blocked in a write: one hyper
|
|
498
|
+
/// handed back, or one the peer's GOAWAY says it never processed whose
|
|
499
|
+
/// HEADERS never reached the socket and whose body yielded nothing. A
|
|
500
|
+
/// stranded request (see `send`) fails with its connection's failure: its
|
|
501
|
+
/// body cannot be recovered, and `stranded` releases a blocked writer.
|
|
502
|
+
async fn respond(
|
|
503
|
+
core: Arc<DriverCore>,
|
|
504
|
+
spec: Arc<RequestSpec>,
|
|
505
|
+
attempt: Attempt,
|
|
506
|
+
abort: Arc<Signal>,
|
|
507
|
+
cancel: Arc<Signal>,
|
|
508
|
+
stranded: Arc<Signal>,
|
|
509
|
+
deliver: oneshot::Sender<Delivered>,
|
|
510
|
+
) {
|
|
511
|
+
let Attempt {
|
|
512
|
+
require_h2,
|
|
513
|
+
deadline,
|
|
514
|
+
ended,
|
|
515
|
+
lease,
|
|
516
|
+
sent,
|
|
517
|
+
mark,
|
|
518
|
+
homed,
|
|
519
|
+
} = attempt;
|
|
520
|
+
let strand = |lease: &Lease| {
|
|
521
|
+
stranded.fire();
|
|
522
|
+
lease.closed_failure()
|
|
523
|
+
};
|
|
524
|
+
let work = async {
|
|
525
|
+
let mut error = match sent.await {
|
|
526
|
+
Ok(response) => return Ok((response, lease)),
|
|
527
|
+
Err(Unanswered::Failed(error)) => error,
|
|
528
|
+
Err(Unanswered::Stranded) => return Err(strand(&lease)),
|
|
529
|
+
};
|
|
530
|
+
// A call canceled before its replacement is queued never sends it.
|
|
531
|
+
let retry = async {
|
|
532
|
+
let body = match error.take_message() {
|
|
533
|
+
// Handed back unsent: the peer never saw it. Spec hold point:
|
|
534
|
+
// it parks, or with a zero bound counts, these retries.
|
|
535
|
+
Some(request) => {
|
|
536
|
+
core.holds.reach("retry:unsent").await;
|
|
537
|
+
request.into_body()
|
|
538
|
+
}
|
|
539
|
+
None => {
|
|
540
|
+
let failure = lease.failure(error.error());
|
|
541
|
+
let unsent = mark.as_ref().is_some_and(|mark| mark.unsent());
|
|
542
|
+
// hyper drops the body around the failure it reports; a
|
|
543
|
+
// body that yielded a frame never comes back.
|
|
544
|
+
let rx = match unsent {
|
|
545
|
+
true => until(deadline, homed).await.and_then(Result::ok),
|
|
546
|
+
false => None,
|
|
547
|
+
};
|
|
548
|
+
let Some(rx) = rx else {
|
|
549
|
+
return Err(failure);
|
|
550
|
+
};
|
|
551
|
+
// Spec hold point: it parks, or with a zero bound counts,
|
|
552
|
+
// these retries.
|
|
553
|
+
core.holds.reach("retry:unprocessed").await;
|
|
554
|
+
// Retried at most once: this body has no receiver to return.
|
|
555
|
+
CallBody::stream(rx, ended, abort.clone(), oneshot::channel().0)
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
let exclude = lease.id();
|
|
559
|
+
drop(lease);
|
|
560
|
+
let mut lease = core
|
|
561
|
+
.acquire(&spec.origin, require_h2, Some(exclude), deadline)
|
|
562
|
+
.await?;
|
|
563
|
+
let request = spec.build(body, deadline, lease.is_h2())?;
|
|
564
|
+
let (sent, _) = send(&mut lease, request, &core.holds);
|
|
565
|
+
Ok((lease, sent))
|
|
566
|
+
};
|
|
567
|
+
let (lease, sent) = tokio::select! {
|
|
568
|
+
biased;
|
|
569
|
+
_ = cancel.wait() => return Err(Failure::new("canceled", "call canceled")),
|
|
570
|
+
retried = retry => retried?,
|
|
571
|
+
};
|
|
572
|
+
match sent.await {
|
|
573
|
+
Ok(response) => Ok((response, lease)),
|
|
574
|
+
Err(Unanswered::Failed(error)) => Err(lease.failure(error.error())),
|
|
575
|
+
Err(Unanswered::Stranded) => Err(strand(&lease)),
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
let delivered = tokio::select! {
|
|
579
|
+
result = work => result,
|
|
580
|
+
_ = abort.wait() => return,
|
|
581
|
+
_ = core.shutdown.wait() => Err(Failure::shutdown()),
|
|
582
|
+
};
|
|
583
|
+
let _ = deliver.send(delivered);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/// `future`'s output, or None once `deadline` passes.
|
|
587
|
+
async fn until<F: Future>(deadline: Option<Instant>, future: F) -> Option<F::Output> {
|
|
588
|
+
match deadline {
|
|
589
|
+
Some(deadline) => tokio::time::timeout_at(deadline.into(), future).await.ok(),
|
|
590
|
+
None => Some(future.await),
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
#[cfg(test)]
|
|
595
|
+
mod tests {
|
|
596
|
+
use super::*;
|
|
597
|
+
|
|
598
|
+
/// Pending at its first poll, which spends the task's whole cooperative
|
|
599
|
+
/// budget; then a tokio oneshot that already holds its value, which
|
|
600
|
+
/// checks the budget before its state, as hyper's promise does.
|
|
601
|
+
struct Exhausting {
|
|
602
|
+
first: bool,
|
|
603
|
+
rx: oneshot::Receiver<u8>,
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
impl Future for Exhausting {
|
|
607
|
+
type Output = Result<u8, ()>;
|
|
608
|
+
|
|
609
|
+
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
|
|
610
|
+
if std::mem::take(&mut self.first) {
|
|
611
|
+
while pin!(tokio::task::consume_budget()).poll(cx).is_ready() {}
|
|
612
|
+
return Poll::Pending;
|
|
613
|
+
}
|
|
614
|
+
Pin::new(&mut self.rx)
|
|
615
|
+
.poll(cx)
|
|
616
|
+
.map(|answer| answer.map_err(|_| ()))
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
fn fired() -> Arc<Signal> {
|
|
621
|
+
let signal = Signal::new();
|
|
622
|
+
signal.fire();
|
|
623
|
+
signal
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
#[test]
|
|
627
|
+
fn an_answer_ready_when_closed_fires_wins_under_an_exhausted_budget() {
|
|
628
|
+
let runtime = tokio::runtime::Builder::new_current_thread()
|
|
629
|
+
.build()
|
|
630
|
+
.expect("runtime");
|
|
631
|
+
let (tx, rx) = oneshot::channel();
|
|
632
|
+
tx.send(7).expect("receiver open");
|
|
633
|
+
let promise = Exhausting { first: true, rx };
|
|
634
|
+
let answer = runtime.block_on(answered(promise, fired(), || true));
|
|
635
|
+
assert!(matches!(answer, Ok(7)));
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
#[test]
|
|
639
|
+
fn a_pending_answer_is_stranded_only_when_nobody_else_can_answer() {
|
|
640
|
+
let runtime = tokio::runtime::Builder::new_current_thread()
|
|
641
|
+
.build()
|
|
642
|
+
.expect("runtime");
|
|
643
|
+
let stranded = runtime.block_on(answered(
|
|
644
|
+
std::future::pending::<Result<u8, ()>>(),
|
|
645
|
+
fired(),
|
|
646
|
+
|| true,
|
|
647
|
+
));
|
|
648
|
+
assert!(matches!(stranded, Err(Unanswered::Stranded)));
|
|
649
|
+
let (tx, rx) = oneshot::channel();
|
|
650
|
+
let answer = answered(async { rx.await.map_err(|_| ()) }, fired(), || false);
|
|
651
|
+
let mut answer = pin!(answer);
|
|
652
|
+
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
|
653
|
+
runtime.block_on(async {
|
|
654
|
+
assert!(answer.as_mut().poll(&mut cx).is_pending());
|
|
655
|
+
tx.send(9).expect("receiver open");
|
|
656
|
+
assert!(matches!(answer.as_mut().poll(&mut cx), Poll::Ready(Ok(9))));
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
}
|