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: filter unaccessible endpoints #1678

Merged
merged 2 commits into from
Nov 30, 2024
Merged

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Nov 27, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced endpoint filtering to exclude specific WebSocket patterns and rate-limited endpoints.
    • Improved error handling and logging in connection management.
  • Bug Fixes

    • Refined logic for establishing connections to ensure only valid endpoints are processed.
  • Documentation

    • Updated method signatures to reflect changes in return types and functionality.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF November 27, 2024 20:21
Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes involve modifications to the endpoint filtering logic in the useEndpoints function, enhancing the criteria for valid endpoints by excluding those matching specific patterns. The fastestConnection function has been refactored to utilize a new helper function, fastestEndpoint, which includes additional filtering for WebSocket endpoints. These updates streamline the connection management and error handling processes, ensuring a more robust approach to establishing API connections.

Changes

File Path Change Summary
packages/extension-polkagate/src/hooks/useEndpoints.ts Updated filtering logic in useEndpoints to exclude endpoints matching the pattern wss://<any_number> and those containing 'onfinality'. Improved handling of endpointOptions based on chain support for light clients.
packages/extension-polkagate/src/util/utils.ts Refactored fastestConnection to use fastestEndpoint for API connections, enhancing error handling and logging. Updated return type to provide a structured response.
packages/extension-polkagate/src/util/workers/utils/fastestEndpoint.js Modified fastestEndpoint to filter out WebSocket endpoints that match wss://<any_number> or contain 'onfinality' before creating WsProvider instances, improving the control flow for valid endpoint processing.

Poem

In the meadow where endpoints play,
A rabbit hops and sings today.
"No more webs of numbers tall,
Just valid paths for one and all!
With faster friends, we'll leap and bound,
In connection's joy, we all are found!" 🐇✨


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

@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 (4)
packages/extension-polkagate/src/util/workers/utils/fastestEndpoint.js (2)

13-18: Consider enhancing the endpoint filtering logic

The current implementation could be improved in several ways:

  1. The regex pattern might be too strict and miss problematic variations
  2. The filtering logic could be more maintainable as a separate function
  3. Consider adding logging for filtered endpoints to help with debugging

Consider this refactoring:

