Files
vue-journal-layer/testing/purge-check.mjs
Jakub Zych 0a01bfeae4 feat: browsers revalidate route-cached pages; document the site cache purge
- privateRevalidate sets max-age=0 on cache-control values with s-maxage
- server/plugins/journal-revalidate.ts wraps res.setHeader per request, so
  Nitro's 200 and h3's 304 answers both carry it
- purge-check: max-age=0 on 200 and 304, purged _payload.json, a second
  purge after re-caching, X-Real-IP refused, 404 on a server without a token
- README: cachePurgeToken row and a Site cache purge section
2026-10-10 18:27:12 +02:00

221 lines
10 KiB
JavaScript

#!/usr/bin/env node
// Site cache purge check: proves on a built Nuxt server with swr route rules
// that a page cached before a content change shows the change on the first
// request after a purge, and that the purge route refuses unauthenticated,
// wrong-token and proxied requests.
//
// node purge-check.mjs --output <.output dir> --fixtures <dir> --kind post|category --slug <slug> --path <page path>
//
// It also checks that route-cached pages and their 304 revalidations tell
// browsers max-age=0, that a page's _payload.json (when the build serves
// one) is purged too, that a second purge after re-caching runs (the route
// is never cached itself) and that a server without a token answers 404.
// The fixtures are copied to a temporary directory, so the source fixtures
// never change. The last line is "purge-check: ok (<n> checks)" on success;
// every failure prints "purge-check: FAIL ..." and exits 1.
import { randomBytes } from 'node:crypto'
import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { startFixtureApi } from './fixture-api.mjs'
import { startNuxtServer } from './nuxt-server.mjs'
const PURGE_PATH = '/api/__journal__/cache/purge'
/** @param {string[]} argv */
function parseArgs(argv) {
/** @type {Record<string, string>} */
const out = {}
const names = new Set(['--output', '--fixtures', '--kind', '--slug', '--path'])
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]
if (!names.has(arg)) throw new Error(`unknown argument ${arg}`)
const v = argv[++i]
if (v === undefined) throw new Error(`${arg} needs a value`)
out[arg.slice(2)] = v
}
for (const name of names) {
if (!out[name.slice(2)]) throw new Error('--output, --fixtures, --kind, --slug and --path are required')
}
if (out.kind !== 'post' && out.kind !== 'category') throw new Error(`--kind must be post or category, got ${out.kind}`)
if (!out.path.startsWith('/')) throw new Error(`--path must start with "/", got ${out.path}`)
return /** @type {{ output: string, fixtures: string, kind: 'post' | 'category', slug: string, path: string }} */ (out)
}
/** @param {any[]} nodes @returns {any[]} */
function flatten(nodes) {
return (nodes ?? []).flatMap((n) => [n, ...flatten(n.children)])
}
/**
* Appends a marker paragraph to the post's content and content_html, or to
* the category's content, in the fixture directory.
* @param {string} dir @param {'post' | 'category'} kind @param {string} slug @param {string} marker
*/
function appendMarker(dir, kind, slug, marker) {
const file = join(dir, kind === 'post' ? 'posts.json' : 'categories.json')
const rows = JSON.parse(readFileSync(file, 'utf8'))
const row = (kind === 'post' ? rows : flatten(rows)).find((/** @type {any} */ r) => r.slug === slug)
if (!row) throw new Error(`no ${kind} with slug ${slug} in ${file}`)
const para = `\n<p>${marker}</p>\n`
if (kind === 'post') {
row.content = (row.content ?? '') + `\n\n${marker}\n`
row.content_html = (row.content_html ?? '') + para
} else {
row.content = (row.content ?? '') + para
}
writeFileSync(file, JSON.stringify(rows, null, 2))
}
/** @param {string} base @param {string} path @param {Record<string, string>} [headers] */
async function get(base, path, headers = {}) {
const res = await fetch(base + path, { redirect: 'manual', headers, signal: AbortSignal.timeout(20000) })
return { status: res.status, headers: res.headers, body: await res.text() }
}
/** @param {string} base @param {{ kind: string, slug: string }} event @param {Record<string, string>} headers */
async function purge(base, event, headers) {
const res = await fetch(base + PURGE_PATH, {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(event),
signal: AbortSignal.timeout(20000),
})
const text = await res.text()
/** @type {any} */
let json = null
try {
json = JSON.parse(text)
} catch {
json = null
}
return { status: res.status, json, text }
}
/** The payload path Nuxt serves for a page path. @param {string} path */
function payloadPath(path) {
return `${path.replace(/\/+$/, '')}/_payload.json`
}
/** @param {string | null} value */
function revalidates(value) {
return /(^|[\s,])max-age=0(\s*,|\s*$)/.test(value ?? '') && /(^|[\s,])s-maxage=/.test(value ?? '')
}
async function main() {
const args = parseArgs(process.argv.slice(2))
const event = { kind: args.kind, slug: args.slug }
const dir = mkdtempSync(join(tmpdir(), 'purge-check-'))
cpSync(resolve(args.fixtures), dir, { recursive: true })
const token = randomBytes(24).toString('hex')
const auth = { authorization: `Bearer ${token}` }
const marker = `purge-check-marker-${randomBytes(6).toString('hex')}`
const second = `purge-check-second-${randomBytes(6).toString('hex')}`
/** @type {string[]} */
const failures = []
let checks = 0
/** @param {boolean} ok @param {string} what */
const check = (ok, what) => {
checks++
if (!ok) failures.push(what)
return ok
}
const api = await startFixtureApi({ dir })
/** @type {{ url: string, close: () => Promise<void> } | null} */
let nuxt = null
// The steps stop at the first failure that makes the later ones
// meaningless; the failures are reported after the servers stop.
const steps = async () => {
nuxt = await startNuxtServer({
outputDir: args.output,
apiBase: `${api.url}/_journal/api/v1`,
env: { NUXT_JOURNAL_CACHE_PURGE_TOKEN: token },
})
const base = nuxt.url
const page = args.path
const payload = payloadPath(page)
// 1. The page (and its payload, when the build has one) render and are cached.
const first = await get(base, page)
if (!check(first.status === 200, `GET ${page} before the change: status ${first.status}, want 200`)) return
const hasPayload = (await get(base, payload)).status === 200
// 2. Change the content behind the API; the cached page must not show it.
appendMarker(dir, args.kind, args.slug, marker)
api.reload()
const cached = await get(base, page)
check(cached.status === 200, `GET ${page} after the change: status ${cached.status}, want 200`)
if (!check(!cached.body.includes(marker), `GET ${page} shows the change before any purge: the page is not route-cached (missing swr route rules?)`)) return
// 3. An authorized purge removes the cached entries.
const purged = await purge(base, event, auth)
check(purged.status === 200, `authorized purge: status ${purged.status}, want 200 (${purged.text.slice(0, 200)})`)
check(typeof purged.json?.purged === 'number' && purged.json.purged >= 1, `authorized purge: answer ${purged.text.slice(0, 200)}, want purged >= 1`)
// 4. The next request shows the change and tells browsers to revalidate.
const fresh = await get(base, page)
check(fresh.status === 200 && fresh.body.includes(marker), `GET ${page} after the purge: status ${fresh.status}, change shown: ${fresh.body.includes(marker)}`)
const cc = fresh.headers.get('cache-control')
check(revalidates(cc), `GET ${page} after the purge: cache-control "${cc}", want max-age=0 and s-maxage`)
const etag = fresh.headers.get('etag')
if (check(!!etag, `GET ${page} after the purge: no ETag`)) {
const revalidated = await get(base, page, { 'if-none-match': /** @type {string} */ (etag) })
check(revalidated.status === 304, `conditional GET ${page}: status ${revalidated.status}, want 304`)
const cc304 = revalidated.headers.get('cache-control')
check(revalidates(cc304), `conditional GET ${page}: cache-control "${cc304}", want max-age=0 and s-maxage`)
}
if (hasPayload) {
const p = await get(base, payload)
check(p.status === 200 && p.body.includes(marker), `GET ${payload} after the purge: status ${p.status}, change shown: ${p.body.includes(marker)}`)
}
// 5. A second purge after the page was cached again runs too: the purge
// route itself is never route-cached.
appendMarker(dir, args.kind, args.slug, second)
api.reload()
const recached = await get(base, page)
check(!recached.body.includes(second), `GET ${page} after the second change: shown before the second purge (page not re-cached)`)
const again = await purge(base, event, auth)
check(again.status === 200 && typeof again.json?.purged === 'number' && again.json.purged >= 1, `second purge: status ${again.status}, answer ${again.text.slice(0, 200)}, want 200 with purged >= 1`)
const fresh2 = await get(base, page)
check(fresh2.body.includes(second), `GET ${page} after the second purge: the second change is not shown (the purge answer came from a cache)`)
// 6. Refused purges.
const none = await purge(base, event, {})
check(none.status === 401, `purge without a token: status ${none.status}, want 401`)
const wrong = await purge(base, event, { authorization: `Bearer ${randomBytes(24).toString('hex')}` })
check(wrong.status === 401, `purge with a wrong token: status ${wrong.status}, want 401`)
const proxied = await purge(base, event, { ...auth, 'x-forwarded-for': '203.0.113.7' })
check(proxied.status === 404, `proxied purge with the right token: status ${proxied.status}, want 404`)
const realIP = await purge(base, event, { ...auth, 'x-real-ip': '203.0.113.7' })
check(realIP.status === 404, `purge with X-Real-IP and the right token: status ${realIP.status}, want 404`)
// 7. A server without a token has no purge route.
await nuxt.close()
nuxt = await startNuxtServer({ outputDir: args.output, apiBase: `${api.url}/_journal/api/v1`, env: { NUXT_JOURNAL_CACHE_PURGE_TOKEN: '' } })
const disabled = await purge(nuxt.url, event, auth)
check(disabled.status === 404, `purge on a server without a token: status ${disabled.status}, want 404`)
}
try {
await steps()
} finally {
if (nuxt) await /** @type {{ close: () => Promise<void> }} */ (nuxt).close()
await api.close()
rmSync(dir, { recursive: true, force: true })
}
if (failures.length > 0) {
for (const f of failures) console.error(`purge-check: FAIL ${f}`)
process.exit(1)
}
console.log(`purge-check: ok (${checks} checks)`)
}
main().catch((err) => {
console.error(`purge-check: FAIL setup: ${err instanceof Error ? err.message : String(err)}`)
process.exit(1)
})