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
//! Experimental Compute features.
use crate::{
    abi::{self, FastlyStatus},
    convert::{ToHeaderName, ToHeaderValue},
    error::BufferSizeError,
    http::{
        header::{HeaderName, HeaderValue},
        request::{
            handle::{redirect_to_grip_proxy, redirect_to_websocket_proxy, RequestHandle},
            CacheKeyGen, Request, SendError, SendErrorCause,
        },
        response::assert_single_downstream_response_is_sent,
    },
    Backend, Error,
};
use anyhow::anyhow;
use fastly_sys::fastly_backend;
use http::header::HeaderMap;
use sha2::{Digest, Sha256};
use std::sync::Arc;

#[doc(inline)]
pub use fastly_sys::fastly_backend::BackendHealth;

pub use crate::backend::{BackendBuilder, BackendCreationError};

/// Parse a user agent string.
#[doc = include_str!("../docs/snippets/experimental.md")]
pub fn uap_parse(
    user_agent: &str,
) -> Result<(String, Option<String>, Option<String>, Option<String>), Error> {
    let user_agent: &[u8] = user_agent.as_ref();
    let max_length = 255;
    let mut family = Vec::with_capacity(max_length);
    let mut major = Vec::with_capacity(max_length);
    let mut minor = Vec::with_capacity(max_length);
    let mut patch = Vec::with_capacity(max_length);
    let mut family_nwritten = 0;
    let mut major_nwritten = 0;
    let mut minor_nwritten = 0;
    let mut patch_nwritten = 0;

    let status = unsafe {
        abi::fastly_uap::parse(
            user_agent.as_ptr(),
            user_agent.len(),
            family.as_mut_ptr(),
            family.capacity(),
            &mut family_nwritten,
            major.as_mut_ptr(),
            major.capacity(),
            &mut major_nwritten,
            minor.as_mut_ptr(),
            minor.capacity(),
            &mut minor_nwritten,
            patch.as_mut_ptr(),
            patch.capacity(),
            &mut patch_nwritten,
        )
    };
    if status.is_err() {
        return Err(Error::msg("fastly_uap::parse failed"));
    }
    assert!(
        family_nwritten <= family.capacity(),
        "fastly_uap::parse wrote too many bytes for family"
    );
    unsafe {
        family.set_len(family_nwritten);
    }
    assert!(
        major_nwritten <= major.capacity(),
        "fastly_uap::parse wrote too many bytes for major"
    );
    unsafe {
        major.set_len(major_nwritten);
    }
    assert!(
        minor_nwritten <= minor.capacity(),
        "fastly_uap::parse wrote too many bytes for minor"
    );
    unsafe {
        minor.set_len(minor_nwritten);
    }
    assert!(
        patch_nwritten <= patch.capacity(),
        "fastly_uap::parse wrote too many bytes for patch"
    );
    unsafe {
        patch.set_len(patch_nwritten);
    }
    Ok((
        String::from_utf8_lossy(&family).to_string(),
        Some(String::from_utf8_lossy(&major).to_string()),
        Some(String::from_utf8_lossy(&minor).to_string()),
        Some(String::from_utf8_lossy(&patch).to_string()),
    ))
}

/// An extension trait for [`Request`]s that adds methods for controlling cache keys.
#[doc = include_str!("../docs/snippets/experimental.md")]
pub trait RequestCacheKey {
    /// See [`Request::set_cache_key()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key(&mut self, key: [u8; 32]);
    /// See [`Request::with_cache_key()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key(self, key: [u8; 32]) -> Self;
    /// See [`Request::set_cache_key_fn()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key_fn(&mut self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static);
    /// See [`Request::with_cache_key_fn()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key_fn(self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static) -> Self;
    /// See [`Request::set_cache_key_str()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key_str(&mut self, key_str: impl AsRef<[u8]>);
    /// See [`Request::with_cache_key_str()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key_str(self, key_str: impl AsRef<[u8]>) -> Self;
}