+const isUnaccessibleEndpoint = (value) => {
+  // Filter out numeric endpoints (e.g., wss://123) due to rate limits
+  const isNumericEndpoint = /^wss:\/\/\d+/.test(value);
+  // Filter out onfinality endpoints due to access restrictions
+  const isOnfinalityEndpoint = value.includes('onfinality');
+  
+  if (isNumericEndpoint || isOnfinalityEndpoint) {
+    console.debug(`Filtering out unaccessible endpoint: ${value}`);
+    return true;
+  }
+  return false;
+};

 const connections = endpoints.map(({ value }) => {
-    // Check if e.value matches the pattern 'wss://<any_number>'
-    // ignore due to its rate limits
-    if (/^wss:\/\/\d+$/.test(value) || (value).includes('onfinality')) {
-      return undefined;
-    }
+    if (isUnaccessibleEndpoint(value)) return undefined;

Line range hint 8-34: Consider architectural improvements for better maintainability

The current implementation could benefit from some architectural improvements:

  1. Consider extracting configuration values (timeout, patterns) to a config file
  2. Consider implementing a retry mechanism for failed connections
  3. Consider implementing connection pooling or caching for frequently used endpoints

Would you like assistance in implementing any of these architectural improvements?

packages/extension-polkagate/src/hooks/useEndpoints.ts (1)

Line range hint 19-19: Consider making the return type more specific.

The current return type DropdownOption[] could be more specific to indicate that it never returns null/undefined (as evidenced by the ?? [] fallback).

-export function useEndpoints (genesisHash: string | null | undefined): DropdownOption[]
+export function useEndpoints (genesisHash: string | null | undefined): readonly DropdownOption[]
packages/extension-polkagate/src/util/utils.ts (1)

15-15: Consider Using import type for WsProvider

Since WsProvider may be used only for type annotations, consider importing it using import type to avoid unnecessary runtime imports.

Apply this diff if WsProvider is used only as a type:

-import { WsProvider } from '@polkadot/api';
+import type { WsProvider } from '@polkadot/api';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 47cd15a and c7a49e8.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/hooks/useEndpoints.ts (2 hunks)
  • packages/extension-polkagate/src/util/utils.ts (3 hunks)
  • packages/extension-polkagate/src/util/workers/utils/fastestEndpoint.js (2 hunks)
🔇 Additional comments (4)
packages/extension-polkagate/src/hooks/useEndpoints.ts (2)

60-60: LGTM! The AUTO_MODE handling is correct.

The condition for adding AUTO_MODE is properly placed after endpoint filtering, ensuring it's only added when multiple valid endpoints are available.


39-45: LGTM! Consider adding fallback handling.

The new filtering logic effectively excludes problematic endpoints. The regex pattern for excluding numeric-only hostnames and the onfinality filter are well-implemented.

Let's verify the impact of these filters on available endpoints:

Consider adding a warning log when all endpoints for a chain are filtered out, to help identify chains that might need additional endpoint options:

    const endpoints = allEndpoints?.filter((e) => e.value &&
      !/^wss:\/\/\d+$/.test(e.value) &&
      !e.value.includes('onfinality') && 
      (
        String(e.info)?.toLowerCase() === chainName?.toLowerCase() ||
        String(e.text)?.toLowerCase()?.includes(chainName?.toLowerCase() ?? '')
      )
    );

+   if (endpoints?.length === 0) {
+     console.warn(`All endpoints were filtered out for chain: ${chainName}`);
+   }
packages/extension-polkagate/src/util/utils.ts (2)

5-5: Optimize Type Imports with import type

Good use of import type for ApiPromise to ensure that only type information is imported without including runtime code. This helps in reducing the bundle size and optimizing the application.


20-20: Verify the Correctness of the Import Path for fastestEndpoint

Ensure that the fastestEndpoint function is correctly imported from './workers/utils' and that the module exports this function as expected.

Run the following script to verify the export of fastestEndpoint:

✅ Verification successful

Import Path for fastestEndpoint is Incorrect

The import path './workers/utils' is incorrect. The actual location of fastestEndpoint is at './workers/utils/fastestEndpoint.js', and it's re-exported through './workers/utils/index.ts'. The import should be from './workers/utils' (without .js extension) since the barrel file (index.ts) handles the re-export.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'fastestEndpoint' is exported from './workers/utils'

# Search for the export statement of 'fastestEndpoint' in 'utils.ts'
rg --type ts --no-filename 'export.*fastestEndpoint' ./workers/utils.ts

Length of output: 132


Script:

#!/bin/bash
# Let's first find the correct location of the file that exports 'fastestEndpoint'
fd -e ts -e js "utils" --type f

# Then search for the export of 'fastestEndpoint' in all typescript files
rg --type ts "export.*fastestEndpoint"

# Also search for any file containing 'fastestEndpoint' definition
ast-grep --pattern 'const fastestEndpoint = $_'

Length of output: 341


Script:

#!/bin/bash
# Let's check the content of the fastestEndpoint.js file
rg -A 5 "export" packages/extension-polkagate/src/util/workers/utils/fastestEndpoint.js

# Also check if there's a .ts version
rg -A 5 "export" packages/extension-polkagate/src/util/workers/utils/fastestEndpoint.ts

# Check the directory structure to understand the import path
fd . packages/extension-polkagate/src/util/workers/

Length of output: 2417

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

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/util/utils.ts (1)

19-19: LGTM: Good architectural decision to use a worker

Moving the endpoint selection logic to a worker is a good architectural decision as it:

  • Prevents blocking the main thread during endpoint selection
  • Improves UI responsiveness
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c7a49e8 and 0e9e675.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/util/utils.ts (3 hunks)
🔇 Additional comments (2)
packages/extension-polkagate/src/util/utils.ts (2)

5-5: LGTM: Type import is correctly added

The type-only import of ApiPromise is properly added and necessary for TypeScript type safety.


503-504: ⚠️ Potential issue

Fix type suppression issues

The code still uses type suppressions that were addressed in a previous review. Please implement the suggested fix to properly type the API provider.

As previously suggested:

-    const urls = endpoints.map(({ value }) => ({ value: value as string }));
-    const { api, connections } = await fastestEndpoint(urls);
-
-    // @ts-ignore
-    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
-    const selectedEndpoint = api.registry.knownTypes.provider.endpoint as string;
+    const urls = endpoints.map(({ value }) => ({ value: String(value) }));
+    const { api, connections } = await fastestEndpoint(urls);
+    const selectedEndpoint = (api?.rpc?.provider as WsProvider).endpoint;

Make sure to import the WsProvider type:

import type { WsProvider } from '@polkadot/api';

@Nick-1979 Nick-1979 merged commit 910108c into main Nov 30, 2024
8 checks passed
@Nick-1979 Nick-1979 deleted the ignoreUnaccessableEndpoints branch November 30, 2024 09:09
github-actions bot pushed a commit that referenced this pull request Nov 30, 2024
## [0.33.1](v0.33.0...v0.33.1) (2024-11-30)

### Bug Fixes

* filter unaccessible endpoints ([#1678](#1678)) ([910108c](910108c))
* scroll issue ([75d3ead](75d3ead))
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