flagnetic 0.1.4__tar.gz → 0.2.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 (61) hide show
  1. {flagnetic-0.1.4 → flagnetic-0.2.0}/PKG-INFO +27 -2
  2. {flagnetic-0.1.4 → flagnetic-0.2.0}/README.md +26 -1
  3. {flagnetic-0.1.4 → flagnetic-0.2.0}/e2e/test_smoke.py +1 -1
  4. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/__init__.py +3 -1
  5. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_client.py +43 -23
  6. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_delivery.py +53 -24
  7. flagnetic-0.2.0/src/flagnetic/_deprecation.py +49 -0
  8. flagnetic-0.2.0/src/flagnetic/_errors.py +11 -0
  9. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/__init__.py +16 -1
  10. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/evaluate.py +4 -0
  11. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/model.py +2 -2
  12. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/ruleset.py +146 -11
  13. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_ingest.py +11 -7
  14. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_overrides.py +34 -16
  15. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_reporting.py +47 -21
  16. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_sse.py +3 -7
  17. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_version.py +1 -1
  18. flagnetic-0.1.4/src/flagnetic/_events.py → flagnetic-0.2.0/src/flagnetic/events.py +16 -6
  19. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/openfeature.py +64 -13
  20. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/protocol.py +1 -1
  21. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_client.py +132 -8
  22. flagnetic-0.2.0/tests/test_deprecation.py +125 -0
  23. flagnetic-0.2.0/tests/test_docs.py +59 -0
  24. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_evaluator.py +37 -2
  25. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_events.py +28 -0
  26. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_fork.py +62 -0
  27. flagnetic-0.2.0/tests/test_log_names.py +44 -0
  28. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_openfeature.py +42 -1
  29. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_protocol.py +11 -2
  30. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_regex.py +9 -0
  31. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_sse.py +14 -0
  32. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_testing.py +29 -0
  33. {flagnetic-0.1.4 → flagnetic-0.2.0}/uv.lock +69 -69
  34. {flagnetic-0.1.4 → flagnetic-0.2.0}/.gitignore +0 -0
  35. {flagnetic-0.1.4 → flagnetic-0.2.0}/LICENSE +0 -0
  36. {flagnetic-0.1.4 → flagnetic-0.2.0}/pyproject.toml +0 -0
  37. {flagnetic-0.1.4 → flagnetic-0.2.0}/scripts/_unicode_tables/main.go +0 -0
  38. {flagnetic-0.1.4 → flagnetic-0.2.0}/scripts/check_dist.py +0 -0
  39. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_changes.py +0 -0
  40. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_detail.py +0 -0
  41. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/__init__.py +0 -0
  42. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/charset.py +0 -0
  43. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/parser.py +0 -0
  44. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/program.py +0 -0
  45. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/unicode_tables.py +0 -0
  46. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/_re2/vm.py +0 -0
  47. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/bucket.py +0 -0
  48. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/instant.py +0 -0
  49. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/operators.py +0 -0
  50. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_eval/semver.py +0 -0
  51. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/_store.py +0 -0
  52. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/py.typed +0 -0
  53. {flagnetic-0.1.4 → flagnetic-0.2.0}/src/flagnetic/testing.py +0 -0
  54. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/conformance.py +0 -0
  55. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/large_ruleset.py +0 -0
  56. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/mock_server.py +0 -0
  57. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_async.py +0 -0
  58. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_conformance.py +0 -0
  59. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_p99.py +0 -0
  60. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_version.py +0 -0
  61. {flagnetic-0.1.4 → flagnetic-0.2.0}/tests/test_without_openfeature.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flagnetic
3
- Version: 0.1.4
3
+ Version: 0.2.0
4
4
  Summary: Python SDK for Flagnetic, self-hosted feature flags and experiments
5
5
  Project-URL: Homepage, https://github.com/azverinus/flagnetic
6
6
  Project-URL: Source, https://github.com/azverinus/flagnetic/tree/main/sdks/python
