| | | 1 | | using Intentum.Core.Intents; |
| | | 2 | | using Intentum.Runtime.Engine; |
| | | 3 | | |
| | | 4 | | namespace Intentum.Runtime.Policy; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A/B policy variants: multiple named policies with a selector to choose which policy applies for a given intent. |
| | | 8 | | /// </summary> |
| | | 9 | | public sealed class PolicyVariantSet |
| | | 10 | | { |
| | | 11 | | private readonly IReadOnlyDictionary<string, IntentPolicy> _variants; |
| | | 12 | | private readonly Func<Intent, string> _selector; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Creates a variant set with named policies and a selector that returns the variant name for a given intent. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="variants">Named policies (e.g. "control", "treatment").</param> |
| | | 18 | | /// <param name="selector">Function that returns which variant name to use for the given intent (e.g. random, by con |
| | 3 | 19 | | public PolicyVariantSet( |
| | 3 | 20 | | IReadOnlyDictionary<string, IntentPolicy> variants, |
| | 3 | 21 | | Func<Intent, string> selector) |
| | 3 | 22 | | { |
| | 3 | 23 | | _variants = variants ?? throw new ArgumentNullException(nameof(variants)); |
| | 3 | 24 | | _selector = selector ?? throw new ArgumentNullException(nameof(selector)); |
| | 3 | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Evaluates the intent with the policy selected by the selector. If the selected variant name is unknown, returns |
| | | 29 | | /// </summary> |
| | | 30 | | public PolicyDecision Decide(Intent intent) |
| | 3 | 31 | | { |
| | 3 | 32 | | var name = _selector(intent); |
| | 3 | 33 | | if (string.IsNullOrEmpty(name) || !_variants.TryGetValue(name, out var policy)) |
| | 1 | 34 | | return PolicyDecision.Observe; |
| | 2 | 35 | | return IntentPolicyEngine.Evaluate(intent, policy); |
| | 3 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Returns the variant names in this set. |
| | | 40 | | /// </summary> |
| | 3 | 41 | | public IReadOnlyCollection<string> GetVariantNames() => _variants.Keys.ToList(); |
| | | 42 | | } |