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/__init__.py +7 -0
- flagdock/_usage.py +81 -0
- flagdock/engine.py +673 -0
- flagdock/provider.py +568 -0
- flagdock/py.typed +0 -0
- flagdock-0.3.1.dist-info/METADATA +94 -0
- flagdock-0.3.1.dist-info/RECORD +9 -0
- flagdock-0.3.1.dist-info/WHEEL +4 -0
- flagdock-0.3.1.dist-info/licenses/LICENSE +21 -0
flagdock/provider.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
"""OpenFeature provider for Flagdock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
14
|
+
from typing import Any, Optional, Union
|
|
15
|
+
|
|
16
|
+
from openfeature.evaluation_context import EvaluationContext
|
|
17
|
+
from openfeature.event import ProviderEventDetails
|
|
18
|
+
from openfeature.exception import ErrorCode
|
|
19
|
+
from openfeature.flag_evaluation import FlagResolutionDetails, Reason
|
|
20
|
+
from openfeature.provider import AbstractProvider, Metadata
|
|
21
|
+
|
|
22
|
+
from . import engine
|
|
23
|
+
from ._usage import ActivityLog, UsageCounter
|
|
24
|
+
|
|
25
|
+
SDK_NAME = "python"
|
|
26
|
+
SDK_VERSION = "0.3.1"
|
|
27
|
+
DEFAULT_URL = "https://edge.flagdock.com"
|
|
28
|
+
DEFAULT_FALLBACK_URL = "https://app.flagdock.com"
|
|
29
|
+
|
|
30
|
+
_ERROR_CODES = {
|
|
31
|
+
"FLAG_NOT_FOUND": ErrorCode.FLAG_NOT_FOUND,
|
|
32
|
+
"TYPE_MISMATCH": ErrorCode.TYPE_MISMATCH,
|
|
33
|
+
"GENERAL": ErrorCode.GENERAL,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
Context = Union[EvaluationContext, Mapping[str, Any], None]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _NoRedirects(urllib.request.HTTPRedirectHandler):
|
|
40
|
+
"""A redirect could carry the SDK key to another host, so none are followed."""
|
|
41
|
+
|
|
42
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_opener = urllib.request.build_opener(_NoRedirects())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _Response:
|
|
50
|
+
def __init__(self, status: int, headers: Mapping[str, str], body: bytes) -> None:
|
|
51
|
+
self.status = status
|
|
52
|
+
self.headers = headers
|
|
53
|
+
self.body = body
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _as_dict(context: Context) -> dict[str, Any]:
|
|
57
|
+
"""An OpenFeature context as the plain mapping the engine reads, with the person's ID as targetingKey."""
|
|
58
|
+
if context is None:
|
|
59
|
+
return {}
|
|
60
|
+
if isinstance(context, EvaluationContext):
|
|
61
|
+
out = dict(context.attributes)
|
|
62
|
+
if context.targeting_key is not None:
|
|
63
|
+
out["targetingKey"] = context.targeting_key
|
|
64
|
+
return out
|
|
65
|
+
return dict(context)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _read_ruleset(path: str) -> Optional[dict[str, Any]]:
|
|
69
|
+
try:
|
|
70
|
+
with open(path, encoding="utf-8") as f:
|
|
71
|
+
parsed = json.load(f)
|
|
72
|
+
except (OSError, ValueError):
|
|
73
|
+
return None
|
|
74
|
+
if not _looks_like_ruleset(parsed):
|
|
75
|
+
return None
|
|
76
|
+
return {"audiences": {}, **parsed}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _looks_like_ruleset(value: Any) -> bool:
|
|
80
|
+
return (
|
|
81
|
+
isinstance(value, dict)
|
|
82
|
+
and isinstance(value.get("version"), int)
|
|
83
|
+
and not isinstance(value.get("version"), bool)
|
|
84
|
+
and isinstance(value.get("flags"), dict)
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class FlagdockProvider(AbstractProvider):
|
|
89
|
+
"""OpenFeature provider for Flagdock.
|
|
90
|
+
|
|
91
|
+
It downloads the environment's rules once, keeps them in memory and answers every flag check from
|
|
92
|
+
there with no network call. A live stream says when to download again; if the stream drops it polls
|
|
93
|
+
until it is back. If the server becomes unreachable it keeps serving the last rules it had, from
|
|
94
|
+
memory or from ``snapshot_file`` after a restart.
|
|
95
|
+
|
|
96
|
+
Thread safe: flag checks may run on any thread while a background thread keeps the rules current.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
key: str,
|
|
102
|
+
*,
|
|
103
|
+
url: Optional[str] = None,
|
|
104
|
+
fallback_urls: Optional[Sequence[str]] = None,
|
|
105
|
+
snapshot_file: Optional[str] = None,
|
|
106
|
+
bootstrap_file: Optional[str] = None,
|
|
107
|
+
app_name: str = "python-app",
|
|
108
|
+
poll_interval: float = 15.0,
|
|
109
|
+
stale_after: float = 300.0,
|
|
110
|
+
start_timeout: float = 10.0,
|
|
111
|
+
usage_interval: float = 60.0,
|
|
112
|
+
stream: bool = True,
|
|
113
|
+
) -> None:
|
|
114
|
+
"""
|
|
115
|
+
:param key: a server SDK key (``hbf_srv_…``) for one environment.
|
|
116
|
+
:param url: where to get the rules. Defaults to the Flagdock edge, ``https://edge.flagdock.com``.
|
|
117
|
+
:param fallback_urls: more places to try, in order, when ``url`` cannot be reached or answers with a
|
|
118
|
+
server error. Defaults to the Flagdock control plane when ``url`` is left out.
|
|
119
|
+
:param snapshot_file: where to keep the last rules downloaded, so a restart during an outage still has
|
|
120
|
+
the newest rules this machine saw. It holds targeting rules: keep it out of public folders.
|
|
121
|
+
:param bootstrap_file: a ruleset JSON file to start from when nothing else is available.
|
|
122
|
+
:param app_name: name shown under "Connected apps" in the console.
|
|
123
|
+
:param poll_interval: seconds between checks for changes while the live stream is down.
|
|
124
|
+
:param stale_after: seconds without a successful sync before the provider reports itself stale.
|
|
125
|
+
:param start_timeout: seconds ``initialize`` waits for the first download.
|
|
126
|
+
:param usage_interval: seconds between usage reports; 0 turns reporting off.
|
|
127
|
+
:param stream: follow changes live. When False the provider only polls.
|
|
128
|
+
"""
|
|
129
|
+
super().__init__()
|
|
130
|
+
if not key:
|
|
131
|
+
raise ValueError("FlagdockProvider needs a server SDK key")
|
|
132
|
+
fallbacks = list(fallback_urls) if fallback_urls is not None else ([] if url else [DEFAULT_FALLBACK_URL])
|
|
133
|
+
self._bases = [u.rstrip("/") for u in [url or DEFAULT_URL, *fallbacks]]
|
|
134
|
+
for base in self._bases:
|
|
135
|
+
if urllib.parse.urlsplit(base).scheme not in ("http", "https"):
|
|
136
|
+
raise ValueError(f"Flagdock URLs must start with https:// (got {base!r})")
|
|
137
|
+
self._key = key
|
|
138
|
+
self._snapshot_file = snapshot_file
|
|
139
|
+
self._bootstrap_file = bootstrap_file
|
|
140
|
+
self._app_name = app_name
|
|
141
|
+
self._poll_interval = poll_interval
|
|
142
|
+
self._stale_after = stale_after
|
|
143
|
+
self._start_timeout = start_timeout
|
|
144
|
+
self._usage_interval = usage_interval
|
|
145
|
+
self._stream = stream
|
|
146
|
+
|
|
147
|
+
self._ruleset: Optional[dict[str, Any]] = None
|
|
148
|
+
self._rules_from: Optional[str] = None
|
|
149
|
+
self._etag: Optional[str] = None
|
|
150
|
+
self._announced: Optional[int] = None
|
|
151
|
+
self._current = 0
|
|
152
|
+
self._last_sync = 0.0
|
|
153
|
+
self._stale = False
|
|
154
|
+
self._stream_up = False
|
|
155
|
+
self._stop = threading.Event()
|
|
156
|
+
self._wake = threading.Event()
|
|
157
|
+
self._sync_lock = threading.Lock()
|
|
158
|
+
self._threads: list[threading.Thread] = []
|
|
159
|
+
self._stream_response: Any = None
|
|
160
|
+
self._usage = UsageCounter()
|
|
161
|
+
self._activity = ActivityLog()
|
|
162
|
+
self._instance_id = str(uuid.uuid4())
|
|
163
|
+
|
|
164
|
+
# --- What it is and where its rules came from ------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
def get_metadata(self) -> Metadata:
|
|
167
|
+
return Metadata(name="flagdock")
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def rules_source(self) -> Optional[str]:
|
|
171
|
+
"""Where the rules in memory came from: ``server``, ``snapshot`` or ``bootstrap``."""
|
|
172
|
+
return self._rules_from
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def ruleset_version(self) -> Optional[int]:
|
|
176
|
+
"""Version of the rules in memory, or None before the first load."""
|
|
177
|
+
return self._ruleset["version"] if self._ruleset else None
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def last_synced_at(self) -> Optional[float]:
|
|
181
|
+
"""When the provider last heard from the server (seconds since 1970), or None if it never has."""
|
|
182
|
+
return self._last_sync or None
|
|
183
|
+
|
|
184
|
+
# --- Starting and stopping -------------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
def initialize(self, evaluation_context: Optional[EvaluationContext] = None) -> None:
|
|
187
|
+
first_error: Optional[BaseException] = None
|
|
188
|
+
try:
|
|
189
|
+
self._download(self._start_timeout)
|
|
190
|
+
except Exception as err: # noqa: BLE001 - any failure falls back to the files below
|
|
191
|
+
first_error = err
|
|
192
|
+
# Newest first: what this machine last downloaded, then what shipped with the app.
|
|
193
|
+
for source, path in (("snapshot", self._snapshot_file), ("bootstrap", self._bootstrap_file)):
|
|
194
|
+
if not path or self._ruleset is not None:
|
|
195
|
+
continue
|
|
196
|
+
loaded = _read_ruleset(path)
|
|
197
|
+
if loaded is not None:
|
|
198
|
+
self._ruleset = loaded
|
|
199
|
+
self._rules_from = source
|
|
200
|
+
elif source == "bootstrap":
|
|
201
|
+
raise RuntimeError(f"Flagdock could not read its bootstrap file {path}") from err
|
|
202
|
+
# Keep trying in the background either way; a later success fixes a bad start.
|
|
203
|
+
self._start_thread(self._run_ticker, "flagdock-sync")
|
|
204
|
+
if self._stream:
|
|
205
|
+
self._start_thread(self._run_stream, "flagdock-stream")
|
|
206
|
+
if self._ruleset is None:
|
|
207
|
+
raise RuntimeError(f"Flagdock could not load its rules: {first_error}") from first_error
|
|
208
|
+
|
|
209
|
+
def shutdown(self) -> None:
|
|
210
|
+
self._stop.set()
|
|
211
|
+
self._wake.set()
|
|
212
|
+
response = self._stream_response
|
|
213
|
+
if response is not None:
|
|
214
|
+
try:
|
|
215
|
+
response.close()
|
|
216
|
+
except Exception: # noqa: BLE001, S110 - closing a stream that is already gone is fine
|
|
217
|
+
pass
|
|
218
|
+
for t in self._threads:
|
|
219
|
+
t.join(timeout=2)
|
|
220
|
+
if self._usage_interval > 0:
|
|
221
|
+
self.flush_usage()
|
|
222
|
+
|
|
223
|
+
def _start_thread(self, target: Callable[[], None], name: str) -> None:
|
|
224
|
+
t = threading.Thread(target=target, name=name, daemon=True)
|
|
225
|
+
self._threads.append(t)
|
|
226
|
+
t.start()
|
|
227
|
+
|
|
228
|
+
def rotate_key(self, key: str) -> None:
|
|
229
|
+
"""Switches to another SDK key without a restart: create the new key, call this, then revoke the old one."""
|
|
230
|
+
if not key:
|
|
231
|
+
raise ValueError("rotate_key needs the new SDK key")
|
|
232
|
+
self._key = key
|
|
233
|
+
self._etag = None
|
|
234
|
+
response = self._stream_response
|
|
235
|
+
if response is not None:
|
|
236
|
+
try:
|
|
237
|
+
response.close() # The stream reconnects with the new key.
|
|
238
|
+
except Exception: # noqa: BLE001, S110 - closing a stream that is already gone is fine
|
|
239
|
+
pass
|
|
240
|
+
self._sync()
|
|
241
|
+
|
|
242
|
+
# --- Talking to the server -------------------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
def _headers(self, extra: Optional[Mapping[str, str]] = None) -> dict[str, str]:
|
|
245
|
+
return {"Authorization": f"Bearer {self._key}", "User-Agent": f"flagdock-python/{SDK_VERSION}", **(extra or {})}
|
|
246
|
+
|
|
247
|
+
def _call(self, base: str, path: str, method: str, headers: Mapping[str, str], body: Optional[bytes], timeout: float) -> _Response:
|
|
248
|
+
request = urllib.request.Request(f"{base}{path}", data=body, method=method, headers=dict(headers)) # noqa: S310 - the scheme is checked in __init__
|
|
249
|
+
try:
|
|
250
|
+
with _opener.open(request, timeout=timeout) as res: # noqa: S310 - the scheme is checked in __init__
|
|
251
|
+
return _Response(res.status, dict(res.headers.items()), res.read())
|
|
252
|
+
except urllib.error.HTTPError as err:
|
|
253
|
+
with err:
|
|
254
|
+
return _Response(err.code, dict(err.headers.items()) if err.headers else {}, err.read())
|
|
255
|
+
|
|
256
|
+
def _request(
|
|
257
|
+
self,
|
|
258
|
+
path: str,
|
|
259
|
+
method: str = "GET",
|
|
260
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
261
|
+
body: Optional[bytes] = None,
|
|
262
|
+
timeout: float = 10.0,
|
|
263
|
+
) -> _Response:
|
|
264
|
+
"""Calls the place that answered last, then the others. A network error or a 5xx moves on to the next."""
|
|
265
|
+
last_error: Optional[BaseException] = None
|
|
266
|
+
n = len(self._bases)
|
|
267
|
+
for i in range(n):
|
|
268
|
+
index = (self._current + i) % n
|
|
269
|
+
try:
|
|
270
|
+
res = self._call(self._bases[index], path, method, headers or {}, body, timeout)
|
|
271
|
+
except (OSError, ValueError) as err:
|
|
272
|
+
last_error = err
|
|
273
|
+
continue
|
|
274
|
+
if res.status >= 500 and i < n - 1:
|
|
275
|
+
last_error = RuntimeError(f"{self._bases[index]} answered {res.status}")
|
|
276
|
+
continue
|
|
277
|
+
self._current = index
|
|
278
|
+
return res
|
|
279
|
+
raise last_error or RuntimeError("no Flagdock URL to call")
|
|
280
|
+
|
|
281
|
+
def _download(self, timeout: float = 10.0) -> None:
|
|
282
|
+
current = self._ruleset
|
|
283
|
+
wanted = (
|
|
284
|
+
f"?version={self._announced}"
|
|
285
|
+
if self._announced is not None and (current is None or self._announced != current["version"])
|
|
286
|
+
else ""
|
|
287
|
+
)
|
|
288
|
+
res = self._request(
|
|
289
|
+
f"/api/v1/sdk/ruleset{wanted}", headers=self._headers({"If-None-Match": self._etag} if self._etag else {}), timeout=timeout
|
|
290
|
+
)
|
|
291
|
+
if res.status == 304:
|
|
292
|
+
self._synced()
|
|
293
|
+
return
|
|
294
|
+
if res.status != 200:
|
|
295
|
+
raise RuntimeError(f"the server answered {res.status} to the rules download")
|
|
296
|
+
nxt = json.loads(res.body)
|
|
297
|
+
if not _looks_like_ruleset(nxt):
|
|
298
|
+
raise RuntimeError("the server sent rules this SDK does not understand")
|
|
299
|
+
nxt.setdefault("audiences", {})
|
|
300
|
+
previous = self._ruleset
|
|
301
|
+
self._ruleset = nxt
|
|
302
|
+
self._rules_from = "server"
|
|
303
|
+
self._etag = next((v for k, v in res.headers.items() if k.lower() == "etag"), None)
|
|
304
|
+
self._save_snapshot(res.body)
|
|
305
|
+
self._synced()
|
|
306
|
+
if previous is not None and previous["version"] != nxt["version"]:
|
|
307
|
+
if previous.get("audiences") != nxt.get("audiences"):
|
|
308
|
+
# A changed audience can alter any flag, so then we name none rather than guess.
|
|
309
|
+
self.emit_provider_configuration_changed(ProviderEventDetails())
|
|
310
|
+
else:
|
|
311
|
+
keys = set(previous["flags"]) | set(nxt["flags"])
|
|
312
|
+
changed = sorted(k for k in keys if previous["flags"].get(k) != nxt["flags"].get(k))
|
|
313
|
+
self.emit_provider_configuration_changed(ProviderEventDetails(flags_changed=changed))
|
|
314
|
+
|
|
315
|
+
def _save_snapshot(self, body: bytes) -> None:
|
|
316
|
+
"""Written to a temporary file first, so a crash never leaves half a snapshot. Failing to write is not fatal."""
|
|
317
|
+
if not self._snapshot_file:
|
|
318
|
+
return
|
|
319
|
+
tmp = f"{self._snapshot_file}.{os.getpid()}.tmp"
|
|
320
|
+
try:
|
|
321
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
322
|
+
with os.fdopen(fd, "wb") as f:
|
|
323
|
+
f.write(body)
|
|
324
|
+
os.replace(tmp, self._snapshot_file)
|
|
325
|
+
except OSError:
|
|
326
|
+
pass # A read-only disk must not take flag checks down with it.
|
|
327
|
+
|
|
328
|
+
def _synced(self) -> None:
|
|
329
|
+
self._last_sync = time.time()
|
|
330
|
+
if self._stale:
|
|
331
|
+
self._stale = False
|
|
332
|
+
self.emit_provider_ready(ProviderEventDetails(message="Flagdock is back in sync"))
|
|
333
|
+
|
|
334
|
+
def _check_stale(self) -> None:
|
|
335
|
+
if self._stale or time.time() - self._last_sync < self._stale_after:
|
|
336
|
+
return
|
|
337
|
+
self._stale = True
|
|
338
|
+
self.emit_provider_stale(
|
|
339
|
+
ProviderEventDetails(message="Flagdock has not reached its server for a while; serving the last known rules")
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
def _sync(self) -> None:
|
|
343
|
+
"""One download at a time; a failure is not raised, the next attempt fixes it."""
|
|
344
|
+
with self._sync_lock:
|
|
345
|
+
try:
|
|
346
|
+
self._download()
|
|
347
|
+
except Exception: # noqa: BLE001, S110 - closing a stream that is already gone is fine
|
|
348
|
+
pass
|
|
349
|
+
|
|
350
|
+
def _run_ticker(self) -> None:
|
|
351
|
+
"""Polls while the stream is down, watches for staleness and sends usage."""
|
|
352
|
+
next_poll = time.monotonic() + self._poll_interval
|
|
353
|
+
next_usage = time.monotonic() + self._usage_interval
|
|
354
|
+
while not self._stop.is_set():
|
|
355
|
+
self._wake.wait(timeout=min(1.0, self._poll_interval))
|
|
356
|
+
self._wake.clear()
|
|
357
|
+
if self._stop.is_set():
|
|
358
|
+
return
|
|
359
|
+
now = time.monotonic()
|
|
360
|
+
if (not self._stream_up or self._ruleset is None) and now >= next_poll:
|
|
361
|
+
self._sync()
|
|
362
|
+
next_poll = time.monotonic() + self._poll_interval
|
|
363
|
+
self._check_stale()
|
|
364
|
+
if self._usage_interval > 0 and now >= next_usage:
|
|
365
|
+
self.flush_usage()
|
|
366
|
+
next_usage = time.monotonic() + self._usage_interval
|
|
367
|
+
|
|
368
|
+
def _run_stream(self) -> None:
|
|
369
|
+
wait = 0.5
|
|
370
|
+
while not self._stop.is_set():
|
|
371
|
+
try:
|
|
372
|
+
request = urllib.request.Request( # noqa: S310 - the scheme is checked in __init__
|
|
373
|
+
f"{self._bases[self._current]}/api/v1/sdk/stream",
|
|
374
|
+
headers=self._headers({"Accept": "text/event-stream"}),
|
|
375
|
+
)
|
|
376
|
+
# The server writes a keep-alive every 25 seconds, so a minute of silence means a dead line.
|
|
377
|
+
with _opener.open(request, timeout=60) as res: # noqa: S310 - the scheme is checked in __init__
|
|
378
|
+
self._stream_response = res
|
|
379
|
+
self._stream_up = True
|
|
380
|
+
wait = 0.5
|
|
381
|
+
block: list[str] = []
|
|
382
|
+
for raw in res:
|
|
383
|
+
if self._stop.is_set():
|
|
384
|
+
return
|
|
385
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
386
|
+
if line:
|
|
387
|
+
block.append(line)
|
|
388
|
+
continue
|
|
389
|
+
if block:
|
|
390
|
+
self._on_stream_event(block)
|
|
391
|
+
block = []
|
|
392
|
+
except Exception: # noqa: BLE001 - reconnect below
|
|
393
|
+
if not self._stream_up and len(self._bases) > 1:
|
|
394
|
+
self._current = (self._current + 1) % len(self._bases)
|
|
395
|
+
finally:
|
|
396
|
+
self._stream_response = None
|
|
397
|
+
self._stream_up = False
|
|
398
|
+
if self._stop.wait(timeout=wait):
|
|
399
|
+
return
|
|
400
|
+
wait = min(wait * 2, 30.0)
|
|
401
|
+
|
|
402
|
+
def _on_stream_event(self, lines: list[str]) -> None:
|
|
403
|
+
event = next((line[6:].strip() for line in lines if line.startswith("event:")), None)
|
|
404
|
+
if event != "ruleset-changed":
|
|
405
|
+
# A heartbeat still proves the server is reachable and nothing has changed.
|
|
406
|
+
if self._ruleset is not None:
|
|
407
|
+
self._synced()
|
|
408
|
+
return
|
|
409
|
+
data = next((line[5:].strip() for line in lines if line.startswith("data:")), "{}")
|
|
410
|
+
try:
|
|
411
|
+
version = json.loads(data).get("version")
|
|
412
|
+
except (ValueError, AttributeError):
|
|
413
|
+
version = None
|
|
414
|
+
if not isinstance(version, int) or isinstance(version, bool):
|
|
415
|
+
version = None
|
|
416
|
+
if version is not None and self._ruleset is not None and version == self._ruleset["version"]:
|
|
417
|
+
self._synced()
|
|
418
|
+
return
|
|
419
|
+
if version is not None and version > (self._announced or 0):
|
|
420
|
+
self._announced = version
|
|
421
|
+
self._sync()
|
|
422
|
+
|
|
423
|
+
# --- Usage and goals -------------------------------------------------------------------------------
|
|
424
|
+
|
|
425
|
+
def flush_usage(self) -> None:
|
|
426
|
+
"""Sends the usage counted so far. Runs on a timer and at shutdown; never raises."""
|
|
427
|
+
counts = self._usage.drain()
|
|
428
|
+
exposures, events = self._activity.drain()
|
|
429
|
+
if not counts and not exposures and not events and self._ruleset is None:
|
|
430
|
+
return
|
|
431
|
+
app: dict[str, Any] = {"name": self._app_name, "instanceId": self._instance_id, "sdk": SDK_NAME, "sdkVersion": SDK_VERSION}
|
|
432
|
+
if self._ruleset is not None:
|
|
433
|
+
app["rulesetVersion"] = self._ruleset["version"]
|
|
434
|
+
report: dict[str, Any] = {"app": app, "counts": counts}
|
|
435
|
+
if exposures:
|
|
436
|
+
report["exposures"] = exposures
|
|
437
|
+
if events:
|
|
438
|
+
report["events"] = events
|
|
439
|
+
try:
|
|
440
|
+
res = self._request(
|
|
441
|
+
"/api/v1/sdk/usage",
|
|
442
|
+
method="POST",
|
|
443
|
+
headers=self._headers({"Content-Type": "application/json"}),
|
|
444
|
+
body=json.dumps(report).encode("utf-8"),
|
|
445
|
+
timeout=5.0,
|
|
446
|
+
)
|
|
447
|
+
if res.status >= 300:
|
|
448
|
+
raise RuntimeError(str(res.status))
|
|
449
|
+
except Exception: # noqa: BLE001
|
|
450
|
+
self._usage.restore(counts)
|
|
451
|
+
self._activity.restore(exposures, events)
|
|
452
|
+
|
|
453
|
+
def track(
|
|
454
|
+
self, tracking_event_name: str, evaluation_context: Optional[EvaluationContext] = None, tracking_event_details: Any = None
|
|
455
|
+
) -> None:
|
|
456
|
+
"""Reports that a person did something, such as placing an order, for goals.
|
|
457
|
+
|
|
458
|
+
Called by OpenFeature's ``client.track(name, context, TrackingEventDetails(value=...))``. Needs the
|
|
459
|
+
person's ID (targeting key); without one the event is dropped.
|
|
460
|
+
"""
|
|
461
|
+
user = evaluation_context.targeting_key if evaluation_context is not None else None
|
|
462
|
+
if self._usage_interval <= 0 or not isinstance(user, str) or user == "":
|
|
463
|
+
return
|
|
464
|
+
value = getattr(tracking_event_details, "value", None)
|
|
465
|
+
self._activity.track(
|
|
466
|
+
tracking_event_name, user, float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
# --- Answering flag checks: memory only, no I/O ----------------------------------------------------
|
|
470
|
+
|
|
471
|
+
def _resolve(
|
|
472
|
+
self, flag_key: str, default_value: Any, context: Context, kind: str
|
|
473
|
+
) -> tuple[engine.Resolution, Optional[FlagResolutionDetails[Any]]]:
|
|
474
|
+
ruleset = self._ruleset
|
|
475
|
+
if ruleset is None:
|
|
476
|
+
return engine.Resolution(default_value, "ERROR"), FlagResolutionDetails(
|
|
477
|
+
value=default_value, reason=Reason.ERROR, error_code=ErrorCode.PROVIDER_NOT_READY, error_message="Flagdock has no rules yet"
|
|
478
|
+
)
|
|
479
|
+
ctx = _as_dict(context)
|
|
480
|
+
r = engine.evaluate(ruleset, flag_key, ctx, default_value, kind)
|
|
481
|
+
if self._usage_interval > 0:
|
|
482
|
+
self._usage.record(flag_key, r.value_key)
|
|
483
|
+
user = ctx.get("targetingKey")
|
|
484
|
+
# Who got which value, so goals can be compared. Only for people the app identifies.
|
|
485
|
+
if r.value_key is not None and isinstance(user, str) and user != "":
|
|
486
|
+
self._activity.expose(flag_key, r.value_key, user)
|
|
487
|
+
if r.reason == "ERROR":
|
|
488
|
+
return r, FlagResolutionDetails(
|
|
489
|
+
value=default_value,
|
|
490
|
+
reason=Reason.ERROR,
|
|
491
|
+
error_code=_ERROR_CODES.get(r.error_code or "GENERAL", ErrorCode.GENERAL),
|
|
492
|
+
error_message=r.error_message,
|
|
493
|
+
)
|
|
494
|
+
return r, None
|
|
495
|
+
|
|
496
|
+
def _details(self, r: engine.Resolution, value: Any) -> FlagResolutionDetails[Any]:
|
|
497
|
+
metadata: dict[str, Any] = {"rulesetVersion": self._ruleset["version"]} if self._ruleset else {}
|
|
498
|
+
if r.rule_id is not None:
|
|
499
|
+
metadata["ruleId"] = r.rule_id
|
|
500
|
+
return FlagResolutionDetails(
|
|
501
|
+
value=value,
|
|
502
|
+
reason=Reason.STALE if self._stale else r.reason,
|
|
503
|
+
variant=r.value_key,
|
|
504
|
+
flag_metadata=metadata,
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
def resolve_boolean_details(
|
|
508
|
+
self, flag_key: str, default_value: bool, evaluation_context: Optional[EvaluationContext] = None
|
|
509
|
+
) -> FlagResolutionDetails[bool]:
|
|
510
|
+
r, failed = self._resolve(flag_key, default_value, evaluation_context, "boolean")
|
|
511
|
+
return failed or self._details(r, r.value)
|
|
512
|
+
|
|
513
|
+
def resolve_string_details(
|
|
514
|
+
self, flag_key: str, default_value: str, evaluation_context: Optional[EvaluationContext] = None
|
|
515
|
+
) -> FlagResolutionDetails[str]:
|
|
516
|
+
r, failed = self._resolve(flag_key, default_value, evaluation_context, "string")
|
|
517
|
+
return failed or self._details(r, r.value)
|
|
518
|
+
|
|
519
|
+
def resolve_integer_details(
|
|
520
|
+
self, flag_key: str, default_value: int, evaluation_context: Optional[EvaluationContext] = None
|
|
521
|
+
) -> FlagResolutionDetails[int]:
|
|
522
|
+
r, failed = self._resolve(flag_key, default_value, evaluation_context, "number")
|
|
523
|
+
if failed:
|
|
524
|
+
return failed
|
|
525
|
+
if isinstance(r.value, float) and not r.value.is_integer():
|
|
526
|
+
return FlagResolutionDetails(
|
|
527
|
+
value=default_value,
|
|
528
|
+
reason=Reason.ERROR,
|
|
529
|
+
error_code=ErrorCode.TYPE_MISMATCH,
|
|
530
|
+
error_message=f'Flag "{flag_key}" is {r.value}, not a whole number',
|
|
531
|
+
)
|
|
532
|
+
return self._details(r, int(r.value))
|
|
533
|
+
|
|
534
|
+
def resolve_float_details(
|
|
535
|
+
self, flag_key: str, default_value: float, evaluation_context: Optional[EvaluationContext] = None
|
|
536
|
+
) -> FlagResolutionDetails[float]:
|
|
537
|
+
r, failed = self._resolve(flag_key, default_value, evaluation_context, "number")
|
|
538
|
+
return failed or self._details(r, float(r.value))
|
|
539
|
+
|
|
540
|
+
def resolve_object_details(
|
|
541
|
+
self, flag_key: str, default_value: Any, evaluation_context: Optional[EvaluationContext] = None
|
|
542
|
+
) -> FlagResolutionDetails[Any]:
|
|
543
|
+
r, failed = self._resolve(flag_key, default_value, evaluation_context, "json")
|
|
544
|
+
return failed or self._details(r, r.value)
|
|
545
|
+
|
|
546
|
+
# --- Answers for a web page and debugging ---------------------------------------------------------
|
|
547
|
+
|
|
548
|
+
def answers_for(self, context: Context) -> Optional[dict[str, Any]]:
|
|
549
|
+
"""Every flag's answer for one person, in the shape ``@flagdock/web`` and ``@flagdock/react`` take as ``bootstrap``.
|
|
550
|
+
|
|
551
|
+
Render it into the page (``json.dumps``) so the browser starts with the right values and no flicker.
|
|
552
|
+
Holds answers only, never rules. Not counted as usage. None before the first rules arrive.
|
|
553
|
+
"""
|
|
554
|
+
ruleset = self._ruleset
|
|
555
|
+
if ruleset is None:
|
|
556
|
+
return None
|
|
557
|
+
ctx = _as_dict(context)
|
|
558
|
+
flags = []
|
|
559
|
+
for key in ruleset["flags"]:
|
|
560
|
+
r = engine.evaluate(ruleset, key, ctx, None)
|
|
561
|
+
if r.reason == "ERROR":
|
|
562
|
+
flags.append({"key": key, "errorCode": r.error_code or "GENERAL", "errorDetails": r.error_message or "Evaluation failed"})
|
|
563
|
+
else:
|
|
564
|
+
answer: dict[str, Any] = {"key": key, "value": r.value, "reason": r.reason}
|
|
565
|
+
if r.value_key is not None:
|
|
566
|
+
answer["variant"] = r.value_key
|
|
567
|
+
flags.append(answer)
|
|
568
|
+
return {"context": ctx, "flags": flags, "metadata": {"rulesetVersion": ruleset["version"]}}
|
flagdock/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: flagdock
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Flagdock feature flags for Python: an OpenFeature provider that downloads the rules once and evaluates in memory
|
|
5
|
+
Project-URL: Homepage, https://flagdock.com
|
|
6
|
+
Author-email: Flagdock <info@flagdock.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: feature-flags,feature-toggles,flagdock,openfeature,openfeature-provider
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: openfeature-sdk<1,>=0.8.0
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# flagdock
|
|
21
|
+
|
|
22
|
+
[Flagdock](https://flagdock.com) feature flags for Python services.
|
|
23
|
+
|
|
24
|
+
It is a provider for the [OpenFeature](https://openfeature.dev) Python SDK. It downloads your
|
|
25
|
+
environment's rules once, answers every flag check from memory with no network call, follows
|
|
26
|
+
changes over a live stream, and keeps serving the last rules it had if Flagdock can't be reached.
|
|
27
|
+
It gives exactly the same answers as the Node, Go and browser SDKs: the same tests run in all of them.
|
|
28
|
+
|
|
29
|
+
The only dependency is `openfeature-sdk`; HTTP uses the standard library. Python 3.10 or newer.
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
1. Install:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
pip install flagdock
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
2. Create a **server** SDK key in the Flagdock console (SDK keys page) and put it in your app's
|
|
40
|
+
environment as `FLAGDOCK_KEY`.
|
|
41
|
+
|
|
42
|
+
3. Check a flag:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
from openfeature import api
|
|
47
|
+
from openfeature.evaluation_context import EvaluationContext
|
|
48
|
+
from flagdock import FlagdockProvider
|
|
49
|
+
|
|
50
|
+
api.set_provider_and_wait(FlagdockProvider(os.environ["FLAGDOCK_KEY"], app_name="checkout-api"))
|
|
51
|
+
flags = api.get_client()
|
|
52
|
+
|
|
53
|
+
if flags.get_boolean_value("new-checkout", False, EvaluationContext(user.id, {"plan": user.plan})):
|
|
54
|
+
... # the new code path
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Call `api.shutdown()` when the process stops, so the last usage counts are sent.
|
|
58
|
+
|
|
59
|
+
Server keys can read your targeting rules, so keep them on the server.
|
|
60
|
+
|
|
61
|
+
## Options
|
|
62
|
+
|
|
63
|
+
| Option | Default | What it does |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `key` | (required) | A server SDK key (`hbf_srv_…`) for one environment. |
|
|
66
|
+
| `app_name` | `python-app` | Name shown under "Connected apps" in the console. |
|
|
67
|
+
| `snapshot_file` | | Keeps the last rules on disk (mode 600), so a restart during an outage still has flags. |
|
|
68
|
+
| `bootstrap_file` | | A ruleset JSON file to start from when nothing else is available. |
|
|
69
|
+
| `poll_interval` | `15` | Seconds between checks for changes while the live stream is down. |
|
|
70
|
+
| `stale_after` | `300` | Seconds without a sync before the provider reports itself stale. |
|
|
71
|
+
| `start_timeout` | `10` | Seconds `initialize` waits for the first download. |
|
|
72
|
+
| `usage_interval` | `60` | Seconds between usage reports; `0` turns reporting off. |
|
|
73
|
+
| `stream` | `True` | Follow changes live; `False` only polls. |
|
|
74
|
+
| `url`, `fallback_urls` | Flagdock edge, then control plane | Where the rules come from. |
|
|
75
|
+
|
|
76
|
+
Number flags can be read with `get_integer_value` (whole numbers only) or `get_float_value`, and
|
|
77
|
+
JSON flags with `get_object_value`. While Flagdock can't be reached, answers carry the reason
|
|
78
|
+
`STALE` and the provider emits `PROVIDER_STALE`, then `PROVIDER_READY` when it is back.
|
|
79
|
+
|
|
80
|
+
Date conditions read ISO 8601 text (`2026-12-01`, `2026-12-01T10:00:00Z`; no offset means UTC),
|
|
81
|
+
epoch milliseconds, `datetime` and `date` values.
|
|
82
|
+
|
|
83
|
+
## More
|
|
84
|
+
|
|
85
|
+
- `provider.answers_for(context)` returns every flag's answer for one person (answers only, no
|
|
86
|
+
rules). Put it in the page as JSON and pass it as `bootstrap` to `@flagdock/web` or
|
|
87
|
+
`@flagdock/react`, so the browser shows the right values in its first render.
|
|
88
|
+
- `provider.rotate_key(new_key)` switches keys without a restart.
|
|
89
|
+
- `client.track("order-completed", EvaluationContext(user.id), TrackingEventDetails(value=order.total))`
|
|
90
|
+
reports a goal event, which the console uses to compare the values of a flag.
|
|
91
|
+
- The provider is thread safe; with forking servers (gunicorn, uWSGI) create it in each worker
|
|
92
|
+
after the fork.
|
|
93
|
+
|
|
94
|
+
MIT licensed. Questions: info@flagdock.com
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
flagdock/__init__.py,sha256=DCJRNB7FhH7XZspMbxFvqh9dbNweULCxPX8fTRY955I,284
|
|
2
|
+
flagdock/_usage.py,sha256=HyH9SgDI4N1-0h8JhJYByDOB1Fq70U4dFLPmMBOOeVg,3220
|
|
3
|
+
flagdock/engine.py,sha256=hWthTk6yda929DPKLx5KVrfq29Ryu-B9EO_fTbaBU1Q,23164
|
|
4
|
+
flagdock/provider.py,sha256=X42oM3pMIFb27voAUiSnZRVNn2LLDmn2ASI3jXqWeKU,25642
|
|
5
|
+
flagdock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
flagdock-0.3.1.dist-info/METADATA,sha256=Gii1U8c4StQ0UALgkUdq2U5Gz-5StcZj0lnWvE0hl30,4187
|
|
7
|
+
flagdock-0.3.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
flagdock-0.3.1.dist-info/licenses/LICENSE,sha256=S5MRdB72y-MuMmtE_yME2xPKrdN8gY_QiyNtHV_DNZw,1065
|
|
9
|
+
flagdock-0.3.1.dist-info/RECORD,,
|