Repository navigation
chore: evaluate client-side rules and rollouts #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6dad30f
chore: evaluate client-side rules and rollouts
lourens-octopus e3ef199
fix: compare non-ASCII context attributes as .NET does
lourens-octopus 6c601bf
test: pin that evaluation never reads a malformed part it doesn't reach
lourens-octopus 5905038
test: keep only the non-ASCII cases where the providers disagree
lourens-octopus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
src/octopus_openfeature_provider/_v4/client_side_evaluation_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| """What a flag's rules and conditions are evaluated against.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from openfeature.evaluation_context import EvaluationContext | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class ClientSideEvaluationContext: | ||
| # The key percentage-by-context buckets against. | ||
| evaluation_key: str | ||
| # The caller's context, or None if they supplied none. | ||
| open_feature_context: EvaluationContext | None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """A named rule the provider evaluates on the client side.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from openfeature.exception import ParseError | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.client_side_condition import ( | ||
| ClientSideCondition, | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True, kw_only=True) | ||
| class ClientSideRule: | ||
| """Matches when every one of its conditions matches. | ||
|
|
||
| A field that was missing or of the wrong type in the response is None, and a | ||
| condition that wasn't a JSON object is None in ``conditions``. | ||
| """ | ||
|
|
||
| name: str | None | ||
| conditions: tuple[ClientSideCondition | None, ...] | None | ||
|
|
||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| # The server only defers a named rule carrying at least one condition, so | ||
| # anything else is a response it could not have sent. | ||
| if self.name is None: | ||
| raise ParseError("A rule has no name.") | ||
|
|
||
| if not self.conditions: | ||
| raise ParseError(f"Rule '{self.name}' has no conditions.") | ||
|
|
||
| for condition in self.conditions: | ||
| if condition is None: | ||
| raise ParseError(f"Rule '{self.name}' has a missing condition.") | ||
|
|
||
| if not condition.matches(context): | ||
| return False | ||
|
|
||
| return True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """The conditions of a client-side rule.""" |
19 changes: 19 additions & 0 deletions
19
src/octopus_openfeature_provider/_v4/conditions/client_side_condition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| """The base type for a condition of a client-side rule.""" | ||
|
|
||
| from abc import ABC, abstractmethod | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
|
|
||
|
|
||
| class ClientSideCondition(ABC): | ||
| __slots__ = () | ||
|
|
||
| @abstractmethod | ||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| """Whether this condition is met. | ||
|
|
||
| A condition that did not arrive in a shape its type can evaluate raises | ||
| ``ParseError`` rather than reading a value it was not sent. | ||
| """ |
9 changes: 9 additions & 0 deletions
9
src/octopus_openfeature_provider/_v4/conditions/condition_type_names.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| """The ``type`` discriminators of the client-side conditions. | ||
|
|
||
| These mirror the values in the evaluations response, so they must not drift from | ||
| the server. | ||
| """ | ||
|
|
||
| CONTEXT_ATTRIBUTE_IS_NOT_ONE_OF = "context-attribute-is-not-one-of" | ||
| CONTEXT_ATTRIBUTE_IS_ONE_OF = "context-attribute-is-one-of" | ||
| PERCENTAGE_BY_CONTEXT = "percentage-by-context" |
26 changes: 26 additions & 0 deletions
26
src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_not_one_of_condition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """The ``context-attribute-is-not-one-of`` condition.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.client_side_condition import ( | ||
| ClientSideCondition, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.context_attributes import is_one_of | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True, kw_only=True) | ||
| class ContextAttributeIsNotOneOfCondition(ClientSideCondition): | ||
| """Matches when the context attribute ``key`` is not one of ``values``. | ||
|
|
||
| The exact negation of ``context-attribute-is-one-of``, so a missing attribute | ||
| matches. | ||
| """ | ||
|
|
||
| key: str | None | ||
| values: tuple[str | None, ...] | None | ||
|
|
||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| return not is_one_of(context, self.key, self.values) |
25 changes: 25 additions & 0 deletions
25
src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_one_of_condition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| """The ``context-attribute-is-one-of`` condition.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.client_side_condition import ( | ||
| ClientSideCondition, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.context_attributes import is_one_of | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True, kw_only=True) | ||
| class ContextAttributeIsOneOfCondition(ClientSideCondition): | ||
| """Matches when the context attribute ``key`` is one of ``values``. | ||
|
|
||
| A missing attribute does not match. | ||
| """ | ||
|
|
||
| key: str | None | ||
| values: tuple[str | None, ...] | None | ||
|
|
||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| return is_one_of(context, self.key, self.values) |
69 changes: 69 additions & 0 deletions
69
src/octopus_openfeature_provider/_v4/conditions/context_attributes.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """The attribute lookup shared by both attribute conditions.""" | ||
|
|
||
| from openfeature.exception import ParseError | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
|
|
||
|
|
||
| def is_one_of( | ||
| context: ClientSideEvaluationContext, | ||
| key: str | None, | ||
| values: tuple[str | None, ...] | None, | ||
| ) -> bool: | ||
| """Whether the context holds an attribute named ``key`` with one of ``values``. | ||
|
|
||
| Keys and values compare case-insensitively, and a non-string attribute counts | ||
| as absent. The SDK passes the context un-flattened, so an attribute can be an | ||
| int, bool, float, datetime, sequence or mapping. Every attribute whose key | ||
| matches is checked, not just the first, as a context can hold several case | ||
| variants of one key. | ||
|
|
||
| Raises: | ||
| ParseError: If the condition is missing its key or values. | ||
| """ | ||
| if key is None: | ||
| raise ParseError("A condition is missing a key.") | ||
|
|
||
| if not values: | ||
| raise ParseError("A condition is missing values.") | ||
|
|
||
| if any(value is None for value in values): | ||
| raise ParseError("A condition is missing a value.") | ||
|
|
||
| open_feature_context = context.open_feature_context | ||
| if open_feature_context is None: | ||
| return False | ||
|
|
||
| upper_key = _ordinal_upper(key) | ||
| upper_values = {_ordinal_upper(value) for value in values if value is not None} | ||
|
|
||
| return any( | ||
| isinstance(attribute_key, str) | ||
| and _ordinal_upper(attribute_key) == upper_key | ||
| and isinstance(attribute, str) | ||
| and _ordinal_upper(attribute) in upper_values | ||
| for attribute_key, attribute in open_feature_context.attributes.items() | ||
| ) | ||
|
|
||
|
|
||
| def _ordinal_upper(text: str) -> str: | ||
| """``text`` uppercased one character at a time, so two strings compare as | ||
| .NET's ``OrdinalIgnoreCase`` and Java's ``equalsIgnoreCase`` compare them. | ||
|
|
||
| ``str.upper`` applies Unicode's full case mappings, some of which expand a | ||
| character, so "Straße" would equal "STRASSE" where .NET and Java say it | ||
| doesn't. A character that expands is kept as it is instead. That agrees with | ||
| .NET on ASCII and on expansions such as "ß" and "fi", but not on the few Greek | ||
| letters with an iota subscript, which .NET maps to their titlecase form. | ||
| """ | ||
| upper = text.upper() | ||
|
|
||
| # Nothing expanded, so every character mapped one to one. | ||
| if len(upper) == len(text): | ||
| return upper | ||
|
|
||
| return "".join( | ||
| upper_char if len(upper_char := char.upper()) == 1 else char for char in text | ||
| ) |
47 changes: 47 additions & 0 deletions
47
src/octopus_openfeature_provider/_v4/conditions/percentage_by_context_condition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """The ``percentage-by-context`` condition.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from openfeature.exception import ParseError | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions import percentage_rollout | ||
| from octopus_openfeature_provider._v4.conditions.client_side_condition import ( | ||
| ClientSideCondition, | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True, kw_only=True) | ||
| class PercentageByContextCondition(ClientSideCondition): | ||
| """Matches when the targeting key falls within the ``percentage``% rollout.""" | ||
|
|
||
| # 0 to 100. None when it was missing or not an integer, which stays | ||
| # distinguishable from an explicit 0, a legitimate "nobody". | ||
| percentage: int | None | ||
|
|
||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| percentage = self.percentage | ||
| if percentage is None: | ||
| raise ParseError("A condition is missing a percentage value.") | ||
|
|
||
| # Rejected rather than clamped: reading 101 as "everyone" would turn a | ||
| # flag on off the back of a bad payload. | ||
| if not 0 <= percentage <= 100: | ||
| raise ParseError(f"A condition has a percentage of {percentage}.") | ||
|
|
||
| open_feature_context = context.open_feature_context | ||
| targeting_key = ( | ||
| open_feature_context.targeting_key if open_feature_context else None | ||
| ) | ||
|
|
||
| # Nothing to bucket, so only a full rollout matches, as the server treats | ||
| # an untenanted caller. Checked with isinstance as well, since a caller | ||
| # without a type checker can pass a targeting key that isn't a str. | ||
| if not targeting_key or not isinstance(targeting_key, str): | ||
| return percentage >= 100 | ||
|
|
||
| return percentage_rollout.includes( | ||
| context.evaluation_key, targeting_key, percentage | ||
| ) |
69 changes: 69 additions & 0 deletions
69
src/octopus_openfeature_provider/_v4/conditions/percentage_rollout.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Buckets a targeting key into a percentage rollout. | ||
|
|
||
| Hashing the flag's evaluation key together with the targeting key keeps a bucket | ||
| stable across evaluations, while giving each flag an independent spread of | ||
| targeting keys. Every provider library shares this bucketing, so a rollout lands | ||
| on the same users whichever one a product uses. | ||
| """ | ||
|
|
||
| _MASK_32 = 0xFFFFFFFF | ||
| _C1 = 0xCC9E2D51 | ||
| _C2 = 0x1B873593 | ||
|
|
||
|
|
||
| def includes(evaluation_key: str, targeting_key: str, percentage: int) -> bool: | ||
| """Whether ``targeting_key`` falls within the first ``percentage`` percent of | ||
| targeting keys for the flag identified by ``evaluation_key``.""" | ||
| return get_normalized_number(evaluation_key, targeting_key) <= percentage | ||
|
|
||
|
|
||
| def get_normalized_number(evaluation_key: str, targeting_key: str) -> int: | ||
| """A deterministic bucket from 1 to 100 inclusive for the two keys. | ||
|
|
||
| Separate from ``includes`` so the shared cross-library test vectors can | ||
| assert on the bucket itself. | ||
| """ | ||
| data = f"{evaluation_key}:{targeting_key}".encode() | ||
| return murmur3_x86_32(data) % 100 + 1 | ||
|
|
||
|
|
||
| def murmur3_x86_32(data: bytes, seed: int = 0) -> int: | ||
| """MurmurHash3 x86_32 of ``data``, as an unsigned 32-bit integer. | ||
|
|
||
| Written out rather than taken from ``mmh3`` so the provider doesn't need a | ||
| native wheel. The blocks are read little-endian, as every provider does. | ||
| """ | ||
| hash_ = seed & _MASK_32 | ||
| block_end = len(data) - len(data) % 4 | ||
|
|
||
| for start in range(0, block_end, 4): | ||
| k = int.from_bytes(data[start : start + 4], "little") | ||
| hash_ ^= _mix_k(k) | ||
| hash_ = _rotl32(hash_, 13) | ||
| hash_ = (hash_ * 5 + 0xE6546B64) & _MASK_32 | ||
|
|
||
| tail = data[block_end:] | ||
| if tail: | ||
| hash_ ^= _mix_k(int.from_bytes(tail, "little")) | ||
|
|
||
| hash_ ^= len(data) & _MASK_32 | ||
| return _fmix32(hash_) | ||
|
|
||
|
|
||
| def _mix_k(k: int) -> int: | ||
| k = (k * _C1) & _MASK_32 | ||
| k = _rotl32(k, 15) | ||
| return (k * _C2) & _MASK_32 | ||
|
|
||
|
|
||
| def _rotl32(value: int, shift: int) -> int: | ||
| return ((value << shift) | (value >> (32 - shift))) & _MASK_32 | ||
|
|
||
|
|
||
| def _fmix32(hash_: int) -> int: | ||
| hash_ ^= hash_ >> 16 | ||
| hash_ = (hash_ * 0x85EBCA6B) & _MASK_32 | ||
| hash_ ^= hash_ >> 13 | ||
| hash_ = (hash_ * 0xC2B2AE35) & _MASK_32 | ||
| hash_ ^= hash_ >> 16 | ||
| return hash_ | ||
29 changes: 29 additions & 0 deletions
29
src/octopus_openfeature_provider/_v4/conditions/unknown_condition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| """A condition whose ``type`` this version of the provider doesn't recognise.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from openfeature.exception import ParseError | ||
|
|
||
| from octopus_openfeature_provider._v4.client_side_evaluation_context import ( | ||
| ClientSideEvaluationContext, | ||
| ) | ||
| from octopus_openfeature_provider._v4.conditions.client_side_condition import ( | ||
| ClientSideCondition, | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True, kw_only=True) | ||
| class UnknownCondition(ClientSideCondition): | ||
| """Never matches, so a newer server's capability is treated as "not met" by | ||
| an older provider rather than failing the flag.""" | ||
|
|
||
| # The unrecognised discriminator, or None if it was missing or not a string. | ||
| type: str | None | ||
|
|
||
| def matches(self, context: ClientSideEvaluationContext) -> bool: | ||
| # No server version emits a condition without a type, so unlike an | ||
| # unrecognised type this is a response that could not have been sent. | ||
| if self.type is None: | ||
| raise ParseError("A condition is missing a type.") | ||
|
|
||
| return False |
12 changes: 12 additions & 0 deletions
12
src/octopus_openfeature_provider/_v4/evaluation_reasons.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| """Reasons returned alongside a client-side evaluation. | ||
|
|
||
| Both match the strings the Feature Flags service produces server-side, so a flag | ||
| reads the same whichever side resolved it. | ||
| """ | ||
|
|
||
|
|
||
| def matched_rule(rule_name: str) -> str: | ||
| return f"Matched rule '{rule_name}'." | ||
|
|
||
|
|
||
| DID_NOT_MATCH_ANY_RULES = "Did not match any rules." |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably doesn't matter too much, but curious about the decision to roll our own.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's to avoid a native dependency. The other providers' libraries are plain .NET/Java/JS, but Python's only maintained option, mmh3, is a C extension. On any platform without a prebuilt wheel (a new CPython release, free-threaded builds, unusual Linux images), installing the provider would need a compiler, and it's one more runtime dependency in customers' apps.