tokio-cronet 0.1.0

Safe Rust bindings for Chromium Cronet's native C API
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::{error, fmt};

use tokio_cronet_sys as sys;

use crate::ResponseInfo;

/// Result type used by this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// An error produced while configuring or using Cronet.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// A string contains an interior NUL and cannot cross the C ABI.
    InvalidString { field: &'static str },
    /// A configured path cannot be represented as UTF-8.
    NonUtf8Path,
    /// A builder option is outside the supported range.
    InvalidConfiguration(&'static str),
    /// Disk caching requires a storage directory that already exists.
    StoragePathMissing,
    /// Cronet returned a synchronous API result code.
    Cronet(ResultCode),
    /// Cronet reported a network failure asynchronously.
    Network(NetworkError),
    /// The request was canceled.
    Canceled,
    /// Redirect following was disabled for this request.
    Redirect {
        location: String,
        response: Box<ResponseInfo>,
    },
    /// The response body exceeded the configured safety limit.
    ResponseTooLarge { limit: usize },
    /// Cronet reported more bytes than fit in the supplied read buffer.
    InvalidReadSize { reported: u64, capacity: u64 },
    /// A native constructor unexpectedly returned a null pointer.
    AllocationFailed(&'static str),
    /// Cronet stopped its callback channel without a terminal callback.
    CallbackChannelClosed,
    /// Engine construction was attempted outside a Tokio runtime.
    TokioRuntimeRequired,
    /// The engine has begun or completed shutdown.
    EngineShutdown,
    /// A Tokio task used for a blocking native operation could not complete.
    TokioTask(String),
    /// An asynchronous upload source failed.
    Upload(String),
    /// The bidirectional stream C API rejected an operation synchronously.
    BidirectionalApi { operation: &'static str, code: i32 },
    /// Chromium's network stack failed a bidirectional stream.
    BidirectionalStream { net_error: i32 },
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidString { field } => write!(formatter, "{field} contains an interior NUL"),
            Self::NonUtf8Path => formatter.write_str("path is not valid UTF-8"),
            Self::InvalidConfiguration(message) => formatter.write_str(message),
            Self::StoragePathMissing => {
                formatter.write_str("disk cache storage path must be an existing directory")
            }
            Self::Cronet(code) => write!(formatter, "Cronet API call failed: {code}"),
            Self::Network(error) => write!(formatter, "Cronet request failed: {error}"),
            Self::Canceled => formatter.write_str("Cronet request was canceled"),
            Self::Redirect { location, .. } => {
                write!(formatter, "redirect was not followed: {location}")
            }
            Self::ResponseTooLarge { limit } => {
                write!(formatter, "response body exceeds the {limit}-byte limit")
            }
            Self::InvalidReadSize { reported, capacity } => write!(
                formatter,
                "Cronet reported a {reported}-byte read for a {capacity}-byte buffer"
            ),
            Self::AllocationFailed(kind) => write!(formatter, "Cronet failed to create {kind}"),
            Self::CallbackChannelClosed => {
                formatter.write_str("Cronet callback channel closed before completion")
            }
            Self::TokioRuntimeRequired => {
                formatter.write_str("Cronet engine must be created inside a Tokio runtime")
            }
            Self::EngineShutdown => formatter.write_str("Cronet engine is shutting down"),
            Self::TokioTask(message) => write!(formatter, "Tokio task failed: {message}"),
            Self::Upload(message) => write!(formatter, "request upload failed: {message}"),
            Self::BidirectionalApi { operation, code } => {
                write!(
                    formatter,
                    "bidirectional stream {operation} failed with code {code}"
                )
            }
            Self::BidirectionalStream { net_error } => {
                write!(
                    formatter,
                    "bidirectional stream failed with net error {net_error}"
                )
            }
        }
    }
}

impl error::Error for Error {}

/// A synchronous result code returned by the native C API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ResultCode {
    IllegalArgument,
    StoragePathMustExist,
    InvalidPin,
    InvalidHostname,
    InvalidHttpMethod,
    InvalidHttpHeader,
    IllegalState,
    StoragePathInUse,
    ShutdownFromNetworkThread,
    EngineAlreadyStarted,
    RequestAlreadyStarted,
    RequestNotInitialized,
    RequestAlreadyInitialized,
    RequestNotStarted,
    UnexpectedRedirect,
    UnexpectedRead,
    ReadFailed,
    NullPointer,
    NullHostname,
    NullPins,
    NullExpirationDate,
    NullEngine,
    NullUrl,
    NullCallback,
    NullExecutor,
    NullMethod,
    NullHeaderName,
    NullHeaderValue,
    NullParams,
    NullFinishedListenerExecutor,
    Unknown(i32),
}

