Unverified Commit f9697190 authored by Josh Story's avatar Josh Story Committed by GitHub

Refactor: Separate RSC renderer from SSR wrapping component (#59676)

This commit updates some of the code organization in app-render in
preparation for supporting dynamic RSC repsonses on top of static SSR
responses for PPR. The main change to notice is the separation of
creating the server component renderer which initiates the RSC render
and executes in the RSC layer with the consuming component which lives
in the SSR layer. By organizing the code this way we can later only call
the server render in certain cases, omitting the SSR render entirely.

This is different than just using the generaetFlight pathway because
that pathway serves client navs and does not actually render the same
output that the intial render does.

Closes NEXT-1889
parent 6bde3e50
import type { RenderOpts } from './types' import type { RenderOpts } from './types'
import type { FlightResponseRef } from './flight-response-ref'
import type { AppPageModule } from '../future/route-modules/app-page/module' import type { AppPageModule } from '../future/route-modules/app-page/module'
import type { createErrorHandler } from './create-error-handler' import type { createErrorHandler } from './create-error-handler'
import React, { use } from 'react'
import { useFlightResponse } from './use-flight-response'
export type ServerComponentRendererOptions = {
ComponentMod: AppPageModule
inlinedDataTransformStream: TransformStream<Uint8Array, Uint8Array>
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
formState: null | any
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>
nonce?: string
}
/** /**
* Create a component that renders the Flight stream. * Create a component that renders the Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers. * This is only used for renderToHTML, the Flight response does not need additional wrappers.
*/ */
export function createServerComponentRenderer<Props>( export function createReactServerRenderer(
ComponentToRender: (props: Props) => any, children: React.ReactNode,
{ ComponentMod: AppPageModule,
ComponentMod, clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
inlinedDataTransformStream, onError: ReturnType<typeof createErrorHandler>,
clientReferenceManifest, onPostpone: (reason: unknown) => void
formState, ): () => ReadableStream<Uint8Array> {
nonce,
serverComponentsErrorHandler,
}: ServerComponentRendererOptions
): (props: Props) => JSX.Element {
let flightStream: ReadableStream<Uint8Array> let flightStream: ReadableStream<Uint8Array>
const createFlightStream = (props: Props) => { return function renderToReactServerStream() {
if (!flightStream) { if (flightStream) {
return flightStream
} else {
flightStream = ComponentMod.renderToReadableStream( flightStream = ComponentMod.renderToReadableStream(
<ComponentToRender {...(props as any)} />, children,
clientReferenceManifest.clientModules, clientReferenceManifest.clientModules,
{ {
onError: serverComponentsErrorHandler, onError,
onPostpone,
} }
) )
}
return flightStream return flightStream
} }
const flightResponseRef: FlightResponseRef = { current: null }
const writable = inlinedDataTransformStream.writable
return function ServerComponentWrapper(props: Props): JSX.Element {
const response = useFlightResponse(
writable,
createFlightStream(props),
clientReferenceManifest,
flightResponseRef,
formState,
nonce
)
return use(response)
} }
} }
export interface FlightResponseRef {
current: Promise<JSX.Element> | null
}
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { FlightResponseRef } from './flight-response-ref'
import { htmlEscapeJsonString } from '../htmlescape' import { htmlEscapeJsonString } from '../htmlescape'
import { import {
...@@ -42,6 +41,11 @@ function createFlightTransformer( ...@@ -42,6 +41,11 @@ function createFlightTransformer(
}) })
} }
const flightResponses = new WeakMap<
ReadableStream<Uint8Array>,
Promise<JSX.Element>
>()
/** /**
* Render Flight stream. * Render Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers. * This is only used for renderToHTML, the Flight response does not need additional wrappers.
...@@ -50,13 +54,15 @@ export function useFlightResponse( ...@@ -50,13 +54,15 @@ export function useFlightResponse(
writable: WritableStream<Uint8Array>, writable: WritableStream<Uint8Array>,
flightStream: ReadableStream<Uint8Array>, flightStream: ReadableStream<Uint8Array>,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
flightResponseRef: FlightResponseRef,
formState: null | any, formState: null | any,
nonce?: string nonce?: string
): Promise<JSX.Element> { ): Promise<JSX.Element> {
if (flightResponseRef.current !== null) { const response = flightResponses.get(flightStream)
return flightResponseRef.current
if (response) {
return response
} }
// react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly
let createFromReadableStream let createFromReadableStream
// @TODO: investigate why the aliasing for turbopack doesn't pick this up, requiring this runtime check // @TODO: investigate why the aliasing for turbopack doesn't pick this up, requiring this runtime check
...@@ -80,21 +86,25 @@ export function useFlightResponse( ...@@ -80,21 +86,25 @@ export function useFlightResponse(
}, },
nonce, nonce,
}) })
flightResponseRef.current = res flightResponses.set(flightStream, res)
pipeFlightDataToInlinedStream(forwardStream, writable, nonce, formState)
return res
}
forwardStream function pipeFlightDataToInlinedStream(
flightStream: ReadableStream<Uint8Array>,
writable: WritableStream<Uint8Array>,
nonce: string | undefined,
formState: unknown | null
): void {
flightStream
.pipeThrough(createDecodeTransformStream()) .pipeThrough(createDecodeTransformStream())
.pipeThrough(createFlightTransformer(nonce, formState)) .pipeThrough(createFlightTransformer(nonce, formState))
.pipeThrough(createEncodeTransformStream()) .pipeThrough(createEncodeTransformStream())
.pipeTo(writable) .pipeTo(writable)
.finally(() => {
// Once the last encoding stream has flushed, then unset the flight
// response ref.
flightResponseRef.current = null
})
.catch((err) => { .catch((err) => {
console.error('Unexpected error while rendering Flight stream', err) console.error('Unexpected error while rendering Flight stream', err)
}) })
return res
} }
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