result.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.result
  4. ~~~~~~~~~~~~~
  5. Task results/state and groups of results.
  6. """
  7. from __future__ import absolute_import
  8. import time
  9. from collections import OrderedDict, deque
  10. from contextlib import contextmanager
  11. from copy import copy
  12. from amqp import promise
  13. from kombu.utils import cached_property
  14. from . import current_app
  15. from . import states
  16. from ._state import _set_task_join_will_block, task_join_will_block
  17. from .app import app_or_default
  18. from .datastructures import DependencyGraph, GraphFormatter
  19. from .exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError
  20. from .five import items, range, string_t, monotonic
  21. from .utils import deprecated
  22. __all__ = ['ResultBase', 'AsyncResult', 'ResultSet', 'GroupResult',
  23. 'EagerResult', 'result_from_tuple']
  24. E_WOULDBLOCK = """\
  25. Never call result.get() within a task!
  26. See http://docs.celeryq.org/en/latest/userguide/tasks.html\
  27. #task-synchronous-subtasks
  28. """
  29. def assert_will_not_block():
  30. if task_join_will_block():
  31. raise RuntimeError(E_WOULDBLOCK)
  32. @contextmanager
  33. def allow_join_result():
  34. reset_value = task_join_will_block()
  35. _set_task_join_will_block(False)
  36. try:
  37. yield
  38. finally:
  39. _set_task_join_will_block(reset_value)
  40. class ResultBase(object):
  41. """Base class for all results"""
  42. #: Parent result (if part of a chain)
  43. parent = None
  44. class AsyncResult(ResultBase):
  45. """Query task state.
  46. :param id: see :attr:`id`.
  47. :keyword backend: see :attr:`backend`.
  48. """
  49. app = None
  50. #: Error raised for timeouts.
  51. TimeoutError = TimeoutError
  52. #: The task's UUID.
  53. id = None
  54. #: The task result backend to use.
  55. backend = None
  56. def __init__(self, id, backend=None,
  57. task_name=None, # deprecated
  58. app=None, parent=None):
  59. if id is None:
  60. raise ValueError(
  61. 'AsyncResult requires valid id, not {0}'.format(type(id)))
  62. self.app = app_or_default(app or self.app)
  63. self.id = id
  64. self.backend = backend or self.app.backend
  65. self.parent = parent
  66. self._cache = None
  67. def as_tuple(self):
  68. parent = self.parent
  69. return (self.id, parent and parent.as_tuple()), None
  70. def forget(self):
  71. """Forget about (and possibly remove the result of) this task."""
  72. self._cache = None
  73. self.backend.forget(self.id)
  74. def revoke(self, connection=None, terminate=False, signal=None,
  75. wait=False, timeout=None):
  76. """Send revoke signal to all workers.
  77. Any worker receiving the task, or having reserved the
  78. task, *must* ignore it.
  79. :keyword terminate: Also terminate the process currently working
  80. on the task (if any).
  81. :keyword signal: Name of signal to send to process if terminate.
  82. Default is TERM.
  83. :keyword wait: Wait for replies from workers. Will wait for 1 second
  84. by default or you can specify a custom ``timeout``.
  85. :keyword timeout: Time in seconds to wait for replies if ``wait``
  86. enabled.
  87. """
  88. self.app.control.revoke(self.id, connection=connection,
  89. terminate=terminate, signal=signal,
  90. reply=wait, timeout=timeout)
  91. def get(self, timeout=None, propagate=True, interval=0.5,
  92. no_ack=True, follow_parents=True, callback=None, on_interval=None,
  93. EXCEPTION_STATES=states.EXCEPTION_STATES,
  94. PROPAGATE_STATES=states.PROPAGATE_STATES):
  95. """Wait until task is ready, and return its result.
  96. .. warning::
  97. Waiting for tasks within a task may lead to deadlocks.
  98. Please read :ref:`task-synchronous-subtasks`.
  99. :keyword timeout: How long to wait, in seconds, before the
  100. operation times out.
  101. :keyword propagate: Re-raise exception if the task failed.
  102. :keyword interval: Time to wait (in seconds) before retrying to
  103. retrieve the result. Note that this does not have any effect
  104. when using the amqp result store backend, as it does not
  105. use polling.
  106. :keyword no_ack: Enable amqp no ack (automatically acknowledge
  107. message). If this is :const:`False` then the message will
  108. **not be acked**.
  109. :keyword follow_parents: Reraise any exception raised by parent task.
  110. :raises celery.exceptions.TimeoutError: if `timeout` is not
  111. :const:`None` and the result does not arrive within `timeout`
  112. seconds.
  113. If the remote call raised an exception then that exception will
  114. be re-raised.
  115. """
  116. assert_will_not_block()
  117. _on_interval = promise()
  118. if follow_parents and propagate and self.parent:
  119. on_interval = promise(self._maybe_reraise_parent_error)
  120. self._maybe_reraise_parent_error()
  121. if on_interval:
  122. _on_interval.then(on_interval)
  123. if self._cache:
  124. if propagate:
  125. self.maybe_reraise()
  126. return self.result
  127. meta = self.backend.wait_for(
  128. self.id, timeout=timeout,
  129. interval=interval,
  130. on_interval=_on_interval,
  131. no_ack=no_ack,
  132. )
  133. if meta:
  134. self._maybe_set_cache(meta)
  135. status = meta['status']
  136. if status in PROPAGATE_STATES and propagate:
  137. raise meta['result']
  138. if callback is not None:
  139. callback(self.id, meta['result'])
  140. return meta['result']
  141. wait = get # deprecated alias to :meth:`get`.
  142. def _maybe_reraise_parent_error(self):
  143. for node in reversed(list(self._parents())):
  144. node.maybe_reraise()
  145. def _parents(self):
  146. node = self.parent
  147. while node:
  148. yield node
  149. node = node.parent
  150. def collect(self, intermediate=False, **kwargs):
  151. """Iterator, like :meth:`get` will wait for the task to complete,
  152. but will also follow :class:`AsyncResult` and :class:`ResultSet`
  153. returned by the task, yielding ``(result, value)`` tuples for each
  154. result in the tree.
  155. An example would be having the following tasks:
  156. .. code-block:: python
  157. from celery import group
  158. from proj.celery import app
  159. @app.task(trail=True)
  160. def A(how_many):
  161. return group(B.s(i) for i in range(how_many))()
  162. @app.task(trail=True)
  163. def B(i):
  164. return pow2.delay(i)
  165. @app.task(trail=True)
  166. def pow2(i):
  167. return i ** 2
  168. Note that the ``trail`` option must be enabled
  169. so that the list of children is stored in ``result.children``.
  170. This is the default but enabled explicitly for illustration.
  171. Calling :meth:`collect` would return:
  172. .. code-block:: pycon
  173. >>> from celery.result import ResultBase
  174. >>> from proj.tasks import A
  175. >>> result = A.delay(10)
  176. >>> [v for v in result.collect()
  177. ... if not isinstance(v, (ResultBase, tuple))]
  178. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  179. """
  180. for _, R in self.iterdeps(intermediate=intermediate):
  181. yield R, R.get(**kwargs)
  182. def get_leaf(self):
  183. value = None
  184. for _, R in self.iterdeps():
  185. value = R.get()
  186. return value
  187. def iterdeps(self, intermediate=False):
  188. stack = deque([(None, self)])
  189. while stack:
  190. parent, node = stack.popleft()
  191. yield parent, node
  192. if node.ready():
  193. stack.extend((node, child) for child in node.children or [])
  194. else:
  195. if not intermediate:
  196. raise IncompleteStream()
  197. def ready(self):
  198. """Returns :const:`True` if the task has been executed.
  199. If the task is still running, pending, or is waiting
  200. for retry then :const:`False` is returned.
  201. """
  202. return self.state in self.backend.READY_STATES
  203. def successful(self):
  204. """Returns :const:`True` if the task executed successfully."""
  205. return self.state == states.SUCCESS
  206. def failed(self):
  207. """Returns :const:`True` if the task failed."""
  208. return self.state == states.FAILURE
  209. def maybe_reraise(self):
  210. if self.state in states.PROPAGATE_STATES:
  211. raise self.result
  212. def build_graph(self, intermediate=False, formatter=None):
  213. graph = DependencyGraph(
  214. formatter=formatter or GraphFormatter(root=self.id, shape='oval'),
  215. )
  216. for parent, node in self.iterdeps(intermediate=intermediate):
  217. graph.add_arc(node)
  218. if parent:
  219. graph.add_edge(parent, node)
  220. return graph
  221. def __str__(self):
  222. """`str(self) -> self.id`"""
  223. return str(self.id)
  224. def __hash__(self):
  225. """`hash(self) -> hash(self.id)`"""
  226. return hash(self.id)
  227. def __repr__(self):
  228. return '<{0}: {1}>'.format(type(self).__name__, self.id)
  229. def __eq__(self, other):
  230. if isinstance(other, AsyncResult):
  231. return other.id == self.id
  232. elif isinstance(other, string_t):
  233. return other == self.id
  234. return NotImplemented
  235. def __ne__(self, other):
  236. res = self.__eq__(other)
  237. return True if res is NotImplemented else not res
  238. def __copy__(self):
  239. return self.__class__(
  240. self.id, self.backend, None, self.app, self.parent,
  241. )
  242. def __reduce__(self):
  243. return self.__class__, self.__reduce_args__()
  244. def __reduce_args__(self):
  245. return self.id, self.backend, None, None, self.parent
  246. def __del__(self):
  247. self._cache = None
  248. @cached_property
  249. def graph(self):
  250. return self.build_graph()
  251. @property
  252. def supports_native_join(self):
  253. return self.backend.supports_native_join
  254. @property
  255. def children(self):
  256. return self._get_task_meta().get('children')
  257. def _maybe_set_cache(self, meta):
  258. if meta:
  259. state = meta['status']
  260. if state == states.SUCCESS or state in states.PROPAGATE_STATES:
  261. return self._set_cache(meta)
  262. return meta
  263. def _get_task_meta(self):
  264. if self._cache is None:
  265. return self._maybe_set_cache(self.backend.get_task_meta(self.id))
  266. return self._cache
  267. def _set_cache(self, d):
  268. children = d.get('children')
  269. if children:
  270. d['children'] = [
  271. result_from_tuple(child, self.app) for child in children
  272. ]
  273. self._cache = d
  274. return d
  275. @property
  276. def result(self):
  277. """When the task has been executed, this contains the return value.
  278. If the task raised an exception, this will be the exception
  279. instance."""
  280. return self._get_task_meta()['result']
  281. info = result
  282. @property
  283. def traceback(self):
  284. """Get the traceback of a failed task."""
  285. return self._get_task_meta().get('traceback')
  286. @property
  287. def state(self):
  288. """The tasks current state.
  289. Possible values includes:
  290. *PENDING*
  291. The task is waiting for execution.
  292. *STARTED*
  293. The task has been started.
  294. *RETRY*
  295. The task is to be retried, possibly because of failure.
  296. *FAILURE*
  297. The task raised an exception, or has exceeded the retry limit.
  298. The :attr:`result` attribute then contains the
  299. exception raised by the task.
  300. *SUCCESS*
  301. The task executed successfully. The :attr:`result` attribute
  302. then contains the tasks return value.
  303. """
  304. return self._get_task_meta()['status']
  305. status = state
  306. @property
  307. def task_id(self):
  308. """compat alias to :attr:`id`"""
  309. return self.id
  310. @task_id.setter # noqa
  311. def task_id(self, id):
  312. self.id = id
  313. class ResultSet(ResultBase):
  314. """Working with more than one result.
  315. :param results: List of result instances.
  316. """
  317. _app = None
  318. #: List of results in in the set.
  319. results = None
  320. def __init__(self, results, app=None, **kwargs):
  321. self._app = app
  322. self.results = results
  323. def add(self, result):
  324. """Add :class:`AsyncResult` as a new member of the set.
  325. Does nothing if the result is already a member.
  326. """
  327. if result not in self.results:
  328. self.results.append(result)
  329. def remove(self, result):
  330. """Remove result from the set; it must be a member.
  331. :raises KeyError: if the result is not a member.
  332. """
  333. if isinstance(result, string_t):
  334. result = self.app.AsyncResult(result)
  335. try:
  336. self.results.remove(result)
  337. except ValueError:
  338. raise KeyError(result)
  339. def discard(self, result):
  340. """Remove result from the set if it is a member.
  341. If it is not a member, do nothing.
  342. """
  343. try:
  344. self.remove(result)
  345. except KeyError:
  346. pass
  347. def update(self, results):
  348. """Update set with the union of itself and an iterable with
  349. results."""
  350. self.results.extend(r for r in results if r not in self.results)
  351. def clear(self):
  352. """Remove all results from this set."""
  353. self.results[:] = [] # don't create new list.
  354. def successful(self):
  355. """Was all of the tasks successful?
  356. :returns: :const:`True` if all of the tasks finished
  357. successfully (i.e. did not raise an exception).
  358. """
  359. return all(result.successful() for result in self.results)
  360. def failed(self):
  361. """Did any of the tasks fail?
  362. :returns: :const:`True` if one of the tasks failed.
  363. (i.e., raised an exception)
  364. """
  365. return any(result.failed() for result in self.results)
  366. def maybe_reraise(self):
  367. for result in self.results:
  368. result.maybe_reraise()
  369. def waiting(self):
  370. """Are any of the tasks incomplete?
  371. :returns: :const:`True` if one of the tasks are still
  372. waiting for execution.
  373. """
  374. return any(not result.ready() for result in self.results)
  375. def ready(self):
  376. """Did all of the tasks complete? (either by success of failure).
  377. :returns: :const:`True` if all of the tasks has been
  378. executed.
  379. """
  380. return all(result.ready() for result in self.results)
  381. def completed_count(self):
  382. """Task completion count.
  383. :returns: the number of tasks completed.
  384. """
  385. return sum(int(result.successful()) for result in self.results)
  386. def forget(self):
  387. """Forget about (and possible remove the result of) all the tasks."""
  388. for result in self.results:
  389. result.forget()
  390. def revoke(self, connection=None, terminate=False, signal=None,
  391. wait=False, timeout=None):
  392. """Send revoke signal to all workers for all tasks in the set.
  393. :keyword terminate: Also terminate the process currently working
  394. on the task (if any).
  395. :keyword signal: Name of signal to send to process if terminate.
  396. Default is TERM.
  397. :keyword wait: Wait for replies from worker. Will wait for 1 second
  398. by default or you can specify a custom ``timeout``.
  399. :keyword timeout: Time in seconds to wait for replies if ``wait``
  400. enabled.
  401. """
  402. self.app.control.revoke([r.id for r in self.results],
  403. connection=connection, timeout=timeout,
  404. terminate=terminate, signal=signal, reply=wait)
  405. def __iter__(self):
  406. return iter(self.results)
  407. def __getitem__(self, index):
  408. """`res[i] -> res.results[i]`"""
  409. return self.results[index]
  410. @deprecated('4.0', '5.0')
  411. def iterate(self, timeout=None, propagate=True, interval=0.5):
  412. """Deprecated method, use :meth:`get` with a callback argument."""
  413. elapsed = 0.0
  414. results = OrderedDict((result.id, copy(result))
  415. for result in self.results)
  416. while results:
  417. removed = set()
  418. for task_id, result in items(results):
  419. if result.ready():
  420. yield result.get(timeout=timeout and timeout - elapsed,
  421. propagate=propagate)
  422. removed.add(task_id)
  423. else:
  424. if result.backend.subpolling_interval:
  425. time.sleep(result.backend.subpolling_interval)
  426. for task_id in removed:
  427. results.pop(task_id, None)
  428. time.sleep(interval)
  429. elapsed += interval
  430. if timeout and elapsed >= timeout:
  431. raise TimeoutError('The operation timed out')
  432. def get(self, timeout=None, propagate=True, interval=0.5,
  433. callback=None, no_ack=True, on_message=None):
  434. """See :meth:`join`
  435. This is here for API compatibility with :class:`AsyncResult`,
  436. in addition it uses :meth:`join_native` if available for the
  437. current result backend.
  438. """
  439. return (self.join_native if self.supports_native_join else self.join)(
  440. timeout=timeout, propagate=propagate,
  441. interval=interval, callback=callback, no_ack=no_ack,
  442. on_message=on_message,
  443. )
  444. def join(self, timeout=None, propagate=True, interval=0.5,
  445. callback=None, no_ack=True, on_message=None, on_interval=None):
  446. """Gathers the results of all tasks as a list in order.
  447. .. note::
  448. This can be an expensive operation for result store
  449. backends that must resort to polling (e.g. database).
  450. You should consider using :meth:`join_native` if your backend
  451. supports it.
  452. .. warning::
  453. Waiting for tasks within a task may lead to deadlocks.
  454. Please see :ref:`task-synchronous-subtasks`.
  455. :keyword timeout: The number of seconds to wait for results before
  456. the operation times out.
  457. :keyword propagate: If any of the tasks raises an exception, the
  458. exception will be re-raised.
  459. :keyword interval: Time to wait (in seconds) before retrying to
  460. retrieve a result from the set. Note that this
  461. does not have any effect when using the amqp
  462. result store backend, as it does not use polling.
  463. :keyword callback: Optional callback to be called for every result
  464. received. Must have signature ``(task_id, value)``
  465. No results will be returned by this function if
  466. a callback is specified. The order of results
  467. is also arbitrary when a callback is used.
  468. To get access to the result object for a particular
  469. id you will have to generate an index first:
  470. ``index = {r.id: r for r in gres.results.values()}``
  471. Or you can create new result objects on the fly:
  472. ``result = app.AsyncResult(task_id)`` (both will
  473. take advantage of the backend cache anyway).
  474. :keyword no_ack: Automatic message acknowledgement (Note that if this
  475. is set to :const:`False` then the messages *will not be
  476. acknowledged*).
  477. :raises celery.exceptions.TimeoutError: if ``timeout`` is not
  478. :const:`None` and the operation takes longer than ``timeout``
  479. seconds.
  480. """
  481. assert_will_not_block()
  482. time_start = monotonic()
  483. remaining = None
  484. if on_message is not None:
  485. raise ImproperlyConfigured(
  486. 'Backend does not support on_message callback')
  487. results = []
  488. for result in self.results:
  489. remaining = None
  490. if timeout:
  491. remaining = timeout - (monotonic() - time_start)
  492. if remaining <= 0.0:
  493. raise TimeoutError('join operation timed out')
  494. value = result.get(
  495. timeout=remaining, propagate=propagate,
  496. interval=interval, no_ack=no_ack, on_interval=on_interval,
  497. )
  498. if callback:
  499. callback(result.id, value)
  500. else:
  501. results.append(value)
  502. return results
  503. def iter_native(self, timeout=None, interval=0.5, no_ack=True,
  504. on_message=None, on_interval=None):
  505. """Backend optimized version of :meth:`iterate`.
  506. .. versionadded:: 2.2
  507. Note that this does not support collecting the results
  508. for different task types using different backends.
  509. This is currently only supported by the amqp, Redis and cache
  510. result backends.
  511. """
  512. results = self.results
  513. if not results:
  514. return iter([])
  515. return self.backend.get_many(
  516. {r.id for r in results},
  517. timeout=timeout, interval=interval, no_ack=no_ack,
  518. on_message=on_message, on_interval=on_interval,
  519. )
  520. def join_native(self, timeout=None, propagate=True,
  521. interval=0.5, callback=None, no_ack=True,
  522. on_message=None, on_interval=None):
  523. """Backend optimized version of :meth:`join`.
  524. .. versionadded:: 2.2
  525. Note that this does not support collecting the results
  526. for different task types using different backends.
  527. This is currently only supported by the amqp, Redis and cache
  528. result backends.
  529. """
  530. assert_will_not_block()
  531. order_index = None if callback else {
  532. result.id: i for i, result in enumerate(self.results)
  533. }
  534. acc = None if callback else [None for _ in range(len(self))]
  535. for task_id, meta in self.iter_native(timeout, interval, no_ack,
  536. on_message, on_interval):
  537. value = meta['result']
  538. if propagate and meta['status'] in states.PROPAGATE_STATES:
  539. raise value
  540. if callback:
  541. callback(task_id, value)
  542. else:
  543. acc[order_index[task_id]] = value
  544. return acc
  545. def _failed_join_report(self):
  546. return (res for res in self.results
  547. if res.backend.is_cached(res.id) and
  548. res.state in states.PROPAGATE_STATES)
  549. def __len__(self):
  550. return len(self.results)
  551. def __eq__(self, other):
  552. if isinstance(other, ResultSet):
  553. return other.results == self.results
  554. return NotImplemented
  555. def __ne__(self, other):
  556. res = self.__eq__(other)
  557. return True if res is NotImplemented else not res
  558. def __repr__(self):
  559. return '<{0}: [{1}]>'.format(type(self).__name__,
  560. ', '.join(r.id for r in self.results))
  561. @property
  562. def supports_native_join(self):
  563. try:
  564. return self.results[0].supports_native_join
  565. except IndexError:
  566. pass
  567. @property
  568. def app(self):
  569. if self._app is None:
  570. self._app = (self.results[0].app if self.results else
  571. current_app._get_current_object())
  572. return self._app
  573. @app.setter
  574. def app(self, app): # noqa
  575. self._app = app
  576. @property
  577. def backend(self):
  578. return self.app.backend if self.app else self.results[0].backend
  579. class GroupResult(ResultSet):
  580. """Like :class:`ResultSet`, but with an associated id.
  581. This type is returned by :class:`~celery.group`.
  582. It enables inspection of the tasks state and return values as
  583. a single entity.
  584. :param id: The id of the group.
  585. :param results: List of result instances.
  586. """
  587. #: The UUID of the group.
  588. id = None
  589. #: List/iterator of results in the group
  590. results = None
  591. def __init__(self, id=None, results=None, **kwargs):
  592. self.id = id
  593. ResultSet.__init__(self, results, **kwargs)
  594. def save(self, backend=None):
  595. """Save group-result for later retrieval using :meth:`restore`.
  596. Example::
  597. >>> def save_and_restore(result):
  598. ... result.save()
  599. ... result = GroupResult.restore(result.id)
  600. """
  601. return (backend or self.app.backend).save_group(self.id, self)
  602. def delete(self, backend=None):
  603. """Remove this result if it was previously saved."""
  604. (backend or self.app.backend).delete_group(self.id)
  605. def __reduce__(self):
  606. return self.__class__, self.__reduce_args__()
  607. def __reduce_args__(self):
  608. return self.id, self.results
  609. def __eq__(self, other):
  610. if isinstance(other, GroupResult):
  611. return other.id == self.id and other.results == self.results
  612. return NotImplemented
  613. def __ne__(self, other):
  614. res = self.__eq__(other)
  615. return True if res is NotImplemented else not res
  616. def __repr__(self):
  617. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  618. ', '.join(r.id for r in self.results))
  619. def as_tuple(self):
  620. return self.id, [r.as_tuple() for r in self.results]
  621. @property
  622. def children(self):
  623. return self.results
  624. @classmethod
  625. def restore(self, id, backend=None):
  626. """Restore previously saved group result."""
  627. return (
  628. backend or (self.app.backend if self.app else current_app.backend)
  629. ).restore_group(id)
  630. class EagerResult(AsyncResult):
  631. """Result that we know has already been executed."""
  632. def __init__(self, id, ret_value, state, traceback=None):
  633. self.id = id
  634. self._result = ret_value
  635. self._state = state
  636. self._traceback = traceback
  637. def _get_task_meta(self):
  638. return {'task_id': self.id, 'result': self._result, 'status':
  639. self._state, 'traceback': self._traceback}
  640. def __reduce__(self):
  641. return self.__class__, self.__reduce_args__()
  642. def __reduce_args__(self):
  643. return (self.id, self._result, self._state, self._traceback)
  644. def __copy__(self):
  645. cls, args = self.__reduce__()
  646. return cls(*args)
  647. def ready(self):
  648. return True
  649. def get(self, timeout=None, propagate=True, **kwargs):
  650. if self.successful():
  651. return self.result
  652. elif self.state in states.PROPAGATE_STATES:
  653. if propagate:
  654. raise self.result
  655. return self.result
  656. wait = get # XXX Compat (remove 5.0)
  657. def forget(self):
  658. pass
  659. def revoke(self, *args, **kwargs):
  660. self._state = states.REVOKED
  661. def __repr__(self):
  662. return '<EagerResult: {0.id}>'.format(self)
  663. @property
  664. def result(self):
  665. """The tasks return value"""
  666. return self._result
  667. @property
  668. def state(self):
  669. """The tasks state."""
  670. return self._state
  671. status = state
  672. @property
  673. def traceback(self):
  674. """The traceback if the task failed."""
  675. return self._traceback
  676. @property
  677. def supports_native_join(self):
  678. return False
  679. def result_from_tuple(r, app=None):
  680. # earlier backends may just pickle, so check if
  681. # result is already prepared.
  682. app = app_or_default(app)
  683. Result = app.AsyncResult
  684. if not isinstance(r, ResultBase):
  685. res, nodes = r
  686. if nodes:
  687. return app.GroupResult(
  688. res, [result_from_tuple(child, app) for child in nodes],
  689. )
  690. # previously did not include parent
  691. id, parent = res if isinstance(res, (list, tuple)) else (res, None)
  692. if parent:
  693. parent = result_from_tuple(parent, app)
  694. return Result(id, parent=parent)
  695. return r