fastly 0.6.0

Fastly Compute@Edge API
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
pub use fastly_shared::CacheOverride;

use crate::abi::{self, MultiValueHostcallError};
use crate::backend::{Backend, BackendError};
use crate::body::{Body, BodyHandle, StreamingBody};
use crate::error::{ensure, BufferSizeError, Error};
use crate::response::{handles_to_response, FastlyResponseMetadata};
use http::header::HeaderValue;
use http::{Extensions, Request, Response};
use lazy_static::lazy_static;
use std::convert::TryInto;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use thiserror::Error;

pub use handle::{downstream_request_and_body_handles, RequestHandle};
pub use pending::{
    select, select_handles, PendingRequest, PendingRequestHandle, PollHandleResult, PollResult,
};

#[macro_use]
mod macros;

mod handle;
mod pending;

/// Get the downstream request.
///
/// This may be called exactly once per execution, otherwise this function will panic.
//
// ACF 2019-11-27: this is a standalone function rather than a method on `RequestExt` because it has
// no receiver to help resolve `T: AsRef<[u8]>`
pub fn downstream_request() -> Request<Body> {
    let (req_handle, body_handle) = downstream_request_and_body_handles();

    let mut req = Request::builder()
        .version(req_handle.get_version())
        .method(
            req_handle
                .get_method(crate::METHOD_MAX_LEN)
                .expect("downstream request HTTP method too large"),
        )
        .uri(
            req_handle
                .get_uri(crate::URI_MAX_LEN)
                .expect("downstream request URI too large"),
        );

    for name in req_handle.get_header_names(crate::HEADER_NAME_MAX_LEN) {
        let name = name.expect("request header names too large");
        for value in req_handle.get_header_values(&name, crate::HEADER_VALUE_MAX_LEN) {
            let value = value.expect("downstream request header values too large");
            req = req.header(&name, value);
        }
    }

    req.body(body_handle.into())
        .expect("downstream request must be valid")
}

/// Get the IP address of the downstream client, if it is known.
pub fn downstream_client_ip_addr() -> Option<IpAddr> {
    let mut octets = [0; 16];
    let mut nwritten = 0;

    let status = unsafe {
        abi::fastly_http_req::downstream_client_ip_addr(octets.as_mut_ptr(), &mut nwritten)
    };
    if status.is_err() {
        panic!("downstream_client_ip_addr failed");
    }
    match nwritten {
        0 => None,
        4 => {
            let octets: [u8; 4] = octets[0..4]
                .try_into()
                .expect("octets is at least 4 bytes long");
            let addr: Ipv4Addr = octets.into();
            Some(addr.into())
        }
        16 => {
            let addr: Ipv6Addr = octets.into();
            Some(addr.into())
        }
        _ => panic!("downstream_client_ip_addr wrote an unexpected number of bytes"),
    }
}

/// Get the raw bytes sent by the client in the ClientHello message
///
/// https://tools.ietf.org/html/rfc5246#section-7.4.1.2
pub fn downstream_tls_client_hello() -> Result<Vec<u8>, Error> {
    let mut ch_size = 0;
    let status = unsafe {
        abi::fastly_http_req::downstream_tls_client_hello(std::ptr::null_mut(), 0, &mut ch_size)
    };
    if status.is_err() && ch_size == 0 {
        panic!("couldn't get the downstream TLS client hello");
    }
    let mut buf = vec![0; ch_size];
    let status = unsafe {
        abi::fastly_http_req::downstream_tls_client_hello(buf.as_mut_ptr(), buf.len(), &mut ch_size)
    };
    if status.is_err() {
        panic!("couldn't get the downstream TLS cipher protocol");
    }
    Ok(buf)
}

/// Get the cipher suite used to secure the downstream client TLS connection.
///
/// The value returned will be consistent with the [OpenSSL name][openssl-mapping] for the cipher
/// suite, for example:
///
/// ```no_run
/// # use fastly::request::downstream_tls_cipher_openssl_name;
/// assert_eq!(downstream_tls_cipher_openssl_name(), "ECDHE-RSA-AES128-GCM-SHA256");
/// ```
///
/// [openssl-mapping]: https://testssl.sh/openssl-iana.mapping.html
pub fn downstream_tls_cipher_openssl_name() -> &'static str {
    lazy_static! {
        static ref OPENSSL_NAME: String = {
            // 3x bigger than any of the cipher suite names in OpenSSL today
            let mut buf = vec![0; 128];
            let mut nwritten = 0;
            let status = unsafe {
                abi::fastly_http_req::downstream_tls_cipher_openssl_name(
                    buf.as_mut_ptr(),
                    buf.len(),
                    &mut nwritten,
                )
            };
            if status.is_err() {
                panic!("couldn't get the downstream TLS cipher's OpenSSL name");
            }
            buf.truncate(nwritten);
            String::from_utf8(buf).expect("TLS cipher OpenSSL name must be valid UTF-8")
        };
    }

    OPENSSL_NAME.as_str()
}

