Repository navigation
fix: close abandoned PDF.js development asset streams - #23054
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe PDF.js development middleware skips opening a file stream when the response is already destroyed. It ties stream cleanup to response close and error events, and destroys the response if the source stream errors. Tests cover abandoned requests, successful GET and HEAD responses, failure cleanup, and pass-through requests. The WebRTC egress probe logs its current phase and includes phase and Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to The PDF middleware now cleans up abandoned streams, while the other changes improve diagnostics, translations, and version input. No material user-facing regression is evident; merge is reasonable once current CI succeeds. Architecture SummaryArchitecture risk: 🔵 Low · up to The change affects 2 systems. Changed systems: Architecture concerns Review detailsSystems and components
Before / after behavior
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Out of Scope Changes checkExplanation The PDF.js middleware and stream tests match the historical [
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
config/scripts/pdfjs-viewer-assets-stream.test.ts (1)
78-95: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPreserve foreign response listeners in the cleanup tests.
The tests assert zero
closeanderrorlisteners, but the fixture does not register listeners owned by other middleware. A regression that removes all listeners would still pass. Register persistent sentinel listeners and assert that only the asset stream's listeners are removed on success, source failure, response failure, and abandoned responses.Suggested fix
function request(method = 'GET', url = '/wasm/fixture.wasm') { const response = Object.assign(new PassThrough({ highWaterMark: 16 }), { setHeader: vi.fn(), statusCode: 0 }) @@ return { response, next, source: observed.streams.at(-1) } } +function addForeignListeners(response: PassThrough) { + const close = vi.fn() + const error = vi.fn() + response.on('close', close) + response.on('error', error) + return { close, error } +} + it('releases file handles after repeated abandoned responses with backpressure', async () => { const responses: PassThrough[] = [] + const foreignListeners = new Map<PassThrough, ReturnType<typeof addForeignListeners>>() for (let index = 0; index < 25; index += 1) { const { response, source } = request() responses.push(response) + foreignListeners.set(response, addForeignListeners(response)) if (!source) { throw new Error('Missing source') } @@ } await expect.poll(() => observed.streams.filter((stream) => !stream.closed).length).toBe(0) expect(observed.streams.every((stream) => stream.fd === null)).toBe(true) - expect(responses.map((response) => response.listenerCount('close'))).toEqual(Array(25).fill(0)) - expect(responses.map((response) => response.listenerCount('error'))).toEqual(Array(25).fill(0)) + for (const [response, { close, error }] of foreignListeners) { + expect(response.listeners('close')).toEqual([close]) + expect(response.listeners('error')).toEqual([error]) + } }) it('preserves successful GET bytes and removes response cleanup listeners', async () => { const { response, source, next } = request('GET', '/cmaps/fixture.bcmap') + const foreign = addForeignListeners(response) const chunks: Buffer[] = [] @@ - expect(response.listenerCount('close')).toBe(0) - expect(response.listenerCount('error')).toBe(0) + expect(response.listeners('close')).toEqual([foreign.close]) + expect(response.listeners('error')).toEqual([foreign.error]) @@ it('closes the response on source failure without leaving listeners', async () => { const { response, source } = request() + const foreign = addForeignListeners(response) @@ - expect(response.listenerCount('close')).toBe(0) - expect(response.listenerCount('error')).toBe(0) + expect(response.listeners('close')).toEqual([foreign.close]) + expect(response.listeners('error')).toEqual([foreign.error]) }) it('closes a source when the response fails', async () => { const { response, source } = request() + const foreign = addForeignListeners(response) @@ - expect(response.listenerCount('close')).toBe(0) - expect(response.listenerCount('error')).toBe(0) + expect(response.listeners('close')).toEqual([foreign.close]) + expect(response.listeners('error')).toEqual([foreign.error]) })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 59617fb4-298d-45e1-a0eb-cf7ca1dbe61d
📒 Files selected for processing (2)
config/build-plugins/pdfjs-viewer-assets.tsconfig/scripts/pdfjs-viewer-assets-stream.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Bind PDF.js asset read stream to response lifetime — in
config/build-plugins/pdfjs-viewer-assets.ts, the GET branch now returns early whenresponse.destroyed, destroys thecreateReadStreamsource on responseclose/error, removes exactly those two listeners when the stream closes, and destroys the response on source error. Headers, bytes, HEAD, path validation, pass-through, and build-time copying are untouched. - Regression tests —
config/scripts/pdfjs-viewer-assets-stream.test.tsadds 10 tests over a mockedcreateReadStream: 25 abandoned backpressured responses (fdnull, zero open streams, zero leftover listeners), exact GET bytes/headers, HEAD without opening a stream, source failure, response failure, four pass-through cases, and an already-closed response.
I verified the fix locally: the suite passes 10/10 at HEAD, and reverting only the middleware to the old createReadStream(filePath).pipe(response) makes 4 of the tests fail (25 retained streams, source-failure timeout, response-failure, already-closed-opens-one-stream). The tests genuinely pin the leak rather than passing vacuously.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Fixed in f7c6828. The closed-response guard now runs before header writes; the regression uses a header setter that throws if touched after close. Cleanup tests now seed foreign close/error listeners and verify they survive success, source failure, response failure, and abandoned responses. The pre-fix closed-response case fails; all 10 cases pass with the fix. The concurrent catalog correction is preserved. |
|
Reviewed the CodeRabbit docstring-coverage warning. This repository explicitly requires concise comments limited to non-obvious reasoning (AGENTS.md), so I am declining the generic 80% docstring suggestion. The existing ownership/behavior comments and focused regression tests cover the decisions in this change. No code change is warranted for that style-only warning. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Guarded a closed response before writing headers — in
config/build-plugins/pdfjs-viewer-assets.ts,if (response.destroyed) returnnow runs beforestatusCode/setHeader(it previously sat just beforecreateReadStream), so a response that a prior middleware already closed can no longer reach the header writes. - Hardened the cleanup-listener tests — the fixture in
config/scripts/pdfjs-viewer-assets-stream.test.tsnow seeds foreignclose/errorlisteners and asserts only the middleware's listeners are removed across success, source failure, response failure, and 25 abandoned backpressured responses; the closed-response regression uses asetHeaderthat throwsERR_HTTP_HEADERS_SENTand asserts it is never called. - Carried a concurrent i18n catalog correction — the six locale files restore the diff-note draft catalog entries and add the missing trailing comma after
commentTooLarge. Unrelated to the stream fix, but intentional per the author, and all six files parse.
The prior CodeRabbit thread on this line is addressed and resolved, and the earlier Pullfrog approval had no open threads. I re-ran the focused suite: pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts → 10/10 pass at f7c6828.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Reviewed the latest scope and docstring warnings. The WebRTC change adds diagnostics only, retaining the existing deadline and assertions; it is disclosed under “CI diagnostic prerequisite.” The two locale lines reconcile shared main-branch catalog maintenance and are disclosed under Notes. Both prerequisites were reviewed separately from the unchanged PDF cleanup. No issue will be created: the user explicitly requested PR-only work. Generic 80% docstring coverage is declined under AGENTS.md’s concise, non-obvious-comments-only policy. No new actionable code finding remains; successful current-head CI is still required. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Merged
mainand kept the ja/ko diff-note wording —72dc809b2cmergesmain; the en/es/fr/zh catalog restore now lives onmainand drops out of this diff, leaving only the intentional ja/ko "note for the AI" recipient wording (f6c449191e). - Instrumented the WebRTC egress probe with phase diagnostics —
8696ea25afaddsenterPhase(...)markers across the generated probe script and recordsphaseplusprotectedGuestin the result file on timeout and in the catch handler. The 20-second deadline, the egress assertions, and the pass/fail semantics are unchanged.
The prior Pullfrog approvals had no open inline threads, and the CodeRabbit thread on the closed-response guard was already resolved by the author. Focused suite (pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts) was green at the previously reviewed head; the delta since then is test-only diagnostics plus a translation-only locale tweak.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Made the hourly-version test hermetic —
getHourlyBuildIdentitynow accepts an optionalpackageVersionthat overrides thepackage.jsonread (config/scripts/hourly-build-version.mjs), and the "unpublished buggy release" test pinspackageVersion: '1.4.201'so its historical fixture no longer drifts as main's package version advances. Production behavior is unchanged: the CLI entrypoint passes no override, so it still readspackage.json(packageVersion ?? JSON.parse(readFileSync(...)).version). - Rest of the PR unchanged since its prior approvals — the PDF.js asset-stream lifetime fix and its test, the WebRTC egress phase diagnostics, and the ja/ko diff-note recipient wording are untouched by this delta.
Ran the focused suite: pnpm test config/scripts/hourly-build-version.test.mjs → 16/16 pass at 120c4ca.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Historical release-test CI prerequisite
The CI merge base advanced the package version beyond a historical release fixture: the test expected 1.4.203 but read today’s 1.4.214 package. The build-identity helper now accepts an optional package version alongside its existing release inputs, and that test supplies its historical 1.4.201 version. Normal callers still read package.json. Both original version/build-number assertions remain; all 16 tests pass, and two exact before/after comparisons confirm unchanged default output. Targeted lint, including the no-module-mocking rule, passes. Application and native terminal code are unchanged; fresh CI remains required.
ELI5
When a developer cancels a PDF asset download, the server now closes the file it was reading for that request.
What Changed
Repeated canceled PDF.js asset requests no longer leave file handles open in Vite. The asset stream stops when its response closes or fails, read errors close the response, and stream completion removes its response listeners. A response that already closed opens no file. GET/HEAD headers, successful bytes, path validation, middleware pass-through and build copies stay the same.
Why
pipe()alone does not destroy the source when a downstream response disappears under backpressure. This uses the same stream-lifetime pattern as the local build feed; keeping that small wiring in the plugin avoids importing desktop updater code into the build configuration.Linked Issue
Fixes #23051
Visual Proof
N/A — development-server file handle cleanup; no rendered interaction or packaged PDF behavior changes.
Performance proof
Actual middleware with real temporary files and25 abandoned, backpressured responses: 25 open file streams → 0, with every descriptor closed and owned response listener removed. The permanent regression fails against the exact baseline. An already-closed response opens zero streams after the fix. No UI or production-server latency claim is made.
CI diagnostic prerequisite
The branch also adds phase markers and a timeout result to the existing WebRTC egress test, after a Linux CI run exited before producing its result file. The probe keeps the same 20-second deadline and all egress assertions; no browser production policy changes. The added diagnostics identify where a future failure occurs. Final-head CI must pass.
Testing
ORCA_BACKGROUND_LAUNCH=1 pnpm test config/scripts/pdfjs-viewer-assets-stream.test.ts.Review
Merge risk: low. Node stream destruction is idempotent and works before the descriptor opens; real-stream tests cover that edge. Source errors disconnect the failed response instead of escaping unhandled. Only this middleware's cleanup listeners are removed.
Negative user-facing trade-offs: none identified. Small per-request lifecycle listeners last only as long as the source stream. This change affects development asset requests, not packaged production rendering.
Agent skill upstream boundary
Notes
The shared diff-note catalog entries are now in main and have dropped out of this diff. The remaining Japanese/Korean values make the AI the note’s recipient.
No timer, polling, subprocess, new cache, wire change, platform-specific path or SSH/folder-workspace assumption. No terminal/session reliability invariant changes.
Checklist