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

Fix an issue where ReadableStream wasn't canceled in dev mode #9971

Merged
merged 3 commits into from
Feb 13, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thin-kangaroos-exist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Fixes an issue where ReadableStream wasn't canceled in dev mode
6 changes: 6 additions & 0 deletions packages/astro/src/vite-plugin-astro-server/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ export async function writeWebResponse(res: http.ServerResponse, webResponse: Re
res.write(body);
} else {
const reader = body.getReader();
res.on('close', () => {
reader.cancel().catch((error: unknown) => {
// eslint-disable-next-line no-console
console.error('An unexpected error occurred in the middle of the stream.', error);
});
});
while (true) {
const { done, value } = await reader.read();
if (done) break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,28 @@ const fileSystem = {
headers.append('Set-Cookie', 'world');
return new Response(null, { headers });
}`,
'/src/pages/streaming.js': `export const GET = ({ locals }) => {
let sentChunks = 0;

const readableStream = new ReadableStream({
async pull(controller) {
if (sentChunks === 3) return controller.close();
else sentChunks++;

await new Promise(resolve => setTimeout(resolve, 1000));
controller.enqueue(new TextEncoder().encode('hello'));
},
cancel() {
locals.cancelledByTheServer = true;
}
});

return new Response(readableStream, {
headers: {
"Content-Type": "text/event-stream"
}
})
}`,
};

describe('endpoints', () => {
Expand Down Expand Up @@ -60,4 +82,23 @@ describe('endpoints', () => {
'set-cookie': ['hello', 'world'],
});
});

it('Headers with multisple values (set-cookie special case)', async () => {
const { req, res, done } = createRequestAndResponse({
method: 'GET',
url: '/streaming',
});

const locals = { cancelledByTheServer: false }
req[Symbol.for("astro.locals")] = locals

container.handle(req, res);

await new Promise(resolve => setTimeout(resolve, 500));
res.emit('close');

await done;

expect(locals).to.deep.equal({ cancelledByTheServer: true });
});
});
Loading