
    ,h^                    P   U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZmZ d dlZd dlZd dlmZ d dlmZ d dlZddlmZmZmZmZmZmZ dd	lmZmZ dd
lmZ er d dl m!Z!m"Z"m#Z# d dl$m%Z%m&Z& d dl'm(Z(  e%d      Z) ed      Z* G d dejV                        Z, e,       Z- ed      Z.de/d<   dZ0 e	       Z1e G d d             Z2 ed      Z3de/d<   ejh                  d.d       Z5d/dZ6d0dZ7d1dZ8 ejr                  dd        G d! d"             Z: ejr                  dd        G d# d$ee*                Z; ejr                  dd        G d% d&ee*                Z<edddd'	 	 	 	 	 	 	 	 	 	 	 d2d(       Z=d/d)Z>	 	 	 	 	 	 d3d*Z?dd+	 	 	 	 	 	 	 d4d,Z@dd+	 	 	 	 	 	 	 d5d-ZAy)6    )annotationsN)count)TYPE_CHECKINGGenericTypeVar)define)current_async_library_cvar   )RunVar	TrioToken
checkpointdisable_ki_protectionenable_ki_protectionstart_thread_soon)CapacityLimiterEvent)coroutine_or_error)	AwaitableCallable	Generator)TypeVarTupleUnpack)RaiseCancelTTsRetTc                  :    e Zd ZU dZded<   ded<   ded<   ded	<   y
)_ParentTaskDatazqGlobal due to Threading API, thread local storage for data related to the
    parent task of native Trio threads.r   tokenboolabandon_on_cancelzlist[RaiseCancelT | None]cancel_registerzlist[trio.lowlevel.Task | None]task_registerN)__name__
__module____qualname____doc____annotations__     O/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/trio/_threads.pyr   r   )   s!    + ..22r)   r   limiterzRunVar[CapacityLimiter]_limiter_local(   c                  "    e Zd ZU ded<   ded<   y)_ActiveThreadCountintr   r   eventNr#   r$   r%   r'   r(   r)   r*   r/   r/   <   s    JLr)   r/   active_threadszRunVar[_ActiveThreadCount]_active_threads_localc               #    K   	 t         j                         } | xj                  dz  c_        	 d  | xj                  dz  c_        | j                  dk(  r*| j                  j                          t	               | _        y y # t        $ r, t        dt	                     } t         j                  |        Y w xY w# | xj                  dz  c_        | j                  dk(  r*| j                  j                          t	               | _        w w xY ww)Nr   r
   )r4   getLookupErrorr/   r   setr   r1   active_threads_locals    r*   _track_active_threadr;   E   s     8488:
 !#1""a'"%%* &&**,). & +  81!UW=!!"678 	""a'"%%* &&**,). & +s?   DB DB9 AD2B63D5B66D9AD		Dc                   K   t                d{    	 t        j                         } | j                  dk7  r3| j
                  j                          d{    | j                  dk7  r2yy7 \# t        $ r Y yw xY w7 'w)a  Wait until no threads are still running tasks.

    This is intended to be used when testing code with trio.to_thread to
    make sure no tasks are still making progress in a thread. See the
    following code for a usage example::

        async def wait_all_settled():
            while True:
                await trio.testing.wait_all_threads_complete()
                await trio.testing.wait_all_tasks_blocked()
                if trio.testing.active_thread_count() == 0:
                    break
    Nr   )r   r4   r6   r7   r   r1   waitr9   s    r*   wait_all_threads_completedr>   W   s      ,488: 
$
$
)"((--/// 
$
$
)    	 	0sC   B A-B A/ ,B A>B +B /	A;8B :A;;B c                 ^    	 t         j                         j                  S # t        $ r Y yw xY w)zwReturns the number of threads that are currently running a task

    See `trio.testing.wait_all_threads_completed`
    r   )r4   r6   r   r7   r(   r)   r*   active_thread_countr@   s   s.    
