
    AHj!                        d dl mZ d dlZd dlmZmZ d dlmZmZ d dlm	Z	 d dl
mZ erd dlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZmZmZmZ  G d d      Z G d de      Z ej8                  d      ZddZddZy)    )annotationsN)datetimetimezone)TYPE_CHECKINGAny)uuid4)Redis)Pipeline   )
BaseWorker)Job)BaseRegistryStartedJobRegistry)as_textcurrent_timestampnowparse_composite_keyc                      e Zd ZdZddZddZedd       Zedd       Zed        Z	e
dd       Zd Ze
dd	       Ze
dd
       ZdddZddZddZddZy)	Executionz)Class to represent an execution of a job.c                l    || _         || _        || _        t               }|| _        || _        d | _        y N)idjob_id
connectionr   
created_atlast_heartbeat_job)selfr   r   r   	right_nows        E/root/tools/cai/cai_env/lib/python3.12/site-packages/rq/executions.py__init__zExecution.__init__   s4    $E	#' $	    c                V    t        |t              sy| j                  |j                  k(  S )NF)
isinstancer   r   )r   others     r    __eq__zExecution.__eq__!   s"    %+ww%((""r"   c                     d| j                    S )Nzrq:execution:)composite_keyr   s    r    keyzExecution.key&   s    t11233r"   c                    | j                   r| j                   S t        j                  | j                  | j                        | _         | j                   S )N)r   r   )r   r   fetchr   r   r)   s    r    jobzExecution.job*   s7    9999III	yyr"   c                8    | j                    d| j                   S )N:)r   r   r)   s    r    r(   zExecution.composite_key1   s    ++ay))r"   c                <     | |||      }|j                          |S )zFetch an execution from Redis.r   r   r   )refresh)clsr   r   r   	executions        r    r,   zExecution.fetch5   s$     2fD	r"   c                \   | j                   j                  | j                        }|st        d| j                   d      t        j                  t        |d         t        j                        | _
        t        j                  t        |d         t        j                        | _        y)z"Refresh execution data from Redis.z
Execution z not found in Rediss
   created_at)tzs   last_heartbeatN)r   hgetallr*   
ValueErrorr   r   fromtimestampfloatr   utcr   r   )r   datas     r    r2   zExecution.refresh<   s    &&txx0z$''2EFGG"00tM7J1KPXP\P\]&44U4@Q;R5SX`XdXder"   c                4    t        |      \  }} | |||      S )z>A combination of job_id and execution_id separated by a colon.r1   )r   )r3   r(   r   r   execution_ids        r    from_composite_keyzExecution.from_composite_keyD   s"      3=Al6jIIr"   c                "   t               j                  } | ||j                  |j                        }|j	                  ||       t        |j                  |      j                  |||       |j                  j                  |||d       |S )zSave execution data to Redis.r1   )ttlpipeliner   r   r4   rA   rB   F)rB   rA   xx)	r   hexr   r   saveExecutionRegistryaddstarted_job_registryadd_execution)r3   r-   rA   rB   r   r4   s         r    createzExecution.createJ   s|     W[[2cffH	32H=AAI[^iqAr  ..y8QTY^._r"   Nc                    ||n| j                   }|j                  | j                  | j                                |j	                  | j                  |       y)z6Save execution data to Redis and JobExecutionRegistry.N)mapping)r   hsetr*   	serializeexpire)r   rA   rB   r   s       r    rG   zExecution.saveT   sA    !)!5X4??
$..*:;$((C(r"   c                    |j                  | j                         |j                  j                  | |       t	        | j
                  | j                        j                  | |       y)zDelete an execution from Redis.)r4   rB   rC   N)deleter*   rJ   remove_executionrH   r   r   remove)r   r-   rB   s      r    rS   zExecution.delete[   sO    !  11D81TIPP[_jrPsr"   c                    | j                   | j                  j                         | j                  j                         dS )N)r   r   r   )r   r   	timestampr   r)   s    r    rP   zExecution.serializea   s5    ''//335"11;;=
 	
r"   c                @   t               | _        |j                  | j                  d| j                  j	                                |j                  | j                  |       |j                  | ||d       t        | j                  |      j                  | ||       y)zUpdate execution heartbeat.r   T)rA   rB   rE   rC   rD   N)
r   r   rO   r*   rW   rQ   rK   rH   r   rI   )r   rJ   rA   rB   s       r    	heartbeatzExecution.heartbeath   s     "edhh 0$2E2E2O2O2QR#&**4S8PT*UBFFQU[^iqFrr"   )r   strr   rZ   r   r	   )r%   objectreturnbool)r\   rZ   )r\   r   )r   rZ   r   rZ   r   r	   r\   r   )r(   rZ   r   r	   r\   r   )r-   r   rA   intrB   r
   r\   r   r   )rA   r^   rB   zPipeline | Noner-   r   rB   r
   )r\   dict)rJ   r   rA   r^   rB   r
   )__name__
__module____qualname____doc__r!   r&   propertyr*   r-   r(   classmethodr,   r2   r?   rL   rG   rS   rP   rY    r"   r    r   r      s    3%#
 4 4   * *  f J J
  )t
sr"   r   c                  R    e Zd ZdZdZddZdddZddZddZdddZ	ddd	Z
dd
Zy)rH   zbClass to represent a registry of job executions.
    Each job has its own execution registry.
    zrq:executions:{0}c                `    || _         || _        | j                  j                  |      | _        y r   )r   r   key_templateformatr*   )r   r   r   s      r    r!   zExecutionRegistry.__init__y   s(    $$$++F3r"   Nc                n    ||n	t               }| j                  j                  | j                  d|       y)zRemove expired jobs from registry.

        Removes jobs with an expiry time earlier than timestamp, specified as
        seconds since the Unix epoch. timestamp defaults to call time if
        unspecified.
        Nr   )r   r   zremrangebyscorer*   )r   rW   exception_handlersscores       r    cleanupzExecutionRegistry.cleanup~   s.     '2	8I8K((1e<r"   c                    t               |z   }|j                  | j                  |j                  |dz   i       |j	                  | j                  |dz          y)a  Register an execution to registry with expiry time of now + ttl, unless it's -1 which is set to +inf

        Args:
            execution (Execution): The Execution to add
            ttl (int, optional): The time to live. Defaults to 0.
            pipeline (Optional[Pipeline], optional): The Redis Pipeline. Defaults to None.

        Returns:
            result (int): The ZADD command result
        <   N)r   zaddr*   r   rQ   )r   r4   rA   rB   ro   s        r    rI   zExecutionRegistry.add   sI     "#c)dhhurz :;#(+r"   c                N    |j                  | j                  |j                        S )z"Remove an execution from registry.)zremr*   r   )r   r4   rB   s      r    rU   zExecutionRegistry.remove   s    }}TXXy||44r"   c                    | j                          | j                  j                  | j                  ||      D cg c]  }t	        |       c}S c c}w )&Returns all executions IDs in registry)rp   r   zranger*   r   )r   startendr   s       r    get_execution_idsz#ExecutionRegistry.get_execution_ids   s;    .2oo.D.DTXXuVY.Z[F[[[s   Ac                    | j                  ||      }g }|D ]=  }|j                  t        j                  || j                  | j
                               ? |S )rw   r1   )r{   appendr   r,   r   r   )r   ry   rz   execution_ids
executionsr>   s         r    get_executionsz ExecutionRegistry.get_executions   sX    ..uc:
) 	pLioodkk^b^m^mono	pr"   c                    | j                         }|D ]  }|j                  ||        |j                  | j                         y)zDelete the registry.)rB   r-   N)r   rS   r*   )r   r-   rB   r   r4   s        r    rS   zExecutionRegistry.delete   sB    ((*
# 	9IhC8	9!r"   )r   rZ   r   r	   )NN)rW   zfloat | Nonern   zlist | None)r4   r   rA   r^   rB   r
   r\   r   )r4   r   rB   r
   r\   r   )r   )ry   r^   rz   r^   r\   z	list[str])ry   r^   rz   r^   r\   zlist[Execution]r_   )ra   rb   rc   rd   rj   r!   rp   rI   rU   r{   r   rS   rg   r"   r    rH   rH   r   s2     'L4
="5\
"r"   rH   z	rq.workerc                P   ddl m} | j                  j                         5 }| j	                  |      }t
        j                  |||      | _        | j                  |j                  |       |j                          ddd       | j                  S # 1 sw Y   | j                  S xY w)az  Prepares execution for a job. This is called by the main Worker (not the horse)
    as it prepares for execution. Do not confuse this with worker.prepare_job_execution()
    which is called by the horse.

    Args:
        worker: The worker preparing the execution
        job: The job to prepare execution for

    Returns:
        Execution: The created Execution object
    r   )WorkerStatusrB   N)worker.baser   r   rB   get_heartbeat_ttlr   rL   r4   	set_stateBUSYexecute)workerr-   r   rB   heartbeat_ttls        r    prepare_executionr      s     *				#	#	% 005$++C+R**X>	
 
 s   ABB%c                    t         j                  d|j                         | j                  d|       | j                  %| j                  j                  ||       d| _        yy)a@  Cleans up the execution of a job.
    It will remove the job execution record from the StartedJobRegistry and delete the Execution object.

    Args:
        worker: The worker to clean up execution for
        job: The job whose execution is being cleaned up
        pipeline: Redis pipeline to use for the cleanup
    zCleaning up execution of job %sNr   )r-   rB   )loggerdebugr   set_current_job_idr4   rS   )r   r-   rB   s      r    cleanup_executionr      s\     LL2CFF;
dX6#C(; $r"   )r   r   r-   r   r\   r   )r   r   r-   r   rB   r
   r\   None) 
__future__r   loggingr   r   typingr   r   uuidr   redisr	   redis.clientr
   r   r   r-   r   registryr   r   utilsr   r   r   r   r   rH   	getLoggerr   r   r   rg   r"   r    <module>r      sf    "  ' %  %'  6 G GZs Zsz>" >"B 
		;	'. r"   