railflag-openfeature 0.1.0__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.
- railflag/__init__.py +9 -0
- railflag/_js.py +154 -0
- railflag/_murmur3.py +58 -0
- railflag/evaluate.py +239 -0
- railflag/provider.py +136 -0
- railflag/py.typed +0 -0
- railflag/source.py +176 -0
- railflag_openfeature-0.1.0.dist-info/METADATA +58 -0
- railflag_openfeature-0.1.0.dist-info/RECORD +10 -0
- railflag_openfeature-0.1.0.dist-info/WHEEL +4 -0
railflag/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Railflag feature flags for Python: an OpenFeature provider that evaluates locally."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .evaluate import EvalResult, evaluate, evaluate_all # noqa: E402
|
|
6
|
+
from .provider import RailflagProvider # noqa: E402
|
|
7
|
+
from .source import ConfigSource # noqa: E402
|
|
8
|
+
|
|
9
|
+
__all__ = ["ConfigSource", "EvalResult", "RailflagProvider", "evaluate", "evaluate_all", "__version__"]
|
railflag/_js.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""JavaScript semantics the evaluator relies on, so Python gives the same answers as the TypeScript
|
|
2
|
+
evaluator (`packages/eval`): `String(x)`, `===`, UTF-16 string ordering and `Date.parse`."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import calendar
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from email.utils import parsedate_to_datetime
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def is_number(v: Any) -> bool:
|
|
14
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def js_number(x: float | int) -> str:
|
|
18
|
+
"""`String(n)` for a JS number: shortest round-trip digits, exponent outside 1e-7..1e21."""
|
|
19
|
+
if isinstance(x, int) and abs(x) < 10**21:
|
|
20
|
+
return str(x)
|
|
21
|
+
x = float(x)
|
|
22
|
+
if math.isnan(x):
|
|
23
|
+
return "NaN"
|
|
24
|
+
if math.isinf(x):
|
|
25
|
+
return "Infinity" if x > 0 else "-Infinity"
|
|
26
|
+
if x == 0:
|
|
27
|
+
return "0"
|
|
28
|
+
sign = "-" if x < 0 else ""
|
|
29
|
+
r = repr(abs(x))
|
|
30
|
+
exp = 0
|
|
31
|
+
if "e" in r:
|
|
32
|
+
r, e = r.split("e")
|
|
33
|
+
exp = int(e)
|
|
34
|
+
int_part, _, frac = r.partition(".")
|
|
35
|
+
all_digits = int_part + frac
|
|
36
|
+
lead = len(all_digits) - len(all_digits.lstrip("0"))
|
|
37
|
+
digits = all_digits.strip("0")
|
|
38
|
+
n = len(int_part) - lead + exp # value = 0.<digits> * 10**n
|
|
39
|
+
k = len(digits)
|
|
40
|
+
if k <= n <= 21:
|
|
41
|
+
out = digits + "0" * (n - k)
|
|
42
|
+
elif 0 < n <= 21:
|
|
43
|
+
out = digits[:n] + "." + digits[n:]
|
|
44
|
+
elif -6 < n <= 0:
|
|
45
|
+
out = "0." + "0" * (-n) + digits
|
|
46
|
+
else:
|
|
47
|
+
e = n - 1
|
|
48
|
+
mant = digits if k == 1 else digits[0] + "." + digits[1:]
|
|
49
|
+
out = f"{mant}e{'+' if e >= 0 else '-'}{abs(e)}"
|
|
50
|
+
return sign + out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def js_string(v: Any) -> str:
|
|
54
|
+
"""`String(v)` for JSON-like values."""
|
|
55
|
+
if v is None:
|
|
56
|
+
return "null"
|
|
57
|
+
if isinstance(v, bool):
|
|
58
|
+
return "true" if v else "false"
|
|
59
|
+
if is_number(v):
|
|
60
|
+
return js_number(v)
|
|
61
|
+
if isinstance(v, str):
|
|
62
|
+
return v
|
|
63
|
+
if isinstance(v, (list, tuple)):
|
|
64
|
+
return ",".join("" if x is None else js_string(x) for x in v)
|
|
65
|
+
return "[object Object]"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def strict_equals(a: Any, b: Any) -> bool:
|
|
69
|
+
"""`a === b` for scalars. `True` is not `1`, and `1 == 1.0`."""
|
|
70
|
+
if is_number(a) and is_number(b):
|
|
71
|
+
return a == b
|
|
72
|
+
if isinstance(a, bool) and isinstance(b, bool):
|
|
73
|
+
return a == b
|
|
74
|
+
if isinstance(a, str) and isinstance(b, str):
|
|
75
|
+
return a == b
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _utf16(s: str) -> bytes:
|
|
80
|
+
return s.encode("utf-16-be", "surrogatepass")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def compare(a: Any, b: Any) -> float | None:
|
|
84
|
+
"""Like `a - b` / `a < b` in JS for number/number and string/string; otherwise None.
|
|
85
|
+
Strings compare by UTF-16 code units, as JavaScript does."""
|
|
86
|
+
if is_number(a) and is_number(b):
|
|
87
|
+
return a - b
|
|
88
|
+
if isinstance(a, str) and isinstance(b, str):
|
|
89
|
+
ua, ub = _utf16(a), _utf16(b)
|
|
90
|
+
return -1 if ua < ub else 1 if ua > ub else 0
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_ISO = re.compile(
|
|
95
|
+
r"^([+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?"
|
|
96
|
+
r"(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})?)?$",
|
|
97
|
+
re.ASCII,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_time(s: str) -> float | None:
|
|
102
|
+
"""`Date.parse` for ISO 8601 and RFC 2822 dates, in epoch milliseconds.
|
|
103
|
+
A date-time without an offset is read as UTC (JavaScript would use the machine's zone)."""
|
|
104
|
+
m = _ISO.match(s)
|
|
105
|
+
if m:
|
|
106
|
+
y, mo, d, h, mi, sec, frac, tz = m.groups()
|
|
107
|
+
try:
|
|
108
|
+
year, month, day = int(y), int(mo or 1), int(d or 1)
|
|
109
|
+
hour, minute, second = int(h or 0), int(mi or 0), int(sec or 0)
|
|
110
|
+
if not (1 <= month <= 12 and 1 <= day <= calendar.monthrange(year, month)[1] and hour <= 24 and minute < 60 and second < 60):
|
|
111
|
+
return None
|
|
112
|
+
if hour == 24 and (minute or second or (frac and int(frac))):
|
|
113
|
+
return None
|
|
114
|
+
ms = int((frac or "0")[:3].ljust(3, "0"))
|
|
115
|
+
days = (calendar.timegm((year, month, 1, 0, 0, 0)) // 86400) + day - 1
|
|
116
|
+
t = ((days * 24 + hour) * 60 + minute) * 60 + second
|
|
117
|
+
if tz and tz != "Z":
|
|
118
|
+
off = int(tz[1:3]) * 60 + int(tz[4:6])
|
|
119
|
+
t -= off * 60 if tz[0] == "+" else -off * 60
|
|
120
|
+
return float(t * 1000 + ms)
|
|
121
|
+
except (ValueError, OverflowError):
|
|
122
|
+
return None
|
|
123
|
+
try:
|
|
124
|
+
dt = parsedate_to_datetime(s)
|
|
125
|
+
except (TypeError, ValueError, IndexError):
|
|
126
|
+
return None
|
|
127
|
+
if dt is None:
|
|
128
|
+
return None
|
|
129
|
+
if dt.tzinfo is None:
|
|
130
|
+
return float(calendar.timegm(dt.timetuple()) * 1000)
|
|
131
|
+
return dt.timestamp() * 1000
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def to_time(v: Any) -> float | None:
|
|
135
|
+
if is_number(v) and math.isfinite(v):
|
|
136
|
+
return float(v)
|
|
137
|
+
if isinstance(v, str):
|
|
138
|
+
return parse_time(v)
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_regex_cache: dict[str, re.Pattern[str] | None] = {}
|
|
143
|
+
_NAMED_GROUP = re.compile(r"\(\?<(?![=!])")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def js_regex(src: str) -> re.Pattern[str] | None:
|
|
147
|
+
"""Compiles a JavaScript regex source for Python's `re` (ASCII \\d and \\w, `(?<name>` groups).
|
|
148
|
+
Returns None when it doesn't compile, which makes the clause not match."""
|
|
149
|
+
if src not in _regex_cache:
|
|
150
|
+
try:
|
|
151
|
+
_regex_cache[src] = re.compile(_NAMED_GROUP.sub("(?P<", src), re.ASCII)
|
|
152
|
+
except re.error:
|
|
153
|
+
_regex_cache[src] = None
|
|
154
|
+
return _regex_cache[src]
|
railflag/_murmur3.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""MurmurHash3 x86 32-bit, matching `packages/eval/src/murmur3.ts` bit for bit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
_C1 = 0xCC9E2D51
|
|
6
|
+
_C2 = 0x1B873593
|
|
7
|
+
_M = 0xFFFFFFFF
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _rotl(x: int, r: int) -> int:
|
|
11
|
+
return ((x << r) | (x >> (32 - r))) & _M
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def hash_bytes(data: bytes, seed: int = 0) -> int:
|
|
15
|
+
h = seed & _M
|
|
16
|
+
n = len(data) & ~3
|
|
17
|
+
for i in range(0, n, 4):
|
|
18
|
+
k = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | (data[i + 3] << 24)
|
|
19
|
+
k = (k * _C1) & _M
|
|
20
|
+
k = _rotl(k, 15)
|
|
21
|
+
k = (k * _C2) & _M
|
|
22
|
+
h ^= k
|
|
23
|
+
h = _rotl(h, 13)
|
|
24
|
+
h = (h * 5 + 0xE6546B64) & _M
|
|
25
|
+
rem = len(data) & 3
|
|
26
|
+
k = 0
|
|
27
|
+
if rem == 3:
|
|
28
|
+
k ^= data[n + 2] << 16
|
|
29
|
+
if rem >= 2:
|
|
30
|
+
k ^= data[n + 1] << 8
|
|
31
|
+
if rem >= 1:
|
|
32
|
+
k ^= data[n]
|
|
33
|
+
k = (k * _C1) & _M
|
|
34
|
+
k = _rotl(k, 15)
|
|
35
|
+
k = (k * _C2) & _M
|
|
36
|
+
h ^= k
|
|
37
|
+
h ^= len(data) & _M
|
|
38
|
+
h ^= h >> 16
|
|
39
|
+
h = (h * 0x85EBCA6B) & _M
|
|
40
|
+
h ^= h >> 13
|
|
41
|
+
h = (h * 0xC2B2AE35) & _M
|
|
42
|
+
h ^= h >> 16
|
|
43
|
+
return h
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _utf16le(s: str) -> bytes:
|
|
47
|
+
return s.encode("utf-16-le", "surrogatepass")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def murmur3(s: str, seed: int = 0) -> int:
|
|
51
|
+
"""Over UTF-8 bytes, with unpaired surrogates encoded as U+FFFD like JavaScript's TextEncoder."""
|
|
52
|
+
well_formed = _utf16le(s).decode("utf-16-le", "replace")
|
|
53
|
+
return hash_bytes(well_formed.encode("utf-8"), seed)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def murmur3_latin1(s: str, seed: int = 0) -> int:
|
|
57
|
+
"""Over the low byte of each UTF-16 code unit, which is how AB Tasty's SDKs hash."""
|
|
58
|
+
return hash_bytes(_utf16le(s)[0::2], seed)
|
railflag/evaluate.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Flag evaluation, ported from `packages/eval` (TypeScript). Both must give identical results for the
|
|
2
|
+
vectors in `packages/eval/vectors/eval-vectors.json`; change them together or not at all."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Mapping, Optional
|
|
9
|
+
|
|
10
|
+
from ._js import compare, is_number, js_regex, js_string, strict_equals, to_time
|
|
11
|
+
from ._murmur3 import murmur3, murmur3_latin1
|
|
12
|
+
|
|
13
|
+
WEIGHT_SCALE = 100_000
|
|
14
|
+
|
|
15
|
+
Snapshot = Mapping[str, Any]
|
|
16
|
+
Context = Mapping[str, Any]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class EvalResult:
|
|
21
|
+
value: Any
|
|
22
|
+
variation_index: Optional[int]
|
|
23
|
+
reason: str # STATIC, DEFAULT, TARGETING_MATCH, SPLIT, DISABLED or ERROR
|
|
24
|
+
rule_id: Optional[str] = None
|
|
25
|
+
flag_version: Optional[int] = None
|
|
26
|
+
error_code: Optional[str] = None # FLAG_NOT_FOUND, TYPE_MISMATCH, GENERAL
|
|
27
|
+
error_message: Optional[str] = None
|
|
28
|
+
|
|
29
|
+
def to_dict(self) -> dict[str, Any]:
|
|
30
|
+
"""The same JSON shape the TypeScript evaluator produces."""
|
|
31
|
+
out: dict[str, Any] = {"variationIndex": self.variation_index, "reason": self.reason}
|
|
32
|
+
if self.variation_index is not None:
|
|
33
|
+
out["value"] = self.value
|
|
34
|
+
for k, v in (("ruleId", self.rule_id), ("flagVersion", self.flag_version), ("errorCode", self.error_code), ("errorMessage", self.error_message)):
|
|
35
|
+
if v is not None:
|
|
36
|
+
out[k] = v
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ---- bucketing ---------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
def bucket_for(flag_key: str, salt: str, value: str, bucketing: Optional[Mapping[str, Any]] = None) -> float:
|
|
43
|
+
"""A bucket in [0, WEIGHT_SCALE). The same inputs always give the same bucket."""
|
|
44
|
+
if bucketing and bucketing.get("algorithm") == "abtasty":
|
|
45
|
+
seed = bucketing.get("seed") or ""
|
|
46
|
+
return (murmur3_latin1(seed + value) % 100) * (WEIGHT_SCALE // 100)
|
|
47
|
+
h = murmur3(f"{flag_key}.{salt}.{value}")
|
|
48
|
+
return float(int((h / 0x1_0000_0000) * WEIGHT_SCALE))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def pick_weighted(weights: list[int], bucket: float) -> Optional[int]:
|
|
52
|
+
total = 0
|
|
53
|
+
for i, w in enumerate(weights):
|
|
54
|
+
total += w
|
|
55
|
+
if bucket < total:
|
|
56
|
+
return i
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---- clauses -----------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
_SEMVER = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?", re.ASCII)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _semver(v: Any) -> Optional[tuple[int, int, int]]:
|
|
66
|
+
if not isinstance(v, str):
|
|
67
|
+
return None
|
|
68
|
+
m = _SEMVER.match(v.strip())
|
|
69
|
+
if not m:
|
|
70
|
+
return None
|
|
71
|
+
return int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _match_one(op: str, actual: Any, expected: Any) -> bool:
|
|
75
|
+
if op == "in":
|
|
76
|
+
return strict_equals(actual, expected)
|
|
77
|
+
if op == "startsWith":
|
|
78
|
+
return isinstance(actual, str) and actual.startswith(js_string(expected))
|
|
79
|
+
if op == "endsWith":
|
|
80
|
+
return isinstance(actual, str) and actual.endswith(js_string(expected))
|
|
81
|
+
if op == "contains":
|
|
82
|
+
return isinstance(actual, str) and js_string(expected) in actual
|
|
83
|
+
if op == "matches":
|
|
84
|
+
rx = js_regex(js_string(expected)) if isinstance(actual, str) else None
|
|
85
|
+
return rx is not None and rx.search(actual) is not None
|
|
86
|
+
if op in ("lt", "lte", "gt", "gte"):
|
|
87
|
+
c = compare(actual, expected)
|
|
88
|
+
if c is None:
|
|
89
|
+
return False
|
|
90
|
+
return c < 0 if op == "lt" else c <= 0 if op == "lte" else c > 0 if op == "gt" else c >= 0
|
|
91
|
+
if op in ("semverEq", "semverLt", "semverGt"):
|
|
92
|
+
a, b = _semver(actual), _semver(expected)
|
|
93
|
+
if a is None or b is None:
|
|
94
|
+
return False
|
|
95
|
+
return a == b if op == "semverEq" else a < b if op == "semverLt" else a > b
|
|
96
|
+
if op in ("before", "after"):
|
|
97
|
+
ta, tb = to_time(actual), to_time(expected)
|
|
98
|
+
if ta is None or tb is None:
|
|
99
|
+
return False
|
|
100
|
+
return ta < tb if op == "before" else ta > tb
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _ClauseEnv:
|
|
105
|
+
__slots__ = ("segments", "context_key", "depth")
|
|
106
|
+
|
|
107
|
+
def __init__(self, segments: Mapping[str, Any], context_key: Optional[str], depth: int) -> None:
|
|
108
|
+
self.segments = segments
|
|
109
|
+
self.context_key = context_key
|
|
110
|
+
self.depth = depth
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _clause_matches(c: Mapping[str, Any], ctx: Context, env: _ClauseEnv) -> bool:
|
|
114
|
+
op = c["op"]
|
|
115
|
+
negate = bool(c.get("negate"))
|
|
116
|
+
if op == "segmentMatch":
|
|
117
|
+
hit = any(_segment_matches(js_string(s), ctx, env) for s in c["values"])
|
|
118
|
+
return not hit if negate else hit
|
|
119
|
+
actual = env.context_key if c["attr"] == "key" else ctx.get(c["attr"])
|
|
120
|
+
if op == "exists":
|
|
121
|
+
present = actual is not None
|
|
122
|
+
return not present if negate else present
|
|
123
|
+
# A missing attribute never matches, negated or not.
|
|
124
|
+
if actual is None:
|
|
125
|
+
return False
|
|
126
|
+
values = actual if isinstance(actual, (list, tuple)) else [actual]
|
|
127
|
+
hit = any(_match_one(op, a, e) for a in values for e in c["values"])
|
|
128
|
+
return not hit if negate else hit
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _segment_matches(key: str, ctx: Context, env: _ClauseEnv) -> bool:
|
|
132
|
+
seg = env.segments.get(key)
|
|
133
|
+
if not seg or env.depth > 5:
|
|
134
|
+
return False
|
|
135
|
+
k = env.context_key
|
|
136
|
+
if k is not None:
|
|
137
|
+
if k in seg.get("excluded", []):
|
|
138
|
+
return False
|
|
139
|
+
if k in seg.get("included", []):
|
|
140
|
+
return True
|
|
141
|
+
inner = _ClauseEnv(env.segments, env.context_key, env.depth + 1)
|
|
142
|
+
return any(all(_clause_matches(c, ctx, inner) for c in r["clauses"]) for r in seg.get("rules", []))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---- evaluation --------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
def context_key_of(ctx: Context) -> Optional[str]:
|
|
148
|
+
k = ctx.get("targetingKey")
|
|
149
|
+
if k is None:
|
|
150
|
+
k = ctx.get("key")
|
|
151
|
+
return None if k is None else js_string(k)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _type_of(v: Any) -> str:
|
|
155
|
+
if isinstance(v, bool):
|
|
156
|
+
return "boolean"
|
|
157
|
+
if isinstance(v, str):
|
|
158
|
+
return "string"
|
|
159
|
+
if is_number(v):
|
|
160
|
+
return "number"
|
|
161
|
+
return "json"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
_Resolved = Optional[tuple[int, str, Optional[str]]] # (variation index, reason, rule id)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _resolve_serve(flag: Mapping[str, Any], serve: Mapping[str, Any], ctx: Context, rule_id: Optional[str]) -> _Resolved:
|
|
168
|
+
if "variation" in serve:
|
|
169
|
+
return serve["variation"], "TARGETING_MATCH" if rule_id else "DEFAULT", rule_id
|
|
170
|
+
rollout = serve["rollout"]
|
|
171
|
+
attr = rollout.get("bucketBy") or "key"
|
|
172
|
+
raw = context_key_of(ctx) if attr == "key" else ctx.get(attr)
|
|
173
|
+
# A missing bucketing value goes to bucket 0, so it is still deterministic.
|
|
174
|
+
bucket = 0.0 if raw is None else bucket_for(flag["key"], flag["salt"], js_string(raw), rollout.get("bucketing"))
|
|
175
|
+
index = pick_weighted(rollout["weights"], bucket)
|
|
176
|
+
if index is None:
|
|
177
|
+
return None
|
|
178
|
+
return index, "SPLIT", rule_id
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _evaluate_flag(snapshot: Snapshot, flag: Mapping[str, Any], ctx: Context, seen: set[str]) -> _Resolved:
|
|
182
|
+
off = flag["offVariation"]
|
|
183
|
+
if not flag["enabled"]:
|
|
184
|
+
return off, "DISABLED", None
|
|
185
|
+
|
|
186
|
+
for p in flag.get("prerequisites", []):
|
|
187
|
+
pre = snapshot["flags"].get(p["key"])
|
|
188
|
+
if not pre or p["key"] in seen:
|
|
189
|
+
return off, "DEFAULT", f"prerequisite:{p['key']}"
|
|
190
|
+
seen.add(p["key"])
|
|
191
|
+
r = _evaluate_flag(snapshot, pre, ctx, seen)
|
|
192
|
+
seen.discard(p["key"])
|
|
193
|
+
if not r or not pre["enabled"] or r[0] != p["variation"]:
|
|
194
|
+
return off, "DEFAULT", f"prerequisite:{p['key']}"
|
|
195
|
+
|
|
196
|
+
key = context_key_of(ctx)
|
|
197
|
+
if key is not None:
|
|
198
|
+
for t in flag.get("targets", []):
|
|
199
|
+
if key in t["values"]:
|
|
200
|
+
return t["variation"], "TARGETING_MATCH", "target"
|
|
201
|
+
|
|
202
|
+
env = _ClauseEnv(snapshot.get("segments", {}), key, 0)
|
|
203
|
+
for rule in flag.get("rules", []):
|
|
204
|
+
if not all(_clause_matches(c, ctx, env) for c in rule["clauses"]):
|
|
205
|
+
continue
|
|
206
|
+
r = _resolve_serve(flag, rule["serve"], ctx, rule["id"])
|
|
207
|
+
if r:
|
|
208
|
+
return r # None = matched but not allocated: continue to the next rule
|
|
209
|
+
|
|
210
|
+
return _resolve_serve(flag, flag["fallthrough"], ctx, None) or (off, "DEFAULT", None)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def evaluate(snapshot: Snapshot, flag_key: str, ctx: Optional[Context] = None, expected_type: Optional[str] = None) -> EvalResult:
|
|
214
|
+
"""Evaluates one flag. Never raises: problems come back as reason ERROR with an error code.
|
|
215
|
+
|
|
216
|
+
`expected_type` is "boolean", "string", "number" or "json"; another type gives TYPE_MISMATCH.
|
|
217
|
+
"""
|
|
218
|
+
ctx = ctx or {}
|
|
219
|
+
try:
|
|
220
|
+
flag = snapshot["flags"].get(flag_key)
|
|
221
|
+
if not flag:
|
|
222
|
+
return EvalResult(None, None, "ERROR", error_code="FLAG_NOT_FOUND", error_message=f"Flag {flag_key} not found")
|
|
223
|
+
r = _evaluate_flag(snapshot, flag, ctx, {flag_key})
|
|
224
|
+
index = r[0] if r else flag["offVariation"]
|
|
225
|
+
variations = flag["variations"]
|
|
226
|
+
version = flag.get("version")
|
|
227
|
+
if index < 0 or index >= len(variations):
|
|
228
|
+
return EvalResult(None, None, "ERROR", flag_version=version, error_code="GENERAL", error_message="Variation index out of range")
|
|
229
|
+
value = variations[index]
|
|
230
|
+
if expected_type and expected_type != "json" and _type_of(value) != expected_type:
|
|
231
|
+
return EvalResult(None, None, "ERROR", flag_version=version, error_code="TYPE_MISMATCH",
|
|
232
|
+
error_message=f"Flag {flag_key} is {flag['type']}, not {expected_type}")
|
|
233
|
+
return EvalResult(value, index, r[1] if r else "DEFAULT", rule_id=r[2] if r else None, flag_version=version)
|
|
234
|
+
except Exception as e: # noqa: BLE001 - evaluation must never raise into the caller
|
|
235
|
+
return EvalResult(None, None, "ERROR", error_code="GENERAL", error_message=str(e))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def evaluate_all(snapshot: Snapshot, ctx: Optional[Context] = None) -> dict[str, EvalResult]:
|
|
239
|
+
return {k: evaluate(snapshot, k, ctx) for k in snapshot["flags"]}
|
railflag/provider.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""OpenFeature provider. Evaluates in process: no network call per flag check."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from datetime import date, datetime, timezone
|
|
7
|
+
from typing import Any, Mapping, Optional, Sequence, Union
|
|
8
|
+
|
|
9
|
+
from openfeature.evaluation_context import EvaluationContext
|
|
10
|
+
from openfeature.event import ProviderEventDetails
|
|
11
|
+
from openfeature.exception import ErrorCode
|
|
12
|
+
from openfeature.flag_evaluation import FlagResolutionDetails, Reason
|
|
13
|
+
from openfeature.provider import AbstractProvider
|
|
14
|
+
from openfeature.provider.metadata import Metadata
|
|
15
|
+
|
|
16
|
+
from .evaluate import evaluate
|
|
17
|
+
from .source import ConfigSource
|
|
18
|
+
|
|
19
|
+
_ERRORS = {
|
|
20
|
+
"FLAG_NOT_FOUND": ErrorCode.FLAG_NOT_FOUND,
|
|
21
|
+
"TYPE_MISMATCH": ErrorCode.TYPE_MISMATCH,
|
|
22
|
+
"PARSE_ERROR": ErrorCode.PARSE_ERROR,
|
|
23
|
+
"GENERAL": ErrorCode.GENERAL,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
JsonValue = Union[Sequence[Any], Mapping[str, Any]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _plain(v: Any) -> Any:
|
|
30
|
+
"""Context values as the evaluator expects them: datetimes become epoch milliseconds."""
|
|
31
|
+
if isinstance(v, datetime):
|
|
32
|
+
if v.tzinfo is None:
|
|
33
|
+
v = v.replace(tzinfo=timezone.utc)
|
|
34
|
+
return v.timestamp() * 1000
|
|
35
|
+
if isinstance(v, date):
|
|
36
|
+
return datetime(v.year, v.month, v.day, tzinfo=timezone.utc).timestamp() * 1000
|
|
37
|
+
if isinstance(v, (list, tuple)):
|
|
38
|
+
return [_plain(x) for x in v]
|
|
39
|
+
if isinstance(v, Mapping):
|
|
40
|
+
return {k: _plain(x) for k, x in v.items()}
|
|
41
|
+
return v
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def to_context(ctx: Optional[EvaluationContext]) -> dict[str, Any]:
|
|
45
|
+
if ctx is None:
|
|
46
|
+
return {}
|
|
47
|
+
out = {k: _plain(v) for k, v in (ctx.attributes or {}).items()}
|
|
48
|
+
if ctx.targeting_key is not None:
|
|
49
|
+
out["targetingKey"] = ctx.targeting_key
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RailflagProvider(AbstractProvider):
|
|
54
|
+
"""
|
|
55
|
+
```python
|
|
56
|
+
from openfeature import api
|
|
57
|
+
from railflag import RailflagProvider
|
|
58
|
+
|
|
59
|
+
api.set_provider(RailflagProvider(sdk_key=os.environ["RAILFLAG_SERVER_KEY"], base_url="https://relay.example.com"))
|
|
60
|
+
client = api.get_client()
|
|
61
|
+
client.get_boolean_value("new-checkout", False, EvaluationContext("user-42", {"plan": "pro"}))
|
|
62
|
+
```
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
sdk_key: str,
|
|
68
|
+
base_url: str,
|
|
69
|
+
stream: bool = True,
|
|
70
|
+
poll_interval: float = 30.0,
|
|
71
|
+
timeout: float = 10.0,
|
|
72
|
+
logger: Optional[logging.Logger] = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
super().__init__()
|
|
75
|
+
self.source = ConfigSource(sdk_key, base_url=base_url, stream=stream, poll_interval=poll_interval, timeout=timeout, logger=logger)
|
|
76
|
+
self.source.on_change(self._changed)
|
|
77
|
+
|
|
78
|
+
def get_metadata(self) -> Metadata:
|
|
79
|
+
return Metadata(name="railflag")
|
|
80
|
+
|
|
81
|
+
def initialize(self, evaluation_context: EvaluationContext) -> None:
|
|
82
|
+
self.source.start()
|
|
83
|
+
|
|
84
|
+
def shutdown(self) -> None:
|
|
85
|
+
self.source.stop()
|
|
86
|
+
|
|
87
|
+
def _changed(self, snap: dict[str, Any], prev: Optional[dict[str, Any]]) -> None:
|
|
88
|
+
if prev is None:
|
|
89
|
+
return # the first load is the READY event, which OpenFeature sends itself
|
|
90
|
+
before, after = prev.get("flags", {}), snap.get("flags", {})
|
|
91
|
+
changed = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))
|
|
92
|
+
self.emit_provider_configuration_changed(ProviderEventDetails(flags_changed=changed, message=f"config version {snap['version']}"))
|
|
93
|
+
|
|
94
|
+
def _resolve(self, flag_key: str, default: Any, ctx: Optional[EvaluationContext], expected: str) -> FlagResolutionDetails[Any]:
|
|
95
|
+
snap = self.source.snapshot
|
|
96
|
+
if snap is None:
|
|
97
|
+
return FlagResolutionDetails(value=default, reason=Reason.ERROR, error_code=ErrorCode.PROVIDER_NOT_READY)
|
|
98
|
+
r = evaluate(snap, flag_key, to_context(ctx), expected_type=expected)
|
|
99
|
+
if r.reason == "ERROR":
|
|
100
|
+
return FlagResolutionDetails(value=default, reason=Reason.ERROR, error_code=_ERRORS.get(r.error_code or "", ErrorCode.GENERAL), error_message=r.error_message)
|
|
101
|
+
meta: dict[str, Union[str, int]] = {"flagVersion": r.flag_version or 0, "configVersion": snap["version"]}
|
|
102
|
+
if r.rule_id:
|
|
103
|
+
meta["ruleId"] = r.rule_id
|
|
104
|
+
return FlagResolutionDetails(value=r.value, reason=r.reason, variant=str(r.variation_index), flag_metadata=meta)
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _mismatch(default: Any, message: str) -> FlagResolutionDetails[Any]:
|
|
108
|
+
return FlagResolutionDetails(value=default, reason=Reason.ERROR, error_code=ErrorCode.TYPE_MISMATCH, error_message=message)
|
|
109
|
+
|
|
110
|
+
def resolve_boolean_details(self, flag_key: str, default_value: bool, evaluation_context: Optional[EvaluationContext] = None) -> FlagResolutionDetails[bool]:
|
|
111
|
+
return self._resolve(flag_key, default_value, evaluation_context, "boolean")
|
|
112
|
+
|
|
113
|
+
def resolve_string_details(self, flag_key: str, default_value: str, evaluation_context: Optional[EvaluationContext] = None) -> FlagResolutionDetails[str]:
|
|
114
|
+
return self._resolve(flag_key, default_value, evaluation_context, "string")
|
|
115
|
+
|
|
116
|
+
def resolve_integer_details(self, flag_key: str, default_value: int, evaluation_context: Optional[EvaluationContext] = None) -> FlagResolutionDetails[int]:
|
|
117
|
+
d = self._resolve(flag_key, default_value, evaluation_context, "number")
|
|
118
|
+
if d.error_code:
|
|
119
|
+
return d
|
|
120
|
+
if isinstance(d.value, float):
|
|
121
|
+
if not d.value.is_integer():
|
|
122
|
+
return self._mismatch(default_value, f"Flag {flag_key} is {d.value}, not an integer")
|
|
123
|
+
d.value = int(d.value)
|
|
124
|
+
return d
|
|
125
|
+
|
|
126
|
+
def resolve_float_details(self, flag_key: str, default_value: float, evaluation_context: Optional[EvaluationContext] = None) -> FlagResolutionDetails[float]:
|
|
127
|
+
d = self._resolve(flag_key, default_value, evaluation_context, "number")
|
|
128
|
+
if not d.error_code:
|
|
129
|
+
d.value = float(d.value)
|
|
130
|
+
return d
|
|
131
|
+
|
|
132
|
+
def resolve_object_details(self, flag_key: str, default_value: JsonValue, evaluation_context: Optional[EvaluationContext] = None) -> FlagResolutionDetails[JsonValue]:
|
|
133
|
+
d = self._resolve(flag_key, default_value, evaluation_context, "json")
|
|
134
|
+
if not d.error_code and not isinstance(d.value, (dict, list)):
|
|
135
|
+
return self._mismatch(default_value, f"Flag {flag_key} value is not an object or list")
|
|
136
|
+
return d
|
railflag/py.typed
ADDED
|
File without changes
|
railflag/source.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Keeps the latest environment snapshot in memory, like `packages/sdk-node/src/source.ts`.
|
|
2
|
+
|
|
3
|
+
Flag checks never wait on the network. Updates arrive over Server-Sent Events; polling every
|
|
4
|
+
`poll_interval` seconds is the safety net, and if Railflag can't be reached the last config keeps
|
|
5
|
+
serving. Uses only the standard library, in two daemon threads.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import socket
|
|
13
|
+
import threading
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from typing import Any, Callable, Optional
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
|
|
20
|
+
_log = logging.getLogger("railflag")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _socket_of(resp: Any) -> Optional[socket.socket]:
|
|
24
|
+
try:
|
|
25
|
+
return resp.fp.raw._sock # http.client.HTTPResponse -> SocketIO -> socket
|
|
26
|
+
except AttributeError:
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ConfigSource:
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
sdk_key: str,
|
|
34
|
+
base_url: str,
|
|
35
|
+
stream: bool = True,
|
|
36
|
+
poll_interval: float = 30.0,
|
|
37
|
+
timeout: float = 10.0,
|
|
38
|
+
stream_read_timeout: float = 60.0,
|
|
39
|
+
logger: Optional[logging.Logger] = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
if not isinstance(base_url, str) or not base_url.startswith(("http://", "https://")):
|
|
42
|
+
raise ValueError(f"base_url must be your Railflag relay URL, like https://relay.example.com (got {base_url!r})")
|
|
43
|
+
self.sdk_key = sdk_key
|
|
44
|
+
self.base_url = base_url.rstrip("/")
|
|
45
|
+
self.stream = stream
|
|
46
|
+
self.poll_interval = poll_interval
|
|
47
|
+
self.timeout = timeout
|
|
48
|
+
# The relay sends a heartbeat every 25 s, so a silent stream for this long is a dead one.
|
|
49
|
+
self.stream_read_timeout = stream_read_timeout
|
|
50
|
+
self.log = logger or _log
|
|
51
|
+
self.snapshot: Optional[dict[str, Any]] = None
|
|
52
|
+
self.streaming = False
|
|
53
|
+
self._etag: Optional[str] = None
|
|
54
|
+
self._listeners: list[Callable[[dict[str, Any], Optional[dict[str, Any]]], None]] = []
|
|
55
|
+
self._fetch_lock = threading.Lock()
|
|
56
|
+
self._stop = threading.Event()
|
|
57
|
+
self._threads: list[threading.Thread] = []
|
|
58
|
+
self._stream_resp: Any = None
|
|
59
|
+
|
|
60
|
+
def on_change(self, listener: Callable[[dict[str, Any], Optional[dict[str, Any]]], None]) -> None:
|
|
61
|
+
"""`listener(new_snapshot, previous_snapshot)` runs on a background thread after each update."""
|
|
62
|
+
self._listeners.append(listener)
|
|
63
|
+
|
|
64
|
+
def start(self) -> None:
|
|
65
|
+
"""Loads the config once (raises if that fails), then keeps it fresh in the background."""
|
|
66
|
+
self.fetch_config()
|
|
67
|
+
self._spawn(self._poll_loop, "railflag-poll")
|
|
68
|
+
if self.stream:
|
|
69
|
+
self._spawn(self._stream_loop, "railflag-stream")
|
|
70
|
+
|
|
71
|
+
def stop(self) -> None:
|
|
72
|
+
self._stop.set()
|
|
73
|
+
# Closing the response would wait for the reader thread, which is blocked in readline().
|
|
74
|
+
# Shutting the socket down wakes it immediately.
|
|
75
|
+
sock = _socket_of(self._stream_resp)
|
|
76
|
+
if sock is not None:
|
|
77
|
+
try:
|
|
78
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
79
|
+
except OSError:
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
def _spawn(self, target: Callable[[], None], name: str) -> None:
|
|
83
|
+
t = threading.Thread(target=target, name=name, daemon=True)
|
|
84
|
+
t.start()
|
|
85
|
+
self._threads.append(t)
|
|
86
|
+
|
|
87
|
+
def _request(self, path: str, extra: Optional[dict[str, str]] = None) -> urllib.request.Request:
|
|
88
|
+
headers = {"Authorization": self.sdk_key, "User-Agent": f"railflag-python/{__version__}"}
|
|
89
|
+
headers.update(extra or {})
|
|
90
|
+
return urllib.request.Request(f"{self.base_url}{path}", headers=headers)
|
|
91
|
+
|
|
92
|
+
def fetch_config(self) -> bool:
|
|
93
|
+
"""Fetches the snapshot if it changed. Returns True when a newer one was applied."""
|
|
94
|
+
with self._fetch_lock:
|
|
95
|
+
extra = {"If-None-Match": self._etag} if self._etag else {}
|
|
96
|
+
try:
|
|
97
|
+
with urllib.request.urlopen(self._request("/sdk/v1/config", extra), timeout=self.timeout) as resp:
|
|
98
|
+
body = resp.read()
|
|
99
|
+
etag = resp.headers.get("etag")
|
|
100
|
+
except urllib.error.HTTPError as e:
|
|
101
|
+
if e.code == 304:
|
|
102
|
+
return False
|
|
103
|
+
raise RuntimeError(f"Railflag config request failed: {e.code} {e.read()[:200]!r}") from e
|
|
104
|
+
snap = json.loads(body)
|
|
105
|
+
prev = self.snapshot
|
|
106
|
+
if prev is not None and snap["version"] < prev["version"]:
|
|
107
|
+
return False
|
|
108
|
+
self.snapshot = snap
|
|
109
|
+
self._etag = etag
|
|
110
|
+
for listener in list(self._listeners):
|
|
111
|
+
try:
|
|
112
|
+
listener(snap, prev)
|
|
113
|
+
except Exception: # noqa: BLE001
|
|
114
|
+
self.log.exception("railflag change listener failed")
|
|
115
|
+
return True
|
|
116
|
+
|
|
117
|
+
def _poll_loop(self) -> None:
|
|
118
|
+
while not self._stop.wait(self.poll_interval):
|
|
119
|
+
try:
|
|
120
|
+
self.fetch_config()
|
|
121
|
+
except Exception as e: # noqa: BLE001
|
|
122
|
+
self.log.warning("railflag poll failed: %s", e)
|
|
123
|
+
|
|
124
|
+
def _stream_loop(self) -> None:
|
|
125
|
+
backoff = 0.5
|
|
126
|
+
while not self._stop.is_set():
|
|
127
|
+
try:
|
|
128
|
+
req = self._request("/sdk/v1/stream", {"Accept": "text/event-stream"})
|
|
129
|
+
with urllib.request.urlopen(req, timeout=self.stream_read_timeout) as resp:
|
|
130
|
+
self._stream_resp = resp
|
|
131
|
+
self.streaming = True
|
|
132
|
+
backoff = 0.5
|
|
133
|
+
self._read_events(resp)
|
|
134
|
+
except Exception as e: # noqa: BLE001
|
|
135
|
+
if not self._stop.is_set():
|
|
136
|
+
self.log.warning("railflag stream dropped, reconnecting: %s", e)
|
|
137
|
+
finally:
|
|
138
|
+
self.streaming = False
|
|
139
|
+
self._stream_resp = None
|
|
140
|
+
if self._stop.wait(backoff):
|
|
141
|
+
return
|
|
142
|
+
backoff = min(backoff * 2, 30.0)
|
|
143
|
+
|
|
144
|
+
def _read_events(self, resp: Any) -> None:
|
|
145
|
+
event: Optional[str] = None
|
|
146
|
+
data: Optional[str] = None
|
|
147
|
+
while not self._stop.is_set():
|
|
148
|
+
raw = resp.readline()
|
|
149
|
+
if not raw:
|
|
150
|
+
return # server closed the stream
|
|
151
|
+
line = raw.decode("utf-8").rstrip("\r\n")
|
|
152
|
+
if line == "":
|
|
153
|
+
if event == "reconnect":
|
|
154
|
+
return
|
|
155
|
+
if event == "config":
|
|
156
|
+
self._on_config_event(data or "{}")
|
|
157
|
+
event, data = None, None
|
|
158
|
+
elif not line.startswith(":"):
|
|
159
|
+
field, _, value = line.partition(":")
|
|
160
|
+
if value.startswith(" "):
|
|
161
|
+
value = value[1:]
|
|
162
|
+
if field == "event":
|
|
163
|
+
event = value
|
|
164
|
+
elif field == "data":
|
|
165
|
+
data = value if data is None else f"{data}\n{value}"
|
|
166
|
+
|
|
167
|
+
def _on_config_event(self, data: str) -> None:
|
|
168
|
+
try:
|
|
169
|
+
version = int(json.loads(data).get("version", 0))
|
|
170
|
+
except (ValueError, TypeError, AttributeError):
|
|
171
|
+
return
|
|
172
|
+
if self.snapshot is None or version > self.snapshot["version"]:
|
|
173
|
+
try:
|
|
174
|
+
self.fetch_config()
|
|
175
|
+
except Exception as e: # noqa: BLE001
|
|
176
|
+
self.log.warning("railflag fetch after stream event failed: %s", e)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: railflag-openfeature
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Railflag OpenFeature provider for Python: local evaluation, streaming updates
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Keywords: feature-flags,openfeature,railflag
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Typing :: Typed
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: openfeature-sdk>=0.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# railflag-openfeature
|
|
14
|
+
|
|
15
|
+
Railflag's OpenFeature provider for Python 3.10+. It downloads your environment's flag config once,
|
|
16
|
+
evaluates every flag check in process (about 15 µs, no network call), and picks up changes within a
|
|
17
|
+
second over Server-Sent Events. If the stream drops it polls every 30 s, and if Railflag can't be
|
|
18
|
+
reached it keeps serving the last config it had. The only dependency is `openfeature-sdk`.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import os
|
|
22
|
+
from openfeature import api
|
|
23
|
+
from openfeature.evaluation_context import EvaluationContext
|
|
24
|
+
from railflag import RailflagProvider
|
|
25
|
+
|
|
26
|
+
api.set_provider_and_wait(RailflagProvider(
|
|
27
|
+
sdk_key=os.environ["RAILFLAG_SERVER_KEY"], # a server key: Environments → keys
|
|
28
|
+
base_url="https://relay-production-aa5b.up.railway.app", # required: your Railflag relay
|
|
29
|
+
))
|
|
30
|
+
client = api.get_client()
|
|
31
|
+
|
|
32
|
+
if client.get_boolean_value("new-checkout", False, EvaluationContext("user-42", {"plan": "pro", "country": "GR"})):
|
|
33
|
+
...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- `get_boolean_value`, `get_string_value`, `get_integer_value`, `get_float_value` and `get_object_value` work as in any OpenFeature provider. A wrong type or unknown flag returns your default with an error code.
|
|
37
|
+
- `datetime` and `date` attributes are compared as instants, so `before`/`after` rules work with them.
|
|
38
|
+
- `api.add_handler(ProviderEvent.PROVIDER_CONFIGURATION_CHANGED, fn)` tells you when flags change; `details.flags_changed` lists them.
|
|
39
|
+
- Server keys can read every rule. Keep them on the server; browsers use the JavaScript SDK with a client key.
|
|
40
|
+
|
|
41
|
+
## Same answers as every other SDK
|
|
42
|
+
|
|
43
|
+
`railflag/evaluate.py` is a port of `packages/eval`. The tests run it against
|
|
44
|
+
`packages/eval/vectors/eval-vectors.json` (hashes, buckets and thousands of evaluations generated by
|
|
45
|
+
the TypeScript evaluator), so a user lands in the same variation whichever SDK evaluates the flag.
|
|
46
|
+
Context values follow JavaScript rules: `1` and `True` are different, numbers print as JavaScript
|
|
47
|
+
prints them, and strings sort by UTF-16 code units.
|
|
48
|
+
|
|
49
|
+
Known differences: regexes in `matches` rules run on Python's `re` (with ASCII `\d`/`\w`), and a
|
|
50
|
+
date-time without a time zone is read as UTC.
|
|
51
|
+
|
|
52
|
+
## Development
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
uv sync
|
|
56
|
+
uv run pytest
|
|
57
|
+
SY_EMAIL=... SY_PASSWORD=... uv run python examples/live_check.py # against production; rotates the Development server key
|
|
58
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
railflag/__init__.py,sha256=uBIn0oWVHadMtdJ5YLbm739KNXJ7iF8w4_ITFEvL32M,389
|
|
2
|
+
railflag/_js.py,sha256=rgY6YFMdHGim9BZ9xZ4biHa4Evstr8cNW7gRcveH6g8,5144
|
|
3
|
+
railflag/_murmur3.py,sha256=NrzXPLwc26jcZ5B5uBPi7PfdVfAsrGvGf3zrlu08Zgc,1561
|
|
4
|
+
railflag/evaluate.py,sha256=Jw0cCxxDyB5kokXZe1IF2L0ZsJVrfxJSkaGLtl91UyM,9729
|
|
5
|
+
railflag/provider.py,sha256=nUZC4rCstztVM2GaSR1-eoDkNpMEaEFsmiELbMrUJxI,6200
|
|
6
|
+
railflag/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
railflag/source.py,sha256=vEoSRP5bKzAzuQ3FBdKjQHPgMX5sLUYSQrJCf54e1ik,7147
|
|
8
|
+
railflag_openfeature-0.1.0.dist-info/METADATA,sha256=aXtsDT5tujUKrTqBwaPMi1w0HF92ESGZAxJ-ZzqsCjg,2703
|
|
9
|
+
railflag_openfeature-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
railflag_openfeature-0.1.0.dist-info/RECORD,,
|