/// Get the TLS protocol version used to secure the downstream client TLS connection.
///
/// ```no_run
/// # use fastly::request::downstream_tls_protocol;
/// assert_eq!(downstream_tls_protocol(), "TLSv1.2");
/// ```
pub fn downstream_tls_protocol() -> &'static str {
    lazy_static! {
        static ref PROTOCOL: String = {
            let mut buf = vec![0; 32];
            let mut nwritten = 0;
            let status = unsafe {
                abi::fastly_http_req::downstream_tls_protocol(
                    buf.as_mut_ptr(),
                    buf.len(),
                    &mut nwritten,
                )
            };
            if status.is_err() {
                panic!("couldn't get the downstream TLS cipher protocol");
            }
            buf.truncate(nwritten);
            String::from_utf8(buf).expect("TLS protocol must be valid UTF-8")
        };
    }

    PROTOCOL.as_str()
}

/// Returns a request's header names list as originally received, in the original order they
/// were received in.
///
/// In comparison to [`downstream_original_header_names`][no-len], this function accepts a manually
/// configurable buffer size.
///
/// If there is a header name that is longer than the provided buffer, this will return a
/// [`BufferSizeError`][buf-err]; you can retry with a larger buffer size if necessary.
///
/// [buf-err]: ../fastly/error/enum.BufferSizeError.html
/// [no-len]: fn.downstream_original_header_names.html
pub fn downstream_original_header_names_with_len(
    buf_size: usize,
) -> impl Iterator<Item = Result<String, BufferSizeError>> {
    abi::MultiValueHostcall::new(
        b'\0',
        buf_size,
        move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
            abi::fastly_http_req::original_header_names_get(
                buf,
                buf_size,
                cursor,
                ending_cursor,
                nwritten,
            )
        },
    )
    .map(move |res| {
        use MultiValueHostcallError::{BufferTooSmall, ClosureError};
        match res {
            // we trust that the hostcall is giving us valid header bytes
            Ok(name_bytes) => Ok(String::from_utf8(name_bytes.to_vec()).unwrap()),
            // return an error if the buffer was not large enough
            Err(BufferTooSmall) => Err(BufferSizeError::new(buf_size)),
            // panic if the hostcall failed for some other reason
            Err(ClosureError(e)) => {
                panic!("fastly_http_req::header_values_get returned error: {:?}", e)
            }
        }
    })
}

/// Returns a request's header names list as originally received, in the original order they
/// were received in.
pub fn downstream_original_header_names() -> impl Iterator<Item = Result<String, BufferSizeError>> {
    downstream_original_header_names_with_len(crate::HEADER_NAME_MAX_LEN)
}

/// Returns the number of headers from the downstream request, as originally received.
pub fn downstream_original_header_count() -> u32 {
    let mut count = 0;
    let status = unsafe { abi::fastly_http_req::original_header_count(&mut count) };
    if status.is_err() || count == 0 {
        panic!("downstream_original_header_count failed")
    }
    count
}

/// An error that occurred while sending a request.
///
/// In practice this error should arise very rarely, usually due to a misconfigured request. Most
/// errors that arise during the actual connection to the backend will be returned as `Ok` values
/// with a 5xx status code response.
///
/// While the body of a request is always consumed when sent, you can recover the headers and other
/// request metadata of the request that failed using `SendError::into_sent_req()`.
#[derive(Debug, Error)]
#[error("error sending request: {error} to backend {backend}")]
pub struct SendError {
    backend: String,
    sent_req: Request<()>,
    #[source]
    error: Error,
}

impl SendError {
    fn new<T>(backend: impl Into<String>, req: Request<T>, error: impl Into<Error>) -> Self {
        SendError {
            backend: backend.into(),
            sent_req: req.map(|_| ()),
            error: error.into(),
        }
    }

