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

bal 2254 rule engine v2 #2470

Merged
merged 8 commits into from
Jun 24, 2024
Merged

Conversation

liorzam
Copy link
Collaborator

@liorzam liorzam commented Jun 23, 2024

image

Summary by CodeRabbit

  • New Features

    • Introduced a Rule Engine module to the application, enhancing rule validation and error handling capabilities.
    • Added custom error handling for rule-based operations.
    • Implemented various comparison operators for comprehensive rule evaluations.
    • Provided type definitions and schemas for structured rule processing.
  • Tests

    • Included unit tests to ensure the accuracy and reliability of rule validations.

Copy link

changeset-bot bot commented Jun 23, 2024

⚠️ No Changeset found

Latest commit: dc70519

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jun 23, 2024

Walkthrough

The changes enhance the rule engine within the workflows-service by introducing extensive new functionality and structure. Key modifications include the integration of the RuleEngineModule into the application's core module, the creation of custom error classes, and the development of various helper classes, schemas, enums, and type definitions. Together, these additions facilitate improved rule validation and error handling, laying a robust foundation for complex rule-based operations.

Changes

Files Change Summary
services/.../src/app.module.ts Imported and included RuleEngineModule for initialization.
services/.../src/rule-engine/core/errors.ts Introduced custom error classes: OperationNotFoundError, DataValueNotFoundError, MissingKeyError, and ValidationFailedError. Added EngineErrors type for handling specific errors.
services/.../src/rule-engine/core/operators/constants.ts Added operationHelpers object mapping operations to helper functions.
services/.../src/rule-engine/core/operators/enums.ts Introduced constants for operations and operators in the rule engine.
services/.../src/rule-engine/core/operators/helpers.ts Defined various comparison operator classes extending BaseOperator, including Equals, GreaterThan, LessThan, and others.
services/.../src/rule-engine/core/operators/schemas.ts Introduced schemas for different operations, such as PrimitiveSchema, BetweenSchema, LastYearsSchema, and ruleSchema.
services/.../src/rule-engine/core/operators/types.ts Added type definitions for operators, like primitive, BetweenParams, and LastYearsParams, and detailed condition function types and mappings.
services/.../src/rule-engine/core/rule-engine.ts Introduced functions validateRule and validateRuleSet for validating rules and rule sets.
services/.../src/rule-engine/core/rule-engine.unit.test.ts Added tests for validating rule sets using mock data, covering different rules and expected outcomes.
services/.../src/rule-engine/core/types.ts Introduced type definitions for operations, rules, rule sets, and validation results, such as TOperation, TOperator, Rule, and RuleSet.
services/.../src/rule-engine/rule-engine.module.ts Created RuleEngineModule for providing and exporting RuleEngineService and RuleStoreService.
services/.../src/rule-engine/rule-store.service.ts Added RuleStoreService class with a method findAll to retrieve RuleSet based on given parameters.

Poem

In the world of code, a rabbit hops,
Bringing rules and constants to the crops.
With errors caught and schemas clear,
The logic flows without a fear.
Operators dance, comparisons cheer,
The rule engine's power now holds dear.
So code and dream, my friend, let's gear!


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 260e7d5 and 9707548.

