Skip to content
Myr

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

2 files+117 added−3 removed

modified:src/jsx/streaming.test.tsx+104 added
879 unmodified lines
880 '<h1>Hello from use()</h1>'881 )882 })883 })884885 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)889890 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 )899900 const onError = vi.fn()901 const stream = renderToReadableStream(902 <Suspense fallback={<p>Loading...</p>}>903 <Content />904 </Suspense>,905 onError906 )907908 const reader = stream.getReader()909 const firstChunk = await reader.read()910 expect(firstChunk.done).toBe(false)911912 // Simulate client disconnect913 await reader.cancel()914915 // Wait for nested Suspense callbacks to fire against the closed controller916 await new Promise((resolve) => setTimeout(resolve))917918 expect(unhandled).toHaveLength(0)919 expect(onError).not.toHaveBeenCalled()920921 process.off('unhandledRejection', onRejection)922 })923924 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)928929 let signalCallbackStarted!: () => void930 const callbackStarted = new Promise<void>((r) => {931 signalCallbackStarted = r932 })933934 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 ])944945 const onError = vi.fn()946 const stream = renderToReadableStream(947 <Suspense fallback={<p>Loading...</p>}>948 <Content />949 </Suspense>,950 onError951 )952953 const reader = stream.getReader()954 await reader.read()955956 await callbackStarted957 await reader.cancel()958959 await new Promise((resolve) => setTimeout(resolve))960961 expect(unhandled).toHaveLength(0)962 expect(onError).not.toHaveBeenCalled()963964 process.off('unhandledRejection', onRejection)965 })966967 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)971972 const onError = vi.fn()973 const stream = renderToReadableStream(974 Promise.resolve(raw('<p>slow content</p>') as HtmlEscapedString),975 onError976 )977978 const reader = stream.getReader()979 await reader.cancel()980981 await new Promise((resolve) => setTimeout(resolve))982983 expect(unhandled).toHaveLength(0)984 expect(onError).not.toHaveBeenCalled()985986 process.off('unhandledRejection', onRejection)987 })988})
modified:src/jsx/streaming.ts+13 added-3 removed
141 unmodified lines
142export 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 lines
157 HtmlEscapedCallbackPhase.BeforeStream,158 true,159 context160 )161 if (!cancelled) {160 controller.enqueue(textEncoder.encode(resolved))162 controller.enqueue(textEncoder.encode(resolved))163 }164165 let resolvedCount = 0166 const callbacks: Promise<void>[] = []167 const then = (promise: Promise<string>) => {
16 unmodified lines
184 // 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).callbacks
8 unmodified lines
203 // maybe the connection was closed204 onError(e)205 }206207 if (!cancelled) {202 controller.close()208 controller.close()209 }210 },211 cancel() {212 cancelled = true213 },214 })215 return reader216}