Repository navigation
Expand file tree
/
Copy pathanalytics.py
More file actions
262 lines (227 loc) · 8.98 KB
/
Copy pathanalytics.py
File metadata and controls
262 lines (227 loc) · 8.98 KB
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
import atexit
import json
import logging
import threading
import typing
from dataclasses import dataclass
from datetime import datetime
from requests_futures.sessions import FuturesSession # type: ignore
from flagsmith.version import __version__
logger = logging.getLogger(__name__)
ANALYTICS_ENDPOINT: typing.Final[str] = "analytics/flags/"
# Used to control how often we send data(in seconds)
ANALYTICS_TIMER: typing.Final[int] = 10
FLAG_EXPOSURE_EVENT: typing.Final[str] = "$flag_exposure"
DEFAULT_EVENT_API_URL: typing.Final[str] = "https://events.api.flagsmith.com/"
session = FuturesSession(max_workers=4)
class AnalyticsProcessor:
"""
AnalyticsProcessor is used to track how often individual Flags are evaluated within
the Flagsmith SDK. Docs: https://docs.flagsmith.com/advanced-use/flag-analytics.
"""
def __init__(
self,
environment_key: str,
base_api_url: str,
timeout: typing.Optional[int] = 3,
analytics_url: typing.Optional[str] = None,
):
"""
Initialise the AnalyticsProcessor to handle sending analytics on flag usage to
the Flagsmith API.
:param environment_key: environment key obtained from the Flagsmith UI
:param base_api_url: base api url to override when using self hosted version
:param timeout: used to tell requests to stop waiting for a response after a
given number of seconds
:param analytics_url: full URL of the flag analytics endpoint, used to override
the default ``<base_api_url>/analytics/flags/``. Intended for deployments
where flag evaluation traffic and analytics traffic must go to different
hosts (for example, evaluating through the Edge Proxy while sending
analytics to the core API).
"""
self.analytics_endpoint = analytics_url or (base_api_url + ANALYTICS_ENDPOINT)
self.environment_key = environment_key
self._last_flushed = datetime.now()
self.analytics_data: typing.MutableMapping[str, typing.Any] = {}
self.timeout = timeout or 3
def flush(self) -> None:
"""
Sends all the collected data to the api asynchronously and resets the timer
"""
if not self.analytics_data:
return
session.post(
self.analytics_endpoint,
data=json.dumps(self.analytics_data),
timeout=self.timeout,
headers={
"X-Environment-Key": self.environment_key,
"Content-Type": "application/json",
},
)
self.analytics_data.clear()
self._last_flushed = datetime.now()
def track_feature(self, feature_name: str) -> None:
self.analytics_data[feature_name] = self.analytics_data.get(feature_name, 0) + 1
if (datetime.now() - self._last_flushed).seconds > ANALYTICS_TIMER:
self.flush()
class ExposureKey(typing.NamedTuple):
feature_name: typing.Optional[str]
identifier: typing.Optional[str]
value: typing.Optional[str]
@dataclass
class EventProcessorConfig:
events_api_url: str = DEFAULT_EVENT_API_URL
max_buffer_items: int = 1000
flush_interval_seconds: float = 10.0
class EventProcessor:
"""
Buffered event processor that batches custom events and POSTs them to the
Flagsmith event endpoint. Flushes on a background timer or when the buffer
fills.
"""
def __init__(
self,
config: EventProcessorConfig,
environment_key: str,
) -> None:
url = config.events_api_url
if not url.endswith("/"):
url = f"{url}/"
self._batch_endpoint = f"{url}v1/events"
self._environment_key = environment_key
self._max_buffer = config.max_buffer_items
self._flush_interval_seconds = config.flush_interval_seconds
self._buffer: typing.List[typing.Dict[str, typing.Any]] = []
self._buffered_exposure_keys: typing.Set[ExposureKey] = set()
self._lock = threading.Lock()
self._timer: typing.Optional[threading.Timer] = None
def track_event(
self,
event: str,
identifier: typing.Optional[str] = None,
value: typing.Optional[typing.Union[str, int, float, bool]] = None,
traits: typing.Optional[typing.Dict[str, typing.Any]] = None,
metadata: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> None:
self._buffer_event(
event=event,
feature_name=None,
identifier=identifier,
value=value,
traits=traits,
metadata=metadata,
)
def track_exposure_event(
self,
feature_name: str,
identifier: typing.Optional[str] = None,
value: typing.Optional[typing.Union[str, int, float, bool]] = None,
traits: typing.Optional[typing.Dict[str, typing.Any]] = None,
metadata: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> None:
self._buffer_event(
event=FLAG_EXPOSURE_EVENT,
feature_name=feature_name,
identifier=identifier,
value=value,
traits=traits,
metadata=metadata,
)
def _buffer_event(
self,
event: str,
feature_name: typing.Optional[str],
identifier: typing.Optional[str],
value: typing.Optional[typing.Union[str, int, float, bool]],
traits: typing.Optional[typing.Dict[str, typing.Any]],
metadata: typing.Optional[typing.Dict[str, typing.Any]],
) -> None:
should_flush = False
with self._lock:
if event == FLAG_EXPOSURE_EVENT:
# An exposure is defined by who saw which variant of which
# feature; equal exposures within one flush interval add no
# information, so only the first is buffered.
exposure_key = ExposureKey(
feature_name=feature_name,
identifier=identifier,
value=str(value) if value is not None else None,
)
if exposure_key in self._buffered_exposure_keys:
logger.debug(
"Skipping duplicate %s event for feature %s, identifier %s",
FLAG_EXPOSURE_EVENT,
feature_name,
identifier,
)
return
self._buffered_exposure_keys.add(exposure_key)
self._buffer.append(
{
"event": event,
"feature_name": feature_name,
"identifier": identifier,
"value": str(value) if value is not None else None,
"traits": dict(traits) if traits else None,
"metadata": {**(metadata or {}), "sdk_version": __version__},
"timestamp": int(datetime.now().timestamp() * 1000),
}
)
if len(self._buffer) >= self._max_buffer:
should_flush = True
if should_flush:
self.flush()
def flush(self) -> None:
with self._lock:
if not self._buffer:
return
events = self._buffer
self._buffer = []
self._buffered_exposure_keys.clear()
payload = json.dumps({"events": events})
try:
future = session.post(
self._batch_endpoint,
data=payload,
timeout=3,
headers={
"Content-Type": "application/json; charset=utf-8",
"X-Environment-Key": self._environment_key,
"Flagsmith-SDK-User-Agent": f"flagsmith-python-client/{__version__}",
},
)
except RuntimeError:
logger.debug("Skipping flush: thread pool already shut down")
return
future.add_done_callback(lambda f: self._handle_flush_result(f, events))
def _handle_flush_result(
self,
future: typing.Any,
events: typing.List[typing.Dict[str, typing.Any]],
) -> None:
try:
response = future.result()
response.raise_for_status()
except Exception:
logger.warning(
"Failed to flush pipeline analytics, re-queuing events", exc_info=True
)
with self._lock:
self._buffer = events + self._buffer
self._buffer = self._buffer[: self._max_buffer]
def start(self) -> None:
self._schedule_flush()
atexit.register(self.stop)
def stop(self) -> None:
atexit.unregister(self.stop)
if self._timer is not None:
self._timer.cancel()
self.flush()
def _schedule_flush(self) -> None:
self._timer = threading.Timer(self._flush_interval_seconds, self._timer_flush)
self._timer.daemon = True
self._timer.start()
def _timer_flush(self) -> None:
self.flush()
self._schedule_flush()