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: support allowH2 on urllib@4 #5356

Closed
wants to merge 9 commits into from
Closed

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Sep 15, 2024

#5347

Summary by CodeRabbit

  • New Features

    • Introduced HTTP/2 support for enhanced request handling.
    • Added a new HTTP client for improved performance on Node.js versions 18 and above.
    • Enhanced configuration options for HTTP client usage, including a new property to allow HTTP/2.
  • Bug Fixes

    • Improved error handling for requests exceeding the timeout limit.
  • Tests

    • Added a comprehensive test suite for the new HTTP client, covering timeout settings, HTTP/1.1 and HTTP/2 request success, and URL validation.
    • Updated existing tests to ensure compatibility with new URLs.

7WanLi and others added 2 commits September 15, 2024 13:27
跟英文版同步,去掉误被提升到标题的注释。

[skip ci]
Copy link

coderabbitai bot commented Sep 15, 2024

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 42 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 0759ef5 and 3e565f3.

Walkthrough

The pull request introduces enhancements to the HTTP client configuration and functionality within the application. Key changes include the addition of the allowH2 property for enabling HTTP/2 support, the implementation of a new HttpClient4 class extending the existing HTTP client, and the introduction of a custom HTTP client that enforces URL validation. Additionally, new tests are added to validate the behavior of the HTTP client under various scenarios, including timeout settings and HTTP/2 requests.

Changes

File Change Summary
config/config.default.js Added allowH2: false and clarified useHttpClientNext: false in the httpclient configuration object.
lib/egg.js Integrated HttpClient4 into EggApplication, modifying the logic for selecting the appropriate HTTP client based on allowH2.
test/lib/core/httpclient.test.js Added a test suite for HTTP client functionality, covering global timeout, HTTP/1.1 and HTTP/2 request success, and URL validation.
.github/workflows/nodejs.yml Changed the installation command from npminstall to a direct npm command with flags to alter dependency installation behavior.
test/doc.test.js Commented out all lines, effectively disabling the entire test suite for broken URL checks.

Possibly related PRs

  • feat: allow to httpClient use HTTP2 first #5332: This PR introduces the allowH2 property in the config.default.js file, which is directly related to the changes made in the main PR regarding the httpclient configuration, specifically enabling HTTP/2 support.

Poem

In the meadow where bunnies play,
A new HTTP client hops today.
With allowH2, it leaps so high,
Validating URLs as it zooms by.
Oh, what joy in code we find,
Enhancements made, so well-designed! 🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

@fengmk2
Copy link
Member Author

fengmk2 commented Sep 15, 2024

debug 日志可以看到是开启了 H2
image

@fengmk2 fengmk2 force-pushed the enableH2-use-undici-v6 branch from 12a6f95 to 6a67a1d Compare September 15, 2024 06:03
Copy link

@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.

Caution

Inline review comments failed to post

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ce4fd67 and 12a6f95.

Files selected for processing (8)
  • config/config.default.js (2 hunks)
  • lib/core/httpclient4.js (1 hunks)
  • lib/egg.js (3 hunks)
  • package.json (1 hunks)
  • test/fixtures/apps/httpclient-allowH2/app.js (1 hunks)
  • test/fixtures/apps/httpclient-allowH2/config/config.default.js (1 hunks)
  • test/fixtures/apps/httpclient-allowH2/package.json (1 hunks)
  • test/lib/core/httpclient.test.js (1 hunks)
Files skipped from review due to trivial changes (1)
  • test/fixtures/apps/httpclient-allowH2/package.json
Additional context used
Biome
lib/core/httpclient4.js

[error] 18-18: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Additional comments not posted (15)
test/fixtures/apps/httpclient-allowH2/config/config.default.js (1)

1-2: Enabling HTTP/2 support is a good performance optimization.

Setting allowH2 to true enables HTTP/2 support for the HTTP client, which can improve performance when communicating with servers that support HTTP/2.

test/fixtures/apps/httpclient-allowH2/app.js (3)

4-17: LGTM!

The CustomHttpClient class implementation looks good:

  • It extends the existing HttpClient4 class to add custom functionality.
  • The request method adds URL validation to ensure the URL starts with "http", enhancing the robustness of HTTP requests.
  • The curl method is a wrapper around the request method, maintaining compatibility with existing usage patterns.

5-12: LGTM!

The request method implementation looks good:

  • It uses a Promise to perform the URL validation asynchronously, without blocking the main execution thread.
  • The validation checks if the URL starts with "http" using a regular expression, ensuring only valid URLs are allowed.
  • If the validation fails, it throws an assertion error with a descriptive message, providing clear feedback.
  • If the validation passes, it calls the superclass request method to continue the HTTP request process, maintaining the original functionality.

14-16: LGTM!

The curl method implementation looks good:

  • It is a simple wrapper around the request method, delegating the functionality to the underlying implementation.
  • It takes the same parameters as the request method and passes them through, ensuring compatibility with existing code.
  • It does not add any additional functionality or modify the behavior of the request method, maintaining the expected behavior.
lib/core/httpclient4.js (4)

4-29: LGTM!

The HttpClient4 class is well-designed and enhances the functionality of the HttpClient from urllib4. It properly normalizes the configuration settings in the constructor and adds tracing support in the request method. The curl method is a nice addition to maintain compatibility with existing code.

Tools
Biome

[error] 18-18: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


16-24: LGTM!

The request method correctly checks for the presence of a tracer in the provided context and falls back to the application instance tracer if no context tracer is found. The current implementation is clear and concise.

Regarding the static analysis hint:
The suggestion to use an optional chain is not necessary in this case, as the current implementation is clear and concise. The condition is straightforward and easy to understand, so changing it to an optional chain would not provide any significant benefit.

Tools
Biome

[error] 18-18: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


26-28: LGTM!

The curl method is a simple wrapper around the request method, which maintains compatibility with existing code that may use curl for making requests. It does not add any additional functionality or modify the arguments, making it a straightforward and useful addition to the class.


31-36: LGTM!

The normalizeConfig function is a useful utility that ensures the timeout configuration is properly converted from a string to a numeric value. It uses the reliable humanize-ms library to handle the conversion, enhancing the robustness of the configuration handling.

package.json (1)

58-58: Verify compatibility with urllib@4.

The PR adds a new dependency urllib4 which is an alias for [email protected]. However, the existing codebase also depends on older versions of urllib (^2.33.0 and ^3.22.4).

Please ensure that the existing code is compatible with urllib@4 and won't break due to any API changes.

Run the following script to verify the urllib imports in the codebase:

Verification successful

Gradual migration to urllib4 confirmed. No immediate compatibility issues detected.

The codebase is implementing a gradual migration strategy from urllib2/3 to urllib4. The new HttpClient4 class in lib/core/httpclient4.js utilizes urllib4 and supports the allowH2 feature mentioned in the PR objectives. The existing HttpClient class is retained for backwards compatibility.

Key observations:

  • Multiple HttpClient classes coexist (HttpClient, HttpClientNext, HttpClient4).
  • No breaking changes in basic API usage (request, curl) were detected.
  • The gradual approach allows for introducing new features while maintaining compatibility.

This strategy minimizes the risk of breaking changes and allows for a smoother transition to urllib4.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify urllib imports in the codebase.

# Test: Search for urllib imports. Expect: Imports from urllib4 or imports without version.
rg --type js -o $'urllib(4)?'

Length of output: 761


Script:

#!/bin/bash
# Description: Examine urllib usage in key files

# Check httpclient4.js
echo "=== Content of lib/core/httpclient4.js ==="
cat lib/core/httpclient4.js

# Check httpclient.js
echo -e "\n=== Content of lib/core/httpclient.js ==="
cat lib/core/httpclient.js

# Check egg.js (first 50 lines)
echo -e "\n=== First 50 lines of lib/egg.js ==="
head -n 50 lib/egg.js

# Check for version-specific API calls
echo -e "\n=== Searching for potential version-specific API calls ==="
rg --type js 'urllib\.(request|curl|requestThunk|request2|curl2)' -C 2

Length of output: 8119

config/config.default.js (2)

306-307: LGTM!

The change improves the clarity of the configuration by explicitly setting the default value of useHttpClientNext to false.


330-330: Approve the addition of the allowH2 configuration option.

The change introduces a new configuration option to enable HTTP/2 support using the urllib@4 HttpClient, which aligns with the PR objective. The default value is set to false, making it an opt-in feature that requires explicit enabling.

