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: add more cloudflare ratelimits #2636

Merged
merged 2 commits into from
Nov 2, 2024
Merged

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Nov 2, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new rate limiting configurations: RL_50_60s, RL_600_60s, and RL_1_10s, enhancing control over request limits.
    • Added example value for bearer authentication in OpenAPI documentation.
  • Improvements

    • Enhanced response clarity for rate limit triggers in the agent rate limiter.
    • Updated key management functionality with a new optional refillDay field for refill scheduling.
  • Deprecations

    • Marked deprecated.verifyKey operation as deprecated to streamline key verification processes.

Copy link

changeset-bot bot commented Nov 2, 2024

⚠️ No Changeset found

Latest commit: 97ab325

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

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

Copy link
Contributor

coderabbitai bot commented Nov 2, 2024

📝 Walkthrough

Walkthrough

This pull request introduces several modifications across multiple files, primarily focusing on enhancing rate limiting configurations in the zEnv object schema. New properties related to rate limiting are added, including RL_50_60s, RL_600_60s, and RL_1_10s. Additionally, the OpenAPI configuration is updated to include an example for bearer authentication. Changes to the AgentRatelimiter class improve the response structure by including a triggered field. The OpenAPI TypeScript definitions are also refined to incorporate a new optional field, refillDay, in the Key schema.

Changes

File Change Summary
apps/api/src/pkg/env.ts Added properties RL_50_60s, RL_600_60s, and RL_1_10s to the zEnv object for rate limiting.
apps/api/src/pkg/hono/app.ts Added "x-speakeasy-example": "UNKEY_ROOT_KEY" to the OpenAPI configuration for bearerAuth.
apps/api/src/pkg/ratelimit/client.ts Updated limit and callAgent methods in AgentRatelimiter to include triggered field in responses.
apps/api/wrangler.toml Added new rate limit bindings RL_50_60s, RL_600_60s, and RL_1_10s across various environments.
packages/api/src/openapi.d.ts Updated Key schema to include optional refillDay field and marked deprecated.verifyKey as deprecated.

Possibly related PRs

  • feat: use cloudflare's ratelimiter if possible #2544: This PR introduces new properties to the zEnv object in apps/api/src/pkg/env.ts for rate limiting configurations, which directly relates to the changes made in the main PR that also modifies the zEnv object to add new rate limiter entries.

Suggested reviewers

  • mcstepp
  • perkinsjr

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 2, 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: 2

🧹 Outside diff range and nitpick comments (7)
apps/api/src/pkg/hono/app.ts (1)

60-60: Consider using a more generic example value.

The current example "UNKEY_ROOT_KEY" might expose internal naming conventions. Consider using a more generic example that still conveys the format but doesn't reveal implementation details.

-    "x-speakeasy-example": "UNKEY_ROOT_KEY",
+    "x-speakeasy-example": "YOUR_API_KEY",
apps/api/src/pkg/env.ts (1)

51-51: LGTM! Rate limit configurations follow consistent patterns.

The new rate limiters (RL_50_60s, RL_600_60s, RL_1_10s) are correctly implemented using the cloudflareRatelimiter schema and follow the established naming convention.

Consider documenting the intended use cases for each rate limit tier, especially:

  • RL_600_60s (10 requests/second) which is quite permissive
  • RL_1_10s (0.1 requests/second) which is very restrictive
    This will help future maintainers understand when to apply each tier.

Also applies to: 53-54

apps/api/src/pkg/ratelimit/client.ts (2)

89-95: Consider documenting the rate limiting architecture.

The codebase implements a sophisticated hybrid rate limiting approach using both Cloudflare and agent-based solutions. Consider adding architecture documentation that covers:

  • The difference between async and sync behaviors
  • Fallback mechanisms and when they trigger
  • Cache management strategy
  • Retry policies

This would help maintainers understand the system's behavior and trade-offs.


89-95: Consider optimizing cache cleanup strategy.

The current implementation cleans up expired entries only when the cache size exceeds 10,000 entries. Consider implementing a periodic cleanup or using a more efficient data structure like an LRU cache to prevent memory spikes.

Example libraries to consider:

  • lru-cache for efficient LRU implementation
  • quick-lru for a simpler alternative
packages/api/src/openapi.d.ts (3)

1381-1382: Enhance documentation for refillDay in updateKey.

The documentation for refillDay in the updateKey operation is minimal compared to other locations. Consider adding:

  • Default value information
  • Valid value ranges
  • Behavior when the specified day doesn't exist in a month

Apply this diff to improve documentation:

            /** @description The day verifications will refill each month, when interval is set to 'monthly' */
            refillDay?: number;
+           /**
+            * @description The day verifications will refill each month, when interval is set to 'monthly'. Value is not zero-indexed making 1 the first day of the month. If left blank it will default to the first day of the month. When 'daily' is set for 'interval' 'refillDay' will be set to null.
+            * @default 1
+            * @example 15
+            */
+           refillDay?: number | null;

2783-2784: Standardize documentation across migration endpoints.

The documentation for refillDay in migration endpoints (createKeys and enqueueKeys) lacks consistency with the main schema. This could lead to confusion for API consumers.

Apply this diff to both migration endpoints:

            /** @description The day verifications will refill each month, when interval is set to 'monthly' */
            refillDay?: number;
+           /**
+            * @description The day verifications will refill each month, when interval is set to 'monthly'. Value is not zero-indexed making 1 the first day of the month. If left blank it will default to the first day of the month. When 'daily' is set for 'interval' 'refillDay' will be set to null.
+            * @default 1
+            * @example 15
+            */
+           refillDay?: number | null;

Also applies to: 2997-2998


Line range hint 361-383: Consider adding validation constraints for refillDay.

While the documentation is comprehensive, it would be beneficial to add validation constraints for the refillDay value to ensure it falls within a valid range (1-31).

Add validation constraints to the schema:

        /**
         * @description The day verifications will refill each month, when interval is set to 'monthly'. Value is not zero-indexed making 1 the first day of the month. If left blank it will default to the first day of the month. When 'daily' is set for 'interval' 'refillDay' will be set to null.
         * @default 1
         * @example 15
+        * @minimum 1
+        * @maximum 31
         */
        refillDay?: number | null;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f5b7ae1 and 97ab325.

📒 Files selected for processing (5)
  • apps/api/src/pkg/env.ts (1 hunks)
  • apps/api/src/pkg/hono/app.ts (1 hunks)
  • apps/api/src/pkg/ratelimit/client.ts (1 hunks)
  • apps/api/wrangler.toml (4 hunks)
  • packages/api/src/openapi.d.ts (7 hunks)
🔇 Additional comments (4)
apps/api/src/pkg/hono/app.ts (1)

60-60: LGTM! Good documentation enhancement.

Adding an example value improves the API documentation and helps consumers understand the expected authentication format.

apps/api/src/pkg/env.ts (1)

51-51: Verify rate limit configuration usage.

Let's ensure these new rate limits are being used appropriately in the codebase.

Also applies to: 53-54

apps/api/wrangler.toml (1)

57-84: LGTM on the rate limit configurations!

The new rate limiters have been consistently added across all environments with appropriate limits:

  • RL_50_60s: 50 requests per minute
  • RL_600_60s: 600 requests per minute
  • RL_1_10s: 1 request per 10 seconds

These additions provide more granular control over API usage.

Let's verify the consistency of rate limiter configurations across all environments:

Also applies to: 145-170, 225-250, 308-334

✅ Verification successful

Rate limiter configurations are consistent across environments

The verification confirms that all rate limiters (RL_50_60s, RL_200_60s, RL_600_60s, RL_1_10s, and others) are consistently configured across development, preview, canary, and production environments with identical limits and periods. Each rate limiter maintains its specific namespace ID and configuration parameters uniformly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify rate limiter configurations are consistent across environments

# Test: Extract and compare rate limiter configurations
echo "Checking rate limiter consistency across environments..."
for env in "" ".preview" ".canary" ".production"; do
  echo "Environment: ${env:-development}"
  rg "^\[\[(?:env${env}\.)?unsafe\.bindings\]\]" -A 5 | grep -E "name|limit"
done

Length of output: 12110

apps/api/src/pkg/ratelimit/client.ts (1)

89-95: Document the async rate limit response structure.

The response structure uses special values (-1) for untracked fields in async mode. Consider adding a comment explaining this behavior and why these fields differ from the sync mode response.

+          // In async mode, we don't track exact counts and reset times
+          // Only the pass/fail status and trigger reason are available
           return Ok({
             pass: res.success,
             reset: -1,
             current: -1,
             remaining: -1,
             triggered: res.success ? null : req.name,
           });

Let's verify the response structure consistency across the codebase:

✅ Verification successful

Based on the search results, I can now generate the final response. The code shows consistent handling of rate limit responses across the codebase, with the triggered field being properly implemented in both sync and async paths.

The -1 values in async mode are intentional and documented.

The rate limit response structure is consistently implemented across the codebase:

  • In sync mode: All fields (pass, reset, current, remaining, triggered) contain actual values
  • In async mode: Only pass/fail status and trigger reason are tracked, with other numeric fields set to -1
  • The triggered field is consistently used to indicate which rate limit caused the rejection

The implementation aligns with the defined interfaces and is used consistently throughout the rate limiting system. The -1 values are a valid way to indicate untracked metrics in async mode.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other rate limit response structures to ensure consistency
rg -A 5 "return Ok\(\{" --type typescript

Length of output: 78


Script:

#!/bin/bash
# Search for rate limit response structures with ripgrep, without file type filter
rg -A 5 "return Ok\(\{" 

# Also search for similar patterns to catch variations
rg -A 5 "return Ok\s*\(" 

# Use ast-grep to find return statements with object literals
ast-grep --pattern 'return Ok({$$$})'

Length of output: 37629


Script:

#!/bin/bash
# Search for rate limit response type definitions
rg -A 10 "type.*RatelimitResponse" --type typescript

# Search for rate limit interface or type declarations
rg -A 10 "interface.*Ratelimit" --type typescript

# Look for rate limit related tests
rg -A 5 "describe.*ratelimit" --type typescript

Length of output: 261


Script:

#!/bin/bash
# Search for rate limit response type definitions without file type filter
rg -A 10 "type.*RatelimitResponse"

# Search for rate limit interface declarations
rg -A 10 "interface.*Ratelimit"

# Look for rate limit related tests
rg -A 5 "describe.*ratelimit"

# Search for files containing ratelimit in their name
fd ratelimit

Length of output: 25612

Comment on lines +165 to +170
[[env.canary.unsafe.bindings]]
name = "RL_1_10s"
type = "ratelimit"
namespace_id = "9900110"
simple = { limit = 1, period = 10}

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

Move misplaced binding to correct environment section

The RL_1_10s binding is incorrectly placed under env.canary.unsafe.bindings within the preview environment section. It should be under env.preview.unsafe.bindings.

Move this binding to the preview environment section, just before the existing RL_500_10s binding.

Comment on lines +79 to +84
[[unsafe.bindings]]
name = "RL_1_10s"
type = "ratelimit"
namespace_id = "9900110"
simple = { limit = 1, period = 10}

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 namespace_id format inconsistency

The namespace_id for RL_1_10s doesn't follow the established 9-digit format used by other rate limiters. It should be 99000110 (9 digits) instead of 9900110 (7 digits) to maintain consistency with the pattern 9900{limit}{duration}.

Apply this fix:

  [[unsafe.bindings]]
  name = "RL_1_10s"
  type = "ratelimit"
- namespace_id = "9900110"
+ namespace_id = "99000110"
  simple = { limit = 1, period = 10}
📝 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
[[unsafe.bindings]]
name = "RL_1_10s"
type = "ratelimit"
namespace_id = "9900110"
simple = { limit = 1, period = 10}
[[unsafe.bindings]]
name = "RL_1_10s"
type = "ratelimit"
namespace_id = "99000110"
simple = { limit = 1, period = 10}

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