Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/octopus_openfeature_provider/_v4/_json_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ def as_bool(value: object) -> bool | None:
return value if isinstance(value, bool) else None


def as_int(value: object) -> int | None:
# bool is a subclass of int, but true isn't a JSON integer. A float such as
# 50.0 isn't either, as .NET would reject it.
return value if isinstance(value, int) and not isinstance(value, bool) else None


def as_list(value: object) -> list[object] | None:
return value if isinstance(value, list) else None

Expand Down
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
42 changes: 42 additions & 0 deletions src/octopus_openfeature_provider/_v4/client_side_rule.py
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""The conditions of a client-side rule."""
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.
"""
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"
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)
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)
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
)
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
)
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.
Comment on lines +33 to +34

Copy link
Copy Markdown
Collaborator

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.

Copy link
Copy Markdown
Contributor Author

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.

"""
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_
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 src/octopus_openfeature_provider/_v4/evaluation_reasons.py
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."
Loading