-
Notifications
You must be signed in to change notification settings - Fork 5
/
lib.rs
323 lines (265 loc) · 9.85 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#![cfg_attr(
not(target_family = "wasm"),
doc = "The [`wtransport`]-powered implementation of [`xwt_core`]."
)]
#![cfg_attr(
target_family = "wasm",
doc = "The `wtransport`-powered implementation of `xwt_core`."
)]
#![cfg(not(target_family = "wasm"))]
mod types;
pub use wtransport;
pub use xwt_core as core;
pub use self::types::*;
impl xwt_core::endpoint::Connect for Endpoint<wtransport::endpoint::endpoint_side::Client> {
type Connecting = xwt_core::utils::dummy::Connecting<Connection>;
type Error = wtransport::error::ConnectingError;
async fn connect(&self, url: &str) -> Result<Self::Connecting, Self::Error> {
let connecting = self.0.connect(url).await.map(Connection)?;
Ok(xwt_core::utils::dummy::Connecting(connecting))
}
}
impl xwt_core::endpoint::Accept for Endpoint<wtransport::endpoint::endpoint_side::Server> {
type Accepting = IncomingSession;
type Error = std::convert::Infallible;
async fn accept(&self) -> Result<Option<Self::Accepting>, Self::Error> {
let incoming_session = self.0.accept().await;
let incoming_session = IncomingSession(incoming_session);
Ok(Some(incoming_session))
}
}
impl xwt_core::endpoint::accept::Accepting for IncomingSession {
type Request = SessionRequest;
type Error = wtransport::error::ConnectionError;
async fn wait_accept(self) -> Result<Self::Request, Self::Error> {
self.0.await.map(SessionRequest)
}
}
impl xwt_core::endpoint::accept::Request for SessionRequest {
type Session = Connection;
type OkError = wtransport::error::ConnectionError;
type CloseError = std::convert::Infallible;
async fn ok(self) -> Result<Self::Session, Self::OkError> {
self.0.accept().await.map(Connection)
}
async fn close(self, status: u16) -> Result<(), Self::CloseError> {
debug_assert!(
status == 404,
"wtransport driver only supports closing requests with 404 status code"
);
self.0.not_found().await;
Ok(())
}
}
impl xwt_core::session::stream::SendSpec for Connection {
type SendStream = SendStream;
}
impl xwt_core::session::stream::RecvSpec for Connection {
type RecvStream = RecvStream;
}
/// Take a pair of stream ends and wrap into our newtypes.
fn map_streams(
streams: (wtransport::SendStream, wtransport::RecvStream),
) -> (SendStream, RecvStream) {
let (send, recv) = streams;
(SendStream(send), RecvStream(recv))
}
impl xwt_core::session::stream::OpeningBi for OpeningBiStream {
type Streams = Connection;
type Error = wtransport::error::StreamOpeningError;
async fn wait_bi(
self,
) -> Result<xwt_core::session::stream::TupleFor<Self::Streams>, Self::Error> {
self.0.await.map(map_streams)
}
}
impl xwt_core::session::stream::OpenBi for Connection {
type Opening = OpeningBiStream;
type Error = wtransport::error::ConnectionError;
async fn open_bi(&self) -> Result<Self::Opening, Self::Error> {
self.0.open_bi().await.map(OpeningBiStream)
}
}
impl xwt_core::session::stream::AcceptBi for Connection {
type Error = wtransport::error::ConnectionError;
async fn accept_bi(&self) -> Result<xwt_core::session::stream::TupleFor<Self>, Self::Error> {
self.0.accept_bi().await.map(map_streams)
}
}
impl xwt_core::session::stream::OpeningUni for OpeningUniStream {
type Streams = Connection;
type Error = wtransport::error::StreamOpeningError;
async fn wait_uni(
self,
) -> Result<<Self::Streams as xwt_core::session::stream::SendSpec>::SendStream, Self::Error>
{
self.0.await.map(SendStream)
}
}
impl xwt_core::session::stream::OpenUni for Connection {
type Opening = OpeningUniStream;
type Error = wtransport::error::ConnectionError;
async fn open_uni(&self) -> Result<Self::Opening, Self::Error> {
self.0.open_uni().await.map(OpeningUniStream)
}
}
impl xwt_core::session::stream::AcceptUni for Connection {
type Error = wtransport::error::ConnectionError;
async fn accept_uni(&self) -> Result<Self::RecvStream, Self::Error> {
self.0.accept_uni().await.map(RecvStream)
}
}
impl xwt_core::stream::Read for RecvStream {
type Error = StreamReadError;
async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, Self::Error> {
self.0.read(buf).await.map_err(StreamReadError)
}
}
impl xwt_core::stream::AsErrorCode for StreamReadError {
type ErrorCode = StreamErrorCode;
fn as_error_code(&self) -> Option<Self::ErrorCode> {
match self.0 {
wtransport::error::StreamReadError::Reset(error_code) => {
let code = error_codes::from_http(error_code.into_inner()).ok()?;
Some(StreamErrorCode(code))
}
_ => None,
}
}
}
impl xwt_core::stream::ReadAbort for RecvStream {
type ErrorCode = StreamErrorCode;
type Error = std::convert::Infallible;
async fn abort(self, error_code: Self::ErrorCode) -> Result<(), Self::Error> {
let code = error_codes::to_http(error_code.0).try_into().unwrap();
self.0.stop(code);
Ok(())
}
}
impl xwt_core::stream::Write for SendStream {
type Error = wtransport::error::StreamWriteError;
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.0.write(buf).await
}
}
impl xwt_core::stream::WriteChunk<xwt_core::stream::chunk::U8> for SendStream {
type Error = wtransport::error::StreamWriteError;
async fn write_chunk<'a>(&'a mut self, buf: &'a [u8]) -> Result<(), Self::Error> {
self.0.write_all(buf).await
}
}
impl xwt_core::session::datagram::MaxSize for Connection {
fn max_datagram_size(&self) -> Option<usize> {
self.0.max_datagram_size()
}
}
impl xwt_core::stream::WriteAbort for SendStream {
type ErrorCode = StreamErrorCode;
type Error = wtransport::error::StreamWriteError;
async fn abort(mut self, error_code: Self::ErrorCode) -> Result<(), Self::Error> {
let code = error_codes::to_http(error_code.0).try_into().unwrap();
self.0.reset(code)?;
Ok(())
}
}
/// An error that can occur while waiting for the write stream being aborted.
#[derive(Debug, thiserror::Error)]
pub enum WriteAbortedError {
/// An unexpected stream write error has occurred.
#[error("stream write: {0}")]
StreamWrite(wtransport::error::StreamWriteError),
/// An error code failed to convert.
#[error("error code conversion: {0}")]
ErrorCodeConversion(error_codes::FromHttpError),
}
impl xwt_core::stream::WriteAborted for SendStream {
type ErrorCode = StreamErrorCode;
type Error = WriteAbortedError;
async fn aborted(mut self) -> Result<Option<Self::ErrorCode>, Self::Error> {
match self.0.quic_stream_mut().stopped().await {
Ok(Some(error_code)) => {
let code = error_codes::from_http(error_code.into_inner())
.map_err(WriteAbortedError::ErrorCodeConversion)?;
Ok(Some(StreamErrorCode(code)))
}
Ok(None) => Ok(None),
Err(wtransport::quinn::StoppedError::ConnectionLost(_)) => Err(
WriteAbortedError::StreamWrite(wtransport::error::StreamWriteError::NotConnected),
),
Err(wtransport::quinn::StoppedError::ZeroRttRejected) => Err(
WriteAbortedError::StreamWrite(wtransport::error::StreamWriteError::QuicProto),
),
}
}
}
impl xwt_core::stream::Finish for SendStream {
type Error = wtransport::error::StreamWriteError;
async fn finish(mut self) -> Result<(), Self::Error> {
self.0.finish().await
}
}
impl xwt_core::session::datagram::Receive for Connection {
type Datagram = Datagram;
type Error = wtransport::error::ConnectionError;
async fn receive_datagram(&self) -> Result<Self::Datagram, Self::Error> {
self.0.receive_datagram().await.map(Datagram)
}
}
impl AsRef<[u8]> for Datagram {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl xwt_core::session::datagram::ReceiveInto for Connection {
type Error = wtransport::error::ConnectionError;
async fn receive_datagram_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
let datagram = self.0.receive_datagram().await?;
let len = datagram.len();
buf[..len].copy_from_slice(&datagram);
Ok(len)
}
}
impl xwt_core::session::datagram::Send for Connection {
type Error = wtransport::error::SendDatagramError;
async fn send_datagram<D>(&self, payload: D) -> Result<(), Self::Error>
where
D: Send + AsRef<[u8]>,
{
self.0.send_datagram(payload)
}
}
/// Conversions of the WebTransport error codes from and to the HTTP3 error
/// codes.
///
/// We need this because [`wtransport`] does not convert error codes at all.
pub mod error_codes {
/// Lower end of the WebTransport HTTP codes.
const FIRST: u64 = 0x52e4a40fa8db;
/// Higher end of the WebTransport HTTP codes.
const LAST: u64 = 0x52e5ac983162;
/// Convert the WebTransport code value to HTTP3 code.
pub fn to_http(n: u32) -> u64 {
if n == 0 {
return 0;
}
let n: u64 = n.into();
FIRST + n + (n / 0x1e)
}
/// An error that occurs when converting the HTTP error code to
/// WebTransport error code.
#[derive(Debug, thiserror::Error)]
#[error("unable to convert HTTP error code to WebTransport error code: {0}")]
pub struct FromHttpError(u64);
/// Convert the HTTP3 code value to WebTransport code.
pub fn from_http(h: u64) -> Result<u32, FromHttpError> {
if h == 0 {
return Ok(0);
}
if !((FIRST..=LAST).contains(&h) && (h - 0x21) % 0x1f != 0) {
return Err(FromHttpError(h));
}
let shifted = h - FIRST;
let val = shifted - (shifted / 0x1f);
Ok(val.try_into().unwrap())
}
}