
    4Rj+                       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j:                  e      ZddZ ddZ!ddZ"ddZ#d dZ$deddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!dZ%ddd"dZ&deddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#dZ'dd	 	 	 	 	 	 	 	 	 d$dZ(y)%    )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@c                $    t        | t              S )N)cap)r
   _POLL_BACKOFF_CAP)attempts    j/var/www/html/meridian/meridian-ai/venv/lib/python3.12/site-packages/anthropic/lib/environments/_poller.py_backoffr      s    7 122    c                    t        | |      S N)r	   )lowhighs     r   _jitterr!   "   s    #tr   c                    t        |       S r   )r   )errs    r   _is_fatal_4xxr$   &   s     %%r   c                D    t        | t              xr | j                  |k(  S r   )
isinstancer   status_code)r#   codes     r   
_is_statusr)   *   s    c>*Fs$/FFr   c                 ^    t        j                          dt               j                  d d  S )N-   )socketgethostnamer   hex r   r   _default_worker_idr1   .   s-       "#1UW[["%5$677r   FT)	worker_idblock_msreclaim_older_than_msdrain	auto_stopextra_headersc          	   #    K   |xs
 t               }t        j                  d|||       d}d}		 	 | j                  |||nt        ||nt        ||      }
d}|
9|rt        j                  d
|       yt        j                  t        dd             et        j                  d|
j                  t        |
j                  dd             	 | j!                  |
j                  ||       d}	|s|
 	 |
 	 | j%                  |
j                  ||       # t
        $ rw}t        |      rt        j                  d|        |dz  }t        |      t        dd      z   }t        j                  d	|||       t        j                  |       Y d}~cd}~ww xY w# t
        $ r}t        |      r@t        j                  d|
j                  |       t#        | |
j                  ||       Y d}~|	dz  }	t        |	      t        dd      z   }t        j                  d|
j                  |	||       t        j                  |       Y d}~d}~ww xY w# t&        $ r8}t)        |d      s!t        j                  d|
j                  |       Y d}~wd}~ww xY w# 	 | j%                  |
j                  ||       w # t&        $ r<}t)        |d      s&t        j                  d|
j                  |       Y d}~w Y d}~w d}~ww xY wxY ww)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   Nr3   r4   anthropic_worker_idr7    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environment_idr7   :ack failed permanently; force-stopping work_id=%s error=%sDack failed, backing off work_id=%s attempt=%d backoff=%.1fs error=%s  stop failed work_id=%s error=%s)r1   loginfopollr   r   r$   errorr   r!   warningtimesleepidgetattrdataack_force_stop_quietlystop	Exceptionr)   workrF   r2   r3   r4   r5   r6   r7   poll_attemptack_attemptitemewaits                r   r   r   5   s    l 1/1IHHFX]_hi LK
	99%-%9t?T?`&;fj$-+  D  <:NKJJwsC()7'$))U[]aBbc	HH-+  " J	OJO		GG#1"/  i    	Q		<a@ALL)GC,==DKKGW[]^_JJt	.   	Q		VX\X_X_abc#D$''.`mn1KK(73+<<DKKVX\X_X_alnrtu JJt	2  O!!S)KK A477ANOO		GG#1"/  
  O!!S)KK A477ANN *Os   ,K?&D A3K?	F '	K?1J 6I K?	FA,F
K?FK?	I!AI&K?,AIK?IK?	J-JK?JK?K<J43K<4	K9=-K4*
K<4K99K<<K?)r7   c                   	 | j                  ||d|       y# t        $ r2}t        |d      st        j	                  d||       Y d}~yY d}~yd}~ww xY w)zBest-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rF   forcer7   rI   ;force-stop of unprocessable work failed work_id=%s error=%sNrW   rX   r)   rK   rN   rZ   work_idrF   r7   r^   s        r   rV   rV      sT    a		'.Ta	b a!S!IISU\^_`` "as    	A#AAc          	      K   |xs
 t               }t        j                  d|||       d}d}		 	 | j                  |||nt        ||nt        ||       d{   }
d}|
A|rt        j                  d
|       yt        j                  t        dd             d{    ut        j                  d|
j                  t        |
j                  dd             	 | j!                  |
j                  ||       d{    d}	|s|
 	 |
 	 | j%                  |
j                  ||       d{    
7 # t
        $ r}t        |      rt        j                  d|        |dz  }t        |      t        dd      z   }t        j                  d	|||       t        j                  |       d{  7   Y d}~d}~ww xY w7 *7 # t
        $ r}t        |      rIt        j                  d|
j                  |       t#        | |
j                  ||       d{  7   Y d}~|	dz  }	t        |	      t        dd      z   }t        j                  d|
j                  |	||       t        j                  |       d{  7   Y d}~_d}~ww xY w7 c# t&        $ r8}t)        |d      s!t        j                  d|
j                  |       Y d}~d}~ww xY w# 	 | j%                  |
j                  ||       d{  7   w # t&        $ r<}t)        |d      s&t        j                  d|
j                  |       Y d}~w Y d}~w d}~ww xY wxY ww)zAsync version of :func:`iter_work`. See its docstring for semantics,
    including how ``extra_headers`` is passed through per request.
    r9   r   Nr:   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rG   rH   rI   rJ   )r1   rK   rL   rM   r   r   r$   rN   r   r!   rO   anyiorQ   rR   rS   rT   rU   _aforce_stop_quietlyrW   rX   r)   rY   s                r   r   r      s!     1/1IHHFX]_hiLK
	%-%9t?T?`&;fj$-+ #  D  <:NK++gc3/0007'$))U[]aBbc	((-+    " J	OJOiiGG#1"/     i    	Q		<a@ALL)GC,==DKKGW[]^_++d###	 1
   	Q		VX\X_X_abc*4gtuuu1KK(73+<<DKKVX\X_X_alnrtu ++d###	(
  O!!S)KK A477ANOOiiGG#1"/     
  O!!S)KK A477ANN *Os?  ,M)D: D8D: ?MG;M!G :G	;G ?
M
K !J 1J2J 6M8D: :	GA/F>2F53F>8M>GM	G 	JAJHJ"M(AJ JJMJMJ 	K -KMKMM!L>L?LM	M
-M;
MM

MMc                  K   	 | j                  ||d|       d{    y7 # t        $ r2}t        |d      st        j	                  d||       Y d}~yY d}~yd}~ww xY ww)z-Async version of :func:`_force_stop_quietly`.Tra   NrI   rc   rd   re   s        r   ri   ri     s]     aiidZgihhh a!S!IISU\^_`` "as6   A"$ "$ A"$ 	A#A
A"AA")r   intreturnfloat)r   rm   r    rm   rl   rm   )r#   rX   rl   bool)r#   rX   r(   rk   rl   rn   )rl   str)rZ   r   rF   ro   r2   
str | Noner3   
int | Noner4   rq   r5   rn   r6   rn   r7   Headers | Nonerl   zIterator[BetaSelfHostedWork])
rZ   r   rf   ro   rF   ro   r7   rr   rl   None)rZ   r   rF   ro   r2   rp   r3   rq   r4   rq   r5   rn   r6   rn   r7   rr   rl   z!AsyncIterator[BetaSelfHostedWork])
rZ   r   rf   ro   rF   ro   r7   rr   rl   rs   ))
__future__r   rP   r-   logginguuidr   collections.abcr   r   rh   _retryr   r	   r
   r   _typesr   r   _exceptionsr   types.beta.environmentsr    resources.beta.environments.workr   r   __all__r   r   	getLogger__name__rK   r   r!   r$   r)   r1   r   rV   r   ri   r0   r   r   <module>r      s   "     3  M M # ) 9 ?  g!3&G8 !((,$(xO
xO xO 	xO
 xO &xO xO xO "xO "xOv ko 
a" !((,$(MO
MO MO 	MO
 MO &MO MO MO "MO 'MOb \`a
a!a69aJXa	ar   