gen.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  1. """``tornado.gen`` is a generator-based interface to make it easier to
  2. work in an asynchronous environment. Code using the ``gen`` module
  3. is technically asynchronous, but it is written as a single generator
  4. instead of a collection of separate functions.
  5. For example, the following asynchronous handler:
  6. .. testcode::
  7. class AsyncHandler(RequestHandler):
  8. @asynchronous
  9. def get(self):
  10. http_client = AsyncHTTPClient()
  11. http_client.fetch("http://example.com",
  12. callback=self.on_fetch)
  13. def on_fetch(self, response):
  14. do_something_with_response(response)
  15. self.render("template.html")
  16. .. testoutput::
  17. :hide:
  18. could be written with ``gen`` as:
  19. .. testcode::
  20. class GenAsyncHandler(RequestHandler):
  21. @gen.coroutine
  22. def get(self):
  23. http_client = AsyncHTTPClient()
  24. response = yield http_client.fetch("http://example.com")
  25. do_something_with_response(response)
  26. self.render("template.html")
  27. .. testoutput::
  28. :hide:
  29. Most asynchronous functions in Tornado return a `.Future`;
  30. yielding this object returns its `~.Future.result`.
  31. You can also yield a list or dict of ``Futures``, which will be
  32. started at the same time and run in parallel; a list or dict of results will
  33. be returned when they are all finished:
  34. .. testcode::
  35. @gen.coroutine
  36. def get(self):
  37. http_client = AsyncHTTPClient()
  38. response1, response2 = yield [http_client.fetch(url1),
  39. http_client.fetch(url2)]
  40. response_dict = yield dict(response3=http_client.fetch(url3),
  41. response4=http_client.fetch(url4))
  42. response3 = response_dict['response3']
  43. response4 = response_dict['response4']
  44. .. testoutput::
  45. :hide:
  46. If the `~functools.singledispatch` library is available (standard in
  47. Python 3.4, available via the `singledispatch
  48. <https://pypi.python.org/pypi/singledispatch>`_ package on older
  49. versions), additional types of objects may be yielded. Tornado includes
  50. support for ``asyncio.Future`` and Twisted's ``Deferred`` class when
  51. ``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.
  52. See the `convert_yielded` function to extend this mechanism.
  53. .. versionchanged:: 3.2
  54. Dict support added.
  55. .. versionchanged:: 4.1
  56. Support added for yielding ``asyncio`` Futures and Twisted Deferreds
  57. via ``singledispatch``.
  58. """
  59. from __future__ import absolute_import, division, print_function, with_statement
  60. import collections
  61. import functools
  62. import itertools
  63. import os
  64. import sys
  65. import textwrap
  66. import types
  67. from tornado.concurrent import Future, TracebackFuture, is_future, chain_future
  68. from tornado.ioloop import IOLoop
  69. from tornado.log import app_log
  70. from tornado import stack_context
  71. from tornado.util import raise_exc_info
  72. try:
  73. try:
  74. from functools import singledispatch # py34+
  75. except ImportError:
  76. from singledispatch import singledispatch # backport
  77. except ImportError:
  78. # In most cases, singledispatch is required (to avoid
  79. # difficult-to-diagnose problems in which the functionality
  80. # available differs depending on which invisble packages are
  81. # installed). However, in Google App Engine third-party
  82. # dependencies are more trouble so we allow this module to be
  83. # imported without it.
  84. if 'APPENGINE_RUNTIME' not in os.environ:
  85. raise
  86. singledispatch = None
  87. try:
  88. try:
  89. from collections.abc import Generator as GeneratorType # py35+
  90. except ImportError:
  91. from backports_abc import Generator as GeneratorType
  92. try:
  93. from inspect import isawaitable # py35+
  94. except ImportError:
  95. from backports_abc import isawaitable
  96. except ImportError:
  97. if 'APPENGINE_RUNTIME' not in os.environ:
  98. raise
  99. from types import GeneratorType
  100. def isawaitable(x):
  101. return False
  102. try:
  103. import builtins # py3
  104. except ImportError:
  105. import __builtin__ as builtins
  106. class KeyReuseError(Exception):
  107. pass
  108. class UnknownKeyError(Exception):
  109. pass
  110. class LeakedCallbackError(Exception):
  111. pass
  112. class BadYieldError(Exception):
  113. pass
  114. class ReturnValueIgnoredError(Exception):
  115. pass
  116. class TimeoutError(Exception):
  117. """Exception raised by ``with_timeout``."""
  118. def _value_from_stopiteration(e):
  119. try:
  120. # StopIteration has a value attribute beginning in py33.
  121. # So does our Return class.
  122. return e.value
  123. except AttributeError:
  124. pass
  125. try:
  126. # Cython backports coroutine functionality by putting the value in
  127. # e.args[0].
  128. return e.args[0]
  129. except (AttributeError, IndexError):
  130. return None
  131. def engine(func):
  132. """Callback-oriented decorator for asynchronous generators.
  133. This is an older interface; for new code that does not need to be
  134. compatible with versions of Tornado older than 3.0 the
  135. `coroutine` decorator is recommended instead.
  136. This decorator is similar to `coroutine`, except it does not
  137. return a `.Future` and the ``callback`` argument is not treated
  138. specially.
  139. In most cases, functions decorated with `engine` should take
  140. a ``callback`` argument and invoke it with their result when
  141. they are finished. One notable exception is the
  142. `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
  143. which use ``self.finish()`` in place of a callback argument.
  144. """
  145. func = _make_coroutine_wrapper(func, replace_callback=False)
  146. @functools.wraps(func)
  147. def wrapper(*args, **kwargs):
  148. future = func(*args, **kwargs)
  149. def final_callback(future):
  150. if future.result() is not None:
  151. raise ReturnValueIgnoredError(
  152. "@gen.engine functions cannot return values: %r" %
  153. (future.result(),))
  154. # The engine interface doesn't give us any way to return
  155. # errors but to raise them into the stack context.
  156. # Save the stack context here to use when the Future has resolved.
  157. future.add_done_callback(stack_context.wrap(final_callback))
  158. return wrapper
  159. def coroutine(func, replace_callback=True):
  160. """Decorator for asynchronous generators.
  161. Any generator that yields objects from this module must be wrapped
  162. in either this decorator or `engine`.
  163. Coroutines may "return" by raising the special exception
  164. `Return(value) <Return>`. In Python 3.3+, it is also possible for
  165. the function to simply use the ``return value`` statement (prior to
  166. Python 3.3 generators were not allowed to also return values).
  167. In all versions of Python a coroutine that simply wishes to exit
  168. early may use the ``return`` statement without a value.
  169. Functions with this decorator return a `.Future`. Additionally,
  170. they may be called with a ``callback`` keyword argument, which
  171. will be invoked with the future's result when it resolves. If the
  172. coroutine fails, the callback will not be run and an exception
  173. will be raised into the surrounding `.StackContext`. The
  174. ``callback`` argument is not visible inside the decorated
  175. function; it is handled by the decorator itself.
  176. From the caller's perspective, ``@gen.coroutine`` is similar to
  177. the combination of ``@return_future`` and ``@gen.engine``.
  178. .. warning::
  179. When exceptions occur inside a coroutine, the exception
  180. information will be stored in the `.Future` object. You must
  181. examine the result of the `.Future` object, or the exception
  182. may go unnoticed by your code. This means yielding the function
  183. if called from another coroutine, using something like
  184. `.IOLoop.run_sync` for top-level calls, or passing the `.Future`
  185. to `.IOLoop.add_future`.
  186. """
  187. return _make_coroutine_wrapper(func, replace_callback=True)
  188. def _make_coroutine_wrapper(func, replace_callback):
  189. """The inner workings of ``@gen.coroutine`` and ``@gen.engine``.
  190. The two decorators differ in their treatment of the ``callback``
  191. argument, so we cannot simply implement ``@engine`` in terms of
  192. ``@coroutine``.
  193. """
  194. # On Python 3.5, set the coroutine flag on our generator, to allow it
  195. # to be used with 'await'.
  196. if hasattr(types, 'coroutine'):
  197. func = types.coroutine(func)
  198. @functools.wraps(func)
  199. def wrapper(*args, **kwargs):
  200. future = TracebackFuture()
  201. if replace_callback and 'callback' in kwargs:
  202. callback = kwargs.pop('callback')
  203. IOLoop.current().add_future(
  204. future, lambda future: callback(future.result()))
  205. try:
  206. result = func(*args, **kwargs)
  207. except (Return, StopIteration) as e:
  208. result = _value_from_stopiteration(e)
  209. except Exception:
  210. future.set_exc_info(sys.exc_info())
  211. return future
  212. else:
  213. if isinstance(result, GeneratorType):
  214. # Inline the first iteration of Runner.run. This lets us
  215. # avoid the cost of creating a Runner when the coroutine
  216. # never actually yields, which in turn allows us to
  217. # use "optional" coroutines in critical path code without
  218. # performance penalty for the synchronous case.
  219. try:
  220. orig_stack_contexts = stack_context._state.contexts
  221. yielded = next(result)
  222. if stack_context._state.contexts is not orig_stack_contexts:
  223. yielded = TracebackFuture()
  224. yielded.set_exception(
  225. stack_context.StackContextInconsistentError(
  226. 'stack_context inconsistency (probably caused '
  227. 'by yield within a "with StackContext" block)'))
  228. except (StopIteration, Return) as e:
  229. future.set_result(_value_from_stopiteration(e))
  230. except Exception:
  231. future.set_exc_info(sys.exc_info())
  232. else:
  233. Runner(result, future, yielded)
  234. try:
  235. return future
  236. finally:
  237. # Subtle memory optimization: if next() raised an exception,
  238. # the future's exc_info contains a traceback which
  239. # includes this stack frame. This creates a cycle,
  240. # which will be collected at the next full GC but has
  241. # been shown to greatly increase memory usage of
  242. # benchmarks (relative to the refcount-based scheme
  243. # used in the absence of cycles). We can avoid the
  244. # cycle by clearing the local variable after we return it.
  245. future = None
  246. future.set_result(result)
  247. return future
  248. return wrapper
  249. class Return(Exception):
  250. """Special exception to return a value from a `coroutine`.
  251. If this exception is raised, its value argument is used as the
  252. result of the coroutine::
  253. @gen.coroutine
  254. def fetch_json(url):
  255. response = yield AsyncHTTPClient().fetch(url)
  256. raise gen.Return(json_decode(response.body))
  257. In Python 3.3, this exception is no longer necessary: the ``return``
  258. statement can be used directly to return a value (previously
  259. ``yield`` and ``return`` with a value could not be combined in the
  260. same function).
  261. By analogy with the return statement, the value argument is optional,
  262. but it is never necessary to ``raise gen.Return()``. The ``return``
  263. statement can be used with no arguments instead.
  264. """
  265. def __init__(self, value=None):
  266. super(Return, self).__init__()
  267. self.value = value
  268. # Cython recognizes subclasses of StopIteration with a .args tuple.
  269. self.args = (value,)
  270. class WaitIterator(object):
  271. """Provides an iterator to yield the results of futures as they finish.
  272. Yielding a set of futures like this:
  273. ``results = yield [future1, future2]``
  274. pauses the coroutine until both ``future1`` and ``future2``
  275. return, and then restarts the coroutine with the results of both
  276. futures. If either future is an exception, the expression will
  277. raise that exception and all the results will be lost.
  278. If you need to get the result of each future as soon as possible,
  279. or if you need the result of some futures even if others produce
  280. errors, you can use ``WaitIterator``::
  281. wait_iterator = gen.WaitIterator(future1, future2)
  282. while not wait_iterator.done():
  283. try:
  284. result = yield wait_iterator.next()
  285. except Exception as e:
  286. print("Error {} from {}".format(e, wait_iterator.current_future))
  287. else:
  288. print("Result {} received from {} at {}".format(
  289. result, wait_iterator.current_future,
  290. wait_iterator.current_index))
  291. Because results are returned as soon as they are available the
  292. output from the iterator *will not be in the same order as the
  293. input arguments*. If you need to know which future produced the
  294. current result, you can use the attributes
  295. ``WaitIterator.current_future``, or ``WaitIterator.current_index``
  296. to get the index of the future from the input list. (if keyword
  297. arguments were used in the construction of the `WaitIterator`,
  298. ``current_index`` will use the corresponding keyword).
  299. On Python 3.5, `WaitIterator` implements the async iterator
  300. protocol, so it can be used with the ``async for`` statement (note
  301. that in this version the entire iteration is aborted if any value
  302. raises an exception, while the previous example can continue past
  303. individual errors)::
  304. async for result in gen.WaitIterator(future1, future2):
  305. print("Result {} received from {} at {}".format(
  306. result, wait_iterator.current_future,
  307. wait_iterator.current_index))
  308. .. versionadded:: 4.1
  309. .. versionchanged:: 4.3
  310. Added ``async for`` support in Python 3.5.
  311. """
  312. def __init__(self, *args, **kwargs):
  313. if args and kwargs:
  314. raise ValueError(
  315. "You must provide args or kwargs, not both")
  316. if kwargs:
  317. self._unfinished = dict((f, k) for (k, f) in kwargs.items())
  318. futures = list(kwargs.values())
  319. else:
  320. self._unfinished = dict((f, i) for (i, f) in enumerate(args))
  321. futures = args
  322. self._finished = collections.deque()
  323. self.current_index = self.current_future = None
  324. self._running_future = None
  325. for future in futures:
  326. future.add_done_callback(self._done_callback)
  327. def done(self):
  328. """Returns True if this iterator has no more results."""
  329. if self._finished or self._unfinished:
  330. return False
  331. # Clear the 'current' values when iteration is done.
  332. self.current_index = self.current_future = None
  333. return True
  334. def next(self):
  335. """Returns a `.Future` that will yield the next available result.
  336. Note that this `.Future` will not be the same object as any of
  337. the inputs.
  338. """
  339. self._running_future = TracebackFuture()
  340. if self._finished:
  341. self._return_result(self._finished.popleft())
  342. return self._running_future
  343. def _done_callback(self, done):
  344. if self._running_future and not self._running_future.done():
  345. self._return_result(done)
  346. else:
  347. self._finished.append(done)
  348. def _return_result(self, done):
  349. """Called set the returned future's state that of the future
  350. we yielded, and set the current future for the iterator.
  351. """
  352. chain_future(done, self._running_future)
  353. self.current_future = done
  354. self.current_index = self._unfinished.pop(done)
  355. @coroutine
  356. def __aiter__(self):
  357. raise Return(self)
  358. def __anext__(self):
  359. if self.done():
  360. # Lookup by name to silence pyflakes on older versions.
  361. raise getattr(builtins, 'StopAsyncIteration')()
  362. return self.next()
  363. class YieldPoint(object):
  364. """Base class for objects that may be yielded from the generator.
  365. .. deprecated:: 4.0
  366. Use `Futures <.Future>` instead.
  367. """
  368. def start(self, runner):
  369. """Called by the runner after the generator has yielded.
  370. No other methods will be called on this object before ``start``.
  371. """
  372. raise NotImplementedError()
  373. def is_ready(self):
  374. """Called by the runner to determine whether to resume the generator.
  375. Returns a boolean; may be called more than once.
  376. """
  377. raise NotImplementedError()
  378. def get_result(self):
  379. """Returns the value to use as the result of the yield expression.
  380. This method will only be called once, and only after `is_ready`
  381. has returned true.
  382. """
  383. raise NotImplementedError()
  384. class Callback(YieldPoint):
  385. """Returns a callable object that will allow a matching `Wait` to proceed.
  386. The key may be any value suitable for use as a dictionary key, and is
  387. used to match ``Callbacks`` to their corresponding ``Waits``. The key
  388. must be unique among outstanding callbacks within a single run of the
  389. generator function, but may be reused across different runs of the same
  390. function (so constants generally work fine).
  391. The callback may be called with zero or one arguments; if an argument
  392. is given it will be returned by `Wait`.
  393. .. deprecated:: 4.0
  394. Use `Futures <.Future>` instead.
  395. """
  396. def __init__(self, key):
  397. self.key = key
  398. def start(self, runner):
  399. self.runner = runner
  400. runner.register_callback(self.key)
  401. def is_ready(self):
  402. return True
  403. def get_result(self):
  404. return self.runner.result_callback(self.key)
  405. class Wait(YieldPoint):
  406. """Returns the argument passed to the result of a previous `Callback`.
  407. .. deprecated:: 4.0
  408. Use `Futures <.Future>` instead.
  409. """
  410. def __init__(self, key):
  411. self.key = key
  412. def start(self, runner):
  413. self.runner = runner
  414. def is_ready(self):
  415. return self.runner.is_ready(self.key)
  416. def get_result(self):
  417. return self.runner.pop_result(self.key)
  418. class WaitAll(YieldPoint):
  419. """Returns the results of multiple previous `Callbacks <Callback>`.
  420. The argument is a sequence of `Callback` keys, and the result is
  421. a list of results in the same order.
  422. `WaitAll` is equivalent to yielding a list of `Wait` objects.
  423. .. deprecated:: 4.0
  424. Use `Futures <.Future>` instead.
  425. """
  426. def __init__(self, keys):
  427. self.keys = keys
  428. def start(self, runner):
  429. self.runner = runner
  430. def is_ready(self):
  431. return all(self.runner.is_ready(key) for key in self.keys)
  432. def get_result(self):
  433. return [self.runner.pop_result(key) for key in self.keys]
  434. def Task(func, *args, **kwargs):
  435. """Adapts a callback-based asynchronous function for use in coroutines.
  436. Takes a function (and optional additional arguments) and runs it with
  437. those arguments plus a ``callback`` keyword argument. The argument passed
  438. to the callback is returned as the result of the yield expression.
  439. .. versionchanged:: 4.0
  440. ``gen.Task`` is now a function that returns a `.Future`, instead of
  441. a subclass of `YieldPoint`. It still behaves the same way when
  442. yielded.
  443. """
  444. future = Future()
  445. def handle_exception(typ, value, tb):
  446. if future.done():
  447. return False
  448. future.set_exc_info((typ, value, tb))
  449. return True
  450. def set_result(result):
  451. if future.done():
  452. return
  453. future.set_result(result)
  454. with stack_context.ExceptionStackContext(handle_exception):
  455. func(*args, callback=_argument_adapter(set_result), **kwargs)
  456. return future
  457. class YieldFuture(YieldPoint):
  458. def __init__(self, future, io_loop=None):
  459. """Adapts a `.Future` to the `YieldPoint` interface.
  460. .. versionchanged:: 4.1
  461. The ``io_loop`` argument is deprecated.
  462. """
  463. self.future = future
  464. self.io_loop = io_loop or IOLoop.current()
  465. def start(self, runner):
  466. if not self.future.done():
  467. self.runner = runner
  468. self.key = object()
  469. runner.register_callback(self.key)
  470. self.io_loop.add_future(self.future, runner.result_callback(self.key))
  471. else:
  472. self.runner = None
  473. self.result_fn = self.future.result
  474. def is_ready(self):
  475. if self.runner is not None:
  476. return self.runner.is_ready(self.key)
  477. else:
  478. return True
  479. def get_result(self):
  480. if self.runner is not None:
  481. return self.runner.pop_result(self.key).result()
  482. else:
  483. return self.result_fn()
  484. def _contains_yieldpoint(children):
  485. """Returns True if ``children`` contains any YieldPoints.
  486. ``children`` may be a dict or a list, as used by `MultiYieldPoint`
  487. and `multi_future`.
  488. """
  489. if isinstance(children, dict):
  490. return any(isinstance(i, YieldPoint) for i in children.values())
  491. if isinstance(children, list):
  492. return any(isinstance(i, YieldPoint) for i in children)
  493. return False
  494. def multi(children, quiet_exceptions=()):
  495. """Runs multiple asynchronous operations in parallel.
  496. ``children`` may either be a list or a dict whose values are
  497. yieldable objects. ``multi()`` returns a new yieldable
  498. object that resolves to a parallel structure containing their
  499. results. If ``children`` is a list, the result is a list of
  500. results in the same order; if it is a dict, the result is a dict
  501. with the same keys.
  502. That is, ``results = yield multi(list_of_futures)`` is equivalent
  503. to::
  504. results = []
  505. for future in list_of_futures:
  506. results.append(yield future)
  507. If any children raise exceptions, ``multi()`` will raise the first
  508. one. All others will be logged, unless they are of types
  509. contained in the ``quiet_exceptions`` argument.
  510. If any of the inputs are `YieldPoints <YieldPoint>`, the returned
  511. yieldable object is a `YieldPoint`. Otherwise, returns a `.Future`.
  512. This means that the result of `multi` can be used in a native
  513. coroutine if and only if all of its children can be.
  514. In a ``yield``-based coroutine, it is not normally necessary to
  515. call this function directly, since the coroutine runner will
  516. do it automatically when a list or dict is yielded. However,
  517. it is necessary in ``await``-based coroutines, or to pass
  518. the ``quiet_exceptions`` argument.
  519. This function is available under the names ``multi()`` and ``Multi()``
  520. for historical reasons.
  521. .. versionchanged:: 4.2
  522. If multiple yieldables fail, any exceptions after the first
  523. (which is raised) will be logged. Added the ``quiet_exceptions``
  524. argument to suppress this logging for selected exception types.
  525. .. versionchanged:: 4.3
  526. Replaced the class ``Multi`` and the function ``multi_future``
  527. with a unified function ``multi``. Added support for yieldables
  528. other than `YieldPoint` and `.Future`.
  529. """
  530. if _contains_yieldpoint(children):
  531. return MultiYieldPoint(children, quiet_exceptions=quiet_exceptions)
  532. else:
  533. return multi_future(children, quiet_exceptions=quiet_exceptions)
  534. Multi = multi
  535. class MultiYieldPoint(YieldPoint):
  536. """Runs multiple asynchronous operations in parallel.
  537. This class is similar to `multi`, but it always creates a stack
  538. context even when no children require it. It is not compatible with
  539. native coroutines.
  540. .. versionchanged:: 4.2
  541. If multiple ``YieldPoints`` fail, any exceptions after the first
  542. (which is raised) will be logged. Added the ``quiet_exceptions``
  543. argument to suppress this logging for selected exception types.
  544. .. versionchanged:: 4.3
  545. Renamed from ``Multi`` to ``MultiYieldPoint``. The name ``Multi``
  546. remains as an alias for the equivalent `multi` function.
  547. .. deprecated:: 4.3
  548. Use `multi` instead.
  549. """
  550. def __init__(self, children, quiet_exceptions=()):
  551. self.keys = None
  552. if isinstance(children, dict):
  553. self.keys = list(children.keys())
  554. children = children.values()
  555. self.children = []
  556. for i in children:
  557. if not isinstance(i, YieldPoint):
  558. i = convert_yielded(i)
  559. if is_future(i):
  560. i = YieldFuture(i)
  561. self.children.append(i)
  562. assert all(isinstance(i, YieldPoint) for i in self.children)
  563. self.unfinished_children = set(self.children)
  564. self.quiet_exceptions = quiet_exceptions
  565. def start(self, runner):
  566. for i in self.children:
  567. i.start(runner)
  568. def is_ready(self):
  569. finished = list(itertools.takewhile(
  570. lambda i: i.is_ready(), self.unfinished_children))
  571. self.unfinished_children.difference_update(finished)
  572. return not self.unfinished_children
  573. def get_result(self):
  574. result_list = []
  575. exc_info = None
  576. for f in self.children:
  577. try:
  578. result_list.append(f.get_result())
  579. except Exception as e:
  580. if exc_info is None:
  581. exc_info = sys.exc_info()
  582. else:
  583. if not isinstance(e, self.quiet_exceptions):
  584. app_log.error("Multiple exceptions in yield list",
  585. exc_info=True)
  586. if exc_info is not None:
  587. raise_exc_info(exc_info)
  588. if self.keys is not None:
  589. return dict(zip(self.keys, result_list))
  590. else:
  591. return list(result_list)
  592. def multi_future(children, quiet_exceptions=()):
  593. """Wait for multiple asynchronous futures in parallel.
  594. This function is similar to `multi`, but does not support
  595. `YieldPoints <YieldPoint>`.
  596. .. versionadded:: 4.0
  597. .. versionchanged:: 4.2
  598. If multiple ``Futures`` fail, any exceptions after the first (which is
  599. raised) will be logged. Added the ``quiet_exceptions``
  600. argument to suppress this logging for selected exception types.
  601. .. deprecated:: 4.3
  602. Use `multi` instead.
  603. """
  604. if isinstance(children, dict):
  605. keys = list(children.keys())
  606. children = children.values()
  607. else:
  608. keys = None
  609. children = list(map(convert_yielded, children))
  610. assert all(is_future(i) for i in children)
  611. unfinished_children = set(children)
  612. future = Future()
  613. if not children:
  614. future.set_result({} if keys is not None else [])
  615. def callback(f):
  616. unfinished_children.remove(f)
  617. if not unfinished_children:
  618. result_list = []
  619. for f in children:
  620. try:
  621. result_list.append(f.result())
  622. except Exception as e:
  623. if future.done():
  624. if not isinstance(e, quiet_exceptions):
  625. app_log.error("Multiple exceptions in yield list",
  626. exc_info=True)
  627. else:
  628. future.set_exc_info(sys.exc_info())
  629. if not future.done():
  630. if keys is not None:
  631. future.set_result(dict(zip(keys, result_list)))
  632. else:
  633. future.set_result(result_list)
  634. listening = set()
  635. for f in children:
  636. if f not in listening:
  637. listening.add(f)
  638. f.add_done_callback(callback)
  639. return future
  640. def maybe_future(x):
  641. """Converts ``x`` into a `.Future`.
  642. If ``x`` is already a `.Future`, it is simply returned; otherwise
  643. it is wrapped in a new `.Future`. This is suitable for use as
  644. ``result = yield gen.maybe_future(f())`` when you don't know whether
  645. ``f()`` returns a `.Future` or not.
  646. .. deprecated:: 4.3
  647. This function only handles ``Futures``, not other yieldable objects.
  648. Instead of `maybe_future`, check for the non-future result types
  649. you expect (often just ``None``), and ``yield`` anything unknown.
  650. """
  651. if is_future(x):
  652. return x
  653. else:
  654. fut = Future()
  655. fut.set_result(x)
  656. return fut
  657. def with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):
  658. """Wraps a `.Future` in a timeout.
  659. Raises `TimeoutError` if the input future does not complete before
  660. ``timeout``, which may be specified in any form allowed by
  661. `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
  662. relative to `.IOLoop.time`)
  663. If the wrapped `.Future` fails after it has timed out, the exception
  664. will be logged unless it is of a type contained in ``quiet_exceptions``
  665. (which may be an exception type or a sequence of types).
  666. Currently only supports Futures, not other `YieldPoint` classes.
  667. .. versionadded:: 4.0
  668. .. versionchanged:: 4.1
  669. Added the ``quiet_exceptions`` argument and the logging of unhandled
  670. exceptions.
  671. """
  672. # TODO: allow yield points in addition to futures?
  673. # Tricky to do with stack_context semantics.
  674. #
  675. # It's tempting to optimize this by cancelling the input future on timeout
  676. # instead of creating a new one, but A) we can't know if we are the only
  677. # one waiting on the input future, so cancelling it might disrupt other
  678. # callers and B) concurrent futures can only be cancelled while they are
  679. # in the queue, so cancellation cannot reliably bound our waiting time.
  680. result = Future()
  681. chain_future(future, result)
  682. if io_loop is None:
  683. io_loop = IOLoop.current()
  684. def error_callback(future):
  685. try:
  686. future.result()
  687. except Exception as e:
  688. if not isinstance(e, quiet_exceptions):
  689. app_log.error("Exception in Future %r after timeout",
  690. future, exc_info=True)
  691. def timeout_callback():
  692. result.set_exception(TimeoutError("Timeout"))
  693. # In case the wrapped future goes on to fail, log it.
  694. future.add_done_callback(error_callback)
  695. timeout_handle = io_loop.add_timeout(
  696. timeout, timeout_callback)
  697. if isinstance(future, Future):
  698. # We know this future will resolve on the IOLoop, so we don't
  699. # need the extra thread-safety of IOLoop.add_future (and we also
  700. # don't care about StackContext here.
  701. future.add_done_callback(
  702. lambda future: io_loop.remove_timeout(timeout_handle))
  703. else:
  704. # concurrent.futures.Futures may resolve on any thread, so we
  705. # need to route them back to the IOLoop.
  706. io_loop.add_future(
  707. future, lambda future: io_loop.remove_timeout(timeout_handle))
  708. return result
  709. def sleep(duration):
  710. """Return a `.Future` that resolves after the given number of seconds.
  711. When used with ``yield`` in a coroutine, this is a non-blocking
  712. analogue to `time.sleep` (which should not be used in coroutines
  713. because it is blocking)::
  714. yield gen.sleep(0.5)
  715. Note that calling this function on its own does nothing; you must
  716. wait on the `.Future` it returns (usually by yielding it).
  717. .. versionadded:: 4.1
  718. """
  719. f = Future()
  720. IOLoop.current().call_later(duration, lambda: f.set_result(None))
  721. return f
  722. _null_future = Future()
  723. _null_future.set_result(None)
  724. moment = Future()
  725. moment.__doc__ = \
  726. """A special object which may be yielded to allow the IOLoop to run for
  727. one iteration.
  728. This is not needed in normal use but it can be helpful in long-running
  729. coroutines that are likely to yield Futures that are ready instantly.
  730. Usage: ``yield gen.moment``
  731. .. versionadded:: 4.0
  732. """
  733. moment.set_result(None)
  734. class Runner(object):
  735. """Internal implementation of `tornado.gen.engine`.
  736. Maintains information about pending callbacks and their results.
  737. The results of the generator are stored in ``result_future`` (a
  738. `.TracebackFuture`)
  739. """
  740. def __init__(self, gen, result_future, first_yielded):
  741. self.gen = gen
  742. self.result_future = result_future
  743. self.future = _null_future
  744. self.yield_point = None
  745. self.pending_callbacks = None
  746. self.results = None
  747. self.running = False
  748. self.finished = False
  749. self.had_exception = False
  750. self.io_loop = IOLoop.current()
  751. # For efficiency, we do not create a stack context until we
  752. # reach a YieldPoint (stack contexts are required for the historical
  753. # semantics of YieldPoints, but not for Futures). When we have
  754. # done so, this field will be set and must be called at the end
  755. # of the coroutine.
  756. self.stack_context_deactivate = None
  757. if self.handle_yield(first_yielded):
  758. self.run()
  759. def register_callback(self, key):
  760. """Adds ``key`` to the list of callbacks."""
  761. if self.pending_callbacks is None:
  762. # Lazily initialize the old-style YieldPoint data structures.
  763. self.pending_callbacks = set()
  764. self.results = {}
  765. if key in self.pending_callbacks:
  766. raise KeyReuseError("key %r is already pending" % (key,))
  767. self.pending_callbacks.add(key)
  768. def is_ready(self, key):
  769. """Returns true if a result is available for ``key``."""
  770. if self.pending_callbacks is None or key not in self.pending_callbacks:
  771. raise UnknownKeyError("key %r is not pending" % (key,))
  772. return key in self.results
  773. def set_result(self, key, result):
  774. """Sets the result for ``key`` and attempts to resume the generator."""
  775. self.results[key] = result
  776. if self.yield_point is not None and self.yield_point.is_ready():
  777. try:
  778. self.future.set_result(self.yield_point.get_result())
  779. except:
  780. self.future.set_exc_info(sys.exc_info())
  781. self.yield_point = None
  782. self.run()
  783. def pop_result(self, key):
  784. """Returns the result for ``key`` and unregisters it."""
  785. self.pending_callbacks.remove(key)
  786. return self.results.pop(key)
  787. def run(self):
  788. """Starts or resumes the generator, running until it reaches a
  789. yield point that is not ready.
  790. """
  791. if self.running or self.finished:
  792. return
  793. try:
  794. self.running = True
  795. while True:
  796. future = self.future
  797. if not future.done():
  798. return
  799. self.future = None
  800. try:
  801. orig_stack_contexts = stack_context._state.contexts
  802. exc_info = None
  803. try:
  804. value = future.result()
  805. except Exception:
  806. self.had_exception = True
  807. exc_info = sys.exc_info()
  808. if exc_info is not None:
  809. yielded = self.gen.throw(*exc_info)
  810. exc_info = None
  811. else:
  812. yielded = self.gen.send(value)
  813. if stack_context._state.contexts is not orig_stack_contexts:
  814. self.gen.throw(
  815. stack_context.StackContextInconsistentError(
  816. 'stack_context inconsistency (probably caused '
  817. 'by yield within a "with StackContext" block)'))
  818. except (StopIteration, Return) as e:
  819. self.finished = True
  820. self.future = _null_future
  821. if self.pending_callbacks and not self.had_exception:
  822. # If we ran cleanly without waiting on all callbacks
  823. # raise an error (really more of a warning). If we
  824. # had an exception then some callbacks may have been
  825. # orphaned, so skip the check in that case.
  826. raise LeakedCallbackError(
  827. "finished without waiting for callbacks %r" %
  828. self.pending_callbacks)
  829. self.result_future.set_result(_value_from_stopiteration(e))
  830. self.result_future = None
  831. self._deactivate_stack_context()
  832. return
  833. except Exception:
  834. self.finished = True
  835. self.future = _null_future
  836. self.result_future.set_exc_info(sys.exc_info())
  837. self.result_future = None
  838. self._deactivate_stack_context()
  839. return
  840. if not self.handle_yield(yielded):
  841. return
  842. finally:
  843. self.running = False
  844. def handle_yield(self, yielded):
  845. # Lists containing YieldPoints require stack contexts;
  846. # other lists are handled in convert_yielded.
  847. if _contains_yieldpoint(yielded):
  848. yielded = multi(yielded)
  849. if isinstance(yielded, YieldPoint):
  850. # YieldPoints are too closely coupled to the Runner to go
  851. # through the generic convert_yielded mechanism.
  852. self.future = TracebackFuture()
  853. def start_yield_point():
  854. try:
  855. yielded.start(self)
  856. if yielded.is_ready():
  857. self.future.set_result(
  858. yielded.get_result())
  859. else:
  860. self.yield_point = yielded
  861. except Exception:
  862. self.future = TracebackFuture()
  863. self.future.set_exc_info(sys.exc_info())
  864. if self.stack_context_deactivate is None:
  865. # Start a stack context if this is the first
  866. # YieldPoint we've seen.
  867. with stack_context.ExceptionStackContext(
  868. self.handle_exception) as deactivate:
  869. self.stack_context_deactivate = deactivate
  870. def cb():
  871. start_yield_point()
  872. self.run()
  873. self.io_loop.add_callback(cb)
  874. return False
  875. else:
  876. start_yield_point()
  877. else:
  878. try:
  879. self.future = convert_yielded(yielded)
  880. except BadYieldError:
  881. self.future = TracebackFuture()
  882. self.future.set_exc_info(sys.exc_info())
  883. if not self.future.done() or self.future is moment:
  884. self.io_loop.add_future(
  885. self.future, lambda f: self.run())
  886. return False
  887. return True
  888. def result_callback(self, key):
  889. return stack_context.wrap(_argument_adapter(
  890. functools.partial(self.set_result, key)))
  891. def handle_exception(self, typ, value, tb):
  892. if not self.running and not self.finished:
  893. self.future = TracebackFuture()
  894. self.future.set_exc_info((typ, value, tb))
  895. self.run()
  896. return True
  897. else:
  898. return False
  899. def _deactivate_stack_context(self):
  900. if self.stack_context_deactivate is not None:
  901. self.stack_context_deactivate()
  902. self.stack_context_deactivate = None
  903. Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])
  904. def _argument_adapter(callback):
  905. """Returns a function that when invoked runs ``callback`` with one arg.
  906. If the function returned by this function is called with exactly
  907. one argument, that argument is passed to ``callback``. Otherwise
  908. the args tuple and kwargs dict are wrapped in an `Arguments` object.
  909. """
  910. def wrapper(*args, **kwargs):
  911. if kwargs or len(args) > 1:
  912. callback(Arguments(args, kwargs))
  913. elif args:
  914. callback(args[0])
  915. else:
  916. callback(None)
  917. return wrapper
  918. # Convert Awaitables into Futures. It is unfortunately possible
  919. # to have infinite recursion here if those Awaitables assume that
  920. # we're using a different coroutine runner and yield objects
  921. # we don't understand. If that happens, the solution is to
  922. # register that runner's yieldable objects with convert_yielded.
  923. if sys.version_info >= (3, 3):
  924. exec(textwrap.dedent("""
  925. @coroutine
  926. def _wrap_awaitable(x):
  927. if hasattr(x, '__await__'):
  928. x = x.__await__()
  929. return (yield from x)
  930. """))
  931. else:
  932. # Py2-compatible version for use with Cython.
  933. # Copied from PEP 380.
  934. @coroutine
  935. def _wrap_awaitable(x):
  936. if hasattr(x, '__await__'):
  937. _i = x.__await__()
  938. else:
  939. _i = iter(x)
  940. try:
  941. _y = next(_i)
  942. except StopIteration as _e:
  943. _r = _value_from_stopiteration(_e)
  944. else:
  945. while 1:
  946. try:
  947. _s = yield _y
  948. except GeneratorExit as _e:
  949. try:
  950. _m = _i.close
  951. except AttributeError:
  952. pass
  953. else:
  954. _m()
  955. raise _e
  956. except BaseException as _e:
  957. _x = sys.exc_info()
  958. try:
  959. _m = _i.throw
  960. except AttributeError:
  961. raise _e
  962. else:
  963. try:
  964. _y = _m(*_x)
  965. except StopIteration as _e:
  966. _r = _value_from_stopiteration(_e)
  967. break
  968. else:
  969. try:
  970. if _s is None:
  971. _y = next(_i)
  972. else:
  973. _y = _i.send(_s)
  974. except StopIteration as _e:
  975. _r = _value_from_stopiteration(_e)
  976. break
  977. raise Return(_r)
  978. def convert_yielded(yielded):
  979. """Convert a yielded object into a `.Future`.
  980. The default implementation accepts lists, dictionaries, and Futures.
  981. If the `~functools.singledispatch` library is available, this function
  982. may be extended to support additional types. For example::
  983. @convert_yielded.register(asyncio.Future)
  984. def _(asyncio_future):
  985. return tornado.platform.asyncio.to_tornado_future(asyncio_future)
  986. .. versionadded:: 4.1
  987. """
  988. # Lists and dicts containing YieldPoints were handled earlier.
  989. if isinstance(yielded, (list, dict)):
  990. return multi(yielded)
  991. elif is_future(yielded):
  992. return yielded
  993. elif isawaitable(yielded):
  994. return _wrap_awaitable(yielded)
  995. else:
  996. raise BadYieldError("yielded unknown object %r" % (yielded,))
  997. if singledispatch is not None:
  998. convert_yielded = singledispatch(convert_yielded)
  999. try:
  1000. # If we can import t.p.asyncio, do it for its side effect
  1001. # (registering asyncio.Future with convert_yielded).
  1002. # It's ugly to do this here, but it prevents a cryptic
  1003. # infinite recursion in _wrap_awaitable.
  1004. # Note that even with this, asyncio integration is unlikely
  1005. # to work unless the application also configures AsyncIOLoop,
  1006. # but at least the error messages in that case are more
  1007. # comprehensible than a stack overflow.
  1008. import tornado.platform.asyncio
  1009. except ImportError:
  1010. pass
  1011. else:
  1012. # Reference the imported module to make pyflakes happy.
  1013. tornado