Fix streaming Astro components (#7895)

This commit is contained in:
Bjorn Lu 2023-08-01 21:30:47 +08:00 committed by GitHub
parent ebf7ebbf7a
commit 0b8375fe82
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 12 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fix streaming Astro components

View file

@ -413,28 +413,35 @@ async function renderHTMLComponent(
}; };
} }
async function renderAstroComponent( function renderAstroComponent(
result: SSRResult, result: SSRResult,
displayName: string, displayName: string,
Component: AstroComponentFactory, Component: AstroComponentFactory,
props: Record<string | number, any>, props: Record<string | number, any>,
slots: any = {} slots: any = {}
): Promise<RenderInstance> { ): RenderInstance {
const instance = createAstroComponentInstance(result, displayName, Component, props, slots); const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
// Eagerly render the component so they are rendered in parallel // Eagerly render the component so they are rendered in parallel.
const chunks: RenderDestinationChunk[] = []; // Render to buffer for now until our returned render function is called.
const temporaryDestination: RenderDestination = { const bufferChunks: RenderDestinationChunk[] = [];
write: (chunk) => chunks.push(chunk), const bufferDestination: RenderDestination = {
write: (chunk) => bufferChunks.push(chunk),
}; };
await instance.render(temporaryDestination); // Don't await for the render to finish to not block streaming
const renderPromise = instance.render(bufferDestination);
return { return {
render(destination) { async render(destination) {
// The real render function will simply pass on the results from the temporary destination // Write the buffered chunks to the real destination
for (const chunk of chunks) { for (const chunk of bufferChunks) {
destination.write(chunk); destination.write(chunk);
} }
// Free memory
bufferChunks.length = 0;
// Re-assign the real destination so `instance.render` will continue and write to the new destination
bufferDestination.write = (chunk) => destination.write(chunk);
await renderPromise;
}, },
}; };
} }
@ -460,7 +467,7 @@ export async function renderComponent(
} }
if (isAstroComponentFactory(Component)) { if (isAstroComponentFactory(Component)) {
return await renderAstroComponent(result, displayName, Component, props, slots); return renderAstroComponent(result, displayName, Component, props, slots);
} }
return await renderFrameworkComponent(result, displayName, Component, props, slots); return await renderFrameworkComponent(result, displayName, Component, props, slots);

View file

@ -48,7 +48,7 @@ describe('Streaming', () => {
let chunk = decoder.decode(bytes); let chunk = decoder.decode(bytes);
chunks.push(chunk); chunks.push(chunk);
} }
expect(chunks.length).to.equal(2); expect(chunks.length).to.equal(3);
}); });
}); });