1pub 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#[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#[doc = include_str!("../docs/snippets/experimental.md")]
125pub trait RequestCacheKey {
126 #[doc = include_str!("../docs/snippets/experimental.md")]
128 fn set_cache_key(&mut self, key: [u8; 32]);
129 #[doc = include_str!("../docs/snippets/experimental.md")]
131 fn with_cache_key(self, key: [u8; 32]) -> Self;
132 #[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 #[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 #[doc = include_str!("../docs/snippets/experimental.md")]
140 fn set_cache_key_str(&mut self, key_str: impl AsRef<[u8]>);
141 #[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 #[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 #[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 #[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 #[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 #[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"); let finalized: [u8; 32] = *sha.finalize().as_ref();
189 self.set_cache_key(finalized)
190 }
191
192 #[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#[doc = include_str!("../docs/snippets/experimental.md")]
203pub trait RequestHandleCacheKey {
204 #[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 #[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
228pub trait RequestUpgradeWebsocket {
230 #[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 #[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 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 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
305pub trait RequestHandleUpgradeWebsocket {
308 #[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 #[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 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 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
368pub trait BackendExt {
370 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
403pub trait GrpcBackend {
405 fn for_grpc(self, value: bool) -> Self;
420}
421
422#[derive(thiserror::Error, Debug)]
424pub enum BodyHandleError {
425 #[error("trailers not yet ready")]
427 TrailersNotReady,
428}
429
430pub trait BodyHandleExt {
432 #[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 #[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 #[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
481pub trait BodyExt {
483 #[doc = include_str!("../docs/snippets/experimental.md")]
489 fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);
490
491 #[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
504pub trait StreamingBodyExt {
506 #[doc = include_str!("../docs/snippets/experimental.md")]
512 fn append_trailer(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue);
513
514 #[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}