ddutils 0.3.0__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.0
3
+ Version: 0.3.2
4
4
  Summary: Domain Driven Utils Library
5
5
  Keywords: python,ddutils
6
6
  Author: davyddd
@@ -519,6 +519,97 @@ that planted a key would be inherited by every request task, making all requests
519
519
  same reason the key is not reset when the block ends, so `scope()` must be entered in a task that does not
520
520
  outlive the block (a request handler, an actor run).
521
521
 
522
+ ## Connections
523
+
524
+ `ddutils.connections` sits between a `ScopedRegistry` and the code that uses a connection: a query, a cache
525
+ lookup, a Kafka send. A registry holds one connection per scope: a pooled client per process, a session
526
+ per task. The connections module adds two things on top:
527
+
528
+ - `ConnectionManagerFactory(registries, default, connection_manager_class=ConnectionManager)` resolves a
529
+ connection alias to its registry, like Django's `using`. Calling it opens a connection manager on the
530
+ chosen registry; `registry(alias)` returns the registry itself; `close()` clears every registry for the
531
+ current scope, calling the connection's destructor, which is the shutdown hook of process-scoped clients.
532
+ - `ConnectionManager(registry)` is the default connection manager: an async context manager that hands out
533
+ the connection of the registry's current scope and releases nothing on exit. Enough for clients that are
534
+ pools themselves, such as ClickHouse, Redis or a Kafka producer.
535
+
536
+ Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
537
+ or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
538
+
539
+ ```python
540
+ import os
541
+ from enum import Enum
542
+
543
+ from ddutils.connections import ConnectionManagerFactory
544
+ from ddutils.scoped_registry import ScopedRegistry
545
+
546
+
547
+ class ClickhouseDB(str, Enum):
548
+ PRIMARY = 'primary'
549
+
550
+
551
+ client_registries = {
552
+ db: ScopedRegistry(create_func=make_client_for(db), scope_func=os.getpid, destructor_method_name='close')
553
+ for db in ClickhouseDB
554
+ }
555
+ clickhouse = ConnectionManagerFactory(client_registries, default=ClickhouseDB.PRIMARY)
556
+
557
+
558
+ async with clickhouse() as client:
559
+ result = await client.query(sql)
560
+
561
+
562
+ # a transactional database: `Atomic` is your unit of work over `registry.scope()`
563
+ atomic = ConnectionManagerFactory(session_registries, default=PostgresDB.PRIMARY, connection_manager_class=Atomic)
564
+
565
+
566
+ async with atomic(alias=PostgresDB.REPLICA) as session:
567
+ ...
568
+
569
+
570
+ # on shutdown: closes the clients of every alias that was used in this process
571
+ await clickhouse.close()
572
+ ```
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
+
522
613
  ## Function Exception Extraction
523
614
 
524
615
  AST-based introspection for extracting exceptions from function source code.
@@ -501,6 +501,97 @@ that planted a key would be inherited by every request task, making all requests
501
501
  same reason the key is not reset when the block ends, so `scope()` must be entered in a task that does not
502
502
  outlive the block (a request handler, an actor run).
503
503
 
504
+ ## Connections
505
+
506
+ `ddutils.connections` sits between a `ScopedRegistry` and the code that uses a connection: a query, a cache
507
+ lookup, a Kafka send. A registry holds one connection per scope: a pooled client per process, a session
508
+ per task. The connections module adds two things on top:
509
+
510
+ - `ConnectionManagerFactory(registries, default, connection_manager_class=ConnectionManager)` resolves a
511
+ connection alias to its registry, like Django's `using`. Calling it opens a connection manager on the
512
+ chosen registry; `registry(alias)` returns the registry itself; `close()` clears every registry for the
513
+ current scope, calling the connection's destructor, which is the shutdown hook of process-scoped clients.
514
+ - `ConnectionManager(registry)` is the default connection manager: an async context manager that hands out
515
+ the connection of the registry's current scope and releases nothing on exit. Enough for clients that are
516
+ pools themselves, such as ClickHouse, Redis or a Kafka producer.
517
+
518
+ Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
519
+ or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
520
+
521
+ ```python
522
+ import os
523
+ from enum import Enum
524
+
525
+ from ddutils.connections import ConnectionManagerFactory
526
+ from ddutils.scoped_registry import ScopedRegistry
527
+
528
+
529
+ class ClickhouseDB(str, Enum):
530
+ PRIMARY = 'primary'
531
+
532
+
533
+ client_registries = {
534
+ db: ScopedRegistry(create_func=make_client_for(db), scope_func=os.getpid, destructor_method_name='close')
535
+ for db in ClickhouseDB
536
+ }
537
+ clickhouse = ConnectionManagerFactory(client_registries, default=ClickhouseDB.PRIMARY)
538
+
539
+
540
+ async with clickhouse() as client:
541
+ result = await client.query(sql)
542
+
543
+
544
+ # a transactional database: `Atomic` is your unit of work over `registry.scope()`
545
+ atomic = ConnectionManagerFactory(session_registries, default=PostgresDB.PRIMARY, connection_manager_class=Atomic)
546
+
547
+
548
+ async with atomic(alias=PostgresDB.REPLICA) as session:
549
+ ...
550
+
551
+
552
+ # on shutdown: closes the clients of every alias that was used in this process
553
+ await clickhouse.close()
554
+ ```
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
+
504
595
  ## Function Exception Extraction
505
596
 
506
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,81 @@
1
+ from collections.abc import Callable, Hashable, Mapping
2
+ from typing import Any, Generic, TypeVar
3
+
4
+ from ddutils.scoped_registry import ScopedRegistry
5
+
6
+ # The name a connection is registered under and selected by, like Django's `using` alias
7
+ ConnectionAliasT = TypeVar('ConnectionAliasT', bound=Hashable)
8
+ # The object a registry holds for a connection: a pooled client, a session
9
+ ConnectionT = TypeVar('ConnectionT')
10
+ # The context manager the factory opens on the chosen registry
11
+ ConnectionManagerT = TypeVar('ConnectionManagerT')
12
+
13
+
14
+ class ConnectionManager(Generic[ConnectionT]):
15
+ """
16
+ Default connection manager: hands out the connection of the registry's current scope and releases nothing on exit.
17
+
18
+ The connection is created on first use via `registry.set()` and kept for the life of its scope,
19
+ typically a process, since a client is itself a connection pool (ClickHouse, Redis, a Kafka producer). Databases
20
+ with transactions need their own connection manager on top of the registry, e.g. a unit of work that begins,
21
+ commits and closes a session on exit.
22
+ """
23
+
24
+ def __init__(self, registry: ScopedRegistry[ConnectionT]) -> None:
25
+ self._registry = registry
26
+
27
+ async def __aenter__(self) -> ConnectionT:
28
+ return await self._registry.set()
29
+
30
+ async def __aexit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> None:
31
+ return None
32
+
33
+
34
+ class ConnectionManagerFactory(Generic[ConnectionAliasT, ConnectionT, ConnectionManagerT]):
35
+ """
36
+ Resolves a connection alias to its registry and opens a connection manager on it, like Django's `using`.
37
+
38
+ `connection_manager_class` is the context manager opened on the chosen registry: `ConnectionManager` by
39
+ default, a project class for anything that needs setup and teardown around the connection (transactions):
40
+
41
+ clickhouse = ConnectionManagerFactory(client_registries, default=ClickhouseAlias.PRIMARY)
42
+ atomic = ConnectionManagerFactory(session_registries, default=PostgresAlias.PRIMARY, connection_manager_class=Atomic)
43
+
44
+ async with clickhouse() as client: ...
45
+ async with atomic(alias=PostgresAlias.REPLICA) as session: ...
46
+ await clickhouse.close() # on shutdown
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ registries: Mapping[ConnectionAliasT, ScopedRegistry[ConnectionT]],
52
+ default: ConnectionAliasT,
53
+ connection_manager_class: Callable[[ScopedRegistry[ConnectionT]], ConnectionManagerT] = ConnectionManager, # type: ignore[assignment]
54
+ ) -> None:
55
+ if default not in registries:
56
+ raise ValueError(f'Default connection {default!r} is not among the registries')
57
+ self.registries = registries
58
+ self.default = default
59
+ self.connection_manager_class = connection_manager_class
60
+
61
+ def registry(self, alias: Hashable | None = None) -> ScopedRegistry[ConnectionT]:
62
+ """The registry of `alias`, or of the default connection; `Hashable` because `Adapter.alias` is untyped."""
63
+ alias = self.default if alias is None else alias
64
+ if alias not in self.registries:
65
+ raise KeyError(f'Unknown connection {alias!r}; expected one of {list(self.registries)!r}')
66
+ return self.registries[alias] # type: ignore[index]
67
+
68
+ def __call__(self, alias: Hashable | None = None) -> ConnectionManagerT:
69
+ return self.connection_manager_class(self.registry(alias))
70
+
71
+ async def close(self) -> None:
72
+ """
73
+ Clears every registry for the current scope, calling the connection's destructor: the shutdown hook of
74
+ a process-scoped client (a pool, a producer with a buffer to flush). A registry without a connection in
75
+ the current scope is left alone, so the hook is safe to call for aliases that were never used.
76
+ """
77
+ for registry in self.registries.values():
78
+ await registry.clear()
79
+
80
+
81
+ __all__ = ('ConnectionManager', 'ConnectionManagerFactory')
@@ -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.0"
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.0"
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