òÕYf§Dã@sNdZddddddgZddlZddlZddlZddlZddlZd d lm Z d d lm Z d Z d Z dZ ejjjZejjZejjZejd ZGdd„deƒZGdd„dƒZdd„ZGdd„dƒZdd„Zdd„Zdd„Zdd„Zdddd„ZdS)z.A Future class similar to the one in PEP 3148.ÚCancelledErrorÚ TimeoutErrorÚInvalidStateErrorÚFutureÚ wrap_futureÚisfutureéNé)Úcompat)ÚeventsZPENDINGZ CANCELLEDZFINISHEDc@seZdZdZdS)rz+The operation is not allowed in this state.N)Ú__name__Ú __module__Ú __qualname__Ú__doc__©rrú4/opt/alt/python35/lib64/python3.5/asyncio/futures.pyrs c@sLeZdZdZdZdd„Zdd „Zd d „Zd d „ZdS)Ú_TracebackLoggera Helper to log a traceback upon destruction if not cleared. This solves a nasty problem with Futures and Tasks that have an exception set: if nobody asks for the exception, the exception is never logged. This violates the Zen of Python: 'Errors should never pass silently. Unless explicitly silenced.' However, we don't want to log the exception as soon as set_exception() is called: if the calling code is written properly, it will get the exception and handle it properly. But we *do* want to log it if result() or exception() was never called -- otherwise developers waste a lot of time wondering why their buggy code fails silently. An earlier attempt added a __del__() method to the Future class itself, but this backfired because the presence of __del__() prevents garbage collection from breaking cycles. A way out of this catch-22 is to avoid having a __del__() method on the Future class itself, but instead to have a reference to a helper object with a __del__() method that logs the traceback, where we ensure that the helper object doesn't participate in cycles, and only the Future has a reference to it. The helper object is added when set_exception() is called. When the Future is collected, and the helper is present, the helper object is also collected, and its __del__() method will log the traceback. When the Future's result() or exception() method is called (and a helper object is present), it removes the helper object, after calling its clear() method to prevent it from logging. One downside is that we do a fair amount of work to extract the traceback from the exception, even when it is never logged. It would seem cheaper to just store the exception object, but that references the traceback, which references stack frames, which may reference the Future, which references the _TracebackLogger, and then the _TracebackLogger would be included in a cycle, which is what we're trying to avoid! As an optimization, we don't immediately format the exception; we only do the work when activate() is called, which call is delayed until after all the Future's callbacks have run. Since usually a Future has at least one callback (typically set by 'yield from') and usually that callback extracts the callback, thereby removing the need to format the exception. PS. I don't claim credit for this solution. I first heard of it in a discussion about closing files when they are collected. ÚloopÚsource_tracebackÚexcÚtbcCs.|j|_|j|_||_d|_dS)N)Ú_looprÚ_source_tracebackrrr)ÚselfÚfuturerrrrÚ__init__Us   z_TracebackLogger.__init__cCs@|j}|dk r<d|_tj|j||jƒ|_dS)N)rÚ tracebackÚformat_exceptionÚ __class__Ú __traceback__r)rrrrrÚactivate[s    z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrrÚclearbs z_TracebackLogger.clearcCs‡|jrƒd}|jrQdjtj|jƒƒ}|d7}|d|jƒ7}|dj|jƒjƒ7}|jjd|iƒdS)Nz*Future/Task exception was never retrieved Úz0Future/Task created at (most recent call last): z%s Úmessage)rrÚjoinrÚ format_listÚrstriprÚcall_exception_handler)rÚmsgÚsrcrrrÚ__del__fs   z_TracebackLogger.__del__N)rrrr) r r r rÚ __slots__rrr r)rrrrr!s 0   rcCst|jdƒo|jdk S)zÓCheck for a Future. This returns True when obj is a Future instance or is advertising itself as duck-type compatible by setting _asyncio_future_blocking. See comment in Future for more details. Ú_asyncio_future_blockingN)Úhasattrrr+)Úobjrrrrqsc@s$eZdZdZeZdZdZdZdZ dZ dZ dZ dddd„Z dd„Zd d „Zd d „Zejr�d d„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd „Zd!d"„Zd#d$„Zejr eZ dS)%raThis class is *almost* compatible with concurrent.futures.Future. Differences: - result() and exception() do not take a timeout argument and raise an exception when the future isn't done yet. - Callbacks registered with add_done_callback() are always called via the event loop's call_soon_threadsafe(). - This class is not compatible with the wait() and as_completed() methods in the concurrent.futures package. (In Python 3.4 or later we may be able to unify the implementations.) NFrcCs^|dkrtjƒ|_n ||_g|_|jjƒrZtjtjdƒƒ|_ dS)zÛInitialize the future. The optional event_loop argument allows explicitly setting the event loop object used by the future. If it's not provided, the future uses the default event loop. Nr) r Úget_event_looprÚ _callbacksZ get_debugrÚ extract_stackÚsysÚ _getframer)rrrrrr¡s    zFuture.__init__cCsÂ|j}t|ƒ}|s!d}dd„}|dkrL||dƒ}nn|dkr�dj||dƒ||dƒƒ}n9|dkrºdj||dƒ|d||d ƒƒ}d |S) Nr!cSstj|fƒS)N)r Z_format_callback_source)ÚcallbackrrrÚ format_cb¶sz,Future.__format_callbacks..format_cbrréz{}, {}z{}, <{} more>, {}zcb=[%s]éÿÿÿÿ)r/ÚlenÚformat)rÚcbÚsizer4rrrZ__format_callbacks°s     ) zFuture.__format_callbackscCsÉ|jjƒg}|jtkrt|jdk rL|jdj|jƒƒn(tj|jƒ}|jdj|ƒƒ|j r�|j|j ƒƒ|j rÅ|j d}|jd|d|dfƒ|S)Nzexception={!r}z result={}rzcreated at %s:%srr6) Ú_stateÚlowerÚ _FINISHEDÚ _exceptionÚappendr8ÚreprlibÚreprÚ_resultr/Ú_Future__format_callbacksr)rÚinfoÚresultÚframerrrÚ _repr_infoÃs   zFuture._repr_infocCs)|jƒ}d|jjdj|ƒfS)Nz<%s %s>ú )rGrr r#)rrDrrrÚ__repr__Ôs zFuture.__repr__cCsb|js dS|j}dd|jjd|d|i}|jrN|j|d<|jj|ƒdS)Nr"z %s exception was never retrievedÚ exceptionrr)Ú_log_tracebackr>rr rrr&)rrÚcontextrrrr)Üs      zFuture.__del__cCs3d|_|jtkrdSt|_|jƒdS)záCancel the future and schedule callbacks. If the future is already done or cancelled, return False. Otherwise, change the future's state to cancelled, schedule the callbacks and return True. FT)rKr;Ú_PENDINGÚ _CANCELLEDÚ_schedule_callbacks)rrrrÚcancelìs    z Future.cancelcCsX|jdd…}|sdSg|jdd…rB)rrrrrEs     z Future.resultcCse|jtkrt‚|jtkr0tdƒ‚d|_|jdk r^|jjƒd|_|jS)a&Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises CancelledError. If the future isn't done yet, raises InvalidStateError. zException is not set.FN) r;rNrr=rrKrTr r>)rrrrrJ)s    zFuture.exceptioncCs9|jtkr%|jj||ƒn|jj|ƒdS)zøAdd a callback to be run when the future becomes done. The callback is called with a single argument - the future object. If the future is already done when this is called, the callback is scheduled with call_soon. N)r;rMrrQr/r?)rÚfnrrrÚadd_done_callback;szFuture.add_done_callbackcsR‡fdd†|jDƒ}t|jƒt|ƒ}|rN||jdd…<|S)z}Remove all instances of a callback from the "call when done" list. Returns the number of callbacks removed. cs"g|]}|ˆkr|‘qSrr)Ú.0Úf)rUrrú Ns z/Future.remove_done_callback..N)r/r7)rrUZfiltered_callbacksZ removed_countr)rUrÚremove_done_callbackIs zFuture.remove_done_callbackcCsJ|jtkr*tdj|j|ƒƒ‚||_t|_|jƒdS)z–Mark the future done and set its result. If the future is already done when this method is called, raises InvalidStateError. z{}: {!r}N)r;rMrr8rBr=rO)rrErrrÚ set_resultVs   zFuture.set_resultcCs½|jtkr*tdj|j|ƒƒ‚t|tƒrB|ƒ}t|ƒtkr`tdƒ‚||_t |_|j ƒt j r‘d|_ n(t||ƒ|_|jj|jjƒdS)z˜Mark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError. z{}: {!r}zPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r;rMrr8Ú isinstanceÚtypeÚ StopIterationÚ TypeErrorr>r=rOr ÚPY34rKrrTrrQr)rrJrrrÚ set_exceptionbs       zFuture.set_exceptionccs$|jƒsd|_|V|jƒS)NT)rSr+rE)rrrrÚ__iter__zs  zFuture.__iter__)!r r r rrMr;rBr>rrr+rKrTrrCrGrIr r`r)rPrOrRrSrErJrVrZr[rarbZPY35Ú __await__rrrrr|s8                 cCs!|jƒrdS|j|ƒdS)z?Helper setting the result only if the future was not cancelled.N)rRr[)ZfutrErrrÚ_set_result_unless_cancelled…s rdcCsk|jƒr|jƒ|jƒs&dS|jƒ}|dk rN|j|ƒn|jƒ}|j|ƒdS)z8Copy state from a future to a concurrent.futures.Future.N)rRrPZset_running_or_notify_cancelrJrarEr[)Ú concurrentÚsourcerJrErrrÚ_set_concurrent_future_stateŒs      rgcCsn|jƒrdS|jƒr)|jƒnA|jƒ}|dk rQ|j|ƒn|jƒ}|j|ƒdS)zqInternal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. N)rRrPrJrarEr[)rfÚdestrJrErrrÚ_copy_future_state›s      ricsñtˆƒ r/tˆtjjƒ r/tdƒ‚tˆƒ r^tˆtjjƒ r^tdƒ‚tˆƒrsˆjnd‰tˆƒrŽˆjnd‰dd„‰‡‡‡fdd†}‡‡‡‡fdd †}ˆj|ƒˆj|ƒdS) aChain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future. z(A future is required for source argumentz-A future is required for destination argumentNcSs-t|ƒrt||ƒn t||ƒdS)N)rrirg)rÚotherrrrÚ _set_state¿s z!_chain_future.._set_statecsE|jƒrAˆdks$ˆˆkr1ˆjƒnˆjˆjƒdS)N)rRrPÚcall_soon_threadsafe)Ú destination)Ú dest_looprfÚ source_looprrÚ_call_check_cancelÅs  z)_chain_future.._call_check_cancelcs?ˆdksˆˆkr(ˆˆ|ƒnˆjˆˆ|ƒdS)N)rl)rf)rkrnrmrorrÚ_call_set_stateÌsz&_chain_future.._call_set_state)rr\reÚfuturesrr_rrV)rfrmrprqr)rkrnrmrfrorÚ _chain_future¯s    rsrcCsEt|ƒr|S|dkr(tjƒ}|jƒ}t||ƒ|S)z&Wrap concurrent.futures.Future object.N)rr r.Z create_futurers)rrZ new_futurerrrrÖs     )rÚ__all__Zconcurrent.futures._basereZloggingr@r1rr!r r rMrNr=rrZ_baseÚErrorrrÚDEBUGZ STACK_DEBUGrrrrrdrgrirsrrrrrÚs6        P ÿ    '