Decorator to add timeout to functions Args: seconds: Maximum number of seconds the function can run
(seconds: int)
| 53 | |
| 54 | |
| 55 | def timeout(seconds: int): |
| 56 | """Decorator to add timeout to functions |
| 57 | |
| 58 | Args: |
| 59 | seconds: Maximum number of seconds the function can run |
| 60 | """ |
| 61 | |
| 62 | def decorator(func): |
| 63 | @functools.wraps(func) |
| 64 | def wrapper(*args, **kwargs): |
| 65 | result = [TimeoutError(f"Function {func.__name__} timed out after {seconds}s")] |
| 66 | |
| 67 | # Copy Flask request context to the new thread |
| 68 | @copy_current_request_context |
| 69 | def target(): |
| 70 | try: |
| 71 | result[0] = func(*args, **kwargs) |
| 72 | except Exception as e: |
| 73 | result[0] = e |
| 74 | |
| 75 | thread = threading.Thread(target=target) |
| 76 | thread.daemon = True |
| 77 | thread.start() |
| 78 | thread.join(timeout=seconds) |
| 79 | |
| 80 | if thread.is_alive(): |
| 81 | logger.error(f"Function {func.__name__} timed out after {seconds}s") |
| 82 | raise TimeoutError(f"Function {func.__name__} timed out after {seconds}s") |
| 83 | |
| 84 | if isinstance(result[0], Exception): |
| 85 | raise result[0] |
| 86 | |
| 87 | return result[0] |
| 88 | |
| 89 | return wrapper |
| 90 | |
| 91 | return decorator |
| 92 | |
| 93 | |
| 94 | @dataclass |
nothing calls this directly
no outgoing calls
no test coverage detected