-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Run tornado gen.coroutines in the context of a task. #2716
Open
BrandonTheBuilder
wants to merge
6
commits into
tornadoweb:master
Choose a base branch
from
BrandonTheBuilder:asyncio-runner
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
36a6413
Add test to assert coroutines run in the context of a task.
5a76222
Update Runner to run coroutine in the context of a task.
88da3a2
Add ExpectLog to infinite_coro test.
d652bb0
Add callbacks to correctly cancel task.
18f1bda
Autoformatting
BrandonTheBuilder 8345ecd
Update type annotations.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -76,7 +76,6 @@ def get(self): | |
from functools import singledispatch | ||
from inspect import isawaitable | ||
import sys | ||
import types | ||
|
||
from tornado.concurrent import ( | ||
Future, | ||
|
@@ -200,31 +199,17 @@ def wrapper(*args, **kwargs): | |
future = None # type: ignore | ||
else: | ||
if isinstance(result, Generator): | ||
# Inline the first iteration of Runner.run. This lets us | ||
# avoid the cost of creating a Runner when the coroutine | ||
# never actually yields, which in turn allows us to | ||
# use "optional" coroutines in critical path code without | ||
# performance penalty for the synchronous case. | ||
try: | ||
yielded = next(result) | ||
except (StopIteration, Return) as e: | ||
future_set_result_unless_cancelled( | ||
future, _value_from_stopiteration(e) | ||
) | ||
except Exception: | ||
future_set_exc_info(future, sys.exc_info()) | ||
else: | ||
# Provide strong references to Runner objects as long | ||
# as their result future objects also have strong | ||
# references (typically from the parent coroutine's | ||
# Runner). This keeps the coroutine's Runner alive. | ||
# We do this by exploiting the public API | ||
# add_done_callback() instead of putting a private | ||
# attribute on the Future. | ||
# (Github issues #1769, #2229). | ||
runner = Runner(result, future, yielded) | ||
future.add_done_callback(lambda _: runner) | ||
yielded = None | ||
# Provide strong references to Runner objects as long | ||
# as their result future objects also have strong | ||
# references (typically from the parent coroutine's | ||
# Runner). This keeps the coroutine's Runner alive. | ||
# We do this by exploiting the public API | ||
# add_done_callback() instead of putting a private | ||
# attribute on the Future. | ||
# (Github issues #1769, #2229). | ||
runner = Runner(result, future) | ||
future.add_done_callback(runner.finish) | ||
|
||
try: | ||
return future | ||
finally: | ||
|
@@ -698,108 +683,81 @@ class Runner(object): | |
""" | ||
|
||
def __init__( | ||
self, | ||
gen: "Generator[_Yieldable, Any, _T]", | ||
result_future: "Future[_T]", | ||
first_yielded: _Yieldable, | ||
self, gen: "Generator[_Yieldable, Any, _T]", result_future: "Future[_T]" | ||
) -> None: | ||
self.gen = gen | ||
self.result_future = result_future | ||
self.future = _null_future # type: Union[None, Future] | ||
self.running = False | ||
self.finished = False | ||
self.io_loop = IOLoop.current() | ||
if self.handle_yield(first_yielded): | ||
gen = result_future = first_yielded = None # type: ignore | ||
self.run() | ||
self.task = asyncio.ensure_future(self.run()) | ||
|
||
async def run(self) -> None: | ||
"Runs the generator to completion in the context of a task" | ||
while True: | ||
future = self.future | ||
if future is None: | ||
raise Exception("No pending future") | ||
if not self.future.done(): # type: ignore | ||
_step = asyncio.Event() | ||
|
||
def step(f: "Future[_T]") -> None: | ||
_step.set() | ||
|
||
self.io_loop.add_future(self.future, step) # type: ignore | ||
await _step.wait() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would have expected this to be simply |
||
self.future = None | ||
try: | ||
exc_info = None | ||
|
||
def run(self) -> None: | ||
"""Starts or resumes the generator, running until it reaches a | ||
yield point that is not ready. | ||
""" | ||
if self.running or self.finished: | ||
return | ||
try: | ||
self.running = True | ||
while True: | ||
future = self.future | ||
if future is None: | ||
raise Exception("No pending future") | ||
if not future.done(): | ||
return | ||
self.future = None | ||
try: | ||
exc_info = None | ||
value = future.result() | ||
except Exception: | ||
exc_info = sys.exc_info() | ||
future = None | ||
|
||
if exc_info is not None: | ||
try: | ||
value = future.result() | ||
except Exception: | ||
exc_info = sys.exc_info() | ||
future = None | ||
|
||
if exc_info is not None: | ||
try: | ||
yielded = self.gen.throw(*exc_info) # type: ignore | ||
finally: | ||
# Break up a reference to itself | ||
# for faster GC on CPython. | ||
exc_info = None | ||
else: | ||
yielded = self.gen.send(value) | ||
yielded = self.gen.throw(*exc_info) # type: ignore | ||
finally: | ||
# Break up a reference to itself | ||
# for faster GC on CPython. | ||
exc_info = None | ||
else: | ||
yielded = self.gen.send(value) | ||
|
||
except (StopIteration, Return) as e: | ||
self.finished = True | ||
self.future = _null_future | ||
future_set_result_unless_cancelled( | ||
self.result_future, _value_from_stopiteration(e) | ||
) | ||
self.result_future = None # type: ignore | ||
return | ||
except Exception: | ||
self.finished = True | ||
self.future = _null_future | ||
future_set_exc_info(self.result_future, sys.exc_info()) | ||
self.result_future = None # type: ignore | ||
return | ||
if not self.handle_yield(yielded): | ||
return | ||
yielded = None | ||
finally: | ||
self.running = False | ||
|
||
def handle_yield(self, yielded: _Yieldable) -> bool: | ||
except (StopIteration, Return) as e: | ||
self.finished = True | ||
self.future = _null_future | ||
future_set_result_unless_cancelled( | ||
self.result_future, _value_from_stopiteration(e) | ||
) | ||
self.result_future = None # type: ignore | ||
return | ||
except Exception: | ||
self.finished = True | ||
self.future = _null_future | ||
future_set_exc_info(self.result_future, sys.exc_info()) | ||
self.result_future = None # type: ignore | ||
return | ||
|
||
self.handle_yield(yielded) | ||
yielded = None | ||
if self.future is moment: | ||
await sleep(0) | ||
|
||
def handle_yield(self, yielded: _Yieldable) -> None: | ||
try: | ||
self.future = convert_yielded(yielded) | ||
except BadYieldError: | ||
self.future = Future() | ||
future_set_exc_info(self.future, sys.exc_info()) | ||
|
||
if self.future is moment: | ||
self.io_loop.add_callback(self.run) | ||
return False | ||
elif self.future is None: | ||
raise Exception("no pending future") | ||
elif not self.future.done(): | ||
|
||
def inner(f: Any) -> None: | ||
# Break a reference cycle to speed GC. | ||
f = None # noqa: F841 | ||
self.run() | ||
|
||
self.io_loop.add_future(self.future, inner) | ||
return False | ||
return True | ||
|
||
def handle_exception( | ||
self, typ: Type[Exception], value: Exception, tb: types.TracebackType | ||
) -> bool: | ||
if not self.running and not self.finished: | ||
self.future = Future() | ||
future_set_exc_info(self.future, (typ, value, tb)) | ||
self.run() | ||
return True | ||
else: | ||
return False | ||
def finish(self, future: "Future[_T]") -> None: | ||
if future.cancelled(): | ||
self.task.cancel() | ||
self.future.cancel() # type: ignore | ||
|
||
|
||
# Convert Awaitables into Futures. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Style note: Tornado uses a leading underscore on "private" class/instance attributes, but local variables should just have plain names like
step
.