-
Notifications
You must be signed in to change notification settings - Fork 3
Cache: honour Cache-Control on cache entries #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
conico974
wants to merge
1
commit into
conico/cache-4-swr-port
Choose a base branch
from
conico/cache-5-cache-control
base: conico/cache-4-swr-port
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| --- | ||
| "@opennextjs/core": patch | ||
| --- | ||
|
|
||
| Derive revalidation from `Cache-Control` on cache entries | ||
|
|
||
| The cache handler function now parses the `Cache-Control` of an entry to decide whether it is fresh, | ||
| stale or expired, instead of relying on the revalidation timestamp alone. `s-maxage`, | ||
| `stale-while-revalidate` and `must-revalidate` are honoured, and the resulting state is carried back | ||
| to the caller in the response headers. | ||
|
|
||
| The `fetch` and `local` cache overrides also forward the cache type when writing an entry. | ||
| Incremental caches that key entries on the type were writing them where `get` does not look. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import type { StoredComposableCacheEntry } from "@/types/cache"; | ||
| import type { CacheEntryType, CacheValue } from "@/types/overrides"; | ||
|
|
||
| import { error } from "../adapters/logger"; | ||
|
|
||
| export const CACHE_ONE_YEAR = 60 * 60 * 24 * 365; | ||
|
|
||
| const NO_STORE = "no-store"; | ||
|
|
||
| /** | ||
| * Composable cache entries may carry `Infinity` (i.e. `cacheLife("max")`), and an entry that was | ||
| * just written has a negative age when `Date.now()` drifts, so every duration is clamped. | ||
| */ | ||
| function clampSeconds(seconds: number): number { | ||
| if (!Number.isFinite(seconds)) { | ||
| return CACHE_ONE_YEAR; | ||
| } | ||
| return Math.max(0, Math.min(Math.floor(seconds), CACHE_ONE_YEAR)); | ||
| } | ||
|
|
||
| function buildCacheControl(sMaxAge: number, staleWhileRevalidate: number): string { | ||
| return `s-maxage=${clampSeconds(sMaxAge)}, stale-while-revalidate=${clampSeconds(staleWhileRevalidate)}`; | ||
| } | ||
|
|
||
| /** | ||
| * Computes the `Cache-Control` of a cache handler `GET` hit, so that an HTTP cache sitting in front | ||
| * of the cache handler function can serve reads without hitting the underlying store. | ||
| * | ||
| * A stale or expired entry is never stored: the next read has to reach the cache handler function so | ||
| * that the staleness is signaled to the server (through `lastModified = 1`). | ||
| * | ||
| * **This is only correct when the cached responses can be purged**, either with a | ||
| * `cdnInvalidationHandler` or through another purge mechanism keyed on the `cache-tag` header that | ||
| * `buildCacheGetResponse` emits. Tag revalidation cannot invalidate an intermediate cache on its own, | ||
| * so without purging `revalidateTag`/`revalidatePath` would be masked for as long as the entry is | ||
| * stored - up to a year for SSG entries. | ||
| */ | ||
| export function computeEntryCacheControl( | ||
| value: CacheValue<CacheEntryType>, | ||
| lastModified: number | undefined, | ||
| isStaleFromTagCache: boolean | ||
| ): string { | ||
| if (isStaleFromTagCache) { | ||
| return NO_STORE; | ||
| } | ||
|
|
||
| // Same discrimination as `buildCacheGetResponse`: fetch entries have a `kind`, cached files have | ||
| // a `type`, composable entries have neither. | ||
| const isFetch = "kind" in value && value.kind === "FETCH"; | ||
| const isCachedFile = "type" in value; | ||
|
|
||
| if (!isFetch && !isCachedFile) { | ||
| return computeComposableCacheControl(value as StoredComposableCacheEntry); | ||
| } | ||
|
|
||
| return computeRevalidateCacheControl(value.revalidate, lastModified); | ||
| } | ||
|
|
||
| function computeComposableCacheControl(value: StoredComposableCacheEntry): string { | ||
| const age = (Date.now() - value.timestamp) / 1000; | ||
|
|
||
| if (age >= value.expire || age >= value.revalidate) { | ||
| return NO_STORE; | ||
| } | ||
|
|
||
| // Composable entries are the only ones carrying an explicit `expire`, so they are also the only | ||
| // ones for which we can derive a real stale-while-revalidate window. | ||
| return buildCacheControl(value.revalidate - age, value.expire - value.revalidate); | ||
| } | ||
|
|
||
| function computeRevalidateCacheControl( | ||
| revalidate: number | false | undefined, | ||
| lastModified: number | undefined | ||
| ): string { | ||
| if (revalidate === 0) { | ||
| return NO_STORE; | ||
| } | ||
|
|
||
| if (revalidate === undefined) { | ||
| // `revalidate` is written by the cache handler for every entry, we should always have one here. | ||
| error("Missing `revalidate` on a cache entry, assuming it is a static (SSG) entry"); | ||
| } | ||
|
|
||
| if (revalidate === undefined || revalidate === false) { | ||
| return buildCacheControl(CACHE_ONE_YEAR, 0); | ||
| } | ||
|
|
||
| const age = (Date.now() - (lastModified ?? Date.now())) / 1000; | ||
| const remainingTtl = revalidate - age; | ||
|
|
||
| if (remainingTtl <= 0) { | ||
| return NO_STORE; | ||
| } | ||
|
|
||
| // `stale-while-revalidate` is intentionally `0` for fetch and cached file entries: a response | ||
| // served during a stale-while-revalidate window still carries its original | ||
| // `x-opennext-cache-last-modified`, which would hide the `lastModified = 1` staleness signal that | ||
| // `cacheInterceptor` and the composable cache rely on to trigger a background revalidation. | ||
| return buildCacheControl(remainingTtl, 0); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Pages built ahead of time are told to stay cached for a year instead of their own refresh interval
Pre-built page entries, which carry no refresh interval, are treated as never-changing and given a one-year lifetime (
buildCacheControl(CACHE_ONE_YEAR, 0)atpackages/core/src/utils/cache-control.ts:85) instead of the page's configured refresh interval, so incrementally-regenerated pages can stay frozen for a year in any cache sitting in front of the cache handler.Impact: Pages that are supposed to refresh every few seconds/minutes may keep serving build-time content until manually purged, and an error is logged on every read of such a page.
Why build-time entries reach this branch without a revalidate value
The cache assets generated at build time (
packages/core/src/build/createAssets.ts:184-197) write only{ type, meta, html, json, rsc, body, segmentData }— there is norevalidatefield. Those files are whatglobalThis.incrementalCache.get(key, "cache")returns until the page is regenerated at runtime (runtime writes do includerevalidate, seepackages/core/src/adapters/cache.ts:145-233).So for every prerendered ISR page,
computeEntryCacheControlhits therevalidate === undefinedpath: it logserror("Missing \revalidate` on a cache entry, ...")(packages/core/src/utils/cache-control.ts:81) and returnss-maxage=31536000`.The pre-existing
computeCacheControlinpackages/core/src/core/routing/cacheInterceptor.ts:42-50handles exactly this case by falling back toPrerenderManifest.routes[path].initialRevalidateSecondswhenrevalidateisundefined; the new util has no equivalent fallback.Prompt for agents
Was this helpful? React with 👍 or 👎 to provide feedback.