Skip to content

[WIP] Trio event loop - #298

Closed
abadger wants to merge 5 commits into
urwid:masterfrom
abadger:trio-event-loop
Closed

abadger wants to merge 5 commits into
urwid:masterfrom
abadger:trio-event-loop

Conversation

@abadger

@abadger abadger commented May 20, 2018 •

Copy link
Copy Markdown
Contributor
Checklist
  • I've ensured that similar functionality has not already been implemented
  • I've ensured that similar functionality has not earlier been proposed and declined
  • I've branched off the master or python-dual-support branch
  • I've merged fresh upstream into my branch recently
  • I've ran tox successfully in local environment
  • I've included docstrings and/or documentation and/or examples for my code (if this is a new feature)
Description:

Trio is an alternative async framework based around the async and await keywords that were added to recent python versions. This PR adds an EventLoop class which uses trio as its backend.

I've marked this as a work in progress as async and await are only available in python-3.6 or greater. I'll have to reorganize the new code so that it is only parsed if we're on python-3.6 or higher. I also want to check whether the eventloop is being tested in tox and try to get a trio developer to look over my work and make sure I'm not making any big mistakes.

abadger added 2 commits May 20, 2018 13:46
Newer tornados on Python3 use the Python3 asyncio event loop instead of
its custom one.
* alarm callbacks fire once and that's all.
* idle callbacks fire whenever the event loop has some downtime.  They
  currently re-register themselves to emulate this behaviour
* watch_file callbacks fire whenever the file is readable. Implement this
  by looping and awaiting something to be readable on the fd
@abadger
abadger force-pushed the trio-event-loop branch from 778af43 to 7eb87c4 Compare May 20, 2018 20:47
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.2%) to 76.055% when pulling e17b7da on abadger:trio-event-loop into 16469df on urwid:master.

@coveralls

coveralls commented May 20, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.1%) to 76.104% when pulling 0c85392 on abadger:trio-event-loop into 16469df on urwid:master.

@njsmith

njsmith commented May 20, 2018

Copy link
Copy Markdown

There is a downside to using Event objects to signal cancellation: if you start waiting for something in the background, and then later cancel it, the background task actually keeps running until whatever its waiting for happens. This might be particularly problematic when watching for fds, because if there's a trio task sitting in wait_readable and the fd it's waiting for gets closed, you can get weird effects. Like the task might keep sleeping forever, or worse, if another fd is opened and gets assigned the same number as the one that was closed, trio could get confused between them. (And unfortunately, there isn't really anything trio can do about this – it's a limitation of the underlying OS APIs.)

The other option would be to signal cancellation using cancel scopes.

    async def _trio_watch_file(self, fd, callback):
        with trio.open_cancel_scope() as cancel_scope:
            while True:
                await trio.hazmat.wait_readable(fd)
                callback()

Now this task can be cancelled by calling cancel_scope.cancel(), and that will immediately clean it up. But there is an awkward problem: how do we get at the cancel_scope object from outside _trio_watch_file?

Though, really, there is a similar problem with the current code as well: it turns out that currently calling trio.Event from outside trio.run works, but this isn't guaranteed...

I think maybe something like this should resolve these issues?

##### Helper class

class CancelHandle:
    def __init__(self):
        self._cancelled = False
        self._cancel_scope = None

##### inside TrioEventLoop

def __init__(self):
    # List of (async_fn, args, handle) tuples
    self._queued = []

def _queue_cancellable_operation(self, async_fn, *args):
    handle = CancelHandle()
    self._queued.append((async_fn, args, handle))
    self._maybe_process_queue()
    return handle

def _maybe_process_queue(self):
    if self._nursery is None:
        return
    for (async_fn, args, handle) in self._queued:
        self._nursery.start_soon(self._run_cancellable_operation, async_fn, args, handle)
    self._queued.clear()

async def _run_cancellable_operation(self, async_fn, args, handle):
    # In case we were cancelled before we even started
    if handle._cancelled:
        return
    with trio.open_cancel_scope() as cancel_scope:
        # In case we're cancelled after we started
        handle._cancel_scope = cancel_scope
        try:
            await async_fn(*args)
        finally:
            # to make sure future calls to _cancel_operation return False
            # and to make sure we don't try doing handle.cancel_scope.cancel() after leaving trio
            handle._cancelled = True

