| 1 | # Dynamic Constraint Functions |
| 2 | |
| 3 | ## Decision |
| 4 | |
| 5 | A new variant of the `AtomicConstraintFunction` will be introduced that allows dynamic evaluation of the `leftOperand` to determine its binding. |
| 6 | |
| 7 | ## Rationale |
| 8 | |
| 9 | Currently, constraint functions can only be bound to a single key (or multiple keys if registered each key) |
| 10 | and the key has to be known at compile-time. The policy evaluation then works on an exact match of the key when evaluating |
| 11 | a `leftOperand` of a constraint. |
| 12 | |
| 13 | We want to enable dynamic use cases where the final shape key it's not known at compile-time, or where users |
| 14 | can write their own matching/dispatching mechanism to the constraint functions. |
| 15 | |
| 16 | ## Approach |
| 17 | |
| 18 | We will introduce a new interface `DynamicAtomicConstraintFunction`: |
| 19 | |
| 20 | ```java |
| 21 | |
| 22 | public interface DynamicAtomicConstraintFunction<R extends Rule> { |
| 23 | |
| 24 | boolean evaluate(Object leftValue, Operator operator, Object rightValue, R rule, PolicyContext context); |
| 25 | |
| 26 | boolean canEvaluate(Object leftValue, Operator operator, Object rightValue, R rule, PolicyContext context); |
| 27 | |
| 28 | } |
| 29 | ``` |
| 30 | |
| 31 | Where the `canEvaluate` method decides if the constraints can be evaluated or not, based in the input parameters. |
| 32 | |
| 33 | The `PolicyEngine` interface will have an additional method for registering those dynamic functions. |
| 34 | |
| 35 | ```java |
| 36 | interface PolicyEngine { |
| 37 | <R extends Rule> void registerFunction(String scope, Class<R> type, DynamicAtomicConstraintFunction<R> function); |
| 38 | } |
| 39 | ``` |
| 40 | |
| 41 | Since constraints are evaluated also based on the `scope`, we will change the `RuleBindingRegistry`, |
| 42 | by adding a new method for registering dynamic binders: |
| 43 | |
| 44 | ```java |
| 45 | public interface RuleBindingRegistry { |
| 46 | void registerDynamicBind(Function<String, Set<String>> binder); |
| 47 | } |
| 48 | ``` |
| 49 | |
| 50 | Dynamic binders are functions that dynamically calculate the scopes for a `ruleType`. |
| 51 | |
| 52 | When evaluating a constraint, the `PolicyEngine` should look up first for the exact match for a specific key binding, |
| 53 | if not found the dynamic functions will be invoked. |