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
use crate::abi::{self, MultiValueHostcallError, XqdStatus};
use crate::backend::Backend;
use crate::body::{Body, BodyHandle, StreamingBody, StreamingBodyHandle};
use crate::error::BufferSizeError;
use bytes::{BufMut, BytesMut};
use http::header::{HeaderName, HeaderValue};
use http::{Request, Response, StatusCode, Version};
use std::convert::TryFrom;
use std::io::Write;

/// A low-level interface to HTTP responses.
///
/// A response handle can be immediately sent downstream to the client using
/// [`send_downstream`], or streamed back to the client with [`send_downstream_streaming`], given
/// a [`BodyHandle`].
///
/// [`send_downstream`]: struct.ResponseHandle.html#method.send_downstream
/// [`send_downstream_streaming`]: struct.ResponseHandle.html#method.send_downstream
/// [`BodyHandle`]: ../body/struct.BodyHandle.html
#[derive(Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct ResponseHandle {
    pub(crate) handle: u32,
}

impl ResponseHandle {
    /// An invalid handle.
    pub const INVALID: Self = ResponseHandle {
        handle: fastly_shared::INVALID_RESPONSE_HANDLE,
    };

    /// Return true if the response handle is valid.
    pub fn is_valid(&self) -> bool {
        !self.is_invalid()
    }

    /// Return true if the response handle is invalid.
    pub fn is_invalid(&self) -> bool {
        self.handle == Self::INVALID.handle
    }

    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    pub(crate) fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Get a mutable reference to the underlying `u32` representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    pub(crate) fn as_u32_mut(&mut self) -> &mut u32 {
        &mut self.handle
    }

    /// Acquire a new response handle.
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let mut handle = ResponseHandle::INVALID;
        let status = unsafe { abi::xqd_resp_new(handle.as_u32_mut()) };
        match status.result().map(|_| handle) {
            Ok(h) if h.is_valid() => h,
            _ => panic!("xqd_resp_new failed"),
        }
    }

    /// Read a response's header names via a buffer of the provided 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]: ../error/struct.BufferSizeError.html
    pub fn get_header_names<'a>(
        &'a self,
        max_len: usize,
    ) -> impl Iterator<Item = Result<HeaderName, BufferSizeError>> + 'a {
        abi::MultiValueHostcall::new(
            b'\0',
            max_len,
            move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
                abi::xqd_resp_header_names_get(
                    self.as_u32(),
                    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(HeaderName::from_bytes(&name_bytes).unwrap()),
                // return an error if the buffer was not large enough
                Err(BufferTooSmall) => Err(BufferSizeError::new(max_len)),
                // panic if the hostcall failed for some other reason
                Err(ClosureError(e)) => panic!("xqd_resp_header_names_get returned error: {:?}", e),
            }
        })
    }

    /// Get a response's header values given a header name, via a buffer of the provided size.
    ///
    /// If there is a header value that is longer than the provided buffer, this will return a
    /// [`BufferSizeError`][buf-err]; you can retry with a larger buffer size if necessary.
    ///
    /// ### Examples
    ///
    /// Collect all the header values into a `Vec`:
    ///
    /// ```no_run
    /// # use fastly::error::Error;
    /// # use fastly::response::ResponseHandle;
    /// # use http::header::{HeaderName, HeaderValue};
    /// #
    /// # fn main() -> Result<(), Error> {
    /// # let response = ResponseHandle::new();
    /// let name = HeaderName::from_static("My-App-Header");
    /// let buf_size = 128;
    /// let header_values: Vec<HeaderValue> = response
    ///     .get_header_values(&name, buf_size)
    ///     .collect::<Result<Vec<HeaderValue>, _>>()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// To try again with a larger buffer if the first call fails, you can use
    /// [`unwrap_or_else`][unwrap]:
    ///
    /// ```no_run
    /// # use fastly::error::BufferSizeError;
    /// # use fastly::response::ResponseHandle;
    /// # use http::header::{HeaderName, HeaderValue};
    /// # let response = ResponseHandle::new();
    /// let name = HeaderName::from_static("My-App-Header");
    /// let buf_size = 128;
    ///
    /// // Collect header values into a `Vec<HeaderValue>`, with a buffer size of `128`.
    /// // If the first call fails, print our error and then try to collect header values
    /// // again. The second call will use a larger buffer size of `1024`.
    /// let header_values: Vec<HeaderValue> = response
    ///     .get_header_values(&name, buf_size)
    ///     .collect::<Result<_, _>>()
    ///     .unwrap_or_else(|err: BufferSizeError| {
    ///         eprintln!("buffer size error: {}", err);
    ///         let larger_buf_size = 1024;
    ///         response
    ///             .get_header_values(&name, larger_buf_size)
    ///             .collect::<Result<_, _>>()
    ///             .unwrap()
    ///     });
    /// ```
    ///
    /// [buf-err]: ../error/struct.BufferSizeError.html
    /// [unwrap]: https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or_else
    pub fn get_header_values<'a>(
        &'a self,
        name: &'a HeaderName,
        max_len: usize,
    ) -> impl Iterator<Item = Result<HeaderValue, BufferSizeError>> + 'a {
        abi::MultiValueHostcall::new(
            b'\0',
            max_len,
            move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
                let name: &[u8] = name.as_ref();
                abi::xqd_resp_header_values_get(
                    self.as_u32(),
                    name.as_ptr(),
                    name.len(),
                    buf,
                    buf_size,
                    cursor,
                    ending_cursor,
                    nwritten,
                )
            },
        )
        .map(move |res| {
            use MultiValueHostcallError::{BufferTooSmall, ClosureError};
            match res {
                Ok(value_bytes) => {
                    let header_value =
                        unsafe { HeaderValue::from_maybe_shared_unchecked(value_bytes) };
                    Ok(header_value)
                }
                Err(BufferTooSmall) => Err(BufferSizeError::new(max_len)),
                Err(ClosureError(e)) => {
                    panic!("xqd_resp_header_values_get returned error: {:?}", e)
                }
            }
        })
    }

    /// Set a response's header values given a header name and a collection of header values.
    pub fn set_header_values<'a, I>(&mut self, name: &HeaderName, values: I)
    where
        I: IntoIterator<Item = &'a HeaderValue>,
    {
        // build a buffer of all the values, each terminated by a nul byte
        let mut buf = vec![];
        for value in values {
            buf.put(value.as_bytes());
            buf.put_u8(b'\0');
        }

        let name: &[u8] = name.as_ref();
        unsafe {
            abi::xqd_resp_header_values_set(
                self.as_u32(),
                name.as_ptr(),
                name.len(),
                buf.as_ptr(),
                buf.len(),
            )
        }
        .result()
        .expect("xqd_req_header_values_set failed");
    }

    /// Get a response's [`HeaderValue`][value], given the [`HeaderName`][name].
    ///
    /// If there are multiple values associated with the name, then the first one is returned.
    ///
    /// If the value is longer than the provided buffer, this will return a
    /// [`BufferSizeError`][buf-err]; you can retry with a larger buffer size if necessary.
    ///
    /// If no header exists with the given name, this function will return `Ok(None)`.
    ///
    /// [buf-err]: ../error/struct.BufferSizeError.html
    /// [name]: https://docs.rs/http/latest/http/header/struct.HeaderName.html
    /// [value]: https://docs.rs/http/latest/http/header/struct.HeaderValue.html
    pub fn get_header_value(
        &self,
        name: &HeaderName,
        max_len: usize,
    ) -> Result<Option<HeaderValue>, BufferSizeError> {
        let name: &[u8] = name.as_ref();
        let mut buf = BytesMut::with_capacity(max_len);
        let mut nwritten = 0;
        let status = unsafe {
            abi::xqd_resp_header_value_get(
                self.as_u32(),
                name.as_ptr(),
                name.len(),
                buf.as_mut_ptr(),
                buf.capacity(),
                &mut nwritten,
            )
        };
        match status.result().map(|_| nwritten) {
            Ok(nwritten) => {
                assert!(nwritten <= buf.capacity(), "hostcall wrote too many bytes");
                unsafe {
                    buf.set_len(nwritten);
                }
                // we trust that the hostcall is giving us valid header bytes
                let value = HeaderValue::from_bytes(&buf).expect("bytes from host are valid");
                Ok(Some(value))
            }
            Err(XqdStatus::INVAL) => Ok(None),
            Err(XqdStatus::BUFLEN) => Err(BufferSizeError::new(max_len)),
            _ => panic!("xqd_resp_header_value_get returned error"),
        }
    }

    /// Insert a new key-value pair into the response's headers.
    ///
    /// If this [`HeaderName`][name] key already existed in the response's headers, associated
    /// [`HeaderValue`][value]s will be overwritten. To preserve pre-existing values, use
    /// [`append_header`][append] instead.
    ///
    /// [append]: struct.ResponseHandle.html#method.append_header
    /// [name]: https://docs.rs/http/latest/http/header/struct.HeaderName.html
    /// [value]: https://docs.rs/http/latest/http/header/struct.HeaderValue.html
    pub fn insert_header(&mut self, name: &HeaderName, value: &HeaderValue) {
        let name_bytes: &[u8] = name.as_ref();
        let value_bytes: &[u8] = value.as_ref();
        unsafe {
            abi::xqd_resp_header_insert(
                self.as_u32(),
                name_bytes.as_ptr(),
                name_bytes.len(),
                value_bytes.as_ptr(),
                value_bytes.len(),
            )
        }
        .result()
        .expect("xqd_resp_header_insert returned error");
    }

    /// Append a new key-value pair to the response's headers.
    ///
    /// If this [`HeaderName`][name] key already existed in the response's headers, the new
    /// [`HeaderValue`][value]s will be added the end of the values associated with that key. To
    /// overwrite other pre-existing values, use [`insert_header`][insert] instead.
    ///
    /// [insert]: struct.ResponseHandle.html#method.insert_header
    /// [name]: https://docs.rs/http/latest/http/header/struct.HeaderName.html
    /// [value]: https://docs.rs/http/latest/http/header/struct.HeaderValue.html
    pub fn append_header(&mut self, name: &HeaderName, value: &HeaderValue) {
        let name_bytes: &[u8] = name.as_ref();
        let value_bytes: &[u8] = value.as_ref();
        unsafe {
            abi::xqd_resp_header_append(
                self.as_u32(),
                name_bytes.as_ptr(),
                name_bytes.len(),
                value_bytes.as_ptr(),
                value_bytes.len(),
            )
        }
        .result()
        .expect("xqd_resp_header_append returned error");
    }

    /// Remove a header from the response, returning `true` if it was formerly present or `false`
    /// otherwise.
    pub fn remove_header(&mut self, name: &HeaderName) -> bool {
        let name_bytes: &[u8] = name.as_ref();
        let status = unsafe {
            abi::xqd_resp_header_remove(self.as_u32(), name_bytes.as_ptr(), name_bytes.len())
        };
        match status.result() {
            Ok(_) => true,
            Err(XqdStatus::INVAL) => false,
            _ => panic!("xqd_req_header_remove returned error"),
        }
    }

    /// Set the response's
    /// [`StatusCode`](https://docs.rs/http/latest/http/status/struct.StatusCode.html).
    pub fn set_status(&mut self, status: StatusCode) {
        unsafe { abi::xqd_resp_status_set(self.as_u32(), status.as_u16()) }
            .result()
            .expect("xqd_resp_status_set returned error")
    }

    /// Get the response's
    /// [`StatusCode`](https://docs.rs/http/latest/http/status/struct.StatusCode.html).
    pub fn get_status(&self) -> StatusCode {
        let mut status = 0;
        let xqd_status = unsafe { abi::xqd_resp_status_get(self.as_u32(), &mut status) };
        match xqd_status.result().map(|_| status) {
            Ok(status) => StatusCode::from_u16(status).expect("invalid http status"),
            _ => panic!("xqd_resp_status_get failed"),
        }
    }

    /// Get the response's
    /// [`Version`](https://docs.rs/http/latest/http/version/struct.Version.html).
    pub fn get_version(&self) -> Version {
        let mut version = 0;
        let status = unsafe { abi::xqd_resp_version_get(self.as_u32(), &mut version) };
        if status.is_err() {
            panic!("xqd_resp_version_get failed");
        } else {
            abi::HttpVersion::try_from(version)
                .map(Into::into)
                .expect("invalid http version")
        }
    }

    /// Set the response's
    /// [`Version`](https://docs.rs/http/latest/http/version/struct.Version.html).
    pub fn set_version(&mut self, v: Version) {
        unsafe { abi::xqd_resp_version_set(self.as_u32(), abi::HttpVersion::from(v) as u32) }
            .result()
            .expect("xqd_req_version_get failed");
    }

    /// Immediately begin sending this response downstream to the client with the given body.
    pub fn send_downstream(self, body: BodyHandle) {
        unsafe { abi::xqd_resp_send_downstream(self.as_u32(), body.as_u32(), false as u32) }
            .result()
            .expect("xqd_resp_send_downstream failed");
    }

    /// Immediately begin sending this response downstream to the client, and return a
    /// `StreamingBodyHandle` that can accept further data to send.
    pub fn send_downstream_streaming(self, body: BodyHandle) -> StreamingBodyHandle {
        let streaming_body_handle = StreamingBodyHandle::from_body_handle(&body);
        let status =
            unsafe { abi::xqd_resp_send_downstream(self.as_u32(), body.as_u32(), true as u32) };
        status
            .result()
            .map(|_| streaming_body_handle)
            .expect("xqd_resp_send_downstream failed")
    }
}

pub(crate) fn handles_to_response(
    resp_handle: ResponseHandle,
    resp_body_handle: BodyHandle,
    metadata: FastlyResponseMetadata,
) -> Response<Body> {
    let mut resp = Response::builder()
        .status(resp_handle.get_status())
        .version(resp_handle.get_version())
        .extension(metadata);

    for name in resp_handle.get_header_names(crate::HEADER_NAME_MAX_LEN) {
        let name = name.expect("response header names too large");
        for value in resp_handle.get_header_values(&name, crate::HEADER_VALUE_MAX_LEN) {
            let value = value.expect("response header values too large");
            resp = resp.header(&name, value);
        }
    }

    resp.body(resp_body_handle.into())
        .expect("invalid response")
}

/// An extension trait for HTTP [`Response`]s.
///
/// This is used to send a response back downstream to a client that made a request.
///
/// [`Response`]: https://docs.rs/http/latest/http/response/struct.Response.html
pub trait ResponseExt: Sized {
    /// Send a response downstream to the client.
    fn send_downstream(self) {
        self.inner_to_body().send_downstream()
    }

    /// Begin streaming a response downstream, returning a
    /// [`StreamingBody`](struct.StreamingBody.html) that can be appended.
    fn send_downstream_streaming(self) -> StreamingBody {
        self.inner_to_body().send_downstream_streaming()
    }

    /// Replace the body of a response with a `Body` with the same contents.
    fn inner_to_body(self) -> Response<Body>;

    /// Replace the body of a response 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 response bodies.
    fn inner_to_bytes(self) -> Response<Vec<u8>>;

    /// Get a reference to the Fastly-specific metadata associated with this response.
    ///
    /// This method will return `None` if this response did not come from an origin server.
    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata>;

    /// Get a mutable reference to the Fastly-specific metadata associated with this response.
    ///
    /// This method will return `None` if this response did not come from an origin server.
    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata>;

    /// Get the `Backend` that this response came from, if this response came from a backend request.
    fn backend(&self) -> Option<&Backend> {
        self.fastly_metadata().and_then(|md| md.backend())
    }

    /// Get the request that this response came from, if this response came from a backend request.
    ///
    /// This method will return `None` if this response did not come from a backend, or the request
    /// has been taken by `backend_request_take()`.
    ///
    /// Since the original request's body is consumed by sending it, the body in this request is
    /// empty (represented by `()`).
    fn backend_request(&self) -> Option<&Request<()>> {
        self.fastly_metadata().and_then(|md| md.sent_req.as_ref())
    }

    /// Take the request that this response came from, if this response came from a backend request.
    ///
    /// This method will return `None` if this response did not come from a backend, or if the
    /// request has been previously taken.
    ///
    /// In contrast to `RequestExt::backend_request()`, this returns an owned `Request<()>`, which
    /// can be used to send another request to a backend.
    ///
    /// Since the original request's body is consumed by sending it, the body in this request is
    /// empty (represented by `()`). To add a new body to the request, use `Request::map()`, for
    /// example:
    ///
    /// ```no_run
    /// # use fastly::{Body, RequestExt, Response, ResponseExt, SendError};
    /// # fn f(mut beresp: Response<Body>) -> Result<impl ResponseExt, SendError> {
    /// let new_body = Body::from("something new");
    /// let new_req = beresp.take_backend_request().unwrap().map(|()| new_body);
    /// new_req.send("my_backend")
    /// # }
    /// ```
    fn take_backend_request(&mut self) -> Option<Request<()>> {
        self.fastly_metadata_mut().and_then(|md| md.sent_req.take())
    }
}

/// Send a response downstream.
///
/// This will return a [`StreamingBody`](struct.StreamingBody.html) if and only if `streaming` is
/// true. If a response has already been sent downstream, this function will panic.
fn send_downstream_impl(resp: Response<Body>, streaming: bool) -> Option<StreamingBody> {
    use std::sync::atomic::{AtomicBool, Ordering};

    /// A flag representing whether or not we have sent a response downstream.
    static SENT: AtomicBool = AtomicBool::new(false);

    // Set our sent flag, and panic if we have already sent a response.
    if SENT.swap(true, Ordering::SeqCst) {
        panic!("cannot send more than one downstream response per execution");
    }

    // Divide the response into parts.
    let (parts, body) = resp.into_parts();

    // Mint a response handle, and set the HTTP status code, version, and headers.
    let resp_handle = {
        let mut resp = ResponseHandle::new();
        resp.set_status(parts.status);
        resp.set_version(parts.version);
        for name in parts.headers.keys() {
            resp.set_header_values(name, parts.headers.get_all(name));
        }
        resp
    };

    // Send the response downstream using the appropriate method based on the `streaming` flag.
    if streaming {
        Some(
            resp_handle
                .send_downstream_streaming(body.into_handle())
                .into(),
        )
    } else {
        resp_handle.send_downstream(body.into_handle());
        None
    }
}

