abacus-flags-client 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.
@@ -0,0 +1,277 @@
1
+ """Client-side SDK for abacus. It can evaluate flags and, with a generator key, mint short-lived access keys.
2
+
3
+ It cannot call admin endpoints or mint any other kind of key. `Client` is synchronous, `AsyncClient` is asyncio.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import logging
9
+ import sys
10
+ import threading
11
+ import time
12
+ from dataclasses import dataclass
13
+ from typing import Any, Dict, Optional
14
+
15
+ import httpx
16
+
17
+ if sys.version_info >= (3, 12):
18
+ from typing import Literal, TypedDict, Unpack
19
+ else:
20
+ from typing_extensions import Literal, TypedDict, Unpack
21
+
22
+ __all__ = ["Client", "AsyncClient", "Evaluation", "EvaluateOptions", "AbacusError"]
23
+
24
+ # A library stays silent until the application configures logging. Never logged: keys, tokens, subject ids.
25
+ log = logging.getLogger("abacus_flags_client")
26
+ log.addHandler(logging.NullHandler())
27
+
28
+ # Renew a minted access key this long before it expires.
29
+ _REFRESH_MARGIN = 30.0
30
+
31
+
32
+ class AbacusError(Exception):
33
+ """The API answered with an error status (`status` is 0 if it could not be reached)."""
34
+
35
+ def __init__(self, status: int, message: str):
36
+ super().__init__(f"abacus {status}: {message}")
37
+ self.status = status
38
+ self.message = message
39
+
40
+
41
+ class EvaluateOptions(TypedDict, total=False):
42
+ """Keyword arguments of `evaluate`. Every one is optional; unset ones are not sent."""
43
+
44
+ subject_id: str # hash input for stickiness and rotation; most strategies need it
45
+ attempt: int # 1-based, required by rotation flags
46
+ country: str # ISO 3166-1 alpha-2, e.g. "US"
47
+ region: str # e.g. "US-CA"
48
+ plan: str
49
+ event_id: str # echoed back and logged by the server
50
+ kind: Literal["boolean", "multivariate"] # the kind you expect; a mismatch is a 400
51
+ namespace: str # overrides the client's default
52
+ environment: str # overrides the client's default
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Evaluation:
57
+ flag: str
58
+ namespace: str
59
+ environment: str
60
+ variant: str
61
+ value: Any
62
+ reason: str
63
+ version: int
64
+ rule: Optional[int] = None
65
+ event_id: Optional[str] = None
66
+
67
+
68
+ class _Base:
69
+ def __init__(
70
+ self,
71
+ base_url: str,
72
+ api_key: str,
73
+ namespace: Optional[str],
74
+ environment: Optional[str],
75
+ client_name: Optional[str],
76
+ ):
77
+ if not api_key:
78
+ raise ValueError("api_key is required")
79
+ self._base = base_url.rstrip("/")
80
+ self._key = api_key
81
+ self._namespace = namespace
82
+ self._environment = environment
83
+ self._headers = {"X-Client-Name": client_name} if client_name else {}
84
+ self._token: Optional[str] = None
85
+ self._token_expires = 0.0
86
+
87
+ def _eval_body(self, flag: str, options: Dict[str, Any]) -> Dict[str, Any]:
88
+ unknown = set(options) - set(EvaluateOptions.__annotations__)
89
+ if unknown:
90
+ raise TypeError(f"evaluate() got unexpected options: {', '.join(sorted(unknown))}")
91
+ body: Dict[str, Any] = {"flag": flag, "namespace": self._namespace, "environment": self._environment}
92
+ body.update(options)
93
+ return {k: v for k, v in body.items() if v is not None}
94
+
95
+ def _auth(self, token: Optional[str]) -> Dict[str, str]:
96
+ return {**self._headers, "Authorization": f"Bearer {token}"} if token else dict(self._headers)
97
+
98
+ @property
99
+ def _is_generator(self) -> bool:
100
+ return self._key.startswith("abg_")
101
+
102
+ def _cached_token(self) -> Optional[str]:
103
+ return self._token if self._token and time.monotonic() < self._token_expires else None
104
+
105
+ def _store_token(self, minted: Dict[str, Any]) -> str:
106
+ log.info("minted access key, valid for %ss", minted["expires_in"])
107
+ self._token = minted["token"]
108
+ self._token_expires = time.monotonic() + minted["expires_in"] - _REFRESH_MARGIN
109
+ return self._token
110
+
111
+ def _logged(self, method: str, path: str, started: float, resp: Optional[httpx.Response], err: Optional[Exception]):
112
+ ms = round((time.perf_counter() - started) * 1000)
113
+ if resp is None: # could not reach the server
114
+ log.warning("%s %s failed after %dms: %s", method, path, ms, err or type(err).__name__)
115
+ return
116
+ st = resp.status_code
117
+ # 401/403 mean the key or its address rule is wrong and 5xx the server is unwell: callers that fall back
118
+ # to a default would otherwise hide it. Other 4xx (unknown flag, bad input) are the caller's to handle.
119
+ level = logging.WARNING if st in (401, 403) or st >= 500 else logging.DEBUG
120
+ log.log(level, "%s %s -> %d in %dms", method, path, st, ms)
121
+
122
+ def _evaluated(self, e: Evaluation) -> Evaluation:
123
+ log.debug("evaluated flag=%s namespace=%s environment=%s variant=%s reason=%s version=%s",
124
+ e.flag, e.namespace, e.environment, e.variant, e.reason, e.version)
125
+ return e
126
+
127
+ @staticmethod
128
+ def _check(resp: httpx.Response) -> httpx.Response:
129
+ if resp.is_success:
130
+ return resp
131
+ try:
132
+ message = str(resp.json()["error"])
133
+ except (ValueError, KeyError, TypeError):
134
+ message = resp.text # 400/415/422 from the framework are plain text
135
+ raise AbacusError(resp.status_code, message)
136
+
137
+ @staticmethod
138
+ def _evaluation(r: Dict[str, Any]) -> Evaluation:
139
+ return Evaluation(
140
+ flag=r["flag"], namespace=r["namespace"], environment=r["environment"], variant=r["variant"],
141
+ value=r["value"], reason=r["reason"], version=r["version"], rule=r.get("rule"), event_id=r.get("event_id"),
142
+ )
143
+
144
+
145
+ class Client(_Base):
146
+ """Synchronous client. `api_key` is any key that may evaluate (`abk_`, `abc_`, `abu_`, `aba_`).
147
+
148
+ A generator key (`abg_`) is also accepted: the client then mints and renews an access key by itself.
149
+ `namespace` and `environment` are optional; the key's defaults apply when both are unset.
150
+ Thread-safe. Use it as a context manager, or call `close()`.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ base_url: str,
156
+ api_key: str,
157
+ *,
158
+ namespace: Optional[str] = None,
159
+ environment: Optional[str] = None,
160
+ client_name: Optional[str] = None,
161
+ timeout: float = 10.0,
162
+ ):
163
+ super().__init__(base_url, api_key, namespace, environment, client_name)
164
+ self._http = httpx.Client(timeout=timeout)
165
+ self._lock = threading.Lock()
166
+
167
+ def close(self) -> None:
168
+ self._http.close()
169
+
170
+ def __enter__(self) -> "Client":
171
+ return self
172
+
173
+ def __exit__(self, *exc: object) -> None:
174
+ self.close()
175
+
176
+ def evaluate(self, flag: str, **options: Unpack[EvaluateOptions]) -> Evaluation:
177
+ body = self._eval_body(flag, dict(options))
178
+ return self._evaluated(self._evaluation(self._send("POST", "/v1/evaluate", self._bearer(), body).json()))
179
+
180
+ def ping(self) -> None:
181
+ """Check that the server is reachable and its database answers (`GET /healthz`, no key needed).
182
+
183
+ Raises `AbacusError` otherwise (`status` is 0 if it could not be reached).
184
+ """
185
+ self._send("GET", "/healthz", None)
186
+
187
+ def authenticated_ping(self) -> None:
188
+ """Check that the configured key is valid (`GET /v1/ping`). Returns nothing on success.
189
+
190
+ Raises `AbacusError`: status 401 with "key does not exist" for any key that cannot be used (unknown, revoked,
191
+ expired, deleted, or called from an address it does not allow; the server gives no further detail),
192
+ or status 0 if the server could not be reached. For a generator key this tests the generator itself.
193
+ """
194
+ self._send("GET", "/v1/ping", self._key)
195
+
196
+ def mint_access_token(self, ttl_seconds: int = 3600) -> Dict[str, Any]:
197
+ """Exchange a generator key for an `aba_` key: `{"token", "expires_at", "expires_in"}`."""
198
+ return self._send("POST", "/v1/access-tokens", self._key, {"ttl_seconds": ttl_seconds}).json()
199
+
200
+ def _bearer(self) -> str:
201
+ if not self._is_generator:
202
+ return self._key
203
+ with self._lock:
204
+ return self._cached_token() or self._store_token(self.mint_access_token())
205
+
206
+ def _send(self, method: str, path: str, token: Optional[str], body: Optional[Dict[str, Any]] = None) -> httpx.Response:
207
+ started = time.perf_counter()
208
+ try:
209
+ resp = self._http.request(method, self._base + path, json=body, headers=self._auth(token))
210
+ except httpx.HTTPError as e:
211
+ self._logged(method, path, started, None, e)
212
+ raise AbacusError(0, str(e) or type(e).__name__) from e
213
+ self._logged(method, path, started, resp, None)
214
+ return self._check(resp)
215
+
216
+
217
+ class AsyncClient(_Base):
218
+ """asyncio client with the same methods as `Client`, all coroutines. Use `async with`, or call `await aclose()`."""
219
+
220
+ def __init__(
221
+ self,
222
+ base_url: str,
223
+ api_key: str,
224
+ *,
225
+ namespace: Optional[str] = None,
226
+ environment: Optional[str] = None,
227
+ client_name: Optional[str] = None,
228
+ timeout: float = 10.0,
229
+ ):
230
+ super().__init__(base_url, api_key, namespace, environment, client_name)
231
+ self._http = httpx.AsyncClient(timeout=timeout)
232
+ self._lock: Optional[asyncio.Lock] = None # created on first use, inside the running loop
233
+
234
+ async def aclose(self) -> None:
235
+ await self._http.aclose()
236
+
237
+ async def __aenter__(self) -> "AsyncClient":
238
+ return self
239
+
240
+ async def __aexit__(self, *exc: object) -> None:
241
+ await self.aclose()
242
+
243
+ async def evaluate(self, flag: str, **options: Unpack[EvaluateOptions]) -> Evaluation:
244
+ body = self._eval_body(flag, dict(options))
245
+ return self._evaluated(self._evaluation((await self._send("POST", "/v1/evaluate", await self._bearer(), body)).json()))
246
+
247
+ async def ping(self) -> None:
248
+ """See `Client.ping`."""
249
+ await self._send("GET", "/healthz", None)
250
+
251
+ async def authenticated_ping(self) -> None:
252
+ """See `Client.authenticated_ping`."""
253
+ await self._send("GET", "/v1/ping", self._key)
254
+
255
+ async def mint_access_token(self, ttl_seconds: int = 3600) -> Dict[str, Any]:
256
+ """See `Client.mint_access_token`."""
257
+ return (await self._send("POST", "/v1/access-tokens", self._key, {"ttl_seconds": ttl_seconds})).json()
258
+
259
+ async def _bearer(self) -> str:
260
+ if not self._is_generator:
261
+ return self._key
262
+ if self._lock is None:
263
+ self._lock = asyncio.Lock()
264
+ async with self._lock:
265
+ return self._cached_token() or self._store_token(await self.mint_access_token())
266
+
267
+ async def _send(
268
+ self, method: str, path: str, token: Optional[str], body: Optional[Dict[str, Any]] = None
269
+ ) -> httpx.Response:
270
+ started = time.perf_counter()
271
+ try:
272
+ resp = await self._http.request(method, self._base + path, json=body, headers=self._auth(token))
273
+ except httpx.HTTPError as e:
274
+ self._logged(method, path, started, None, e)
275
+ raise AbacusError(0, str(e) or type(e).__name__) from e
276
+ self._logged(method, path, started, resp, None)
277
+ return self._check(resp)
File without changes
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: abacus-flags-client
3
+ Version: 0.1.0
4
+ Summary: Client-side SDK for abacus feature flags: evaluate flags, no admin actions.
5
+ Project-URL: Repository, https://github.com/loggerheads-with-binary/abacus
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Typing :: Typed
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: httpx>=0.24
11
+ Requires-Dist: typing-extensions>=4.4; python_version < '3.12'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # abacus-flags-client (Python)
15
+
16
+ Client-side SDK for [abacus](https://github.com/loggerheads-with-binary/abacus), the feature flag and A/B testing service. It evaluates flags. It has no admin calls and cannot create keys. Built on [httpx](https://www.python-httpx.org/), with a synchronous `Client` and an asyncio `AsyncClient`. Python 3.9+.
17
+
18
+ ```sh
19
+ pip install abacus-flags-client
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ ```python
25
+ import os
26
+ from abacus_flags_client import Client
27
+
28
+ abacus = Client("https://abacus.example.com", os.environ["ABACUS_KEY"], environment="prod", client_name="checkout")
29
+
30
+ r = abacus.evaluate("new-checkout", subject_id="user-42", country="US", plan="pro")
31
+ if r.value:
32
+ ...
33
+ ```
34
+
35
+ `AsyncClient` has the same methods as coroutines:
36
+
37
+ ```python
38
+ from abacus_flags_client import AsyncClient
39
+
40
+ async with AsyncClient("https://abacus.example.com", key, environment="prod") as abacus:
41
+ r = await abacus.evaluate("new-checkout", subject_id="user-42")
42
+ ```
43
+
44
+ Both clients keep a connection pool. Use them as context managers (`with` / `async with`), or call `close()` / `await aclose()`. Create one client and reuse it.
45
+
46
+ ### Options
47
+
48
+ `evaluate(flag, **options)` takes keyword arguments described by the `EvaluateOptions` `TypedDict`, so type checkers and editors complete and check them. All are optional, and unset ones are not sent. A misspelt option raises `TypeError`.
49
+
50
+ | Option | Meaning |
51
+ |---|---|
52
+ | `subject_id` | Hash input for stickiness and rotation. Most strategies need it. |
53
+ | `attempt` | 1-based attempt counter, required by rotation flags. |
54
+ | `country` | ISO 3166-1 alpha-2, e.g. `"US"`. |
55
+ | `region` | e.g. `"US-CA"`. |
56
+ | `plan` | The subject's plan name. |
57
+ | `event_id` | Correlation id, echoed back and logged by the server. |
58
+ | `kind` | `"boolean"` or `"multivariate"`. A mismatch is a 400. |
59
+ | `namespace`, `environment` | Override the client's defaults for one call. |
60
+
61
+ The result is an `Evaluation` with `flag`, `namespace`, `environment`, `variant`, `value`, `reason`, `version`, `rule` and `event_id`.
62
+
63
+ ## Recommended: wrap evaluation in a closure
64
+
65
+ Region, plan and subject usually come from the current request or user, not from the place where a flag is checked. Build a small function once per request that takes only the flag name and returns its value, and pass that function around. Call sites then cannot forget the context, and every flag is evaluated for the same subject.
66
+
67
+ ```python
68
+ from abacus_flags_client import AbacusError
69
+
70
+ def flags_for(request):
71
+ def flag(name, default=False):
72
+ try:
73
+ return abacus.evaluate(
74
+ name,
75
+ subject_id=request.user.id,
76
+ country=request.geo.country,
77
+ region=request.geo.region,
78
+ plan=request.user.plan,
79
+ ).value
80
+ except AbacusError:
81
+ return default # decide what a failed lookup means for this flag
82
+ return flag
83
+
84
+ flag = flags_for(request)
85
+ if flag("new-checkout"):
86
+ ...
87
+ ```
88
+
89
+ With `AsyncClient`, make the inner function `async def` and `await` the call.
90
+
91
+ ## Errors
92
+
93
+ Every failure raises `AbacusError` with `.status` and `.message`. `status` is 0 when the server could not be reached. The SDK picks no fallback value, so choose your own (see the closure above).
94
+
95
+ ## Logging
96
+
97
+ The package logs through the standard `logging` module under the logger name `abacus_flags_client`. It adds only a `NullHandler`, so nothing is printed until your application configures logging.
98
+
99
+ ```python
100
+ import logging
101
+ logging.getLogger("abacus_flags_client").setLevel(logging.DEBUG)
102
+ ```
103
+
104
+ | Level | What |
105
+ |---|---|
106
+ | `DEBUG` | Every request (method, path, status, milliseconds) and every evaluation (flag, namespace, environment, variant, reason, version). |
107
+ | `INFO` | A generator key minted a new access key. |
108
+ | `WARNING` | The server could not be reached, answered 5xx, or answered 401 or 403 (bad key or address rule). |
109
+
110
+ Errors are raised, not also logged at `ERROR`, so one failure is not reported twice. API keys, access keys and `subject_id` are never logged.
111
+
112
+ ## Ping
113
+
114
+ - `ping()` checks that the server is reachable and healthy. It sends no key.
115
+ - `authenticated_ping()` checks that your key is valid.
116
+
117
+ Both return nothing and raise `AbacusError` on failure. A key that cannot be used (unknown, revoked, expired, deleted, or used from an address it does not allow) always gives `status` 401 and `"key does not exist"`. The server gives no more detail on purpose.
118
+
119
+ ## Keys
120
+
121
+ Any key that may evaluate works: `abk_` (service), `abc_` (client), `abu_` (user), `aba_` (access).
122
+
123
+ With a generator key (`abg_`) the client calls `POST /v1/access-tokens` for you, caches the short-lived `aba_` key and renews it 30 seconds before it expires. `mint_access_token(ttl_seconds)` returns one directly. Generator keys are the only keys this SDK can exchange. It cannot mint any other kind.
124
+
125
+ `namespace` and `environment` are optional. When both are unset, the key's defaults apply.
126
+
127
+ ## License
128
+
129
+ MIT
@@ -0,0 +1,5 @@
1
+ abacus_flags_client/__init__.py,sha256=AfAdXZQBtx-ZXA76t-yF--NJ9o--BleAdnHCpvZwXvo,11131
2
+ abacus_flags_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ abacus_flags_client-0.1.0.dist-info/METADATA,sha256=dF-CMVkcOVFbLkMMbTTOqf2l5HUDScnV4TJxo99hy1o,5441
4
+ abacus_flags_client-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ abacus_flags_client-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any