forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
purge-edge-cache.js
75 lines (64 loc) · 2.56 KB
/
purge-edge-cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import got from 'got'
// Because we use Origin Shielding, it's recommended that you purge twice
// so it purges the edge nodes *and* the origin.
// The documentation says:
//
// One solution to this race condition problem is simply to purge
// twice. For purge-all operations, the two purges should be
// around 30 seconds apart and, for single object and surrogate
// key purges, around 2 seconds apart.
//
// See https://developer.fastly.com/learning/concepts/purging/#shielding
const DELAY_BEFORE_FIRST_PURGE = 5 * 1000
const DELAY_BEFORE_SECOND_PURGE = 30 * 1000
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function purgeFastlyBySurrogateKey({ apiToken, serviceId, surrogateKey }) {
const safeServiceId = encodeURIComponent(serviceId)
const headers = {
'fastly-key': apiToken,
accept: 'application/json',
'fastly-soft-purge': '1',
}
const requestPath = `https://api.fastly.com/service/${safeServiceId}/purge/${surrogateKey}`
return got.post(requestPath, { headers, json: true })
}
export default async function purgeEdgeCache(
surrogateKey,
{
purgeTwice = true,
delayBeforeFirstPurge = DELAY_BEFORE_FIRST_PURGE,
delayBeforeSecondPurge = DELAY_BEFORE_SECOND_PURGE,
} = {}
) {
if (!surrogateKey) {
throw new Error('No key set and/or no FASTLY_SURROGATE_KEY env var set')
}
console.log(`Fastly purgeEdgeCache initialized for: '${surrogateKey}'`)
const { FASTLY_TOKEN, FASTLY_SERVICE_ID } = process.env
if (!FASTLY_TOKEN || !FASTLY_SERVICE_ID) {
throw new Error('Fastly env vars not detected; skipping purgeEdgeCache step')
}
const purgingParams = {
apiToken: FASTLY_TOKEN,
serviceId: FASTLY_SERVICE_ID,
surrogateKey,
}
// Give the app some extra time to wake up before the thundering herd of
// Fastly requests.
if (delayBeforeFirstPurge) {
console.log('Waiting extra time to prevent a Thundering Herd problem...')
await sleep(delayBeforeFirstPurge)
}
console.log('Attempting first Fastly purge...')
const firstPurge = await purgeFastlyBySurrogateKey(purgingParams)
console.log('First Fastly purge result:', firstPurge.body || firstPurge)
// Evidence has shown that it's necessary to purge twice to ensure all
// customers see fresh content.
if (purgeTwice) {
console.log('Waiting to purge a second time...')
await sleep(delayBeforeSecondPurge)
console.log('Attempting second Fastly purge...')
const secondPurge = await purgeFastlyBySurrogateKey(purgingParams)
console.log('Second Fastly purge result:', secondPurge.body || secondPurge)
}
}