impl RequestCacheKey for Request {
    /// Set the cache key to be used when attempting to satisfy this request from a cached response.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key(&mut self, key: [u8; 32]) {
        self.cache_key = Some(CacheKeyGen::Set(key));
    }

    /// Builder-style equivalent of [`set_cache_key()`](Self::set_cache_key()).
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key(mut self, key: [u8; 32]) -> Self {
        self.set_cache_key(key);
        self
    }

    /// Set the function that will be used to compute the cache key for this request.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key_fn(&mut self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static) {
        self.cache_key = Some(CacheKeyGen::Lazy(Arc::new(f)));
    }

    /// Builder-style equivalent of [`set_cache_key_fn()`](Self::set_cache_key_fn()).
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key_fn(
        mut self,
        f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static,
    ) -> Self {
        self.set_cache_key_fn(f);
        self
    }

    /// Set a string as the cache key to be used when attempting to satisfy this request from a
    /// cached response.
    ///
    /// The string representation of the key is hashed to the same `[u8; 32]` representation used by
    /// [`set_cache_key()`][`Self::set_cache_key()`].
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key_str(&mut self, key_str: impl AsRef<[u8]>) {
        let mut sha = Sha256::new();
        sha.update(key_str);
        sha.update(b"\x00\xf0\x9f\xa7\x82\x00"); // extra salt
        self.set_cache_key(*sha.finalize().as_ref())
    }

    /// Builder-style equivalent of [`set_cache_key_str()`](Self::set_cache_key_str()).
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn with_cache_key_str(mut self, key_str: impl AsRef<[u8]>) -> Self {
        self.set_cache_key_str(key_str);
        self
    }
}

/// An extension trait for [`RequestHandle`](RequestHandle)s that adds methods for controlling cache
/// keys.
#[doc = include_str!("../docs/snippets/experimental.md")]
pub trait RequestHandleCacheKey {
    /// See [`RequestHandle::set_cache_key()`](RequestHandle::set_cache_key).
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key(&mut self, key: &[u8; 32]);
}

impl RequestHandleCacheKey for RequestHandle {
    /// Set the cache key to be used when attempting to satisfy this request from a cached response.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn set_cache_key(&mut self, key: &[u8; 32]) {
        const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
        let mut hex = [0; 64];
        for (i, b) in key.iter().enumerate() {
            hex[i * 2] = DIGITS[(b >> 4) as usize];
            hex[i * 2 + 1] = DIGITS[(b & 0xf) as usize];
        }

        self.insert_header(
            &HeaderName::from_static("fastly-xqd-cache-key"),
            &HeaderValue::from_bytes(&hex).unwrap(),
        )
    }
}

/// An extension trait for [`Request`]s that adds a method for upgrading websockets.
pub trait RequestUpgradeWebsocket {
    /// See [`Request::handoff_websocket()`].
    fn handoff_websocket(self, backend: &str) -> Result<(), SendError>;

    /// See [`Request::handoff_fanout()`].
    fn handoff_fanout(self, backend: &str) -> Result<(), SendError>;
}
impl RequestUpgradeWebsocket for Request {
    /// Pass the WebSocket directly to a backend.
    ///
    /// This can only be used on services that have the WebSockets feature enabled and on requests
    /// that are valid WebSocket requests.
    ///
    /// The sending completes in the background. Once this method has been called, no other
    /// response can be sent to this request, and the application can exit without affecting the
    /// send.
    fn handoff_websocket(self, backend: &str) -> Result<(), SendError> {
        assert_single_downstream_response_is_sent(true);
        let req_handle = self.make_request_handle();
        let status = redirect_to_websocket_proxy(req_handle, backend);
        if status.is_err() {
            Err(SendError::new(
                backend,
                self,
                SendErrorCause::status(status),
            ))
        } else {
            Ok(())
        }
    }

    /// Pass the request through the Fanout GRIP proxy and on to a backend.
    ///
    /// This can only be used on services that have the Fanout feature enabled.
    ///
    /// The sending completes in the background. Once this method has been called, no other
    /// response can be sent to this request, and the application can exit without affecting the
    /// send.
    fn handoff_fanout(self, backend: &str) -> Result<(), SendError> {
        assert_single_downstream_response_is_sent(true);
        let req_handle = self.make_request_handle();
        let status = redirect_to_grip_proxy(req_handle, backend);
        if status.is_err() {
            Err(SendError::new(
                backend,
                self,
                SendErrorCause::status(status),
            ))
        } else {
            Ok(())
        }
    }
}