Files selected for processing (13)
  • services/workflows-service/src/app.module.ts (2 hunks)
  • services/workflows-service/src/rule-engine/core/errors.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/constants.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/enums.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/helpers.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/schemas.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/types.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.unit.test.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/types.ts (1 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.module.ts (1 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.service.ts (1 hunks)
  • services/workflows-service/src/rule-engine/rule-store.service.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • services/workflows-service/src/rule-engine/core/operators/enums.ts
  • services/workflows-service/src/rule-engine/rule-engine.module.ts
Additional comments not posted (12)
services/workflows-service/src/rule-engine/core/operators/types.ts (1)

1-16: Well-defined types for rule engine operations.

The type definitions in this file are crucial for ensuring type safety and clarity across the rule engine functionality. The use of generic types in ConditionFn is particularly commendable as it provides flexibility while maintaining type safety.

services/workflows-service/src/rule-engine/core/operators/constants.ts (1)

1-13: Effective mapping of operations to helper functions.

This mapping ensures that each operation can be easily associated with its corresponding logic, which is fundamental for the maintainability and scalability of the rule engine. The use of as const ensures that the object is treated as a constant, preventing unintended modifications.

services/workflows-service/src/rule-engine/rule-engine.service.ts (1)

1-20: Well-structured method for running rule engine operations.

The run method is well-implemented, with clear steps for retrieving rules, creating a rule engine instance, and executing it. This structure enhances readability and maintainability.

services/workflows-service/src/rule-engine/core/types.ts (1)

1-36: Comprehensive type definitions enhancing the rule engine's robustness.

The extended type definitions for operations, operators, and results are crucial for ensuring the rule engine's functionality is robust and error-resistant. The clear distinction between PassedRuleResult and FailedRuleResult is particularly beneficial for handling different outcomes explicitly.

services/workflows-service/src/rule-engine/core/errors.ts (4)

3-8: Ensure consistent error naming convention.

The OperationNotFoundError class explicitly sets its name using this.name = OperationNotFoundError.name;. This is a good practice as it ensures the error's name property matches the class name, which can be helpful for debugging and logging.


10-15: Consistent error handling approach.

The DataValueNotFoundError follows the same pattern as OperationNotFoundError, setting its name explicitly. This consistency in error handling across different classes is good for maintainability.


24-41: Detailed error information in ValidationFailedError.

The constructor of ValidationFailedError optionally accepts a ZodError, and if present, it formats and sets detailed error information. This is a robust design choice as it leverages the structured error information from Zod to provide more detailed feedback.


43-48: Type alias for error handling.

EngineErrors type alias is used to define a union of the custom errors and the generic Error. This is useful for type-checking and ensuring that error handling in the application can accommodate both specific and unexpected errors.

services/workflows-service/src/rule-engine/core/rule-engine.ts (1)

13-38: Robust rule validation logic in validateRule.

The validateRule function comprehensively checks for various error conditions (missing key, invalid data value, unknown operation) and throws the appropriate custom errors. This ensures that rules are thoroughly validated before execution, contributing to the reliability of the rule engine.

services/workflows-service/src/rule-engine/core/rule-engine.unit.test.ts (1)

12-150: Comprehensive test coverage in rule-engine.unit.test.ts.

The unit tests cover a variety of scenarios including simple rule validation, handling missing keys, unknown operations, and incorrect values. The use of descriptive test names and the structured arrangement of tests enhance readability and maintainability.

services/workflows-service/src/app.module.ts (1)

124-124: Proper integration of RuleEngineModule.

The RuleEngineModule has been correctly added to the imports array in AppModule. This ensures that the rule engine's functionality is available application-wide, aligning with the modular architecture of NestJS.

services/workflows-service/src/rule-engine/core/operators/helpers.ts (1)

7-197: Well-structured operator classes in helpers.ts.

The operator classes (Equals, GreaterThan, LessThan, etc.) are well-defined and extend the BaseOperator abstract class, which handles common validation logic. This structure promotes code reuse and maintainability. The explicit handling of validation using Zod schemas in each operator class enhances the robustness of the rule validation process.

Comment on lines +1 to +14
import { Injectable } from '@nestjs/common';
import { RuleSet } from './core/types';

export type RuleStoreServiceFindAllOptions = {
databaseId: string;
source: 'notion';
};

@Injectable()
export class RuleStoreService {
public async findAll({ databaseId, source }: RuleStoreServiceFindAllOptions): Promise<RuleSet> {
throw new Error('Unsupported source');
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider implementing support for multiple sources.

Currently, the findAll method throws an error for any source. This might limit the flexibility and usability of the rule engine. Consider implementing actual retrieval logic or supporting multiple sources.

Comment on lines +1 to +22
import { z } from 'zod';
import { OPERATION } from './enums';

export const PrimitiveSchema = z.union([z.number(), z.string(), z.boolean()]);

export const BetweenSchema = z.object({
min: PrimitiveSchema,
max: PrimitiveSchema,
});

export const LastYearsSchema = z.object({
years: z.number().positive(),
});

// TODO: TBD
const ruleSchema = z.object({
key: z.string(),
operation: z.literal(OPERATION.LAST_YEAR),
value: z.object({
years: z.number(),
}),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure completion of the ruleSchema definition.

The TODO: TBD comment above the ruleSchema suggests that this part of the schema is not yet finalized. It's crucial to complete this to ensure the rule engine can validate and operate correctly.

services/workflows-service/src/rule-engine/core/errors.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9707548 and dc70519.

Files selected for processing (7)
  • services/workflows-service/src/rule-engine/core/errors.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/constants.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/operators/helpers.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.unit.test.ts (1 hunks)
  • services/workflows-service/src/rule-engine/core/types.ts (1 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (6)
  • services/workflows-service/src/rule-engine/core/errors.ts
  • services/workflows-service/src/rule-engine/core/operators/constants.ts
  • services/workflows-service/src/rule-engine/core/operators/helpers.ts
  • services/workflows-service/src/rule-engine/core/rule-engine.unit.test.ts
  • services/workflows-service/src/rule-engine/core/types.ts
  • services/workflows-service/src/rule-engine/rule-engine.service.ts
Additional context used
Biome
services/workflows-service/src/rule-engine/core/rule-engine.ts

[error] 54-56: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

Additional comments not posted (5)
services/workflows-service/src/rule-engine/core/rule-engine.ts (5)

7-35: Review of validateRule function.

The function's logic and error handling are well implemented. The use of lodash for checking emptiness and retrieving values is appropriate, and the structured error handling ensures that all possible errors are accounted for.


45-45: Clarify error handling strategy.

The TODO comment raises a valid concern about whether to throw an error when encountering an OperationNotFoundError. Consider standardizing the error handling across different cases for consistency.


38-76: Optimize error handling in runRuleSet.

The function effectively handles both individual rules and nested rule sets. However, simplifying the error handling could improve readability.

Tools
Biome

[error] 54-56: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


79-79: Clarify the helper injection strategy.

The TODO comment suggests a need to finalize how helpers are injected. Clarify or implement this part to ensure extendibility.


78-89: Review of RuleEngine function.

The function setup is clear and allows for flexible injection of helpers, which could be beneficial for testing and extending functionality.

Comment on lines +54 to +56
} else {
throw error;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unnecessary else clause.

Following the static analysis suggestion, the else clause can be omitted for cleaner and more efficient code.

- } else {
-   throw error;
- }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else {
throw error;
}
}
throw error;
Tools
Biome

[error] 54-56: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

[OPERATION.GTE]: GTE,
[OPERATION.LT]: LT,
[OPERATION.LTE]: LTE,
[OPERATION.LAST_YEAR]: LAST_YEAR,
Copy link
Collaborator

@Blokh Blokh Jun 24, 2024

Choose a reason for hiding this comment

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

Why is last year a a part of helper operations?

LT: 'LT',
GTE: 'GTE',
LTE: 'LTE',
LAST_YEAR: 'LAST_YEAR',
Copy link
Collaborator

Choose a reason for hiding this comment

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

this should not be here

};
}

class Between extends BaseOperator<BetweenParams> {
Copy link
Collaborator

Choose a reason for hiding this comment

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

between should be by 2 operators, before x and after y.

this.lte = new LessThanOrEqual();
}

eval: ConditionFn<BetweenParams> = (
Copy link
Collaborator

Choose a reason for hiding this comment

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

eval is the functionality of one of the conversions of the values.
evaluate is a rule valuation function

expect(result[0]).toMatchObject({
error: expect.any(MissingKeyError),
message: 'Rule is missing the key field',
passed: false,
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

remove

@liorzam liorzam changed the base branch from dev to bal-2130-epic-rule-engine June 24, 2024 09:16
@liorzam liorzam merged commit dc4d8df into bal-2130-epic-rule-engine Jun 24, 2024
9 checks passed
@liorzam liorzam deleted the bal-2254-rule-engine-v2 branch June 24, 2024 09:16
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.

None yet

3 participants