mageml-singer-python 5.13.0.post3__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.
singer/utils.py ADDED
@@ -0,0 +1,311 @@
1
+ import argparse
2
+ import collections
3
+ import datetime
4
+ import functools
5
+ import json
6
+ import time
7
+ from warnings import warn
8
+
9
+ import dateutil.parser
10
+ import pytz
11
+ import backoff as backoff_module
12
+
13
+ from singer.catalog import Catalog
14
+
15
+ DATETIME_PARSE = "%Y-%m-%dT%H:%M:%SZ"
16
+ DATETIME_FMT = "%04Y-%m-%dT%H:%M:%S.%fZ"
17
+ DATETIME_FMT_SAFE = "%Y-%m-%dT%H:%M:%S.%fZ"
18
+
19
+ def now():
20
+ return datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=pytz.UTC)
21
+
22
+ def strptime_with_tz(dtime):
23
+ d_object = dateutil.parser.parse(dtime)
24
+ if d_object.tzinfo is None:
25
+ return d_object.replace(tzinfo=pytz.UTC)
26
+
27
+ return d_object
28
+
29
+ def strptime(dtime):
30
+ """DEPRECATED Use strptime_to_utc instead.
31
+
32
+ Parse DTIME according to DATETIME_PARSE without TZ safety.
33
+
34
+ >>> strptime("2018-01-01T00:00:00Z")
35
+ datetime.datetime(2018, 1, 1, 0, 0)
36
+
37
+ Requires the Z TZ signifier
38
+ >>> strptime("2018-01-01T00:00:00")
39
+ Traceback (most recent call last):
40
+ ...
41
+ ValueError: time data '2018-01-01T00:00:00' does not match format '%Y-%m-%dT%H:%M:%SZ'
42
+
43
+ Can't parse non-UTC DTs
44
+ >>> strptime("2018-01-01T00:00:00-04:00")
45
+ Traceback (most recent call last):
46
+ ...
47
+ ValueError: time data '2018-01-01T00:00:00-04:00' does not match format '%Y-%m-%dT%H:%M:%SZ'
48
+
49
+ Does not support fractional seconds
50
+ >>> strptime("2018-01-01T00:00:00.000000Z")
51
+ Traceback (most recent call last):
52
+ ...
53
+ ValueError: time data '2018-01-01T00:00:00.000000Z' does not match format '%Y-%m-%dT%H:%M:%SZ'
54
+ """
55
+
56
+ warn("Use strptime_to_utc instead", DeprecationWarning, stacklevel=2)
57
+
58
+ return datetime.datetime.strptime(dtime, DATETIME_PARSE)
59
+
60
+ def strptime_to_utc(dtimestr):
61
+ d_object = dateutil.parser.parse(dtimestr)
62
+ if d_object.tzinfo is None:
63
+ return d_object.replace(tzinfo=pytz.UTC)
64
+ else:
65
+ return d_object.astimezone(tz=pytz.UTC)
66
+
67
+ def strftime(dtime, format_str=DATETIME_FMT):
68
+ if dtime.utcoffset() != datetime.timedelta(0):
69
+ raise Exception("datetime must be pegged at UTC tzoneinfo")
70
+
71
+ dt_str = None
72
+ try:
73
+ dt_str = dtime.strftime(format_str)
74
+ if dt_str.startswith('4Y'):
75
+ dt_str = dtime.strftime(DATETIME_FMT_SAFE)
76
+ except ValueError:
77
+ dt_str = dtime.strftime(DATETIME_FMT_SAFE)
78
+
79
+ return dt_str
80
+
81
+ def ratelimit(limit, every):
82
+ def limitdecorator(func):
83
+ times = collections.deque()
84
+
85
+ @functools.wraps(func)
86
+ def wrapper(*args, **kwargs):
87
+ if len(times) >= limit:
88
+ tim0 = times.pop()
89
+ tim = time.time()
90
+ sleep_time = every - (tim - tim0)
91
+ if sleep_time > 0:
92
+ time.sleep(sleep_time)
93
+
94
+ times.appendleft(time.time())
95
+ return func(*args, **kwargs)
96
+
97
+ return wrapper
98
+
99
+ return limitdecorator
100
+
101
+
102
+ def chunk(array, num):
103
+ for i in range(0, len(array), num):
104
+ yield array[i:i + num]
105
+
106
+
107
+ def load_json(path):
108
+ with open(path) as fil:
109
+ return json.load(fil)
110
+
111
+
112
+ def update_state(state, entity, dtime):
113
+ if dtime is None:
114
+ return
115
+
116
+ if isinstance(dtime, datetime.datetime):
117
+ dtime = strftime(dtime)
118
+
119
+ if entity not in state:
120
+ state[entity] = dtime
121
+
122
+ if dtime >= state[entity]:
123
+ state[entity] = dtime
124
+
125
+
126
+ def parse_args(required_config_keys):
127
+ '''Parse standard command-line args.
128
+
129
+ Parses the command-line arguments mentioned in the SPEC and the
130
+ BEST_PRACTICES documents:
131
+
132
+ -c,--config Config file
133
+ -s,--state State file
134
+ -d,--discover Run in discover mode
135
+ -p,--properties Properties file: DEPRECATED, please use --catalog instead
136
+ --catalog Catalog file
137
+ --dev Runs the tap in dev mode
138
+
139
+ Returns the parsed args object from argparse. For each argument that
140
+ point to JSON files (config, state, properties), we will automatically
141
+ load and parse the JSON file.
142
+ '''
143
+ parser = argparse.ArgumentParser()
144
+
145
+ parser.add_argument(
146
+ '-c', '--config',
147
+ help='Config file',
148
+ required=True)
149
+
150
+ parser.add_argument(
151
+ '-s', '--state',
152
+ help='State file')
153
+
154
+ parser.add_argument(
155
+ '-p', '--properties',
156
+ help='Property selections: DEPRECATED, Please use --catalog instead')
157
+
158
+ parser.add_argument(
159
+ '--catalog',
160
+ help='Catalog file')
161
+
162
+ parser.add_argument(
163
+ '-d', '--discover',
164
+ action='store_true',
165
+ help='Do schema discovery')
166
+
167
+ parser.add_argument(
168
+ '--dev',
169
+ action='store_true',
170
+ help='Runs tap in dev mode')
171
+
172
+ args = parser.parse_args()
173
+ if args.config:
174
+ setattr(args, 'config_path', args.config)
175
+ args.config = load_json(args.config)
176
+ if args.state:
177
+ setattr(args, 'state_path', args.state)
178
+ args.state = load_json(args.state)
179
+ else:
180
+ args.state = {}
181
+ if args.properties:
182
+ setattr(args, 'properties_path', args.properties)
183
+ args.properties = load_json(args.properties)
184
+ if args.catalog:
185
+ setattr(args, 'catalog_path', args.catalog)
186
+ args.catalog = Catalog.load(args.catalog)
187
+
188
+ check_config(args.config, required_config_keys)
189
+
190
+ return args
191
+
192
+
193
+ def check_config(config, required_keys):
194
+ missing_keys = [key for key in required_keys if key not in config]
195
+ if missing_keys:
196
+ raise Exception("Config is missing required keys: {}".format(missing_keys))
197
+
198
+
199
+ def backoff(exceptions, giveup):
200
+ """Decorates a function to retry up to 5 times using an exponential backoff
201
+ function.
202
+
203
+ exceptions is a tuple of exception classes that are retried
204
+ giveup is a function that accepts the exception and returns True to retry
205
+ """
206
+ return backoff_module.on_exception(
207
+ backoff_module.expo,
208
+ exceptions,
209
+ max_tries=5,
210
+ giveup=giveup,
211
+ factor=2)
212
+
213
+
214
+ def exception_is_4xx(exception):
215
+ """Returns True if exception is in the 4xx range."""
216
+ if not hasattr(exception, "response"):
217
+ return False
218
+
219
+ if exception.response is None:
220
+ return False
221
+
222
+ if not hasattr(exception.response, "status_code"):
223
+ return False
224
+
225
+ return 400 <= exception.response.status_code < 500
226
+
227
+
228
+ def handle_top_exception(logger):
229
+ """A decorator that will catch exceptions and log the exception's message
230
+ as a CRITICAL log."""
231
+ def decorator(fnc):
232
+ @functools.wraps(fnc)
233
+ def wrapped(*args, **kwargs):
234
+ try:
235
+ return fnc(*args, **kwargs)
236
+ except Exception as exc:
237
+ for line in str(exc).splitlines():
238
+ logger.critical(line)
239
+ raise
240
+ return wrapped
241
+ return decorator
242
+
243
+
244
+ def should_sync_field(inclusion, selected, default=False):
245
+ """
246
+ Returns True if a field should be synced.
247
+
248
+ inclusion: automatic|available|unsupported
249
+ selected: True|False|None
250
+ default: (default: False) True|False
251
+
252
+ "automatic" inclusion always returns True:
253
+ >>> should_sync_field("automatic", None, False)
254
+ True
255
+ >>> should_sync_field("automatic", True, False)
256
+ True
257
+ >>> should_sync_field("automatic", False, False)
258
+ True
259
+ >>> should_sync_field("automatic", None, True)
260
+ True
261
+ >>> should_sync_field("automatic", True, True)
262
+ True
263
+ >>> should_sync_field("automatic", False, True)
264
+ True
265
+
266
+
267
+ "unsupported" inclusion always returns False
268
+ >>> should_sync_field("unsupported", None, False)
269
+ False
270
+ >>> should_sync_field("unsupported", True, False)
271
+ False
272
+ >>> should_sync_field("unsupported", False, False)
273
+ False
274
+ >>> should_sync_field("unsupported", None, True)
275
+ False
276
+ >>> should_sync_field("unsupported", True, True)
277
+ False
278
+ >>> should_sync_field("unsupported", False, True)
279
+ False
280
+
281
+ "available" inclusion uses the selected value when set
282
+ >>> should_sync_field("available", True, False)
283
+ True
284
+ >>> should_sync_field("available", False, False)
285
+ False
286
+ >>> should_sync_field("available", True, True)
287
+ True
288
+ >>> should_sync_field("available", False, True)
289
+ False
290
+
291
+ "available" inclusion uses the default value when selected is None
292
+ >>> should_sync_field("available", None, False)
293
+ False
294
+ >>> should_sync_field("available", None, True)
295
+ True
296
+ """
297
+ # always select automatic fields
298
+ if inclusion == "automatic":
299
+ return True
300
+
301
+ # never select unsupported fields
302
+ if inclusion == "unsupported":
303
+ return False
304
+
305
+ # at this point inclusion == "available"
306
+ # selected could be None, otherwise use the value of selected
307
+ if selected is not None:
308
+ return selected
309
+
310
+ # if there was no selected value, use the default
311
+ return default