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: require support paths #118

Merged
merged 1 commit into from
Dec 30, 2024
Merged

fix: require support paths #118

merged 1 commit into from
Dec 30, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 30, 2024

Summary by CodeRabbit

Release Notes

  • Dependencies

    • Updated @eggjs/utils package to version 4.2.1
  • Enhancements

    • Improved module loading mechanism with new baseDir option
    • Added support for specifying module search paths during import
  • Testing

    • Enhanced agent worker test suite with additional module injection
    • Added module execution verification in tests
  • Deprecation Notice

    • HTTPS configuration now recommends object-based format with key and cert

Copy link

coderabbitai bot commented Dec 30, 2024

Walkthrough

The pull request introduces modifications to the @eggjs/cluster package, focusing on enhancing module loading and testing capabilities. Key changes include adding a baseDir property to module import options across multiple files, updating the @eggjs/utils dependency version, and modifying test fixtures to support additional module injection and debugging. The changes aim to improve module resolution and provide more flexible configuration options for the Egg.js cluster management.

Changes

File Change Summary
package.json Updated @eggjs/utils dependency from ^4.1.6 to ^4.2.1
src/agent_worker.ts, src/app_worker.ts Added baseDir property to options object for module import paths
src/utils/options.ts Modified parseOptions to include baseDir in module import options and added deprecation warning for HTTPS configuration
test/agent_worker.test.ts Updated test case to include additional module injection and execution verification
test/fixtures/apps/agent-debug-port/agent.js Removed 'use strict' directive
test/fixtures/apps/agent-debug-port/inject1.js Added console log to indicate script execution

Sequence Diagram

sequenceDiagram
    participant CLI as Command Line
    participant AgentWorker as Agent Worker
    participant AppWorker as App Worker
    participant ModuleLoader as Module Loader

    CLI->>AgentWorker: Start with options
    AgentWorker->>ModuleLoader: Import modules with baseDir
    ModuleLoader-->>AgentWorker: Resolve and load modules
    
    CLI->>AppWorker: Start with options
    AppWorker->>ModuleLoader: Import modules with baseDir
    ModuleLoader-->>AppWorker: Resolve and load modules
Loading

Poem

🐰 Hop, hop, through code's domain,
Modules dance with baseDir's refrain,
Cluster's magic, now more bright,
Importing paths with pure delight!
A rabbit's code, both swift and neat, 🚀


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.

Copy link

pkg-pr-new bot commented Dec 30, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/cluster/@eggjs/cluster@118

commit: 4663c73

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

🧹 Nitpick comments (1)
src/app_worker.ts (1)

30-32: Add error handling for module imports

While the module resolution path configuration is correct, consider adding try-catch error handling to provide better error messages when modules can't be resolved from the specified baseDir.

 if (options.require) {
   // inject
   for (const mod of options.require) {
+    try {
       await importModule(mod, {
         paths: [ options.baseDir ],
       });
+    } catch (err) {
+      consoleLogger.error('[app_worker] Failed to load required module %s: %s', mod, err.message);
+      throw err;
+    }
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa3034f and 4663c73.

📒 Files selected for processing (7)
  • package.json (1 hunks)
  • src/agent_worker.ts (2 hunks)
  • src/app_worker.ts (3 hunks)
  • src/utils/options.ts (1 hunks)
  • test/agent_worker.test.ts (1 hunks)
  • test/fixtures/apps/agent-debug-port/agent.js (0 hunks)
  • test/fixtures/apps/agent-debug-port/inject1.js (1 hunks)
💤 Files with no reviewable changes (1)
  • test/fixtures/apps/agent-debug-port/agent.js
✅ Files skipped from review due to trivial changes (1)
  • test/fixtures/apps/agent-debug-port/inject1.js
🔇 Additional comments (7)
src/agent_worker.ts (3)

21-21: Well-defined optional property baseDir

This property addition is straightforward, allowing dynamic resolution of modules with a base directory.


27-31: Asynchronous module imports with baseDir

The loop correctly imports modules from the options.require array. Using importModule with paths: [ options.baseDir ] ensures modules are resolved relative to baseDir. This change enables more flexible module resolution.

  • Potential Improvement: Add a defensive check to confirm that options.baseDir is defined or a valid path before importing.

42-44: Importing the framework with baseDir

The same approach is used when importing the framework. Ensure baseDir is always set correctly or fallback to a default if it’s undefined. Otherwise, runtime errors may occur if baseDir is missing.

src/utils/options.ts (1)

109-111: Explicitly setting paths in importModule

The addition of paths: [ options.baseDir! ] clarifies module resolution. This is beneficial for monorepo setups or custom directory structures.

test/agent_worker.test.ts (1)

18-21: Testing module injection

Adding { require: [ './inject1.js' ] } and asserting the stdout message is a good way to ensure custom modules are loaded. This test case effectively verifies that the code paths for baseDir and require are exercised.

package.json (1)

36-36: Dependency update to @eggjs/utils v4.2.1

Upgrading to ^4.2.1 can bring new features or fixes. Double-check any breaking changes or deprecations in the changelog.

src/app_worker.ts (1)

18-18: LGTM: Well-placed baseDir property addition

The addition of the mandatory baseDir property is appropriate for specifying module resolution paths.

Comment on lines +46 to +48
const { Application } = await importModule(options.framework, {
paths: [ options.baseDir ],
});
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Framework resolution is safe, but error handling can be improved

Based on the codebase analysis:

  1. The framework import pattern is consistent across the codebase (app_worker.ts, agent_worker.ts, and utils/options.ts).
  2. Error handling exists at the application initialization level but not specifically for framework imports.
  3. The codebase follows a pattern of using consoleLogger.error for error logging before throwing.

Here's a refined suggestion for error handling:

-  const { Application } = await importModule(options.framework, {
-    paths: [ options.baseDir ],
-  });
+  try {
+    const { Application } = await importModule(options.framework, {
+      paths: [ options.baseDir ],
+    });
+    if (!Application) {
+      throw new Error(`Framework ${options.framework} does not export an Application class`);
+    }
+  } catch (err) {
+    consoleLogger.error('[app_worker] Failed to load framework: %s', err.message);
+    throw err;
+  }
🔗 Analysis chain

Verify framework resolution and enhance error handling

The framework import configuration looks correct, but let's ensure it doesn't break framework discovery and add specific error handling.

Let's verify the framework resolution:

Consider adding specific error handling:

-  const { Application } = await importModule(options.framework, {
-    paths: [ options.baseDir ],
-  });
+  let Application;
+  try {
+    const framework = await importModule(options.framework, {
+      paths: [ options.baseDir ],
+    });
+    Application = framework.Application;
+    if (!Application) {
+      throw new Error(`Framework ${options.framework} does not export an Application class`);
+    }
+  } catch (err) {
+    consoleLogger.error('[app_worker] Failed to load framework %s: %s', options.framework, err.message);
+    throw err;
+  }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the framework can be resolved from baseDir
ast-grep --pattern 'new $_(options)' | rg -A 2 'Application'

Length of output: 117


Script:

#!/bin/bash
# Let's check how importModule is used for framework loading across the codebase
rg "importModule.*framework" -B 2 -A 2

Length of output: 799


Script:

#!/bin/bash
# Check the framework loading patterns and error handling
ast-grep --pattern 'try {
  $$$
  const $_ = await importModule($_, $_);
  $$$
}'

Length of output: 83


Script:

#!/bin/bash
# Check if there are any framework-specific error handlers
rg "Failed to load framework" -B 2 -A 2

Length of output: 41


Script:

#!/bin/bash
# Let's check for any existing error handling patterns in the codebase
rg "catch.*err" -B 2 -A 2

Length of output: 4186


Script:

#!/bin/bash
# Check how errors are logged in the codebase
rg "consoleLogger.error" -B 2 -A 2

Length of output: 1828


Script:

#!/bin/bash
# Check the importModule implementation
ast-grep --pattern 'async function importModule($_) {
  $$$
}'

Length of output: 64

@fengmk2 fengmk2 merged commit b74872c into master Dec 30, 2024
16 checks passed
@fengmk2 fengmk2 deleted the fix-require branch December 30, 2024 09:01
fengmk2 pushed a commit that referenced this pull request Dec 30, 2024
[skip ci]

## [3.0.1](v3.0.0...v3.0.1) (2024-12-30)

### Bug Fixes

* require support paths ([#118](#118)) ([b74872c](b74872c))
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.

1 participant