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,513 @@
|
|
|
1
|
+
//! What one HTTP/2 connection's frames say about its streams, for the GOAWAY
|
|
2
|
+
//! retry (plan D12). h2 exposes neither a GOAWAY's last stream id nor, through
|
|
3
|
+
//! hyper, a request's stream id, so the transport observes both itself:
|
|
4
|
+
//!
|
|
5
|
+
//! - `Tap` sits between hyper and the socket (above TLS, so it sees plaintext
|
|
6
|
+
//! frames) and reads only the 9-byte frame headers and a GOAWAY's last
|
|
7
|
+
//! stream id. It records the lowest last stream id the peer's GOAWAYs name
|
|
8
|
+
//! and the highest client stream id whose HEADERS frame header h2 offered
|
|
9
|
+
//! to the socket, written or not. h2 0.4.20's `FramedWrite` encodes frames
|
|
10
|
+
//! into one buffer and offers all of it (DATA payloads aside) on each write
|
|
11
|
+
//! attempt, which follows every encode in the same poll, so a HEADERS frame
|
|
12
|
+
//! is offered before it can be written.
|
|
13
|
+
//! - A request body's first `size_hint` call takes the connection's next
|
|
14
|
+
//! stream index. In hyper 1.13.0 (`proto/h2/client.rs`,
|
|
15
|
+
//! `ClientTask::poll_dispatch`) the dispatch task pops requests in order,
|
|
16
|
+
//! skips one whose caller has gone, then calls `size_hint` exactly once
|
|
17
|
+
//! and, in the same synchronous poll, h2's `send_request`. That consumes
|
|
18
|
+
//! the next client stream id (1, 3, 5, ...) unless the connection already
|
|
19
|
+
//! failed, and that failure is permanent, so no later request gets an id
|
|
20
|
+
//! either. Index n is therefore stream 2n + 1. h2 can also skip an id
|
|
21
|
+
//! while resetting a stream the peer should not have opened; that only
|
|
22
|
+
//! makes an index lower than its stream, which never authorises a replay.
|
|
23
|
+
//! A CONNECT request may be dropped after `size_hint` without an id, so
|
|
24
|
+
//! one disables the record for its connection.
|
|
25
|
+
//!
|
|
26
|
+
//! A stream above a GOAWAY's last stream id was never processed (RFC 9113
|
|
27
|
+
//! 6.8): the peer's GOAWAY is the authority on that, as its REFUSED_STREAM
|
|
28
|
+
//! is. The tap follows frame lengths as h2 does, so each GOAWAY it reads is
|
|
29
|
+
//! one the peer sent, whatever h2 makes of the frames around it; it does not
|
|
30
|
+
//! repeat h2's validation. A peer that lies about what it processed can make
|
|
31
|
+
//! any client replay a request. A sent request is also replayed only when h2
|
|
32
|
+
//! itself failed its stream for a GOAWAY; any other replay needs proof that
|
|
33
|
+
//! the request's HEADERS never reached the socket. Anything the record cannot
|
|
34
|
+
//! vouch for answers "no".
|
|
35
|
+
//!
|
|
36
|
+
//! The tap also records that the server started HTTP/2 (its first non-ACK
|
|
37
|
+
//! SETTINGS frame, RFC 9113 3.4), for the pool dial's waiters (pool.rs).
|
|
38
|
+
use std::io;
|
|
39
|
+
use std::pin::Pin;
|
|
40
|
+
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
|
41
|
+
use std::sync::{Arc, OnceLock};
|
|
42
|
+
use std::task::{Context, Poll};
|
|
43
|
+
|
|
44
|
+
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
|
45
|
+
|
|
46
|
+
use crate::holds::Holds;
|
|
47
|
+
|
|
48
|
+
const PREFACE: usize = 24;
|
|
49
|
+
const HEAD: usize = 9;
|
|
50
|
+
const NONE: u32 = u32::MAX;
|
|
51
|
+
|
|
52
|
+
const HEADERS: u8 = 0x1;
|
|
53
|
+
const SETTINGS: u8 = 0x4;
|
|
54
|
+
const ACK: u8 = 0x1;
|
|
55
|
+
const GOAWAY: u8 = 0x7;
|
|
56
|
+
const CONTINUATION: u8 = 0x9;
|
|
57
|
+
|
|
58
|
+
pub struct Wire {
|
|
59
|
+
next: AtomicU64,
|
|
60
|
+
/// Set when the record cannot be trusted: a CONNECT request, a GOAWAY
|
|
61
|
+
/// that is malformed or raises the last stream id, or client frames the
|
|
62
|
+
/// reader cannot follow.
|
|
63
|
+
disabled: AtomicBool,
|
|
64
|
+
/// The lowest last stream id of the GOAWAYs read, or NONE.
|
|
65
|
+
goaway: AtomicU32,
|
|
66
|
+
/// The highest client stream id whose HEADERS frame header h2 offered to
|
|
67
|
+
/// the socket. It only grows, so one read answers "may it be sent".
|
|
68
|
+
offered: AtomicU32,
|
|
69
|
+
/// The server started HTTP/2: the tap read a non-ACK SETTINGS frame from
|
|
70
|
+
/// it, its connection preface. Also set when the server-frame reader lost
|
|
71
|
+
/// its place first, so the record never claims a preface was missing
|
|
72
|
+
/// when it cannot tell. `disabled` does not touch it: CONNECT and the
|
|
73
|
+
/// client-frame reader leave server frames readable.
|
|
74
|
+
started: AtomicBool,
|
|
75
|
+
holds: Arc<Holds>,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
impl Wire {
|
|
79
|
+
pub fn new(holds: Arc<Holds>) -> Arc<Self> {
|
|
80
|
+
Arc::new(Self {
|
|
81
|
+
next: AtomicU64::new(0),
|
|
82
|
+
disabled: AtomicBool::new(false),
|
|
83
|
+
goaway: AtomicU32::new(NONE),
|
|
84
|
+
offered: AtomicU32::new(0),
|
|
85
|
+
started: AtomicBool::new(false),
|
|
86
|
+
holds,
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// The stream indexes hyper's dispatch has taken so far.
|
|
91
|
+
pub fn taken(&self) -> u64 {
|
|
92
|
+
self.next.load(Ordering::SeqCst)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
pub fn disable(&self) {
|
|
96
|
+
self.disabled.store(true, Ordering::SeqCst);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// A GOAWAY arrived: the connection admits nothing more.
|
|
100
|
+
pub fn going_away(&self) -> bool {
|
|
101
|
+
self.goaway.load(Ordering::SeqCst) != NONE
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// The server's preface arrived, or the reader can no longer tell (see
|
|
105
|
+
/// `started`). A connection that ends before it never was an HTTP/2
|
|
106
|
+
/// connection: a TLS 1.3 server rejecting the client's certificate sends
|
|
107
|
+
/// its alert where its SETTINGS would be.
|
|
108
|
+
pub fn server_started(&self) -> bool {
|
|
109
|
+
self.started.load(Ordering::SeqCst)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
fn record_started(&self) {
|
|
113
|
+
if !self.started.swap(true, Ordering::SeqCst) {
|
|
114
|
+
// Spec hold point: armed with a zero bound, it counts the
|
|
115
|
+
// connections whose server preface the tap read.
|
|
116
|
+
self.holds.block("wire:settings");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
fn record_goaway(&self, last: u32) -> bool {
|
|
121
|
+
let current = self.goaway.load(Ordering::SeqCst);
|
|
122
|
+
// RFC 9113 6.8 forbids raising it; h2 fails the connection.
|
|
123
|
+
if current != NONE && last > current {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
self.goaway.store(last, Ordering::SeqCst);
|
|
127
|
+
true
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
fn record_headers(&self, stream: u32) {
|
|
131
|
+
self.offered.fetch_max(stream, Ordering::SeqCst);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// The stream id of `mark`'s request if the peer's GOAWAY says it never
|
|
135
|
+
/// processed it.
|
|
136
|
+
fn unprocessed(&self, mark: &Mark) -> Option<u32> {
|
|
137
|
+
if self.disabled.load(Ordering::SeqCst) {
|
|
138
|
+
return None;
|
|
139
|
+
}
|
|
140
|
+
let index = *mark.index.get()?;
|
|
141
|
+
let stream = u32::try_from(2 * index + 1).ok()?;
|
|
142
|
+
let last = self.goaway.load(Ordering::SeqCst);
|
|
143
|
+
(last != NONE && stream > last).then_some(stream)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// Whether a HEADERS frame for `stream` reached the socket or still
|
|
147
|
+
/// waits in h2's write buffer.
|
|
148
|
+
fn sent(&self, stream: u32) -> bool {
|
|
149
|
+
self.offered.load(Ordering::SeqCst) >= stream
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// A request's claim on its connection's stream order.
|
|
154
|
+
pub struct Mark {
|
|
155
|
+
wire: Arc<Wire>,
|
|
156
|
+
index: OnceLock<u64>,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
impl Mark {
|
|
160
|
+
pub fn new(wire: Arc<Wire>) -> Arc<Self> {
|
|
161
|
+
Arc::new(Self {
|
|
162
|
+
wire,
|
|
163
|
+
index: OnceLock::new(),
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// Called from the body's `size_hint`, in hyper's dispatch task.
|
|
168
|
+
pub fn take_index(&self) {
|
|
169
|
+
self.index.get_or_init(|| {
|
|
170
|
+
// Spec hold points: armed with a zero bound, they count the
|
|
171
|
+
// requests hyper's dispatch task passed to h2, and each stream id
|
|
172
|
+
// derived for one, so a spec can compare them with the ids h2 put
|
|
173
|
+
// on the wire.
|
|
174
|
+
let holds = &self.wire.holds;
|
|
175
|
+
holds.block("request:indexed");
|
|
176
|
+
let index = self.wire.next.fetch_add(1, Ordering::SeqCst);
|
|
177
|
+
if holds.armed() {
|
|
178
|
+
holds.block(&format!("request:stream:{}", 2 * index + 1));
|
|
179
|
+
}
|
|
180
|
+
index
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/// hyper's dispatch task passed the request to h2 (`take_index`), so h2
|
|
185
|
+
/// and the stream's response task, not the dispatcher, answer it. Read
|
|
186
|
+
/// directly: a disabled record still says whether hyper took it.
|
|
187
|
+
pub fn indexed(&self) -> bool {
|
|
188
|
+
self.index.get().is_some()
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/// A GOAWAY names a last stream id below this request's stream.
|
|
192
|
+
pub fn unprocessed(&self) -> bool {
|
|
193
|
+
self.wire.unprocessed(self).is_some()
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// Above the cutoff as above, and h2 never offered its HEADERS to the
|
|
197
|
+
/// socket. Asked after the request failed. Once h2 has failed the stream
|
|
198
|
+
/// for that GOAWAY, or for a connection error, it has dropped the
|
|
199
|
+
/// stream's queued frames, so the HEADERS never go out. A request hyper
|
|
200
|
+
/// dropped after an earlier GOAWAY that disowned nothing may still be
|
|
201
|
+
/// opened before h2 reads the GOAWAY the tap already saw; then RFC 9113
|
|
202
|
+
/// 6.8 keeps the peer from processing it.
|
|
203
|
+
pub fn unsent(&self) -> bool {
|
|
204
|
+
self.wire
|
|
205
|
+
.unprocessed(self)
|
|
206
|
+
.is_some_and(|stream| !self.wire.sent(stream))
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// Incremental frame-header reader for one direction.
|
|
211
|
+
#[derive(Clone)]
|
|
212
|
+
struct Frames {
|
|
213
|
+
/// Bytes of the client preface still to pass (write side only).
|
|
214
|
+
preface: usize,
|
|
215
|
+
header: [u8; HEAD],
|
|
216
|
+
have: usize,
|
|
217
|
+
/// Payload bytes of the current frame still to pass.
|
|
218
|
+
remaining: usize,
|
|
219
|
+
/// The current frame is a GOAWAY: its payload bytes seen so far.
|
|
220
|
+
goaway: Option<([u8; 4], usize)>,
|
|
221
|
+
/// The current frame is a non-ACK SETTINGS (server side): it counts as
|
|
222
|
+
/// the server's preface only once its whole payload has passed, as
|
|
223
|
+
/// grpc-go reads the full frame before accepting the preface.
|
|
224
|
+
settings: bool,
|
|
225
|
+
broken: bool,
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
impl Frames {
|
|
229
|
+
fn new(preface: usize) -> Self {
|
|
230
|
+
Self {
|
|
231
|
+
preface,
|
|
232
|
+
header: [0; HEAD],
|
|
233
|
+
have: 0,
|
|
234
|
+
remaining: 0,
|
|
235
|
+
goaway: None,
|
|
236
|
+
settings: false,
|
|
237
|
+
broken: false,
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/// Server frames: records each GOAWAY, and the first non-ACK SETTINGS,
|
|
242
|
+
/// once its payload passed.
|
|
243
|
+
fn read(&mut self, wire: &Wire, mut bytes: &[u8]) {
|
|
244
|
+
while !self.broken && !bytes.is_empty() {
|
|
245
|
+
if self.remaining > 0 {
|
|
246
|
+
let take = self.remaining.min(bytes.len());
|
|
247
|
+
if let Some((last, seen)) = self.goaway.as_mut() {
|
|
248
|
+
let want = 4usize.saturating_sub(*seen).min(take);
|
|
249
|
+
last[*seen..*seen + want].copy_from_slice(&bytes[..want]);
|
|
250
|
+
*seen += want;
|
|
251
|
+
}
|
|
252
|
+
self.remaining -= take;
|
|
253
|
+
bytes = &bytes[take..];
|
|
254
|
+
if self.remaining == 0 {
|
|
255
|
+
self.end_frame(wire);
|
|
256
|
+
}
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
let take = (HEAD - self.have).min(bytes.len());
|
|
260
|
+
self.header[self.have..self.have + take].copy_from_slice(&bytes[..take]);
|
|
261
|
+
self.have += take;
|
|
262
|
+
bytes = &bytes[take..];
|
|
263
|
+
if self.have < HEAD {
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
self.have = 0;
|
|
267
|
+
self.server_header();
|
|
268
|
+
if self.remaining == 0 {
|
|
269
|
+
self.end_frame(wire);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if self.broken {
|
|
273
|
+
wire.disable();
|
|
274
|
+
// The reader stops here: it can no longer vouch that no SETTINGS
|
|
275
|
+
// follows.
|
|
276
|
+
wire.started.store(true, Ordering::SeqCst);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
fn server_header(&mut self) {
|
|
281
|
+
let (length, kind, flags, stream) = parse(&self.header);
|
|
282
|
+
self.settings = kind == SETTINGS && flags & ACK == 0;
|
|
283
|
+
if kind == GOAWAY && (stream != 0 || length < 8) {
|
|
284
|
+
// Not a GOAWAY anyone can read a last stream id from.
|
|
285
|
+
self.broken = true;
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
self.goaway = (kind == GOAWAY).then_some(([0; 4], 0));
|
|
289
|
+
self.remaining = length;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
fn end_frame(&mut self, wire: &Wire) {
|
|
293
|
+
if std::mem::take(&mut self.settings) {
|
|
294
|
+
wire.record_started();
|
|
295
|
+
}
|
|
296
|
+
if let Some((last, _)) = self.goaway.take() {
|
|
297
|
+
let last = u32::from_be_bytes(last) & 0x7fff_ffff;
|
|
298
|
+
if !wire.record_goaway(last) {
|
|
299
|
+
self.broken = true;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/// Client frames: records the HEADERS frame headers written.
|
|
305
|
+
fn write(&mut self, wire: &Wire, bytes: &[u8]) {
|
|
306
|
+
self.walk(bytes, |stream| wire.record_headers(stream));
|
|
307
|
+
if self.broken {
|
|
308
|
+
wire.disable();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// The highest stream id with a HEADERS frame header in `chunks`, which
|
|
313
|
+
/// follow what was written, without consuming them.
|
|
314
|
+
fn scan<'a>(&self, chunks: impl Iterator<Item = &'a [u8]>) -> u32 {
|
|
315
|
+
let mut ahead = self.clone();
|
|
316
|
+
let mut highest = 0;
|
|
317
|
+
for chunk in chunks {
|
|
318
|
+
ahead.walk(chunk, |stream| highest = highest.max(stream));
|
|
319
|
+
}
|
|
320
|
+
highest
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
fn walk(&mut self, mut bytes: &[u8], mut headers: impl FnMut(u32)) {
|
|
324
|
+
while !self.broken && !bytes.is_empty() {
|
|
325
|
+
if self.preface > 0 {
|
|
326
|
+
let take = self.preface.min(bytes.len());
|
|
327
|
+
self.preface -= take;
|
|
328
|
+
bytes = &bytes[take..];
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if self.remaining > 0 {
|
|
332
|
+
let take = self.remaining.min(bytes.len());
|
|
333
|
+
self.remaining -= take;
|
|
334
|
+
bytes = &bytes[take..];
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
let take = (HEAD - self.have).min(bytes.len());
|
|
338
|
+
self.header[self.have..self.have + take].copy_from_slice(&bytes[..take]);
|
|
339
|
+
self.have += take;
|
|
340
|
+
bytes = &bytes[take..];
|
|
341
|
+
if self.have < HEAD {
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
self.have = 0;
|
|
345
|
+
let (length, kind, _, stream) = parse(&self.header);
|
|
346
|
+
if kind > CONTINUATION {
|
|
347
|
+
// h2 sends no extension frames: the reader lost its place.
|
|
348
|
+
self.broken = true;
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
if kind == HEADERS {
|
|
352
|
+
headers(stream);
|
|
353
|
+
}
|
|
354
|
+
self.remaining = length;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
fn parse(header: &[u8; HEAD]) -> (usize, u8, u8, u32) {
|
|
360
|
+
let length = u32::from_be_bytes([0, header[0], header[1], header[2]]) as usize;
|
|
361
|
+
let stream = u32::from_be_bytes([header[5], header[6], header[7], header[8]]) & 0x7fff_ffff;
|
|
362
|
+
(length, header[3], header[4], stream)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/// The connection's IO as hyper sees it, observed by `Wire`.
|
|
366
|
+
pub struct Tap<T> {
|
|
367
|
+
inner: T,
|
|
368
|
+
wire: Arc<Wire>,
|
|
369
|
+
read: Frames,
|
|
370
|
+
write: Frames,
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
impl<T> Tap<T> {
|
|
374
|
+
pub fn new(inner: T, wire: Arc<Wire>) -> Self {
|
|
375
|
+
Self {
|
|
376
|
+
inner,
|
|
377
|
+
wire,
|
|
378
|
+
read: Frames::new(0),
|
|
379
|
+
write: Frames::new(PREFACE),
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/// Commits the bytes the socket took; HEADERS in the rest count as
|
|
384
|
+
/// offered too.
|
|
385
|
+
fn wrote(&mut self, result: &Poll<io::Result<usize>>, bufs: &[io::IoSlice<'_>]) {
|
|
386
|
+
let mut taken = match result {
|
|
387
|
+
Poll::Ready(Ok(n)) => *n,
|
|
388
|
+
// A failed TLS write may still have sent part of the offer.
|
|
389
|
+
Poll::Pending | Poll::Ready(Err(_)) => 0,
|
|
390
|
+
};
|
|
391
|
+
let mut split = (bufs.len(), 0);
|
|
392
|
+
for (index, buf) in bufs.iter().enumerate() {
|
|
393
|
+
let take = taken.min(buf.len());
|
|
394
|
+
self.write.write(&self.wire, &buf[..take]);
|
|
395
|
+
taken -= take;
|
|
396
|
+
if take < buf.len() {
|
|
397
|
+
split = (index, take);
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
let (index, offset) = split;
|
|
402
|
+
let rest = bufs
|
|
403
|
+
.get(index)
|
|
404
|
+
.map(|buf| &buf[offset..])
|
|
405
|
+
.into_iter()
|
|
406
|
+
.chain(bufs.iter().skip(index + 1).map(|buf| &buf[..]));
|
|
407
|
+
let ahead = self.write.scan(rest);
|
|
408
|
+
self.wire.record_headers(ahead);
|
|
409
|
+
if ahead > 0 {
|
|
410
|
+
// Spec hold point: armed with a zero bound, it counts writes that
|
|
411
|
+
// left a HEADERS frame offered but not yet taken.
|
|
412
|
+
self.wire.holds.block("wire:headers-queued");
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
impl<T: AsyncRead + Unpin> AsyncRead for Tap<T> {
|
|
418
|
+
fn poll_read(
|
|
419
|
+
self: Pin<&mut Self>,
|
|
420
|
+
cx: &mut Context<'_>,
|
|
421
|
+
buf: &mut ReadBuf<'_>,
|
|
422
|
+
) -> Poll<io::Result<()>> {
|
|
423
|
+
let this = self.get_mut();
|
|
424
|
+
let before = buf.filled().len();
|
|
425
|
+
let result = Pin::new(&mut this.inner).poll_read(cx, buf);
|
|
426
|
+
if let Poll::Ready(Ok(())) = result {
|
|
427
|
+
this.read.read(&this.wire, &buf.filled()[before..]);
|
|
428
|
+
}
|
|
429
|
+
result
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
impl<T: AsyncWrite + Unpin> AsyncWrite for Tap<T> {
|
|
434
|
+
fn poll_write(
|
|
435
|
+
self: Pin<&mut Self>,
|
|
436
|
+
cx: &mut Context<'_>,
|
|
437
|
+
buf: &[u8],
|
|
438
|
+
) -> Poll<io::Result<usize>> {
|
|
439
|
+
let this = self.get_mut();
|
|
440
|
+
let result = Pin::new(&mut this.inner).poll_write(cx, buf);
|
|
441
|
+
this.wrote(&result, &[io::IoSlice::new(buf)]);
|
|
442
|
+
result
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
fn poll_write_vectored(
|
|
446
|
+
self: Pin<&mut Self>,
|
|
447
|
+
cx: &mut Context<'_>,
|
|
448
|
+
bufs: &[io::IoSlice<'_>],
|
|
449
|
+
) -> Poll<io::Result<usize>> {
|
|
450
|
+
let this = self.get_mut();
|
|
451
|
+
let result = Pin::new(&mut this.inner).poll_write_vectored(cx, bufs);
|
|
452
|
+
this.wrote(&result, bufs);
|
|
453
|
+
result
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
fn is_write_vectored(&self) -> bool {
|
|
457
|
+
self.inner.is_write_vectored()
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
461
|
+
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
465
|
+
Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
#[cfg(test)]
|
|
470
|
+
mod tests {
|
|
471
|
+
use super::*;
|
|
472
|
+
|
|
473
|
+
fn frame(kind: u8, flags: u8, stream: u32, payload: &[u8]) -> Vec<u8> {
|
|
474
|
+
let length = u32::try_from(payload.len())
|
|
475
|
+
.expect("small payload")
|
|
476
|
+
.to_be_bytes();
|
|
477
|
+
let mut bytes = vec![length[1], length[2], length[3], kind, flags];
|
|
478
|
+
bytes.extend_from_slice(&stream.to_be_bytes());
|
|
479
|
+
bytes.extend_from_slice(payload);
|
|
480
|
+
bytes
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
fn read(frames: &[Vec<u8>]) -> Arc<Wire> {
|
|
484
|
+
let wire = Wire::new(Arc::default());
|
|
485
|
+
let mut reader = Frames::new(0);
|
|
486
|
+
for bytes in frames {
|
|
487
|
+
// One byte at a time: headers split across reads still count.
|
|
488
|
+
for byte in bytes {
|
|
489
|
+
reader.read(&wire, std::slice::from_ref(byte));
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
wire
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
#[test]
|
|
496
|
+
fn a_server_settings_frame_starts_http2_and_its_ack_does_not() {
|
|
497
|
+
assert!(!read(&[frame(SETTINGS, ACK, 0, &[])]).server_started());
|
|
498
|
+
assert!(read(&[frame(SETTINGS, 0, 0, &[0, 3, 0, 0, 0, 100])]).server_started());
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
#[test]
|
|
502
|
+
fn a_settings_frame_cut_short_is_no_preface() {
|
|
503
|
+
let whole = frame(SETTINGS, 0, 0, &[0, 3, 0, 0, 0, 100]);
|
|
504
|
+
assert!(!read(&[whole[..whole.len() - 1].to_vec()]).server_started());
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
#[test]
|
|
508
|
+
fn a_reader_that_lost_its_place_cannot_vouch_for_a_missing_preface() {
|
|
509
|
+
let wire = read(&[frame(GOAWAY, 0, 1, &[0; 8])]);
|
|
510
|
+
assert!(wire.server_started());
|
|
511
|
+
assert!(wire.disabled.load(Ordering::SeqCst));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ConnectRPC
|
|
4
|
+
module Hyper
|
|
5
|
+
module Native
|
|
6
|
+
# Raised by the extension. `kind` classifies the failure; `reset_code` is
|
|
7
|
+
# the HTTP/2 error code, if any, of a stream reset or connection error,
|
|
8
|
+
# the peer's or h2's own; `errno` is the OS error, if any. Messages never
|
|
9
|
+
# carry paths or key material.
|
|
10
|
+
class Failure < StandardError
|
|
11
|
+
attr_reader :kind, :reset_code, :errno
|
|
12
|
+
|
|
13
|
+
def initialize(message, kind, reset_code, errno)
|
|
14
|
+
super(message)
|
|
15
|
+
@kind = kind
|
|
16
|
+
@reset_code = reset_code
|
|
17
|
+
@errno = errno
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Fixed, non-secret phrases naming what failed (core's transport phrases).
|
|
23
|
+
# Local failures keep the native failure as their cause.
|
|
24
|
+
module Errors
|
|
25
|
+
CLOSED = "HTTP transport admission is closed"
|
|
26
|
+
PHRASES = {
|
|
27
|
+
dns: "name resolution failed", refused: "connection refused", unreachable: "host unreachable",
|
|
28
|
+
connect: "connection failed", connect_timeout: "timed out", timeout: "timed out",
|
|
29
|
+
tls_verify: "TLS verification failed", tls: "TLS error", closed: "connection closed",
|
|
30
|
+
goaway: "connection closed", shutdown: "connection closed", protocol: "malformed response",
|
|
31
|
+
alpn: "ALPN negotiation failed", reset: "stream reset",
|
|
32
|
+
# Core NetHTTP's proxy phrases. Proxy reply bytes never reach them.
|
|
33
|
+
proxy_auth: "proxy authentication failed", proxy_refused: "proxy tunnel refused",
|
|
34
|
+
proxy_failed: "proxy tunnel failed", proxy_timeout: "proxy tunnel timed out",
|
|
35
|
+
proxy_scheme: "unsupported proxy scheme", proxy_address: "invalid proxy address",
|
|
36
|
+
proxy_cgi: "proxy refused in CGI environment"
|
|
37
|
+
}.freeze
|
|
38
|
+
# The Async transport's mapping of server RST_STREAM codes for gRPC.
|
|
39
|
+
GRPC_RESET = { 3 => :resource_exhausted, 7 => :unavailable, 8 => :canceled, 11 => :resource_exhausted,
|
|
40
|
+
12 => :permission_denied }.freeze
|
|
41
|
+
|
|
42
|
+
# A proxy the call must not use, raised before any socket opens.
|
|
43
|
+
def self.proxy(kind) = Native::Failure.new(PHRASES.fetch(kind), kind, nil, nil)
|
|
44
|
+
|
|
45
|
+
def self.transport(kind)
|
|
46
|
+
reason = PHRASES[kind]
|
|
47
|
+
Error.new(:unavailable, reason ? "HTTP transport failed: #{reason}" : "HTTP transport failed")
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Maps a native failure; deadline and cancellation are the caller's
|
|
51
|
+
# arbiter's to raise first.
|
|
52
|
+
def self.translate(failure, grpc:)
|
|
53
|
+
case failure.kind
|
|
54
|
+
when :admission then raise Error.new(:unavailable, CLOSED), cause: nil
|
|
55
|
+
when :response_limit then raise Error.new(:resource_exhausted, "Response exceeds byte limit"), cause: nil
|
|
56
|
+
when :field_limit then raise Error.new(:resource_exhausted, "gRPC field block exceeds byte limit"), cause: nil
|
|
57
|
+
when :reset
|
|
58
|
+
if grpc
|
|
59
|
+
raise Error.new(GRPC_RESET.fetch(failure.reset_code, :internal), "HTTP/2 stream reset"), cause: failure
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
raise transport(failure.kind), cause: failure
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Runs one native operation for a request: cancellation and deadline
|
|
66
|
+
# first, then lifecycle failure recording (a per-wait timeout included,
|
|
67
|
+
# as the Async transport records it), then the fixed phrase.
|
|
68
|
+
def self.native(request, grpc:)
|
|
69
|
+
yield
|
|
70
|
+
rescue Native::Failure => e
|
|
71
|
+
request.cancellation ? request.cancellation.check! : request.deadline&.check!
|
|
72
|
+
request.lifecycle&.record_failure(e)
|
|
73
|
+
raise Error.new(:unavailable, "HTTP transport failed: timed out"), cause: nil if e.kind == :timeout
|
|
74
|
+
|
|
75
|
+
translate(e, grpc: grpc)
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ConnectRPC
|
|
4
|
+
module Hyper
|
|
5
|
+
# One streaming call for core's exchange SPI. Operations run on the
|
|
6
|
+
# calling thread and block in Rust with the GVL released; each wait is
|
|
7
|
+
# bounded by the call deadline and the per-wait timeout.
|
|
8
|
+
class Exchange
|
|
9
|
+
def initialize(native, request, grpc:)
|
|
10
|
+
@native = native
|
|
11
|
+
@request = request
|
|
12
|
+
@grpc = grpc
|
|
13
|
+
@head = nil
|
|
14
|
+
@trailers = nil
|
|
15
|
+
@read_eof = false
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def response_head(timeout: nil)
|
|
19
|
+
@response_head ||= begin
|
|
20
|
+
status, headers, end_stream = wait(timeout) { |limit| @native.head(limit) }
|
|
21
|
+
if @grpc
|
|
22
|
+
# h2 accepts blocks up to 16 MiB; core's field limit applies here.
|
|
23
|
+
GRPCProtocol.check_fields!(headers)
|
|
24
|
+
GRPCHead.new(status: status, headers: headers, end_stream: end_stream)
|
|
25
|
+
else
|
|
26
|
+
StreamHead.new(status: status, headers: headers)
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def read(length, timeout: nil)
|
|
32
|
+
bytes = wait(timeout) { |limit| @native.read(length, limit) }
|
|
33
|
+
receive_trailers if bytes.nil? && @grpc
|
|
34
|
+
bytes
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def write(bytes)
|
|
38
|
+
wait(nil) { |limit| @native.write(bytes, limit) }
|
|
39
|
+
nil
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def close_send
|
|
43
|
+
@native.close_send
|
|
44
|
+
nil
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def response_trailers
|
|
48
|
+
raise StreamStateError, "Trailers require response EOF" unless @read_eof
|
|
49
|
+
|
|
50
|
+
@trailers
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def finish(timeout: nil)
|
|
54
|
+
wait(timeout) { |limit| @native.finish(limit) }
|
|
55
|
+
return unless @grpc
|
|
56
|
+
|
|
57
|
+
receive_trailers
|
|
58
|
+
head = @response_head
|
|
59
|
+
raise Error.new(:internal, "Missing final gRPC HEADERS"), cause: nil unless head&.end_stream || @trailers
|
|
60
|
+
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def abort
|
|
65
|
+
@native.abort
|
|
66
|
+
nil
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
def receive_trailers
|
|
72
|
+
return if @read_eof
|
|
73
|
+
|
|
74
|
+
trailers = @native.trailers
|
|
75
|
+
GRPCProtocol.check_fields!(trailers) if trailers
|
|
76
|
+
@trailers = trailers
|
|
77
|
+
@read_eof = true
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def wait(timeout)
|
|
81
|
+
Errors.native(@request, grpc: @grpc) do
|
|
82
|
+
@request.cancellation ? @request.cancellation.check! : @request.deadline&.check!
|
|
83
|
+
remaining = @request.deadline&.remaining
|
|
84
|
+
yield [timeout, remaining].compact.min
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|