Skip to content

Commit 31d060c

Browse files
committed
Add fix for timeout()
timeout function, if given a bad timeout bound (zero or less), could run forever.
1 parent 598a84b commit 31d060c

1 file changed

Lines changed: 21 additions & 5 deletions

File tree

popper/util.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import NamedTuple
1010
from time import perf_counter
1111
from contextlib import contextmanager
12+
from typing import Any, Callable, Dict, Iterable, Optional, Set, Tuple, TypeVar
1213

1314
class Literal(NamedTuple):
1415
predicate: str
@@ -68,27 +69,42 @@ def parse_args():
6869

6970
return parser.parse_args()
7071

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]:
7281
result = None
73-
class TimeoutError(Exception):
74-
pass
82+
if kwargs is None:
83+
kwargs = {}
7584

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:
7790
raise TimeoutError()
7891

7992
# set the timeout handler
8093
signal.signal(signal.SIGALRM, handler)
8194
signal.alarm(timeout_duration)
8295
try:
8396
result = func(*args, **kwargs)
84-
except TimeoutError as _exc:
97+
except TimeoutError:
8598
settings.logger.warn(f'TIMEOUT OF {int(settings.timeout)} SECONDS EXCEEDED')
8699
return result
100+
# I'm not sure why we claim that there's a timeout issue here
87101
except AttributeError as moo:
88102
if '_SolveEventHandler' in str(moo):
89103
settings.logger.warn(f'TIMEOUT OF {int(settings.timeout)} SECONDS EXCEEDED')
90104
return result
91105
raise moo
106+
else:
107+
settings.logger.info('Normal termination of timeout block with result %s', result)
92108
finally:
93109
signal.alarm(0)
94110

0 commit comments

Comments
 (0)