-
Notifications
You must be signed in to change notification settings - Fork 834
/
handler.py
80 lines (69 loc) · 2.41 KB
/
handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""RetryHandler interface.
You can pass an array of handlers to customize retry logics in supported API clients.
"""
import time
from typing import Optional
from slack_sdk.http_retry.state import RetryState
from slack_sdk.http_retry.request import HttpRequest
from slack_sdk.http_retry.response import HttpResponse
from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator
from slack_sdk.http_retry.builtin_interval_calculators import (
BackoffRetryIntervalCalculator,
)
default_interval_calculator = BackoffRetryIntervalCalculator()
# Note that you cannot add aiohttp to this class as the external dependency is optional
class RetryHandler:
"""RetryHandler interface.
You can pass an array of handlers to customize retry logics in supported API clients.
"""
max_retry_count: int
interval_calculator: RetryIntervalCalculator
def __init__(
self,
max_retry_count: int = 1,
interval_calculator: RetryIntervalCalculator = default_interval_calculator,
):
"""RetryHandler interface.
Args:
max_retry_count: The maximum times to do retries
interval_calculator: Pass an interval calculator for customizing the logic
"""
self.max_retry_count = max_retry_count
self.interval_calculator = interval_calculator
def can_retry(
self,
*,
state: RetryState,
request: HttpRequest,
response: Optional[HttpResponse] = None,
error: Optional[Exception] = None,
) -> bool:
if state.current_attempt >= self.max_retry_count:
return False
return self._can_retry(
state=state,
request=request,
response=response,
error=error,
)
def _can_retry(
self,
*,
state: RetryState,
request: HttpRequest,
response: Optional[HttpResponse] = None,
error: Optional[Exception] = None,
) -> bool:
raise NotImplementedError()
def prepare_for_next_attempt(
self,
*,
state: RetryState,
request: HttpRequest,
response: Optional[HttpResponse] = None,
error: Optional[Exception] = None,
) -> None:
state.next_attempt_requested = True
duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt)
time.sleep(duration)
state.increment_current_attempt()