future.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # Copyright 2015 gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """A Future interface.
  15. Python doesn't have a Future interface in its standard library. In the absence
  16. of such a standard, three separate, incompatible implementations
  17. (concurrent.futures.Future, ndb.Future, and asyncio.Future) have appeared. This
  18. interface attempts to be as compatible as possible with
  19. concurrent.futures.Future. From ndb.Future it adopts a traceback-object accessor
  20. method.
  21. Unlike the concrete and implemented Future classes listed above, the Future
  22. class defined in this module is an entirely abstract interface that anyone may
  23. implement and use.
  24. The one known incompatibility between this interface and the interface of
  25. concurrent.futures.Future is that this interface defines its own CancelledError
  26. and TimeoutError exceptions rather than raising the implementation-private
  27. concurrent.futures._base.CancelledError and the
  28. built-in-but-only-in-3.3-and-later TimeoutError.
  29. """
  30. import abc
  31. import six
  32. class TimeoutError(Exception):
  33. """Indicates that a particular call timed out."""
  34. class CancelledError(Exception):
  35. """Indicates that the computation underlying a Future was cancelled."""
  36. class Future(six.with_metaclass(abc.ABCMeta)):
  37. """A representation of a computation in another control flow.
  38. Computations represented by a Future may be yet to be begun, may be ongoing,
  39. or may have already completed.
  40. """
  41. # NOTE(nathaniel): This isn't the return type that I would want to have if it
  42. # were up to me. Were this interface being written from scratch, the return
  43. # type of this method would probably be a sum type like:
  44. #
  45. # NOT_COMMENCED
  46. # COMMENCED_AND_NOT_COMPLETED
  47. # PARTIAL_RESULT<Partial_Result_Type>
  48. # COMPLETED<Result_Type>
  49. # UNCANCELLABLE
  50. # NOT_IMMEDIATELY_DETERMINABLE
  51. @abc.abstractmethod
  52. def cancel(self):
  53. """Attempts to cancel the computation.
  54. This method does not block.
  55. Returns:
  56. True if the computation has not yet begun, will not be allowed to take
  57. place, and determination of both was possible without blocking. False
  58. under all other circumstances including but not limited to the
  59. computation's already having begun, the computation's already having
  60. finished, and the computation's having been scheduled for execution on a
  61. remote system for which a determination of whether or not it commenced
  62. before being cancelled cannot be made without blocking.
  63. """
  64. raise NotImplementedError()
  65. # NOTE(nathaniel): Here too this isn't the return type that I'd want this
  66. # method to have if it were up to me. I think I'd go with another sum type
  67. # like:
  68. #
  69. # NOT_CANCELLED (this object's cancel method hasn't been called)
  70. # NOT_COMMENCED
  71. # COMMENCED_AND_NOT_COMPLETED
  72. # PARTIAL_RESULT<Partial_Result_Type>
  73. # COMPLETED<Result_Type>
  74. # UNCANCELLABLE
  75. # NOT_IMMEDIATELY_DETERMINABLE
  76. #
  77. # Notice how giving the cancel method the right semantics obviates most
  78. # reasons for this method to exist.
  79. @abc.abstractmethod
  80. def cancelled(self):
  81. """Describes whether the computation was cancelled.
  82. This method does not block.
  83. Returns:
  84. True if the computation was cancelled any time before its result became
  85. immediately available. False under all other circumstances including but
  86. not limited to this object's cancel method not having been called and
  87. the computation's result having become immediately available.
  88. """
  89. raise NotImplementedError()
  90. @abc.abstractmethod
  91. def running(self):
  92. """Describes whether the computation is taking place.
  93. This method does not block.
  94. Returns:
  95. True if the computation is scheduled to take place in the future or is
  96. taking place now, or False if the computation took place in the past or
  97. was cancelled.
  98. """
  99. raise NotImplementedError()
  100. # NOTE(nathaniel): These aren't quite the semantics I'd like here either. I
  101. # would rather this only returned True in cases in which the underlying
  102. # computation completed successfully. A computation's having been cancelled
  103. # conflicts with considering that computation "done".
  104. @abc.abstractmethod
  105. def done(self):
  106. """Describes whether the computation has taken place.
  107. This method does not block.
  108. Returns:
  109. True if the computation is known to have either completed or have been
  110. unscheduled or interrupted. False if the computation may possibly be
  111. executing or scheduled to execute later.
  112. """
  113. raise NotImplementedError()
  114. @abc.abstractmethod
  115. def result(self, timeout=None):
  116. """Accesses the outcome of the computation or raises its exception.
  117. This method may return immediately or may block.
  118. Args:
  119. timeout: The length of time in seconds to wait for the computation to
  120. finish or be cancelled, or None if this method should block until the
  121. computation has finished or is cancelled no matter how long that takes.
  122. Returns:
  123. The return value of the computation.
  124. Raises:
  125. TimeoutError: If a timeout value is passed and the computation does not
  126. terminate within the allotted time.
  127. CancelledError: If the computation was cancelled.
  128. Exception: If the computation raised an exception, this call will raise
  129. the same exception.
  130. """
  131. raise NotImplementedError()
  132. @abc.abstractmethod
  133. def exception(self, timeout=None):
  134. """Return the exception raised by the computation.
  135. This method may return immediately or may block.
  136. Args:
  137. timeout: The length of time in seconds to wait for the computation to
  138. terminate or be cancelled, or None if this method should block until
  139. the computation is terminated or is cancelled no matter how long that
  140. takes.
  141. Returns:
  142. The exception raised by the computation, or None if the computation did
  143. not raise an exception.
  144. Raises:
  145. TimeoutError: If a timeout value is passed and the computation does not
  146. terminate within the allotted time.
  147. CancelledError: If the computation was cancelled.
  148. """
  149. raise NotImplementedError()
  150. @abc.abstractmethod
  151. def traceback(self, timeout=None):
  152. """Access the traceback of the exception raised by the computation.
  153. This method may return immediately or may block.
  154. Args:
  155. timeout: The length of time in seconds to wait for the computation to
  156. terminate or be cancelled, or None if this method should block until
  157. the computation is terminated or is cancelled no matter how long that
  158. takes.
  159. Returns:
  160. The traceback of the exception raised by the computation, or None if the
  161. computation did not raise an exception.
  162. Raises:
  163. TimeoutError: If a timeout value is passed and the computation does not
  164. terminate within the allotted time.
  165. CancelledError: If the computation was cancelled.
  166. """
  167. raise NotImplementedError()
  168. @abc.abstractmethod
  169. def add_done_callback(self, fn):
  170. """Adds a function to be called at completion of the computation.
  171. The callback will be passed this Future object describing the outcome of
  172. the computation.
  173. If the computation has already completed, the callback will be called
  174. immediately.
  175. Args:
  176. fn: A callable taking this Future object as its single parameter.
  177. """
  178. raise NotImplementedError()