Skip to content

Refactor and improve performance of the component that embed RSC payload into the html stream #1738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

AbanoubGhadban
Copy link
Collaborator

@AbanoubGhadban AbanoubGhadban commented Jun 18, 2025

Summary

Remove this paragraph and provide a general description of the code changes in your pull
request... were there any bugs you had fixed? If so, mention them. If
these bugs have open GitHub issues, be sure to tag them here as well,
to keep the conversation linked together.

Pull Request checklist

Remove this line after checking all the items here. If the item is not applicable to the PR, both check it out and wrap it by ~.

  • Add/update test to cover these changes
  • Update documentation
  • Update CHANGELOG file

Add the CHANGELOG entry at the top of the file.

Other Information

Remove this paragraph and mention any other important and relevant information such as benchmarks.


This change is Reviewable

Summary by CodeRabbit

  • Refactor
    • Enhanced the streaming process for React Server Components to improve hydration accuracy and streaming efficiency, resulting in smoother and more reliable page rendering without altering user-facing features.

Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

Walkthrough

The injectRSCPayload function has been refactored to implement a buffered and scheduled flushing mechanism for embedding React Server Components (RSC) payloads into an HTML stream. The update introduces separate buffers for initialization scripts, HTML, and payload scripts, ensuring controlled and ordered output, with improved batching and precise timing for client hydration.

Changes

File(s) Change Summary
node_package/src/injectRSCPayload.ts Refactored to use separate buffers for RSC payload initialization scripts, HTML chunks, and payload chunk scripts; implemented scheduled flush with setTimeout; reorganized event handlers and output order; replaced direct stream writes with buffered string generation and combined output via a single PassThrough stream.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant injectRSCPayload
    participant HTMLStream
    participant OutputStream

    Client->>injectRSCPayload: Call with HTMLStream and context
    injectRSCPayload->>HTMLStream: Listen for data/error/end
    HTMLStream-->>injectRSCPayload: On data (HTML chunk)
    injectRSCPayload->>injectRSCPayload: Buffer HTML chunk
    injectRSCPayload->>injectRSCPayload: Buffer RSC init/payload scripts as needed
    injectRSCPayload->>injectRSCPayload: Schedule flush (setTimeout)
    injectRSCPayload->>OutputStream: On flush, write init scripts, HTML, then payload scripts
    HTMLStream-->>injectRSCPayload: On end/error
    injectRSCPayload->>OutputStream: Final flush and cleanup
    OutputStream-->>Client: Combined output stream (ordered)
Loading

Suggested reviewers

  • justin808

Poem

🐇 Buffers stacked, scripts in a line,
HTML waits for its perfect time.
Flushes scheduled, chunks all aligned,
Streams now dance, perfectly timed.
Hydration’s rhythm, smooth and bright,
Code hops forward, swift as light! ✨

✨ Finishing Touches
  • 📝 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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
node_package/src/injectRSCPayload.ts (2)

22-24: Consider CSP-friendly <script> helper

If your app ever enforces a Content-Security-Policy with a script-src 'nonce-…', you’ll need a way to inject that nonce attribute. A tiny change to let the caller pass attributes (or at least a nonce) would avoid future refactors.


124-136: Large-buffer allocation may spike memory

Buffer.allocUnsafe(totalSize) copies every pending sub-buffer into one mega-buffer.
For long-running streams this can transiently double memory (buffers + combined copy).
Using resultStream.cork() / uncork() or simply resultStream.write() each sub-buffer avoids the extra copy while still batching under Node’s internal high-water-mark.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 122e85a and aabf2f0.

📒 Files selected for processing (1)
  • node_package/src/injectRSCPayload.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: rspec-package-tests (oldest)
  • GitHub Check: build-dummy-app-webpack-test-bundles (newest)
🔇 Additional comments (1)
node_package/src/injectRSCPayload.ts (1)

221-229: Race: initialization script may miss the very first flush

startRSC() pushes the initialization script but does not call scheduleFlush().
If the first HTML chunk scheduled a flush before startRSC() executes, the flush could run with an empty rscInitializationBuffers, violating the “initialisation-before-HTML” guarantee.

rscInitializationBuffers.push(Buffer.from(initializationScript));
+scheduleFlush(); // ensure array init goes out with or before first HTML chunk

