abacus-flags-client 0.1.0__tar.gz
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.
- abacus_flags_client-0.1.0/.gitignore +12 -0
- abacus_flags_client-0.1.0/PKG-INFO +129 -0
- abacus_flags_client-0.1.0/README.md +116 -0
- abacus_flags_client-0.1.0/pyproject.toml +26 -0
- abacus_flags_client-0.1.0/src/abacus_flags_client/__init__.py +277 -0
- abacus_flags_client-0.1.0/src/abacus_flags_client/py.typed +0 -0
- abacus_flags_client-0.1.0/tests/test_client.py +159 -0
|
@@ -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,116 @@
|
|
|
1
|
+
# abacus-flags-client (Python)
|
|
2
|
+
|
|
3
|
+
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+.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install abacus-flags-client
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import os
|
|
13
|
+
from abacus_flags_client import Client
|
|
14
|
+
|
|
15
|
+
abacus = Client("https://abacus.example.com", os.environ["ABACUS_KEY"], environment="prod", client_name="checkout")
|
|
16
|
+
|
|
17
|
+
r = abacus.evaluate("new-checkout", subject_id="user-42", country="US", plan="pro")
|
|
18
|
+
if r.value:
|
|
19
|
+
...
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`AsyncClient` has the same methods as coroutines:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from abacus_flags_client import AsyncClient
|
|
26
|
+
|
|
27
|
+
async with AsyncClient("https://abacus.example.com", key, environment="prod") as abacus:
|
|
28
|
+
r = await abacus.evaluate("new-checkout", subject_id="user-42")
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
### Options
|
|
34
|
+
|
|
35
|
+
`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`.
|
|
36
|
+
|
|
37
|
+
| Option | Meaning |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `subject_id` | Hash input for stickiness and rotation. Most strategies need it. |
|
|
40
|
+
| `attempt` | 1-based attempt counter, required by rotation flags. |
|
|
41
|
+
| `country` | ISO 3166-1 alpha-2, e.g. `"US"`. |
|
|
42
|
+
| `region` | e.g. `"US-CA"`. |
|
|
43
|
+
| `plan` | The subject's plan name. |
|
|
44
|
+
| `event_id` | Correlation id, echoed back and logged by the server. |
|
|
45
|
+
| `kind` | `"boolean"` or `"multivariate"`. A mismatch is a 400. |
|
|
46
|
+
| `namespace`, `environment` | Override the client's defaults for one call. |
|
|
47
|
+
|
|
48
|
+
The result is an `Evaluation` with `flag`, `namespace`, `environment`, `variant`, `value`, `reason`, `version`, `rule` and `event_id`.
|
|
49
|
+
|
|
50
|
+
## Recommended: wrap evaluation in a closure
|
|
51
|
+
|
|
52
|
+
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.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from abacus_flags_client import AbacusError
|
|
56
|
+
|
|
57
|
+
def flags_for(request):
|
|
58
|
+
def flag(name, default=False):
|
|
59
|
+
try:
|
|
60
|
+
return abacus.evaluate(
|
|
61
|
+
name,
|
|
62
|
+
subject_id=request.user.id,
|
|
63
|
+
country=request.geo.country,
|
|
64
|
+
region=request.geo.region,
|
|
65
|
+
plan=request.user.plan,
|
|
66
|
+
).value
|
|
67
|
+
except AbacusError:
|
|
68
|
+
return default # decide what a failed lookup means for this flag
|
|
69
|
+
return flag
|
|
70
|
+
|
|
71
|
+
flag = flags_for(request)
|
|
72
|
+
if flag("new-checkout"):
|
|
73
|
+
...
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
With `AsyncClient`, make the inner function `async def` and `await` the call.
|
|
77
|
+
|
|
78
|
+
## Errors
|
|
79
|
+
|
|
80
|
+
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).
|
|
81
|
+
|
|
82
|
+
## Logging
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import logging
|
|
88
|
+
logging.getLogger("abacus_flags_client").setLevel(logging.DEBUG)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
| Level | What |
|
|
92
|
+
|---|---|
|
|
93
|
+
| `DEBUG` | Every request (method, path, status, milliseconds) and every evaluation (flag, namespace, environment, variant, reason, version). |
|
|
94
|
+
| `INFO` | A generator key minted a new access key. |
|
|
95
|
+
| `WARNING` | The server could not be reached, answered 5xx, or answered 401 or 403 (bad key or address rule). |
|
|
96
|
+
|
|
97
|
+
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.
|
|
98
|
+
|
|
99
|
+
## Ping
|
|
100
|
+
|
|
101
|
+
- `ping()` checks that the server is reachable and healthy. It sends no key.
|
|
102
|
+
- `authenticated_ping()` checks that your key is valid.
|
|
103
|
+
|
|
104
|
+
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.
|
|
105
|
+
|
|
106
|
+
## Keys
|
|
107
|
+
|
|
108
|
+
Any key that may evaluate works: `abk_` (service), `abc_` (client), `abu_` (user), `aba_` (access).
|
|
109
|
+
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
`namespace` and `environment` are optional. When both are unset, the key's defaults apply.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "abacus-flags-client"
|
|
7
|
+
# the release pipeline overwrites this with the git tag
|
|
8
|
+
version = "0.1.0"
|
|
9
|
+
description = "Client-side SDK for abacus feature flags: evaluate flags, no admin actions."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"httpx>=0.24",
|
|
15
|
+
'typing_extensions>=4.4; python_version < "3.12"',
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Repository = "https://github.com/loggerheads-with-binary/abacus"
|
|
24
|
+
|
|
25
|
+
[tool.hatch.build.targets.wheel]
|
|
26
|
+
packages = ["src/abacus_flags_client"]
|
|
@@ -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,159 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import threading
|
|
4
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from abacus_flags_client import AbacusError, AsyncClient, Client
|
|
9
|
+
|
|
10
|
+
calls = []
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class H(BaseHTTPRequestHandler):
|
|
14
|
+
def log_message(self, *a):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
def do_GET(self):
|
|
18
|
+
calls.append((self.path, self.headers.get("Authorization"), None, None))
|
|
19
|
+
auth = self.headers.get("Authorization")
|
|
20
|
+
if self.path == "/healthz":
|
|
21
|
+
out, code = b"ok", 200
|
|
22
|
+
elif auth in ("Bearer abc_ok", "Bearer abg_gen"):
|
|
23
|
+
out, code = b'{"status":"ok"}', 200
|
|
24
|
+
else:
|
|
25
|
+
out, code = b'{"error":"key does not exist"}', 401
|
|
26
|
+
self.send_response(code)
|
|
27
|
+
self.send_header("Content-Length", str(len(out)))
|
|
28
|
+
self.end_headers()
|
|
29
|
+
self.wfile.write(out)
|
|
30
|
+
|
|
31
|
+
def do_POST(self):
|
|
32
|
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
|
33
|
+
calls.append((self.path, self.headers["Authorization"], self.headers.get("X-Client-Name"), body))
|
|
34
|
+
if self.path == "/v1/access-tokens":
|
|
35
|
+
out, code = {"token": "aba_1", "expires_in": 3600}, 200
|
|
36
|
+
elif self.headers["Authorization"] == "Bearer aba_1" or self.headers["Authorization"] == "Bearer abc_ok":
|
|
37
|
+
if body["flag"] == "missing":
|
|
38
|
+
out, code = {"error": "flag not found"}, 404
|
|
39
|
+
else:
|
|
40
|
+
out, code = {"flag": body["flag"], "namespace": "default", "environment": body["environment"],
|
|
41
|
+
"variant": "true", "value": True, "reason": "static", "version": 2, "rule": None,
|
|
42
|
+
"event_id": None}, 200
|
|
43
|
+
else:
|
|
44
|
+
out, code = {"error": "missing or invalid API key"}, 401
|
|
45
|
+
data = json.dumps(out).encode()
|
|
46
|
+
self.send_response(code)
|
|
47
|
+
self.send_header("Content-Length", str(len(data)))
|
|
48
|
+
self.end_headers()
|
|
49
|
+
self.wfile.write(data)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@pytest.fixture(scope="module")
|
|
53
|
+
def url():
|
|
54
|
+
srv = HTTPServer(("127.0.0.1", 0), H)
|
|
55
|
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
56
|
+
yield f"http://127.0.0.1:{srv.server_port}/"
|
|
57
|
+
srv.shutdown()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_evaluate_sends_only_set_fields(url):
|
|
61
|
+
calls.clear()
|
|
62
|
+
r = Client(url, "abc_ok", environment="prod", client_name="web").evaluate("banner", subject_id="u1")
|
|
63
|
+
assert (r.value, r.reason, r.version) == (True, "static", 2)
|
|
64
|
+
assert calls[0] == ("/v1/evaluate", "Bearer abc_ok", "web", {"flag": "banner", "environment": "prod", "subject_id": "u1"})
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_error_status_and_message(url):
|
|
68
|
+
with pytest.raises(AbacusError) as e:
|
|
69
|
+
Client(url, "abc_ok", environment="prod").evaluate("missing")
|
|
70
|
+
assert (e.value.status, e.value.message) == (404, "flag not found")
|
|
71
|
+
with pytest.raises(AbacusError) as e:
|
|
72
|
+
Client(url, "abc_bad").evaluate("x")
|
|
73
|
+
assert e.value.status == 401
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_generator_mints_once_and_reuses(url):
|
|
77
|
+
calls.clear()
|
|
78
|
+
c = Client(url, "abg_gen", environment="prod")
|
|
79
|
+
c.evaluate("a")
|
|
80
|
+
c.evaluate("b")
|
|
81
|
+
assert [p for p, *_ in calls] == ["/v1/access-tokens", "/v1/evaluate", "/v1/evaluate"]
|
|
82
|
+
assert calls[0][1] == "Bearer abg_gen" and calls[1][1] == "Bearer aba_1"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_ping_needs_no_key_and_authenticated_ping_checks_it(url):
|
|
86
|
+
calls.clear()
|
|
87
|
+
c = Client(url, "abc_ok")
|
|
88
|
+
c.ping()
|
|
89
|
+
c.authenticated_ping()
|
|
90
|
+
assert calls == [("/healthz", None, None, None), ("/v1/ping", "Bearer abc_ok", None, None)]
|
|
91
|
+
Client(url, "abg_gen").authenticated_ping()
|
|
92
|
+
assert calls[-1][1] == "Bearer abg_gen" # tests the generator itself, mints nothing
|
|
93
|
+
with pytest.raises(AbacusError) as e:
|
|
94
|
+
Client(url, "abc_gone").authenticated_ping()
|
|
95
|
+
assert (e.value.status, e.value.message) == (401, "key does not exist")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_ping_unreachable():
|
|
99
|
+
with pytest.raises(AbacusError) as e:
|
|
100
|
+
Client("http://127.0.0.1:1", "abc_ok", timeout=1).ping()
|
|
101
|
+
assert e.value.status == 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_unknown_option_is_rejected(url):
|
|
105
|
+
with pytest.raises(TypeError):
|
|
106
|
+
Client(url, "abc_ok").evaluate("x", subjectid="typo")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_async_client_has_the_same_behaviour(url):
|
|
110
|
+
async def go():
|
|
111
|
+
calls.clear()
|
|
112
|
+
async with AsyncClient(url, "abc_ok", environment="prod", client_name="web") as c:
|
|
113
|
+
r = await c.evaluate("banner", subject_id="u1", plan="pro")
|
|
114
|
+
assert (r.value, r.reason) == (True, "static")
|
|
115
|
+
assert calls[0] == ("/v1/evaluate", "Bearer abc_ok", "web",
|
|
116
|
+
{"flag": "banner", "environment": "prod", "subject_id": "u1", "plan": "pro"})
|
|
117
|
+
with pytest.raises(AbacusError) as e:
|
|
118
|
+
await c.evaluate("missing")
|
|
119
|
+
assert (e.value.status, e.value.message) == (404, "flag not found")
|
|
120
|
+
await c.ping()
|
|
121
|
+
await c.authenticated_ping()
|
|
122
|
+
async with AsyncClient(url, "abc_gone") as c:
|
|
123
|
+
with pytest.raises(AbacusError) as e:
|
|
124
|
+
await c.authenticated_ping()
|
|
125
|
+
assert (e.value.status, e.value.message) == (401, "key does not exist")
|
|
126
|
+
calls.clear()
|
|
127
|
+
async with AsyncClient(url, "abg_gen", environment="prod") as c:
|
|
128
|
+
await asyncio.gather(c.evaluate("a"), c.evaluate("b"))
|
|
129
|
+
await c.evaluate("c")
|
|
130
|
+
assert [p for p, *_ in calls].count("/v1/access-tokens") == 1
|
|
131
|
+
async with AsyncClient("http://127.0.0.1:1", "abc_ok", timeout=1) as c:
|
|
132
|
+
with pytest.raises(AbacusError) as e:
|
|
133
|
+
await c.ping()
|
|
134
|
+
assert e.value.status == 0
|
|
135
|
+
|
|
136
|
+
asyncio.run(go())
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_logging_levels_and_no_secrets(url, caplog):
|
|
140
|
+
import logging
|
|
141
|
+
|
|
142
|
+
caplog.set_level(logging.DEBUG, logger="abacus_flags_client")
|
|
143
|
+
c = Client(url, "abg_gen", environment="prod")
|
|
144
|
+
c.evaluate("banner", subject_id="user-secret-42")
|
|
145
|
+
with pytest.raises(AbacusError):
|
|
146
|
+
c.evaluate("missing") # 404: debug only
|
|
147
|
+
with pytest.raises(AbacusError):
|
|
148
|
+
Client(url, "abc_gone").authenticated_ping() # 401: warning
|
|
149
|
+
with pytest.raises(AbacusError):
|
|
150
|
+
Client("http://127.0.0.1:1", "abc_ok", timeout=1).ping() # unreachable: warning
|
|
151
|
+
by = {lvl: [r.getMessage() for r in caplog.records if r.levelno == lvl] for lvl in (10, 20, 30)}
|
|
152
|
+
assert any(m.startswith("minted access key") for m in by[20])
|
|
153
|
+
assert any("evaluated flag=banner" in m and "reason=static" in m for m in by[10])
|
|
154
|
+
assert any("/v1/evaluate -> 404" in m for m in by[10])
|
|
155
|
+
assert any("/v1/ping -> 401" in m for m in by[30])
|
|
156
|
+
assert any("/healthz failed" in m for m in by[30])
|
|
157
|
+
text = caplog.text
|
|
158
|
+
for secret in ("abg_gen", "aba_1", "abc_gone", "abc_ok", "user-secret-42"):
|
|
159
|
+
assert secret not in text
|