
    3 d'6                     B   d Z ddlZddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZmZmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddl m!Z!m"Z" dedefdZ#defdZ$defdZ%de
defdZ&dede'de
defdZ( G d de          Z)de	de'de
defdZ*dee
         defdZ+dee
         dee
         defdZ,dee
         defd Z-ded!e
defd"Z.d#e	d!e
defd$Z/defd%Z0d&e
d'ef         de
fd(Z1de
defd)Z2d*edefd+Z3d*edeeef         fd,Z4dS )-z5
Helper functions for dealing with Twisted deferreds
    N)Futurewraps)AnyAsyncGeneratorAsyncIterableCallable	Coroutine	GeneratorIterableIteratorListOptionalUnion)defer)DeferredDeferredListensureDeferred)
Cooperator)failure)Failure)IgnoreRequest)_get_asyncio_event_loopis_asyncio_reactor_installed_failurereturnc                 f    ddl m} t                      }|                    d|j        |            |S )zSame as twisted.internet.defer.fail but delay calling errback until
    next reactor loop

    It delays by 100ms so reactor has a chance to go through readers and writers
    before attending pending delayed calls, so do not set delay to zero.
    r   reactor皙?)twisted.internetr   r   	callLatererrback)r   r   ds      2lib/python3.11/site-packages/scrapy/utils/defer.py
defer_failr&       s>     )(((((

Ac19h///H    c                 f    ddl m} t                      }|                    d|j        |            |S )zSame as twisted.internet.defer.succeed but delay calling callback until
    next reactor loop

    It delays by 100ms so reactor has a chance to go through readers and writers
    before attending pending delayed calls, so do not set delay to zero.
    r   r   r    )r!   r   r   r"   callback)resultr   r$   s      r%   defer_succeedr+   .   s>     )(((((

Ac1:v...Hr'   c                     t          | t                    r| S t          | t          j                  rt	          |           S t          |           S N)
isinstancer   r   r   r&   r+   )r*   s    r%   defer_resultr/   <   sI    &(## &'/** "&!!!   r'   fc                     	  | |i |}t          |          S # t          $ r+}t          t          j        |                    cY d}~S d}~wt
          $ r# t          t          j                              cY S w xY w)znSame as twisted.internet.defer.maybeDeferred, but delay calling
    callback/errback to next reactor loop
    N)r/   r   r&   r   r   	Exception)r0   argskwr*   es        r%   mustbe_deferredr6   D   s    
$DB F###  . . .'/!,,-------- - - -'/++,,,,,-s     
A9 A	A9	-A98A9iterablecountcallablec                     t                      fd| D             t          fdt          |          D                       S )zExecute a callable over the objects in the given iterable, in parallel,
    using no more than ``count`` concurrent calls.

    Taken from: https://jcalderone.livejournal.com/24285.html
    c              3   0   K   | ]} |gR i V  d S r-    ).0elemr3   r9   nameds     r%   	<genexpr>zparallel.<locals>.<genexpr>^   s=      @@tHHT*D***E**@@@@@@r'   c                 :    g | ]}                               S r<   	coiterater=   _coopworks     r%   
<listcomp>zparallel.<locals>.<listcomp>_   s%    DDD!--DDDr'   )r   r   range)r7   r8   r9   r3   r?   rF   rG   s     ```@@r%   parallelrJ   U   s]     <<D@@@@@@x@@@DDDDDDuU||DDDEEEr'   c                   V    e Zd ZdZdedefdZdeddfdZd	e	ddfd
Z
ddZdefdZdS )_AsyncCooperatorAdaptera[
  A class that wraps an async iterable into a normal iterator suitable
    for using in Cooperator.coiterate(). As it's only needed for parallel_async(),
    it calls the callable directly in the callback, instead of providing a more
    generic interface.

    On the outside, this class behaves as an iterator that yields Deferreds.
    Each Deferred is fired with the result of the callable which was called on
    the next result from aiterator. It raises StopIteration when aiterator is
    exhausted, as expected.

    Cooperator calls __next__() multiple times and waits on the Deferreds
    returned from it. As async generators (since Python 3.8) don't support
    awaiting on __anext__() several times in parallel, we need to serialize
    this. It's done by storing the Deferreds returned from __next__() and
    firing the oldest one when a result from __anext__() is available.

    The workflow:
    1. When __next__() is called for the first time, it creates a Deferred, stores it
    in self.waiting_deferreds and returns it. It also makes a Deferred that will wait
    for self.aiterator.__anext__() and puts it into self.anext_deferred.
    2. If __next__() is called again before self.anext_deferred fires, more Deferreds
    are added to self.waiting_deferreds.
    3. When self.anext_deferred fires, it either calls _callback() or _errback(). Both
    clear self.anext_deferred.
    3.1. _callback() calls the callable passing the result value that it takes, pops a
    Deferred from self.waiting_deferreds, and if the callable result was a Deferred, it
    chains those Deferreds so that the waiting Deferred will fire when the result
    Deferred does, otherwise it fires it directly. This causes one awaiting task to
    receive a result. If self.waiting_deferreds is still not empty, new __anext__() is
    called and self.anext_deferred is populated.
    3.2. _errback() checks the exception class. If it's StopAsyncIteration it means
    self.aiterator is exhausted and so it sets self.finished and fires all
    self.waiting_deferreds. Other exceptions are propagated.
    4. If __next__() is called after __anext__() was handled, then if self.finished is
    True, it raises StopIteration, otherwise it acts like in step 2, but if
    self.anext_deferred is now empty is also populates it with a new __anext__().

    Note that CooperativeTask ignores the value returned from the Deferred that it waits
    for, so we fire them with None when needed.

    It may be possible to write an async iterator-aware replacement for
    Cooperator/CooperativeTask and use it instead of this adapter to achieve the same
    goal.
    	aiterabler9   c                     |                                 | _        || _        || _        || _        d| _        g | _        d | _        d S )NF)	__aiter__	aiteratorr9   callable_argscallable_kwargsfinishedwaiting_deferredsanext_deferred)selfrM   r9   rQ   rR   s        r%   __init__z _AsyncCooperatorAdapter.__init__   sK     #,,.. *.1326r'   r*   r   Nc                 8   d | _          | j        |g| j        R i | j        }| j                            d          }t          |t                    r|                    |           n|	                    d            | j        r| 
                                 d S d S )Nr   )rU   r9   rQ   rR   rT   popr.   r   chainDeferredr)   _call_anext)rV   r*   r$   s      r%   	_callbackz!_AsyncCooperatorAdapter._callback   s     #vS(:SSSd>RSS"&&q))fh'' 	  ####JJt! 		 	r'   r   c                     d | _          |j        t                     d| _        | j        D ]}|                    d            d S )NT)rU   trapStopAsyncIterationrS   rT   r)   )rV   r   r$   s      r%   _errbackz _AsyncCooperatorAdapter._errback   sW     #'(((' 	 	AJJt	 	r'   c                     t          | j                                                  | _        | j                            | j        | j                   d S r-   )deferred_from_cororP   	__anext__rU   addCallbacksr\   r`   )rV   s    r%   r[   z#_AsyncCooperatorAdapter._call_anext   sE     11I1I1K1KLL((GGGGGr'   c                     | j         rt          t                      }| j                            |           | j        s|                                  |S r-   )rS   StopIterationr   rT   appendrU   r[   )rV   r$   s     r%   __next__z _AsyncCooperatorAdapter.__next__   sV     = 	 JJ%%a(((" 	r'   )r   N)__name__
__module____qualname____doc__r   r	   rW   r   r\   r   r`   r[   r   rh   r<   r'   r%   rL   rL   b   s        + +Z7 7 7 7 7 7      D    H H H H	( 	 	 	 	 	 	r'   rL   async_iterablec                     t                      t          | |g|R i |t          fdt          |          D                       }|S )z%Like parallel but for async iteratorsc                 :    g | ]}                               S r<   rB   rD   s     r%   rH   z"parallel_async.<locals>.<listcomp>   s%    BBBt~~d++BBBr'   )r   rL   r   rI   )rm   r8   r9   r3   r?   dlrF   rG   s         @@r%   parallel_asyncrq      s^     <<D">8LdLLLeLLD	BBBBBU5\\BBB	C	CBIr'   	callbacksc                 x    t                      }| D ]} |j        |g|R i | |                    |           |S )z7Return a Deferred built by chaining the given callbacks)r   addCallbackr)   )rr   inputar4   r$   xs         r%   process_chainrx      sV    

A # #a"!"""r""""JJuHr'   errbacksc           	         t                      }t          | |          D ] \  }}|                    ||||||           !t          |t          j                  r|                    |           n|                    |           |S )zDReturn a Deferred built by chaining the given callbacks and errbacks)r)   r#   callbackArgscallbackKeywordserrbackArgserrbackKeywords)r   ziprd   r.   r   r   r#   r)   )rr   ry   ru   rv   r4   r$   cbebs           r%   process_chain_bothr      s     	

Ai** 
 
B	 	 	
 	
 	
 	
 %)) 			%	

5Hr'   c                     fd| D             }t          |dd          }|                    d d            |S )zYReturn a Deferred with the output of all successful calls to the given
    callbacks
    c                 V    g | ]%} t          j                  j        |gR i &S r<   )r   succeedrt   )r=   rw   rv   ru   r4   s     r%   rH   z$process_parallel.<locals>.<listcomp>   sA    MMMa,EM%  ,Q9999b99MMMr'   T)fireOnOneErrbackconsumeErrorsc                     d | D             S )Nc                     g | ]
}|d          S )   r<   )r=   rw   s     r%   rH   z6process_parallel.<locals>.<lambda>.<locals>.<listcomp>   s    ...qad...r'   r<   )rs    r%   <lambda>z"process_parallel.<locals>.<lambda>   s    ..A... r'   c                     | j         j        S r-   )value
subFailure)r0   s    r%   r   z"process_parallel.<locals>.<lambda>   s    !':L r'   )r   rd   )rr   ru   rv   r4   dfdsr$   s    ```  r%   process_parallelr      s\     NMMMMM9MMMDTDEEEANN..0L0LMMMHr'   r#   c              /      K   t          |           }	 	 t          |          V  n9# t          $ r Y dS t          $ r   |t	          j                    g|R i | Y nw xY wM)zWWraps an iterable calling an errback if an error is caught while
    iterating it.
    TN)iternextrf   r2   r   r   )r7   r#   rv   r4   its        r%   iter_errbackr      s       
hB1	1r((NNNN 	 	 	EE 	1 	1 	1GGO%%0000R00000	11s   & 
A&AArM   c                   K   |                                  }	 	 |                                 d{V W V  n9# t          $ r Y dS t          $ r   |t	          j                    g|R i | Y nw xY wY)zWraps an async iterable calling an errback if an error is caught while
    iterating it. Similar to scrapy.utils.defer.iter_errback()
    TN)rO   rc   r_   r2   r   r   )rM   r#   rv   r4   r   s        r%   aiter_errbackr     s       
				B1	1&&&&&&&&&&&! 	 	 	EE 	1 	1 	1GGO%%0000R00000	11s   7 
A-&A-,A-c                 *   t          | t                    r| S t          j        |           st	          j        |           rSt                      st          |           S t                      }t          j	        t          j
        | |                    S | S )zYConverts a coroutine into a Deferred, or returns the object as is if it isn't a coroutine)loop)r.   r   asyncioisfutureinspectisawaitabler   r   r   
fromFutureensure_future)o
event_loops     r%   rb   rb     s    !X  Ng1!44 N+-- 	% "!$$$,..
"7#8#L#L#LMMMHr'   coro_f.c                 <     t                      fd            }|S )a-  Converts a coroutine function into a function that returns a Deferred.

    The coroutine function will be called at the time when the wrapper is called. Wrapper args will be passed to it.
    This is useful for callback chains, as callback functions are called with the previous callback result.
    c                  .    t           | i |          S r-   )rb   )	coro_argscoro_kwargsr   s     r%   r0   z!deferred_f_from_coro_f.<locals>.f.  s     !&&)"C{"C"CDDDr'   r   )r   r0   s   ` r%   deferred_f_from_coro_fr   '  s:     6]]E E E E ]E Hr'   c                    	  | |i |}n8#  t          j        t          j        t          j                            cY S xY wt          |t                    r|S t          j        |          st          j
        |          rt          |          S t          |t          j                  rt          j        |          S t          j        |          S )zGCopy of defer.maybeDeferred that also converts coroutines to Deferreds.)captureVars)r   failr   r   r   debugr.   r   r   r   r   rb   r   )r0   r3   r4   r*   s       r%   maybeDeferred_coror   5  s    GDBGz'/hnEEEFFFFF&(##  *7#6v#>#> *!&)))&'/** "z&!!!=   s	    3A r$   c                 D    |                      t                                S )a  
    .. versionadded:: 2.6.0

    Return an :class:`asyncio.Future` object that wraps *d*.

    When :ref:`using the asyncio reactor <install-asyncio>`, you cannot await
    on :class:`~twisted.internet.defer.Deferred` objects from :ref:`Scrapy
    callables defined as coroutines <coroutine-support>`, you can only await on
    ``Future`` objects. Wrapping ``Deferred`` objects into ``Future`` objects
    allows you to wait on them::

        class MySpider(Spider):
            ...
            async def parse(self, response):
                d = treq.get('https://example.com/additional')
                additional_response = await deferred_to_future(d)
    )asFuturer   r$   s    r%   deferred_to_futurer   E  s    $ ::-//000r'   c                 @    t                      s| S t          |           S )a  
    .. versionadded:: 2.6.0

    Return *d* as an object that can be awaited from a :ref:`Scrapy callable
    defined as a coroutine <coroutine-support>`.

    What you can await in Scrapy callables defined as coroutines depends on the
    value of :setting:`TWISTED_REACTOR`:

    -   When not using the asyncio reactor, you can only await on
        :class:`~twisted.internet.defer.Deferred` objects.

    -   When :ref:`using the asyncio reactor <install-asyncio>`, you can only
        await on :class:`asyncio.Future` objects.

    If you want to write code that uses ``Deferred`` objects but works with any
    reactor, use this function on all ``Deferred`` objects::

        class MySpider(Spider):
            ...
            async def parse(self, response):
                d = treq.get('https://example.com/additional')
                extra_response = await maybe_deferred_to_future(d)
    )r   r   r   s    r%   maybe_deferred_to_futurer   Z  s%    2 ()) a   r'   )5rl   r   r   r   	functoolsr   typingr   r   r   r	   r
   r   r   r   r   r   r   r!   r   twisted.internet.deferr   r   r   twisted.internet.taskr   twisted.pythonr   twisted.python.failurer   scrapy.exceptionsr   scrapy.utils.reactorr   r   r&   r+   r/   r6   intrJ   rL   rq   rx   r   r   r   r   rb   r   r   r   r   r<   r'   r%   <module>r      s                                           # " " " " " I I I I I I I I I I , , , , , , " " " " " " * * * * * * + + + + + + V V V V V V V V X    X    !H ! ! ! !$x $ $ $ $ $"
F
F"
F.6
F
F 
F 
F 
Fc c c c ch c c cL!*-9A   Xh/ X    !-5h-?   * 2     18 1h 1Y 1 1 1 111'/11 1 1 1 S    8CN#;     !( !H ! ! ! ! 1( 1v 1 1 1 1*! !U8V3C-D ! ! ! ! ! !r'   