Commit ae13741e authored by Janka Uryga's avatar Janka Uryga

refactor postponed state types

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