Skip to content

Commit cd31bc1

Browse files
fix(utils/stream): re-acquire writer lock when pipe() throws (#4988)
1 parent 569b419 commit cd31bc1

2 files changed

Lines changed: 43 additions & 2 deletions

File tree

‎src/utils/stream.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,44 @@ describe('StreamingApi', () => {
5757
expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))
5858
})
5959

60+
it('pipe() re-acquires writer lock when pipeTo() throws', async () => {
61+
const { readable, writable } = new TransformStream()
62+
const api = new StreamingApi(writable, readable)
63+
const reader = api.responseReadable.getReader()
64+
65+
const erroringReadable = new ReadableStream({
66+
start(controller) {
67+
controller.error(new Error('upstream error'))
68+
},
69+
})
70+
71+
await expect(api.pipe(erroringReadable)).rejects.toThrow('upstream error')
72+
api.write('after pipe')
73+
expect((await reader.read()).value).toEqual(new TextEncoder().encode('after pipe'))
74+
})
75+
76+
it('pipe() can be called again after a previous pipe() throws', async () => {
77+
const { readable, writable } = new TransformStream()
78+
const api = new StreamingApi(writable, readable)
79+
const reader = api.responseReadable.getReader()
80+
81+
const erroringReadable = new ReadableStream({
82+
start(controller) {
83+
controller.error(new Error('upstream error'))
84+
},
85+
})
86+
await expect(api.pipe(erroringReadable)).rejects.toThrow('upstream error')
87+
88+
const src = new ReadableStream({
89+
start(controller) {
90+
controller.enqueue(new TextEncoder().encode('second pipe'))
91+
controller.close()
92+
},
93+
})
94+
await api.pipe(src)
95+
expect((await reader.read()).value).toEqual(new TextEncoder().encode('second pipe'))
96+
})
97+
6098
it('close()', async () => {
6199
const { readable, writable } = new TransformStream()
62100
const api = new StreamingApi(writable, readable)

‎src/utils/stream.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,11 @@ export class StreamingApi {
7777

7878
async pipe(body: ReadableStream) {
7979
this.writer.releaseLock()
80-
await body.pipeTo(this.writable, { preventClose: true })
81-
this.writer = this.writable.getWriter()
80+
try {
81+
await body.pipeTo(this.writable, { preventClose: true, preventAbort: true })
82+
} finally {
83+
this.writer = this.writable.getWriter()
84+
}
8285
}
8386

8487
onAbort(listener: () => void | Promise<void>) {

0 commit comments

Comments
 (0)