"""This module provides an implementation of an exponential backoff mechanism.Classes: BackoffPolicy: Policy class for the exponential backoff mechanism.Functions: exponential_backoff: Decorator function to apply exponential backoff retries to a function.Exceptions: MaxRetriesExceededError: Raised when the maximum number of retries is exceeded."""importfunctoolsimportrandomimporttimefromdataclassesimportdataclassfromvein.exceptionsimportMaxRetriesExceededError
[docs]@dataclassclassBackoffPolicy:""" Policy for the exponential backoff mechanism. Attributes: max_retries (int): Maximum number of retry attempts. base_delay (float): Initial delay between retries in seconds. max_delay (float): Maximum delay between retries in seconds. factor (float): Multiplicative factor for delay growth. jitter (bool): If True, adds a random jitter to the delay. """max_retries:intbase_delay:floatmax_delay:floatfactor:floatjitter:bool
[docs]defexponential_backoff(backoff_policy:BackoffPolicy):""" Decorator for exponential backoff retries. Args: backoff_policy (BackoffPolicy): Policy object containing: - max_retries (int): Maximum number of retry attempts. - base_delay (float): Initial delay between retries in seconds. - max_delay (float): Maximum delay between retries in seconds. - factor (float): Multiplicative factor for delay growth. - jitter (bool): If True, adds a random jitter to the delay. Returns: function: Wrapped function with retry mechanism. """defdecorator(func):@functools.wraps(func)defwrapper(*args,**kwargs):delay=backoff_policy.base_delaytotal_time_slept=0forattemptinrange(backoff_policy.max_retries):try:returnfunc(*args,**kwargs)exceptExceptionasexc:ifattempt==backoff_policy.max_retries-1:raiseMaxRetriesExceededError(backoff_policy,total_time_slept)fromexcsleep_time=delay*(backoff_policy.factor**attempt)ifbackoff_policy.jitter:sleep_time=min(sleep_time,backoff_policy.max_delay)*(0.5+random.random()/2)else:sleep_time=min(sleep_time,backoff_policy.max_delay)time.sleep(sleep_time)total_time_slept+=sleep_timereturnfunc(*args,**kwargs)returnwrapperreturndecorator