flagnetic 0.1.2__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {flagnetic-0.1.2 → flagnetic-0.1.4}/PKG-INFO +6 -2
  2. {flagnetic-0.1.2 → flagnetic-0.1.4}/README.md +5 -1
  3. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_client.py +40 -10
  4. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_delivery.py +47 -9
  5. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/charset.py +15 -2
  6. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/ruleset.py +43 -2
  7. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_events.py +12 -5
  8. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_ingest.py +7 -5
  9. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_reporting.py +22 -1
  10. flagnetic-0.1.4/src/flagnetic/_store.py +78 -0
  11. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_version.py +1 -1
  12. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/protocol.py +2 -1
  13. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_client.py +222 -2
  14. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_events.py +48 -0
  15. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_protocol.py +11 -2
  16. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_regex.py +21 -0
  17. flagnetic-0.1.2/src/flagnetic/_store.py +0 -35
  18. {flagnetic-0.1.2 → flagnetic-0.1.4}/.gitignore +0 -0
  19. {flagnetic-0.1.2 → flagnetic-0.1.4}/LICENSE +0 -0
  20. {flagnetic-0.1.2 → flagnetic-0.1.4}/e2e/test_smoke.py +0 -0
  21. {flagnetic-0.1.2 → flagnetic-0.1.4}/pyproject.toml +0 -0
  22. {flagnetic-0.1.2 → flagnetic-0.1.4}/scripts/_unicode_tables/main.go +0 -0
  23. {flagnetic-0.1.2 → flagnetic-0.1.4}/scripts/check_dist.py +0 -0
  24. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/__init__.py +0 -0
  25. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_changes.py +0 -0
  26. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_detail.py +0 -0
  27. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/__init__.py +0 -0
  28. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/__init__.py +0 -0
  29. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/parser.py +0 -0
  30. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/program.py +0 -0
  31. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/unicode_tables.py +0 -0
  32. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/_re2/vm.py +0 -0
  33. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/bucket.py +0 -0
  34. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/evaluate.py +0 -0
  35. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/instant.py +0 -0
  36. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/model.py +0 -0
  37. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/operators.py +0 -0
  38. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_eval/semver.py +0 -0
  39. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_overrides.py +0 -0
  40. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/_sse.py +0 -0
  41. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/openfeature.py +0 -0
  42. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/py.typed +0 -0
  43. {flagnetic-0.1.2 → flagnetic-0.1.4}/src/flagnetic/testing.py +0 -0
  44. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/conformance.py +0 -0
  45. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/large_ruleset.py +0 -0
  46. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/mock_server.py +0 -0
  47. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_async.py +0 -0
  48. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_conformance.py +0 -0
  49. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_evaluator.py +0 -0
  50. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_fork.py +0 -0
  51. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_openfeature.py +0 -0
  52. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_p99.py +0 -0
  53. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_sse.py +0 -0
  54. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_testing.py +0 -0
  55. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_version.py +0 -0
  56. {flagnetic-0.1.2 → flagnetic-0.1.4}/tests/test_without_openfeature.py +0 -0
  57. {flagnetic-0.1.2 → flagnetic-0.1.4}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flagnetic
3
- Version: 0.1.2
3
+ Version: 0.1.4
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
@@ -49,7 +49,11 @@ client.close()
49
49
  The getters never block and never raise: they read the ruleset the client holds and serve the default you pass when
50
50
  they cannot serve the flag. One background thread fetches the ruleset with `If-None-Match`, holds the ruleset stream
51
51
  (a kill switch reaches the client within two seconds), polls every 30 seconds while the stream is down, and backs
52
- off with jitter. `store="/var/lib/app/flagnetic.json"` keeps the last good ruleset across restarts.
52
+ 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
54
+ `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
+ by a digest of the SDK key, so one written under another key (another environment's, say) is discarded with
56
+ `store_failed`.
53
57
 
54
58
  ## Experiments and events
55
59
 
@@ -31,7 +31,11 @@ client.close()
31
31
  The getters never block and never raise: they read the ruleset the client holds and serve the default you pass when
32
32
  they cannot serve the flag. One background thread fetches the ruleset with `If-None-Match`, holds the ruleset stream
33
33
  (a kill switch reaches the client within two seconds), polls every 30 seconds while the stream is down, and backs
34
- off with jitter. `store="/var/lib/app/flagnetic.json"` keeps the last good ruleset across restarts.
34
+ 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
36
+ `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
+ by a digest of the SDK key, so one written under another key (another environment's, say) is discarded with
38
+ `store_failed`.
35
39
 
36
40
  ## Experiments and events
37
41
 
@@ -144,8 +144,10 @@ class Client:
144
144
  ``store``
145
145
  A file path. Every accepted ruleset is written there, readable by its
146
146
  owner only, and loaded at construction as ``last_good`` before any
147
- network call. A ruleset the store cannot load or save logs
148
- ``store_failed``; a corrupt file leaves the client at ``built_in``.
147
+ network call. The file is headed by a SHA-256 digest of ``sdk_key``:
148
+ one written under another key, or under none, is discarded. A ruleset
149
+ the store cannot load or save logs ``store_failed``; a corrupt or
150
+ discarded file leaves the client at ``built_in``.
149
151
  ``logger``
150
152
  A hook called with ``(level, event, fields)`` for every log event, from
151
153
  any thread; the default sends them to the ``flagnetic`` logger of
@@ -231,6 +233,7 @@ class Client:
231
233
  # version whose unsupported rules were last logged.
232
234
  self._mismatched: set[str] = set()
233
235
  self._unsupported_logged: dict[str, int] = {}
236
+ self._invalid_logged: dict[str, int] = {}
234
237
  self._platform = platform if platform is not None else _system()
235
238
  self._app_version = app_version or ""
236
239
  self._send_summaries = send_summaries
@@ -258,6 +261,11 @@ class Client:
258
261
 
259
262
  if not isinstance(sdk_key, str) or not sdk_key:
260
263
  raise ValueError("flagnetic: the SDK key is empty")
264
+ if not sdk_key.isascii() or not sdk_key.isprintable() or any(c.isspace() for c in sdk_key):
265
+ # A trailing newline from an env file is the usual cause. The key is not repeated: it is a secret.
266
+ raise ValueError(
267
+ "flagnetic: the SDK key holds whitespace or a character that cannot be part of an HTTP header"
268
+ )
261
269
  if sdk_key.startswith(_CLIENT_KEY_PREFIX):
262
270
  raise ValueError(
263
271
  "flagnetic: a client SDK key cannot fetch the ruleset; the Python SDK needs a server key"
@@ -268,7 +276,7 @@ class Client:
268
276
 
269
277
  self._store_path = Path(store) if store is not None else None
270
278
  if self._store_path is not None:
271
- self._load_store(self._store_path)
279
+ self._load_store(self._store_path, sdk_key)
272
280
  self._online = _Online(
273
281
  sdk_key=sdk_key,
274
282
  base_url=base_url,
@@ -829,6 +837,7 @@ class Client:
829
837
  flags=len(ruleset.flags),
830
838
  )
831
839
  self._report_unsupported(ruleset)
840
+ self._report_invalid(ruleset)
832
841
  changed = changed_flags(None if previous is None else previous.document, raw)
833
842
  dropped = self._overrides._refuse(ruleset)
834
843
  return sorted(set(changed) | set(dropped)) if dropped else changed
@@ -854,19 +863,39 @@ class Client:
854
863
  ruleset_version=ruleset.version,
855
864
  )
856
865
 
857
- def _load_store(self, path: Path) -> None:
866
+ def _report_invalid(self, ruleset: Ruleset) -> None:
867
+ """Logs condition_invalid for every flag holding a condition this evaluator cannot evaluate.
868
+
869
+ Once per flag and ruleset version, when the ruleset loads: the flag
870
+ serves its default wherever evaluation reaches the condition, and
871
+ nothing else says why.
872
+ """
873
+ for key, reasons in sorted(ruleset.invalid_conditions().items()):
874
+ if self._invalid_logged.get(key) == ruleset.version:
875
+ continue
876
+ self._invalid_logged[key] = ruleset.version
877
+ self._log(
878
+ logging.ERROR,
879
+ _events.CONDITION_INVALID,
880
+ flag=key,
881
+ conditions=reasons,
882
+ ruleset_version=ruleset.version,
883
+ )
884
+
885
+ def _load_store(self, path: Path, sdk_key: str) -> None:
858
886
  """Seeds the client with the ruleset persisted at ``path`` as last_good.
859
887
 
860
- An absent file is a first start; an unreadable or invalid one logs
861
- store_failed and leaves the client at built_in.
888
+ An absent file is a first start; an unreadable or invalid one, or one
889
+ written under another key, logs store_failed and leaves the client at
890
+ built_in.
862
891
  """
863
892
  try:
864
- found = _store.read(path)
893
+ found = _store.read(path, sdk_key)
865
894
  if found is None:
866
895
  return
867
896
  document, written = found
868
897
  ruleset, raw = self._decode(document)
869
- except (OSError, Rejected) as err:
898
+ except (OSError, Rejected, _store.StoreRefused) as err:
870
899
  self._log(logging.WARNING, _events.STORE_FAILED, path=str(path), op="load", cause=str(err))
871
900
  return
872
901
  # The file was written when the ruleset was received, so its age shows through received_at.
@@ -874,10 +903,11 @@ class Client:
874
903
  self._set_stage(Stage.LAST_GOOD)
875
904
 
876
905
  def _persist(self, document: bytes) -> None:
877
- if self._store_path is None:
906
+ online = self._online
907
+ if self._store_path is None or online is None:
878
908
  return
879
909
  try:
880
- _store.write(self._store_path, document)
910
+ _store.write(self._store_path, online.sdk_key, document)
881
911
  except OSError as err:
882
912
  self._log(
883
913
  logging.WARNING, _events.STORE_FAILED, path=str(self._store_path), op="save", cause=str(err)
@@ -45,9 +45,10 @@ UNAUTHORIZED_CAP = 900.0
45
45
  # The server sends a comment every 15 seconds, so three missed ones reconnect.
46
46
  HEARTBEAT_TIMEOUT = 45.0
47
47
  STREAM_RETRY_CAP = 30.0
48
- # A server-side close is routine: the platform closes every stream after about an hour.
48
+ # The close of a stable stream (one that has delivered a heartbeat) is routine: the platform
49
+ # closes every stream after about an hour.
49
50
  CLOSE_JITTER_CAP = 2.0
50
- # How long a connection must hold for the reconnect backoff to start from the base again.
51
+ # How long the delivery loop must run for the backoff after a crash to start from the base again.
51
52
  STABLE_FOR = 60.0
52
53
  # The waits before re-fetching when the ruleset endpoint answered below the version an event
53
54
  # announced, a replica still behind. After the last one the safety poll takes over.
@@ -67,6 +68,9 @@ CAUSE_SCHEMA_UNSUPPORTED = "schema_unsupported"
67
68
  CAUSE_WRONG_SCOPE = "wrong_scope"
68
69
  CAUSE_VERSION_DOWNGRADE = "version_downgrade"
69
70
  CAUSE_SERVER_CLOSED = "server_closed"
71
+ # A stream the server closed before its first heartbeat, as a draining replica or a proxy that
72
+ # ends an event stream early does.
73
+ CAUSE_CLOSED_EARLY = "closed_early"
70
74
  CAUSE_SILENCE = "silence"
71
75
  CAUSE_MALFORMED = "malformed"
72
76
 
@@ -155,6 +159,27 @@ class Host(Protocol):
155
159
  _MAX_DOUBLINGS = 64
156
160
 
157
161
 
162
+ class RequestNotBuilt(http.client.HTTPException):
163
+ """The HTTP library refused a request: names the error, never its text, which may hold a header."""
164
+
165
+
166
+ def send_request(
167
+ conn: http.client.HTTPConnection,
168
+ method: str,
169
+ path: str,
170
+ headers: dict[str, str],
171
+ body: bytes | None = None,
172
+ ) -> None:
173
+ """``conn.request`` with a refusal to build the request reported by its class alone.
174
+
175
+ ``http.client`` quotes the offending header in its ``ValueError``; the Authorization header is the key.
176
+ """
177
+ try:
178
+ conn.request(method, path, body=body, headers=headers)
179
+ except ValueError as err:
180
+ raise RequestNotBuilt(f"request not built: {type(err).__name__}") from None
181
+
182
+
158
183
  def backoff_ceiling(failures: int, base: float, limit: float) -> float:
159
184
  """The exponential ceiling of the nth consecutive failure: the base doubling up to the limit."""
160
185
  doublings = min(max(failures - 1, 0), _MAX_DOUBLINGS)
@@ -259,7 +284,8 @@ class Delivery:
259
284
  self._stream_stopped = False
260
285
  self._stream_failures = 0
261
286
  self._next_stream = 0.0
262
- self._stream_started = 0.0
287
+ # The stream has delivered a heartbeat, which is what makes it stable.
288
+ self._stream_stable = False
263
289
  self._last_data = 0.0
264
290
  self._first_attempt_done = not stream
265
291
  self._first_connect = True
@@ -497,7 +523,7 @@ class Delivery:
497
523
  # A close that came while connecting found no socket to shut down.
498
524
  if self._closing.is_set():
499
525
  return _FETCH_CLOSING
500
- conn.request("GET", self._ruleset_path, headers=headers)
526
+ send_request(conn, "GET", self._ruleset_path, headers)
501
527
  resp = conn.getresponse()
502
528
  status = resp.status
503
529
  if status == 304:
@@ -590,7 +616,7 @@ class Delivery:
590
616
  if self._closing.is_set():
591
617
  conn.close()
592
618
  return
593
- conn.request("GET", self._stream_path, headers=headers)
619
+ send_request(conn, "GET", self._stream_path, headers)
594
620
  resp = conn.getresponse()
595
621
  except TimeoutError as err:
596
622
  conn.close()
@@ -637,7 +663,8 @@ class Delivery:
637
663
  self._parser = EventStreamParser()
638
664
  self._stream_connected = True
639
665
  now = time.monotonic()
640
- self._stream_started = self._last_data = now
666
+ self._last_data = now
667
+ self._stream_stable = False
641
668
  host.log(logging.INFO, _events.SSE_CONNECTED, last_event_id=last_event_id)
642
669
  if not self._first_connect:
643
670
  # Versions may have been missed while the stream was down.
@@ -669,6 +696,10 @@ class Delivery:
669
696
  self._stream_dropped(CAUSE_NETWORK, str(err) or type(err).__name__, errored=True)
670
697
  return
671
698
  if not data:
699
+ # stop() shuts the socket down, which reads as an EOF here: the SDK's own close is not
700
+ # a server close, and before a heartbeat it would otherwise be logged as closed_early.
701
+ if self._closing.is_set():
702
+ return
672
703
  self._stream_dropped(CAUSE_SERVER_CLOSED, "EOF", errored=False)
673
704
  return
674
705
  try:
@@ -686,7 +717,10 @@ class Delivery:
686
717
 
687
718
  def _frame(self, frame: Frame) -> bool:
688
719
  """Acts on a frame; False when the stream was dropped over it."""
689
- if frame.comment or frame.event != RULESET_EVENT:
720
+ if frame.comment:
721
+ self._stream_stable = True
722
+ return True
723
+ if frame.event != RULESET_EVENT:
690
724
  return True
691
725
  try:
692
726
  announced = json.loads(frame.data)
@@ -705,12 +739,16 @@ class Delivery:
705
739
 
706
740
  def _stream_dropped(self, cause: str, error: str, *, errored: bool) -> None:
707
741
  """Logs sse_dropped, closes the connection and schedules the reconnect."""
742
+ if cause == CAUSE_SERVER_CLOSED and not self._stream_stable:
743
+ # A stream is stable once it has delivered a heartbeat. One the server ends before
744
+ # that is a failed connection, so a draining replica or a proxy that closes every
745
+ # stream at once is backed off from instead of reconnected to every other second.
746
+ cause, errored = CAUSE_CLOSED_EARLY, True
708
747
  level = logging.WARNING if errored or cause != CAUSE_SERVER_CLOSED else logging.INFO
709
748
  self._host.log(level, _events.SSE_DROPPED, cause=cause, error=error, reconnect=True)
710
749
  now = time.monotonic()
711
- held_for = now - self._stream_started
712
750
  self._drop_stream_connection()
713
- if held_for >= self._waits.stable_for:
751
+ if self._stream_stable:
714
752
  self._stream_failures = 0
715
753
  if errored:
716
754
  self._stream_failures += 1
@@ -121,10 +121,16 @@ def canonical_name(name: str) -> str:
121
121
 
122
122
 
123
123
  @cache
124
- def _aliases() -> dict[str, str]:
124
+ def _category_aliases() -> dict[str, str]:
125
125
  return {canonical_name(alias): actual for alias, actual in tables.CATEGORY_ALIASES.items()}
126
126
 
127
127
 
128
+ @cache
129
+ def _script_names() -> dict[str, str]:
130
+ """Go's aliases.scripts: a script by its canonical name, so Old_Italic is read as OldItalic."""
131
+ return {canonical_name(name): name for name in tables.SCRIPTS}
132
+
133
+
128
134
  def _lookup(name: str) -> tuple[Ranges, Ranges, int] | None:
129
135
  """Go's unicodeTable: the table, the characters folding into it, and its sign."""
130
136
  if name == "Any":
@@ -143,13 +149,20 @@ def _lookup(name: str) -> tuple[Ranges, Ranges, int] | None:
143
149
  ):
144
150
  if name in table:
145
151
  return _decode(table[name]), _decode(folds[name]) if name in folds else [], 1
146
- actual = _aliases().get(name)
152
+ actual = _category_aliases().get(name)
147
153
  if actual is not None:
148
154
  return (
149
155
  _decode(tables.CATEGORIES[actual]),
150
156
  _decode(tables.FOLD_CATEGORIES[actual]) if actual in tables.FOLD_CATEGORIES else [],
151
157
  1,
152
158
  )
159
+ script = _script_names().get(name)
160
+ if script is not None:
161
+ return (
162
+ _decode(tables.SCRIPTS[script]),
163
+ _decode(tables.FOLD_SCRIPTS[script]) if script in tables.FOLD_SCRIPTS else [],
164
+ 1,
165
+ )
153
166
  return None
154
167
 
155
168
 
@@ -41,6 +41,7 @@ class Condition:
41
41
  __slots__ = (
42
42
  "attribute",
43
43
  "broken",
44
+ "error",
44
45
  "flag",
45
46
  "kind",
46
47
  "match",
@@ -53,6 +54,9 @@ class Condition:
53
54
  def __init__(self, kind: str) -> None:
54
55
  self.kind = kind
55
56
  self.broken = False
57
+ # Why the condition cannot be evaluated, set beside broken when the
58
+ # cause is not an unknown construct.
59
+ self.error = ""
56
60
  # Set beside broken when the condition holds an operator or condition
57
61
  # kind this evaluator does not know.
58
62
  self.unsupported: Construct | None = None
@@ -138,7 +142,16 @@ class Ruleset:
138
142
  so any number of threads read it at once without a lock.
139
143
  """
140
144
 
141
- __slots__ = ("environment_key", "flags", "keys", "protected", "segments", "unsupported", "version")
145
+ __slots__ = (
146
+ "environment_key",
147
+ "flags",
148
+ "invalid",
149
+ "keys",
150
+ "protected",
151
+ "segments",
152
+ "unsupported",
153
+ "version",
154
+ )
142
155
 
143
156
  version: int
144
157
  environment_key: str
@@ -147,6 +160,7 @@ class Ruleset:
147
160
  segments: dict[str, Segment]
148
161
  keys: tuple[str, ...]
149
162
  unsupported: dict[str, list[Construct]]
163
+ invalid: dict[str, list[str]]
150
164
 
151
165
  def flag(self, key: str) -> Flag | None:
152
166
  """The flag with key, as the document has it, or None."""
@@ -161,6 +175,17 @@ class Ruleset:
161
175
  """
162
176
  return {key: list(constructs) for key, constructs in self.unsupported.items()}
163
177
 
178
+ def invalid_conditions(self) -> dict[str, list[str]]:
179
+ """Why conditions of each flag cannot be evaluated by this evaluator, by flag key.
180
+
181
+ Apart from the unsupported constructs ``unsupported_rules`` reports: a
182
+ pattern outside what it reads, an undeclared attribute, a value of the
183
+ wrong type. Each reason comes once, in document order, for the
184
+ conditions of the flag's rules and of the segments they name. A flag
185
+ with none is absent.
186
+ """
187
+ return {key: list(reasons) for key, reasons in self.invalid.items()}
188
+
164
189
 
165
190
  # Go's int and int64, the widest integer a ruleset member holds: every
166
191
  # evaluator refuses a document whose integer does not fit, as Go's decoder does.
@@ -313,11 +338,13 @@ def _compile_condition(
313
338
  attribute_type = types.get(attribute)
314
339
  if attribute_type is None:
315
340
  cond.broken = True
341
+ cond.error = f"attribute {attribute!r} is not declared"
316
342
  return cond
317
343
  try:
318
344
  cond.match = compile_operator(attribute_type, op, raw.get("value"))
319
- except OperatorError:
345
+ except OperatorError as err:
320
346
  cond.broken = True
347
+ cond.error = f"attribute {attribute!r}: {err}"
321
348
  return cond
322
349
  cond.attribute = attribute
323
350
  cond.unit = attribute in units
@@ -362,6 +389,11 @@ def _valid_experiment(serve: Serve, variations: Mapping[str, Any]) -> bool:
362
389
  return total == BUCKETS
363
390
 
364
391
 
392
+ def _add_reason(reasons: list[str], cond: Condition) -> None:
393
+ if cond.error and not cond.unsupported and cond.error not in reasons:
394
+ reasons.append(cond.error)
395
+
396
+
365
397
  def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: set[str]) -> None:
366
398
  rs.segments = {}
367
399
  for raw in _objects(top, "segments", "the document"):
@@ -379,6 +411,8 @@ def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: se
379
411
  conditions.append(broken)
380
412
  if kind not in _CONDITION_KINDS:
381
413
  _add(found, _unsupported("condition_kind", kind))
414
+ else:
415
+ broken.error = f"segment {key!r} has a {kind!r} condition"
382
416
  continue
383
417
  cond = _compile_condition(c, types, units, f"segment {key!r}")
384
418
  conditions.append(cond)
@@ -387,6 +421,7 @@ def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: se
387
421
 
388
422
  rs.flags = {}
389
423
  rs.unsupported = {}
424
+ rs.invalid = {}
390
425
  keys: list[str] = []
391
426
  for raw in _objects(top, "flags", "the document"):
392
427
  f = Flag()
@@ -410,6 +445,7 @@ def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: se
410
445
  )
411
446
  rules: list[Rule] = []
412
447
  found = []
448
+ reasons: list[str] = []
413
449
  for r in _objects(raw, "rules", where):
414
450
  rule_where = f"{where} rule {_string(r, 'id', where)!r}"
415
451
  conditions = []
@@ -417,10 +453,13 @@ def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: se
417
453
  cond = _compile_condition(c, types, units, rule_where)
418
454
  conditions.append(cond)
419
455
  _add(found, cond.unsupported)
456
+ _add_reason(reasons, cond)
420
457
  segment = rs.segments.get(cond.segment) if cond.segment else None
421
458
  if segment is not None:
422
459
  for construct in segment.unsupported:
423
460
  _add(found, construct)
461
+ for member in segment.conditions:
462
+ _add_reason(reasons, member)
424
463
  serve = Serve(_object(r.get("serve"), f"{rule_where}.serve"), rule_where)
425
464
  invalid = serve.kind == SERVE_EXPERIMENT and not _valid_experiment(serve, f.variations)
426
465
  if serve.kind not in _SERVE_KINDS:
@@ -429,6 +468,8 @@ def _build(rs: Ruleset, top: Mapping[str, Any], types: dict[str, str], units: se
429
468
  f.rules = tuple(rules)
430
469
  if found:
431
470
  rs.unsupported[f.key] = found
471
+ if reasons:
472
+ rs.invalid[f.key] = reasons
432
473
  rs.flags[f.key] = f
433
474
  keys.append(f.key)
434
475
  rs.keys = tuple(keys)
@@ -20,9 +20,10 @@ RULESET_LOADED = "ruleset_loaded"
20
20
  FETCH_FAILED = "fetch_failed"
21
21
  #: info: the ruleset stream is open. Fields: last_event_id, the held version the stream resumes from.
22
22
  SSE_CONNECTED = "sse_connected"
23
- #: info for a server-side close, warning otherwise: the ruleset stream ended. Fields: cause
24
- #: (server_closed, silence, timeout, network, http_status, unauthorized, malformed), error,
25
- #: reconnect (false where the stream stays down), and status for an HTTP status.
23
+ #: info for a server-side close of a stable stream, warning otherwise: the ruleset stream ended.
24
+ #: Fields: cause (server_closed, closed_early for a stream closed before its first heartbeat,
25
+ #: silence, timeout, network, http_status, unauthorized, malformed), error, reconnect (false where
26
+ #: the stream stays down), and status for an HTTP status.
26
27
  SSE_DROPPED = "sse_dropped"
27
28
  #: info to fresh, warning otherwise: the fallback chain moved. Fields: from, to.
28
29
  STAGE_CHANGED = "stage_changed"
@@ -36,6 +37,11 @@ SCHEMA_UNSUPPORTED = "schema_unsupported"
36
37
  #: does not know, typically because the server is newer; logged once per flag and ruleset version.
37
38
  #: Fields: flag, constructs (each as "<kind> <name>"), ruleset_version.
38
39
  RULE_UNSUPPORTED = "rule_unsupported"
40
+ #: error: a flag of an accepted ruleset holds a condition this SDK cannot evaluate although the
41
+ #: server accepted it, such as a pattern its regular expression engine refuses; the flag serves
42
+ #: its default with inconsistent_ruleset in this SDK only. Logged once per flag and ruleset
43
+ #: version. Fields: flag, conditions (the reason of each), ruleset_version.
44
+ CONDITION_INVALID = "condition_invalid"
39
45
  #: warning: the store file could not be loaded or saved. Fields: path, op (load or save), cause.
40
46
  STORE_FAILED = "store_failed"
41
47
  #: warning: a getter asked for a type other than the flag's; logged once per flag key. Fields:
@@ -49,8 +55,9 @@ LISTENER_FAILED = "listener_failed"
49
55
  #: warning: a batch of events failed and goes again with the same event IDs. Fields: cause, events,
50
56
  #: retry_in (seconds), status for an HTTP status, and kind for the evaluation summary.
51
57
  EVENTS_FAILED = "events_failed"
52
- #: warning: events or summary rows were given up on. Fields: cause (queue_full, client_error,
53
- #: refused_by_the_server, window_too_old) and what was dropped.
58
+ #: warning: events or summary rows were given up on. Fields: cause (queue_full, not_serialisable,
59
+ #: client_error, refused_by_the_server, window_too_old) and what was dropped; fault, the kind of
60
+ #: encoding error, for not_serialisable.
54
61
  QUEUE_DROPPED = "queue_dropped"
55
62
  #: warning: send_exposures is off, so no exposure or alias leaves this client; logged at construction.
56
63
  EXPOSURES_OFF = "exposures_off"
@@ -24,7 +24,7 @@ from enum import Enum
24
24
  from typing import Any
25
25
  from urllib.parse import urlsplit
26
26
 
27
- from ._delivery import API_PATH
27
+ from ._delivery import API_PATH, send_request
28
28
 
29
29
  #: This SDK's name in the envelope and in the SDK inventory, as the User-Agent names it.
30
30
  SDK_NAME = "flagnetic-python"
@@ -92,8 +92,8 @@ def event_id(at: datetime) -> str:
92
92
  return f"{text[:8]}-{text[8:12]}-{text[12:16]}-{text[16:20]}-{text[20:]}"
93
93
 
94
94
 
95
- def _size(event: Event) -> int:
96
- return len(json.dumps(event, separators=(",", ":"), ensure_ascii=False).encode())
95
+ def encoded_size(event: Event) -> int:
96
+ return len(json.dumps(event, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode())
97
97
 
98
98
 
99
99
  class Ingest:
@@ -137,7 +137,7 @@ class Ingest:
137
137
  size = 0
138
138
  for event in events:
139
139
  # One comma per event after the first.
140
- cost = _size(event) + 1
140
+ cost = encoded_size(event) + 1
141
141
  if current and (len(current) == MAX_EVENTS_PER_BATCH or size + cost > budget):
142
142
  batches.append(current)
143
143
  current, size = [], 0
@@ -167,7 +167,7 @@ class Ingest:
167
167
  self._conn = conn
168
168
  deadline = time.monotonic() + self._timeout
169
169
  try:
170
- conn.request("POST", self._path, body=body, headers=headers)
170
+ send_request(conn, "POST", self._path, headers, body)
171
171
  resp = conn.getresponse()
172
172
  status = resp.status
173
173
  if status == 202:
@@ -218,6 +218,8 @@ class Ingest:
218
218
  },
219
219
  separators=(",", ":"),
220
220
  ensure_ascii=False,
221
+ # NaN and Infinity are no JSON: a body holding one fails to parse and loses every event in it.
222
+ allow_nan=False,
221
223
  ).encode()
222
224
 
223
225
  @staticmethod
@@ -18,7 +18,7 @@ from typing import Any
18
18
 
19
19
  from . import _events
20
20
  from ._delivery import backoff_ceiling, full_jitter
21
- from ._ingest import MAX_SUMMARY_ROWS, Event, Ingest, Outcome, Sent, event_id, iso
21
+ from ._ingest import MAX_SUMMARY_ROWS, Event, Ingest, Outcome, Sent, encoded_size, event_id, iso
22
22
 
23
23
  Log = Callable[..., None]
24
24
 
@@ -268,6 +268,12 @@ class Timing:
268
268
  batch_size: int = 500
269
269
 
270
270
 
271
+ def _fault(err: Exception) -> str:
272
+ if isinstance(err, UnicodeEncodeError):
273
+ return f"UnicodeEncodeError: {err.reason}"
274
+ return type(err).__name__
275
+
276
+
271
277
  class EventQueue:
272
278
  """The bounded in-memory queue of exposures and aliases.
273
279
 
@@ -293,6 +299,21 @@ class EventQueue:
293
299
  self._full = False
294
300
 
295
301
  def record(self, event: Event) -> None:
302
+ try:
303
+ # Encoded now, where the event is one among those being recorded: left to the flush, one
304
+ # that does not encode would fail every batch it heads until newer events evicted it.
305
+ encoded_size(event)
306
+ except (TypeError, ValueError, RecursionError) as err:
307
+ # The fault only: the exception text of a value that is no JSON value can hold the
308
+ # event's content, and unit IDs are not logged.
309
+ self._log(
310
+ logging.WARNING,
311
+ _events.QUEUE_DROPPED,
312
+ cause="not_serialisable",
313
+ events=1,
314
+ fault=_fault(err),
315
+ )
316
+ return
296
317
  with self._lock:
297
318
  self._queue.append(event)
298
319
  over = len(self._queue) - self._timing.capacity
@@ -0,0 +1,78 @@
1
+ """The file that keeps the last good ruleset across restarts.
2
+
3
+ A store file is a header line naming the key the ruleset was received under, then the ruleset
4
+ document exactly as the endpoint served it. The header holds a digest of the key, never the key.
5
+ Without it, a process restarted with another environment's key on the same path would serve that
6
+ environment's ruleset as last_good, and refuse the right one as a downgrade whenever the old
7
+ version was higher.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+ _FORMAT = 1
20
+
21
+
22
+ class StoreRefused(Exception):
23
+ """The file is not one to serve from: it belongs to no key, to another key or is in another format."""
24
+
25
+
26
+ def _digest(sdk_key: str) -> str:
27
+ return hashlib.sha256(sdk_key.encode("utf-8")).hexdigest()
28
+
29
+
30
+ def encode(sdk_key: str, document: bytes) -> bytes:
31
+ """The content of a store file holding ``document``, received under ``sdk_key``."""
32
+ header = json.dumps({"flagnetic_store": _FORMAT, "key": _digest(sdk_key)}, separators=(",", ":"))
33
+ return header.encode("ascii") + b"\n" + document
34
+
35
+
36
+ def decode(sdk_key: str, content: bytes) -> bytes:
37
+ """The document in a store file for ``sdk_key``; raises StoreRefused for any other file."""
38
+ line, newline, document = content.partition(b"\n")
39
+ try:
40
+ header = json.loads(line) if newline else None
41
+ except ValueError:
42
+ header = None
43
+ if not isinstance(header, dict) or "flagnetic_store" not in header:
44
+ raise StoreRefused("the store was written under no key")
45
+ fmt = header["flagnetic_store"]
46
+ if type(fmt) is not int or fmt != _FORMAT:
47
+ raise StoreRefused("the store was written in a format this client does not read")
48
+ if header.get("key") != _digest(sdk_key):
49
+ raise StoreRefused("the store was written under another key")
50
+ return document
51
+
52
+
53
+ def read(path: Path, sdk_key: str) -> tuple[bytes, float] | None:
54
+ """The document at ``path`` under ``sdk_key`` and when it was written; None on a first start."""
55
+ try:
56
+ content, written = path.read_bytes(), path.stat().st_mtime
57
+ except FileNotFoundError:
58
+ return None
59
+ return decode(sdk_key, content), written
60
+
61
+
62
+ def write(path: Path, sdk_key: str, document: bytes) -> None:
63
+ """Replaces the file by rename, so that a crash never leaves half a document.
64
+
65
+ The file is readable by its owner only, since a ruleset carries private segments.
66
+ """
67
+ # mkstemp creates the file with mode 0600.
68
+ fd, tmp = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)
69
+ try:
70
+ with os.fdopen(fd, "wb") as out:
71
+ out.write(encode(sdk_key, document))
72
+ out.flush()
73
+ os.fsync(out.fileno())
74
+ os.replace(tmp, path)
75
+ except BaseException:
76
+ with contextlib.suppress(OSError):
77
+ os.unlink(tmp)
78
+ raise
@@ -2,4 +2,4 @@
2
2
 
