events-sdk-python 0.0.1__tar.gz → 0.0.2__tar.gz

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.
Files changed (28) hide show
  1. {events-sdk-python-0.0.1/events_sdk_python.egg-info → events-sdk-python-0.0.2}/PKG-INFO +1 -1
  2. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2/events_sdk_python.egg-info}/PKG-INFO +1 -1
  3. events-sdk-python-0.0.2/events_sdk_python.egg-info/SOURCES.txt +24 -0
  4. events-sdk-python-0.0.2/events_sdk_python.egg-info/top_level.txt +1 -0
  5. events-sdk-python-0.0.2/hightouch/htevents/__init__.py +98 -0
  6. events-sdk-python-0.0.2/hightouch/htevents/client.py +428 -0
  7. events-sdk-python-0.0.2/hightouch/htevents/consumer.py +159 -0
  8. events-sdk-python-0.0.2/hightouch/htevents/oauth_manager.py +278 -0
  9. events-sdk-python-0.0.2/hightouch/htevents/request.py +107 -0
  10. events-sdk-python-0.0.2/hightouch/htevents/test/__init__.py +91 -0
  11. events-sdk-python-0.0.2/hightouch/htevents/test/client.py +382 -0
  12. events-sdk-python-0.0.2/hightouch/htevents/test/constants.py +6 -0
  13. events-sdk-python-0.0.2/hightouch/htevents/test/consumer.py +198 -0
  14. events-sdk-python-0.0.2/hightouch/htevents/test/module.py +50 -0
  15. events-sdk-python-0.0.2/hightouch/htevents/test/oauth.py +232 -0
  16. events-sdk-python-0.0.2/hightouch/htevents/test/request.py +75 -0
  17. events-sdk-python-0.0.2/hightouch/htevents/test/utils.py +74 -0
  18. events-sdk-python-0.0.2/hightouch/htevents/utils.py +88 -0
  19. events-sdk-python-0.0.2/hightouch/htevents/version.py +1 -0
  20. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/pyproject.toml +2 -4
  21. events-sdk-python-0.0.1/MANIFEST.in +0 -2
  22. events-sdk-python-0.0.1/events_sdk_python.egg-info/SOURCES.txt +0 -10
  23. events-sdk-python-0.0.1/events_sdk_python.egg-info/top_level.txt +0 -1
  24. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/LICENSE +0 -0
  25. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/README.md +0 -0
  26. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/events_sdk_python.egg-info/dependency_links.txt +0 -0
  27. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/events_sdk_python.egg-info/requires.txt +0 -0
  28. {events-sdk-python-0.0.1 → events-sdk-python-0.0.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: events-sdk-python
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Events SDK Python for Hightouch event collection.
5
5
  Author-email: Hightouch <engineering@hightouch.com>
6
6
  License: MIT License
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: events-sdk-python
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Events SDK Python for Hightouch event collection.
5
5
  Author-email: Hightouch <engineering@hightouch.com>
6
6
  License: MIT License
@@ -0,0 +1,24 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ events_sdk_python.egg-info/PKG-INFO
6
+ events_sdk_python.egg-info/SOURCES.txt
7
+ events_sdk_python.egg-info/dependency_links.txt
8
+ events_sdk_python.egg-info/requires.txt
9
+ events_sdk_python.egg-info/top_level.txt
10
+ hightouch/htevents/__init__.py
11
+ hightouch/htevents/client.py
12
+ hightouch/htevents/consumer.py
13
+ hightouch/htevents/oauth_manager.py
14
+ hightouch/htevents/request.py
15
+ hightouch/htevents/utils.py
16
+ hightouch/htevents/version.py
17
+ hightouch/htevents/test/__init__.py
18
+ hightouch/htevents/test/client.py
19
+ hightouch/htevents/test/constants.py
20
+ hightouch/htevents/test/consumer.py
21
+ hightouch/htevents/test/module.py
22
+ hightouch/htevents/test/oauth.py
23
+ hightouch/htevents/test/request.py
24
+ hightouch/htevents/test/utils.py
@@ -0,0 +1,98 @@
1
+ from hightouch.htevents.client import Client
2
+ from hightouch.htevents.version import VERSION
3
+
4
+ __version__ = VERSION
5
+
6
+ """Settings."""
7
+ write_key = Client.DefaultConfig.write_key
8
+ host = Client.DefaultConfig.host
9
+ on_error = Client.DefaultConfig.on_error
10
+ debug = Client.DefaultConfig.debug
11
+ log_handler = Client.DefaultConfig.log_handler
12
+ send = Client.DefaultConfig.send
13
+ sync_mode = Client.DefaultConfig.sync_mode
14
+ max_queue_size = Client.DefaultConfig.max_queue_size
15
+ gzip = Client.DefaultConfig.gzip
16
+ timeout = Client.DefaultConfig.timeout
17
+ max_retries = Client.DefaultConfig.max_retries
18
+
19
+ """Oauth Settings."""
20
+ oauth_client_id = Client.DefaultConfig.oauth_client_id
21
+ oauth_client_key = Client.DefaultConfig.oauth_client_key
22
+ oauth_key_id = Client.DefaultConfig.oauth_key_id
23
+ oauth_auth_server = Client.DefaultConfig.oauth_auth_server
24
+ oauth_scope = Client.DefaultConfig.oauth_scope
25
+
26
+ default_client = None
27
+
28
+
29
+ def track(*args, **kwargs):
30
+ """Send a track call."""
31
+ return _proxy('track', *args, **kwargs)
32
+
33
+
34
+ def identify(*args, **kwargs):
35
+ """Send a identify call."""
36
+ return _proxy('identify', *args, **kwargs)
37
+
38
+
39
+ def group(*args, **kwargs):
40
+ """Send a group call."""
41
+ return _proxy('group', *args, **kwargs)
42
+
43
+
44
+ def alias(*args, **kwargs):
45
+ """Send a alias call."""
46
+ return _proxy('alias', *args, **kwargs)
47
+
48
+
49
+ def page(*args, **kwargs):
50
+ """Send a page call."""
51
+ return _proxy('page', *args, **kwargs)
52
+
53
+
54
+ def screen(*args, **kwargs):
55
+ """Send a screen call."""
56
+ return _proxy('screen', *args, **kwargs)
57
+
58
+
59
+ def flush():
60
+ """Tell the client to flush."""
61
+ _proxy('flush')
62
+
63
+
64
+ def join():
65
+ """Block program until the client clears the queue"""
66
+ _proxy('join')
67
+
68
+
69
+ def shutdown():
70
+ """Flush all messages and cleanly shutdown the client"""
71
+ _proxy('flush')
72
+ _proxy('join')
73
+
74
+
75
+ def _proxy(method, *args, **kwargs):
76
+ """Create an htevents client if one doesn't exist and send to it."""
77
+ global default_client
78
+ if not default_client:
79
+ default_client = Client(
80
+ write_key,
81
+ host=host,
82
+ debug=debug,
83
+ max_queue_size=max_queue_size,
84
+ send=send,
85
+ on_error=on_error,
86
+ gzip=gzip,
87
+ max_retries=max_retries,
88
+ sync_mode=sync_mode,
89
+ timeout=timeout,
90
+ oauth_client_id=oauth_client_id,
91
+ oauth_client_key=oauth_client_key,
92
+ oauth_key_id=oauth_key_id,
93
+ oauth_auth_server=oauth_auth_server,
94
+ oauth_scope=oauth_scope,
95
+ )
96
+
97
+ fn = getattr(default_client, method)
98
+ return fn(*args, **kwargs)
@@ -0,0 +1,428 @@
1
+ import atexit
2
+ import json
3
+ import logging
4
+ import numbers
5
+ import queue
6
+ from datetime import datetime
7
+ from uuid import uuid4
8
+
9
+ from dateutil.tz import tzutc
10
+
11
+ from hightouch.htevents.consumer import MAX_MSG_SIZE, Consumer
12
+ from hightouch.htevents.oauth_manager import OauthManager
13
+ from hightouch.htevents.request import DatetimeSerializer, post
14
+ from hightouch.htevents.utils import clean, guess_timezone
15
+ from hightouch.htevents.version import VERSION
16
+
17
+ ID_TYPES = (numbers.Number, str)
18
+
19
+
20
+ class Client(object):
21
+ class DefaultConfig(object):
22
+ write_key = None
23
+ host = None
24
+ on_error = None
25
+ debug = False
26
+ log_handler = None
27
+ send = True
28
+ sync_mode = False
29
+ max_queue_size = 10000
30
+ gzip = False
31
+ timeout = 15
32
+ max_retries = 10
33
+ proxies = None
34
+ thread = 1
35
+ upload_interval = 0.5
36
+ upload_size = 100
37
+ oauth_client_id = None
38
+ oauth_client_key = None
39
+ oauth_key_id = None
40
+ oauth_auth_server = 'https://oauth2.hightouch.io'
41
+ oauth_scope = 'tracking_api:write'
42
+
43
+ """Create a new Hightouch client."""
44
+ log = logging.getLogger('hightouch')
45
+
46
+ def __init__(
47
+ self,
48
+ write_key=DefaultConfig.write_key,
49
+ host=DefaultConfig.host,
50
+ debug=DefaultConfig.debug,
51
+ max_queue_size=DefaultConfig.max_queue_size,
52
+ send=DefaultConfig.send,
53
+ on_error=DefaultConfig.on_error,
54
+ gzip=DefaultConfig.gzip,
55
+ max_retries=DefaultConfig.max_retries,
56
+ sync_mode=DefaultConfig.sync_mode,
57
+ timeout=DefaultConfig.timeout,
58
+ proxies=DefaultConfig.proxies,
59
+ thread=DefaultConfig.thread,
60
+ upload_size=DefaultConfig.upload_size,
61
+ upload_interval=DefaultConfig.upload_interval,
62
+ log_handler=DefaultConfig.log_handler,
63
+ oauth_client_id=DefaultConfig.oauth_client_id,
64
+ oauth_client_key=DefaultConfig.oauth_client_key,
65
+ oauth_key_id=DefaultConfig.oauth_key_id,
66
+ oauth_auth_server=DefaultConfig.oauth_auth_server,
67
+ oauth_scope=DefaultConfig.oauth_scope,
68
+ ):
69
+ require('write_key', write_key, str)
70
+
71
+ self.queue = queue.Queue(max_queue_size)
72
+ self.write_key = write_key
73
+ self.on_error = on_error
74
+ self.debug = debug
75
+ self.send = send
76
+ self.sync_mode = sync_mode
77
+ self.host = host
78
+ self.gzip = gzip
79
+ self.timeout = timeout
80
+ self.proxies = proxies
81
+ self.oauth_manager = None
82
+ if oauth_client_id and oauth_client_key and oauth_key_id:
83
+ self.oauth_manager = OauthManager(
84
+ oauth_client_id,
85
+ oauth_client_key,
86
+ oauth_key_id,
87
+ oauth_auth_server,
88
+ oauth_scope,
89
+ timeout,
90
+ max_retries,
91
+ )
92
+
93
+ if log_handler:
94
+ self.log.addHandler(log_handler)
95
+
96
+ if debug:
97
+ self.log.setLevel(logging.DEBUG)
98
+ if not log_handler:
99
+ # default log handler does not print debug or info
100
+ self.log.addHandler(logging.StreamHandler())
101
+
102
+ if sync_mode:
103
+ self.consumers = None
104
+ else:
105
+ # On program exit, allow the consumer thread to exit cleanly.
106
+ # This prevents exceptions and a messy shutdown when the
107
+ # interpreter is destroyed before the daemon thread finishes
108
+ # execution. However, it is *not* the same as flushing the queue!
109
+ # To guarantee all messages have been delivered, you'll still need
110
+ # to call flush().
111
+ if send:
112
+ atexit.register(self.join)
113
+ for _ in range(thread):
114
+ self.consumers = []
115
+ consumer = Consumer(
116
+ self.queue,
117
+ write_key,
118
+ host=host,
119
+ on_error=on_error,
120
+ upload_size=upload_size,
121
+ upload_interval=upload_interval,
122
+ gzip=gzip,
123
+ retries=max_retries,
124
+ timeout=timeout,
125
+ proxies=proxies,
126
+ oauth_manager=self.oauth_manager,
127
+ )
128
+ self.consumers.append(consumer)
129
+
130
+ # if we've disabled sending, just don't start the consumer
131
+ if send:
132
+ consumer.start()
133
+
134
+ def identify(
135
+ self,
136
+ user_id=None,
137
+ traits=None,
138
+ context=None,
139
+ timestamp=None,
140
+ anonymous_id=None,
141
+ integrations=None,
142
+ message_id=None,
143
+ ):
144
+ traits = traits or {}
145
+ context = context or {}
146
+ integrations = integrations or {}
147
+ require('user_id or anonymous_id', user_id or anonymous_id, ID_TYPES)
148
+ require('traits', traits, dict)
149
+
150
+ msg = {
151
+ 'integrations': integrations,
152
+ 'anonymousId': anonymous_id,
153
+ 'timestamp': timestamp,
154
+ 'context': context,
155
+ 'type': 'identify',
156
+ 'userId': user_id,
157
+ 'traits': traits,
158
+ 'messageId': message_id,
159
+ }
160
+
161
+ return self._enqueue(msg)
162
+
163
+ def track(
164
+ self,
165
+ user_id=None,
166
+ event=None,
167
+ properties=None,
168
+ context=None,
169
+ timestamp=None,
170
+ anonymous_id=None,
171
+ integrations=None,
172
+ message_id=None,
173
+ ):
174
+ properties = properties or {}
175
+ context = context or {}
176
+ integrations = integrations or {}
177
+ require('user_id or anonymous_id', user_id or anonymous_id, ID_TYPES)
178
+ require('properties', properties, dict)
179
+ require('event', event, str)
180
+
181
+ msg = {
182
+ 'integrations': integrations,
183
+ 'anonymousId': anonymous_id,
184
+ 'properties': properties,
185
+ 'timestamp': timestamp,
186
+ 'context': context,
187
+ 'userId': user_id,
188
+ 'type': 'track',
189
+ 'event': event,
190
+ 'messageId': message_id,
191
+ }
192
+
193
+ return self._enqueue(msg)
194
+
195
+ def alias(
196
+ self,
197
+ previous_id=None,
198
+ user_id=None,
199
+ context=None,
200
+ timestamp=None,
201
+ integrations=None,
202
+ message_id=None,
203
+ ):
204
+ context = context or {}
205
+ integrations = integrations or {}
206
+ require('previous_id', previous_id, ID_TYPES)
207
+ require('user_id', user_id, ID_TYPES)
208
+
209
+ msg = {
210
+ 'integrations': integrations,
211
+ 'previousId': previous_id,
212
+ 'timestamp': timestamp,
213
+ 'context': context,
214
+ 'userId': user_id,
215
+ 'type': 'alias',
216
+ 'messageId': message_id,
217
+ }
218
+
219
+ return self._enqueue(msg)
220
+
221
+ def group(
222
+ self,
223
+ user_id=None,
224
+ group_id=None,
225
+ traits=None,
226
+ context=None,
227
+ timestamp=None,
228
+ anonymous_id=None,
229
+ integrations=None,
230
+ message_id=None,
231
+ ):
232
+ traits = traits or {}
233
+ context = context or {}
234
+ integrations = integrations or {}
235
+ require('user_id or anonymous_id', user_id or anonymous_id, ID_TYPES)
236
+ require('group_id', group_id, ID_TYPES)
237
+ require('traits', traits, dict)
238
+
239
+ msg = {
240
+ 'integrations': integrations,
241
+ 'anonymousId': anonymous_id,
242
+ 'timestamp': timestamp,
243
+ 'groupId': group_id,
244
+ 'context': context,
245
+ 'userId': user_id,
246
+ 'traits': traits,
247
+ 'type': 'group',
248
+ 'messageId': message_id,
249
+ }
250
+
251
+ return self._enqueue(msg)
252
+
253
+ def page(
254
+ self,
255
+ user_id=None,
256
+ category=None,
257
+ name=None,
258
+ properties=None,
259
+ context=None,
260
+ timestamp=None,
261
+ anonymous_id=None,
262
+ integrations=None,
263
+ message_id=None,
264
+ ):
265
+ properties = properties or {}
266
+ context = context or {}
267
+ integrations = integrations or {}
268
+ require('user_id or anonymous_id', user_id or anonymous_id, ID_TYPES)
269
+ require('properties', properties, dict)
270
+
271
+ if name:
272
+ require('name', name, str)
273
+ if category:
274
+ require('category', category, str)
275
+
276
+ msg = {
277
+ 'integrations': integrations,
278
+ 'anonymousId': anonymous_id,
279
+ 'properties': properties,
280
+ 'timestamp': timestamp,
281
+ 'category': category,
282
+ 'context': context,
283
+ 'userId': user_id,
284
+ 'type': 'page',
285
+ 'name': name,
286
+ 'messageId': message_id,
287
+ }
288
+
289
+ return self._enqueue(msg)
290
+
291
+ def screen(
292
+ self,
293
+ user_id=None,
294
+ category=None,
295
+ name=None,
296
+ properties=None,
297
+ context=None,
298
+ timestamp=None,
299
+ anonymous_id=None,
300
+ integrations=None,
301
+ message_id=None,
302
+ ):
303
+ properties = properties or {}
304
+ context = context or {}
305
+ integrations = integrations or {}
306
+ require('user_id or anonymous_id', user_id or anonymous_id, ID_TYPES)
307
+ require('properties', properties, dict)
308
+
309
+ if name:
310
+ require('name', name, str)
311
+ if category:
312
+ require('category', category, str)
313
+
314
+ msg = {
315
+ 'integrations': integrations,
316
+ 'anonymousId': anonymous_id,
317
+ 'properties': properties,
318
+ 'timestamp': timestamp,
319
+ 'category': category,
320
+ 'context': context,
321
+ 'userId': user_id,
322
+ 'type': 'screen',
323
+ 'name': name,
324
+ 'messageId': message_id,
325
+ }
326
+
327
+ return self._enqueue(msg)
328
+
329
+ def _enqueue(self, msg):
330
+ """Push a new `msg` onto the queue, return `(success, msg)`"""
331
+ timestamp = msg['timestamp']
332
+ if timestamp is None:
333
+ timestamp = datetime.utcnow().replace(tzinfo=tzutc())
334
+ message_id = msg.get('messageId')
335
+ if message_id is None:
336
+ message_id = uuid4()
337
+
338
+ require('integrations', msg['integrations'], dict)
339
+ require('type', msg['type'], str)
340
+ require('timestamp', timestamp, datetime)
341
+ require('context', msg['context'], dict)
342
+
343
+ # add common
344
+ timestamp = guess_timezone(timestamp)
345
+ msg['timestamp'] = timestamp.isoformat(timespec='milliseconds')
346
+ msg['messageId'] = stringify_id(message_id)
347
+ msg['context']['library'] = {'name': 'events-sdk-python', 'version': VERSION}
348
+
349
+ msg['userId'] = stringify_id(msg.get('userId', None))
350
+ msg['anonymousId'] = stringify_id(msg.get('anonymousId', None))
351
+
352
+ msg = clean(msg)
353
+ self.log.debug('queueing: %s', msg)
354
+
355
+ # Check message size.
356
+ msg_size = len(json.dumps(msg, cls=DatetimeSerializer).encode())
357
+ if msg_size > MAX_MSG_SIZE:
358
+ raise RuntimeError(
359
+ 'Message exceeds %skb limit. (%s)',
360
+ str(int(MAX_MSG_SIZE / 1024)),
361
+ str(msg),
362
+ )
363
+
364
+ # if send is False, return msg as if it was successfully queued
365
+ if not self.send:
366
+ return True, msg
367
+
368
+ if self.sync_mode:
369
+ self.log.debug('enqueued with blocking %s.', msg['type'])
370
+ post(
371
+ self.write_key,
372
+ self.host,
373
+ gzip=self.gzip,
374
+ timeout=self.timeout,
375
+ proxies=self.proxies,
376
+ oauth_manager=self.oauth_manager,
377
+ batch=[msg],
378
+ )
379
+
380
+ return True, msg
381
+
382
+ try:
383
+ self.queue.put(msg, block=False)
384
+ self.log.debug('enqueued %s.', msg['type'])
385
+ return True, msg
386
+ except queue.Full:
387
+ self.log.warning('htevents-python queue is full')
388
+ return False, msg
389
+
390
+ def flush(self):
391
+ """Forces a flush from the internal queue to the server"""
392
+ queue = self.queue
393
+ size = queue.qsize()
394
+ queue.join()
395
+ # Note that this message may not be precise, because of threading.
396
+ self.log.debug('successfully flushed about %s items.', size)
397
+
398
+ def join(self):
399
+ """Ends the consumer thread once the queue is empty.
400
+ Blocks execution until finished
401
+ """
402
+ for consumer in self.consumers:
403
+ consumer.pause()
404
+ try:
405
+ consumer.join()
406
+ except RuntimeError:
407
+ # consumer thread has not started
408
+ pass
409
+
410
+ def shutdown(self):
411
+ """Flush all messages and cleanly shutdown the client"""
412
+ self.flush()
413
+ self.join()
414
+
415
+
416
+ def require(name, field, data_type):
417
+ """Require that the named `field` has the right `data_type`"""
418
+ if not isinstance(field, data_type):
419
+ msg = '{0} must have {1}, got: {2}'.format(name, data_type, field)
420
+ raise AssertionError(msg)
421
+
422
+
423
+ def stringify_id(val):
424
+ if val is None:
425
+ return None
426
+ if isinstance(val, str):
427
+ return val
428
+ return str(val)