
    s,g                       U 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mZ d dl	m
Z
 d dlmZmZmZmZmZmZmZmZmZmZ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  er6d d
l!m"Z" 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, ddl-m.Z.  G d d      Z/ddl0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE  ej                  d      ZG G d deHe
      ZIdeHdeHfdZJ G d d      ZK eL       ZMdeNd <   	 d/d!eHd"d#d$eOfd%ZPd0d"ed#   d&ed'   ded'   fd(ZQd1d!eHd"d#dd'fd)ZR G d* d'      ZS e5       ZT G d+ d,      ZU G d- d.      ZVy)2    N)datetime	timedeltatimezone)Enum)TYPE_CHECKINGAnyCallableDictIterableListMappingOptionalTupleTypeUnion)uuid4)
WatchError   )CALLBACK_TIMEOUT#UNSERIALIZABLE_RETURN_VALUE_PAYLOAD)BaseDeathPenaltyJobTimeoutException)ExcInfo)Redis)Pipeline)Unpack)	ExecutionExecutionRegistryQueueResultc                       e Zd Zy)UnevaluatedTypeN)__name__
__module____qualname__     `/var/www/trellinator.diamondhoofcare.com/public_html/venv/lib/python3.12/site-packages/rq/job.pyr$   r$      s    r)   r$   )DeserializationErrorInvalidJobOperationNoSuchJobError)
LocalStack)resolve_serializer)FunctionReferenceTypeJobDependencyType)
as_textdecode_redis_hashensure_listget_call_stringget_versionimport_attributenowparse_timeoutstr_to_date	utcformatzrq.jobc                   0    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zy
)	JobStatusz9The Status of Job within its lifecycle at any given time.queuedfinishedfailedstarteddeferred	scheduledstoppedcanceledN)r%   r&   r'   __doc__QUEUEDFINISHEDFAILEDSTARTEDDEFERRED	SCHEDULEDSTOPPEDCANCELEDr(   r)   r*   r=   r=   3   s-    CFHFGHIGHr)   r=   job_or_execution_idreturnc                 6    d| v r| j                  d      d   S | S )zbParse a string and returns job ID. This function supports both job ID and execution composite key.:r   )split)rO   s    r*   parse_job_idrT   @   s'    
!!"((-a00r)   c                   2    e Zd Zddeedef      dedefdZy)
DependencyjobsJoballow_failureenqueue_at_frontc                     t        |      }t        d |D              st        d      t        |      dk  rt        d      || _        || _        || _        y)a  The definition of a Dependency.

        Args:
            jobs (List[Union[Job, str]]): A list of Job instances or Job IDs.
                Anything different will raise a ValueError
            allow_failure (bool, optional): Whether to allow for failure when running the depency,
                meaning, the dependencies should continue running even after one of them failed.
                Defaults to False.
            enqueue_at_front (bool, optional): Whether this dependecy should be enqueued at the front of the queue.
                Defaults to False.

        Raises:
            ValueError: If the `jobs` param has anything different than `str` or `Job` class or the job list is empty
        c              3   f   K   | ])  }|st        |t              xs t        |t               + y wN)
isinstancerX   str).0jobs     r*   	<genexpr>z&Dependency.__init__.<locals>.<genexpr>X   s)     aC]`:c3'?:c3+??as   1'1zJjobs: must contain objects of type Job and/or strings representing Job idsr   zjobs: cannot be empty.N)r4   all
ValueErrorlendependenciesrY   rZ   )selfrW   rY   rZ   dependent_jobss        r*   __init__zDependency.__init__H   sY     %T*a>aaijj 1$566** 0r)   N)FF)r%   r&   r'   r   r   r_   boolri   r(   r)   r*   rV   rV   G   s+    1T%s
"34 1T 1ei 1r)   rV   UNEVALUATEDjob_id
connectionr   enqueue_dependentsc                 T    t         j                  | ||      j                  |       y)a  Cancels the job with the given job ID, preventing execution.
    Use with caution. This will discard any job info (i.e. it can't be requeued later).

    Args:
        job_id (str): The Job ID
        connection (Optional[Redis], optional): The Redis Connection. Defaults to None.
        serializer (str, optional): The string of the path to the serializer to use. Defaults to None.
        enqueue_dependents (bool, optional): Whether dependents should still be enqueued. Defaults to False.
    rm   
serializer)rn   N)rX   fetchcancel)rl   rm   rq   rn   s       r*   
cancel_jobrt   h   s%     IIf
ICJJ^pJqr)   	job_classrX   c                     | rt        j                  dt               |rt        j                  dt               t        j                  S )a  Returns the Job instance that is currently being executed.
    If this function is invoked from outside a job context, None is returned.

    Args:
        connection (Optional[Redis], optional): The connection to use. Defaults to None.
        job_class (Optional[Job], optional): The job class (DEPRECATED). Defaults to None.

    Returns:
        job (Optional[Job]): The current Job running
    z6connection argument for get_current_job is deprecated.z5job_class argument for get_current_job is deprecated.)warningswarnDeprecationWarning
_job_stacktop)rm   ru   s     r*   get_current_jobr|   u   s4     NPbcMOab>>r)   c                 R    t         j                  | ||      }|j                         S )aG  Fetches a Job by ID and requeues it using the `requeue()` method.

    Args:
        job_id (str): The Job ID that should be requeued.
        connection (Redis): The Redis Connection to use
        serializer (Optional[str], optional): The serializer. Defaults to None.

    Returns:
        Job: The requeued Job object.
    rp   )rX   rr   requeue)rl   rm   rq   ra   s       r*   requeue_jobr      s$     ))Fzj)
IC;;=r)   c            ,       	   e Zd ZU dZed    ed<   dZddee   ded   fdZe		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddddd	d
e
deeeef      deeeef      ded   dee   dee   dee   dee   dee   dee   dee   dedeeeef      dee   dee   deededef   f      deededef   f      deededef   f      dd f&d       Zdee   fdZddedee   fd Zdded!ed"   ddfd#Zddedefd$Zedefd%       Zedefd&       Zedefd'       Zedefd(       Zedefd)       Zedefd*       Z edefd+       Z!edefd,       Z"ed-        Z#eded    fd.       Z$ede%e   fd/       Z&ed0        Z'ed1        Z(edefd2       Z)ed3        Z*edefd4       Z+ed5        Z,edefd6       Z-d7 Z.ed8        Z/e/j`                  d9        Z/ed:        Z1e1j`                  d;        Z1ed<        Z2e2j`                  d=        Z2edeeef   fd>       Z3e3j`                  d?        Z3edeeef   fd@       Z4e4j`                  dA        Z4e	dBedddefdC       Z5e	ddeded   dd fdD       Z6e	ddEe7e   ddde%ed       fdF       Z8dG Z9dH Z:dI Z;dJ Z<defdKZ=dLeddfdMZ>ddNe?ded!ed"   dOefdPZ@ ee=e>      ZAe	dBedeBfdQ       ZCe	dBedefdR       ZDedS        ZEedT        ZFedU        ZGddVed!ed"   de%d    fdWZHedee   fdX       ZIddedee   fdYZJedefdZ       ZKde%d[   fd\ZLddeded[   fd]ZMdefd^ZNd_ ZOdd`edaedePfdbZQdd!ed"   d`edaefdcZRedefdd       ZSdeTeeef   fdeZUdf ZVdd!ed"   dgefdhZWddiedd fdjZXeddk       ZYde%dl   fdmZZdd!ed"   dnefdoZ[	 dd!ed"   dnedpefdqZ\dd!ed"   fdrZ]defdsZ^dted!d"fduZ_defdvZ`ddwee   dee   fdxZadwedefdyZbdee   fdzZcddee   d!ed"   dnefd{Zded|        Zeed}        Zfed~        Zgdehei   defdZjdehei   fdZkdehei   fdZlded!d"fdZmded!d"fdZnddZodefdZpedefd       ZqddZrdd!ed"   fdZsede%eB   fd       Zt	 	 	 dded    d!ed"   dee   defdZuy)rX   zHA Job is just a convenient datastructure to pass around job (meta) data._dependencyzrq:job:Nidrm   r   c                    |st        d      || _        || _        t               | _        t
        | _        t
        | _        t
        | _        t
        | _	        t
        | _
        d | _        t
        | _        d | _        t
        | _        d | _        t
        | _        d | _        d| _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _         g | _!        i | _"        tG        |      | _$        d | _%        d | _&        d | _'        d | _(        d | _)        d | _*        d | _+        d | _,        ddl-m.} d | _/        y )Nz8Job.__init__() missing 1 required argument: 'connection' r   r!   )0	TypeErrorrm   _idr8   
created_atrk   _data
_func_name	_instance_args_kwargs_success_callback_name_success_callback_failure_callback_name_failure_callback_stopped_callback_name_stopped_callbackdescriptionoriginenqueued_at
started_atended_at_result	_exc_infotimeout_success_callback_timeout_failure_callback_timeout_stopped_callback_timeout
result_ttlfailure_ttlttlworker_name_status_dependency_idsmetar/   rq   retries_leftnumber_of_retriesretry_intervalsredis_server_versionlast_heartbeatallow_dependency_failuresrZ   group_idresultsr"   _cached_result)rg   r   rm   rq   r"   s        r*   ri   zJob.__init__   s^    VWW$% 
9DEP<G
AL59#al59# 	 6:#\g*./3.2,0&*(,(,8<&8<&8<&)-*."&*.,0*,$&	,Z8+/0448DH!269=&04'+#04r)   )
on_success
on_failure
on_stoppedfuncargskwargsr   r   statusr   
depends_onr   r   r   r   r   r   Callback.r   r   rP   c                   |d}|i }t        |t        t        f      st        dj	                  |            t        |t
              st        dj	                  |             | ||      }||j                  |       |r||_        d|_        t        j                  |      r#|j                  |_        |j                  |_        nt        j                  |      st        j                  |      r,dj	                  |j                   |j"                        |_        nkt        |t$              rt'        |      |_        nJt        j(                  |      st+        |d      r||_        d|_        nt        dj	                  |            ||_        ||_        |rWt        |t0              s%t3        j4                  d	t6               t1        |      }|j8                  |_        |j<                  |_        |rWt        |t0              s%t3        j4                  d
t6               t1        |      }|j8                  |_         |j<                  |_!        |rWt        |t0              s%t3        j4                  dt6               t1        |      }|j8                  |_"        |j<                  |_#        |xs |jI                         |_%        tM        |      |_'        tM        |      |_(        tM        |      |_)        tM        |
      |_        ||_*        |xs i |_+        ||_,        |	g }t[        |	      D ]  }t        |t\              rZ|j^                  xs |j^                  |_/        |j`                  xs |jb                  |_0        |je                  |jf                         m|je                  t[        |              |D cg c]   }t        |th              r|jj                  n|" c}|_6        |S c c}w )a  Creates a new Job instance for the given function, arguments, and
        keyword arguments.

        Args:
            func (FunctionReference): The function/method/callable for the Job. This can be
                a reference to a concrete callable or a string representing the  path of function/method to be
                imported. Effectively this is the only required attribute when creating a new Job.
            args (Union[List[Any], Optional[Tuple]], optional): A Tuple / List of positional arguments to pass the
                callable.  Defaults to None, meaning no args being passed.
            kwargs (Optional[Dict], optional): A Dictionary of keyword arguments to pass the callable.
                Defaults to None, meaning no kwargs being passed.
            connection (Redis): The Redis connection to use. Defaults to None.
                This will be "resolved" using the `resolve_connection` function when initialzing the Job Class.
            result_ttl (Optional[int], optional): The amount of time in seconds the results should live.
                Defaults to None.
            ttl (Optional[int], optional): The Time To Live (TTL) for the job itself. Defaults to None.
            status (JobStatus, optional): The Job Status. Defaults to None.
            description (Optional[str], optional): The Job Description. Defaults to None.
            depends_on (Union['Dependency', List[Union['Dependency', 'Job']]], optional): What the jobs depends on.
                This accepts a variaty of different arguments including a `Dependency`, a list of `Dependency` or a
                `Job` list of `Job`. Defaults to None.
            timeout (Optional[int], optional): The amount of time in seconds that should be a hardlimit for a job
                execution. Defaults to None.
            id (Optional[str], optional): An Optional ID (str) for the Job. Defaults to None.
            origin (Optional[str], optional): The queue of origin. Defaults to None.
            meta (Optional[Dict[str, Any]], optional): Custom metadata about the job, takes a dictioanry.
                Defaults to None.
            failure_ttl (Optional[int], optional): THe time to live in seconds for failed-jobs information.
                Defaults to None.
            serializer (Optional[str], optional): The serializer class path to use. Should be a string with the import
                path for the serializer to use. eg. `mymodule.myfile.MySerializer` Defaults to None.
            on_success (Optional[Union['Callback', Callable[..., Any]]], optional): A callback to run when/if the Job
                finishes sucessfully. Defaults to None. Passing a callable is deprecated.
            on_failure (Optional[Union['Callback', Callable[..., Any]]], optional): A callback to run when/if the Job
                fails. Defaults to None. Passing a callable is deprecated.
            on_stopped (Optional[Union['Callback', Callable[..., Any]]], optional): A callback to run when/if the Job
                is stopped. Defaults to None. Passing a callable is deprecated.
            group_id (Optional[str], optional): A group ID that the job is being added to. Defaults to None.

        Raises:
            TypeError: If `args` is not a tuple/list
            TypeError: If `kwargs` is not a dict
            TypeError: If the `func` is something other than a string or a Callable reference
            ValueError: If `on_failure` is not a Callback or function or string
            ValueError: If `on_success` is not a Callback or function or string
            ValueError: If `on_stopped` is not a Callback or function or string

        Returns:
            Job: A job instance.
        Nr(   z{0!r} is not a valid args listz {0!r} is not a valid kwargs dictrp   {0}.{1}__call__z-Expected a callable or a string, but got: {0}zTPassing a string or function for `on_success` is deprecated, pass `Callback` insteadzTPassing a string or function for `on_failure` is deprecated, pass `Callback` insteadzTPassing a string or function for `on_stopped` is deprecated, pass `Callback` instead)7r^   tuplelistr   formatdictset_idr   r   inspectismethod__self__r%   r   
isfunction	isbuiltinr&   r'   r_   r2   isclasshasattrr   r   r   rw   rx   ry   namer   r   r   r   r   r   r   r5   r   r9   r   r   r   r   r   r   r4   rV   rZ   r   rY   extendrf   rX   r   r   )clsr   r   r   rm   r   r   r   r   r   r   r   r   r   r   rq   r   r   r   r   ra   depends_on_listdepends_on_itemdeps                           r*   createz
Job.create   s5   T <D>F$.<CCDIJJ&$'>EEfMNNZJ?>JJrNCJ D! MMCM!]]CN%):):4)@&--doot?P?PQCNc"$T]CN&74+D CM'CNKRRSWXYY	j(3j& &j1
)3C&,6,>,>C)j(3j& &j1
)3C&,6,>,>C)j(3j& &j1
)3C&,6,>,>C) &>)<)<)>&z2'4$#G,:2 ! O#.z#: Ioz: ,/+?+?+c?CcCcC(474Q4Q4rUdUrUrC1#**?+G+GH#**;+GHI Wf"fsZS-A366s#J"fC
 #gs   0%Oc                     ddl m} | j                  r9 || j                  | j                        }|j	                  | j
                        S y)zsGet's the job's position on the queue

        Returns:
            position (Optional[int]): The position
        r   r   )r   rm   N)queuer    r   rm   get_job_positionr   )rg   r    qs      r*   get_positionzJob.get_positionu  s:     	!;;4;;4??CA%%dgg..r)   refreshc                     |rY| j                   j                  | j                  d      }|st        d| j                         t        t        |            | _        | j                  S )a3  Gets the Job Status

        Args:
            refresh (bool, optional): Whether to refresh the Job. Defaults to True.

        Raises:
            InvalidJobOperation: If refreshing and nothing is returned from the `HGET` operation.

        Returns:
            status (JobStatus): The Job Status
        r   z#Failed to retrieve status for job: )rm   hgetkeyr,   r   r=   r2   r   )rg   r   r   s      r*   
get_statuszJob.get_status  sX     __))$((H=F),OPTPWPWy*YZZ$WV_5DL||r)   pipeliner   c                     || _         ||n| j                  }|j                  | j                  d| j                          y)zSet's the Job Status

        Args:
            status (JobStatus): The Job Status to be set
            pipeline (Optional[Pipeline], optional): Optional Redis Pipeline to use. Defaults to None.
        Nr   )r   rm   hsetr   )rg   r   r   rm   s       r*   
set_statuszJob.set_status  s3     *2*>hDOO
(DLL9r)   c                     |rJ| j                   j                  | j                  d      }|r| j                  j	                  |      ni | _        | j
                  S )zGet's the metadata for a Job, an arbitrary dictionary.

        Args:
            refresh (bool, optional): Whether to refresh. Defaults to True.

        Returns:
            meta (Dict): The dictionary of metadata
        r   )rm   r   r   rq   loadsr   )rg   r   r   s      r*   get_metazJob.get_meta  sE     ??''&9D7;--d3DIyyr)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rH   rg   s    r*   is_finishedzJob.is_finished       I$6$666r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rG   r   s    r*   	is_queuedzJob.is_queued       I$4$444r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rI   r   s    r*   	is_failedzJob.is_failed  r   r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rJ   r   s    r*   
is_startedzJob.is_started       I$5$555r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rK   r   s    r*   is_deferredzJob.is_deferred  r   r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rN   r   s    r*   is_canceledzJob.is_canceled  r   r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rL   r   s    r*   is_scheduledzJob.is_scheduled  s     I$7$777r)   c                 D    | j                         t        j                  k(  S r]   )r   r=   rM   r   s    r*   
is_stoppedzJob.is_stopped  r   r)   c                 :    | j                   r| j                   d   S y)z}Returns the first item in self._dependency_ids. Present to
        preserve compatibility with third party packages.
        r   N)r   r   s    r*   _dependency_idzJob._dependency_id  s#    
 ''**  r)   c                     | j                   syt        | d      r| j                  S | j                  | j                   d   | j                  | j
                        }|| _        |S )zReturns a job's first dependency. To avoid repeated Redis fetches, we cache
        job.dependency as job._dependency.
        Nr   r   rp   )r   r   r   rr   rm   rq   )rg   ra   s     r*   
dependencyzJob.dependency  s]    
 ##4'###jj--a0T__Y]YhYhji
r)   c                 z    t        t        t        | j                  j	                  | j
                                    S )zaReturns a list of ids of jobs whose execution depends on this
        job's successful execution.)r   mapr2   rm   smembersdependents_keyr   s    r*   dependent_idszJob.dependent_ids  s+     C!9!9$:M:M!NOPPr)   c                     | j                   }|y | j                  rt        | j                  |      S t        | j                         S r]   )	func_nameinstancegetattrr7   )rg   r   s     r*   r   zJob.func  s;    NN	==4==)44//r)   c                     | j                   t        u r9| j                  r&t        | j                        | _         | j                   S d | _         | j                   S r]   )r   rk   r   r7   r   s    r*   success_callbackzJob.success_callback  P    !![0**)9$:U:U)V& %%% *.&%%%r)   c                 >    | j                   t        S | j                   S r]   )r   r   r   s    r*   success_callback_timeoutzJob.success_callback_timeout       ))1##---r)   c                     | j                   t        u r9| j                  r&t        | j                        | _         | j                   S d | _         | j                   S r]   )r   rk   r   r7   r   s    r*   failure_callbackzJob.failure_callback  r  r)   c                 >    | j                   t        S | j                   S r]   )r   r   r   s    r*   failure_callback_timeoutzJob.failure_callback_timeout  r  r)   c                     | j                   t        u r9| j                  r&t        | j                        | _         | j                   S d | _         | j                   S r]   )r   rk   r   r7   r   s    r*   stopped_callbackzJob.stopped_callback  r  r)   c                 >    | j                   t        S | j                   S r]   )r   r   r   s    r*   stopped_callback_timeoutzJob.stopped_callback_timeout!  r  r)   c                     	 | j                   j                  | j                        \  | _        | _        | _        | _        y# t        $ r}t               |d}~ww xY w)zDeserializes the Job `data` into a tuple.
        This includes the `_func_name`, `_instance`, `_args` and `_kwargs`

        Raises:
            DeserializationError: Cathes any deserialization error (since serializers are generic)
        N)	rq   r   datar   r   r   r   	Exceptionr+   )rg   es     r*   _deserialize_datazJob._deserialize_data(  sN    	0HLH]H]^b^g^gHhEDOT^TZ 	0&(a/	0s   >A 	A
AAc                    | j                   t        u r| j                  t        u rt        d      | j                  t        u rd | _        | j
                  t        u rd| _        | j                  t        u ri | _        | j                  | j                  | j
                  | j                  f}| j                  j                  |      | _         | j                   S )NzCannot build the job datar(   )	r   rk   r   rd   r   r   r   rq   dumps)rg   	job_tuples     r*   r  zJob.data4  s    ::$+- !<==~~,!%zz[(
||{*!T\\QI..y9DJzzr)   c                 j    || _         t        | _        t        | _        t        | _        t        | _        y r]   )r   rk   r   r   r   r   rg   values     r*   r  zJob.dataG  s%    
%$ 
"r)   c                 ^    | j                   t        u r| j                          | j                   S r]   )r   rk   r  r   s    r*   r   zJob.func_nameO  s$    ??k)""$r)   c                 (    || _         t        | _        y r]   )r   rk   r   r  s     r*   r   zJob.func_nameU  s     
r)   c                 ^    | j                   t        u r| j                          | j                   S r]   )r   rk   r  r   s    r*   r   zJob.instanceZ  s$    >>[(""$~~r)   c                 (    || _         t        | _        y r]   )r   rk   r   r  s     r*   r   zJob.instance`  s     
r)   c                 ^    | j                   t        u r| j                          | j                   S r]   )r   rk   r  r   s    r*   r   zJob.argse  s$    ::$""$zzr)   c                 (    || _         t        | _        y r]   )r   rk   r   r  s     r*   r   zJob.argsk  s    
 
