-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathEngine.cs
More file actions
457 lines (403 loc) · 19.5 KB
/
Engine.cs
File metadata and controls
457 lines (403 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using FlagsmithEngine.Interfaces;
using FlagsmithEngine.Segment;
using FlagsmithEngine.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Semver;
namespace FlagsmithEngine
{
public class SegmentOverride<FeatureMetadataT>
{
public FeatureContext<FeatureMetadataT> FeatureContext { get; set; }
public string SegmentName { get; set; }
}
public class Engine : IEngine
{
public static Hashing Hashing = new Hashing();
public const double StrongestPriority = double.NegativeInfinity;
public const double WeakestPriority = double.PositiveInfinity;
/// <summary>
/// Get the evaluation result for a given context
/// </summary>
/// <typeparam name="SegmentMetadataT">Segment metadata type</typeparam>
/// <typeparam name="FeatureMetadataT">Feature metadata type</typeparam>
/// <param name="context"></param>
/// <returns></returns>
public EvaluationResult<SegmentMetadataT, FeatureMetadataT> GetEvaluationResult<SegmentMetadataT, FeatureMetadataT>(EvaluationContext<SegmentMetadataT, FeatureMetadataT> context)
{
context = GetEnrichedEvaluationContext(context);
var result = new EvaluationResult<SegmentMetadataT, FeatureMetadataT>();
var segmentEvaluationResult = EvaluateSegments(context);
result.Flags = EvaluateFlags(context, segmentEvaluationResult.SegmentOverrides);
result.Segments = segmentEvaluationResult.Segments;
return result;
}
private EvaluationContext<SegmentMetadataT, FeatureMetadataT> GetEnrichedEvaluationContext<SegmentMetadataT, FeatureMetadataT>(EvaluationContext<SegmentMetadataT, FeatureMetadataT> context)
{
if (context.Identity != null)
{
if (string.IsNullOrEmpty(context.Identity.Key))
{
context = context.Clone();
context.Identity.Key = context.Environment.Key + "_" + context.Identity.Identifier;
}
}
return context;
}
private static (SegmentResult<SegmentMetadataT>[] Segments, Dictionary<string, SegmentOverride<FeatureMetadataT>> SegmentOverrides) EvaluateSegments<SegmentMetadataT, FeatureMetadataT>(EvaluationContext<SegmentMetadataT, FeatureMetadataT> context)
{
var segmentOverrides = new Dictionary<string, SegmentOverride<FeatureMetadataT>>();
if (context?.Segments is null)
{ return (Array.Empty<SegmentResult<SegmentMetadataT>>(), segmentOverrides); }
var segmentResults = new List<SegmentResult<SegmentMetadataT>>();
foreach (var segmentItem in context.Segments)
{
var segmentContext = segmentItem.Value;
if (!IsContextInSegment(context, segmentContext))
continue;
segmentResults.Add(new SegmentResult<SegmentMetadataT>
{
Name = segmentContext.Name,
Metadata = segmentContext.Metadata
});
if (segmentContext.Overrides is null)
continue;
foreach (var segmentOverride in segmentContext.Overrides)
{
var featureName = segmentOverride.Name;
if (segmentOverrides.ContainsKey(featureName))
{
var existingPriority = segmentOverrides[featureName].FeatureContext.Priority ?? WeakestPriority;
if ((segmentOverride.Priority ?? WeakestPriority) > existingPriority)
continue;
}
segmentOverrides[segmentOverride.Name] = new SegmentOverride<FeatureMetadataT>
{
FeatureContext = segmentOverride,
SegmentName = segmentContext.Name
};
}
}
return (segmentResults.ToArray(), segmentOverrides);
}
private static Dictionary<string, FlagResult<FeatureMetadataT>> EvaluateFlags<Any, FeatureMetadataT>(EvaluationContext<Any, FeatureMetadataT> context, Dictionary<string, SegmentOverride<FeatureMetadataT>> segmentOverrides)
{
var flags = new Dictionary<string, FlagResult<FeatureMetadataT>>();
if (context?.Features is null)
return flags;
foreach (var featureItem in context.Features)
{
var featureContext = featureItem.Value;
var featureName = featureContext.Name;
if (segmentOverrides.ContainsKey(featureName))
{
var segmentOverride = segmentOverrides[featureName];
flags[featureName] = GetFlagResult(
context,
segmentOverride.FeatureContext,
$"TARGETING_MATCH; segment={segmentOverride.SegmentName}"
);
}
else
{
flags[featureName] = GetFlagResult(
context,
featureContext,
"DEFAULT"
);
}
}
return flags;
}
private static bool IsContextInSegment<_, __>(EvaluationContext<_, __> context, SegmentContext<_, __> segmentContext)
{
return (
segmentContext?.Rules != null &&
segmentContext.Rules.All(rule => ContextMatchesRule(
context,
rule,
segmentContext.Key
))
);
}
private static bool ContextMatchesRule<_, __>(EvaluationContext<_, __> context, SegmentRule rule, string segmentKey)
{
bool matchesConditions;
if (rule?.Conditions is null || !rule.Conditions.Any())
// Sometimes rules are just groupers of subrules, having no intrinsic conditions
matchesConditions = true;
else
switch (rule.Type)
{
case TypeEnum.All:
matchesConditions = rule.Conditions.All(condition => ContextMatchesCondition(context, condition, segmentKey));
break;
case TypeEnum.Any:
matchesConditions = rule.Conditions.Any(condition => ContextMatchesCondition(context, condition, segmentKey));
break;
case TypeEnum.None:
matchesConditions = !rule.Conditions.Any(condition => ContextMatchesCondition(context, condition, segmentKey));
break;
default:
matchesConditions = false;
break;
}
return matchesConditions && (rule.Rules?.All(r => ContextMatchesRule(context, r, segmentKey)) ?? true);
}
private static bool ContextMatchesCondition<_, __>(EvaluationContext<_, __> context, Condition condition, string segmentKey)
{
var contextValue = GetContextValue(context, condition.Property);
switch (condition.Operator)
{
case Operator.In:
if (contextValue == null || contextValue.GetType() == typeof(bool))
return false;
HashSet<string> inValues;
if (condition.Value.StringArray != null)
{
inValues = new HashSet<string>(condition.Value.StringArray);
}
else
{
try
{
inValues = new HashSet<string>(JsonConvert.DeserializeObject<string[]>(condition.Value.String));
}
catch (JsonException)
{
inValues = new HashSet<string>(condition.Value.String.Split(','));
}
}
return inValues.Contains(contextValue.ToString());
case Operator.PercentageSplit:
List<string> objectIds;
if (contextValue != null)
objectIds = new List<string> { segmentKey, contextValue.ToString() };
else if (string.IsNullOrEmpty(condition.Property) && context.Identity?.Key != null)
objectIds = new List<string> { segmentKey, context.Identity.Key };
else
return false;
float floatConditionValue;
try
{
floatConditionValue = float.Parse(condition.Value.String);
}
catch (FormatException)
{
return false;
}
return Hashing.GetHashedPercentageForObjectIds(objectIds) <= floatConditionValue;
case Operator.IsNotSet:
return contextValue == null;
case Operator.IsSet:
return contextValue != null;
default:
if (contextValue == null)
return false;
return MatchesContextValue(contextValue, condition);
}
}
private static object GetContextValue<_, __>(EvaluationContext<_, __> context, string property)
{
object value = null;
if (!(context.Identity?.Traits?.TryGetValue(property, out value) ?? false))
{
if (property.StartsWith("$."))
{
var jToken = JToken.FromObject(context).SelectToken(property);
if (jToken is JValue jValue)
{
value = jValue.ToObject<object>();
}
}
}
return value;
}
private static FlagResult<FeatureMetadataT> GetFlagResult<_, FeatureMetadataT>(EvaluationContext<_, FeatureMetadataT> context, FeatureContext<FeatureMetadataT> featureContext, String reason)
{
FlagResult<FeatureMetadataT> flagResult = null;
var key = context?.Identity?.Key;
if (key != null && featureContext.Variants != null)
{
var percentageValue = Hashing.GetHashedPercentageForObjectIds(new List<string>() { featureContext.Key, key });
var startPercentage = 0.0f;
float limit;
foreach (var variant in featureContext.Variants.OrderBy(v => v.Priority))
{
var weight = (float)variant.Weight;
limit = weight + startPercentage;
if (startPercentage <= percentageValue && percentageValue < limit)
{
flagResult = new FlagResult<FeatureMetadataT>
{
Name = featureContext.Name,
Enabled = featureContext.Enabled,
Value = variant.Value,
Metadata = featureContext.Metadata,
Reason = FormattableString.Invariant($"SPLIT; weight={weight}"),
};
break;
}
startPercentage += weight;
}
}
if (flagResult is null)
{
flagResult = new FlagResult<FeatureMetadataT>
{
Name = featureContext.Name,
Enabled = featureContext.Enabled,
Value = featureContext.Value,
Metadata = featureContext.Metadata,
Reason = reason
};
}
return flagResult;
}
private static bool MatchesContextValue(object contextValue, Condition condition)
{
switch (condition.Operator)
{
case Operator.NotContains:
return !contextValue.ToString().Contains(condition.Value.String);
case Operator.Regex:
return Regex.Match(contextValue.ToString(), condition.Value.String).Success;
case Operator.Modulo:
return EvaluateModulo(contextValue.ToString(), condition.Value.String);
default:
return MatchingFunctionName(contextValue, condition);
}
}
private static bool EvaluateModulo(string contextValue, string conditionValue)
{
try
{
string[] parts = conditionValue.Split('|');
if (parts.Length != 2) { return false; }
double divisor = Convert.ToDouble(parts[0]);
double remainder = Convert.ToDouble(parts[1]);
return Convert.ToDouble(contextValue) % divisor == remainder;
}
catch (FormatException)
{
return false;
}
}
private static bool MatchingFunctionName(object contextValue, Condition condition)
{
switch (contextValue.GetType().FullName)
{
case "System.Int32":
return IntOperations((Int32)contextValue, condition);
case "System.Int64":
return LongOperations((Int64)contextValue, condition);
case "System.Double":
return DoubleOperations((double)contextValue, condition);
case "System.Boolean":
return BoolOperations((bool)contextValue, condition);
default:
return StringOperations((string)contextValue, condition);
}
}
private static bool StringOperations(string contextValue, Condition condition)
{
var conditionValue = condition.Value.String;
if (conditionValue.EndsWith(":semver"))
{
return SemVerOperations(contextValue, condition);
}
switch (condition.Operator)
{
case Operator.Equal: return contextValue == conditionValue;
case Operator.NotEqual: return contextValue != conditionValue;
case Operator.Contains: return contextValue.Contains(conditionValue);
default: throw new ArgumentException("Invalid Operator");
}
}
private static bool LongOperations(long contextValue, Condition condition)
{
long conditionValue;
try
{
conditionValue = InvariantConvert.ToInt64(condition.Value.String);
}
catch (FormatException)
{
return false;
}
switch (condition.Operator)
{
case Operator.Equal: return contextValue == conditionValue;
case Operator.NotEqual: return contextValue != conditionValue;
case Operator.GreaterThan: return contextValue > conditionValue;
case Operator.GreaterThanInclusive: return contextValue >= conditionValue;
case Operator.LessThan: return contextValue < conditionValue;
case Operator.LessThanInclusive: return contextValue <= conditionValue;
default: throw new ArgumentException("Invalid Operator");
}
}
private static bool IntOperations(long contextValue, Condition condition)
{
switch (condition.Operator)
{
case Operator.Equal: return contextValue == InvariantConvert.ToInt32(condition.Value.String);
case Operator.NotEqual: return contextValue != InvariantConvert.ToInt32(condition.Value.String);
case Operator.GreaterThan: return contextValue > InvariantConvert.ToInt32(condition.Value.String);
case Operator.GreaterThanInclusive: return contextValue >= InvariantConvert.ToInt32(condition.Value.String);
case Operator.LessThan: return contextValue < InvariantConvert.ToInt32(condition.Value.String);
case Operator.LessThanInclusive: return contextValue <= InvariantConvert.ToInt32(condition.Value.String);
default: throw new ArgumentException("Invalid Operator");
}
}
private static bool DoubleOperations(double contextValue, Condition condition)
{
switch (condition.Operator)
{
case Operator.Equal: return contextValue == InvariantConvert.ToDouble(condition.Value.String);
case Operator.NotEqual: return contextValue != InvariantConvert.ToDouble(condition.Value.String);
case Operator.GreaterThan: return contextValue > InvariantConvert.ToDouble(condition.Value.String);
case Operator.GreaterThanInclusive: return contextValue >= InvariantConvert.ToDouble(condition.Value.String);
case Operator.LessThan: return contextValue < InvariantConvert.ToDouble(condition.Value.String);
case Operator.LessThanInclusive: return contextValue <= InvariantConvert.ToDouble(condition.Value.String);
default: throw new ArgumentException("Invalid Operator");
}
}
private static bool BoolOperations(bool contextValue, Condition condition)
{
switch (condition.Operator)
{
case Operator.Equal: return contextValue == ToBoolean(condition.Value.String);
case Operator.NotEqual: return contextValue != ToBoolean(condition.Value.String);
default: throw new ArgumentException("Invalid Operator");
}
}
private static bool SemVerOperations(string contextValue, Condition condition)
{
try
{
string conditionValue = condition.Value.String.Substring(0, condition.Value.String.Length - 7);
SemVersion conditionValueAsVersion = SemVersion.Parse(conditionValue, SemVersionStyles.Strict);
SemVersion contextValueAsVersion = SemVersion.Parse(contextValue, SemVersionStyles.Strict);
switch (condition.Operator)
{
case Operator.Equal: return contextValueAsVersion == conditionValueAsVersion;
case Operator.NotEqual: return contextValueAsVersion != conditionValueAsVersion;
case Operator.GreaterThan: return contextValueAsVersion.ComparePrecedenceTo(conditionValueAsVersion) > 0;
case Operator.GreaterThanInclusive: return contextValueAsVersion.ComparePrecedenceTo(conditionValueAsVersion) >= 0;
case Operator.LessThan: return contextValueAsVersion.ComparePrecedenceTo(conditionValueAsVersion) < 0;
case Operator.LessThanInclusive: return contextValueAsVersion.ComparePrecedenceTo(conditionValueAsVersion) <= 0;
default: throw new ArgumentException("Invalid Operator");
}
}
catch (FormatException)
{
return false;
}
}
private static bool ToBoolean(string conditionValue) => !new[] { "false", "False" }.Contains(conditionValue);
}
}