…to 15.0.0.rc.0 for improved stability and features.
Comment on lines +167 to +169
rscInitializationBuffers.length = 0;
htmlBuffers.length = 0;
rscPayloadBuffers.length = 0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
rscInitializationBuffers.length = 0;
htmlBuffers.length = 0;
rscPayloadBuffers.length = 0;
rscInitializationBuffers = [];
htmlBuffers = [];
rscPayloadBuffers = [];

(and make them let) seems more natural.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
node_package/src/injectRSCPayload.ts (1)

30-32: Payload-breaking </script> escape bug is still here

Previous review already flagged that escaping the whole script string corrupts the JSON payload when the chunk itself contains </script>. The new version has not addressed it – escapeScript() is still called after JSON.stringify(chunk), producing the invalid sequence "</\script>", which will throw on JSON.parse and break hydration.

This is the exact issue described in the past review comment; please apply that fix (escape inside the chunk before it is stringified).

🧹 Nitpick comments (1)
node_package/src/injectRSCPayload.ts (1)

137-161: Manual buffer stitching adds complexity without gain

Buffer.allocUnsafe(totalSize) + manual copy loops work, but Buffer.concat([...]) is simpler, less error-prone, and avoids having to pre-compute totalSize:

-const combinedBuffer = Buffer.allocUnsafe(totalSize);
-let offset = 0;
-for (const buffer of rscInitializationBuffers) {
-  buffer.copy(combinedBuffer, offset);
-  offset += buffer.length;
-}
-
-resultStream.push(combinedBuffer);
+const combinedBuffer = Buffer.concat([
+  ...rscInitializationBuffers,
+  ...htmlBuffers,
+  ...rscPayloadBuffers,
+]);
+resultStream.push(combinedBuffer);

Unless you have a benchmark proving a meaningful win, prefer the concise approach.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aabf2f0 and aa20a9f.

⛔ Files ignored due to path filters (1)
  • Gemfile.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • node_package/src/injectRSCPayload.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: dummy-app-integration-tests (oldest)
  • GitHub Check: dummy-app-integration-tests (newest)
  • GitHub Check: build
  • GitHub Check: examples (oldest)
  • GitHub Check: rspec-package-tests (oldest)
  • GitHub Check: rspec-package-tests (newest)

Comment on lines +1 to 4
import { PassThrough } from 'stream';
import { finished } from 'stream/promises';
import { createRSCPayloadKey } from './utils.ts';
import { RailsContextWithServerComponentCapabilities, PipeableOrReadableStream } from './types/index.ts';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Drop the “.ts” extension in local imports

The emitted JavaScript files will be named utils.js and types/index.js, so at runtime Node will fail to resolve paths that still end with “.ts”.

-import { createRSCPayloadKey } from './utils.ts';
-import { RailsContextWithServerComponentCapabilities, PipeableOrReadableStream } from './types/index.ts';
+import { createRSCPayloadKey } from './utils';
+import {
+  RailsContextWithServerComponentCapabilities,
+  PipeableOrReadableStream,
+} from './types/index';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { PassThrough } from 'stream';
import { finished } from 'stream/promises';
import { createRSCPayloadKey } from './utils.ts';
import { RailsContextWithServerComponentCapabilities, PipeableOrReadableStream } from './types/index.ts';
import { PassThrough } from 'stream';
import { finished } from 'stream/promises';
import { createRSCPayloadKey } from './utils';
import {
RailsContextWithServerComponentCapabilities,
PipeableOrReadableStream,
} from './types/index';
🤖 Prompt for AI Agents
In node_package/src/injectRSCPayload.ts at lines 1 to 4, the local import
statements incorrectly include the ".ts" extension, which will cause runtime
resolution errors since the emitted JavaScript files have ".js" extensions.
Remove the ".ts" extension from the import paths for './utils.ts' and
'./types/index.ts' so they read './utils' and './types/index' respectively.

@AbanoubGhadban AbanoubGhadban merged commit 236e475 into master Jun 18, 2025
11 checks passed
@AbanoubGhadban AbanoubGhadban deleted the abanoubghadban/dont-send-first-chunk-until-shell-is-rendered branch June 18, 2025 17:00
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.

2 participants