/// An extension trait for [`RequestHandle`]s that adds methods for upgrading
/// websockets.
pub trait RequestHandleUpgradeWebsocket {
    /// See [`RequestHandle::handoff_websocket()`].
    fn handoff_websocket(&mut self, backend: &str) -> Result<(), SendErrorCause>;

    /// See [`RequestHandle::handoff_fanout()`].
    fn handoff_fanout(&mut self, backend: &str) -> Result<(), SendErrorCause>;
}

impl RequestHandleUpgradeWebsocket for RequestHandle {
    /// Pass the WebSocket directly to a backend.
    ///
    /// This can only be used on services that have the WebSockets feature enabled and on requests
    /// that are valid WebSocket requests.
    ///
    /// The sending completes in the background. Once this method has been called, no other
    /// response can be sent to this request, and the application can exit without affecting the
    /// send.
    fn handoff_websocket(&mut self, backend: &str) -> Result<(), SendErrorCause> {
        match unsafe {
            abi::fastly_http_req::redirect_to_websocket_proxy_v2(
                self.as_u32(),
                backend.as_ptr(),
                backend.len(),
            )
        } {
            FastlyStatus::OK => Ok(()),
            status => Err(SendErrorCause::status(status)),
        }
    }

    /// Pass the request through the Fanout GRIP proxy and on to a backend.
    ///
    /// This can only be used on services that have the Fanout feature enabled.
    ///
    /// The sending completes in the background. Once this method has been called, no other
    /// response can be sent to this request, and the application can exit without affecting the
    /// send.
    fn handoff_fanout(&mut self, backend: &str) -> Result<(), SendErrorCause> {
        match unsafe {
            abi::fastly_http_req::redirect_to_grip_proxy_v2(
                self.as_u32(),
                backend.as_ptr(),
                backend.len(),
            )
        } {
            FastlyStatus::OK => Ok(()),
            status => Err(SendErrorCause::status(status)),
        }
    }
}

/// An extension trait for experimental [`Backend`] methods.
pub trait BackendExt {
    #[deprecated(
        since = "0.9.3",
        note = "The BackendExt::builder trait method is now part of Backend."
    )]
    #[doc = include_str!("../docs/snippets/dynamic-backend-builder.md")]
    fn builder(name: impl ToString, target: impl ToString) -> BackendBuilder;

    /// Return the health of the backend if configured and currently known.
    ///
    /// For backends without a configured healthcheck, this will always return `Unknown`.
    fn is_healthy(&self) -> Result<BackendHealth, Error>;
}

impl BackendExt for Backend {
    fn builder(name: impl ToString, target: impl ToString) -> BackendBuilder {
        BackendBuilder::new(name.to_string(), target.to_string())
    }

    fn is_healthy(&self) -> Result<BackendHealth, Error> {
        let mut backend_health_out = BackendHealth::Unknown;
        unsafe {
            fastly_backend::is_healthy(
                self.name().as_ptr(),
                self.name().len(),
                &mut backend_health_out,
            )
        }
        .result()
        .map_err(|e| match e {
            FastlyStatus::NONE => anyhow!("backend not found"),
            _ => anyhow!("backend healthcheck error: {:?}", e),
        })?;
        Ok(backend_health_out)
    }
}

/// An extension trait to support gRPC backend definition.
pub trait GrpcBackend {
    /// Set whether or not this backend will be used for gRPC traffic.
    ///
    /// Warning: Setting this for backends that will not be used with gRPC may have
    /// unpredictable effects. Fastly only currently guarantees that this connection
    /// will work for gRPC traffic.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn for_grpc(self, value: bool) -> Self;
}

/// Errors that can arise from reading trailer information.
#[derive(thiserror::Error, Debug)]
pub enum BodyHandleError {
    /// The trailers are not ready; please consume all of the body data before retrying.
    #[error("trailers not yet ready")]
    TrailersNotReady,
}

