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

Use ReadableStream in RenderResult #34005

Merged
merged 4 commits into from Feb 5, 2022
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
6 changes: 0 additions & 6 deletions packages/next/server/node-polyfill-readable-stream.js

This file was deleted.

7 changes: 7 additions & 0 deletions packages/next/server/node-polyfill-web-streams.js
@@ -0,0 +1,7 @@
import { ReadableStream, TransformStream } from './web/sandbox/readable-stream'

// Polyfill Web Streams in the Node.js environment
if (!global.ReadableStream) {
global.ReadableStream = ReadableStream
global.TransformStream = TransformStream
}
50 changes: 22 additions & 28 deletions packages/next/server/render-result.ts
@@ -1,14 +1,9 @@
import type { ServerResponse } from 'http'

export type ResultPiper = (
push: (chunks: Uint8Array[]) => void,
next: (err?: Error) => void
) => void

export default class RenderResult {
_result: string | ResultPiper
_result: string | ReadableStream

constructor(response: string | ResultPiper) {
constructor(response: string | ReadableStream) {
this._result = response
}

Expand All @@ -33,31 +28,30 @@ export default class RenderResult {
? () => (res as any).flush()
: () => {}

return new Promise((resolve, reject) => {
return (async () => {
const reader = response.getReader()
let fatalError = false
response(
(chunks) => {
// The state of the stream is non-deterministic after
// writing, so any error becomes fatal.
fatalError = true
res.cork()
chunks.forEach((chunk) => res.write(chunk))
res.uncork()
flush()
},
(err) => {
if (err) {
if (fatalError) {
res.destroy(err)
}
reject(err)
} else {

try {
while (true) {
const { done, value } = await reader.read()

if (done) {
res.end()
resolve()
return
}

fatalError = true
res.write(value)
flush()
}
)
})
} catch (err) {
if (fatalError) {
res.destroy(err as any)
}
throw err
}
})()
}

isDynamic(): boolean {
Expand Down