
    i                         d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	m
Z
mZmZ  ee          Zdddddded	ef         d
eegdf         dz  dededej        dz  deg ef         dz  dededdfdZdS )a  This module contains a network retry loop implementation.
Its specifically tailored to handling the Telegram API and its errors.

.. versionadded:: 21.11

Hint:
    It was originally part of the `Updater` class, but as part of #4657 it was extracted into its
    own module to be used by other parts of the library.

Warning:
    Contents of this module are intended to be used internally by the library and *not* by the
    user. Changes to this module are not considered breaking changes and may not be documented in
    the changelog.
    N)Callable	Coroutine)
get_logger)InvalidToken
RetryAfterTelegramErrorTimedOutF)	on_err_cb
stop_event
is_runningrepeat_on_success	action_cb.r
   descriptionintervalr   r   max_retriesr   returnc                    K   |rdk    rt          d          d| d|pd }ddt          dt          d	t          ffd
}	d fd}
t                              d           |}d} |            rO	  |
             d{V  |s#t                              d           	 |dz  }dS 	 |}n# t          $ r=}d}||j                                        z   }| d| d} |	||          r Y d}~nd}~wt          $ r}d}d| d} |	||          r Y d}~nsd}~wt          $ r t                              d            t          $ r>}|r ||            |	|          r |dk    rdnt          dd|z            }Y d}~nd}~ww xY w|dz  }n
# |dz  }w xY w|rt          j        |           d{V   |            MdS dS )a  Perform a loop calling `action_cb`, retrying after network errors.

    Stop condition for loop in case of ``max_retries < 0``:
        * `is_running()` evaluates :obj:`False`
        * `stop_event` is set.
        * calling `action_cb` succeeds and `repeat_on_success` is :obj:`False`.

    Additional stop condition for loop in case of `max_retries >= 0``:
        * a call to `action_cb` succeeds
        * or `max_retries` is reached.

    Args:
        action_cb (:term:`coroutine function`): Network oriented callback function to call.
        on_err_cb (:obj:`callable`): Optional. Callback to call when TelegramError is caught.
            Receives the exception object as a parameter.

            Hint:
                Only required if you want to handle the error in a special way. Logging about
                the error is already handled by the loop.

            Important:
                Must not raise exceptions! If it does, the loop will be aborted.
        description (:obj:`str`): Description text to use for logs and exception raised.
        interval (:obj:`float` | :obj:`int`): Interval to sleep between each call to
            `action_cb`.
        stop_event (:class:`asyncio.Event` | :obj:`None`): Event to wait on for stopping the
            loop. Setting the event will make the loop exit even if `action_cb` is currently
            running. Defaults to :obj:`None`.
        is_running (:obj:`callable`): Function to check if the loop should continue running.
            Must return a boolean value. Defaults to `lambda: True`.
        max_retries (:obj:`int`): Maximum number of retries before stopping the loop.

            * < 0: Retry indefinitely.
            * 0: No retries.
            * > 0: Number of retries.

        repeat_on_success (:obj:`bool`): Whether to repeat the action after a successful call.
            Defaults to :obj:`False`.

    Raises:
        ValueError: When passing `repeat_on_success=True` and `max_retries >= 0`. This case is
            currently not supported.

    r   z7Cannot use repeat_on_success=True with max_retries >= 0zNetwork Retry Loop (z):c                      dS )NT r       _/Users/shanyulin/my-agent/.venv/lib/python3.11/site-packages/telegram/ext/_utils/networkloop.py<lambda>z$network_retry_loop.<locals>.<lambda>h   s    $ r    current_retriesexception_infor   c                     |r d| n}dk     s| k     rt                               d||            dS t                               d||            dS )aL  Check if max retries reached and log accordingly.

        Args:
            current_retries: The current retry count.
            exception_info: Additional context about the exception (e.g., "Timed out: ...").

        Returns:
            bool: True if max retries reached (should abort), False otherwise (should retry).
         r   z(%s Failed run number %s of %s. Retrying.Fz(%s Failed run number %s of %s. Aborting.T)_LOGGERdebug	exception)r   r   prefix_with_info
log_prefixr   s      r   check_max_retries_and_logz5network_retry_loop.<locals>.check_max_retries_and_logj   s     @N]j;;>;;;S]??o;;MM: 	   56		
 	
 	
 tr   Nc                    K   s              d {V  d S t          j                               } t          j                                                  }t          j        | |ft           j                   d {V \  }}t	          j        t           j                  5  |D ]}|                                 	 d d d            n# 1 swxY w Y   ||v rt          	                    d           d S | 
                                 d S )N)return_whenz%s Cancelled)asynciocreate_taskwaitFIRST_COMPLETED
contextlibsuppressCancelledErrorcancelr   r   result)action_cb_task	stop_taskdonependingtaskr   r"   r   s        r   	do_actionz%network_retry_loop.<locals>.do_action   su      	)++F ,YY[[99'
(9(9::	%lY'W5L
 
 
 
 
 
 
 
 
g  !788 	 	  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 MM.*555F 	s   #C

CCz%s Startingz#%s Action succeeded. Stopping loop.   g      ?z	. Adding z seconds to the specified time.zTimed out: .z&%s Invalid token. Aborting retry loop.   g      ?)r   )r   N)
ValueErrorintstrboolr   r   r   _retry_aftertotal_secondsr	   r   r    r   minr&   sleep)r   r
   r   r   r   r   r   r   effective_is_runningr#   r4   cur_intervalretriesexc
slack_timer   toetelegram_excr"   s   `   ` `           @r   network_retry_looprG   ,   s>     n  T[A--RSSS7777J%7,, 3  UY       8               , MM-,,,LG


 
  ).%	)++$ CZPPPB qLGGGGB $LL=  	 	 	J%(8(F(F(H(HHL #YYjYYYN )(.AA      	 	 	L13111N )(.AA      	 	 	F
SSS 	S 	S 	S (	,'''((11  !- 1 111s2s\?Q7R7RLLLLLL	S qLGGGqLGGGGG 	.----------S 

 
  ). ). ). ). ).sT   9-B2 /F 2
F<3C4/F 4FDF 2F4FF FF F)__doc__r&   r*   collections.abcr   r   telegram._utils.loggingr   telegram.errorr   r   r   r	   __name__r   r:   floatEventr;   r9   rG   r   r   r   <module>rO      sS  &       / / / / / / / / . . . . . . L L L L L L L L L L L L
*X

 9= (,,0#\. \. \.Y'\. -.5\. 	\.
 \. $\. T"T)\. \. \. 
\. \. \. \. \. \.r   