-
Notifications
You must be signed in to change notification settings - Fork 1
/
konfug.py
327 lines (268 loc) · 10.5 KB
/
konfug.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# -*- coding: utf-8 -*-
import abc
import os
import json
import functools
import firebase_admin
from google.cloud import datastore
from google.cloud import secretmanager
from google.auth.exceptions import DefaultCredentialsError
DEFAULT_FALSEY_EXPRESSIONS = ('0', 'false', 0, False, None,)
UTF8 = 'UTF-8'
class KonfugError(Exception):
pass
class KonfugMissingError(KonfugError):
def __init__(self, missing_setting, is_secret=False):
self._missing_setting = missing_setting
space = "setting" if is_secret is False else "secret"
self.message = f'Missing {space} "{missing_setting}"'
super(KonfugMissingError, self).__init__(self.message)
class KonfugMetaConfigError(KonfugError):
def __init__(self, global_name, kwarg_name):
self._global_name = global_name
self._kwarg_name = kwarg_name
self.message = f'Missing {global_name} env or {kwarg_name} kwarg'
super(KonfugMetaConfigError, self).__init__(self.message)
class HotFugError(KonfugError):
def __init__(self, message):
self.message = message
super(HotFugError, self).__init__(self.message)
class HotFug(abc.ABC):
__metaclass__ = abc.ABCMeta
_FIREBASE = None
COLLECTION = None
FIREBASE_CREDENTIAL_JSON = None
def __init__(self, key, default_val=None, apply_=None):
self._key = key
self._default_val = default_val
self._apply = apply_ if apply_ else lambda v: v
@classmethod
def _firebase(cls):
if not cls._FIREBASE:
try:
firebase_admin.get_app()
except ValueError:
cred = firebase_admin.credentials.Certificate(
cls.FIREBASE_CREDENTIAL_JSON
)
try:
firebase_admin.initialize_app(cred)
except ValueError:
pass
except firebase_admin.exceptions.FirebaseError as err:
raise HotFugError("Could not initialize firebase") from err
# Caching Firebase client at class level.
cls._FIREBASE = (
firebase_admin.firestore.client().collection(cls.COLLECTION)
)
return cls._FIREBASE
def retrieve(self):
doc = type(self)._firebase().document(self._key).get()
if doc.exists:
val = self._apply(doc.to_dict().get('value'))
elif self._default_val:
val = self._default_val
else:
val = None
return val
@classmethod
def hotfug_cls(cls, credentials, collection):
return type(
f'_{cls.__name__}',
(cls,),
{
'FIREBASE_CREDENTIAL_JSON': credentials,
'COLLECTION': collection
}
)
class HotFugCollection(object):
def __init__(self):
self._hotconfs = []
def __getattribute__(self, attribute):
value = super(HotFugCollection, self).__getattribute__(attribute)
if issubclass(type(value), (HotFug,)):
value = value.retrieve()
if value is None:
if attribute in self._hotconfs:
value = self._hotconfs[attribute]
else:
raise KonfugMissingError(attribute)
return value
def __setattr__(self, name, value):
if issubclass(type(value), (HotFug,)):
self._hotconfs.append(name)
super(HotFugCollection, self).__setattr__(name, value)
class Konfug(object):
def __init__(self, **kwargs):
try:
cls = type(self)
project_id = cls.check_metaconfig(
kwargs, 'GOOGLE_CLOUD_PROJECT', 'project_id'
)
settings_kind = cls.check_metaconfig(
kwargs, 'KONFUG_DATASTORE_SETTINGS_KIND', 'settings_kind'
)
namespace = cls.check_metaconfig(
kwargs, 'KONFUG_DATASTORE_NAMESPACE', 'namespace'
)
common_namespace = cls.check_metaconfig(
kwargs,
'KONFUG_DATASTORE_COMMON_NAMESPACE',
'common_namespace',
required=False
)
stringlist_separator = cls.check_metaconfig(
kwargs,
'KONFUG_STRINGLIST_SEPARATOR',
'stringlist_separator',
required=False
)
self._stringlist_separator = stringlist_separator or ','
self._falsey_expressions = kwargs.get(
'falsey_expressions', DEFAULT_FALSEY_EXPRESSIONS
)
self._to_bool = functools.partial(
type(self).to_bool, falsey_expressions=self._falsey_expressions
)
self._to_stringlist = functools.partial(
type(self).to_stringlist, sep=self._stringlist_separator
)
self._to_int = int
self._to_dict = type(self).to_dict
self._to_float = float
force_datastore = cls.to_bool(
cls.check_metaconfig(
kwargs,
'KONFUG_FORCE_DATASTORE',
'force_datastore',
required=False
),
falsey_expressions=self._falsey_expressions
)
self._secret_resource_name_tpl = (
f"projects/{project_id}/"
f"secrets/{{secret_id}}/"
f"versions/latest"
)
self._skip_datastore = kwargs.get('skip_datastore', False)
self._skip_secret_manager = kwargs.get(
'skip_secret_manager', False
)
self._skip_firebase = kwargs.get('skip_firebase', False)
self._hotcollection = HotFugCollection()
self._hot_cls = HotFug
self._dataclient = None
self._secretclient = None
if not self._skip_datastore:
self._dataclient = datastore.Client(project=project_id)
else:
self._dataclient = None
if not self._skip_secret_manager:
self._secretclient = secretmanager.SecretManagerServiceClient()
else:
self._secretclient = None
def fetch_kinds(ns):
kinds = {}
if self._skip_datastore is False:
kinds = self._dataclient.query(
kind=settings_kind, namespace=ns
).fetch()
kinds = dict(next(iter(kinds)))
return kinds
self._settings = fetch_kinds(namespace)
if common_namespace:
self._common_settings = fetch_kinds(common_namespace)
else:
self._common_settings = {}
except (StopIteration, TypeError, DefaultCredentialsError):
if force_datastore:
raise
# Defaults to empty dictionary. Settings will be taken from the
# environment variables.
self._common_settings = {}
else:
self._common_settings.update(self._settings)
@staticmethod
def check_metaconfig(kwargs, global_name, kwarg_name, required=True):
if kwargs.get(kwarg_name):
return kwargs[kwarg_name]
elif os.environ.get(global_name):
return os.environ[global_name]
if required:
raise KonfugMetaConfigError(global_name, kwarg_name)
def raw_setting(
self, key, default_val=None, apply_=None, nullable=False, hot=False
):
if hot and not self._skip_firebase:
return self._hot_cls(key, default_val=default_val, apply_=apply_)
if key in os.environ:
val = os.getenv(key)
elif key in self._common_settings:
val = self._common_settings[key]
elif default_val is not None:
val = default_val
elif not nullable:
raise KonfugMissingError(key)
else:
val = None
return apply_(val) if callable(apply_) else val
def string(self, key, default_val=None, hot=False):
return self.raw_setting(key, default_val=default_val, hot=hot)
def flag(self, key, default_val=None, hot=False):
return self.raw_setting(
key, default_val=default_val, apply_=self._to_bool, hot=hot
)
def stringlist(self, key, default_val=None, hot=False):
return self.raw_setting(
key, default_val=default_val, apply_=self._to_stringlist, hot=hot
)
def integer(self, key, default_val=None, hot=False):
return self.raw_setting(
key, default_val=default_val, apply_=self._to_int, hot=hot
)
def dictionary(self, key, default_val=None, hot=False):
return self.raw_setting(
key, default_val=default_val, apply_=self._to_dict, hot=hot
)
def floatnum(self, key, default_val=None, hot=False):
return self.raw_setting(
key, default_val=default_val, apply_=self._to_float, hot=hot
)
@staticmethod
def to_bool(val, falsey_expressions=DEFAULT_FALSEY_EXPRESSIONS):
return val not in falsey_expressions
@staticmethod
def to_stringlist(val, sep=','):
return [v.strip() for v in val.split(sep) if v.strip()]
@staticmethod
def to_dict(val):
try:
# os.environ has a JSON formatted string.
dict_ = json.loads(val)
except TypeError:
# Google Datastore should return a dictionary.
dict_ = val
if not isinstance(dict_, dict):
raise ValueError(f'Not a dict {val}')
else:
return dict_
def secret(self, key, default_val=None, transform=None, encoding=UTF8):
if key in os.environ:
val = os.getenv(key)
elif self._skip_secret_manager or self._secretclient is None:
val = None
else:
name = self._secret_resource_name_tpl.format(secret_id=key)
secret = self._secretclient.access_secret_version(
request={"name": name})
val = secret.payload.data.decode(encoding)
if transform and callable(transform) and val:
val = transform(val)
if val is None and default_val:
val = default_val
elif val is None:
raise KonfugMissingError(key, is_secret=True)
return val
def hot_settings(self, credentials=None, collection=None):
self._hot_cls = HotFug.hotfug_cls(credentials, collection)
return self._hotcollection