|
| 1 | +# Copyright (C) 2025 Robotec.AI |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import signal |
| 16 | +from functools import wraps |
| 17 | +from typing import Any, Callable, TypeVar |
| 18 | + |
| 19 | +F = TypeVar("F", bound=Callable[..., Any]) |
| 20 | + |
| 21 | + |
| 22 | +class TimeoutError(Exception): |
| 23 | + """Raised when an operation times out.""" |
| 24 | + |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +def timeout(seconds: float, timeout_message: str = None) -> Callable[[F], F]: |
| 29 | + """ |
| 30 | + Decorator that adds timeout functionality to a function. |
| 31 | +
|
| 32 | + Parameters |
| 33 | + ---------- |
| 34 | + seconds : float |
| 35 | + Timeout duration in seconds |
| 36 | + timeout_message : str, optional |
| 37 | + Custom timeout message. If not provided, a default message will be used. |
| 38 | +
|
| 39 | + Returns |
| 40 | + ------- |
| 41 | + Callable |
| 42 | + Decorated function with timeout functionality |
| 43 | +
|
| 44 | + Raises |
| 45 | + ------ |
| 46 | + TimeoutError |
| 47 | + When the decorated function exceeds the specified timeout |
| 48 | +
|
| 49 | + Examples |
| 50 | + -------- |
| 51 | + >>> @timeout(5.0, "Operation timed out") |
| 52 | + ... def slow_operation(): |
| 53 | + ... import time |
| 54 | + ... time.sleep(10) |
| 55 | + ... return "Done" |
| 56 | + >>> |
| 57 | + >>> try: |
| 58 | + ... result = slow_operation() |
| 59 | + ... except TimeoutError as e: |
| 60 | + ... print(f"Timeout: {e}") |
| 61 | + """ |
| 62 | + |
| 63 | + def decorator(func: F) -> F: |
| 64 | + @wraps(func) |
| 65 | + def wrapper(*args, **kwargs): |
| 66 | + def timeout_handler(signum, frame): |
| 67 | + message = ( |
| 68 | + timeout_message |
| 69 | + or f"Function '{func.__name__}' timed out after {seconds} seconds" |
| 70 | + ) |
| 71 | + raise TimeoutError(message) |
| 72 | + |
| 73 | + # Set up timeout |
| 74 | + old_handler = signal.signal(signal.SIGALRM, timeout_handler) |
| 75 | + signal.alarm(int(seconds)) |
| 76 | + |
| 77 | + try: |
| 78 | + return func(*args, **kwargs) |
| 79 | + finally: |
| 80 | + # Clean up timeout |
| 81 | + signal.alarm(0) |
| 82 | + signal.signal(signal.SIGALRM, old_handler) |
| 83 | + |
| 84 | + return wrapper |
| 85 | + |
| 86 | + return decorator |
| 87 | + |
| 88 | + |
| 89 | +def timeout_method(seconds: float, timeout_message: str = None) -> Callable[[F], F]: |
| 90 | + """ |
| 91 | + Decorator that adds timeout functionality to a method. |
| 92 | + Similar to timeout but designed for class methods. |
| 93 | +
|
| 94 | + Parameters |
| 95 | + ---------- |
| 96 | + seconds : float |
| 97 | + Timeout duration in seconds |
| 98 | + timeout_message : str, optional |
| 99 | + Custom timeout message. If not provided, a default message will be used. |
| 100 | +
|
| 101 | + Returns |
| 102 | + ------- |
| 103 | + Callable |
| 104 | + Decorated method with timeout functionality |
| 105 | +
|
| 106 | + Examples |
| 107 | + -------- |
| 108 | + >>> class MyClass: |
| 109 | + ... @timeout_method(3.0, "Method timed out") |
| 110 | + ... def slow_method(self): |
| 111 | + ... import time |
| 112 | + ... time.sleep(5) |
| 113 | + ... return "Done" |
| 114 | + """ |
| 115 | + |
| 116 | + def decorator(func: F) -> F: |
| 117 | + @wraps(func) |
| 118 | + def wrapper(self, *args, **kwargs): |
| 119 | + def timeout_handler(signum, frame): |
| 120 | + message = ( |
| 121 | + timeout_message |
| 122 | + or f"Method '{func.__name__}' of {self.__class__.__name__} timed out after {seconds} seconds" |
| 123 | + ) |
| 124 | + raise TimeoutError(message) |
| 125 | + |
| 126 | + # Set up timeout |
| 127 | + old_handler = signal.signal(signal.SIGALRM, timeout_handler) |
| 128 | + signal.alarm(int(seconds)) |
| 129 | + |
| 130 | + try: |
| 131 | + return func(self, *args, **kwargs) |
| 132 | + finally: |
| 133 | + # Clean up timeout |
| 134 | + signal.alarm(0) |
| 135 | + signal.signal(signal.SIGALRM, old_handler) |
| 136 | + |
| 137 | + return wrapper |
| 138 | + |
| 139 | + return decorator |
0 commit comments