Skip to content

fix: Use more efficient stream reading - #3691

Merged
nielsenko merged 1 commit into
serverpod:mainfrom
nielsenko:fix-3633-stream-reading
Jun 20, 2025
Merged

nielsenko merged 1 commit into
serverpod:mainfrom
nielsenko:fix-3633-stream-reading

Conversation

@nielsenko

@nielsenko nielsenko commented Jun 19, 2025 •

Copy link
Copy Markdown
Collaborator

Refactor stream data handling in FileUploader to use http.ByteStream().toBytes() directly.

Fixes: #3633

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

If you need help, consider asking for advice on the discussion board.

Summary by CodeRabbit

  • Refactor
    • Improved the process for handling binary uploads, resulting in a more efficient file upload experience.
  • Chores
    • Removed unused code to streamline the application.

@coderabbitai

coderabbitai Bot commented Jun 19, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The code refactors the file upload process by removing a custom stream reading method and instead uses http.ByteStream(stream).toBytes() to handle stream-to-bytes conversion for HTTP POST requests. Additionally, unused helper methods are removed, resulting in a cleaner and more direct implementation for binary uploads.

Changes

File(s) Change Summary
packages/serverpod_client/lib/src/file_uploader.dart Removed custom stream reading method and unused helpers; switched to using http.ByteStream(stream).toBytes() for upload.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FileUploader
    participant HTTP

    Client->>FileUploader: upload(stream, length)
    FileUploader->>HTTP: POST uploadDescription.url (body: await ByteStream(stream).toBytes())
    HTTP-->>FileUploader: HTTP response
    FileUploader-->>Client: Upload result (success/failure)
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix file upload to prevent "Invalid array length" error by correctly reading stream data (#3633) ✅

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e38b321 and 66e401e.

📒 Files selected for processing (1)
  • packages/serverpod_client/lib/src/file_uploader.dart (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (23)
  • GitHub Check: Bootstrap tests (3.24.0, windows-latest, tests/bootstrap_project)
  • GitHub Check: Serverpod E2E web tests (3.32.1)
  • GitHub Check: Serverpod E2E web tests (3.24.0)
  • GitHub Check: Bootstrap tests (3.32.1, windows-latest, tests/bootstrap_project)
  • GitHub Check: Bootstrap tests (3.32.1, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: Bootstrap tests (3.24.0, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: Serverpod integration tests (server) (3.24.0)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.24.0)
  • GitHub Check: Serverpod integration tests (server) (3.32.1)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.32.1)
  • GitHub Check: Unit tests IO (3.24.0, ubuntu-latest)
  • GitHub Check: Migration e2e tests (3.24.0)
  • GitHub Check: Unit tests IO (3.32.1, ubuntu-latest)
  • GitHub Check: Unit tests IO (3.24.0, windows-latest)
  • GitHub Check: Migration e2e tests (3.32.1)
  • GitHub Check: Unit tests IO (3.32.1, windows-latest)
  • GitHub Check: CLI e2e tests (3.32.1, ubuntu-latest, tests/serverpod_cli_e2e_test)
  • GitHub Check: serverpod generate (3.24.0)
  • GitHub Check: dart analyze latest (3.32.1, windows-latest)
  • GitHub Check: serverpod generate (3.32.1)
  • GitHub Check: dart analyze downgrade (3.24.0, windows-latest)
  • GitHub Check: dart analyze downgrade (3.32.1, windows-latest)
  • GitHub Check: dart analyze (3.24.0, windows-latest)
🔇 Additional comments (1)
packages/serverpod_client/lib/src/file_uploader.dart (1)

40-40: LGTM! Excellent refactoring to use the http package's built-in stream conversion.

This change effectively leverages http.ByteStream().toBytes() instead of custom stream reading logic, which is more efficient and cleaner. The http package's implementation is likely optimized and well-tested, making this a solid improvement that addresses issue #3633.


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.

@nielsenko nielsenko self-assigned this Jun 19, 2025
@nielsenko
nielsenko marked this pull request as ready for review June 19, 2025 12:39
@nielsenko
nielsenko requested a review from Copilot June 19, 2025 12:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR aims to refactor stream data handling in the FileUploader by replacing a custom stream reading implementation with the more efficient built-in http.ByteStream().toBytes() method.

  • Replaces the custom _readStreamData method with http.ByteStream().toBytes() in the HTTP POST request.
  • Removes obsolete commented-out helper functions for stream reading.
Comments suppressed due to low confidence (2)

packages/serverpod_client/lib/src/file_uploader.dart:40

  • Consider adding a comment above this line explaining the choice of http.ByteStream for direct conversion to bytes, emphasizing its performance benefits for larger files.
          body: await http.ByteStream(stream).toBytes(),

packages/serverpod_client/lib/src/file_uploader.dart:40

  • Ensure that tests adequately cover this new stream conversion implementation, especially with large data streams, to identify any potential performance or memory issues.
          body: await http.ByteStream(stream).toBytes(),

@nielsenko
nielsenko requested a review from SandPod June 19, 2025 12:40
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai While this will fix the immediate issue, we should avoid reading the full stream into memory before starting the upload. Could you make a follow-up issue for that?

@coderabbitai

coderabbitai Bot commented Jun 19, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll create a follow-up issue to track the stream memory optimization concern.

@nielsenko I've created a follow-up issue to track the stream memory optimization concern. The issue covers the need to implement a streaming upload mechanism that avoids loading the full file into memory before starting the upload, which would be especially important for large file uploads.

/|   /|   

( ✌️ ✌️ )
) (
( >o< )
^^ ^^


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for the stream memory optimization
gh issue create \
  --title "Optimize FileUploader to avoid loading full stream into memory during upload" \
  --body "## Issue Description

The current FileUploader implementation in \`packages/serverpod_client/lib/src/file_uploader.dart\` uses \`http.ByteStream(stream).toBytes()\` to convert the entire stream to bytes before uploading. While this fixes the immediate issue with stream reading, it loads the complete file into memory before starting the upload.

## Problem

For large file uploads, this approach can cause:
- High memory usage
- Potential out-of-memory errors on devices with limited RAM
- Poor performance due to buffering overhead

## Proposed Solution

Implement a streaming upload mechanism that can send data directly from the stream to the HTTP request without buffering the entire content in memory first. This would involve:
- Using the stream directly in the HTTP request body
- Ensuring proper chunked transfer encoding
- Maintaining compatibility with the existing upload flow

## Context

This issue was identified during the review of PR #3691 which fixed the immediate stream reading issue but introduced the memory buffering concern.

**Related:**
- PR: https://github.com/serverpod/serverpod/pull/3691
- Comment: https://github.com/serverpod/serverpod/pull/3691#issuecomment-$(gh api repos/serverpod/serverpod/pulls/3691/reviews --jq '.[-1].id')

**Reporter:** @nielsenko" \
  --assignee nielsenko

Length of output: 1481


@nielsenko Perfect! I've successfully created issue #3692 to track the stream memory optimization: #3692

The issue covers the need to implement a streaming upload mechanism that avoids buffering the entire file content in memory, which will be especially important for large file uploads on memory-constrained devices.

/|   /|   

( ^.^ )
) (
( v )
^^ ^^


✏️ Learnings added
Learnt from: nielsenko
URL: https://github.com/serverpod/serverpod/pull/3691

Timestamp: 2025-06-19T12:43:05.099Z
Learning: In FileUploader implementations, avoid using `http.ByteStream(stream).toBytes()` for large file uploads as it loads the entire stream into memory before uploading. Instead, use streaming upload mechanisms that send data directly from the stream to the HTTP request without buffering the complete content in memory first.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@nielsenko

nielsenko commented Jun 19, 2025 •

Copy link
Copy Markdown
Collaborator Author

@alexander This PR uses ByteStream.toBytes that again uses ByteConversionSink, which use an Unit8List for buffer instead of the <int>[] in our previous naive implementation.

I'll look at #3692 for a more thorough solution while I wait for you review

@tp tp left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, and thanks for the explanation. Crazy if you think about it, that without this an 1MB file upload would take 8MB of memory just for the file 😅

@nielsenko
nielsenko merged commit 7c78ce0 into serverpod:main Jun 20, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Jun 20, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

File upload results in: Invalid array length

3 participants