braincraft 1.0.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.
braincraft/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ braincraft - A workshop of small, sharp utilities - carefully shaped helpers
3
+ you reuse across projects to keep everyday coding tasks fast, tidy, and consistent.
4
+
5
+ :author: Ron Webb
6
+ :since: 1.0.0
7
+ """
8
+
9
+ __version__ = "1.0.0"
10
+
11
+ from braincraft.retry import retry_rand_exp
12
+
13
+ __all__ = ["retry_rand_exp"]
braincraft/retry.py ADDED
@@ -0,0 +1,86 @@
1
+ """
2
+ braincraft.retry - Retry utilities with exponential back-off and full jitter.
3
+
4
+ Provides a generic async retry helper and a function that computes the next
5
+ sleep interval using the "Full Jitter" algorithm described in the AWS
6
+ Architecture Blog (exponential back-off + full random jitter).
7
+
8
+ :author: Ron Webb
9
+ :since: 1.0.0
10
+ """
11
+
12
+ import asyncio
13
+ import random
14
+ from collections.abc import Callable, Coroutine
15
+ from typing import Any
16
+
17
+ from logenrich import setup_logger
18
+
19
+ _logger = setup_logger(__name__)
20
+
21
+
22
+ def _compute_delay(attempt: int, base_delay: float, max_delay: float) -> float:
23
+ """Computes the next sleep interval using full-jitter exponential back-off.
24
+
25
+ The formula is: ``random.uniform(0, min(max_delay, base_delay * 2 ** attempt))``.
26
+
27
+ :param attempt: Zero-based attempt index (0 = first retry).
28
+ :param base_delay: Initial delay in seconds before jitter is applied.
29
+ :param max_delay: Upper cap in seconds for the computed sleep interval.
30
+ :return: A non-negative float representing the number of seconds to sleep.
31
+ """
32
+ ceiling = min(max_delay, base_delay * (2**attempt))
33
+ return random.uniform(0, ceiling)
34
+
35
+
36
+ async def retry_rand_exp[T]( # pylint: disable=invalid-name
37
+ func: Callable[..., Coroutine[Any, Any, T]],
38
+ *args: Any,
39
+ max_attempts: int,
40
+ base_delay: float,
41
+ max_delay: float,
42
+ **kwargs: Any,
43
+ ) -> T:
44
+ """Calls an async coroutine function with retry and exponential-jitter back-off.
45
+
46
+ Retries on any :class:`Exception` up to *max_attempts* times. After each
47
+ failure the caller sleeps for a jittered duration before the next attempt.
48
+ If all attempts are exhausted the last exception is re-raised.
49
+
50
+ :param func: Async callable to invoke.
51
+ :param args: Positional arguments forwarded to *func*.
52
+ :param max_attempts: Total number of attempts (must be >= 1).
53
+ :param base_delay: Base delay in seconds used for back-off calculation.
54
+ :param max_delay: Maximum sleep duration cap in seconds.
55
+ :param kwargs: Keyword arguments forwarded to *func*.
56
+ :return: The return value of a successful *func* invocation.
57
+ :raises ValueError: If *max_attempts* is less than 1.
58
+ :raises Exception: Re-raises the last exception when all attempts fail.
59
+ """
60
+ if max_attempts < 1:
61
+ raise ValueError(f"max_attempts must be >= 1, got {max_attempts}")
62
+ last_exc: Exception | None = None
63
+ for attempt in range(max_attempts):
64
+ try:
65
+ return await func(*args, **kwargs)
66
+ except Exception as exc: # pylint: disable=broad-exception-caught
67
+ last_exc = exc
68
+ if attempt < max_attempts - 1:
69
+ delay = _compute_delay(attempt, base_delay, max_delay)
70
+ _logger.warning(
71
+ "Attempt %d/%d failed (%s). Retrying in %.2fs.",
72
+ attempt + 1,
73
+ max_attempts,
74
+ exc,
75
+ delay,
76
+ )
77
+ await asyncio.sleep(delay)
78
+ else:
79
+ _logger.error(
80
+ "Attempt %d/%d failed (%s). No more retries.",
81
+ attempt + 1,
82
+ max_attempts,
83
+ exc,
84
+ )
85
+ assert last_exc is not None # guaranteed when max_attempts >= 1
86
+ raise last_exc
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: braincraft
3
+ Version: 1.0.0
4
+ Summary: A workshop of small, sharp utilities - carefully shaped helpers you reuse across projects to keep everyday coding tasks fast, tidy, and consistent.
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 Ron Webb
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ License-File: LICENSE
27
+ Author: Ron Webb
28
+ Requires-Python: >=3.14
29
+ Classifier: License :: Other/Proprietary License
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: Programming Language :: Python :: 3.14
32
+ Requires-Dist: logenrich (>=1.0.1,<2.0.0)
33
+ Description-Content-Type: text/markdown
34
+
35
+ # braincraft
36
+
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
38
+ [![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)](CHANGELOG.md)
39
+
40
+ A workshop of small, sharp utilities - carefully shaped helpers you reuse across projects to keep everyday coding tasks fast, tidy, and consistent.
41
+
42
+ ## Requirements
43
+
44
+ - Python `>=3.14`
45
+
46
+ ## Usage
47
+
48
+ ### `retry_rand_exp`
49
+
50
+ Calls an async coroutine with automatic retry and full-jitter exponential back-off.
51
+ Retries on any exception up to `max_attempts` times, sleeping a random jittered
52
+ duration between attempts. Re-raises the last exception when all attempts are exhausted.
53
+
54
+ ```python
55
+ from braincraft import retry_rand_exp
56
+
57
+ async def fetch_data(url: str) -> str:
58
+ # your async operation here
59
+ ...
60
+
61
+ result = await retry_rand_exp(
62
+ fetch_data,
63
+ "https://example.com/api",
64
+ max_attempts=5,
65
+ base_delay=1.0,
66
+ max_delay=30.0,
67
+ )
68
+ ```
69
+
70
+ ## Development
71
+
72
+ ### Prerequisites
73
+
74
+ - [Poetry](https://python-poetry.org/) `2.2+`
75
+
76
+ ### Install dependencies
77
+
78
+ ```bash
79
+ poetry install
80
+ ```
81
+
82
+ ### Format and lint
83
+
84
+ ```bash
85
+ poetry run black braincraft; poetry run pylint braincraft
86
+ ```
87
+
88
+ ### Run tests with coverage
89
+
90
+ ```bash
91
+ poetry run pytest --cov=braincraft tests --cov-report html
92
+ ```
93
+
94
+ ## Changelog
95
+
96
+ See [CHANGELOG.md](CHANGELOG.md) for a full history of changes.
97
+
98
+ ## License
99
+
100
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
101
+
@@ -0,0 +1,6 @@
1
+ braincraft/__init__.py,sha256=s7D2bzZyOWvTPBfVYU5gWgT8rzEwM-KdBaPlxw295zI,313
2
+ braincraft/retry.py,sha256=HXrov2fdCJ8YGOhBDbd4Zkv9WZZxJAxfG5c2MVu9VU4,3385
3
+ braincraft-1.0.0.dist-info/licenses/LICENSE,sha256=2cmui6TBSfJF5E2Qr0xNS8x4ZY0grz8qLEBEW1CgpjA,1086
4
+ braincraft-1.0.0.dist-info/METADATA,sha256=_a0SuHlN5SfOjiLjmlw1AFdHYK54IaYY4KlrsElhAro,3194
5
+ braincraft-1.0.0.dist-info/WHEEL,sha256=Vz2fHgx6HFtSwhs8KvkHLqH5Ea4w1_rner5uNVGCeIE,88
6
+ braincraft-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.3.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ron Webb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.