dynatrace-openfeature-provider-python 0.2.0__tar.gz → 0.3.0__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 (17) hide show
  1. dynatrace_openfeature_provider_python-0.3.0/PKG-INFO +91 -0
  2. dynatrace_openfeature_provider_python-0.3.0/README.md +72 -0
  3. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/pyproject.toml +22 -6
  4. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/pyproject.toml.orig +11 -6
  5. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_cdn.py +101 -24
  6. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_polling.py +28 -18
  7. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_retry.py +17 -14
  8. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/provider.py +83 -37
  9. dynatrace_openfeature_provider_python-0.2.0/PKG-INFO +0 -96
  10. dynatrace_openfeature_provider_python-0.2.0/README.md +0 -78
  11. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/LICENSE +0 -0
  12. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/__init__.py +0 -0
  13. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_metrics_aggregator.py +0 -0
  14. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_metrics_flusher.py +0 -0
  15. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/_metrics_hook.py +0 -0
  16. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/options.py +0 -0
  17. {dynatrace_openfeature_provider_python-0.2.0 → dynatrace_openfeature_provider_python-0.3.0}/src/dynatrace/openfeature/py.typed +0 -0
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: dynatrace-openfeature-provider-python
3
+ Version: 0.3.0
4
+ Summary: The official Dynatrace OpenFeature provider for Python
5
+ Keywords: openfeature,dynatrace,feature-flags,feature-management
6
+ Author: Dynatrace
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Requires-Dist: openfeature-sdk>=0.8.2
13
+ Requires-Dist: openfeature-flagd-core>=2.0.0,<3.0.0
14
+ Requires-Dist: requests>=2.27.0
15
+ Requires-Dist: urllib3>=2.3.0
16
+ Requires-Python: >=3.10
17
+ Project-URL: Homepage, https://github.com/Dynatrace/openfeature-provider-python
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Dynatrace OpenFeature Provider for Python
21
+
22
+ The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
23
+
24
+ The provider evaluates flags in-process: on initialization it fetches your flag configuration from the Dynatrace CDN and refreshes it in the background, so evaluations are local and do not make a network call.
25
+
26
+ > **Status:** Early alpha — not yet ready for production use.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install dynatrace-openfeature-provider-python
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```python
37
+ from openfeature import api
38
+ from openfeature.evaluation_context import EvaluationContext
39
+
40
+ from dynatrace.openfeature import DynatraceProvider
41
+
42
+ api.set_provider(DynatraceProvider("dt01.server_us_<key>"))
43
+
44
+ client = api.get_client()
45
+ ctx = EvaluationContext(targeting_key="user-123")
46
+ enabled = client.get_boolean_value("my-flag", False, ctx)
47
+
48
+ # On shutdown:
49
+ api.shutdown()
50
+ ```
51
+
52
+ Once the provider is registered, all flag evaluation goes through the OpenFeature API. See the
53
+ [OpenFeature Python SDK documentation](https://openfeature.dev/docs/reference/technologies/server/python/)
54
+ for evaluation contexts, hooks, events, and the rest of the SDK surface.
55
+
56
+ ## Configuration
57
+
58
+ Pass options as keyword arguments to `DynatraceProvider`:
59
+
60
+ ```python
61
+ api.set_provider(
62
+ DynatraceProvider(
63
+ sdk_key,
64
+ config_origin="https://cdn.eu.fm.dynatracelabs.com",
65
+ metrics_origin="https://metrics.eu.fm.dynatracelabs.com",
66
+ )
67
+ )
68
+ ```
69
+
70
+ | Option | Type | Default | Description |
71
+ | --- | --- | --- | --- |
72
+ | `config_origin` | `str` | derived from SDK key | Override the flag configuration origin. |
73
+ | `metrics_origin` | `str` | derived from SDK key | Override the evaluation metrics ingest origin. |
74
+
75
+ ## Running the e2e tests
76
+
77
+ The shared [provider test harness](https://github.com/Dynatrace/fm-provider-test-harness) gherkin suite runs against its mock server in a container, so Docker is required:
78
+
79
+ ```bash
80
+ uv run poe e2e
81
+ ```
82
+
83
+ This initializes the `fm-provider-test-harness` submodule and runs the suite with pytest-bdd. Set `SKIP_HARNESS_UPDATE=1` to keep a local harness checkout, and `MOCKSERVER_IMAGE` to use a locally built mock server image.
84
+
85
+ ## Contributing
86
+
87
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
88
+
89
+ ## License
90
+
91
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,72 @@
1
+ # Dynatrace OpenFeature Provider for Python
2
+
3
+ The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
4
+
5
+ The provider evaluates flags in-process: on initialization it fetches your flag configuration from the Dynatrace CDN and refreshes it in the background, so evaluations are local and do not make a network call.
6
+
7
+ > **Status:** Early alpha — not yet ready for production use.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install dynatrace-openfeature-provider-python
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from openfeature import api
19
+ from openfeature.evaluation_context import EvaluationContext
20
+
21
+ from dynatrace.openfeature import DynatraceProvider
22
+
23
+ api.set_provider(DynatraceProvider("dt01.server_us_<key>"))
24
+
25
+ client = api.get_client()
26
+ ctx = EvaluationContext(targeting_key="user-123")
27
+ enabled = client.get_boolean_value("my-flag", False, ctx)
28
+
29
+ # On shutdown:
30
+ api.shutdown()
31
+ ```
32
+
33
+ Once the provider is registered, all flag evaluation goes through the OpenFeature API. See the
34
+ [OpenFeature Python SDK documentation](https://openfeature.dev/docs/reference/technologies/server/python/)
35
+ for evaluation contexts, hooks, events, and the rest of the SDK surface.
36
+
37
+ ## Configuration
38
+
39
+ Pass options as keyword arguments to `DynatraceProvider`:
40
+
41
+ ```python
42
+ api.set_provider(
43
+ DynatraceProvider(
44
+ sdk_key,
45
+ config_origin="https://cdn.eu.fm.dynatracelabs.com",
46
+ metrics_origin="https://metrics.eu.fm.dynatracelabs.com",
47
+ )
48
+ )
49
+ ```
50
+
51
+ | Option | Type | Default | Description |
52
+ | --- | --- | --- | --- |
53
+ | `config_origin` | `str` | derived from SDK key | Override the flag configuration origin. |
54
+ | `metrics_origin` | `str` | derived from SDK key | Override the evaluation metrics ingest origin. |
55
+
56
+ ## Running the e2e tests
57
+
58
+ The shared [provider test harness](https://github.com/Dynatrace/fm-provider-test-harness) gherkin suite runs against its mock server in a container, so Docker is required:
59
+
60
+ ```bash
61
+ uv run poe e2e
62
+ ```
63
+
64
+ This initializes the `fm-provider-test-harness` submodule and runs the suite with pytest-bdd. Set `SKIP_HARNESS_UPDATE=1` to keep a local harness checkout, and `MOCKSERVER_IMAGE` to use a locally built mock server image.
65
+
66
+ ## Contributing
67
+
68
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
69
+
70
+ ## License
71
+
72
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "dynatrace-openfeature-provider-python"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "The official Dynatrace OpenFeature provider for Python"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -22,8 +22,9 @@ keywords = [
22
22
  ]
23
23
  dependencies = [
24
24
  "openfeature-sdk>=0.8.2",
25
- "openfeature-flagd-core>=1.0.0,<2.0.0",
25
+ "openfeature-flagd-core>=2.0.0,<3.0.0",
26
26
  "requests>=2.27.0",
27
+ "urllib3>=2.3.0",
27
28
  ]
28
29
  requires-python = ">=3.10"
29
30
 
@@ -43,6 +44,8 @@ dev = [
43
44
  "pre-commit>=4.0.0",
44
45
  "ruff>=0.15.13",
45
46
  "types-requests>=2.32.0,<3.0.0",
47
+ "pytest-bdd>=8.1.0,<9.0.0",
48
+ "testcontainers>=4.13.0,<5.0.0",
46
49
  ]
47
50
 
48
51
  [tool.uv.build-backend]
@@ -54,8 +57,14 @@ namespace = true
54
57
  omit = ["tests/**"]
55
58
 
56
59
  [tool.mypy]
57
- mypy_path = "src"
58
- files = "src"
60
+ mypy_path = [
61
+ "src",
62
+ "tests/e2e",
63
+ ]
64
+ files = [
65
+ "src",
66
+ "tests/e2e",
67
+ ]
59
68
  python_version = "3.10"
60
69
  namespace_packages = true
61
70
  explicit_package_bases = true
@@ -147,8 +156,8 @@ keep-runtime-typing = true
147
156
  strict = true
148
157
 
149
158
  [tool.poe.tasks]
150
- test = "pytest tests"
151
- test-cov = "coverage run -m pytest tests"
159
+ test = "pytest tests --ignore=tests/e2e"
160
+ test-cov = "coverage run -m pytest tests --ignore=tests/e2e"
152
161
  cov-report = "coverage xml"
153
162
  cov = [
154
163
  "test-cov",
@@ -157,3 +166,10 @@ cov = [
157
166
  mypy = "mypy"
158
167
  lint = "ruff check src tests"
159
168
  fmt = "ruff format src tests"
169
+
170
+ [tool.poe.tasks.e2e]
171
+ sequence = [
172
+ { shell = '[ -n "$SKIP_HARNESS_UPDATE" ] || git submodule update --init fm-provider-test-harness' },
173
+ "pytest tests/e2e",
174
+ ]
175
+ default_item_type = "cmd"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "dynatrace-openfeature-provider-python"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "The official Dynatrace OpenFeature provider for Python"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "Dynatrace" }]
@@ -18,8 +18,10 @@ classifiers = [
18
18
  keywords = ["openfeature", "dynatrace", "feature-flags", "feature-management"]
19
19
  dependencies = [
20
20
  "openfeature-sdk>=0.8.2",
21
- "openfeature-flagd-core>=1.0.0,<2.0.0",
21
+ "openfeature-flagd-core>=2.0.0,<3.0.0",
22
22
  "requests>=2.27.0",
23
+ # 2.3 added HTTPResponse.shutdown, which _cdn uses to enforce the fetch deadline
24
+ "urllib3>=2.3.0",
23
25
  ]
24
26
  requires-python = ">=3.10"
25
27
 
@@ -36,6 +38,8 @@ dev = [
36
38
  "pre-commit>=4.0.0",
37
39
  "ruff>=0.15.13",
38
40
  "types-requests>=2.32.0,<3.0.0",
41
+ "pytest-bdd>=8.1.0,<9.0.0",
42
+ "testcontainers>=4.13.0,<5.0.0",
39
43
  ]
40
44
 
41
45
  [tool.uv.build-backend]
@@ -47,8 +51,8 @@ namespace = true
47
51
  omit = ["tests/**"]
48
52
 
49
53
  [tool.mypy]
50
- mypy_path = "src"
51
- files = "src"
54
+ mypy_path = ["src", "tests/e2e"]
55
+ files = ["src", "tests/e2e"]
52
56
  python_version = "3.10"
53
57
  namespace_packages = true
54
58
  explicit_package_bases = true
@@ -100,10 +104,11 @@ keep-runtime-typing = true
100
104
  strict = true
101
105
 
102
106
  [tool.poe.tasks]
103
- test = "pytest tests"
104
- test-cov = "coverage run -m pytest tests"
107
+ test = "pytest tests --ignore=tests/e2e"
108
+ test-cov = "coverage run -m pytest tests --ignore=tests/e2e"
105
109
  cov-report = "coverage xml"
106
110
  cov = ["test-cov", "cov-report"]
107
111
  mypy = "mypy"
108
112
  lint = "ruff check src tests"
109
113
  fmt = "ruff format src tests"
114
+ e2e = { sequence = [{ shell = "[ -n \"$SKIP_HARNESS_UPDATE\" ] || git submodule update --init fm-provider-test-harness" }, "pytest tests/e2e"], default_item_type = "cmd" }
@@ -9,14 +9,26 @@ from datetime import datetime
9
9
  from email.utils import parsedate_to_datetime
10
10
 
11
11
  import requests
12
-
13
- from ._retry import RetryStrategy, default_should_retry_status
12
+ from urllib3.util import Timeout as Urllib3Timeout
13
+
14
+ from ._retry import (
15
+ MAX_ATTEMPTS,
16
+ MAX_BACKOFF_S,
17
+ RetryStrategy,
18
+ default_should_retry_status,
19
+ )
14
20
  from .options import DynatraceProviderOptions
15
21
 
16
22
  log = logging.getLogger(__name__)
17
23
 
18
- REQUEST_TIMEOUT_S: float = 5.0
24
+ REQUEST_TIMEOUT_S: float = 4.0
25
+
26
+ #: worst-case wall time of a fetch (all attempts + backoff); stays under the shortest poll interval so two polls never overlap (providers.md 2.1); asserted in DynatraceProvider
27
+ MAX_FETCH_DURATION_S: float = REQUEST_TIMEOUT_S * MAX_ATTEMPTS + MAX_BACKOFF_S
28
+
19
29
  _DEFAULT_RETRY_AFTER_MS: float = 60_000.0
30
+ _BODY_CHUNK_BYTES = 64 * 1024
31
+ _BUDGET_EXCEEDED = "response body exceeded the fetch budget"
20
32
 
21
33
 
22
34
  @dataclass
@@ -71,10 +83,29 @@ class CdnFetcher:
71
83
  t = now if now is not None else self._clock()
72
84
  return t < self._rate_limited_until
73
85
 
86
+ def invalidate_cache(self) -> None:
87
+ """Forget the cached validators.
88
+
89
+ They are stored as soon as a 2xx arrives, before the caller applies the
90
+ body. If applying it fails they describe a config we never loaded, and
91
+ the next conditional request would come back 304 over an empty store.
92
+ """
93
+ with self._fetch_lock:
94
+ self._cache = _CacheState()
95
+
74
96
  def fetch(self, cancel: threading.Event | None = None) -> FetchResult:
97
+ """Fetch the config, or skip without making a request.
98
+
99
+ A skip (fetch in flight, section 2.1.1; or an open Retry-After window,
100
+ section 2.3) is neither success nor failure and must not be reported as
101
+ either. PollingManager serialises its own fetches, so the in-flight
102
+ guard is for callers outside it -- initialize() fetches on the caller's
103
+ thread -- and it keeps a conditional request from storing an ETag and a
104
+ Last-Modified that came from different responses.
105
+ """
75
106
  if self.is_rate_limited():
76
107
  log.debug("rate limited; skipping fetch")
77
- return FetchResult(429, None, None, None)
108
+ return FetchResult(0, None, None, None, skipped=True)
78
109
  if not self._fetch_lock.acquire(blocking=False):
79
110
  log.debug("fetch already in progress; skipping")
80
111
  return FetchResult(0, None, None, None, skipped=True)
@@ -96,28 +127,34 @@ class CdnFetcher:
96
127
  if cache.last_modified_header is not None:
97
128
  headers["If-Modified-Since"] = cache.last_modified_header
98
129
 
99
- try:
100
- resp = self._session.get(
101
- self._url,
102
- headers=headers,
103
- timeout=REQUEST_TIMEOUT_S,
104
- )
105
- except requests.RequestException:
106
- raise
107
-
108
- if resp.status_code == 304:
109
- return FetchResult(304, None, cache.etag, cache.last_modified_header)
130
+ deadline = time.monotonic() + REQUEST_TIMEOUT_S
131
+ # total bounds connect + time-to-first-byte as one budget (a tuple would give each phase the full timeout)
132
+ timeout = Urllib3Timeout(
133
+ connect=REQUEST_TIMEOUT_S,
134
+ read=REQUEST_TIMEOUT_S,
135
+ total=REQUEST_TIMEOUT_S,
136
+ )
137
+ with self._session.get(
138
+ self._url,
139
+ headers=headers,
140
+ timeout=timeout, # type: ignore[arg-type]
141
+ # each hop gets a fresh timeout, so following a chain would blow the budget (Java never follows one either)
142
+ allow_redirects=False,
143
+ stream=True,
144
+ ) as resp:
145
+ if resp.status_code == 304:
146
+ return FetchResult(304, None, cache.etag, cache.last_modified_header)
110
147
 
111
- if resp.status_code == 429:
112
- retry_after = resp.headers.get("Retry-After")
113
- delay_ms = _parse_retry_after_ms(retry_after, self._clock())
114
- self._rate_limited_until = self._clock() + delay_ms / 1000.0
115
- log.warning("rate limited (429); pausing fetches for %.0fms", delay_ms)
116
- return FetchResult(429, None, None, None)
148
+ if resp.status_code == 429:
149
+ retry_after = resp.headers.get("Retry-After")
150
+ delay_ms = _parse_retry_after_ms(retry_after, self._clock())
151
+ self._rate_limited_until = self._clock() + delay_ms / 1000.0
152
+ log.warning("rate limited (429); pausing fetches for %.0fms", delay_ms)
153
+ return FetchResult(429, None, None, None)
117
154
 
118
- new_etag = resp.headers.get("ETag")
119
- new_last_modified = resp.headers.get("Last-Modified")
120
- body = resp.text
155
+ new_etag = resp.headers.get("ETag")
156
+ new_last_modified = resp.headers.get("Last-Modified")
157
+ body = _read_body_within(resp, deadline)
121
158
 
122
159
  if resp.status_code >= 200 and resp.status_code < 300:
123
160
  new_lm_at = _parse_http_date(new_last_modified)
@@ -142,6 +179,46 @@ class CdnFetcher:
142
179
  return FetchResult(resp.status_code, body, new_etag, new_last_modified)
143
180
 
144
181
 
182
+ def _read_body_within(resp: requests.Response, deadline: float) -> str:
183
+ """Read the response body, giving up once ``deadline`` passes.
184
+
185
+ No timeout in the stack bounds this: they all measure inactivity between
186
+ socket reads, so a server trickling bytes resets the clock on every one and
187
+ MAX_FETCH_DURATION_S stops being a bound. Checking the clock between chunks
188
+ is not enough either, since a read blocks until its chunk is full, so the
189
+ deadline interrupts the read itself via HTTPResponse.shutdown.
190
+ """
191
+ raw = resp.raw
192
+ expired = threading.Event()
193
+
194
+ def _abort() -> None:
195
+ expired.set()
196
+ try:
197
+ raw.shutdown()
198
+ except Exception: # connection already released, or nothing to interrupt
199
+ log.debug("could not shut down the response socket", exc_info=True)
200
+
201
+ watchdog = threading.Timer(max(0.0, deadline - time.monotonic()), _abort)
202
+ watchdog.daemon = True
203
+ watchdog.start()
204
+ chunks: list[bytes] = []
205
+ try:
206
+ chunks.extend(resp.iter_content(_BODY_CHUNK_BYTES))
207
+ except (requests.RequestException, OSError):
208
+ # A torn-down socket surfaces as a read error.
209
+ if expired.is_set():
210
+ raise requests.Timeout(_BUDGET_EXCEEDED) from None
211
+ raise
212
+ finally:
213
+ watchdog.cancel()
214
+
215
+ if expired.is_set():
216
+ # Arrived, just not in time.
217
+ raise requests.Timeout(_BUDGET_EXCEEDED)
218
+
219
+ return b"".join(chunks).decode(resp.encoding or "utf-8", errors="replace")
220
+
221
+
145
222
  def _parse_http_date(value: str | None) -> datetime | None:
146
223
  if not value:
147
224
  return None
@@ -15,9 +15,11 @@ class PollingManager:
15
15
  Polls on a fixed-rate schedule anchored to request initiation, not completion.
16
16
 
17
17
  A ticker thread fires every interval_s regardless of how long the previous
18
- fetch took. When the ticker fires it cancels any in-flight poll and starts a
19
- fresh one on a worker thread. Cancelled polls are silent: no emitFailure is
20
- called.
18
+ fetch took. At most one fetch is in flight at a time (providers.md section
19
+ 2.1.1): a tick firing during a poll is skipped and emits nothing, so it does
20
+ not reset the staleness grace timer. The section 2.1 bound should keep that
21
+ from happening at all, but the bound is a design invariant rather than
22
+ something the runtime enforces, so the case is handled.
21
23
  """
22
24
 
23
25
  def __init__(
@@ -36,7 +38,8 @@ class PollingManager:
36
38
  self._emit_failure = emit_failure
37
39
  self._interval_s = interval_s
38
40
  self._stop_event = threading.Event()
39
- self._current_cancel: threading.Event | None = None
41
+ self._in_flight = False
42
+ self._in_flight_lock = threading.Lock()
40
43
  self._ticker_thread: threading.Thread | None = None
41
44
 
42
45
  def start(self) -> None:
@@ -51,12 +54,11 @@ class PollingManager:
51
54
  self._ticker_thread.start()
52
55
 
53
56
  def stop(self) -> None:
57
+ # stop event doubles as the fetch cancel signal, so an in-flight poll abandons its backoff
54
58
  self._stop_event.set()
59
+ # leave _in_flight alone: only _run_poll's finally clears it; clearing here would let a restart double up
55
60
  if self._ticker_thread is not None:
56
61
  self._ticker_thread.join(timeout=2.0)
57
- cancel = self._current_cancel
58
- if cancel is not None:
59
- cancel.set()
60
62
 
61
63
  def _ticker_loop(self) -> None:
62
64
  next_tick = time.monotonic() + self._interval_s
@@ -73,28 +75,36 @@ class PollingManager:
73
75
  def _dispatch(self) -> None:
74
76
  if self._stop_event.is_set():
75
77
  return
76
- prev = self._current_cancel
77
- if prev is not None:
78
- prev.set()
79
- cancel = threading.Event()
80
- self._current_cancel = cancel
78
+ with self._in_flight_lock:
79
+ if self._in_flight:
80
+ # Neither failed nor succeeded: the tick learned nothing.
81
+ log.debug("poll tick skipped: a fetch is already in flight")
82
+ return
83
+ self._in_flight = True
81
84
  threading.Thread(
82
- target=self._poll,
83
- args=(cancel,),
85
+ target=self._run_poll,
84
86
  name="dt-provider-poller",
85
87
  daemon=True,
86
88
  ).start()
87
89
 
88
- def _poll(self, cancel: threading.Event) -> None:
90
+ def _run_poll(self) -> None:
91
+ try:
92
+ self._poll()
93
+ finally:
94
+ with self._in_flight_lock:
95
+ self._in_flight = False
96
+
97
+ def _poll(self) -> None:
98
+ cancel = self._stop_event
89
99
  try:
90
100
  result = self._fetch_flags(cancel)
91
101
 
92
102
  if cancel.is_set():
93
- log.debug("poll cancelled after fetch returned; discarding result")
103
+ log.debug("provider stopped during fetch; discarding result")
94
104
  return
95
105
 
96
106
  if result.skipped:
97
- log.debug("fetch skipped (lock contention); retaining cached state")
107
+ log.debug("fetch skipped (single-flight); emitting nothing")
98
108
  return
99
109
 
100
110
  if result.is_not_modified:
@@ -124,7 +134,7 @@ class PollingManager:
124
134
 
125
135
  except Exception as exc:
126
136
  if cancel.is_set():
127
- log.debug("poll cancelled")
137
+ log.debug("poll abandoned during shutdown")
128
138
  return
129
139
  log.warning("poll failed: %s", type(exc).__name__)
130
140
  self._emit_failure(type(exc).__name__)
@@ -11,10 +11,15 @@ log = logging.getLogger(__name__)
11
11
 
12
12
  T = typing.TypeVar("T")
13
13
 
14
- _MAX_ATTEMPTS = 5
15
- _BASE_DELAY_MS = 100.0
16
- _MULTIPLIER = 2.0
17
- _MAX_JITTER_FACTOR = 0.20
14
+ # two attempts so a fetch stays under the shortest poll interval (providers.md 2.1): 4s + 0.12s + 4s < 10s
15
+ MAX_ATTEMPTS = 2
16
+ BASE_DELAY_MS = 100.0
17
+ MAX_JITTER_FACTOR = 0.20
18
+
19
+ #: worst-case backoff within one fetch; derives the fetch-duration bound in :mod:`._cdn`
20
+ MAX_BACKOFF_S = (
21
+ (MAX_ATTEMPTS - 1) * BASE_DELAY_MS * (1.0 + MAX_JITTER_FACTOR)
22
+ ) / 1000.0
18
23
 
19
24
 
20
25
  class RetryStrategy:
@@ -30,9 +35,8 @@ class RetryStrategy:
30
35
  ) -> T:
31
36
  last_exception: BaseException | None = None
32
37
  last_result: T | None = None
33
- delay_ms = _BASE_DELAY_MS
34
38
 
35
- for attempt in range(1, _MAX_ATTEMPTS + 1):
39
+ for attempt in range(1, MAX_ATTEMPTS + 1):
36
40
  try:
37
41
  result = fn()
38
42
  last_result = result
@@ -41,18 +45,18 @@ class RetryStrategy:
41
45
  log.warning(
42
46
  "attempt %d/%d returned retryable result; retrying",
43
47
  attempt,
44
- _MAX_ATTEMPTS,
48
+ MAX_ATTEMPTS,
45
49
  )
46
50
  except retryable_exceptions as exc:
47
51
  last_exception = exc
48
52
  log.warning(
49
- "attempt %d/%d failed: %s; retrying", attempt, _MAX_ATTEMPTS, exc
53
+ "attempt %d/%d failed: %s; retrying", attempt, MAX_ATTEMPTS, exc
50
54
  )
51
55
  except Exception as exc:
52
56
  raise OSError("unexpected error during fetch") from exc
53
57
 
54
- if attempt < _MAX_ATTEMPTS:
55
- delay_ms = self._backoff(delay_ms, cancel)
58
+ if attempt < MAX_ATTEMPTS:
59
+ self._backoff(cancel)
56
60
  if cancel is not None and cancel.is_set():
57
61
  break
58
62
 
@@ -62,14 +66,13 @@ class RetryStrategy:
62
66
  raise last_exception
63
67
  raise OSError("all retry attempts failed")
64
68
 
65
- def _backoff(self, delay_ms: float, cancel: threading.Event | None) -> float:
66
- jitter = delay_ms * self._rng.random() * _MAX_JITTER_FACTOR
67
- sleep_ms = delay_ms + jitter
69
+ def _backoff(self, cancel: threading.Event | None) -> None:
70
+ jitter = BASE_DELAY_MS * self._rng.random() * MAX_JITTER_FACTOR
71
+ sleep_ms = BASE_DELAY_MS + jitter
68
72
  if cancel is not None:
69
73
  cancel.wait(sleep_ms / 1000.0)
70
74
  else:
71
75
  time.sleep(sleep_ms / 1000.0)
72
- return delay_ms * _MULTIPLIER
73
76
 
74
77
 
75
78
  def default_should_retry_status(status: int) -> bool:
@@ -11,12 +11,12 @@ import requests
11
11
  from openfeature.contrib.tools.flagd.core import FlagdCore
12
12
  from openfeature.evaluation_context import EvaluationContext
13
13
  from openfeature.event import ProviderEventDetails
14
- from openfeature.exception import GeneralError, ParseError
14
+ from openfeature.exception import GeneralError
15
15
  from openfeature.flag_evaluation import FlagResolutionDetails, FlagValueType
16
16
  from openfeature.hook import Hook
17
17
  from openfeature.provider import AbstractProvider, Metadata, ProviderStatus
18
18
 
19
- from ._cdn import REQUEST_TIMEOUT_S as _REQUEST_TIMEOUT_S
19
+ from ._cdn import MAX_FETCH_DURATION_S as _MAX_FETCH_DURATION_S
20
20
  from ._cdn import CdnFetcher
21
21
  from ._metrics_aggregator import (
22
22
  HARD_CAP_DISTINCT_FLAGS,
@@ -61,10 +61,11 @@ class DynatraceProvider(AbstractProvider):
61
61
  options = DynatraceProviderOptions.from_sdk_key(
62
62
  sdk_key, config_origin=config_origin, metrics_origin=metrics_origin
63
63
  )
64
- if fetcher is None and poll_interval_s <= _REQUEST_TIMEOUT_S:
64
+ # providers.md 2.1: a poll must not outlive its interval; the bound is the whole fetch, not one request
65
+ if fetcher is None and poll_interval_s <= _MAX_FETCH_DURATION_S:
65
66
  raise ValueError(
66
67
  f"poll_interval_s ({poll_interval_s}s) must be greater than the "
67
- f"request timeout ({_REQUEST_TIMEOUT_S}s)"
68
+ f"maximum fetch duration ({_MAX_FETCH_DURATION_S:.2f}s)"
68
69
  )
69
70
  if metrics_flush_interval_s <= 0:
70
71
  raise ValueError(
@@ -108,58 +109,103 @@ class DynatraceProvider(AbstractProvider):
108
109
  self._generation += 1
109
110
  generation = self._generation
110
111
 
112
+ body = self._fetch_initial_body(generation)
113
+
114
+ try:
115
+ self._flagd_core.set_flags(body)
116
+ except Exception as exc:
117
+ # not just ParseError: a non-JSON body raises JSONDecodeError, which must still leave a recoverable provider
118
+ self._fail_initialization(generation, f"invalid config: {exc}")
119
+ raise GeneralError(f"initial CDN config is invalid: {exc}") from exc
120
+
121
+ # set the aggregator version eagerly so it is authoritative before any evaluation is recorded
122
+ self._update_metrics_version_from_flag_set()
123
+
124
+ with self._lock:
125
+ if self._generation != generation:
126
+ # a concurrent shutdown/re-initialize superseded us mid-fetch; do not resurrect the provider
127
+ log.info(
128
+ "initialize superseded by a concurrent shutdown/initialize; "
129
+ "not starting poller"
130
+ )
131
+ return
132
+ self._cancel_grace_timer()
133
+ self._state = ProviderStatus.READY
134
+ self._start_poller_locked()
135
+ self._metrics_flusher.start()
136
+ log.info("Dynatrace provider initialized successfully")
137
+
138
+ def _fetch_initial_body(self, generation: int) -> str:
139
+ """Fetch the startup config, or fail initialization and raise.
140
+
141
+ Bounded like any other fetch (providers.md section 2.4). Failing is not
142
+ terminal: the provider enters ERROR and the polling timer carries it to
143
+ READY if the failure was transient.
144
+ """
111
145
  try:
112
146
  result = self._fetcher.fetch()
113
147
  except (OSError, requests.RequestException) as exc:
148
+ self._fail_initialization(generation, f"fetch failed: {type(exc).__name__}")
114
149
  raise GeneralError(
115
150
  f"initial CDN fetch failed: {type(exc).__name__}"
116
151
  ) from exc
117
152
 
153
+ if result.skipped:
154
+ # No request was made, so there is no status to report.
155
+ self._fail_initialization(generation, "fetch skipped")
156
+ raise GeneralError("initial CDN fetch was skipped; no request was made")
157
+
118
158
  if not result.is_success:
159
+ self._fail_initialization(generation, f"HTTP {result.status}")
119
160
  raise GeneralError(f"initial CDN fetch returned HTTP {result.status}")
120
161
 
121
162
  body = result.body
122
163
  if not body or not body.strip():
164
+ self._fail_initialization(generation, "empty response body")
123
165
  raise GeneralError("initial CDN response body was empty")
124
166
 
125
- try:
126
- self._flagd_core.set_flags(body)
127
- except ParseError as exc:
128
- raise GeneralError(f"initial CDN config is invalid: {exc}") from exc
167
+ return body
168
+
169
+ def _start_poller_locked(self) -> None:
170
+ """Replace any existing poller with a fresh one. Caller holds ``_lock``."""
171
+ if self._poller is not None:
172
+ self._poller.stop()
173
+ self._poller = PollingManager(
174
+ fetch_flags=self._fetcher.fetch,
175
+ store_flags=self._store_flags,
176
+ emit_change=self._on_configuration_changed,
177
+ emit_success=self._on_fetch_success,
178
+ emit_failure=self._on_fetch_failure,
179
+ interval_s=self._poll_interval_s,
180
+ )
181
+ self._poller.start()
129
182
 
130
- # Set the aggregator version eagerly so it is authoritative before any
131
- # evaluation is recorded.
132
- self._update_metrics_version_from_flag_set()
183
+ def _fail_initialization(self, generation: int, reason: str) -> None:
184
+ """Enter ERROR and start polling so the provider can still recover.
133
185
 
186
+ The caller raises afterwards, so initialization is still seen to fail;
187
+ the polling timer is what brings the provider back (section 2.4). Auth
188
+ failures take this path too, since 401/403 are ERROR and never FATAL.
189
+ """
134
190
  with self._lock:
135
191
  if self._generation != generation:
136
- # A concurrent shutdown() or re-initialize() superseded us while
137
- # the fetch was in flight; do not resurrect the provider.
192
+ # A newer generation owns the fetcher; its cache is not ours.
138
193
  log.info(
139
194
  "initialize superseded by a concurrent shutdown/initialize; "
140
- "not starting poller"
195
+ "not starting recovery poller"
141
196
  )
142
197
  return
198
+ # nothing was applied, so cached validators would let the recovery poll 304 its way to READY over an empty store
199
+ self._fetcher.invalidate_cache()
200
+ log.warning("initialization failed (%s); polling for recovery", reason)
201
+ self._state = ProviderStatus.ERROR
143
202
  self._cancel_grace_timer()
144
- if self._poller is not None:
145
- self._poller.stop()
146
- self._state = ProviderStatus.READY
147
- self._poller = PollingManager(
148
- fetch_flags=self._fetcher.fetch,
149
- store_flags=self._store_flags,
150
- emit_change=self._on_configuration_changed,
151
- emit_success=self._on_fetch_success,
152
- emit_failure=self._on_fetch_failure,
153
- interval_s=self._poll_interval_s,
154
- )
155
- self._poller.start()
203
+ self._start_poller_locked()
156
204
  self._metrics_flusher.start()
157
- log.info("Dynatrace provider initialized successfully")
158
205
 
159
206
  def shutdown(self) -> None:
160
207
  with self._lock:
161
- # Always bump the generation, even when already idle, so an
162
- # in-flight initialize() detects it was superseded and aborts.
208
+ # always bump the generation, even when idle, so an in-flight initialize detects it was superseded
163
209
  self._generation += 1
164
210
  already_idle = (
165
211
  self._state == ProviderStatus.NOT_READY and self._poller is None
@@ -171,10 +217,7 @@ class DynatraceProvider(AbstractProvider):
171
217
  if self._poller is not None:
172
218
  self._poller.stop()
173
219
  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.
220
+ # always release the flusher and its session (created in __init__), even if init never finished; shutdown() is idempotent
178
221
  try:
179
222
  self._metrics_flusher.shutdown()
180
223
  except Exception as exc:
@@ -235,13 +278,16 @@ class DynatraceProvider(AbstractProvider):
235
278
  )
236
279
 
237
280
  def _store_flags(self, body: str) -> list[str]:
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.
281
+ # seal + enqueue + flush the old-version batch before applying the new config, so pre-rotation counts flush under the old version
241
282
  sealed = self._metrics_aggregator.drain()
242
283
  self._metrics_flusher.enqueue_sealed_batch(sealed)
243
284
  self._metrics_flusher.trigger_flush()
244
- changed = self._flagd_core.set_flags_and_get_changed_keys(body)
285
+ try:
286
+ changed = self._flagd_core.set_flags_and_get_changed_keys(body)
287
+ except Exception:
288
+ # fetched but not applied, so its validators would make the next poll a 304 over the previous config
289
+ self._fetcher.invalidate_cache()
290
+ raise
245
291
  self._update_metrics_version_from_flag_set()
246
292
  return changed
247
293
 
@@ -1,96 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: dynatrace-openfeature-provider-python
3
- Version: 0.2.0
4
- Summary: The official Dynatrace OpenFeature provider for Python
5
- Keywords: openfeature,dynatrace,feature-flags,feature-management
6
- Author: Dynatrace
7
- License-Expression: Apache-2.0
8
- License-File: LICENSE
9
- Classifier: Programming Language :: Python
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: Apache Software License
12
- Requires-Dist: openfeature-sdk>=0.8.2
13
- Requires-Dist: openfeature-flagd-core>=1.0.0,<2.0.0
14
- Requires-Dist: requests>=2.27.0
15
- Requires-Python: >=3.10
16
- Project-URL: Homepage, https://github.com/Dynatrace/openfeature-provider-python
17
- Description-Content-Type: text/markdown
18
-
19
- # Dynatrace OpenFeature Provider for Python
20
-
21
- The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
22
-
23
- > **Status:** Early alpha — not yet ready for production use!
24
-
25
- ## Installation
26
-
27
- ```bash
28
- pip install dynatrace-openfeature-provider-python
29
- ```
30
-
31
- ## Usage
32
-
33
- ```python
34
- from openfeature import api
35
- from openfeature.evaluation_context import EvaluationContext
36
- from dynatrace.openfeature import DynatraceProvider, DynatraceProviderOptions
37
-
38
- options = DynatraceProviderOptions.from_sdk_key(
39
- 'dt01.server_us_<key>.de848e97..._a1b2c3d4e5'
40
- )
41
-
42
- api.set_provider(DynatraceProvider(options))
43
- client = api.get_client()
44
-
45
- ctx = EvaluationContext(targeting_key='user-123')
46
- enabled = client.get_boolean_value('my-feature', False, ctx)
47
-
48
- # On shutdown:
49
- api.shutdown()
50
- ```
51
-
52
- ### Config origin override (labs / dev environments)
53
-
54
- By default the config endpoint is derived from the SDK key. To point the provider at a
55
- different environment or at an SDK proxy, pass `config_origin`. The value is an origin
56
- only — scheme, host, and optional port, with no path. The provider appends the platform
57
- and key segments itself.
58
-
59
- ```python
60
- api.set_provider(
61
- DynatraceProvider(sdk_key, config_origin='https://cdn.eu.fm.dynatracelabs.com')
62
- )
63
- ```
64
-
65
- ### Metrics origin override
66
-
67
- By default the metrics ingest endpoint is derived from the SDK key. To point
68
- metrics at a different environment or an SDK proxy, pass `metrics_origin`. The
69
- value is an origin only: scheme, host, and optional port, with no path. The
70
- provider appends `/v1/metrics` itself.
71
-
72
- ```python
73
- api.set_provider(
74
- DynatraceProvider(
75
- sdk_key,
76
- metrics_origin='https://metrics.eu.fm.dynatracelabs.com',
77
- )
78
- )
79
- ```
80
-
81
- ## Architecture
82
-
83
- The provider performs in-process flag evaluation using [flagd-core](https://github.com/open-feature/python-sdk-contrib/tree/main/tools/openfeature-flagd-core).
84
- On initialization it fetches a flagd-format JSON config from the Dynatrace CDN and polls for
85
- updates every 10 seconds. No external bucketing API is called during evaluation.
86
-
87
- State transitions follow [providers.md §4.1](https://github.com/Dynatrace/feature-management-knowledge-base):
88
- `NOT_READY → READY → STALE → ERROR`, with a 1-minute grace period before STALE → ERROR.
89
-
90
- ## Contributing
91
-
92
- See [CONTRIBUTING.md](CONTRIBUTING.md).
93
-
94
- ## License
95
-
96
- Apache 2.0 — see [LICENSE](LICENSE).
@@ -1,78 +0,0 @@
1
- # Dynatrace OpenFeature Provider for Python
2
-
3
- The official [Dynatrace](https://dynatrace.com) [OpenFeature](https://openfeature.dev) provider for Python server-side applications.
4
-
5
- > **Status:** Early alpha — not yet ready for production use!
6
-
7
- ## Installation
8
-
9
- ```bash
10
- pip install dynatrace-openfeature-provider-python
11
- ```
12
-
13
- ## Usage
14
-
15
- ```python
16
- from openfeature import api
17
- from openfeature.evaluation_context import EvaluationContext
18
- from dynatrace.openfeature import DynatraceProvider, DynatraceProviderOptions
19
-
20
- options = DynatraceProviderOptions.from_sdk_key(
21
- 'dt01.server_us_<key>.de848e97..._a1b2c3d4e5'
22
- )
23
-
24
- api.set_provider(DynatraceProvider(options))
25
- client = api.get_client()
26
-
27
- ctx = EvaluationContext(targeting_key='user-123')
28
- enabled = client.get_boolean_value('my-feature', False, ctx)
29
-
30
- # On shutdown:
31
- api.shutdown()
32
- ```
33
-
34
- ### Config origin override (labs / dev environments)
35
-
36
- By default the config endpoint is derived from the SDK key. To point the provider at a
37
- different environment or at an SDK proxy, pass `config_origin`. The value is an origin
38
- only — scheme, host, and optional port, with no path. The provider appends the platform
39
- and key segments itself.
40
-
41
- ```python
42
- api.set_provider(
43
- DynatraceProvider(sdk_key, config_origin='https://cdn.eu.fm.dynatracelabs.com')
44
- )
45
- ```
46
-
47
- ### Metrics origin override
48
-
49
- By default the metrics ingest endpoint is derived from the SDK key. To point
50
- metrics at a different environment or an SDK proxy, pass `metrics_origin`. The
51
- value is an origin only: scheme, host, and optional port, with no path. The
52
- provider appends `/v1/metrics` itself.
53
-
54
- ```python
55
- api.set_provider(
56
- DynatraceProvider(
57
- sdk_key,
58
- metrics_origin='https://metrics.eu.fm.dynatracelabs.com',
59
- )
60
- )
61
- ```
62
-
63
- ## Architecture
64
-
65
- The provider performs in-process flag evaluation using [flagd-core](https://github.com/open-feature/python-sdk-contrib/tree/main/tools/openfeature-flagd-core).
66
- On initialization it fetches a flagd-format JSON config from the Dynatrace CDN and polls for
67
- updates every 10 seconds. No external bucketing API is called during evaluation.
68
-
69
- State transitions follow [providers.md §4.1](https://github.com/Dynatrace/feature-management-knowledge-base):
70
- `NOT_READY → READY → STALE → ERROR`, with a 1-minute grace period before STALE → ERROR.
71
-
72
- ## Contributing
73
-
74
- See [CONTRIBUTING.md](CONTRIBUTING.md).
75
-
76
- ## License
77
-
78
- Apache 2.0 — see [LICENSE](LICENSE).