tilo-net 0.5.1

The network capability on Linux, macOS and the web: async HTTP with streaming bodies, WebSocket, WebTransport, network status, raw sockets on the desktop, and Tilo's one TLS provider and trust source.
Documentation
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! HTTP requests with streaming bodies, the same on every target.

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use ::http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT};
use ::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use bytes::{Bytes, BytesMut};
use url::Url;

use crate::NetError;
use crate::proxy::ProxyUse;

#[cfg(not(target_family = "wasm"))]
use crate::native::http as backend;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use crate::web::fetch as backend;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Redirects {
    /// Follow up to this many hops; a page stops at 20 whatever the limit.
    Follow(u8),
    /// Answer the redirect itself; a page cannot read redirect responses, so
    /// there the request fails with [`NetError::Redirect`].
    None,
}

impl Default for Redirects {
    fn default() -> Self {
        Self::Follow(10)
    }
}

#[derive(Clone, Debug, Default)]
pub(crate) struct Config {
    pub(crate) timeout: Option<Duration>,
    pub(crate) connect_timeout: Option<Duration>,
    pub(crate) default_headers: HeaderMap,
    pub(crate) redirects: Redirects,
    pub(crate) proxy: ProxyUse,
    #[cfg(not(target_family = "wasm"))]
    pub(crate) tls: Option<rustls::ClientConfig>,
    #[cfg(not(target_family = "wasm"))]
    pub(crate) lookup: Option<Looking>,
    #[cfg(not(target_family = "wasm"))]
    pub(crate) direct: bool,
}

/// Resolves a name to its addresses: what a [`Client`] built with
/// [`ClientBuilder::lookup`] dials for that name. It has the shape of the
/// fetch proxy's own lookup, so one value serves both.
#[cfg(not(target_family = "wasm"))]
pub type Lookup = Arc<
    dyn Fn(
            String,
        )
            -> std::pin::Pin<Box<dyn Future<Output = std::io::Result<Vec<std::net::IpAddr>>> + Send>>
        + Send
        + Sync,
>;

/// The [`Lookup`] a client was given, which has no `Debug` of its own.
#[cfg(not(target_family = "wasm"))]
#[derive(Clone)]
pub(crate) struct Looking(pub(crate) Lookup);

#[cfg(not(target_family = "wasm"))]
impl fmt::Debug for Looking {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Lookup")
    }
}

/// Why a [`Lookup`] would not have a name dialled, told apart from a lookup
/// that failed.
#[cfg(not(target_family = "wasm"))]
#[derive(Debug)]
pub(crate) struct RefusedLookup(pub(crate) String);

#[cfg(not(target_family = "wasm"))]
impl fmt::Display for RefusedLookup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(not(target_family = "wasm"))]
impl std::error::Error for RefusedLookup {}

/// What a [`Lookup`] answers for a name it refuses to have dialled, saying
/// `why`: the request the lookup was for is not sent and ends as
/// [`NetError::Blocked`], where a lookup that failed ends as a connection
/// that failed.
#[cfg(not(target_family = "wasm"))]
#[must_use]
pub fn refused_lookup(why: impl Into<String>) -> std::io::Error {
    std::io::Error::other(RefusedLookup(why.into()))
}

/// An HTTP client: a connection pool on the desktop, the page's `fetch` on
/// the web. Clones share the pool, and every request future is `Send`.
#[derive(Clone)]
pub struct Client {
    inner: Arc<Inner>,
}

struct Inner {
    config: Config,
    backend: backend::Backend,
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("config", &self.inner.config)
            .finish_non_exhaustive()
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

impl Client {
    #[must_use]
    pub fn new() -> Self {
        #[allow(
            clippy::expect_used,
            reason = "the default configuration has no invalid values"
        )]
        Self::builder()
            .build()
            .expect("the default HTTP client builds")
    }

    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    pub fn request(&self, method: Method, url: impl AsRef<str>) -> RequestBuilder {
        let request = Url::parse(url.as_ref())
            .map_err(|error| NetError::InvalidUrl(format!("{}: {error}", url.as_ref())))
            .and_then(|url| Request::checked(method, url));
        RequestBuilder {
            client: self.clone(),
            request,
        }
    }

    pub fn get(&self, url: impl AsRef<str>) -> RequestBuilder {
        self.request(Method::GET, url)
    }

    pub fn post(&self, url: impl AsRef<str>) -> RequestBuilder {
        self.request(Method::POST, url)
    }

    pub fn put(&self, url: impl AsRef<str>) -> RequestBuilder {
        self.request(Method::PUT, url)
    }

    pub fn delete(&self, url: impl AsRef<str>) -> RequestBuilder {
        self.request(Method::DELETE, url)
    }

    pub fn head(&self, url: impl AsRef<str>) -> RequestBuilder {
        self.request(Method::HEAD, url)
    }

    /// Sends the request and waits for the response head; the body streams
    /// through the [`Response`]. A 4xx or 5xx status is a successful response,
    /// not an error.
    pub fn send(
        &self,
        mut request: Request,
    ) -> impl Future<Output = Result<Response, NetError>> + Send + use<> {
        for (name, value) in &self.inner.config.default_headers {
            if !request.headers.contains_key(name) {
                request.headers.insert(name.clone(), value.clone());
            }
        }
        if request.proxy.is_none() {
            request.proxy = Some(self.inner.config.proxy);
        }
        if request.timeout.is_none() {
            request.timeout = self.inner.config.timeout;
        }
        let inner = Arc::clone(&self.inner);
        async move {
            let raw = inner.backend.send(&inner.config, request).await?;
            Ok(Response {
                status: raw.status,
                headers: raw.headers,
                url: raw.url,
                body: raw.body,
            })
        }
    }
}

#[derive(Clone, Debug, Default)]
#[must_use]
pub struct ClientBuilder {
    config: Config,
    error: Option<NetError>,
}

impl ClientBuilder {
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = Some(timeout);
        self
    }

    /// The longest establishing a connection may take; a page has no separate
    /// connection phase and applies only the overall timeout.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.config.connect_timeout = Some(timeout);
        self
    }

    /// The `User-Agent` header; a page sends the browser's own, except through
    /// the host's fetch proxy.
    pub fn user_agent(self, agent: impl AsRef<str>) -> Self {
        self.default_header(USER_AGENT, agent.as_ref())
    }

    pub fn default_header<K, V>(mut self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: fmt::Display,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: fmt::Display,
    {
        match header(name, value) {
            Ok((name, value)) => {
                self.config.default_headers.insert(name, value);
            }
            Err(error) => self.error = self.error.or(Some(error)),
        }
        self
    }

    pub fn redirects(mut self, redirects: Redirects) -> Self {
        self.config.redirects = redirects;
        self
    }

    /// Whether requests may go through the host's fetch [`proxy`](crate::proxy);
    /// off unless the app opts in.
    pub fn fetch_proxy(mut self, proxy: ProxyUse) -> Self {
        self.config.proxy = proxy;
        self
    }

    /// Verify servers with `tls` instead of the system's trust.
    #[cfg(not(target_family = "wasm"))]
    pub fn tls(mut self, mut tls: rustls::ClientConfig) -> Self {
        if tls.alpn_protocols.is_empty() {
            tls.alpn_protocols = vec![b"http/1.1".to_vec()];
        }
        self.config.tls = Some(tls);
        self
    }

    /// Dial, for every name, only the addresses `lookup` answers for it, in
    /// the one lookup the connection itself makes. A caller that keeps its
    /// requests off some addresses refuses them there ([`refused_lookup`]),
    /// and no second lookup can answer otherwise behind that check. An
    /// address written into the URL is not looked up, and a proxy taken from
    /// the environment resolves what is sent through it itself.
    #[cfg(not(target_family = "wasm"))]
    pub fn lookup(mut self, lookup: Lookup) -> Self {
        self.config.lookup = Some(Looking(lookup));
        self
    }

    /// Dial every address itself: take no proxy from the environment. A proxy
    /// resolves the names sent through it by a lookup of its own, behind the
    /// one [`Self::lookup`] judges. A caller no sandbox stands around, which
    /// must reach only what its own lookup answered, dials directly.
    #[cfg(not(target_family = "wasm"))]
    pub fn direct(mut self) -> Self {
        self.config.direct = true;
        self
    }

    pub fn build(self) -> Result<Client, NetError> {
        if let Some(error) = self.error {
            return Err(error);
        }
        let backend = backend::Backend::new(&self.config)?;
        Ok(Client {
            inner: Arc::new(Inner {
                config: self.config,
                backend,
            }),
        })
    }
}

fn header<K, V>(name: K, value: V) -> Result<(HeaderName, HeaderValue), NetError>
where
    HeaderName: TryFrom<K>,
    <HeaderName as TryFrom<K>>::Error: fmt::Display,
    HeaderValue: TryFrom<V>,
    <HeaderValue as TryFrom<V>>::Error: fmt::Display,
{
    let name = HeaderName::try_from(name)
        .map_err(|error| NetError::InvalidRequest(format!("header name: {error}")))?;
    let value = HeaderValue::try_from(value)
        .map_err(|error| NetError::InvalidRequest(format!("header {name}: {error}")))?;
    Ok((name, value))
}

