| | | 1 | | namespace Intentum.Runtime.Policy; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Ruleset for evaluating intent decisions. |
| | | 5 | | /// </summary> |
| | | 6 | | public sealed class IntentPolicy |
| | | 7 | | { |
| | 109 | 8 | | private readonly List<PolicyRule> _rules = []; |
| | | 9 | | |
| | 125 | 10 | | public IReadOnlyCollection<PolicyRule> Rules => _rules; |
| | | 11 | | |
| | | 12 | | /// <summary>Creates an empty policy.</summary> |
| | 279 | 13 | | public IntentPolicy() { } |
| | | 14 | | |
| | | 15 | | /// <summary>Creates a policy with the given rules (e.g. for composition).</summary> |
| | 16 | 16 | | public IntentPolicy(IEnumerable<PolicyRule> rules) |
| | 16 | 17 | | { |
| | 16 | 18 | | _rules.AddRange(rules); |
| | 16 | 19 | | } |
| | | 20 | | |
| | | 21 | | public IntentPolicy AddRule(PolicyRule rule) |
| | 178 | 22 | | { |
| | 178 | 23 | | _rules.Add(rule); |
| | 178 | 24 | | return this; |
| | 178 | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Returns a new policy that evaluates this policy's rules after the base policy's rules (base first, then this). F |
| | | 29 | | /// </summary> |
| | | 30 | | public IntentPolicy WithBase(IntentPolicy basePolicy) |
| | 2 | 31 | | { |
| | 2 | 32 | | ArgumentNullException.ThrowIfNull(basePolicy); |
| | 2 | 33 | | return new IntentPolicy(basePolicy.Rules.Concat(_rules)); |
| | 2 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Returns a new policy that merges all given policies: rules from the first policy first, then the second, etc. Fi |
| | | 38 | | /// </summary> |
| | | 39 | | public static IntentPolicy Merge(params IntentPolicy[] policies) |
| | 3 | 40 | | { |
| | 3 | 41 | | if (policies.Length == 0) |
| | 1 | 42 | | return new IntentPolicy(); |
| | 5 | 43 | | return new IntentPolicy(policies.SelectMany(p => p.Rules)); |
| | 3 | 44 | | } |
| | | 45 | | |
| | | 46 | | public void Validate() |
| | 3 | 47 | | { |
| | 3 | 48 | | if (Rules.Count == 0) |
| | 1 | 49 | | throw new InvalidOperationException("IntentPolicy must contain at least one rule."); |
| | | 50 | | |
| | 10 | 51 | | var duplicateNames = Rules.GroupBy(r => r.Name).Where(g => g.Count() > 1); |
| | 2 | 52 | | if (duplicateNames.Any()) |
| | 2 | 53 | | throw new InvalidOperationException($"Duplicate rule names found: {string.Join(", ", duplicateNames.Select(g |
| | 1 | 54 | | } |
| | | 55 | | } |