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: impl MultiInstanceInfo decorator #239

Merged
merged 4 commits into from
Sep 29, 2024
Merged

Conversation

killagu
Copy link
Contributor

@killagu killagu commented Sep 29, 2024

Add multi instances info for constructor inject mode.

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

Summary by CodeRabbit

  • New Features

    • Introduced the MultiInstanceInfo decorator for enhanced multi-instance management.
    • Added support for multi-instance constructor attributes and indexing in relevant classes.
    • Enhanced getEggObject method to accept additional parameters for improved flexibility.
  • Bug Fixes

    • Improved the construction logic for EggObject to handle multi-instance information.
  • Tests

    • Added a test case to verify the loading of multiple instances using the new constructor pattern.
  • Documentation

    • Updated interface definitions to include properties related to multi-instance management.

Add multi instances info for constructor inject mode.
Copy link

coderabbitai bot commented Sep 29, 2024

Walkthrough

The changes introduce a new decorator, MultiInstanceInfo, which enhances the management of multi-instance behavior in classes. This involves adding new properties and methods across several files, enabling the storage and retrieval of multi-instance constructor metadata. Updates also include modifications to existing classes and interfaces to accommodate these functionalities, as well as new test cases to validate the implementation.

Changes

File Path Change Summary
core/core-decorator/index.ts Added export for MultiInstanceInfo from ./src/decorator.
core/core-decorator/src/decorator/MultiInstanceInfo.ts Introduced MultiInstanceInfo decorator function for class methods/parameters.
core/core-decorator/src/util/PrototypeUtil.ts Added methods for setting/retrieving multi-instance constructor attributes and index; introduced two new symbols.
core/metadata/src/impl/EggPrototypeBuilder.ts Added properties for multiInstanceConstructorIndex and multiInstanceConstructorAttributes; updated methods to utilize these properties.
core/metadata/src/impl/EggPrototypeImpl.ts Added optional properties for multi-instance constructor metadata; updated constructor signature.
core/runtime/src/impl/EggObjectImpl.ts Enhanced construction logic to handle multi-instance constructor information.
core/runtime/test/LoadUnitInstance.test.ts Added test case for loading multiple instances with constructor attributes.
core/runtime/test/fixtures/modules/multi-instance-module/MultiInstanceConstructor.ts Introduced Bar and FooLoggerConstructor classes for multi-instance prototype testing.
core/types/metadata/model/EggPrototype.ts Added optional properties for multi-instance constructor metadata in the EggPrototype interface.

Possibly related PRs

  • feat: @Middleware support Advice #231: The changes involve middleware support, which may relate to the decorator functionality introduced in the main PR, particularly in how decorators can be applied to manage multi-instance behavior.
  • feat: add LifecyclePreLoad #234: This PR introduces lifecycle hooks that could interact with the multi-instance management features in the main PR, as both enhance the framework's capabilities for managing instances and their lifecycles.
  • feat: support inject in constructor #237: Enhancements to dependency injection within constructors, related to the management of multi-instance behavior and constructor attributes.

🐇 In the meadow where bunnies play,
New decorators hop in, brightening the day.
Multi-instance magic, oh what a sight,
With attributes dancing, everything feels right!
So let’s cheer for the code, with a joyful thump,
For decorators and instances, we all love to jump! 🐰✨


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

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

🧹 Outside diff range and nitpick comments (4)
core/metadata/src/impl/EggPrototypeImpl.ts (1)

44-45: LGTM: Constructor updated correctly, with a minor suggestion

The constructor has been properly updated to include the new properties:

  • The signature includes the new optional parameters with correct types.
  • The new properties are correctly initialized in the constructor body.

For consistency with other optional parameters, consider adding default values:

constructor(
  // ... other parameters ...
- multiInstanceConstructorIndex?: number,
- multiInstanceConstructorAttributes?: QualifierAttribute[],
+ multiInstanceConstructorIndex: number | undefined = undefined,
+ multiInstanceConstructorAttributes: QualifierAttribute[] | undefined = undefined,
) {
  // ... other initializations ...
  this.multiInstanceConstructorIndex = multiInstanceConstructorIndex;
  this.multiInstanceConstructorAttributes = multiInstanceConstructorAttributes;
}

This change would make the new parameters consistent with the injectType parameter, which has a default value.

Also applies to: 58-59

core/core-decorator/src/util/PrototypeUtil.ts (1)

159-165: LGTM: New methods for managing multi-instance constructor index

The setMultiInstanceConstructorIndex and getMultiInstanceConstructorIndex methods are well-implemented:

  • They use MetadataUtil consistently with other methods in the class.
  • The methods follow the existing code style and naming conventions.

For consistency with the getMultiInstanceConstructorAttributes method, consider initializing the index with a default value in the getter:

 static getMultiInstanceConstructorIndex(clazz: EggProtoImplClass): number | undefined {
-  return MetadataUtil.getMetaData(PrototypeUtil.MULTI_INSTANCE_CONSTRUCTOR_INDEX, clazz);
+  return MetadataUtil.getMetaData(PrototypeUtil.MULTI_INSTANCE_CONSTRUCTOR_INDEX, clazz) ?? -1;
 }

This change would ensure that the method always returns a number, making it easier to use in other parts of the codebase.

core/metadata/src/impl/EggPrototypeBuilder.ts (1)

38-39: Add documentation for new properties

To improve code maintainability and readability, consider adding JSDoc comments for the newly added properties multiInstanceConstructorIndex and multiInstanceConstructorAttributes to explain their purpose and usage.

core/runtime/src/impl/EggObjectImpl.ts (1)

Line range hint 95-106: Consider handling empty injectObjects array

When mapping over this.proto.injectObjects!, if injectObjects is an empty array, Promise.all will resolve to an empty array. Ensure that this is the intended behavior and that constructArgs will be correctly formed even when there are no inject objects.

If necessary, you can add a check or a comment to clarify that this case has been considered.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6cbdfc7 and 311bc39.

📒 Files selected for processing (9)
  • core/core-decorator/index.ts (1 hunks)
  • core/core-decorator/src/decorator/MultiInstanceInfo.ts (1 hunks)
  • core/core-decorator/src/util/PrototypeUtil.ts (3 hunks)
  • core/metadata/src/impl/EggPrototypeBuilder.ts (4 hunks)
  • core/metadata/src/impl/EggPrototypeImpl.ts (4 hunks)
  • core/runtime/src/impl/EggObjectImpl.ts (2 hunks)
  • core/runtime/test/LoadUnitInstance.test.ts (2 hunks)
  • core/runtime/test/fixtures/modules/multi-instance-module/MultiInstanceConstructor.ts (1 hunks)
  • core/types/metadata/model/EggPrototype.ts (1 hunks)
🔇 Additional comments (14)
core/core-decorator/src/decorator/MultiInstanceInfo.ts (2)

1-2: LGTM: Imports are appropriate.

The imports are correctly structured and seem to provide the necessary dependencies for the implementation.


1-9: Overall, the implementation looks good with room for minor improvements.

The MultiInstanceInfo decorator is well-structured and focused on its purpose. The suggested improvements in type safety and input validation will enhance its robustness. Consider adding unit tests to verify the behavior of this decorator, especially with different input scenarios.

To ensure proper test coverage, let's check for existing tests:

core/core-decorator/index.ts (1)

10-10: LGTM! Verify implementation and update documentation.

The new export for MultiInstanceInfo is correctly added and follows the existing pattern in the file. This aligns with the PR objective of implementing the MultiInstanceInfo decorator.

To ensure completeness:

  1. Verify that the MultiInstanceInfo decorator is properly implemented in ./src/decorator/MultiInstanceInfo.ts.
  2. Update the module's documentation to include information about this new decorator.

Run the following script to check the implementation:

core/metadata/src/impl/EggPrototypeImpl.ts (3)

1-1: LGTM: Import statement updated correctly

The addition of QualifierAttribute to the import statement is consistent with its usage in the new property multiInstanceConstructorAttributes.


29-30: LGTM: New properties added correctly

The new properties multiInstanceConstructorIndex and multiInstanceConstructorAttributes are well-defined:

  • They are correctly declared as readonly, which is good for immutability.
  • The optional modifier (?) is appropriate, as these properties might not always be needed.
  • The types are consistent with their intended use.
  • The naming is clear and descriptive.

Line range hint 1-59: Summary: MultiInstanceInfo implementation looks good

The changes to EggPrototypeImpl successfully implement the MultiInstanceInfo functionality:

  1. New properties multiInstanceConstructorIndex and multiInstanceConstructorAttributes are added.
  2. The constructor is updated to initialize these properties.
  3. Import statements are correctly updated.

These changes enhance the class's capability to handle multi-instance constructors without altering existing functionality, aligning well with the PR objectives.

To ensure the changes are used correctly throughout the codebase, run the following script:

✅ Verification successful

Verification Successful: MultiInstanceInfo properties are correctly utilized

The new properties multiInstanceConstructorIndex and multiInstanceConstructorAttributes are actively used across the codebase:

  • multiInstanceConstructorIndex

    • core/types/metadata/model/EggPrototype.ts
    • core/runtime/src/impl/EggObjectImpl.ts
    • core/metadata/src/impl/EggPrototypeBuilder.ts
    • core/metadata/src/impl/EggPrototypeImpl.ts
    • core/core-decorator/src/util/PrototypeUtil.ts
  • multiInstanceConstructorAttributes

    • core/core-decorator/src/util/PrototypeUtil.ts
    • core/metadata/src/impl/EggPrototypeImpl.ts
    • core/metadata/src/impl/EggPrototypeBuilder.ts
    • core/types/metadata/model/EggPrototype.ts
    • core/runtime/src/impl/EggObjectImpl.ts

No related TODOs were found, ensuring there are no pending tasks concerning these changes. The implementation aligns with the PR objectives, enhancing the class's capability to handle multi-instance constructors without impacting existing functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify usage of new MultiInstanceInfo properties

# Test: Search for usages of the new properties
echo "Searching for usages of multiInstanceConstructorIndex:"
rg --type typescript 'multiInstanceConstructorIndex'

echo "Searching for usages of multiInstanceConstructorAttributes:"
rg --type typescript 'multiInstanceConstructorAttributes'

# Test: Check for any TODOs related to these changes
echo "Checking for related TODOs:"
rg --type typescript -i 'todo.*multiinstance'

Length of output: 576


Script:

#!/bin/bash
# Description: Verify usage of new MultiInstanceInfo properties without specifying file type

# Test: Search for usages of the new properties
echo "Searching for usages of multiInstanceConstructorIndex:"
rg 'multiInstanceConstructorIndex'

echo "Searching for usages of multiInstanceConstructorAttributes:"
rg 'multiInstanceConstructorAttributes'

# Test: Check for any TODOs related to these changes
echo "Checking for related TODOs:"
rg -i 'todo.*multiinstance'

Length of output: 2618

core/types/metadata/model/EggPrototype.ts (1)

112-113: LGTM! Consider adding documentation for new properties.

The addition of multiInstanceConstructorIndex and multiInstanceConstructorAttributes aligns well with the PR objective of implementing functionality for handling multiple instances information in the constructor injection mode. These optional properties maintain backward compatibility while extending the interface's capabilities.

Consider adding JSDoc comments for these new properties to improve clarity:

/**
 * Index of the constructor parameter that handles multiple instances.
 */
readonly multiInstanceConstructorIndex?: number;

/**
 * Additional metadata for qualifying multiple instances.
 */
readonly multiInstanceConstructorAttributes?: QualifierAttribute[];

Let's verify if these changes are consistent across the codebase:

✅ Verification successful

Let's adjust the shell scripts to correctly target TypeScript files by specifying the file patterns directly.


LGTM! The added properties are consistently used across the codebase. Consider adding documentation for the new properties.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of new properties and related multi-instance functionality

# Test 1: Search for usages of multiInstanceConstructorIndex
echo "Searching for multiInstanceConstructorIndex usage:"
rg --type typescript "multiInstanceConstructorIndex"

# Test 2: Search for usages of multiInstanceConstructorAttributes
echo "Searching for multiInstanceConstructorAttributes usage:"
rg --type typescript "multiInstanceConstructorAttributes"

# Test 3: Search for other multi-instance related functionality
echo "Searching for other multi-instance related functionality:"
rg --type typescript "multiInstance"

Length of output: 609


Script:

# 
#!/bin/bash
# Description: Check for usage of new properties and related multi-instance functionality

# Test 1: Search for usages of multiInstanceConstructorIndex
echo "Searching for multiInstanceConstructorIndex usage in .ts and .tsx files:"
rg -g "*.ts" -g "*.tsx" "multiInstanceConstructorIndex"

# Test 2: Search for usages of multiInstanceConstructorAttributes
echo "Searching for multiInstanceConstructorAttributes usage in .ts and .tsx files:"
rg -g "*.ts" -g "*.tsx" "multiInstanceConstructorAttributes"

# Test 3: Search for other multi-instance related functionality
echo "Searching for other multi-instance related functionality in .ts and .tsx files:"
rg -g "*.ts" -g "*.tsx" "multiInstance"

Length of output: 7033

core/runtime/test/LoadUnitInstance.test.ts (1)

Line range hint 1-141: Overall, good addition to the test suite with room for minor improvements.

The new test case "should load multi instance with constructor" is a valuable addition to the test suite. It extends the coverage to include constructor-based multi-instance creation, which is important for ensuring the robustness of the MultiInstanceInfo decorator implementation.

After addressing the issues mentioned in the previous comment, this test will provide a solid verification of the multi-instance functionality with constructors. Good job on maintaining test coverage alongside feature development.

core/core-decorator/src/util/PrototypeUtil.ts (3)

10-10: LGTM: New import added for QualifierAttribute

The addition of the QualifierAttribute import is appropriate for the new functionality being implemented.


25-26: LGTM: New symbols added for multi-instance constructor metadata

The addition of MULTI_INSTANCE_CONSTRUCTOR_INDEX and MULTI_INSTANCE_CONSTRUCTOR_ATTRIBUTES symbols is consistent with the existing code style and naming conventions. These symbols will be used to manage metadata for multi-instance constructors.


151-157: LGTM: New methods for managing multi-instance constructor attributes

The setMultiInstanceConstructorAttributes and getMultiInstanceConstructorAttributes methods are well-implemented:

  • They use MetadataUtil consistently with other methods in the class.
  • The getter method returns an empty array if no attributes are found, which is a good practice.
  • The methods follow the existing code style and naming conventions.
core/runtime/test/fixtures/modules/multi-instance-module/MultiInstanceConstructor.ts (1)

37-40: Constructor correctly initializes properties with injected values

The constructor effectively uses @Inject() to inject an instance of Bar and @MultiInstanceInfo() to access the ObjectInfo. The properties foo and bar are properly initialized using the qualifier value and the injected Bar instance, respectively.

core/metadata/src/impl/EggPrototypeBuilder.ts (1)

2-2: Import of QualifierAttribute is appropriate

The import statement correctly includes QualifierAttribute from @eggjs/core-decorator, which is used later in the code.

core/runtime/src/impl/EggObjectImpl.ts (1)

118-118: Ensure multiInstanceConstructorIndex is within bounds

When using constructArgs.splice(this.proto.multiInstanceConstructorIndex, 0, objInfo);, there's a risk of multiInstanceConstructorIndex being out of the bounds of the constructArgs array, which could lead to unexpected behavior.

Verify that multiInstanceConstructorIndex is a valid index within the range of constructArgs to prevent potential runtime errors.

Run the following script to check the validity of multiInstanceConstructorIndex:

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)
plugin/tegg/typings/index.d.ts (1)

62-62: LGTM! Consider adding JSDoc comments for clarity.

The addition of name and qualifiers parameters to the getEggObject method signature enhances its flexibility and aligns with the PR objective of handling multiple instances. This change is well-implemented and consistent with the summary.

Consider adding JSDoc comments to explain the purpose and usage of these new parameters. For example:

/**
 * Retrieves an egg object based on the provided class, name, and qualifiers.
 * @param clazz The class of the egg object to retrieve.
 * @param name Optional name to identify the egg object.
 * @param qualifiers Optional qualifiers to further specify the egg object.
 * @returns A promise that resolves to the requested egg object.
 */
getEggObject<T>(clazz: EggProtoImplClass<T>, name?: string, qualifiers?: QualifierInfo | QualifierInfo[]): Promise<T>;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 311bc39 and 292b5ff.

📒 Files selected for processing (2)
  • core/runtime/src/impl/EggObjectImpl.ts (3 hunks)
  • plugin/tegg/typings/index.d.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/runtime/src/impl/EggObjectImpl.ts
🔇 Additional comments (2)
plugin/tegg/typings/index.d.ts (2)

71-71: LGTM! Consistent implementation across interfaces.

The changes to the getEggObject method in the TEggContext interface mirror those in the TEggApplication interface. This consistency is commendable and maintains coherence across the codebase.


Line range hint 1-85: Overall assessment: Well-implemented changes with minor suggestions.

The modifications to the getEggObject method signatures in both TEggApplication and TEggContext interfaces are well-implemented and align with the PR objectives. They enhance the flexibility of the egg module in handling multiple instances. Consider adding JSDoc comments to improve documentation, as suggested earlier.

@killagu killagu merged commit 70d4d95 into master Sep 29, 2024
12 checks passed
@killagu killagu deleted the feat/mult_instance_proto branch September 29, 2024 07:52
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