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

feat: UTApi.generateSignedURL #1146

Merged
merged 8 commits into from
Feb 11, 2025
Merged

feat: UTApi.generateSignedURL #1146

merged 8 commits into from
Feb 11, 2025

Conversation

juliusmarminge
Copy link
Member

@juliusmarminge juliusmarminge commented Feb 11, 2025

Summary by CodeRabbit

  • Documentation

    • Updated API references with clearer guidelines for generating secure, presigned URLs.
    • Simplified explanations regarding the usage of the new generateSignedURL method.
  • New Features

    • Introduced an optimized approach for generating secure URLs for private files that reduces latency.
    • Deprecated the legacy URL generation approach in favor of the new efficient solution.
    • Enhanced API responses with additional file access details, including a new ufsUrl.
    • Added configuration options for customizing file service host URLs.
  • Tests

    • Added a new test suite to validate the functionality of the generateSignedURL method, including various scenarios for the expiresIn parameter.

Copy link

vercel bot commented Feb 11, 2025

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 Feb 11, 2025 6:11pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Feb 11, 2025 6:11pm

Copy link

changeset-bot bot commented Feb 11, 2025

🦋 Changeset detected

Latest commit: ac1f2ca

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
uploadthing Minor

Not sure what this means? Click here to learn what changesets are.

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

Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Warning

Rate limit exceeded

@juliusmarminge has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f249405 and ac1f2ca.

📒 Files selected for processing (4)
  • .changeset/poor-needles-drive.md (1 hunks)
  • docs/src/app/(docs)/api-reference/ut-api/page.mdx (2 hunks)
  • packages/uploadthing/src/sdk/index.ts (3 hunks)
  • playground/lib/actions.ts (1 hunks)

Walkthrough

This pull request updates the API documentation and SDK code to replace the deprecated getSignedURL method with a new generateSignedURL method. The new method generates a presigned URL directly, bypassing an extra fetch call, and includes enhanced validation for the expiresIn parameter. The response format has been updated to include the ufsUrl field. Additionally, configuration constants for default host URLs have been introduced, and new test suites have been added to cover the updated URL generation functionality.

Changes

File(s) Change Summary
docs/src/app/(docs)/api-reference/ut-api/page.mdx
docs/src/app/(docs)/concepts/regions-acl/page.mdx
docs/src/app/(docs)/working-with-files/page.mdx
Updated documentation to reflect the renaming of getSignedURL to generateSignedURL, with changes in descriptions, parameter details, and return types.
packages/uploadthing/src/sdk/index.ts
packages/uploadthing/src/sdk/types.ts
Added the generateSignedURL method in the UTApi class with improved validation for the expiresIn parameter; updated getSignedURL to include the ufsUrl in its response; introduced the new GenerateSignedURLOptions interface.
packages/uploadthing/src/_internal/config.ts Added new configuration constants UtfsHost and UfsHost with default values to allow specification of different host URLs.
packages/uploadthing/test/__test-helpers.ts
packages/uploadthing/test/sdk.test.ts
Updated test helpers to include the ufsUrl property in responses; added a new test suite for the generateSignedURL method covering valid inputs and error scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant UTApi
    participant Shared

    Client->>UTApi: Call generateSignedURL(key, options)
    UTApi->>Shared: Validate "expiresIn" and generate presigned URL
    Shared-->>UTApi: Return generated { ufsUrl }
    UTApi->>Client: Return response { ufsUrl }
Loading

Possibly related PRs

Suggested reviewers

  • markflorkowski

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

pkg-pr-new bot commented Feb 11, 2025

Copy link
Contributor

github-actions bot commented Feb 11, 2025

📦 Bundle size comparison

Bundle Size (gzip) Visualization
Main 30.67KB See Treemap 📊
PR (2a72ef7) 30.67KB See Treemap 📊
Diff No 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: 1

🧹 Nitpick comments (5)
packages/uploadthing/src/sdk/index.ts (1)

388-444: Consider extracting repeated expiration checks into a helper function.

Both this new generateSignedURL method and the existing getSignedURL method implement very similar checks for expiresIn. To reduce duplication and ensure consistency, consider refactoring them into a shared utility (e.g., validateExpiresIn()).

Additionally, note that the log span name is "getSignedURL" whereas this method is called generateSignedURL. For clarity, rename the log span or adopt a generic name like "signedURL".

+// Example helper for expiration validation
+function validateExpiresIn(expiresIn: number) {
+  if (isNaN(expiresIn)) {
+    throw new UploadThingError({
+      code: "BAD_REQUEST",
+      message: "expiresIn must be a valid time string or number (in seconds)."
+    });
+  }
+  if (expiresIn > 86400 * 7) {
+    throw new UploadThingError({
+      code: "BAD_REQUEST",
+      message: "expiresIn must be less than 7 days (604800 seconds)."
+    });
+  }
+  return expiresIn;
+}
+
 generateSignedURL = async (key: string, opts?: GetSignedURLOptions) => {
   guardServerOnly();
-  const expiresIn = parseTimeToSeconds(opts?.expiresIn ?? "5 minutes");
-  if (opts?.expiresIn && isNaN(expiresIn)) {
-    ...
-  }
-  if (expiresIn > 86400 * 7) {
-    ...
-  }
+  const expiresIn = validateExpiresIn(
+    parseTimeToSeconds(opts?.expiresIn ?? "5 minutes")
+  );
 
   // ...
 };
packages/uploadthing/src/_internal/config.ts (1)

95-102: Unused UtfsHost constant.

UfsHost is used in the SDK, but UtfsHost currently appears unused. Consider removing UtfsHost if it’s not needed or ensure it’s referenced where appropriate.

packages/uploadthing/src/sdk/types.ts (1)

104-112: Align the default value notation with actual usage.

The code defaults expiresIn to "5 minutes", while the documentation states @default 5min. Consistency helps avoid confusion.

- * @default 5min
+ * @default 5 minutes
docs/src/app/(docs)/api-reference/ut-api/page.mdx (2)

422-461: Consider enhancing the documentation for generateSignedURL.

The documentation would benefit from:

  1. A note about the performance improvement (e.g., "This method is significantly faster as it avoids the extra network round-trip").
  2. Adding the keyType parameter to maintain consistency with getSignedURL.
 ## `generateSignedURL` {{ tag: 'method', since: '7.5'}}

-Generate a presigned URL for a private file.
+Generate a presigned URL for a private file. This method is significantly faster than `getSignedURL` as it avoids the extra network round-trip.

 ### Parameters

 <Properties>
   <Property name="key" type="string" since="7.5" required>
     The key of the file to get a signed URL for
   </Property>
+  <Property
+    name="options.keyType"
+    type="customId | fileKey"
+    since="7.5"
+    defaultValue="fileKey"
+  >
+    The type of key to use for the signed URL.
+  </Property>
   <Property name="options.expiresIn" type="number | TimeString" since="7.5">

466-468: Fix grammar in the deprecation notice.

Add a comma after "API" to separate the independent clauses.

-file. This method is no longer recommended as it makes a fetch request to the UploadThing API which incurs redundant latency. Use
+file. This method is no longer recommended as it makes a fetch request to the UploadThing API, which incurs redundant latency. Use
🧰 Tools
🪛 LanguageTool

