switch utils.deadline to a context manager

This commit is contained in:
jesopo 2019-08-30 18:13:12 +01:00
parent 162aab9851
commit a57a06b1cc
2 changed files with 11 additions and 8 deletions

View file

@ -55,10 +55,10 @@ class Module(ModuleManager.BaseModule):
for_user = event["user"].nickname if self._closest_setting(event,
"sed-sender-only", False) else None
def _find():
return event["target"].buffer.find(pattern, from_self=False,
with utils.deadline():
match = event["target"].buffer.find(pattern, from_self=False,
for_user=for_user, not_pattern=REGEX_SED)
match = utils.deadline(_find)
if match:
new_message = re.sub(pattern, replace, match.line.message,
count)

View file

@ -1,4 +1,5 @@
import datetime, decimal, enum, io, ipaddress, re, signal, threading, typing
import contextlib, datetime, decimal, enum, io, ipaddress, re, signal
import threading, typing
from src.utils import cli, consts, irc, http, parse, security
class Direction(enum.Enum):
@ -348,11 +349,13 @@ class DeadlineExceededException(Exception):
def _raise_deadline():
raise DeadlineExceededException()
def deadline(f: typing.Callable[[], typing.Any], seconds: int=10) -> typing.Any:
signal.signal(signal.SIGALRM, lambda _1, _2: _raise_deadline())
@contextlib.contextmanager
def deadline(seconds: int=10):
old_handler = signal.signal(signal.SIGALRM,
lambda _1, _2: _raise_deadline())
signal.alarm(seconds)
try:
return f()
yield
finally:
signal.signal(signal.SIGALRM, signal.SIG_IGN)
signal.signal(signal.SIGALRM, old_handler)