Skip to content
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

feat: Support transient identities and traits #93

Merged
merged 14 commits into from
Jul 19, 2024
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.10.1
hooks:
- id: mypy
args: [--strict]
Expand Down
44 changes: 25 additions & 19 deletions flagsmith/flagsmith.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,14 @@
from flagsmith.offline_handlers import BaseOfflineHandler
from flagsmith.polling_manager import EnvironmentDataPollingManager
from flagsmith.streaming_manager import EventStreamManager, StreamEvent
from flagsmith.utils.identities import Identity, generate_identities_data
from flagsmith.types import JsonType
from flagsmith.utils.identities import generate_identity_data

logger = logging.getLogger(__name__)

DEFAULT_API_URL = "https://edge.api.flagsmith.com/api/v1/"
DEFAULT_REALTIME_API_URL = "https://realtime.flagsmith.com/"

JsonType = typing.Union[
None,
int,
str,
bool,
typing.List["JsonType"],
typing.List[typing.Mapping[str, "JsonType"]],
typing.Dict[str, "JsonType"],
]


class Flagsmith:
"""A Flagsmith client.
Expand Down Expand Up @@ -238,6 +229,9 @@ def get_identity_flags(
self,
identifier: str,
traits: typing.Optional[typing.Mapping[str, TraitValue]] = None,
*,
transient: bool = False,
transient_traits: typing.Optional[typing.List[str]] = None,
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved
) -> Flags:
"""
Get all the flags for the current environment for a given identity. Will also
Expand All @@ -247,13 +241,18 @@ def get_identity_flags(
:param identifier: a unique identifier for the identity in the current
environment, e.g. email address, username, uuid
:param traits: a dictionary of traits to add / update on the identity in
Flagsmith, e.g. {"num_orders": 10}
Flagsmith, e.g. `{"num_orders": 10}`
:param transient: if `True`, the identity won't get persisted
:param transient_traits: a list of trait keys that won't get persisted,
e.g. `["num_orders"]`
:return: Flags object holding all the flags for the given identity.
"""
traits = traits or {}
if (self.offline_mode or self.enable_local_evaluation) and self._environment:
return self._get_identity_flags_from_document(identifier, traits)
return self._get_identity_flags_from_api(identifier, traits)
return self._get_identity_flags_from_api(
identifier, traits, transient=transient, transient_traits=transient_traits
)

def get_identity_segments(
self,
Expand Down Expand Up @@ -339,13 +338,22 @@ def _get_environment_flags_from_api(self) -> Flags:
raise

def _get_identity_flags_from_api(
self, identifier: str, traits: typing.Mapping[str, typing.Any]
self,
identifier: str,
traits: typing.Mapping[str, typing.Any],
*,
transient: bool = False,
transient_traits: typing.Optional[typing.List[str]] = None,
) -> Flags:
request_body = generate_identity_data(
identifier, traits, transient=transient, transient_traits=transient_traits
)
try:
data = generate_identities_data(identifier, traits)
json_response: typing.Dict[str, typing.List[typing.Dict[str, JsonType]]] = (
self._get_json_response(
url=self.identities_url, method="POST", body=data
url=self.identities_url,
method="POST",
body=request_body,
)
)
return Flags.from_api_flags(
Expand All @@ -364,9 +372,7 @@ def _get_json_response(
self,
url: str,
method: str,
body: typing.Optional[
typing.Union[Identity, typing.Dict[str, JsonType]]
] = None,
body: typing.Optional[JsonType] = None,
) -> typing.Any:
Comment on lines +377 to 378
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the return type be JsonType?

Copy link
Member Author

@khvn26 khvn26 Jul 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return type here corresponds to response.json() type, which is typing.Any.
Casting to a specific type is responsibility of the caller, see e.g.

json_response: typing.Dict[str, typing.List[typing.Dict[str, JsonType]]] = (
self._get_json_response(

try:
request_method = getattr(self.session, method.lower())
Expand Down
14 changes: 14 additions & 0 deletions flagsmith/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import typing

_JsonScalarType = typing.Union[
int,
str,
float,
bool,
None,
]
JsonType = typing.Union[
_JsonScalarType,
typing.Dict[str, "JsonType"],
typing.List["JsonType"],
]
39 changes: 24 additions & 15 deletions flagsmith/utils/identities.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,29 @@

from flag_engine.identities.traits.types import TraitValue

Identity = typing.TypedDict(
"Identity",
{"identifier": str, "traits": typing.List[typing.Mapping[str, TraitValue]]},
)
from flagsmith.types import JsonType


def generate_identities_data(
identifier: str, traits: typing.Optional[typing.Mapping[str, TraitValue]] = None
) -> Identity:
return {
"identifier": identifier,
"traits": (
[{"trait_key": k, "trait_value": v} for k, v in traits.items()]
if traits
else []
),
}
def generate_identity_data(
identifier: str,
traits: typing.Optional[typing.Mapping[str, TraitValue]],
*,
transient: bool,
transient_traits: typing.Optional[typing.List[str]],
) -> JsonType:
identity_data: typing.Dict[str, JsonType] = {"identifier": identifier}
if traits:
traits_data: typing.List[JsonType] = []
transient_trait_keys = set(transient_traits) if transient_traits else set()
for trait_key, trait_value in traits.items():
trait_data: typing.Dict[str, JsonType] = {
"trait_key": trait_key,
"trait_value": trait_value,
}
if trait_key in transient_trait_keys:
trait_data["transient"] = True
traits_data.append(trait_data)
identity_data["traits"] = traits_data
if transient:
identity_data["transient"] = True
return identity_data
71 changes: 35 additions & 36 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ packages = [{ include = "flagsmith" }]

[tool.poetry.dependencies]
python = ">=3.8.1,<4"
requests = "^2.27.1"
requests-futures = "^1.0.0"
requests = "^2.32.3"
requests-futures = "^1.0.1"
flagsmith-flag-engine = "^5.1.0"
sseclient-py = "^1.8.0"

Expand All @@ -27,8 +27,8 @@ pre-commit = "^2.17.0"
responses = "^0.24.1"
flake8 = "^6.1.0"
isort = "^5.12.0"
mypy = "^1.7.1"
types-requests = "^2.31.0.10"
mypy = "^1.10.1"
types-requests = "^2.32"
pytest-cov = "^4.1.0"

[tool.mypy]
Expand Down
72 changes: 72 additions & 0 deletions tests/test_flagsmith.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
import requests
import responses
from responses import matchers
from flag_engine.environments.models import EnvironmentModel
from flag_engine.features.models import FeatureModel, FeatureStateModel
from pytest_mock import MockerFixture
Expand Down Expand Up @@ -172,6 +173,77 @@ def test_get_identity_flags_uses_local_environment_when_available(
assert identity_flags[0].value == feature_state.get_value()


@responses.activate()
def test_get_identity_flags__transient_identity__calls_expected(
flagsmith: Flagsmith,
identities_json: str,
environment_model: EnvironmentModel,
mocker: MockerFixture,
) -> None:
# Given
responses.add(
method="POST",
url=flagsmith.identities_url,
body=identities_json,
match=[matchers.json_params_matcher({"transient": True}, strict_match=False)],
)
flagsmith._environment = environment_model
flagsmith.enable_local_evaluation = True
mock_engine = mocker.patch("flagsmith.flagsmith.engine")

feature_state = FeatureStateModel(
feature=FeatureModel(id=1, name="some_feature", type="STANDARD"),
enabled=True,
featurestate_uuid=str(uuid.uuid4()),
)
mock_engine.get_identity_feature_states.return_value = [feature_state]

# When & Then
flagsmith.get_identity_flags(
"identifier",
traits={"some_trait": "some_value"},
transient=True,
).all_flags()
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved


@responses.activate()
def test_get_identity_flags__transient_traits__calls_expected(
flagsmith: Flagsmith,
identities_json: str,
environment_model: EnvironmentModel,
mocker: MockerFixture,
) -> None:
# Given
responses.add(
method="POST",
url=flagsmith.identities_url,
body=identities_json,
match=[
matchers.json_params_matcher(
{"traits": [{"trait_key": "some_trait", "transient": True}]},
strict_match=False,
)
],
)
flagsmith._environment = environment_model
flagsmith.enable_local_evaluation = True
mock_engine = mocker.patch("flagsmith.flagsmith.engine")

feature_state = FeatureStateModel(
feature=FeatureModel(id=1, name="some_feature", type="STANDARD"),
enabled=True,
featurestate_uuid=str(uuid.uuid4()),
)
mock_engine.get_identity_feature_states.return_value = [feature_state]

# When & Then
flagsmith.get_identity_flags(
"identifier",
traits={"some_trait": "some_value"},
transient_traits=["some_trait"],
).all_flags()
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved


def test_request_connection_error_raises_flagsmith_api_error(
mocker: MockerFixture, api_key: str
) -> None:
Expand Down
Loading