@@ -31,6 +31,9 @@ supported upstream (a release reaching its end of life is dropped in a minor ver
31
31
  0.1.0 on ([compatibility](../../docs/sdks/compatibility.md)); [docs/sdks/python.md](../../docs/sdks/python.md) is how
32
32
  it is deployed and tested.
33
33
 
34
+ Because that engine is pure Python, the `matches` operator treats a context value longer than 64 KiB of UTF-8 as a
35
+ non-match, not an error: the cost of a match is the input times the pattern, and a caller chose the input.
36
+
34
37
  ## Quick start
35
38
 
36
39
  ```python
@@ -50,11 +53,15 @@ The getters never block and never raise: they read the ruleset the client holds
50
53
  they cannot serve the flag. One background thread fetches the ruleset with `If-None-Match`, holds the ruleset stream
51
54
  (a kill switch reaches the client within two seconds), polls every 30 seconds while the stream is down, and backs
52
55
  off with jitter. A stream is stable once it has delivered a heartbeat: one the server closes before that (a draining
53
- replica, a proxy that ends the stream early) is a failure like any other and logs `sse_dropped` with the cause
56
+ replica, a proxy that ends the stream early) is a failure like any other and logs `stream_dropped` with the cause
54
57
  `closed_early`, while the close of a stable stream waits 0 to 2 seconds. `store="/var/lib/app/flagnetic.json"` keeps the last good ruleset across restarts. The file is headed
55
58
  by a digest of the SDK key, so one written under another key (another environment's, say) is discarded with
56
59
  `store_failed`.
57
60
 
61
+ A flag value nesting arrays and objects deeper than 32 levels, which the server refuses to store, fails that flag
62
+ alone: its getters serve your default with `inconsistent_ruleset`, `condition_invalid` names the variation once per
63
+ flag and ruleset version, and every other flag of the ruleset serves.
64
+
58
65
  ## Experiments and events
59
66
 
60
67
  The same thread reports an evaluation summary every minute (counts per flag, variation and reason, never a unit ID or
@@ -131,6 +138,9 @@ client.track(
131
138
  )
132
139
  ```
133
140
 
141
+ `track("exposure")` records the exposure of the provider's most recent evaluation of that flag for the same units, with
142
+ the context the evaluation had when a `before` hook added attributes to it, as the client's `exposure` does.
143
+
134
144
  The targeting key is the unit ID of `unit_type`; the `units` attribute adds further units by unit type; every other
135
145
  attribute is an attribute of the context. Reasons map as in every Flagnetic provider:
136
146
 
@@ -151,6 +161,21 @@ is fresh again and `PROVIDER_ERROR` when the SDK key is revoked. Initialization
151
161
  (default 10) for the first fetch and never fails. `provider.client` is the wrapped client, for local overrides,
152
162
  `flush` and the recorder of an offline provider (`Provider("", "", offline=document)`).
153
163
 
164
+ ## What 1.0 promises
165
+
166
+ From 1.0 the public API below changes only additively until 2.0: a name is added, never renamed, removed or given another meaning, and a removal is announced first in a minor release and made in a major one. The public API is:
167
+
168
+ - **Client**: `flagnetic.Client` with its keyword options, the getters `get_bool`, `get_string`, `get_number`, `get_int`, `get_json` and `get_detail`, `ready`, `stage`, `status`, `on_change`, `on_stage`, `exposure`, `alias`, `flush`, `close`, the `aready`, `aflush` and `aclose` forms, `recorder` and `local_overrides`.
169
+ - **Values**: `flagnetic.Context`, `Detail`, `Experiment`, `Stage`, `Status`, `Document` (the accepted forms of an offline ruleset) and, of what `recorder` returns, `Exposure`, `Alias`, `SummaryCount` and `Recorder`.
170
+ - **Local overrides**: `LocalOverrides` and its methods `set`, `remove`, `clear` and `list`.
171
+ - **Errors**: `FlagneticError` and the two it is the base of, `LocalOverridesNotAllowed` and `LocalOverrideRefused`. A bad option is a `ValueError` and an override value of the wrong type a `TypeError`; getters never raise.
172
+ - **Logging**: `Logger`, the hook's type, and the event names in `flagnetic.events`, which are the strings operators alert on.
173
+ - **Tests**: the functions of `flagnetic.testing` and the `TestClient` they return.
174
+ - **OpenFeature**: `flagnetic.openfeature.Provider`, its arguments and the flag metadata it fills.
175
+ - **`flagnetic.__version__`.**
176
+
177
+ Everything else is internal and may change in any release: every module and name starting with an underscore, the modules behind them, and what is not named above. Import the public names from `flagnetic`, `flagnetic.events`, `flagnetic.testing` and `flagnetic.openfeature`.
178
+
154
179
  ## Development
155
180
 
156
181
  ```bash
@@ -13,6 +13,9 @@ supported upstream (a release reaching its end of life is dropped in a minor ver
13
13
  0.1.0 on ([compatibility](../../docs/sdks/compatibility.md)); [docs/sdks/python.md](../../docs/sdks/python.md) is how
14
14
  it is deployed and tested.
15
15
 
16
+ Because that engine is pure Python, the `matches` operator treats a context value longer than 64 KiB of UTF-8 as a
17
+ non-match, not an error: the cost of a match is the input times the pattern, and a caller chose the input.
18
+
16
19
  ## Quick start
17
20
 
18
21
  ```python
@@ -32,11 +35,15 @@ The getters never block and never raise: they read the ruleset the client holds
32
35
  they cannot serve the flag. One background thread fetches the ruleset with `If-None-Match`, holds the ruleset stream
33
36
  (a kill switch reaches the client within two seconds), polls every 30 seconds while the stream is down, and backs
34
37
  off with jitter. A stream is stable once it has delivered a heartbeat: one the server closes before that (a draining
35
- replica, a proxy that ends the stream early) is a failure like any other and logs `sse_dropped` with the cause
38
+ replica, a proxy that ends the stream early) is a failure like any other and logs `stream_dropped` with the cause
36
39
  `closed_early`, while the close of a stable stream waits 0 to 2 seconds. `store="/var/lib/app/flagnetic.json"` keeps the last good ruleset across restarts. The file is headed
37
40
  by a digest of the SDK key, so one written under another key (another environment's, say) is discarded with
38
41
  `store_failed`.
39
42
 
43
+ A flag value nesting arrays and objects deeper than 32 levels, which the server refuses to store, fails that flag
44
+ alone: its getters serve your default with `inconsistent_ruleset`, `condition_invalid` names the variation once per
45
+ flag and ruleset version, and every other flag of the ruleset serves.
46
+
40
47
  ## Experiments and events
41
48
 
42
49
  The same thread reports an evaluation summary every minute (counts per flag, variation and reason, never a unit ID or
@@ -113,6 +120,9 @@ client.track(
113
120
  )
114
121
  ```
115
122
 
123
+ `track("exposure")` records the exposure of the provider's most recent evaluation of that flag for the same units, with
124
+ the context the evaluation had when a `before` hook added attributes to it, as the client's `exposure` does.
125
+
116
126
  The targeting key is the unit ID of `unit_type`; the `units` attribute adds further units by unit type; every other
117
127
  attribute is an attribute of the context. Reasons map as in every Flagnetic provider:
118
128
 
@@ -133,6 +143,21 @@ is fresh again and `PROVIDER_ERROR` when the SDK key is revoked. Initialization
133
143
  (default 10) for the first fetch and never fails. `provider.client` is the wrapped client, for local overrides,
134
144
  `flush` and the recorder of an offline provider (`Provider("", "", offline=document)`).
135
145
 
146
+ ## What 1.0 promises
147
+
148
+ From 1.0 the public API below changes only additively until 2.0: a name is added, never renamed, removed or given another meaning, and a removal is announced first in a minor release and made in a major one. The public API is:
149
+
150
+ - **Client**: `flagnetic.Client` with its keyword options, the getters `get_bool`, `get_string`, `get_number`, `get_int`, `get_json` and `get_detail`, `ready`, `stage`, `status`, `on_change`, `on_stage`, `exposure`, `alias`, `flush`, `close`, the `aready`, `aflush` and `aclose` forms, `recorder` and `local_overrides`.
151
+ - **Values**: `flagnetic.Context`, `Detail`, `Experiment`, `Stage`, `Status`, `Document` (the accepted forms of an offline ruleset) and, of what `recorder` returns, `Exposure`, `Alias`, `SummaryCount` and `Recorder`.
152
+ - **Local overrides**: `LocalOverrides` and its methods `set`, `remove`, `clear` and `list`.
153
+ - **Errors**: `FlagneticError` and the two it is the base of, `LocalOverridesNotAllowed` and `LocalOverrideRefused`. A bad option is a `ValueError` and an override value of the wrong type a `TypeError`; getters never raise.
154
+ - **Logging**: `Logger`, the hook's type, and the event names in `flagnetic.events`, which are the strings operators alert on.
155
+ - **Tests**: the functions of `flagnetic.testing` and the `TestClient` they return.
156
+ - **OpenFeature**: `flagnetic.openfeature.Provider`, its arguments and the flag metadata it fills.
157
+ - **`flagnetic.__version__`.**
158
+
159
+ Everything else is internal and may change in any release: every module and name starting with an underscore, the modules behind them, and what is not named above. Import the public names from `flagnetic`, `flagnetic.events`, `flagnetic.testing` and `flagnetic.openfeature`.
160
+
136
161
  ## Development
137
162
 
138
163
  ```bash
@@ -144,7 +144,7 @@ def test_a_kill_switch_through_replica_a_reaches_the_sdk_streaming_from_replica_
144
144
  context = unit(SEED["units"]["outside_rollout"])
145
145
  client, logs = clients(SEED["replicas"]["b"], poll_interval=3600)
146
146
  assert client.ready(timeout=10) == flagnetic.Stage.FRESH
147
- assert eventually(lambda: "sse_connected" in logs, 10), "the stream to replica B never connected"
147
+ assert eventually(lambda: "stream_connected" in logs, 10), "the stream to replica B never connected"
148
148
  # The replica announces the version the client holds as the stream opens;
149
149
  # give it a moment so that the kill switch is news to it.
150
150
  time.sleep(0.5)
@@ -2,11 +2,12 @@
2
2
 
3
3
  from flagnetic._client import Client, Document
4
4
  from flagnetic._detail import Detail, Experiment, Stage, Status
5
+ from flagnetic._errors import FlagneticError
5
6
  from flagnetic._eval import Context
6
- from flagnetic._events import Logger
7
7
  from flagnetic._overrides import LocalOverrideRefused, LocalOverrides, LocalOverridesNotAllowed
8
8
  from flagnetic._reporting import Alias, Exposure, Recorder, SummaryCount
9
9
  from flagnetic._version import __version__
10
+ from flagnetic.events import Logger
10
11
 
11
12
  __all__ = [
12
13
  "Alias",
@@ -16,6 +17,7 @@ __all__ = [
16
17
  "Document",
17
18
  "Experiment",
18
19
  "Exposure",
20
+ "FlagneticError",
19
21
  "LocalOverrideRefused",
20
22
  "LocalOverrides",
21
23
  "LocalOverridesNotAllowed",
@@ -14,13 +14,13 @@ import threading
14
14
  import time
15
15
  import weakref
16
16
  from collections.abc import Callable, Mapping
17
- from dataclasses import dataclass
17
+ from dataclasses import dataclass, field
18
18
  from datetime import UTC, datetime
19
19
  from pathlib import Path
20
20
  from typing import Any, TypeAlias
21
21
  from urllib.parse import urlsplit
22
22
 
23
- from . import _events, _store
23
+ from . import _store, events
24
24
  from ._changes import changed_flags
25
25
  from ._delivery import (
26
26
  CAUSE_PARSE,
@@ -34,9 +34,9 @@ from ._delivery import (
34
34
  Waits,
35
35
  user_agent,
36
36
  )
37
+ from ._deprecation import DeprecationNotes
37
38
  from ._detail import Detail, Experiment, Stage, Status
38
39
  from ._eval import SCHEMA_VERSION, Context, Ruleset, RulesetError, decode, evaluate, parse
39
- from ._events import Logger, standard_logger
40
40
  from ._ingest import Ingest, event_id
41
41
  from ._overrides import LocalOverride, LocalOverrides
42
42
  from ._reporting import (
@@ -53,6 +53,7 @@ from ._reporting import (
53
53
  fingerprint,
54
54
  )
55
55
  from ._version import __version__
56
+ from .events import Logger, standard_logger
56
57
 
57
58
  #: A ruleset document as the ruleset endpoint serves it: JSON text, its UTF-8 bytes, or the parsed object.
58
59
  Document: TypeAlias = bytes | str | Mapping[str, Any]
@@ -94,7 +95,8 @@ _DETAIL_MEMORY = 10_000
94
95
  class _Online:
95
96
  """What a client that talks to a server was built with, kept to restart its thread after a fork."""
96
97
 
97
- sdk_key: str
98
+ # Out of the repr: error trackers that capture frame locals would record the key with it.
99
+ sdk_key: str = field(repr=False)
98
100
  base_url: str
99
101
  waits: Waits
100
102
  stream: bool
@@ -225,6 +227,7 @@ class Client:
225
227
  self._schema_logged = False
226
228
  self._ready = threading.Event()
227
229
  self._closed = False
230
+ self._closed_logged = False
228
231
  self._lock = threading.Lock()
229
232
  self._listeners: dict[int, Callable[[list[str]], None]] = {}
230
233
  self._stage_listeners: dict[int, Callable[[Stage], None]] = {}
@@ -234,6 +237,12 @@ class Client:
234
237
  self._mismatched: set[str] = set()
235
238
  self._unsupported_logged: dict[str, int] = {}
236
239
  self._invalid_logged: dict[str, int] = {}
240
+ if platform is not None and (
241
+ not isinstance(platform, str) or not platform.isascii() or not platform.isprintable()
242
+ ):
243
+ # The platform goes into the User-Agent header, where a control character or a
244
+ # non-ASCII one makes every request fail.
245
+ raise ValueError("flagnetic: platform holds a character that cannot be part of an HTTP header")
237
246
  self._platform = platform if platform is not None else _system()
238
247
  self._app_version = app_version or ""
239
248
  self._send_summaries = send_summaries
@@ -249,9 +258,9 @@ class Client:
249
258
  self._source: Callable[[], Document] | None = None
250
259
  self._store_path: Path | None = None
251
260
  if allow_overrides:
252
- self._log(logging.WARNING, _events.LOCAL_OVERRIDES_ALLOWED)
261
+ self._log(logging.WARNING, events.LOCAL_OVERRIDES_ALLOWED)
253
262
  if not send_exposures:
254
- self._log(logging.WARNING, _events.EXPOSURES_OFF)
263
+ self._log(logging.WARNING, events.EXPOSURES_OFF)
255
264
 
256
265
  if offline is not None:
257
266
  self._source = offline if callable(offline) else (lambda: offline)
@@ -302,7 +311,9 @@ class Client:
302
311
  unauthorized_cap=waits.unauthorized_cap,
303
312
  )
304
313
  agent = user_agent(__version__, self._platform)
314
+ notes = DeprecationNotes(self._log)
305
315
  ingest = Ingest(
316
+ notes=notes,
306
317
  base_url=online.base_url,
307
318
  sdk_key=online.sdk_key,
308
319
  agent=agent,
@@ -347,6 +358,7 @@ class Client:
347
358
  schema_version=SCHEMA_VERSION,
348
359
  reporter=reporter,
349
360
  ingest=ingest if reporter is not None else None,
361
+ notes=notes,
350
362
  )
351
363
  self._delivery = delivery
352
364
  delivery.start()
@@ -409,14 +421,14 @@ class Client:
409
421
  try:
410
422
  detail = self._detail(loaded, context, key, requested, default)
411
423
  except Exception as err:
412
- self._log(logging.ERROR, _events.EVALUATION_FAILED, flag=key, cause=repr(err))
424
+ self._log(logging.ERROR, events.EVALUATION_FAILED, flag=key, cause=repr(err))
413
425
  detail = self._fallback(loaded, default, _ERROR_GENERAL)
414
426
  try:
415
427
  self._count(key, detail.variation, detail.reason)
416
428
  if self._send_exposures and loaded is not None:
417
429
  self._served_detail(loaded, context, key, detail)
418
430
  except Exception as err:
419
- self._log(logging.ERROR, _events.EVALUATION_FAILED, operation="report", flag=key, cause=repr(err))
431
+ self._log(logging.ERROR, events.EVALUATION_FAILED, operation="report", flag=key, cause=repr(err))
420
432
  return detail
421
433
 
422
434
  def _count(self, flag: str, variation: str, reason: str) -> None:
@@ -498,6 +510,8 @@ class Client:
498
510
  self._mismatch(key, local.type, requested)
499
511
  return self._fallback(loaded, default, _ERROR_TYPE_MISMATCH)
500
512
  served = _served_value(flag_type, local.value)
513
+ if served is _INVALID:
514
+ return self._fallback(loaded, default, _ERROR_INCONSISTENT)
501
515
  if requested == _INT64:
502
516
  served = _as_int64(served)
503
517
  if served is _INVALID:
@@ -529,7 +543,7 @@ class Client:
529
543
  self._mismatched.add(key)
530
544
  self._log(
531
545
  logging.WARNING,
532
- _events.TYPE_MISMATCH,
546
+ events.TYPE_MISMATCH,
533
547
  flag=key,
534
548
  flag_type=flag_type,
535
549
  requested_type="number" if requested == _INT64 else requested,
@@ -615,17 +629,17 @@ class Client:
615
629
  if not self._send_exposures:
616
630
  return
617
631
  if key in self._overrides._by_key and not self._protected():
618
- self._log(logging.DEBUG, _events.EXPOSURE_SKIPPED, flag=key, cause="local_override")
632
+ self._log(logging.DEBUG, events.EXPOSURE_SKIPPED, flag=key, cause="local_override")
619
633
  return
620
634
  served = self._served.recall(key, _fingerprint(context))
621
635
  if served is None:
622
636
  cause = "no_detail" if self._served.ever_carried(key) else "no_experiment"
623
- self._log(logging.DEBUG, _events.EXPOSURE_SKIPPED, flag=key, cause=cause)
637
+ self._log(logging.DEBUG, events.EXPOSURE_SKIPPED, flag=key, cause=cause)
624
638
  return
625
639
  self._emit(context, key, served.reason, served.ruleset_version, served.experiment)
626
640
  except Exception as err:
627
641
  self._log(
628
- logging.ERROR, _events.EVALUATION_FAILED, operation="exposure", flag=key, cause=repr(err)
642
+ logging.ERROR, events.EVALUATION_FAILED, operation="exposure", flag=key, cause=repr(err)
629
643
  )
630
644
 
631
645
  def alias(self, from_unit_type: str, from_unit_id: str, to_unit_type: str, to_unit_id: str) -> None:
@@ -638,7 +652,7 @@ class Client:
638
652
  if self._send_exposures:
639
653
  self._record(alias_of(from_unit_type, from_unit_id, to_unit_type, to_unit_id))
640
654
  except Exception as err:
641
- self._log(logging.ERROR, _events.EVALUATION_FAILED, operation="alias", cause=repr(err))
655
+ self._log(logging.ERROR, events.EVALUATION_FAILED, operation="alias", cause=repr(err))
642
656
 
643
657
  def _emit(
644
658
  self, context: Context, key: str, reason: str, ruleset_version: int, experiment: Experiment
@@ -677,6 +691,12 @@ class Client:
677
691
  if self._recorder is not None:
678
692
  self._recorder._record(event)
679
693
  elif self._queue is not None:
694
+ if self._closed:
695
+ # Nothing sends the queue any more: what is added now would sit in it unreported.
696
+ if not self._closed_logged:
697
+ self._closed_logged = True
698
+ self._log(logging.WARNING, events.EXPOSURE_SKIPPED, cause="closed")
699
+ return
680
700
  self._queue.record(event._wire())
681
701
 
682
702
  def flush(self, timeout: float | None = DEFAULT_CLOSE_TIMEOUT) -> None:
@@ -818,7 +838,7 @@ class Client:
818
838
  self._schema_logged = True
819
839
  self._log(
820
840
  logging.ERROR,
821
- _events.SCHEMA_UNSUPPORTED,
841
+ events.SCHEMA_UNSUPPORTED,
822
842
  schema_version=schema_version,
823
843
  supported=[SCHEMA_VERSION],
824
844
  )
@@ -831,7 +851,7 @@ class Client:
831
851
  self._loaded = _Loaded(ruleset, raw, received_at)
832
852
  self._log(
833
853
  logging.INFO,
834
- _events.RULESET_LOADED,
854
+ events.RULESET_LOADED,
835
855
  source=source,
836
856
  ruleset_version=ruleset.version,
837
857
  flags=len(ruleset.flags),
@@ -857,7 +877,7 @@ class Client:
857
877
  self._unsupported_logged[key] = ruleset.version
858
878
  self._log(
859
879
  logging.ERROR,
860
- _events.RULE_UNSUPPORTED,
880
+ events.RULE_UNSUPPORTED,
861
881
  flag=key,
862
882
  constructs=[f"{c.kind} {c.name}" for c in constructs],
863
883
  ruleset_version=ruleset.version,
@@ -876,7 +896,7 @@ class Client:
876
896
  self._invalid_logged[key] = ruleset.version
877
897
  self._log(
878
898
  logging.ERROR,
879
- _events.CONDITION_INVALID,
899
+ events.CONDITION_INVALID,
880
900
  flag=key,
881
901
  conditions=reasons,
882
902
  ruleset_version=ruleset.version,
@@ -896,7 +916,7 @@ class Client:
896
916
  document, written = found
897
917
  ruleset, raw = self._decode(document)
898
918
  except (OSError, Rejected, _store.StoreRefused) as err:
899
- self._log(logging.WARNING, _events.STORE_FAILED, path=str(path), op="load", cause=str(err))
919
+ self._log(logging.WARNING, events.STORE_FAILED, path=str(path), op="load", cause=str(err))
900
920
  return
901
921
  # The file was written when the ruleset was received, so its age shows through received_at.
902
922
  self._swap(ruleset, raw, "store", datetime.fromtimestamp(written, UTC))
@@ -910,7 +930,7 @@ class Client:
910
930
  _store.write(self._store_path, online.sdk_key, document)
911
931
  except OSError as err:
912
932
  self._log(
913
- logging.WARNING, _events.STORE_FAILED, path=str(self._store_path), op="save", cause=str(err)
933
+ logging.WARNING, events.STORE_FAILED, path=str(self._store_path), op="save", cause=str(err)
914
934
  )
915
935
 
916
936
  def _set_stage(self, stage: Stage) -> None:
@@ -921,7 +941,7 @@ class Client:
921
941
  self._stage = stage
922
942
  self._log(
923
943
  logging.INFO if stage == Stage.FRESH else logging.WARNING,
924
- _events.STAGE_CHANGED,
944
+ events.STAGE_CHANGED,
925
945
  **{"from": previous.value, "to": stage.value},
926
946
  )
927
947
  with self._lock:
@@ -941,7 +961,7 @@ class Client:
941
961
  try:
942
962
  listener(argument)
943
963
  except Exception as err:
944
- self._log(logging.ERROR, _events.LISTENER_FAILED, cause=repr(err))
964
+ self._log(logging.ERROR, events.LISTENER_FAILED, cause=repr(err))
945
965
 
946
966
 
947
967
  class _Host:
@@ -978,7 +998,7 @@ class _Host:
978
998
  fields: dict[str, Any] = {"cause": cause, "error": error}
979
999
  if status:
980
1000
  fields["status"] = status
981
- client._log(logging.WARNING, _events.FETCH_FAILED, **fields)
1001
+ client._log(logging.WARNING, events.FETCH_FAILED, **fields)
982
1002
  if client._stale_since is None:
983
1003
  client._stale_since = datetime.now(UTC)
984
1004
  if client._stage == Stage.FRESH:
@@ -989,7 +1009,7 @@ class _Host:
989
1009
  client = self._client
990
1010
  if not client._revoked:
991
1011
  client._revoked = True
992
- client._log(logging.ERROR, _events.KEY_REVOKED, status=status)
1012
+ client._log(logging.ERROR, events.KEY_REVOKED, status=status)
993
1013
 
994
1014
  def log(self, level: int, event: str, **fields: Any) -> None:
995
1015
  self._client._log(level, event, **fields)
@@ -20,12 +20,12 @@ import ssl
20
20
  import threading
21
21
  import time
22
22
  import zlib
23
- from collections.abc import Callable
24
23
  from dataclasses import dataclass
25
24
  from typing import TYPE_CHECKING, Any, Protocol, cast
26
25
  from urllib.parse import urlsplit
27
26
 
28
- from . import _events
27
+ from . import events
28
+ from ._deprecation import DeprecationNotes
29
29
  from ._sse import ChunkedDecoder, EventStreamParser, Frame, StreamError
30
30
 
31
31
  if TYPE_CHECKING:
@@ -39,6 +39,9 @@ DEFAULT_REQUEST_TIMEOUT = 10.0
39
39
  DEFAULT_POLL_INTERVAL = 300.0
40
40
  MIN_POLL_INTERVAL = 30.0
41
41
  DEFAULT_DOWN_POLL_INTERVAL = 30.0
42
+ # How long the first fetch waits for the first attempt to open the stream: a stream endpoint slow to
43
+ # answer must not keep the ruleset from being fetched.
44
+ FIRST_STREAM_WAIT = 2.0
42
45
  RETRY_BASE = 1.0
43
46
  RETRY_CAP = 300.0
44
47
  UNAUTHORIZED_CAP = 900.0
@@ -58,7 +61,7 @@ MAX_RULESET_BYTES = 256 << 20
58
61
 
59
62
  RULESET_EVENT = "ruleset"
60
63
 
61
- # Causes of fetch_failed and sse_dropped.
64
+ # Causes of fetch_failed and stream_dropped.
62
65
  CAUSE_TIMEOUT = "timeout"
63
66
  CAUSE_NETWORK = "network"
64
67
  CAUSE_HTTP_STATUS = "http_status"
@@ -89,6 +92,7 @@ class Waits:
89
92
  """
90
93
 
91
94
  request_timeout: float
95
+ first_stream: float
92
96
  poll: float
93
97
  down_poll: float
94
98
  retry_base: float
@@ -111,6 +115,7 @@ class Waits:
111
115
  poll = DEFAULT_POLL_INTERVAL if poll_interval is None else poll_interval
112
116
  return cls(
113
117
  request_timeout=request_timeout,
118
+ first_stream=min(request_timeout, FIRST_STREAM_WAIT / divisor),
114
119
  poll=max(poll / divisor, MIN_POLL_INTERVAL / divisor),
115
120
  down_poll=down_poll_interval / divisor,
116
121
  retry_base=RETRY_BASE / divisor,
@@ -235,10 +240,10 @@ class Delivery:
235
240
  schema_version: int,
236
241
  reporter: Reporter | None = None,
237
242
  ingest: Ingest | None = None,
238
- ssl_context: ssl.SSLContext | None = None,
239
- sleep_hook: Callable[[], None] | None = None,
243
+ notes: DeprecationNotes,
240
244
  ) -> None:
241
245
  self._host = host
246
+ self._notes = notes
242
247
  self._reporter = reporter
243
248
  # The reporter's connection to the events endpoint, cut at close like the ruleset's.
244
249
  self._ingest = ingest
@@ -254,7 +259,6 @@ class Delivery:
254
259
  self._stream_enabled = stream
255
260
  self._agent = agent
256
261
  self._schema_version = schema_version
257
- self._ssl_context = ssl_context
258
262
  self._closing = threading.Event()
259
263
  self._wake_read, self._wake_write = socket.socketpair()
260
264
  self._wake_read.setblocking(False)
@@ -282,6 +286,8 @@ class Delivery:
282
286
  self._parser = EventStreamParser()
283
287
  self._stream_connected = False
284
288
  self._stream_stopped = False
289
+ self._fetch_successes = 0
290
+ self._reopen_after = 0
285
291
  self._stream_failures = 0
286
292
  self._next_stream = 0.0
287
293
  # The stream has delivered a heartbeat, which is what makes it stable.
@@ -386,7 +392,7 @@ class Delivery:
386
392
  self._crash_kinds.add(kind)
387
393
  with contextlib.suppress(Exception):
388
394
  self._host.log(
389
- logging.ERROR, _events.EVALUATION_FAILED, flag="", cause=f"delivery thread: {err!r}"
395
+ logging.ERROR, events.EVALUATION_FAILED, flag="", cause=f"delivery thread: {err!r}"
390
396
  )
391
397
 
392
398
  def _recover(self) -> None:
@@ -469,9 +475,11 @@ class Delivery:
469
475
 
470
476
  def _connection(self, secure: bool, stream: bool) -> http.client.HTTPConnection:
471
477
  timeout = self._waits.request_timeout
478
+ if stream and not self._first_attempt_done:
479
+ timeout = self._waits.first_stream
472
480
  if secure:
473
481
  cls = _SecureStreamConnection if stream else http.client.HTTPSConnection
474
- return cls(self._netloc_host, self._port, timeout=timeout, context=self._ssl_context)
482
+ return cls(self._netloc_host, self._port, timeout=timeout)
475
483
  cls_plain = _StreamConnection if stream else http.client.HTTPConnection
476
484
  return cls_plain(self._netloc_host, self._port, timeout=timeout)
477
485
 
@@ -493,6 +501,12 @@ class Delivery:
493
501
  )
494
502
  else:
495
503
  self._fetch_failures = 0
504
+ self._fetch_successes += 1
505
+ if self._stream_stopped and self._fetch_successes > self._reopen_after:
506
+ # The key that was refused on the stream answers the fetch: a restored key, or a
507
+ # refusal that was a proxy's, so the stream is tried again.
508
+ self._stream_stopped = False
509
+ self._next_stream = now
496
510
  if self._target != self._announced:
497
511
  self._announced, self._catch_ups = self._target, 0
498
512
  if self._host.held_version() < self._announced and self._catch_ups < len(self._waits.catch_up):
@@ -525,6 +539,7 @@ class Delivery:
525
539
  return _FETCH_CLOSING
526
540
  send_request(conn, "GET", self._ruleset_path, headers)
527
541
  resp = conn.getresponse()
542
+ self._notes.observe("GET", self._ruleset_path, resp)
528
543
  status = resp.status
529
544
  if status == 304:
530
545
  if held:
@@ -568,7 +583,9 @@ class Delivery:
568
583
  def _read_body(resp: http.client.HTTPResponse, deadline: float) -> bytes:
569
584
  """The body, gunzipped when the server did, read in pieces so that a slow one meets the deadline."""
570
585
  gzipped = (resp.getheader("Content-Encoding") or "").lower() == "gzip"
586
+ decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) if gzipped else None
571
587
  parts: list[bytes] = []
588
+ wire = 0
572
589
  size = 0
573
590
  while True:
574
591
  if time.monotonic() > deadline:
@@ -576,20 +593,24 @@ class Delivery:
576
593
  piece = resp.read(1 << 16)
577
594
  if not piece:
578
595
  break
579
- parts.append(piece)
596
+ # The wire is bounded as well as the document: a gzipped body is otherwise held whole
597
+ # before anything is known about it.
598
+ wire += len(piece)
599
+ if wire > MAX_RULESET_BYTES:
600
+ raise ValueError(f"ruleset larger than {MAX_RULESET_BYTES} bytes")
601
+ if decompressor is not None:
602
+ # Decompressed piece by piece, each capped at what the document may still grow
603
+ # by, so a small body that expands enormously is never held.
604
+ piece = decompressor.decompress(piece, MAX_RULESET_BYTES - size + 1)
605
+ if decompressor.unconsumed_tail:
606
+ raise ValueError(f"ruleset larger than {MAX_RULESET_BYTES} bytes")
580
607
  size += len(piece)
581
- if not gzipped and size > MAX_RULESET_BYTES:
608
+ if size > MAX_RULESET_BYTES:
582
609
  raise ValueError(f"ruleset larger than {MAX_RULESET_BYTES} bytes")
583
- body = b"".join(parts)
584
- if not gzipped:
585
- return body
586
- decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
587
- out = decompressor.decompress(body, MAX_RULESET_BYTES + 1)
588
- if len(out) > MAX_RULESET_BYTES:
589
- raise ValueError(f"ruleset larger than {MAX_RULESET_BYTES} bytes")
590
- if not decompressor.eof:
610
+ parts.append(piece)
611
+ if decompressor is not None and not decompressor.eof:
591
612
  raise EOFError("gzip stream ends early")
592
- return out
613
+ return b"".join(parts)
593
614
 
594
615
  # -- the ruleset stream ------------------------------------------------
595
616
 
@@ -618,6 +639,7 @@ class Delivery:
618
639
  return
619
640
  send_request(conn, "GET", self._stream_path, headers)
620
641
  resp = conn.getresponse()
642
+ self._notes.observe("GET", self._stream_path, resp)
621
643
  except TimeoutError as err:
622
644
  conn.close()
623
645
  self._first_attempt_done = True
@@ -640,13 +662,16 @@ class Delivery:
640
662
  host.key_revoked(resp.status)
641
663
  host.log(
642
664
  logging.WARNING,
643
- _events.SSE_DROPPED,
665
+ events.STREAM_DROPPED,
644
666
  cause=CAUSE_UNAUTHORIZED,
645
667
  error=f"stream: {resp.status} {resp.reason}",
646
668
  reconnect=False,
647
669
  status=resp.status,
648
670
  )
649
671
  self._stream_stopped = True
672
+ # The fetch that follows a refusal at startup shows nothing the refusal did not: the
673
+ # stream is tried again by the one after it.
674
+ self._reopen_after = max(self._fetch_successes, 1)
650
675
  return
651
676
  if resp.status != 200:
652
677
  conn.close()
@@ -665,7 +690,7 @@ class Delivery:
665
690
  now = time.monotonic()
666
691
  self._last_data = now
667
692
  self._stream_stable = False
668
- host.log(logging.INFO, _events.SSE_CONNECTED, last_event_id=last_event_id)
693
+ host.log(logging.INFO, events.STREAM_CONNECTED, last_event_id=last_event_id)
669
694
  if not self._first_connect:
670
695
  # Versions may have been missed while the stream was down.
671
696
  self._wake_fetch = True
@@ -675,7 +700,7 @@ class Delivery:
675
700
  fields: dict[str, Any] = {"cause": cause, "error": str(err), "reconnect": True}
676
701
  if status:
677
702
  fields["status"] = status
678
- self._host.log(logging.WARNING, _events.SSE_DROPPED, **fields)
703
+ self._host.log(logging.WARNING, events.STREAM_DROPPED, **fields)
679
704
  self._stream_failures += 1
680
705
  self._next_stream = time.monotonic() + full_jitter(
681
706
  backoff_ceiling(self._stream_failures, self._waits.retry_base, self._waits.stream_retry_cap)
@@ -738,16 +763,20 @@ class Delivery:
738
763
  return True
739
764
 
740
765
  def _stream_dropped(self, cause: str, error: str, *, errored: bool) -> None:
741
- """Logs sse_dropped, closes the connection and schedules the reconnect."""
766
+ """Logs stream_dropped, closes the connection and schedules the reconnect."""
742
767
  if cause == CAUSE_SERVER_CLOSED and not self._stream_stable:
743
768
  # A stream is stable once it has delivered a heartbeat. One the server ends before
744
769
  # that is a failed connection, so a draining replica or a proxy that closes every
745
770
  # stream at once is backed off from instead of reconnected to every other second.
746
771
  cause, errored = CAUSE_CLOSED_EARLY, True
747
772
  level = logging.WARNING if errored or cause != CAUSE_SERVER_CLOSED else logging.INFO
748
- self._host.log(level, _events.SSE_DROPPED, cause=cause, error=error, reconnect=True)
773
+ self._host.log(level, events.STREAM_DROPPED, cause=cause, error=error, reconnect=True)
749
774
  now = time.monotonic()
750
775
  self._drop_stream_connection()
776
+ # The fetch scheduled while the stream was up may be a poll interval away; without the
777
+ # stream, a change is noticed only by fetching, so the safety poll takes over at once.
778
+ if self._next_fetch is not None and self._next_fetch > now + self._waits.down_poll:
779
+ self._next_fetch = now + self._waits.down_poll
751
780
  if self._stream_stable:
752
781
  self._stream_failures = 0
753
782
  if errored: