|
| 1 | +import { createHash } from "node:crypto"; |
| 2 | + |
| 3 | +import { NextConfig, PrerenderManifest } from "config/index"; |
| 4 | +import { InternalEvent, InternalResult } from "types/open-next"; |
| 5 | +import { emptyReadableStream, toReadableStream } from "utils/stream"; |
| 6 | + |
| 7 | +import { debug } from "../../adapters/logger"; |
| 8 | +import { CacheValue } from "../../cache/incremental/types"; |
| 9 | +import { localizePath } from "./i18n"; |
| 10 | +import { generateMessageGroupId } from "./util"; |
| 11 | + |
| 12 | +const CACHE_ONE_YEAR = 60 * 60 * 24 * 365; |
| 13 | +const CACHE_ONE_MONTH = 60 * 60 * 24 * 30; |
| 14 | + |
| 15 | +async function computeCacheControl( |
| 16 | + path: string, |
| 17 | + body: string, |
| 18 | + host: string, |
| 19 | + revalidate?: number | false, |
| 20 | + lastModified?: number, |
| 21 | +) { |
| 22 | + let finalRevalidate = CACHE_ONE_YEAR; |
| 23 | + |
| 24 | + const existingRoute = Object.entries(PrerenderManifest.routes).find( |
| 25 | + (p) => p[0] === path, |
| 26 | + )?.[1]; |
| 27 | + if (revalidate === undefined && existingRoute) { |
| 28 | + finalRevalidate = |
| 29 | + existingRoute.initialRevalidateSeconds === false |
| 30 | + ? CACHE_ONE_YEAR |
| 31 | + : existingRoute.initialRevalidateSeconds; |
| 32 | + // eslint-disable-next-line sonarjs/elseif-without-else |
| 33 | + } else if (revalidate !== undefined) { |
| 34 | + finalRevalidate = revalidate === false ? CACHE_ONE_YEAR : revalidate; |
| 35 | + } |
| 36 | + // calculate age |
| 37 | + const age = Math.round((Date.now() - (lastModified ?? 0)) / 1000); |
| 38 | + const hash = (str: string) => createHash("md5").update(str).digest("hex"); |
| 39 | + const etag = hash(body); |
| 40 | + if (revalidate === 0) { |
| 41 | + // This one should never happen |
| 42 | + return { |
| 43 | + "cache-control": |
| 44 | + "private, no-cache, no-store, max-age=0, must-revalidate", |
| 45 | + "x-opennext-cache": "ERROR", |
| 46 | + etag, |
| 47 | + }; |
| 48 | + } else if (finalRevalidate !== CACHE_ONE_YEAR) { |
| 49 | + const sMaxAge = Math.max(finalRevalidate - age, 1); |
| 50 | + debug("sMaxAge", { |
| 51 | + finalRevalidate, |
| 52 | + age, |
| 53 | + lastModified, |
| 54 | + revalidate, |
| 55 | + }); |
| 56 | + const isStale = sMaxAge === 1; |
| 57 | + if (isStale) { |
| 58 | + let url = NextConfig.trailingSlash ? `${path}/` : path; |
| 59 | + if (NextConfig.basePath) { |
| 60 | + // We need to add the basePath to the url |
| 61 | + url = `${NextConfig.basePath}${url}`; |
| 62 | + } |
| 63 | + await globalThis.queue.send({ |
| 64 | + MessageBody: { host, url }, |
| 65 | + MessageDeduplicationId: hash(`${path}-${lastModified}-${etag}`), |
| 66 | + MessageGroupId: generateMessageGroupId(path), |
| 67 | + }); |
| 68 | + } |
| 69 | + return { |
| 70 | + "cache-control": `s-maxage=${sMaxAge}, stale-while-revalidate=${CACHE_ONE_MONTH}`, |
| 71 | + "x-opennext-cache": isStale ? "STALE" : "HIT", |
| 72 | + etag, |
| 73 | + }; |
| 74 | + } else { |
| 75 | + return { |
| 76 | + "cache-control": `s-maxage=${CACHE_ONE_YEAR}, stale-while-revalidate=${CACHE_ONE_MONTH}`, |
| 77 | + "x-opennext-cache": "HIT", |
| 78 | + etag, |
| 79 | + }; |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +async function generateResult( |
| 84 | + event: InternalEvent, |
| 85 | + localizedPath: string, |
| 86 | + cachedValue: CacheValue<false>, |
| 87 | + lastModified?: number, |
| 88 | +): Promise<InternalResult> { |
| 89 | + debug("Returning result from experimental cache"); |
| 90 | + let body = ""; |
| 91 | + let type = "application/octet-stream"; |
| 92 | + let isDataRequest = false; |
| 93 | + switch (cachedValue.type) { |
| 94 | + case "app": |
| 95 | + isDataRequest = Boolean(event.headers["rsc"]); |
| 96 | + body = isDataRequest ? cachedValue.rsc : cachedValue.html; |
| 97 | + type = isDataRequest ? "text/x-component" : "text/html; charset=utf-8"; |
| 98 | + break; |
| 99 | + case "page": |
| 100 | + isDataRequest = Boolean(event.query["__nextDataReq"]); |
| 101 | + body = isDataRequest |
| 102 | + ? JSON.stringify(cachedValue.json) |
| 103 | + : cachedValue.html; |
| 104 | + type = isDataRequest ? "application/json" : "text/html; charset=utf-8"; |
| 105 | + break; |
| 106 | + } |
| 107 | + const cacheControl = await computeCacheControl( |
| 108 | + localizedPath, |
| 109 | + body, |
| 110 | + event.headers["host"], |
| 111 | + cachedValue.revalidate, |
| 112 | + lastModified, |
| 113 | + ); |
| 114 | + return { |
| 115 | + type: "core", |
| 116 | + statusCode: 200, |
| 117 | + body: toReadableStream(body, false), |
| 118 | + isBase64Encoded: false, |
| 119 | + headers: { |
| 120 | + ...cacheControl, |
| 121 | + "content-type": type, |
| 122 | + ...cachedValue.meta?.headers, |
| 123 | + }, |
| 124 | + }; |
| 125 | +} |
| 126 | + |
| 127 | +export async function cacheInterceptor( |
| 128 | + event: InternalEvent, |
| 129 | +): Promise<InternalEvent | InternalResult> { |
| 130 | + if ( |
| 131 | + Boolean(event.headers["next-action"]) || |
| 132 | + Boolean(event.headers["x-prerender-revalidate"]) |
| 133 | + ) |
| 134 | + return event; |
| 135 | + // We localize the path in case i18n is enabled |
| 136 | + let localizedPath = localizePath(event); |
| 137 | + // If using basePath we need to remove it from the path |
| 138 | + if (NextConfig.basePath) { |
| 139 | + localizedPath = localizedPath.replace(NextConfig.basePath, ""); |
| 140 | + } |
| 141 | + // We also need to remove trailing slash |
| 142 | + localizedPath = localizedPath.replace(/\/$/, ""); |
| 143 | + // If empty path, it means we want index |
| 144 | + if (localizedPath === "") { |
| 145 | + localizedPath = "index"; |
| 146 | + } |
| 147 | + |
| 148 | + debug("Checking cache for", localizedPath, PrerenderManifest); |
| 149 | + |
| 150 | + const isISR = |
| 151 | + Object.keys(PrerenderManifest.routes).includes(localizedPath) || |
| 152 | + Object.values(PrerenderManifest.dynamicRoutes).some((dr) => |
| 153 | + new RegExp(dr.routeRegex).test(localizedPath), |
| 154 | + ); |
| 155 | + debug("isISR", isISR); |
| 156 | + if (isISR) { |
| 157 | + try { |
| 158 | + const cachedData = await globalThis.incrementalCache.get(localizedPath); |
| 159 | + debug("cached data in interceptor", cachedData); |
| 160 | + if (cachedData.value?.type === "app") { |
| 161 | + // We need to check the tag cache now |
| 162 | + const _lastModified = await globalThis.tagCache.getLastModified( |
| 163 | + localizedPath, |
| 164 | + cachedData.lastModified, |
| 165 | + ); |
| 166 | + if (_lastModified === -1) { |
| 167 | + // If some tags are stale we need to force revalidation |
| 168 | + return event; |
| 169 | + } |
| 170 | + } |
| 171 | + const host = event.headers["host"]; |
| 172 | + switch (cachedData.value?.type) { |
| 173 | + case "app": |
| 174 | + case "page": |
| 175 | + return generateResult( |
| 176 | + event, |
| 177 | + localizedPath, |
| 178 | + cachedData.value, |
| 179 | + cachedData.lastModified, |
| 180 | + ); |
| 181 | + case "redirect": |
| 182 | + const cacheControl = await computeCacheControl( |
| 183 | + localizedPath, |
| 184 | + "", |
| 185 | + host, |
| 186 | + cachedData.value.revalidate, |
| 187 | + cachedData.lastModified, |
| 188 | + ); |
| 189 | + return { |
| 190 | + type: "core", |
| 191 | + statusCode: cachedData.value.meta?.status ?? 307, |
| 192 | + body: emptyReadableStream(), |
| 193 | + headers: { |
| 194 | + ...((cachedData.value.meta?.headers as Record<string, string>) ?? |
| 195 | + {}), |
| 196 | + ...cacheControl, |
| 197 | + }, |
| 198 | + isBase64Encoded: false, |
| 199 | + }; |
| 200 | + default: |
| 201 | + return event; |
| 202 | + } |
| 203 | + } catch (e) { |
| 204 | + debug("Error while fetching cache", e); |
| 205 | + // In case of error we fallback to the server |
| 206 | + return event; |
| 207 | + } |
| 208 | + } |
| 209 | + return event; |
| 210 | +} |
0 commit comments