flagdock 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flagdock/engine.py ADDED
@@ -0,0 +1,673 @@
1
+ """The Flagdock flag engine, ported line by line from ``@flagdock/core``.
2
+
3
+ Pure and synchronous: no I/O, no clock and no randomness, so this SDK, the edge and every other SDK
4
+ give every person the same answer. ``tests/test_parity.py`` checks it against thousands of answers
5
+ worked out by the TypeScript engine (``packages/core/vectors/parity.json``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime as _dt
11
+ import math
12
+ import re
13
+ from decimal import Decimal as _Decimal
14
+ from collections.abc import Mapping, Sequence
15
+ from dataclasses import dataclass, replace
16
+ from typing import Any, Optional
17
+
18
+ __all__ = [
19
+ "BUCKETS",
20
+ "Resolution",
21
+ "evaluate",
22
+ "in_audience",
23
+ "js_string",
24
+ "matches_condition",
25
+ "murmur3",
26
+ "rollout_bucket",
27
+ "split_bucket",
28
+ ]
29
+
30
+ # --- Hashing ------------------------------------------------------------------------------------------
31
+
32
+ _MASK = 0xFFFFFFFF
33
+
34
+
35
+ def _rotl(x: int, r: int) -> int:
36
+ return ((x << r) | (x >> (32 - r))) & _MASK
37
+
38
+
39
+ def murmur3(text: str, seed: int = 0) -> int:
40
+ """MurmurHash3 (x86, 32-bit) over the UTF-8 bytes of a string."""
41
+ try:
42
+ data = text.encode("utf-8")
43
+ except UnicodeEncodeError:
44
+ # A lone surrogate becomes U+FFFD, as JavaScript's TextEncoder does.
45
+ data = text.encode("utf-16", "surrogatepass").decode("utf-16", "replace").encode("utf-8")
46
+ length = len(data)
47
+ h = seed & _MASK
48
+ c1, c2 = 0xCC9E2D51, 0x1B873593
49
+ blocks = length // 4
50
+ for i in range(blocks):
51
+ o = i * 4
52
+ k = data[o] | (data[o + 1] << 8) | (data[o + 2] << 16) | (data[o + 3] << 24)
53
+ k = (k * c1) & _MASK
54
+ k = _rotl(k, 15)
55
+ k = (k * c2) & _MASK
56
+ h ^= k
57
+ h = _rotl(h, 13)
58
+ h = (h * 5 + 0xE6546B64) & _MASK
59
+ tail = blocks * 4
60
+ k = 0
61
+ rest = length & 3
62
+ if rest == 3:
63
+ k ^= data[tail + 2] << 16
64
+ if rest >= 2:
65
+ k ^= data[tail + 1] << 8
66
+ if rest >= 1:
67
+ k ^= data[tail]
68
+ k = (k * c1) & _MASK
69
+ k = _rotl(k, 15)
70
+ k = (k * c2) & _MASK
71
+ h ^= k
72
+ h ^= length
73
+ h ^= h >> 16
74
+ h = (h * 0x85EBCA6B) & _MASK
75
+ h ^= h >> 13
76
+ h = (h * 0xC2B2AE35) & _MASK
77
+ h ^= h >> 16
78
+ return h
79
+
80
+
81
+ #: Buckets run 0..9999, so percentages are exact to two decimals.
82
+ BUCKETS = 10_000
83
+ _ROLLOUT_SEED = 0x4842 # "HB"
84
+ _SPLIT_SEED = 0x464C4147 # "FLAG"
85
+
86
+
87
+ def rollout_bucket(salt: str, bucket_value: str) -> int:
88
+ """Bucket used to decide whether someone is inside a percentage rollout."""
89
+ return murmur3(f"{salt}:{bucket_value}", _ROLLOUT_SEED) % BUCKETS
90
+
91
+
92
+ def split_bucket(salt: str, bucket_value: str) -> int:
93
+ """Bucket used to pick a value in a split; independent of the rollout bucket."""
94
+ return murmur3(f"{salt}:{bucket_value}", _SPLIT_SEED) % BUCKETS
95
+
96
+
97
+ # --- JavaScript's way of turning values into text and numbers -----------------------------------------
98
+
99
+
100
+ def _is_number(v: Any) -> bool:
101
+ # bool is an int in Python, but never a number in JavaScript.
102
+ return isinstance(v, (int, float)) and not isinstance(v, bool)
103
+
104
+
105
+ def js_string(n: float) -> str:
106
+ """Formats a number exactly like JavaScript's ``String(n)``."""
107
+ if isinstance(n, int) and not isinstance(n, bool):
108
+ if abs(n) < 10**21:
109
+ return str(n)
110
+ n = float(n)
111
+ if math.isnan(n):
112
+ return "NaN"
113
+ if math.isinf(n):
114
+ return "Infinity" if n > 0 else "-Infinity"
115
+ if n == 0:
116
+ return "0"
117
+ sign = "-" if n < 0 else ""
118
+ # repr gives the shortest digits that read back as the same number, as JavaScript does.
119
+ parts = _Decimal(repr(abs(n))).as_tuple()
120
+ digits = "".join(str(d) for d in parts.digits).lstrip("0")
121
+ exponent = int(parts.exponent)
122
+ trimmed = digits.rstrip("0")
123
+ exponent += len(digits) - len(trimmed) # each trailing zero dropped moves the point one place
124
+ digits = trimmed
125
+ point = len(digits) + exponent # where the decimal point goes, counted from the first digit
126
+ k = len(digits)
127
+ if k <= point <= 21:
128
+ return sign + digits + "0" * (point - k)
129
+ if 0 < point <= 21:
130
+ return sign + digits[:point] + "." + digits[point:]
131
+ if -6 < point <= 0:
132
+ return sign + "0." + "0" * (-point) + digits
133
+ e = point - 1
134
+ exp_text = ("+" if e >= 0 else "-") + str(abs(e))
135
+ return sign + digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + exp_text
136
+
137
+
138
+ def _value_string(v: Any) -> str:
139
+ """JavaScript's ``String(v)`` for the values in a condition."""
140
+ if v is None:
141
+ return "null"
142
+ s = _as_string(v)
143
+ return s if s is not None else str(v)
144
+
145
+
146
+ def _as_string(v: Any) -> Optional[str]:
147
+ if isinstance(v, str):
148
+ return v
149
+ if isinstance(v, bool):
150
+ return "true" if v else "false"
151
+ if _is_number(v):
152
+ return js_string(v)
153
+ return None
154
+
155
+
156
+ # The characters JavaScript's String.prototype.trim removes.
157
+ _JS_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
158
+ _DECIMAL = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\Z", re.ASCII)
159
+ _RADIX = re.compile(r"0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\Z", re.ASCII)
160
+
161
+
162
+ def _as_number(v: Any) -> Optional[float]:
163
+ if _is_number(v):
164
+ return float(v) if math.isfinite(v) else None
165
+ if isinstance(v, str):
166
+ s = v.strip(_JS_SPACE)
167
+ if s == "":
168
+ return None
169
+ if _DECIMAL.match(s):
170
+ n = float(s)
171
+ elif _RADIX.match(s):
172
+ n = float(int(s, 0))
173
+ else:
174
+ return None
175
+ return n if math.isfinite(n) else None
176
+ return None
177
+
178
+
179
+ _ISO = re.compile(
180
+ r"([+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?"
181
+ r"(?:[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?"
182
+ r"([Zz]|[+-]\d{2}:?\d{2})?\Z",
183
+ re.ASCII,
184
+ )
185
+
186
+
187
+ def _days_from_civil(y: int, m: int, d: int) -> int:
188
+ """Days since 1970-01-01 for a proleptic Gregorian date; days past the month's end roll over, as in JavaScript."""
189
+ y -= m <= 2
190
+ era = (y if y >= 0 else y - 399) // 400
191
+ yoe = y - era * 400
192
+ mp = (m + 9) % 12
193
+ doy = (153 * mp + 2) // 5 + 1 - 1
194
+ doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
195
+ return era * 146097 + doe - 719468 + (d - 1)
196
+
197
+
198
+ def _parse_iso(text: str) -> Optional[float]:
199
+ """Milliseconds since 1970 for an ISO 8601 date or date-time. Date-times without an offset are read as UTC."""
200
+ m = _ISO.match(text.strip(_JS_SPACE))
201
+ if not m:
202
+ return None
203
+ year_s, month_s, day_s, hh, mm, ss, frac, offset = m.groups()
204
+ if year_s == "-000000":
205
+ return None
206
+ year = int(year_s)
207
+ month = int(month_s) if month_s else 1
208
+ day = int(day_s) if day_s else 1
209
+ if hh is not None and day_s is None:
210
+ return None
211
+ if offset is not None and hh is None:
212
+ return None
213
+ if not 1 <= month <= 12 or not 1 <= day <= 31:
214
+ return None
215
+ hour = int(hh) if hh else 0
216
+ minute = int(mm) if mm else 0
217
+ second = int(ss) if ss else 0
218
+ millis = int((frac or "0")[:3].ljust(3, "0"))
219
+ if minute > 59 or second > 59:
220
+ return None
221
+ if hour > 24 or (hour == 24 and (minute or second or millis)):
222
+ return None
223
+ t = (_days_from_civil(year, month, day) * 86400 + hour * 3600 + minute * 60 + second) * 1000 + millis
224
+ if offset and offset not in ("Z", "z"):
225
+ sign = -1 if offset[0] == "-" else 1
226
+ digits = offset[1:].replace(":", "")
227
+ oh, om = int(digits[:2]), int(digits[2:])
228
+ if oh > 23 or om > 59:
229
+ return None
230
+ t -= sign * (oh * 60 + om) * 60_000
231
+ if abs(t) > 8.64e15:
232
+ return None
233
+ return float(t)
234
+
235
+
236
+ def _as_time(v: Any) -> Optional[float]:
237
+ if isinstance(v, _dt.datetime):
238
+ aware = v if v.tzinfo else v.replace(tzinfo=_dt.timezone.utc)
239
+ return math.floor(aware.timestamp() * 1000)
240
+ if isinstance(v, _dt.date):
241
+ return float(_days_from_civil(v.year, v.month, v.day) * 86_400_000)
242
+ if _is_number(v):
243
+ return float(v) if math.isfinite(v) else None
244
+ if isinstance(v, str):
245
+ return _parse_iso(v)
246
+ return None
247
+
248
+
249
+ _VERSION_PART = re.compile(r"\d+\Z", re.ASCII)
250
+
251
+
252
+ def _parse_version(v: Any) -> Optional[tuple[list[int], bool]]:
253
+ s = _as_string(v)
254
+ if s is None:
255
+ return None
256
+ s = s.strip(_JS_SPACE)
257
+ if s[:1] in ("v", "V"):
258
+ s = s[1:]
259
+ if not s:
260
+ return None
261
+ main, *rest = s.split("+")[0].split("-")
262
+ pieces = main.split(".")
263
+ if len(pieces) > 4 or not all(_VERSION_PART.match(p) for p in pieces):
264
+ return None
265
+ parts = [int(p) for p in pieces]
266
+ while len(parts) < 3:
267
+ parts.append(0)
268
+ return parts, len(rest) > 0
269
+
270
+
271
+ def _compare_versions(a: Any, b: Any) -> Optional[int]:
272
+ x = _parse_version(a)
273
+ y = _parse_version(b)
274
+ if x is None or y is None:
275
+ return None
276
+ n = max(len(x[0]), len(y[0]))
277
+ for i in range(n):
278
+ d = (x[0][i] if i < len(x[0]) else 0) - (y[0][i] if i < len(y[0]) else 0)
279
+ if d != 0:
280
+ return -1 if d < 0 else 1
281
+ if x[1] != y[1]:
282
+ return -1 if x[1] else 1
283
+ return 0
284
+
285
+
286
+ def _fold(s: str, ignore_case: bool) -> str:
287
+ return s.lower() if ignore_case else s
288
+
289
+
290
+ # --- Conditions and audiences ---------------------------------------------------------------------------
291
+
292
+ _MISSING = object()
293
+
294
+
295
+ def _attribute(context: Mapping[str, Any], name: str) -> Any:
296
+ return context.get(name, _MISSING) if isinstance(context, Mapping) else _MISSING
297
+
298
+
299
+ def _candidates(actual: Any) -> Sequence[Any]:
300
+ return actual if isinstance(actual, list) else [actual]
301
+
302
+
303
+ _KNOWN_OPS = frozenset(
304
+ [
305
+ "is_one_of",
306
+ "is_not_one_of",
307
+ "contains",
308
+ "starts_with",
309
+ "ends_with",
310
+ "greater_than",
311
+ "greater_or_equal",
312
+ "less_than",
313
+ "less_or_equal",
314
+ "version_at_least",
315
+ "version_below",
316
+ "before",
317
+ "after",
318
+ ]
319
+ )
320
+
321
+
322
+ def _check(cond: Mapping[str, Any], actual: Any) -> bool:
323
+ op = cond.get("op")
324
+ values = cond.get("values") or []
325
+ ignore_case = bool(cond.get("ignoreCase"))
326
+ missing = actual is _MISSING or actual is None
327
+
328
+ if op == "is_not_one_of":
329
+ if missing:
330
+ return True
331
+ wanted = {_fold(_value_string(v), ignore_case) for v in values}
332
+ for a in _candidates(actual):
333
+ s = _as_string(a)
334
+ if s is not None and _fold(s, ignore_case) in wanted:
335
+ return False
336
+ return True
337
+ if missing:
338
+ return False
339
+
340
+ def some(fn: Any) -> bool:
341
+ return any(fn(a, v) for a in _candidates(actual) for v in values)
342
+
343
+ def text(fn: Any) -> bool:
344
+ def one(a: Any, v: Any) -> bool:
345
+ s = _as_string(a)
346
+ return s is not None and fn(_fold(s, ignore_case), _fold(_value_string(v), ignore_case))
347
+
348
+ return some(one)
349
+
350
+ def num(fn: Any) -> bool:
351
+ def one(a: Any, v: Any) -> bool:
352
+ x, y = _as_number(a), _as_number(v)
353
+ return x is not None and y is not None and fn(x, y)
354
+
355
+ return some(one)
356
+
357
+ def ver(fn: Any) -> bool:
358
+ def one(a: Any, v: Any) -> bool:
359
+ c = _compare_versions(a, v)
360
+ return c is not None and fn(c)
361
+
362
+ return some(one)
363
+
364
+ def time(fn: Any) -> bool:
365
+ def one(a: Any, v: Any) -> bool:
366
+ x, y = _as_time(a), _as_time(v)
367
+ return x is not None and y is not None and fn(x, y)
368
+
369
+ return some(one)
370
+
371
+ if op == "is_one_of":
372
+ return text(lambda a, v: a == v)
373
+ if op == "contains":
374
+ return text(lambda a, v: v in a)
375
+ if op == "starts_with":
376
+ return text(lambda a, v: a.startswith(v))
377
+ if op == "ends_with":
378
+ return text(lambda a, v: a.endswith(v))
379
+ if op == "greater_than":
380
+ return num(lambda a, v: a > v)
381
+ if op == "greater_or_equal":
382
+ return num(lambda a, v: a >= v)
383
+ if op == "less_than":
384
+ return num(lambda a, v: a < v)
385
+ if op == "less_or_equal":
386
+ return num(lambda a, v: a <= v)
387
+ if op == "version_at_least":
388
+ return ver(lambda c: c >= 0)
389
+ if op == "version_below":
390
+ return ver(lambda c: c < 0)
391
+ if op == "before":
392
+ return time(lambda a, v: a < v)
393
+ if op == "after":
394
+ return time(lambda a, v: a > v)
395
+ return False
396
+
397
+
398
+ def matches_condition(cond: Mapping[str, Any], context: Mapping[str, Any]) -> bool:
399
+ """True when the condition holds. An operator this version does not know fails closed, even negated."""
400
+ if cond.get("op") not in _KNOWN_OPS:
401
+ return False
402
+ result = _check(cond, _attribute(context, str(cond.get("attribute"))))
403
+ return not result if cond.get("negate") else result
404
+
405
+
406
+ def _matches_all(conditions: Optional[Sequence[Mapping[str, Any]]], context: Mapping[str, Any]) -> bool:
407
+ return all(matches_condition(c, context) for c in conditions or [])
408
+
409
+
410
+ # A list can hold thousands of IDs and is asked on every check, so each one is turned into a set once.
411
+ _member_sets: dict[int, tuple[Sequence[Any], frozenset[str]]] = {}
412
+
413
+
414
+ def _members(audience: Mapping[str, Any]) -> frozenset[str]:
415
+ members = audience.get("members") or []
416
+ cached = _member_sets.get(id(members))
417
+ if cached is not None and cached[0] is members:
418
+ return cached[1]
419
+ result = frozenset(m for m in members if isinstance(m, str))
420
+ if len(_member_sets) > 10_000:
421
+ _member_sets.clear()
422
+ _member_sets[id(members)] = (members, result)
423
+ return result
424
+
425
+
426
+ def _on_list(audience: Optional[Mapping[str, Any]], context: Mapping[str, Any]) -> Optional[bool]:
427
+ if not audience or not audience.get("members"):
428
+ return None
429
+ ident = _attribute(context, _or(audience.get("memberAttribute"), "targetingKey"))
430
+ if isinstance(ident, str):
431
+ return ident in _members(audience)
432
+ if _is_number(ident):
433
+ return js_string(ident) in _members(audience)
434
+ return False
435
+
436
+
437
+ def in_audience(audience: Optional[Mapping[str, Any]], context: Mapping[str, Any]) -> bool:
438
+ """Whether the person is in the audience: on its list, or meeting all its conditions."""
439
+ if audience is None:
440
+ return False
441
+ if _on_list(audience, context):
442
+ return True
443
+ if audience.get("members") and len(audience.get("conditions") or []) == 0:
444
+ return False
445
+ return _matches_all(audience.get("conditions"), context)
446
+
447
+
448
+ # --- Evaluation ------------------------------------------------------------------------------------------
449
+
450
+
451
+ @dataclass(frozen=True)
452
+ class Resolution:
453
+ """What one flag returns for one context, and why."""
454
+
455
+ value: Any
456
+ reason: str
457
+ value_key: Optional[str] = None
458
+ error_code: Optional[str] = None
459
+ error_message: Optional[str] = None
460
+ rule_id: Optional[str] = None
461
+ rule_index: Optional[int] = None
462
+ bucket: Optional[int] = None
463
+ prerequisite: Optional[str] = None
464
+
465
+ def to_dict(self) -> dict[str, Any]:
466
+ """The same keys the TypeScript engine uses, leaving out the ones that are not set."""
467
+ out: dict[str, Any] = {"value": self.value, "reason": self.reason}
468
+ for name, key in (
469
+ ("value_key", "valueKey"),
470
+ ("error_code", "errorCode"),
471
+ ("error_message", "errorMessage"),
472
+ ("rule_id", "ruleId"),
473
+ ("rule_index", "ruleIndex"),
474
+ ("bucket", "bucket"),
475
+ ("prerequisite", "prerequisite"),
476
+ ):
477
+ v = getattr(self, name)
478
+ if v is not None:
479
+ out[key] = v
480
+ return out
481
+
482
+
483
+ def _bucket_value(rule: Mapping[str, Any], context: Mapping[str, Any]) -> Optional[str]:
484
+ raw = _attribute(context, _or(rule.get("bucketBy"), "targetingKey"))
485
+ if isinstance(raw, str):
486
+ return None if raw == "" else raw
487
+ if _is_number(raw) and math.isfinite(raw):
488
+ return js_string(raw)
489
+ return None
490
+
491
+
492
+ def _or(value: Any, default: Any) -> Any:
493
+ """JavaScript's ``value ?? default``: only a missing value falls back, not an empty one."""
494
+ return default if value is None else value
495
+
496
+
497
+ def _js_round(x: float) -> int:
498
+ return math.floor(x + 0.5)
499
+
500
+
501
+ def _threshold(rule: Mapping[str, Any]) -> int:
502
+ raw = rule.get("percentage")
503
+ pct = float(raw) if isinstance(raw, (int, float)) and not isinstance(raw, bool) else 0.0
504
+ return _js_round(min(100.0, max(0.0, pct)) * (BUCKETS / 100))
505
+
506
+
507
+ def _rule_matches(
508
+ rule: Mapping[str, Any], flag: Mapping[str, Any], ruleset: Mapping[str, Any], context: Mapping[str, Any]
509
+ ) -> tuple[bool, Optional[int]]:
510
+ if not _matches_all(rule.get("conditions"), context):
511
+ return False, None
512
+ audiences = ruleset.get("audiences") or {}
513
+ for key in rule.get("audiences") or []:
514
+ if not in_audience(audiences.get(key), context):
515
+ return False, None
516
+ kind = rule.get("type")
517
+ if kind == "everyone":
518
+ return True, None
519
+ if kind == "audience":
520
+ return len(rule.get("audiences") or []) + len(rule.get("conditions") or []) > 0, None
521
+ if kind == "users":
522
+ key = _attribute(context, "targetingKey")
523
+ return isinstance(key, str) and key in (rule.get("users") or []), None
524
+ if kind == "percentage":
525
+ value = _bucket_value(rule, context)
526
+ if value is None:
527
+ return False, None
528
+ bucket = rollout_bucket(_or(rule.get("salt"), flag["key"]), value)
529
+ return bucket < _threshold(rule), bucket
530
+ return False, None
531
+
532
+
533
+ def _pick_from_split(
534
+ split: Sequence[Mapping[str, Any]], rule: Mapping[str, Any], flag: Mapping[str, Any], context: Mapping[str, Any]
535
+ ) -> Optional[str]:
536
+ usable = [s for s in split if _is_number(s.get("weight")) and s["weight"] > 0]
537
+ total = sum(s["weight"] for s in usable)
538
+ if total <= 0:
539
+ return None
540
+ value = _bucket_value(rule, context)
541
+ # Without something stable to hash, everyone gets the first value rather than a random one.
542
+ if value is None:
543
+ return str(usable[0]["value"])
544
+ point = (split_bucket(_or(rule.get("salt"), flag["key"]), value) / BUCKETS) * total
545
+ upto = 0.0
546
+ for s in usable:
547
+ upto += s["weight"]
548
+ if point < upto:
549
+ return str(s["value"])
550
+ return str(usable[-1]["value"])
551
+
552
+
553
+ def _kind_of(value: Any) -> str:
554
+ if isinstance(value, bool):
555
+ return "boolean"
556
+ if isinstance(value, str):
557
+ return "string"
558
+ if _is_number(value):
559
+ return "number"
560
+ return "json"
561
+
562
+
563
+ def evaluate(
564
+ ruleset: Mapping[str, Any],
565
+ flag_key: str,
566
+ context: Mapping[str, Any],
567
+ fallback: Any,
568
+ expected_kind: Optional[str] = None,
569
+ ) -> Resolution:
570
+ """Decides what one flag returns for one context.
571
+
572
+ ``fallback`` is returned when the flag is unknown or its configuration is broken. When
573
+ ``expected_kind`` is given, a flag of another kind returns the fallback with TYPE_MISMATCH.
574
+ """
575
+ return _evaluate_at(ruleset, flag_key, context, fallback, expected_kind, 0)[0]
576
+
577
+
578
+ #: How many flags deep prerequisites may go. Deeper chains, and loops, are treated as broken.
579
+ MAX_PREREQUISITE_DEPTH = 10
580
+
581
+
582
+ def _evaluate_at(
583
+ ruleset: Mapping[str, Any],
584
+ flag_key: str,
585
+ context: Mapping[str, Any],
586
+ fallback: Any,
587
+ expected_kind: Optional[str],
588
+ depth: int,
589
+ ) -> tuple[Resolution, bool]:
590
+ """``evaluate`` at a prerequisite depth; the flag says the result comes from a broken chain."""
591
+ flags = ruleset.get("flags") or {}
592
+ flag = flags.get(flag_key)
593
+ if flag is None:
594
+ return Resolution(fallback, "ERROR", error_code="FLAG_NOT_FOUND", error_message=f'Flag "{flag_key}" does not exist'), False
595
+ if expected_kind and flag.get("kind") != expected_kind:
596
+ return Resolution(
597
+ fallback,
598
+ "ERROR",
599
+ error_code="TYPE_MISMATCH",
600
+ error_message=f'Flag "{flag_key}" is a {flag.get("kind")} flag, not {expected_kind}',
601
+ ), False
602
+
603
+ values = flag.get("values") or {}
604
+
605
+ def serve(
606
+ value_key: Any,
607
+ reason: str,
608
+ rule_id: Optional[str] = None,
609
+ rule_index: Optional[int] = None,
610
+ bucket: Optional[int] = None,
611
+ prerequisite: Optional[str] = None,
612
+ ) -> tuple[Resolution, bool]:
613
+ if not isinstance(value_key, str) or value_key not in values:
614
+ return Resolution(
615
+ fallback,
616
+ "ERROR",
617
+ error_code="GENERAL",
618
+ error_message=f'Flag "{flag_key}" refers to a value "{value_key}" it does not have',
619
+ ), False
620
+ value = values[value_key]
621
+ if flag.get("kind") != "json" and _kind_of(value) != flag.get("kind"):
622
+ return Resolution(
623
+ fallback,
624
+ "ERROR",
625
+ error_code="TYPE_MISMATCH",
626
+ error_message=f'Value "{value_key}" of flag "{flag_key}" is not a {flag.get("kind")}',
627
+ ), False
628
+ resolved = Resolution(
629
+ value, reason, value_key=value_key, rule_id=rule_id, rule_index=rule_index, bucket=bucket, prerequisite=prerequisite
630
+ )
631
+ return resolved, False
632
+
633
+ if not flag.get("enabled"):
634
+ return serve(flag.get("offValue"), "DISABLED")
635
+
636
+ # Each prerequisite is evaluated for the same person. Only a switched-on flag that gives a listed
637
+ # value lets this one go on.
638
+ prerequisites = flag.get("prerequisites")
639
+ if prerequisites:
640
+ if depth >= MAX_PREREQUISITE_DEPTH:
641
+ message = f'Prerequisites of flag "{flag_key}" go more than {MAX_PREREQUISITE_DEPTH} flags deep, or loop'
642
+ return Resolution(fallback, "ERROR", error_code="GENERAL", error_message=message), True
643
+ for prerequisite in prerequisites:
644
+ got, broken = _evaluate_at(ruleset, prerequisite.get("flag"), context, None, None, depth + 1)
645
+ # A broken chain (too deep, or a loop) breaks every flag that depends on it, rather than quietly serving off.
646
+ if broken:
647
+ return replace(got, value=fallback), True
648
+ passed = (
649
+ got.reason not in ("DISABLED", "ERROR")
650
+ and got.value_key is not None
651
+ and got.value_key in (prerequisite.get("values") or [])
652
+ )
653
+ if not passed:
654
+ return serve(flag.get("offValue"), "PREREQUISITE_FAILED", prerequisite=prerequisite.get("flag"))
655
+
656
+ last_bucket: Optional[int] = None
657
+ for i, rule in enumerate(flag.get("rules") or []):
658
+ matched, bucket = _rule_matches(rule, flag, ruleset, context)
659
+ if bucket is not None:
660
+ last_bucket = bucket
661
+ if not matched:
662
+ continue
663
+ served = rule.get("serve")
664
+ if isinstance(served, Mapping) and "split" in served:
665
+ picked = _pick_from_split(served.get("split") or [], rule, flag, context)
666
+ if picked is None:
667
+ message = f'Rule "{rule.get("id")}" has an empty split'
668
+ return Resolution(fallback, "ERROR", error_code="GENERAL", error_message=message), False
669
+ return serve(picked, "SPLIT", rule.get("id"), i, bucket)
670
+ value_key = served.get("value") if isinstance(served, Mapping) and served.get("value") is not None else flag.get("matchValue")
671
+ return serve(value_key, "TARGETING_MATCH", rule.get("id"), i, bucket)
672
+
673
+ return serve(flag.get("defaultValue"), "DEFAULT", bucket=last_bucket)