Skip to content

Commit

Permalink
Fix an issue where ReadableStream wasn't canceled in dev mode (#9971)
Browse files Browse the repository at this point in the history
* Fix an issue where ReadableStream wasn't canceled in dev mode

* Add changeset

* add test

---------

Co-authored-by: lilnasy <[email protected]>
  • Loading branch information
mingjunlu and lilnasy authored Feb 13, 2024
1 parent bedb3b0 commit d9266c4
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
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 });
});
});

0 comments on commit d9266c4

Please sign in to comment.