|
5 | 5 | from functools import cached_property |
6 | 6 |
|
7 | 7 | from flag_engine import engine |
8 | | -from flag_engine.context.types import SegmentContext |
| 8 | +from flag_engine.context.types import SegmentContext, SegmentRule |
9 | 9 |
|
10 | 10 | from flagsmith.api.types import EnvironmentModel |
11 | 11 | from flagsmith.mappers import ( |
|
26 | 26 | TraitMapping, |
27 | 27 | ) |
28 | 28 |
|
| 29 | +IDENTITY_FREE_PROPERTY_PREFIXES = ( |
| 30 | + "$.environment.", |
| 31 | + "$.environment[", |
| 32 | + "$.flags.", |
| 33 | + "$.flags[", |
| 34 | +) |
| 35 | + |
29 | 36 |
|
30 | 37 | class LocalEvaluation: |
31 | 38 | """Per-environment-document state for local evaluation.""" |
@@ -67,11 +74,20 @@ def from_environment_document( |
67 | 74 |
|
68 | 75 | @cached_property |
69 | 76 | def environment_flags(self) -> typing.Dict[str, Flag]: |
70 | | - """Environment flags, which depend on the environment document only.""" |
71 | | - context_without_segments = self.context.copy() |
72 | | - context_without_segments.pop("segments", None) |
| 77 | + """Environment flags, which depend on the environment document only. |
| 78 | +
|
| 79 | + Evaluated without an identity, so segments reading traits or identity |
| 80 | + context are left out. |
| 81 | + """ |
| 82 | + environment_context = self.context.copy() |
| 83 | + if segments := environment_context.get("segments"): |
| 84 | + environment_context["segments"] = { |
| 85 | + segment_key: segment_context |
| 86 | + for segment_key, segment_context in segments.items() |
| 87 | + if _is_identity_free(segment_context["rules"]) |
| 88 | + } |
73 | 89 | evaluation_result = engine.get_evaluation_result( |
74 | | - context=context_without_segments, |
| 90 | + context=environment_context, |
75 | 91 | ) |
76 | 92 | return { |
77 | 93 | feature_name: Flag.from_evaluation_result(flag_result) |
@@ -113,3 +129,14 @@ def _index_overrides( |
113 | 129 | for override in segment_context.get("overrides") or () |
114 | 130 | if (feature_name := override["name"]) |
115 | 131 | } |
| 132 | + |
| 133 | + |
| 134 | +def _is_identity_free(rules: typing.Iterable[SegmentRule]) -> bool: |
| 135 | + return all( |
| 136 | + all( |
| 137 | + condition["property"].startswith(IDENTITY_FREE_PROPERTY_PREFIXES) |
| 138 | + for condition in rule.get("conditions") or () |
| 139 | + ) |
| 140 | + and _is_identity_free(rule.get("rules") or ()) |
| 141 | + for rule in rules |
| 142 | + ) |
0 commit comments