impl ResponseExt for Response<Body> {
    /// Immediately begin sending this response downstream to the client.
    fn send_downstream(self) {
        let res = send_downstream_impl(self, false);
        debug_assert!(res.is_none());
    }

    /// Immediately begin sending this response downstream to the client, and return a
    /// `StreamingBody` that can accept further data to send.
    fn send_downstream_streaming(self) -> StreamingBody {
        let res = send_downstream_impl(self, true);
        // streaming = true means we always get back a `Some`
        res.expect("streaming body is present")
    }

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

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

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

impl ResponseExt for Response<&[u8]> {
    fn inner_to_body(self) -> Response<Body> {
        let mut body = Body::new();
        body.write_all(self.body())
            .expect("xqd_body_write returned error");
        self.map(|_| body)
    }

    fn inner_to_bytes(self) -> Response<Vec<u8>> {
        self.map(|b| b.to_vec())
    }

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

impl ResponseExt for Response<Vec<u8>> {
    fn inner_to_body(self) -> Response<Body> {
        let mut body = Body::new();
        body.write_all(self.body())
            .expect("xqd_body_write returned error");
        self.map(|_| body)
    }

    fn inner_to_bytes(self) -> Response<Vec<u8>> {
        self
    }

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

impl ResponseExt for Response<&str> {
    fn inner_to_body(self) -> Response<Body> {
        let mut body = Body::new();
        body.write_all(self.body().as_bytes())
            .expect("xqd_body_write returned error");
        self.map(|_| body)
    }

    fn inner_to_bytes(self) -> Response<Vec<u8>> {
        self.map(|b| b.as_bytes().to_vec())
    }

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

impl ResponseExt for Response<String> {
    fn inner_to_body(self) -> Response<Body> {
        let mut body = Body::new();
        body.write_all(self.body().as_bytes())
            .expect("xqd_body_write returned error");
        self.map(|_| body)
    }

    fn inner_to_bytes(self) -> Response<Vec<u8>> {
        self.map(|b| b.into_bytes())
    }

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

impl ResponseExt for Response<()> {
    fn inner_to_body(self) -> Response<Body> {
        let body = Body::new();
        self.map(|_| body)
    }

    fn inner_to_bytes(self) -> Response<Vec<u8>> {
        self.map(|_| vec![])
    }

    fn fastly_metadata(&self) -> Option<&FastlyResponseMetadata> {
        self.extensions().get::<FastlyResponseMetadata>()
    }

    fn fastly_metadata_mut(&mut self) -> Option<&mut FastlyResponseMetadata> {
        self.extensions_mut().get_mut::<FastlyResponseMetadata>()
    }
}

/// Additional Fastly-specific metadata for responses.
pub struct FastlyResponseMetadata {
    backend: Backend,
    sent_req: Option<Request<()>>,
}

impl FastlyResponseMetadata {
    /// Create a response metadata object, given the request [`Parts`][parts] and the backend name.
    ///
    /// [parts]: https://docs.rs/http/latest/http/request/struct.Parts.html
    pub fn new<T>(backend: Backend, sent_req: Request<T>) -> Self {
        Self {
            backend,
            sent_req: Some(sent_req.map(|_| ())),
        }
    }

    /// Get a reference to the [`Backend`][backend] that this response came from.
    ///
    /// [backend]: backend/struct.Backend.html
    pub fn backend(&self) -> Option<&Backend> {
        // ACF 2020-06-17: this is wrapped in an option for future compatibility when we might have
        // `FastlyResponseMetadata`s on responses that didn't come from a backend
        Some(&self.backend)
    }

    /// Get a reference to the original [`Request`][req] associated with this [`Response`][resp].
    ///
    /// Note that the request's original body has already been sent, so this contains an empty `()`
    /// body.
    ///
    /// [req]: https://docs.rs/http/latest/http/request/struct.Request.html
    /// [resp]: https://docs.rs/http/latest/http/response/struct.Response.html
    pub fn sent_req(&self) -> Option<&Request<()>> {
        self.sent_req.as_ref()
    }

    pub(crate) fn take_sent_req(&mut self) -> Option<Request<()>> {
        self.sent_req.take()
    }
}