esa-pcg-cli 0.1.18 → 0.1.20-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -27
- package/dist/_inline-overrides.js +3 -3
- package/dist/_protocol/endpoints.d.ts +1 -0
- package/dist/_protocol/endpoints.js +2 -1
- package/dist/_protocol/keys.d.ts +14 -0
- package/dist/_protocol/keys.js +14 -2
- package/dist/_protocol/types.d.ts +84 -0
- package/dist/_protocol/types.js +1 -1
- package/dist/adapters/wrappers/node-server.d.ts +7 -1
- package/dist/adapters/wrappers/node-server.js +6 -3
- package/dist/artifacts/layout.d.ts +20 -0
- package/dist/artifacts/layout.js +168 -0
- package/dist/artifacts/next.d.ts +8 -0
- package/dist/artifacts/next.js +202 -0
- package/dist/artifacts/nuxt.d.ts +7 -0
- package/dist/artifacts/nuxt.js +72 -0
- package/dist/astro/build-metadata.d.ts +23 -0
- package/dist/astro/build-metadata.js +4 -0
- package/dist/astro/compatibility/matrix.d.ts +36 -0
- package/dist/astro/compatibility/matrix.js +131 -0
- package/dist/astro/overlay/config-overlay.d.ts +16 -0
- package/dist/astro/overlay/config-overlay.js +330 -0
- package/dist/astro/packaging/artifact-layout.d.ts +11 -0
- package/dist/astro/packaging/artifact-layout.js +190 -0
- package/dist/astro/packaging/integrity.d.ts +11 -0
- package/dist/astro/packaging/integrity.js +97 -0
- package/dist/astro/packaging/trace-server.d.ts +23 -0
- package/dist/astro/packaging/trace-server.js +182 -0
- package/dist/astro-runtime/cache-provider.mjs +665 -0
- package/dist/astro-runtime/gateway-client.mjs +81 -0
- package/dist/astro-runtime/image-endpoint.mjs +161 -0
- package/dist/astro-runtime/request-header-logger.mjs +68 -0
- package/dist/astro-runtime/session-driver-core.mjs +71 -0
- package/dist/astro-runtime/session-driver-v5.mjs +9 -0
- package/dist/astro-runtime/session-driver-v6plus.mjs +9 -0
- package/dist/bin/cli.d.ts +1 -0
- package/dist/bin/cli.js +3 -2
- package/dist/commands/build-astro.d.ts +13 -0
- package/dist/commands/build-astro.js +232 -0
- package/dist/commands/build-next.d.ts +15 -0
- package/dist/commands/build-next.js +233 -0
- package/dist/commands/build-nuxt.d.ts +21 -0
- package/dist/commands/build-nuxt.js +239 -0
- package/dist/commands/build.d.ts +4 -0
- package/dist/commands/build.js +79 -185
- package/dist/commands/deploy.js +4 -4
- package/dist/commands/purge.js +2 -2
- package/dist/commands/serve.d.ts +6 -1
- package/dist/commands/serve.js +104 -74
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/nitro-preset/driver.mjs +304 -0
- package/dist/nitro-preset/index.mjs +49 -0
- package/dist/nitro-preset/package.json +30 -0
- package/dist/runtime/gateway-auth.d.ts +6 -3
- package/dist/runtime/gateway-auth.js +12 -12
- package/package.json +8 -5
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
// Astro Route Cache provider backed by Gateway storage, tag epochs, and ESA purge.
|
|
2
|
+
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
5
|
+
import { gatewayFetch, loadGatewayConfig } from './gateway-client.mjs';
|
|
6
|
+
|
|
7
|
+
const GLOBAL_CACHE_KEY = Symbol.for('pcg.astro.local.route-cache');
|
|
8
|
+
const GLOBAL_REFRESH_KEY = Symbol.for('pcg.astro.route-cache.refreshes');
|
|
9
|
+
const GLOBAL_EDGE_CONTEXT_KEY = Symbol.for('pcg.astro.edge-context.als');
|
|
10
|
+
const LOGICAL_TAG_HEADER = 'X-PCG-Astro-Logical-Tags';
|
|
11
|
+
const PRIVATE_CACHE_CONTROL =
|
|
12
|
+
'private, no-cache, no-store, max-age=0, must-revalidate';
|
|
13
|
+
const MAX_TAGS = 64;
|
|
14
|
+
const MAX_TAG_LENGTH = 128;
|
|
15
|
+
const ESA_CACHE_TAG_BATCH_SIZE = 30;
|
|
16
|
+
const TRACKING_PARAMS = new Set([
|
|
17
|
+
'fbclid',
|
|
18
|
+
'gclid',
|
|
19
|
+
'gbraid',
|
|
20
|
+
'wbraid',
|
|
21
|
+
'dclid',
|
|
22
|
+
'msclkid',
|
|
23
|
+
'mc_cid',
|
|
24
|
+
'mc_eid',
|
|
25
|
+
'_ga',
|
|
26
|
+
'_gl',
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const edgeContextStorage =
|
|
30
|
+
globalThis[GLOBAL_EDGE_CONTEXT_KEY] ||
|
|
31
|
+
(globalThis[GLOBAL_EDGE_CONTEXT_KEY] = new AsyncLocalStorage());
|
|
32
|
+
|
|
33
|
+
function firstHeaderValue(value) {
|
|
34
|
+
const first = value?.split(',')[0]?.trim();
|
|
35
|
+
return first || undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseSiteId(value) {
|
|
39
|
+
if (value === undefined || value === null) return undefined;
|
|
40
|
+
const trimmed = String(value).trim();
|
|
41
|
+
if (!trimmed) return undefined;
|
|
42
|
+
const numeric = Number(trimmed);
|
|
43
|
+
return Number.isFinite(numeric) && trimmed === String(numeric)
|
|
44
|
+
? numeric
|
|
45
|
+
: trimmed;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function edgeContextFromRequest(request) {
|
|
49
|
+
const forwardedHost = request.headers.get('x-forwarded-host');
|
|
50
|
+
const hostname =
|
|
51
|
+
firstHeaderValue(request.headers.get('host')) ||
|
|
52
|
+
firstHeaderValue(forwardedHost);
|
|
53
|
+
const siteId = parseSiteId(request.headers.get('x-er-origin-site-id'));
|
|
54
|
+
return { hostname, siteId };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function resolvePurgeTarget() {
|
|
58
|
+
const context = edgeContextStorage.getStore() || {};
|
|
59
|
+
const hostname =
|
|
60
|
+
context.hostname ||
|
|
61
|
+
process.env.ESA_CACHE_GW_HOSTNAME ||
|
|
62
|
+
process.env.PCG_HOSTNAME ||
|
|
63
|
+
process.env.PCG_ASTRO_HOSTNAME;
|
|
64
|
+
const siteId = parseSiteId(
|
|
65
|
+
context.siteId ??
|
|
66
|
+
process.env.ESA_CACHE_GW_SITE_ID ??
|
|
67
|
+
process.env.PCG_SITE_ID ??
|
|
68
|
+
process.env.PCG_ASTRO_SITE_ID
|
|
69
|
+
);
|
|
70
|
+
if (!hostname || siteId === undefined || siteId === '') {
|
|
71
|
+
console.warn(
|
|
72
|
+
`[pcg astro cache] ESA purge skipped: edge context missing ` +
|
|
73
|
+
`(hostname=${hostname ?? '∅'} siteId=${siteId ?? '∅'}); ` +
|
|
74
|
+
'the inbound request must include host and x-er-origin-site-id'
|
|
75
|
+
);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
return { hostname, siteId };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function cacheMap() {
|
|
82
|
+
if (!globalThis[GLOBAL_CACHE_KEY]) globalThis[GLOBAL_CACHE_KEY] = new Map();
|
|
83
|
+
return globalThis[GLOBAL_CACHE_KEY];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function refreshMap() {
|
|
87
|
+
if (!globalThis[GLOBAL_REFRESH_KEY]) {
|
|
88
|
+
globalThis[GLOBAL_REFRESH_KEY] = new Map();
|
|
89
|
+
}
|
|
90
|
+
return globalThis[GLOBAL_REFRESH_KEY];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function digest(value) {
|
|
94
|
+
return createHash('sha256').update(value).digest('hex');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function normalizeUrl(input) {
|
|
98
|
+
const url = new URL(input);
|
|
99
|
+
for (const key of [...url.searchParams.keys()]) {
|
|
100
|
+
if (
|
|
101
|
+
key.toLowerCase().startsWith('utm_') ||
|
|
102
|
+
TRACKING_PARAMS.has(key.toLowerCase())
|
|
103
|
+
) {
|
|
104
|
+
url.searchParams.delete(key);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
url.searchParams.sort();
|
|
108
|
+
url.hash = '';
|
|
109
|
+
return url.href;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function primaryCacheKey(request) {
|
|
113
|
+
const gateway = loadGatewayConfig();
|
|
114
|
+
const scope = gateway ? `${gateway.appId}:${gateway.version}` : 'local:local';
|
|
115
|
+
const varySeed = [
|
|
116
|
+
request.headers.get('accept') || '',
|
|
117
|
+
request.headers.get('accept-language') || '',
|
|
118
|
+
].join('\0');
|
|
119
|
+
return `${scope}\0${normalizeUrl(request.url)}\0${varySeed}`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function storageKey(gateway, cacheKey) {
|
|
123
|
+
return `${gateway.appId}/${gateway.version}/__astro-route/${digest(
|
|
124
|
+
cacheKey
|
|
125
|
+
)}.cache`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function tagKey(gateway, tag) {
|
|
129
|
+
return `${gateway.version}/astro/${digest(tag)}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function pathTag(pathname) {
|
|
133
|
+
// Keep byte-for-byte compatibility with Astro's provider-utils.pathTag().
|
|
134
|
+
return `astro-path:${pathname}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function normalizeTags(tags) {
|
|
138
|
+
const result = [...new Set((tags || []).map(tag => String(tag)))];
|
|
139
|
+
if (result.length > MAX_TAGS) {
|
|
140
|
+
throw new RangeError(`Astro cache tags exceed the ${MAX_TAGS} tag limit`);
|
|
141
|
+
}
|
|
142
|
+
for (const tag of result) {
|
|
143
|
+
if (
|
|
144
|
+
tag.length === 0 ||
|
|
145
|
+
tag.length > MAX_TAG_LENGTH ||
|
|
146
|
+
/[\0\r\n,]/.test(tag)
|
|
147
|
+
) {
|
|
148
|
+
throw new RangeError('Astro cache tag is empty, too long, or invalid');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function esaCacheTag(gateway, tag) {
|
|
155
|
+
return `pcg-${digest(`${gateway.appId}:${gateway.version}:${tag}`)}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function runRefreshOnce(key, task) {
|
|
159
|
+
const current = refreshMap().get(key);
|
|
160
|
+
if (current) return current;
|
|
161
|
+
const refresh = Promise.resolve()
|
|
162
|
+
.then(task)
|
|
163
|
+
.finally(() => refreshMap().delete(key));
|
|
164
|
+
refreshMap().set(key, refresh);
|
|
165
|
+
return refresh;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function parseCacheControl(value) {
|
|
169
|
+
let maxAge = 0;
|
|
170
|
+
let swr = 0;
|
|
171
|
+
for (const part of (value || '').split(',')) {
|
|
172
|
+
const token = part.trim().toLowerCase();
|
|
173
|
+
if (token.startsWith('max-age=')) {
|
|
174
|
+
maxAge = Number.parseInt(token.slice(8), 10) || 0;
|
|
175
|
+
} else if (token.startsWith('stale-while-revalidate=')) {
|
|
176
|
+
swr = Number.parseInt(token.slice(23), 10) || 0;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return { maxAge, swr };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function responseLogicalTags(response, request) {
|
|
183
|
+
let tags = [];
|
|
184
|
+
const encoded = response.headers.get(LOGICAL_TAG_HEADER);
|
|
185
|
+
if (encoded) {
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(encoded);
|
|
188
|
+
if (Array.isArray(parsed)) tags = parsed;
|
|
189
|
+
} catch {
|
|
190
|
+
throw new Error('Invalid internal Astro cache tag header');
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
tags.push(pathTag(new URL(request.url).pathname));
|
|
194
|
+
return normalizeTags(tags);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function varyHeaders(response) {
|
|
198
|
+
const value = response.headers.get('vary');
|
|
199
|
+
if (!value) return [];
|
|
200
|
+
if (value.split(',').some(name => name.trim() === '*')) return null;
|
|
201
|
+
return value
|
|
202
|
+
.split(',')
|
|
203
|
+
.map(name => name.trim().toLowerCase())
|
|
204
|
+
.filter(name => name && name !== 'cookie' && name !== 'set-cookie');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function matchesVary(request, envelope) {
|
|
208
|
+
for (const name of envelope.vary || []) {
|
|
209
|
+
if (
|
|
210
|
+
(request.headers.get(name) || '') !== (envelope.varyValues?.[name] || '')
|
|
211
|
+
) {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function cacheAge(envelope) {
|
|
219
|
+
return (Date.now() - envelope.storedAt) / 1000;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function setSharedCacheControl(response, maxAge, swr) {
|
|
223
|
+
// Match Next.js' ISR contract: only supply the shared-cache policy when the
|
|
224
|
+
// application did not set Cache-Control itself. In particular, never
|
|
225
|
+
// overwrite private/no-store directives with a public cache policy.
|
|
226
|
+
if (response.headers.has('cache-control')) return response;
|
|
227
|
+
const directives = [`s-maxage=${Math.max(0, maxAge)}`];
|
|
228
|
+
if (swr > 0) directives.push(`stale-while-revalidate=${swr}`);
|
|
229
|
+
response.headers.set('Cache-Control', directives.join(', '));
|
|
230
|
+
return response;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function setEnvelopeCacheControl(response, envelope) {
|
|
234
|
+
const age = Math.max(0, cacheAge(envelope));
|
|
235
|
+
const totalRemaining = Math.max(
|
|
236
|
+
0,
|
|
237
|
+
Math.ceil(envelope.maxAge + envelope.swr - age)
|
|
238
|
+
);
|
|
239
|
+
const freshRemaining = Math.max(0, Math.ceil(envelope.maxAge - age));
|
|
240
|
+
// A stale L2 response is exposed to L1 for at most one fresh second while
|
|
241
|
+
// the provider refreshes it in the background. Deduct that second from SWR
|
|
242
|
+
// so the combined L1 + L2 windows track the policy at whole-second precision.
|
|
243
|
+
const maxAge =
|
|
244
|
+
freshRemaining > 0 ? freshRemaining : Math.min(1, totalRemaining);
|
|
245
|
+
const swr = Math.max(0, totalRemaining - maxAge);
|
|
246
|
+
response.headers.set(
|
|
247
|
+
'CDN-Cache-Control',
|
|
248
|
+
`public, max-age=${maxAge}, stale-while-revalidate=${swr}`
|
|
249
|
+
);
|
|
250
|
+
if (response.headers.has('cache-control')) {
|
|
251
|
+
// An application policy wins, just as it does in Next.js. Propagate the
|
|
252
|
+
// L2 object's age so a downstream shared cache does not restart that
|
|
253
|
+
// policy's full lifetime on every L2 hit.
|
|
254
|
+
response.headers.set('Age', String(Math.floor(age)));
|
|
255
|
+
return response;
|
|
256
|
+
}
|
|
257
|
+
return setSharedCacheControl(response, maxAge, swr);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function responseFromEnvelope(envelope, state) {
|
|
261
|
+
const response = new Response(Buffer.from(envelope.body, 'base64'), {
|
|
262
|
+
status: envelope.status,
|
|
263
|
+
headers: envelope.headers,
|
|
264
|
+
});
|
|
265
|
+
setEnvelopeCacheControl(response, envelope);
|
|
266
|
+
response.headers.set('X-Astro-Cache', state);
|
|
267
|
+
return response;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function requestIsPrivate(request) {
|
|
271
|
+
return request.method !== 'GET' || request.headers.has('authorization');
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function responseIsPrivate(response) {
|
|
275
|
+
const cacheControl = response.headers.get('cache-control') || '';
|
|
276
|
+
return (
|
|
277
|
+
response.headers.has('set-cookie') ||
|
|
278
|
+
/(?:^|,)\s*(?:private|no-store)(?:\s|,|$)/i.test(cacheControl)
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function stripSharedCacheHeaders(response, forcePrivate = false) {
|
|
283
|
+
response.headers.delete(LOGICAL_TAG_HEADER);
|
|
284
|
+
response.headers.delete('Cache-Tag');
|
|
285
|
+
response.headers.delete('CDN-Cache-Control');
|
|
286
|
+
if (
|
|
287
|
+
forcePrivate &&
|
|
288
|
+
!/(?:^|,)\s*(?:private|no-store)(?:\s|,|$)/i.test(
|
|
289
|
+
response.headers.get('cache-control') || ''
|
|
290
|
+
)
|
|
291
|
+
) {
|
|
292
|
+
response.headers.set('Cache-Control', PRIVATE_CACHE_CONTROL);
|
|
293
|
+
}
|
|
294
|
+
return response;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function bypassSharedCache(next, forcePrivate = false) {
|
|
298
|
+
const response = await next();
|
|
299
|
+
return stripSharedCacheHeaders(
|
|
300
|
+
response,
|
|
301
|
+
forcePrivate || responseIsPrivate(response)
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function serializeResponse(
|
|
306
|
+
response,
|
|
307
|
+
request,
|
|
308
|
+
maxAge,
|
|
309
|
+
swr,
|
|
310
|
+
tags,
|
|
311
|
+
maxBytes
|
|
312
|
+
) {
|
|
313
|
+
const declared = Number(response.headers.get('content-length'));
|
|
314
|
+
if (Number.isFinite(declared) && declared > maxBytes) return null;
|
|
315
|
+
const body = await readBodyLimited(response, maxBytes);
|
|
316
|
+
if (body === null) return null;
|
|
317
|
+
const headers = [];
|
|
318
|
+
response.headers.forEach((value, name) => {
|
|
319
|
+
const lower = name.toLowerCase();
|
|
320
|
+
if (lower !== 'set-cookie' && lower !== LOGICAL_TAG_HEADER.toLowerCase()) {
|
|
321
|
+
headers.push([name, value]);
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
const vary = varyHeaders(response);
|
|
325
|
+
// `Vary: *` explicitly means that the response cannot be reused for a
|
|
326
|
+
// subsequent request, so it must never enter the shared L2 cache.
|
|
327
|
+
if (vary === null) return null;
|
|
328
|
+
const varyValues = {};
|
|
329
|
+
for (const name of vary) varyValues[name] = request.headers.get(name) || '';
|
|
330
|
+
return {
|
|
331
|
+
schemaVersion: 1,
|
|
332
|
+
body: body.toString('base64'),
|
|
333
|
+
status: response.status,
|
|
334
|
+
headers,
|
|
335
|
+
storedAt: Date.now(),
|
|
336
|
+
maxAge,
|
|
337
|
+
swr,
|
|
338
|
+
tags,
|
|
339
|
+
vary,
|
|
340
|
+
varyValues,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function readBodyLimited(response, maxBytes) {
|
|
345
|
+
if (!response.body) return Buffer.alloc(0);
|
|
346
|
+
const reader = response.body.getReader();
|
|
347
|
+
const chunks = [];
|
|
348
|
+
let total = 0;
|
|
349
|
+
try {
|
|
350
|
+
while (true) {
|
|
351
|
+
const { done, value } = await reader.read();
|
|
352
|
+
if (done) break;
|
|
353
|
+
const chunk = Buffer.from(value);
|
|
354
|
+
total += chunk.byteLength;
|
|
355
|
+
if (total > maxBytes) {
|
|
356
|
+
// A cloned Response is backed by ReadableStream.tee(); waiting for the
|
|
357
|
+
// clone's cancel promise would deadlock until the caller consumes the
|
|
358
|
+
// original branch, which cannot happen before onRequest returns.
|
|
359
|
+
void reader.cancel('Astro cache object exceeds its byte limit');
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
chunks.push(chunk);
|
|
363
|
+
}
|
|
364
|
+
return Buffer.concat(chunks, total);
|
|
365
|
+
} finally {
|
|
366
|
+
reader.releaseLock();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function readRemote(gateway, cacheKey) {
|
|
371
|
+
const key = storageKey(gateway, cacheKey);
|
|
372
|
+
try {
|
|
373
|
+
const response = await gatewayFetch(gateway, `/storage/${key}`, {
|
|
374
|
+
method: 'GET',
|
|
375
|
+
timeoutMs: 5000,
|
|
376
|
+
});
|
|
377
|
+
if (response.status === 404) return null;
|
|
378
|
+
if (!response.ok) throw new Error(`status ${response.status}`);
|
|
379
|
+
const value = await response.json();
|
|
380
|
+
return value?.schemaVersion === 1 ? value : null;
|
|
381
|
+
} catch (error) {
|
|
382
|
+
console.warn(`[pcg astro cache] L2 read failed: ${String(error)}`);
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function writeRemote(gateway, cacheKey, envelope) {
|
|
388
|
+
const key = storageKey(gateway, cacheKey);
|
|
389
|
+
const response = await gatewayFetch(gateway, `/storage/${key}`, {
|
|
390
|
+
method: 'PUT',
|
|
391
|
+
headers: { 'Content-Type': 'application/vnd.pcg.astro-cache+json' },
|
|
392
|
+
body: JSON.stringify(envelope),
|
|
393
|
+
timeoutMs: 10000,
|
|
394
|
+
});
|
|
395
|
+
if (!response.ok) throw new Error(`L2 write failed with ${response.status}`);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async function lastInvalidatedAt(gateway, tags) {
|
|
399
|
+
if (tags.length === 0) return 0;
|
|
400
|
+
try {
|
|
401
|
+
const primaryKeys = tags.map(tag => [
|
|
402
|
+
{ name: 'app_id', value: gateway.appId },
|
|
403
|
+
{ name: 'tag', value: tagKey(gateway, tag) },
|
|
404
|
+
]);
|
|
405
|
+
const response = await gatewayFetch(gateway, '/table/batch-get-row', {
|
|
406
|
+
method: 'POST',
|
|
407
|
+
headers: { 'Content-Type': 'application/json' },
|
|
408
|
+
body: JSON.stringify({ primaryKeys }),
|
|
409
|
+
timeoutMs: 3000,
|
|
410
|
+
});
|
|
411
|
+
if (!response.ok) throw new Error(`status ${response.status}`);
|
|
412
|
+
const body = await response.json();
|
|
413
|
+
let latest = 0;
|
|
414
|
+
for (const row of body.rows || []) {
|
|
415
|
+
for (const column of row.columns || []) {
|
|
416
|
+
if (
|
|
417
|
+
column.name === 'revalidatedAt' &&
|
|
418
|
+
typeof column.value === 'number'
|
|
419
|
+
) {
|
|
420
|
+
latest = Math.max(latest, column.value);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return latest;
|
|
425
|
+
} catch (error) {
|
|
426
|
+
console.warn(`[pcg astro cache] tag read failed: ${String(error)}`);
|
|
427
|
+
// Fail closed: a tag backend failure must not serve a possibly invalid object.
|
|
428
|
+
return Number.POSITIVE_INFINITY;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function writeInvalidations(gateway, tags) {
|
|
433
|
+
if (tags.length === 0) return;
|
|
434
|
+
const now = Date.now();
|
|
435
|
+
const rows = tags.map(tag => ({
|
|
436
|
+
primaryKey: [
|
|
437
|
+
{ name: 'app_id', value: gateway.appId },
|
|
438
|
+
{ name: 'tag', value: tagKey(gateway, tag) },
|
|
439
|
+
],
|
|
440
|
+
columns: [{ name: 'revalidatedAt', value: now }],
|
|
441
|
+
}));
|
|
442
|
+
const response = await gatewayFetch(gateway, '/table/batch-write', {
|
|
443
|
+
method: 'POST',
|
|
444
|
+
headers: { 'Content-Type': 'application/json' },
|
|
445
|
+
body: JSON.stringify({ rows }),
|
|
446
|
+
timeoutMs: 5000,
|
|
447
|
+
});
|
|
448
|
+
if (!response.ok) {
|
|
449
|
+
throw new Error(`tag invalidation failed with ${response.status}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async function purgeEsa(gateway, options, tags) {
|
|
454
|
+
const target = resolvePurgeTarget();
|
|
455
|
+
if (!target) return;
|
|
456
|
+
const { hostname, siteId } = target;
|
|
457
|
+
const bodies = [];
|
|
458
|
+
if (options.path) {
|
|
459
|
+
bodies.push({
|
|
460
|
+
hostname,
|
|
461
|
+
siteId,
|
|
462
|
+
urls: [`https://${hostname}${options.path}`],
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const explicitTags = options.tags
|
|
467
|
+
? Array.isArray(options.tags)
|
|
468
|
+
? options.tags
|
|
469
|
+
: [options.tags]
|
|
470
|
+
: [];
|
|
471
|
+
if (!options.path || explicitTags.length > 0) {
|
|
472
|
+
const cacheTags = tags.map(tag => esaCacheTag(gateway, tag));
|
|
473
|
+
for (
|
|
474
|
+
let offset = 0;
|
|
475
|
+
offset < cacheTags.length;
|
|
476
|
+
offset += ESA_CACHE_TAG_BATCH_SIZE
|
|
477
|
+
) {
|
|
478
|
+
bodies.push({
|
|
479
|
+
hostname,
|
|
480
|
+
siteId,
|
|
481
|
+
cacheTags: cacheTags.slice(offset, offset + ESA_CACHE_TAG_BATCH_SIZE),
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
for (const body of bodies) {
|
|
487
|
+
const response = await gatewayFetch(gateway, '/cache/refresh', {
|
|
488
|
+
method: 'POST',
|
|
489
|
+
headers: { 'Content-Type': 'application/json' },
|
|
490
|
+
body: JSON.stringify(body),
|
|
491
|
+
timeoutMs: 10000,
|
|
492
|
+
});
|
|
493
|
+
if (!response.ok) {
|
|
494
|
+
throw new Error(`ESA purge failed with ${response.status}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export default function pcgAstroCacheProvider(config = {}) {
|
|
500
|
+
const maxBytes = Number(config.maxObjectBytes) || 10 * 1024 * 1024;
|
|
501
|
+
const local = process.env.PCG_ASTRO_LOCAL_CACHE === '1';
|
|
502
|
+
return {
|
|
503
|
+
name: 'pcg-gateway',
|
|
504
|
+
setHeaders(options, request) {
|
|
505
|
+
const maxAge = Math.max(0, Number(options.maxAge) || 0);
|
|
506
|
+
const swr = Math.max(0, Number(options.swr) || 0);
|
|
507
|
+
const headers = new Headers();
|
|
508
|
+
headers.set(
|
|
509
|
+
'CDN-Cache-Control',
|
|
510
|
+
`public, max-age=${maxAge}, stale-while-revalidate=${swr}`
|
|
511
|
+
);
|
|
512
|
+
const logicalTags = normalizeTags([
|
|
513
|
+
...(options.tags || []),
|
|
514
|
+
...(request ? [pathTag(new URL(request.url).pathname)] : []),
|
|
515
|
+
]);
|
|
516
|
+
if (logicalTags.length) {
|
|
517
|
+
const gateway = loadGatewayConfig();
|
|
518
|
+
headers.set(
|
|
519
|
+
'Cache-Tag',
|
|
520
|
+
logicalTags
|
|
521
|
+
.map(tag => (gateway ? esaCacheTag(gateway, tag) : tag))
|
|
522
|
+
.join(',')
|
|
523
|
+
);
|
|
524
|
+
headers.set(LOGICAL_TAG_HEADER, JSON.stringify(logicalTags));
|
|
525
|
+
}
|
|
526
|
+
if (options.etag) headers.set('ETag', options.etag);
|
|
527
|
+
if (options.lastModified) {
|
|
528
|
+
headers.set(
|
|
529
|
+
'Last-Modified',
|
|
530
|
+
new Date(options.lastModified).toUTCString()
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
return headers;
|
|
534
|
+
},
|
|
535
|
+
async onRequest(context, next) {
|
|
536
|
+
return edgeContextStorage.run(
|
|
537
|
+
edgeContextFromRequest(context.request),
|
|
538
|
+
async () => {
|
|
539
|
+
if (process.env.PCG_ASTRO_BUILD === '1') {
|
|
540
|
+
return bypassSharedCache(next);
|
|
541
|
+
}
|
|
542
|
+
if (requestIsPrivate(context.request)) {
|
|
543
|
+
return bypassSharedCache(next, true);
|
|
544
|
+
}
|
|
545
|
+
const key = primaryCacheKey(context.request);
|
|
546
|
+
const gateway = loadGatewayConfig();
|
|
547
|
+
if (!local && !gateway) {
|
|
548
|
+
console.warn(
|
|
549
|
+
'[pcg astro cache] Gateway env missing; bypassing shared cache.'
|
|
550
|
+
);
|
|
551
|
+
return bypassSharedCache(next);
|
|
552
|
+
}
|
|
553
|
+
const cached = local
|
|
554
|
+
? cacheMap().get(key) || null
|
|
555
|
+
: await readRemote(gateway, key);
|
|
556
|
+
if (cached && matchesVary(context.request, cached)) {
|
|
557
|
+
const invalidatedAt = local
|
|
558
|
+
? 0
|
|
559
|
+
: await lastInvalidatedAt(gateway, cached.tags || []);
|
|
560
|
+
if (invalidatedAt <= cached.storedAt) {
|
|
561
|
+
const age = cacheAge(cached);
|
|
562
|
+
if (age < cached.maxAge)
|
|
563
|
+
return responseFromEnvelope(cached, 'HIT');
|
|
564
|
+
if (age < cached.maxAge + cached.swr) {
|
|
565
|
+
const refresh = runRefreshOnce(key, async () => {
|
|
566
|
+
let fresh;
|
|
567
|
+
try {
|
|
568
|
+
fresh = await next();
|
|
569
|
+
const policy = parseCacheControl(
|
|
570
|
+
fresh.headers.get('CDN-Cache-Control')
|
|
571
|
+
);
|
|
572
|
+
if (policy.maxAge <= 0 || responseIsPrivate(fresh)) return;
|
|
573
|
+
const tags = responseLogicalTags(fresh, context.request);
|
|
574
|
+
fresh.headers.delete(LOGICAL_TAG_HEADER);
|
|
575
|
+
const envelope = await serializeResponse(
|
|
576
|
+
fresh,
|
|
577
|
+
context.request,
|
|
578
|
+
policy.maxAge,
|
|
579
|
+
policy.swr,
|
|
580
|
+
tags,
|
|
581
|
+
maxBytes
|
|
582
|
+
);
|
|
583
|
+
if (!envelope) return;
|
|
584
|
+
if (local) cacheMap().set(key, envelope);
|
|
585
|
+
else await writeRemote(gateway, key, envelope);
|
|
586
|
+
} finally {
|
|
587
|
+
fresh?.headers.delete(LOGICAL_TAG_HEADER);
|
|
588
|
+
}
|
|
589
|
+
}).catch(error =>
|
|
590
|
+
console.warn(
|
|
591
|
+
`[pcg astro cache] revalidation failed: ${String(error)}`
|
|
592
|
+
)
|
|
593
|
+
);
|
|
594
|
+
if (context.waitUntil) context.waitUntil(refresh);
|
|
595
|
+
return responseFromEnvelope(cached, 'STALE');
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const response = await next();
|
|
601
|
+
const policy = parseCacheControl(
|
|
602
|
+
response.headers.get('CDN-Cache-Control')
|
|
603
|
+
);
|
|
604
|
+
const privateResponse = responseIsPrivate(response);
|
|
605
|
+
if (policy.maxAge <= 0 || privateResponse) {
|
|
606
|
+
return stripSharedCacheHeaders(response, privateResponse);
|
|
607
|
+
}
|
|
608
|
+
const tags = responseLogicalTags(response, context.request);
|
|
609
|
+
response.headers.delete(LOGICAL_TAG_HEADER);
|
|
610
|
+
const envelope = await serializeResponse(
|
|
611
|
+
response.clone(),
|
|
612
|
+
context.request,
|
|
613
|
+
policy.maxAge,
|
|
614
|
+
policy.swr,
|
|
615
|
+
tags,
|
|
616
|
+
maxBytes
|
|
617
|
+
);
|
|
618
|
+
if (!envelope) return stripSharedCacheHeaders(response);
|
|
619
|
+
try {
|
|
620
|
+
if (local) cacheMap().set(key, envelope);
|
|
621
|
+
else await writeRemote(gateway, key, envelope);
|
|
622
|
+
response.headers.set('X-Astro-Cache', 'MISS');
|
|
623
|
+
} catch (error) {
|
|
624
|
+
console.warn(
|
|
625
|
+
`[pcg astro cache] L2 write skipped: ${String(error)}`
|
|
626
|
+
);
|
|
627
|
+
}
|
|
628
|
+
setEnvelopeCacheControl(response, envelope);
|
|
629
|
+
return response;
|
|
630
|
+
}
|
|
631
|
+
);
|
|
632
|
+
},
|
|
633
|
+
async invalidate(options) {
|
|
634
|
+
const explicit = options.tags
|
|
635
|
+
? Array.isArray(options.tags)
|
|
636
|
+
? options.tags
|
|
637
|
+
: [options.tags]
|
|
638
|
+
: [];
|
|
639
|
+
const tags = [
|
|
640
|
+
...new Set(
|
|
641
|
+
normalizeTags([
|
|
642
|
+
...explicit,
|
|
643
|
+
...(options.path ? [pathTag(options.path)] : []),
|
|
644
|
+
])
|
|
645
|
+
),
|
|
646
|
+
];
|
|
647
|
+
if (local) {
|
|
648
|
+
for (const [key, envelope] of cacheMap()) {
|
|
649
|
+
if ((envelope.tags || []).some(tag => tags.includes(tag))) {
|
|
650
|
+
cacheMap().delete(key);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const gateway = loadGatewayConfig();
|
|
656
|
+
if (!gateway) {
|
|
657
|
+
throw new Error(
|
|
658
|
+
'[pcg astro cache] Gateway env missing during invalidation'
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
await writeInvalidations(gateway, tags);
|
|
662
|
+
await purgeEsa(gateway, options, tags);
|
|
663
|
+
},
|
|
664
|
+
};
|
|
665
|
+
}
|