@klnap/cache-invalidation 0.0.0-stage → 0.1.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/CHANGELOG.md +145 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/dist/consumers/next/compile-tag-template.d.ts +16 -0
- package/dist/consumers/next/compile-tag-template.js +83 -0
- package/dist/consumers/next/consumer-types.d.ts +98 -0
- package/dist/consumers/next/consumer-types.js +3 -0
- package/dist/consumers/next/define-cache.d.ts +4 -0
- package/dist/consumers/next/define-cache.js +281 -0
- package/dist/consumers/next/host-types.d.ts +44 -0
- package/dist/consumers/next/host-types.js +3 -0
- package/dist/consumers/next/index.d.ts +5 -0
- package/dist/consumers/next/index.js +2 -0
- package/dist/consumers/next/param-values.d.ts +8 -0
- package/dist/consumers/next/param-values.js +23 -0
- package/dist/consumers/next/profile.d.ts +2 -0
- package/dist/consumers/next/profile.js +18 -0
- package/dist/consumers/next/registry-builders.d.ts +3 -0
- package/dist/consumers/next/registry-builders.js +155 -0
- package/dist/consumers/next/revalidation-handler.d.ts +6 -0
- package/dist/consumers/next/revalidation-handler.js +2 -0
- package/dist/consumers/next/runtime.d.ts +5 -0
- package/dist/consumers/next/runtime.js +560 -0
- package/dist/core/cloudevents.d.ts +27 -0
- package/dist/core/cloudevents.js +172 -0
- package/dist/core/dispatch-outcome.d.ts +4 -0
- package/dist/core/dispatch-outcome.js +17 -0
- package/dist/core/errors.d.ts +16 -0
- package/dist/core/errors.js +28 -0
- package/dist/core/event-limits.d.ts +15 -0
- package/dist/core/event-limits.js +20 -0
- package/dist/core/event-selector.d.ts +9 -0
- package/dist/core/event-selector.js +5 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.js +6 -0
- package/dist/core/resource-changed-schema.d.ts +35 -0
- package/dist/core/resource-changed-schema.js +12 -0
- package/dist/core/standard-schema.d.ts +2 -0
- package/dist/core/standard-schema.js +7 -0
- package/dist/core/types.d.ts +35 -0
- package/dist/core/types.js +1 -0
- package/dist/core/url-segment.d.ts +2 -0
- package/dist/core/url-segment.js +17 -0
- package/dist/dispatchers/http/index.d.ts +20 -0
- package/dist/dispatchers/http/index.js +274 -0
- package/dist/dispatchers/http/targets.d.ts +14 -0
- package/dist/dispatchers/http/targets.js +26 -0
- package/dist/dispatchers/index.d.ts +1 -0
- package/dist/dispatchers/index.js +1 -0
- package/dist/producers/payload/exclude-fields.d.ts +19 -0
- package/dist/producers/payload/exclude-fields.js +75 -0
- package/dist/producers/payload/index.d.ts +4 -0
- package/dist/producers/payload/index.js +3 -0
- package/dist/producers/payload/lifecycle/deferred.d.ts +55 -0
- package/dist/producers/payload/lifecycle/deferred.js +111 -0
- package/dist/producers/payload/lifecycle/dispatch.d.ts +18 -0
- package/dist/producers/payload/lifecycle/dispatch.js +21 -0
- package/dist/producers/payload/lifecycle/doc-content.d.ts +8 -0
- package/dist/producers/payload/lifecycle/doc-content.js +88 -0
- package/dist/producers/payload/lifecycle/draft-status.d.ts +6 -0
- package/dist/producers/payload/lifecycle/draft-status.js +15 -0
- package/dist/producers/payload/lifecycle/helpers.d.ts +13 -0
- package/dist/producers/payload/lifecycle/helpers.js +12 -0
- package/dist/producers/payload/lifecycle/identifier-field.d.ts +8 -0
- package/dist/producers/payload/lifecycle/identifier-field.js +48 -0
- package/dist/producers/payload/lifecycle/identifiers.d.ts +4 -0
- package/dist/producers/payload/lifecycle/identifiers.js +5 -0
- package/dist/producers/payload/lifecycle/locale-published.d.ts +7 -0
- package/dist/producers/payload/lifecycle/locale-published.js +19 -0
- package/dist/producers/payload/lifecycle/locale.d.ts +24 -0
- package/dist/producers/payload/lifecycle/locale.js +44 -0
- package/dist/producers/payload/lifecycle/log.d.ts +31 -0
- package/dist/producers/payload/lifecycle/log.js +67 -0
- package/dist/producers/payload/lifecycle/media-equality.d.ts +4 -0
- package/dist/producers/payload/lifecycle/media-equality.js +36 -0
- package/dist/producers/payload/lifecycle/operation.d.ts +2 -0
- package/dist/producers/payload/lifecycle/operation.js +7 -0
- package/dist/producers/payload/lifecycle/orderable-hooks.d.ts +21 -0
- package/dist/producers/payload/lifecycle/orderable-hooks.js +26 -0
- package/dist/producers/payload/lifecycle/orderable-neighbors.d.ts +21 -0
- package/dist/producers/payload/lifecycle/orderable-neighbors.js +151 -0
- package/dist/producers/payload/lifecycle/public-snapshots.d.ts +16 -0
- package/dist/producers/payload/lifecycle/public-snapshots.js +173 -0
- package/dist/producers/payload/lifecycle/revalidate.d.ts +16 -0
- package/dist/producers/payload/lifecycle/revalidate.js +162 -0
- package/dist/producers/payload/lifecycle/skip-rules.d.ts +19 -0
- package/dist/producers/payload/lifecycle/skip-rules.js +57 -0
- package/dist/producers/payload/lifecycle/types.d.ts +32 -0
- package/dist/producers/payload/lifecycle/types.js +1 -0
- package/dist/producers/payload/media/media-references.d.ts +31 -0
- package/dist/producers/payload/media/media-references.js +127 -0
- package/dist/producers/payload/media/resolve-media-affected-locales.d.ts +22 -0
- package/dist/producers/payload/media/resolve-media-affected-locales.js +70 -0
- package/dist/producers/payload/media/resolve-media-dependents.d.ts +39 -0
- package/dist/producers/payload/media/resolve-media-dependents.js +157 -0
- package/dist/producers/payload/media/resolve-media-slug.d.ts +7 -0
- package/dist/producers/payload/media/resolve-media-slug.js +17 -0
- package/dist/producers/payload/media/revalidate-media-dependents.d.ts +14 -0
- package/dist/producers/payload/media/revalidate-media-dependents.js +222 -0
- package/dist/producers/payload/plugin.d.ts +36 -0
- package/dist/producers/payload/plugin.js +235 -0
- package/dist/producers/payload/publish-all/context.d.ts +2 -0
- package/dist/producers/payload/publish-all/context.js +2 -0
- package/dist/producers/payload/publish-all/edited-locale.d.ts +5 -0
- package/dist/producers/payload/publish-all/edited-locale.js +5 -0
- package/dist/producers/payload/publish-all/index.d.ts +3 -0
- package/dist/producers/payload/publish-all/index.js +3 -0
- package/dist/producers/payload/publish-all/localization.d.ts +7 -0
- package/dist/producers/payload/publish-all/localization.js +1 -0
- package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.d.ts +19 -0
- package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.js +32 -0
- package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.d.ts +2 -0
- package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.js +145 -0
- package/dist/producers/payload/publish-all/read-localized-scalar.d.ts +2 -0
- package/dist/producers/payload/publish-all/read-localized-scalar.js +24 -0
- package/dist/producers/payload/publish-all/request-flags.d.ts +13 -0
- package/dist/producers/payload/publish-all/request-flags.js +9 -0
- package/dist/producers/payload/publish-all/restore-guard.d.ts +2 -0
- package/dist/producers/payload/publish-all/restore-guard.js +12 -0
- package/dist/producers/payload/publish-all/restore-locales-after-publish-all.d.ts +2 -0
- package/dist/producers/payload/publish-all/restore-locales-after-publish-all.js +85 -0
- package/dist/producers/payload/revalidation-custom.d.ts +37 -0
- package/dist/producers/payload/revalidation-custom.js +54 -0
- package/dist/producers/payload/schema.d.ts +3 -0
- package/dist/producers/payload/schema.js +23 -0
- package/docs/concepts/architecture.md +32 -0
- package/docs/concepts/cache-tags.md +97 -0
- package/docs/concepts/event-contract.md +38 -0
- package/docs/consumers/custom.md +19 -0
- package/docs/consumers/next.md +277 -0
- package/docs/dispatchers/custom.md +38 -0
- package/docs/dispatchers/http.md +66 -0
- package/docs/extending.md +26 -0
- package/docs/migration/0.3.0-to-0.4.0.md +67 -0
- package/docs/migration/0.4.0-to-0.5.0.md +60 -0
- package/docs/migration/0.5.x-to-0.0.0.md +143 -0
- package/docs/producers/custom.md +63 -0
- package/docs/producers/payload-media-dependencies.md +45 -0
- package/docs/producers/payload.md +140 -0
- package/docs/reliability.md +35 -0
- package/docs/security.md +34 -0
- package/docs/troubleshooting.md +14 -0
- package/package.json +120 -4
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
import { revalidatePath, revalidateTag } from 'next/cache.js';
|
|
2
|
+
import { Webhook } from 'standardwebhooks';
|
|
3
|
+
import { assertLimit, DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_EVENT_ITEMS, MAX_BODY_BYTES_CEILING, MAX_EVENT_ITEMS_CEILING, } from '../../core/event-limits.js';
|
|
4
|
+
import { CacheConfigurationError, CacheRequestError, CacheSchemaError, CacheSourceError, CLOUDEVENTS_BATCH_JSON, CLOUDEVENTS_JSON, CloudEventParseError, parseCloudEvents, validateStandardSchema, } from '../../core/index.js';
|
|
5
|
+
import { resourceChangeV1DataSchema, resourceChangeV1DataSchemaUri, } from '../../core/resource-changed-schema.js';
|
|
6
|
+
import { getTagTemplateMeta } from './compile-tag-template.js';
|
|
7
|
+
import { CACHE_DEFINITION, } from './consumer-types.js';
|
|
8
|
+
import { PATH_SCOPE_SYMBOL, PATH_SYMBOL, TAG_SYMBOL, } from './host-types.js';
|
|
9
|
+
import { assertPathValue, assertTagValue, pathValueProblem } from './param-values.js';
|
|
10
|
+
import { isCacheProfile } from './profile.js';
|
|
11
|
+
class SourceAuthorizationError extends Error {
|
|
12
|
+
}
|
|
13
|
+
const withEventData = (event, data) => {
|
|
14
|
+
const { data_base64: _dataBase64, ...attributes } = event;
|
|
15
|
+
return { ...attributes, data };
|
|
16
|
+
};
|
|
17
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
18
|
+
const asList = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
19
|
+
const readRawBody = async (request, maxBytes, timeoutMs) => {
|
|
20
|
+
const declared = request.headers.get('content-length');
|
|
21
|
+
if (declared && Number(declared) > maxBytes)
|
|
22
|
+
throw new CacheSourceError('Request body too large');
|
|
23
|
+
if (!request.body)
|
|
24
|
+
return new Uint8Array();
|
|
25
|
+
const reader = request.body.getReader();
|
|
26
|
+
const chunks = [];
|
|
27
|
+
let size = 0;
|
|
28
|
+
let timeout;
|
|
29
|
+
let timedOut = false;
|
|
30
|
+
let rejectTimeout = () => { };
|
|
31
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
32
|
+
rejectTimeout = reject;
|
|
33
|
+
});
|
|
34
|
+
timeout = setTimeout(() => {
|
|
35
|
+
timedOut = true;
|
|
36
|
+
rejectTimeout(new CacheSourceError('Request body timed out'));
|
|
37
|
+
void reader.cancel().catch(() => undefined);
|
|
38
|
+
}, timeoutMs);
|
|
39
|
+
try {
|
|
40
|
+
while (true) {
|
|
41
|
+
const next = await Promise.race([reader.read(), timeoutPromise]);
|
|
42
|
+
if (next.done)
|
|
43
|
+
break;
|
|
44
|
+
size += next.value.byteLength;
|
|
45
|
+
if (size > maxBytes) {
|
|
46
|
+
void reader.cancel().catch(() => undefined);
|
|
47
|
+
throw new CacheSourceError('Request body too large');
|
|
48
|
+
}
|
|
49
|
+
chunks.push(next.value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
clearTimeout(timeout);
|
|
54
|
+
if (!timedOut)
|
|
55
|
+
reader.releaseLock();
|
|
56
|
+
}
|
|
57
|
+
const body = new Uint8Array(size);
|
|
58
|
+
let offset = 0;
|
|
59
|
+
for (const chunk of chunks) {
|
|
60
|
+
body.set(chunk, offset);
|
|
61
|
+
offset += chunk.byteLength;
|
|
62
|
+
}
|
|
63
|
+
return body;
|
|
64
|
+
};
|
|
65
|
+
const json = (value) => {
|
|
66
|
+
if (Array.isArray(value))
|
|
67
|
+
return `[${value.map(json).join(',')}]`;
|
|
68
|
+
if (isRecord(value))
|
|
69
|
+
return `{${Object.keys(value)
|
|
70
|
+
.sort()
|
|
71
|
+
.map((key) => `${JSON.stringify(key)}:${json(value[key])}`)
|
|
72
|
+
.join(',')}}`;
|
|
73
|
+
return JSON.stringify(value);
|
|
74
|
+
};
|
|
75
|
+
const response = (status, body, requestId) => new Response(JSON.stringify(body), {
|
|
76
|
+
status,
|
|
77
|
+
headers: { 'Content-Type': 'application/json', 'X-Cache-Request-Id': requestId },
|
|
78
|
+
});
|
|
79
|
+
const buildParams = (data) => {
|
|
80
|
+
const params = Object.create(null);
|
|
81
|
+
for (const [key, value] of Object.entries(data))
|
|
82
|
+
if (typeof value === 'string')
|
|
83
|
+
params[key] = value;
|
|
84
|
+
if (typeof data.id === 'number' && Number.isFinite(data.id))
|
|
85
|
+
params.id = String(data.id);
|
|
86
|
+
return params;
|
|
87
|
+
};
|
|
88
|
+
const resolveReference = (reference, data, kind, tags, paths) => {
|
|
89
|
+
const symbols = kind === 'tag' ? tags : paths;
|
|
90
|
+
const symbol = kind === 'tag' ? TAG_SYMBOL : PATH_SYMBOL;
|
|
91
|
+
if (typeof reference !== 'function' ||
|
|
92
|
+
!(symbol in reference) ||
|
|
93
|
+
symbols[reference[symbol]] !== reference)
|
|
94
|
+
throw new CacheSchemaError(`Invalid ${kind} reference`);
|
|
95
|
+
const scope = kind === 'path'
|
|
96
|
+
? reference[PATH_SCOPE_SYMBOL]
|
|
97
|
+
: undefined;
|
|
98
|
+
if (scope)
|
|
99
|
+
return { value: reference(), scope };
|
|
100
|
+
const meta = getTagTemplateMeta(reference);
|
|
101
|
+
if (!meta)
|
|
102
|
+
throw new CacheSchemaError(`Invalid ${kind} reference`);
|
|
103
|
+
const params = buildParams(data);
|
|
104
|
+
for (const key of meta.keys) {
|
|
105
|
+
const value = params[key];
|
|
106
|
+
if (value === undefined || value === '')
|
|
107
|
+
throw new CacheSchemaError(`Missing required ${kind} parameter "${key}"`);
|
|
108
|
+
if (kind === 'tag')
|
|
109
|
+
assertTagValue(key, value);
|
|
110
|
+
else
|
|
111
|
+
assertPathValue(key, value);
|
|
112
|
+
}
|
|
113
|
+
const value = meta.render(params);
|
|
114
|
+
if (!value)
|
|
115
|
+
throw new CacheSchemaError(`Missing required ${kind} parameter`);
|
|
116
|
+
return { value };
|
|
117
|
+
};
|
|
118
|
+
const normalizeRule = (action) => {
|
|
119
|
+
if (Array.isArray(action)) {
|
|
120
|
+
const tags = [];
|
|
121
|
+
const paths = [];
|
|
122
|
+
for (const item of action) {
|
|
123
|
+
if (Array.isArray(item) && item.length === 2 && Array.isArray(item[1])) {
|
|
124
|
+
if (!isCacheProfile(item[0]) || item[1].length === 0)
|
|
125
|
+
throw new CacheSchemaError('Invalid Next.js tag profile group');
|
|
126
|
+
for (const reference of item[1])
|
|
127
|
+
tags.push({ reference, profile: item[0] });
|
|
128
|
+
}
|
|
129
|
+
else if (typeof item === 'function' && PATH_SYMBOL in item)
|
|
130
|
+
paths.push(item);
|
|
131
|
+
else
|
|
132
|
+
tags.push({ reference: item });
|
|
133
|
+
}
|
|
134
|
+
return { tags, paths, operations: [] };
|
|
135
|
+
}
|
|
136
|
+
if (!isRecord(action))
|
|
137
|
+
throw new CacheSchemaError('Invalid cache invalidation rule');
|
|
138
|
+
for (const key of Object.keys(action))
|
|
139
|
+
if (key !== 'tags' && key !== 'paths' && key !== 'operations')
|
|
140
|
+
throw new CacheSchemaError(`Unsupported cache rule property "${key}"`);
|
|
141
|
+
const tags = [];
|
|
142
|
+
for (const item of asList(action.tags)) {
|
|
143
|
+
if (Array.isArray(item) && item.length === 2 && Array.isArray(item[1])) {
|
|
144
|
+
if (!isCacheProfile(item[0]) || item[1].length === 0)
|
|
145
|
+
throw new CacheSchemaError('Invalid Next.js tag profile group');
|
|
146
|
+
for (const reference of item[1])
|
|
147
|
+
tags.push({ reference, profile: item[0] });
|
|
148
|
+
}
|
|
149
|
+
else
|
|
150
|
+
tags.push({ reference: item });
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
tags,
|
|
154
|
+
paths: asList(action.paths),
|
|
155
|
+
operations: asList(action.operations),
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
const renderOperations = (result, contextData, config, max, allowTemplateParameters = true) => {
|
|
159
|
+
const data = isRecord(contextData) ? contextData : Object.create(null);
|
|
160
|
+
const ops = [];
|
|
161
|
+
const custom = [];
|
|
162
|
+
const normalized = normalizeRule(result);
|
|
163
|
+
const defaultProfile = config.profile ?? { expire: 0 };
|
|
164
|
+
if (!isCacheProfile(defaultProfile))
|
|
165
|
+
throw new CacheSchemaError('Invalid Next.js cache profile');
|
|
166
|
+
for (const operation of normalized.operations) {
|
|
167
|
+
if (!isRecord(operation) ||
|
|
168
|
+
typeof operation.layer !== 'string' ||
|
|
169
|
+
!operation.layer ||
|
|
170
|
+
!Object.hasOwn(config.execute ?? {}, operation.layer))
|
|
171
|
+
throw new CacheConfigurationError('Rule references an unconfigured execution layer');
|
|
172
|
+
custom.push({ layer: operation.layer, value: operation.value });
|
|
173
|
+
}
|
|
174
|
+
for (const item of normalized.tags) {
|
|
175
|
+
const raw = item.reference;
|
|
176
|
+
const chosen = item.profile ?? defaultProfile;
|
|
177
|
+
if (!isCacheProfile(chosen))
|
|
178
|
+
throw new CacheSchemaError('Invalid Next.js cache profile');
|
|
179
|
+
let value;
|
|
180
|
+
if (typeof raw === 'function' && TAG_SYMBOL in raw) {
|
|
181
|
+
const meta = getTagTemplateMeta(raw);
|
|
182
|
+
if (!allowTemplateParameters && meta?.keys.length)
|
|
183
|
+
throw new CacheSchemaError('Parameterized declarative rules require Resource Change V1; use a programmable rule for custom event data');
|
|
184
|
+
value = resolveReference(raw, data, 'tag', config.tags, config.paths).value;
|
|
185
|
+
}
|
|
186
|
+
else if (typeof raw === 'string')
|
|
187
|
+
value = raw;
|
|
188
|
+
else
|
|
189
|
+
throw new CacheSchemaError('Invalid Next.js cache tag');
|
|
190
|
+
if (!value || value.length > 256)
|
|
191
|
+
throw new CacheSchemaError('Invalid Next.js cache tag');
|
|
192
|
+
ops.push({ kind: 'tag', value, profile: chosen });
|
|
193
|
+
}
|
|
194
|
+
for (const item of normalized.paths) {
|
|
195
|
+
const raw = Array.isArray(item) ? item[0] : item;
|
|
196
|
+
const override = Array.isArray(item) ? item[1] : undefined;
|
|
197
|
+
if (override !== undefined && override !== 'page' && override !== 'layout')
|
|
198
|
+
throw new CacheSchemaError('Invalid Next.js cache path scope');
|
|
199
|
+
let value;
|
|
200
|
+
let scope;
|
|
201
|
+
if (typeof raw === 'function' && PATH_SYMBOL in raw) {
|
|
202
|
+
const meta = getTagTemplateMeta(raw);
|
|
203
|
+
if (!allowTemplateParameters && meta?.keys.length)
|
|
204
|
+
throw new CacheSchemaError('Parameterized declarative rules require Resource Change V1; use a programmable rule for custom event data');
|
|
205
|
+
const rendered = resolveReference(raw, data, 'path', config.tags, config.paths);
|
|
206
|
+
value = rendered.value;
|
|
207
|
+
scope = override ?? rendered.scope;
|
|
208
|
+
}
|
|
209
|
+
else if (typeof raw === 'string')
|
|
210
|
+
value = raw;
|
|
211
|
+
else
|
|
212
|
+
throw new CacheSchemaError('Invalid Next.js cache path');
|
|
213
|
+
if (!value.startsWith('/') ||
|
|
214
|
+
value.length > 1024 ||
|
|
215
|
+
/[?#\\]/.test(value) ||
|
|
216
|
+
value.includes('//'))
|
|
217
|
+
throw new CacheSchemaError('Invalid Next.js cache path');
|
|
218
|
+
for (const segment of value.split('/').slice(1)) {
|
|
219
|
+
if (segment === '.' || segment === '..')
|
|
220
|
+
throw new CacheSchemaError('Invalid Next.js cache path');
|
|
221
|
+
if (!segment.includes('[') && pathValueProblem(segment))
|
|
222
|
+
throw new CacheSchemaError('Invalid Next.js cache path');
|
|
223
|
+
}
|
|
224
|
+
ops.push({ kind: 'path', value, ...(scope ? { type: scope } : {}) });
|
|
225
|
+
}
|
|
226
|
+
if (ops.length + custom.length > max)
|
|
227
|
+
throw new CacheSourceError(`Too many operations (max ${max})`);
|
|
228
|
+
return { cache: ops, custom };
|
|
229
|
+
};
|
|
230
|
+
const validateChange = async (event) => {
|
|
231
|
+
if (event.dataschema !== resourceChangeV1DataSchemaUri)
|
|
232
|
+
return undefined;
|
|
233
|
+
try {
|
|
234
|
+
return (await validateStandardSchema(resourceChangeV1DataSchema, event.data));
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
throw new CacheSchemaError('Invalid Resource Change V1 data');
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
const snapshots = (change) => [change.before, change.after].filter((value) => value !== null);
|
|
241
|
+
const planEvent = async (event, change, config, max) => {
|
|
242
|
+
const action = Object.hasOwn(config.rules, event.type)
|
|
243
|
+
? config.rules[event.type]
|
|
244
|
+
: undefined;
|
|
245
|
+
const plans = [];
|
|
246
|
+
const makeContext = (data) => ({
|
|
247
|
+
event: event,
|
|
248
|
+
data,
|
|
249
|
+
tags: config.tagHelpers,
|
|
250
|
+
paths: config.pathHelpers,
|
|
251
|
+
});
|
|
252
|
+
if (action !== undefined) {
|
|
253
|
+
if (typeof action === 'function') {
|
|
254
|
+
const data = event.data ?? change;
|
|
255
|
+
const result = action(makeContext(data));
|
|
256
|
+
if (result) {
|
|
257
|
+
const rendered = renderOperations(result, data, config, max);
|
|
258
|
+
plans.push({ event, data, ...rendered });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
else if (!change) {
|
|
262
|
+
const rendered = renderOperations(action, event.data, config, max, false);
|
|
263
|
+
plans.push({ event, data: event.data, ...rendered });
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
const direct = normalizeRule(action);
|
|
267
|
+
const primaryData = snapshots(change);
|
|
268
|
+
if (!primaryData.length) {
|
|
269
|
+
const onlyStatic = {
|
|
270
|
+
tags: direct.tags
|
|
271
|
+
.filter((item) => typeof item.reference !== 'function')
|
|
272
|
+
.map((item) => item.profile === undefined ? item.reference : [item.profile, [item.reference]]),
|
|
273
|
+
paths: direct.paths.filter((item) => typeof (Array.isArray(item) ? item[0] : item) !== 'function'),
|
|
274
|
+
operations: direct.operations,
|
|
275
|
+
};
|
|
276
|
+
if (onlyStatic.tags.length || onlyStatic.paths.length)
|
|
277
|
+
plans.push({
|
|
278
|
+
event,
|
|
279
|
+
data: change,
|
|
280
|
+
...renderOperations(onlyStatic, {}, config, max),
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
for (const data of primaryData)
|
|
284
|
+
plans.push({ event, data, ...renderOperations(action, data, config, max) });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (change) {
|
|
288
|
+
for (const dependent of change.affected ?? []) {
|
|
289
|
+
const dependentAction = Object.hasOwn(config.rules, dependent.type)
|
|
290
|
+
? config.rules[dependent.type]
|
|
291
|
+
: undefined;
|
|
292
|
+
if (!dependentAction || typeof dependentAction === 'function')
|
|
293
|
+
continue;
|
|
294
|
+
const data = dependent.data;
|
|
295
|
+
const ops = renderOperations(dependentAction, data, config, max);
|
|
296
|
+
plans.push({ event, data, custom: [], cache: ops.cache });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return plans;
|
|
300
|
+
};
|
|
301
|
+
const errorStatus = (error) => error instanceof CacheRequestError
|
|
302
|
+
? 401
|
|
303
|
+
: error instanceof SourceAuthorizationError
|
|
304
|
+
? 403
|
|
305
|
+
: error instanceof CloudEventParseError
|
|
306
|
+
? 400
|
|
307
|
+
: error instanceof CacheSourceError
|
|
308
|
+
? error.message === 'Request body timed out'
|
|
309
|
+
? 408
|
|
310
|
+
: error.message === 'Request body too large' || error.message.startsWith('Too many')
|
|
311
|
+
? 413
|
|
312
|
+
: 400
|
|
313
|
+
: error instanceof CacheSchemaError || error instanceof CacheConfigurationError
|
|
314
|
+
? 400
|
|
315
|
+
: 500;
|
|
316
|
+
const publicError = (status) => {
|
|
317
|
+
if (status === 401)
|
|
318
|
+
return 'Unauthorized';
|
|
319
|
+
if (status === 403)
|
|
320
|
+
return 'Event source not allowed';
|
|
321
|
+
if (status === 408)
|
|
322
|
+
return 'Request timed out';
|
|
323
|
+
if (status === 413)
|
|
324
|
+
return 'Request limit exceeded';
|
|
325
|
+
if (status >= 500)
|
|
326
|
+
return 'Internal server error';
|
|
327
|
+
return 'Invalid request';
|
|
328
|
+
};
|
|
329
|
+
export const createCacheInvalidationPostHandler = (input) => {
|
|
330
|
+
if (typeof input.secret !== 'string' || input.secret.length === 0)
|
|
331
|
+
throw new CacheConfigurationError('A non-empty webhook secret is required');
|
|
332
|
+
const state = input.config[CACHE_DEFINITION];
|
|
333
|
+
const config = {
|
|
334
|
+
tags: state.tagReferences,
|
|
335
|
+
paths: state.pathReferences,
|
|
336
|
+
tagHelpers: input.config.tags,
|
|
337
|
+
pathHelpers: input.config.paths,
|
|
338
|
+
schemas: state.schemas,
|
|
339
|
+
rules: state.rules,
|
|
340
|
+
profile: state.profile,
|
|
341
|
+
execute: state.execute,
|
|
342
|
+
};
|
|
343
|
+
const allowedSources = input.allowedSources;
|
|
344
|
+
if (allowedSources?.some((source) => {
|
|
345
|
+
try {
|
|
346
|
+
return new URL(source).protocol.length === 0;
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
}))
|
|
352
|
+
throw new CacheConfigurationError('allowedSources must contain absolute URIs');
|
|
353
|
+
const maxBodyBytes = assertLimit('maxBodyBytes', input.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES, MAX_BODY_BYTES_CEILING);
|
|
354
|
+
const bodyTimeoutMs = assertLimit('bodyTimeoutMs', input.bodyTimeoutMs ?? 15_000, 60_000);
|
|
355
|
+
const maxEvents = assertLimit('maxEvents', input.maxEvents ?? DEFAULT_MAX_EVENT_ITEMS, MAX_EVENT_ITEMS_CEILING);
|
|
356
|
+
const maxOperations = assertLimit('maxOperations', input.maxOperations ?? 1000, 10_000);
|
|
357
|
+
const executionTimeoutMs = assertLimit('executionTimeoutMs', input.executionTimeoutMs ?? 15_000, 60_000);
|
|
358
|
+
const webhook = new Webhook(input.secret);
|
|
359
|
+
const POST = async (request) => {
|
|
360
|
+
const requestId = crypto.randomUUID();
|
|
361
|
+
if (request.method !== 'POST')
|
|
362
|
+
return response(405, { error: 'Method not allowed' }, requestId);
|
|
363
|
+
const contentType = request.headers.get('content-type') ?? '';
|
|
364
|
+
const mediaType = contentType.split(';', 1)[0].trim().toLowerCase();
|
|
365
|
+
if (mediaType !== CLOUDEVENTS_JSON && mediaType !== CLOUDEVENTS_BATCH_JSON)
|
|
366
|
+
return response(415, { error: 'Unsupported content type' }, requestId);
|
|
367
|
+
let webhookId = '';
|
|
368
|
+
try {
|
|
369
|
+
const body = await readRawBody(request, maxBodyBytes, bodyTimeoutMs);
|
|
370
|
+
const id = request.headers.get('webhook-id') ?? '';
|
|
371
|
+
const timestamp = request.headers.get('webhook-timestamp') ?? '';
|
|
372
|
+
const signature = request.headers.get('webhook-signature') ?? '';
|
|
373
|
+
if (!id || !/^\d+$/.test(timestamp) || !signature)
|
|
374
|
+
throw new CacheRequestError('Invalid webhook headers');
|
|
375
|
+
try {
|
|
376
|
+
webhook.verify(body, { 'webhook-id': id, 'webhook-timestamp': timestamp, 'webhook-signature': signature }, { jsonParse: false });
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
throw new CacheRequestError('Invalid webhook signature or timestamp');
|
|
380
|
+
}
|
|
381
|
+
webhookId = id;
|
|
382
|
+
let parsed;
|
|
383
|
+
try {
|
|
384
|
+
parsed = JSON.parse(new TextDecoder().decode(body));
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
throw new CacheSchemaError('Invalid JSON');
|
|
388
|
+
}
|
|
389
|
+
const events = parseCloudEvents(parsed, contentType);
|
|
390
|
+
if (events.length > maxEvents)
|
|
391
|
+
throw new CacheSourceError(`Too many events (max ${maxEvents})`);
|
|
392
|
+
const unique = new Map();
|
|
393
|
+
for (const event of events) {
|
|
394
|
+
if (allowedSources && !allowedSources.includes(event.source))
|
|
395
|
+
throw new SourceAuthorizationError('Disallowed event source');
|
|
396
|
+
const key = `${event.source}\0${event.id}`;
|
|
397
|
+
const previous = unique.get(key);
|
|
398
|
+
if (previous && json(previous) !== json(event))
|
|
399
|
+
throw new CacheSchemaError('Conflicting CloudEvents share the same source and id');
|
|
400
|
+
if (!previous)
|
|
401
|
+
unique.set(key, event);
|
|
402
|
+
}
|
|
403
|
+
const plans = [];
|
|
404
|
+
const ignored = [];
|
|
405
|
+
let operationCount = 0;
|
|
406
|
+
for (let event of unique.values()) {
|
|
407
|
+
const hasRule = Object.hasOwn(config.rules, event.type);
|
|
408
|
+
const knownSchema = Object.hasOwn(config.schemas, event.type)
|
|
409
|
+
? config.schemas[event.type]
|
|
410
|
+
: undefined;
|
|
411
|
+
let change = await validateChange(event);
|
|
412
|
+
if (!hasRule && !change) {
|
|
413
|
+
ignored.push(event.id);
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (knownSchema)
|
|
417
|
+
event = withEventData(event, await validateStandardSchema(knownSchema, event.data));
|
|
418
|
+
if (change) {
|
|
419
|
+
change = await validateChange(withEventData(event, event.data));
|
|
420
|
+
event = withEventData(event, change);
|
|
421
|
+
}
|
|
422
|
+
const eventPlans = await planEvent(event, change, config, maxOperations - operationCount);
|
|
423
|
+
if (!eventPlans.length)
|
|
424
|
+
ignored.push(event.id);
|
|
425
|
+
for (const plan of eventPlans)
|
|
426
|
+
operationCount += plan.cache.length + plan.custom.length;
|
|
427
|
+
if (operationCount > maxOperations)
|
|
428
|
+
throw new CacheSourceError(`Too many operations (max ${maxOperations})`);
|
|
429
|
+
plans.push(...eventPlans);
|
|
430
|
+
}
|
|
431
|
+
const profiles = new Map();
|
|
432
|
+
for (const op of plans.flatMap((plan) => plan.cache))
|
|
433
|
+
if (op.kind === 'tag') {
|
|
434
|
+
const value = typeof op.profile === 'string' ? op.profile : JSON.stringify(op.profile);
|
|
435
|
+
const prior = profiles.get(op.value);
|
|
436
|
+
if (prior !== undefined && prior !== value)
|
|
437
|
+
throw new CacheSchemaError(`Conflicting cache profiles for tag "${op.value}"`);
|
|
438
|
+
profiles.set(op.value, value);
|
|
439
|
+
}
|
|
440
|
+
const results = ignored.map((eventId) => ({
|
|
441
|
+
layer: 'next',
|
|
442
|
+
operation: eventId,
|
|
443
|
+
status: 'skipped',
|
|
444
|
+
error: { code: 'UNHANDLED_EVENT', message: 'No local rule handles this event type' },
|
|
445
|
+
}));
|
|
446
|
+
const eligible = [];
|
|
447
|
+
let failed = false;
|
|
448
|
+
for (const plan of plans) {
|
|
449
|
+
let succeeded = true;
|
|
450
|
+
for (const [index, operation] of plan.custom.entries()) {
|
|
451
|
+
const executor = config.execute?.[operation.layer];
|
|
452
|
+
const controller = new AbortController();
|
|
453
|
+
let timer;
|
|
454
|
+
try {
|
|
455
|
+
await Promise.race([
|
|
456
|
+
executor({
|
|
457
|
+
event: plan.event,
|
|
458
|
+
data: plan.data,
|
|
459
|
+
value: operation.value,
|
|
460
|
+
signal: controller.signal,
|
|
461
|
+
}),
|
|
462
|
+
new Promise((_, reject) => {
|
|
463
|
+
timer = setTimeout(() => {
|
|
464
|
+
reject(new Error('Custom cache execution timed out'));
|
|
465
|
+
controller.abort();
|
|
466
|
+
}, executionTimeoutMs);
|
|
467
|
+
}),
|
|
468
|
+
]);
|
|
469
|
+
results.push({ layer: operation.layer, operation: plan.event.id, status: 'success' });
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
failed = true;
|
|
473
|
+
succeeded = false;
|
|
474
|
+
const timeout = controller.signal.aborted;
|
|
475
|
+
results.push({
|
|
476
|
+
layer: operation.layer,
|
|
477
|
+
operation: plan.event.id,
|
|
478
|
+
status: 'failed',
|
|
479
|
+
error: {
|
|
480
|
+
code: timeout ? 'CUSTOM_EXECUTION_TIMEOUT' : 'CUSTOM_EXECUTION_FAILED',
|
|
481
|
+
message: timeout
|
|
482
|
+
? 'Custom cache execution timed out'
|
|
483
|
+
: 'Custom cache execution failed',
|
|
484
|
+
},
|
|
485
|
+
});
|
|
486
|
+
for (const skipped of plan.custom.slice(index + 1))
|
|
487
|
+
results.push({
|
|
488
|
+
layer: skipped.layer,
|
|
489
|
+
operation: plan.event.id,
|
|
490
|
+
status: 'skipped',
|
|
491
|
+
error: {
|
|
492
|
+
code: 'DEPENDENCY_FAILED',
|
|
493
|
+
message: 'A preceding custom operation failed',
|
|
494
|
+
},
|
|
495
|
+
});
|
|
496
|
+
input.logger?.error?.({
|
|
497
|
+
requestId,
|
|
498
|
+
webhookId,
|
|
499
|
+
eventId: plan.event.id,
|
|
500
|
+
error: error instanceof Error ? error.name : 'UnknownError',
|
|
501
|
+
}, 'cache.layer.failed');
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
clearTimeout(timer);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (succeeded)
|
|
509
|
+
eligible.push(...plan.cache);
|
|
510
|
+
else
|
|
511
|
+
for (const operation of plan.cache)
|
|
512
|
+
results.push({
|
|
513
|
+
layer: 'next',
|
|
514
|
+
operation: operation.kind,
|
|
515
|
+
status: 'skipped',
|
|
516
|
+
error: {
|
|
517
|
+
code: 'DEPENDENCY_FAILED',
|
|
518
|
+
message: 'A custom operation for this rule failed',
|
|
519
|
+
},
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
const dedup = new Map();
|
|
523
|
+
for (const operation of eligible)
|
|
524
|
+
dedup.set(JSON.stringify(operation), operation);
|
|
525
|
+
for (const operation of dedup.values()) {
|
|
526
|
+
try {
|
|
527
|
+
if (operation.kind === 'tag')
|
|
528
|
+
await revalidateTag(operation.value, operation.profile);
|
|
529
|
+
else if (operation.type)
|
|
530
|
+
await revalidatePath(operation.value, operation.type);
|
|
531
|
+
else
|
|
532
|
+
await revalidatePath(operation.value);
|
|
533
|
+
results.push({ layer: 'next', operation: operation.kind, status: 'success' });
|
|
534
|
+
}
|
|
535
|
+
catch (error) {
|
|
536
|
+
failed = true;
|
|
537
|
+
results.push({
|
|
538
|
+
layer: 'next',
|
|
539
|
+
operation: operation.kind,
|
|
540
|
+
status: 'failed',
|
|
541
|
+
error: { code: 'CACHE_OPERATION_FAILED', message: 'Next.js cache operation failed' },
|
|
542
|
+
});
|
|
543
|
+
input.logger?.error?.({ requestId, webhookId, error: error instanceof Error ? error.name : 'UnknownError' }, 'cache.operation.failed');
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return response(failed ? 500 : 200, { requestId, results }, requestId);
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
const status = errorStatus(error);
|
|
550
|
+
input.logger?.error?.({
|
|
551
|
+
requestId,
|
|
552
|
+
status,
|
|
553
|
+
webhookId,
|
|
554
|
+
error: error instanceof Error ? error.name : 'UnknownError',
|
|
555
|
+
}, 'cache.request.failed');
|
|
556
|
+
return response(status, { requestId, error: publicError(status) }, requestId);
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
return POST;
|
|
560
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare const CLOUDEVENTS_JSON = "application/cloudevents+json";
|
|
2
|
+
export declare const CLOUDEVENTS_BATCH_JSON = "application/cloudevents-batch+json";
|
|
3
|
+
type CloudEventBase = {
|
|
4
|
+
specversion: '1.0';
|
|
5
|
+
id: string;
|
|
6
|
+
source: string;
|
|
7
|
+
type: string;
|
|
8
|
+
time?: string | null;
|
|
9
|
+
subject?: string | null;
|
|
10
|
+
datacontenttype?: string | null;
|
|
11
|
+
dataschema?: string | null;
|
|
12
|
+
[extension: string]: unknown;
|
|
13
|
+
};
|
|
14
|
+
export type CloudEvent<TData = unknown> = CloudEventBase & ({
|
|
15
|
+
data?: TData;
|
|
16
|
+
data_base64?: never;
|
|
17
|
+
} | {
|
|
18
|
+
data?: never;
|
|
19
|
+
data_base64: string | null;
|
|
20
|
+
});
|
|
21
|
+
export declare const serializeCloudEvent: (event: CloudEvent) => string;
|
|
22
|
+
export declare const serializeCloudEventBatch: (events: readonly CloudEvent[]) => string;
|
|
23
|
+
export declare class CloudEventParseError extends Error {
|
|
24
|
+
constructor(message: string);
|
|
25
|
+
}
|
|
26
|
+
export declare const parseCloudEvents: (value: unknown, contentType: string) => CloudEvent[];
|
|
27
|
+
export {};
|