ddutils 0.3.1__tar.gz → 0.3.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ddutils
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Domain Driven Utils Library
5
5
  Keywords: python,ddutils
6
6
  Author: davyddd
@@ -571,6 +571,45 @@ async with atomic(alias=PostgresDB.REPLICA) as session:
571
571
  await clickhouse.close()
572
572
  ```
573
573
 
574
+ ## Feature Flags
575
+
576
+ `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
577
+ of readers that see it, a free-form payload), the `FeatureFlagStorage` interface and `FeatureFlags`, which reads
578
+ through a storage with a per-process cache (`BASE_TTL` plus a random jitter). While the storage fails, the last
579
+ known record is served and re-read with an exponential backoff from `ERROR_TTL` up to the TTL. The storages live
580
+ with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`, `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
581
+
582
+ Readers see booleans and payloads, not records. `is_enabled` is the flag's switch and its proportion in one answer:
583
+ off for everyone when the flag is off, on for the `proportion` of the readers when it is on, so a kill-switch is a
584
+ flag with proportion 1.0. With an `idempotent_key` (a user id, an account id) the split is repeatable, the same
585
+ user always lands on the same side; without one it is random per call. `get_payload` is the payload as stored; its shape is the application's,
586
+ parse it there.
587
+
588
+ ```python
589
+ from ddredis.feature_flags import RedisFeatureFlagStorage
590
+ from ddutils.feature_flags import FeatureFlags
591
+
592
+ feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
593
+
594
+ # a kill-switch: proportion 1.0, on or off for everyone
595
+ if await feature_flags.is_enabled('new_checkout'):
596
+ ...
597
+
598
+ # a gradual rollout: on for `proportion` of the users, the same users every time
599
+ if await feature_flags.is_enabled('new_ranking', user_id):
600
+ ...
601
+
602
+ # a kill-switch with settings
603
+ if await feature_flags.is_enabled('email_provider_block'):
604
+ rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
605
+ ```
606
+
607
+ A storage implements `get`, `get_map`, `put` and `delete`; `rename` defaults to
608
+ put-then-delete and is overridden where the storage can do it atomically. `FeatureFlagRecord` validates itself on
609
+ construction; a storage builds it with `from_dict` and, when what it read is not a valid record, logs it and reads
610
+ it as the defaults. A storage failure raises `FeatureFlagStorageError`
611
+ with the cause chained.
612
+
574
613
  ## Function Exception Extraction
575
614
 
576
615
  AST-based introspection for extracting exceptions from function source code.
@@ -553,6 +553,45 @@ async with atomic(alias=PostgresDB.REPLICA) as session:
553
553
  await clickhouse.close()
554
554
  ```
555
555
 
556
+ ## Feature Flags
557
+
558
+ `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
559
+ of readers that see it, a free-form payload), the `FeatureFlagStorage` interface and `FeatureFlags`, which reads
560
+ through a storage with a per-process cache (`BASE_TTL` plus a random jitter). While the storage fails, the last
561
+ known record is served and re-read with an exponential backoff from `ERROR_TTL` up to the TTL. The storages live
562
+ with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`, `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
563
+
564
+ Readers see booleans and payloads, not records. `is_enabled` is the flag's switch and its proportion in one answer:
565
+ off for everyone when the flag is off, on for the `proportion` of the readers when it is on, so a kill-switch is a
566
+ flag with proportion 1.0. With an `idempotent_key` (a user id, an account id) the split is repeatable, the same
567
+ user always lands on the same side; without one it is random per call. `get_payload` is the payload as stored; its shape is the application's,
568
+ parse it there.
569
+
570
+ ```python
571
+ from ddredis.feature_flags import RedisFeatureFlagStorage
572
+ from ddutils.feature_flags import FeatureFlags
573
+
574
+ feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
575
+
576
+ # a kill-switch: proportion 1.0, on or off for everyone
577
+ if await feature_flags.is_enabled('new_checkout'):
578
+ ...
579
+
580
+ # a gradual rollout: on for `proportion` of the users, the same users every time
581
+ if await feature_flags.is_enabled('new_ranking', user_id):
582
+ ...
583
+
584
+ # a kill-switch with settings
585
+ if await feature_flags.is_enabled('email_provider_block'):
586
+ rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
587
+ ```
588
+
589
+ A storage implements `get`, `get_map`, `put` and `delete`; `rename` defaults to
590
+ put-then-delete and is overridden where the storage can do it atomically. `FeatureFlagRecord` validates itself on
591
+ construction; a storage builds it with `from_dict` and, when what it read is not a valid record, logs it and reads
592
+ it as the defaults. A storage failure raises `FeatureFlagStorageError`
593
+ with the cause chained.
594
+
556
595
  ## Function Exception Extraction
557
596
 
558
597
  AST-based introspection for extracting exceptions from function source code.
@@ -1,8 +1,10 @@
1
1
  from . import (
2
2
  annotation_helpers,
3
3
  class_helpers,
4
+ connections,
4
5
  convertors,
5
6
  datetime_helpers,
7
+ feature_flags,
6
8
  function_exceptions_extractor,
7
9
  function_helpers,
8
10
  module_getter,
@@ -16,8 +18,10 @@ from . import (
16
18
  __all__ = (
17
19
  'annotation_helpers',
18
20
  'class_helpers',
21
+ 'connections',
19
22
  'convertors',
20
23
  'datetime_helpers',
24
+ 'feature_flags',
21
25
  'function_exceptions_extractor',
22
26
  'function_helpers',
23
27
  'module_getter',
@@ -0,0 +1,227 @@
1
+ import hashlib
2
+ import logging
3
+ import random
4
+ import time
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, field, fields
8
+ from typing import Any, NamedTuple, Protocol, Self
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ DEFAULT_PROPORTION = 0.01
13
+
14
+ BASE_TTL = 15 # seconds a record is served from the cache before it is re-read
15
+ JITTER = 5 # seconds added at random to the TTL, so the readers of a process do not re-read at once
16
+ ERROR_TTL = 1 # seconds before the first re-read after a storage error; doubles on every failure up to `base_ttl`
17
+
18
+ _BUCKETS = 1 << 32
19
+
20
+
21
+ class Stringable(Protocol):
22
+ def __str__(self) -> str: ...
23
+
24
+
25
+ _TRUE_WORDS = frozenset({'true', '1', 'yes', 'on', 't', 'y'})
26
+ _FALSE_WORDS = frozenset({'false', '0', 'no', 'off', 'f', 'n'})
27
+
28
+
29
+ def _parse_bool(value: Any) -> bool:
30
+ """A bool from what a storage may hold: a bool, 0 / 1, or a word like `true`, `'1'`, `yes`, `on`."""
31
+ if isinstance(value, bool):
32
+ return value
33
+ if isinstance(value, int) and value in (0, 1):
34
+ return bool(value)
35
+ if isinstance(value, bytes):
36
+ value = value.decode()
37
+ if isinstance(value, str):
38
+ word = value.strip().lower()
39
+ if word in _TRUE_WORDS:
40
+ return True
41
+ if word in _FALSE_WORDS:
42
+ return False
43
+ raise ValueError(f'`enabled` must be a bool, got {value!r}')
44
+
45
+
46
+ def _parse_proportion(value: Any) -> float:
47
+ if isinstance(value, bool) or not isinstance(value, int | float | str):
48
+ raise ValueError(f'`proportion` must be a number in 0..1, got {value!r}')
49
+ try:
50
+ proportion = float(value)
51
+ except ValueError as e:
52
+ raise ValueError(f'`proportion` must be a number in 0..1, got {value!r}') from e
53
+ if not 0 <= proportion <= 1:
54
+ raise ValueError(f'`proportion` must be in 0..1, got {proportion!r}')
55
+ return proportion
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class FeatureFlagRecord:
60
+ """
61
+ What a storage holds for one flag: whether it is on, the proportion of readers that see it and a free-form
62
+ payload. The contract between a storage and `FeatureFlags`; readers see `bool`s and payloads, not records.
63
+
64
+ Validated on construction: `enabled` takes a bool or what a storage may hold for one (`1`, `'true'`, `'1'`,
65
+ `'yes'`), `proportion` is a number in 0..1, `payload` a mapping (copied). Anything else is a `ValueError`.
66
+ Storages build records with `from_dict` and write `to_dict`.
67
+ """
68
+
69
+ enabled: bool = False
70
+ proportion: float = DEFAULT_PROPORTION
71
+ payload: Mapping[str, Any] = field(default_factory=dict)
72
+
73
+ def __post_init__(self) -> None:
74
+ object.__setattr__(self, 'enabled', _parse_bool(self.enabled))
75
+ object.__setattr__(self, 'proportion', _parse_proportion(self.proportion))
76
+ if not isinstance(self.payload, Mapping):
77
+ raise ValueError(f'`payload` must be a mapping, got {type(self.payload).__name__}')
78
+ object.__setattr__(self, 'payload', dict(self.payload))
79
+
80
+ @classmethod
81
+ def from_dict(cls, data: Any) -> Self:
82
+ """A record from what a storage read; `ValueError` for anything that is not a valid record."""
83
+ if not isinstance(data, Mapping):
84
+ raise ValueError(f'a record must be a mapping, got {type(data).__name__}')
85
+ unknown = set(data) - {f.name for f in fields(cls)}
86
+ if unknown:
87
+ raise ValueError(f'unknown record fields {sorted(unknown)!r}')
88
+ return cls(**data)
89
+
90
+ def to_dict(self) -> dict[str, Any]:
91
+ return {'enabled': self.enabled, 'proportion': self.proportion, 'payload': dict(self.payload)}
92
+
93
+
94
+ class FeatureFlagStorageError(Exception):
95
+ """The storage could not answer (connection, timeout, server error); the cause is chained."""
96
+
97
+
98
+ class FeatureFlagStorage(ABC):
99
+ """
100
+ Where the flags live. One flag is one `FeatureFlagRecord` under its name.
101
+
102
+ A missing flag is `None`, a malformed one is read as the defaults: only a failure of the storage itself
103
+ raises, as `FeatureFlagStorageError`, so that `FeatureFlags` can keep serving the last known values.
104
+ Implementations: `ddredis.feature_flags.RedisFeatureFlagStorage`, `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
105
+ """
106
+
107
+ @abstractmethod
108
+ async def get(self, name: str) -> FeatureFlagRecord | None: ...
109
+
110
+ @abstractmethod
111
+ async def get_map(self) -> dict[str, FeatureFlagRecord]:
112
+ """Every flag by name."""
113
+
114
+ @abstractmethod
115
+ async def put(self, name: str, record: FeatureFlagRecord) -> None:
116
+ """Create or overwrite the flag."""
117
+
118
+ @abstractmethod
119
+ async def delete(self, name: str) -> bool:
120
+ """False when there was no such flag."""
121
+
122
+ async def rename(self, old_name: str, new_name: str, record: FeatureFlagRecord) -> None:
123
+ """Write the flag under `new_name` and drop `old_name`; atomic where the storage allows it."""
124
+ await self.put(new_name, record)
125
+ await self.delete(old_name)
126
+
127
+
128
+ class _CacheEntry(NamedTuple):
129
+ record: FeatureFlagRecord
130
+ expiration_time: float
131
+ failures: int # consecutive storage errors behind this entry; 0 when it was read
132
+
133
+
134
+ class FeatureFlags:
135
+ """
136
+ Feature flags read through a `FeatureFlagStorage`, with a per-process cache.
137
+
138
+ Each flag is on or off, has a proportion for gradual rollouts and a payload for arbitrary data. Records are
139
+ cached for `base_ttl` plus a random jitter so the storage is not read on every call. While the storage
140
+ fails the last known record (or the defaults, for a flag never read) is served, re-read after `ERROR_TTL`
141
+ and then with an exponential backoff up to `base_ttl`.
142
+
143
+ `is_enabled` is the flag's switch and its proportion in one answer: off for everyone when the flag is off,
144
+ on for the `proportion` of the readers when it is on (a kill-switch is a flag with proportion 1.0). With an
145
+ `idempotent_key` (a user id, an account id) the split is repeatable: every call with the same key lands on
146
+ the same side, so a rollout is a consistent group. Without one it is random per call.
147
+ `get_payload` is the flag's payload as stored; its shape is the application's business, parse it there.
148
+
149
+ Example:
150
+ feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
151
+
152
+ if await feature_flags.is_enabled('new_checkout'): # proportion 1.0: on or off for everyone
153
+ ...
154
+ if await feature_flags.is_enabled('new_ranking', user_id): # on for `proportion` of the users
155
+ ...
156
+ if await feature_flags.is_enabled('email_provider_block'):
157
+ rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
158
+ """
159
+
160
+ def __init__(self, storage: FeatureFlagStorage, base_ttl: int = BASE_TTL) -> None:
161
+ self.storage = storage
162
+ self.base_ttl = base_ttl
163
+ self._cache: dict[str, _CacheEntry] = {}
164
+
165
+ async def is_enabled(self, name: str, idempotent_key: Stringable | None = None) -> bool:
166
+ """
167
+ Whether the flag is on for this reader: the stored switch is on and the reader falls into the
168
+ `proportion`. A missing flag is off. `idempotent_key` (a user id, an account id) makes the split
169
+ repeatable: the key is hashed into a bucket of the flag, so the same key always lands on the same side
170
+ and a rollout is a consistent group, not a coin flip per call. Without a key the decision is random on
171
+ every call.
172
+ """
173
+ record = await self._get_record(name)
174
+ return record.enabled and self._in_proportion(name, idempotent_key, record.proportion)
175
+
176
+ async def get_payload(self, name: str) -> Mapping[str, Any]:
177
+ """The payload of the flag as stored, empty for a missing flag; check `is_enabled` first."""
178
+ return (await self._get_record(name)).payload
179
+
180
+ @staticmethod
181
+ def _in_proportion(name: str, idempotent_key: Stringable | None, proportion: float) -> bool:
182
+ if idempotent_key is None:
183
+ return random.random() < proportion
184
+ # The flag name is part of the hash, so one user is not in the first N% of every flag at once
185
+ digest = hashlib.blake2b(f'{name}:{idempotent_key}'.encode(), digest_size=4).digest()
186
+ return int.from_bytes(digest, 'big') / _BUCKETS < proportion
187
+
188
+ async def _get_record(self, name: str) -> FeatureFlagRecord:
189
+ entry = self._cache.get(name)
190
+ now = time.time()
191
+ if entry is not None and now < entry.expiration_time:
192
+ return entry.record
193
+
194
+ try:
195
+ record = await self.storage.get(name)
196
+ except FeatureFlagStorageError as e:
197
+ # Keep serving the last known record (or the defaults) and retry with a backoff
198
+ failures = entry.failures + 1 if entry is not None else 1
199
+ record = entry.record if entry is not None else FeatureFlagRecord()
200
+ ttl = min(ERROR_TTL * 2 ** (failures - 1), self.base_ttl)
201
+ logger.error(
202
+ {
203
+ 'message': 'FEATURE_FLAGS: Storage error, serving the last known record',
204
+ 'flag_name': name,
205
+ 'retry_in': ttl,
206
+ 'error': repr(e.__cause__ or e),
207
+ }
208
+ )
209
+ else:
210
+ failures = 0
211
+ record = record if record is not None else FeatureFlagRecord()
212
+ ttl = self.base_ttl + random.randint(0, JITTER)
213
+
214
+ self._cache[name] = _CacheEntry(record, now + ttl, failures)
215
+ return record
216
+
217
+
218
+ __all__ = (
219
+ 'BASE_TTL',
220
+ 'DEFAULT_PROPORTION',
221
+ 'ERROR_TTL',
222
+ 'FeatureFlagRecord',
223
+ 'FeatureFlagStorage',
224
+ 'FeatureFlagStorageError',
225
+ 'FeatureFlags',
226
+ 'Stringable',
227
+ )
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "ddutils"
3
3
  description = "Domain Driven Utils Library"
4
- version = "0.3.1"
4
+ version = "0.3.2"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
7
7
  readme = "README.md"
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "ddutils"
3
3
  description = "Domain Driven Utils Library"
4
- version = "0.3.1"
4
+ version = "0.3.2"
5
5
  authors = [{ name = "davyddd" }]
6
6
  license = "MIT"
7
7
  license-files = ["LICENSE"]
File without changes
File without changes
File without changes
File without changes