|
1 | 1 | import { nextTestSetup } from 'e2e-utils' |
2 | | -import { sleep } from './sleep' |
3 | | -import { get } from 'http' |
4 | 2 |
|
5 | 3 | describe('streaming responses cancel inner stream after disconnect', () => { |
6 | 4 | const { next } = nextTestSetup({ |
7 | 5 | files: __dirname, |
8 | 6 | }) |
9 | 7 |
|
10 | | - function prime(url: string, noData?: boolean) { |
11 | | - return new Promise<void>((resolve, reject) => { |
12 | | - url = new URL(url, next.url).href |
| 8 | + async function prime(url: string, noData?: boolean) { |
| 9 | + url = new URL(url, next.url).href |
13 | 10 |
|
14 | | - // There's a bug in node-fetch v2 where aborting the fetch will never abort |
15 | | - // the connection, because the body is a transformed stream that doesn't |
16 | | - // close the connection stream. |
17 | | - // https://github.com/node-fetch/node-fetch/pull/670 |
18 | | - const req = get(url, async (res) => { |
19 | | - while (true) { |
20 | | - const value = res.read(1) |
21 | | - if (value) break |
22 | | - await sleep(5) |
23 | | - } |
| 11 | + const controller = new AbortController() |
24 | 12 |
|
25 | | - res.destroy() |
26 | | - resolve() |
27 | | - }) |
28 | | - req.on('error', reject) |
29 | | - req.end() |
| 13 | + if (noData) { |
| 14 | + const promise = fetch(url, { signal: controller.signal }) |
| 15 | + setTimeout(() => { |
| 16 | + controller.abort() |
| 17 | + }, 100) |
30 | 18 |
|
31 | | - if (noData) { |
32 | | - req.on('error', (e) => { |
33 | | - // Swallow the "socket hang up" message that happens if you abort |
34 | | - // before the a response connection is received. |
35 | | - if ((e as any).code !== 'ECONNRESET') { |
36 | | - throw e |
37 | | - } |
38 | | - }) |
| 19 | + // Swallow the AbortError that happens if you abort before the |
| 20 | + // response connection is received. |
| 21 | + await promise.catch((err) => { |
| 22 | + if (err.name !== 'AbortError') { |
| 23 | + throw err |
| 24 | + } |
| 25 | + }) |
| 26 | + return |
| 27 | + } |
39 | 28 |
|
40 | | - setTimeout(() => { |
41 | | - req.abort() |
42 | | - resolve() |
43 | | - }, 100) |
44 | | - } |
45 | | - }) |
| 29 | + const res = await fetch(url, { signal: controller.signal }) |
| 30 | + const reader = res.body!.getReader() |
| 31 | + // Wait for the first byte of the response body, then abort the |
| 32 | + // connection abruptly so the server observes a client disconnect. |
| 33 | + await reader.read() |
| 34 | + controller.abort() |
46 | 35 | } |
47 | 36 |
|
48 | 37 | describe.each([ |
|
0 commit comments