3
3
  # release-please keeps it equal to the package's tag through the marker; 0.0.0
4
4
  # is a build from the repository before the first release.
5
- __version__ = "0.1.2" # x-release-please-version
5
+ __version__ = "0.1.4" # x-release-please-version
@@ -12,6 +12,7 @@ from pathlib import Path
12
12
  from typing import Any
13
13
 
14
14
  import flagnetic
15
+ from flagnetic import _store
15
16
  from mock_server import MockServer, Request, Response
16
17
 
17
18
  from conformance import ROOT, same_json
@@ -366,7 +367,7 @@ class Player:
366
367
  stored = self.scenario["given"].get("stored")
367
368
  if stored:
368
369
  path = Path(tempfile.mkdtemp()) / "ruleset.json"
369
- path.write_bytes(read(stored))
370
+ path.write_bytes(_store.encode(SDK_KEY, read(stored)))
370
371
  kwargs["store"] = path
371
372
  self.script.last_end = time.monotonic()
372
373
  client = flagnetic.Client(SDK_KEY, server.url, **kwargs)
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import gzip
6
+ import hashlib
7
+ import http.client
6
8
  import json
7
9
  import logging
8
10
  import os
@@ -11,16 +13,19 @@ import resource
11
13
  import stat
12
14
  import threading
13
15
  import time
16
+ from functools import partial
14
17
  from pathlib import Path
15
18
  from typing import Any
16
19
 
17
20
  import pytest
18
21
 
19
22
  import flagnetic
20
- from flagnetic import _delivery
23
+ from flagnetic import _delivery, _ingest, _store
21
24
  from mock_server import MockServer, Request, Response
22
25
  from protocol import SDK_KEY, Logs, eventually, read, read_json
23
26
 
27
+ from conformance import ROOT as CONFORMANCE
28
+
24
29
  RULESET = read("server/ruleset.json")
25
30
  AFTER_KILL_SWITCH = read("server/ruleset-after-kill-switch.json")
26
31
  CONTEXT = flagnetic.Context(**read_json("scenarios.json")["context"])
@@ -272,7 +277,10 @@ def test_the_ruleset_is_persisted_and_serves_the_next_start_before_any_request(
272
277
  first = clients(serving(RULESET), store=store)
273
278
  assert first.ready(5) is flagnetic.Stage.FRESH
274
279
  assert stat.S_IMODE(os.stat(store).st_mode) == 0o600
275
- assert json.loads(store.read_bytes()) == json.loads(RULESET)
280
+ # Byte for byte what every server SDK writes, so a store moves between them.
281
+ digest = hashlib.sha256(SDK_KEY.encode()).hexdigest().encode()
282
+ assert store.read_bytes() == b'{"flagnetic_store":1,"key":"' + digest + b'"}\n' + RULESET
283
+ assert SDK_KEY.encode() not in store.read_bytes()
276
284
  assert not [p for p in tmp_path.iterdir() if p != store]
277
285
 
278
286
  # The server is down at the next start: the store serves.
@@ -291,6 +299,81 @@ def test_the_ruleset_is_persisted_and_serves_the_next_start_before_any_request(
291
299
  @pytest.mark.parametrize("content", [b"{not json", b"", RULESET.replace(b'"server"', b'"client"')])
292
300
  def test_a_store_that_cannot_be_loaded_is_reported_and_leaves_built_in(
293
301
  tmp_path: Path, content: bytes
302
+ ) -> None:
303
+ store = tmp_path / "flagnetic.json"
304
+ store.write_bytes(_store.encode(SDK_KEY, content))
305
+ logs = Logs()
306
+ client = flagnetic.Client(
307
+ SDK_KEY, "http://127.0.0.1:1", stream=False, request_timeout=1, store=store, logger=logs
308
+ )
309
+ try:
310
+ assert client.stage is flagnetic.Stage.BUILT_IN
311
+ assert [f["op"] for f in logs.named("store_failed")] == ["load"]
312
+ finally:
313
+ client.close()
314
+
315
+
316
+ def test_a_store_written_under_another_key_is_discarded_and_the_right_ruleset_is_no_downgrade(
317
+ tmp_path: Path,
318
+ ) -> None:
319
+ store = tmp_path / "flagnetic.json"
320
+ # Another environment's ruleset, at a version higher than this one's.
321
+ old_server = serving(with_version(RULESET, 99))
322
+ old = flagnetic.Client("fn_srv_another_environment", old_server.url, stream=False, store=store)
323
+ try:
324
+ assert old.ready(5) is flagnetic.Stage.FRESH
325
+ finally:
326
+ old.close()
327
+ old_server.close()
328
+
329
+ seen: list[Request] = []
330
+
331
+ def handler(request: Request) -> Response:
332
+ seen.append(request)
333
+ if request.path.endswith("/stream"):
334
+ return Response(404)
335
+ return Response(200, {"Content-Type": "application/json", "ETag": '"1"'}, RULESET)
336
+
337
+ server = MockServer(handler)
338
+ logs = Logs()
339
+ client = flagnetic.Client(SDK_KEY, server.url, stream=False, store=store, logger=logs)
340
+ try:
341
+ assert client.stage is flagnetic.Stage.BUILT_IN
342
+ assert client.ready(5) is flagnetic.Stage.FRESH
343
+ failed = logs.named("store_failed")
344
+ assert [(f["op"], f["cause"]) for f in failed] == [
345
+ ("load", "the store was written under another key")
346
+ ]
347
+ assert client.get_detail(CONTEXT, "checkout", False).ruleset_version == 1
348
+ assert "if-none-match" not in seen[0].headers
349
+ finally:
350
+ client.close()
351
+ server.close()
352
+ # The accepted ruleset rewrote the file under this key.
353
+ assert store.read_bytes() == _store.encode(SDK_KEY, RULESET)
354
+
355
+
356
+ @pytest.mark.parametrize(
357
+ "content",
358
+ [
359
+ RULESET,
360
+ RULESET + b"\n",
361
+ json.dumps(json.loads(RULESET), indent=2).encode(),
362
+ _store.encode(SDK_KEY, RULESET).replace(b'"flagnetic_store":1', b'"flagnetic_store":2'),
363
+ _store.encode(SDK_KEY, RULESET).replace(b'"flagnetic_store":1', b'"flagnetic_store":"1"'),
364
+ _store.encode(SDK_KEY, RULESET).replace(b'"flagnetic_store":1', b'"flagnetic_store":true'),
365
+ ],
366
+ ids=[
367
+ "bare",
368
+ "bare with newline",
369
+ "bare on several lines",
370
+ "later format",
371
+ "format as a string",
372
+ "format true",
373
+ ],
374
+ )
375
+ def test_a_store_written_under_no_key_or_in_another_format_is_discarded(
376
+ tmp_path: Path, content: bytes
294
377
  ) -> None:
295
378
  store = tmp_path / "flagnetic.json"
296
379
  store.write_bytes(content)
@@ -494,6 +577,52 @@ def test_a_malformed_ruleset_event_drops_the_stream_and_it_reconnects(clients: A
494
577
  assert streams[1].headers["last-event-id"] == "1"
495
578
 
496
579
 
580
+ def test_a_stream_closed_before_its_first_heartbeat_backs_off_and_a_heartbeat_restarts_it(
581
+ clients: Any, monkeypatch: pytest.MonkeyPatch
582
+ ) -> None:
583
+ ceilings: list[float] = []
584
+
585
+ def record(ceiling: float) -> float:
586
+ ceilings.append(ceiling)
587
+ return 0.0
588
+
589
+ monkeypatch.setattr(_delivery, "full_jitter", record)
590
+ logs = Logs()
591
+ streams: list[Request] = []
592
+
593
+ def handler(request: Request) -> Response:
594
+ if request.path.endswith("/stream"):
595
+ streams.append(request)
596
+ return Response(200, {"Content-Type": "text/event-stream"}, stream=True)
597
+ return Response(200, JSON, RULESET)
598
+
599
+ server = MockServer(handler)
600
+ client = clients(server, stream=True, logger=logs, _time_divisor=100, poll_interval=3600)
601
+ assert client.ready(5) is flagnetic.Stage.FRESH
602
+ preamble = b'retry: 3000\n\nevent: ruleset\nid: 1\ndata: {"version":1}\n\n'
603
+
604
+ # A draining replica or a proxy answers 200 and ends the stream at once: each close is a
605
+ # failure, so the wait doubles. A heartbeat then makes the stream stable, its close routine,
606
+ # and the failures before it forgotten.
607
+ def opened(count: int) -> list[str]:
608
+ return [] if len(streams) == count else [f"{len(streams)} streams, want {count}"]
609
+
610
+ for n in (1, 2, 3):
611
+ assert eventually(partial(opened, n)) == []
612
+ server.stream_send(preamble)
613
+ server.stream_close()
614
+ assert eventually(partial(opened, 4)) == []
615
+ server.stream_send(b": hb\n\n")
616
+ server.stream_close()
617
+ assert eventually(partial(opened, 5)) == []
618
+ server.stream_close()
619
+ assert eventually(partial(opened, 6)) == []
620
+ # The waits are 1 s doubling, then the routine 0-2 s, then 1 s again, all divided by 100.
621
+ assert ceilings == pytest.approx([0.01, 0.02, 0.04, 0.02, 0.01])
622
+ early = "closed_early"
623
+ assert [f["cause"] for f in logs.named("sse_dropped")] == [early, early, early, "server_closed", early]
624
+
625
+
497
626
  def test_close_ends_the_thread_while_the_stream_waits_for_its_answer(clients: Any) -> None:
498
627
  release = threading.Event()
499
628
  arrived = threading.Event()
@@ -622,3 +751,94 @@ def test_flush_without_a_timeout_returns_when_the_thread_is_gone(
622
751
  done.start()
623
752
  done.join(5)
624
753
  assert not done.is_alive()
754
+
755
+
756
+ @pytest.mark.parametrize("suffix", ["\n", "\r\n", " ", "\t", "\x00", "\x7f", "é"])
757
+ def test_a_key_that_is_no_header_token_is_refused_without_repeating_it(suffix: str) -> None:
758
+ key = SDK_KEY + suffix
759
+ with pytest.raises(ValueError, match="flagnetic") as refused:
760
+ flagnetic.Client(key, "http://127.0.0.1:1")
761
+ assert SDK_KEY not in str(refused.value)
762
+ assert SDK_KEY not in repr(refused.value)
763
+
764
+
765
+ def test_an_error_raised_while_building_a_request_is_named_by_its_class_only() -> None:
766
+ conn = http.client.HTTPConnection("127.0.0.1", 1)
767
+ secret = "fn_srv_secret\n"
768
+ with pytest.raises(http.client.HTTPException) as failed:
769
+ _delivery.send_request(conn, "GET", "/x", {"Authorization": f"Bearer {secret}"})
770
+ assert secret.strip() not in str(failed.value)
771
+ assert "ValueError" in str(failed.value)
772
+
773
+
774
+ def test_a_key_the_http_library_refuses_never_reaches_the_log(
775
+ clients: Any, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
776
+ ) -> None:
777
+ # Construction refuses such a key; this hands one past it to show what fetch, stream and report log.
778
+ bad_key = SDK_KEY + "\n"
779
+ for target in (_delivery.Delivery, _ingest.Ingest):
780
+ original = target.__init__
781
+
782
+ def with_bad_key(self: Any, *args: Any, _original: Any = original, **kwargs: Any) -> None:
783
+ _original(self, *args, **{**kwargs, "sdk_key": bad_key})
784
+
785
+ monkeypatch.setattr(target, "__init__", with_bad_key)
786
+ logs = Logs()
787
+ with caplog.at_level(logging.DEBUG):
788
+ client = clients(serving(RULESET), stream=True, logger=logs, _time_divisor=100)
789
+ client.alias("anonymous", "d-1", "user", "u-1")
790
+ client.flush(timeout=2)
791
+ assert (
792
+ eventually(lambda: [] if logs.count("sse_dropped") and logs.count("fetch_failed") else ["none"])
793
+ == []
794
+ )
795
+ logged = repr(logs.events) + caplog.text
796
+ assert SDK_KEY not in logged
797
+ assert logs.count("evaluation_failed") == 0
798
+
799
+
800
+ INVALID = json.loads((CONFORMANCE / "fixtures" / "errors" / "codes.json").read_text(encoding="utf-8"))[
801
+ "ruleset"
802
+ ]
803
+
804
+
805
+ def test_a_condition_the_evaluator_cannot_compile_is_logged_once_per_flag_at_load(clients: Any) -> None:
806
+ logs = Logs()
807
+ document = json.dumps({**INVALID, "version": 7}).encode()
808
+ client = clients(serving(document), logger=logs)
809
+ client.ready(5)
810
+ lines = logs.named("condition_invalid")
811
+ keys = [line["flag"] for line in lines]
812
+ assert keys == sorted(keys)
813
+ assert {"invalid_regex", "undeclared_attribute"} <= set(keys)
814
+ assert "fine" not in keys
815
+ assert all(line["ruleset_version"] == 7 and line["conditions"] for line in lines)
816
+ assert any(
817
+ "matches" in reason
818
+ for line in lines
819
+ if line["flag"] == "invalid_regex"
820
+ for reason in line["conditions"]
821
+ )
822
+ assert logs.count("rule_unsupported") == 0
823
+ # Evaluating, or receiving the same version again, logs nothing more.
824
+ for key in keys:
825
+ client.get_detail(CONTEXT, key, "d")
826
+ assert logs.count("condition_invalid") == len(keys)
827
+
828
+
829
+ def test_a_new_ruleset_version_with_the_condition_is_logged_again(clients: Any) -> None:
830
+ logs = Logs()
831
+ served = [json.dumps({**INVALID, "version": 7}).encode()]
832
+
833
+ def handler(request: Request) -> Response:
834
+ if request.path.endswith("/stream"):
835
+ return Response(404)
836
+ return Response(200, {"Content-Type": "application/json"}, served[0])
837
+
838
+ client = clients(MockServer(handler), logger=logs, poll_interval=30, _time_divisor=1000)
839
+ client.ready(5)
840
+ once = logs.count("condition_invalid")
841
+ assert once
842
+ served[0] = json.dumps({**INVALID, "version": 8}).encode()
843
+ assert eventually(lambda: [] if logs.count("condition_invalid") == 2 * once else ["waiting"]) == []
844
+ assert sorted({line["ruleset_version"] for line in logs.named("condition_invalid")}) == [7, 8]
@@ -5,12 +5,14 @@ from __future__ import annotations
5
5
  import json
6
6
  import threading
7
7
  import time
8
+ import uuid
8
9
  from collections.abc import Callable
9
10
  from typing import Any
10
11
 
11
12
  import pytest
12
13
 
13
14
  import flagnetic
15
+ from flagnetic import _reporting as reporting
14
16
  from mock_server import MockServer, Request, Response
15
17
  from protocol import SDK_KEY, Logs, eventually, read, read_json
16
18
 
@@ -142,6 +144,52 @@ def test_a_batch_the_server_will_never_take_is_dropped_and_not_sent_again(ingest
142
144
  assert [f["cause"] for f in logs.named("queue_dropped")] == ["client_error"]
143
145
 
144
146
 
147
+ @pytest.mark.parametrize(
148
+ "unit_id",
149
+ [
150
+ uuid.UUID("8f1c0000-0000-4000-8000-000000000000"),
151
+ "bad-\ud800-unit",
152
+ float("nan"),
153
+ float("inf"),
154
+ ],
155
+ ids=["not_a_json_value", "lone_surrogate", "nan", "infinity"],
156
+ )
157
+ def test_an_event_that_does_not_serialise_is_dropped_alone(ingest: Any, unit_id: Any) -> None:
158
+ logs = Logs()
159
+ server, client = ingest(send_summaries=False, logger=logs)
160
+ client.alias("anonymous", "d-1", "user", "u-1")
161
+ client.alias("anonymous", unit_id, "user", "u-2")
162
+ client.alias("anonymous", "d-3", "user", "u-3")
163
+ client.flush()
164
+ assert [e["from_unit_id"] for e in server.events("alias")] == ["d-1", "d-3"]
165
+ (dropped,) = logs.named("queue_dropped")
166
+ assert (dropped["cause"], dropped["events"]) == ("not_serialisable", 1)
167
+ assert dropped["fault"]
168
+ assert "u-2" not in repr(dropped) and "bad-" not in repr(dropped) and "8f1c" not in repr(dropped)
169
+
170
+
171
+ def test_an_event_nested_past_the_interpreters_limit_is_dropped_alone(
172
+ ingest: Any, monkeypatch: pytest.MonkeyPatch
173
+ ) -> None:
174
+ # Whether a deep value raises depends on the interpreter, so the encoder's failure is staged.
175
+ logs = Logs()
176
+ server, client = ingest(send_summaries=False, logger=logs)
177
+
178
+ def encode(event: Any) -> int:
179
+ if event["from_unit_id"] == "d-2":
180
+ raise RecursionError
181
+ return 0
182
+
183
+ monkeypatch.setattr(reporting, "encoded_size", encode)
184
+ for i in (1, 2, 3):
185
+ client.alias("anonymous", f"d-{i}", "user", "u-1")
186
+ monkeypatch.undo()
187
+ client.flush()
188
+ assert [e["from_unit_id"] for e in server.events("alias")] == ["d-1", "d-3"]
189
+ (dropped,) = logs.named("queue_dropped")
190
+ assert (dropped["cause"], dropped["fault"]) == ("not_serialisable", "RecursionError")
191
+
192
+
145
193
  def test_a_summary_that_failed_merges_into_the_next_window(ingest: Any) -> None:
146
194
  logs = Logs()
147
195
 
@@ -11,6 +11,7 @@ from typing import Any
11
11
  import pytest
12
12
 
13
13
  import flagnetic
14
+ from flagnetic import _delivery
14
15
  from mock_server import MockServer, Request, Response
15
16
  from protocol import (
16
17
  SDK_KEY,
@@ -25,6 +26,7 @@ from protocol import (
25
26
 
26
27
  FILES = read_json("scenarios.json")
27
28
  VERSIONING = read_json("versioning-scenarios.json")
29
+ STABILITY = read_json("stream-stability-scenarios.json")
28
30
  EXPERIMENTS = read_json("experiment-scenarios.json")
29
31
  CONTEXT = flagnetic.Context(**FILES["context"])
30
32
 
@@ -41,6 +43,11 @@ DIVISORS = {
41
43
  "server: 45 seconds of silence reconnect the stream": 40,
42
44
  CATCH_UP: 40,
43
45
  }
46
+ # The scenarios about how long a wait is. Every jitter is drawn at the top of its window, and time
47
+ # is not compressed, so a reconnect that skips the backoff (the routine 0-2 s against the first
48
+ # failure's 0-1 s) misses a window that the scheduling slack of a step does not widen to cover.
49
+ WINDOW_TOP = {"server: a stream closed before its first heartbeat is retried with backoff": 1}
50
+ DIVISORS.update(WINDOW_TOP)
44
51
  DEFAULT_DIVISOR = 50
45
52
 
46
53
  # Steps that wait for the server's answer to a flush need a fetch loop that is quiet meanwhile: these
@@ -50,7 +57,7 @@ DIVISORS["server: offline mode makes no request"] = 100
50
57
 
51
58
 
52
59
  def server_scenarios() -> list[dict[str, Any]]:
53
- every = FILES["scenarios"] + VERSIONING["scenarios"] + EXPERIMENTS["scenarios"]
60
+ every = FILES["scenarios"] + VERSIONING["scenarios"] + STABILITY["scenarios"] + EXPERIMENTS["scenarios"]
54
61
  return [s for s in every if s["mode"] == "server"]
55
62
 
56
63
 
@@ -70,8 +77,10 @@ def scenario_report() -> Iterator[None]:
70
77
 
71
78
 
72
79
  @pytest.mark.parametrize("name", [s["name"] for s in server_scenarios()])
73
- def test_scenario(name: str) -> None:
80
+ def test_scenario(name: str, monkeypatch: pytest.MonkeyPatch) -> None:
74
81
  scenario = next(s for s in server_scenarios() if s["name"] == name)
82
+ if name in WINDOW_TOP:
83
+ monkeypatch.setattr(_delivery, "full_jitter", lambda ceiling: ceiling)
75
84
  answers = {**FILES["answers"], **EXPERIMENTS["answers"]}
76
85
  errors = play(scenario, CONTEXT, answers, DIVISORS.get(name, DEFAULT_DIVISOR))
77
86
  assert not errors, "\n".join(errors)
@@ -81,3 +81,24 @@ def test_multiline_anchors() -> None:
81
81
  assert matches("(?m)^b$", "a\nb\nc")
82
82
  assert not matches("^b$", "a\nb\nc")
83
83
  assert not matches("a$", "a\n")
84
+
85
+
86
+ @pytest.mark.parametrize(
87
+ "pattern",
88
+ [
89
+ r"\p{Old_Italic}",
90
+ r"\p{old italic}",
91
+ r"\p{OLD-ITALIC}",
92
+ r"\p{OldItalic}",
93
+ r"\p{oLd_iTaLiC}",
94
+ r"[\p{Old_Italic}x]",
95
+ ],
96
+ )
97
+ def test_a_script_of_several_words_is_read_under_any_spelling_the_server_reads(pattern: str) -> None:
98
+ # Go 1.27 canonicalises script names like category aliases; the shared vectors
99
+ # leave these out because Go 1.26 refuses them.
100
+ assert matches(pattern, "\U00010300")
101
+ assert not matches(pattern, "a")
102
+ assert matches(r"(?i)\p{Old_Italic}", "\U00010300")
103
+ assert matches(r"\P{Old_Italic}", "a")
104
+ assert matches(r"\p{^Old_Italic}", "a")
@@ -1,35 +0,0 @@
1
- """The file that keeps the last good ruleset across restarts."""
2
-
3
- from __future__ import annotations
4
-
5
- import contextlib
6
- import os
7
- import tempfile
8
- from pathlib import Path
9
-
10
-
11
- def read(path: Path) -> tuple[bytes, float] | None:
12
- """The document at ``path`` and when it was written, or None when there is no file (a first start)."""
13
- try:
14
- return path.read_bytes(), path.stat().st_mtime
15
- except FileNotFoundError:
16
- return None
17
-
18
-
19
- def write(path: Path, document: bytes) -> None:
20
- """Replaces the file by rename, so that a crash never leaves half a document.
21
-
22
- The file is readable by its owner only, since a ruleset carries private segments.
23
- """
24
- # mkstemp creates the file with mode 0600.
25
- fd, tmp = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)
26
- try:
27
- with os.fdopen(fd, "wb") as out:
28
- out.write(document)
29
- out.flush()
30
- os.fsync(out.fileno())
31
- os.replace(tmp, path)
32
- except BaseException:
33
- with contextlib.suppress(OSError):
34
- os.unlink(tmp)
35
- raise
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes