Skip to content

Commit

Permalink
Critical tasks now cause the app to exit, instead of letting it conti…
Browse files Browse the repository at this point in the history
…nue with broken functionality
  • Loading branch information
DevilXD committed Jul 16, 2024
1 parent f32c8f2 commit 016955c
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 19 deletions.
11 changes: 5 additions & 6 deletions twitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ async def _watch_sleep(self, delay: float) -> None:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._watching_restart.wait(), timeout=delay)

@task_wrapper
@task_wrapper(critical=True)
async def _watch_loop(self) -> NoReturn:
interval: float = WATCH_INTERVAL.total_seconds()
while True:
Expand Down Expand Up @@ -898,7 +898,7 @@ async def _watch_loop(self) -> NoReturn:
logger.log(CALL, "No active drop could be determined")
await self._watch_sleep(interval)

@task_wrapper
@task_wrapper(critical=True)
async def _maintenance_task(self) -> None:
claim_period = timedelta(minutes=30)
max_period = timedelta(hours=1)
Expand All @@ -911,10 +911,9 @@ async def _maintenance_task(self) -> None:
break
next_trigger = min(now + claim_period, next_period)
trigger_cleanup = False
while self._mnt_triggers and (switch_trigger := self._mnt_triggers[0]) <= next_trigger:
while self._mnt_triggers and self._mnt_triggers[0] <= next_trigger:
next_trigger = self._mnt_triggers.popleft()
trigger_cleanup = True
self._mnt_triggers.popleft()
next_trigger = switch_trigger
if next_trigger == next_period:
trigger_type: str = "Reload"
elif trigger_cleanup:
Expand Down Expand Up @@ -943,7 +942,7 @@ async def _maintenance_task(self) -> None:
await watching_channel.claim_bonus()
except Exception:
pass # we intentionally silently skip anything else
# this triggers this task restart every (up to) 60 minutes
# this triggers a restart of this task every (up to) 60 minutes
logger.log(CALL, "Maintenance task requests a reload")
self.change_state(State.INVENTORY_FETCH)

Expand Down
42 changes: 30 additions & 12 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,18 +131,36 @@ def deduplicate(iterable: abc.Iterable[_T]) -> list[_T]:


def task_wrapper(
afunc: abc.Callable[_P, abc.Coroutine[Any, Any, _T]]
) -> abc.Callable[_P, abc.Coroutine[Any, Any, _T]]:
@wraps(afunc)
async def wrapper(*args: _P.args, **kwargs: _P.kwargs):
try:
await afunc(*args, **kwargs)
except (ExitRequest, ReloadRequest):
pass
except Exception:
logger.exception(f"Exception in {afunc.__name__} task")
raise # raise up to the wrapping task
return wrapper
afunc: abc.Callable[_P, abc.Coroutine[Any, Any, _T]] | None = None, *, critical: bool = False
):
def decorator(
afunc: abc.Callable[_P, abc.Coroutine[Any, Any, _T]]
) -> abc.Callable[_P, abc.Coroutine[Any, Any, _T]]:
@wraps(afunc)
async def wrapper(*args: _P.args, **kwargs: _P.kwargs):
try:
await afunc(*args, **kwargs)
except (ExitRequest, ReloadRequest):
pass
except Exception:
logger.exception(f"Exception in {afunc.__name__} task")
if critical:
# critical task's death should trigger a termination.
# there isn't an easy and sure way to obtain the Twitch instance here,
# but we can improvise finding it
from twitch import Twitch # cyclic import
probe = args and args[0] or None # extract from 'self' arg
if isinstance(probe, Twitch):
probe.close()
elif probe is not None:
probe = getattr(probe, "_twitch", None) # extract from '_twitch' attr
if isinstance(probe, Twitch):
probe.close()
raise # raise up to the wrapping task
return wrapper
if afunc is None:
return decorator
return decorator(afunc)


def invalidate_cache(instance, *attrnames):
Expand Down
2 changes: 1 addition & 1 deletion websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ async def _backoff_connect(
)
break

@task_wrapper
@task_wrapper(critical=True)
async def _handle(self):
# ensure we're logged in before connecting
self.set_status(_("gui", "websocket", "initializing"))
Expand Down

0 comments on commit 016955c

Please sign in to comment.