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: cf cache ratelimits #2112

Merged
merged 14 commits into from
Sep 19, 2024
Merged

fix: cf cache ratelimits #2112

merged 14 commits into from
Sep 19, 2024

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Sep 18, 2024

  • fix: default ratelimits
  • revert
  • fix: cache ratelimits on cloudflare correctly

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive test suites for validating rate limits on identities and API keys.
    • Added a new package to simulate high-frequency request scenarios for testing.
  • Bug Fixes

    • Adjusted lower limit calculations in rate limit accuracy tests to allow for broader acceptance of results.
  • Chores

    • Improved logging practices by modifying verbosity levels and removing unnecessary output.
  • Refactor

    • Enhanced the caching mechanism in the rate limiter to track blocked requests more effectively.
    • Streamlined timestamp management for isolate creation to ensure consistency.

Copy link

vercel bot commented Sep 18, 2024

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

Name Status Preview Comments Updated (UTC)
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 19, 2024 1:28pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 19, 2024 1:28pm
3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
dashboard ⬜️ Ignored (Inspect) Visit Preview Sep 19, 2024 1:28pm
planetfall ⬜️ Ignored (Inspect) Visit Preview Sep 19, 2024 1:28pm
workflows ⬜️ Ignored (Inspect) Visit Preview Sep 19, 2024 1:28pm

Copy link

changeset-bot bot commented Sep 18, 2024

⚠️ No Changeset found

Latest commit: d79b641

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

Warning

Rate limit exceeded

@chronark has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 48 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

Files that changed from the base of the PR and between 5036426 and d79b641.

Walkthrough

Walkthrough

The changes encompass the addition of new test files for validating rate limits on identities and API keys within the Unkey SDK. Modifications were made to logging behaviors in various components, including the circuit breaker and event router services. Enhancements to the caching mechanism in the rate limiter class were implemented, alongside adjustments to the calculation of acceptable limits in existing tests. These updates aim to refine the accuracy and reliability of rate limiting functionality across the system.

Changes

File Path Change Summary
apps/agent/integration/identities/identities_ratelimits_accuracy_test.go Added a test suite for validating rate limits on identities, simulating high-frequency requests and asserting success rates against defined limits.
apps/agent/integration/keys/ratelimits_test.go Introduced integration tests for API key rate limiting, validating accuracy through simulated requests and assertions on success rates.
apps/agent/pkg/circuitbreaker/lib.go Changed logging level from Info to Debug in the preflight function to reduce log verbosity during normal operation.
apps/agent/pkg/clickhouse/flush.go Removed a debug print statement to clean up console output during row processing in the flush function.
apps/agent/pkg/testutil/attack.go Introduced a new package for simulating high-frequency function calls, including the Attack function and Rate struct for managing execution rates.
apps/agent/services/eventrouter/service.go Removed a log statement related to key verification events, potentially affecting visibility during runtime.
apps/api/src/pkg/middleware/init.ts Added a variable to store the timestamp of isolate creation, ensuring consistency across calls to the init function.
apps/api/src/pkg/middleware/metrics.ts Removed commented-out logging code and simplified the calculation of isolateLifetime.
apps/api/src/pkg/ratelimit/client.ts Enhanced the caching mechanism in the AgentRatelimiter class by adding a blocked property to cache entries, modifying related methods accordingly.
apps/api/src/routes/v1_keys_verifyKey.ratelimit_accuracy.test.ts Updated the lowerLimit calculation in a test case to 95% of the exactLimit, increasing the threshold for acceptable values in assertions.
apps/api/src/routes/v1_ratelimit_limit.accuracy.test.ts Similar update to the lowerLimit calculation as in the previous test file, adjusting the threshold for the pass/fail criteria.

Possibly related PRs

  • fix: default ratelimits #2103: The changes in this PR involve modifications to rate limit handling in the KeyService class, which is directly related to the rate limiting functionality being tested in the main PR's new test suite for identities.

Suggested reviewers

  • perkinsjr
  • jdoe
  • smith

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

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

@chronark chronark marked this pull request as ready for review September 19, 2024 13:11
@chronark chronark changed the title cf cache ratelimits fix: cf cache ratelimits Sep 19, 2024
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: 8

Outside diff range and nitpick comments (3)
apps/agent/integration/keys/ratelimits_test.go (2)

