
    R3iT"              	       H   d Z ddl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m	Z	 ddl
mZ ddlmZmZmZ ddlmZmZ ddlZddlmZ ddlmZ d	d
lmZmZ de	eeef      dedeeeef   dz  df   fdZ G d deej<                        Z G d deej<                        Z dedefdZ!defdZ"deez  defdZ#de ddfdZ$deddfdZ%dedefdZ&dededz  fdZ'dedz  defd Z(d!ededefd"Z)e G d# d$             Z*d%edeee*f   fd&Z+	 d,d'ed(ee   d)edz  ddfd*Z,g d+Z-y)-z%Support functions for the docket CLI.    N)AsyncGeneratorAsyncIterator)	dataclass)datetime	timedeltatimezone)Any
Collection)Console)Table   )DocketSnapshot
WorkerInfoiteratortimeoutreturnc                0  K   ddl }	 	 	 |j                  | j                         |       d{    .7 # |j                  $ r d Y t        $ r Y nw xY w	 | j                          d{  7   y# | j                          d{  7   w xY ww)a  Iterate over an async iterator with timeout, ensuring proper cleanup.

    Wraps an async iterator to add timeout support and guaranteed cleanup.
    On timeout, yields None to allow the caller to handle polling fallback.

    Args:
        iterator: An async generator (must have __anext__ and aclose methods)
        timeout: Timeout in seconds for each iteration

    Yields:
        Items from the iterator, or None if timeout expires
    r   N)r   )asynciowait_for	__anext__TimeoutErrorStopAsyncIterationaclose)r   r   r   s      ]/mnt/e/genesis-system/.venvs/voice-bridge/lib/python3.12/site-packages/docket/_cli_support.pyiterate_with_timeoutr      s      
 #,,X-?-?-A7,SSS S'' 
% oohoosl   BA8 $9 79 A8 9 AA8 AA8 AA8 B1A42B8BBBBc                        e Zd ZdZdZdZdZdZy)LogLevelDEBUGINFOWARNINGERRORCRITICALN)__name__
__module____qualname__r   r   r    r!   r"        r   r   r   3   s    EDGEHr'   r   c                       e Zd ZdZdZdZy)	LogFormatrichplainjsonN)r#   r$   r%   RICHPLAINJSONr&   r'   r   r)   r)   ;   s    DEDr'   r)   whenc                 @    | j                         j                  d      S )Nz%Y-%m-%d %H:%M:%S %z)
astimezonestrftime)r0   s    r   
local_timer4   A   s    ??%%&<==r'   c                  X    t        j                          dt        j                          S )N#)socketgethostnameosgetpidr&   r'   r   default_worker_namer;   E   s#      "#1RYY[M22r'   duration_strc                 H   t        | t              r| S d| v r}| j                  d      }t        |      dk(  r t	        t
        |      \  }}t        ||      S t        |      dk(  r"t	        t
        |      \  }}}t        |||      S t        d|        | j                  d      rt        t        | dd	       
      S | j                  d      rt        t        | dd	             S | j                  d      rt        t        | dd	             S t        t        |       
      S )z
    Parse a duration string into a timedelta.

    Supported formats:
    - 123 = 123 seconds
    - 123s = 123 seconds
    - 123m = 123 minutes
    - 123h = 123 hours
    - 00:00 = mm:ss
    - 00:00:00 = hh:mm:ss
    :   )minutesseconds   )hoursr@   rA   zInvalid duration string: sNrA   mr@   h)rC   )
isinstancer   splitlenmapint
ValueErrorendswith)r<   partsr@   rA   rC   s        r   durationrR   I   s    ,	*
l""3'u:?"3GWWg>>Z1_&)#uo#E7G5'7KK8GHH			s	#\#2%6!788			s	#\#2%6!788			s	#s<#4566\!233r'   formatc                 n   t        j                         }| t        j                  k(  rWddlm}  |dd      }t        j                  t        j                        }|j                  |       |j                  |       y | t        j                  k(  r^t        j                  t        j                        }t        j                  dd	      }|j                  |       |j                  |       y dd
lm}  |       }t        j                  dd	      }|j                  |       |j                  |       y )Nr   )JsonFormatterz-{name}{asctime}{levelname}{message}{exc_info}{style)streamz4[%(asctime)s] %(levelname)s - %(name)s - %(message)sz%Y-%m-%d %H:%M:%S)datefmt)RichHandlerz%(message)sz[%X])logging	getLoggerr)   r/   pythonjsonlogger.jsonrU   StreamHandlersysstdoutsetFormatter
addHandlerr.   	Formatterrich.loggingr[   )rS   root_loggerrU   	formatterhandlerr[   s         r   set_logging_formatri   l   s    ##%K7!;3
	 ''szz:Y'w'	9??	"''szz:%%B'
	 	Y'w',-%%mVD	Y'w'r'   levelc                 ^    t        j                         j                  | j                         y N)r\   r]   setLevelvalue)rj   s    r   set_logging_levelro      s      -r'   urlc                 R    | j                  d      rt        j                  d      | S )z
    Validate that the provided URL is compatible with the CLI.

    The memory:// backend is not compatible with the CLI as it doesn't persist
    across processes.
    z	memory://zThe memory:// URL scheme is not supported by the CLI.
The memory backend does not persist across processes.
Please use a persistent backend like Redis or Valkey.)
startswithtyperBadParameter)rp   s    r   validate_urlru      s0     ~~k"  D
 	

 Jr'   rn   c                     | dv ry | S )N) *r&   )rn   s    r   handle_strike_wildcardry      s    	Lr'   c                 .   | y | j                  d      \  }}} |s| S |j                  d      \  }}}t        j                  |xs d      }t        ||      }|t        u rt	        t        |             S |t        u r| j                         dk(  S  ||       S )Nr>   .builtinsrF   true)
rpartition	importlibimport_modulegetattrr   rN   boollower)rn   type_module_namemember_namemodulemembers          r   interpret_python_valuer      s    }%%c*ND!U"&//#"6KK$$[%>J?FV[)F U,,	4{{}&&e}r'   nowc                     | |z
  }|t        d       k  rdt        |       S |t        d      k  rd|  S |t        d      k  r| dS dt        |       S )N   rH   zat r   zin  ago)r   r4   )r   r0   deltas      r   relative_timer      st    $JE	"%%%Z%&''	1	eVH~	2&	&~Z%&''r'   c                       e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
dz  ed<   dZe
dz  ed<   dZe
dz  ed	<   dZe
dz  ed
<   y)	TaskStatsz&Statistics for a single task function.r   runningqueuedtotalNoldest_queuedlatest_queuedoldest_startedlatest_started)r#   r$   r%   __doc__r   rN   __annotations__r   r   r   r   r   r   r   r&   r'   r   r   r      sY    0GSFCOE3N%)M8d?)%)M8d?)&*NHtO*&*NHtO*r'   r   snapshotc                    i }| j                   D ]  }|j                  }||vrt               ||<   ||   }|xj                   dz  c_         |xj                  dz  c_        |j                  }|j
                  }|||k  r||_        |j                  }|||kD  s||_         | j                  D ]  }|j                  }||vrt               ||<   ||   }|xj                  dz  c_        |xj                  dz  c_        |j                  }|j                  }|||k  r||_
        |j                  }|||kD  s||_         |S )z?Get task count statistics by function name with timestamp data.r   )r   function_namer   r   startedr   r   futurer   r0   r   r   )	r   stats	execution	func_name
task_statsr   oldestlatestr0   s	            r   get_task_statsr      sb   "$E %% 0	++	E!({E)9%
aA ##**>Wv-(/J%**>Wv-(/J%0$ __ ,	++	E!({E)9%
QA ~~))>TF]'+J$))>TF]'+J$," Lr'   docket_nameworkershighlight_taskc                 $   t        |d d      }t        d|        }|j                  dd       |j                  d	d
       |j                  dd       t        j                  t
        j                        }|D ]q  }||j                  z
  }t        |j                        D cg c]  }||k(  rd| dn| }	}|j                  |j                  | d|	rdj                  |	      nd       s t               }
|
j                  |       y c c}w )Nc                     | j                   S rl   )	last_seen)ws    r   <lambda>zprint_workers.<locals>.<lambda>  s
    1;; r'   T)keyreversezWorkers in Docket: )titleNamecyanrW   z	Last SeengreenTasksyellowz[bold]z[/bold]r   
z(none))sortedr   
add_columnr   r   r   utcr   tasksadd_rownamejoinr   print)r   r   r   sorted_workerstabler   workertime_agotaskr   consoles              r   print_workersr      s   
 G)>MN-k];<E	V6*	[0	WH-
,,x||
$C  
))) v||,
 '+n&<fTF'"$F
 

 	KKj %DIIe8	

 iGMM%
s   &D)r   r   r)   r4   r;   rR   ri   ro   ru   ry   r   r   r   r   r   rl   ).r   enumr   r\   r9   r7   r`   collections.abcr   r   dataclassesr   r   r   r   typingr	   r
   rs   rich.consoler   
rich.tabler   docketr   r   dictstrfloatr   Enumr   r)   r4   r;   rR   ri   ro   ru   ry   r   r   r   r   r   __all__r&   r'   r   <module>r      s   +    	  
 9 ! 2 2 "     . DcN+ 6; DcNT)4/0 <sDII TYY >X ># >3S 3 43?  4y  4F(y (T (8.X .$ .c c  # #* #*  ,	(x 	(x 	(C 	( 	+ 	+ 	+(^ (S)^0D (\ "&
# $J 
	Br'   