
    !h*B                       S r SSKJr  SSKrSSKrSSKrSSKJr  SSKJrJ	r	J
r
Jr  SSKJr  SSKJr  SSKJrJrJrJrJrJrJr  SS	KJr  SS
KJrJrJr  SSKJr  SSK J!r!  SSK"J#r#J$r$  SSK%J&r&J'r'  \(       a  SSKJ(r(J)r)  SSK*J+r+  SSK,J-r-J.r.  \." S5      r/\" S5      r0\" S5      r1Sr2S0S jr3S1S jr4S2S jr5S3S jr6\        S4S j5       r7\        S5S j5       r7\        S6S j5       r7        S7S jr7            S8S jr8 " S S \\\0   5      r9            S9S! jr:          S:S" jr;            S;S# jr<          S<S$ jr=          S=S% jr>          S>S& jr?\" S'\\\\4   S(9r@\S?S) j5       rA\S@S* j5       rASAS+ jrA    SBS, jrB        SCS- jrCSDS. jrDSES/ jrEg)Fz5
Helper functions for dealing with Twisted deferreds
    )annotationsN)Future)	Awaitable	CoroutineIterableIteratorwraps)CoroutineType)TYPE_CHECKINGAnyGenericTypeVarUnioncastoverload)defer)DeferredDeferredListensureDeferred)
Cooperatorfailure)IgnoreRequestScrapyDeprecationWarning)_get_asyncio_event_loopis_asyncio_reactor_installed)AsyncIteratorCallable)Failure)Concatenate	ParamSpec_P_T_T2g?c                h    SSK Jn  [        5       nUR                  [        UR
                  U 5        U$ )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_DEFER_DELAYerrback)_failurer(   ds      Y/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/scrapy/utils/defer.py
defer_failr0   .   s)     )zAlAIIx8H    c                h    SSK Jn  [        5       nUR                  [        UR
                  U 5        U$ )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_succeedr6   <   s)     )jAlAJJ7Hr1   c                 h    SSK Jn   [        5       nU R                  [        UR
                  S5        U$ )zNLike ``defer_succeed`` and ``defer_fail`` but doesn't call any real callbacks.r   r'   Nr3   )r(   r.   s     r/   _defer_sleepr8   J   s'    ( 
AlAJJ5Hr1   c                    [        U [        5      (       a  U $ [        U [        R                  5      (       a  [	        U 5      $ [        U 5      $ N)
isinstancer   r   r    r0   r6   )r5   s    r/   defer_resultr<   S   s;    &(##&'//**&!!  r1   c                    g r:    fargskws      r/   mustbe_deferredrC   [        r1   c                    g r:   r>   r?   s      r/   rC   rC   a   s    
 r1   c                    g r:   r>   r?   s      r/   rC   rC   i   rD   r1   c                     U " U0 UD6n[        U5      $ ! [          a)  n[        [        R                  " U5      5      s SnA$ SnAf[         a!    [        [        R                  " 5       5      s $ f = f)zfSame as twisted.internet.defer.maybeDeferred, but delay calling
callback/errback to next reactor loop
N)r   r0   r   r    	Exceptionr<   )r@   rA   rB   r5   es        r/   rC   rC   o   sa    -DB 	  .'//!,-- -'//+,,-s    
A1AA1+A10A1c                   ^^^ [        5       nUUU4S jU  5       n[        [        U5       Vs/ s H  ouR                  U5      PM     sn5      $ s  snf )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  <   >#    U  H  nT" U/TQ70 TD6v   M     g 7fr:   r>   ).0elemrA   callablenameds     r/   	<genexpr>parallel.<locals>.<genexpr>   s      Ohd8D94959hs   )r   r   range	coiterate)iterablecountrN   rA   rO   coopwork_s     ```   r/   parallelrY      s>     <DOhODuU|D|!-|DEEDs   Ac                  Z    \ rS rSrSr        S
S jrSS jrSS jrSS jrSS jr	Sr
g	)_AsyncCooperatorAdapter   a	  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.
c                |    UR                  5       U l        X l        X0l        X@l        SU l        / U l        S U l        g )NF)	__aiter__	aiteratorrN   callable_argscallable_kwargsfinishedwaiting_deferredsanext_deferred)self	aiterablerN   r`   ra   s        r/   __init__ _AsyncCooperatorAdapter.__init__   s<     -6,?,?,AMU.;/>#6837r1   c                P   S U l         U R                  " U/U R                  Q70 U R                  D6nU R                  R                  S5      n[        U[        5      (       a  UR                  U5        OUR                  S 5        U R                  (       a  U R                  5         g g )Nr   )rd   rN   r`   ra   rc   popr;   r   chainDeferredr4   _call_anext)re   r5   callable_resultr.   s       r/   	_callback!_AsyncCooperatorAdapter._callback   s     #--
''
+/+?+?
 ""&&q)ox00))!,JJt!! "r1   c                    S U l         UR                  " [        5        SU l        U R                   H  nUR                  S 5        M     g )NT)rd   trapStopAsyncIterationrb   rc   r4   )re   r   r.   s      r/   _errback _AsyncCooperatorAdapter._errback   s<     #'(''AJJt (r1   c                    [        U R                  R                  5       5      U l        U R                  R	                  U R
                  U R                  5        g r:   )deferred_from_coror_   	__anext__rd   addCallbacksrn   rs   )re   s    r/   rl   #_AsyncCooperatorAdapter._call_anext   s<     11I1I1KL((Gr1   c                    U R                   (       a  [        e[        5       nU R                  R	                  U5        U R
                  (       d  U R                  5         U$ r:   )rb   StopIterationr   rc   appendrd   rl   )re   r.   s     r/   __next__ _AsyncCooperatorAdapter.__next__   sF     ==#:%%a(""r1   )r_   rd   rN   r`   ra   rb   rc   N)rf   AsyncIterator[_T]rN   3Callable[Concatenate[_T, _P], Deferred[Any] | None]r`   _P.argsra   	_P.kwargs)r5   r$   returnNone)r   r    r   r   )r   r   )r   Deferred[Any])__name__
__module____qualname____firstlineno____doc__rg   rn   rs   rl   r}   __static_attributes__r>   r1   r/   r[   r[      sI    +Z8$8 F8  	8
 %8 H	r1   r[   c                    [        5       n[        X/UQ70 UD6n[        [        U5       Vs/ s H  ouR	                  U5      PM     sn5      nU$ s  snf )z)Like ``parallel`` but for async iterators)r   r[   r   rR   rS   )	async_iterablerU   rN   rA   rO   rV   rW   rX   dls	            r/   parallel_asyncr      s`     <D$;%#'%+0%D @L',U|4|!	|4@B I 	5s   Ac                z    [        5       nU  H  nUR                  " U/UQ70 UD6  M     UR                  U5        U$ )z7Return a Deferred built by chaining the given callbacks)r   addCallbackr4   )	callbacksinputarB   r.   xs         r/   process_chainr     s<     jA	a"!"r" JJuHr1   c                T   [         R                  " S[        SS9  [        5       n[	        X5       H1  u  pgUR
                  " U/UQ70 UD6  UR                  " U/UQ70 UD6  M3     [        U[        R                  5      (       a  UR                  U5        U$ UR                  U5        U$ )zDReturn a Deferred built by chaining the given callbacks and errbackszRprocess_chain_both() is deprecated and will be removed in a future Scrapy version.   )
stacklevel)warningswarnr   r   zipr   
addErrbackr;   r   r    r,   r4   )r   errbacksr   r   rB   r.   cbebs           r/   process_chain_bothr     s     MM	 	 *Ai*	b#1##	R"!"r" + %))			% H 	


5Hr1   c                    U  Vs/ s H-  n[         R                  " U5      R                  " U/UQ70 UD6PM/     nn[        USSS9nUR                  S 5      nSS jnUR	                  U5        U$ s  snf )zQReturn a Deferred with the output of all successful calls to the given
callbacks
T)fireOnOneErrbackconsumeErrorsc                6    U  Vs/ s H  oS   PM	     sn$ s  snf )N   r>   )rr   s     r/   <lambda>"process_parallel.<locals>.<lambda>B  s    Q6GQtQ6G6Gs   c                .    U R                   R                  $ r:   )value
subFailurer   s    r/   r   process_parallel.<locals>.ebD  s    }}'''r1   )r   r    r   r    )r   succeedr   r   r   )	r   r   r   rB   r   dfdsr.   d2r   s	            r/   process_parallelr   5  sx     DMM9aEMM% ,,Q99b99DM*6t4+A  mm,GHB( MM"I Ns   4A0c              /     #    [        U 5      n  [        U5      v   M  ! [         a     g[         a"    U" [        R
                  " 5       /UQ70 UD6   N8f = f7f)zOWraps an iterable calling an errback if an error is caught while
iterating it.
N)iternextr{   rH   r   r    )rT   r,   r   rB   its        r/   iter_errbackr   K  sZ      
hB
	1r(N   	 	1GOO%00R0	1s/   A A
AA(AAAAc                  #    U R                  5       n  UR                  5       I Sh  vN 7v   M   N	! [         a     g[         a"    U" [        R
                  " 5       /UQ70 UD6   N:f = f7f)zWraps an async iterable calling an errback if an error is caught while
iterating it. Similar to :func:`scrapy.utils.defer.iter_errback`.
N)r^   rw   rr   rH   r   r    )rf   r,   r   rB   r   s        r/   aiter_errbackr   ^  sf      
			B
	1&& &! 	 	1GOO%00R0	1s<   A.4 24 A.4 
A+A. (A+(A.*A++A._CT)boundc                    g r:   r>   os    r/   rv   rv   t  s    ,/r1   c                    g r:   r>   r   s    r/   rv   rv   x  s    %(r1   c                x   [        U [        5      (       a  U $ [        R                  " U 5      (       d  [        R
                  " U 5      (       al  [        5       (       d+  [        [        [        [        [        [        4   U 5      5      $ [        5       n[        R                  " [        R                  " XS95      $ U $ )ztConverts a coroutine or other awaitable object into a Deferred,
or returns the object as is if it isn't a coroutine.)loop)r;   r   asyncioisfutureinspectisawaitabler   r   r   r   r   r   
fromFutureensure_future)r   
event_loops     r/   rv   rv   |  s     !Xg11!44+-- "$y31C'Da"HII,.
""7#8#8#LMMHr1   c                4   ^  [        T 5      SU 4S jj5       nU$ )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" U 0 UD65      $ r:   )rv   )	coro_argscoro_kwargscoro_fs     r/   r@   !deferred_f_from_coro_f.<locals>.f  s    !&)"C{"CDDr1   )r   r   r   r   r   r   r	   )r   r@   s   ` r/   deferred_f_from_coro_fr     s$     6]E E Hr1   c                    U " U0 UD6n[        U[        5      (       a  U$ [        R                  " U5      (       d  [        R                  " U5      (       a  [        U5      $ [        U[        R                  5      (       a  [         R                  " U5      $ [         R                  " U5      $ !   [         R                  " [        R                  " [        R
                  S95      s $ = f)zGCopy of defer.maybeDeferred that also converts coroutines to Deferreds.)captureVars)r   failr   r    r   debugr;   r   r   r   r   rv   r   )r@   rA   rB   r5   s       r/   maybeDeferred_coror     s    GDB &(##7#6#6v#>#>!&))&'//**zz&!!==  Gzz'//hnnEFFs   B- -8C'c                4    U R                  [        5       5      $ )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):
            additional_request = scrapy.Request('https://example.org/price')
            deferred = self.crawler.engine.download(additional_request)
            additional_response = await deferred_to_future(deferred)
)asFuturer   r.   s    r/   deferred_to_futurer     s    & ::-/00r1   c                :    [        5       (       d  U $ [        U 5      $ )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 :ref:`using the asyncio reactor <install-asyncio>`, you can only
    await on :class:`asyncio.Future` objects.

-   When not using the asyncio reactor, you can only await on
    :class:`~twisted.internet.defer.Deferred` 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):
            additional_request = scrapy.Request('https://example.org/price')
            deferred = self.crawler.engine.download(additional_request)
            additional_response = await maybe_deferred_to_future(deferred)
)r   r   r   s    r/   maybe_deferred_to_futurer     s    4 ())a  r1   )r-   r    r   r   )r5   r$   r   Deferred[_T])r   zDeferred[None])r5   r   r   r   )r@   Callable[_P, Deferred[_T]]rA   r   rB   r   r   r   )r@   z/Callable[_P, Coroutine[Deferred[Any], Any, _T]]rA   r   rB   r   r   r   )r@   zCallable[_P, _T]rA   r   rB   r   r   r   )r@   zCCallable[_P, Deferred[_T] | Coroutine[Deferred[Any], Any, _T] | _T]rA   r   rB   r   r   r   )rT   Iterable[_T]rU   intrN   z"Callable[Concatenate[_T, _P], _T2]rA   r   rO   r   r   z*Deferred[list[tuple[bool, Iterator[_T2]]]])r   r   rU   r   rN   r   rA   r   rO   r   r   z4Deferred[list[tuple[bool, Iterator[Deferred[Any]]]]])
r   z+Iterable[Callable[Concatenate[_T, _P], _T]]r   r$   r   r   rB   r   r   r   )r   z,Iterable[Callable[Concatenate[_T, _P], Any]]r   z1Iterable[Callable[Concatenate[Failure, _P], Any]]r   r   r   r   rB   r   r   r   )
r   z,Iterable[Callable[Concatenate[_T, _P], _T2]]r   r$   r   r   rB   r   r   zDeferred[list[_T2]])
rT   r   r,   'Callable[Concatenate[Failure, _P], Any]r   r   rB   r   r   r   )
rf   r   r,   r   r   r   rB   r   r   r   )r   r   r   r   )r   r$   r   r$   )r   r$   r   zDeferred | _T)r   z%Callable[_P, Coroutine[Any, Any, _T]]r   r   )r@   zCallable[_P, Any]rA   r   rB   r   r   r   )r.   r   r   z
Future[_T])r.   r   r   zDeferred[_T] | Future[_T])Fr   
__future__r   r   r   r   r   collections.abcr   r   r   r   	functoolsr
   typesr   typingr   r   r   r   r   r   r   r)   r   twisted.internet.deferr   r   r   twisted.internet.taskr   twisted.pythonr   scrapy.exceptionsr   r   scrapy.utils.reactorr   r   r   r   twisted.python.failurer    typing_extensionsr!   r"   r#   r$   r%   r+   r0   r6   r8   r<   rC   rY   r[   r   r   r   r   r   r   r   rv   r   r   r   r   r>   r1   r/   <module>r      s}   #     D D   N N N " 
 - " E V7. 9	4B T]en ! 
!*19B 

 
6  	 
 
 '/8 

 J     	 (FFF 1F 	F
 F 0F"eh eP% B 	
  :$: 	 	
 ;?  		
  2; 	 	
 ,1141 	1 	1
 1&1 141 	1 	1
 1& e5M6!ABC 
 / 
 / 
 ( 
 ( 1 !!!(!09!!$1,!r1   