|
| 1 | +""" |
| 2 | +Minimal CPython threading timeout helper. |
| 3 | +
|
| 4 | +This replaces the small subset of ``stopit`` used by the validator workflow. |
| 5 | +``stopit`` imports ``pkg_resources`` at module import time, and that module was |
| 6 | +removed from setuptools 82.0.0. |
| 7 | +""" |
| 8 | + |
| 9 | +import ctypes |
| 10 | +import threading |
| 11 | + |
| 12 | + |
| 13 | +class TimeoutException(Exception): |
| 14 | + """Raised when a code block exceeds the allowed timeout.""" |
| 15 | + |
| 16 | + |
| 17 | +def _async_raise(thread_id, exception_type): |
| 18 | + result = ctypes.pythonapi.PyThreadState_SetAsyncExc( |
| 19 | + ctypes.c_long(thread_id), ctypes.py_object(exception_type) |
| 20 | + ) |
| 21 | + if result == 0: |
| 22 | + raise ValueError(f"Invalid thread ID {thread_id}") |
| 23 | + if result > 1: |
| 24 | + ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), None) |
| 25 | + raise SystemError("PyThreadState_SetAsyncExc failed") |
| 26 | + |
| 27 | + |
| 28 | +class ThreadingTimeout: |
| 29 | + EXECUTED, EXECUTING, TIMED_OUT, INTERRUPTED, CANCELED = range(5) |
| 30 | + |
| 31 | + def __init__(self, seconds, swallow_exc=True): |
| 32 | + self.seconds = seconds |
| 33 | + self.swallow_exc = swallow_exc |
| 34 | + self.state = self.EXECUTED |
| 35 | + self._target_tid = threading.current_thread().ident |
| 36 | + self._timer = None |
| 37 | + |
| 38 | + def __bool__(self): |
| 39 | + return self.state in (self.EXECUTED, self.EXECUTING, self.CANCELED) |
| 40 | + |
| 41 | + __nonzero__ = __bool__ |
| 42 | + |
| 43 | + def __enter__(self): |
| 44 | + self.state = self.EXECUTING |
| 45 | + self._timer = threading.Timer(self.seconds, self._trigger_timeout) |
| 46 | + self._timer.start() |
| 47 | + return self |
| 48 | + |
| 49 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 50 | + if exc_type is TimeoutException: |
| 51 | + if self.state != self.TIMED_OUT: |
| 52 | + self.state = self.INTERRUPTED |
| 53 | + self._cancel_timer() |
| 54 | + return self.swallow_exc |
| 55 | + |
| 56 | + if exc_type is None: |
| 57 | + self.state = self.EXECUTED |
| 58 | + |
| 59 | + self._cancel_timer() |
| 60 | + return False |
| 61 | + |
| 62 | + def cancel(self): |
| 63 | + self.state = self.CANCELED |
| 64 | + self._cancel_timer() |
| 65 | + |
| 66 | + def _cancel_timer(self): |
| 67 | + if self._timer is not None: |
| 68 | + self._timer.cancel() |
| 69 | + |
| 70 | + def _trigger_timeout(self): |
| 71 | + self.state = self.TIMED_OUT |
| 72 | + _async_raise(self._target_tid, TimeoutException) |
0 commit comments