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 file returning async functions when loading it #272

Merged
merged 8 commits into from
Dec 18, 2024

Conversation

AntiMoron
Copy link
Contributor

@AntiMoron AntiMoron commented Dec 11, 2024

Use Case:

dynamically load mysql connection configuration from a remote config center to keep it secure.

// config.default.ts

export default async function() {
  return {
    mysql: {
      ...(await nacos.get('mysqlConfig'))
    }
  };
}

Summary by CodeRabbit

  • New Features

    • Enhanced asynchronous file loading capabilities, including support for both CommonJS and ES modules.
    • Introduction of new modules that return promises with configuration data.
  • Bug Fixes

    • Improved handling of promises in the file loading process.
  • Tests

    • Added multiple test cases to verify the functionality of loading various types of modules, including asynchronous functions and promise-based exports.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

The pull request introduces enhancements to file loading mechanisms, focusing on improving support for asynchronous modules and promises. The changes primarily involve updating the egg_loader.ts to handle promise-based module loading, and adding multiple test fixtures and test cases to validate the new functionality. The modifications aim to provide more robust handling of different module types, including CommonJS and ES modules with various async export patterns.

Changes

File Change Summary
src/loader/egg_loader.ts Updated import statements and modified loadFile method to handle promise-based module loading
test/fixtures/load_file/* Added multiple test fixture modules with async/promise exports
test/loader/load_file.test.ts Added comprehensive test cases for loading different module types
test/utils/index.test.ts Added test cases for loading ES modules with async/promise default exports

Sequence Diagram

sequenceDiagram
    participant Loader as EggLoader
    participant Module as File Module
    participant Promise as Promise Handler

    Loader->>Module: Load File
    alt Is Promise
        Module-->>Promise: Await Promise
        Promise-->>Loader: Resolve Module
    else Is Regular Module
        Module-->>Loader: Return Module
    end
Loading

Poem

🐰 A Loader's Tale of Async Grace 🌟

In modules deep, where promises hide,
Our loader dances, takes async in stride
With isPromise as its trusty guide
Awaiting results with rabbit-like pride
Async or sync, it handles with care! 🚀

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.

@fengmk2 fengmk2 self-assigned this Dec 11, 2024
Copy link

pkg-pr-new bot commented Dec 11, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/egg-core/@eggjs/core@272

commit: 0d78b15

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

🧹 Outside diff range and nitpick comments (2)
test/fixtures/loadfile/es-module-default-async.js (2)

1-2: Remove redundant 'use strict' directive

The 'use strict' directive is redundant in ES modules as they are automatically in strict mode.

-"use strict";
 exports.__esModule = true;
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-12: Consider reducing the timeout duration for faster tests

The 500ms timeout in the test fixture might slow down the test suite unnecessarily. Consider reducing this value to improve test execution time while still demonstrating the async behavior.

   fn() {
     return new Promise((res) => {
       setTimeout(() => {
         res({
           clients: 'Test Config'
         });
-      }, 500);
+      }, 10); // Reduced timeout for faster tests
     });
   },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8bf0ba5 and 6ea00a4.

📒 Files selected for processing (2)
  • test/fixtures/loadfile/es-module-default-async.js (1 hunks)
  • test/loader/load_file.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
test/fixtures/loadfile/es-module-default-async.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/loader/load_file.test.ts Outdated Show resolved Hide resolved
test/loader/load_file.test.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
package.json (1)

Line range hint 91-111: Well-structured dual module format support

The exports field configuration is well-structured to support both ESM and CommonJS modules, which is essential for:

  • Compatibility with different module systems
  • Proper type definitions in both formats
  • Source file access for debugging

This setup aligns with the PR's need to support async function loading in both module formats.

Consider documenting the module format support in the README, especially regarding:

  • How async functions are handled in both ESM and CommonJS contexts
  • Any limitations or considerations when using async configurations
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6ea00a4 and 2628dcf.

📒 Files selected for processing (1)
  • package.json (1 hunks)
🔇 Additional comments (2)
package.json (2)

Line range hint 6-8: Verify Node.js version requirement aligns with async function support needs

The upgrade to Node.js >= 18.19.0 is appropriate as it ensures robust support for:

  • ESM modules
  • Top-level await
  • Enhanced async/await capabilities

This aligns well with the PR's objective of supporting async function returns in configuration files.

✅ Verification successful

Based on the search results, I can now generate the final response since I have enough evidence to verify the Node.js version requirement:

Node.js version requirement is appropriate for async function support

The codebase shows extensive use of async/await functionality and ESM modules:

  • Multiple async function declarations in core loaders (src/loader/file_loader.ts, src/loader/egg_loader.ts)
  • Support for loading async functions from configuration files (test/loader/load_file.test.ts)
  • ESM module handling with top-level await (src/utils/index.ts)

Node.js 18.19.0+ provides stable support for these features:

  • Top-level await in ESM modules
  • Enhanced async/await capabilities
  • Stable ESM implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Node.js version compatibility with async features
# Check for any potential compatibility issues in the codebase

# Search for top-level await usage
rg "await\s+(?!.*\{)" --type ts

# Search for async function exports
rg "export\s+(?:default\s+)?async\s+function" --type ts

Length of output: 319


Script:

#!/bin/bash
# Let's try a simpler approach to verify async usage and Node.js compatibility

# Search for async function declarations and exports
rg "async function" --type ts -A 2

# Search for top-level await usage (simplified pattern)
rg "await " --type ts -A 2

# Check for any ESM-specific syntax
rg "export |import " --type ts

Length of output: 67804


18-18: Clarify the purpose of the -p flag in test script

The addition of the -p flag to egg-bin test command needs documentation. Please clarify if this is related to:

  • Parallel test execution
  • Process isolation for async tests
  • Other test runner configurations

@fengmk2 fengmk2 mentioned this pull request Dec 11, 2024
32 tasks
@AntiMoron
Copy link
Contributor Author

所有测试用例补充 + fix

  • loadfile-esm 增加 esm 层 aysnc, promise function 的测试用例
  • loadfile增加 es 层 aysnc, promise function 的测试用例
  • load_file 增加应用层 aysnc, promise function, default=null, 基础 default import 的测试用例

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

🧹 Nitpick comments (11)
test/fixtures/loadfile-esm/es-module-default-async.js (1)

1-1: Remove redundant "use strict" directive

ES modules are automatically in strict mode, making this directive unnecessary.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile-esm/es-module-default-promise.js (1)

1-1: Remove redundant "use strict" directive

ES modules are automatically in strict mode, making this directive unnecessary.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/es-module-default-async.js (1)

1-1: Remove redundant "use strict" directive

Even in CommonJS-style modules that use ES module features, the strict mode directive is redundant when __esModule is true.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/es-module-default-null.js (1)

1-1: Remove redundant "use strict" directive

The "use strict" directive is unnecessary in ES modules as they are automatically in strict mode.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/loader/load_file.test.ts (1)

52-74: Consider adding error handling test cases

While the happy path tests are comprehensive, consider adding test cases for:

  • Rejected promises
  • Timeout scenarios
  • Invalid async function implementations

Example test cases:

it('should handle rejected promises in ES modules', async () => {
  app = createApp('load_file');
  await assert.rejects(async () => {
    await app.loader.loadFile(getFilepath('load_file/es-module-default-async-error.js'));
  }, /Expected error/);
});

it('should handle timeout in async functions', async () => {
  app = createApp('load_file');
  await assert.rejects(async () => {
    await app.loader.loadFile(getFilepath('load_file/es-module-default-async-timeout.js'));
  }, /Timeout/);
});
test/utils/index.test.ts (2)

60-68: Enhance promise type checking

The current check typeof result().then === 'function' could be improved for more robust promise detection.

Consider using:

-assert(typeof result().then === 'function');
+assert(result() instanceof Promise);

123-131: Add value assertion after promise resolution

The tests verify that a promise is returned but don't verify the resolved value.

Consider adding:

it('should resolve with correct value from async function', async () => {
  const result = await utils.loadFile(path.join(baseDir, 'es-module-default-async.js'));
  const value = await result();
  assert.deepEqual(value, { clients: 'Test Config' });
});
test/fixtures/load_file/es-module-default.js (1)

3-5: Add documentation for test fixture purpose

Since this is a test fixture, adding a brief comment explaining its purpose would improve maintainability.

+// Test fixture for ES module default export loading
 exports["default"] = {
   fn() {}
 };
test/fixtures/load_file/async.js (1)

3-5: Consider expanding test data to match real-world scenarios

Since this fixture tests async config loading (particularly for MySQL configs as mentioned in PR objectives), consider using more realistic test data.

 module.exports = async () => {
-  return { clients: "Test Config" };
+  return {
+    clients: {
+      mysql: {
+        host: 'test-host',
+        port: 3306,
+        user: 'test-user',
+        password: 'test-password',
+        database: 'test-db'
+      }
+    }
+  };
 };
test/fixtures/load_file/es-module-default-promise.js (1)

1-1: Remove redundant 'use strict' directive

ES modules are automatically in strict mode, making this directive unnecessary.

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile/es-module-default-promise.js (1)

3-5: LGTM! Consider enhancing test clarity

The implementation correctly demonstrates a Promise-returning function for testing async module loading. However, to make the test case more explicit about its purpose, consider adding a small delay to better simulate real-world async scenarios.

 exports["default"] = function () {
-  return Promise.resolve({ clients: "Test Config" });
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve({ clients: "Test Config" });
+    }, 10);
+  });
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e8ea36 and 0d78b15.

📒 Files selected for processing (13)
  • src/loader/egg_loader.ts (2 hunks)
  • test/fixtures/load_file/async.js (1 hunks)
  • test/fixtures/load_file/es-module-default-async.js (1 hunks)
  • test/fixtures/load_file/es-module-default-null.js (1 hunks)
  • test/fixtures/load_file/es-module-default-promise.js (1 hunks)
  • test/fixtures/load_file/es-module-default.js (1 hunks)
  • test/fixtures/load_file/promise_function.js (1 hunks)
  • test/fixtures/loadfile-esm/es-module-default-async.js (1 hunks)
  • test/fixtures/loadfile-esm/es-module-default-promise.js (1 hunks)
  • test/fixtures/loadfile/es-module-default-async.js (1 hunks)
  • test/fixtures/loadfile/es-module-default-promise.js (1 hunks)
  • test/loader/load_file.test.ts (1 hunks)
  • test/utils/index.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/fixtures/load_file/promise_function.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/loader/egg_loader.ts
🧰 Additional context used
🪛 Biome (1.9.4)
test/fixtures/load_file/es-module-default-promise.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/es-module-default-async.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile-esm/es-module-default-async.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile-esm/es-module-default-promise.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile/es-module-default-promise.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/async.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/es-module-default-null.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/load_file/es-module-default.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile/es-module-default-async.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (7)
test/fixtures/loadfile-esm/es-module-default-async.js (1)

2-4: LGTM! Clean and focused test fixture.

The async function implementation correctly demonstrates the use case of returning a configuration object asynchronously.

test/fixtures/loadfile-esm/es-module-default-promise.js (1)

2-4: LGTM! Good coverage of Promise-based returns.

The direct Promise.resolve() implementation provides good test coverage alongside the async/await pattern in the previous fixture.

test/fixtures/load_file/es-module-default-async.js (2)

2-5: LGTM! Good CommonJS compatibility test.

The implementation correctly demonstrates async function support in a CommonJS-style module, providing good coverage alongside the ES module fixtures.


1-5: Verify test coverage across module patterns

The test fixtures provide good coverage of different module patterns:

  1. ES modules with async/await
  2. ES modules with direct Promise returns
  3. CommonJS-style modules with async functions

Let's verify that these are all the module patterns we need to test:

✅ Verification successful

Test coverage for module patterns is comprehensive

The test fixtures cover all essential async/Promise module patterns:

  • ES modules with async/await (es-module-default-async.js)
  • ES modules with Promise returns (es-module-default-promise.js)
  • CommonJS with Promise returns (promise_function.js)
  • CommonJS with async/await (async.js)

The patterns include variations in:

  • Module systems (ES modules vs CommonJS)
  • Async handling (async/await vs Promise.resolve)
  • Function syntax (arrow functions vs regular functions)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any other async/promise-related test fixtures we might have missed
fd -e js -e ts . test/fixtures/ -x grep -l "async\|Promise\|resolve"

Length of output: 4922


Script:

#!/bin/bash
# Let's check the actual content of load_file test fixtures to understand the module patterns
echo "=== ES Module Default Async ==="
cat test/fixtures/load_file/es-module-default-async.js
echo -e "\n=== ES Module Default Promise ==="
cat test/fixtures/load_file/es-module-default-promise.js
echo -e "\n=== Promise Function ==="
cat test/fixtures/load_file/promise_function.js
echo -e "\n=== Async Function ==="
cat test/fixtures/load_file/async.js

Length of output: 915

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/loadfile/es-module-default-async.js (1)

3-5: LGTM! Implementation aligns with PR objectives.

The async function implementation correctly demonstrates the use case of returning configuration asynchronously, which is essential for the PR's goal of supporting dynamic config loading.

test/loader/load_file.test.ts (1)

40-50: LGTM! Good test coverage for CJS modules

The tests effectively verify:

  • Functions returning promises
  • Async functions
test/fixtures/load_file/es-module-default-promise.js (1)

3-5: LGTM! Clean implementation of async config loading

The implementation correctly demonstrates the async config loading use case mentioned in the PR objectives. The function returns a Promise that resolves to a configuration object, which is exactly what's needed for loading async configurations (e.g., from remote config centers).

@fengmk2 fengmk2 merged commit cb48d0e into eggjs:master Dec 18, 2024
20 checks passed
fengmk2 pushed a commit that referenced this pull request Dec 18, 2024
[skip ci]

## [6.2.0](v6.1.0...v6.2.0) (2024-12-18)

### Features

* support file returning async functions when loading it ([#272](#272)) ([cb48d0e](cb48d0e))
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