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

fix: updating name does not affect ratelimits #2693

Merged
merged 2 commits into from
Nov 29, 2024

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced test coverage for key updates, ensuring name changes do not affect rate limit settings.
  • Refactor

    • Streamlined the key update logic for improved clarity and maintainability.
    • Simplified handling of identity-related fields (externalId and ownerId).
  • Bug Fixes

    • Maintained consistent error handling for invalid configurations during key updates.

Copy link

vercel bot commented Nov 29, 2024

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 29, 2024 3:15pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 29, 2024 3:15pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 29, 2024 3:15pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 29, 2024 3:15pm

Copy link

changeset-bot bot commented Nov 29, 2024

⚠️ No Changeset found

Latest commit: 6d5fcbb

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 Nov 29, 2024

📝 Walkthrough

Walkthrough

The pull request introduces updates to the key management functionality within the API. It includes a new test suite for verifying that the name update of a key does not alter its rate limit settings. Additionally, the updateKey route has been refactored to improve code maintainability, utilizing a structured changes object for updates. The handling of externalId and ownerId has been streamlined, and error handling remains consistent with previous implementations. Type imports and exports have also been updated for clarity.

Changes

File Path Change Summary
apps/api/src/routes/v1_keys_updateKey.happy.test.ts Added a new test suite "update name" with a test case that verifies the name update of a key does not affect its rate limit configuration.
apps/api/src/routes/v1_keys_updateKey.ts Refactored the updateKey route to use a changes object for updates, simplifying the logic for handling externalId and ownerId. Error handling remains unchanged, and type imports/exports have been updated.

Possibly related PRs

Suggested labels

Feature, 🕹️ oss.gg, :joystick: 50 points

Suggested reviewers

  • perkinsjr
  • mcstepp
  • chronark

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

github-actions bot commented Nov 29, 2024

Thank you for following the naming conventions for pull request titles! 🙏

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

🧹 Outside diff range and nitpick comments (3)
apps/api/src/routes/v1_keys_updateKey.happy.test.ts (1)

1062-1130: Consider adding edge cases to strengthen test coverage.

While the current test effectively covers the basic scenario, consider adding tests for:

  1. Multiple consecutive name updates
  2. Concurrent updates of name and other non-rate-limit fields
  3. Edge cases for name values (empty, very long, special characters)

Example test case:

test("should preserve ratelimit config after multiple name updates", async (t) => {
  // ... setup code ...
  
  // First name update
  await h.post<V1KeysUpdateKeyRequest, V1KeysUpdateKeyResponse>({
    // ... update to "name1" ...
  });
  
  // Second name update
  await h.post<V1KeysUpdateKeyRequest, V1KeysUpdateKeyResponse>({
    // ... update to "name2" ...
  });
  
  // Verify rate limits remained unchanged after multiple updates
  const verify = await h.post<V1KeysVerifyKeyRequest, V1KeysVerifyKeyResponse>({
    // ... verification code ...
  });
  
  expect(verify.body.ratelimit!.limit).toBe(10);
  expect(verify.body.ratelimit!.remaining).toBe(9);
});
apps/api/src/routes/v1_keys_updateKey.ts (2)

375-387: Simplify 'ratelimit' handling by deprecating old fields

The code currently handles both new and deprecated fields within req.ratelimit, such as async, type, limit, refillRate, duration, and refillInterval. This adds complexity and potential for errors. Consider updating the code to handle only the current fields (async, limit, duration), and handle deprecation separately to simplify the logic.

For example:

-if (typeof req.ratelimit !== "undefined") {
-  if (req.ratelimit === null) {
-    changes.ratelimitAsync = null;
-    changes.ratelimitLimit = null;
-    changes.ratelimitDuration = null;
-  } else {
-    changes.ratelimitAsync =
-      typeof req.ratelimit.async === "boolean"
-        ? req.ratelimit.async
-        : req.ratelimit.type === "fast";
-    changes.ratelimitLimit = req.ratelimit.limit ?? req.ratelimit.refillRate;
-    changes.ratelimitDuration = req.ratelimit.duration ?? req.ratelimit.refillInterval;
-  }
+if (req.ratelimit === null) {
+  changes.ratelimitAsync = null;
+  changes.ratelimitLimit = null;
+  changes.ratelimitDuration = null;
+} else if (typeof req.ratelimit !== "undefined") {
+  changes.ratelimitAsync = req.ratelimit.async ?? false;
+  changes.ratelimitLimit = req.ratelimit.limit;
+  changes.ratelimitDuration = req.ratelimit.duration;
+}

Ensure that the deprecated fields are handled appropriately elsewhere if necessary.


381-384: Clarify 'ratelimitAsync' assignment logic

The assignment of changes.ratelimitAsync involves fallback logic between req.ratelimit.async and req.ratelimit.type === "fast". To improve readability and avoid confusion, consider adding comments explaining this logic, especially regarding the use of deprecated fields.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1020546 and 6d5fcbb.

📒 Files selected for processing (2)
  • apps/api/src/routes/v1_keys_updateKey.happy.test.ts (1 hunks)
  • apps/api/src/routes/v1_keys_updateKey.ts (2 hunks)
🔇 Additional comments (6)
apps/api/src/routes/v1_keys_updateKey.happy.test.ts (1)

1062-1130: Well-structured test implementation!

The test suite effectively validates that updating a key's name preserves rate limit settings through:

  • Comprehensive setup with proper permissions
  • Clear separation of concerns (create, update, verify)
  • Thorough assertions on both DB state and API behavior
apps/api/src/routes/v1_keys_updateKey.ts (5)

7-7: Approved: Importing 'Key' type

The addition of the Key type import is appropriate as it's used for typing the changes object later in the code.


343-346: Approved: Initializing 'changes' as Partial

Initializing the changes object with Partial<Key> ensures type safety for the fields being updated.


399-399: Validate default value for 'refillDay'

When setting changes.refillDay, the code defaults to 1 if req.refill.refillDay is undefined. Ensure that this default aligns with business logic, especially since refillDay should only be set when interval is 'monthly'.


405-407: Approved: Conditional database update

Updating the database only when there are changes (Object.keys(changes).length > 0) prevents unnecessary write operations.


385-386: Ensure proper assignment of 'ratelimitLimit' and 'ratelimitDuration'

The use of nullish coalescing with potentially undefined deprecated fields (req.ratelimit.limit ?? req.ratelimit.refillRate and req.ratelimit.duration ?? req.ratelimit.refillInterval) could lead to unintended undefined values. Verify that these assignments always result in valid numbers.

To confirm, you can check all usages of these fields in the codebase:

apps/api/src/routes/v1_keys_updateKey.ts Show resolved Hide resolved
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