-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathcache.ts
More file actions
571 lines (541 loc) · 17.7 KB
/
cache.ts
File metadata and controls
571 lines (541 loc) · 17.7 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import type {
CacheHandlerValue,
IncrementalCacheContext,
IncrementalCacheValue,
} from "types/cache";
import {
getTagsFromValue,
hasBeenRevalidated,
isStale,
writeTags,
} from "utils/cache";
import { isBinaryContentType } from "../utils/binary";
import { compareSemver } from "../utils/semver";
import { debug, error, warn } from "./logger";
export const SOFT_TAG_PREFIX = "_N_T_/";
function isFetchCache(
options?:
| boolean
| {
fetchCache?: boolean;
kindHint?: "app" | "pages" | "fetch";
kind?: "FETCH";
},
): boolean {
if (typeof options === "boolean") {
return options;
}
if (typeof options === "object") {
return (
options.kindHint === "fetch" ||
options.fetchCache ||
options.kind === "FETCH"
);
}
return false;
}
// We need to use globalThis client here as this class can be defined at load time in next 12 but client is not available at load time
export default class Cache {
public async get(
key: string,
// fetchCache is for next 13.5 and above, kindHint is for next 14 and above and boolean is for earlier versions
options?:
| boolean
| {
fetchCache?: boolean;
kindHint?: "app" | "pages" | "fetch";
tags?: string[];
softTags?: string[];
kind?: "FETCH";
},
) {
if (globalThis.openNextConfig.dangerous?.disableIncrementalCache) {
return null;
}
const softTags = typeof options === "object" ? options.softTags : [];
const tags = typeof options === "object" ? options.tags : [];
return isFetchCache(options)
? this.getFetchCache(key, softTags, tags)
: this.getIncrementalCache(key);
}
async getFetchCache(key: string, softTags?: string[], tags?: string[]) {
debug("get fetch cache", { key, softTags, tags });
try {
const cachedEntry = await globalThis.incrementalCache.get(key, "fetch");
if (cachedEntry?.value === undefined) return null;
const _tags = [...(tags ?? []), ...(softTags ?? [])];
const _lastModified = cachedEntry.lastModified ?? Date.now();
const _hasBeenRevalidated = cachedEntry.shouldBypassTagCache
? false
: await hasBeenRevalidated(key, _tags, cachedEntry);
if (_hasBeenRevalidated) return null;
// For cases where we don't have tags, we need to ensure that the soft tags are not being revalidated
// We only need to check for the path as it should already contain all the tags
if ((tags ?? []).length === 0) {
// Then we need to find the path for the given key
const path = softTags?.find(
(tag) =>
tag.startsWith(SOFT_TAG_PREFIX) &&
!tag.endsWith("layout") &&
!tag.endsWith("page"),
);
if (path) {
const hasPathBeenUpdated = cachedEntry.shouldBypassTagCache
? false
: await hasBeenRevalidated(
path.replace(SOFT_TAG_PREFIX, ""),
[],
cachedEntry,
);
if (hasPathBeenUpdated) {
// In case the path has been revalidated, we don't want to use the fetch cache
return null;
}
}
}
const _isStale = cachedEntry.shouldBypassTagCache
? false
: await isStale(key, _tags, _lastModified);
return {
lastModified: _isStale ? 1 : _lastModified,
value: cachedEntry.value,
} as CacheHandlerValue;
} catch (e) {
// We can usually ignore errors here as they are usually due to cache not being found
debug("Failed to get fetch cache", e);
return null;
}
}
async getIncrementalCache(key: string): Promise<CacheHandlerValue | null> {
try {
const cachedEntry = await globalThis.incrementalCache.get(key, "cache");
if (!cachedEntry?.value) {
return null;
}
const cacheData = cachedEntry.value;
const meta = cacheData.meta;
const tags = getTagsFromValue(cacheData);
let _lastModified = cachedEntry.lastModified ?? Date.now();
const _hasBeenRevalidated = cachedEntry.shouldBypassTagCache
? false
: await hasBeenRevalidated(key, tags, cachedEntry);
if (_hasBeenRevalidated) return null;
const _isStale = cachedEntry.shouldBypassTagCache
? false
: await isStale(key, tags, _lastModified);
const store = globalThis.__openNextAls.getStore();
if (store) {
store.lastModified = _isStale ? 1 : _lastModified;
_lastModified = store.lastModified;
}
if (cacheData?.type === "route") {
return {
lastModified: _lastModified,
value: {
kind: compareSemver(globalThis.nextVersion, ">=", "15.0.0")
? "APP_ROUTE"
: "ROUTE",
body: Buffer.from(
cacheData.body ?? Buffer.alloc(0),
isBinaryContentType(String(meta?.headers?.["content-type"]))
? "base64"
: "utf8",
),
status: meta?.status,
headers: meta?.headers,
},
} as CacheHandlerValue;
}
if (cacheData?.type === "page" || cacheData?.type === "app") {
if (
compareSemver(globalThis.nextVersion, ">=", "15.0.0") &&
cacheData?.type === "app"
) {
const segmentData = new Map<string, Buffer>();
if (cacheData.segmentData) {
for (const [segmentPath, segmentContent] of Object.entries(
cacheData.segmentData ?? {},
)) {
segmentData.set(segmentPath, Buffer.from(segmentContent));
}
}
return {
lastModified: _lastModified,
value: {
kind: "APP_PAGE",
html: cacheData.html,
rscData: Buffer.from(cacheData.rsc),
status: meta?.status,
headers: meta?.headers,
postponed: meta?.postponed,
segmentData,
},
} as CacheHandlerValue;
}
return {
lastModified: _lastModified,
value: {
kind: compareSemver(globalThis.nextVersion, ">=", "15.0.0")
? "PAGES"
: "PAGE",
html: cacheData.html,
pageData:
cacheData.type === "page" ? cacheData.json : cacheData.rsc,
status: meta?.status,
headers: meta?.headers,
},
} as CacheHandlerValue;
}
if (cacheData?.type === "redirect") {
return {
lastModified: _lastModified,
value: {
kind: "REDIRECT",
props: cacheData.props,
},
} as CacheHandlerValue;
}
warn("Unknown cache type", cacheData);
return null;
} catch (e) {
// We can usually ignore errors here as they are usually due to cache not being found
debug("Failed to get body cache", e);
return null;
}
}
async set(
key: string,
data?: IncrementalCacheValue,
ctx?: IncrementalCacheContext,
): Promise<void> {
if (globalThis.openNextConfig.dangerous?.disableIncrementalCache) {
return;
}
// This one might not even be necessary anymore
// Better be safe than sorry
const detachedPromise = globalThis.__openNextAls
.getStore()
?.pendingPromiseRunner.withResolvers<void>();
try {
if (data === null || data === undefined) {
await globalThis.incrementalCache.delete(key);
} else {
const revalidate = this.extractRevalidateForSet(ctx);
switch (data.kind) {
case "ROUTE":
case "APP_ROUTE": {
const { body, status, headers } = data;
await globalThis.incrementalCache.set(
key,
{
type: "route",
body: body.toString(
isBinaryContentType(String(headers["content-type"]))
? "base64"
: "utf8",
),
meta: {
status,
headers,
},
revalidate,
},
"cache",
);
break;
}
case "PAGE":
case "PAGES": {
const { html, pageData, status, headers } = data;
const isAppPath = typeof pageData === "string";
if (isAppPath) {
await globalThis.incrementalCache.set(
key,
{
type: "app",
html,
rsc: pageData,
meta: {
status,
headers,
},
revalidate,
},
"cache",
);
} else {
await globalThis.incrementalCache.set(
key,
{
type: "page",
html,
json: pageData,
revalidate,
},
"cache",
);
}
break;
}
case "APP_PAGE": {
const { html, rscData, headers, status, segmentData, postponed } =
data;
const segmentToWrite: Record<string, string> = {};
if (segmentData) {
for (const [
segmentPath,
segmentContent,
] of segmentData.entries()) {
segmentToWrite[segmentPath] = segmentContent.toString("utf8");
}
}
await globalThis.incrementalCache.set(
key,
{
type: "app",
html,
rsc: rscData.toString("utf8"),
meta: {
status,
headers,
postponed,
},
revalidate,
segmentData: segmentData ? segmentToWrite : undefined,
},
"cache",
);
break;
}
case "FETCH":
await globalThis.incrementalCache.set(key, data, "fetch");
break;
case "REDIRECT":
await globalThis.incrementalCache.set(
key,
{
type: "redirect",
props: data.props,
revalidate,
},
"cache",
);
break;
case "IMAGE":
// Not implemented
break;
}
}
await this.updateTagsOnSet(key, data, ctx);
debug("Finished setting cache");
} catch (e) {
error("Failed to set cache", e);
} finally {
// We need to resolve the promise even if there was an error
detachedPromise?.resolve();
}
}
public async revalidateTag(
tags: string | string[],
durations?: { expire?: number },
) {
const config = globalThis.openNextConfig.dangerous;
if (config?.disableTagCache || config?.disableIncrementalCache) {
return;
}
const _tags = Array.isArray(tags) ? tags : [tags];
if (_tags.length === 0) {
return;
}
try {
if (globalThis.tagCache.mode === "nextMode") {
const paths = (await globalThis.tagCache.getPathsByTags?.(_tags)) ?? [];
const now = Date.now();
const tagsToWrite = _tags.map((tag) => {
if (durations) {
// Use provided durations
return {
tag,
stale: now,
expire:
durations.expire !== undefined
? now + durations.expire * 1000
: undefined,
};
}
// Immediate expiration, default behavior before next 16, now only with {expire: 0}
return {
tag,
expire: now,
};
});
await writeTags(tagsToWrite);
if (paths.length > 0) {
// TODO: we should introduce a new method in cdnInvalidationHandler to invalidate paths by tags for cdn that supports it
// It also means that we'll need to provide the tags used in every request to the wrapper or converter.
await globalThis.cdnInvalidationHandler.invalidatePaths(
paths.map((path) => ({
initialPath: path,
rawPath: path,
resolvedRoutes: [
{
route: path,
// TODO: ideally here we should check if it's an app router page or route
type: "app",
},
],
})),
);
}
return;
}
for (const tag of _tags) {
debug("revalidateTag", tag);
// Find all keys with the given tag
const paths = await globalThis.tagCache.getByTag(tag);
debug("Items", paths);
const now = Date.now();
const toInsert = paths.map((path) => {
const baseEntry = { path, tag };
if (durations) {
// Use provided durations
return {
...baseEntry,
stale: now,
expire:
durations.expire !== undefined
? now + durations.expire * 1000
: undefined,
};
}
// Default behavior: immediate expiration
return {
...baseEntry,
expire: now,
};
});
// If the tag is a soft tag, we should also revalidate the hard tags
if (tag.startsWith(SOFT_TAG_PREFIX)) {
for (const path of paths) {
// We need to find all hard tags for a given path
const _tags = await globalThis.tagCache.getByPath(path);
const hardTags = _tags.filter(
(t) => !t.startsWith(SOFT_TAG_PREFIX),
);
// For every hard tag, we need to find all paths and revalidate them
for (const hardTag of hardTags) {
const _paths = await globalThis.tagCache.getByTag(hardTag);
debug({ hardTag, _paths });
toInsert.push(
..._paths.map((path) => {
const baseEntry = { path, tag: hardTag };
if (durations) {
return {
...baseEntry,
stale: now,
expire:
durations.expire !== undefined
? now + durations.expire * 1000
: undefined,
};
}
return {
...baseEntry,
expire: now,
};
}),
);
}
}
}
// Update all keys with the given tag with revalidatedAt set to now
await writeTags(toInsert);
// We can now invalidate all paths in the CDN
// This only applies to `revalidateTag`, not to `res.revalidate()`
const uniquePaths = Array.from(
new Set(
toInsert
// We need to filter fetch cache key as they are not in the CDN
.filter((t) => t.tag.startsWith(SOFT_TAG_PREFIX))
.map((t) => `/${t.path}`),
),
);
if (uniquePaths.length > 0) {
await globalThis.cdnInvalidationHandler.invalidatePaths(
uniquePaths.map((path) => ({
initialPath: path,
rawPath: path,
resolvedRoutes: [
{
route: path,
// TODO: ideally here we should check if it's an app router page or route
type: "app",
},
],
})),
);
}
}
} catch (e) {
error("Failed to revalidate tag", e);
}
}
// TODO: We should delete/update tags in this method
// This will require an update to the tag cache interface
private async updateTagsOnSet(
key: string,
data?: IncrementalCacheValue,
ctx?: IncrementalCacheContext,
) {
if (
globalThis.openNextConfig.dangerous?.disableTagCache ||
globalThis.tagCache.mode === "nextMode" ||
// Here it means it's a delete
!data
) {
return;
}
// Write derivedTags to the tag cache
// If we use an in house version of getDerivedTags in build we should use it here instead of next's one
const derivedTags: string[] =
data?.kind === "FETCH"
? //@ts-expect-error - On older versions of next, ctx was a number, but for these cases we use data?.data?.tags
(ctx?.tags ?? data?.data?.tags ?? []) // before version 14 next.js used data?.data?.tags so we keep it for backward compatibility
: data?.kind === "PAGE"
? (data.headers?.["x-next-cache-tags"]?.split(",") ?? [])
: [];
debug("derivedTags", derivedTags);
// Get all tags stored in dynamodb for the given key
// If any of the derived tags are not stored in dynamodb for the given key, write them
const storedTags = await globalThis.tagCache.getByPath(key);
const tagsToWrite = derivedTags.filter((tag) => !storedTags.includes(tag));
if (tagsToWrite.length > 0) {
await writeTags(
tagsToWrite.map((tag) => ({
path: key,
tag: tag,
// In case the tags are not there we just need to create them
// but we don't want them to return from `getLastModified` as they are not stale
revalidatedAt: 1,
})),
);
}
}
private extractRevalidateForSet(
ctx?: IncrementalCacheContext,
): number | false | undefined {
if (ctx === undefined) {
return undefined;
}
if (typeof ctx === "number" || ctx === false) {
return ctx;
}
if ("revalidate" in ctx) {
return ctx.revalidate;
}
if ("cacheControl" in ctx) {
return ctx.cacheControl?.revalidate;
}
return undefined;
}
}