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: override methods in sdk #2668

Merged
merged 2 commits into from
Nov 25, 2024
Merged

feat: override methods in sdk #2668

merged 2 commits into from
Nov 25, 2024

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Nov 18, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a ratelimit override API, allowing users to adjust rate limits under specific conditions.
  • Improvements

    • Enhanced the clarity and readability of response structures in the verification process.
    • Reformatted API type definitions for better maintainability and understanding.
    • Streamlined error handling and response messages for loading keys by keyId and ownerId.

These updates aim to enhance user experience and streamline API interactions.

Copy link

changeset-bot bot commented Nov 18, 2024

🦋 Changeset detected

Latest commit: a92f1d7

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

This PR includes changesets to release 6 packages
Name Type
@unkey/api Minor
@unkey/hono Patch
@unkey/nextjs Patch
@unkey/ratelimit Patch
planetfall Patch
@unkey/dashboard Patch

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

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces a ratelimit override API within the "@unkey/api" package, allowing users to adjust rate limits under certain conditions. Additionally, modifications are made to the getVerifications route to enhance response data structure and error handling. Changes to the UnkeyOptions and Result types in the client file improve clarity and maintainability. The TypeScript definitions in openapi.d.ts are also reformatted for better readability, without introducing new functionality.

Changes

File Path Change Summary
.changeset/wild-spies-punch.md Introduced a ratelimit override API in the "@unkey/api" package.
apps/api/src/routes/v1_keys_getVerifications.ts Modified getVerifications route to improve JSON response formatting, streamlined error handling, and updated exported types and functions.
packages/api/src/client.ts Reformatted UnkeyOptions and Result types for clarity, reintroduced methods related to rate limits (getOverride, listOverrides, setOverride, deleteOverride), and updated method signatures for consistency.
packages/api/src/openapi.d.ts Updated TypeScript definitions for clarity, including changes to XOR, OneOf, and various request body structures, while enhancing readability without adding new functionality.

Possibly related PRs

Suggested labels

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

Suggested reviewers

  • mcstepp
  • perkinsjr
  • MichaelUnkey

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 18, 2024

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

Copy link

vercel bot commented Nov 18, 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 25, 2024 5:40pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 5:40pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 5:40pm
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 5:40pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 5:40pm

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

🧹 Outside diff range and nitpick comments (1)
.changeset/wild-spies-punch.md (1)

4-5: Enhance the changeset description for better changelog clarity.

The current description is too brief. Consider expanding it to include:

  • What the ratelimit override API does
  • Key features or capabilities
  • Basic usage example
  • Any important considerations

Example:

-Add ratelimit override API
+Add ratelimit override API to dynamically adjust rate limits
+
+- Introduces new methods: getOverride, listOverrides, setOverride, deleteOverride
+- Allows dynamic adjustment of rate limits under specific conditions
+- Includes validation and error handling for override operations
+- Example: await client.setOverride({ ... })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e97c730 and a92f1d7.

📒 Files selected for processing (4)
  • .changeset/wild-spies-punch.md (1 hunks)
  • apps/api/src/routes/v1_keys_getVerifications.ts (2 hunks)
  • packages/api/src/client.ts (3 hunks)
  • packages/api/src/openapi.d.ts (35 hunks)
🧰 Additional context used
🪛 Biome
apps/api/src/routes/v1_keys_getVerifications.ts

[error] 253-253: Expected a default, or a case but instead found 'verifications'.

Expected a default, or a case here.

(parse)


[error] 255-256: Expected a statement but instead found 'case "RATE_LIMITED":
verifications[d.time].rateLimited += d.count'.

Expected a statement here.

(parse)


[error] 258-259: Expected a statement but instead found 'case "USAGE_EXCEEDED":
verifications[d.time].usageExceeded += d.count'.

Expected a statement here.

(parse)


[error] 264-265: expected , but instead found return

Remove return

(parse)


[error] 256-257: This code is unreachable

... because this statement will break the flow of the code beforehand

(lint/correctness/noUnreachable)


[error] 259-260: This code is unreachable

... because this statement will break the flow of the code beforehand

(lint/correctness/noUnreachable)

🔇 Additional comments (10)
apps/api/src/routes/v1_keys_getVerifications.ts (2)

119-122: LGTM: Identity data structure is well-formed

The identity object structure is clean and properly typed.


265-274: LGTM: Response formatting is clean and type-safe

The response structure is well-formatted and maintains type safety through proper parsing of time values and consistent object structure.

packages/api/src/client.ts (4)

9-27: LGTM! Well-structured type definition with clear documentation.

The UnkeyOptions type effectively uses TypeScript's discriminated unions with the never type to ensure mutually exclusive options. The documentation clearly explains the deprecation of token in favor of rootKey.


80-90: LGTM! Clear separation of GET and POST request types.

The ApiRequest type union provides good type safety by ensuring GET requests can't have a body and POST requests can't have query parameters.


94-105: LGTM! Well-defined Result type with explicit error handling.

The Result type effectively uses discriminated unions to ensure type safety between success and error cases. The error structure is comprehensive with all necessary fields.


379-432: LGTM! Well-implemented rate limit override methods.

The new rate limit override methods are well-structured and consistent with the existing codebase patterns. They properly leverage:

  • Type safety through OpenAPI types
  • Consistent error handling
  • Proper HTTP method usage
  • Common fetch implementation with retry logic

However, let's verify the OpenAPI types are properly defined for these new endpoints.

✅ Verification successful

OpenAPI types and routes are properly defined and consistent

The verification confirms that:

  • All four rate limit override endpoints have proper OpenAPI route definitions
  • The endpoints use consistent authentication with bearerAuth
  • Input validation is implemented using Zod schemas
  • The types in the client match the route definitions
  • Request/response schemas are properly defined with appropriate content types

The implementation is type-safe and follows the API's established patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify OpenAPI types for new rate limit override endpoints

# Check if the OpenAPI types exist for all new endpoints
rg -A 2 '"\/v1\/ratelimits\.(get|list|set|delete)Override"' --type ts

Length of output: 188


Script:

#!/bin/bash
# Description: Verify OpenAPI types for new rate limit override endpoints with corrected regex

# Check if the OpenAPI types exist for all new endpoints
rg -A 2 '/v1/ratelimits\.(get|list|set|delete)Override' --type ts

Length of output: 10912


Script:

#!/bin/bash
# Let's verify the OpenAPI route definitions for these endpoints

# Check route definitions
rg -A 10 'path: "/v1/ratelimits\.(get|list|set|delete)Override",' --type ts

Length of output: 2872

packages/api/src/openapi.d.ts (4)

9-10: LGTM: Type helper improvements

The parentheses addition in the XOR type and the recursive OneOf implementation improve type safety and readability.


533-533: LGTM: Enhanced verification status codes

The expanded set of verification status codes provides more granular error reporting, particularly for authorization and permission-related scenarios.


559-563: LGTM: Improved permission query formatting

The reformatted PermissionQuery type enhances readability while maintaining the same logical structure.


Line range hint 2673-2882: LGTM: Well-structured migration endpoints

The new migration endpoints provide comprehensive functionality for batch operations with proper validation and configuration options. The documentation is thorough and includes all necessary parameters.

Comment on lines +252 to +260
// case "VALID":
verifications[d.time].success += d.count;
break;
break;
case "RATE_LIMITED":
verifications[d.time].rateLimited += d.count;
break;
verifications[d.time].rateLimited += d.count;
break;
case "USAGE_EXCEEDED":
verifications[d.time].usageExceeded += d.count;
break;
verifications[d.time].usageExceeded += d.count;
break;
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 broken switch statement syntax and logic

There are several critical issues in the switch statement:

  1. The syntax is incorrect, leading to parsing errors
  2. The "VALID" case is commented out, which means successful verifications aren't being counted
  3. The break statements are unreachable due to incorrect structure

Apply this fix to restore proper functionality:

        switch (d.outcome) {
-          // case "VALID":
-            verifications[d.time].success += d.count;
-        break;
-          case "RATE_LIMITED":
-verifications[d.time].rateLimited += d.count;
-break;
-          case "USAGE_EXCEEDED":
-verifications[d.time].usageExceeded += d.count;
-break;
+          case "VALID":
+            verifications[d.time].success += d.count;
+            break;
+          case "RATE_LIMITED":
+            verifications[d.time].rateLimited += d.count;
+            break;
+          case "USAGE_EXCEEDED":
+            verifications[d.time].usageExceeded += d.count;
+            break;
+          default:
+            logger.warn(`Unknown verification outcome: ${d.outcome}`);
        }