#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Request {
    pub method: Method,
    pub url: Url,
    pub headers: HeaderMap,
    pub body: Option<Bytes>,
    pub timeout: Option<Duration>,
    pub proxy: Option<ProxyUse>,
}

impl Request {
    pub fn new(method: Method, url: Url) -> Result<Self, NetError> {
        Self::checked(method, url)
    }

    fn checked(method: Method, url: Url) -> Result<Self, NetError> {
        if !matches!(url.scheme(), "http" | "https") {
            return Err(NetError::InvalidUrl(format!(
                "{url}: only http and https URLs can be fetched"
            )));
        }
        Ok(Self {
            method,
            url,
            headers: HeaderMap::new(),
            body: None,
            timeout: None,
            proxy: None,
        })
    }
}

/// A request being assembled; [`send`](Self::send) reports any error made
/// while building it.
#[must_use = "a request does nothing until it is sent"]
pub struct RequestBuilder {
    client: Client,
    request: Result<Request, NetError>,
}

impl fmt::Debug for RequestBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestBuilder")
            .field("request", &self.request)
            .finish_non_exhaustive()
    }
}

impl RequestBuilder {
    fn map(mut self, change: impl FnOnce(&mut Request) -> Result<(), NetError>) -> Self {
        if let Ok(request) = &mut self.request
            && let Err(error) = change(request)
        {
            self.request = Err(error);
        }
        self
    }

    /// Adds a header; repeated names are all sent.
    pub fn header<K, V>(self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: fmt::Display,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: fmt::Display,
    {
        let parsed = header(name, value);
        self.map(|request| {
            let (name, value) = parsed?;
            request.headers.append(name, value);
            Ok(())
        })
    }

    pub fn headers(self, headers: HeaderMap) -> Self {
        self.map(|request| {
            let mut current = None;
            for (name, value) in headers {
                if name.is_some() {
                    current = name;
                }
                if let Some(name) = &current {
                    request.headers.append(name.clone(), value);
                }
            }
            Ok(())
        })
    }

    pub fn bearer_auth(self, token: impl fmt::Display) -> Self {
        self.sensitive_header(AUTHORIZATION, format!("Bearer {token}"))
    }

    pub fn basic_auth(self, user: impl fmt::Display, password: Option<impl fmt::Display>) -> Self {
        use base64::Engine as _;
        let credentials = match password {
            Some(password) => format!("{user}:{password}"),
            None => format!("{user}:"),
        };
        let encoded = base64::engine::general_purpose::STANDARD.encode(credentials);
        self.sensitive_header(AUTHORIZATION, format!("Basic {encoded}"))
    }

    fn sensitive_header(self, name: HeaderName, value: String) -> Self {
        self.map(|request| {
            let mut value = HeaderValue::try_from(value)
                .map_err(|error| NetError::InvalidRequest(format!("header {name}: {error}")))?;
            value.set_sensitive(true);
            request.headers.insert(name, value);
            Ok(())
        })
    }

    pub fn query<K: AsRef<str>, V: AsRef<str>>(self, pairs: &[(K, V)]) -> Self {
        self.map(|request| {
            request
                .url
                .query_pairs_mut()
                .extend_pairs(pairs.iter().map(|(k, v)| (k.as_ref(), v.as_ref())));
            Ok(())
        })
    }

    pub fn body(self, body: impl Into<Bytes>) -> Self {
        let body = body.into();
        self.map(|request| {
            request.body = Some(body);
            Ok(())
        })
    }

    pub fn form<K: AsRef<str>, V: AsRef<str>>(self, pairs: &[(K, V)]) -> Self {
        let encoded = url::form_urlencoded::Serializer::new(String::new())
            .extend_pairs(pairs.iter().map(|(k, v)| (k.as_ref(), v.as_ref())))
            .finish();
        self.map(|request| {
            request.headers.insert(
                CONTENT_TYPE,
                HeaderValue::from_static("application/x-www-form-urlencoded"),
            );
            request.body = Some(Bytes::from(encoded));
            Ok(())
        })
    }

    #[cfg(feature = "json")]
    pub fn json<T: serde::Serialize + ?Sized>(self, value: &T) -> Self {
        let encoded = serde_json::to_vec(value);
        self.map(|request| {
            let encoded = encoded.map_err(|error| NetError::InvalidRequest(error.to_string()))?;
            request
                .headers
                .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
            request.body = Some(Bytes::from(encoded));
            Ok(())
        })
    }

    pub fn timeout(self, timeout: Duration) -> Self {
        self.map(|request| {
            request.timeout = Some(timeout);
            Ok(())
        })
    }

    pub fn fetch_proxy(self, proxy: ProxyUse) -> Self {
        self.map(|request| {
            request.proxy = Some(proxy);
            Ok(())
        })
    }

    pub fn build(self) -> Result<Request, NetError> {
        self.request
    }

    pub fn send(self) -> impl Future<Output = Result<Response, NetError>> + Send + use<> {
        let sent = self.request.map(|request| self.client.send(request));
        async move { sent?.await }
    }
}

/// A response head; the body streams on demand.
pub struct Response {
    status: StatusCode,
    headers: HeaderMap,
    url: Url,
    body: backend::Body,
}

impl fmt::Debug for Response {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Response")
            .field("status", &self.status)
            .field("url", &self.url.as_str())
            .field("headers", &self.headers)
            .finish_non_exhaustive()
    }
}

