Unverified Commit 89c67992 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Statically prerender metadata image routes under Cache Components (#94957)

Under Cache Components, metadata image routes such as `opengraph-image`
and `icon` that return an `ImageResponse` were always rendered on demand
(`ƒ`) rather than prerendered. `ImageResponse` defers rasterizing its
element tree into the response body stream, and the route-handler
prerender unwraps that body within a single task; the rasterization
never finishes within that budget, so the route was classified as
dynamic. This change renders and caches the image during the prerender
so these routes become static (`○`).

During the prerender we serialize the `ImageResponse` arguments with
React Flight's `prerenderToNodeStream` inside the prerender work-unit
store, which runs the user's component tree once in the correct scope.
This brings any user-space I/O inside that tree, such as `cookies()` or
an uncached `fetch`, under the same Cache Components rules that already
governed I/O elsewhere in the handler. The hanging-input abort signal
bounds the serialization and decides static versus dynamic: if the tree
is still waiting on dynamic input once the prerender's cache-sourced
input is ready, the serialization can't complete and we return a hanging
promise, so the final prerender's macrotask budget classifies the route
as dynamic; a tree that resolves entirely from static data or `use
cache` finishes serializing and is rendered to an image. This mirrors
`encryptActionBoundArgs`, which serializes server action bound args with
React Flight under the same hanging-input abort signal during a
prerender.

The fully resolved element tree is then handed to satori. Because React
Flight encodes an async Server Component's output as a `React.lazy` that
satori can't walk, those references are resolved into plain elements
first; this lets an async server component, including one that uses `use
cache`, be passed as the `ImageResponse` element. Rasterization runs
outside the prerender work-unit store: inside a Cache Components
prerender an uncached `fetch`, such as the renderer loading a font, is
turned into a hanging promise (Cache Components skips I/O that would not
be cached anyway), so running satori with no store lets those framework
fetches resolve normally. Crucially, because satori only walks the
already-resolved tree, no user component runs in that storeless scope,
so uncached user-space I/O can't be wrongly allowed there and let a
route that should be dynamic render as static.

The rendered image is stored as an `ArrayBuffer` in a new in-memory
`imageResponses` store on the Resume Data Cache, keyed by a base64
encoding of its serialized arguments, and the cache signal is held open
until it is stored so the prospective prerender waits for it. The final
prerender retrieves the array buffer from memory within microtasks. The
store is in-memory only and is never serialized, so the image array
buffers never enter the resume data that ships with the prerender.

The caching path lives in a separate `cache-image-response` module that
is loaded only for Cache Components builds, gated behind
`process.env.__NEXT_CACHE_COMPONENTS` so the `require` and its React
Flight dependencies are eliminated as dead code otherwise; apps without
Cache Components keep `ImageResponse`'s original streaming behavior
unchanged.

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent db565337
......@@ -1371,5 +1371,6 @@
"1370": "Route %s used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1371": "Route %s used \\`io()\\` inside \\`after()\\`. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1372": "Route %s used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1373": "Route %s used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after"
"1373": "Route %s used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1374": "Expected a work store while caching an `ImageResponse` during prerendering."
}
......@@ -26,6 +26,7 @@ import type {
PrerenderStoreLegacy,
PrerenderStoreModern,
ValidationStoreClient,
PrerenderStoreModernServer,
} from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
......@@ -554,6 +555,12 @@ export function createRenderInBrowserAbortSignal(): AbortSignal {
* stalling on connection() or because they're loading dynamic data. In that
* case we need to abort the encoding of arguments since they'll never complete.
*/
export function createHangingInputAbortSignal(
workUnitStore: PrerenderStoreModernServer
): AbortSignal
export function createHangingInputAbortSignal(
workUnitStore: WorkUnitStore
): AbortSignal | undefined
export function createHangingInputAbortSignal(
workUnitStore: WorkUnitStore
): AbortSignal | undefined {
......
......@@ -77,6 +77,7 @@ describe('getDynamicHTMLPostponedState', () => {
"decryptedBoundArgs": Map {},
"encryptedBoundArgs": Map {},
"fetch": Map {},
"imageResponses": Map {},
"mutable": false,
},
"type": 2,
......@@ -125,6 +126,7 @@ describe('getDynamicHTMLPostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
mutable: false,
},
})
......@@ -161,6 +163,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
mutable: false,
},
})
......@@ -183,6 +186,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
mutable: false,
},
})
......@@ -200,6 +204,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
mutable: false,
},
})
......
This diff is collapsed.
......@@ -10,6 +10,30 @@ function importModule(): Promise<
)
}
// The Cache Components-specific caching path (and its React Flight and Node
// stream dependencies) lives in a separate module that is only required for
// Node.js Cache Components builds. The `NEXT_RUNTIME` guard matters because
// `__NEXT_CACHE_COMPONENTS` is derived from config, not the per-route runtime,
// so it stays `true` in edge bundles too. A Pages Router edge route that
// renders an `ImageResponse` is valid under Cache Components, and without the
// guard this node-only module would be pulled into that edge bundle and fail to
// compile. (App Router edge routes, including metadata routes, are
// independently rejected at compile time under Cache Components.) Both checks
// fold to constants at build time, so the `require` is eliminated as dead code
// for edge builds and for apps without Cache Components, which keep
// ImageResponse's original streaming behavior.
let getCachedImageResponseBody:
| typeof import('./cache-image-response').getCachedImageResponseBody
| undefined
if (
process.env.NEXT_RUNTIME !== 'edge' &&
process.env.__NEXT_CACHE_COMPONENTS
) {
getCachedImageResponseBody = (
require('./cache-image-response') as typeof import('./cache-image-response')
).getCachedImageResponseBody
}
/**
* The ImageResponse class allows you to generate dynamic images using JSX and CSS.
* This is useful for generating social media images such as Open Graph images, Twitter cards, and more.
......@@ -19,28 +43,33 @@ function importModule(): Promise<
export class ImageResponse extends Response {
public static displayName = 'ImageResponse'
constructor(...args: ConstructorParameters<OgModule['ImageResponse']>) {
const readable = new ReadableStream({
async start(controller) {
const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse =
// So far we have to manually determine which build to use,
// as the auto resolving is not working
(await importModule()).ImageResponse
const imageResponse = new OGImageResponse(...args) as Response
// Under Cache Components, route the render through the cache so metadata
// image routes can be statically prerendered. Otherwise stream the rendered
// image directly from the underlying `@vercel/og` response.
const readable = getCachedImageResponseBody
? getCachedImageResponseBody(args)
: new ReadableStream({
async start(controller) {
const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse =
// So far we have to manually determine which build to use, as the
// auto resolving is not working
(await importModule()).ImageResponse
const imageResponse = new OGImageResponse(...args) as Response
if (!imageResponse.body) {
return controller.close()
}
if (!imageResponse.body) {
return controller.close()
}
const reader = imageResponse.body!.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
return controller.close()
}
controller.enqueue(value)
}
},
})
const reader = imageResponse.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
return controller.close()
}
controller.enqueue(value)
}
},
})
const options = args[1] || {}
......
......@@ -30,6 +30,16 @@ export type EncryptedBoundArgsCacheStore = CacheStore<string>
*/
export type DecryptedBoundArgsCacheStore = CacheStore<string>
/**
* An in-memory-only cache store for rendered `ImageResponse` array buffers,
* keyed by a serialization of the `ImageResponse` constructor args. This lets
* the prospective prerender render the image once and hand the array buffer to
* the final prerender within microtasks, so that metadata image routes can be
* statically prerendered under Cache Components. Never serialized into the
* resume store.
*/
export type ImageResponseCacheStore = CacheStore<Promise<ArrayBuffer>>
/**
* Serialized format for "use cache" entries
*/
......
......@@ -6,6 +6,7 @@ import {
serializeUseCacheCacheStore,
parseUseCacheCacheStore,
type DecryptedBoundArgsCacheStore,
type ImageResponseCacheStore,
type UseCacheCacheStoreSerialized,
} from './cache-store'
......@@ -48,6 +49,14 @@ export interface RenderResumeDataCache {
*/
readonly decryptedBoundArgs: Omit<DecryptedBoundArgsCacheStore, 'set'>
/**
* A read-only in-memory Map store for rendered `ImageResponse` array buffers.
* This is only intended for in-memory usage during pre-rendering, and must
* not be persisted in the resume store. The 'set' operation is omitted to
* enforce immutability.
*/
readonly imageResponses: Omit<ImageResponseCacheStore, 'set'>
/**
* Serialized cache keys that were intentionally skipped during the
* prospective prerender (e.g. because the cached function accessed fallback
......@@ -101,6 +110,13 @@ export interface PrerenderResumeDataCache {
*/
readonly decryptedBoundArgs: DecryptedBoundArgsCacheStore
/**
* A mutable in-memory Map store for rendered `ImageResponse` array buffers.
* Filled during the prospective prerender and read during the final
* prerender. Never persisted in the resume store.
*/
readonly imageResponses: ImageResponseCacheStore
/**
* Tracks serialized cache keys that were intentionally skipped during the
* prospective prerender (e.g. because the cached function accessed fallback
......@@ -204,6 +220,7 @@ export function createPrerenderResumeDataCache(
fetch: new Map(source.fetch),
encryptedBoundArgs: new Map(source.encryptedBoundArgs),
decryptedBoundArgs: new Map(source.decryptedBoundArgs),
imageResponses: new Map(source.imageResponses),
dynamicCacheKeys: source.dynamicCacheKeys
? new Set(source.dynamicCacheKeys)
: new Set(),
......@@ -215,6 +232,7 @@ export function createPrerenderResumeDataCache(
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
dynamicCacheKeys: new Set(),
}
}
......@@ -265,6 +283,7 @@ export function createRenderResumeDataCache(
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
}
}
......@@ -308,6 +327,7 @@ export function createRenderResumeDataCache(
Object.entries(json.store.encryptedBoundArgs)
),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
}
}
}
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
export const size = { width: 180, height: 180 }
export default function appleIcon() {
return new ImageResponse(<AsyncAppleIcon />)
}
async function AsyncAppleIcon() {
'use cache'
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return (
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 88,
background: '#fff',
color: '#000',
}}
>
{data}
</div>
)
}
import { cookies } from 'next/headers'
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
export const alt = 'Twitter'
export const size = { width: 1600, height: 900 }
export default function twitterImage() {
return new ImageResponse(<AsyncTwitterImage />, size)
}
async function AsyncTwitterImage() {
const cookieStore = await cookies()
const numCookies = cookieStore.getAll().length
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return (
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 128,
background: 'lavender',
}}
>
{data} {numCookies}
</div>
)
}
......@@ -13,11 +13,7 @@ describe('use-cache-metadata-route-handler', () => {
if (isNextStart) {
const [buildStatus] = next.cliOutput.match(/. \/opengraph-image/)
// TODO: Should always be `○ /opengraph-image`.
expect(buildStatus).toBeOneOf([
'○ /opengraph-image',
'ƒ /opengraph-image',
])
expect(buildStatus).toBe('○ /opengraph-image')
}
})
......@@ -29,8 +25,31 @@ describe('use-cache-metadata-route-handler', () => {
if (isNextStart) {
const [buildStatus] = next.cliOutput.match(/. \/icon/)
// TODO: Should always be `○ /icon`.
expect(buildStatus).toBeOneOf(['○ /icon', 'ƒ /icon'])
expect(buildStatus).toBe('○ /icon')
}
})
it('should statically prerender an image whose component uses "use cache" directly', async () => {
const res = await next.fetch('/apple-icon')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
if (isNextStart) {
const [buildStatus] = next.cliOutput.match(/. \/apple-icon/)
expect(buildStatus).toBe('○ /apple-icon')
}
})
it('should treat a twitter image that reads request data as dynamic', async () => {
const res = await next.fetch('/twitter-image')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
if (isNextStart) {
const [buildStatus] = next.cliOutput.match(/. \/twitter-image/)
expect(buildStatus).toBe('ƒ /twitter-image')
}
})
......
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