From d4d79b2d9b9c43ed1061a3d3beeb3099368669a8 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Thu, 17 Feb 2022 16:05:15 +0100 Subject: [PATCH] Fix chunk buffering for server components (#34474) --- packages/next/server/render.tsx | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/packages/next/server/render.tsx b/packages/next/server/render.tsx index 87b45ab0b44af..4c00eb0b92fca 100644 --- a/packages/next/server/render.tsx +++ b/packages/next/server/render.tsx @@ -1764,19 +1764,28 @@ function createInlineDataStream( if (!dataStreamFinished && dataStream) { const dataStreamReader = dataStream.getReader() - dataStreamFinished = (async () => { - try { - while (true) { - const { done, value } = await dataStreamReader.read() - if (done) { - return + + // We are buffering here for the inlined data stream because the + // "shell" stream might be chunkenized again by the underlying stream + // implementation, e.g. with a specific high-water mark. To ensure it's + // the safe timing to pipe the data stream, this extra tick is + // necessary. + dataStreamFinished = new Promise((res) => + setTimeout(async () => { + try { + while (true) { + const { done, value } = await dataStreamReader.read() + if (done) { + return res() + } + controller.enqueue(value) } - controller.enqueue(value) + } catch (err) { + controller.error(err) } - } catch (err) { - controller.error(err) - } - })() + res() + }, 0) + ) } }, flush() {