Dynamic business rule engine execution method and device, equipment and storage medium

By converting business rule expressions into an intermediate representation and compiling them into DLL files, the performance issues of the rule engine in high-concurrency scenarios are resolved, achieving efficient, secure, and flexible rule execution, and improving system stability and debugging efficiency.

CN120950144APending Publication Date: 2025-11-14SHENZHEN KINGSUN SCIENCE & TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511070715.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-07-31
Publication Date
2025-11-14

AI Technical Summary

Technical Problem

Existing rule engines suffer from poor performance, difficulty in debugging, and insufficient type checking and security in high-concurrency scenarios, making it difficult to meet the requirements for flexibility and stability.

Method used

The system converts business rule expressions into an intermediate representation, generates intermediate language code through namespaces and compiles it into a DLL file, caches execution instances, and uses Emit technology to avoid the overhead of interpreted execution and script calls. It also supports hot updates and strong type validation.

Benefits of technology

It improved rule execution efficiency, reduced type errors, enhanced system security, and increased business flexibility and system stability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120950144A_ABST
    Figure CN120950144A_ABST
Patent Text Reader

Abstract

The invention discloses a dynamic business rule engine execution method and device, equipment and a storage medium. The method comprises the following steps: receiving a business rule expression submitted by a user; converting the business rule expression into an intermediate expression form; generating an intermediate language code from the intermediate representation form through a namespace, and compiling the intermediate language code into a DLL file; the DLL file is loaded into a memory, and a corresponding execution instance is cached; and calling the execution instance in the cache to execute the rule logic based on the input business data, and returning an execution result. According to the method, the rule expression is directly compiled into the IL code by adopting the Emit technology, and the DLL file is generated, so that the extra overhead of interpretive execution or script calling is avoided, the rule execution efficiency is close to the original compiled code, and the performance in a high-concurrency scene is remarkably improved. And secondly, an intermediate representation form is constructed and a strong type is generated, so that the rule logic is ensured to finish type verification in a compiling stage, and type errors during operation are reduced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer technology, and in particular to a method, apparatus, device, and storage medium for executing a dynamic business rule engine. Background Technology

[0002] In enterprise information systems, business rules are typically hard-coded into the system as program code, resulting in a high degree of coupling between business logic and system code. When business requirements change, frequent code modifications and redeployment are necessary, which is time-consuming and prone to introducing errors. To solve this problem, rule engines (business rule management systems) have emerged. Rule engines decouple business logic from code, presenting it as configurable rules that allow business personnel to manage rules in a manner similar to configuration files or Excel spreadsheets. For example, dynamic business logic such as risk control judgments, user segmentation, and pricing strategies can all be implemented through a rule engine, enabling flexible configuration and rapid iteration of business rules.

[0003] The current mainstream rule engine implementation methods mainly include the following three:

[0004] Interpreted execution: Tools such as NCalc and JEXL parse the rule expressions in string form and interpret and execute them line by line at runtime. This method relies on string parsing and dynamic calculation, resulting in low execution efficiency and difficulty in meeting the performance requirements of high-concurrency scenarios.

[0005] Script execution: Scripting languages ​​such as Lua and Groovy execute scripts by writing code and calling an interpreter. While this method offers flexibility, the dynamic loading and execution of scripts can introduce security risks (such as code injection), and the debugging and maintenance costs are relatively high.

[0006] Expression Tree + Reflection: This approach generates delegate execution rules by constructing an ExpressionTree and calling the Compile() method. While it offers good support for statically typed expressions, the dynamically generated code cannot be directly reused for C# compiler optimizations, and reflection invocation incurs significant performance overhead, making it difficult to handle high-frequency call scenarios.

[0007] The above methods generally suffer from the following problems:

[0008] Interpreted execution and script execution require dynamic rule parsing at runtime, resulting in additional performance overhead; the compilation process of ExpressionTree also consumes a lot of resources, making it difficult to meet the needs of high-concurrency business.

[0009] The rules and logic are scattered in strings or scripts, making debugging difficult; business users need to rely on developers to modify the rules, which limits flexibility.

[0010] Dynamic regular expressions only perform type checking at runtime, which can easily lead to exceptions due to type mismatches, resulting in decreased system stability.

[0011] The execution of external scripts may introduce malicious code or unexpected behavior, especially in open systems where the risk is higher. Summary of the Invention

[0012] The purpose of this invention is to provide a dynamic business rule engine execution method, apparatus, device, and storage medium, aiming to solve the problem of low execution efficiency of existing rule engines.

[0013] In a first aspect, embodiments of the present invention provide a method for executing a dynamic business rule engine, comprising:

[0014] Receive business rule expressions submitted by users;

[0015] Convert the business rule expression into an intermediate representation;

[0016] The intermediate representation is used to generate intermediate language code using namespaces, and the intermediate language code is then compiled into a DLL file.

[0017] Load the DLL file into memory and cache the corresponding execution instance;

[0018] Based on the input business data, the execution instance in the cache is invoked to execute the rule logic and the execution result is returned.

[0019] Secondly, embodiments of the present invention provide a dynamic business rule engine execution device, comprising:

[0020] The receiving unit receives the business rule expressions submitted by the user.

[0021] A conversion unit is used to convert the business rule expression into an intermediate representation.

[0022] A compilation unit is used to generate intermediate language code from the intermediate representation using a namespace, and to compile the intermediate language code into a DLL file;

[0023] A caching unit is used to load the DLL file into memory and cache the corresponding execution instance;

[0024] The execution unit is used to execute rule logic by calling the execution instance in the cache based on the input business data, and return the execution result.

[0025] Thirdly, embodiments of the present invention provide a computer device, which includes a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the dynamic business rule engine execution method described in the first aspect.

[0026] Fourthly, embodiments of the present invention also provide a computer-readable storage medium, wherein the computer-readable storage medium stores a computer program, which, when executed by a processor, implements the dynamic business rule engine execution method described in the first aspect.

[0027] This invention discloses a dynamic business rule engine execution method, apparatus, device, and storage medium. The method includes: receiving a business rule expression submitted by a user; converting the business rule expression into an intermediate representation; generating intermediate language code from the intermediate representation through a namespace, and compiling the intermediate language code into a DLL file; loading the DLL file into memory and caching the corresponding execution instance; executing the rule logic by calling the cached execution instance based on the input business data, and returning the execution result. This invention uses Emit technology to directly compile the rule expression into IL code and generate a DLL file, avoiding the extra overhead of interpreted execution or script calls, making the rule execution efficiency close to that of native compiled code, and significantly improving performance in high-concurrency scenarios. Secondly, by constructing an intermediate representation and generating strong types, it ensures that the rule logic completes type verification during the compilation stage, reducing runtime type errors. Simultaneously, the dynamically generated DLL file is independent of external scripts, avoiding script injection risks and enhancing system security. Furthermore, the rule engine supports a hot update mechanism, allowing business personnel to update rules in real time without restarting the program, improving business flexibility. The present invention also provides a dynamic business rule engine execution device, a computer-readable storage medium, and a computer device, which have the above-mentioned beneficial effects, and will not be described in detail here. Attached Figure Description

[0028] To more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings used in the following description of the embodiments will be briefly introduced. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0029] Figure 1 This is a flowchart illustrating the execution method of the dynamic business rule engine.

[0030] Figure 2 This is another flowchart illustrating the execution method of the dynamic business rule engine;

[0031] Figure 3 This is a schematic block diagram of the dynamic business rule engine execution device. Detailed Implementation

[0032] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0033] It should be understood that, when used in this specification and the appended claims, the terms “comprising” and “including” indicate the presence of the described features, integrals, steps, operations, elements and / or components, but do not exclude the presence or addition of one or more of its features, integrals, steps, operations, elements, components and / or collections thereof.

[0034] It should also be understood that the terminology used in this specification is for the purpose of describing particular embodiments only and is not intended to limit the invention. As used in this specification and the appended claims, the singular forms “a,” “an,” and “the” are intended to include the plural forms unless the context clearly indicates otherwise.

[0035] It should also be further understood that the term "and / or" as used in this specification and the appended claims refers to any combination of one or more of the associated listed items and all possible combinations, and includes such combinations.

[0036] Please see Figure 1 and Figure 2 This embodiment provides a method for executing a dynamic business rule engine, including:

[0037] S101: Receive the business rule expression submitted by the user;

[0038] Specifically, the receiving of user-submitted business rule expressions is implemented through the rule modeling module, which provides a user-friendly UI or API interface for user operation. Users can submit rule expressions through tools such as the tree editor and structured input boxes in the UI interface, or they can submit them programmatically through the API interface. Submitted business rule expression formats include JSON, DSL rule strings, and logical expressions. For example, users can submit a JSON-formatted expression: {Condition: user.Age>18&&user.IsMember, Action: GrantAccess()}, which includes conditional judgment and execution action; they can also submit custom DSL-formatted expressions, such as IF user.Age>18ANDuser.IsMemberTHENGrantAccess, describing business rules in a more natural language-like way; they can also directly submit logical string-formatted expressions, such as "IF(user.Age>18)AND(user.IsMember)THENGrantAccess()". After receiving these expressions, the rule modeling module will perform preliminary format recognition and temporary storage, providing a foundation for subsequent expression processing.

[0039] S102: Convert the business rule expression into an intermediate representation;

[0040] In this embodiment, the process before converting the business rule expression into an intermediate representation includes:

[0041] Perform syntax validation and type safety checks on business rule expressions.

[0042] Specifically, before converting the business rule expression into an intermediate representation, the rule modeling module first performs syntax validation and type safety checks on the received business rule expression. The syntax validation stage primarily verifies the structural integrity and legality of the expression. For example, it checks whether the spelling of keywords such as "IF," "AND," and "THEN" in the custom DSL is correct, whether the use of logical operators conforms to specifications, whether parentheses are paired and closed, and whether the association between conditions and actions conforms to the preset format. Taking the expression "IF user.Age>18ANuser.IsMemberTHENGrantAccess" as an example, the syntax validation will identify "AN" as an incorrect keyword (it should be "AND") and return a specific syntax error message. The type safety check focuses on the type matching of variables, attributes, and operations involved in the expression. For example, for an expression like "user.Age>18," it checks whether "user.Age" (assuming it's of type int) and the string "18" on the right can be compared. If there is a type incompatibility, a type error message will be displayed. For action functions like "GrantAccess()," it verifies whether they are in the preset list of callable functions to ensure the legality of the function call. Only business rule expressions that pass these two checks will proceed to the subsequent process of converting them into intermediate representations.

[0043] After syntax validation and type safety checks pass, the business rule expression is then converted into an intermediate representation. This conversion is achieved using an expression translator.

[0044] Converting business rule expressions into intermediate representations includes:

[0045] The parser tool converts the business rule expression into an intermediate representation, which is a tree structure consisting of condition nodes, operation nodes, and logical operator nodes.

[0046] Specifically, the parser employs different transformation strategies based on the expression type: for JSON-formatted regular expressions, it converts them into an internal object model through deserialization; for custom DSLs or logical strings, it uses tools such as ANTLR and Irony.NET to generate an Abstract Syntax Tree (AST). For example, for the regular expression IF(user.Age>18)AND(user.IsMember)THENGrantAccess(), the parser first performs lexical analysis, breaking it down into tokens such as IF, (user.Age>18), and AND, and then performs syntactic analysis to construct the AST. Each node in the AST corresponds to a logical unit in the rule, such as condition nodes, operation nodes, logical operator nodes, and function call nodes. For compound conditional expressions, the parser generates a hierarchical tree structure that clearly expresses the relationships between logical units. During the AST generation process, the parser performs type inference and binding to prepare for the subsequent generation of intermediate language code.

[0047] Among them, the AST object is a rule syntax tree. The object is usually a structure composed of a set of node classes, representing the syntax structure of a logical rule.

[0048] S103: Generate intermediate language code from the intermediate representation using a namespace, and compile the intermediate language code into a DLL file;

[0049] Specifically, the intermediate representation is used to generate intermediate language code through the namespace (System.Reflection.Emit), and the intermediate language code is compiled into a DLL file, including:

[0050] By traversing the intermediate representations, the corresponding intermediate language code is generated using ILGenerator;

[0051] Dynamic assemblies are built using AssemblyBuilder, and the classes and methods of the dynamic assemblies are defined using ModuleBuilder and TypeBuilder.

[0052] Embed intermediate language code into the class of the dynamic assembly;

[0053] Save the dynamic assembly with embedded intermediate language code as a DLL file.

[0054] More specifically, the system traverses the tree structure of the intermediate representation and uses ILGenerator to generate corresponding intermediate language code, i.e., IL instructions. Taking the regular expression IF(user.Age>18)AND(user.IsMember r=true)THENCalculateDiscount() as an example, when traversing to the comparison node user.Age>18, ILGenerator will generate a series of IL instructions such as loading the user object, getting the Age attribute value, loading the constant 18, and performing the greater than comparison operation; for the AND logical operator node, it will generate conditional jump instructions to implement the logical AND operation; for the function call node CalculateDiscount(), it will generate instructions to call the corresponding method.

[0055] Subsequently, a dynamic assembly is built using AssemblyBuilder, setting the assembly name (e.g., DynamicRulesAssembly) and access permissions (RunAndSave), and a module (e.g., DynamicRulesModule) is defined using ModuleBuilder. A dynamic type is defined using TypeBuilder, which implements a predefined unified interface (e.g., IRuleExecutor) to ensure that the generated classes have a consistent call entry point. Within the type, an execution method (e.g., Execute) is defined using MethodBuilder; this method will contain the execution logic for the entire business rule.

[0056] Next, the previously generated intermediate language code is embedded into the class methods of the dynamic assembly. The ILGenerator writes the generated IL instructions into the corresponding method body of the MethodBuilder, forming complete executable logic. These IL instructions strictly follow the tree structure of the intermediate representation, ensuring that the logical order and operational relationships of the business rules are accurately implemented.

[0057] Finally, the dynamic assembly containing the intermediate language code is saved as a DLL file. The `Save` method of `AssemblyBuilder` is called to save the assembly with a specified filename (e.g., `Rule_12345.dll`) to a preset directory. The filename typically includes a rule identifier or version information for easy management and traceability. The generated DLL file can be subsequently loaded into memory for execution, enabling dynamic and efficient execution of business rules.

[0058] The generated DLL file contains the following content:

[0059] Assembly metadata: includes assembly name, version number, and dependency information.

[0060] Dynamic class definition: Contains the IL code of the RuleExecutor_{RuleKey} class and its Execute method.

[0061] Interface implementation: Ensure that the class implements the IRuleExecutor interface to support unified calling logic.

[0062] In some embodiments, this example uses dynamic assembly construction to illustrate how to distinguish the IL code of multiple rules by namespace or class name and compile them into the same DLL file to reduce disk storage space usage. The system manages multiple rule classes through a unified assembly, avoiding the generation of independent DLL files for each rule, thereby improving resource utilization.

[0063] The specific steps are as follows:

[0064] Logically related rules (such as user grouping rules and pricing strategy rules) are grouped by business modules, for example, UserGroupingRules and PricingRules.

[0065] Then assign an independent namespace to each group of rules (such as RuleEngine.Rules.UserGrouping and RuleEngine.Rules.Pricing), and specify a uniform namespace when defining the assembly using AssemblyBuilder.

[0066] Next, use AssemblyBuilder.DefineDynamicAssembly to create a dynamic assembly, and set the assembly name to RuleEngine.MultiRules_Assembly.

[0067] The module is then defined using ModuleBuilder.DefineDynamicModule, and its name is set to MultiRules_Module.

[0068] Then, in the module, define an independent class for each rule using TypeBuilder. The class name format is Rule_{RuleKey} (such as Rule_VIPCustomerRule, Rule_PriceDiscountRule), and ensure that the class name is unique.

[0069] For each rule, its AST is traversed to generate the corresponding IL code, which is then injected into the Execute method of the corresponding class via ILGenerator.

[0070] All classes share the same interface IRuleExecutor<TInput,TResult> This ensures the consistency of execution logic.

[0071] After completing the IL code injection for all rule classes, save the assembly as a single DLL file named Rule_MultiRules_v{Version}.dll using the AssemblyBuilder.Save method.

[0072] The file contains the IL code and namespace structure for all rule classes.

[0073] When loading a DLL file, the assembly is read via Assembly.LoadFile, and specific rule instances are obtained based on the namespace and class name.

[0074] During execution, the Execute method is called through the interface, and the parameter type is determined by the rule definition (such as User or Order).

[0075] More specifically, during the dynamic assembly construction process, the system groups logically related rules according to business modules. For example, user grouping rules are grouped into the UserGroupingRules group, and pricing strategy rules are grouped into the PricingRules group. Each group of rules is assigned an independent namespace; for example, the UserGroupingRules group corresponds to the RuleEngine.Rules.UserGrouping namespace, and the PricingRules group corresponds to the RuleEngine.Rules.Pricing namespace. When defining an assembly using AssemblyBuilder, a unified assembly name is specified as RuleEngine.MultiRules_Assembly to integrate these rules.

[0076] Next, a dynamic assembly is created using AssemblyBuilder.DefineDynamicAssembly, and a module is defined using ModuleBuilder.DefineDynamicModule, named MultiRules_Module. Within this module, an independent class is defined for each rule, with class names in the format Rule_{RuleKey}. For example, a Rule_VIPCustomerRule class is generated for VIP customer judgment rules, and a Rule_PriceDiscountRule class is generated for price discount rules, ensuring that each class name is unique.

[0077] For each rule class, the system traverses its Abstract Syntax Tree (AST), converts the rule logic into corresponding IL code, and injects it into the class's Execute method via ILGenerator. All rule classes implement IRuleExecutor.<TInput,TResult> An interface ensures the consistency of execution logic. For example, the class implementing user segmentation rules is IRuleExecutor.<User,GroupResult> The interface, the class implementing pricing rules, is IRuleExecutor.<Order,PriceResult> interface.

[0078] After injecting the IL code for all rule classes, save the assembly as a single DLL file using the AssemblyBuilder.Save method, named Rule_MultiRules_v{Version}.dll, such as Rule_MultiRules_v1.0.dll. This file contains the IL code for all rule classes and the complete namespace structure, for example:

[0079] The RuleEngine.Rules.UserGrouping namespace contains the Rule_VIPCustomerRule and Rule_NewCustomerRule classes.

[0080] The RuleEngine.Rules.Pricing namespace contains the Rule_PriceDiscountRule and Rule_TieredPricingRule classes.

[0081] When loading a DLL file, the system reads the assembly using Assembly.LoadFile and retrieves a specific rule instance based on the rule's namespace and class name. For example, when retrieving an instance of the VIP customer judgment rule, the fully qualified type name "RuleEngine.Rules.UserGrouping.Rule_VIPCustomerRule" is specified. When executing a rule, the corresponding parameter object (such as a User or Order object) is passed to the Execute method of the interface to invoke the rule logic and obtain the execution result. In this way, the system integrates the IL code of multiple rules into a single DLL file, avoiding the generation of a separate DLL file for each rule, significantly reducing disk storage space usage and improving resource utilization.

[0082] S104: Load the DLL file into memory and cache the corresponding execution instance;

[0083] In this embodiment, loading the DLL file into memory and caching the corresponding execution instance further includes:

[0084] Persist the DLL file to the specified directory;

[0085] The DLL file is loaded into memory based on the specified directory and using Assembly.LoadFile.

[0086] When loading a DLL file into memory and caching the corresponding execution instance, the dynamically compiled DLL file is first persisted to a system-preset specified directory. This directory is usually the / rules / folder under the project, which facilitates centralized management of DLL files corresponding to all rules. For example, RiskLevelEvaluator.dll generated by the risk control level judgment rule and DiscountCalculator.dll generated by the e-commerce discount rule will be stored in this directory according to rule identifiers or function categories, and the filenames will contain rule-related information to distinguish different rules.

[0087] After persistence is complete, the system loads the DLL file into memory using the `Assembly.LoadFile` method based on the specified directory. Specifically, the program locates the corresponding DLL file path in the ` / rules / ` directory according to the rule identifier, calls `Assembly.LoadFile(path)` to load the file, and generates the corresponding `Assembly` object. Subsequently, it retrieves the target type that implements a unified interface (such as `IRuleExecutor`) from this `Assembly` object, and creates an instance of that type, i.e., an execution instance, through reflection.

[0088] Next, loading the DLL file into memory and caching the corresponding execution instance includes:

[0089] The rule identifier and rule version are used as the cache key, and the execution instance is stored in the memory cache through ConcurrentDictionary or MemoryCache.

[0090] Specifically, when loading a DLL file into memory and caching the corresponding execution instance, the system uses a combination of the rule identifier (such as RuleKey or RuleID) and the rule version as the cache key. For example, for a business rule with the rule identifier "VIPCustomerRule" and version number "1.0", its cache key is "VIPCustomerRule_1.0"; for a rule with the rule identifier "RiskLevelEvaluator" and version number "2.1", the cache key is "RiskLevelEvaluator_2.1". The system stores the execution instance in the memory cache using either ConcurrentDictionary or MemoryCache containers: if ConcurrentDictionary is used, its key-value pair format is...<string,IRuleExecutor> The key is a combination of the rule identifier and version, and the value is the execution instance that implements the IRuleExecutor interface loaded from the DLL file. If MemoryCache is used, the same combination string is used as the key for the cache item, and the execution instance is stored as the cache value. A cache expiration policy can be set to optimize memory usage. In this way, it is ensured that rule execution instances with different identifiers and versions are uniquely stored in the cache, and the corresponding execution instance can be quickly located and retrieved by rule identifier and version during subsequent business calls.

[0091] In some embodiments, in single-threaded or low-concurrency scenarios, a Dictionary is used.<string,IRule> Store cache instances;

[0092] In multi-threaded or high-concurrency scenarios, ConcurrentDictionary is used.<string,IRule> Implement thread-safe cache management to avoid concurrent access conflicts.

[0093] Specifically, in single-threaded or low-concurrency scenarios, the system uses a dictionary.<string,IRule> Store cached instances. For example, in an enterprise's low-frequency rule query system, where the daily rule calls are few and there is no need for multi-threaded concurrent operations, a combination of rule identifier and version can be used as the key (e.g., InsurancePremiumRule_v1), and the corresponding execution instance can be stored as the value in a Dictionary. This approach is simple to implement, meets basic caching and querying needs, and is suitable for scenarios where thread safety requirements are not high.

[0094] In multi-threaded or high-concurrency scenarios, the system uses ConcurrentDictionary.<string,IRule> Implement thread-safe cache management. For example, in the real-time order discount calculation of e-commerce platforms, thousands of rule calls need to be processed per second, and there are situations where multiple threads read and update the cache simultaneously. ConcurrentDictionary, through its built-in thread synchronization mechanism, supports atomic operations such as TryAdd, TryGetValue, and AddOrUpdate, which can avoid resource contention and data inconsistency issues that occur when multiple threads access the cache at the same time, ensuring the safety and stability of cache operations under high concurrency.

[0095] In some embodiments, hot update is also included, which includes:

[0096] Generate a new hash value based on the updated rule expression;

[0097] If the hash value changes, a recompile is triggered and the cache instance is replaced.

[0098] During the hot update process, the system first generates a new hash value for the updated business rule expression. Specifically, when business users modify the rule expression through the rule modeling module (for example, changing "spend 200 minus 30" in an e-commerce discount rule to "spend 300 minus 50"), the system uses hash algorithms such as MD5 or SHA256 to calculate the unique corresponding new hash value for the updated expression string. Simultaneously, the system retains the hash values ​​of previous versions of the rule for comparison to determine whether the rule has undergone a substantial change.

[0099] If the newly generated hash value is inconsistent with the historical hash value, the system determines that the rule expression has been effectively updated and triggers a recompilation process: the expression translator translates the updated rule expression into a new intermediate representation, and then the code generator and dynamic compilation module use Emit technology to regenerate the corresponding IL code and compile it into a new DLL file. Afterwards, the assembly loading and caching module loads the new DLL file into memory, creates a new execution instance, and replaces the corresponding old cache instance in ConcurrentDictionary or MemoryCache with a cache key consisting of the original rule identifier and the updated version number. This allows the new rule to take effect immediately without requiring a program restart.

[0100] S105: Based on the input business data, call the execution instance in the cache to execute the rule logic and return the execution result.

[0101] When a business request triggers rule execution, the system first constructs a cache key (e.g., RiskLevelEvaluator_2.1) based on the rule identifier (e.g., RiskLevelEvaluator) and version number (e.g., 2.1) in the request, and then quickly locates the corresponding execution instance from ConcurrentDictionary or MemoryCache. For example, when an e-commerce order processing system receives order data and needs to execute the OrderDiscountRule_3.0 rule to calculate the discount amount, the system will directly retrieve the execution instance corresponding to that rule from the cache.

[0102] After obtaining an execution instance, the system passes the input business data (such as an order object containing user information, a product list, and order amount) as parameters to the unified interface method of the execution instance (such as the ExecuteRule method). The execution instance internally encapsulates the rule logic generated through Emit technology, enabling direct processing of business data. For example, for risk control assessment rules, the execution instance reads the user's historical transaction records, current transaction amount, and other data, and executes a preset risk scoring algorithm; for discount calculation rules, it determines whether the user meets the discount conditions based on factors such as product type and order amount, and calculates the discount percentage.

[0103] After execution, the execution instance returns the processing result (such as risk level, discount amount, processing suggestions, etc.) to the caller through a unified return object structure. The entire process does not require re-parsing the rule expression or compiling the code; it directly utilizes the cached execution instance to achieve efficient rule execution. For example, after the order processing system calls the rule execution, it directly obtains the result of enjoying an 80% discount, which can be immediately applied to the order amount calculation, significantly improving business processing efficiency.

[0104] This embodiment targets a rule engine that relies solely on a memory cache (ConcurrentDictionary).<string,IRule> The issue of cache invalidation or disk DLL redundancy was not addressed. An improvement plan is proposed: introduce an LRU eviction policy to automatically clean up low-frequency rule instances, and add a disk DLL garbage collection mechanism to periodically delete old version DLL files that are not cached.

[0105] Specifically, in the memory caching improvement, the system dynamically manages the cache using the LRU algorithm to avoid memory overflow. In practice, a doubly linked list (LinkedList) is used. <rulecachenode>The access order of rule instances is maintained, with the head of the linked list containing the most recently used rule and the tail containing the least recently used rule; a hash table (ConcurrentDictionary) is also used. <string,LinkedListNode <rulecachenode>This system enables fast location of rule instances within the linked list. The `RuleCacheNode` contains the rule key (e.g., `OrderDiscountRule_v3.0`), the rule instance (an `IRule` object), and an access count. When a rule instance is accessed (e.g., an e-commerce system calls `VIPCustomerRule_v2.1` to calculate membership benefits), the system finds its corresponding linked list node using a hash table, moves that node to the head of the list, and marks it as recently used. If the cache is not full, a new rule (e.g., `NewUserDiscountRule_v1.0`) is directly inserted at the head of the list. If the cache reaches a preset limit (e.g., 500 instances), low-frequency rules at the tail of the list (e.g., `2023HolidayRule_v1.0`, which hasn't been accessed in 30 days) are deleted, and a new rule is inserted at the head. To ensure thread safety, the system combines the atomic operations of `ConcurrentDictionary` with the read-write lock mechanism of `ReaderWriterLockSlim` to avoid node corruption or data conflicts during concurrent access.

[0106] The disk DLL garbage collection mechanism executes the following steps: First, it traverses the rule storage directory (e.g., / Rules / Assemblies / ) to collect the path and version information of all DLL files (e.g., Rule_VIPCustomerRule_v1.0.dll, Rule_MultiRules_v2.0.dll); it extracts the rule key (e.g., VIPCustomerRule and MultiRules) and version number (e.g., 1.0, 2.0) from the filename using regular expressions; then it checks whether an instance with the corresponding rule key exists in the current LRU memory cache. If a DLL (e.g., Rule_... If the rule key of VIPCustomerRule_v1.0.dll is not referenced in the cache and its version is not the latest (the latest is v2.0), it is marked as not referenced. Then, the marked file is deleted and recorded in the log (e.g., Deleted: Rule_VIPCustomerRule_v1.0.dll). At the same time, the latest version of the DLL file (e.g., Rule_MultiRules_v2.0.dll) is retained to prevent accidental deletion. Finally, the above scanning and cleaning process is automatically executed every day at 2:00 AM by setting System.Threading.Timer to release disk space periodically.

[0107] In some embodiments, to address the problem of low full-scale compilation efficiency caused by frequent rule updates in the rule engine, an improvement scheme is proposed: supporting incremental compilation (generating local IL code only for modified AST nodes) and pre-compiled templates (pre-generating IL templates for general logic and dynamically filling parameters) to improve compilation efficiency and reduce resource consumption.

[0108] Specifically, in the incremental compilation of AST nodes, the system achieves local compilation by identifying the smallest AST node where the rule is modified, reusing the unchanged IL code. For example, when an e-commerce discount rule is updated from "spend 200 minus 30" to "spend 200 minus 50", the system first performs AST change detection: comparing the old and new rule ASTs, the old AST has the condition node "TotalAmount>=200" and the action node "TotalAmount-30", while the new AST only has the action node "TotalAmount-50". Control flow graph analysis determines that only the action node and its directly dependent subtrees need to be recompiled. Next, local IL code generation is performed: the marked action node subtree is recompiled to generate the IL instructions corresponding to "TotalAmount-50" (such as loading TotalAmount, loading 50, and performing subtraction), while the IL code of the condition node "TotalAmount>=200" is reused directly from the LRU cache because it has not changed. Finally, dynamic linking and optimization are performed: the locally generated IL code is dynamically concatenated with the cached condition node IL code to form a complete rule execution logic, and constant folding optimization is performed (e.g., confirming that 50 is a constant and does not need further calculation) to reduce the final code size and runtime overhead.

[0109] Precompiled templates reduce compilation overhead by templating common logic IL. For example, the system identifies frequently reused if-else conditional branch structures in rules and abstracts them into IL templates. These templates contain fixed IL instructions for the conditional judgment framework (such as loading input parameters, conditional jumps, and result returns) and reserve placeholders for conditional expressions and branch results. When the risk control rule is updated (e.g., from "CreditScore<600→HIGH" to "CreditScore<550→'HIGH'"), there is no need to recompile the entire if-else framework. Only the new conditional expression "CreditScore<550" needs to be parsed using reflection, and its corresponding IL instructions (loading CreditScore, loading 550, performing comparisons) need to be filled into the conditional placeholders in the template. Simultaneously, the result "HIGH" needs to be filled into the branch placeholders, generating the final IL code. The system uses a ConcurrentDictionary to cache this template instance with the key "if-else template + conditional parameter hash". Subsequent updates to similar rules directly reuse the cached template, only replacing the placeholder content, significantly reducing repetitive compilation overhead.

[0110] In some embodiments, to address the issue of unverified compatibility between input data and rule fields when rule expressions are directly mapped to C# code in the rule engine, an improvement is proposed: adding a strong type validation layer during the translation phase, binding field types (such as Age: int) when parsing expressions, and verifying the matching of input entity structures before compilation, thereby improving the stability of rule execution and development efficiency.

[0111] Specifically, in the strong type validation layer design, the system ensures the compatibility of rule expressions and data sources by binding field types to the input entity structure for validation. First, metadata is defined. For example, in e-commerce membership rules, field type mapping relationships are defined through configuration files: Age:int, sVip:bool, OrderAmount:decimal, etc., and stored in the rule metadata table of the database. When parsing the rule expression Age>30&&IsVip==true, the expression parser loads the field types from the metadata, verifies that Age is of type int and IsVip is of type bool, ensuring that operators in the expression (such as > and ==) are compatible with the field types. If a mismatch occurs (such as writing the expression as IsVip>0), the system will recognize that IsVip is of type bool, and the operator > is only applicable to numeric types, immediately throwing a compilation exception: type mismatch: cannot apply the > operator to bool type.

[0112] During the input entity structure validation phase, when a rule is instantiated (e.g., executing a membership discount calculation rule), the system uses reflection to obtain the attribute information of the input entity (e.g., a Customer object) and compares it with the fields defined in the metadata. If the input entity lacks a field defined in the metadata (e.g., the IsVip attribute is missing), or the field type does not match (e.g., OrderAmount is defined as decimal in the metadata, but is string in the input entity), the system will prevent rule execution and throw an exception: Input entity structure mismatch: missing required field IsVip or field type mismatch. This strong type validation mechanism ensures that the fields operated on by the rule expression are consistent with the structure and type of the actual input data, avoiding system failures caused by runtime type errors and improving the reliability and stability of rule execution.

[0113] In some embodiments, to address the problem of difficulty in debugging dynamically generated IL code, an improvement scheme is proposed: PDB symbol files are output synchronously when generating DLLs to support Visual Studio debugging of dynamic rule logic; and source code mapping relationships (SourceMap) are recorded during the AST traversal stage to enable error location to the original expression line number, thereby improving debugging efficiency and problem location accuracy.

[0114] Specifically, in the implementation of PDB symbol file generation and debugging support, the system dynamically generates IL code via System.Reflection.Emit and simultaneously creates PDB symbol files to support debugging. Specifically, when creating a dynamic assembly using AssemblyBuilder, debugging information generation is enabled by setting the DebuggableAttribute, and the RunAndSave mode is specified in AssemblyBuilderAccess. This ensures that while generating the DLL file, a corresponding PDB file (e.g., Rule_Discount_v1.0.pdb) is output in the same directory (e.g., C:\Rules\Debug\), containing mapping information between IL code and the original rule expressions. When configuring the debugger in Visual Studio, developers need to open "Tools > Options > Debugging > Symbols" and add the local PDB file path (e.g., C:\Rules\Debug\) so that the debugger can recognize the dynamically generated symbol files. During the debugging and verification phase, after loading the dynamically generated Rule_Discount_v1.0.dll, developers can set breakpoints on rule execution methods (such as Execute) in Visual Studio. If the PDB file is generated correctly, the debugger will display the source code of the rule expression (such as IFOrderAmount>1000THENDiscount=0.1) and synchronously display the correspondence between IL code and source code during single-step debugging, thus enabling debugging of dynamic rule logic as if it were static code.

[0115] In the source code mapping record during the AST traversal phase, the system achieves precise error location by associating AST nodes with the original source code locations. When parsing regular expressions, such as processing Age>30&&IsVip==true (assuming this expression is located on line 5 of the original input), the parser appends source code location information to each AST node: the condition node Age>30 is annotated with line number 5 and column numbers 1-10; the logical operator node && is annotated with line number 5 and column numbers 12-13; and the condition node IsVip==true is annotated with line number 5 and column numbers 15-28. When traversing the AST to generate IL code, the system synchronously writes the SourceLine information of each node (such as line number 5) into the debugging symbols of the PDB file, establishing a mapping between IL instructions and the original line numbers. When the dynamically generated IL code triggers an exception (such as a null reference exception caused by the Age field being null), the Visual Studio debugger will directly locate line 5 of the original regular expression through the source code mapping information of the PDB file, enabling developers to quickly associate the exception with the specific regular expression location, greatly improving debugging efficiency.

[0116] In some embodiments, to address the issues of blocking the main thread and repeatedly compiling IL code when loading rules for the first time in the rule engine, an improvement solution is proposed: asynchronous compilation (Task.Run) is used to generate DLL files to avoid blocking the main thread; high-frequency rules are preloaded based on historical access frequency; and the overhead of repeated compilation is reduced by caching IL instruction sequences, thereby improving the response efficiency and resource utilization of the rule engine.

[0117] Specifically, in the implementation of decoupling asynchronous compilation from the main thread, the system avoids blocking the main thread when a rule is first loaded using an asynchronous task. For example, when loading a "limited-time discount rule" in the order submission process of an e-commerce platform, the main thread calls `Task.Run(=>CompileRuleAsync(ast))` to initiate an asynchronous compilation task. This task translates the rule's AST into IL code in a background thread and generates the corresponding DLL file. During asynchronous compilation, if compilation fails due to AST node errors, the system logs detailed error information (such as "node type mismatch: Condition node lacks comparison operator") and returns the default rule (such as no discount) or throws a compilation exception based on the business configuration. Simultaneously, a `cancellationToken` is created through `CancellationTokenSource` to allow canceling the compilation task and releasing thread resources when the rule loading times out (e.g., 5 seconds). The main thread then waits for the asynchronous task result using `await`, during which time it can continue to process user interactions or other business logic (such as order product inventory verification), ensuring smooth UI or API responses.

[0118] The high-frequency rule preheating strategy reduces cold start latency by preloading frequently accessed rules. The system maintains a ConcurrentDictionary.<string,int> A counter is used to record the number of times each rule is called in real time. For example, the "Member Level Determination Rule" is called 100,000 times per day, and the "Discount Calculation Rule" is called 80,000 times per day. During the system's off-peak hours in the early morning (e.g., 2:00-4:00), the scheduling service triggers a preheating task, selecting the top 10% of rules based on their call count (such as the two high-frequency rules mentioned above). The DLL files of these rules are asynchronously loaded into the memory cache via a background thread using the LoadRuleAsync method, and simple validity checks are performed (e.g., calling the Execute method with test data). If the "Product Category Table," which the "Discount Calculation Rule" depends on, is not loaded during the preheating process, the system will record an alarm log (e.g., "Preheating Failed: Dependency Table Missing"), but this will not affect the normal operation of the service. The table will be reloaded when the rule is actually called. In this way, when the morning peak arrives (e.g., 9:00), the high-frequency rules are already in a cache-ready state, avoiding compilation and loading delays during the first call.

[0119] IL instruction sequence caching optimization reduces the overhead of repeated compilation by caching already generated IL code. The system uses ConcurrentDictionary.<string,byte[]> As a cache container, the key is a unique hash generated based on the rule content (e.g., "Rule_VIPCustomerRule_v1.0_Age>18_IsVip=true"), and the value is a byte array of the corresponding IL instruction sequence. When loading the "VIP customer discount rule", the system first calculates the rule content hash and queries the cache. If a match is found, the cached IL code is directly reused to generate an execution instance; if no match is found, asynchronous compilation is triggered, and the IL code is stored in the cache after compilation. When the rule version is updated (e.g., the "VIP customer discount rule" is upgraded to v2.0), the system triggers the RuleUpdatedEvent event. After the listener captures the event, it calls _ilCache.Remove(oldRuleKey) to clear the old version of the IL code cache. At the same time, an LRU eviction mechanism is implemented in conjunction with MemoryCache, setting a cache capacity limit (e.g., 1000 entries). When the cache is full, the least recently used IL code (e.g., "holiday exclusive rule" called less than 10 times per month) is automatically removed to balance memory usage and cache hit rate. For high-frequency rules such as "order amount verification rules" that are called more than a thousand times per second, the IL code cache is set to expire after 24 hours to further reduce the overhead of repeated generation.

[0120] In some embodiments, to address the security deficiencies of dynamically generated DLL files and the risk of code execution in untrusted environments, an improvement scheme is proposed: adding a digital signature (such as StrongName) to dynamically generated DLL files to ensure that the loaded assemblies have not been tampered with; and using .NET's AppDomain to isolate or containerize (such as Docker) the rule logic to prevent malicious code from damaging the main process, thereby improving the security and isolation of the rule engine.

[0121] Specifically, in the practice of dynamic DLL digital signatures, the system ensures that the dynamically generated DLL has not been tampered with through digital signatures. First, a self-signed certificate is generated: the makecert tool is used to generate the root certificate, with a command such as makecert -nCN=RuleEngineSigning-r-svRuleSign.pvkRuleSign.cer, where -n specifies the certificate name, -r indicates self-signing, and -sv generates the private key file; then, the certificate is converted to PFX format (containing the private key) using pvk2pfx-pvkRuleSign.pvk-spcRuleSign.cer-pfxRuleSign.pfx-popassword for subsequent signing. When signing dynamically generated DLLs, if using Authenticode signing, call `signtoolsign / fRuleSign.pfx / ppasswordC:\Rules\Rule_MultiRules_v1.0.dll` to add a digital signature to the DLL. If StrongName signing is required (to ensure the integrity of the .NET assembly), then when dynamically generating the assembly, pass `newStrongNameKeyPair(File.ReadAllBytes(RuleSign.snk))` to the constructor of `AssemblyBuilder.DefineDynamicAssembly` to make the generated DLL have a built-in strong name signature. To verify the signature, use `signtoolverify / paC:\Rules\Rule_MultiRules_v1.0.dll` to verify the validity of the Authenticode signature. For StrongName signing, use the .NET reflection API `Assembly.LoadFrom(Rule_MultiRules_v1.0.dll).GetName().Verify()` to check if the signature is complete; if it returns true, it indicates that the DLL has not been tampered with.

[0122] A sandbox execution environment is built to isolate the execution of untrusted rules and prevent malicious code from affecting the main process. In the .NET Framework environment, AppDomain isolation is used: a restricted application domain is created, and ApplicationBase is set to the rule DLL directory via AppDomainSetup, with PermissionSet configured to restrict permissions; before loading the DLL, its StrongName signature is verified to ensure a trustworthy source, and then the rule instance is loaded via domain.CreateInstanceFromAndUnwrap, allowing the rule logic to execute in an independent domain. The main process communicates via cross-domain delegation. If the code within the sandbox domain malfunctions, the main process can safely terminate that domain without affecting itself. For cross-platform or high-security requirements (such as handling rules submitted by external users), Docker container isolation is used: a lightweight image (based on .NET Runtime image) is built, containing only the necessary dependencies for rule execution; when starting the container, a dynamic DLL directory is mounted via -vC:\Rules: / app / rules, and --networknone is configured to disable network access and --read-only is configured to set a read-only file system, restricting container permissions; the rule execution logic runs independently within the container, and the main system calls and obtains results through the container API, so even if the code inside the container is maliciously attacked, it cannot break through the container boundary and affect the host system.

[0123] In some embodiments, to address the issues of high latency in accessing hot data, low efficiency in loading cold data, and inconsistency in cross-node caching in the rule engine, an improvement scheme is proposed: construct a three-level caching architecture (L1 is a ConcurrentDictionary in memory, L2 is a local disk persistent cache, and L3 is a distributed cache such as Redis). Through layered storage and dynamic synchronization strategies, high-frequency rules can be accessed quickly, cold rules can be loaded on demand, and the cross-node rule reuse rate can be improved, thereby reducing database pressure and response latency.

[0124] L1 cache (memory cache):

[0125] Implementation: Using ConcurrentDictionary<string,object> It stores high-frequency rules and supports multi-threaded safe read and write operations.

[0126] Strategy: Automatically adjust cache content based on access frequency, prioritizing high-frequency rules. Set a maximum capacity (e.g., 1000 entries) and expiration time (e.g., 5 minutes) to avoid memory overflow.

[0127] Advantages: Millisecond-level access speed, suitable for high-concurrency scenarios.

[0128] L2 cache (local disk cache):

[0129] Implementation: Use a file system or a lightweight storage engine such as SQLite to persist rules (e.g., serialize to JSON or binary files).

[0130] Strategy: Use the LRU algorithm to manage disk cache capacity, evicting the least used rules. Compress cold data for storage to reduce disk usage.

[0131] Advantages: Avoids cache rebuilding overhead during frequent restarts and adapts to low-to-medium frequency rules.

[0132] L3 cache (distributed cache):

[0133] Implementation: Redis is used as a distributed cache, supporting cross-node sharing and high availability.

[0134] Strategy: Set a reasonable TTL (e.g., 1 hour) for the rules, and use the LFU algorithm to evict low-frequency data. Horizontal scaling is achieved through Redis cluster deployment, adapting to large-scale distributed scenarios.

[0135] Advantages: Ensures data consistency across nodes and adapts to the needs of cold data and cross-service reuse.

[0136] The hot rule loading process is as follows: L1 cache is prioritized; requests first query the ConcurrentDictionary, and if a match is found, the result is returned directly. If L1 is not found, the rule is read from the local disk and loaded into L1, so subsequent requests will directly hit L1. If L2 is not found, the rule is loaded from Redis and synchronized to both L1 and L2 to ensure a fast response for the next request.

[0137] Cold rule loading and synchronization specifically involves: When a cold rule is loaded for the first time, it is read from Redis, and simultaneously, other nodes are notified via a message queue (such as RabbitMQ) to synchronize the rule to their local L1 / L2 cache. Based on historical access frequency, high-frequency rules are preloaded to L1 / L2 during off-peak periods to reduce cold start latency.

[0138] At the same time, a version number is set for the rule, and atomicity is ensured during updates through the CAS (Check-And-Set) mechanism.

[0139] When rules are updated, all nodes are notified to refresh their local caches via Redis publish-subscribe mechanisms (such as the PUBLISH command).

[0140] Specifically, in the multi-level caching architecture design, the system balances performance and resource consumption through three layers of caching: L1, L2, and L3. L1 is a memory cache, using ConcurrentDictionary.<string,object> The system is implemented with three layers: L1, L2, and L3. L3 is a dedicated cache for high-frequency access rules, such as "membership level discount rules" and "real-time inventory verification rules" that are called over 500 times per second in e-commerce platforms. L2 has a maximum capacity of 1000 rules and an expiration time of 5 minutes. Multi-threaded safe read / write support ensures millisecond-level response times in high-concurrency scenarios. L4 is a local disk cache, based on SQLite to store low-frequency rules, such as "quarterly promotion rules" and "holiday exclusive discount rules." It uses the LRU algorithm for management; when the disk cache reaches its 10GB limit, rules not accessed for 30 days are automatically evicted, and the stored content is GZip compressed to reduce disk usage and avoid frequent cache rebuilding during service restarts. L5 is a Redis distributed cache, serving as shared cold data storage across nodes, such as "new user registration gift rules" and "region-limited activity rules." It has a TTL of 1 hour and uses the LFU algorithm to evict rules accessed less than 100 times per year. Deployment via a Redis cluster supports large-scale distributed scenarios, ensuring rule reuse across services.

[0141] A dynamic loading and synchronization mechanism for hot and cold rules ensures efficient rule access. When loading hot rules, requests prioritize querying the L1 cache. For example, if a "Membership Level Discount Rule" is found in L1, it is returned directly. If L1 is not found (e.g., the rule has just been updated), it is read from the L2 disk cache and loaded into L1. For example, the "Quarterly Promotion Rule" is loaded into memory from SQLite on the first access, and subsequent requests directly hit L1. If L2 is also not found, it is loaded from L3 Redis. For example, the "Region-Limited Activity Rule" is retrieved from Redis on the first cross-node call, and simultaneously synchronized to L1 and L2 to ensure fast response on subsequent accesses. When loading cold rules, cross-node synchronization is achieved via RabbitMQ. For example, after service node A loads the "New User Registration Gift Pack Rule," it sends a message to notify nodes B and C to synchronize the rule to their local L1 and L2. During off-peak periods (e.g., 2 AM), based on historical access data, the top 10% of high-frequency rules (e.g., "Real-Time Inventory Verification Rule") are preloaded into L1 and L2 to reduce cold start latency. Cache consistency is ensured through version control. Each rule is associated with a version number (e.g., "Member Rule_v2.3"). When updated, an atomic replacement is performed using the CAS mechanism. At the same time, Redis publish-subscribe is used. When a rule is updated, the "RuleUpdated" channel message is triggered, and all nodes immediately refresh their local cache after receiving the notification.

[0142] Furthermore, performance optimization and verification improved system performance through multi-dimensional measures. Cache hit rate monitoring showed that the L1 cache hit rate for "Membership Level Discount Rules" and "Real-time Inventory Verification Rules" remained stable above 85%, the L2 cache hit rate for "Quarterly Promotion Rules" was approximately 25%, and the L3 cache hit rate for cold rules was controlled within 5%, meeting the preset targets. Regarding cold start optimization, historically high-frequency rules were prioritized for loading into L1 upon service startup, reducing rule response latency from 500ms to 80ms within the initial 30 minutes. In terms of resource control, L1 used a capacity limit (1000 entries) and a 5-minute expiration policy, keeping memory usage stable below 200MB; L2 used LRU eviction, keeping disk usage below 8GB. In exception handling, for illegal requests such as "Rule ID=9999" that do not exist, an empty value is returned directly and a log is recorded to avoid cache penetration; a random TTL (such as 1 hour ± 10 minutes) is set for the rules to prevent cache avalanche caused by batch expiration of rules such as "holiday exclusive discount rules", thereby improving system throughput and reducing database query pressure.

[0143] This embodiment employs Emit technology to directly compile rule expressions into IL code and generate a DLL file, avoiding the overhead of interpreted execution or script calls. This makes rule execution efficiency approach that of native compiled code, significantly improving performance in high-concurrency scenarios. Secondly, by constructing an intermediate representation and generating strong types, it ensures that the rule logic completes type verification during the compilation phase, reducing runtime type errors. Simultaneously, the dynamically generated DLL file is independent of external scripts, avoiding script injection risks and enhancing system security. Furthermore, the rule engine supports a hot update mechanism, allowing business users to update rules in real time without restarting the program, improving business flexibility.

[0144] Please see Figure 3 This embodiment provides a dynamic business rule engine execution device 200, including:

[0145] Receiving unit 201 receives the business rule expression submitted by the user;

[0146] The conversion unit 202 is used to convert the business rule expression into an intermediate representation.

[0147] Compilation unit 203 is used to generate intermediate language code from the intermediate representation form through a namespace, and compile the intermediate language code into a DLL file;

[0148] Cache unit 204 is used to load the DLL file into memory and cache the corresponding execution instance;

[0149] Execution unit 205 is used to call the execution instance in the cache to execute the rule logic based on the input business data and return the execution result.

[0150] Furthermore, the format of the business rule expression includes: JSON, DSL rule string, and logical expression.

[0151] Furthermore, the conversion unit 202 includes:

[0152] The form conversion subunit is used to convert the business rule expression into an intermediate representation form through a parser tool. The intermediate representation form includes a tree structure composed of condition nodes, operation nodes, and logical operator nodes.

[0153] Furthermore, the compilation unit 203 includes:

[0154] The code generation subunit is used to generate corresponding intermediate language code by traversing the intermediate representation and using ILGenerator;

[0155] Define sub-units for building dynamic assemblies using AssemblyBuilder, and define the classes and methods of the dynamic assemblies using ModuleBuilder and TypeBuilder;

[0156] An embedding subunit is used to embed the intermediate language code into the class of the dynamic assembly;

[0157] The file saving subunit is used to save the dynamic assembly containing the intermediate language code as a DLL file.

[0158] Furthermore, the cache unit 204 includes:

[0159] The instance storage subunit is used to store the execution instance in memory using a combination of rule identifier and rule version as a cache key, and through ConcurrentDictionary or MemoryCache.

[0160] Furthermore, the cache unit 204 also includes:

[0161] The persistence subunit is used to persist the DLL file to a specified directory;

[0162] The file loading subunit is used to load the DLL file into memory based on the specified directory and via Assembly.LoadFile.

[0163] Furthermore, the conversion unit 202 includes:

[0164] The validation subunit is used to perform syntax validation and type safety checks on the business rule expression.

[0165] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working process of the above-described apparatus and unit can be referred to the corresponding process in the foregoing method embodiments, and will not be repeated here.

[0166] The present invention also provides a computer-readable storage medium having a computer program stored thereon, which, when executed, can implement the methods provided in the above embodiments. The storage medium may include various media capable of storing program code, such as a USB flash drive, a portable hard drive, a read-only memory (ROM), a random access memory (RAM), a magnetic disk, or an optical disk.

[0167] The present invention also provides a computer device, which may include a memory and a processor. The memory stores a computer program, and when the processor calls the computer program in the memory, it can implement the methods provided in the above embodiments. Of course, the computer device may also include various network interfaces, power supplies, and other components.

[0168] The various embodiments in this specification are described in a progressive manner, with each embodiment focusing on its differences from other embodiments. Similar or identical parts between embodiments can be referred to interchangeably. For the apparatus disclosed in the embodiments, since it corresponds to the method disclosed in the embodiments, the description is relatively simple; relevant parts can be referred to in the method section. It should be noted that those skilled in the art can make various improvements and modifications to this invention without departing from its principles, and these improvements and modifications also fall within the protection scope of the claims of this invention.

[0169] It should also be noted that, in this specification, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusivity.

[0170] The term "comprises" implies that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Unless otherwise specified, an element defined by the phrase "comprises a..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes said element.< / rulecachenode> < / rulecachenode>

Claims

1. A method for executing a dynamic business rule engine, characterized in that, include: Receive business rule expressions submitted by users; Convert the business rule expression into an intermediate representation; The intermediate representation is used to generate intermediate language code using namespaces, and the intermediate language code is then compiled into a DLL file. Load the DLL file into memory and cache the corresponding execution instance; Based on the input business data, the execution instance in the cache is invoked to execute the rule logic and the execution result is returned.

2. The dynamic business rule engine execution method according to claim 1, characterized in that, The formats of the business rule expressions include: JSON, DSL rule strings, and logical expressions.

3. The dynamic business rule engine execution method according to claim 1, characterized in that, The step of converting the business rule expression into an intermediate representation includes: The business rule expression is converted into an intermediate representation using a parser tool. The intermediate representation contains a tree structure consisting of condition nodes, operation nodes, and logical operator nodes.

4. The dynamic business rule engine execution method according to claim 1, characterized in that, The step of generating intermediate language code from the intermediate representation through a namespace and compiling the intermediate language code into a DLL file includes: By traversing the intermediate representations, the corresponding intermediate language code is generated using ILGenerator; Dynamic assemblies are constructed using AssemblyBuilder, and the classes and methods of the dynamic assemblies are defined using ModuleBuilder and TypeBuilder. The intermediate language code is embedded into the class of the dynamic assembly; Save the dynamic assembly containing the intermediate language code as a DLL file.

5. The dynamic business rule engine execution method according to claim 1, characterized in that, The step of loading the DLL file into memory and caching the corresponding execution instance includes: The combination of rule identifier and rule version is used as the cache key, and the execution instance is stored in memory through ConcurrentDictionary or MemoryCache.

6. The dynamic business rule engine execution method according to claim 1, characterized in that, The step of loading the DLL file into memory and caching the corresponding execution instance also includes: Persist the DLL file to the specified directory; The DLL file is loaded into memory based on the specified directory and using Assembly.LoadFile.

7. The dynamic business rule engine execution method according to claim 1, characterized in that, The process of converting the business rule expression into an intermediate representation includes: The business rule expression is subjected to syntax validation and type safety checks.

8. A dynamic business rule engine execution device, characterized in that, include: The receiving unit receives the business rule expressions submitted by the user. A conversion unit is used to convert the business rule expression into an intermediate representation. A compilation unit is used to generate intermediate language code from the intermediate representation using a namespace, and to compile the intermediate language code into a DLL file; A caching unit is used to load the DLL file into memory and cache the corresponding execution instance; The execution unit is used to execute rule logic by calling the execution instance in the cache based on the input business data, and return the execution result.

9. A computer device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the computer program, it implements the dynamic business rule engine execution method as described in any one of claims 1 to 7.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, causes the processor to perform the dynamic business rule engine execution method as described in any one of claims 1 to 7.