|
| 1 | +import { fetchWithRetry } from '@/frame/lib/fetch-utils' |
| 2 | + |
| 3 | +// Purges the ENTIRE Fastly cache for the docs service via Fastly's purge_all |
| 4 | +// endpoint. This is the workflow equivalent of the "Purge all" button in the |
| 5 | +// Fastly UI. It is intentionally a separate, manually triggered entry point: |
| 6 | +// routine post-deploy purging is handled by |
| 7 | +// `purge-fastly-edge-cache-per-language.ts`, and a gentler "refresh everything" |
| 8 | +// can be done by running the Purge Fastly workflow with an empty languages |
| 9 | +// input (a soft surrogate-key purge of every language). |
| 10 | +// |
| 11 | +// NOTE: Fastly's purge_all is always a HARD purge. The `fastly-soft-purge` |
| 12 | +// header has no effect on this endpoint, so every object is evicted immediately |
| 13 | +// and origin sees a traffic spike while the cache refills. Only reach for this |
| 14 | +// when a targeted purge will not do. |
| 15 | +// https://www.fastly.com/documentation/reference/api/purging/ |
| 16 | + |
| 17 | +async function purgeFastlyAll({ apiToken, serviceId }: { apiToken: string; serviceId: string }) { |
| 18 | + const safeServiceId = encodeURIComponent(serviceId) |
| 19 | + const requestPath = `https://api.fastly.com/service/${safeServiceId}/purge_all` |
| 20 | + const response = await fetchWithRetry( |
| 21 | + requestPath, |
| 22 | + { |
| 23 | + method: 'POST', |
| 24 | + headers: { |
| 25 | + 'fastly-key': apiToken, |
| 26 | + accept: 'application/json', |
| 27 | + 'Content-Type': 'application/json', |
| 28 | + }, |
| 29 | + }, |
| 30 | + { |
| 31 | + retries: 0, |
| 32 | + timeout: 30_000, |
| 33 | + throwHttpErrors: false, |
| 34 | + }, |
| 35 | + ) |
| 36 | + if (!response.ok) { |
| 37 | + // Fastly puts permission/feature-disabled details in the response body, |
| 38 | + // which is often the only actionable signal, so surface it best-effort. |
| 39 | + let body = '' |
| 40 | + try { |
| 41 | + body = await response.text() |
| 42 | + } catch { |
| 43 | + body = '' |
| 44 | + } |
| 45 | + throw new Error( |
| 46 | + `Fastly purge_all failed: HTTP ${response.status} ${response.statusText}${body ? `: ${body}` : ''}`, |
| 47 | + ) |
| 48 | + } |
| 49 | + return response |
| 50 | +} |
| 51 | + |
| 52 | +const { FASTLY_TOKEN, FASTLY_SERVICE_ID } = process.env |
| 53 | +if (!FASTLY_TOKEN || !FASTLY_SERVICE_ID) { |
| 54 | + throw new Error('Fastly env vars not detected; refusing to run purge_all') |
| 55 | +} |
| 56 | + |
| 57 | +console.log('Attempting Fastly purge_all (hard purge of the entire cache)...') |
| 58 | +const result = await purgeFastlyAll({ apiToken: FASTLY_TOKEN, serviceId: FASTLY_SERVICE_ID }) |
| 59 | +console.log('Fastly purge_all result:', result.status) |
0 commit comments