[uncategorized] ~467-~467: Possible missing comma found.
Context: ...akes a fetch request to the UploadThing API which incurs redundant latency. Use [`g...

(AI_HYDRA_LEO_MISSING_COMMA)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00ae433 and b0702ac.

📒 Files selected for processing (8)
  • docs/src/app/(docs)/api-reference/ut-api/page.mdx (2 hunks)
  • docs/src/app/(docs)/concepts/regions-acl/page.mdx (1 hunks)
  • docs/src/app/(docs)/working-with-files/page.mdx (1 hunks)
  • packages/uploadthing/src/_internal/config.ts (1 hunks)
  • packages/uploadthing/src/sdk/index.ts (3 hunks)
  • packages/uploadthing/src/sdk/types.ts (1 hunks)
  • packages/uploadthing/test/__test-helpers.ts (1 hunks)
  • packages/uploadthing/test/sdk.test.ts (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/src/app/(docs)/api-reference/ut-api/page.mdx

[uncategorized] ~467-~467: Possible missing comma found.
Context: ...akes a fetch request to the UploadThing API which incurs redundant latency. Use [`g...

(AI_HYDRA_LEO_MISSING_COMMA)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: typecheck
  • GitHub Check: build
  • GitHub Check: analyze-bundle (current-pr)
  • GitHub Check: e2e-node (backend-adapters)
  • GitHub Check: e2e-node (minimal-pagedir)
  • GitHub Check: lint
  • GitHub Check: e2e-node (minimal-appdir)
  • GitHub Check: build
  • GitHub Check: build
🔇 Additional comments (8)
packages/uploadthing/src/sdk/index.ts (4)

16-20: Imports appear valid and consistently used.

All imported symbols—from generateSignedURL to uploadThingError—are referenced in this file. Good job keeping the dependencies tight and relevant.


22-27: Imports from _internal/config look appropriate.

These new constants (ApiUrl, UfsHost, UPLOADTHING_VERSION, UTToken) are now used throughout the file without redundancy. Everything appears consistent.


446-453: Deprecation notice is clear.

The documentation clearly communicates that getSignedURL will be deprecated. This helps guide users toward the recommended method. Nicely done.


480-480: Verify ufsUrl is consistently returned across the codebase.

Adding ufsUrl to GetSignedUrlResponse is beneficial. Ensure the server always populates it and no code paths return undefined.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for places where GetSignedUrlResponse or 'ufsUrl' is referenced
rg -A 3 'ufsUrl'

Length of output: 16846


Subject: ufsUrl Consistency Verified Across Codebase

The search results confirm that ufsUrl is defined and consistently used in the response schemas, SDK utilities, and throughout the test suite (which validates its format via ufsUrlPattern). There are no indications that any server code paths return undefined for ufsUrl.

  • Confirmed definition in response schemas (e.g., S.String in packages/uploadthing/src/sdk/index.ts and internal types).
  • Consistent usage in client-side and server-side examples.
  • Tests validate ufsUrl with expected URL signature patterns.
docs/src/app/(docs)/concepts/regions-acl/page.mdx (1)

75-77: LGTM! Documentation updated correctly.

The documentation has been updated to reflect the new generateSignedURL method name, maintaining consistency with the API changes.

docs/src/app/(docs)/api-reference/ut-api/page.mdx (1)

1-560: Documentation is well-structured and comprehensive!

The documentation provides clear explanations, helpful code examples, and thorough parameter descriptions for all methods.

🧰 Tools
🪛 LanguageTool

[grammar] ~205-~205: Possible subject-verb agreement error.
Context: ...mUrl` {{ tag: 'method', since: '5.3'}} Have a file hosted somewhere else you want t...

(WH_AUX_SG_NOUN_AGR)


[grammar] ~229-~229: The verb form ‘are’ does not appear to fit in this context.
Context: ...sponse[] ``` ### Parameters The first argument are the URLs of the files you want to uploa...

(SINGULAR_NOUN_VERB_AGREEMENT)


[style] ~229-~229: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ... argument are the URLs of the files you want to upload. They may also be an object with...

(REP_WANT_TO_VB)


[style] ~230-~230: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...bject with a url property in case you want to override the name, or set a `customId...

(REP_WANT_TO_VB)


[typographical] ~308-~308: Do not use a colon (:) before a series that is introduced by a preposition (‘since’). Remove the colon or add a noun or a noun phrase after the preposition.
Context: ...ct ##getFileUrls{{ tag: 'method', since: '4.0', deprecated: true }} getFileUrl...

(RP_COLON)


[uncategorized] ~467-~467: Possible missing comma found.
Context: ...akes a fetch request to the UploadThing API which incurs redundant latency. Use [`g...

(AI_HYDRA_LEO_MISSING_COMMA)

packages/uploadthing/test/__test-helpers.ts (1)

125-126: LGTM!

The ufsUrl property follows the expected format and includes the required signature parameter.

packages/uploadthing/test/sdk.test.ts (1)

378-429: LGTM! Comprehensive test coverage for the new generateSignedURL method.

The test suite thoroughly covers:

  • Basic URL generation
  • Different formats of expiresIn parameter
  • Error handling for invalid inputs
  • Validation of URL format and signature

Comment on lines +58 to +59
[`UTApi.generateSignedURL`](/api-reference/ut-api#get-signed-url). Here's a
reference implementation using Node.js crypto:
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

Fix incorrect API reference link.

The link to the API reference points to #get-signed-url but should point to #generate-signed-url to match the new method name.

-[`UTApi.generateSignedURL`](/api-reference/ut-api#get-signed-url)
+[`UTApi.generateSignedURL`](/api-reference/ut-api#generate-signed-url)
📝 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
[`UTApi.generateSignedURL`](/api-reference/ut-api#get-signed-url). Here's a
reference implementation using Node.js crypto:
[`UTApi.generateSignedURL`](/api-reference/ut-api#generate-signed-url). Here's a
reference implementation using Node.js crypto:

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 (1)
packages/uploadthing/src/sdk/index.ts (1)

477-482: Add JSDoc comments for response fields.

Consider adding JSDoc comments to explain the difference between url and ufsUrl fields for better API documentation.

 class GetSignedUrlResponse extends S.Class<GetSignedUrlResponse>(
   "GetSignedUrlResponse",
 )({
+  /** The legacy signed URL */
   url: S.String,
+  /** The UFS (Unified File Storage) signed URL */
   ufsUrl: S.String,
 }) {}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b0702ac and f249405.

📒 Files selected for processing (2)
  • packages/uploadthing/src/sdk/index.ts (3 hunks)
  • packages/uploadthing/test/__test-helpers.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/uploadthing/test/__test-helpers.ts
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: typecheck
  • GitHub Check: lint
  • GitHub Check: analyze-bundle (current-pr)
  • GitHub Check: build
  • GitHub Check: e2e-node (backend-adapters)
  • GitHub Check: e2e-node (minimal-pagedir)
  • GitHub Check: e2e-node (minimal-appdir)
  • GitHub Check: build
  • GitHub Check: build
🔇 Additional comments (3)
packages/uploadthing/src/sdk/index.ts (3)

16-27: LGTM! Import statements are well-organized.

The new imports are correctly structured and include all necessary dependencies for the URL generation functionality.


388-445: Well-implemented URL generation with proper validation!

The implementation is robust with several notable benefits:

  • Eliminates extra API call for better performance
  • Includes comprehensive validation for the expiresIn parameter
  • Uses proper protocol selection based on environment

447-454: Excellent deprecation notice with clear migration path!

The documentation effectively communicates:

  • The deprecation timeline
  • Performance implications of the old method
  • Clear reference to the new recommended method

juliusmarminge and others added 2 commits February 11, 2025 18:58
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@vercel vercel bot temporarily deployed to Preview – legacy-docs-uploadthing February 11, 2025 18:08 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants