Unverified Commit 1f0cd93b authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[refactor] Rename `encodeCacheTag` to `encodeHeaderSafe` (#96936)

The helper percent-encodes anything outside Node's valid header-value
class so a string can be serialized into an HTTP header. That is a
property of the transport, not of cache tags, and the next caller is
`unstable_cache`'s synthetic `fetchUrl`, which is a cache item name
rather than a tag. Naming the function after one of its callers would
make that call site read as though it were tagging something.

This change renames the module to `encode-header-safe.ts` and the
function to `encodeHeaderSafe`, and generalizes the leading paragraph of
the doc comment accordingly. The rationale specific to cache tags stays,
since tag construction and invalidation remain the callers today. The
doc now also names the `ByteString` conversion that `fetch` performs on
header values, alongside `validateHeaderValue`; both already applied to
tags, because the Vercel bridge sends them through `fetch`.

There is no behavior change. The function body is identical apart from
the parameter name.
parent b8c2c0b0
/**
* Percent-encode every character outside printable ASCII so a tag value can be
* safely serialized as part of the `x-next-cache-tags` HTTP header.
*
* Node's `validateHeaderValue` rejects any code unit outside `\t\x20-\x7e`, so
* a matched route path or user-supplied tag containing a non-ASCII character
* (Hebrew, Arabic, Chinese, emoji, …) would otherwise throw `ERR_INVALID_CHAR`
* and crash ISR on every affected request.
*
* This is applied at the public boundaries — tag construction
* (`getImplicitTags`, `validateTags`) and invalidation input (`revalidatePath`,
* `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see
* the same canonical ASCII-safe form.
*
* The character class `[\t\x20-\x7e]` mirrors Node's `validHdrChars` table —
* `\t` plus printable ASCII through `~`. Anything outside that is rejected
* by `validateHeaderValue`, so we encode runs of those characters and leave
* everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\t`, …) byte-for-byte
* unchanged. This preserves the comma-separated header format and the
* dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).
*
* Properties:
* - Fast-path: input that already fits the validation class is returned
* unchanged. This makes the encoder idempotent on already-encoded `%xx`
* sequences.
* - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an
* emoji) are handed to `encodeURIComponent` as a complete code point — a
* per-code-unit regex would split the pair and throw `URIError`.
*/
const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/
const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g
export function encodeCacheTag(tag: string): string {
return OUT_OF_CLASS_CHAR.test(tag)
? tag.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))
: tag
}
/**
* Percent-encode every character other than horizontal tab and printable ASCII
* so a value can be safely serialized into an HTTP header.
*
* Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept
* different character ranges. Restricting values to `\t\x20-\x7e` produces a
* conservative representation that both can serialize. Characters outside a
* transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would
* otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or
* fails a cache read on every affected request.
*
* Cache tags are encoded at the public boundaries — tag construction
* (`getImplicitTags`, `validateTags`) and invalidation input
* (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison,
* and the wire all see the same canonical form.
*
* The class is narrower than either transport accepts. Everything inside it
* passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and
* `\t`, which preserves the comma-separated header format and the
* dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).
*
* Properties:
* - Fast-path: input that already fits the class is returned unchanged. This
* makes the encoder idempotent on already-encoded `%xx` sequences.
* - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an
* emoji) are handed to `encodeURIComponent` as a complete code point — a
* per-code-unit regex would split the pair and throw `URIError`.
*/
const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/
const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g
export function encodeHeaderSafe(value: string): string {
return OUT_OF_CLASS_CHAR.test(value)
? value.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))
: value
}
import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants' import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params' import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import { getCacheHandlerEntries } from '../use-cache/handlers' import { getCacheHandlerEntries } from '../use-cache/handlers'
import { encodeCacheTag } from './encode-cache-tag' import { encodeHeaderSafe } from './encode-header-safe'
import { createLazyResult, type LazyResult } from './lazy-result' import { createLazyResult, type LazyResult } from './lazy-result'
export interface ImplicitTags { export interface ImplicitTags {
...@@ -92,14 +92,14 @@ export async function getImplicitTags( ...@@ -92,14 +92,14 @@ export async function getImplicitTags(
// `x-next-cache-tags`. Idempotent on already-ASCII input. // `x-next-cache-tags`. Idempotent on already-ASCII input.
const derivedTags = getDerivedTags(page) const derivedTags = getDerivedTags(page)
for (let tag of derivedTags) { for (let tag of derivedTags) {
tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`) tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)
tags.add(tag) tags.add(tag)
} }
// Add the tags from the pathname. If the route has unknown params, we don't // Add the tags from the pathname. If the route has unknown params, we don't
// want to add the pathname as a tag, as it will be invalid. // want to add the pathname as a tag, as it will be invalid.
if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) { if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {
const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`) const tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)
tags.add(tag) tags.add(tag)
} }
......
...@@ -37,7 +37,7 @@ import { ...@@ -37,7 +37,7 @@ import {
import { cloneResponse } from './clone-response' import { cloneResponse } from './clone-response'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { RenderStage } from '../app-render/staged-rendering' import { RenderStage } from '../app-render/staged-rendering'
import { encodeCacheTag } from './encode-cache-tag' import { encodeHeaderSafe } from './encode-header-safe'
import type { Span } from './trace/tracer' import type { Span } from './trace/tracer'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -147,7 +147,7 @@ export function validateTags(tags: any[], description: string) { ...@@ -147,7 +147,7 @@ export function validateTags(tags: any[], description: string) {
// Encode so a non-ASCII tag can be safely serialized into the // Encode so a non-ASCII tag can be safely serialized into the
// `x-next-cache-tags` HTTP header without tripping Node's header // `x-next-cache-tags` HTTP header without tripping Node's header
// validation. Length is checked on the raw input above. // validation. Length is checked on the raw input above.
validTags.push(encodeCacheTag(tag)) validTags.push(encodeHeaderSafe(tag))
} }
if (validTags.length > NEXT_CACHE_TAG_MAX_ITEMS) { if (validTags.length > NEXT_CACHE_TAG_MAX_ITEMS) {
......
...@@ -16,7 +16,7 @@ import { ...@@ -16,7 +16,7 @@ import {
ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate, ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,
} from '../../../shared/lib/action-revalidation-kind' } from '../../../shared/lib/action-revalidation-kind'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
import { encodeCacheTag } from '../../lib/encode-cache-tag' import { encodeHeaderSafe } from '../../lib/encode-header-safe'
import { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile' import { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'
type CacheLifeConfig = { type CacheLifeConfig = {
...@@ -40,7 +40,7 @@ export function revalidateTag(tag: string, profile: string | CacheLifeConfig) { ...@@ -40,7 +40,7 @@ export function revalidateTag(tag: string, profile: string | CacheLifeConfig) {
} else if (typeof profile === 'object') { } else if (typeof profile === 'object') {
profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' }) profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })
} }
return revalidate([encodeCacheTag(tag)], `revalidateTag ${tag}`, profile) return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)
} }
/** /**
...@@ -62,7 +62,7 @@ export function updateTag(tag: string) { ...@@ -62,7 +62,7 @@ export function updateTag(tag: string) {
) )
} }
// updateTag uses immediate expiration (no profile) without deprecation warning // updateTag uses immediate expiration (no profile) without deprecation warning
return revalidate([encodeCacheTag(tag)], `updateTag ${tag}`, undefined) return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)
} }
/** /**
...@@ -105,7 +105,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') { ...@@ -105,7 +105,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
return return
} }
let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeCacheTag(removeTrailingSlash(originalPath))}` let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`
if (type) { if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}` normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment