Skip to main content

fastly/
experimental.rs

1//! Experimental Compute features.
2//!
3//! These features are not yet stable and may change in backwards-incompatible
4//! ways without major-version bumps.
5
6pub mod dynamic_backend_healthchecks;
7pub mod reusable_sessions;
8#[deprecated(
9    since = "0.11.4",
10    note = "The shielding module is not longer experimental. Please use `fastly::shielding` instead."
11)]
12pub mod shielding;
13
14use crate::{
15    abi::{self, FastlyStatus},
16    convert::{ToHeaderName, ToHeaderValue},
17    error::BufferSizeError,
18    http::{
19        header::{HeaderName, HeaderValue},
20        request::{
21            handle::{redirect_to_grip_proxy, redirect_to_websocket_proxy, RequestHandle},
22            CacheKeyGen, Request, SendError, SendErrorCause,
23        },
24        response::assert_single_downstream_response_is_sent,
25    },
26    Backend, Error,
27};
28#[cfg(target_env = "p1")]
29use anyhow::anyhow;
30use bytes::Bytes;
31#[cfg(target_env = "p1")]
32use fastly_sys::fastly_backend;
33#[cfg(not(target_env = "p1"))]
34use fastly_sys::service_0_1::fastly::compute as wit;
35use http::header::HeaderMap;
36use sha2::{Digest, Sha256};
37use std::sync::Arc;
38
39#[cfg(target_env = "p1")]
40#[doc(inline)]
41pub use fastly_sys::fastly_backend::BackendHealth;
42#[cfg(not(target_env = "p1"))]
43#[doc(inline)]
44pub use wit::backend::BackendHealth;
45
46pub use crate::backend::{BackendBuilder, BackendCreationError};
47pub use crate::Response;
48
49/// Parse a user agent string.
50#[doc = include_str!("../docs/snippets/experimental.md")]
51#[deprecated(since = "0.10.1")]
52pub fn uap_parse(
53    user_agent: &str,
54) -> Result<(String, Option<String>, Option<String>, Option<String>), Error> {
55    let user_agent: &[u8] = user_agent.as_ref();
56    let max_length = 255;
57    let mut family = Vec::with_capacity(max_length);
58    let mut major = Vec::with_capacity(max_length);
59    let mut minor = Vec::with_capacity(max_length);
60    let mut patch = Vec::with_capacity(max_length);
61    let mut family_nwritten = 0;
62    let mut major_nwritten = 0;
63    let mut minor_nwritten = 0;
64    let mut patch_nwritten = 0;
65
66    let status = unsafe {
67        abi::fastly_uap::parse(
68            user_agent.as_ptr(),
69            user_agent.len(),
70            family.as_mut_ptr(),
71            family.capacity(),
72            &mut family_nwritten,
73            major.as_mut_ptr(),
74            major.capacity(),
75            &mut major_nwritten,
76            minor.as_mut_ptr(),
77            minor.capacity(),
78            &mut minor_nwritten,
79            patch.as_mut_ptr(),
80            patch.capacity(),
81            &mut patch_nwritten,
82        )
83    };
84    if status.is_err() {
85        return Err(Error::msg("fastly_uap::parse failed"));
86    }
87    assert!(
88        family_nwritten <= family.capacity(),
89        "fastly_uap::parse wrote too many bytes for family"
90    );
91    unsafe {
92        family.set_len(family_nwritten);
93    }
94    assert!(
95        major_nwritten <= major.capacity(),
96        "fastly_uap::parse wrote too many bytes for major"
97    );
98    unsafe {
99        major.set_len(major_nwritten);
100    }
101    assert!(
102        minor_nwritten <= minor.capacity(),
103        "fastly_uap::parse wrote too many bytes for minor"
104    );
105    unsafe {
106        minor.set_len(minor_nwritten);
107    }
108    assert!(
109        patch_nwritten <= patch.capacity(),
110        "fastly_uap::parse wrote too many bytes for patch"
111    );
112    unsafe {
113        patch.set_len(patch_nwritten);
114    }
115    Ok((
116        String::from_utf8_lossy(&family).to_string(),
117        Some(String::from_utf8_lossy(&major).to_string()),
118        Some(String::from_utf8_lossy(&minor).to_string()),
119        Some(String::from_utf8_lossy(&patch).to_string()),
120    ))
121}
122
123/// An extension trait for [`Request`]s that adds methods for controlling cache keys.
124#[doc = include_str!("../docs/snippets/experimental.md")]
125pub trait RequestCacheKey {
126    /// See [`Request::set_cache_key()`].
127    #[doc = include_str!("../docs/snippets/experimental.md")]
128    fn set_cache_key(&mut self, key: [u8; 32]);
129    /// See [`Request::with_cache_key()`].
130    #[doc = include_str!("../docs/snippets/experimental.md")]
131    fn with_cache_key(self, key: [u8; 32]) -> Self;
132    /// See [`Request::set_cache_key_fn()`].
133    #[doc = include_str!("../docs/snippets/experimental.md")]
134    fn set_cache_key_fn(&mut self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static);
135    /// See [`Request::with_cache_key_fn()`].
136    #[doc = include_str!("../docs/snippets/experimental.md")]
137    fn with_cache_key_fn(self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static) -> Self;
138    /// See [`Request::set_cache_key_str()`].
139    #[doc = include_str!("../docs/snippets/experimental.md")]
140    fn set_cache_key_str(&mut self, key_str: impl AsRef<[u8]>);
141    /// See [`Request::with_cache_key_str()`].
142    #[doc = include_str!("../docs/snippets/experimental.md")]
143    fn with_cache_key_str(self, key_str: impl AsRef<[u8]>) -> Self;
144}
145
146impl RequestCacheKey for Request {
147    /// Set the cache key to be used when attempting to satisfy this request from a cached response.
148    #[doc = include_str!("../docs/snippets/experimental.md")]
149    fn set_cache_key(&mut self, key: [u8; 32]) {
150        self.metadata.override_cache_key = Some(CacheKeyGen::Set(Vec::from(key).into()));
151    }
152
153    /// Builder-style equivalent of [`set_cache_key()`](Self::set_cache_key()).
154    #[doc = include_str!("../docs/snippets/experimental.md")]
155    fn with_cache_key(mut self, key: [u8; 32]) -> Self {
156        self.set_cache_key(key);
157        self
158    }
159
160    /// Set the function that will be used to compute the cache key for this request.
161    #[doc = include_str!("../docs/snippets/experimental.md")]
162    fn set_cache_key_fn(&mut self, f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static) {
163        self.metadata.override_cache_key = Some(CacheKeyGen::Lazy(Arc::new(move |req| {
164            Bytes::from(Vec::from(f(req)))
165        })));
166    }
167
168    /// Builder-style equivalent of [`set_cache_key_fn()`](Self::set_cache_key_fn()).
169    #[doc = include_str!("../docs/snippets/experimental.md")]
170    fn with_cache_key_fn(
171        mut self,
172        f: impl Fn(&Request) -> [u8; 32] + Send + Sync + 'static,
173    ) -> Self {
174        self.set_cache_key_fn(f);
175        self
176    }
177
178    /// Set a string as the cache key to be used when attempting to satisfy this request from a
179    /// cached response.
180    ///
181    /// The string representation of the key is hashed to the same `[u8; 32]` representation used by
182    /// [`set_cache_key()`][`Self::set_cache_key()`].
183    #[doc = include_str!("../docs/snippets/experimental.md")]
184    fn set_cache_key_str(&mut self, key_str: impl AsRef<[u8]>) {
185        let mut sha = Sha256::new();
186        sha.update(key_str);
187        sha.update(b"\x00\xf0\x9f\xa7\x82\x00"); // extra salt
188        let finalized: [u8; 32] = *sha.finalize().as_ref();
189        self.set_cache_key(finalized)
190    }
191
192    /// Builder-style equivalent of [`set_cache_key_str()`](Self::set_cache_key_str()).
193    #[doc = include_str!("../docs/snippets/experimental.md")]
194    fn with_cache_key_str(mut self, key_str: impl AsRef<[u8]>) -> Self {
195        self.set_cache_key_str(key_str);
196        self
197    }
198}
199
200/// An extension trait for [`RequestHandle`](RequestHandle)s that adds methods for controlling cache
201/// keys.
202#[doc = include_str!("../docs/snippets/experimental.md")]
203pub trait RequestHandleCacheKey {
204    /// See [`RequestHandle::set_cache_key()`](RequestHandle::set_cache_key).
205    #[doc = include_str!("../docs/snippets/experimental.md")]
206    fn set_cache_key(&mut self, key: impl AsRef<[u8]>);
207}
208
209impl RequestHandleCacheKey for RequestHandle {
210    /// Set the cache key to be used when attempting to satisfy this request from a cached response.
211    #[doc = include_str!("../docs/snippets/experimental.md")]
212    fn set_cache_key(&mut self, key: impl AsRef<[u8]>) {
213        let key = key.as_ref();
214        const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
215        let mut hex = Vec::with_capacity(key.len() * 2);
216        for b in key.iter() {
217            hex.push(DIGITS[(b >> 4) as usize]);
218            hex.push(DIGITS[(b & 0xf) as usize]);
219        }
220
221        self.insert_header(
222            &HeaderName::from_static("fastly-xqd-cache-key"),
223            &HeaderValue::try_from(hex).unwrap(),
224        )
225    }
226}
227
228/// An extension trait for [`Request`]s that adds a method for upgrading websockets.
229pub trait RequestUpgradeWebsocket {
230    /// See [`Request::handoff_websocket()`].
231    #[deprecated(
232        since = "0.10.0",
233        note = "The RequestUpgradeWebsocket::handoff_websocket() trait method is now part of Request."
234    )]
235    fn handoff_websocket(self, backend: &str) -> Result<(), SendError>;
236
237    /// See [`Request::handoff_fanout()`].
238    #[deprecated(
239        since = "0.10.0",
240        note = "The RequestUpgradeWebsocket::handoff_fanout() trait method is now part of Request."
241    )]
242    fn handoff_fanout(self, backend: &str) -> Result<(), SendError>;
243}
244impl RequestUpgradeWebsocket for Request {
245    /// Pass the WebSocket directly to a backend.
246    ///
247    /// This can only be used on services that have the WebSockets feature enabled and on requests
248    /// that are valid WebSocket requests.
249    ///
250    /// The sending completes in the background. Once this method has been called, no other
251    /// response can be sent to this request, and the application can exit without affecting the
252    /// send.
253    fn handoff_websocket(self, backend: &str) -> Result<(), SendError> {
254        assert_single_downstream_response_is_sent(None, true);
255        let cloned = self.clone_without_body();
256        let (req_handle, _) = self.into_handles();
257        let status = redirect_to_websocket_proxy(req_handle, backend);
258        if status == FastlyStatus::UNSUPPORTED {
259            Err(SendError::new(
260                backend,
261                cloned,
262                SendErrorCause::FanoutNotEnabled,
263            ))
264        } else if status.is_err() {
265            Err(SendError::new(
266                backend,
267                cloned,
268                SendErrorCause::status(status),
269            ))
270        } else {
271            Ok(())
272        }
273    }
274
275    /// Pass the request through the Fanout GRIP proxy and on to a backend.
276    ///
277    /// This can only be used on services that have the Fanout feature enabled.
278    ///
279    /// The sending completes in the background. Once this method has been called, no other
280    /// response can be sent to this request, and the application can exit without affecting the
281    /// send.
282    fn handoff_fanout(self, backend: &str) -> Result<(), SendError> {
283        assert_single_downstream_response_is_sent(None, true);
284        let cloned = self.clone_without_body();
285        let (req_handle, _) = self.into_handles();
286        let status = redirect_to_grip_proxy(req_handle, backend);
287        if status == FastlyStatus::UNSUPPORTED {
288            Err(SendError::new(
289                backend,
290                cloned,
291                SendErrorCause::FanoutNotEnabled,
292            ))
293        } else if status.is_err() {
294            Err(SendError::new(
295                backend,
296                cloned,
297                SendErrorCause::status(status),
298            ))
299        } else {
300            Ok(())
301        }
302    }
303}
304
305/// An extension trait for [`RequestHandle`]s that adds methods for upgrading
306/// websockets.
307pub trait RequestHandleUpgradeWebsocket {
308    /// See [`RequestHandle::handoff_websocket()`].
309    #[deprecated(
310        since = "0.10.0",
311        note = "The RequestHandleUpgradeWebsocket::handoff_websocket() trait method is now part of RequestHandle."
312    )]
313    fn handoff_websocket(&mut self, backend: &str) -> Result<(), SendErrorCause>;
314
315    /// See [`RequestHandle::handoff_fanout()`].
316    #[deprecated(
317        since = "0.10.0",
318        note = "The RequestHandleUpgradeWebsocket::handoff_fanout() trait method is now part of RequestHandle."
319    )]
320    fn handoff_fanout(&mut self, backend: &str) -> Result<(), SendErrorCause>;
321}
322
323impl RequestHandleUpgradeWebsocket for RequestHandle {
324    /// Pass the WebSocket directly to a backend.
325    ///
326    /// This can only be used on services that have the WebSockets feature enabled and on requests
327    /// that are valid WebSocket requests.
328    ///
329    /// The sending completes in the background. Once this method has been called, no other
330    /// response can be sent to this request, and the application can exit without affecting the
331    /// send.
332    fn handoff_websocket(&mut self, backend: &str) -> Result<(), SendErrorCause> {
333        match unsafe {
334            abi::fastly_http_req::redirect_to_websocket_proxy_v2(
335                self.as_u32(),
336                backend.as_ptr(),
337                backend.len(),
338            )
339        } {
340            FastlyStatus::OK => Ok(()),
341            FastlyStatus::UNSUPPORTED => Err(SendErrorCause::FanoutNotEnabled),
342            status => Err(SendErrorCause::status(status)),
343        }
344    }
345
346    /// Pass the request through the Fanout GRIP proxy and on to a backend.
347    ///
348    /// This can only be used on services that have the Fanout feature enabled.
349    ///
350    /// The sending completes in the background. Once this method has been called, no other
351    /// response can be sent to this request, and the application can exit without affecting the
352    /// send.
353    fn handoff_fanout(&mut self, backend: &str) -> Result<(), SendErrorCause> {
354        match unsafe {
355            abi::fastly_http_req::redirect_to_grip_proxy_v2(
356                self.as_u32(),
357                backend.as_ptr(),
358                backend.len(),
359            )
360        } {
361            FastlyStatus::OK => Ok(()),
362            FastlyStatus::UNSUPPORTED => Err(SendErrorCause::FanoutNotEnabled),
363            status => Err(SendErrorCause::status(status)),
364        }
365    }
366}
367
368/// An extension trait for experimental [`Backend`] methods.
369pub trait BackendExt {
370    /// Return the health of the backend if configured and currently known.
371    ///
372    /// For backends without a configured healthcheck, this will always return `Unknown`.
373    fn is_healthy(&self) -> Result<BackendHealth, Error>;
374}
375
376impl BackendExt for Backend {
377    fn is_healthy(&self) -> Result<BackendHealth, Error> {
378        #[cfg(target_env = "p1")]
379        {
380            let mut backend_health_out = BackendHealth::Unknown;
381            unsafe {
382                fastly_backend::is_healthy(
383                    self.name().as_ptr(),
384                    self.name().len(),
385                    &mut backend_health_out,
386                )
387            }
388            .result()
389            .map_err(|e| match e {
390                FastlyStatus::NONE | FastlyStatus::INVAL => anyhow!("backend not found"),
391                _ => anyhow!("backend healthcheck error: {e:?}"),
392            })?;
393            Ok(backend_health_out)
394        }
395
396        #[cfg(not(target_env = "p1"))]
397        {
398            Ok(self.as_handle().is_healthy()?)
399        }
400    }
401}
402
403/// An extension trait to support gRPC backend definition.
404pub trait GrpcBackend {
405    /// Set whether or not this backend will be used for gRPC traffic.
406    ///
407    /// Warning: Using for_grpc will cause Fastly to assume that the origin server accepts
408    /// HTTP/2 traffic natively: either directly (for HTTP), or via an HTTP/2-only ALPN
409    /// negotiation (for HTTPS). Connections will fail if the server attempts to negotiate
410    /// a different connection type in any way.
411    ///
412    /// Stability: Fastly's support for gRPC is under ongoing development. Certain forms of
413    /// gRPC traffic are known to work, and work well; typically, these are gRPC flows in
414    /// which a client opens a connection to a server, makes a small number of requests,
415    /// waits for responses, and then closes the connection. Flows in which many requests
416    /// are sent over a single connection are unlikely to work. Users should expect
417    /// changes to supported flows as we refine our ability to handle gRPC requests over
418    /// time.
419    fn for_grpc(self, value: bool) -> Self;
420}
421
422/// Errors that can arise from reading trailer information.
423#[derive(thiserror::Error, Debug)]
424pub enum BodyHandleError {
425    /// The trailers are not ready; please consume all of the body data before retrying.
426    #[error("trailers not yet ready")]
427    TrailersNotReady,
428}
429
430/// Extensions to the [`crate::handle::BodyHandle`] type to support trailers.
431pub trait BodyHandleExt {
432    /// Get the names of the trailers associated with this body.
433    ///
434    /// The resulting iterator will produce either the header names or an indication
435    /// that the provided buffer size was too small. In that case, calling with a
436    /// larger buffer size (information about how large a buffer is recommended is
437    /// provided in [`BufferSizeError`]) should resolve the situation.
438    #[doc = include_str!("../docs/snippets/trailers.md")]
439    #[doc = include_str!("../docs/snippets/experimental.md")]
440    fn get_trailer_names<'a>(
441        &'a self,
442        buf_size: usize,
443    ) -> Result<Box<dyn Iterator<Item = Result<HeaderName, BufferSizeError>> + 'a>, BodyHandleError>;
444
445    /// Get the value for the trailer with the given name.
446    ///
447    /// If there are multiple values for this header, only one is returned, which may be
448    /// any of the values. See [`BodyHandleExt::get_trailer_values`] if you need to get
449    /// all of the values.
450    ///
451    /// There are several options in the return value, ignoring the common trailer case
452    /// in which you must read more data from the body:
453    ///    * Ok(Some(value)): The trailer existed, and had the given value
454    ///    * Ok(None): A trailer with that name does not exist
455    ///    * Err(BufferSizeError): The trailer existed, but the provided max length was
456    ///      too small.
457    ///
458    /// In the last case, [`BufferSizeError`] should provide information about what
459    /// size buffer will be required to hold the requested data.
460    #[doc = include_str!("../docs/snippets/trailers.md")]
461    #[doc = include_str!("../docs/snippets/experimental.md")]
462    fn get_trailer_value(
463        &self,
464        name: &HeaderName,
465        max_len: usize,
466    ) -> Result<Result<Option<HeaderValue>, BufferSizeError>, BodyHandleError>;
467
468    /// Get all the values associated with the trailer with the given name.
469    ///
470    /// As opposed to [`BodyHandleExt::get_trailer_value`], this function returns all
471    /// of the values for this trailer.
472    #[doc = include_str!("../docs/snippets/trailers.md")]
473    #[doc = include_str!("../docs/snippets/experimental.md")]
474    fn get_trailer_values<'a>(
475        &'a self,
476        name: &'a HeaderName,
477        max_len: usize,
478    ) -> Result<Box<dyn Iterator<Item = Result<HeaderValue, BufferSizeError>> + 'a>, BodyHandleError>;
479}
480
481/// Extensions to the [`crate::http::body::Body`] type to support trailers.
482pub trait BodyExt {
483    /// Append the given trailer name and value to this body.
484    ///
485    /// Trailers will be sent once the body send is complete. This function will not
486    /// discard any existing values for the trailer; this value will simply be appended
487    /// to the set of existing values.
488    #[doc = include_str!("../docs/snippets/experimental.md")]
489    fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);
490
491    /// Get the trailers associated with this body.
492    ///
493    /// Note that modifying this [`HeaderMap`] will have no effect on the trailers
494    /// for the body; in order to add trailers, you will need to use [`BodyExt::append_trailer`].
495    /// If you need to remove a trailer, the only current mechanism to do so is to
496    /// create a fresh body, and then copy over the trailers you wish to maintain.
497    /// (If this inconvenient, please contact your Fastly support team, and mention
498    /// this shortcoming.)
499    #[doc = include_str!("../docs/snippets/trailers.md")]
500    #[doc = include_str!("../docs/snippets/experimental.md")]
501    fn get_trailers(&mut self) -> Result<HeaderMap, Error>;
502}
503
504/// Extensions to the [`crate::http::body::StreamingBody`] type to support trailers.
505pub trait StreamingBodyExt {
506    /// Append the given trailer name and value to this body.
507    ///
508    /// Trailers will be sent once the body send is complete. This function will not
509    /// discard any existing values for the trailer; this value will simply be appended
510    /// to the set of existing values.
511    #[doc = include_str!("../docs/snippets/experimental.md")]
512    fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);
513
514    /// Get the trailers associated with this body.
515    ///
516    /// Note that modifying this [`HeaderMap`] will have no effect on the trailers
517    /// for the body; in order to add trailers, you will need to use [`BodyExt::append_trailer`].
518    /// If you need to remove a trailer, the only current mechanism to do so is to
519    /// create a fresh body, and then copy over the trailers you wish to maintain.
520    /// (If this inconvenient, please contact your Fastly support team, and mention
521    /// this shortcoming.)
522    #[doc = include_str!("../docs/snippets/trailers.md")]
523    #[doc = include_str!("../docs/snippets/experimental.md")]
524    fn finish_with_trailers(self, trailers: &HeaderMap) -> Result<(), std::io::Error>;
525}