|
7 | 7 | import uuid
|
8 | 8 | from collections.abc import Callable, Generator
|
9 | 9 | from contextlib import contextmanager
|
| 10 | +from dataclasses import dataclass |
10 | 11 | from functools import wraps
|
| 12 | +from inspect import signature |
11 | 13 | from pathlib import Path
|
12 |
| -from typing import ParamSpec, TypeVar |
| 14 | +from typing import Any, ParamSpec, TypeVar |
13 | 15 |
|
14 | 16 | from nicegui import run
|
15 | 17 |
|
@@ -143,3 +145,37 @@ def tear_down() -> None:
|
143 | 145 | _kill(process)
|
144 | 146 | running_sh_processes.clear()
|
145 | 147 | log.info('teardown complete.')
|
| 148 | + |
| 149 | + |
| 150 | +@dataclass(slots=True, kw_only=True, frozen=True) |
| 151 | +class OnFailedArguments: |
| 152 | + attempt: int |
| 153 | + max_attempts: int |
| 154 | + |
| 155 | + |
| 156 | +async def retry(func: Callable, *, |
| 157 | + max_attempts: int = 3, |
| 158 | + max_timeout: float | None = None, |
| 159 | + on_failed: Callable | None = None) -> Any: |
| 160 | + """Call a function repeatedly until it succeeds or reaches the maximum number of attempts. |
| 161 | +
|
| 162 | + :param func: A function to retry |
| 163 | + :param max_attempts: Maximum number of attempts |
| 164 | + :param max_timeout: Optional maximum time in seconds to wait per attempt |
| 165 | + :param on_failed: Optional callback to execute after each failed attempt (optional argument of type ``OnFailedArguments``) |
| 166 | + :return: Result of the called function |
| 167 | + :raises RuntimeError: If all attempts fail |
| 168 | + """ |
| 169 | + for attempt in range(max_attempts): |
| 170 | + try: |
| 171 | + return await asyncio.wait_for(func(), timeout=max_timeout) |
| 172 | + except Exception: |
| 173 | + if on_failed is None: |
| 174 | + continue |
| 175 | + if signature(on_failed).parameters: |
| 176 | + result = on_failed(OnFailedArguments(attempt=attempt, max_attempts=max_attempts)) |
| 177 | + else: |
| 178 | + result = on_failed() |
| 179 | + if asyncio.iscoroutinefunction(on_failed): |
| 180 | + await result |
| 181 | + raise RuntimeError(f'Running {func.__name__} failed.') |
0 commit comments