impl Response {
    #[must_use]
    pub fn status(&self) -> StatusCode {
        self.status
    }

    #[must_use]
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    #[must_use]
    pub fn url(&self) -> &Url {
        &self.url
    }

    #[must_use]
    pub fn content_length(&self) -> Option<u64> {
        self.headers
            .get(CONTENT_LENGTH)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.trim().parse().ok())
    }

    pub fn error_for_status(self) -> Result<Self, NetError> {
        if self.status.is_client_error() || self.status.is_server_error() {
            Err(NetError::Status(self.status))
        } else {
            Ok(self)
        }
    }

    pub fn chunk(&mut self) -> impl Future<Output = Result<Option<Bytes>, NetError>> + Send + '_ {
        self.body.chunk()
    }

    pub async fn bytes(self) -> Result<Bytes, NetError> {
        self.bytes_limited(usize::MAX).await
    }

    pub async fn bytes_limited(mut self, limit: usize) -> Result<Bytes, NetError> {
        if let Some(declared) = self.content_length()
            && usize::try_from(declared).map_or(true, |declared| declared > limit)
        {
            return Err(NetError::TooLarge { limit });
        }
        let mut body = BytesMut::new();
        while let Some(chunk) = self.chunk().await? {
            if body.len().saturating_add(chunk.len()) > limit {
                return Err(NetError::TooLarge { limit });
            }
            body.extend_from_slice(&chunk);
        }
        Ok(body.freeze())
    }

    pub async fn text(self) -> Result<String, NetError> {
        let bytes = self.bytes().await?;
        Ok(String::from_utf8_lossy(&bytes).into_owned())
    }

    #[cfg(feature = "json")]
    pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, NetError> {
        let bytes = self.bytes().await?;
        serde_json::from_slice(&bytes).map_err(|error| NetError::Protocol(error.to_string()))
    }
}

pub(crate) struct RawResponse {
    pub(crate) status: StatusCode,
    pub(crate) headers: HeaderMap,
    pub(crate) url: Url,
    pub(crate) body: backend::Body,
}

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

    tilo_test_env::scenario! {
        fn a_request_builder_checks_and_assembles_its_request;

        phase only_http_urls_are_requests;
        {
            let client = Client::new();
            assert!(matches!(
                client.get("ftp://example.com/").build(),
                Err(NetError::InvalidUrl(_))
            ));
            assert!(matches!(
                client.get("not a url").build(),
                Err(NetError::InvalidUrl(_))
            ));
            assert!(client.get("https://example.com/").build().is_ok());
        }

        phase a_bad_header_surfaces_at_build;
        {
            let client = Client::new();
            let built = client
                .get("https://example.com/")
                .header("bad header", "x")
                .build();
            assert!(matches!(built, Err(NetError::InvalidRequest(_))));
        }

        phase builders_assemble_the_request;
        {
            let client = Client::new();
            let request = client
                .post("https://example.com/search")
                .query(&[("q", "a b")])
                .basic_auth("user", Some("pw"))
                .form(&[("k", "v&w")])
                .timeout(Duration::from_secs(3))
                .build()
                .unwrap();
            assert_eq!(request.url.as_str(), "https://example.com/search?q=a+b");
            assert_eq!(request.headers[AUTHORIZATION], "Basic dXNlcjpwdw==");
            assert!(request.headers[AUTHORIZATION].is_sensitive());
            assert_eq!(request.body.as_deref(), Some(&b"k=v%26w"[..]));
            assert_eq!(request.timeout, Some(Duration::from_secs(3)));
        }
    }
}