r)   c                 ^    | j                   t        u r| j                          | j                   S r]   )r   rk   r  r   s    r*   r   z
Job.kwargsp  s$    <<;&""$||r)   c                 (    || _         t        | _        y r]   )r   rk   r   r  s     r*   r   z
Job.kwargsv  s     
r)   rl   c                 \    | j                  |      }|j                  |      }t        |      S )a  Checks whether a Job Hash exists for the given Job ID

        Args:
            job_id (str): The Job ID
            connection (Optional[Redis], optional): Optional connection to use. Defaults to None.

        Returns:
            job_exists (bool): Whether the Job exists
        )key_forexistsrj   )r   rl   rm   job_key
job_existss        r*   r"  z
Job.exists{  s-     ++f%&&w/
Jr)   c                 N     | t        |      ||      }|j                          |S )a  Fetches a persisted Job from its corresponding Redis key and instantiates it

        Args:
            id (str): The Job to fetch
            connection (Optional[&#39;Redis&#39;], optional): An optional Redis connection. Defaults to None.
            serializer (_type_, optional): The serializer to use. Defaults to None.

        Returns:
            Job: The Job instance
        rp   )rT   r   )r   r   rm   rq   ra   s        r*   rr   z	Job.fetch  s%     ,r"zjQ
r)   job_idsc                    |D cg c]  }t        |       }}|j                         5 }|D ]"  }|j                  | j                  |             $ |j	                         }ddd       g }t        |      D ]L  \  }	}|	   s|j                  d        | |||      }
|
j                  ||	          |j                  |
       N |S c c}w # 1 sw Y   lxY w)a  
        Bulk version of Job.fetch

        For any job_ids which a job does not exist, the corresponding item in
        the returned list will be None.

        Args:
            job_ids (Iterable[str]): A list of job ids.
            connection (Redis): Redis connection
            serializer (Callable): A serializer

        Returns:
            jobs (list[Optional[Job]]): A list of Jobs instances, elements are None if a job_id does not exist.
        Nrp   )rT   r   hgetallr!  execute	enumerateappendrestore)r   r&  rm   rq   rl   
parsed_idsr   r   rW   ira   s              r*   
fetch_manyzJob.fetch_many  s      :AAvl6*A
A  " 	)h$ 6  V!456&&(G	)
 ')":. 	IAv1:D!f
KCKK
#KK	 ! B	) 	)s   C8CCc                 x    dj                  | j                  j                  | j                  | j                        S )Nz{0}({1!r}, enqueued_at={2!r}))r   	__class__r%   r   r   r   s    r*   __repr__zJob.__repr__  s,    .55dnn6M6MtxxY]YiYijjr)   c                 x    dj                  | j                  j                  | j                  | j                        S )Nz<{0} {1}: {2}>)r   r1  r%   r   r   r   s    r*   __str__zJob.__str__  s+    &&t~~'>'>IYIYZZr)   c                 d    t        || j                        xr | j                  |j                  k(  S r]   )r^   r1  r   )rg   others     r*   __eq__z
Job.__eq__  s%    %0HTWW5HHr)   c                 ,    t        | j                        S r]   )hashr   r   s    r*   __hash__zJob.__hash__  s    DGG}r)   c                 b    | j                   t        t                     | _         | j                   S )zThe job ID for this job instance. Generates an ID lazily the
        first time the ID is requested.

        Returns:
            job_id (str): The Job ID
        )r   r_   r   r   s    r*   get_idz
Job.get_id  s$     8857|DHxxr)   r  c                     t        |t              s#t        dj                  t	        |                  d|v rt        d      || _        y)zkSets a job ID for the given job

        Args:
            value (str): The value to set as Job ID
        zid must be a string, not {0}rR   zid must not contain ":"N)r^   r_   r   r   typerd   r   r  s     r*   r   z
Job.set_id  sC     %%:AA$u+NOO%<677r)   	timestampxxc                     || _         ||n| j                  }|j                  | j                  dt	        | j                                y)a  Sets the heartbeat for a job.
        It will set a hash in Redis with the `last_heartbeat` key and datetime value.
        If a Redis' pipeline is passed, it will use that, else, it will use the job's own connection.

        Args:
            timestamp (datetime): The timestamp to use
            ttl (int): The time to live
            pipeline (Optional[Pipeline], optional): Can receive a Redis' pipeline to use. Defaults to None.
            xx (bool, optional): Only sets the key if already exists. Defaults to False.
        Nr   )r   rm   r   r   r;   )rg   r?  r   r   r@  rm   s         r*   	heartbeatzJob.heartbeat  s<     (!)!5X4??
"2Id>Q>Q4RSr)   c                 >    | j                   |z   j                  d      S )zThe Redis key that is used to store job hash under.

        Args:
            job_id (str): The Job ID

        Returns:
            redis_job_key (bytes): The Redis fully qualified key for the job
        utf-8)redis_job_namespace_prefixencoder   rl   s     r*   r!  zJob.key_for  s      ..7??HHr)   c                 :    dj                  | j                  |      S )zThe Redis key that is used to store job dependents hash under.

        Args:
            job_id (str): The "parent" job id

        Returns:
            dependents_key (str): The dependents key
        z{0}{1}:dependents)r   rE  rG  s     r*   dependents_key_forzJob.dependents_key_for  s     #))#*H*H&QQr)   c                 8    | j                  | j                        S )z3The Redis key that is used to store job hash under.)r!  r   r   s    r*   r   zJob.key  s     ||DGG$$r)   c                 8    | j                  | j                        S )z>The Redis key that is used to store job dependents hash under.)rI  r   r   s    r*   r   zJob.dependents_key  s     &&tww//r)   c                 N    dj                  | j                  | j                        S )Nz{0}:{1}:dependencies)r   rE  r   r   s    r*   dependencies_keyzJob.dependencies_key  s    %,,T-L-LdggVVr)   watchc                 J   ||n| j                   }|rB| j                  r6 |j                  | j                  D cg c]  }| j                  |       c}  | j	                  | j                  | j                   | j
                        }|D cg c]  }|s|	 }}|S c c}w c c}w )a  Fetch all of a job's dependencies. If a pipeline is supplied, and
        watch is true, then set WATCH on all the keys of all dependencies.

        Returned jobs will use self's connection, not the pipeline supplied.

        If a job has been deleted from redis, it is not returned.

        Args:
            watch (bool, optional): Wether to WATCH the keys. Defaults to False.
            pipeline (Optional[Pipeline]): The Redis' pipeline to use. Defaults to None.

        Returns:
            jobs (list[Job]): A list of Jobs
        rp   )rm   r   rN  r!  r/  rq   )rg   rN  r   rm   dependency_iddependencies_listra   rW   s           r*   fetch_dependencieszJob.fetch_dependencies  s     "*!5X4??
T))JPTPdPde}t||M:ef OO  T__ , 
  18C88 f
 9s   BB B c                 R   t        j                  dt               ddlm} | j
                  rp| j                  s| j                         | _        | j                  rC| j                  j                  |j                  j                  k(  r| j                  j                  S | j                  S )zf
        Get the latest result and returns `exc_info` only if the latest result is a failure.
        z<job.exc_info is deprecated, use job.latest_result() instead.r   r!   )rw   rx   ry   r   r"   supports_redis_streamsr   latest_resultr>  r   rI   
exc_stringr   rg   r"   s     r*   exc_infozJob.exc_info5  s|    
 	TVhi#&&&&&*&8&8&:#""t':':'?'?6;;CUCU'U**555~~r)   c                    ddl m} |rd| _        | j                  sm| j                  | j                  S | j
                  j                  | j                  d      }|,| j                  j                  |      | _        | j                  S y| j                  s| j                         | _        | j                  rC| j                  j                  |j                  j                  k(  r| j                  j                  S y)a  Returns the return value of the latest execution, if it was successful.

        Args:
            refresh (bool, optional): Whether to refresh the current status. Defaults to False.

        Returns:
            result (Optional[Any]): The job return value.
        r   r!   Nresult)r   r"   r   rT  r   rm   r   r   rq   r   rU  r>  r   
SUCCESSFULreturn_value)rg   r   r"   rvs       r*   r\  zJob.return_valueG  s     	$"&D**||'||#%%dhh9B~#44R8||#"""&"4"4"6D4#6#6#;#;v{{?U?U#U&&333r)   c                    t        j                  dt               ddlm} | j
                  rp| j                  s| j                         | _        | j                  rC| j                  j                  |j                  j                  k(  r| j                  j                  S | j                  H| j                  j                  | j                  d      }| | j                   j#                  |      | _        | j                  S )a  Returns the return value of the job.

        Initially, right after enqueueing a job, the return value will be
        None.  But when the job has been executed, and had a return value or
        exception, this will return that value or exception.

        Note that, when the job has no return value (i.e. returns None), the
        ReadOnlyJob object is useless, as the result won't be written back to
        Redis.

        Also note that you cannot draw the conclusion that a job has _not_
        been executed when its return value is None, since return values
        written back to Redis will expire after a given amount of time (500
        seconds by default).
        z7job.result is deprecated, use job.return_value instead.r   r!   rZ  )rw   rx   ry   r   r"   rT  r   rU  r>  r   r[  r\  r   rm   r   r   rq   r   )rg   r"   r]  s      r*   rZ  z
Job.resulth  s    $ 	OQcd#&&&&&*&8&8&:#""t':':'?'?6;;CYCY'Y**777 <<%%dhh9B~#44R8||r)   r"   c                 J    ddl m}  |j                  | | j                        S )zxReturns all Result objects

        Returns:
            all_results (List[Result]): A list of 'Result' objects
        r   r!   )rq   )r   r"   rc   rq   rW  s     r*   r   zJob.results  s     	$vzz$4??;;r)   c                 L    ddl m}  |j                  | | j                  |      S )zGet the latest job result.

        Args:
            timeout (int, optional): Number of seconds to block waiting for a result. Defaults to 0 (no blocking).

        Returns:
            result (Result): The Result object
        r   r!   )rq   r   )r   r"   fetch_latestrq   )rg   r   r"   s      r*   rU  zJob.latest_result  s"     	$"v""4DOOWUUr)   c                    t        |      }	 |d   }	 t	        j
                  |      | _        t        |j                  d            | _
        |j                  d      rt        |d         nd| _        |j                  d      r|d   j                         nd| _        |j                  d      rt        |d         nd| _        t        |j                  d	            | _        t        |j                  d
            | _        t        |j                  d            | _        t        |j                  d            | _        |j                  d      rt        |d         nd| _        |j                  d      }|r!	 | j*                  j-                  |      | _        |j                  d      rt5        |j                  d            nd| _        |j                  d      rt9        |d         nd| _        |j                  d      rt9        |d         nd| _        |j                  d      rt?        t        |d               nd| _         |j                  d      r|d   j                         | _!        d|v rt9        |d         | _"        |j                  d      r|d   j                         | _#        d|v rt9        |d         | _$        |j                  d      r|d   j                         | _%        d|v rt9        |d         | _&        |j                  d      }|j                  d      }|r#tO        j,                  |j                               n|r|j                         gng | _(        |j                  d      }|rtS        t9        |            nd| _*        d|v rtS        t9        |d               nd| _+        |j                  d      rt9        |d         nd| _,        	 |j                  d      r| j*                  j-                  |d         ni | _-        |j                  d       rt9        |d          nd| _.        |j                  d!      rt9        |d!         nd| _/        |j                  d"      r+tO        j,                  |d"   j                               | _0        |j                  d#      }|r%	 t        t	        j
                  |            | _1        yy# t        $ r t        dj                  |            w xY w# t        j                  $ r || _        Y w xY w# t0        $ r t2        | _        Y w xY w# t0        $ r d|j                  di       i| _-        Y Iw xY w# t        j                  $ r t        |      | _1        Y yw xY w)$zOverwrite properties with the provided values stored in Redis.

        Args:
            raw_data (_type_): The raw data to load the job data from

        Raises:
            NoSuchJobError: If there way an error getting the job data
        r  zUnexpected job format: {0}r   r   r   r   Nr   r   r   r   r   r   rZ  r   r   r   r   success_callback_namer  failure_callback_namer  stopped_callback_namer  dependency_idsrP  r   rZ   r   r   unserializedr   r   r   rX  )2r3   KeyErrorr-   r   zlib
decompressr  errorr:   getr   r2   r   decoder   r   r   r   r   r   r   rq   r   r   r  r   r9   r   intr   r   r=   r   r   r   r   r   r   r   jsonr   rj   r   rZ   r   r   r   r   r   r   )rg   raw_dataobjrZ  dep_idsdep_idallow_failuresraw_exc_infos           r*   r,  zJob.restore  s     )	K6{H	!1DI
 &cggl&;<030Agc(m,r:=''-:P3}-446VZ:=''-:P73}#56VZ&sww}'=>%cggl&;<#CGGJ$78)#''2B*CD47GGJ4GJ0T"C#44V< =@GGI<N}SWWY%78TX47GGL4I#c,/0t69ggm6L3s=12RV<?GGH<MyX!78SW77*+*-.E*F*M*M*OD'%,-05O1P-QD*77*+*-.E*F*M*M*OD'%,-05O1P-QD*77*+*-.E*F*M*M*OD'%,-05O1P-QD*''*+)?Ftzz'..*:;agV]]_L]mo!<=FTc..A)BZ^&FX\_F_S-?)@%A Bei&)ggen3s5z?$	>>Aggfo--c&k:SUDI CF''J]B^S)<%=!>dh8;8OCN 34UY77$%#'::c2C.D.K.K.M#ND wwz*7!()F!G C  	K !=!D!DS!IJJ	K
 zz 	! DI	!"  CBCD  	>')<=DI	> :: 7!(!67sR   S S< 9 T 6T8 0#U! $S9<TTT54T58"UU!#VVc                     | j                   j                  | j                        }|s$t        dj	                  | j                              | j                  |       y)zOverwrite the current instance's properties with the values in the
        corresponding Redis key.

        Will raise a NoSuchJobError if no corresponding Redis key exists.
        zNo such job: {0}N)rm   r(  r   r-   r   r,  )rg   r  s     r*   r   zJob.refresh  sF     &&txx0 !3!:!:488!DEETr)   include_metainclude_resultc                    t        | j                  xs
 t                     t        j                  | j
                        | j                  r| j                  nd| j                  r| j                  nd| j                  r| j                  nd| j                  rt        | j                        nd| j                  rt        | j                        nd| j                  rt        | j                        nd| j                  xs d| j                  xs dd
}| j                  | j                  |d<   | j                  | j                  |d<   | j                   "t#        j$                  | j                         |d<   | j&                  r| j&                  |d<   | j(                  | j(                  |d<   | j*                  t        | j*                        |d<   | j,                  +|r)	 | j.                  j%                  | j,                        |d	<   | j0                  <|r:t        j                  t3        | j0                        j5                  d            |d<   | j6                  | j6                  |d<   | j8                  | j8                  |d<   | j:                  | j:                  |d<   | j<                  | j<                  |d<   | j>                  | j>                  |d<   | j@                  | j@                  |d<   | jB                  | jB                  |d<   | jD                  r4| jD                  d   |d<   t#        j$                  | jD                        |d<   | jF                  r*|r(| j.                  j%                  | jF                        |d<   | jH                  r| jH                  |d<   | jJ                  tM        | jJ                        |d<   | jN                  tM        | jN                        |d<   |S #  d
|d	<   Y xY w)a  Returns a serialization of the current job instance

        You can exclude serializing the `meta` dictionary by setting
        `include_meta=False`.

        Args:
            include_meta (bool, optional): Whether to include the Job's metadata. Defaults to True.
            include_result (bool, optional): Whether to include the Job's result. Defaults to True.

        Returns:
            dict: The Job serialized as a dictionary
        r   )
r   r  rc  rd  re  r   r   r   r   r   r   r   r   r   r   r   rZ  zUnserializable return valuerD  rX  r   r  r  r  r   r   r   r   rP  rf  r   r   r   rZ   )(r;   r   r8   ri  compressr  r   r   r   r   r   r   r   r   r   r   r   ro  r  r   r   r   r   rq   r   r_   rF  r   r   r   r   r   r   r   r   r   r   r   rn  rZ   )rg   rw  rx  rq  s       r*   to_dictzJob.to_dict  s\    $DOO$<su=MM$)),DHD_D_T%@%@egDHD_D_T%@%@egDHD_D_T%@%@eg8<)DOO4R48MM	$--0r@D@S@Si(;(;<Y[++1r+
 !!-'+'='=C#$("&"3"3C+%)ZZ0D0D%EC!";; KKCM'!%!1!1C'!*4+;+;!<C<<#> $ 5 5dll CH >>%."mmC,?,F,Fw,OPC
O<<#!\\C	N))5.2.L.LC*+))5.2.L.LC*+))5.2.L.LC*+??& $C'!%!1!1C<<# LLCM#'#7#7#:C $(JJt/C/C$DC !99////		:CK88CJ))5/243Q3Q/RC+,  ,&)$*?*?&@C"#
C> =Hs   (O& &O0c                     | j                   }||n| j                  }| j                  ||      }|j                  ||       y)a  Dumps the current job instance to its corresponding Redis key.

        Exclude saving the `meta` dictionary by setting
        `include_meta=False`. This is useful to prevent clobbering
        user metadata without an expensive `refresh()` call first.

        Redis key persistence may be altered by `cleanup()` method.

        Args:
            pipeline (Optional[Pipeline], optional): The Redis' pipeline to use. Defaults to None.
            include_meta (bool, optional): Whether to include the job's metadata. Defaults to True.
            include_result (bool, optional): Whether to include the job's result. Defaults to True.
        N)rw  rx  mapping)r   rm   r{  r   )rg   r   rw  rx  r   rm   r~  s          r*   savezJob.saveR  s?     hh!)!5X4??
,,L,XW-r)   c                 (    | j                         dk\  S )z2Only supported by Redis server >= 5.0 is required.)   r   r   )get_redis_server_versionr   s    r*   rT  zJob.supports_redis_streamsf  s     ,,.);;r)   c                 f    | j                   t        | j                        | _         | j                   S )zReturn Redis server version of connection

        Returns:
            redis_server_version (Tuple[int, int, int]): The Redis version within a Tuple of integers, eg (5, 0, 9)
        )r   r6   rm   r   s    r*   r  zJob.get_redis_server_versionk  s-     $$,(3DOO(DD%(((r)   c                     | j                   j                  | j                        }| j                  j	                  | j
                  d|       y)zEStores job meta from the job instance to the corresponding Redis key.r   N)rq   r  r   rm   r   r   )rg   r   s     r*   	save_metazJob.save_metav  s4    $$TYY/TXXvt4r)   rn   c                    | j                   r(t        dj                  | j                                     ddlm} ddlm} |xs | j                  j                         }	 	  || j                  | j                  | j                  | j                        }| j                  t        j                  |       |r;||j!                  | j"                         |j%                  | || j&                  	       | j)                  |d
        || j                  | j                  | j                  | j                        }|j+                  | |       ||j-                          y# t.        $ r |Y  w xY w)a  Cancels the given job, which will prevent the job from ever being
        ran (or inspected).

        This method merely exists as a high-level API call to cancel jobs
        without worrying about the internals required to implement job
        cancellation.

        You can enqueue the jobs dependents optionally,
        Same pipelining behavior as Queue.enqueue_dependents on whether or not a pipeline is passed in.

        Args:
            pipeline (Optional[Pipeline], optional): The Redis' pipeline to use. Defaults to None.
            enqueue_dependents (bool, optional): Whether to enqueue dependents jobs. Defaults to False.

        Raises:
            InvalidJobOperation: If the job has already been cancelled.
        z&Cannot cancel already canceled job: {}r   r   CanceledJobRegistryT)r   rm   ru   rq   r   N)r   exclude_job_idr   remove_from_queue)ru   rq   )r   r,   r   r<  r   r    registryr  rm   r   r   r1  rq   r   r=   rN   rN  r   rn   r   _remove_from_registriesaddr)  r   )rg   r   rn   r    r  piper   r  s           r*   rs   z
Job.cancel{  sB   $ %&N&U&UVZVaVaVc&dee 154??335DNNgkgvgv 	 2 2TB%'

4#6#67((QUQXQX(Y,,dd,S.KKDNNW[WfWf TD1#LLN #
 s   !C>E   E0.E0at_frontc                 <    | j                   j                  | |      S )zRequeues job

        Args:
            at_front (bool, optional): Whether the job should be requeued at the front of the queue. Defaults to False.

        Returns:
            job (Job): The requeued Job instance
        )r  )failed_job_registryr~   )rg   r  s     r*   r~   zJob.requeue  s      ''//x/HHr)   c                 J    ddl m}  || j                  | j                        S )Nr   )r   )rm   )
executionsr   r   rm   )rg   r   s     r*   execution_registryzJob.execution_registry  s    1 T__EEr)   r   c                 6    | j                   j                         S r]   )r  get_executionsr   s    r*   r  zJob.get_executions  s    &&5577r)   r  c                    ddl m} |rBddlm}  || j                  | j
                  | j                        }|j                  | |       | j                  rNddl m	}  || j                  | j
                  | j                  | j                        }|j                  | |       y | j                  rNddl m}  || j                  | j
                  | j                  | j                        }|j                  | |       y | j                  radd	l m}	  |	| j                  | j
                  | j                  | j                        }|j                  | |       |j                  | |       y | j                   rNdd
l m}
  |
| j                  | j
                  | j                  | j                        }|j                  | |       y | j$                  s| j&                  r| j(                  j                  | |       y | j*                  rNddl m}  || j                  | j
                  | j                  | j                        }|j                  | |       y y )Nr   )BaseRegistryr   )r   rm   rq   r  FinishedJobRegistryrm   ru   rq   DeferredJobRegistryStartedJobRegistry)ScheduledJobRegistryr  )r  r  r   r    r   rm   rq   remover   r  r1  r   r  r   r  remove_executionsr   r  r   r   r  r   r  )rg   r   r  r  r    r   r  r  r  r  r  r  s               r*   r  zJob._remove_from_registries  s   *$4;;4??t_AHHTHH-5*4>>^b^m^mH OOD8O45*4>>^b^m^mH OOD8O4__4 *4>>^b^m^mH &&th&?OOD8O46+4>>^b^m^mH OOD8O4^^t$$++D8+D5*4>>^b^m^mH OOD8O4 r)   delete_dependentsc                    ||n| j                   }| j                  ||       |r| j                  |       | j                  j	                  | |       | j
                  rIddlm} |j                  | j
                  | j                         }|j                  | j                  |       |j	                  | j                  | j                  | j                         y)a  Cancels the job and deletes the job hash from Redis. Jobs depending
        on this job can optionally be deleted as well.

        Args:
            pipeline (Optional[Pipeline], optional): Redis' piepline. Defaults to None.
            remove_from_queue (bool, optional): Whether the job should be removed from the queue. Defaults to True.
            delete_dependents (bool, optional): Whether job dependents should also be deleted. Defaults to False.
        Nr  r  )ra   r   r   )Group)rm   r  r  r  deleter   groupr  rr   
delete_jobr   r   r   rM  )rg   r   r  r  rm   r  r  s          r*   r  z
Job.delete  s     "*!5X4??
$$hJ[$\""H"5&&4*&E==$KKt?ETWWx8$((D$7$79N9NOr)   c                    ||n| j                   }| j                  D ]B  }	 t        j                  || j                   | j                        }|j                  |d       D |j                  | j                         y# t        $ r Y lw xY w)zDelete jobs depending on this job.

        Args:
            pipeline (Optional[Pipeline], optional): Redis' piepline. Defaults to None.
        Nrp   Fr  )rm   r   rX   rr   rq   r  r-   r   )rg   r   rm   dependent_idra   s        r*   r  zJob.delete_dependents  s     "*!5X4??
 .. 	LiiUYUdUdie

H
F	 	$--. " s   ?A>>	B
	B
c                 $   | j                   j                  | j                         t        j	                  |        	 | j                         | _        | t        j                         u sJ | j                  S # | t        j                         u sJ w xY w)zThe main execution method. Invokes the job function with the job arguments.
        This is the method that actually performs the job - it's what its called by the worker.

        Returns:
            result (Any): The job result
        )rm   persistr   rz   push_executer   popr   s    r*   performzJob.perform)  sp     	)	,==?DL:>>++++|| :>>++++s   A5 5Br   c                 $   || _         t               | _        | j                  | _        t        j
                  | _        t        | j                        | j                  t        | j                        |d}|j                  | j                  |       y)a#  Prepares the job for execution, setting the worker name,
        heartbeat information, status and other metadata before execution begins.

        Args:
            worker_name (str): The worker that will perform the job
            pipeline (Pipeline): The Redis' piipeline to use
        )r   r   r   r   r}  N)
r   r8   r   r   r=   rJ   r   r;   r   r   )rg   r   r   r~  s       r*   prepare_for_executionzJob.prepare_for_execution8  sq     '!e-- (('(;(;<ll#DOO4&	
 	dhh0r)   c                      | j                   | j                  i | j                  }t        j                  |      r't        j
                         }|j                  |      }|S |S )au  Actually runs the function with it's *args and **kwargs.
        It will use the `func` property, which was already resolved and ready to run at this point.
        If the function is a coroutine (it's an async function/method), then the `result`
        will have to be awaited within an event loop.

        Returns:
            result (Any): The function result
        )r   r   r   asyncioiscoroutinenew_event_looprun_until_complete)rg   rZ  loopcoro_results       r*   r  zJob._executeL  sX     DII55v&))+D11&9Kr)   default_ttlc                 6    | j                   |S | j                   S )aR  Returns ttl for a job that determines how long a job will be
        persisted. In the future, this method will also be responsible
        for determining ttl for repeated jobs.

        Args:
            default_ttl (Optional[int]): The default time to live for the job

        Returns:
            ttl (int): The time to live
        )r   rg   r  s     r*   get_ttlzJob.get_ttl\  s     #hh.{<DHH<r)   c                 6    | j                   |S | j                   S )ap  Returns ttl for a job that determines how long a jobs result will
        be persisted. In the future, this method will also be responsible
        for determining ttl for repeated jobs.

        Args:
            default_ttl (Optional[int]): The default time to live for the job result

        Returns:
            ttl (int): The time to live for the result
        )r   r  s     r*   get_result_ttlzJob.get_result_ttli  s     #oo5{J4??Jr)   c                 `    t        | j                  | j                  | j                  d      }|S )zReturns a string representation of the call, formatted as a regular
        Python function invocation statement.

        Returns:
            call_repr (str): The string representation
        K   )
max_length)r5   r   r   r   )rg   	call_reprs     r*   r5   zJob.get_call_stringw  s'     $DNNDIIt{{WYZ	r)   c                    |dk(  r| j                  ||       y|sy|dkD  re||n| j                  }|j                  | j                  |       |j                  | j                  |       |j                  | j
                  |       yy)a  Prepare job for eventual deletion (if needed).
        This method is usually called after successful execution.
        How long we persist the job and its result depends on the value of ttl:
        - If ttl is 0, cleanup the job immediately.
        - If it's a positive number, set the job to expire in X seconds.
        - If ttl is negative, don't set an expiry to it (persist forever)

        Args:
            ttl (Optional[int], optional): Time to live. Defaults to None.
            pipeline (Optional[Pipeline], optional): Redis' pipeline. Defaults to None.
            remove_from_queue (bool, optional): Whether the job should be removed from the queue. Defaults to True.
        r   r  N)r  rm   expirer   r   rM  )rg   r   r   r  rm   s        r*   cleanupzJob.cleanup  s~     !8KK=NKO1W%-%9tJdhh,d1137d33S9	 r)   c                 v    ddl m}  || j                  | j                  | j                  | j
                        S )Nr   r  r  )r  r  r   rm   r1  rq   )rg   r  s     r*   started_job_registryzJob.started_job_registry  s.    0!KKDOOt~~Z^ZiZi
 	
r)   c                 v    ddl m}  || j                  | j                  | j                  | j
                        S )Nr   )FailedJobRegistryr  )r  r  r   rm   r1  rq   )rg   r  s     r*   r  zJob.failed_job_registry  s.    / KKDOOt~~Z^ZiZi
 	
r)   c                 v    ddl m}  || j                  | j                  | j                  | j
                        S )Nr   r  r  )r  r  r   rm   r1  rq   )rg   r  s     r*   finished_job_registryzJob.finished_job_registry  s.    1"KKDOOt~~Z^ZiZi
 	
r)   death_penalty_classrZ  c                    | j                   syt        j                  d| j                          || j                  t
        | j                        5  | j                  | | j                  |       ddd       y# 1 sw Y   yxY w)zExecutes success_callback for a job.
        with timeout .

        Args:
            death_penalty_class (Type[BaseDeathPenalty]): The penalty class to use for timeout
            result (Any): The job's result.
        Nz Running success callbacks for %srl   )r   loggerdebugr   r  r   rm   )rg   r  rZ  s      r*   execute_success_callbackzJob.execute_success_callback  sl     $$7A !>!>@S\`\c\cd 	A!!$@	A 	A 	As   A88Bc                 h   | j                   syt        j                  d| j                         	  || j                  t
        | j                        5   | j                   | | j                  g|  ddd       y# 1 sw Y   yxY w# t        $ r" t        j                  d| j                          w xY w)z/Executes failure_callback with possible timeoutNz Running failure callbacks for %sr  z.Job %s: error while executing failure callback)	r  r  r  r   r  r   rm   r  	exception)rg   r  rX  s      r*   execute_failure_callbackzJob.execute_failure_callback  s    $$7A	$T%B%BDW`d`g`gh H%%%dDOOGhGH H H 	MtwwW	s)   #B A:1B :B?B B +B1c                 J   t         j                  d| j                         	  || j                  t        | j                        5  | j                  | | j                         ddd       y# 1 sw Y   yxY w# t        $ r" t         j                  d| j                          w xY w)z/Executes stopped_callback with possible timeoutz Running stopped callbacks for %sr  Nz.Job %s: error while executing stopped callback)	r  r  r   r  r   r
  rm   r  r  )rg   r  s     r*   execute_stopped_callbackzJob.execute_stopped_callback  s    7A	$T%B%BDW`d`g`gh =%%dDOO<= = = 	MtwwW	s)   #A7 A+"A7 +A40A7 4A7 7+B"c                 `   | j                  t        j                  |       | j                   }| j	                  |d|       | j                  r;ddlm}  |j                  | |j                  j                  | j                  ||       |dk7  r | j                  }|j                  | ||       yy)	z0Saves and cleanup job after successful executionr  F)r   rw  rx  r   r!   )r\  r   r   r   N)r   r=   rH   rT  r  r   r"   r   r   r[  r   r  r  )rg   r   r   rx  r"   r  s         r*   _handle_successzJob._handle_success  s     		**X> "888		8%	W &&'FMM$ 6 6T\\Waltu?$($>$>!!%%dJA r)   rV  c                     | j                   }| j                   }|j                  | | j                  |||       | j                  r'ddlm}  |j                  | | j                  ||       y y )N)r   rV  r   _save_exc_to_jobr   r!   )rV  r   )r  rT  r  r   r   r"   create_failure)rg   rV  r   r  r  r"   s         r*   _handle_failurezJob._handle_failure  sw    "66  $:::  !- 	  	
 &&'!F!!$(8(8ZZbc 'r)   c                     | j                   r%ddlm}  |j                  | | j                  |       | j
                  sdn| j
                  dz   | _        |j                  | |       y )Nr   r!   r  )rT  r   r"   create_retriedr   r   _enqueue_job)rg   r   r   r"   s       r*   _handle_retry_resultzJob._handle_retry_result  sY    &&'!F!!$(8(88L*.*@*@dF\F\_`F`4(3r)   c                     | j                   yt        | j                         }| j                  sJ t        || j                  z
  d      }| j                   |   S )zReturns the desired retry interval.
        If number of retries is bigger than length of intervals, the first
        value in the list will be used multiple times.

        Returns:
            retry_interval (int): The desired retry interval
        r   )r   re   r   max)rg   number_of_intervalsindexs      r*   get_retry_intervalzJob.get_retry_interval  s\     '!$"6"67    '$*;*;;Q?##E**r)   c                 @    | j                   d uxr | j                   dkD  S )Nr   )r   r   s    r*   should_retryzJob.should_retry  s#    !!-G$2C2Ca2GHr)   c                    | j                         }| j                  sJ | j                  dz
  | _        |rt        j                  t        j
                        t        |      z   }| j                  t        j                         |j                  | ||       t        j                  d| j                  || j                         y|j                  | |       t        j                  d       y)a  Requeue or schedule this job for execution.
        If the the `retry_interval` was set on the job itself,
        it will calculate a scheduled time for the job to run, and instead
        of just regularly `enqueing` the job, it will `schedule` it.

        Args:
            queue (Queue): The queue to retry the job on
            pipeline (Pipeline): The Redis' pipeline to use
        r   )secondsr  z/Job %s: scheduled for retry at %s, %s remainingz(Job %s: enqueued for retry, %s remainingN)r  r   r   r8   r   utcr   r   r=   rL   schedule_jobr  infor   r  )rg   r   r   retry_intervalscheduled_datetimes        r*   retryz	Job.retry  s     002     --1!)hll!;iP^>_!_OOI//0t%7(KKKA477L^`d`q`q th7KKBCr)   c                    ddl m}  || j                  | j                  | j                  | j
                        }|j                  | || j                         ||n| j                  }| j                  D ]K  }| j                  |      }|j                  || j                         |j                  | j                  |       M y)a&  Jobs may have dependencies. Jobs are enqueued only if the jobs they
        depend on are successfully performed. We record this relation as
        a reverse dependency (a Redis set), with a key that looks something
        like:
        ..codeblock:python::

            rq:job:job_id:dependents = {'job_id_1', 'job_id_2'}

        This method adds the job in its dependencies' dependents sets,
        and adds the job to DeferredJobRegistry.

        Args:
            pipeline (Optional[Pipeline]): The Redis' pipeline. Defaults to None
        r   r  r  )r   r   N)r  r  r   rm   r1  rq   r  r   r   rI  saddr   rM  )rg   r   r  r  rm   rP  r   s          r*   register_dependencyzJob.register_dependency.  s     	2&KKDOOt~~Z^ZiZi
 	TH$((;!)!5X4??
!11 	BM!44]CNOONDGG4OOD11=A	Br)   c                     | j                   j                  | j                        }|D cg c]%  }t        j	                  |j                               ' c}S c c}w r]   )rm   r   rM  rX   r!  rm  )rg   rf   r   s      r*   rf  zJob.dependency_idsK  s?    //0E0EF5ABcCJJL)BBBs   *A
parent_jobr  c                   
 ||n| j                   }|6 |j                  | j                  D cg c]  }| j                  |       c}  |j	                  | j
                        D ch c]  }|j                          }}|r$|j                  |       |r|j                  |k(  rd}|rj|j                  |j                         |j                         t        j                  k(  ry|j                  t        j                  k(  r| j                  sy|sy|j                         5 }|D ]#  }|j!                  | j                  |      d       % |j#                         }	ddd       t        j$                  g
| j                  r
j'                  t        j                         t)        
fd	D              S c c}w c c}w # 1 sw Y   cxY w)ae  Returns a boolean indicating if all of this job's dependencies are `FINISHED`

        If a pipeline is passed, all dependencies are WATCHed.

        `parent_job` allows us to directly pass parent_job for the status check.
        This is useful when enqueueing the dependents of a _successful_ job -- that status of
        `FINISHED` may not be yet set in redis, but said job is indeed _done_ and this
        method is _called_ in the _stack_ of its dependents are being enqueued.

        Args:
            parent_job (Optional[Job], optional): The parent Job. Defaults to None.
            pipeline (Optional[Pipeline], optional): The Redis' pipeline. Defaults to None.
            exclude_job_id (Optional[str], optional): Whether to exclude the job id.. Defaults to None.

        Returns:
            are_met (bool): Whether the dependencies were met.
        NFTr   c              3   H   K   | ]  }|s|j                         v   y wr]   )rm  )r`   r   allowed_statusess     r*   rb   z+Job.dependencies_are_met.<locals>.<genexpr>  s      e6^d6==?&66es   "")rm   rN  r   r!  r   rM  rm  discardr   r   r=   rN   r   rI   r   r   r   r)  rH   r+  rc   )rg   r  r   r  rm   rP  r   dependencies_idsr   dependencies_statusesr  s             @r*   dependencies_are_metzJob.dependencies_are_metP  s   . "*!5X4??
JPTPdPde}t||M:ef4>4G4GH]H]4^_SCJJL__$$^4jmm~=!
 $$Z]]3$$&)*<*<<##y'7'77@^@^ $  " 	7h' ;dll3/:; %-$4$4$6!		7 &../))##I$4$45eEZeeeC f_*	7 	7s   F3'F8"9F==G)NNN)NNNNNNNNNNr   NNNN)Tr]   NNNF)FN)Fr   )TT)NTT)rP   r   )NT)NTF)NNT)r   r    r   r   )vr%   r&   r'   rF   r   __annotations__rE  r_   ri   classmethodr0   r   r   r   r
   r   rn  r=   r1   r	   r   r   rj   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r
  r  r  r  setterr   r   r   r   r"  rr   r   r/  r2  r4  r7  r:  r<  r   r   rB  r   bytesr!  rI  r   r   rM  rR  rX  r\  rZ  r   rU  r,  r   r   r{  r  rT  r   r  r  rs   r~   r  r  r  r  r  r  r  r  r  r  r5   r  r  r  r  r   r   r  r  r  r  r  r  r  r  r  r  rf  r  r(   r)   r*   rX   rX      su
   R% !*358C= 35Xg=N 35j  .2+/(,$(!&*%)26!% )-%)"&#a& GKFJFJ+a#a uT5[)*a c3h(	a
 W%a SMa c]a #a c]a ./a #a SMa a tCH~&a c]a" 3-#a& U:xS/A#ABC'a( U:xS/A#ABC)a* U:xS/A#ABC+a, 
-a aFhsm $ (92E &	: 	:hz6J 	:VZ 	:   7T 7 7 54 5 5 54 5 5 6D 6 6 7T 7 7 7T 7 7 8d 8 8 6D 6 6 + + 
HUO 
 
 QtCy Q Q
 0 0 & & .# . . & & .# . . & & .# . .
0  $ 
[[# #  
 ! !  
 __! ! eD%K(  
 
[[! ! S#X  
 ]]! !  C  W       s (9 V[    # G Y]^fgl^mYn  Bk[I	 	C D T8 T# T*AU Tbf T  
&&	!B	IS 	IU 	I 	I 	R 	R 	R 	R % % 0 0 W W @T `dej`k 4 (3-  "D Xc] B " " "H<h <VS V(1C VR73 R7j	LD L LQU L\.Xj1 . .ei .( < < <	)%S#*> 	)5
5x
3 5PT 5n	I 	I 	I F F
8[ 1 8650D 65`d 65r puP ,PHLPhlP4/(:*> /" 1 1
 1(#  =8C= =HSM =K# K# K# :8C= :8J;O :ko :. 
 
 
 
 
 
ADAQ<R A\_ ADAQ<R DAQ<R B# B B*d# d d"4+C + Id I ID0BHZ,@ B: CU C C '+)-(,	;fUO;f :&;f !	;f
 
;fr)   c                   j     e Zd Zd	dedeeee   f   f fdZededeeee   df   defd       Z	 xZ
S )
Retryr  intervalc                 
   t         |           |dk  rt        d      t        |t              r|dk  rt        d      |g}n2t        |t
              r"|D ]  }|dk  s	t        d       t        |      }|| _        | _        y)a  The main object to defined Retry logics for jobs.

        Args:
            max (int): The max number of times a job should be retried
            interval (Union[int, List[int]], optional): The interval between retries.
                Can be a positive number (int) or a list of ints. Defaults to 0 (meaning no interval between retries).

        Raises:
            ValueError: If the `max` argument is lower than 1
            ValueError: If the interval param is negative or the list contains negative numbers
        r   z(max: please enter a value greater than 0r   z*interval: negative numbers are not allowedN)	superri   rd   r^   rn  r   r   r  	intervals)rg   r  r	  r  r.  r1  s        r*   ri   zRetry.__init__  s     	7GHHh$!| !MNN!
I(+ Sq5$%QRRS XI"r)   countr  NrP   c                 j    t        |t              r|S |syt        |      }t        |dz
  |      }||   S )a  Returns the appropriate retry interval based on retry count and intervals.
        If intervals is an integer, returns that value directly.
        If intervals is a list and retry count is bigger than length of intervals,
        the first value in the list will be used.

        Args:
            count (int): The current retry count
            intervals (Union[int, List[int]]): Either a single interval value or list of intervals to use

        Returns:
            retry_interval (int): The appropriate retry interval
        r   r   )r^   rn  re   min)r   r  r  r  r  s        r*   get_intervalzRetry.get_interval  sE     i%  ")n'!+U3r)   r  )r%   r&   r'   rn  r   r   ri   r  r   r  __classcell__)r1  s   @r*   r  r    s^    #C #5hsm1C+D #:    sDIt7K1L  QT    r)   r  c                   N    e Zd Zddeeedef   f   dee   fdZe	defd       Z
y)	r   Nr   .r   c                     t        |t              s5t        j                  |      s t        j                  |      st        d      || _        |rt        |      | _	        y t        | _	        y )Nz,Callback `func` must be a string or function)
r^   r_   r   r   r   rd   r   r9   r   r   )rg   r   r   s      r*   ri   zCallback.__init__  sO    $$W-?-?-EgN_N_`dNeKLL	18}W->Nr)   rP   c                     t        | j                  t              r| j                  S dj                  | j                  j                  | j                  j
                        S )Nr   )r^   r   r_   r   r&   r'   r   s    r*   r   zCallback.name  sA    dii%99		 4 4dii6L6LMMr)   r]   )r%   r&   r'   r   r_   r	   r   r   ri   r  r   r(   r)   r*   r   r     sM    OU3c(:#:; Ohsm O Nc N Nr)   r   r   r  r]   )Wr  r   ro  loggingrw   ri  r   r   r   enumr   typingr   r   r	   r
   r   r   r   r   r   r   r   uuidr   redisr   defaultsr   r   timeoutsr   r   	_typeshedr   r   redis.clientr   typing_extensionsr   r  r   r   r   r    r   r"   r$   
exceptionsr+   r,   r-   localr.   serializersr/   typesr0   r1   utilsr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   	getLoggerr  r_   r=   rT   rV   objectrk   r  rj   rt   r|   r   rX   rz   r  r   r(   r)   r*   <module>r&     s`         2 2  l l l l   K ;!%(8  R Q  + ;   
		8	$
T 
c c 1 16 "( )

rs 
r 
rVZ 
r 1 Xe_ `hin`o $  e uf ufp/ \
7  7 tN Nr)   