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

perf(arns): cache resolution for non-existent name #208

Merged
merged 1 commit into from
Sep 20, 2024

Conversation

djwhitt
Copy link
Collaborator

@djwhitt djwhitt commented Sep 20, 2024

Without this it's easy for non-existent names to DOS the CUs we're using to resolve names. This change caches non-existent name resolutions for 5 minutes in the in-memory/Redis cache.

Copy link
Contributor

coderabbitai bot commented Sep 20, 2024

Warning

Rate limit exceeded

@djwhitt has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 27 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 3754d37 and 8a92d91.

Walkthrough

Walkthrough

The pull request includes modifications to the CompositeArNSResolver and OnDemandArNSResolver classes to enhance functionality and error handling. Additionally, new interfaces for name resolution outcomes have been introduced in the types.d.ts file, allowing for improved error management and resolution states.

Changes

File Change Summary
src/resolution/composite-arns-resolver.ts, src/resolution/on-demand-arns-resolver.ts Updated the CompositeArNSResolver class by correcting a comment typo and modifying the condition for validating resolutions. Enhanced the OnDemandArNSResolver class's error handling to return structured objects instead of throwing errors and added a comment regarding a future method replacement.
src/types.d.ts Introduced new interfaces MissingNameResolution and FailedNameResolution, and updated the NameResolution type to include these interfaces for better handling of resolution outcomes.

Possibly related PRs

Suggested reviewers

  • karlprieb

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

codecov bot commented Sep 20, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 70.13%. Comparing base (51b6748) to head (5ea9906).
Report is 4 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop     #208   +/-   ##
========================================
  Coverage    70.13%   70.13%           
========================================
  Files           32       32           
  Lines         7834     7834           
  Branches       429      429           
========================================
  Hits          5494     5494           
  Misses        2340     2340           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (2)
src/resolution/on-demand-arns-resolver.ts (2)

70-70: Acknowledged the TODO comment.

The comment indicates a future plan to replace the getArNSRecord method with getRecords. This is a valid TODO and does not affect the current functionality.

Let me know if you need any assistance with this future improvement or want me to open a GitHub issue to track this task.


94-105: Changes align with the PR objectives and improve resilience against DoS attacks.

The updated error handling logic returns a structured object with default values when the arnsRecord is undefined, null, or its processId is undefined. This change provides a consistent response format for non-existent names and prevents the method from throwing errors and terminating execution.

The caching of non-existent name resolutions for 5 minutes, as indicated by the hardcoded ttl value of 300 seconds, reduces the load on the system and improves performance by avoiding unnecessary processing of repeated invalid requests. This aligns with the PR objectives of enhancing the system's resilience against DoS attacks.

Consider making the ttl value configurable for flexibility. This can be done by introducing a new configuration variable in the config.js file and using that variable instead of the hardcoded value. For example:

import * as config from '../config.js';

// ...

return {
  name,
  resolvedId: undefined,
  resolvedAt: Date.now(),
  ttl: config.ARNS_NON_EXISTENT_NAME_CACHE_TTL,
  processId: undefined,
};

In the config.js file:

export const ARNS_NON_EXISTENT_NAME_CACHE_TTL = 300; // 5 minutes
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 878fde0 and 5ea9906.

Files selected for processing (3)
  • src/resolution/composite-arns-resolver.ts (2 hunks)
  • src/resolution/on-demand-arns-resolver.ts (2 hunks)
  • src/types.d.ts (1 hunks)
Additional comments not posted (3)
src/resolution/composite-arns-resolver.ts (2)

52-52: LGTM!

The comment provides useful context about the purpose of the cachedResolution variable.


74-74: Verify the impact of the change in the if condition.

The if condition has been changed from checking resolution.resolvedId to checking resolution.resolvedAt. This change may alter the logic flow related to caching and logging resolved names.

Please ensure that this change aligns with the expected behavior and does not introduce any unintended consequences. Consider the following:

  • What is the purpose of checking resolution.resolvedAt instead of resolution.resolvedId?
  • How does this change affect the determination of a valid resolution?
  • Are there any other parts of the codebase that rely on the previous behavior of checking resolution.resolvedId?

To help verify the impact, you can run the following script to search for other occurrences of resolution.resolvedId and resolution.resolvedAt in the codebase:

Review the search results to ensure that the change in the if condition is consistent with the usage of resolution.resolvedId and resolution.resolvedAt throughout the codebase.

Verification successful

This script uses multiple methods to search for the relevant terms, which should provide us with the necessary information to verify the impact of the change, even if one method fails.


Verification confirms the change is consistent and purposeful.

The change from checking resolution.resolvedId to resolution.resolvedAt in the composite-arns-resolver.ts file is verified to be consistent with the usage of these properties throughout the codebase. This modification serves to improve the precision of cache validation:

  • resolvedAt is a timestamp that allows for more accurate determination of cache validity based on time elapsed.
  • The change aligns with the existing pattern of using both resolvedId and resolvedAt in resolution objects across various files.
  • No inconsistencies or unintended consequences were found as a result of this change.

The updated condition enhances the caching mechanism by using a time-based approach, which is generally more reliable for determining the freshness of cached data compared to using only the resolvedId.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for occurrences of `resolution.resolvedId` and `resolution.resolvedAt` in the codebase.

# Test 1: Search for occurrences of `resolution.resolvedId`.
rg --type typescript $'resolution\.resolvedId'

# Test 2: Search for occurrences of `resolution.resolvedAt`.
rg --type typescript $'resolution\.resolvedAt'

Length of output: 165


Script:

#!/bin/bash
# Description: Search for occurrences of `resolvedId` and `resolvedAt` in the codebase using multiple methods.

# Method 1: Use rg without specifying file type
echo "=== Method 1: Using rg without file type specification ==="
echo "Searching for 'resolvedId':"
rg 'resolvedId'
echo -e "\nSearching for 'resolvedAt':"
rg 'resolvedAt'

# Method 2: Use fd to find TypeScript files and xargs with grep
echo -e "\n=== Method 2: Using fd and grep ==="
echo "Searching for 'resolvedId':"
fd -e ts -e tsx | xargs grep -n 'resolvedId'
echo -e "\nSearching for 'resolvedAt':"
fd -e ts -e tsx | xargs grep -n 'resolvedAt'

# Method 3: Search for 'resolvedAt' property in general
echo -e "\n=== Method 3: Searching for 'resolvedAt' property ==="
rg '\.resolvedAt'

Length of output: 9747

src/types.d.ts (1)

617-620: Ensure consistent typing across NameResolution union type

With the addition of MissingNameResolution and FailedNameResolution to the NameResolution type, ensure that all interfaces in the union have consistent property definitions. Using optional properties allows for better type safety and cleaner code when handling different resolution states.

Comment on lines +608 to 615
// An error occured while resolving the name
export interface FailedNameResolution {
name: string;
resolvedId: undefined;
resolvedAt: undefined;
ttl: undefined;
processId: undefined;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct typo in comment and use optional properties in FailedNameResolution

  • The comment on line 608 has a typo: "occured" should be "occurred".
  • Similar to the previous interface, consider using optional properties instead of assigning undefined to the properties.

Here is the suggested diff:

-// An error occured while resolving the name
+// An error occurred while resolving the name
 export interface FailedNameResolution {
   name: string;
-  resolvedId: undefined;
-  resolvedAt: undefined;
-  ttl: undefined;
-  processId: undefined;
+  resolvedId?: string;
+  resolvedAt?: number;
+  ttl?: number;
+  processId?: string;
 }
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
// An error occured while resolving the name
export interface FailedNameResolution {
name: string;
resolvedId: undefined;
resolvedAt: undefined;
ttl: undefined;
processId: undefined;
}
// An error occurred while resolving the name
export interface FailedNameResolution {
name: string;
resolvedId?: string;
resolvedAt?: number;
ttl?: number;
processId?: string;
}

Comment on lines +599 to +606
// Name resolved, but is missing
export interface MissingNameResolution {
name: string;
resolvedId: undefined;
resolvedAt: number;
ttl: number;
processId: undefined;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Typo in comment and suggest using optional properties for better TypeScript practices

  • There's a typo in the comment on line 599: "occured" should be "occurred".
  • Instead of assigning properties to undefined, consider making these properties optional using ?, which is more idiomatic in TypeScript.

Apply this diff to correct the typo and update the interface:

-// Name resolved, but is missing
+// Name resolved, but is missing details
 export interface MissingNameResolution {
   name: string;
-  resolvedId: undefined;
+  resolvedId?: string;
   resolvedAt: number;
   ttl: number;
-  processId: undefined;
+  processId?: string;
 }
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
// Name resolved, but is missing
export interface MissingNameResolution {
name: string;
resolvedId: undefined;
resolvedAt: number;
ttl: number;
processId: undefined;
}
// Name resolved, but is missing details
export interface MissingNameResolution {
name: string;
resolvedId?: string;
resolvedAt: number;
ttl: number;
processId?: string;
}

if (arnsRecord === undefined || arnsRecord.processId === undefined) {
throw new Error('Invalid name, arns record not found');
if (
arnsRecord === undefined ||
Copy link
Contributor

Choose a reason for hiding this comment

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

Keep throwing on arnsRecord === undefined

@djwhitt djwhitt force-pushed the cache-non-existent-name-resolutions branch from 5ea9906 to 3754d37 Compare September 20, 2024 20:56
Without this it's easy for non-existent names to DOS the CUs we're using
to resolve names. This change caches non-existent name resolutions for 5
minutes in the in-memory/Redis cache.
@djwhitt djwhitt force-pushed the cache-non-existent-name-resolutions branch from 3754d37 to 8a92d91 Compare September 20, 2024 21:00
@djwhitt djwhitt merged commit 84583b2 into develop Sep 20, 2024
2 of 4 checks passed
@djwhitt djwhitt deleted the cache-non-existent-name-resolutions branch September 20, 2024 21:02
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