canonicalwebteam.store-api 6.7.0__py3-none-any.whl → 6.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of canonicalwebteam.store-api might be problematic. Click here for more details.

@@ -14,6 +14,46 @@ class StoreApiConnectionError(StoreApiError):
14
14
  pass
15
15
 
16
16
 
17
+ class StoreApiInternalError(StoreApiConnectionError):
18
+ """
19
+ Store API internal error
20
+ """
21
+
22
+ pass
23
+
24
+
25
+ class StoreApiNotImplementedError(StoreApiConnectionError):
26
+ """
27
+ Store API doesn't implement this method
28
+ """
29
+
30
+ pass
31
+
32
+
33
+ class StoreApiBadGatewayError(StoreApiConnectionError):
34
+ """
35
+ Got and invalid response from Store API
36
+ """
37
+
38
+ pass
39
+
40
+
41
+ class StoreApiServiceUnavailableError(StoreApiConnectionError):
42
+ """
43
+ Store API is not available
44
+ """
45
+
46
+ pass
47
+
48
+
49
+ class StoreApiGatewayTimeoutError(StoreApiConnectionError):
50
+ """
51
+ Request to Store API timed out
52
+ """
53
+
54
+ pass
55
+
56
+
17
57
  class StoreApiResourceNotFound(StoreApiError):
18
58
  """
19
59
  The requested resource is not found
@@ -0,0 +1,170 @@
1
+ from typing import Callable, Tuple, Type, TypeVar
2
+ from random import random
3
+ from sys import maxsize as MAX_INT
4
+ import functools
5
+
6
+
7
+ P = TypeVar("P")
8
+ R = TypeVar("R")
9
+
10
+
11
+ def retry(
12
+ func: Callable[P, R] = None,
13
+ *,
14
+ limit: int = MAX_INT,
15
+ delay_fn: Callable[[int], float] = (lambda x: 0.0),
16
+ sleep_fn: Callable[[float], None] = (lambda x: None),
17
+ callback_fn: Callable[[Exception], bool] = (lambda x: False),
18
+ logger_fn: Callable[[str], None] = (lambda x: None),
19
+ exceptions: Tuple[Type[Exception]] = (Exception),
20
+ ) -> Callable[P, R]:
21
+ """
22
+ Decorator that implements retry logic for `func` when any of the
23
+ Exceptions in `exceptions` happen.
24
+
25
+ Arguments:
26
+ func: function what will be retried
27
+
28
+ Keyword arguments:
29
+ limit: max number of retry attempts
30
+ exceptions: tuple containing the types of exceptions we can catch and
31
+ that trigger a retry
32
+ callback_fn: function that takes as argument an exception caught a during
33
+ the retry loop, it should return a bool indicating whether to abort
34
+ the loop or not; it will be called every time a member of `exceptions`
35
+ is caught
36
+ logger_fn: function that logs errors caught and not propagated during
37
+ the retry loop; it will be called every time a member of `exceptions`
38
+ is caught
39
+ delay_fn: function that takes the current attempt as an argument and
40
+ returns a float indicating the delay in seconds before calling `func`
41
+ again
42
+ sleep_fn: function that takes a float indicating a delay in seconds and
43
+ waits for this specified time before executing `func` again; it's
44
+ user's responsibility to make sure the sleep function is appropriate
45
+ for their usage (e.g. use an async sleep in and async environment)
46
+ """
47
+
48
+ if func is None:
49
+ # if the decorator is applied using parameters (e.g. @retry(limit=3)),
50
+ # `func` will be None, so we must first do a partial application on
51
+ # the decorator itself to actually wrap `func` correctly
52
+ return functools.partial(
53
+ retry,
54
+ limit=limit,
55
+ delay_fn=delay_fn,
56
+ sleep_fn=sleep_fn,
57
+ callback_fn=callback_fn,
58
+ logger_fn=logger_fn,
59
+ exceptions=exceptions,
60
+ )
61
+
62
+ if limit <= 0:
63
+ raise ValueError("The limit must be at least 1")
64
+
65
+ @functools.wraps(func)
66
+ def _retry(*args, **kwargs):
67
+ retry_attempts = 0
68
+ last_exception = None
69
+
70
+ while retry_attempts < limit:
71
+ if retry_attempts > 0:
72
+ # only sleep if we've already tried once
73
+ sleep_fn(delay_fn(retry_attempts))
74
+
75
+ try:
76
+ return func(*args, **kwargs)
77
+ except exceptions as e:
78
+ last_exception = e
79
+ retry_attempts += 1
80
+
81
+ if callback_fn(e):
82
+ # stop early if callback says so, raise `e` immediately
83
+ raise e
84
+
85
+ logger_fn(
86
+ f"@retry ({retry_attempts}/{limit}) `{func.__name__}`: {e}"
87
+ )
88
+
89
+ # if we made it here, it means we ran the loop and couldn't get a
90
+ # clean run, raise the last exception we caught and let the user
91
+ # deal with it
92
+ raise last_exception
93
+
94
+ return _retry
95
+
96
+
97
+ def delay_constant(delay: float):
98
+ """
99
+ Returns a function that always returns `delay`
100
+ """
101
+ if delay < 0:
102
+ raise ValueError("The delay must be at least 0")
103
+
104
+ def _delay_constant(_: int):
105
+ return delay
106
+
107
+ return _delay_constant
108
+
109
+
110
+ def delay_random(min: float, max: float):
111
+ """
112
+ Returns a function that picks a random delay between `min` and `max`
113
+ """
114
+ if min < 0:
115
+ raise ValueError("The minimum delay must be at least 0")
116
+ if max <= min:
117
+ raise ValueError("The maximum delay must be greater than the minimum")
118
+
119
+ def _delay_random(_: int):
120
+ return min + random() * (max - min)
121
+
122
+ return _delay_random
123
+
124
+
125
+ def delay_exponential(
126
+ delay_mult: float, exp_base: float, max_delay: float = float("inf")
127
+ ):
128
+ """
129
+ Returns a function that implements an exponential backoff with an upper
130
+ limit based on the number of attempts made `n`, according to the following
131
+ formula:
132
+ min(`max_delay`, `delay_mult` * `exp_base`^`n`)
133
+ """
134
+ if delay_mult <= 0:
135
+ raise ValueError("The delay multiplier must be greater than 0")
136
+ if exp_base <= 1:
137
+ raise ValueError("The exponential base must be greater than 1")
138
+ if max_delay <= 0:
139
+ raise ValueError("The maximum delay must be greater than 0")
140
+
141
+ def _delay_exponential(attempt: int):
142
+ return min(max_delay, delay_mult * (exp_base**attempt))
143
+
144
+ return _delay_exponential
145
+
146
+
147
+ """
148
+ Example usage:
149
+
150
+ @retry(
151
+ limit=5,
152
+ logger_fn=print,
153
+ exceptions=(TypeError),
154
+ sleep_fn=sleep,
155
+ delay_fn=delay_exponential(1, 2)
156
+ )
157
+ def test_fn(val: int):
158
+ return None + val # this will raise TypeError
159
+
160
+ try:
161
+ test_fn(2)
162
+ except TypeError as e:
163
+ print(e)
164
+
165
+ This will attempt to run `test_fn` 5 times, will catch TypeError 4 times and
166
+ then it will let the exception propagate after executing the function for the
167
+ last time. Each time, it will take an exponentially longer amount of time to
168
+ run, making the total execution time around 30s (plus some small random delay
169
+ caused by the OS).
170
+ """
@@ -1,12 +1,17 @@
1
1
  from canonicalwebteam.exceptions import (
2
+ PublisherAgreementNotSigned,
3
+ PublisherMacaroonRefreshRequired,
4
+ PublisherMissingUsername,
5
+ StoreApiBadGatewayError,
2
6
  StoreApiConnectionError,
7
+ StoreApiGatewayTimeoutError,
8
+ StoreApiInternalError,
9
+ StoreApiNotImplementedError,
3
10
  StoreApiResourceNotFound,
4
11
  StoreApiResponseDecodeError,
5
12
  StoreApiResponseError,
6
13
  StoreApiResponseErrorList,
7
- PublisherAgreementNotSigned,
8
- PublisherMacaroonRefreshRequired,
9
- PublisherMissingUsername,
14
+ StoreApiServiceUnavailableError,
10
15
  )
11
16
 
12
17
 
@@ -17,7 +22,22 @@ class Base:
17
22
  def process_response(self, response):
18
23
  # 5xx responses are not in JSON format
19
24
  if response.status_code >= 500:
20
- raise StoreApiConnectionError("Service Unavailable")
25
+ if response.status_code == 500:
26
+ raise StoreApiInternalError("Internal error upstream")
27
+ elif response.status_code == 501:
28
+ raise StoreApiNotImplementedError(
29
+ "Service doesn't implement this method"
30
+ )
31
+ elif response.status_code == 502:
32
+ raise StoreApiBadGatewayError("Invalid response from upstream")
33
+ elif response.status_code == 503:
34
+ raise StoreApiServiceUnavailableError("Service is unavailable")
35
+ elif response.status_code == 504:
36
+ raise StoreApiGatewayTimeoutError("Upstream request timed out")
37
+ else:
38
+ raise StoreApiConnectionError(
39
+ f"Service unavailable, code {response.status_code}"
40
+ )
21
41
 
22
42
  try:
23
43
  body = response.json()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: canonicalwebteam.store-api
3
- Version: 6.7.0
3
+ Version: 6.8.0
4
4
  Summary:
5
5
  License: LGPL-3.0
6
6
  Author: Canonical Web Team
@@ -0,0 +1,12 @@
1
+ canonicalwebteam/__init__.py,sha256=ED6jHcYiuYpr_0vjGz0zx2lrrmJT9sDJCzIljoDfmlM,65
2
+ canonicalwebteam/exceptions.py,sha256=Uf9HxtLH5fAXPdDm6H14tA8jUxKQAWUmWIovzHLtdRw,2134
3
+ canonicalwebteam/retry_utils.py,sha256=KcaWscyVbzhP4VNPWUnh-mlIKe5T09z4jdI1bJgtvfg,5422
4
+ canonicalwebteam/store_api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ canonicalwebteam/store_api/base.py,sha256=_kx3_hPQHJPUtdf3z4NXmcwHlswV1g1mw483fZXD5LM,3331
6
+ canonicalwebteam/store_api/dashboard.py,sha256=M5JLjTTahN-bfiVz9SuP6ahLjqEvOalwmNim6X5Ky6o,22796
7
+ canonicalwebteam/store_api/devicegw.py,sha256=YXmVXdHCZhukNHJq-eaFUCxa2VxqLT8qt19UrqgXGN0,9777
8
+ canonicalwebteam/store_api/publishergw.py,sha256=u2D2Y76xC8ms16XTZcUe_KmRdcyzqOV2g0aN9HYZBrQ,29702
9
+ canonicalwebteam_store_api-6.8.0.dist-info/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
10
+ canonicalwebteam_store_api-6.8.0.dist-info/METADATA,sha256=_u5GFZweT4nhOYTN9pSs0E3zLvJnFBgbtevUyjsByuQ,2253
11
+ canonicalwebteam_store_api-6.8.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
12
+ canonicalwebteam_store_api-6.8.0.dist-info/RECORD,,
@@ -1,11 +0,0 @@
1
- canonicalwebteam/__init__.py,sha256=ED6jHcYiuYpr_0vjGz0zx2lrrmJT9sDJCzIljoDfmlM,65
2
- canonicalwebteam/exceptions.py,sha256=A49LRhiEIfXNB2zC-zNcZEcdh0ugw6G7fBbXbs-BWxA,1517
3
- canonicalwebteam/store_api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- canonicalwebteam/store_api/base.py,sha256=DmfVcefWxGYNQxzYmaDVhmthTCg2vEwEnvczU9Bk5zE,2414
5
- canonicalwebteam/store_api/dashboard.py,sha256=M5JLjTTahN-bfiVz9SuP6ahLjqEvOalwmNim6X5Ky6o,22796
6
- canonicalwebteam/store_api/devicegw.py,sha256=YXmVXdHCZhukNHJq-eaFUCxa2VxqLT8qt19UrqgXGN0,9777
7
- canonicalwebteam/store_api/publishergw.py,sha256=u2D2Y76xC8ms16XTZcUe_KmRdcyzqOV2g0aN9HYZBrQ,29702
8
- canonicalwebteam_store_api-6.7.0.dist-info/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
9
- canonicalwebteam_store_api-6.7.0.dist-info/METADATA,sha256=PJgxFUHDwul_1i3n7LbmZrLHxPNMJB9GPGXDYBUUD_0,2253
10
- canonicalwebteam_store_api-6.7.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
11
- canonicalwebteam_store_api-6.7.0.dist-info/RECORD,,