dynatrace-openfeature-provider-python 0.0.2__tar.gz → 0.0.4__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.
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/PKG-INFO +2 -2
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/README.md +1 -1
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/pyproject.toml +1 -1
- dynatrace_openfeature_provider_python-0.0.4/src/dynatrace/openfeature/_metrics_aggregator.py +122 -0
- dynatrace_openfeature_provider_python-0.0.4/src/dynatrace/openfeature/_metrics_flusher.py +270 -0
- dynatrace_openfeature_provider_python-0.0.4/src/dynatrace/openfeature/_metrics_hook.py +121 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/options.py +16 -3
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/provider.py +81 -12
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/LICENSE +0 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/__init__.py +0 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/_cdn.py +0 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/_polling.py +0 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/_retry.py +0 -0
- {dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/src/dynatrace/openfeature/py.typed +0 -0
{dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dynatrace-openfeature-provider-python
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.4
|
|
4
4
|
Summary: The official Dynatrace OpenFeature provider for Python
|
|
5
5
|
Keywords: openfeature,dynatrace,feature-flags,feature-management
|
|
6
6
|
Author: Dynatrace
|
|
@@ -20,7 +20,7 @@ Description-Content-Type: text/markdown
|
|
|
20
20
|
|
|
21
21
|
The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
|
|
22
22
|
|
|
23
|
-
> **Status:** Early alpha — not yet ready for production use
|
|
23
|
+
> **Status:** Early alpha — not yet ready for production use!
|
|
24
24
|
|
|
25
25
|
## Installation
|
|
26
26
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
|
|
4
4
|
|
|
5
|
-
> **Status:** Early alpha — not yet ready for production use
|
|
5
|
+
> **Status:** Early alpha — not yet ready for production use!
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import threading
|
|
5
|
+
import typing
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
# Soft/hard caps on distinct flag keys. Faithful to the Java provider, these are
|
|
10
|
+
# fixed constants and are NOT user-configurable.
|
|
11
|
+
SOFT_CAP_DISTINCT_FLAGS = 1_000
|
|
12
|
+
HARD_CAP_DISTINCT_FLAGS = 2_000
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EvaluationMetricKey(typing.NamedTuple):
|
|
16
|
+
"""Typed dimension key for one aggregation bucket.
|
|
17
|
+
|
|
18
|
+
Using a tuple (rather than a delimiter-joined string) gives value-based
|
|
19
|
+
equality/hashing for free and avoids delimiter-collision ambiguity.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
variant: str
|
|
23
|
+
reason: str
|
|
24
|
+
error_code: str | None
|
|
25
|
+
timestamp_sec: int
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Two-level live map: {flag_key: {dimension_key: count}}.
|
|
29
|
+
_FlagBuckets = dict[EvaluationMetricKey, int]
|
|
30
|
+
_AggregateMap = dict[str, _FlagBuckets]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class DrainedBatch:
|
|
34
|
+
"""An immutable snapshot drained from the aggregator, tagged with the config
|
|
35
|
+
version that was active when it was drained."""
|
|
36
|
+
|
|
37
|
+
__slots__ = ("_evaluations", "_version")
|
|
38
|
+
|
|
39
|
+
def __init__(self, evaluations: _AggregateMap, version: str | None) -> None:
|
|
40
|
+
self._evaluations = evaluations
|
|
41
|
+
self._version = version
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def is_empty(self) -> bool:
|
|
45
|
+
return not self._evaluations
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def evaluations(self) -> _AggregateMap:
|
|
49
|
+
return self._evaluations
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def version(self) -> str | None:
|
|
53
|
+
return self._version
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DynatraceMetricsAggregator:
|
|
57
|
+
"""In-memory aggregate map backing the evaluation-metrics hook.
|
|
58
|
+
|
|
59
|
+
All public methods are guarded by a single lock so a record can never land in
|
|
60
|
+
a snapshot after that snapshot has been drained.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, max_distinct_flags: int = HARD_CAP_DISTINCT_FLAGS) -> None:
|
|
64
|
+
if max_distinct_flags <= 0:
|
|
65
|
+
raise ValueError("max_distinct_flags must be positive")
|
|
66
|
+
self._metrics: _AggregateMap = {}
|
|
67
|
+
self._max_distinct_flags = max_distinct_flags
|
|
68
|
+
self._version: str | None = None
|
|
69
|
+
self._lock = threading.RLock()
|
|
70
|
+
|
|
71
|
+
def record(
|
|
72
|
+
self,
|
|
73
|
+
flag_key: str,
|
|
74
|
+
variant: str,
|
|
75
|
+
reason: str,
|
|
76
|
+
error_code: str | None,
|
|
77
|
+
timestamp_sec: int,
|
|
78
|
+
evaluation_version: str | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
with self._lock:
|
|
81
|
+
if self._version is None:
|
|
82
|
+
log.debug(
|
|
83
|
+
"dropping evaluation for %r: no config version observed yet",
|
|
84
|
+
flag_key,
|
|
85
|
+
)
|
|
86
|
+
return
|
|
87
|
+
if evaluation_version is not None and evaluation_version != self._version:
|
|
88
|
+
# Guards against cross-version contamination within a batch.
|
|
89
|
+
return
|
|
90
|
+
buckets = self._metrics.get(flag_key)
|
|
91
|
+
if buckets is None:
|
|
92
|
+
if len(self._metrics) >= self._max_distinct_flags:
|
|
93
|
+
log.debug("dropping metrics due to max aggregator size")
|
|
94
|
+
return
|
|
95
|
+
buckets = self._metrics[flag_key] = {}
|
|
96
|
+
key = EvaluationMetricKey(variant, reason, error_code, timestamp_sec)
|
|
97
|
+
buckets[key] = buckets.get(key, 0) + 1
|
|
98
|
+
|
|
99
|
+
def set_version(self, version: str | None) -> None:
|
|
100
|
+
"""Records the latest config version. Version transitions are the
|
|
101
|
+
provider's responsibility; record() never mutates the version."""
|
|
102
|
+
with self._lock:
|
|
103
|
+
if version is not None and version.strip():
|
|
104
|
+
self._version = version
|
|
105
|
+
|
|
106
|
+
def get_version(self) -> str | None:
|
|
107
|
+
with self._lock:
|
|
108
|
+
return self._version
|
|
109
|
+
|
|
110
|
+
def size(self) -> int:
|
|
111
|
+
"""Number of distinct flag keys currently in the live map."""
|
|
112
|
+
with self._lock:
|
|
113
|
+
return len(self._metrics)
|
|
114
|
+
|
|
115
|
+
def drain(self) -> DrainedBatch:
|
|
116
|
+
"""Swaps the live map for a fresh one and returns the previous contents.
|
|
117
|
+
The version is preserved on the batch (it remains valid for the drained
|
|
118
|
+
data); the aggregator keeps its current version."""
|
|
119
|
+
with self._lock:
|
|
120
|
+
previous = self._metrics
|
|
121
|
+
self._metrics = {}
|
|
122
|
+
return DrainedBatch(previous, self._version)
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections import deque
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
|
|
12
|
+
from ._metrics_aggregator import DrainedBatch, DynatraceMetricsAggregator, _AggregateMap
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
_SDK_TYPE = "server"
|
|
17
|
+
_HTTP_TIMEOUT_S = 10.0
|
|
18
|
+
# Cooldown applied to out-of-band (capacity) flushes after a failed delivery, to
|
|
19
|
+
# avoid hammering a struggling endpoint between periodic flush ticks.
|
|
20
|
+
_FAILED_CAPACITY_RETRY_COOLDOWN_S = 30.0
|
|
21
|
+
# Maximum number of sealed batches held in the queue at any time.
|
|
22
|
+
_MAX_SEALED_BATCHES = 10
|
|
23
|
+
|
|
24
|
+
_THREAD_NAME = "dt-provider-metrics-flusher"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_payload(
|
|
28
|
+
evaluations: _AggregateMap,
|
|
29
|
+
version: str | None,
|
|
30
|
+
sdk_version: str,
|
|
31
|
+
provider_name: str,
|
|
32
|
+
) -> str:
|
|
33
|
+
"""Serializes the documented Dynatrace evaluation-metrics payload."""
|
|
34
|
+
evals: list[dict[str, object]] = []
|
|
35
|
+
for flag_key, buckets in evaluations.items():
|
|
36
|
+
for key, count in buckets.items():
|
|
37
|
+
entry: dict[str, object] = {
|
|
38
|
+
"flagKey": flag_key,
|
|
39
|
+
"variant": key.variant,
|
|
40
|
+
"evaluationReason": key.reason,
|
|
41
|
+
}
|
|
42
|
+
if key.error_code is not None:
|
|
43
|
+
entry["errorCode"] = key.error_code
|
|
44
|
+
entry["timestampSec"] = key.timestamp_sec
|
|
45
|
+
entry["count"] = count
|
|
46
|
+
evals.append(entry)
|
|
47
|
+
root = {
|
|
48
|
+
"version": version,
|
|
49
|
+
"sdkType": _SDK_TYPE,
|
|
50
|
+
"sdkVersion": sdk_version,
|
|
51
|
+
"providerName": provider_name,
|
|
52
|
+
"evaluations": evals,
|
|
53
|
+
}
|
|
54
|
+
return json.dumps(root)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class EvaluationMetricsFlusher:
|
|
58
|
+
"""Drains the aggregator, serializes the payload, and POSTs it to the metrics
|
|
59
|
+
ingest endpoint.
|
|
60
|
+
|
|
61
|
+
All HTTP work happens on a single dedicated daemon thread, never on the
|
|
62
|
+
evaluation path. Flush triggers: periodic (the worker's wait timeout),
|
|
63
|
+
capacity (:meth:`on_record`), version-rotation (:meth:`trigger_flush` after
|
|
64
|
+
:meth:`enqueue_sealed_batch`), and shutdown (final synchronous flush).
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__( # noqa: PLR0913 - all keyword-only config + injectable test seams
|
|
68
|
+
self,
|
|
69
|
+
aggregator: DynatraceMetricsAggregator,
|
|
70
|
+
*,
|
|
71
|
+
sdk_key: str,
|
|
72
|
+
metrics_url: str,
|
|
73
|
+
flush_interval_s: float,
|
|
74
|
+
capacity_threshold: int,
|
|
75
|
+
sdk_version: str,
|
|
76
|
+
provider_name: str,
|
|
77
|
+
session: requests.Session | None = None,
|
|
78
|
+
clock: Callable[[], float] = time.monotonic,
|
|
79
|
+
) -> None:
|
|
80
|
+
self._aggregator = aggregator
|
|
81
|
+
self._metrics_url = metrics_url
|
|
82
|
+
self._authorization_header = f"Bearer {sdk_key}"
|
|
83
|
+
self._flush_interval_s = flush_interval_s
|
|
84
|
+
self._capacity_threshold = capacity_threshold
|
|
85
|
+
self._sdk_version = sdk_version
|
|
86
|
+
self._provider_name = provider_name
|
|
87
|
+
self._session = session or requests.Session()
|
|
88
|
+
# Only close the session we created ourselves; never an injected one.
|
|
89
|
+
self._owns_session = session is None
|
|
90
|
+
self._clock = clock
|
|
91
|
+
|
|
92
|
+
self._started = False
|
|
93
|
+
self._shutdown = False
|
|
94
|
+
self._next_out_of_band_flush_allowed = 0.0
|
|
95
|
+
self._state_lock = threading.Lock()
|
|
96
|
+
self._stop_event = threading.Event()
|
|
97
|
+
self._wake = threading.Event()
|
|
98
|
+
self._thread: threading.Thread | None = None
|
|
99
|
+
|
|
100
|
+
self._queue_lock = threading.Lock()
|
|
101
|
+
self._sealed: deque[DrainedBatch] = deque()
|
|
102
|
+
|
|
103
|
+
def start(self) -> None:
|
|
104
|
+
"""Starts periodic flushing. Idempotent."""
|
|
105
|
+
with self._state_lock:
|
|
106
|
+
if self._started or self._shutdown:
|
|
107
|
+
return
|
|
108
|
+
self._started = True
|
|
109
|
+
self._thread = threading.Thread(
|
|
110
|
+
target=self._run, name=_THREAD_NAME, daemon=True
|
|
111
|
+
)
|
|
112
|
+
self._thread.start()
|
|
113
|
+
log.debug(
|
|
114
|
+
"evaluation metrics flusher started (interval=%ss, url=%s)",
|
|
115
|
+
self._flush_interval_s,
|
|
116
|
+
self._metrics_url,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def enqueue_sealed_batch(self, batch: DrainedBatch | None) -> None:
|
|
120
|
+
"""Accepts a pre-drained batch for delivery ahead of the next periodic
|
|
121
|
+
tick, preserving per-version ordering. No-op for empty batches."""
|
|
122
|
+
if batch is None or batch.is_empty:
|
|
123
|
+
return
|
|
124
|
+
with self._queue_lock:
|
|
125
|
+
if len(self._sealed) >= _MAX_SEALED_BATCHES:
|
|
126
|
+
log.warning(
|
|
127
|
+
"sealed batch queue full (%d batches); dropping incoming batch "
|
|
128
|
+
"for version %s to prevent unbounded growth",
|
|
129
|
+
_MAX_SEALED_BATCHES,
|
|
130
|
+
batch.version,
|
|
131
|
+
)
|
|
132
|
+
return
|
|
133
|
+
self._sealed.append(batch)
|
|
134
|
+
|
|
135
|
+
def trigger_flush(self) -> None:
|
|
136
|
+
"""Wakes the worker so a just-enqueued sealed batch is picked up promptly."""
|
|
137
|
+
if self._shutdown:
|
|
138
|
+
return
|
|
139
|
+
self._wake.set()
|
|
140
|
+
|
|
141
|
+
def on_record(self) -> None:
|
|
142
|
+
"""Capacity callback invoked by the hook after each evaluation. Never
|
|
143
|
+
blocks the calling thread."""
|
|
144
|
+
if not self._started or self._shutdown:
|
|
145
|
+
return
|
|
146
|
+
if self._aggregator.size() < self._capacity_threshold:
|
|
147
|
+
return
|
|
148
|
+
if self._clock() < self._next_out_of_band_flush_allowed:
|
|
149
|
+
return
|
|
150
|
+
self._wake.set()
|
|
151
|
+
|
|
152
|
+
def shutdown(self) -> None:
|
|
153
|
+
"""Stops the worker and performs a final synchronous flush. Idempotent."""
|
|
154
|
+
with self._state_lock:
|
|
155
|
+
if self._shutdown:
|
|
156
|
+
return
|
|
157
|
+
self._shutdown = True
|
|
158
|
+
thread = self._thread
|
|
159
|
+
self._stop_event.set()
|
|
160
|
+
self._wake.set()
|
|
161
|
+
if thread is not None:
|
|
162
|
+
thread.join(timeout=_HTTP_TIMEOUT_S + 2.0)
|
|
163
|
+
# Final synchronous flush of anything still queued/accumulated.
|
|
164
|
+
self._flush_quietly()
|
|
165
|
+
# Release the connection pool we own once no more requests will be made.
|
|
166
|
+
if self._owns_session:
|
|
167
|
+
try:
|
|
168
|
+
self._session.close()
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
log.debug("metrics flusher session close failed: %r", exc)
|
|
171
|
+
|
|
172
|
+
def _run(self) -> None:
|
|
173
|
+
while not self._stop_event.is_set():
|
|
174
|
+
self._wake.wait(self._flush_interval_s)
|
|
175
|
+
self._wake.clear()
|
|
176
|
+
if self._stop_event.is_set():
|
|
177
|
+
break
|
|
178
|
+
self._flush_quietly()
|
|
179
|
+
|
|
180
|
+
def _flush_quietly(self) -> None:
|
|
181
|
+
try:
|
|
182
|
+
self._flush()
|
|
183
|
+
except Exception as exc:
|
|
184
|
+
log.warning("evaluation metrics flush failed: %r", exc)
|
|
185
|
+
|
|
186
|
+
def _flush(self) -> None:
|
|
187
|
+
# Flush sealed version-rotation batches first to preserve per-version
|
|
188
|
+
# ordering. A delivery failure requeues at the head and stops the cycle.
|
|
189
|
+
while True:
|
|
190
|
+
with self._queue_lock:
|
|
191
|
+
sealed = self._sealed.popleft() if self._sealed else None
|
|
192
|
+
if sealed is None:
|
|
193
|
+
break
|
|
194
|
+
delivered = False
|
|
195
|
+
try:
|
|
196
|
+
delivered = self._flush_batch(sealed)
|
|
197
|
+
finally:
|
|
198
|
+
if not delivered:
|
|
199
|
+
with self._queue_lock:
|
|
200
|
+
self._sealed.appendleft(sealed)
|
|
201
|
+
if not delivered:
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
# Then flush whatever has accumulated in the live aggregator.
|
|
205
|
+
live = self._aggregator.drain()
|
|
206
|
+
if live.is_empty:
|
|
207
|
+
return
|
|
208
|
+
delivered = False
|
|
209
|
+
try:
|
|
210
|
+
delivered = self._flush_batch(live)
|
|
211
|
+
finally:
|
|
212
|
+
if not delivered:
|
|
213
|
+
with self._queue_lock:
|
|
214
|
+
self._sealed.appendleft(live)
|
|
215
|
+
|
|
216
|
+
def _flush_batch(self, batch: DrainedBatch) -> bool:
|
|
217
|
+
"""POSTs ``batch``. Returns True if delivered (or non-retryable and
|
|
218
|
+
dropped); False if the caller should requeue it."""
|
|
219
|
+
try:
|
|
220
|
+
body = build_payload(
|
|
221
|
+
batch.evaluations,
|
|
222
|
+
batch.version,
|
|
223
|
+
self._sdk_version,
|
|
224
|
+
self._provider_name,
|
|
225
|
+
)
|
|
226
|
+
response = self._session.post(
|
|
227
|
+
self._metrics_url,
|
|
228
|
+
data=body,
|
|
229
|
+
headers={
|
|
230
|
+
"Content-Type": "application/json",
|
|
231
|
+
"Authorization": self._authorization_header,
|
|
232
|
+
},
|
|
233
|
+
timeout=_HTTP_TIMEOUT_S,
|
|
234
|
+
)
|
|
235
|
+
except Exception as exc:
|
|
236
|
+
# Any failure (network, serialization, or an injected session's own
|
|
237
|
+
# errors) must apply the cooldown so out-of-band flushes back off,
|
|
238
|
+
# mirroring the Java flusher's catch-all behavior.
|
|
239
|
+
log.warning("evaluation metrics flush error: %r", exc)
|
|
240
|
+
self._apply_failure_cooldown()
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
status = response.status_code
|
|
244
|
+
if 200 <= status < 300:
|
|
245
|
+
self._next_out_of_band_flush_allowed = 0.0
|
|
246
|
+
log.debug(
|
|
247
|
+
"evaluation metrics flush ok (status=%d, payload bytes=%d)",
|
|
248
|
+
status,
|
|
249
|
+
len(body),
|
|
250
|
+
)
|
|
251
|
+
return True
|
|
252
|
+
if status == 400:
|
|
253
|
+
log.warning(
|
|
254
|
+
"evaluation metrics payload rejected with HTTP 400; dropping "
|
|
255
|
+
"non-retryable batch (payload bytes=%d)",
|
|
256
|
+
len(body),
|
|
257
|
+
)
|
|
258
|
+
return True
|
|
259
|
+
log.warning(
|
|
260
|
+
"evaluation metrics flush returned HTTP %d; payload bytes=%d",
|
|
261
|
+
status,
|
|
262
|
+
len(body),
|
|
263
|
+
)
|
|
264
|
+
self._apply_failure_cooldown()
|
|
265
|
+
return False
|
|
266
|
+
|
|
267
|
+
def _apply_failure_cooldown(self) -> None:
|
|
268
|
+
self._next_out_of_band_flush_allowed = (
|
|
269
|
+
self._clock() + _FAILED_CAPACITY_RETRY_COOLDOWN_S
|
|
270
|
+
)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import enum
|
|
4
|
+
import logging
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
from openfeature.exception import ErrorCode
|
|
9
|
+
from openfeature.flag_evaluation import FlagEvaluationDetails, FlagValueType, Reason
|
|
10
|
+
from openfeature.hook import Hook, HookContext, HookHints
|
|
11
|
+
|
|
12
|
+
from ._metrics_aggregator import DynatraceMetricsAggregator
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
DEFAULT_VARIANT = "__default__"
|
|
17
|
+
DEFAULT_REASON = Reason.DEFAULT.value.lower()
|
|
18
|
+
UNKNOWN_REASON = Reason.UNKNOWN.value.lower()
|
|
19
|
+
ERROR_REASON = Reason.ERROR.value.lower()
|
|
20
|
+
_VERSION_METADATA_KEY = "version"
|
|
21
|
+
|
|
22
|
+
_TIMESTAMP_BUCKET_SEC = 10
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _reason_token(reason: str | Reason | None) -> str | None:
|
|
26
|
+
"""Returns the canonical (upper-case enum-name style) token for a reason,
|
|
27
|
+
accepting either a Reason enum or a plain string."""
|
|
28
|
+
if reason is None:
|
|
29
|
+
return None
|
|
30
|
+
if isinstance(reason, enum.Enum):
|
|
31
|
+
return str(reason.value)
|
|
32
|
+
return str(reason)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DynatraceMetricsHook(Hook):
|
|
36
|
+
"""Provider-owned ``finally_after`` hook that captures every flag evaluation
|
|
37
|
+
(success and error) into the Dynatrace evaluation-metrics aggregate map."""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
aggregator: DynatraceMetricsAggregator,
|
|
42
|
+
*,
|
|
43
|
+
clock: Callable[[], float] = time.time,
|
|
44
|
+
on_record: Callable[[], None] | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
self._aggregator = aggregator
|
|
47
|
+
self._clock = clock
|
|
48
|
+
self._on_record = on_record or (lambda: None)
|
|
49
|
+
|
|
50
|
+
def finally_after(
|
|
51
|
+
self,
|
|
52
|
+
hook_context: HookContext,
|
|
53
|
+
details: FlagEvaluationDetails[FlagValueType],
|
|
54
|
+
hints: HookHints,
|
|
55
|
+
) -> None:
|
|
56
|
+
flag_key = details.flag_key or hook_context.flag_key
|
|
57
|
+
if not flag_key or not flag_key.strip():
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
version = self._read_version(details)
|
|
61
|
+
raw_reason = details.reason
|
|
62
|
+
error_code = self._normalize_error_code(details.error_code)
|
|
63
|
+
self._aggregator.record(
|
|
64
|
+
flag_key,
|
|
65
|
+
self._normalize_variant(details.variant, raw_reason, error_code),
|
|
66
|
+
self._normalize_reason(raw_reason, error_code),
|
|
67
|
+
error_code,
|
|
68
|
+
self._current_timestamp_bucket_sec(),
|
|
69
|
+
version,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
self._on_record()
|
|
74
|
+
except Exception as exc:
|
|
75
|
+
log.warning("metrics hook on_record callback failed: %r", exc)
|
|
76
|
+
|
|
77
|
+
def _normalize_variant(
|
|
78
|
+
self, variant: str | None, reason: str | Reason | None, error_code: str | None
|
|
79
|
+
) -> str:
|
|
80
|
+
if (
|
|
81
|
+
error_code is not None
|
|
82
|
+
or self._is_default_reason(reason)
|
|
83
|
+
or not variant
|
|
84
|
+
or not variant.strip()
|
|
85
|
+
):
|
|
86
|
+
return DEFAULT_VARIANT
|
|
87
|
+
return variant
|
|
88
|
+
|
|
89
|
+
def _normalize_reason(
|
|
90
|
+
self, reason: str | Reason | None, error_code: str | None
|
|
91
|
+
) -> str:
|
|
92
|
+
if error_code is not None:
|
|
93
|
+
return ERROR_REASON
|
|
94
|
+
token = _reason_token(reason)
|
|
95
|
+
if token is None or not token.strip():
|
|
96
|
+
return UNKNOWN_REASON
|
|
97
|
+
return token.lower()
|
|
98
|
+
|
|
99
|
+
def _is_default_reason(self, reason: str | Reason | None) -> bool:
|
|
100
|
+
token = _reason_token(reason)
|
|
101
|
+
return token is not None and token.upper() == Reason.DEFAULT.value
|
|
102
|
+
|
|
103
|
+
def _normalize_error_code(self, error_code: ErrorCode | None) -> str | None:
|
|
104
|
+
if error_code is None:
|
|
105
|
+
return None
|
|
106
|
+
if isinstance(error_code, enum.Enum):
|
|
107
|
+
return error_code.name.lower()
|
|
108
|
+
return str(error_code).lower()
|
|
109
|
+
|
|
110
|
+
def _read_version(
|
|
111
|
+
self, details: FlagEvaluationDetails[FlagValueType]
|
|
112
|
+
) -> str | None:
|
|
113
|
+
metadata = details.flag_metadata
|
|
114
|
+
if not metadata:
|
|
115
|
+
return None
|
|
116
|
+
value = metadata.get(_VERSION_METADATA_KEY)
|
|
117
|
+
return value if isinstance(value, str) else None
|
|
118
|
+
|
|
119
|
+
def _current_timestamp_bucket_sec(self) -> int:
|
|
120
|
+
epoch_sec = int(self._clock())
|
|
121
|
+
return (epoch_sec // _TIMESTAMP_BUCKET_SEC) * _TIMESTAMP_BUCKET_SEC
|
|
@@ -10,17 +10,19 @@ _KEY_PATTERN = re.compile(
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
class DynatraceProviderOptions:
|
|
13
|
-
__slots__ = ("_cdn_url", "_key")
|
|
13
|
+
__slots__ = ("_cdn_url", "_key", "_metrics_url")
|
|
14
14
|
|
|
15
|
-
def __init__(self, key: str, cdn_url: str) -> None:
|
|
15
|
+
def __init__(self, key: str, cdn_url: str, metrics_url: str) -> None:
|
|
16
16
|
self._key = key
|
|
17
17
|
self._cdn_url = cdn_url
|
|
18
|
+
self._metrics_url = metrics_url
|
|
18
19
|
|
|
19
20
|
@classmethod
|
|
20
21
|
def from_sdk_key(
|
|
21
22
|
cls,
|
|
22
23
|
sdk_key: str,
|
|
23
24
|
cdn_base_url: str | None = None,
|
|
25
|
+
metrics_url: str | None = None,
|
|
24
26
|
) -> DynatraceProviderOptions:
|
|
25
27
|
if not sdk_key or not sdk_key.strip():
|
|
26
28
|
raise ValueError("sdk_key must not be null or blank")
|
|
@@ -42,7 +44,14 @@ class DynatraceProviderOptions:
|
|
|
42
44
|
else:
|
|
43
45
|
base = f"https://cdn.{geo}.fm.dynatrace.com/server/"
|
|
44
46
|
cdn_url = base + trimmed + ".json"
|
|
45
|
-
|
|
47
|
+
if metrics_url is not None:
|
|
48
|
+
metrics_url = metrics_url.strip()
|
|
49
|
+
if not metrics_url:
|
|
50
|
+
raise ValueError("metrics_url must not be blank")
|
|
51
|
+
resolved_metrics_url = metrics_url
|
|
52
|
+
else:
|
|
53
|
+
resolved_metrics_url = f"https://metrics.{geo}.fm.dynatrace.com/v1/metrics"
|
|
54
|
+
return cls(key=trimmed, cdn_url=cdn_url, metrics_url=resolved_metrics_url)
|
|
46
55
|
|
|
47
56
|
@property
|
|
48
57
|
def public_key(self) -> str:
|
|
@@ -53,3 +62,7 @@ class DynatraceProviderOptions:
|
|
|
53
62
|
@property
|
|
54
63
|
def cdn_url(self) -> str:
|
|
55
64
|
return self._cdn_url
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def metrics_url(self) -> str:
|
|
68
|
+
return self._metrics_url
|
|
@@ -3,6 +3,8 @@ from __future__ import annotations
|
|
|
3
3
|
import logging
|
|
4
4
|
import threading
|
|
5
5
|
from collections.abc import Mapping, Sequence
|
|
6
|
+
from importlib.metadata import PackageNotFoundError
|
|
7
|
+
from importlib.metadata import version as _pkg_version
|
|
6
8
|
|
|
7
9
|
import requests
|
|
8
10
|
|
|
@@ -16,6 +18,13 @@ from openfeature.provider import AbstractProvider, Metadata, ProviderStatus
|
|
|
16
18
|
|
|
17
19
|
from ._cdn import REQUEST_TIMEOUT_S as _REQUEST_TIMEOUT_S
|
|
18
20
|
from ._cdn import CdnFetcher
|
|
21
|
+
from ._metrics_aggregator import (
|
|
22
|
+
HARD_CAP_DISTINCT_FLAGS,
|
|
23
|
+
SOFT_CAP_DISTINCT_FLAGS,
|
|
24
|
+
DynatraceMetricsAggregator,
|
|
25
|
+
)
|
|
26
|
+
from ._metrics_flusher import EvaluationMetricsFlusher
|
|
27
|
+
from ._metrics_hook import DynatraceMetricsHook
|
|
19
28
|
from ._polling import PollingManager
|
|
20
29
|
from .options import DynatraceProviderOptions
|
|
21
30
|
|
|
@@ -24,27 +33,43 @@ log = logging.getLogger(__name__)
|
|
|
24
33
|
_PROVIDER_NAME = "dynatrace"
|
|
25
34
|
_POLL_INTERVAL_S: float = 10.0
|
|
26
35
|
_GRACE_PERIOD_S: float = 60.0
|
|
36
|
+
_METRICS_FLUSH_INTERVAL_S: float = 30.0
|
|
37
|
+
_VERSION_METADATA_KEY = "version"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _resolve_sdk_version() -> str:
|
|
41
|
+
try:
|
|
42
|
+
return _pkg_version("dynatrace-openfeature-provider-python")
|
|
43
|
+
except PackageNotFoundError:
|
|
44
|
+
return "0.0.0"
|
|
27
45
|
|
|
28
46
|
|
|
29
47
|
class DynatraceProvider(AbstractProvider):
|
|
30
|
-
def __init__(
|
|
48
|
+
def __init__( # noqa: PLR0913 - public constructor with optional injectable seams
|
|
31
49
|
self,
|
|
32
50
|
sdk_key: str,
|
|
33
51
|
*,
|
|
34
52
|
cdn_base_url: str | None = None,
|
|
53
|
+
metrics_url: str | None = None,
|
|
35
54
|
flagd_core: FlagdCore | None = None,
|
|
36
55
|
fetcher: CdnFetcher | None = None,
|
|
56
|
+
metrics_flusher: EvaluationMetricsFlusher | None = None,
|
|
37
57
|
poll_interval_s: float = _POLL_INTERVAL_S,
|
|
38
58
|
grace_period_s: float = _GRACE_PERIOD_S,
|
|
59
|
+
metrics_flush_interval_s: float = _METRICS_FLUSH_INTERVAL_S,
|
|
39
60
|
) -> None:
|
|
40
61
|
options = DynatraceProviderOptions.from_sdk_key(
|
|
41
|
-
sdk_key, cdn_base_url=cdn_base_url
|
|
62
|
+
sdk_key, cdn_base_url=cdn_base_url, metrics_url=metrics_url
|
|
42
63
|
)
|
|
43
64
|
if fetcher is None and poll_interval_s <= _REQUEST_TIMEOUT_S:
|
|
44
65
|
raise ValueError(
|
|
45
66
|
f"poll_interval_s ({poll_interval_s}s) must be greater than the "
|
|
46
67
|
f"request timeout ({_REQUEST_TIMEOUT_S}s)"
|
|
47
68
|
)
|
|
69
|
+
if metrics_flush_interval_s <= 0:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"metrics_flush_interval_s ({metrics_flush_interval_s}s) must be positive"
|
|
72
|
+
)
|
|
48
73
|
self._options = options
|
|
49
74
|
self._flagd_core = flagd_core or FlagdCore()
|
|
50
75
|
self._fetcher = fetcher or CdnFetcher(options)
|
|
@@ -57,11 +82,25 @@ class DynatraceProvider(AbstractProvider):
|
|
|
57
82
|
# bumped by initialize/shutdown so a slow init can detect it was superseded
|
|
58
83
|
self._generation = 0
|
|
59
84
|
|
|
85
|
+
self._metrics_aggregator = DynatraceMetricsAggregator(HARD_CAP_DISTINCT_FLAGS)
|
|
86
|
+
self._metrics_flusher = metrics_flusher or EvaluationMetricsFlusher(
|
|
87
|
+
self._metrics_aggregator,
|
|
88
|
+
sdk_key=sdk_key.strip(),
|
|
89
|
+
metrics_url=options.metrics_url,
|
|
90
|
+
flush_interval_s=metrics_flush_interval_s,
|
|
91
|
+
capacity_threshold=SOFT_CAP_DISTINCT_FLAGS,
|
|
92
|
+
sdk_version=_resolve_sdk_version(),
|
|
93
|
+
provider_name=_PROVIDER_NAME,
|
|
94
|
+
)
|
|
95
|
+
self._metrics_hook = DynatraceMetricsHook(
|
|
96
|
+
self._metrics_aggregator, on_record=self._metrics_flusher.on_record
|
|
97
|
+
)
|
|
98
|
+
|
|
60
99
|
def get_metadata(self) -> Metadata:
|
|
61
100
|
return Metadata(name=_PROVIDER_NAME)
|
|
62
101
|
|
|
63
102
|
def get_provider_hooks(self) -> list[Hook]:
|
|
64
|
-
return []
|
|
103
|
+
return [self._metrics_hook]
|
|
65
104
|
|
|
66
105
|
def initialize(self, evaluation_context: EvaluationContext | None = None) -> None:
|
|
67
106
|
log.info("initializing Dynatrace provider (key=%s)", self._options.public_key)
|
|
@@ -88,6 +127,10 @@ class DynatraceProvider(AbstractProvider):
|
|
|
88
127
|
except ParseError as exc:
|
|
89
128
|
raise GeneralError(f"initial CDN config is invalid: {exc}") from exc
|
|
90
129
|
|
|
130
|
+
# Set the aggregator version eagerly so it is authoritative before any
|
|
131
|
+
# evaluation is recorded.
|
|
132
|
+
self._update_metrics_version_from_flag_set()
|
|
133
|
+
|
|
91
134
|
with self._lock:
|
|
92
135
|
if self._generation != generation:
|
|
93
136
|
# A concurrent shutdown() or re-initialize() superseded us while
|
|
@@ -110,6 +153,7 @@ class DynatraceProvider(AbstractProvider):
|
|
|
110
153
|
interval_s=self._poll_interval_s,
|
|
111
154
|
)
|
|
112
155
|
self._poller.start()
|
|
156
|
+
self._metrics_flusher.start()
|
|
113
157
|
log.info("Dynatrace provider initialized successfully")
|
|
114
158
|
|
|
115
159
|
def shutdown(self) -> None:
|
|
@@ -117,14 +161,26 @@ class DynatraceProvider(AbstractProvider):
|
|
|
117
161
|
# Always bump the generation, even when already idle, so an
|
|
118
162
|
# in-flight initialize() detects it was superseded and aborts.
|
|
119
163
|
self._generation += 1
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
self.
|
|
127
|
-
self._poller
|
|
164
|
+
already_idle = (
|
|
165
|
+
self._state == ProviderStatus.NOT_READY and self._poller is None
|
|
166
|
+
)
|
|
167
|
+
if not already_idle:
|
|
168
|
+
log.info("shutting down Dynatrace provider")
|
|
169
|
+
self._state = ProviderStatus.NOT_READY
|
|
170
|
+
self._cancel_grace_timer()
|
|
171
|
+
if self._poller is not None:
|
|
172
|
+
self._poller.stop()
|
|
173
|
+
self._poller = None
|
|
174
|
+
# Always release the flusher (and the session it owns), even when the
|
|
175
|
+
# provider never finished initializing: the flusher's session is created
|
|
176
|
+
# in __init__, so an early return here would otherwise leak it.
|
|
177
|
+
# flusher.shutdown() is idempotent and safe when never started.
|
|
178
|
+
try:
|
|
179
|
+
self._metrics_flusher.shutdown()
|
|
180
|
+
except Exception as exc:
|
|
181
|
+
log.warning("metrics flusher shutdown failed: %r", exc)
|
|
182
|
+
if already_idle:
|
|
183
|
+
return
|
|
128
184
|
super().shutdown()
|
|
129
185
|
log.info("Dynatrace provider shut down")
|
|
130
186
|
|
|
@@ -179,7 +235,20 @@ class DynatraceProvider(AbstractProvider):
|
|
|
179
235
|
)
|
|
180
236
|
|
|
181
237
|
def _store_flags(self, body: str) -> list[str]:
|
|
182
|
-
|
|
238
|
+
# Seal the old-version batch and enqueue/trigger its flush BEFORE applying
|
|
239
|
+
# the new config and bumping the version, so pre-rotation counts are
|
|
240
|
+
# flushed under the old version.
|
|
241
|
+
sealed = self._metrics_aggregator.drain()
|
|
242
|
+
self._metrics_flusher.enqueue_sealed_batch(sealed)
|
|
243
|
+
self._metrics_flusher.trigger_flush()
|
|
244
|
+
changed = self._flagd_core.set_flags_and_get_changed_keys(body)
|
|
245
|
+
self._update_metrics_version_from_flag_set()
|
|
246
|
+
return changed
|
|
247
|
+
|
|
248
|
+
def _update_metrics_version_from_flag_set(self) -> None:
|
|
249
|
+
version = self._flagd_core.get_flag_set_metadata().get(_VERSION_METADATA_KEY)
|
|
250
|
+
if isinstance(version, str) and version.strip():
|
|
251
|
+
self._metrics_aggregator.set_version(version)
|
|
183
252
|
|
|
184
253
|
def _on_fetch_success(self) -> None:
|
|
185
254
|
with self._lock:
|
{dynatrace_openfeature_provider_python-0.0.2 → dynatrace_openfeature_provider_python-0.0.4}/LICENSE
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|