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: mv Singleton from egg #288

Merged
merged 5 commits into from
Jan 20, 2025
Merged

feat: mv Singleton from egg #288

merged 5 commits into from
Jan 20, 2025

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Jan 20, 2025

Summary by CodeRabbit

  • New Features

    • Added singleton management functionality to the application.
    • Enhanced logging capabilities for core system components.
    • Introduced new methods for managing application-wide singleton instances.
  • Improvements

    • Expanded module exports to include singleton-related utilities.
    • Provided more explicit interfaces for accessing loggers.
  • Bug Fixes

    • Improved error handling and validation in singleton instance creation.
  • Tests

    • Added extensive test coverage for the Singleton class, validating various creation scenarios.

Copy link

coderabbitai bot commented Jan 20, 2025

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 43 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

Reviewing files that changed from the base of the PR and between a4c7901 and c44d4b8.

📒 Files selected for processing (2)
  • package.json (0 hunks)
  • test/egg.test.ts (1 hunks)

Walkthrough

This pull request introduces several enhancements to the Egg.js framework, focusing on singleton management and logging capabilities. Key changes include the addition of a new Singleton class in src/singleton.ts, which supports both synchronous and asynchronous instance creation. The EggCore class in src/egg.ts is extended with new getter methods for logging and a method for adding singletons. Additionally, the module's exports are updated to include the new singleton functionality, and comprehensive tests for the Singleton class are added.

Changes

File Changes
src/egg.ts - Added logger and coreLogger getter methods
- Introduced addSingleton method for singleton management
- Added new imports for singleton-related types
src/index.ts - Added re-export for singleton.js module
src/singleton.ts - New Singleton class implementation
- Added types and interfaces for singleton management
- Methods for synchronous and asynchronous instance creation
test/index.test.ts - Updated to include Singleton in expected module properties
test/singleton.test.ts - Added comprehensive test suite for Singleton class
- Included test utilities like DataService and creation functions

Sequence Diagram

sequenceDiagram
    participant App as EggCore
    participant Singleton
    participant Client as Singleton Instance

    App->>Singleton: addSingleton(name, createMethod)
    Singleton-->>App: Register singleton initialization
    App->>Singleton: init()
    alt Sync Creation
        Singleton->>Client: createInstance()
    else Async Creation
        Singleton->>Client: createInstanceAsync()
    end
    Singleton-->>App: Initialized Client
Loading

Possibly related PRs

Poem

🐰 Singleton Hop, a Rabbit's Tale

In Egg.js world, where instances prevail,
A singleton dance, both sync and async sail
One instance to rule, with methods so neat
Our framework now dances to a more elegant beat!

🥚✨ Hop, hop, hooray! 🎉


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 Jan 20, 2025

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/core/@eggjs/core@288

commit: c44d4b8

Copy link

codecov bot commented Jan 20, 2025

Codecov Report

Attention: Patch coverage is 92.85714% with 13 lines in your changes missing coverage. Please review.

Project coverage is 97.51%. Comparing base (7adabd5) to head (c44d4b8).
Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/egg.ts 59.37% 13 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #288      +/-   ##
==========================================
- Coverage   97.76%   97.51%   -0.26%     
==========================================
  Files          10       11       +1     
  Lines        3363     3544     +181     
  Branches      599      630      +31     
==========================================
+ Hits         3288     3456     +168     
- Misses         75       88      +13     

☔ 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: 4

🧹 Nitpick comments (3)
src/singleton.ts (2)

32-61: Refactor duplicated code in initSync() and initAsync() methods

The initSync() and initAsync() methods contain duplicated logic for handling options.client and options.clients. Refactoring the common code into a shared private method would improve maintainability and reduce redundancy.

Consider creating a private method like initClients() to handle the shared logic. For example:

private initClients(clientGetter: (config: Record<string, any>, name: string) => T | Promise<T>) {
  const options = this.options;
  if (options.client) {
    const client = clientGetter(options.client, options.name);
    this.#setClientToApp(client);
    this.#extendDynamicMethods(client);
    return;
  }

  if (options.clients) {
    const clientEntries = Object.entries(options.clients);
    const clientsPromise = clientEntries.map(([id, config]) =>
      Promise.resolve(clientGetter(config as Record<string, any>, id))
        .then(client => this.clients.set(id, client as T))
    );
    return Promise.all(clientsPromise)
      .then(() => {
        this.#setClientToApp(this);
      });
  }

  // No config.clients and config.client
  this.#setClientToApp(this);
}

Then, initSync() and initAsync() can utilize this method:

initSync() {
  assert(!isAsyncFunction(this.create), `[egg:singleton] ${this.name} create method must be synchronous`);
  this.initClients(this.createInstance.bind(this));
}

async initAsync() {
  assert(isAsyncFunction(this.create), `[egg:singleton] ${this.name} create method must be asynchronous`);
  await this.initClients(this.createInstanceAsync.bind(this));
}

Also applies to: 63-88


94-99: Deprecation of get(id: string) method

The get(id: string) method is marked as deprecated in favor of getSingletonInstance(id). To enforce this deprecation:

  • Use the @deprecated JSDoc tag properly so that IDEs and compilers can warn users.
  • If possible, consider removing the deprecated method in a future major release to clean up the API.

Here's how you can update the JSDoc:

/**
- * @deprecated please use `getSingletonInstance(id)` instead
+ * @deprecated Use `getSingletonInstance(id)` instead.
 */
test/singleton.test.ts (1)

26-29: Consider using undefined assignment instead of delete operator.

The delete operator can impact performance. Consider using undefined assignment instead:

  afterEach(() => {
-   delete (DataService as any).prototype.createInstance;
-   delete (DataService as any).prototype.createInstanceAsync;
+   (DataService as any).prototype.createInstance = undefined;
+   (DataService as any).prototype.createInstanceAsync = undefined;
  });
🧰 Tools
🪛 Biome (1.9.4)

[error] 27-27: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c07821d and 4dec832.

📒 Files selected for processing (5)
  • src/egg.ts (3 hunks)
  • src/index.ts (1 hunks)
  • src/singleton.ts (1 hunks)
  • test/index.test.ts (1 hunks)
  • test/singleton.test.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/egg.ts

[warning] 192-193: src/egg.ts#L192-L193
Added lines #L192 - L193 were not covered by tests


[warning] 196-197: src/egg.ts#L196-L197
Added lines #L196 - L197 were not covered by tests


[warning] 205-217: src/egg.ts#L205-L217
Added lines #L205 - L217 were not covered by tests

🪛 Biome (1.9.4)
test/singleton.test.ts

[error] 27-27: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Node.js / Test (windows-latest, 23)
  • GitHub Check: Node.js / Test (windows-latest, 22)
  • GitHub Check: Node.js / Test (windows-latest, 20)
  • GitHub Check: Node.js / Test (windows-latest, 18.19.0)
  • GitHub Check: Node.js / Test (windows-latest, 18)
🔇 Additional comments (5)
src/index.ts (1)

8-8: Expose Singleton in module exports

The addition of export * from './singleton.js'; properly re-exports the Singleton class and its associated types, making them available for external use.

test/index.test.ts (1)

32-32: Confirm inclusion of 'Singleton' in exported properties

The test has been updated to include 'Singleton' in the list of expected keys from EggCore. This change ensures that the Singleton class is correctly exported and available for use.

Please run the test suite to confirm that all assertions pass and that Singleton is accessible as intended.

test/singleton.test.ts (3)

172-172: Verify error handling for createInstanceAsync.

The test calls createInstanceAsync but doesn't verify error cases. Consider adding tests for:

  • Invalid config parameters
  • Initialization failures
  • Timeout scenarios

Also applies to: 201-201


358-365: LGTM! Good error handling test.

The test properly verifies that synchronous creation is rejected when only asynchronous creation is supported.


150-176: LGTM! Comprehensive edge case testing.

Excellent test coverage for unextensible and frozen objects. The tests verify that the singleton functionality works correctly with Object.preventExtensions and Object.freeze.

Also applies to: 178-205

src/singleton.ts Outdated Show resolved Hide resolved
src/singleton.ts Outdated Show resolved Hide resolved
src/egg.ts Show resolved Hide resolved
Comment on lines +204 to +217
addSingleton(name: string, create: SingletonCreateMethod) {
const options: SingletonOptions = {
name,
create,
app: this,
};
const singleton = new Singleton(options);
const initPromise = singleton.init();
if (initPromise) {
this.beforeStart(async () => {
await initPromise;
});
}
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for addSingleton method in egg.test.ts

While the Singleton class and beforeStart hook are well tested individually, the addSingleton method needs dedicated test coverage to verify:

  • Integration between Singleton creation and beforeStart hook registration
  • Error handling for invalid inputs
  • Proper initialization flow
  • Cases where init returns a promise vs no promise
🔗 Analysis chain

Add test coverage for addSingleton method.

The addSingleton method implementation looks correct but lacks test coverage. The method:

  1. Creates a new Singleton instance
  2. Initializes it
  3. Registers a beforeStart hook if initialization is asynchronous

However, we should verify:

  • Error handling for invalid inputs
  • The beforeStart hook registration
  • The initialization promise handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing addSingleton tests
rg -l "addSingleton" test/

Length of output: 26


Script:

#!/bin/bash
# Find all test files
echo "=== All test files ==="
fd -e test.ts -e spec.ts -e test.js -e spec.js

echo -e "\n=== Files containing 'singleton' (case-insensitive) ==="
rg -il "singleton" 

echo -e "\n=== Test patterns for initialization ==="
rg "beforeStart|init\(" test/ || true

Length of output: 5955


Script:

#!/bin/bash
# Check singleton test content
echo "=== Singleton test content ==="
rg "addSingleton|describe\('Singleton" -A 5 test/singleton.test.ts

echo -e "\n=== Egg test singleton content ==="
rg "addSingleton|describe\('singleton" -A 5 test/egg.test.ts

Length of output: 293


Script:

#!/bin/bash
# View complete singleton test content
echo "=== Complete singleton test content ==="
cat test/singleton.test.ts

echo -e "\n=== Relevant egg test sections ==="
rg -B 2 -A 10 "singleton|Singleton" test/egg.test.ts

Length of output: 11116

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 205-217: src/egg.ts#L205-L217
Added lines #L205 - L217 were not covered by tests

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 (3)
src/singleton.ts (2)

25-25: Fix grammatical error in assertion message

The assertion message on line 25 contains a grammatical error. It should read "already exists" instead of "is already exists".

Apply this diff to correct the message:

-    assert(!(options.name in options.app), `[@eggjs/core/singleton] ${options.name} is already exists in app`);
+    assert(!(options.name in options.app), `[@eggjs/core/singleton] ${options.name} already exists in app`);

111-111: Fix grammatical error in assertion message in createInstance()

The assertion message in createInstance() contains a grammatical error. It should read "only supports synchronous creation" instead of "only support synchronous creation".

Apply this diff to correct the message:

-    `[@eggjs/core/singleton] ${this.name} only support synchronous creation, please use createInstanceAsync`);
+    `[@eggjs/core/singleton] ${this.name} only supports synchronous creation; please use createInstanceAsync`);
test/singleton.test.ts (1)

27-28: Avoid using the delete operator for performance reasons

Using the delete operator can negatively impact performance because it forces the engine to reconfigure the object's property map. It's recommended to set the property to undefined instead.

Apply this diff to avoid the use of delete:

-    delete (DataService as any).prototype.createInstance;
-    delete (DataService as any).prototype.createInstanceAsync;
+    (DataService as any).prototype.createInstance = undefined;
+    (DataService as any).prototype.createInstanceAsync = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 27-27: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dec832 and a4c7901.

📒 Files selected for processing (2)
  • src/singleton.ts (1 hunks)
  • test/singleton.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
test/singleton.test.ts

[error] 27-27: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Node.js / Test (windows-latest, 23)
  • GitHub Check: Node.js / Test (windows-latest, 22)
  • GitHub Check: Node.js / Test (windows-latest, 20)
  • GitHub Check: Node.js / Test (windows-latest, 18.19.0)
  • GitHub Check: Node.js / Test (windows-latest, 18)
  • GitHub Check: Node.js / Test (ubuntu-latest, 18.19.0)
  • GitHub Check: Node.js / Test (macos-latest, 18.19.0)
🔇 Additional comments (1)
src/singleton.ts (1)

135-146: Avoid modifying __proto__ and extending non-extensible objects

In the #extendDynamicMethods() method, modifying __proto__ is discouraged due to performance and maintainability concerns. This can lead to hard-to-debug issues.

Consider alternative approaches:

  • Avoid modifying the prototype chain. Instead of using client.__proto__, consider refactoring to avoid changing the object's prototype.
  • Wrap the client object. If the client is not extensible or is frozen, you might wrap it in another object that provides the additional methods.
  • Access methods directly. Document how to access createInstance methods directly from the singleton without extending the client.

@fengmk2 fengmk2 merged commit b5ebf68 into master Jan 20, 2025
22 of 24 checks passed
@fengmk2 fengmk2 deleted the singleton branch January 20, 2025 14:42
fengmk2 pushed a commit that referenced this pull request Jan 20, 2025
[skip ci]

## [6.3.0](v6.2.13...v6.3.0) (2025-01-20)

### Features

* mv Singleton from egg ([#288](#288)) ([b5ebf68](b5ebf68))
fengmk2 added a commit to eggjs/egg that referenced this pull request Jan 20, 2025
fengmk2 added a commit to eggjs/egg that referenced this pull request Jan 21, 2025
eggjs/core#288

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

Based on the comprehensive summary, here are the release notes:

- **New Features**
- Added new CI workflows for different testing clusters and library
testing
  - Enhanced continuous integration configuration

- **Dependency Updates**
  - Updated `@eggjs/core` from version 6.2.13 to 6.3.0

- **Testing Improvements**
  - Added new test scripts for specific test clusters
  - Expanded error handling and logging test coverage
  - Restructured test file organization

- **Code Refactoring**
  - Removed singleton implementation from core library
  - Updated type assertions and import paths
  - Simplified error handling in test cases

- **Chores**
  - Updated GitHub Actions workflows
  - Reorganized test directory structure
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant