Skip to content

Commit

Permalink
Add switch for the wait_for_status
Browse files Browse the repository at this point in the history
  • Loading branch information
drew2a committed Jul 14, 2023
1 parent 75b3ca8 commit 090ae75
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from tribler.core.components.libtorrent.utils.torrent_utils import check_handle, get_info_from_handle, require_handle
from tribler.core.components.reporter.exception_handler import NoCrashException
from tribler.core.exceptions import SaveResumeDataError
from tribler.core.utilities.async_force_switch import switch
from tribler.core.utilities.notifier import Notifier
from tribler.core.utilities.osutils import fix_filebasename
from tribler.core.utilities.path_util import Path
Expand Down Expand Up @@ -138,6 +139,7 @@ def wait_for_alert(self, success_type: str, success_getter: Getter = None,

async def wait_for_status(self, *status):
while self.get_state().get_status() not in status:
await switch()
await self.wait_for_alert('state_changed_alert')

def get_def(self) -> TorrentDef:
Expand All @@ -147,10 +149,12 @@ def get_handle(self) -> Awaitable[lt.torrent_handle]:
"""
Returns a deferred that fires with a valid libtorrent download handle.
"""
if self.handle and self.handle.is_valid():
if self.handle:
# This block could be safely omitted because `self.future_added` does the same thing.
# However, it is used in tests, therefore it is better to keep it for now.
return succeed(self.handle)

return self.wait_for_alert('add_torrent_alert', lambda a: a.handle)
return self.future_added

def get_atp(self) -> Dict:
save_path = self.config.get_dest_dir()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ def create_session(self, hops=0, store_listen_port=True):
ltsession.add_dht_router(*router)
ltsession.start_lsd()

self._logger.debug("Started libtorrent session for %d hops on port %d", hops, ltsession.listen_port())
self._logger.info(f"Started libtorrent session for {hops} hops on port {ltsession.listen_port()}")
self.lt_session_shutdown_ready[hops] = False

return ltsession
Expand Down
7 changes: 6 additions & 1 deletion src/tribler/core/utilities/async_force_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
import functools


async def switch():
""" Coroutine that yields control to the event loop."""
await asyncio.sleep(0)


def force_switch(func):
"""Decorator for forced coroutine switch. The switch will occur before calling the function.
Expand All @@ -11,7 +16,7 @@ def force_switch(func):

@functools.wraps(func)
async def wrapper(*args, **kwargs):
await asyncio.sleep(0)
await switch()
return await func(*args, **kwargs)

return wrapper
Expand Down

0 comments on commit 090ae75

Please sign in to comment.