Skip to content
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

chore: add TB to internal file size converter #1094

Merged
merged 2 commits into from
Dec 12, 2024

Conversation

juliusmarminge
Copy link
Collaborator

@juliusmarminge juliusmarminge commented Dec 11, 2024

Summary by CodeRabbit

  • New Features

    • Expanded file size unit support to include terabytes (TB).
    • Enhanced file size calculations to align with binary conventions.
  • Bug Fixes

    • Improved error messages for file size validation and middleware errors for better clarity.
    • Enhanced error handling for file type matching with clearer error messages.
  • Chores

    • Updated configuration handling for both array and object inputs.

Copy link

vercel bot commented Dec 11, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-uploadthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 12, 2024 8:23am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Dec 12, 2024 8:23am

Copy link

changeset-bot bot commented Dec 11, 2024

⚠️ No Changeset found

Latest commit: aba4fe9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request focus on enhancing the functionality of the utils.ts file within the shared package. Key modifications include the addition of "TB" (terabytes) to the FILESIZE_UNITS constant, a change in the logarithmic base for the bytesToFileSize function from 1000 to 1024, and improvements to the error handling in functions like matchFileType. The fillInputRouteConfig function has been updated to better handle input configurations, while the safeParseJSON function remains unchanged. Additionally, the request handler tests for the upload functionality have been updated to improve error messages and handling.

Changes

File Path Change Summary
packages/shared/src/utils.ts - Updated FILESIZE_UNITS to include "TB".
- Changed bytesToFileSize logarithmic base to 1024.
- Modified fillInputRouteConfig for better input handling.
- Enhanced error handling in matchFileType with clearer error messages.
- safeParseJSON function retained without changes.
packages/uploadthing/test/request-handler.test.ts - Updated error message for file size validation.
- Refined error handling for middleware with more specific error messages.

Possibly related PRs

Suggested labels

sdk, ❗ infra changes required

Suggested reviewers

  • markflorkowski
  • t3dotgg

Poem

In the land of bytes and files,
A rabbit hops and smiles,
With terabytes now in sight,
Configs handled just right.
Errors caught with gentle care,
In the code, we dance and share! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Experiment)
  • @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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 817df76 and d934b41.

📒 Files selected for processing (1)
  • packages/shared/src/utils.ts (2 hunks)
🔇 Additional comments (2)
packages/shared/src/utils.ts (2)

139-139: LGTM: TB unit addition is well-integrated

The addition of "TB" to FILESIZE_UNITS is properly implemented and automatically works with existing parsing logic.


Line range hint 139-167: Verify the impact of file size changes

Let's verify the impact of these changes on tests and documentation.

✅ Verification successful

Let me gather more specific information about the test usage of these utility functions.


Let me fix the import search pattern and look for any direct usage of these functions.


Let me try one final search with corrected patterns to find any usage of these functions.


Based on the gathered information, I can now provide the final response:

File size utility functions are actively used in core functionality

The fileSizeToBytes and bytesToFileSize functions are integral parts of the upload functionality:

  • Used in packages/uploadthing/src/internal/route-config.ts for file size validation
  • Used in packages/uploadthing/src/client.ts for processing size limits
  • No breaking changes detected in the implementation

The changes appear to be maintaining the existing behavior while improving the code structure. The functions are used in critical paths for file size validation and display, making them essential utilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential impacts of file size changes

# Check for test files using these functions
echo "Checking test files..."
rg -l "bytesToFileSize|fileSizeToBytes|FILESIZE_UNITS" --glob "**/*.test.*"

# Check for documentation references
echo -e "\nChecking documentation..."
rg -l "KB|MB|GB|TB" --glob "**/*.md"

# Check for examples in code
echo -e "\nChecking code examples..."
rg "(\\d+)\\s*(KB|MB|GB|TB)" --glob "**/*.{ts,js,tsx,jsx}"

Length of output: 6251


Script:

#!/bin/bash
# Check for direct usage of the utility functions in tests
echo "Checking test files for utility functions usage..."
rg -A 5 "fileSizeToBytes|bytesToFileSize" --glob "**/*.test.*"

# Check implementation details
echo -e "\nChecking implementation in utils.ts..."
rg -A 10 "^export const (fileSizeToBytes|bytesToFileSize)" packages/shared/src/utils.ts

# Check for any imports of these functions
echo -e "\nChecking imports..."
rg "import.*{.*(fileSizeToBytes|bytesToFileSize).*} from.*utils"

Length of output: 1259


Script:

#!/bin/bash
# Check for imports and usage
echo "Checking imports and usage..."
rg "import.*[{ ]+(fileSizeToBytes|bytesToFileSize)[} ].*from.*utils"

# Check for direct usage of these functions in the codebase
echo -e "\nChecking direct usage..."
rg "\b(fileSizeToBytes|bytesToFileSize)\(" --type ts --type tsx

# Check if there are any tests specifically for these utilities
echo -e "\nChecking for utility tests..."
rg -B 2 -A 5 "describe.*('|\")(fileSizeToBytes|bytesToFileSize)" --glob "**/*.test.*"

Length of output: 463


Script:

#!/bin/bash
# Search for any usage of these functions in the codebase
echo "Checking for function usage..."
rg "\b(fileSizeToBytes|bytesToFileSize)\b" --type ts

# Check for any test files that might contain these functions
echo -e "\nChecking test files..."
rg -l "(fileSizeToBytes|bytesToFileSize)" packages/shared/src/**/*.test.ts

# Check if these functions are exported from index files
echo -e "\nChecking exports..."
rg "export.*{.*\b(fileSizeToBytes|bytesToFileSize)\b.*}" packages/shared/src/index.ts

Length of output: 1363

Comment on lines +166 to +167
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, i)).toFixed(2)}${FILESIZE_UNITS[i]}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider aligning size units with standard conventions

The change from base 1000 to 1024 for size calculations introduces a discrepancy with the displayed units. Currently:

  • Using 1024 as base (binary prefix standard)
  • But displaying KB, MB, etc. (decimal prefix standard)

This mixing of standards could be confusing as:

  • 1 KB should be 1000 bytes (SI standard)
  • 1 KiB should be 1024 bytes (Binary standard)

Consider one of these solutions:

  1. Keep 1024 but use binary prefixes:
-export const FILESIZE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const;
+export const FILESIZE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB"] as const;
  1. Or revert to 1000 to match current decimal prefixes:
-  const i = Math.floor(Math.log(bytes) / Math.log(1024));
-  return `${(bytes / Math.pow(1024, i)).toFixed(2)}${FILESIZE_UNITS[i]}`;
+  const i = Math.floor(Math.log(bytes) / Math.log(1000));
+  return `${(bytes / Math.pow(1000, i)).toFixed(2)}${FILESIZE_UNITS[i]}`;

Committable suggestion skipped: line range outside the PR's diff.

Copy link

pkg-pr-new bot commented Dec 11, 2024

Open in Stackblitz

More templates

npm i https://pkg.pr.new/pingdotgg/uploadthing/@uploadthing/shared@1094
npm i https://pkg.pr.new/pingdotgg/uploadthing@1094

commit: aba4fe9

Copy link
Contributor

github-actions bot commented Dec 11, 2024

📦 Bundle size comparison

Bundle Size (gzip) Visualization
Main 27.60KB See Treemap 📊
PR (075bf74) 27.60KB See Treemap 📊
Diff No change

Copy link
Collaborator

@markflorkowski markflorkowski left a comment

Choose a reason for hiding this comment

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

Gotta update tests b/c of 1000/1024 change

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: 0

🧹 Outside diff range and nitpick comments (1)
packages/uploadthing/test/request-handler.test.ts (1)

157-157: Fix grammatical error in error message

The error message contains a grammatical error. It should be "an image file" instead of "a image file" since "image" starts with a vowel sound.

-        "Error: You uploaded a image file that was 3.00MB, but the limit for that type is 2MB",
+        "Error: You uploaded an image file that was 3.00MB, but the limit for that type is 2MB",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d934b41 and aba4fe9.

📒 Files selected for processing (1)
  • packages/uploadthing/test/request-handler.test.ts (1 hunks)
🔇 Additional comments (1)
packages/uploadthing/test/request-handler.test.ts (1)

157-157: Verify file size calculation consistency

The error message shows a file size of "3.00MB" which appears to be using the new base-1024 calculation (as mentioned in the AI summary). Let's verify that this is consistent with the actual test setup.

✅ Verification successful

Let me gather more information about the file size limits and calculations to ensure consistency.


Let me check one more thing to verify the file size limit configuration for the image uploader route.


File size calculation is consistent with base-1024 standard

The verification shows that:

  1. The test file correctly uses base-1024 calculation: size: 3 * 1024 * 1024
  2. The error message accurately reflects this as "3.00MB"
  3. The size limit validation is handled by FileSizeMismatch error, which uses the same calculation standard
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for file size calculations and unit conversions in the codebase
# to ensure consistency with the new base-1024 standard.

# Look for file size calculations
rg -A 2 "size.*1024|1024.*size"

# Look for byte conversion functions
ast-grep --pattern 'function $_(bytes) {
  $$$
  1024
  $$$
}'

Length of output: 777


Script:

#!/bin/bash
# Look for file size limit configurations and related code
rg -A 3 "fileSize|maxSize|sizeLimit" packages/uploadthing/

# Look for the specific test case setup
rg -B 5 -A 5 "3.*1024.*1024" packages/uploadthing/test/

Length of output: 3241


Script:

#!/bin/bash
# Look for the image uploader route configuration in the test file
rg -B 10 -A 5 "imageUploader.*=.*createUploadthing" packages/uploadthing/test/

# Also check for any file size related error messages
rg -B 2 "FileSizeMismatch|file.*size.*limit" packages/uploadthing/

Length of output: 1780

@juliusmarminge juliusmarminge merged commit f9ad103 into main Dec 12, 2024
21 checks passed
@juliusmarminge juliusmarminge deleted the juliusmarminge-patch-5 branch December 12, 2024 08:23
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