|
| 1 | +#![doc = include_str!("../README.md")] |
| 2 | + |
| 3 | +use reqwest::Client; |
| 4 | +use reqwest::header::{HeaderValue, InvalidHeaderValue}; |
| 5 | +use secrecy::{ExposeSecret, SecretString}; |
| 6 | +use thiserror::Error; |
| 7 | +use tracing::{debug, instrument, trace}; |
| 8 | + |
| 9 | +#[derive(Debug, Error)] |
| 10 | +pub enum Error { |
| 11 | + #[error("Wildcard invalidations are not supported for Fastly")] |
| 12 | + WildcardNotSupported, |
| 13 | + |
| 14 | + #[error("Invalid API token format")] |
| 15 | + InvalidApiToken(#[from] InvalidHeaderValue), |
| 16 | + |
| 17 | + #[error("Failed to `POST {url}`{}: {source}", status.map(|s| format!(" (status: {})", s)).unwrap_or_default())] |
| 18 | + PurgeFailed { |
| 19 | + url: String, |
| 20 | + status: Option<reqwest::StatusCode>, |
| 21 | + #[source] |
| 22 | + source: reqwest::Error, |
| 23 | + }, |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Debug)] |
| 27 | +pub struct Fastly { |
| 28 | + client: Client, |
| 29 | + api_token: SecretString, |
| 30 | +} |
| 31 | + |
| 32 | +impl Fastly { |
| 33 | + pub fn new(api_token: SecretString) -> Self { |
| 34 | + let client = Client::new(); |
| 35 | + Self { client, api_token } |
| 36 | + } |
| 37 | + |
| 38 | + /// Invalidate a path on Fastly |
| 39 | + /// |
| 40 | + /// This method takes a path and invalidates the cached content on Fastly. The path must not |
| 41 | + /// contain a wildcard, since the Fastly API does not support wildcard invalidations. Paths are |
| 42 | + /// invalidated for both domains that are associated with the Fastly service. |
| 43 | + /// |
| 44 | + /// Requests are authenticated using a token that is sent in a header. The token is passed to |
| 45 | + /// the application as an environment variable. |
| 46 | + /// |
| 47 | + /// More information on Fastly's APIs for cache invalidations can be found here: |
| 48 | + /// <https://developer.fastly.com/reference/api/purging/> |
| 49 | + #[instrument(skip(self))] |
| 50 | + pub async fn purge_both_domains(&self, base_domain: &str, path: &str) -> Result<(), Error> { |
| 51 | + self.purge(base_domain, path).await?; |
| 52 | + |
| 53 | + let prefixed_domain = format!("fastly-{base_domain}"); |
| 54 | + self.purge(&prefixed_domain, path).await?; |
| 55 | + |
| 56 | + Ok(()) |
| 57 | + } |
| 58 | + |
| 59 | + /// Invalidate a path on Fastly |
| 60 | + /// |
| 61 | + /// This method takes a domain and path and invalidates the cached content |
| 62 | + /// on Fastly. The path must not contain a wildcard, since the Fastly API |
| 63 | + /// does not support wildcard invalidations. |
| 64 | + /// |
| 65 | + /// More information on Fastly's APIs for cache invalidations can be found here: |
| 66 | + /// <https://developer.fastly.com/reference/api/purging/> |
| 67 | + #[instrument(skip(self))] |
| 68 | + pub async fn purge(&self, domain: &str, path: &str) -> Result<(), Error> { |
| 69 | + if path.contains('*') { |
| 70 | + return Err(Error::WildcardNotSupported); |
| 71 | + } |
| 72 | + |
| 73 | + let path = path.trim_start_matches('/'); |
| 74 | + let url = format!("https://api.fastly.com/purge/{domain}/{path}"); |
| 75 | + |
| 76 | + trace!(?url); |
| 77 | + |
| 78 | + debug!("sending invalidation request to Fastly"); |
| 79 | + let response = self |
| 80 | + .client |
| 81 | + .post(&url) |
| 82 | + .header("Fastly-Key", self.token_header_value()?) |
| 83 | + .send() |
| 84 | + .await |
| 85 | + .map_err(|source| Error::PurgeFailed { |
| 86 | + url: url.clone(), |
| 87 | + status: None, |
| 88 | + source, |
| 89 | + })?; |
| 90 | + |
| 91 | + let status = response.status(); |
| 92 | + |
| 93 | + match response.error_for_status_ref() { |
| 94 | + Ok(_) => { |
| 95 | + debug!(?status, "invalidation request accepted by Fastly"); |
| 96 | + Ok(()) |
| 97 | + } |
| 98 | + Err(error) => { |
| 99 | + let headers = response.headers().clone(); |
| 100 | + let body = response.text().await; |
| 101 | + debug!( |
| 102 | + ?status, |
| 103 | + ?headers, |
| 104 | + ?body, |
| 105 | + "invalidation request to Fastly failed" |
| 106 | + ); |
| 107 | + |
| 108 | + Err(Error::PurgeFailed { |
| 109 | + url, |
| 110 | + status: Some(status), |
| 111 | + source: error, |
| 112 | + }) |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + fn token_header_value(&self) -> Result<HeaderValue, InvalidHeaderValue> { |
| 118 | + let api_token = self.api_token.expose_secret(); |
| 119 | + |
| 120 | + let mut header_value = HeaderValue::try_from(api_token)?; |
| 121 | + header_value.set_sensitive(true); |
| 122 | + Ok(header_value) |
| 123 | + } |
| 124 | +} |
0 commit comments