Commit 04733878 authored by Jimmy Lai's avatar Jimmy Lai

feat: eager HTML cache regeneration on updateTag/refresh

When updateTag() or refresh() is called in a server action, this change ensures:
1. User A (action caller) sees fresh data immediately (read-your-own-writes)
2. User B (cold visitor) gets the same cached data from HTML cache
3. Both users see identical data from a single render

Implementation uses client-side stream splitting:
- Server concatenates action result stream and page stream with a boundary
- Client splits on boundary, processes each stream independently
- Results combined at JS object level

Files changed:
- lib/constants.ts: Added FLIGHT_STREAM_BOUNDARY constant
- node-web-streams-helper.ts: Added concatenateFlightStreams()
- action-handler.ts: Trigger logic for updateTag/refresh
- fetch-server-response.ts: Added splitFlightStreams()
- server-action-reducer.ts: Handle split streams on client
- render-result.ts: Added toReadableStream() method

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent 40a4c11b
...@@ -973,5 +973,6 @@ ...@@ -973,5 +973,6 @@
"972": "Failed to resolve pattern \"%s\": %s", "972": "Failed to resolve pattern \"%s\": %s",
"973": "Server Actions are not enabled for this application. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action", "973": "Server Actions are not enabled for this application. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"974": "Failed to find Server Action%s. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action", "974": "Failed to find Server Action%s. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action" "975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"976": "Split flight boundary not found in response"
} }
...@@ -37,3 +37,6 @@ export const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const ...@@ -37,3 +37,6 @@ export const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const
// TODO: Should this include nextjs in the name, like the others? // TODO: Should this include nextjs in the name, like the others?
export const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const export const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const
// Header to indicate split flight response (action result + page data with boundary)
export const NEXT_SPLIT_FLIGHT_HEADER = 'x-next-split-flight' as const
...@@ -503,3 +503,77 @@ function createUnclosingPrefetchStream( ...@@ -503,3 +503,77 @@ function createUnclosingPrefetchStream(
}, },
}) })
} }
/**
* Splits a Flight stream that contains two concatenated streams separated by a boundary.
* Used for split flight responses where action result and page data are sent together.
*
* @param body - The response body containing [action stream][boundary][page stream]
* @param boundary - The boundary string that separates the two streams
* @returns Two separate streams that can be processed independently
*/
export async function splitFlightStreams(
body: ReadableStream<Uint8Array>,
boundary: string
): Promise<{
actionStream: ReadableStream<Uint8Array>
pageStream: ReadableStream<Uint8Array>
}> {
const reader = body.getReader()
const decoder = new TextDecoder()
const encoder = new TextEncoder()
const boundaryBytes = encoder.encode(boundary)
let buffer = new Uint8Array(0)
let boundaryIndex = -1
// Read until we find the boundary
while (boundaryIndex === -1) {
const { done, value } = await reader.read()
if (done) {
throw new Error('Split flight boundary not found in response')
}
// Append to buffer
const newBuffer = new Uint8Array(buffer.length + value.length)
newBuffer.set(buffer)
newBuffer.set(value, buffer.length)
buffer = newBuffer
// Search for boundary in the accumulated buffer
const text = decoder.decode(buffer)
boundaryIndex = text.indexOf(boundary)
}
// Split buffer at boundary
const actionBytes = buffer.slice(0, boundaryIndex)
const pageStartBytes = buffer.slice(boundaryIndex + boundaryBytes.length)
// Create action stream from the buffered action bytes
const actionStream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(actionBytes)
controller.close()
},
})
// Create page stream: starts with buffered remainder, then pipes rest of original stream
const pageStream = new ReadableStream<Uint8Array>({
async start(controller) {
// First enqueue the buffered bytes after the boundary
if (pageStartBytes.length > 0) {
controller.enqueue(pageStartBytes)
}
// Then pipe through the rest of the original stream
while (true) {
const { done, value } = await reader.read()
if (done) break
controller.enqueue(value)
}
controller.close()
},
})
return { actionStream, pageStream }
}
...@@ -13,7 +13,13 @@ import { ...@@ -13,7 +13,13 @@ import {
NEXT_URL, NEXT_URL,
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
NEXT_SPLIT_FLIGHT_HEADER,
} from '../../app-router-headers' } from '../../app-router-headers'
import { FLIGHT_STREAM_BOUNDARY } from '../../../../lib/constants'
import {
splitFlightStreams,
createFromNextReadableStream,
} from '../fetch-server-response'
import { UnrecognizedActionError } from '../../unrecognized-action-error' import { UnrecognizedActionError } from '../../unrecognized-action-error'
// TODO: Explicitly import from client.browser // TODO: Explicitly import from client.browser
...@@ -211,23 +217,55 @@ async function fetchServerAction( ...@@ -211,23 +217,55 @@ async function fetchServerAction(
let actionFlightDataCouldBeIntercepted: FetchServerActionResult['actionFlightDataCouldBeIntercepted'] let actionFlightDataCouldBeIntercepted: FetchServerActionResult['actionFlightDataCouldBeIntercepted']
if (isRscResponse) { if (isRscResponse) {
const response: ActionFlightResponse = await createFromFetch( // Check if this is a split flight response (action result + page data separated by boundary)
Promise.resolve(res), const isSplitFlight = res.headers.get(NEXT_SPLIT_FLIGHT_HEADER) === '1'
{
callServer, if (isSplitFlight && res.body) {
findSourceMapURL, // Split the response body on boundary and process each stream independently
temporaryReferences, const { actionStream, pageStream } = await splitFlightStreams(
debugChannel: createDebugChannel && createDebugChannel(headers), res.body,
FLIGHT_STREAM_BOUNDARY
)
// Process each stream independently using createFromNextReadableStream
// We cast to RequestHeaders since headers is a Record<string, string>
const requestHeaders =
headers as import('../fetch-server-response').RequestHeaders
const actionResponse: ActionFlightResponse =
await createFromNextReadableStream(actionStream, requestHeaders)
const pageResponse: ActionFlightResponse =
await createFromNextReadableStream(pageStream, requestHeaders)
// Combine at JS object level
// Action result comes from the action stream
actionResult = redirectLocation ? undefined : actionResponse.a
// Flight data comes from the page stream (internal request result)
const maybeFlightData = normalizeFlightData(pageResponse.f)
if (maybeFlightData !== '') {
actionFlightData = maybeFlightData
actionFlightDataRenderedSearch = pageResponse.q as NormalizedSearch
actionFlightDataCouldBeIntercepted = pageResponse.i
} }
) } else {
// Standard single-stream response
const response: ActionFlightResponse = await createFromFetch(
Promise.resolve(res),
{
callServer,
findSourceMapURL,
temporaryReferences,
debugChannel: createDebugChannel && createDebugChannel(headers),
}
)
// An internal redirect can send an RSC response, but does not have a useful `actionResult`. // An internal redirect can send an RSC response, but does not have a useful `actionResult`.
actionResult = redirectLocation ? undefined : response.a actionResult = redirectLocation ? undefined : response.a
const maybeFlightData = normalizeFlightData(response.f) const maybeFlightData = normalizeFlightData(response.f)
if (maybeFlightData !== '') { if (maybeFlightData !== '') {
actionFlightData = maybeFlightData actionFlightData = maybeFlightData
actionFlightDataRenderedSearch = response.q as NormalizedSearch actionFlightDataRenderedSearch = response.q as NormalizedSearch
actionFlightDataCouldBeIntercepted = response.i actionFlightDataCouldBeIntercepted = response.i
}
} }
} else { } else {
// An external redirect doesn't contain RSC data. // An external redirect doesn't contain RSC data.
......
...@@ -26,6 +26,12 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER = ...@@ -26,6 +26,12 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =
export const NEXT_RESUME_HEADER = 'next-resume' export const NEXT_RESUME_HEADER = 'next-resume'
// Header to indicate split flight streams (action result + page data)
export const NEXT_SPLIT_FLIGHT_HEADER = 'x-next-split-flight'
// Boundary to separate action result stream from page stream in split flight responses
export const FLIGHT_STREAM_BOUNDARY = '__NEXT_FLIGHT_BOUNDARY__\n'
// if these change make sure we update the related // if these change make sure we update the related
// documentation as well // documentation as well
export const NEXT_CACHE_TAG_MAX_ITEMS = 128 export const NEXT_CACHE_TAG_MAX_ITEMS = 128
......
...@@ -43,7 +43,11 @@ import { ...@@ -43,7 +43,11 @@ import {
JSON_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
NEXT_SPLIT_FLIGHT_HEADER,
FLIGHT_STREAM_BOUNDARY,
} from '../../lib/constants' } from '../../lib/constants'
import { concatenateFlightStreams } from '../stream-utils/node-web-streams-helper'
import { getClientReferenceManifest } from './manifests-singleton'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta' import { getServerActionRequestMetadata } from '../lib/server-action-request-meta'
import { isCsrfOriginAllowed } from './csrf-protection' import { isCsrfOriginAllowed } from './csrf-protection'
import { warn } from '../../build/output/log' import { warn } from '../../build/output/log'
...@@ -70,6 +74,13 @@ import { ...@@ -70,6 +74,13 @@ import {
ActionDidRevalidateStaticAndDynamic, ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind' } from '../../shared/lib/action-revalidation-kind'
// Used for filtering stack frames in renderToReadableStream
const filterStackFrame =
process.env.NODE_ENV !== 'production'
? (require('../lib/source-maps') as typeof import('../lib/source-maps'))
.filterStackFrameDEV
: undefined
/** /**
* Checks if the app has any server actions defined in any runtime. * Checks if the app has any server actions defined in any runtime.
*/ */
...@@ -444,6 +455,100 @@ async function createRedirectRenderResult( ...@@ -444,6 +455,100 @@ async function createRedirectRenderResult(
return RenderResult.EMPTY return RenderResult.EMPTY
} }
/**
* Creates a render result by making an internal request to the current page.
* This is used for updateTag/refresh to ensure the HTML cache gets populated
* with the same data that the action caller sees (read-your-own-writes consistency).
*
* Similar to createRedirectRenderResult but for the current page instead of a redirect URL.
*/
async function createInternalRequestRenderResult(
req: BaseNextRequest,
res: BaseNextResponse,
originalHost: Host,
pagePath: string,
basePath: string,
workStore: WorkStore
): Promise<RenderResult | null> {
if (!originalHost) {
return null
}
const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC_HEADER, '1')
const proto =
getRequestMeta(req, 'initProtocol')?.replace(/:+$/, '') || 'https'
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
const origin =
process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${originalHost.value}`
const fetchUrl = new URL(`${origin}${basePath}${pagePath}`)
if (workStore.pendingRevalidatedTags?.length) {
forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
workStore.pendingRevalidatedTags.map((item) => item.tag).join(',')
)
forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
workStore.incrementalCache?.prerenderManifest?.preview?.previewModeId ||
''
)
}
// Keep the router state tree header for partial rendering - Next.js's
// group revalidation will handle writing the full HTML cache
// Remove action header since this is now a page render request
forwardedHeaders.delete(ACTION_HEADER)
try {
setCacheBustingSearchParam(fetchUrl, {
[NEXT_ROUTER_PREFETCH_HEADER]: forwardedHeaders.get(
NEXT_ROUTER_PREFETCH_HEADER
)
? ('1' as const)
: undefined,
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]:
forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined,
[NEXT_ROUTER_STATE_TREE_HEADER]:
forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,
[NEXT_URL]: forwardedHeaders.get(NEXT_URL) ?? undefined,
})
const response = await fetch(fetchUrl, {
method: 'GET',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
if (
response.headers.get('content-type')?.startsWith(RSC_CONTENT_TYPE_HEADER)
) {
// Copy headers from the response
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value)
}
}
return new FlightRenderResult(response.body!)
} else {
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
response.body?.cancel()
}
} catch (err) {
console.error('Failed to get internal request response for updateTag:', err)
}
return null
}
// Used to compare Host header and Origin header. // Used to compare Host header and Origin header.
const enum HostType { const enum HostType {
XForwardedHost = 'x-forwarded-host', XForwardedHost = 'x-forwarded-host',
...@@ -1084,6 +1189,64 @@ export async function handleAction({ ...@@ -1084,6 +1189,64 @@ export async function handleAction({
addRevalidationHeader(res, { workStore, requestStore }) addRevalidationHeader(res, { workStore, requestStore })
}) })
// For updateTag() or refresh() calls, use internal request to ensure
// the HTML cache gets populated with the same data the action caller sees.
// This provides read-your-own-writes consistency between User A (action caller)
// and User B (subsequent cold visitor).
const hasUpdateTagCalls = workStore.pendingRevalidatedTags?.some(
(item) => item.profile === undefined
)
const hasRefreshCall =
workStore.pathWasRevalidated !== undefined &&
workStore.pathWasRevalidated !== ActionDidNotRevalidate
const shouldUseSplitFlightResponse = hasUpdateTagCalls || hasRefreshCall
if (
isFetchAction &&
shouldUseSplitFlightResponse &&
!actionWasForwarded
) {
// Make an internal request to get the page render stream.
// This ensures the same data is used for both action response and HTML cache.
const pageResult = await createInternalRequestRenderResult(
req,
res,
host,
workStore.route,
ctx.renderOpts.basePath,
workStore
)
if (pageResult) {
// Encode the action result as a separate Flight stream
const { clientModules } = getClientReferenceManifest()
const actionResultPayload = { a: Promise.resolve(actionResult) }
const actionResultStream = ComponentMod.renderToReadableStream(
actionResultPayload,
clientModules,
{ temporaryReferences, filterStackFrame }
)
// Set header to indicate split flight response
res.setHeader(NEXT_SPLIT_FLIGHT_HEADER, '1')
// Concatenate: [action result stream][BOUNDARY][page stream]
// Client will split on boundary and process each stream independently
const combinedStream = concatenateFlightStreams(
actionResultStream,
pageResult.toReadableStream(),
FLIGHT_STREAM_BOUNDARY
)
return {
type: 'done',
result: new FlightRenderResult(combinedStream),
}
}
// If internal request failed, fall through to regular generateFlight
}
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
return { return {
......
...@@ -195,6 +195,13 @@ export default class RenderResult< ...@@ -195,6 +195,13 @@ export default class RenderResult<
return this.response return this.response
} }
/**
* Returns a readable stream of the response.
*/
public toReadableStream(): ReadableStream<Uint8Array> {
return this.readable
}
/** /**
* Returns a readable stream of the response. * Returns a readable stream of the response.
*/ */
......
...@@ -96,6 +96,26 @@ export function streamFromBuffer(chunk: Buffer): ReadableStream<Uint8Array> { ...@@ -96,6 +96,26 @@ export function streamFromBuffer(chunk: Buffer): ReadableStream<Uint8Array> {
}) })
} }
/**
* Concatenates two Flight streams with a boundary delimiter.
* Used for split flight responses where action result and page data
* are sent as separate streams that the client will split and process independently.
*/
export function concatenateFlightStreams(
actionResultStream: ReadableStream<Uint8Array>,
pageStream: ReadableStream<Uint8Array>,
boundary: string
): ReadableStream<Uint8Array> {
const boundaryStream = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(boundary))
controller.close()
},
})
return chainStreams(actionResultStream, boundaryStream, pageStream)
}
async function streamToChunks( async function streamToChunks(
stream: ReadableStream<Uint8Array> stream: ReadableStream<Uint8Array>
): Promise<Array<Uint8Array>> { ): Promise<Array<Uint8Array>> {
......
'use server'
import { updateTag, cacheTag, cacheLife } from 'next/cache'
async function getCachedTimestamp() {
'use cache'
cacheTag('eager-complex-test')
cacheLife('max')
return Date.now().toString()
}
export async function complexAction() {
updateTag('eager-complex-test')
const cachedTimestamp = await getCachedTimestamp()
return {
nested: {
value: 'nested-value',
deep: {
array: [1, 2, 3, 4, 5],
},
},
array: ['a', 'b', 'c'],
timestamp: Date.now(),
cachedTimestamp,
}
}
'use client'
import { useActionState } from 'react'
import { complexAction } from './actions'
type ComplexResult = {
nested: {
value: string
deep: { array: number[] }
}
array: string[]
timestamp: number
cachedTimestamp: string
} | null
export default function Page() {
const [state, formAction, isPending] = useActionState(
complexAction,
null as ComplexResult
)
return (
<div>
<p id="cached-timestamp">{state?.cachedTimestamp ?? 'none'}</p>
<p id="result">
{state
? `nested: ${state.nested.value}, array: ${state.array.join(',')}, deep: ${state.nested.deep.array.join(',')}`
: 'no result yet'}
</p>
<p id="pending">{isPending ? 'pending' : 'idle'}</p>
<form action={formAction}>
<button id="complex-action" type="submit">
Complex Action
</button>
</form>
</div>
)
}
'use server'
import { updateTag, refresh, cacheTag, cacheLife } from 'next/cache'
async function getCachedTimestamp() {
'use cache'
cacheTag('eager-refresh-test')
cacheLife('max')
return Date.now().toString()
}
export async function refreshOnly() {
refresh()
}
export async function updateTagAndRefresh() {
updateTag('eager-refresh-test')
refresh()
}
export async function refreshWithReturn() {
refresh()
const cachedTimestamp = await getCachedTimestamp()
return {
refreshed: true,
timestamp: Date.now().toString(),
cachedTimestamp,
}
}
'use client'
import { useActionState } from 'react'
import { refreshOnly, updateTagAndRefresh, refreshWithReturn } from './actions'
export function RefreshClient() {
const [state, formAction, isPending] = useActionState(refreshWithReturn, {
refreshed: false,
timestamp: '',
cachedTimestamp: '',
})
return (
<div>
<p id="action-result">
{state.refreshed
? `refreshed: true, timestamp: ${state.timestamp}`
: 'no result yet'}
</p>
<p id="pending">{isPending ? 'pending' : 'idle'}</p>
<form>
<button id="refresh-only" formAction={refreshOnly} type="submit">
Refresh Only
</button>
<button
id="update-and-refresh"
formAction={updateTagAndRefresh}
type="submit"
>
Update Tag and Refresh
</button>
<button id="refresh-with-return" formAction={formAction} type="submit">
Refresh With Return
</button>
</form>
</div>
)
}
import { cacheTag, cacheLife } from 'next/cache'
import { RefreshClient } from './client'
async function getCachedTimestamp() {
'use cache'
cacheTag('eager-refresh-test')
cacheLife('max')
return Date.now().toString()
}
export default async function Page() {
const cachedTimestamp = await getCachedTimestamp()
return (
<div>
<p id="cached-timestamp">{cachedTimestamp}</p>
<RefreshClient />
</div>
)
}
'use server'
import { updateTag, cacheTag, cacheLife } from 'next/cache'
export async function getCachedTimestamp() {
'use cache'
cacheTag('eager-return-test')
cacheLife('max')
return Date.now().toString()
}
export async function updateTagAndReturn() {
updateTag('eager-return-test')
const cachedTimestamp = await getCachedTimestamp()
return {
success: true,
timestamp: Date.now().toString(),
cachedTimestamp,
}
}
'use client'
import { useActionState } from 'react'
import { updateTagAndReturn } from './actions'
export default function Page() {
const [state, formAction, isPending] = useActionState(updateTagAndReturn, {
success: false,
timestamp: '',
cachedTimestamp: '',
})
return (
<div>
<p id="cached-timestamp">{state.cachedTimestamp}</p>
<p id="action-result">
{state.success
? `success: true, timestamp: ${state.timestamp}`
: 'no result yet'}
</p>
<p id="pending">{isPending ? 'pending' : 'idle'}</p>
<form action={formAction}>
<button id="update-and-return" type="submit">
Update Tag and Return
</button>
</form>
</div>
)
}
import { updateTag, cacheTag, cacheLife } from 'next/cache'
async function getCachedTimestamp() {
'use cache'
cacheTag('eager-test')
cacheLife('max')
return Date.now().toString()
}
export default async function Page() {
const timestamp = await getCachedTimestamp()
return (
<div>
<p id="timestamp">{timestamp}</p>
<form>
<button
id="update-tag"
formAction={async () => {
'use server'
updateTag('eager-test')
}}
>
Update Tag
</button>
</form>
</div>
)
}
...@@ -484,6 +484,10 @@ describe('use-cache', () => { ...@@ -484,6 +484,10 @@ describe('use-cache', () => {
'/directive-in-node-modules/without-handler', '/directive-in-node-modules/without-handler',
'/draft-mode/with-cookies', '/draft-mode/with-cookies',
'/draft-mode/without-cookies', '/draft-mode/without-cookies',
'/eager-revalidation',
'/eager-revalidation-complex-return',
'/eager-revalidation-refresh',
'/eager-revalidation-with-return',
'/form', '/form',
'/imported-from-client', '/imported-from-client',
'/logs', '/logs',
...@@ -715,6 +719,151 @@ describe('use-cache', () => { ...@@ -715,6 +719,151 @@ describe('use-cache', () => {
// This proves revalidateTag with profile does NOT cause read-your-own-writes // This proves revalidateTag with profile does NOT cause read-your-own-writes
// (Unlike the bug where click 3 would show a different stale value) // (Unlike the bug where click 3 would show a different stale value)
}) })
// Test for updateTag read-your-own-writes and eager HTML cache regeneration
it('should provide read-your-own-writes and eagerly regenerate HTML cache after updateTag', async () => {
// 1. Open page in browser and get initial value
const browser = await next.browser('/eager-revalidation')
const initial = await browser.elementByCss('#timestamp').text()
// 2. Call updateTag via server action - User A should see fresh data (read-your-own-writes)
await browser.elementByCss('#update-tag').click()
// Wait for action response
let userAValue: string
await retry(async () => {
const afterAction = await browser.elementByCss('#timestamp').text()
// KEY ASSERTION: User A sees fresh content immediately (read-your-own-writes)
expect(afterAction).not.toBe(initial)
userAValue = afterAction
})
// 3. Wait for async HTML cache regeneration
await new Promise((r) => setTimeout(r, 2000))
// 4. Fresh cold visitor (User B) should get same cached HTML
const res = await next.fetch('/eager-revalidation')
const html = await res.text()
const userBValue = html.match(/id="timestamp">(\d+)</)?.[1]
// KEY ASSERTION: User B gets the same fresh value as User A (HTML cache was pre-warmed)
expect(userBValue).toBe(userAValue!)
// 5. Verify it's actually cached (second fetch returns same value)
const res2 = await next.fetch('/eager-revalidation')
const html2 = await res2.text()
const secondFetch = html2.match(/id="timestamp">(\d+)</)?.[1]
expect(secondFetch).toBe(userBValue) // Same cached value
})
// Test for action return values being preserved with split streams
it('should preserve action return values with split flight streams', async () => {
const browser = await next.browser('/eager-revalidation-with-return')
// Click the action button that returns a value
await browser.elementByCss('#update-and-return').click()
// Wait for action to complete and verify the returned value is displayed
await retry(async () => {
const result = await browser.elementByCss('#action-result').text()
expect(result).toContain('success: true')
expect(result).toContain('timestamp:')
})
// Verify page data was also updated (from the page stream)
const cachedTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
expect(cachedTimestamp).not.toBe('')
})
// Test for refresh() triggering eager regeneration
it('should eagerly regenerate HTML cache when refresh() is called', async () => {
const browser = await next.browser('/eager-revalidation-refresh')
// Call refresh with return value
await browser.elementByCss('#refresh-with-return').click()
// Wait for action to complete
await retry(async () => {
const result = await browser.elementByCss('#action-result').text()
expect(result).toContain('refreshed: true')
})
const userATimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
// Wait for cache to be populated
await new Promise((r) => setTimeout(r, 2000))
// Cold visitor should get the same cached value
const res = await next.fetch('/eager-revalidation-refresh')
const html = await res.text()
const userBValue = html.match(/id="cached-timestamp">(\d+)</)?.[1]
// Both users should see the same cached timestamp
expect(userBValue).toBe(userATimestamp)
})
// Test that refresh() does NOT invalidate tagged cached data
// refresh() should only cause re-render with fresh dynamic data, but tagged caches should remain
it('should NOT invalidate tagged cached data when only refresh() is called', async () => {
const browser = await next.browser('/eager-revalidation-refresh')
// Get initial cached timestamp (from build/first render)
const initialTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
// Call refresh() only (not updateTag)
await browser.elementByCss('#refresh-only').click()
// Wait for action to complete and page to re-render
await new Promise((r) => setTimeout(r, 2000))
// The cached timestamp should be THE SAME - refresh() should NOT invalidate tagged caches
const afterRefreshTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
// KEY ASSERTION: Tagged cached data should NOT be invalidated by refresh()
expect(afterRefreshTimestamp).toBe(initialTimestamp)
})
// Test for complex return values across split streams
it('should handle complex return values across split flight streams', async () => {
const browser = await next.browser('/eager-revalidation-complex-return')
await browser.elementByCss('#complex-action').click()
await retry(async () => {
const result = await browser.elementByCss('#result').text()
// Verify nested object, array, and deep array are all present
expect(result).toContain('nested: nested-value')
expect(result).toContain('array: a,b,c')
expect(result).toContain('deep: 1,2,3,4,5')
})
// Verify cached timestamp was also updated
const cachedTimestamp = await browser
.elementByCss('#cached-timestamp')
.text()
expect(cachedTimestamp).not.toBe('none')
})
// Test that regular actions without updateTag/refresh are not affected
it('should not use split streams for actions without updateTag or refresh', async () => {
// This uses the existing cache-tag page which has regular revalidateTag
const browser = await next.browser('/cache-tag')
const initial = await browser.elementByCss('#a').text()
// Revalidate without updateTag - should work normally
await browser.elementByCss('#revalidate-a').click()
await retry(async () => {
expect(await browser.elementByCss('#a').text()).not.toBe(initial)
})
})
} }
it('should override fetch with cookies/auth in use cache properly', async () => { it('should override fetch with cookies/auth in use cache properly', async () => {
......
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