Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1 | """A Future class similar to the one in PEP 3148.""" |
| 2 | |
| 3 | __all__ = ['CancelledError', 'TimeoutError', |
| 4 | 'InvalidStateError', |
| 5 | 'Future', 'wrap_future', |
| 6 | ] |
| 7 | |
| 8 | import concurrent.futures._base |
| 9 | import logging |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 10 | import sys |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 11 | import traceback |
| 12 | |
| 13 | from . import events |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 14 | |
| 15 | # States for Future. |
| 16 | _PENDING = 'PENDING' |
| 17 | _CANCELLED = 'CANCELLED' |
| 18 | _FINISHED = 'FINISHED' |
| 19 | |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 20 | _PY34 = sys.version_info >= (3, 4) |
| 21 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 22 | # TODO: Do we really want to depend on concurrent.futures internals? |
| 23 | Error = concurrent.futures._base.Error |
| 24 | CancelledError = concurrent.futures.CancelledError |
| 25 | TimeoutError = concurrent.futures.TimeoutError |
| 26 | |
| 27 | STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging |
| 28 | |
| 29 | |
| 30 | class InvalidStateError(Error): |
| 31 | """The operation is not allowed in this state.""" |
| 32 | # TODO: Show the future, its state, the method, and the required state. |
| 33 | |
| 34 | |
| 35 | class _TracebackLogger: |
| 36 | """Helper to log a traceback upon destruction if not cleared. |
| 37 | |
| 38 | This solves a nasty problem with Futures and Tasks that have an |
| 39 | exception set: if nobody asks for the exception, the exception is |
| 40 | never logged. This violates the Zen of Python: 'Errors should |
| 41 | never pass silently. Unless explicitly silenced.' |
| 42 | |
| 43 | However, we don't want to log the exception as soon as |
| 44 | set_exception() is called: if the calling code is written |
| 45 | properly, it will get the exception and handle it properly. But |
| 46 | we *do* want to log it if result() or exception() was never called |
| 47 | -- otherwise developers waste a lot of time wondering why their |
| 48 | buggy code fails silently. |
| 49 | |
| 50 | An earlier attempt added a __del__() method to the Future class |
| 51 | itself, but this backfired because the presence of __del__() |
| 52 | prevents garbage collection from breaking cycles. A way out of |
| 53 | this catch-22 is to avoid having a __del__() method on the Future |
| 54 | class itself, but instead to have a reference to a helper object |
| 55 | with a __del__() method that logs the traceback, where we ensure |
| 56 | that the helper object doesn't participate in cycles, and only the |
| 57 | Future has a reference to it. |
| 58 | |
| 59 | The helper object is added when set_exception() is called. When |
| 60 | the Future is collected, and the helper is present, the helper |
| 61 | object is also collected, and its __del__() method will log the |
| 62 | traceback. When the Future's result() or exception() method is |
| 63 | called (and a helper object is present), it removes the the helper |
| 64 | object, after calling its clear() method to prevent it from |
| 65 | logging. |
| 66 | |
| 67 | One downside is that we do a fair amount of work to extract the |
| 68 | traceback from the exception, even when it is never logged. It |
| 69 | would seem cheaper to just store the exception object, but that |
| 70 | references the traceback, which references stack frames, which may |
| 71 | reference the Future, which references the _TracebackLogger, and |
| 72 | then the _TracebackLogger would be included in a cycle, which is |
| 73 | what we're trying to avoid! As an optimization, we don't |
| 74 | immediately format the exception; we only do the work when |
| 75 | activate() is called, which call is delayed until after all the |
| 76 | Future's callbacks have run. Since usually a Future has at least |
| 77 | one callback (typically set by 'yield from') and usually that |
| 78 | callback extracts the callback, thereby removing the need to |
| 79 | format the exception. |
| 80 | |
| 81 | PS. I don't claim credit for this solution. I first heard of it |
| 82 | in a discussion about closing files when they are collected. |
| 83 | """ |
| 84 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 85 | __slots__ = ['exc', 'tb', 'loop'] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 86 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 87 | def __init__(self, exc, loop): |
| 88 | self.loop = loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 89 | self.exc = exc |
| 90 | self.tb = None |
| 91 | |
| 92 | def activate(self): |
| 93 | exc = self.exc |
| 94 | if exc is not None: |
| 95 | self.exc = None |
| 96 | self.tb = traceback.format_exception(exc.__class__, exc, |
| 97 | exc.__traceback__) |
| 98 | |
| 99 | def clear(self): |
| 100 | self.exc = None |
| 101 | self.tb = None |
| 102 | |
| 103 | def __del__(self): |
| 104 | if self.tb: |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 105 | msg = 'Future/Task exception was never retrieved:\n{tb}' |
| 106 | context = { |
| 107 | 'message': msg.format(tb=''.join(self.tb)), |
| 108 | } |
| 109 | self.loop.call_exception_handler(context) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 110 | |
| 111 | |
| 112 | class Future: |
| 113 | """This class is *almost* compatible with concurrent.futures.Future. |
| 114 | |
| 115 | Differences: |
| 116 | |
| 117 | - result() and exception() do not take a timeout argument and |
| 118 | raise an exception when the future isn't done yet. |
| 119 | |
| 120 | - Callbacks registered with add_done_callback() are always called |
| 121 | via the event loop's call_soon_threadsafe(). |
| 122 | |
| 123 | - This class is not compatible with the wait() and as_completed() |
| 124 | methods in the concurrent.futures package. |
| 125 | |
| 126 | (In Python 3.4 or later we may be able to unify the implementations.) |
| 127 | """ |
| 128 | |
| 129 | # Class variables serving as defaults for instance variables. |
| 130 | _state = _PENDING |
| 131 | _result = None |
| 132 | _exception = None |
| 133 | _loop = None |
| 134 | |
| 135 | _blocking = False # proper use of future (yield vs yield from) |
| 136 | |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 137 | _log_traceback = False # Used for Python 3.4 and later |
| 138 | _tb_logger = None # Used for Python 3.3 only |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 139 | |
| 140 | def __init__(self, *, loop=None): |
| 141 | """Initialize the future. |
| 142 | |
| 143 | The optional event_loop argument allows to explicitly set the event |
| 144 | loop object used by the future. If it's not provided, the future uses |
| 145 | the default event loop. |
| 146 | """ |
| 147 | if loop is None: |
| 148 | self._loop = events.get_event_loop() |
| 149 | else: |
| 150 | self._loop = loop |
| 151 | self._callbacks = [] |
| 152 | |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 153 | def _format_callbacks(self): |
| 154 | cb = self._callbacks |
| 155 | size = len(cb) |
| 156 | if not size: |
| 157 | cb = '' |
| 158 | |
| 159 | def format_cb(callback): |
| 160 | return events._format_callback(callback, ()) |
| 161 | |
| 162 | if size == 1: |
| 163 | cb = format_cb(cb[0]) |
| 164 | elif size == 2: |
| 165 | cb = '{}, {}'.format(format_cb(cb[0]), format_cb(cb[1])) |
| 166 | elif size > 2: |
| 167 | cb = '{}, <{} more>, {}'.format(format_cb(cb[0]), |
| 168 | size-2, |
| 169 | format_cb(cb[-1])) |
| 170 | return 'cb=[%s]' % cb |
| 171 | |
| 172 | def _format_result(self): |
| 173 | if self._state != _FINISHED: |
| 174 | return None |
| 175 | elif self._exception is not None: |
| 176 | return 'exception={!r}'.format(self._exception) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 177 | else: |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 178 | return 'result={!r}'.format(self._result) |
| 179 | |
| 180 | def __repr__(self): |
| 181 | info = [self._state.lower()] |
| 182 | if self._state == _FINISHED: |
| 183 | info.append(self._format_result()) |
| 184 | if self._callbacks: |
| 185 | info.append(self._format_callbacks()) |
| 186 | return '<%s %s>' % (self.__class__.__name__, ' '.join(info)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 187 | |
Victor Stinner | a02f81f | 2014-06-24 22:37:53 +0200 | [diff] [blame] | 188 | # On Python 3.3 or older, objects with a destructor part of a reference |
| 189 | # cycle are never destroyed. It's not more the case on Python 3.4 thanks to |
| 190 | # the PEP 442. |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 191 | if _PY34: |
| 192 | def __del__(self): |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 193 | if not self._log_traceback: |
| 194 | # set_exception() was not called, or result() or exception() |
| 195 | # has consumed the exception |
| 196 | return |
| 197 | exc = self._exception |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 198 | context = { |
| 199 | 'message': 'Future/Task exception was never retrieved', |
| 200 | 'exception': exc, |
| 201 | 'future': self, |
| 202 | } |
| 203 | self._loop.call_exception_handler(context) |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 204 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 205 | def cancel(self): |
| 206 | """Cancel the future and schedule callbacks. |
| 207 | |
| 208 | If the future is already done or cancelled, return False. Otherwise, |
| 209 | change the future's state to cancelled, schedule the callbacks and |
| 210 | return True. |
| 211 | """ |
| 212 | if self._state != _PENDING: |
| 213 | return False |
| 214 | self._state = _CANCELLED |
| 215 | self._schedule_callbacks() |
| 216 | return True |
| 217 | |
| 218 | def _schedule_callbacks(self): |
| 219 | """Internal: Ask the event loop to call all callbacks. |
| 220 | |
| 221 | The callbacks are scheduled to be called as soon as possible. Also |
| 222 | clears the callback list. |
| 223 | """ |
| 224 | callbacks = self._callbacks[:] |
| 225 | if not callbacks: |
| 226 | return |
| 227 | |
| 228 | self._callbacks[:] = [] |
| 229 | for callback in callbacks: |
| 230 | self._loop.call_soon(callback, self) |
| 231 | |
| 232 | def cancelled(self): |
| 233 | """Return True if the future was cancelled.""" |
| 234 | return self._state == _CANCELLED |
| 235 | |
| 236 | # Don't implement running(); see http://bugs.python.org/issue18699 |
| 237 | |
| 238 | def done(self): |
| 239 | """Return True if the future is done. |
| 240 | |
| 241 | Done means either that a result / exception are available, or that the |
| 242 | future was cancelled. |
| 243 | """ |
| 244 | return self._state != _PENDING |
| 245 | |
| 246 | def result(self): |
| 247 | """Return the result this future represents. |
| 248 | |
| 249 | If the future has been cancelled, raises CancelledError. If the |
| 250 | future's result isn't yet available, raises InvalidStateError. If |
| 251 | the future is done and has an exception set, this exception is raised. |
| 252 | """ |
| 253 | if self._state == _CANCELLED: |
| 254 | raise CancelledError |
| 255 | if self._state != _FINISHED: |
| 256 | raise InvalidStateError('Result is not ready.') |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 257 | self._log_traceback = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 258 | if self._tb_logger is not None: |
| 259 | self._tb_logger.clear() |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 260 | self._tb_logger = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 261 | if self._exception is not None: |
| 262 | raise self._exception |
| 263 | return self._result |
| 264 | |
| 265 | def exception(self): |
| 266 | """Return the exception that was set on this future. |
| 267 | |
| 268 | The exception (or None if no exception was set) is returned only if |
| 269 | the future is done. If the future has been cancelled, raises |
| 270 | CancelledError. If the future isn't done yet, raises |
| 271 | InvalidStateError. |
| 272 | """ |
| 273 | if self._state == _CANCELLED: |
| 274 | raise CancelledError |
| 275 | if self._state != _FINISHED: |
| 276 | raise InvalidStateError('Exception is not set.') |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 277 | self._log_traceback = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 278 | if self._tb_logger is not None: |
| 279 | self._tb_logger.clear() |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 280 | self._tb_logger = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 281 | return self._exception |
| 282 | |
| 283 | def add_done_callback(self, fn): |
| 284 | """Add a callback to be run when the future becomes done. |
| 285 | |
| 286 | The callback is called with a single argument - the future object. If |
| 287 | the future is already done when this is called, the callback is |
| 288 | scheduled with call_soon. |
| 289 | """ |
| 290 | if self._state != _PENDING: |
| 291 | self._loop.call_soon(fn, self) |
| 292 | else: |
| 293 | self._callbacks.append(fn) |
| 294 | |
| 295 | # New method not in PEP 3148. |
| 296 | |
| 297 | def remove_done_callback(self, fn): |
| 298 | """Remove all instances of a callback from the "call when done" list. |
| 299 | |
| 300 | Returns the number of callbacks removed. |
| 301 | """ |
| 302 | filtered_callbacks = [f for f in self._callbacks if f != fn] |
| 303 | removed_count = len(self._callbacks) - len(filtered_callbacks) |
| 304 | if removed_count: |
| 305 | self._callbacks[:] = filtered_callbacks |
| 306 | return removed_count |
| 307 | |
| 308 | # So-called internal methods (note: no set_running_or_notify_cancel()). |
| 309 | |
| 310 | def set_result(self, result): |
| 311 | """Mark the future done and set its result. |
| 312 | |
| 313 | If the future is already done when this method is called, raises |
| 314 | InvalidStateError. |
| 315 | """ |
| 316 | if self._state != _PENDING: |
| 317 | raise InvalidStateError('{}: {!r}'.format(self._state, self)) |
| 318 | self._result = result |
| 319 | self._state = _FINISHED |
| 320 | self._schedule_callbacks() |
| 321 | |
| 322 | def set_exception(self, exception): |
| 323 | """Mark the future done and set an exception. |
| 324 | |
| 325 | If the future is already done when this method is called, raises |
| 326 | InvalidStateError. |
| 327 | """ |
| 328 | if self._state != _PENDING: |
| 329 | raise InvalidStateError('{}: {!r}'.format(self._state, self)) |
Victor Stinner | 9572898 | 2014-01-30 16:01:54 -0800 | [diff] [blame] | 330 | if isinstance(exception, type): |
| 331 | exception = exception() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 332 | self._exception = exception |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 333 | self._state = _FINISHED |
| 334 | self._schedule_callbacks() |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 335 | if _PY34: |
Victor Stinner | e40c078 | 2013-12-21 00:19:33 +0100 | [diff] [blame] | 336 | self._log_traceback = True |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 337 | else: |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 338 | self._tb_logger = _TracebackLogger(exception, self._loop) |
Victor Stinner | 4c3c699 | 2013-12-19 22:42:40 +0100 | [diff] [blame] | 339 | # Arrange for the logger to be activated after all callbacks |
| 340 | # have had a chance to call result() or exception(). |
| 341 | self._loop.call_soon(self._tb_logger.activate) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 342 | |
| 343 | # Truly internal methods. |
| 344 | |
| 345 | def _copy_state(self, other): |
| 346 | """Internal helper to copy state from another Future. |
| 347 | |
| 348 | The other Future may be a concurrent.futures.Future. |
| 349 | """ |
| 350 | assert other.done() |
Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 351 | if self.cancelled(): |
| 352 | return |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 353 | assert not self.done() |
| 354 | if other.cancelled(): |
| 355 | self.cancel() |
| 356 | else: |
| 357 | exception = other.exception() |
| 358 | if exception is not None: |
| 359 | self.set_exception(exception) |
| 360 | else: |
| 361 | result = other.result() |
| 362 | self.set_result(result) |
| 363 | |
| 364 | def __iter__(self): |
| 365 | if not self.done(): |
| 366 | self._blocking = True |
| 367 | yield self # This tells Task to wait for completion. |
| 368 | assert self.done(), "yield from wasn't used with future" |
| 369 | return self.result() # May raise too. |
| 370 | |
| 371 | |
| 372 | def wrap_future(fut, *, loop=None): |
| 373 | """Wrap concurrent.futures.Future object.""" |
| 374 | if isinstance(fut, Future): |
| 375 | return fut |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 376 | assert isinstance(fut, concurrent.futures.Future), \ |
| 377 | 'concurrent.futures.Future is expected, got {!r}'.format(fut) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 378 | if loop is None: |
| 379 | loop = events.get_event_loop() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 380 | new_future = Future(loop=loop) |
Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 381 | |
| 382 | def _check_cancel_other(f): |
| 383 | if f.cancelled(): |
| 384 | fut.cancel() |
| 385 | |
| 386 | new_future.add_done_callback(_check_cancel_other) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 387 | fut.add_done_callback( |
| 388 | lambda future: loop.call_soon_threadsafe( |
| 389 | new_future._copy_state, fut)) |
| 390 | return new_future |