Enabling HTTP/2 support can potentially improve performance for certain types of requests and network conditions. However, it's important to ensure that the underlying infrastructure and dependencies support HTTP/2 before enabling this feature in production environments.

The opt-in nature of the feature mitigates the risk of unexpected behavior for existing applications.

lib/egg.js (3)

17-17: LGTM!

The import statement for HttpClient4 is necessary and correctly added.


55-55: LGTM!

The assignment of HttpClient4 to this.HttpClient4 is correctly added in the constructor of the EggApplication class.


298-300: Verify the new condition for instantiating HttpClient4.

The new condition that checks this.config.httpclient.allowH2 and instantiates HttpClient4 if true is correctly added. However, ensure that this change is thoroughly tested to confirm that it behaves as expected and does not introduce any unexpected behavior.

Run the following script to verify the usage of the new condition:

Verification successful

Verified: New condition for HttpClient4 is correctly implemented

The new condition this.config.httpclient.allowH2 is correctly implemented in lib/egg.js and is the only occurrence in the codebase. The order of conditions (allowH2 -> useHttpClientNext -> enableDNSCache) ensures the intended behavior for selecting the appropriate HTTP client.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new condition for instantiating `HttpClient4`.

# Test: Search for the usage of `this.config.httpclient.allowH2`. Expect: Only occurrences in the new condition.
rg --type js -A 5 $'this\.config\.httpclient\.allowH2'

Length of output: 454

test/lib/core/httpclient.test.js (1)

258-304: LGTM!

The new test suite for the HTTP client functionality with allowH2 set to true is comprehensive and well-structured. It covers critical aspects such as global timeout settings, successful HTTP/1.1 and HTTP/2 requests, and URL validation.

The test cases help ensure the correctness and reliability of the HTTP client when allowH2 is enabled. They enhance the overall testing coverage and provide confidence in the HTTP client's behavior.

Great job on adding this test suite!

Comments failed to post (2)
test/fixtures/apps/httpclient-allowH2/config/config.default.js (1)

3-5: Increase the timeout value to avoid premature request failures.

The timeout value of 99 milliseconds is extremely short and might lead to premature request failures, especially in high-latency environments or for requests that take longer to process.

Consider increasing the timeout to a more reasonable value, such as 5000 milliseconds (5 seconds), to allow sufficient time for requests to complete:

exports.httpclient = {
  allowH2: true,
  request: {
-   timeout: 99,
+   timeout: 5000,
  },
};
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.

  request: {
    timeout: 5000,
  },
package.json (1)

58-58: Consider removing older versions of urllib.

The project now has 3 different versions of urllib specified in package.json:

  • urllib@^2.33.0
  • urllib-next aliased to urllib@^3.22.4
  • urllib4 aliased to urllib@^4.3.0

Having multiple versions of the same dependency can lead to inconsistencies and maintenance overhead. If the older versions are no longer needed, consider removing them.

Apply this diff to remove the older versions:

-    "urllib": "^2.33.0",
-    "urllib-next": "npm:urllib@^3.22.4",

Committable suggestion was skipped due to low confidence.

Copy link

codecov bot commented Sep 15, 2024

Codecov Report

Attention: Patch coverage is 90.38462% with 5 lines in your changes missing coverage. Please review.

Project coverage is 96.74%. Comparing base (44ab507) to head (140ad0c).
Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
lib/core/httpclient4.js 86.84% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5356      +/-   ##
==========================================
- Coverage   99.86%   96.74%   -3.12%     
==========================================
  Files          36       36              
  Lines        3628     3567      -61     
  Branches      520      502      -18     
==========================================
- Hits         3623     3451     -172     
- Misses          5      116     +111     

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

Copy link

@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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 140ad0c and 0759ef5.

Files selected for processing (2)
  • .github/workflows/nodejs.yml (1 hunks)
  • test/doc.test.js (1 hunks)
Files skipped from review due to trivial changes (1)
  • test/doc.test.js

.github/workflows/nodejs.yml Outdated Show resolved Hide resolved
@fengmk2 fengmk2 changed the base branch from master to 3.x September 15, 2024 09:43
@fengmk2 fengmk2 closed this Sep 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants