forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase.py
249 lines (207 loc) · 8.16 KB
/
base.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
Base for Parameter providers
"""
import base64
import json
from abc import ABC, abstractmethod
from collections import namedtuple
from datetime import datetime, timedelta
from typing import Dict, Optional, Tuple, Union
from .exceptions import GetParameterError, TransformParameterError
DEFAULT_MAX_AGE_SECS = 5
ExpirableValue = namedtuple("ExpirableValue", ["value", "ttl"])
# These providers will be dynamically initialized on first use of the helper functions
DEFAULT_PROVIDERS = {}
TRANSFORM_METHOD_JSON = "json"
TRANSFORM_METHOD_BINARY = "binary"
SUPPORTED_TRANSFORM_METHODS = [TRANSFORM_METHOD_JSON, TRANSFORM_METHOD_BINARY]
class BaseProvider(ABC):
"""
Abstract Base Class for Parameter providers
"""
store = None
def __init__(self):
"""
Initialize the base provider
"""
self.store = {}
def _has_not_expired(self, key: Tuple[str, Optional[str]]) -> bool:
return key in self.store and self.store[key].ttl >= datetime.now()
def get(
self,
name: str,
max_age: int = DEFAULT_MAX_AGE_SECS,
transform: Optional[str] = None,
force_fetch: bool = False,
**sdk_options,
) -> Union[str, list, dict, bytes]:
"""
Retrieve a parameter value or return the cached value
Parameters
----------
name: str
Parameter name
max_age: int
Maximum age of the cached value
transform: str
Optional transformation of the parameter value. Supported values
are "json" for JSON strings and "binary" for base 64 encoded
values.
force_fetch: bool, optional
Force update even before a cached item has expired, defaults to False
sdk_options: dict, optional
Arguments that will be passed directly to the underlying API call
Raises
------
GetParameterError
When the parameter provider fails to retrieve a parameter value for
a given name.
TransformParameterError
When the parameter provider fails to transform a parameter value.
"""
# If there are multiple calls to the same parameter but in a different
# transform, they will be stored multiple times. This allows us to
# optimize by transforming the data only once per retrieval, thus there
# is no need to transform cached values multiple times. However, this
# means that we need to make multiple calls to the underlying parameter
# store if we need to return it in different transforms. Since the number
# of supported transform is small and the probability that a given
# parameter will always be used in a specific transform, this should be
# an acceptable tradeoff.
key = (name, transform)
if not force_fetch and self._has_not_expired(key):
return self.store[key].value
try:
value = self._get(name, **sdk_options)
# Encapsulate all errors into a generic GetParameterError
except Exception as exc:
raise GetParameterError(str(exc))
if transform is not None:
value = transform_value(value, transform)
self.store[key] = ExpirableValue(value, datetime.now() + timedelta(seconds=max_age),)
return value
@abstractmethod
def _get(self, name: str, **sdk_options) -> str:
"""
Retrieve parameter value from the underlying parameter store
"""
raise NotImplementedError()
def get_multiple(
self,
path: str,
max_age: int = DEFAULT_MAX_AGE_SECS,
transform: Optional[str] = None,
raise_on_transform_error: bool = False,
force_fetch: bool = False,
**sdk_options,
) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]:
"""
Retrieve multiple parameters based on a path prefix
Parameters
----------
path: str
Parameter path used to retrieve multiple parameters
max_age: int, optional
Maximum age of the cached value
transform: str, optional
Optional transformation of the parameter value. Supported values
are "json" for JSON strings, "binary" for base 64 encoded
values or "auto" which looks at the attribute key to determine the type.
raise_on_transform_error: bool, optional
Raises an exception if any transform fails, otherwise this will
return a None value for each transform that failed
force_fetch: bool, optional
Force update even before a cached item has expired, defaults to False
sdk_options: dict, optional
Arguments that will be passed directly to the underlying API call
Raises
------
GetParameterError
When the parameter provider fails to retrieve parameter values for
a given path.
TransformParameterError
When the parameter provider fails to transform a parameter value.
"""
key = (path, transform)
if not force_fetch and self._has_not_expired(key):
return self.store[key].value
try:
values: Dict[str, Union[str, bytes, dict, None]] = self._get_multiple(path, **sdk_options)
# Encapsulate all errors into a generic GetParameterError
except Exception as exc:
raise GetParameterError(str(exc))
if transform is not None:
for (key, value) in values.items():
_transform = get_transform_method(key, transform)
if _transform is None:
continue
values[key] = transform_value(value, _transform, raise_on_transform_error)
self.store[key] = ExpirableValue(values, datetime.now() + timedelta(seconds=max_age),)
return values
@abstractmethod
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
"""
Retrieve multiple parameter values from the underlying parameter store
"""
raise NotImplementedError()
def get_transform_method(key: str, transform: Optional[str] = None) -> Optional[str]:
"""
Determine the transform method
Examples
-------
>>> get_transform_method("key", "any_other_value")
'any_other_value'
>>> get_transform_method("key.json", "auto")
'json'
>>> get_transform_method("key.binary", "auto")
'binary'
>>> get_transform_method("key", "auto")
None
>>> get_transform_method("key", None)
None
Parameters
---------
key: str
Only used when the tranform is "auto".
transform: str, optional
Original transform method, only "auto" will try to detect the transform method by the key
Returns
------
Optional[str]:
The transform method either when transform is "auto" then None, "json" or "binary" is returned
or the original transform method
"""
if transform != "auto":
return transform
for transform_method in SUPPORTED_TRANSFORM_METHODS:
if key.endswith("." + transform_method):
return transform_method
return None
def transform_value(value: str, transform: str, raise_on_transform_error: bool = True) -> Union[dict, bytes, None]:
"""
Apply a transform to a value
Parameters
---------
value: str
Parameter value to transform
transform: str
Type of transform, supported values are "json" and "binary"
raise_on_transform_error: bool, optional
Raises an exception if any transform fails, otherwise this will
return a None value for each transform that failed
Raises
------
TransformParameterError:
When the parameter value could not be transformed
"""
try:
if transform == TRANSFORM_METHOD_JSON:
return json.loads(value)
elif transform == TRANSFORM_METHOD_BINARY:
return base64.b64decode(value)
else:
raise ValueError(f"Invalid transform type '{transform}'")
except Exception as exc:
if raise_on_transform_error:
raise TransformParameterError(str(exc))
return None