impl ResultCode {
    pub(crate) fn from_raw(value: sys::Cronet_RESULT) -> Option<Self> {
        match value {
            sys::Cronet_RESULT_SUCCESS => None,
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT => Some(Self::IllegalArgument),
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST => {
                Some(Self::StoragePathMustExist)
            }
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_PIN => Some(Self::InvalidPin),
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME => Some(Self::InvalidHostname),
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HTTP_METHOD => {
                Some(Self::InvalidHttpMethod)
            }
            sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HTTP_HEADER => {
                Some(Self::InvalidHttpHeader)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE => Some(Self::IllegalState),
            sys::Cronet_RESULT_ILLEGAL_STATE_STORAGE_PATH_IN_USE => Some(Self::StoragePathInUse),
            sys::Cronet_RESULT_ILLEGAL_STATE_CANNOT_SHUTDOWN_ENGINE_FROM_NETWORK_THREAD => {
                Some(Self::ShutdownFromNetworkThread)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE_ENGINE_ALREADY_STARTED => {
                Some(Self::EngineAlreadyStarted)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_ALREADY_STARTED => {
                Some(Self::RequestAlreadyStarted)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_NOT_INITIALIZED => {
                Some(Self::RequestNotInitialized)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_ALREADY_INITIALIZED => {
                Some(Self::RequestAlreadyInitialized)
            }
            sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_NOT_STARTED => Some(Self::RequestNotStarted),
            sys::Cronet_RESULT_ILLEGAL_STATE_UNEXPECTED_REDIRECT => Some(Self::UnexpectedRedirect),
            sys::Cronet_RESULT_ILLEGAL_STATE_UNEXPECTED_READ => Some(Self::UnexpectedRead),
            sys::Cronet_RESULT_ILLEGAL_STATE_READ_FAILED => Some(Self::ReadFailed),
            sys::Cronet_RESULT_NULL_POINTER => Some(Self::NullPointer),
            sys::Cronet_RESULT_NULL_POINTER_HOSTNAME => Some(Self::NullHostname),
            sys::Cronet_RESULT_NULL_POINTER_SHA256_PINS => Some(Self::NullPins),
            sys::Cronet_RESULT_NULL_POINTER_EXPIRATION_DATE => Some(Self::NullExpirationDate),
            sys::Cronet_RESULT_NULL_POINTER_ENGINE => Some(Self::NullEngine),
            sys::Cronet_RESULT_NULL_POINTER_URL => Some(Self::NullUrl),
            sys::Cronet_RESULT_NULL_POINTER_CALLBACK => Some(Self::NullCallback),
            sys::Cronet_RESULT_NULL_POINTER_EXECUTOR => Some(Self::NullExecutor),
            sys::Cronet_RESULT_NULL_POINTER_METHOD => Some(Self::NullMethod),
            sys::Cronet_RESULT_NULL_POINTER_HEADER_NAME => Some(Self::NullHeaderName),
            sys::Cronet_RESULT_NULL_POINTER_HEADER_VALUE => Some(Self::NullHeaderValue),
            sys::Cronet_RESULT_NULL_POINTER_PARAMS => Some(Self::NullParams),
            sys::Cronet_RESULT_NULL_POINTER_REQUEST_FINISHED_INFO_LISTENER_EXECUTOR => {
                Some(Self::NullFinishedListenerExecutor)
            }
            other => Some(Self::Unknown(other)),
        }
    }
}

impl fmt::Display for ResultCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{self:?}")
    }
}

/// Detailed failure copied from the callback-owned `Cronet_Error` value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkError {
    pub code: NetworkErrorCode,
    pub message: String,
    pub internal_error_code: i32,
    pub immediately_retryable: bool,
    pub quic_detailed_error_code: i32,
}

impl fmt::Display for NetworkError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{} ({:?})", self.message, self.code)
    }
}

/// Stable classification of a Cronet request failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NetworkErrorCode {
    Callback,
    HostnameNotResolved,
    InternetDisconnected,
    NetworkChanged,
    TimedOut,
    ConnectionClosed,
    ConnectionTimedOut,
    ConnectionRefused,
    ConnectionReset,
    AddressUnreachable,
    QuicProtocolFailed,
    Other,
    Unknown(u32),
}

impl NetworkErrorCode {
    pub(crate) fn from_raw(value: sys::Cronet_Error_ERROR_CODE) -> Self {
        match value {
            sys::Cronet_Error_ERROR_CODE_ERROR_CALLBACK => Self::Callback,
            sys::Cronet_Error_ERROR_CODE_ERROR_HOSTNAME_NOT_RESOLVED => Self::HostnameNotResolved,
            sys::Cronet_Error_ERROR_CODE_ERROR_INTERNET_DISCONNECTED => Self::InternetDisconnected,
            sys::Cronet_Error_ERROR_CODE_ERROR_NETWORK_CHANGED => Self::NetworkChanged,
            sys::Cronet_Error_ERROR_CODE_ERROR_TIMED_OUT => Self::TimedOut,
            sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_CLOSED => Self::ConnectionClosed,
            sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_TIMED_OUT => Self::ConnectionTimedOut,
            sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_REFUSED => Self::ConnectionRefused,
            sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_RESET => Self::ConnectionReset,
            sys::Cronet_Error_ERROR_CODE_ERROR_ADDRESS_UNREACHABLE => Self::AddressUnreachable,
            sys::Cronet_Error_ERROR_CODE_ERROR_QUIC_PROTOCOL_FAILED => Self::QuicProtocolFailed,
            sys::Cronet_Error_ERROR_CODE_ERROR_OTHER => Self::Other,
            other => Self::Unknown(other),
        }
    }
}

pub(crate) fn check(value: sys::Cronet_RESULT) -> Result<()> {
    ResultCode::from_raw(value).map_or(Ok(()), |code| Err(Error::Cronet(code)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn success_is_not_an_error() {
        assert_eq!(ResultCode::from_raw(sys::Cronet_RESULT_SUCCESS), None);
    }

    #[test]
    fn preserves_unknown_result_code() {
        assert_eq!(ResultCode::from_raw(-999), Some(ResultCode::Unknown(-999)));
    }

    #[test]
    #[allow(
        clippy::too_many_lines,
        reason = "the exhaustive native result-code table is clearer kept in one place"
    )]
    fn maps_every_native_result_code() {
        let cases = [
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT,
                ResultCode::IllegalArgument,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST,
                ResultCode::StoragePathMustExist,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_PIN,
                ResultCode::InvalidPin,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME,
                ResultCode::InvalidHostname,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HTTP_METHOD,
                ResultCode::InvalidHttpMethod,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HTTP_HEADER,
                ResultCode::InvalidHttpHeader,
            ),
            (sys::Cronet_RESULT_ILLEGAL_STATE, ResultCode::IllegalState),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_STORAGE_PATH_IN_USE,
                ResultCode::StoragePathInUse,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_CANNOT_SHUTDOWN_ENGINE_FROM_NETWORK_THREAD,
                ResultCode::ShutdownFromNetworkThread,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_ENGINE_ALREADY_STARTED,
                ResultCode::EngineAlreadyStarted,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_ALREADY_STARTED,
                ResultCode::RequestAlreadyStarted,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_NOT_INITIALIZED,
                ResultCode::RequestNotInitialized,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_ALREADY_INITIALIZED,
                ResultCode::RequestAlreadyInitialized,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_REQUEST_NOT_STARTED,
                ResultCode::RequestNotStarted,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_UNEXPECTED_REDIRECT,
                ResultCode::UnexpectedRedirect,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_UNEXPECTED_READ,
                ResultCode::UnexpectedRead,
            ),
            (
                sys::Cronet_RESULT_ILLEGAL_STATE_READ_FAILED,
                ResultCode::ReadFailed,
            ),
            (sys::Cronet_RESULT_NULL_POINTER, ResultCode::NullPointer),
            (
                sys::Cronet_RESULT_NULL_POINTER_HOSTNAME,
                ResultCode::NullHostname,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_SHA256_PINS,
                ResultCode::NullPins,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_EXPIRATION_DATE,
                ResultCode::NullExpirationDate,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_ENGINE,
                ResultCode::NullEngine,
            ),
            (sys::Cronet_RESULT_NULL_POINTER_URL, ResultCode::NullUrl),
            (
                sys::Cronet_RESULT_NULL_POINTER_CALLBACK,
                ResultCode::NullCallback,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_EXECUTOR,
                ResultCode::NullExecutor,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_METHOD,
                ResultCode::NullMethod,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_HEADER_NAME,
                ResultCode::NullHeaderName,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_HEADER_VALUE,
                ResultCode::NullHeaderValue,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_PARAMS,
                ResultCode::NullParams,
            ),
            (
                sys::Cronet_RESULT_NULL_POINTER_REQUEST_FINISHED_INFO_LISTENER_EXECUTOR,
                ResultCode::NullFinishedListenerExecutor,
            ),
        ];

        for (raw, expected) in cases {
            assert_eq!(ResultCode::from_raw(raw), Some(expected));
        }
    }

    #[test]
    fn maps_every_native_network_error_code() {
        let cases = [
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_CALLBACK,
                NetworkErrorCode::Callback,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_HOSTNAME_NOT_RESOLVED,
                NetworkErrorCode::HostnameNotResolved,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_INTERNET_DISCONNECTED,
                NetworkErrorCode::InternetDisconnected,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_NETWORK_CHANGED,
                NetworkErrorCode::NetworkChanged,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_TIMED_OUT,
                NetworkErrorCode::TimedOut,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_CLOSED,
                NetworkErrorCode::ConnectionClosed,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_TIMED_OUT,
                NetworkErrorCode::ConnectionTimedOut,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_REFUSED,
                NetworkErrorCode::ConnectionRefused,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_CONNECTION_RESET,
                NetworkErrorCode::ConnectionReset,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_ADDRESS_UNREACHABLE,
                NetworkErrorCode::AddressUnreachable,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_QUIC_PROTOCOL_FAILED,
                NetworkErrorCode::QuicProtocolFailed,
            ),
            (
                sys::Cronet_Error_ERROR_CODE_ERROR_OTHER,
                NetworkErrorCode::Other,
            ),
        ];

        for (raw, expected) in cases {
            assert_eq!(NetworkErrorCode::from_raw(raw), expected);
        }
        assert_eq!(
            NetworkErrorCode::from_raw(999),
            NetworkErrorCode::Unknown(999)
        );
    }
}