o
    î6WjÔ+  ã                   @  s<  d dl m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	 d dl
Z
ddlmZmZmZmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZmZ g d¢ZdZdZe e¡ZdAdd„Z dBdd„Z!dCdd„Z"dDdd „Z#dEd"d#„Z$dedd$d%dd&œdFd4d5„Z%dd6œdGd9d:„Z&dedd$d%dd&œdHd=d>„Z'dd6œdId?d@„Z(dS )Jé    )ÚannotationsN)Úuuid4)ÚIteratorÚAsyncIteratoré   )ÚTRANSIENT_ERRORSÚjitterÚbackoffÚis_fatal_status_erroré   )ÚHeadersÚomit)ÚAPIStatusError)ÚBetaSelfHostedWork)ÚWorkÚ	AsyncWork)Ú	iter_workÚ
aiter_workÚPOLL_BLOCK_MSiç  g      N@ÚattemptÚintÚreturnÚfloatc                 C  s   t | td�S )N)Úcap)r	   Ú_POLL_BACKOFF_CAP)r   © r   úq/home/esfera/Documents/content_generation/venv/lib/python3.10/site-packages/anthropic/lib/environments/_poller.pyÚ_backoff   s   r   ÚlowÚhighc                 C  s
   t | |ƒS ©N)r   )r   r   r   r   r   Ú_jitter"   s   
r!   ÚerrÚ	ExceptionÚboolc                 C  s   t | ƒS r    )r
   )r"   r   r   r   Ú_is_fatal_4xx&   s   r%   Úcodec                 C  s   t | tƒo	| j|kS r    )Ú
isinstancer   Ústatus_code)r"   r&   r   r   r   Ú
_is_status*   s   r)   Ústrc                   C  s   t  ¡ › dtƒ jd d… › �S )Nú-é   )ÚsocketÚgethostnamer   Úhexr   r   r   r   Ú_default_worker_id.   s   r0   FT)Ú	worker_idÚblock_msÚreclaim_older_than_msÚdrainÚ	auto_stopÚextra_headersÚworkr   Úenvironment_idr1   ú
str | Noner2   ú
int | Noner3   r4   r5   r6   úHeaders | NoneúIterator[BetaSelfHostedWork]c                c  s˜  � |pt ƒ }t d|||¡ d}d}		 z| j||dur|nt|dur$|nt||d�}
W n7 tyb } z+t|ƒr>t d|¡ ‚ |d7 }t|ƒt	dd	ƒ }t 
d
|||¡ t |¡ W Y d}~qd}~ww d}|
du r||rst d|¡ dS t t	d	dƒ¡ qt d|
jt|
jddƒ¡ z| j|
j||d� W nI tyÝ } z=t|ƒr·t d|
j|¡ t| |
j||d� W Y d}~q|	d7 }	t|	ƒt	dd	ƒ }t 
d|
j|	||¡ t |¡ W Y d}~qd}~ww d}	|sæ|
V  qz1|
V  W z| j|
j||d� W nT t�y } zt|dƒ�st 
d|
j|¡ W Y d}~n8d}~ww z| j|
j||d� W w  t�yJ } zt|dƒ�s@t 
d|
j|¡ W Y d}~w W Y d}~w d}~ww q)uã	  Iterate work items claimed from a self-hosted environment.

    Each yielded :class:`BetaSelfHostedWork` has already been ack'd. The ``work``
    resource must be bound to a client authenticated for the environment â€” the
    poller itself does not handle credentials. Use
    ``client.beta.environments.work.poller(...)`` for the user-facing entry
    point that constructs a scoped sub-client for you.

    Two consumption shapes are supported:

    - **Long-running runner** (``drain=False, auto_stop=True``, the default):
      loops forever, sleeps with jitter on empty polls, and calls ``work.stop``
      when the consuming for-loop body returns or raises. The poller owns the
      whole work-item lifecycle.
    - **Drain-and-dispatch** (``drain=True, auto_stop=False``): returns as soon
      as the queue is empty and never calls ``work.stop`` â€” use this when each
      yielded item is handed off to another process (e.g. a webhook handler
      that spawns a sandbox per work item) and that process owns ``stop``.

    Args:
      block_ms: How long the server holds an empty poll open (long-poll).
        Pass ``None`` to omit the param for a non-blocking poll â€” the server
        rejects ``0``. Drain callers usually want ``None`` so the final empty
        poll returns immediately.
      drain: When True, return after the first empty poll instead of sleeping
        and re-polling. Lets a webhook-driven dispatcher drain the queue and
        respond.
      auto_stop: When True (default), call ``work.stop`` after the consumer's
        loop body completes. Set False when the work item is handed off to
        another process that owns the stop call â€” otherwise the lease is
        terminated out from under it.
      reclaim_older_than_ms: Forwarded to ``work.poll``. Reclaim un-ack'd work
        older than this many ms. Useful in drain mode so a dead runner's
        work re-surfaces on the next webhook delivery.
      extra_headers: Optional headers passed through per request on every
        poll / ack / stop call (including the force-stop of an unprocessable
        item). They are threaded into each call's ``extra_headers=`` and are
        never assigned onto the client, so client state is not mutated.
        Credentials and ``x-stainless-helper`` come from the bound client,
        not this argument; a header given here overrides the bound client's
        same-named default for that one request, so use it for caller
        passthrough (e.g. trace ids), not to set auth.
    ú7poller starting environment_id=%s drain=%s auto_stop=%sr   TN©r2   r3   Úanthropic_worker_idr6   ú poll failed permanently error=%sé   ç        ç      ð?ú-poll failed attempt=%d backoff=%.1fs error=%súqueue drained environment_id=%sç      @ú$claimed work work_id=%s work_type=%sÚtype©r8   r6   ú:ack failed permanently; force-stopping work_id=%s error=%súDack failed, backing off work_id=%s attempt=%d backoff=%.1fs error=%sé™  ústop failed work_id=%s error=%s)r0   ÚlogÚinfoÚpollr   r   r%   Úerrorr   r!   ÚwarningÚtimeÚsleepÚidÚgetattrÚdataÚackÚ_force_stop_quietlyÚstopr#   r)   ©r7   r8   r1   r2   r3   r4   r5   r6   Úpoll_attemptÚack_attemptÚitemÚeÚwaitr   r   r   r   5   s¦   €