    /// Create a `SendError` from a `FastlyResponseMetadata` and an underlying error.
    ///
    /// Panics if the metadata does not contain a backend and a sent request. This should only be
    /// called in contexts where those are guaranteed to be present, like the metadata from a
    /// `PendingRequest`.
    fn from_resp_metadata(mut metadata: FastlyResponseMetadata, error: impl Into<Error>) -> Self {
        let sent_req = metadata.take_sent_req().expect("sent_req must be present");
        let backend_name = metadata.backend().expect("backend must be present").name();
        Self::new(backend_name, sent_req, error)
    }

    /// Create a `SendError` from a `PendingRequest` and an underlying error.
    fn from_pending_req(pending_req: PendingRequest, error: impl Into<Error>) -> Self {
        Self::from_resp_metadata(pending_req.metadata, error)
    }

    /// Get the name of the backend that returned this error.
    pub fn backend_name(&self) -> &str {
        self.backend.as_str()
    }

    /// Convert the error back into the request that was originally sent.
    ///
    /// Since the original request's body is consumed by sending it, the body in the returned
    /// request is empty (represented by `()`). To add a new body to the request, use
    /// `Request::map()`, for example:
    ///
    /// ```no_run
    /// # use fastly::{Body, Error, Request, RequestExt};
    /// # fn f(bereq: Request<Body>) -> Result<(), Error> {
    /// if let Err(e) = bereq.send("my_backend") {
    ///     let new_body = Body::from("something new");
    ///     let new_req = e.into_sent_req().map(|()| new_body);
    ///     new_req.send("my_other_backend")?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_sent_req(self) -> Request<()> {
        self.sent_req
    }
}

/// A Fastly-specific extension trait for [`Request`]s.
///
/// This is most commonly used to [`send`] a request to a backend associated with a Compute@Edge
/// service.
///
/// [`Request`]: https://docs.rs/http/latest/http/request/struct.Request.html
/// [`send`]: trait.RequestExt.html#method.send
pub trait RequestExt: Sized {
    /// Send a request via the given backend, returning as soon as the headers are available.
    fn send(self, backend: &str) -> Result<Response<Body>, SendError> {
        self.inner_to_body().send(backend)
    }

    /// Send a request asynchronously via the given backend, returning as soon as the request has
    /// begun sending.
    ///
    /// The resulting [`PendingRequest`](struct.PendingRequest.html) can be evaluated using
    /// [`PendingRequest::poll()`](struct.PendingRequest.html#method.poll),
    /// [`PendingRequest::wait()`](struct.PendingRequest.html#method.wait), or
    /// [`select`](fn.select.html). It can also be discarded if the request was sent for effects it
    /// might have, and the response is unimportant.
    fn send_async(self, backend: &str) -> Result<PendingRequest, SendError> {
        self.inner_to_body().send_async(backend)
    }

    /// Send a request asynchronously via the given backend, and return a
    /// [`StreamingBody`][streaming-body] to allow continued writes to the request body.
    ///
    /// The resulting `StreamingBody` must be dropped in order to finish sending the request.
    ///
    /// [streaming-body]: ../body/struct.StreamingBody.html
    fn send_async_streaming(
        self,
        backend: &str,
    ) -> Result<(StreamingBody, PendingRequest), SendError> {
        self.inner_to_body().send_async_streaming(backend)
    }

    /// Replace the body of a request with a `Body` with the same contents.
    //
    // TODO ACF 2020-01-15: better name?
    fn inner_to_body(self) -> Request<Body>;

    /// Replace the body of a request with the remaining contents of its body.
    ///
    /// Note that this will involve copying and buffering the body, and so should only be used for
    /// convenience on small request bodies.
    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error>;

    /// Get a reference to the Fastly-specific metadata associated with this request.
    fn fastly_metadata(&self) -> &FastlyRequestMetadata;

    /// Get a mutable reference to the Fastly-specific metadata associated with this request.
    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata;

    /// Set the cache override behavior for this request.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous override calls on this request (e.g., `set_pass()`, `set_ttl()`).
    fn cache_override_mut(&mut self) -> &mut CacheOverride {
        &mut self.fastly_metadata_mut().cache_override
    }

    /// Get the cache override behavior for this request.
    fn cache_override(&self) -> &CacheOverride {
        &self.fastly_metadata().cache_override
    }

    /// Set the cache override behavior for this request to Pass.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this request to set the TTL or `stale-while-revalidate` time.
    fn set_pass(&mut self) {
        self.cache_override_mut().set_pass();
    }

    /// Set the cache override behavior for this request to use given TTL.
    ///
    /// This option can be combined with a `stale-while-revalidate` override.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this request to set Pass.
    fn set_ttl(&mut self, ttl: u32) {
        self.cache_override_mut().set_ttl(ttl);
    }

    /// Set the cache override behavior for this request to use given `stale-while-revalidate` time.
    ///
    /// This option can be combined with a TTL override.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this request to set Pass.
    fn set_stale_while_revalidate(&mut self, swr: u32) {
        self.cache_override_mut().set_stale_while_revalidate(swr);
    }

    /// Set the cache override behavior for this request to enable or disable PCI/HIPAA
    /// non-volatile caching.
    ///
    /// See the [Fastly documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery)
    /// for more information.
    ///
    /// This option may combined with TTL and `stale-while-revalidate` options.
    ///
    /// This will override any previous calls on this request to set Pass.
    fn set_pci(&mut self, pci: bool) {
        self.cache_override_mut().set_pci(pci);
    }

    /// Set a Surrogate-Key for a cached response.
    ///
    /// See the [Fastly documentation](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys)
    /// for more information on how Surrogate Keys can be used.
    ///
    /// This option may be combined with any other caching option.  This will override any previous
    /// calls on this request to set Pass.
    ///
    /// The keys implied here will be added to any Surrogate-Key response header from the origin.
    fn set_surrogate_key(&mut self, surrogate_key: HeaderValue) {
        self.cache_override_mut().set_surrogate_key(surrogate_key);
    }
}

/// A helperful function for decomposing a [`Request`][req] into handles for use in hostcalls.
///
/// Note that in addition to the [`RequestHandle`][req-handle] and [`BodyHandle`][body-handle],
/// the tuple returned also includes a copy of the original request so that metadata about
/// the request can be inspected later using the `FastlyResponseMetadata` extension.
///
/// This will return an error if the backend name is invalid, or if the request does not have a
/// valid URI.
///
/// [body-handle]: ../body/struct.BodyHandle.html
/// [parts]: https://docs.rs/http/latest/http/request/struct.Parts.html
/// [req]: https://docs.rs/http/latest/http/request/struct.Request.html
/// [req-handle]: struct.RequestHandle.html
fn prepare_handles(
    backend: &str,
    req: Request<Body>,
) -> Result<(RequestHandle, BodyHandle, Request<()>), SendError> {
    // First, validate the request.
    if let Err(e) = validate_request(&req) {
        return Err(SendError::new(backend, req, e));
    }
    let req_handle = {
        let mut req_handle = RequestHandle::new();
        // Set the handle's version, method, URI, and cache override using the request.
        req_handle.set_version(req.version());
        req_handle.set_method(req.method());
        req_handle.set_uri(req.uri());
        req_handle.set_cache_override(req.cache_override());
        for name in req.headers().keys() {
            // Copy the request's header values to the handle.
            req_handle.set_header_values(name, req.headers().get_all(name));
        }
        req_handle
    };
    let (body_handle, sent_req) = {
        let (parts, body) = req.into_parts();
        let body_handle = body.into_handle();
        let sent_req = Request::from_parts(parts, ());
        (body_handle, sent_req)
    };
    Ok((req_handle, body_handle, sent_req))
}

/// Check whether a request looks suitable for sending to a backend.
///
/// Note that this is *not* meant to be a filter for things that could cause security issues, it is
/// only meant to catch errors before the hostcalls do in order to yield friendlier error messages.
fn validate_request(req: &Request<Body>) -> Result<(), Error> {
    ensure!(
        req.uri().scheme().is_some() && req.uri().authority().is_some(),
        "request URIs must have a scheme (http/https) and an authority (host)"
    );
    Ok(())
}

fn get_or_default_metadata(exts: &Extensions) -> &FastlyRequestMetadata {
    static DEFAULT: FastlyRequestMetadata = FastlyRequestMetadata::default();

    if let Some(md) = exts.get::<FastlyRequestMetadata>() {
        md
    } else {
        &DEFAULT
    }
}

fn get_or_insert_metadata(exts: &mut Extensions) -> &mut FastlyRequestMetadata {
    if exts.get::<FastlyRequestMetadata>().is_none() {
        exts.insert(FastlyRequestMetadata::default());
    }
    exts.get_mut::<FastlyRequestMetadata>().unwrap()
}

impl RequestExt for Request<Body> {
    fn send(self, backend: &str) -> Result<Response<Body>, SendError> {
        let backend = try_with_req!(backend, self, backend.parse::<Backend>());
        let (req_handle, req_body_handle, sent_req) = prepare_handles(backend.name(), self)?;
        let (resp_handle, resp_body_handle) = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send(req_body_handle, backend.name())
        );
        Ok(handles_to_response(
            resp_handle,
            resp_body_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        ))
    }

    fn send_async(self, backend: &str) -> Result<PendingRequest, SendError> {
        let backend = try_with_req!(backend, self, backend.parse::<Backend>());
        let (req_handle, req_body_handle, sent_req) = prepare_handles(backend.name(), self)?;
        let pending_req_handle = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send_async(req_body_handle, backend.name())
        );
        let pending_req = PendingRequest::new(
            pending_req_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        );
        Ok(pending_req)
    }

    fn send_async_streaming(
        self,
        backend: &str,
    ) -> Result<(StreamingBody, PendingRequest), SendError> {
        let backend = try_with_req!(backend, self, backend.parse::<Backend>());
        let (req_handle, req_body_handle, sent_req) = prepare_handles(backend.name(), self)?;
        let (streaming_body_handle, pending_req_handle) = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send_async_streaming(req_body_handle, backend.name())
        );
        let pending_req = PendingRequest::new(
            pending_req_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        );
        Ok((streaming_body_handle.into(), pending_req))
    }

    fn inner_to_body(self) -> Request<Body> {
        self
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        let (parts, body) = self.into_parts();
        Ok(Request::from_parts(parts, body.into_bytes()))
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

impl RequestExt for Request<&[u8]> {
    fn inner_to_body(self) -> Request<Body> {
        self.map(Body::from)
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        Ok(self.map(|b| b.to_vec()))
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

impl RequestExt for Request<Vec<u8>> {
    fn inner_to_body(self) -> Request<Body> {
        self.map(Body::from)
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        Ok(self)
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

impl RequestExt for Request<&str> {
    fn inner_to_body(self) -> Request<Body> {
        self.map(Body::from)
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        Ok(self.map(|b| b.as_bytes().to_vec()))
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

impl RequestExt for Request<String> {
    fn inner_to_body(self) -> Request<Body> {
        self.map(Body::from)
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        Ok(self.map(|b| b.into_bytes()))
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

impl RequestExt for Request<()> {
    fn inner_to_body(self) -> Request<Body> {
        self.map(|_| Body::new())
    }

    fn inner_to_bytes(self) -> Result<Request<Vec<u8>>, Error> {
        Ok(self.map(|_| vec![]))
    }

    fn fastly_metadata(&self) -> &FastlyRequestMetadata {
        get_or_default_metadata(self.extensions())
    }

    fn fastly_metadata_mut(&mut self) -> &mut FastlyRequestMetadata {
        get_or_insert_metadata(self.extensions_mut())
    }
}

/// Additional Fastly-specific metadata for requests.
#[derive(Debug)]
pub struct FastlyRequestMetadata {
    backend: Option<Backend>,
    cache_override: CacheOverride,
}

impl FastlyRequestMetadata {
    /// Create a new `FastlyRequestMetadata` with default settings.
    pub const fn default() -> Self {
        Self {
            backend: None,
            cache_override: CacheOverride::default(),
        }
    }

    /// Get a reference to the destination `Backend` of this request, if one exists.
    pub fn backend(&self) -> &Option<Backend> {
        &self.backend
    }

    /// Get a mutable reference to the destination `Backend` of this request, if one exists.
    pub fn backend_mut(&mut self) -> &mut Option<Backend> {
        &mut self.backend
    }

    /// Get a reference to the `CacheOverride` of this request.
    pub fn cache_override(&self) -> &CacheOverride {
        &self.cache_override
    }

    /// Get a mutable reference to the `CacheOverride` of this request.
    pub fn cache_override_mut(&mut self) -> &mut CacheOverride {
        &mut self.cache_override
    }
}

/// Fastly-specific extensions to [`http::request::Builder`][Builder].
///
/// [Builder]: https://docs.rs/http/latest/http/request/struct.Builder.html
pub trait RequestBuilderExt: Sized {
    /// Get a reference to the Fastly-specific metadata associated with this request.
    ///
    /// Returns `None` if this builder has an error.
    fn fastly_metadata_ref(&self) -> Option<&FastlyRequestMetadata>;

    /// Get a mutable reference to the Fastly-specific metadata associated with this request.
    ///
    /// Returns `None` if this builder has an error.
    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyRequestMetadata>;

    /// Set the associated [`Backend`][backend] that this request will be sent to.
    ///
    /// This will return an error if the given backend name was not valid.
    ///
    /// [backend]: ../backend/struct.Backend.html
    fn backend(mut self, backend: impl AsRef<str>) -> Result<Self, BackendError> {
        let backend = backend.as_ref().parse()?;
        self.fastly_metadata_mut()
            .map(|md| md.backend = Some(backend));
        Ok(self)
    }

    /// Get a reference to the [`Backend`][backend] that this request will be sent to.
    ///
    /// [backend]: ../backend/struct.Backend.html
    fn backend_ref(&self) -> Option<&Backend> {
        self.fastly_metadata_ref()
            .and_then(|md| md.backend.as_ref())
    }

    /// Get a mutable reference to the [`Backend`][backend] that this request will be sent to.
    ///
    /// [backend]: ../backend/struct.Backend.html
    fn backend_mut(&mut self) -> Option<&mut Backend> {
        self.fastly_metadata_mut()
            .and_then(|md| md.backend.as_mut())
    }

    /// Set the cache override behavior for this request.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous override calls on this builder (e.g., `pass()`, `ttl()`).
    fn cache_override(mut self, cache_override: CacheOverride) -> Self {
        self.fastly_metadata_mut()
            .map(|md| md.cache_override = cache_override);
        self
    }

    /// Get a reference to the cache override behavior for this request.
    ///
    /// Returns `None` if this builder has an error.
    fn cache_override_ref(&self) -> Option<&CacheOverride> {
        self.fastly_metadata_ref().map(|md| &md.cache_override)
    }

    /// Get a mutable reference to the cache override behavior for this request.
    ///
    /// Returns `None` if this builder has an error.
    fn cache_override_mut(&mut self) -> Option<&mut CacheOverride> {
        self.fastly_metadata_mut().map(|md| &mut md.cache_override)
    }

    /// Set the cache override behavior for this request to Pass.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this builder to set the TTL or `stale-while-revalidate` time.
    fn pass(mut self) -> Self {
        self.cache_override_mut().map(|co| co.set_pass());
        self
    }

    /// Set the cache override behavior for this request to use given TTL.
    ///
    /// This option can be combined with a `stale-while-revalidate` override.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this builder to set Pass.
    fn ttl(mut self, ttl: u32) -> Self {
        self.cache_override_mut().map(|co| co.set_ttl(ttl));
        self
    }

    /// Set the cache override behavior for this request to use given `stale-while-revalidate` time.
    ///
    /// This option can be combined with a TTL override.
    ///
    /// This will override the behavior defined by the backend response headers, as well as any
    /// previous calls on this builder to set Pass.
    fn stale_while_revalidate(mut self, swr: u32) -> Self {
        self.cache_override_mut()
            .map(|co| co.set_stale_while_revalidate(swr));
        self
    }

    /// Set the cache override behavior for this request to enable PCI/HIPAA non-volatile storage
    /// caching.
    ///
    /// See the [Fastly documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery)
    /// for more information.
    fn pci(mut self, pci: bool) -> Self {
        self.cache_override_mut().map(|co| co.set_pci(pci));
        self
    }

    /// Set a Surrogate-Key header value, holding potentially a number of surrogate keys, to be
    /// attached to the cached response. If the response from origin had a Surrogate-Key response,
    /// these keys will be added to them.
    ///
    /// See the [Fastly documentation](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys)
    /// for more information on how Surrogate Keys can be used.
    fn surrogate_key(mut self, surrogate_key: HeaderValue) -> Self {
        self.cache_override_mut()
            .map(|co| co.set_surrogate_key(surrogate_key));
        self
    }
}

impl RequestBuilderExt for http::request::Builder {
    fn fastly_metadata_ref(&self) -> Option<&FastlyRequestMetadata> {
        self.extensions_ref().map(get_or_default_metadata)
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyRequestMetadata> {
        self.extensions_mut().map(get_or_insert_metadata)
    }
}