Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify RenderResult #28900

Merged
merged 2 commits into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
}

if (renderMode) return { html: result, renderOpts }
return result ? await result.toUnchunkedString() : null
return result ? result.toUnchunkedString() : null
} catch (err) {
if (!parsedUrl!) {
parsedUrl = parseUrl(req.url!, true)
Expand Down
4 changes: 2 additions & 2 deletions packages/next/export/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ export default async function exportPage({
}
}

const html = renderResult ? await renderResult.toUnchunkedString() : ''
const html = renderResult ? renderResult.toUnchunkedString() : ''
if (inAmpMode && !curRenderOpts.ampSkipValidation) {
if (!results.ssgNotFound) {
await validateAmp(html, path, curRenderOpts.ampValidatorPath)
Expand Down Expand Up @@ -460,7 +460,7 @@ export default async function exportPage({
}

const ampHtml = ampRenderResult
? await ampRenderResult.toUnchunkedString()
? ampRenderResult.toUnchunkedString()
: ''
if (!curRenderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1')
Expand Down
41 changes: 23 additions & 18 deletions packages/next/server/render-result.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,45 @@
import { ServerResponse } from 'http'
import Observable from 'next/dist/compiled/zen-observable'

export default class RenderResult {
_response: string | Observable<string>
_dynamic: boolean

constructor(response: string | Observable<string>, dynamic: boolean) {
constructor(response: string | Observable<string>) {
this._response = response
this._dynamic = dynamic
}

async toUnchunkedString(): Promise<string> {
if (typeof this._response === 'string') {
return this._response
toUnchunkedString(): string {
if (typeof this._response !== 'string') {
throw new Error(
'invariant: dynamic responses cannot be unchunked. This is a bug in Next.js'
)
}
const chunks: string[] = []
await this._response.forEach((chunk) => chunks.push(chunk))
return chunks.join('')
return this._response
}

forEach(fn: (chunk: string) => void): Promise<void> {
async pipe(res: ServerResponse): Promise<void> {
if (typeof this._response === 'string') {
const value = this._response
return new Promise((resolve) => {
fn(value)
resolve()
})
throw new Error(
'invariant: static responses cannot be piped. This is a bug in Next.js'
)
}
return this._response.forEach(fn)
const maybeFlush =
typeof (res as any).flush === 'function'
? () => (res as any).flush()
: () => {}
await this._response.forEach((chunk) => {
res.write(chunk)
maybeFlush()
})
res.end()
}

isDynamic(): boolean {
return this._dynamic
return typeof this._response !== 'string'
}

static fromStatic(value: string): RenderResult {
return new RenderResult(value, false)
return new RenderResult(value)
}

static empty = RenderResult.fromStatic('')
Expand Down
55 changes: 4 additions & 51 deletions packages/next/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ export async function renderToHTML(
doResolve()
},
})
}).then(multiplexObservable)
})

const renderDocument = async () => {
if (Document.getInitialProps) {
Expand Down Expand Up @@ -1214,8 +1214,9 @@ export async function renderToHTML(
}

return new RenderResult(
resultsToObservable(results),
generateStaticHTML === false
generateStaticHTML
? (await observableToChunks(resultsToObservable(results))).join('')
: resultsToObservable(results)
)
}

Expand Down Expand Up @@ -1252,54 +1253,6 @@ async function observableToChunks(
return chunks
}

function multiplexObservable(result: Observable<string>): Observable<string> {
const chunks: Array<string> = []
const subscribers: Set<ZenObservable.SubscriptionObserver<string>> = new Set()
let terminator:
| ((subscriber: ZenObservable.SubscriptionObserver<string>) => void)
| null = null

result.subscribe({
next(chunk) {
chunks.push(chunk)
subscribers.forEach((subscriber) => subscriber.next(chunk))
},
error(error) {
if (!terminator) {
terminator = (subscriber) => subscriber.error(error)
subscribers.forEach(terminator)
subscribers.clear()
}
},
complete() {
if (!terminator) {
terminator = (subscriber) => subscriber.complete()
subscribers.forEach(terminator)
subscribers.clear()
}
},
})

return new Observable((observer) => {
for (const chunk of chunks) {
if (observer.closed) {
return
}
observer.next(chunk)
}

if (terminator) {
terminator(observer)
return
}

subscribers.add(observer)
return () => {
subscribers.delete(observer)
}
})
}

function errorToJSON(err: Error): Error {
const { name, message, stack } = err
return { name, message, stack }
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/response-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export default class ResponseCache {
cacheEntry.value?.kind === 'PAGE'
? {
kind: 'PAGE',
html: await cacheEntry.value.html.toUnchunkedString(),
html: cacheEntry.value.html.toUnchunkedString(),
pageData: cacheEntry.value.pageData,
}
: cacheEntry.value,
Expand Down
10 changes: 1 addition & 9 deletions packages/next/server/send-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,7 @@ export async function sendRenderResult({
} else if (payload) {
res.end(payload)
} else {
const maybeFlush =
typeof (res as any).flush === 'function'
? () => (res as any).flush()
: () => {}
await result.forEach((chunk) => {
res.write(chunk)
maybeFlush()
})
res.end()
await result.pipe(res)
}
}

Expand Down