6
û
€ø	
ýÿ
€õ
ý€þú
ýÿ€ÿÇr   )r6   Úwork_idÚNonec             
   C  sf   z| j ||d|d� W dS  ty2 } zt|dƒs't d||¡ W Y d}~dS W Y d}~dS d}~ww )zÛBest-effort ``work.stop(force=True)`` for an item that can't be processed.

    A 409 just means the work already stopped; anything else is logged but not
    raised, since the poll loop must keep going regardless.
    T©r8   Úforcer6   rL   ú;force-stop of unprocessable work failed work_id=%s error=%sN©rZ   r#   r)   rN   rQ   ©r7   ra   r8   r6   r_   r   r   r   rY   °   s   
ÿ€ÿrY   r   ú!AsyncIterator[BetaSelfHostedWork]c                C sÈ  �|pt ƒ }t d|||¡ d}d}		 z| j||dur|nt|dur$|nt||d�I dH }
W n: tyh } z.t|ƒrAt d|¡ ‚ |d7 }t|ƒt	dd	ƒ }t 
d
|||¡ t |¡I dH  W Y d}~qd}~ww d}|
du r…|ryt d|¡ dS t t	d	dƒ¡I dH  qt d|
jt|
jddƒ¡ z| j|
j||d�I dH  W nO tyï } zCt|ƒrÆt d|
j|¡ t| |
j||d�I dH  W Y d}~q|	d7 }	t|	ƒt	dd	ƒ }t 
d|
j|	||¡ t |¡I dH  W Y d}~qd}~ww d}	|sø|
V  qz4|
V  W z| j|
j||d�I dH  W nW t�y, } zt|dƒ�s"t 
d|
j|¡ W Y d}~n;d}~ww z| j|
j||d�I dH  W w  t�yb } zt|dƒ�sXt 
d|
j|¡ W Y d}~w W Y d}~w d}~ww q)zŒAsync version of :func:`iter_work`. See its docstring for semantics,
    including how ``extra_headers`` is passed through per request.
    r=   r   TNr>   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   )r0   rN   rO   rP   r   r   r%   rQ   r   r!   rR   ÚanyiorT   rU   rV   rW   rX   Ú_aforce_stop_quietlyrZ   r#   r)   r[   r   r   r   r   ½   s¦   €
û€ø	ýÿ€õý€þúýÿ€ÿÇr   c             
   Ã  sn   �z| j ||d|d�I dH  W dS  ty6 } zt|dƒs+t d||¡ W Y d}~dS W Y d}~dS d}~ww )z-Async version of :func:`_force_stop_quietly`.Trc   NrL   re   rf   rg   r   r   r   rj     s   €
ÿ€ÿrj   )r   r   r   r   )r   r   r   r   r   r   )r"   r#   r   r$   )r"   r#   r&   r   r   r$   )r   r*   )r7   r   r8   r*   r1   r9   r2   r:   r3   r:   r4   r$   r5   r$   r6   r;   r   r<   )
r7   r   ra   r*   r8   r*   r6   r;   r   rb   )r7   r   r8   r*   r1   r9   r2   r:   r3   r:   r4   r$   r5   r$   r6   r;   r   rh   )
r7   r   ra   r*   r8   r*   r6   r;   r   rb   ))Ú
__future__r   rS   r-   ÚloggingÚuuidr   Úcollections.abcr   r   ri   Ú_retryr   r   r	   r
   Ú_typesr   r   Ú_exceptionsr   Útypes.beta.environmentsr   Ú resources.beta.environments.workr   r   Ú__all__r   r   Ú	getLoggerÚ__name__rN   r   r!   r%   r)   r0   r   rY   r   rj   r   r   r   r   Ú<module>   sL    





÷{÷Qÿ