fix(jsx): Fix "Invalid state: Controller is already closed" (#4770)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add failing test cases for Invalid state: Controller is already closed * Fix the crashes * refactored Co-authored-by: Taku Amano <taku@taaas.jp> ---------
authored by dan · committed by GitHub · parent 8c4d7f3 · Browse files · 2 files·+117 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
2 files+117 added−3 removed
- tests:+104 added−0 removed
- other:+13 added−3 removed
Provenance
- Commit
b8cff18- Tree
b59011c- Author
dan <dan.abramov@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8c4d7f3
2 files changed+117 added−3 removed
modified:src/jsx/streaming.test.tsx+104 added
879 unmodified lines880 '<h1>Hello from use()</h1>'881 )882 })883 })884+885+ it('should not throw ERR_INVALID_STATE when reader is cancelled during nested Suspense streaming', async () => {886+ const unhandled: unknown[] = []887+ const onRejection = (e: unknown) => unhandled.push(e)888+ process.on('unhandledRejection', onRejection)889+890+ const SubContent = async () => <h2>World</h2>891+ const Content = async () => (892+ <>893+ <h1>Hello</h1>894+ <Suspense fallback={<p>Loading sub...</p>}>895+ <SubContent />896+ </Suspense>897+ </>898+ )899+900+ const onError = vi.fn()901+ const stream = renderToReadableStream(902+ <Suspense fallback={<p>Loading...</p>}>903+ <Content />904+ </Suspense>,905+ onError906+ )907+908+ const reader = stream.getReader()909+ const firstChunk = await reader.read()910+ expect(firstChunk.done).toBe(false)911+912+ // Simulate client disconnect913+ await reader.cancel()914+915+ // Wait for nested Suspense callbacks to fire against the closed controller916+ await new Promise((resolve) => setTimeout(resolve))917+918+ expect(unhandled).toHaveLength(0)919+ expect(onError).not.toHaveBeenCalled()920+921+ process.off('unhandledRejection', onRejection)922+ })923+924+ it('should not call onError when reader is cancelled during a slow callback resolution', async () => {925+ const unhandled: unknown[] = []926+ const onRejection = (e: unknown) => unhandled.push(e)927+ process.on('unhandledRejection', onRejection)928+929+ let signalCallbackStarted!: () => void930+ const callbackStarted = new Promise<void>((r) => {931+ signalCallbackStarted = r932+ })933+934+ const Content = async () =>935+ raw('<p>content</p>', [936+ ((opts: any) => {937+ if (opts.phase === HtmlEscapedCallbackPhase.BeforeStream) {938+ signalCallbackStarted()939+ return new Promise<string>((r) => setTimeout(() => r('')))940+ }941+ return undefined942+ }) as any,943+ ])944+945+ const onError = vi.fn()946+ const stream = renderToReadableStream(947+ <Suspense fallback={<p>Loading...</p>}>948+ <Content />949+ </Suspense>,950+ onError951+ )952+953+ const reader = stream.getReader()954+ await reader.read()955+956+ await callbackStarted957+ await reader.cancel()958+959+ await new Promise((resolve) => setTimeout(resolve))960+961+ expect(unhandled).toHaveLength(0)962+ expect(onError).not.toHaveBeenCalled()963+964+ process.off('unhandledRejection', onRejection)965+ })966+967+ it('should not throw when cancelled before initial content resolves', async () => {968+ const unhandled: unknown[] = []969+ const onRejection = (e: unknown) => unhandled.push(e)970+ process.on('unhandledRejection', onRejection)971+972+ const onError = vi.fn()973+ const stream = renderToReadableStream(974+ Promise.resolve(raw('<p>slow content</p>') as HtmlEscapedString),975+ onError976+ )977+978+ const reader = stream.getReader()979+ await reader.cancel()980+981+ await new Promise((resolve) => setTimeout(resolve))982+983+ expect(unhandled).toHaveLength(0)984+ expect(onError).not.toHaveBeenCalled()985+986+ process.off('unhandledRejection', onRejection)987+ })988 })modified:src/jsx/streaming.ts+13 added-3 removed
141 unmodified lines142 export const renderToReadableStream = (143 content: HtmlEscapedString | JSXNode | Promise<HtmlEscapedString>,144 onError: (e: unknown) => string | void = console.trace145 ): ReadableStream<Uint8Array> => {146+ let cancelled = false147 const reader = new ReadableStream<Uint8Array>({148 async start(controller) {149 try {150 if (content instanceof JSXNode) {6 unmodified lines157 HtmlEscapedCallbackPhase.BeforeStream,158 true,159 context160 )161+ if (!cancelled) {160- controller.enqueue(textEncoder.encode(resolved))162+ controller.enqueue(textEncoder.encode(resolved))163+ }164 165 let resolvedCount = 0166 const callbacks: Promise<void>[] = []167 const then = (promise: Promise<string>) => {16 unmodified lines184 // eslint-disable-next-line @typescript-eslint/no-explicit-any185 .filter<Promise<string>>(Boolean as any)186 .forEach(then)187 resolvedCount++188+ if (!cancelled) {185- controller.enqueue(textEncoder.encode(res))189+ controller.enqueue(textEncoder.encode(res))190+ }191 })192 )193 }194 ;(resolved as HtmlEscapedString).callbacks8 unmodified lines203 // maybe the connection was closed204 onError(e)205 }206 207+ if (!cancelled) {202- controller.close()208+ controller.close()209+ }210 },211+ cancel() {212+ cancelled = true213+ },214 })215 return reader216 }