|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use anyhow::Context; |
| 4 | +use crates_io_worker::BackgroundJob; |
| 5 | + |
| 6 | +use crate::worker::Environment; |
| 7 | + |
| 8 | +/// A background job that invalidates the given paths on all CDNs in use on crates.io. |
| 9 | +#[derive(Deserialize, Serialize)] |
| 10 | +pub struct InvalidateCdns { |
| 11 | + paths: Vec<String>, |
| 12 | +} |
| 13 | + |
| 14 | +impl InvalidateCdns { |
| 15 | + pub fn new<I>(paths: I) -> Self |
| 16 | + where |
| 17 | + I: Iterator, |
| 18 | + I::Item: ToString, |
| 19 | + { |
| 20 | + Self { |
| 21 | + paths: paths.map(|path| path.to_string()).collect(), |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl BackgroundJob for InvalidateCdns { |
| 27 | + const JOB_NAME: &'static str = "invalidate_cdns"; |
| 28 | + |
| 29 | + type Context = Arc<Environment>; |
| 30 | + |
| 31 | + async fn run(&self, ctx: Self::Context) -> anyhow::Result<()> { |
| 32 | + // Fastly doesn't provide an API to purge multiple paths at once, except through the use of |
| 33 | + // surrogate keys. We can't use surrogate keys right now because they require a |
| 34 | + // Fastly-specific header, and not all of our traffic goes through Fastly. |
| 35 | + // |
| 36 | + // For now, we won't parallelise: most crate deletions are for new crates with one (or very |
| 37 | + // few) versions, so the actual number of paths being invalidated is likely to be small, and |
| 38 | + // this is all happening from either a background job or admin command anyway. |
| 39 | + if let Some(fastly) = ctx.fastly() { |
| 40 | + for path in self.paths.iter() { |
| 41 | + fastly |
| 42 | + .invalidate(path) |
| 43 | + .await |
| 44 | + .with_context(|| format!("Failed to invalidate path on Fastly CDN: {path}"))?; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if let Some(cloudfront) = ctx.cloudfront() { |
| 49 | + cloudfront |
| 50 | + .invalidate_many(self.paths.clone()) |
| 51 | + .await |
| 52 | + .context("Failed to invalidate paths on CloudFront CDN")?; |
| 53 | + } |
| 54 | + |
| 55 | + Ok(()) |
| 56 | + } |
| 57 | +} |
0 commit comments