📝 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
// case "VALID":
verifications[d.time].success += d.count;
break;
break;
case "RATE_LIMITED":
verifications[d.time].rateLimited += d.count;
break;
verifications[d.time].rateLimited += d.count;
break;
case "USAGE_EXCEEDED":
verifications[d.time].usageExceeded += d.count;
break;
verifications[d.time].usageExceeded += d.count;
break;
switch (d.outcome) {
case "VALID":
verifications[d.time].success += d.count;
break;
case "RATE_LIMITED":
verifications[d.time].rateLimited += d.count;
break;
case "USAGE_EXCEEDED":
verifications[d.time].usageExceeded += d.count;
break;
default:
logger.warn(`Unknown verification outcome: ${d.outcome}`);
}
🧰 Tools
🪛 Biome

[error] 253-253: Expected a default, or a case but instead found 'verifications'.

Expected a default, or a case here.

(parse)


[error] 255-256: Expected a statement but instead found 'case "RATE_LIMITED":
verifications[d.time].rateLimited += d.count'.

Expected a statement here.

(parse)


[error] 258-259: Expected a statement but instead found 'case "USAGE_EXCEEDED":
verifications[d.time].usageExceeded += d.count'.

Expected a statement here.

(parse)


[error] 256-257: This code is unreachable

... because this statement will break the flow of the code beforehand

(lint/correctness/noUnreachable)


[error] 259-260: This code is unreachable

... because this statement will break the flow of the code beforehand

(lint/correctness/noUnreachable)

@@ -249,27 +249,27 @@
verifications[d.time] = { success: 0, rateLimited: 0, usageExceeded: 0 };
}
switch (d.outcome) {
case "VALID":
// case "VALID":
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the git history and code context, I can now provide a final response:

Commenting out "VALID" case appears to be unintentional

The change was introduced in commit a92f1d7 "feat: override methods in sdk" but seems to be an accidental formatting change rather than an intentional feature modification because:

  • The code still increments the success counter (verifications[d.time].success += d.count)
  • The case is only commented out, not properly removed
  • Other verification types (RATE_LIMITED, USAGE_EXCEEDED) remain active
  • The change appears alongside formatting-only modifications in the commit

This should be fixed by uncommenting the "VALID" case to maintain proper verification counting.

🔗 Analysis chain

Verify the intent of commenting out the "VALID" case

The "VALID" case has been commented out, which means successful verifications are not being counted. Is this intentional and related to the rate limit override API changes mentioned in the PR objectives?


Let me gather more context about this specific file and the changes around this code section.


Let me try one more verification to understand if this is part of recent changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related changes in verification handling
rg -A 5 "case \"VALID\"" 

Length of output: 2152


Script:

#!/bin/bash
# Get the full context of the verification handling in this file
rg -B 10 -A 10 "case \"VALID\"" apps/api/src/routes/v1_keys_getVerifications.ts

# Check git history for this specific line
git log -L '/case "VALID":/apps/api/src/routes/v1_keys_getVerifications.ts'

Length of output: 922


Script:

#!/bin/bash
# Check recent commits that modified this file
git log --patch apps/api/src/routes/v1_keys_getVerifications.ts

# Also check if there are any related test files
fd "v1_keys_getVerifications" --type f

Length of output: 14265

Comment on lines +608 to +622
/**
* @description The name of the ratelimit.
* @example tokens
*/
name: string;
/**
* @description Optionally override how expensive this operation is and how many tokens are deducted from the current limit.
* @default 1
*/
cost?: number;
/** @description Optionally override the limit. */
limit?: number;
/** @description Optionally override the ratelimit window duration. */
duration?: number;
}[];
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the search results, I can now generate the final response as we have comprehensive information about the usage of deprecated rate limit properties across the codebase.

Migration required for rate limit configuration changes

Several files need updates to handle the rate limit property changes:

  • apps/api/src/routes/v1_keys_*.ts: Update rate limit handling to use new async property instead of type: "fast" and consolidate refillRate/refillInterval to limit/duration
  • apps/dashboard/lib/zod-helper.ts: Remove or update the deprecated rate limit type enum
  • apps/api/src/benchmarks/ratelimit_latency.test.ts: Update test configuration to use new properties
  • apps/api/src/routes/legacy_*.ts: Legacy routes need to be updated or marked for deprecation
🔗 Analysis chain

Verify rate limit property migrations

The rate limit configuration has significant changes:

  • New async property for controlling rate limit behavior
  • Deprecation of type, refillRate, and refillInterval properties
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for usage of deprecated rate limit properties
echo "Checking for usage of deprecated rate limit properties..."
rg -A 2 'type.*fast|type.*consistent|refillRate|refillInterval' --type ts

# Look for existing rate limit configurations that need migration
echo "Checking for rate limit configurations that need updating..."
ast-grep --pattern 'ratelimit: {
  $$$
}'

Length of output: 24744

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.

1 participant