dynatrace-openfeature-provider-python 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.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Dynatrace LLC
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: dynatrace-openfeature-provider-python
3
+ Version: 0.0.2
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
+ ### CDN base URL override (labs / dev environments)
53
+
54
+ ```python
55
+ options = DynatraceProviderOptions.from_sdk_key(sdk_key)
56
+ ```
57
+
58
+ ## Architecture
59
+
60
+ The provider performs in-process flag evaluation using [flagd-core](https://github.com/open-feature/python-sdk-contrib/tree/main/tools/openfeature-flagd-core).
61
+ On initialization it fetches a flagd-format JSON config from the Dynatrace CDN and polls for
62
+ updates every 10 seconds. No external bucketing API is called during evaluation.
63
+
64
+ State transitions follow [providers.md §4.1](https://github.com/Dynatrace/feature-management-knowledge-base):
65
+ `NOT_READY → READY → STALE → ERROR`, with a 1-minute grace period before STALE → ERROR.
66
+
67
+ ## Contributing
68
+
69
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
70
+
71
+ ## License
72
+
73
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,55 @@
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
+ ### CDN base URL override (labs / dev environments)
35
+
36
+ ```python
37
+ options = DynatraceProviderOptions.from_sdk_key(sdk_key)
38
+ ```
39
+
40
+ ## Architecture
41
+
42
+ The provider performs in-process flag evaluation using [flagd-core](https://github.com/open-feature/python-sdk-contrib/tree/main/tools/openfeature-flagd-core).
43
+ On initialization it fetches a flagd-format JSON config from the Dynatrace CDN and polls for
44
+ updates every 10 seconds. No external bucketing API is called during evaluation.
45
+
46
+ State transitions follow [providers.md §4.1](https://github.com/Dynatrace/feature-management-knowledge-base):
47
+ `NOT_READY → READY → STALE → ERROR`, with a 1-minute grace period before STALE → ERROR.
48
+
49
+ ## Contributing
50
+
51
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
52
+
53
+ ## License
54
+
55
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,109 @@
1
+ [build-system]
2
+ requires = ["uv_build~=0.10.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "dynatrace-openfeature-provider-python"
7
+ version = "0.0.2"
8
+ description = "The official Dynatrace OpenFeature provider for Python"
9
+ readme = "README.md"
10
+ authors = [{ name = "Dynatrace" }]
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ classifiers = [
14
+ "Programming Language :: Python",
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ ]
18
+ keywords = ["openfeature", "dynatrace", "feature-flags", "feature-management"]
19
+ dependencies = [
20
+ "openfeature-sdk>=0.8.2",
21
+ "openfeature-flagd-core>=1.0.0,<2.0.0",
22
+ "requests>=2.27.0",
23
+ ]
24
+ requires-python = ">=3.10"
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/Dynatrace/openfeature-provider-python"
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "coverage[toml]>=7.10.0,<8.0.0",
32
+ "mypy>=1.18.0,<2.0.0",
33
+ "poethepoet>=0.37.0",
34
+ "pytest>=9.0.0,<10.0.0",
35
+ "responses>=0.25.0,<1.0.0",
36
+ "pre-commit>=4.0.0",
37
+ "ruff>=0.15.13",
38
+ "types-requests>=2.32.0,<3.0.0",
39
+ ]
40
+
41
+ [tool.uv.build-backend]
42
+ module-name = "dynatrace"
43
+ module-root = "src"
44
+ namespace = true
45
+
46
+ [tool.coverage.run]
47
+ omit = ["tests/**"]
48
+
49
+ [tool.mypy]
50
+ mypy_path = "src"
51
+ files = "src"
52
+ python_version = "3.10"
53
+ namespace_packages = true
54
+ explicit_package_bases = true
55
+ local_partial_types = true
56
+ allow_redefinition_new = true
57
+ fixed_format_cache = true
58
+ pretty = true
59
+ strict = true
60
+ disallow_any_generics = false
61
+
62
+ [tool.ruff]
63
+ target-version = "py310"
64
+ exclude = [".git", ".venv", "__pycache__", "venv"]
65
+
66
+ [tool.ruff.lint]
67
+ select = [
68
+ "A", "B", "C4", "C90", "E", "F", "FLY", "FURB", "I", "ICN003",
69
+ "LOG", "N", "PERF", "PGH", "PLC", "PLR0913", "PLR0915",
70
+ "RUF", "S", "SIM", "T10", "T20", "TID251", "UP", "W", "YTT",
71
+ ]
72
+ ignore = ["E501"]
73
+
74
+ [tool.ruff.lint.per-file-ignores]
75
+ "**/tests/**/*" = ["S101"]
76
+
77
+ [tool.ruff.lint.flake8-import-conventions]
78
+ banned-from = ["typing"]
79
+
80
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
81
+ "typing.Awaitable".msg = "Use collections.abc.Awaitable instead"
82
+ "typing.Callable".msg = "Use collections.abc.Callable instead"
83
+ "typing.Collection".msg = "Use collections.abc.Collection instead"
84
+ "typing.Mapping".msg = "Use collections.abc.Mapping instead"
85
+ "typing.MutableMapping".msg = "Use collections.abc.MutableMapping instead"
86
+ "typing.MutableSequence".msg = "Use collections.abc.MutableSequence instead"
87
+ "typing.Sequence".msg = "Use collections.abc.Sequence instead"
88
+
89
+ [tool.ruff.lint.isort]
90
+ known-first-party = ["dynatrace"]
91
+
92
+ [tool.ruff.lint.pylint]
93
+ max-args = 8
94
+ max-statements = 30
95
+
96
+ [tool.ruff.lint.pyupgrade]
97
+ keep-runtime-typing = true
98
+
99
+ [tool.pytest.ini_options]
100
+ strict = true
101
+
102
+ [tool.poe.tasks]
103
+ test = "pytest tests"
104
+ test-cov = "coverage run -m pytest tests"
105
+ cov-report = "coverage xml"
106
+ cov = ["test-cov", "cov-report"]
107
+ mypy = "mypy"
108
+ lint = "ruff check src tests"
109
+ fmt = "ruff format src tests"
@@ -0,0 +1,5 @@
1
+ from .options import DynatraceProviderOptions
2
+ from .provider import DynatraceProvider
3
+
4
+ __version__ = "0.0.1"
5
+ __all__ = ["DynatraceProvider", "DynatraceProviderOptions"]
@@ -0,0 +1,167 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ import time
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from email.utils import parsedate_to_datetime
10
+
11
+ import requests
12
+
13
+ from ._retry import RetryStrategy, default_should_retry_status
14
+ from .options import DynatraceProviderOptions
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ REQUEST_TIMEOUT_S: float = 5.0
19
+ _DEFAULT_RETRY_AFTER_MS: float = 60_000.0
20
+
21
+
22
+ @dataclass
23
+ class FetchResult:
24
+ status: int
25
+ body: str | None
26
+ etag: str | None
27
+ last_modified: str | None
28
+ skipped: bool = False
29
+
30
+ @property
31
+ def is_not_modified(self) -> bool:
32
+ return self.status == 304
33
+
34
+ @property
35
+ def is_rate_limited(self) -> bool:
36
+ return self.status == 429
37
+
38
+ @property
39
+ def is_success(self) -> bool:
40
+ return 200 <= self.status < 300
41
+
42
+
43
+ @dataclass
44
+ class _CacheState:
45
+ etag: str | None = None
46
+ last_modified_header: str | None = None
47
+ last_modified_at: datetime | None = None
48
+
49
+
50
+ def _should_retry_fetch(result: FetchResult) -> bool:
51
+ return default_should_retry_status(result.status)
52
+
53
+
54
+ class CdnFetcher:
55
+ def __init__(
56
+ self,
57
+ options: DynatraceProviderOptions,
58
+ retry_strategy: RetryStrategy | None = None,
59
+ *,
60
+ clock: Callable[[], float] | None = None,
61
+ ) -> None:
62
+ self._url = options.cdn_url
63
+ self._retry = retry_strategy or RetryStrategy()
64
+ self._session = requests.Session()
65
+ self._clock: Callable[[], float] = clock or time.time
66
+ self._cache = _CacheState()
67
+ self._rate_limited_until: float = 0.0
68
+ self._fetch_lock = threading.RLock()
69
+
70
+ def is_rate_limited(self, now: float | None = None) -> bool:
71
+ t = now if now is not None else self._clock()
72
+ return t < self._rate_limited_until
73
+
74
+ def fetch(self, cancel: threading.Event | None = None) -> FetchResult:
75
+ if self.is_rate_limited():
76
+ log.debug("rate limited; skipping fetch")
77
+ return FetchResult(429, None, None, None)
78
+ if not self._fetch_lock.acquire(blocking=False):
79
+ log.debug("fetch already in progress; skipping")
80
+ return FetchResult(0, None, None, None, skipped=True)
81
+ try:
82
+ return self._retry.execute(
83
+ self._do_fetch,
84
+ should_retry=_should_retry_fetch,
85
+ retryable_exceptions=(OSError, requests.RequestException),
86
+ cancel=cancel,
87
+ )
88
+ finally:
89
+ self._fetch_lock.release()
90
+
91
+ def _do_fetch(self) -> FetchResult:
92
+ cache = self._cache
93
+ headers: dict[str, str] = {}
94
+ if cache.etag is not None:
95
+ headers["If-None-Match"] = cache.etag
96
+ if cache.last_modified_header is not None:
97
+ headers["If-Modified-Since"] = cache.last_modified_header
98
+
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)
110
+
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)
117
+
118
+ new_etag = resp.headers.get("ETag")
119
+ new_last_modified = resp.headers.get("Last-Modified")
120
+ body = resp.text
121
+
122
+ if resp.status_code >= 200 and resp.status_code < 300:
123
+ new_lm_at = _parse_http_date(new_last_modified)
124
+ if (
125
+ new_lm_at is not None
126
+ and cache.last_modified_at is not None
127
+ and not new_lm_at > cache.last_modified_at
128
+ ):
129
+ log.warning(
130
+ "CDN returned 200 but Last-Modified (%s) is not later than stored (%s);"
131
+ " treating as 304 (suspected stale node)",
132
+ new_last_modified,
133
+ cache.last_modified_header,
134
+ )
135
+ return FetchResult(304, None, cache.etag, cache.last_modified_header)
136
+ self._cache = _CacheState(
137
+ etag=new_etag,
138
+ last_modified_header=new_last_modified,
139
+ last_modified_at=new_lm_at,
140
+ )
141
+
142
+ return FetchResult(resp.status_code, body, new_etag, new_last_modified)
143
+
144
+
145
+ def _parse_http_date(value: str | None) -> datetime | None:
146
+ if not value:
147
+ return None
148
+ try:
149
+ return parsedate_to_datetime(value.strip())
150
+ except Exception:
151
+ log.warning("unparseable HTTP-date %r", value)
152
+ return None
153
+
154
+
155
+ def _parse_retry_after_ms(retry_after: str | None, now: float) -> float:
156
+ if not retry_after or not retry_after.strip():
157
+ return _DEFAULT_RETRY_AFTER_MS
158
+ try:
159
+ return float(retry_after.strip()) * 1000.0
160
+ except ValueError:
161
+ pass
162
+ try:
163
+ dt = parsedate_to_datetime(retry_after.strip())
164
+ return max((dt.timestamp() - now) * 1000.0, 0.0)
165
+ except Exception:
166
+ log.warning("unparseable Retry-After %r; using default", retry_after)
167
+ return _DEFAULT_RETRY_AFTER_MS
@@ -0,0 +1,130 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ import time
6
+ from collections.abc import Callable
7
+
8
+ from ._cdn import FetchResult
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+
13
+ class PollingManager:
14
+ """
15
+ Polls on a fixed-rate schedule anchored to request initiation, not completion.
16
+
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.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ fetch_flags: Callable[[threading.Event | None], FetchResult],
26
+ store_flags: Callable[[str], list[str]],
27
+ emit_change: Callable[[list[str]], None],
28
+ emit_success: Callable[[], None],
29
+ emit_failure: Callable[[str], None],
30
+ interval_s: float,
31
+ ) -> None:
32
+ self._fetch_flags = fetch_flags
33
+ self._store_flags = store_flags
34
+ self._emit_change = emit_change
35
+ self._emit_success = emit_success
36
+ self._emit_failure = emit_failure
37
+ self._interval_s = interval_s
38
+ self._stop_event = threading.Event()
39
+ self._current_cancel: threading.Event | None = None
40
+ self._ticker_thread: threading.Thread | None = None
41
+
42
+ def start(self) -> None:
43
+ if self._ticker_thread is not None and self._ticker_thread.is_alive():
44
+ return
45
+ self._stop_event.clear()
46
+ self._ticker_thread = threading.Thread(
47
+ target=self._ticker_loop,
48
+ name="dt-provider-ticker",
49
+ daemon=True,
50
+ )
51
+ self._ticker_thread.start()
52
+
53
+ def stop(self) -> None:
54
+ self._stop_event.set()
55
+ if self._ticker_thread is not None:
56
+ self._ticker_thread.join(timeout=2.0)
57
+ cancel = self._current_cancel
58
+ if cancel is not None:
59
+ cancel.set()
60
+
61
+ def _ticker_loop(self) -> None:
62
+ next_tick = time.monotonic() + self._interval_s
63
+ while not self._stop_event.is_set():
64
+ wait = max(0.0, next_tick - time.monotonic())
65
+ if self._stop_event.wait(wait):
66
+ break
67
+ next_tick += self._interval_s
68
+ now = time.monotonic()
69
+ if next_tick < now:
70
+ next_tick = now + self._interval_s
71
+ self._dispatch()
72
+
73
+ def _dispatch(self) -> None:
74
+ if self._stop_event.is_set():
75
+ return
76
+ prev = self._current_cancel
77
+ if prev is not None:
78
+ prev.set()
79
+ cancel = threading.Event()
80
+ self._current_cancel = cancel
81
+ threading.Thread(
82
+ target=self._poll,
83
+ args=(cancel,),
84
+ name="dt-provider-poller",
85
+ daemon=True,
86
+ ).start()
87
+
88
+ def _poll(self, cancel: threading.Event) -> None:
89
+ try:
90
+ result = self._fetch_flags(cancel)
91
+
92
+ if cancel.is_set():
93
+ log.debug("poll cancelled after fetch returned; discarding result")
94
+ return
95
+
96
+ if result.skipped:
97
+ log.debug("fetch skipped (lock contention); retaining cached state")
98
+ return
99
+
100
+ if result.is_not_modified:
101
+ log.debug("flags not modified")
102
+ self._emit_success()
103
+ return
104
+
105
+ if result.is_rate_limited:
106
+ log.debug("rate limited; serving cached values")
107
+ return
108
+
109
+ if not result.is_success:
110
+ self._emit_failure(f"HTTP {result.status}")
111
+ return
112
+
113
+ body = result.body
114
+ if not body:
115
+ self._emit_failure("empty response body")
116
+ return
117
+
118
+ changed_keys = self._store_flags(body)
119
+ self._emit_success()
120
+
121
+ if changed_keys:
122
+ log.info("flag configuration changed: %s", changed_keys)
123
+ self._emit_change(changed_keys)
124
+
125
+ except Exception as exc:
126
+ if cancel.is_set():
127
+ log.debug("poll cancelled")
128
+ return
129
+ log.warning("poll failed: %s", type(exc).__name__)
130
+ self._emit_failure(type(exc).__name__)
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ import time
6
+ import typing
7
+ from collections.abc import Callable
8
+ from random import Random
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+ T = typing.TypeVar("T")
13
+
14
+ _MAX_ATTEMPTS = 5
15
+ _BASE_DELAY_MS = 100.0
16
+ _MULTIPLIER = 2.0
17
+ _MAX_JITTER_FACTOR = 0.20
18
+
19
+
20
+ class RetryStrategy:
21
+ def __init__(self, rng: Random | None = None) -> None:
22
+ self._rng = rng or Random() # noqa: S311
23
+
24
+ def execute(
25
+ self,
26
+ fn: Callable[[], T],
27
+ should_retry: Callable[[T], bool] = lambda _: False,
28
+ retryable_exceptions: tuple[type[BaseException], ...] = (OSError,),
29
+ cancel: threading.Event | None = None,
30
+ ) -> T:
31
+ last_exception: BaseException | None = None
32
+ last_result: T | None = None
33
+ delay_ms = _BASE_DELAY_MS
34
+
35
+ for attempt in range(1, _MAX_ATTEMPTS + 1):
36
+ try:
37
+ result = fn()
38
+ last_result = result
39
+ if not should_retry(result):
40
+ return result
41
+ log.warning(
42
+ "attempt %d/%d returned retryable result; retrying",
43
+ attempt,
44
+ _MAX_ATTEMPTS,
45
+ )
46
+ except retryable_exceptions as exc:
47
+ last_exception = exc
48
+ log.warning(
49
+ "attempt %d/%d failed: %s; retrying", attempt, _MAX_ATTEMPTS, exc
50
+ )
51
+ except Exception as exc:
52
+ raise OSError("unexpected error during fetch") from exc
53
+
54
+ if attempt < _MAX_ATTEMPTS:
55
+ delay_ms = self._backoff(delay_ms, cancel)
56
+ if cancel is not None and cancel.is_set():
57
+ break
58
+
59
+ if last_result is not None:
60
+ return last_result
61
+ if last_exception is not None:
62
+ raise last_exception
63
+ raise OSError("all retry attempts failed")
64
+
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
68
+ if cancel is not None:
69
+ cancel.wait(sleep_ms / 1000.0)
70
+ else:
71
+ time.sleep(sleep_ms / 1000.0)
72
+ return delay_ms * _MULTIPLIER
73
+
74
+
75
+ def default_should_retry_status(status: int) -> bool:
76
+ return 500 <= status < 600
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+ # SDK key format per providers.md §3.0:
6
+ # {token}.server_{geo}_{publicRandom}.{secret}_{sha1}
7
+ _KEY_PATTERN = re.compile(
8
+ r"^(dt[0-9]{2})\.(server)_([a-z]{2,})_([a-zA-Z0-9]{10,})\.([a-fA-F0-9]{32,})_([a-f0-9]{10,})$"
9
+ )
10
+
11
+
12
+ class DynatraceProviderOptions:
13
+ __slots__ = ("_cdn_url", "_key")
14
+
15
+ def __init__(self, key: str, cdn_url: str) -> None:
16
+ self._key = key
17
+ self._cdn_url = cdn_url
18
+
19
+ @classmethod
20
+ def from_sdk_key(
21
+ cls,
22
+ sdk_key: str,
23
+ cdn_base_url: str | None = None,
24
+ ) -> DynatraceProviderOptions:
25
+ if not sdk_key or not sdk_key.strip():
26
+ raise ValueError("sdk_key must not be null or blank")
27
+ trimmed = sdk_key.strip()
28
+ key_match = _KEY_PATTERN.match(trimmed)
29
+ if not key_match:
30
+ last_dot = trimmed.rfind(".")
31
+ public_part = trimmed[:last_dot] if last_dot > 0 else "<redacted>"
32
+ raise ValueError(
33
+ f"invalid key format (public: {public_part!r}); "
34
+ "expected dt{NN}.server_{geo}_{rand}.{secret}_{sha}"
35
+ )
36
+ _token, _platform, geo, _rand, _secret, _sha = key_match.groups()
37
+ if cdn_base_url is not None:
38
+ cdn_base_url = cdn_base_url.strip()
39
+ if not cdn_base_url:
40
+ raise ValueError("cdn_base_url must not be blank")
41
+ base = cdn_base_url if cdn_base_url.endswith("/") else cdn_base_url + "/"
42
+ else:
43
+ base = f"https://cdn.{geo}.fm.dynatrace.com/server/"
44
+ cdn_url = base + trimmed + ".json"
45
+ return cls(key=trimmed, cdn_url=cdn_url)
46
+
47
+ @property
48
+ def public_key(self) -> str:
49
+ # Everything before the last '.' — safe to log; never exposes the secret segment.
50
+ idx = self._key.rfind(".")
51
+ return self._key[:idx] if idx > 0 else "<redacted>"
52
+
53
+ @property
54
+ def cdn_url(self) -> str:
55
+ return self._cdn_url
@@ -0,0 +1,236 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ from collections.abc import Mapping, Sequence
6
+
7
+ import requests
8
+
9
+ from openfeature.contrib.tools.flagd.core import FlagdCore
10
+ from openfeature.evaluation_context import EvaluationContext
11
+ from openfeature.event import ProviderEventDetails
12
+ from openfeature.exception import GeneralError, ParseError
13
+ from openfeature.flag_evaluation import FlagResolutionDetails, FlagValueType
14
+ from openfeature.hook import Hook
15
+ from openfeature.provider import AbstractProvider, Metadata, ProviderStatus
16
+
17
+ from ._cdn import REQUEST_TIMEOUT_S as _REQUEST_TIMEOUT_S
18
+ from ._cdn import CdnFetcher
19
+ from ._polling import PollingManager
20
+ from .options import DynatraceProviderOptions
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+ _PROVIDER_NAME = "dynatrace"
25
+ _POLL_INTERVAL_S: float = 10.0
26
+ _GRACE_PERIOD_S: float = 60.0
27
+
28
+
29
+ class DynatraceProvider(AbstractProvider):
30
+ def __init__(
31
+ self,
32
+ sdk_key: str,
33
+ *,
34
+ cdn_base_url: str | None = None,
35
+ flagd_core: FlagdCore | None = None,
36
+ fetcher: CdnFetcher | None = None,
37
+ poll_interval_s: float = _POLL_INTERVAL_S,
38
+ grace_period_s: float = _GRACE_PERIOD_S,
39
+ ) -> None:
40
+ options = DynatraceProviderOptions.from_sdk_key(
41
+ sdk_key, cdn_base_url=cdn_base_url
42
+ )
43
+ if fetcher is None and poll_interval_s <= _REQUEST_TIMEOUT_S:
44
+ raise ValueError(
45
+ f"poll_interval_s ({poll_interval_s}s) must be greater than the "
46
+ f"request timeout ({_REQUEST_TIMEOUT_S}s)"
47
+ )
48
+ self._options = options
49
+ self._flagd_core = flagd_core or FlagdCore()
50
+ self._fetcher = fetcher or CdnFetcher(options)
51
+ self._poll_interval_s = poll_interval_s
52
+ self._grace_period_s = grace_period_s
53
+ self._poller: PollingManager | None = None
54
+ self._grace_timer: threading.Timer | None = None
55
+ self._state = ProviderStatus.NOT_READY
56
+ self._lock = threading.RLock()
57
+ # bumped by initialize/shutdown so a slow init can detect it was superseded
58
+ self._generation = 0
59
+
60
+ def get_metadata(self) -> Metadata:
61
+ return Metadata(name=_PROVIDER_NAME)
62
+
63
+ def get_provider_hooks(self) -> list[Hook]:
64
+ return []
65
+
66
+ def initialize(self, evaluation_context: EvaluationContext | None = None) -> None:
67
+ log.info("initializing Dynatrace provider (key=%s)", self._options.public_key)
68
+ with self._lock:
69
+ self._generation += 1
70
+ generation = self._generation
71
+
72
+ try:
73
+ result = self._fetcher.fetch()
74
+ except (OSError, requests.RequestException) as exc:
75
+ raise GeneralError(
76
+ f"initial CDN fetch failed: {type(exc).__name__}"
77
+ ) from exc
78
+
79
+ if not result.is_success:
80
+ raise GeneralError(f"initial CDN fetch returned HTTP {result.status}")
81
+
82
+ body = result.body
83
+ if not body or not body.strip():
84
+ raise GeneralError("initial CDN response body was empty")
85
+
86
+ try:
87
+ self._flagd_core.set_flags(body)
88
+ except ParseError as exc:
89
+ raise GeneralError(f"initial CDN config is invalid: {exc}") from exc
90
+
91
+ with self._lock:
92
+ if self._generation != generation:
93
+ # A concurrent shutdown() or re-initialize() superseded us while
94
+ # the fetch was in flight; do not resurrect the provider.
95
+ log.info(
96
+ "initialize superseded by a concurrent shutdown/initialize; "
97
+ "not starting poller"
98
+ )
99
+ return
100
+ self._cancel_grace_timer()
101
+ if self._poller is not None:
102
+ self._poller.stop()
103
+ self._state = ProviderStatus.READY
104
+ self._poller = PollingManager(
105
+ fetch_flags=self._fetcher.fetch,
106
+ store_flags=self._store_flags,
107
+ emit_change=self._on_configuration_changed,
108
+ emit_success=self._on_fetch_success,
109
+ emit_failure=self._on_fetch_failure,
110
+ interval_s=self._poll_interval_s,
111
+ )
112
+ self._poller.start()
113
+ log.info("Dynatrace provider initialized successfully")
114
+
115
+ def shutdown(self) -> None:
116
+ with self._lock:
117
+ # Always bump the generation, even when already idle, so an
118
+ # in-flight initialize() detects it was superseded and aborts.
119
+ self._generation += 1
120
+ if self._state == ProviderStatus.NOT_READY and self._poller is None:
121
+ return
122
+ log.info("shutting down Dynatrace provider")
123
+ self._state = ProviderStatus.NOT_READY
124
+ self._cancel_grace_timer()
125
+ if self._poller is not None:
126
+ self._poller.stop()
127
+ self._poller = None
128
+ super().shutdown()
129
+ log.info("Dynatrace provider shut down")
130
+
131
+ def resolve_boolean_details(
132
+ self,
133
+ flag_key: str,
134
+ default_value: bool,
135
+ evaluation_context: EvaluationContext | None = None,
136
+ ) -> FlagResolutionDetails[bool]:
137
+ return self._flagd_core.resolve_boolean_value(
138
+ flag_key, default_value, evaluation_context
139
+ )
140
+
141
+ def resolve_string_details(
142
+ self,
143
+ flag_key: str,
144
+ default_value: str,
145
+ evaluation_context: EvaluationContext | None = None,
146
+ ) -> FlagResolutionDetails[str]:
147
+ return self._flagd_core.resolve_string_value(
148
+ flag_key, default_value, evaluation_context
149
+ )
150
+
151
+ def resolve_integer_details(
152
+ self,
153
+ flag_key: str,
154
+ default_value: int,
155
+ evaluation_context: EvaluationContext | None = None,
156
+ ) -> FlagResolutionDetails[int]:
157
+ return self._flagd_core.resolve_integer_value(
158
+ flag_key, default_value, evaluation_context
159
+ )
160
+
161
+ def resolve_float_details(
162
+ self,
163
+ flag_key: str,
164
+ default_value: float,
165
+ evaluation_context: EvaluationContext | None = None,
166
+ ) -> FlagResolutionDetails[float]:
167
+ return self._flagd_core.resolve_float_value(
168
+ flag_key, default_value, evaluation_context
169
+ )
170
+
171
+ def resolve_object_details(
172
+ self,
173
+ flag_key: str,
174
+ default_value: Sequence[FlagValueType] | Mapping[str, FlagValueType],
175
+ evaluation_context: EvaluationContext | None = None,
176
+ ) -> FlagResolutionDetails[Sequence[FlagValueType] | Mapping[str, FlagValueType]]:
177
+ return self._flagd_core.resolve_object_value(
178
+ flag_key, default_value, evaluation_context
179
+ )
180
+
181
+ def _store_flags(self, body: str) -> list[str]:
182
+ return self._flagd_core.set_flags_and_get_changed_keys(body)
183
+
184
+ def _on_fetch_success(self) -> None:
185
+ with self._lock:
186
+ if self._state == ProviderStatus.NOT_READY:
187
+ return
188
+ self._cancel_grace_timer()
189
+ if self._state in (ProviderStatus.STALE, ProviderStatus.ERROR):
190
+ prev_state = self._state
191
+ self._state = ProviderStatus.READY
192
+ log.info("recovered from %s to READY", prev_state)
193
+ self.emit_provider_ready(ProviderEventDetails(message="recovered"))
194
+
195
+ def _on_fetch_failure(self, reason: str) -> None:
196
+ with self._lock:
197
+ if self._state == ProviderStatus.NOT_READY:
198
+ return
199
+ if self._state == ProviderStatus.READY:
200
+ self._state = ProviderStatus.STALE
201
+ log.warning("poll failed, transitioning to STALE: %s", reason)
202
+ self.emit_provider_stale(ProviderEventDetails(message=reason))
203
+ self._start_grace_timer()
204
+ else:
205
+ log.warning("poll failed (state=%s): %s", self._state, reason)
206
+
207
+ def _on_configuration_changed(self, changed_keys: list[str]) -> None:
208
+ with self._lock:
209
+ if self._state == ProviderStatus.NOT_READY:
210
+ return
211
+ self.emit_provider_configuration_changed(
212
+ ProviderEventDetails(flags_changed=changed_keys)
213
+ )
214
+
215
+ def _start_grace_timer(self) -> None:
216
+ self._cancel_grace_timer()
217
+ t = threading.Timer(self._grace_period_s, self._grace_expired)
218
+ t.daemon = True
219
+ t.name = "dt-provider-grace-timer"
220
+ t.start()
221
+ self._grace_timer = t
222
+
223
+ def _cancel_grace_timer(self) -> None:
224
+ if self._grace_timer is not None:
225
+ self._grace_timer.cancel()
226
+ self._grace_timer = None
227
+
228
+ def _grace_expired(self) -> None:
229
+ with self._lock:
230
+ if self._state != ProviderStatus.STALE:
231
+ return
232
+ self._state = ProviderStatus.ERROR
233
+ log.error("grace period expired, transitioning to ERROR")
234
+ self.emit_provider_error(
235
+ ProviderEventDetails(message="grace period expired; CDN unreachable")
236
+ )