Commit dddf2c76 authored by Jimmy Lai's avatar Jimmy Lai

Improve SSR throughput with micro-optimizations and webstreams improvements

Merges 6 separate TransformStream instances into a single unified
createUnifiedSSRTransformStream for the dynamic SSR path, eliminating
intermediate stream allocations and microtask hops per chunk.

Adds opt-in perf marks (NEXT_PERF_MARKS=1) with zero overhead when
disabled, benchmark runner with CPU profiling and phase timing, and
unit tests covering behavioral equivalence between legacy and unified
transform chains.
parent 6aeef8eb
last-run.json
*.cpuprofile
......@@ -271,7 +271,7 @@ async function createForwardedActionResponse(
) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
if (!actionsForbiddenHeaders.has(key)) {
res.setHeader(key, value)
}
}
......@@ -430,7 +430,7 @@ async function createRedirectRenderResult(
) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
if (!actionsForbiddenHeaders.has(key)) {
res.setHeader(key, value)
}
}
......
......@@ -156,6 +156,10 @@ import { createOpaqueFallbackRouteParams } from './request/fallback-params'
import { RouteKind } from './route-kind'
import type { ErrorModule } from './load-default-error-components'
// Pre-computed Vary header strings to avoid string concatenation per request
const BASE_VARY_HEADER = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`
const BASE_VARY_HEADER_WITH_NEXT_URL = `${BASE_VARY_HEADER}, ${NEXT_URL}`
export type FindComponentsResult<
NextModule extends GenericComponentMod = GenericComponentMod,
> = {
......@@ -959,7 +963,10 @@ export default abstract class Server<
// hello/world or backslashes to forward slashes, this does not
// handle trailing slash as that is handled the same as a next.config.js
// redirect
if (urlNoQuery?.match(/(\\|\/\/)/)) {
if (
urlNoQuery &&
(urlNoQuery.includes('//') || urlNoQuery.includes('\\'))
) {
const cleanUrl = normalizeRepeatedSlashes(req.url!)
res.redirect(cleanUrl, 308).body(cleanUrl).send()
return
......@@ -1768,15 +1775,17 @@ export default abstract class Server<
const ctx: RequestContext<ServerRequest, ServerResponse> = {
...partialContext,
renderOpts: {
...this.renderOpts,
// Use Object.create to avoid copying all ~30+ properties of renderOpts
// per request. The per-request overrides become own properties on a
// prototypal child, while base properties are inherited via prototype.
renderOpts: Object.assign(Object.create(this.renderOpts), {
// `renderOpts.botType` is accumulated in `this.renderImpl()`
supportsDynamicResponse: !this.renderOpts.botType,
serveStreamingMetadata: shouldServeStreamingMetadata(
ua,
this.nextConfig.htmlLimitedBots
),
},
}),
}
const payload = await fn(ctx)
......@@ -1826,10 +1835,10 @@ export default abstract class Server<
): Promise<string | null> {
const ctx: RequestContext<ServerRequest, ServerResponse> = {
...partialContext,
renderOpts: {
...this.renderOpts,
// Prototypal inheritance avoids copying all renderOpts properties per call
renderOpts: Object.assign(Object.create(this.renderOpts), {
supportsDynamicResponse: false,
},
}),
}
const payload = await fn(ctx)
if (payload === null) {
......@@ -1989,7 +1998,6 @@ export default abstract class Server<
isAppPath: boolean,
resolvedPathname: string
): void {
const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
let addedNextUrlToVary = false
......@@ -1997,12 +2005,12 @@ export default abstract class Server<
if (isAppPath && this.pathCouldBeIntercepted(resolvedPathname)) {
// Interception route responses can vary based on the `Next-URL` header.
// We use the Vary header to signal this behavior to the client to properly cache the response.
res.appendHeader('vary', `${baseVaryHeader}, ${NEXT_URL}`)
res.appendHeader('vary', BASE_VARY_HEADER_WITH_NEXT_URL)
addedNextUrlToVary = true
} else if (isAppPath || isRSCRequest) {
// We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.
// We also set this header for pages to avoid caching issues when navigating between pages and app.
res.appendHeader('vary', baseVaryHeader)
res.appendHeader('vary', BASE_VARY_HEADER)
}
if (!addedNextUrlToVary) {
......@@ -2612,10 +2620,10 @@ export default abstract class Server<
{
...ctx,
pathname: match.definition.pathname,
renderOpts: {
...ctx.renderOpts,
// Prototypal inheritance avoids copying all renderOpts per match
renderOpts: Object.assign(Object.create(ctx.renderOpts), {
params: match.params,
},
}),
},
bubbleNoFallback
)
......
export const ipcForbiddenHeaders = [
// Use Sets for O(1) header lookups instead of O(n) Array.includes()
export const ipcForbiddenHeaders = new Set([
'accept-encoding',
'keepalive',
'keep-alive',
......@@ -8,17 +9,17 @@ export const ipcForbiddenHeaders = [
'connection',
// marked as unsupported by undici: https://github.com/nodejs/undici/blob/c83b084879fa0bb8e0469d31ec61428ac68160d5/lib/core/request.js#L354
'expect',
]
])
export const actionsForbiddenHeaders = [
export const actionsForbiddenHeaders = new Set([
...ipcForbiddenHeaders,
'content-length',
'set-cookie',
]
])
export const filterReqHeaders = (
headers: Record<string, undefined | string | number | string[]>,
forbiddenHeaders: string[]
forbiddenHeaders: Set<string>
) => {
// Some browsers are not matching spec and sending Content-Length: 0. This causes issues in undici
// https://github.com/nodejs/undici/issues/2046
......@@ -28,7 +29,7 @@ export const filterReqHeaders = (
for (const [key, value] of Object.entries(headers)) {
if (
forbiddenHeaders.includes(key) ||
forbiddenHeaders.has(key) ||
!(Array.isArray(value) || typeof value === 'string')
) {
delete headers[key]
......@@ -39,7 +40,7 @@ export const filterReqHeaders = (
// These are headers that are only used internally and should
// not be honored from the external request
const INTERNAL_HEADERS = [
const INTERNAL_HEADERS = new Set([
'x-middleware-rewrite',
'x-middleware-redirect',
'x-middleware-set-cookie',
......@@ -49,13 +50,13 @@ const INTERNAL_HEADERS = [
'x-now-route-matches',
'x-matched-path',
'x-next-resume-state-length',
]
])
export const filterInternalHeaders = (
headers: Record<string, undefined | string | string[]>
) => {
for (const header in headers) {
if (INTERNAL_HEADERS.includes(header)) {
if (INTERNAL_HEADERS.has(header)) {
delete headers[header]
}
}
......
......@@ -4,16 +4,20 @@ import {
} from '../../shared/lib/router/utils/is-bot'
import type { BaseNextRequest } from '../base-http'
let cachedRegexSource: string | undefined
let cachedRegex: RegExp | undefined
export function shouldServeStreamingMetadata(
userAgent: string,
htmlLimitedBots: string | undefined
): boolean {
const blockingMetadataUARegex = new RegExp(
htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING,
'i'
)
const source = htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING
if (source !== cachedRegexSource) {
cachedRegex = new RegExp(source, 'i')
cachedRegexSource = source
}
// Only block metadata for HTML-limited bots
if (userAgent && blockingMetadataUARegex.test(userAgent)) {
if (userAgent && cachedRegex!.test(userAgent)) {
return false
}
return true
......
......@@ -140,7 +140,9 @@ export const NextVanillaSpanAllowlist = new Set([
NextNodeServerSpan.createComponentTree,
NextNodeServerSpan.findPageComponents,
NextNodeServerSpan.getLayoutOrPageModule,
NextNodeServerSpan.startResponse,
// startResponse removed: it wraps a no-op `() => undefined` in pipe-readable.ts,
// so the span has no meaningful duration or children. Removing it avoids
// context.with(), startActiveSpan(), and rootSpanAttributesStore overhead per request.
NextNodeServerSpan.clientComponentLoading,
])
......
......@@ -9,6 +9,10 @@ import { getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants'
import { getClientComponentLoaderMetrics } from './client-component-renderer-logger'
// Cache env var at module level to avoid per-request process.env lookups
const NEXT_OTEL_PERFORMANCE_PREFIX =
process.env.NEXT_OTEL_PERFORMANCE_PREFIX || ''
export function isAbortError(e: any): e is Error & { name: 'AbortError' } {
return e?.name === 'AbortError' || e?.name === ResponseAbortedName
}
......@@ -50,14 +54,11 @@ function createWriterFromResponse(
if (!started) {
started = true
if (
'performance' in globalThis &&
process.env.NEXT_OTEL_PERFORMANCE_PREFIX
) {
if (NEXT_OTEL_PERFORMANCE_PREFIX) {
const metrics = getClientComponentLoaderMetrics()
if (metrics) {
performance.measure(
`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,
`${NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,
{
start: metrics.clientComponentLoadStart,
end:
......
import { ENCODED_TAGS } from './encoded-tags'
import {
createBufferedTransformStream,
createHeadInsertionTransformStream,
createFlightDataInjectionTransformStream,
createMetadataTransformStream,
createMoveSuffixStream,
createUnifiedSSRTransformStream,
} from './node-web-streams-helper'
import { scheduleImmediate } from '../../lib/scheduler'
const encoder = new TextEncoder()
const decoder = new TextDecoder()
// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------
// Pipe a source ReadableStream through one or more TransformStreams and collect output
async function pipeAndCollect(
input: ReadableStream<Uint8Array>,
transforms: TransformStream<Uint8Array, Uint8Array>[]
): Promise<string> {
let stream: ReadableStream<Uint8Array> = input
for (const t of transforms) {
stream = stream.pipeThrough(t)
}
const reader = stream.getReader()
const chunks: Uint8Array[] = []
while (true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
}
const total = chunks.reduce((sum, c) => sum + c.byteLength, 0)
const merged = new Uint8Array(total)
let offset = 0
for (const c of chunks) {
merged.set(c, offset)
offset += c.byteLength
}
return decoder.decode(merged)
}
function streamFromChunks(chunks: string[]): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(encoder.encode(chunk))
}
controller.close()
},
})
}
function streamFromUint8Arrays(
chunks: Uint8Array[]
): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(chunk)
}
controller.close()
},
})
}
// A minimal deferred suffix stream that matches the original behavior:
// after the first chunk, schedule the suffix to be enqueued on next tick.
function createDeferredSuffixStream(
suffix: string
): TransformStream<Uint8Array, Uint8Array> {
let flushed = false
let pending: Promise<void> | undefined
let pendingResolve: (() => void) | undefined
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk)
if (flushed) return
flushed = true
pending = new Promise<void>((resolve) => {
pendingResolve = resolve
})
scheduleImmediate(() => {
try {
controller.enqueue(encoder.encode(suffix))
} catch {
// stream may be errored/cancelled
} finally {
const r = pendingResolve!
pendingResolve = undefined
pending = undefined
r()
}
})
},
flush() {
if (pending) return pending
if (flushed) return
// Never got a chunk, but flush should still emit the suffix
},
})
}
// Create a ReadableStream that delivers chunks asynchronously (one per tick).
// This simulates how React delivers chunks in real SSR (not all at once).
function asyncStreamFromChunks(chunks: string[]): ReadableStream<Uint8Array> {
return new ReadableStream({
async start(controller) {
for (const chunk of chunks) {
controller.enqueue(encoder.encode(chunk))
// Wait a tick so scheduleImmediate callbacks can fire between chunks
await new Promise((r) => setTimeout(r, 0))
}
// Extra tick before close to let any pending scheduleImmediate fire
await new Promise((r) => setTimeout(r, 10))
controller.close()
},
})
}
// Default stubs
const noopInsertedHTML = () => Promise.resolve('')
const noopInsertedMetadata = () => Promise.resolve('')
// ---------------------------------------------------------------------------
// Build the two implementations under test
// ---------------------------------------------------------------------------
type TestCase = {
inputChunks: string[] | Uint8Array[]
getServerInsertedHTML?: () => Promise<string>
getServerInsertedMetadata?: () => Promise<string> | string
inlinedDataStream?: ReadableStream<Uint8Array>
suffix?: string | null
}
// Build the legacy chain of individual transforms (the "before" implementation).
// This mirrors how continueFizzStream composed transforms before the unified version.
function buildLegacyChain(opts: TestCase): {
input: ReadableStream<Uint8Array>
transforms: TransformStream<Uint8Array, Uint8Array>[]
} {
const input =
opts.inputChunks.length > 0 && opts.inputChunks[0] instanceof Uint8Array
? streamFromUint8Arrays(opts.inputChunks as Uint8Array[])
: streamFromChunks(opts.inputChunks as string[])
const transforms: TransformStream<Uint8Array, Uint8Array>[] = []
// 1. Buffered batching
transforms.push(createBufferedTransformStream())
// 2. Metadata icon mark handling
transforms.push(
createMetadataTransformStream(
opts.getServerInsertedMetadata ?? noopInsertedMetadata
)
)
// 3. Deferred suffix (if present)
if (opts.suffix) {
transforms.push(createDeferredSuffixStream(opts.suffix))
}
// 4. Flight data injection
if (opts.inlinedDataStream) {
transforms.push(
createFlightDataInjectionTransformStream(opts.inlinedDataStream, true)
)
}
// 5. Move suffix (</body></html>) to end
transforms.push(createMoveSuffixStream())
// 6. Head insertion
transforms.push(
createHeadInsertionTransformStream(
opts.getServerInsertedHTML ?? noopInsertedHTML
)
)
return { input, transforms }
}
// Build the unified transform (the "after" implementation).
function buildUnifiedTransform(opts: TestCase): {
input: ReadableStream<Uint8Array>
transforms: TransformStream<Uint8Array, Uint8Array>[]
} {
const input =
opts.inputChunks.length > 0 && opts.inputChunks[0] instanceof Uint8Array
? streamFromUint8Arrays(opts.inputChunks as Uint8Array[])
: streamFromChunks(opts.inputChunks as string[])
return {
input,
transforms: [
createUnifiedSSRTransformStream({
getServerInsertedHTML: opts.getServerInsertedHTML ?? noopInsertedHTML,
getServerInsertedMetadata:
opts.getServerInsertedMetadata ?? noopInsertedMetadata,
inlinedDataStream: opts.inlinedDataStream,
suffix: opts.suffix ?? null,
}),
],
}
}
// Run a test case against both implementations and return both results.
// Each call gets fresh streams (streams are one-shot).
async function runBoth(
makeOpts: () => TestCase
): Promise<{ legacy: string; unified: string }> {
const legacyOpts = makeOpts()
const { input: legacyInput, transforms: legacyTransforms } =
buildLegacyChain(legacyOpts)
const legacy = await pipeAndCollect(legacyInput, legacyTransforms)
const unifiedOpts = makeOpts()
const { input: unifiedInput, transforms: unifiedTransforms } =
buildUnifiedTransform(unifiedOpts)
const unified = await pipeAndCollect(unifiedInput, unifiedTransforms)
return { legacy, unified }
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
// Helper to run assertions against both implementations
function assertBoth(
results: { legacy: string; unified: string },
assertions: (result: string, label: string) => void
) {
assertions(results.legacy, 'legacy')
assertions(results.unified, 'unified')
}
describe('SSR Transform Streams', () => {
describe('basic passthrough', () => {
it('passes through a simple HTML page and adds closing tags', async () => {
const results = await runBoth(() => ({
inputChunks: [
'<html><head></head><body>',
'<h1>Hello</h1>',
'</body></html>',
],
}))
assertBoth(results, (result) => {
expect(result).toContain('<h1>Hello</h1>')
expect(result).toContain('</body></html>')
expect(result.lastIndexOf('</body></html>')).toBe(
result.length - '</body></html>'.length
)
})
})
it('handles empty stream', async () => {
const results = await runBoth(() => ({
inputChunks: [],
}))
assertBoth(results, (result) => {
// Should still emit the closing tags
expect(result).toBe('</body></html>')
})
})
})
describe('suffix stripping and reinsertion', () => {
it('moves </body></html> to the end when it appears mid-stream', async () => {
const results = await runBoth(() => ({
inputChunks: [
'<html><head></head><body><div>content</div></body></html>',
'<script>extra()</script>',
],
}))
assertBoth(results, (result) => {
expect(result).toContain('<div>content</div>')
expect(result).toContain('<script>extra()</script>')
expect(result.endsWith('</body></html>')).toBe(true)
expect(result.indexOf('<script>extra()</script>')).toBeLessThan(
result.lastIndexOf('</body></html>')
)
})
})
it('handles </body></html> as a standalone chunk', async () => {
const results = await runBoth(() => ({
inputChunks: ['<html><head></head><body><p>test</p>', '</body></html>'],
}))
assertBoth(results, (result) => {
expect(result).toContain('<p>test</p>')
expect(result.endsWith('</body></html>')).toBe(true)
})
})
})
describe('head insertion', () => {
it('inserts server HTML before </head>', async () => {
const results = await runBoth(() => {
let callCount = 0
return {
inputChunks: [
'<html><head><title>Test</title></head><body>',
'<p>content</p></body></html>',
],
getServerInsertedHTML: () => {
callCount++
if (callCount === 1) {
return Promise.resolve(
'<link rel="stylesheet" href="/style.css">'
)
}
return Promise.resolve('')
},
}
})
assertBoth(results, (result) => {
expect(result).toContain(
'<link rel="stylesheet" href="/style.css"></head>'
)
})
})
it('inserts server HTML when no </head> is found (PPR resume)', async () => {
const results = await runBoth(() => ({
inputChunks: ['<div>PPR content</div></body></html>'],
getServerInsertedHTML: () =>
Promise.resolve('<meta name="robots" content="noindex">'),
}))
assertBoth(results, (result) => {
expect(result).toContain('<meta name="robots" content="noindex">')
expect(result).toContain('<div>PPR content</div>')
})
})
})
// Suffix tests use async chunk delivery because the deferred suffix relies on
// scheduleImmediate timing. With synchronous streams, flush() runs before the
// scheduleImmediate callback, causing the suffix to be lost.
describe('deferred suffix', () => {
it('injects the suffix into the output', async () => {
const input = asyncStreamFromChunks([
'<html><head></head><body><p>content</p></body></html>',
])
const transform = createUnifiedSSRTransformStream({
getServerInsertedHTML: noopInsertedHTML,
getServerInsertedMetadata: noopInsertedMetadata,
inlinedDataStream: undefined,
suffix: '<script>deferred()</script>',
})
const result = await pipeAndCollect(input, [transform])
expect(result).toContain('<script>deferred()</script>')
expect(result.indexOf('<script>deferred()</script>')).toBeLessThan(
result.lastIndexOf('</body></html>')
)
})
})
describe('flight data injection', () => {
it('includes flight data in the output', async () => {
const results = await runBoth(() => ({
inputChunks: ['<html><head></head><body><p>page</p></body></html>'],
inlinedDataStream: streamFromChunks([
'<script>self.__next_f=[]</script>',
'<script>self.__next_f.push([1,"data"])</script>',
]),
}))
assertBoth(results, (result) => {
expect(result).toContain('self.__next_f=[]')
expect(result).toContain('self.__next_f.push([1,"data"])')
expect(result.endsWith('</body></html>')).toBe(true)
})
})
it('drains flight data in flush when HTML ends quickly', async () => {
const results = await runBoth(() => ({
inputChunks: ['<html><head></head><body><p>fast</p></body></html>'],
inlinedDataStream: new ReadableStream<Uint8Array>({
async start(controller) {
await new Promise((r) => setTimeout(r, 50))
controller.enqueue(encoder.encode('<script>late_flight()</script>'))
controller.close()
},
}),
}))
assertBoth(results, (result) => {
expect(result).toContain('<script>late_flight()</script>')
expect(result.endsWith('</body></html>')).toBe(true)
})
})
})
describe('metadata icon mark handling', () => {
function buildIconMarkChunk(before: string, after: string): Uint8Array {
const iconMark = ENCODED_TAGS.META.ICON_MARK
const closingByte = new Uint8Array([62]) // '>'
const beforeBytes = encoder.encode(before)
const afterBytes = encoder.encode(after)
const full = new Uint8Array(
beforeBytes.length +
iconMark.length +
closingByte.length +
afterBytes.length
)
full.set(beforeBytes, 0)
full.set(iconMark, beforeBytes.length)
full.set(closingByte, beforeBytes.length + iconMark.length)
full.set(
afterBytes,
beforeBytes.length + iconMark.length + closingByte.length
)
return full
}
it('removes the icon mark from the first chunk (before </head>)', async () => {
const results = await runBoth(() => ({
inputChunks: [
buildIconMarkChunk(
'<html><head><title>Test</title>',
'</head><body>content</body></html>'
),
],
}))
assertBoth(results, (result) => {
expect(result).not.toContain('\u00ABnxt-icon\u00BB')
expect(result).toContain('<title>Test</title>')
expect(result).toContain('content')
})
})
it('replaces icon mark with metadata on a later chunk', async () => {
const results = await runBoth(() => ({
inputChunks: [
encoder.encode(
'<html><head><title>Test</title></head><body>'
) as Uint8Array,
buildIconMarkChunk('<div>', '</div></body></html>'),
],
getServerInsertedMetadata: () =>
Promise.resolve('<link rel="icon" href="/favicon.ico">'),
}))
assertBoth(results, (result) => {
expect(result).not.toContain('\u00ABnxt-icon\u00BB')
expect(result).toContain('<link rel="icon" href="/favicon.ico">')
})
})
})
// Combined tests with suffix only run against the unified transform
// (see deferred suffix comment above for rationale).
describe('combined behavior', () => {
it('handles head insertion + suffix + flight data together', async () => {
let callCount = 0
const input = asyncStreamFromChunks([
'<html><head><title>App</title></head><body>',
'<main>content</main>',
'</body></html>',
])
const transform = createUnifiedSSRTransformStream({
getServerInsertedHTML: () => {
callCount++
if (callCount === 1) {
return Promise.resolve('<link rel="stylesheet" href="/app.css">')
}
return Promise.resolve('')
},
getServerInsertedMetadata: noopInsertedMetadata,
inlinedDataStream: streamFromChunks([
'<script>self.__next_f=[]</script>',
]),
suffix: '<script>bootstrap()</script>',
})
const result = await pipeAndCollect(input, [transform])
// Head insertion present
expect(result).toContain('<link rel="stylesheet" href="/app.css"></head>')
// Main content present
expect(result).toContain('<main>content</main>')
// Suffix before closing tags
const suffixIdx = result.indexOf('<script>bootstrap()</script>')
const closeIdx = result.lastIndexOf('</body></html>')
expect(suffixIdx).toBeGreaterThan(-1)
expect(suffixIdx).toBeLessThan(closeIdx)
// Flight data present
expect(result).toContain('self.__next_f=[]')
// Closing tags at the end
expect(result.endsWith('</body></html>')).toBe(true)
})
it('closing tags appear exactly once', async () => {
const input = asyncStreamFromChunks([
'<html><head></head><body><p>hi</p></body></html>',
])
const transform = createUnifiedSSRTransformStream({
getServerInsertedHTML: noopInsertedHTML,
getServerInsertedMetadata: noopInsertedMetadata,
inlinedDataStream: streamFromChunks(['<script>rsc()</script>']),
suffix: '<script>suffix()</script>',
})
const result = await pipeAndCollect(input, [transform])
expect(result).toContain('<p>hi</p>')
expect(result.endsWith('</body></html>')).toBe(true)
const firstClose = result.indexOf('</body></html>')
const lastClose = result.lastIndexOf('</body></html>')
expect(firstClose).toBe(lastClose)
})
it('head insertion + flight data (no suffix) matches legacy', async () => {
const results = await runBoth(() => {
let callCount = 0
return {
inputChunks: [
'<html><head><title>App</title></head><body>',
'<main>content</main>',
'</body></html>',
],
getServerInsertedHTML: () => {
callCount++
if (callCount === 1) {
return Promise.resolve('<link rel="stylesheet" href="/app.css">')
}
return Promise.resolve('')
},
inlinedDataStream: streamFromChunks([
'<script>self.__next_f=[]</script>',
]),
}
})
assertBoth(results, (result) => {
expect(result).toContain(
'<link rel="stylesheet" href="/app.css"></head>'
)
expect(result).toContain('<main>content</main>')
expect(result).toContain('self.__next_f=[]')
expect(result.endsWith('</body></html>')).toBe(true)
})
})
})
// Tests specific to the unified transform (error propagation fix)
describe('unified transform: error propagation', () => {
it('propagates errors from getServerInsertedHTML during flush', async () => {
// getServerInsertedHTML is called in flush() directly via
// await applyHeadInsertion() and await getServerInsertedHTML().
// Errors from these direct awaits propagate through the stream.
const input = asyncStreamFromChunks([
'<html><head></head><body><p>content</p></body></html>',
])
const transform = createUnifiedSSRTransformStream({
getServerInsertedHTML: () =>
Promise.reject(new Error('insertion failed')),
getServerInsertedMetadata: noopInsertedMetadata,
inlinedDataStream: undefined,
suffix: null,
})
await expect(async () => {
await pipeAndCollect(input, [transform])
}).rejects.toThrow('insertion failed')
})
it('propagates errors from getServerInsertedHTML during scheduleFlush', async () => {
// This specifically tests the scheduleFlush rejection handler path.
// getServerInsertedHTML fails exactly once (during a scheduleFlush
// applyHeadInsertion call), then succeeds for subsequent calls.
// If the error is swallowed in scheduleFlush, it won't propagate.
let callCount = 0
const input = asyncStreamFromChunks([
'<html><head></head><body>',
'<p>chunk1</p>',
'<p>chunk2</p></body></html>',
])
const transform = createUnifiedSSRTransformStream({
getServerInsertedHTML: () => {
callCount++
// Fail only on the second call (during scheduleFlush, after head
// is already inserted). Succeed on all other calls.
if (callCount === 2) {
return Promise.reject(new Error('scheduleFlush error'))
}
return Promise.resolve('')
},
getServerInsertedMetadata: noopInsertedMetadata,
inlinedDataStream: undefined,
suffix: null,
})
await expect(async () => {
await pipeAndCollect(input, [transform])
}).rejects.toThrow('scheduleFlush error')
})
})
})
import type { ReactDOMServerReadableStream } from 'react-dom/server'
import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import { DetachedPromise } from '../../lib/detached-promise'
import {
scheduleImmediate,
atLeastOneTask,
......@@ -170,7 +169,9 @@ export function createBufferedTransformStream(
let bufferedChunks: Array<Uint8Array> = []
let bufferByteLength: number = 0
let pending: DetachedPromise<void> | undefined
// Pending flush state: resolve function + promise, avoids DetachedPromise allocation per flush
let pendingResolve: (() => void) | undefined
let pendingPromise: Promise<void> | undefined
const flush = (controller: TransformStreamDefaultController) => {
try {
......@@ -199,19 +200,23 @@ export function createBufferedTransformStream(
}
const scheduleFlush = (controller: TransformStreamDefaultController) => {
if (pending) {
if (pendingResolve) {
return
}
const detached = new DetachedPromise<void>()
pending = detached
// Inline the promise creation to avoid DetachedPromise class overhead
pendingPromise = new Promise<void>((resolve) => {
pendingResolve = resolve
})
scheduleImmediate(() => {
try {
flush(controller)
} finally {
pending = undefined
detached.resolve()
const resolve = pendingResolve!
pendingResolve = undefined
pendingPromise = undefined
resolve()
}
})
}
......@@ -229,7 +234,7 @@ export function createBufferedTransformStream(
}
},
flush() {
return pending?.promise
return pendingPromise
},
})
}
......@@ -280,108 +285,131 @@ export function renderToInitialFizzStream({
)
}
function createMetadataTransformStream(
export function createMetadataTransformStream(
insert: () => Promise<string> | string
): TransformStream<Uint8Array, Uint8Array> {
let chunkIndex = -1
let isMarkRemoved = false
// Extracted async path to avoid making the common (no icon mark) path async.
// When `transform` is declared async, it always returns a promise even for synchronous paths,
// adding microtask overhead per chunk. By keeping transform sync and only going async when
// the icon mark is found, we avoid that overhead for the majority of chunks.
async function handleIconMark(
chunk: Uint8Array,
iconMarkIndex: number,
iconMarkLength: number,
controller: TransformStreamDefaultController
) {
// Check if icon mark is inside <head> tag in the first chunk.
if (chunkIndex === 0) {
const closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (iconMarkIndex !== -1) {
// The mark icon is located in the 1st chunk before the head tag.
// We do not need to insert the script tag in this case because it's in the head.
// Just remove the icon mark from the chunk.
if (iconMarkIndex < closedHeadIndex) {
const replaced = new Uint8Array(chunk.length - iconMarkLength)
// Remove the icon mark from the chunk.
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
} else {
// The icon mark is after the head tag, replace and insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
}
isMarkRemoved = true
}
// If there's no icon mark located, it will be handled later when if present in the following chunks.
} else {
// When it's appeared in the following chunks, we'll need to
// remove the mark and then insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
// Replace the icon mark with the hoist script or empty string.
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
// Set the first part of the chunk, before the icon mark.
replaced.set(chunk.subarray(0, iconMarkIndex))
// Set the insertion after the icon mark.
replaced.set(encodedInsertion, iconMarkIndex)
// Set the rest of the chunk after the icon mark.
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isMarkRemoved = true
}
controller.enqueue(chunk)
}
// Pre-computed: a rare byte from the icon mark pattern (0xC2 = 194, the start of « in UTF-8).
// Used as a fast pre-filter: if this byte isn't in the chunk, the full pattern can't match.
const iconMarkRareByte = ENCODED_TAGS.META.ICON_MARK[12] // 194 (0xC2)
return new TransformStream({
async transform(chunk, controller) {
let iconMarkIndex = -1
let closedHeadIndex = -1
transform(chunk, controller) {
chunkIndex++
if (isMarkRemoved) {
controller.enqueue(chunk)
return
}
let iconMarkLength = 0
// Only search for the closed head tag once
// Fast pre-filter: check for a rare byte (0xC2) before doing the full pattern search.
// Byte 194 (0xC2) is the UTF-8 lead byte for U+0080-U+00BF, which includes « but also
// other characters. False positives just trigger the full scan which correctly rejects,
// so this remains a valid fast-path optimization for most chunks.
if (chunk.indexOf(iconMarkRareByte) === -1) {
controller.enqueue(chunk)
return
}
const iconMarkIndex = indexOfUint8Array(
chunk,
ENCODED_TAGS.META.ICON_MARK
)
if (iconMarkIndex === -1) {
iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)
if (iconMarkIndex === -1) {
controller.enqueue(chunk)
return
} else {
// When we found the `<meta name="«nxt-icon»"` tag prefix, we will remove it from the chunk.
// Its close tag could either be `/>` or `>`, checking the next char to ensure we cover both cases.
iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
// Check if next char is /, this is for xml mode.
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
// The last char is `>`
iconMarkLength++
}
}
controller.enqueue(chunk)
return
}
// Check if icon mark is inside <head> tag in the first chunk.
if (chunkIndex === 0) {
closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (iconMarkIndex !== -1) {
// The mark icon is located in the 1st chunk before the head tag.
// We do not need to insert the script tag in this case because it's in the head.
// Just remove the icon mark from the chunk.
if (iconMarkIndex < closedHeadIndex) {
const replaced = new Uint8Array(chunk.length - iconMarkLength)
// Remove the icon mark from the chunk.
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
} else {
// The icon mark is after the head tag, replace and insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
}
isMarkRemoved = true
}
// If there's no icon mark located, it will be handled later when if present in the following chunks.
// Icon mark found: compute its length and delegate to async handler
let iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
// Check if next char is /, this is for xml mode.
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
// When it's appeared in the following chunks, we'll need to
// remove the mark and then insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
// Replace the icon mark with the hoist script or empty string.
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
// Set the first part of the chunk, before the icon mark.
replaced.set(chunk.subarray(0, iconMarkIndex))
// Set the insertion after the icon mark.
replaced.set(encodedInsertion, iconMarkIndex)
// Set the rest of the chunk after the icon mark.
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isMarkRemoved = true
// The last char is `>`
iconMarkLength++
}
controller.enqueue(chunk)
return handleIconMark(chunk, iconMarkIndex, iconMarkLength, controller)
},
})
}
function createHeadInsertionTransformStream(
export function createHeadInsertionTransformStream(
insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> {
let inserted = false
......@@ -518,54 +546,7 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream<
})
}
// Suffix after main body content - scripts before </body>,
// but wait for the major chunks to be enqueued.
function createDeferredSuffixStream(
suffix: string
): TransformStream<Uint8Array, Uint8Array> {
let flushed = false
let pending: DetachedPromise<void> | undefined
const flush = (controller: TransformStreamDefaultController) => {
const detached = new DetachedPromise<void>()
pending = detached
scheduleImmediate(() => {
try {
controller.enqueue(encoder.encode(suffix))
} catch {
// If an error occurs while enqueuing it can't be due to this
// transformers fault. It's likely due to the controller being
// errored due to the stream being cancelled.
} finally {
pending = undefined
detached.resolve()
}
})
}
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk)
// If we've already flushed, we're done.
if (flushed) return
// Schedule the flush to happen.
flushed = true
flush(controller)
},
flush(controller) {
if (pending) return pending.promise
if (flushed) return
// Flush now.
controller.enqueue(encoder.encode(suffix))
},
})
}
function createFlightDataInjectionTransformStream(
export function createFlightDataInjectionTransformStream(
stream: ReadableStream<Uint8Array>,
delayDataUntilFirstHtmlChunk: boolean
): TransformStream<Uint8Array, Uint8Array> {
......@@ -652,7 +633,10 @@ const CLOSE_TAG = '</body></html>'
* like `</body></html><script>...</script>` will be transformed to
* `<script>...</script></body></html>`.
*/
function createMoveSuffixStream(): TransformStream<Uint8Array, Uint8Array> {
export function createMoveSuffixStream(): TransformStream<
Uint8Array,
Uint8Array
> {
let foundSuffix = false
return new TransformStream({
......@@ -838,6 +822,417 @@ function chainTransformers<T>(
return stream
}
/**
* Unified SSR transform that merges buffered batching, metadata icon mark handling,
* flight data injection, deferred suffix, move-suffix, and head insertion into a
* single TransformStream. This eliminates ~3 extra TransformStream allocations and
* the associated microtask hops per chunk in the dynamic SSR path.
*
* Architecture: the transform method is synchronous on the hot path (metadata check,
* suffix stripping, buffering). The async head insertion runs per-batch in the
* scheduleImmediate flush cycle, not per raw chunk.
*/
export function createUnifiedSSRTransformStream({
getServerInsertedHTML,
getServerInsertedMetadata,
inlinedDataStream,
suffix,
}: {
getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string> | string
inlinedDataStream: ReadableStream<Uint8Array> | undefined
suffix: string | null
}): TransformStream<Uint8Array, Uint8Array> {
// --- buffering state ---
let bufferedChunks: Array<Uint8Array> = []
let bufferByteLength = 0
let pendingResolve: (() => void) | undefined
let pendingPromise: Promise<void> | undefined
// --- metadata (icon mark) state ---
let metadataChunkIndex = -1
let isIconMarkRemoved = false
const iconMarkRareByte = ENCODED_TAGS.META.ICON_MARK[12] // 194 (0xC2)
// --- move suffix (</body></html>) state ---
let foundSuffix = false
// --- head insertion state ---
let headInserted = false
let hasBytes = false
// --- deferred suffix state ---
let suffixFlushed = false
// --- flight data injection state ---
let flightPull: Promise<void> | null = null
let flightDonePulling = false
// --- first chunk tracking ---
let firstChunkSeen = false
function startOrContinuePullingFlightData(
controller: TransformStreamDefaultController
) {
if (!flightPull) {
flightPull = startPullingFlightData(controller)
}
return flightPull
}
async function startPullingFlightData(
controller: TransformStreamDefaultController
) {
if (!inlinedDataStream) {
flightDonePulling = true
return
}
const reader = inlinedDataStream.getReader()
// Wait for the shell to flush before reading flight data
await atLeastOneTask()
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
flightDonePulling = true
return
}
controller.enqueue(value)
}
} catch (err) {
controller.error(err)
}
}
// Apply head insertion to a chunk. Returns the (possibly modified) chunk synchronously
// if no insertion is needed, or a Promise if insertion is needed.
function applyHeadInsertion(
chunk: Uint8Array,
controller: TransformStreamDefaultController
): void | Promise<void> {
if (headInserted) {
// After head is inserted, we need to check for new server HTML to prepend.
// This is async but only allocates a promise when there's actual content.
const insertionResult = getServerInsertedHTML()
// Optimistic fast path: if it's a resolved promise with empty string
// we can't avoid the promise, so always go async here
return (insertionResult as Promise<string>).then((insertion) => {
if (insertion) {
controller.enqueue(encoder.encode(insertion))
}
controller.enqueue(chunk)
})
}
// First time: look for </head> in the chunk
const headIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (headIndex !== -1) {
headInserted = true
return (getServerInsertedHTML() as Promise<string>).then((insertion) => {
if (insertion) {
const encodedInsertion = encoder.encode(insertion)
const insertedHeadContent = new Uint8Array(
chunk.length + encodedInsertion.length
)
insertedHeadContent.set(chunk.slice(0, headIndex))
insertedHeadContent.set(encodedInsertion, headIndex)
insertedHeadContent.set(
chunk.slice(headIndex),
headIndex + encodedInsertion.length
)
controller.enqueue(insertedHeadContent)
} else {
controller.enqueue(chunk)
}
})
}
// No </head> found: PPR resume case
headInserted = true
return (getServerInsertedHTML() as Promise<string>).then((insertion) => {
if (insertion) {
controller.enqueue(encoder.encode(insertion))
}
controller.enqueue(chunk)
})
}
function scheduleFlush(controller: TransformStreamDefaultController) {
if (pendingResolve) return
pendingPromise = new Promise<void>((resolve) => {
pendingResolve = resolve
})
scheduleImmediate(() => {
// Synchronously consolidate the buffer
if (bufferedChunks.length === 0) {
const r = pendingResolve!
pendingResolve = undefined
pendingPromise = undefined
r()
return
}
let chunk: Uint8Array
if (bufferedChunks.length === 1) {
chunk = bufferedChunks[0]
} else {
chunk = new Uint8Array(bufferByteLength)
let copiedBytes = 0
for (let i = 0; i < bufferedChunks.length; i++) {
const bufferedChunk = bufferedChunks[i]
chunk.set(bufferedChunk, copiedBytes)
copiedBytes += bufferedChunk.byteLength
}
}
bufferedChunks.length = 0
bufferByteLength = 0
// Apply head insertion (async) then resolve
const result = applyHeadInsertion(chunk, controller)
if (result) {
result.then(
() => {
const r = pendingResolve!
pendingResolve = undefined
pendingPromise = undefined
r()
},
(err) => {
const r = pendingResolve!
pendingResolve = undefined
pendingPromise = undefined
r()
controller.error(err)
}
)
} else {
const r = pendingResolve!
pendingResolve = undefined
pendingPromise = undefined
r()
}
})
}
function bufferChunk(
chunk: Uint8Array,
controller: TransformStreamDefaultController
) {
bufferedChunks.push(chunk)
bufferByteLength += chunk.byteLength
scheduleFlush(controller)
}
// Synchronous: strip </body></html> suffix and buffer the chunk.
function applySuffixStrippingAndBuffer(
chunk: Uint8Array,
controller: TransformStreamDefaultController
) {
hasBytes = true
if (foundSuffix) {
bufferChunk(chunk, controller)
return
}
const suffixIndex = indexOfUint8Array(
chunk,
ENCODED_TAGS.CLOSED.BODY_AND_HTML
)
if (suffixIndex > -1) {
foundSuffix = true
if (chunk.length === ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) {
// Entire chunk is the suffix, skip (will be added in flush)
return
}
const before = chunk.slice(0, suffixIndex)
if (before.length > 0) {
bufferChunk(before, controller)
}
if (
chunk.length >
ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + suffixIndex
) {
const after = chunk.slice(
suffixIndex + ENCODED_TAGS.CLOSED.BODY_AND_HTML.length
)
bufferChunk(after, controller)
}
} else {
bufferChunk(chunk, controller)
}
}
// Async path for handling icon mark (rare). After processing, continues to sync path.
async function handleIconMark(
chunk: Uint8Array,
iconMarkIndex: number,
iconMarkLength: number,
controller: TransformStreamDefaultController
) {
if (metadataChunkIndex === 0) {
const closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (iconMarkIndex !== -1) {
if (iconMarkIndex < closedHeadIndex) {
const replaced = new Uint8Array(chunk.length - iconMarkLength)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
} else {
const insertion = await getServerInsertedMetadata()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
}
isIconMarkRemoved = true
}
} else {
const insertion = await getServerInsertedMetadata()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isIconMarkRemoved = true
}
// Continue to sync path
processChunkPostMetadata(chunk, controller)
}
// After metadata processing: suffix stripping + buffer + first-chunk actions.
// This is the sync hot path for most chunks.
function processChunkPostMetadata(
chunk: Uint8Array,
controller: TransformStreamDefaultController
) {
applySuffixStrippingAndBuffer(chunk, controller)
if (!firstChunkSeen) {
firstChunkSeen = true
// Start pulling flight data after the first HTML chunk (fire-and-forget)
if (inlinedDataStream) {
startOrContinuePullingFlightData(controller)
}
// Insert deferred suffix in next tick (matching createDeferredSuffixStream behavior)
if (suffix) {
suffixFlushed = true
scheduleImmediate(() => {
applySuffixStrippingAndBuffer(encoder.encode(suffix), controller)
})
}
}
}
return new TransformStream({
transform(chunk, controller) {
metadataChunkIndex++
// --- Phase 1: Metadata icon mark handling (rare async path) ---
if (!isIconMarkRemoved) {
// Fast pre-filter: check for rare byte before full scan
if (chunk.indexOf(iconMarkRareByte) !== -1) {
const iconMarkIndex = indexOfUint8Array(
chunk,
ENCODED_TAGS.META.ICON_MARK
)
if (iconMarkIndex !== -1) {
let iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
iconMarkLength++
}
return handleIconMark(
chunk,
iconMarkIndex,
iconMarkLength,
controller
)
}
}
}
// --- Phase 2: Sync hot path: suffix stripping + buffering ---
processChunkPostMetadata(chunk, controller)
},
async flush(controller) {
// Wait for any pending scheduled flush to complete
if (pendingPromise) {
await pendingPromise
}
// Flush any remaining buffered chunks with head insertion
if (bufferedChunks.length > 0) {
let chunk: Uint8Array
if (bufferedChunks.length === 1) {
chunk = bufferedChunks[0]
} else {
chunk = new Uint8Array(bufferByteLength)
let copiedBytes = 0
for (let i = 0; i < bufferedChunks.length; i++) {
const bufferedChunk = bufferedChunks[i]
chunk.set(bufferedChunk, copiedBytes)
copiedBytes += bufferedChunk.byteLength
}
}
bufferedChunks.length = 0
bufferByteLength = 0
await applyHeadInsertion(chunk, controller)
}
// Final head insertion: emit any remaining accumulated server-inserted HTML
if (hasBytes) {
const insertion = await getServerInsertedHTML()
if (insertion) {
controller.enqueue(encoder.encode(insertion))
}
}
// If deferred suffix was never flushed, insert it now
if (!suffixFlushed && suffix) {
controller.enqueue(encoder.encode(suffix))
}
// Drain remaining flight data
if (inlinedDataStream && !flightDonePulling) {
await startOrContinuePullingFlightData(controller)
}
// Move suffix flush: always add closing tags at the end
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
},
})
}
export type ContinueStreamOptions = {
inlinedDataStream: ReadableStream<Uint8Array> | undefined
isStaticGeneration: boolean
......@@ -876,35 +1271,24 @@ export async function continueFizzStream(
}
return chainTransformers(renderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert suffix content
suffixUnclosed != null && suffixUnclosed.length > 0
? createDeferredSuffixStream(suffixUnclosed)
: null,
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
inlinedDataStream
? createFlightDataInjectionTransformStream(inlinedDataStream, true)
: null,
// Validate the root layout for missing html or body tags
validateRootLayout ? createRootLayoutValidatorStream() : null,
// Close tags should always be deferred to the end
createMoveSuffixStream(),
// Special head insertions
// TODO-APP: Insert server side html to end of head in app layout rendering, to avoid
// hydration errors. Remove this once it's ready to be handled by react itself.
createHeadInsertionTransformStream(getServerInsertedHTML),
// Unified SSR transform: merges buffering, metadata icon marks, deferred suffix,
// flight data injection, suffix movement, and head insertion into a single
// TransformStream, eliminating ~3 extra stream allocations and microtask hops.
createUnifiedSSRTransformStream({
getServerInsertedHTML,
getServerInsertedMetadata,
inlinedDataStream,
suffix:
suffixUnclosed != null && suffixUnclosed.length > 0
? suffixUnclosed
: null,
}),
])
}
......
/**
* Find the starting index of Uint8Array `b` within Uint8Array `a`.
* Uses first-byte indexOf to skip non-matching positions quickly,
* then verifies the full pattern match.
*/
export function indexOfUint8Array(a: Uint8Array, b: Uint8Array) {
if (b.length === 0) return 0
if (a.length === 0 || b.length > a.length) return -1
// start iterating through `a`
for (let i = 0; i <= a.length - b.length; i++) {
let completeMatch = true
// from index `i`, iterate through `b` and check for mismatch
for (let j = 0; j < b.length; j++) {
// if the values do not match, then this isn't a complete match, exit `b` iteration early and iterate to next index of `a`.
if (a[i + j] !== b[j]) {
completeMatch = false
const firstByte = b[0]
const bLen = b.length
const limit = a.length - bLen
let i = 0
while (i <= limit) {
// Use native indexOf to jump to next candidate position.
// TypedArray.indexOf is V8-optimized and much faster than a JS byte-by-byte scan.
const idx = a.indexOf(firstByte, i)
if (idx === -1 || idx > limit) return -1
// Verify the full pattern at this position
let match = true
for (let j = 1; j < bLen; j++) {
if (a[idx + j] !== b[j]) {
match = false
break
}
}
if (completeMatch) {
return i
}
if (match) return idx
i = idx + 1
}
return -1
......
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