|
9 | 9 | from typing import NamedTuple |
10 | 10 | from time import perf_counter |
11 | 11 | from contextlib import contextmanager |
| 12 | +from typing import Any, Callable, Dict, Iterable, Optional, Set, Tuple, TypeVar |
12 | 13 |
|
13 | 14 | class Literal(NamedTuple): |
14 | 15 | predicate: str |
@@ -68,27 +69,42 @@ def parse_args(): |
68 | 69 |
|
69 | 70 | return parser.parse_args() |
70 | 71 |
|
71 | | -def timeout(settings, func, args=(), kwargs={}, timeout_duration=1): |
| 72 | + |
| 73 | +T = TypeVar("T") |
| 74 | + |
| 75 | + |
| 76 | +def timeout(settings: 'Settings', |
| 77 | + func: Callable[..., T], |
| 78 | + args: Tuple[Any, ...] = (), |
| 79 | + kwargs: Optional[Dict] = None, |
| 80 | + timeout_duration: int = 1) -> Optional[T]: |
72 | 81 | result = None |
73 | | - class TimeoutError(Exception): |
74 | | - pass |
| 82 | + if kwargs is None: |
| 83 | + kwargs = {} |
75 | 84 |
|
76 | | - def handler(signum, frame): |
| 85 | + if timeout_duration <= 0: |
| 86 | + settings.logger.error("Attempting to run %s(%s) with timeout value of zero or below.", str(func), str(args)) |
| 87 | + return result |
| 88 | + |
| 89 | + def handler(signum: int, frame: Any) -> None: |
77 | 90 | raise TimeoutError() |
78 | 91 |
|
79 | 92 | # set the timeout handler |
80 | 93 | signal.signal(signal.SIGALRM, handler) |
81 | 94 | signal.alarm(timeout_duration) |
82 | 95 | try: |
83 | 96 | result = func(*args, **kwargs) |
84 | | - except TimeoutError as _exc: |
| 97 | + except TimeoutError: |
85 | 98 | settings.logger.warn(f'TIMEOUT OF {int(settings.timeout)} SECONDS EXCEEDED') |
86 | 99 | return result |
| 100 | + # I'm not sure why we claim that there's a timeout issue here |
87 | 101 | except AttributeError as moo: |
88 | 102 | if '_SolveEventHandler' in str(moo): |
89 | 103 | settings.logger.warn(f'TIMEOUT OF {int(settings.timeout)} SECONDS EXCEEDED') |
90 | 104 | return result |
91 | 105 | raise moo |
| 106 | + else: |
| 107 | + settings.logger.info('Normal termination of timeout block with result %s', result) |
92 | 108 | finally: |
93 | 109 | signal.alarm(0) |
94 | 110 |
|
|
0 commit comments