Commit ae13741e authored by Janka Uryga's avatar Janka Uryga

refactor postponed state types

parent f971b0f8
...@@ -107,13 +107,11 @@ import { ...@@ -107,13 +107,11 @@ import {
import { import {
DynamicState, DynamicState,
type PostponedState, type PostponedState,
DynamicHTMLPreludeState,
parsePostponedState, parsePostponedState,
} from './postponed-state' } from './postponed-state'
import { import {
getDynamicDataPostponedState, getFullHtmlPostponedState,
getDynamicHTMLPostponedState, getDynamicHTMLPostponedState,
getPostponedFromState,
} from './postponed-state' } from './postponed-state'
import { isDynamicServerError } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { import {
...@@ -2276,7 +2274,7 @@ async function renderToStream( ...@@ -2276,7 +2274,7 @@ async function renderToStream(
// If provided, the postpone state should be parsed as JSON so it can be // If provided, the postpone state should be parsed as JSON so it can be
// provided to React. // provided to React.
if (typeof renderOpts.postponed === 'string') { if (typeof renderOpts.postponed === 'string') {
if (postponedState?.type === DynamicState.DATA) { if (postponedState?.type === DynamicState.FullHtml) {
// We have a complete HTML Document in the prerender but we need to // We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included // still include the new server component render because it was not included
// in the static prelude. // in the static prelude.
...@@ -2292,8 +2290,6 @@ async function renderToStream( ...@@ -2292,8 +2290,6 @@ async function renderToStream(
) )
} else if (postponedState) { } else if (postponedState) {
// We assume we have dynamic HTML requiring a resume render to complete // We assume we have dynamic HTML requiring a resume render to complete
const { postponed, preludeState } =
getPostponedFromState(postponedState)
const resume = ( const resume = (
require('react-dom/server') as typeof import('react-dom/server') require('react-dom/server') as typeof import('react-dom/server')
).resume ).resume
...@@ -2308,7 +2304,7 @@ async function renderToStream( ...@@ -2308,7 +2304,7 @@ async function renderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
/>, />,
postponed, postponedState.postponed,
{ onError: htmlRendererErrorHandler, nonce } { onError: htmlRendererErrorHandler, nonce }
) )
...@@ -2325,7 +2321,7 @@ async function renderToStream( ...@@ -2325,7 +2321,7 @@ async function renderToStream(
// If we have a non-empty-prelude (i.e. a static HTML shell), then it's already been sent separately, // If we have a non-empty-prelude (i.e. a static HTML shell), then it's already been sent separately,
// so we shouldn't wait for any HTML to be emitted from the resume before sending RSC data. // so we shouldn't wait for any HTML to be emitted from the resume before sending RSC data.
delayDataUntilFirstHtmlChunk: delayDataUntilFirstHtmlChunk:
preludeState === DynamicHTMLPreludeState.Empty, postponedState.type === DynamicState.EmptyHtml,
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consume(), reactServerResult.consume(),
nonce, nonce,
...@@ -3925,17 +3921,14 @@ async function prerenderToStream( ...@@ -3925,17 +3921,14 @@ async function prerenderToStream(
if (postponed != null) { if (postponed != null) {
// Dynamic HTML case // Dynamic HTML case
metadata.postponed = await getDynamicHTMLPostponedState( metadata.postponed = await getDynamicHTMLPostponedState(
preludeIsEmpty ? DynamicState.EmptyHtml : DynamicState.PartialHtml,
postponed, postponed,
preludeIsEmpty
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams, fallbackRouteParams,
resumeDataCache resumeDataCache
) )
} else { } else {
// Dynamic Data case // Dynamic Data case
metadata.postponed = metadata.postponed = await getFullHtmlPostponedState(resumeDataCache)
await getDynamicDataPostponedState(resumeDataCache)
} }
reactServerResult.consume() reactServerResult.consume()
return { return {
...@@ -4148,16 +4141,14 @@ async function prerenderToStream( ...@@ -4148,16 +4141,14 @@ async function prerenderToStream(
if (postponed != null) { if (postponed != null) {
// Dynamic HTML case. // Dynamic HTML case.
metadata.postponed = await getDynamicHTMLPostponedState( metadata.postponed = await getDynamicHTMLPostponedState(
preludeIsEmpty ? DynamicState.EmptyHtml : DynamicState.PartialHtml,
postponed, postponed,
preludeIsEmpty
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams, fallbackRouteParams,
prerenderResumeDataCache prerenderResumeDataCache
) )
} else { } else {
// Dynamic Data case. // Dynamic Data case.
metadata.postponed = await getDynamicDataPostponedState( metadata.postponed = await getFullHtmlPostponedState(
prerenderResumeDataCache prerenderResumeDataCache
) )
} }
...@@ -4182,7 +4173,7 @@ async function prerenderToStream( ...@@ -4182,7 +4173,7 @@ async function prerenderToStream(
} }
} else if (fallbackRouteParams && fallbackRouteParams.size > 0) { } else if (fallbackRouteParams && fallbackRouteParams.size > 0) {
// Rendering the fallback case. // Rendering the fallback case.
metadata.postponed = await getDynamicDataPostponedState( metadata.postponed = await getFullHtmlPostponedState(
prerenderResumeDataCache prerenderResumeDataCache
) )
......
...@@ -5,10 +5,9 @@ import { ...@@ -5,10 +5,9 @@ import {
} from '../stream-utils/node-web-streams-helper' } from '../stream-utils/node-web-streams-helper'
import { import {
DynamicState, DynamicState,
getDynamicDataPostponedState,
getDynamicHTMLPostponedState, getDynamicHTMLPostponedState,
getFullHtmlPostponedState,
parsePostponedState, parsePostponedState,
DynamicHTMLPreludeState,
type PostponedState, type PostponedState,
} from './postponed-state' } from './postponed-state'
...@@ -30,11 +29,11 @@ it('can serialize and deserialize a HTML postponed state with fallback params an ...@@ -30,11 +29,11 @@ it('can serialize and deserialize a HTML postponed state with fallback params an
) )
const state = await getDynamicHTMLPostponedState( const state = await getDynamicHTMLPostponedState(
DynamicState.PartialHtml,
{ {
[fallbackParam]: fallbackParam, [fallbackParam]: fallbackParam,
nested: { [fallbackParam]: fallbackParam }, nested: { [fallbackParam]: fallbackParam },
}, },
DynamicHTMLPreludeState.Full,
fallbackRouteParams, fallbackRouteParams,
prerenderResumeDataCache prerenderResumeDataCache
) )
...@@ -42,16 +41,13 @@ it('can serialize and deserialize a HTML postponed state with fallback params an ...@@ -42,16 +41,13 @@ it('can serialize and deserialize a HTML postponed state with fallback params an
const paramValue = '123' const paramValue = '123'
const parsed = parsePostponedState(state, { slug: paramValue }) const parsed = parsePostponedState(state, { slug: paramValue })
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.PartialHtml,
data: [ postponed: {
DynamicHTMLPreludeState.Full,
{
[paramValue]: paramValue, [paramValue]: paramValue,
nested: { nested: {
[paramValue]: paramValue, [paramValue]: paramValue,
}, },
}, },
],
renderResumeDataCache: expect.any(Object), renderResumeDataCache: expect.any(Object),
} satisfies PostponedState) } satisfies PostponedState)
...@@ -67,8 +63,8 @@ it('can serialize and deserialize a HTML postponed state with fallback params an ...@@ -67,8 +63,8 @@ it('can serialize and deserialize a HTML postponed state with fallback params an
const fallbackParam = '%%drp:slug:e9615126684e5%%' const fallbackParam = '%%drp:slug:e9615126684e5%%'
const fallbackRouteParams = new Map([['slug', fallbackParam]]) const fallbackRouteParams = new Map([['slug', fallbackParam]])
const state = await getDynamicHTMLPostponedState( const state = await getDynamicHTMLPostponedState(
DynamicState.PartialHtml,
{ [fallbackParam]: fallbackParam }, { [fallbackParam]: fallbackParam },
DynamicHTMLPreludeState.Full,
fallbackRouteParams, fallbackRouteParams,
createPrerenderResumeDataCache() createPrerenderResumeDataCache()
) )
...@@ -77,8 +73,8 @@ it('can serialize and deserialize a HTML postponed state with fallback params an ...@@ -77,8 +73,8 @@ it('can serialize and deserialize a HTML postponed state with fallback params an
const params = { slug: paramValue } const params = { slug: paramValue }
const parsed = parsePostponedState(state, params) const parsed = parsePostponedState(state, params)
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.PartialHtml,
data: [DynamicHTMLPreludeState.Full, { [paramValue]: paramValue }], postponed: { [paramValue]: paramValue },
renderResumeDataCache: createPrerenderResumeDataCache(), renderResumeDataCache: createPrerenderResumeDataCache(),
} satisfies PostponedState) } satisfies PostponedState)
...@@ -89,34 +85,34 @@ it('can serialize and deserialize a HTML postponed state with fallback params an ...@@ -89,34 +85,34 @@ it('can serialize and deserialize a HTML postponed state with fallback params an
it.each([ it.each([
{ {
description: 'empty prelude', description: 'empty prelude',
preludeState: DynamicHTMLPreludeState.Empty, type: DynamicState.EmptyHtml as const,
}, },
{ {
description: 'non-empty prelude', description: 'non-empty prelude',
preludeState: DynamicHTMLPreludeState.Full, type: DynamicState.PartialHtml as const,
}, },
])( ])(
'can serialize and deserialize a HTML postponed state with no fallback params - $description', 'can serialize and deserialize a HTML postponed state with no fallback params - $description',
async ({ preludeState }) => { async ({ type }) => {
const fallbackRouteParams = new Map() const fallbackRouteParams = new Map()
const postponed = { fake: 'state' } const postponed = { fake: 'state' }
const state = await getDynamicHTMLPostponedState( const state = await getDynamicHTMLPostponedState(
type,
postponed, postponed,
preludeState,
fallbackRouteParams, fallbackRouteParams,
createPrerenderResumeDataCache() createPrerenderResumeDataCache()
) )
const parsed = parsePostponedState(state, {}) const parsed = parsePostponedState(state, {})
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type,
data: [preludeState, postponed], postponed,
renderResumeDataCache: createPrerenderResumeDataCache(), renderResumeDataCache: createPrerenderResumeDataCache(),
} satisfies PostponedState) } satisfies PostponedState)
} }
) )
it('can serialize and deserialize a data postponed state', async () => { it('can serialize and deserialize a full-html postponed state', async () => {
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
prerenderResumeDataCache.cache.set( prerenderResumeDataCache.cache.set(
'1', '1',
...@@ -130,10 +126,10 @@ it('can serialize and deserialize a data postponed state', async () => { ...@@ -130,10 +126,10 @@ it('can serialize and deserialize a data postponed state', async () => {
}) })
) )
const state = await getDynamicDataPostponedState(prerenderResumeDataCache) const state = await getFullHtmlPostponedState(prerenderResumeDataCache)
const parsed = parsePostponedState(state, {})
expect(parsed.type).toBe(DynamicState.DATA) const parsed = parsePostponedState(state, {})
expect(parsed.type).toBe(DynamicState.FullHtml)
const cacheValue = await parsed.renderResumeDataCache.cache.get('1') const cacheValue = await parsed.renderResumeDataCache.cache.get('1')
expect(cacheValue).toBeDefined() expect(cacheValue).toBeDefined()
......
...@@ -15,24 +15,35 @@ import { ...@@ -15,24 +15,35 @@ import {
export enum DynamicState { export enum DynamicState {
/** /**
* The dynamic access occurred during the RSC render phase. * A dynamic access prevented us from rendering any HTML.
*/ */
DATA = 1, EmptyHtml = 1,
/** /**
* The dynamic access occurred during the HTML shell render phase. * We rendered partial HTML, with some dynamic holes.
*/ */
HTML = 2, PartialHtml = 2,
/**
* A dynamic access occurred during the RSC render phase,
* but did not result in any dynamic holes in the HTML.
*/
FullHtml = 3,
} }
type ReactPostponed = NonNullable<
import('react-dom/static').PrerenderResult['postponed']
>
/** /**
* The postponed state for dynamic data. * The postponed state for a prerender that used dynamic data on the server, but produced complete HTML.
*
* This can happen if dynamic data is passed as a prop to a client component but was not used during SSR.
* (it may be used in an effect, or the usage is guarded behind a `typeof window !== undefined` check)
* We won't get a dynamic hole in the HTML, but still need to render RSC dynamically.
*/ */
export type DynamicDataPostponedState = { export type FullHtmlPostponedState = {
/** readonly type: DynamicState.FullHtml
* The type of dynamic state.
*/
readonly type: DynamicState.DATA
/** /**
* The immutable resume data cache. * The immutable resume data cache.
...@@ -40,22 +51,11 @@ export type DynamicDataPostponedState = { ...@@ -40,22 +51,11 @@ export type DynamicDataPostponedState = {
readonly renderResumeDataCache: RenderResumeDataCache readonly renderResumeDataCache: RenderResumeDataCache
} }
/** export type DynamicHTMLPostponedStateBase = {
* The postponed state for dynamic HTML.
*/
export type DynamicHTMLPostponedState = {
/**
* The type of dynamic state.
*/
readonly type: DynamicState.HTML
/** /**
* The postponed data used by React. * The postponed data used by React.
*/ */
readonly data: [ readonly postponed: ReactPostponed
preludeState: DynamicHTMLPreludeState,
postponed: ReactPostponed,
]
/** /**
* The immutable resume data cache. * The immutable resume data cache.
...@@ -63,18 +63,25 @@ export type DynamicHTMLPostponedState = { ...@@ -63,18 +63,25 @@ export type DynamicHTMLPostponedState = {
readonly renderResumeDataCache: RenderResumeDataCache readonly renderResumeDataCache: RenderResumeDataCache
} }
export const enum DynamicHTMLPreludeState { /**
Empty = 0, * The postponed state for a partial prerender that produced an HTML shell,
Full = 1, * but has dynamic holes.
} */
export type PartialHTMLPostponedState = {
readonly type: DynamicState.PartialHtml
} & DynamicHTMLPostponedStateBase
type ReactPostponed = NonNullable< /**
import('react-dom/static').PrerenderResult['postponed'] * The postponed state for a partial prerender that produced no HTML shell.
> */
export type EmptyHTMLPostponedState = {
readonly type: DynamicState.EmptyHtml
} & DynamicHTMLPostponedStateBase
export type PostponedState = export type PostponedState =
| DynamicDataPostponedState | EmptyHTMLPostponedState
| DynamicHTMLPostponedState | PartialHTMLPostponedState
| FullHtmlPostponedState
function serializeStateParts(state: SerializedStateParts) { function serializeStateParts(state: SerializedStateParts) {
return lengthEncodeTupleWithTag(state) return lengthEncodeTupleWithTag(state)
...@@ -84,12 +91,14 @@ function deserializeStateParts(serialized: string) { ...@@ -84,12 +91,14 @@ function deserializeStateParts(serialized: string) {
return lengthDecodeTupleWithTag(serialized) as SerializedStateParts return lengthDecodeTupleWithTag(serialized) as SerializedStateParts
} }
type SerializedStateParts = SerializedDynamicData | SerializedDynamicHTML type SerializedStateParts =
| SerializedFullHtml
| SerializedEmptyHTML
| SerializedPartialHTML
type SerializedDynamicData = [tag: DynamicState.DATA, resumeDataCache: string] type SerializedFullHtml = [tag: DynamicState.FullHtml, resumeDataCache: string]
type SerializedDynamicHTML = [ type SerializedDynamicHTMLBase = [
tag: DynamicState.HTML,
resumeDataCache: string, resumeDataCache: string,
/** JSON, but might need to have `replacements` applied before decoding */ /** JSON, but might need to have `replacements` applied before decoding */
postponed: string, postponed: string,
...@@ -97,16 +106,25 @@ type SerializedDynamicHTML = [ ...@@ -97,16 +106,25 @@ type SerializedDynamicHTML = [
replacements: string, replacements: string,
] ]
type SerializedEmptyHTML = [
tag: DynamicState.EmptyHtml,
...SerializedDynamicHTMLBase,
]
type SerializedPartialHTML = [
tag: DynamicState.PartialHtml,
...SerializedDynamicHTMLBase,
]
type ParamReplacements = Array<[string, string]> | null type ParamReplacements = Array<[string, string]> | null
export async function getDynamicHTMLPostponedState( export async function getDynamicHTMLPostponedState(
type: DynamicState.EmptyHtml | DynamicState.PartialHtml,
postponed: ReactPostponed, postponed: ReactPostponed,
preludeState: DynamicHTMLPreludeState,
fallbackRouteParams: FallbackRouteParams | null, fallbackRouteParams: FallbackRouteParams | null,
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
): Promise<string> { ): Promise<string> {
const data: DynamicHTMLPostponedState['data'] = [preludeState, postponed] const dataString = JSON.stringify(postponed)
const dataString = JSON.stringify(data)
let replacements: ParamReplacements = null let replacements: ParamReplacements = null
if (!fallbackRouteParams || fallbackRouteParams.size === 0) { if (!fallbackRouteParams || fallbackRouteParams.size === 0) {
...@@ -117,18 +135,18 @@ export async function getDynamicHTMLPostponedState( ...@@ -117,18 +135,18 @@ export async function getDynamicHTMLPostponedState(
const replacementsString = JSON.stringify(replacements) const replacementsString = JSON.stringify(replacements)
return serializeStateParts([ return serializeStateParts([
DynamicState.HTML, type,
await stringifyResumeDataCache(resumeDataCache), await stringifyResumeDataCache(resumeDataCache),
dataString, dataString,
replacementsString, replacementsString,
]) ])
} }
export async function getDynamicDataPostponedState( export async function getFullHtmlPostponedState(
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
): Promise<string> { ): Promise<string> {
return serializeStateParts([ return serializeStateParts([
DynamicState.DATA, DynamicState.FullHtml,
await stringifyResumeDataCache( await stringifyResumeDataCache(
createRenderResumeDataCache(resumeDataCache) createRenderResumeDataCache(resumeDataCache)
), ),
...@@ -139,21 +157,26 @@ export function parsePostponedState( ...@@ -139,21 +157,26 @@ export function parsePostponedState(
state: string, state: string,
params: Params | undefined params: Params | undefined
): PostponedState { ): PostponedState {
// If the deserialization fails, we can fall back to treating thisa s a `FullHtml` render,
// i.e. as if the prerender produced full HTML but still needs dynamic RSC.
// The HTML shell may in fact be incomplete or empty, but we should produce an RSC payload
// that will let the browser client-render a functional page.
try { try {
const parts = deserializeStateParts(state) const parts = deserializeStateParts(state)
const tag = parts[0] const tag = parts[0]
switch (tag) { switch (tag) {
case DynamicState.DATA: { case DynamicState.FullHtml: {
const [, resumeDataCacheString] = parts const [, resumeDataCacheString] = parts
const renderResumeDataCache = createRenderResumeDataCache( const renderResumeDataCache = createRenderResumeDataCache(
resumeDataCacheString resumeDataCacheString
) )
return { return {
type: DynamicState.DATA, type: DynamicState.FullHtml,
renderResumeDataCache, renderResumeDataCache,
} }
} }
case DynamicState.HTML: { case DynamicState.EmptyHtml:
case DynamicState.PartialHtml: {
let [, resumeDataCacheString, postponedString, replacementsString] = let [, resumeDataCacheString, postponedString, replacementsString] =
parts parts
...@@ -178,13 +201,13 @@ export function parsePostponedState( ...@@ -178,13 +201,13 @@ export function parsePostponedState(
} }
return { return {
type: DynamicState.HTML, type: tag,
data: JSON.parse(postponedString), postponed: JSON.parse(postponedString),
renderResumeDataCache, renderResumeDataCache,
} }
} catch (err) { } catch (err) {
console.error('Failed to parse postponed state', err) console.error('Failed to parse postponed state', err)
return { type: DynamicState.DATA, renderResumeDataCache } return { type: DynamicState.FullHtml, renderResumeDataCache }
} }
} }
default: { default: {
...@@ -195,13 +218,8 @@ export function parsePostponedState( ...@@ -195,13 +218,8 @@ export function parsePostponedState(
} catch (err) { } catch (err) {
console.error('Failed to parse postponed state', err) console.error('Failed to parse postponed state', err)
return { return {
type: DynamicState.DATA, type: DynamicState.FullHtml,
renderResumeDataCache: createPrerenderResumeDataCache(), renderResumeDataCache: createPrerenderResumeDataCache(),
} }
} }
} }
export function getPostponedFromState(state: DynamicHTMLPostponedState) {
const [preludeState, postponed] = state.data
return { preludeState, postponed }
}
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