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: export HttpAgent as standalone class to avoid namespace clutter and support ESM style imports #119

Merged
merged 3 commits into from
Dec 29, 2024

Conversation

smoke
Copy link
Contributor

@smoke smoke commented Dec 28, 2024

Checklist
  • npm test passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines
Affected core subsystem(s)
Description of change

This PR changes that HttpAgent class is exported as standalone member,
allowing use of import { HttpAgent } from 'agentkeepalive'; or const HttpAgent = require('agentkeepalive').HttpAgent;It also deprecates use ofimport * as HttpAgent from 'agentkeepalive'; or const HttpAgent = require('agentkeepalive');

This way fixing case when using Typescript and having "esModuleInterop": false (that is the default), users can not import and use the HttpAgent class and construct objects of it, because of compiler / type errors like Type 'typeof AgentKeepAlive' has no construct signatures.

Summary by CodeRabbit

  • Documentation

    • Updated README.md with consistent usage of HttpAgent instead of Agent
    • Renamed code examples to use HttpAgent across documentation
  • Refactor

    • Renamed Agent to HttpAgent in multiple files and test fixtures
    • Updated TypeScript type definitions and import statements
    • Modified module export structure in index.js
  • Tests

    • Updated test files to use HttpAgent
    • Adjusted test configurations and compiler options
  • Security

    • Increased key size from 1024 to 2048 bits in test key generation script

Remove need of `"esModuleInterop": true` when used with Typescript,
clearing the module structure, types and imports
Fixes `Error: error:0A00018F:SSL routines::ee key too small`
Copy link

coderabbitai bot commented Dec 28, 2024

Walkthrough

The pull request introduces a significant refactoring of the agentkeepalive package, focusing on renaming and explicitly defining the HttpAgent class. This change affects multiple files across the project, including README, benchmark scripts, examples, type definitions, and test files. The modifications aim to improve clarity and specificity in how the HTTP agent is imported, instantiated, and used throughout the package. The core functionality remains unchanged, but the export and import mechanisms have been updated to provide a more explicit and type-safe interface.

Changes

File Change Summary
README.md Renamed Agent to HttpAgent in usage examples
benchmark/echo.js, benchmark/proxy.js Updated agent instantiation from Agent/AgentKeepalive to HttpAgent
example/http_agent.js Renamed agent to http_agent, using HttpAgent
index.d.ts Renamed HttpAgent to _HttpAgent, added new HttpAgent export
index.js Modified export structure to explicitly include HttpAgent
test/fixtures/genkey.sh Increased key size from 1024 to 2048 bits
test/fixtures/ts/index.ts Updated imports and type references
test/fixtures/ts/tsconfig.json Removed esModuleInterop option
Multiple test files Updated agent import to use HttpAgent from module

Sequence Diagram

sequenceDiagram
    participant User
    participant Module as agentkeepalive
    participant HttpAgent
    
    User->>Module: Import HttpAgent
    Module-->>User: Provide HttpAgent
    User->>HttpAgent: Create new instance
    HttpAgent-->>User: Return configured agent
    User->>HttpAgent: Use for HTTP requests
Loading

Poem

🐰 Hop, hop, through the code we go,
Renaming agents with a rabbit's glow
HttpAgent shines, crystal clear
Refactoring brings us coding cheer!
A leap of change, precise and bright 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@smoke smoke changed the title fix: export HttpAgent as standalone class to avoid namespace clutter fix: export HttpAgent as standalone class to avoid namespace clutter and support ESM style imports Dec 28, 2024
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: 0

🧹 Nitpick comments (7)
example/http_agent.js (1)

37-37: Trim unnecessary console output
Logging the entire http_agent object may produce very large output. Consider logging only essential fields to keep logs manageable.

-  console.log('keep alive sockets:', http_agent);
+  console.log('keep alive sockets:', {
+    statusChanged: http_agent.statusChanged,
+    sockets: Object.keys(http_agent.sockets).length,
+    freeSockets: Object.keys(http_agent.freeSockets).length,
+  });
benchmark/echo.js (1)

57-57: Clarify log statement
Renaming the reference from Agent(...) to HttpAgent(...) in the log provides more accurate details, matching the new class name. Consider additionally renaming the local variable agent to httpAgent for full consistency.

-  console.log('[%s] [worker:%d] HttpAgent(%s,%sms,%s,%s): requests: %d, created: %d, timeout: %d, ...',
+  console.log('[%s] [worker:%d] httpAgent(%s,%sms,%s,%s): requests: %d, created: %d, timeout: %d, ...',
test/test-ECONNRESET.test.js (1)

5-5: Refactor import statement to a named import if desired.
While this import is valid, you could consider using named imports (ES modules) to align with future usage, e.g., import { HttpAgent } from '...'.

benchmark/proxy.js (3)

4-4: Consider replacing var with const.
As recommended by linting tools, using const HttpAgent would improve clarity and readability here.

Apply this diff to address it:

-var HttpAgent = require('../').HttpAgent;
+const HttpAgent = require('../').HttpAgent;
🧰 Tools
🪛 eslint

[error] 4-4: Unexpected var, use let or const instead.

(no-var)


10-15: Avoid var to align with modern JavaScript standards.
Use const or let for agentKeepalive since it is never reassigned.

-var agentKeepalive = new HttpAgent({
+const agentKeepalive = new HttpAgent({

Additionally, you can apply object shorthand for keys mirroring property names.

🧰 Tools
🪛 eslint

[error] 10-15: Unexpected var, use let or const instead.

(no-var)


[error] 12-12: Expected property shorthand.

(object-shorthand)


[error] 13-13: Expected property shorthand.

(object-shorthand)


16-16: Avoid var to align with modern JavaScript standards.
Use const or let for agentHttp since it is never reassigned.

-var agentHttp = new HttpAgent({
+const agentHttp = new HttpAgent({
🧰 Tools
🪛 eslint

[error] 16-19: Unexpected var, use let or const instead.

(no-var)

test/http_agent.test.js (1)

108-108: Rename test description to avoid confusion.

This test name still references http.Agent(), but the code now uses HttpAgent. Renaming would avoid confusion and keep the test suite consistent.

- it.skip('should request with connection: close with http.Agent()', done => {
+ it.skip('should request with connection: close with HttpAgent()', done => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6db01a0 and e2cb6d1.

⛔ Files ignored due to path filters (3)
  • test/fixtures/agenttest-cert.pem is excluded by !**/*.pem
  • test/fixtures/agenttest-key.pem is excluded by !**/*.pem
  • test/fixtures/ca.pem is excluded by !**/*.pem
📒 Files selected for processing (13)
  • README.md (2 hunks)
  • benchmark/echo.js (2 hunks)
  • benchmark/proxy.js (1 hunks)
  • example/http_agent.js (2 hunks)
  • index.d.ts (3 hunks)
  • index.js (1 hunks)
  • test/fixtures/ca.key (1 hunks)
  • test/fixtures/genkey.sh (1 hunks)
  • test/fixtures/ts/index.ts (2 hunks)
  • test/fixtures/ts/tsconfig.json (1 hunks)
  • test/http_agent.test.js (43 hunks)
  • test/server_timeout.test.js (2 hunks)
  • test/test-ECONNRESET.test.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/fixtures/ca.key
🧰 Additional context used
🪛 eslint
benchmark/proxy.js

[error] 4-4: Unexpected var, use let or const instead.

(no-var)


[error] 6-6: Unexpected var, use let or const instead.

(no-var)


[error] 7-7: Unexpected var, use let or const instead.

(no-var)


[error] 8-8: Unexpected var, use let or const instead.

(no-var)


[error] 10-15: Unexpected var, use let or const instead.

(no-var)


[error] 12-12: Expected property shorthand.

(object-shorthand)


[error] 13-13: Expected property shorthand.

(object-shorthand)

🔇 Additional comments (65)
index.js (1)

3-5: Exporting both the default and a named HttpAgent is consistent with the PR goals
Exporting HttpAgent in both default and named styles allows flexible consumption by TypeScript and CommonJS users. This change aligns well with the PR objective of reducing namespace clutter and addressing TypeScript import issues.

example/http_agent.js (4)

4-4: Good use of named import
Importing HttpAgent through a named property clarifies intent and avoids potential collisions with other default exports.


6-6: Instantiating HttpAgent correctly
Creating a new HttpAgent instance adheres to the proposed interface changes, helping to validate the new export.


14-14: Supplying the agent via http_agent
Attaching the newly instantiated http_agent to request options is straightforward and consistent with the refactor.


43-45: Properly monitoring agent sockets
Accessing getName, sockets, and freeSockets is appropriate for debugging. Ensure no concurrency issues arise if multiple calls occur simultaneously.

test/fixtures/ts/index.ts (5)

1-2: Named import usage
Switching to a named import for HttpAgent, HttpsAgent, and related types is more explicit, improving clarity for TypeScript consumers.


9-9: Using HttpOptions
Declaring httpOpt as HttpOptions clarifies that it is specifically for HttpAgent configuration, eliminating confusion with all-purpose agent types.


15-15: Creating HttpAgent
Instantiating HttpAgent with httpOpt confirms the new named import structure functions correctly and improves type safety.


42-42: Tracking AgentStatus
Retrieving status via getCurrentStatus() and storing it in a typed AgentStatus variable is aligned with the updated agent pattern.


48-55: Consistent usage for HTTPS
Likewise, HttpsOptions and the resulting AgentStatus ensure the new architecture is fully mirrored for HTTPS as well.

benchmark/echo.js (2)

3-3: Loading the HttpAgent from the new export
This reflects the updated module export and ensures that the benchmark script aligns with the refactor.


5-5: Instantiating HttpAgent with keep-alive settings
Explicitly passing keep-alive parameters into the constructor is a correct approach for performance testing.

test/test-ECONNRESET.test.js (1)

30-30: Agent instantiation looks good.
The new HttpAgent provides a more explicit name and clarifies its purpose in the test scenario.

index.d.ts (3)

9-9: Naming convention changes are clear.
Renaming HttpAgent to _HttpAgent to differentiate the internal class from the exported class is acceptable. Ensure that the rest of the codebase references _HttpAgent only internally.


28-31: Deprecation notice is well-defined.
Marking AgentKeepAlive as deprecated, with guidance to use HttpAgent, is a good approach for a transitional release.


57-57: New HttpAgent export finalizes the refactor.
This allows external consumers to properly import the more descriptive entity. Keep thorough documentation around these changes to ensure a smooth transition for end-users.

test/server_timeout.test.js (2)

5-5: Use HttpAgent import aligned with the new export structure.
The import statement aligns with the updated export strategy, clarifying usage for maintainers and test readers.


33-33: Instantiation is accurate for the test environment.
Specifying { keepAlive: true } with HttpAgent ensures behavior remains consistent with prior usage.

test/http_agent.test.js (42)

8-8: Switch to HttpAgent import.

This import statement now references HttpAgent instead of the generic Agent, aligning with the PR’s goal of a standalone class export.


18-18: Same update as line 8.


132-132: Same update as line 8.


183-183: Same update as line 8.


277-277: Same update as line 8.


311-311: Same update as line 8.


349-349: Same update as line 8.


385-385: Same update as line 8.


399-399: Same update as line 8.


428-428: Same update as line 8.


451-451: Same update as line 8.


524-524: Same update as line 8.


575-575: Same update as line 8.


608-608: Same update as line 8.


656-656: Same update as line 8.


683-683: Same update as line 8.


711-711: Same update as line 8.


767-767: Same update as line 8.


819-819: Same update as line 8.


893-893: Same update as line 8.


929-929: Same update as line 8.


970-970: Same update as line 8.


1003-1003: Same update as line 8.


1023-1023: Same update as line 8.


1055-1055: Same update as line 8.


1099-1099: Same update as line 8.


1148-1148: Same update as line 8.


1180-1180: Same update as line 8.


1216-1216: Same update as line 8.


1259-1259: Same update as line 8.


1337-1337: Same update as line 8.


1387-1387: Same update as line 8.


1454-1454: Same update as line 8.


1499-1499: Same update as line 8.


1537-1537: Same update as line 8.


1569-1569: Same update as line 8.


1603-1603: Same update as line 8.


1650-1650: Same update as line 8.


1692-1692: Same update as line 8.


1733-1733: Same update as line 8.


1769-1769: Same update as line 8.


1807-1807: Same update as line 8.

test/fixtures/ts/tsconfig.json (1)

24-24: Confirm removal of esModuleInterop.

Removing this option might break certain default imports in projects that rely on ES module interop. Please verify that all TypeScript imports remain valid, especially in environments without "esModuleInterop".

test/fixtures/genkey.sh (2)

9-9: Increased RSA key size from 1024 to 2048.

This improvement enhances security by using a stronger key strength. Ensure that all references to the old 1024-bit key remain compatible with the 2048-bit version.


13-13: Reusing the updated key for certificate signing.

The CSR command now references the newly generated 2048-bit private key (agenttest-key.pem).

README.md (2)

64-66: Switched to HttpAgent in the code example.

Renaming Agent to HttpAgent clarifies usage and supports the new standalone export. The snippet remains functionally similar.


165-166: Updated usage example to HttpAgent.

Similarly, these lines now demonstrate HttpAgent instead of the older Agent name, in line with the PR’s objectives.

@fengmk2 fengmk2 changed the title fix: export HttpAgent as standalone class to avoid namespace clutter and support ESM style imports feat: export HttpAgent as standalone class to avoid namespace clutter and support ESM style imports Dec 29, 2024
@fengmk2 fengmk2 merged commit 7d79ddd into node-modules:master Dec 29, 2024
7 checks passed
@fengmk2
Copy link
Member

fengmk2 commented Dec 29, 2024

4.6.0 Released

@smoke Thanks a lot!

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.

2 participants