/// Extensions to the [`crate::handle::BodyHandle`] type to support trailers.
pub trait BodyHandleExt {
    /// Get the names of the trailers associated with this body.
    ///
    /// The resulting iterator will produce either the header names or an indication
    /// that the provided buffer size was too small. In that case, calling with a
    /// larger buffer size (information about how large a buffer is recommended is
    /// provided in [`BufferSizeError`]) should resolve the situation.
    #[doc = include_str!("../docs/snippets/trailers.md")]
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn get_trailer_names<'a>(
        &'a self,
        buf_size: usize,
    ) -> Result<Box<dyn Iterator<Item = Result<HeaderName, BufferSizeError>> + 'a>, BodyHandleError>;

    /// Get the value for the trailer with the given name.
    ///
    /// If there are multiple values for this header, only one is returned, which may be
    /// any of the values. See [`BodyHandleExt::get_trailer_values`] if you need to get
    /// all of the values.
    ///
    /// There are several options in the return value, ignoring the common tailer case
    /// in which you must read more data from the body:
    ///    * Ok(Some(value)): The trailer existed, and had the given value
    ///    * Ok(None): A trailer with that name does not exist
    ///    * Err(BufferSizeError): The trailer existed, but the provided max length was
    ///      too small.
    ///
    /// In the last case, [`BufferSizeError`] should provide information about what
    /// size buffer will be required to hold the requested data.
    #[doc = include_str!("../docs/snippets/trailers.md")]
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn get_trailer_value(
        &self,
        name: &HeaderName,
        max_len: usize,
    ) -> Result<Result<Option<HeaderValue>, BufferSizeError>, BodyHandleError>;

    /// Get all the values associated with the trailer with the given name.
    ///
    /// As opposed to [`BodyHandleExt::get_trailer_value`], this function returns all
    /// of the values for this trailer.
    #[doc = include_str!("../docs/snippets/trailers.md")]
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn get_trailer_values<'a>(
        &'a self,
        name: &'a HeaderName,
        max_len: usize,
    ) -> Result<Box<dyn Iterator<Item = Result<HeaderValue, BufferSizeError>> + 'a>, BodyHandleError>;
}

/// Extensions to the [`crate::http::body::Body`] type to support trailers.
pub trait BodyExt {
    /// Append the given trailer name and value to this body.
    ///
    /// Trailers will be sent once the body send is complete. This function will not
    /// discard any existing values for the trailer; this value will simply be appended
    /// to the set of existing values.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);

    /// Get the trailers associated with this body.
    ///
    /// Note that modifying this [`HeaderMap`] will have no effect on the trailers
    /// for the body; in order to add trailers, you will need to use [`BodyExt::append_trailer`].
    /// If you need to remove a trailer, the only current mechanism to do so is to
    /// create a fresh body, and then copy over the trailers you wish to maintain.
    /// (If this inconvenient, please contact your Fastly support team, and mention
    /// this shortcoming.)
    #[doc = include_str!("../docs/snippets/trailers.md")]
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn get_trailers(&mut self) -> Result<HeaderMap, Error>;
}

/// Extensions to the [`crate::http::body::StreamingBody`] type to support trailers.
pub trait StreamingBodyExt {
    /// Append the given trailer name and value to this body.
    ///
    /// Trailers will be sent once the body send is complete. This function will not
    /// discard any existing values for the trailer; this value will simply be appended
    /// to the set of existing values.
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);

    /// Get the trailers associated with this body.
    ///
    /// Note that modifying this [`HeaderMap`] will have no effect on the trailers
    /// for the body; in order to add trailers, you will need to use [`BodyExt::append_trailer`].
    /// If you need to remove a trailer, the only current mechanism to do so is to
    /// create a fresh body, and then copy over the trailers you wish to maintain.
    /// (If this inconvenient, please contact your Fastly support team, and mention
    /// this shortcoming.)
    #[doc = include_str!("../docs/snippets/trailers.md")]
    #[doc = include_str!("../docs/snippets/experimental.md")]
    fn finish_with_trailers(self, trailers: &HeaderMap) -> Result<(), std::io::Error>;
}