$((*000 s     	,,c                     	 t         j                         } | S # t        $ r( t        t              } t         j                  |        Y | S w xY w)zGet the default `~trio.CapacityLimiter` used by
    `trio.to_thread.run_sync`.

    The most common reason to call this would be if you want to modify its
    :attr:`~trio.CapacityLimiter.total_tokens` attribute.

    )r,   r6   r7   r   DEFAULT_LIMITr8   )r+   s    r*   current_default_thread_limiterrC   ~   sJ    $ $$& N  $!-07#N$s    -A	A	F)eqslotsc                      e Zd ZU ded<   y)ThreadPlaceholderstrnameNr2   r(   r)   r*   rG   rG      s    
Ir)   rG   c                      e Zd ZU ded<   ded<    ej
                  dej                        Zded<    ej
                  de	j                        Zd	ed
<   edd       ZddZddZddZddZy)RunzCallable[..., Awaitable[RetT]]afntuple[object, ...]argsFinitfactorycontextvars.Contextcontext/stdlib_queue.SimpleQueue[outcome.Outcome[RetT]]queuec                b   K   t        | j                  g| j                   }| d {   S 7 wN)r   rL   rN   )selfcoros     r*   unprotected_afnzRun.unprotected_afn   s'     !$((7TYY7zzs   &/-/c                  K   t         j                  j                         }|j                  }| j                  j	                         |_        t         j                  j                          d {    t        j                  | j                         d {   }||_        t         j                  j                          d {    | j                  j                  |       y 7 t7 O7 $wrW   )triolowlevelcurrent_taskrS   copycancel_shielded_checkpointoutcomeacapturerZ   rU   
put_nowait)rX   taskold_contextresults       r*   runzRun.run   s     }}))+ll||((*mm66888''(<(<=="mm66888

f%	 	9=8s6   A+C(-C".&C(C$,C(C&!C($C(&C(c                   K   t        j                  | j                         d {   }| j                  j	                  |       y 7  wrW   )ra   rb   rZ   rU   rc   rX   rf   s     r*   
run_systemzRun.run_system   s6     ''(<(<==

f% >s   #AA!Ac                X     t         j                  d fd}|j                  |       y )Nc                     d   } | J d       t         j                  j                  | t        j                               y Nr   z)guaranteed by abandon_on_cancel semanticsr\   r]   
reschedulera   Valuerd   rX   r"   s    r*   in_trio_threadz,Run.run_in_host_task.<locals>.in_trio_thread   9     #D#P%PPMM$$T7==+>?r)   returnNonePARENT_TASK_DATAr"   run_sync_soonrX   r   rr   r"   s   `  @r*   run_in_host_taskzRun.run_in_host_task   $    (66	@
 	N+r)   c                4     d fd}|j                  |       y )Nc                 (   	 t         j                  j                   j                   j                   j
                         y # t        $ rD  j                  j                  t        j                  t        j                  d                   Y y w xY w)N)rI   rS   zsystem nursery is closed)r\   r]   spawn_system_taskrj   rL   rS   RuntimeErrorrU   rc   ra   ErrorRunFinishedError)rX   s   r*   rr   z1Run.run_in_system_nursery.<locals>.in_trio_thread   so    	//OO LL 0 
   

%%MM$"7"78R"STs   A A A
BBrt   )ry   )rX   r   rr   s   `  r*   run_in_system_nurseryzRun.run_in_system_nursery   s    
	 	N+r)   Nru   r   rt   r   r   ru   rv   )r#   r$   r%   r'   attrsfieldcontextvarscopy_contextrS   stdlib_queueSimpleQueuerU   r   rZ   rg   rj   r{   r   r(   r)   r*   rK   rK      s    	''
#.5;;(($G   >IU[[((>E: 
  	&&,,r)   rK   c                      e Zd ZU ded<   ded<    ej
                  dej                        Zded<    ej
                  de	j                        Zd	ed
<   edd       ZddZddZddZy)RunSynczCallable[..., RetT]fnrM   rN   FrO   rR   rS   rT   rU   c           	     $    | j                   j                  | j                  g| j                   }t	        j
                  |      rI|j                          t        dj                  t        | j                  d| j                                    |S )NzITrio expected a synchronous function, but {!r} appears to be asynchronousr%   )
rS   rg   r   rN   inspectiscoroutineclose	TypeErrorformatgetattr)rX   rets     r*   unprotected_fnzRunSync.unprotected_fn   sp    dlltww33s#IIK%vgdgg~tww&OP 
 
r)   c                x    t        j                  | j                        }| j                  j	                  |       y rW   )ra   capturer   rU   rc   ri   s     r*   run_synczRunSync.run_sync   s(    !4!45

f%r)   c                X     t         j                  d fd}|j                  |       y )Nc                     d   } | J d       t         j                  j                  | t        j                               y rm   rn   rq   s    r*   rr   z0RunSync.run_in_host_task.<locals>.in_trio_thread   rs   r)   rt   rw   rz   s   `  @r*   r{   zRunSync.run_in_host_task   r|   r)   c                :    |j                  | j                         y rW   )ry   r   )rX   r   s     r*   r   zRunSync.run_in_system_nursery   s    DMM*r)   Nr   rt   r   )r#   r$   r%   r'   r   r   r   r   rS   r   r   rU   r   r   r   r{   r   r(   r)   r*   r   r      s|    
#.5;;(($G   >IU[[((>E: 
  &,+r)   r   )thread_namer    r+   c                  
K   t         j                  j                          d{    t        |      

t	               t         j                  j                         gdgdt        t               }t        |      dfdt         j                  j                         |8t         dd       dt         j                  j                         j                   }d
 fd}t        j                         j                  t        j                   d       dfd}j#                         d{    t%               5  	 t'        |||       d
fd}	 t         j                  j+                  |       d{   }	t-        |	t.        j0                        r|	j3                         cddd       S t-        |	t4              r|	j                          d{    n0t-        |	t6              r|	j9                          nt;        d	|	d
      ~	7 7 #  j)                          xY w7 7 U# 1 sw Y   yxY ww)u  Convert a blocking operation into an async operation using a thread.

    These two lines are equivalent::

        sync_fn(*args)
        await trio.to_thread.run_sync(sync_fn, *args)

    except that if ``sync_fn`` takes a long time, then the first line will
    block the Trio loop while it runs, while the second line allows other Trio
    tasks to continue working while ``sync_fn`` runs. This is accomplished by
    pushing the call to ``sync_fn(*args)`` off into a worker thread.

    From inside the worker thread, you can get back into Trio using the
    functions in `trio.from_thread`.

    Args:
      sync_fn: An arbitrary synchronous callable.
      *args: Positional arguments to pass to sync_fn. If you need keyword
          arguments, use :func:`functools.partial`.
      abandon_on_cancel (bool): Whether to abandon this thread upon
          cancellation of this operation. See discussion below.
      thread_name (str): Optional string to set the name of the thread.
          Will always set `threading.Thread.name`, but only set the os name
          if pthread.h is available (i.e. most POSIX installations).
          pthread names are limited to 15 characters, and can be read from
          ``/proc/<PID>/task/<SPID>/comm`` or with ``ps -eT``, among others.
          Defaults to ``{sync_fn.__name__|None} from {trio.lowlevel.current_task().name}``.
      limiter (None, or CapacityLimiter-like object):
          An object used to limit the number of simultaneous threads. Most
          commonly this will be a `~trio.CapacityLimiter`, but it could be
          anything providing compatible
          :meth:`~trio.CapacityLimiter.acquire_on_behalf_of` and
          :meth:`~trio.CapacityLimiter.release_on_behalf_of` methods. This
          function will call ``acquire_on_behalf_of`` before starting the
          thread, and ``release_on_behalf_of`` after the thread has finished.

          If None (the default), uses the default `~trio.CapacityLimiter`, as
          returned by :func:`current_default_thread_limiter`.

    **Cancellation handling**: Cancellation is a tricky issue here, because
    neither Python nor the operating systems it runs on provide any general
    mechanism for cancelling an arbitrary synchronous function running in a
    thread. This function will always check for cancellation on entry, before
    starting the thread. But once the thread is running, there are two ways it
    can handle being cancelled:

    * If ``abandon_on_cancel=False``, the function ignores the cancellation and
      keeps going, just like if we had called ``sync_fn`` synchronously. This
      is the default behavior.

    * If ``abandon_on_cancel=True``, then this function immediately raises
      `~trio.Cancelled`. In this case **the thread keeps running in
      background** – we just abandon it to do whatever it's going to do, and
      silently discard any return value or errors that it raises. Only use
      this if you know that the operation is safe and side-effect free. (For
      example: :func:`trio.socket.getaddrinfo` uses a thread with
      ``abandon_on_cancel=True``, because it doesn't really affect anything if a
      stray hostname lookup keeps running in the background.)

      The ``limiter`` is only released after the thread has *actually*
      finished – which in the case of cancellation may be some time after this
      function has returned. If :func:`trio.run` finishes before the thread
      does, then the limiter release method will never be called at all.

    .. warning::

       You should not use this function to call long-running CPU-bound
       functions! In addition to the usual GIL-related reasons why using
       threads for CPU-bound work is not very effective in Python, there is an
       additional problem: on CPython, `CPU-bound threads tend to "starve out"
       IO-bound threads <https://bugs.python.org/issue7946>`__, so using
       threads for CPU-bound work is likely to adversely affect the main
       thread running Trio. If you need to do this, you're better off using a
       worker process, or perhaps PyPy (which still has a GIL, but may do a
       better job of fairly allocating CPU time between threads).

    Returns:
      Whatever ``sync_fn(*args)`` returns.

    Raises:
      Exception: Whatever ``sync_fn(*args)`` raises.

    Nztrio.to_thread.run_sync-c                     d fd}t        j                  |       d   7t        j                  j	                  d   t        j
                                y y )Nc                 t    	 j                          j                         S #  j                         w xY wrW   )unwraprelease_on_behalf_of)r+   placeholderrf   s   r*   do_release_then_return_resultz`to_thread_run_sync.<locals>.report_back_in_trio_thread_fn.<locals>.do_release_then_return_resulto  s.    
:}},,[9,,[9s   $ 7r   r   )ra   r   r\   r]   ro   rp   )rf   r   r+   r   r"   s   ` r*   report_back_in_trio_thread_fnz9to_thread_run_sync.<locals>.report_back_in_trio_thread_fnn  sK    	: !>?'MM$$]1%5w}}V7LM (r)   r#   z from c            	        t         _        t         _        t         _        t         _        	  j
                  g } t        j                  |       r5| j                          t        dj                  t        d                  | t         `t         `t         `t         `S # t         `t         `t         `t         `w xY w)NzBTrio expected a sync function, but {!r} appears to be asynchronousr%   )rx   r   r    r!   r"   rg   r   r   r   r   r   r   )r   abandon_boolrN   r!   rS   current_trio_tokensync_fnr"   s    r*   	worker_fnz%to_thread_run_sync.<locals>.worker_fn  s    !3-9*+:()6&	/'++g--C""3'		##)6''>7*S#T 
  & 2 0 . !& 2 0 .s   AB& &C c                    t        j                  t        j                        5  j	                  |        d d d        y # 1 sw Y   y xY wrW   )
contextlibsuppressr\   r   ry   )rf   r   r   s    r*   deliver_worker_fn_resultz4to_thread_run_sync.<locals>.deliver_worker_fn_result  sC       !6!67 	T,,-JFS	T 	T 	Ts   AA
c                    | d<   r)d d<   t         j                  j                  j                  S t         j                  j                  j                  S )Nr   )r\   r]   Abort	SUCCEEDEDFAILED)raise_cancelr   r!   r"   s    r*   abortz!to_thread_run_sync.<locals>.abort  sF    !-OA#'a }}**444}}**111r)   z=trio.to_thread.run_sync received unrecognized thread message .)rf   zoutcome.Outcome[RetT]ru   rv   r   )r   r   ru   ztrio.lowlevel.Abort)r\   r]   checkpoint_if_cancelledr   rC   r^   next_thread_counterrG   r   r   rI   r   r   rg   r	   r8   acquire_on_behalf_ofr;   r   r   wait_task_rescheduled
isinstancera   Outcomer   rK   r   r   r   )r   r   r    r+   rN   rI   r   r   r   msg_from_threadr   r!   rS   r   r   r   r"   s   `  ``     @@@@@@@r*   to_thread_run_syncr      s    v --
/
/
111 )*L02
 7;mm6P6P6R5SM 37O%d?&;%<=D#D)KN 99; *d;<F4==C]C]C_CdCdBef/ /. &&(G
 KK*..5T 
&
&{
333		   	i)A;O
	2  mm99%@@  /7??;&--//     0 OS1%))+++OW5((*STcSffgh    } 2X 4	((5 A
 ,3     s|   "IH DIH#II H%"+I H<-I ;
I#I (H>)7I  I#I%H99I >I  I	Ic                 r    	 t         j                  d   } |  |         yy# t        $ r t        d      dw xY w)a  Raise `trio.Cancelled` if the associated Trio task entered a cancelled status.

     Only applicable to threads spawned by `trio.to_thread.run_sync`. Poll to allow
     ``abandon_on_cancel=False`` threads to raise :exc:`~trio.Cancelled` at a suitable
     place, or to end abandoned ``abandon_on_cancel=True`` threads sooner than they may
     otherwise.

    Raises:
        Cancelled: If the corresponding call to `trio.to_thread.run_sync` has had a
            delivery of cancellation attempted against it, regardless of the value of
            ``abandon_on_cancel`` supplied as an argument to it.
        RuntimeError: If this thread is not spawned from `trio.to_thread.run_sync`.

    .. note::

       To be precise, :func:`~trio.from_thread.check_cancelled` checks whether the task
       running :func:`trio.to_thread.run_sync` has ever been cancelled since the last
       time it was running a :func:`trio.from_thread.run` or :func:`trio.from_thread.run_sync`
       function. It may raise `trio.Cancelled` even if a cancellation occurred that was
       later hidden by a modification to `trio.CancelScope.shield` between the cancelled
       `~trio.CancelScope` and :func:`trio.to_thread.run_sync`. This differs from the
       behavior of normal Trio checkpoints, which raise `~trio.Cancelled` only if the
       cancellation is still active when the checkpoint executes. The distinction here is
       *exceedingly* unlikely to be relevant to your application, but we mention it
       for completeness.
    r   z@this thread wasn't created by Trio, can't check for cancellationN)rx   r!   AttributeErrorr   )r   s    r*   from_thread_check_cancelledr     sM    6'77:
   	  N
	s     6c                   | du}|s	 t         j                  } nt	        | t
              st        d      	 t        j                  j                          t        d      # t        $ r t        d      dw xY w# t        $ r Y nw xY w|st         j                  r|j                  |        n|j                  |        |j                  j                         j                         S )z%Shared logic of from_thread functionsNz=this thread wasn't created by Trio, pass kwarg trio_token=...z0Passed kwarg trio_token is not of type TrioTokenz2this is a blocking function; call it from a thread)rx   r   r   r   r   r   r\   r]   r^   r    r   r{   rU   r6   r   )
trio_tokenmessage_to_triotoken_provideds      r*   _send_message_to_trior     s    
  t+N	)//J
 
I.MNNQ""$ OPP  	O	  
 );;--j9((4  $$&--//s   A A7 A47	BB)r   c               .    t        |t        | |            S )a8  Run the given async function in the parent Trio thread, blocking until it
    is complete.

    Returns:
      Whatever ``afn(*args)`` returns.

    Returns or raises whatever the given function returns or raises. It
    can also raise exceptions of its own:

    Raises:
        RunFinishedError: if the corresponding call to :func:`trio.run` has
            already completed, or if the run has started its final cleanup phase
            and can no longer spawn new system tasks.
        Cancelled: If the original call to :func:`trio.to_thread.run_sync` is cancelled
            (if *trio_token* is None) or the call to :func:`trio.run` completes
            (if *trio_token* is not None) while ``afn(*args)`` is running,
            then *afn* is likely to raise :exc:`trio.Cancelled`.
        RuntimeError: if you try calling this from inside the Trio thread,
            which would otherwise cause a deadlock, or if no ``trio_token`` was
            provided, and we can't infer one from context.
        TypeError: if ``afn`` is not an asynchronous function.

    **Locating a TrioToken**: There are two ways to specify which
    `trio.run` loop to reenter:

        - Spawn this thread from `trio.to_thread.run_sync`. Trio will
          automatically capture the relevant Trio token and use it
          to re-enter the same Trio task.
        - Pass a keyword argument, ``trio_token`` specifying a specific
          `trio.run` loop to re-enter. This is useful in case you have a
          "foreign" thread, spawned using some other framework, and still want
          to enter Trio, or if you want to use a new system task to call ``afn``,
          maybe to avoid the cancellation context of a corresponding
          `trio.to_thread.run_sync` task. You can get this token from
          :func:`trio.lowlevel.current_trio_token`.
    )r   rK   )rL   r   rN   s      r*   from_thread_runr     s    R !Sd^<<r)   c               .    t        |t        | |            S )a6  Run the given sync function in the parent Trio thread, blocking until it
    is complete.

    Returns:
      Whatever ``fn(*args)`` returns.

    Returns or raises whatever the given function returns or raises. It
    can also raise exceptions of its own:

    Raises:
        RunFinishedError: if the corresponding call to `trio.run` has
            already completed.
        RuntimeError: if you try calling this from inside the Trio thread,
            which would otherwise cause a deadlock or if no ``trio_token`` was
            provided, and we can't infer one from context.
        TypeError: if ``fn`` is an async function.

    **Locating a TrioToken**: There are two ways to specify which
    `trio.run` loop to reenter:

        - Spawn this thread from `trio.to_thread.run_sync`. Trio will
          automatically capture the relevant Trio token and use it when you
          want to re-enter Trio.
        - Pass a keyword argument, ``trio_token`` specifying a specific
          `trio.run` loop to re-enter. This is useful in case you have a
          "foreign" thread, spawned using some other framework, and still want
          to enter Trio, or if you want to use a new system task to call ``fn``,
          maybe to avoid the cancellation context of a corresponding
          `trio.to_thread.run_sync` task.
    )r   r   )r   r   rN   s      r*   from_thread_run_syncr   =  s    F !WR->??r)   )ru   zGenerator[None, None, None]rt   )ru   r0   )ru   r   )r   Callable[[Unpack[Ts]], RetT]rN   
Unpack[Ts]r   z
str | Noner    r   r+   zCapacityLimiter | Noneru   r   )r   TrioToken | Noner   zRun[RetT] | RunSync[RetT]ru   r   )rL   z'Callable[[Unpack[Ts]], Awaitable[RetT]]rN   r   r   r   ru   r   )r   r   rN   r   r   r   ru   r   )B
__future__r   r   r   r   rU   r   	threading	itertoolsr   typingr   r   r   r   ra   r   sniffior	   r\   _corer   r   r   r   r   r   _syncr   r   _utilr   collections.abcr   r   r   typing_extensionsr   r   trio._core._trapsr   r   r   localr   rx   r,   r'   rB   r   r/   r4   contextmanagerr;   r>   r@   rC   frozenrG   rK   r   r   r   r   r   r   r(   r)   r*   <module>r      sZ   "       2 2    .   * %>>6.	d	Bv3ioo 3 #$ *0*;' ; '   
 5;;K4L 1 L 1 1"08( e$  %
 e$7,'$- 7, %7,t e$)+gdm )+ %)+X  ##&*G )G G  G  	G 
 $G  
G  G T"J0 0.0 
0H $()=	0)=)= !)= 
	)=^ $(#@$#@#@ !#@ 
	#@r)   