45-46: Optimize Test Duration for CI Efficiency

The test durations of 1 minute and 5 minutes can significantly lengthen the CI pipeline. Consider reducing the testDuration or implementing mock rate limits to simulate the desired conditions more efficiently.

Also applies to: 49-50


81-83: Improve Variable Naming for Clarity

Renaming variables total and passed to totalRequests and successfulRequests enhances readability and better reflects their purpose.

Apply this diff for clearer naming:

-total := 0
-passed := 0
+totalRequests := 0
+successfulRequests := 0

...

-for valid := range results {
-    total++
-    if valid {
-        passed++
+for isValid := range results {
+    totalRequests++
+    if isValid {
+        successfulRequests++
     }
 }

...

 t.Logf("Total: %d, Passed: %d, lowerLimit: %d, exactLimit: %d, upperLimit: %d", total, passed, lowerLimit, exactLimit, upperLimit)
+// Update log statement with new variable names
+t.Logf("Total: %d, Passed: %d, lowerLimit: %d, exactLimit: %d, upperLimit: %d", totalRequests, successfulRequests, lowerLimit, exactLimit, upperLimit)

...

-require.GreaterOrEqual(t, passed, lowerLimit)
-require.LessOrEqual(t, passed, upperLimit)
+require.GreaterOrEqual(t, successfulRequests, lowerLimit)
+require.LessOrEqual(t, successfulRequests, upperLimit)

Also applies to: 99-106

apps/agent/integration/identities/identities_ratelimits_accuracy_test.go (1)

39-39: Review commented-out test cases for multiple keys

At line 39, the loop over nKeys only includes [1], with other values commented out (//, 3, 10, 1000}). If you intend to test with multiple keys, consider uncommenting these values to include them in the test. If they are not needed, removing them can clean up the code.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 071f461 and a43b948.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (11)
  • apps/agent/integration/identities/identities_ratelimits_accuracy_test.go (1 hunks)
  • apps/agent/integration/keys/ratelimits_test.go (1 hunks)
  • apps/agent/pkg/circuitbreaker/lib.go (1 hunks)
  • apps/agent/pkg/clickhouse/flush.go (0 hunks)
  • apps/agent/pkg/testutil/attack.go (1 hunks)
  • apps/agent/services/eventrouter/service.go (0 hunks)
  • apps/api/src/pkg/middleware/init.ts (2 hunks)
  • apps/api/src/pkg/middleware/metrics.ts (1 hunks)
  • apps/api/src/pkg/ratelimit/client.ts (7 hunks)
  • apps/api/src/routes/v1_keys_verifyKey.ratelimit_accuracy.test.ts (1 hunks)
  • apps/api/src/routes/v1_ratelimit_limit.accuracy.test.ts (1 hunks)
Files not reviewed due to no reviewable changes (2)
  • apps/agent/pkg/clickhouse/flush.go
  • apps/agent/services/eventrouter/service.go
Files skipped from review due to trivial changes (2)
  • apps/agent/pkg/circuitbreaker/lib.go
  • apps/api/src/pkg/middleware/metrics.ts
Additional comments not posted (14)
apps/agent/pkg/testutil/attack.go (3)

10-13: LGTM!

The Rate struct is well-defined with clear and self-explanatory field names. The Freq field represents the frequency of function calls, and the Per field represents the time period over which the function calls should occur.


15-17: LGTM!

The String() method provides a clear and concise string representation of the Rate struct by including both the Freq and Per fields. The use of fmt.Sprintf is appropriate for formatting the string.


24-69: LGTM!

The Attack function is well-implemented and suitable for performance testing or stress testing scenarios. The use of goroutines and channels for concurrent execution is appropriate and efficient. The function signature is well-defined and uses generics to allow for any response type. The use of a wait group to track the completion of all function calls is a good practice. The logging statements provide useful information about the execution state.

apps/api/src/routes/v1_keys_verifyKey.ratelimit_accuracy.test.ts (1)

97-97: Consider the impact on test sensitivity.

The change increases the lower limit from 75% to 95% of the exact limit. This means the test will now permit a slightly higher number of passed results before failing.

While this allows for some margin to account for rate limit variations, it's important to ensure that the test remains effective at catching rate limit violations that are close to the exact limit.

Please consider the trade-off between allowing some leniency and maintaining the test's ability to identify violations. If the increased tolerance is acceptable based on the specific requirements and expected behavior of the rate limiting functionality being tested, then this change should be good to merge.

apps/api/src/routes/v1_ratelimit_limit.accuracy.test.ts (1)

100-100: Verify the reasoning behind the change in the lower limit calculation.

The change in the calculation of the lowerLimit from 75% to 95% of the exactLimit may affect the pass/fail criteria of the tests, potentially making them more lenient.

Please ensure that the new lower limit still provides an adequate level of accuracy and effectiveness in testing the rate limiting functionality. Consider providing additional context or justification for this change to ensure it aligns with the expected behavior of the rate limiting functionality.

apps/api/src/pkg/middleware/init.ts (1)

40-44: LGTM!

The changes ensure that the isolateCreatedAt value is initialized only once with the current timestamp when it is undefined. This fixes the issue where the timestamp was being reset with each invocation of the init function.

The benefits of this fix include:

  • Preserving the original creation timestamp of the isolate across subsequent requests.
  • Ensuring consistency of the isolateCreatedAt value for the same isolate.
  • Improving the reliability of the timestamp for tracking and debugging purposes.

Setting the isolateCreatedAt value in the context object makes it accessible to other parts of the application.

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

17-17: LGTM!

The addition of the blocked property to the cache entry type aligns with the PR objective and enhances the caching mechanism to track blocked requests.


23-23: Looks good!

The constructor has been updated to accept a cache with the new cache entry type, ensuring consistency with the blocked property addition.


38-38: Nice refactor!

The method rename and the addition of the blocked parameter improve the clarity and functionality of the cache setting method.


58-58: LGTM!

Setting the cache with the updated structure, including the blocked property, ensures that the cache accurately reflects the state of the rate limiter.


126-126: Looks good!

The default value for cached has been updated to include the blocked property, ensuring consistency with the updated cache entry type.


Line range hint 127-134: Great optimization!

Checking the blocked state early and returning a blocked response if true allows the system to bypass further processing for already blocked requests. This optimization can lead to more efficient request handling.


173-173: LGTM!

Updating the cache with the correct blocked state based on the rate limiting results ensures that the cache accurately reflects the state of the requests. Setting blocked to !res.val.pass and explicitly setting it to false when necessary maintains the integrity of the cache.

Also applies to: 184-184, 207-207

apps/agent/integration/keys/ratelimits_test.go (1)

34-36: Remove Redundant Check for Empty baseURL

Since UNKEY_BASE_URL is already required to be set and not empty (line 28), the condition if baseURL != "" is unnecessary. You can simplify the code by directly appending the WithServerURL option.

Apply this diff to streamline the code:

 if baseURL != "" {
     options = append(options, unkey.WithServerURL(baseURL))
 }
+// Since baseURL is guaranteed to be non-empty, the check is redundant.
+options = append(options, unkey.WithServerURL(baseURL))

Likely invalid or redundant comment.

Copy link
Collaborator

@perkinsjr perkinsjr left a comment

Choose a reason for hiding this comment

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

image

@chronark chronark added this pull request to the merge queue Sep 19, 2024
Merged via the queue into main with commit fe03252 Sep 19, 2024
25 checks passed
@chronark chronark deleted the cf-cache-ratelimits branch September 19, 2024 14:03
harshsbhat pushed a commit to harshsbhat/unkey that referenced this pull request Sep 19, 2024
* fix: default ratelimits

* revert

* fix: cache ratelimits on cloudflare correctly

* chore: remove logs

* chore: remove log

* perf: remove unnecessary switch

* fix: track isolate start time

* test: tighten lower ratelimit threshold

* fix: only cache ratelimit blocks

* chore: sync lockfile

* test: improve accuracy of lower limit calculation in rate limit tests

* fix: address rabbit suggestions
harshsbhat pushed a commit to harshsbhat/unkey that referenced this pull request Oct 3, 2024
* fix: default ratelimits

* revert

* fix: cache ratelimits on cloudflare correctly

* chore: remove logs

* chore: remove log

* perf: remove unnecessary switch

* fix: track isolate start time

* test: tighten lower ratelimit threshold

* fix: only cache ratelimit blocks

* chore: sync lockfile

* test: improve accuracy of lower limit calculation in rate limit tests

* fix: address rabbit suggestions
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