
    R3i                         d Z ddlZddlmZ ddlmZmZ ddlmZmZm	Z	m
Z
mZmZ ddlmZ ddlmZ erdd	lmZ  G d
 de      Z G d de      Z G d d      Zg dZy)z&Progress tracking for task executions.    N)contextmanager)datetimetimezone)TYPE_CHECKINGAnyAsyncGenerator	GeneratorLiteral	TypedDict   )suppress_instrumentation)Self)Docketc                   b    e Zd ZU ed   ed<   eed<   edz  ed<   eed<   edz  ed<   edz  ed<   y)	ProgressEventprogresstypekeyNcurrenttotalmessage
updated_at)__name__
__module____qualname__r
   __annotations__strint     d/mnt/e/genesis-system/.venvs/voice-bridge/lib/python3.12/site-packages/docket/_execution_progress.pyr   r      s5    
*
	H4ZJ4Zd
r    r   c                   |    e Zd ZU ed   ed<   eed<   eed<   eed<   edz  ed<   edz  ed<   edz  ed<   edz  ed	<   y)

StateEventstater   r   whenNworker
started_atcompleted_aterror)r   r   r   r
   r   r   r   r    r!   r#   r#      sD    
'
	HJ
I$Jd
*:r    r#   c                       e Zd ZdZdddeddfdZeded   fd	       Ze	dddede
fd
       ZdeddfdZddeddfdZdedz  ddfdZddZddZdeeef   ddfdZdeedf   fdZy)ExecutionProgressa  Manages user-reported progress for a task execution.

    Progress data is stored in Redis hash {docket}:progress:{key} and includes:
    - current: Current progress value (integer)
    - total: Total/target value (integer)
    - message: User-provided status message (string)
    - updated_at: Timestamp of last update (ISO 8601 string)

    This data is ephemeral and deleted when the task completes.
    docketr   r   returnNc                     || _         || _        |j                  d|       | _        d| _        d| _        d| _        d| _        y)zInitialize progress tracker for a specific task.

        Args:
            docket: The docket instance
            key: The task execution key
        	progress:Nr   )r,   r   
_redis_keyr   r   r   r   )selfr,   r   s      r!   __init__zExecutionProgress.__init__/   sE      **y%67#'
#'+/r    )NNNc              #      K   | j                   j                  st               5  d ddd       yd y# 1 sw Y   yxY ww)zASuppress OTel auto-instrumentation for internal Redis operations.N)r,   enable_internal_instrumentationr   )r1   s    r!   _maybe_suppress_instrumentationz1ExecutionProgress._maybe_suppress_instrumentation>   s<      {{::)+    s   !A6A?Ac                 T   K    | ||      }|j                          d{    |S 7 w)a  Create and initialize progress tracker by reading from Redis.

        Args:
            docket: The docket instance
            key: The task execution key

        Returns:
            ExecutionProgress instance with attributes populated from Redis
        N)sync)clsr,   r   instances       r!   createzExecutionProgress.createG   s-      vs#mmo 	s   (&(r   c                   K   |dk  rt        d      t        j                  t        j                        }|j                         }| j                  j                         4 d{   }|j                  | j                  t        |      |d       d{    ddd      d{    || _        || _        | j                  ||d       d{    y7 p7 A7 3# 1 d{  7  sw Y   CxY w7  w)zSet the total/target value for progress tracking.

        Args:
            total: The total number of units to complete. Must be at least 1.
        r   zTotal must be at least 1N)r   r   mapping)
ValueErrorr   nowr   utc	isoformatr,   redishsetr0   r   r   r   _publish)r1   r   updated_at_dtr   rB   s        r!   	set_totalzExecutionProgress.set_totalV   s      19788 X\\2",,.
;;$$& 	 	%** Z",    	 	 
'mme:FGGG		 	 	 	 	Hsf   A"C2$C%C2(-CCCC2%C&)C2C0C2CC2C-!C$"C-)C2amountc                   K   |dk  rt        d      t        j                  t        j                        }|j                         }| j                  j                         4 d{   }|j                  | j                  d|       d{   }|j                  | j                  d|       d{    ddd      d{    | _        || _        | j                  ||d       d{    y7 7 f7 C7 5# 1 d{  7  sw Y   ExY w7 "w)zAtomically increment the current progress value.

        Args:
            amount: Amount to increment by. Must be at least 1.
        r   zAmount must be at least 1Nr   r   )r   r   )r>   r   r?   r   r@   rA   r,   rB   hincrbyr0   rC   r   r   rD   )r1   rG   rE   r   rB   new_currents         r!   	incrementzExecutionProgress.incremento   s      A:899 X\\2",,.
;;$$& 	 	% %dooy& QQK**  	 	 #'mm:NOOO	Q	 	 	 	 	Psx   A"D$C.%D(!C6	C0
$C6.C2/C63D>C4?)D(D)D0C62C64D6D<C?=DDr   c                   K   t        j                  t        j                        }|j	                         }| j
                  j                         4 d{   }|j                  | j                  ||d       d{    ddd      d{    || _	        || _
        | j                  ||d       d{    y7 g7 A7 3# 1 d{  7  sw Y   CxY w7  w)z{Update the progress status message.

        Args:
            message: Status message describing current progress
        N)r   r   r<   )r   r?   r   r@   rA   r,   rB   rC   r0   r   r   rD   )r1   r   rE   r   rB   s        r!   set_messagezExecutionProgress.set_message   s      !X\\2",,.
;;$$& 	 	%**&",    	 	 'mmzJKKK		 	 	 	 	Lsf   ACB<C$C<B>=CCC )C6C7C>C CCC	CCc                   K   | j                         5  | j                  j                         4 d{   }|j                  | j                         d{   }|rt        |j                  dd            | _        t        |j                  dd            | _        d|v r|d   j                         nd| _
        d|v r&t        j                  |d   j                               nd| _        nd| _        d| _        d| _
        d| _        ddd      d{    ddd       y7 7 7 # 1 d{  7  sw Y   !xY w# 1 sw Y   yxY ww)	zSynchronize instance attributes with current progress data from Redis.

        Updates self.current, self.total, self.message, and self.updated_at
        with values from Redis. Sets attributes to None if no data exists.
        Ns   current   0s   totals   100s   messages
   updated_atd   )r5   r,   rB   hgetallr0   r   getr   r   decoder   r   fromisoformatr   )r1   rB   datas      r!   r7   zExecutionProgress.sync   s*     113 	+{{((* + +e"]]4??;;#&txx
D'A#BDL!$TXXh%?!@DJ5?45GZ(//1T L
 )D0 !..tM/B/I/I/KL! O $(DL!$DJ#'DL&*DO#+ +	+ 	++;+ + + +	+ 	+st   ED<D!D<D'D#B2D'D<D%D<	E!D<#D'%D<'D9	-D0.D9	5D<<EEc                 p  K   | j                         5  | j                  j                         4 d{   }|j                  | j                         d{    ddd      d{    ddd       d| _        d| _        d| _        d| _        y7 \7 ;7 -# 1 d{  7  sw Y   =xY w# 1 sw Y   AxY ww)zgDelete the progress data from Redis.

        Called internally when task execution completes.
        NrP   )	r5   r,   rB   deleter0   r   r   r   r   )r1   rB   s     r!   rW   zExecutionProgress.delete   s     
 113 	4{{((* 4 4ell4??3334 4	4 
434 4 4 4	4 	4ss   B6B*BB*BBBB*%B&B**%B6B*BB*B'	BB'	#B**B3/B6rU   c                 j  K   | j                   j                  d| j                         }d| j                  | j                  | j                  nd| j                  | j                  |j                  d      d}| j                   j                  |t        j                  |             d{    y7 w)zPublish progress update to Redis pub/sub channel.

        Args:
            data: Progress data to publish (partial update)
        r/   r   Nr   r   )r   r   r   r   r   r   )	r,   r   r   r   r   rR   rD   jsondumps)r1   rU   channelpayloads       r!   rD   zExecutionProgress._publish   s      ++//IdhhZ"8988'+||'?t||QZZ||((<0"
 kk""7DJJw,?@@@s   B)B3+B1,B3c                  K   | j                   j                  d| j                         }| j                   j                         4 d{   }|j                  |       d{    |j	                         2 3 d{   }|d   dk(  st        j                  |d          .7 [7 D7 -6 ddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a~  Subscribe to progress updates for this task.

        Yields:
            Dict containing progress update events with fields:
            - type: "progress"
            - key: task key
            - current: current progress value
            - total: total/target value (or None)
            - message: status message (or None)
            - updated_at: ISO 8601 timestamp
        r/   Nr   r   rU   )r,   r   _pubsub	subscribelistenrY   loads)r1   r[   pubsubr   s       r!   r_   zExecutionProgress.subscribe   s      ++//IdhhZ"89;;&&( 	6 	6F""7+++!' 6 6g6?i/**WV_55		6+6	6 	6 	6 	6 	6s   AC	B%
CB>"B'#B>7B+;B)<B+?	B>	B>%C'B>)B++B>,C7B:8C>CCCC)r   )r-   N)r   r   r   __doc__r   r2   r   r	   r5   classmethodr   r:   r   rF   rK   rM   r7   rW   dictr   rD   r   r   r_   r   r    r!   r+   r+   #   s    	0x 0c 0d 0 ;K1L   (    HS HT H2Pc P$ P0Lt L L,+4A4S> Ad A"6t0C!D 6r    r+   )r+   r   r#   )rc   rY   
contextlibr   r   r   typingr   r   r   r	   r
   r   
_telemetryr   typing_extensionsr   r,   r   r   r#   r+   __all__r   r    r!   <module>rk      sO    ,  % ' T T 0 "I  D6 D6Nr    