def _cancel_operation(self, handle):
    if handle._cancelled:
        return False
    else:
        handle._cancelled = True
        if handle._cancel_scope is not None:
            handle._cancel_scope.cancel()
        return True

Then alarm, watch_file, enter_idle become simple wrappers around _queue_cancellable_operation, and remove_* are all return self._cancel_operation(handle). What do you think?

BTW, I think the current implementation of enter_idle is way more complicated than it needs to be :-). Instead of having a task that spawns a task which spawns a task, etc., like you have to in Twisted, you can just write:

async def _idle_loop(self, callback):
    while True:
        await trio.sleep(self._idle_emulation_delay)
        callback()

def enter_idle(self, callback):
    return self._queue_cancellable_operation(self._idle_loop, callback)

@abadger

abadger commented May 20, 2018 via email

Copy link
Copy Markdown
Contributor Author

@njsmith

njsmith commented May 20, 2018

Copy link
Copy Markdown

Some more thoughts:

  • I'm not sure how urwid expects its event loop to respond when a callback raises an unexpected exception, but you should probably check :-)

  • currently this doesn't provide any way to run regular trio code alongside urwid code :-). My suggestion: keep the run method so you can run urwid's test suite, but don't actually recommend people use it. Instead, provide some methods like:

    async def __aenter__(self):
        assert self._nursery is None
        self._nursery = await trio.open_nursery().__aenter__()
        return self
    
    async def __aexit__(self, *args):
        try:
            await self._nursery.__aexit__(*args)
        finally:
            self._nursery = None

    So then people could use it like:

    async def main():
        async with urwid.TrioMainLoop(...) as urwid_main_loop:
            # arbitrary trio code here
    
    trio.run(main)

    I guess you might also want a way for trio code to interact with urwid's main loop exiting logic? Not sure.

  • I'm not quite sure what urwid actually expects from an "idle" callback – it's not a very well-defined concept. But trio does actually have a way to wait for everything to be idle: trio.testing.wait_all_tasks_blocked. I really can't recommend using this for anything except testing, because it creates such weird global coupling; I think probably sticking with the current "idle" semantics of "we call this callback occasionally" is probably better. But figured I should mention it so this could be an intentional decision.

@njsmith

njsmith commented Aug 21, 2018

Copy link
Copy Markdown

FYI, there's now an issue on the trio tracker (python-trio/trio#607) for making cancel scopes natively support being created at a different place than they're used.

@tonycpsu

tonycpsu commented Apr 6, 2019

Copy link
Copy Markdown
Collaborator

@abadger : is this still something you're working on?

@abadger

abadger commented Apr 6, 2019 via email

Copy link
Copy Markdown
Contributor Author

@tonycpsu

tonycpsu commented Apr 6, 2019

Copy link
Copy Markdown
Collaborator

No worries, I was just going through the backlog and this seemed like something that (a) folks might like and (b) seemed reasonably far along. We'll just leave it open for now.

@ntamas

ntamas commented Oct 23, 2019

Copy link
Copy Markdown
Contributor

I wish I had found this PR earlier because I have just spent a few hours on implementing a Trio event loop for urwid on my own. My implementation is to be found in this gist. It is reasonably similar to this PR but uses detached cancel scopes as suggested by @njsmith in this comment.

@abadger, do you plan to revive this PR in the near future?

@abadger

abadger commented Oct 24, 2019

Copy link
Copy Markdown
Contributor Author

@ntamas if you'd like to take over and get your changes merged instead, that suits me just fine :-). This has been a tumultuous couple years for me so i haven't had as much time as if like for working on anything in my free time :-)

@ntamas ntamas mentioned this pull request Oct 24, 2019
6 tasks done
@ntamas

ntamas commented Oct 24, 2019 •

Copy link
Copy Markdown
Contributor

Okay, I have sent my version of the Trio-based event loop as PR #372.

@abadger

abadger commented Oct 24, 2019

Copy link
Copy Markdown
Contributor Author

CLosing in favor of #372

@abadger abadger closed this Oct 24, 2019
@abadger
abadger deleted the trio-event-loop branch January 27, 2020 17:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants