Skip to content

Close CDP streams after reading - #609

Open
i7a wants to merge 3 commits into
rubycdp:mainfrom
i7a:fix/close-cdp-stream
Open

Close CDP streams after reading#609
i7a wants to merge 3 commits into
rubycdp:mainfrom
i7a:fix/close-cdp-stream

Conversation

@i7a

@i7a i7a commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Close CDP streams with IO.close after reading:

  • the stream returned by Page.printToPDF
  • the stream reported by the Tracing.tracingComplete event

Motivation

Ferrum requests stream-based output from CDP for PDF generation and tracing.It reads each stream with IO.read until EOF, but does not close the stream handle afterward.

For PDF generation, the handle is returned by Page.printToPDF. For tracing, the handle is delivered through the Tracing.tracingComplete event after Tracing.end is called.

CDP provides IO.close to release a stream handle and discard any temporary backing storage associated with it. Explicitly closing the stream after use keeps its lifecycle well-defined and avoids relying on implicit browser-side cleanup.

This affects streams used by:

  • Ferrum::Browser#pdf
  • Ferrum::Page::Tracing#record

Error handling

IO.close is called from an ensure block, so cleanup is attempted when:

  • the stream reaches EOF
  • IO.read fails
  • writing to the output fails

If reading or writing has already failed, an IO.close error is suppressed so that it does not replace the original exception.If the stream was read successfully, an IO.close error is propagated to the caller.

Tests

Added unit tests covering:

  • reading multiple chunks until EOF
  • Base64-encoded chunks
  • IO.read failures
  • closing after EOF
  • closing after output write failures
  • preserving the original read/write exception when closing also fails
  • preserving non-StandardError exceptions
  • propagating an IO.close failure after a successful read

@i7a

i7a commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Two behavior questions for maintainers:

  1. Page::Stream#stream previously returned nil as an incidental result of the loop. The completion flag introduced here makes it return true. Its current callers ignore the return value, and its RBS return type is untyped. Is this acceptable, or would you prefer preserving nil?

  2. When IO.read fails with a timeout, the synchronous IO.close attempted by the ensure block may wait for another timeout period. I kept the close synchronous so that cleanup is attempted consistently. Would you prefer a different policy for TimeoutError or DeadBrowserError?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant