flagsmith-flag-engine 0.1.1__py3-none-any.whl

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.
@@ -0,0 +1,12 @@
1
+ Copyright (c) 2021 Bullet Train Ltd (https://www.flagsmith.com/) and individual contributors.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7
+
8
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9
+
10
+ 3. Neither the name of the Sentry nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11
+
12
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.1
2
+ Name: Flagsmith-Flag-Engine
3
+ Version: 0.1.1
4
+ Summary: Flag engine for the Flagsmith API.
5
+ Home-page: http://pypi.python.org/pypi/flagsmith-flag-engine/
6
+ Author: Matthew Elwell
7
+ Author-email: matthew.elwell@flagsmith.com
8
+ License: LICENSE.txt
9
+ Platform: UNKNOWN
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE.txt
12
+ Requires-Dist: marshmallow
13
+ Requires-Dist: dataclasses
14
+
15
+ [![Feature Flag, Remote Config and A/B Testing platform, Flagsmith](https://github.com/Flagsmith/flagsmith/raw/main/static-files/hero.png)](https://www.flagsmith.com/)
16
+
17
+ [Flagsmith](https://www.flagsmith.com/) is an open source, fully featured, Feature Flag and Remote Config service. Use
18
+ our hosted API, deploy to your own private cloud, or run on-premise.
19
+
20
+ # Flagsmith Flag Engine
21
+
22
+ This project powers the core [Flagsmith API](https://github.com/Flagsmith/flagsmith-api) flag evaluations engine.
23
+
24
+ ## Setup
25
+
26
+ ```bash
27
+ python -m venv .venv
28
+ source .venv/bin/activate
29
+ python -m pip install -r requirements-dev.txt
30
+ ```
31
+
32
+ ## Design
33
+
34
+ * Marshmallow Schemas
35
+ * Plain Python
36
+
37
+
@@ -0,0 +1,33 @@
1
+ flag_engine/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ flag_engine/environments/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ flag_engine/environments/builders.py,sha256=U9e5UP65uwW92rtdZQ-RAqNfYQkJbRcf08d64Vann5k,452
4
+ flag_engine/environments/models.py,sha256=eZjdVBNktPr-2sq76IuR7fPVQfzZxxOQoMe5G7YgRZc,738
5
+ flag_engine/environments/schemas.py,sha256=sfrrrU0DTwBNL9nAzZuA2W0yIoDSbrjS6itIxTDrWvo,1166
6
+ flag_engine/environments/integrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ flag_engine/environments/integrations/models.py,sha256=NC9UFCvNBmQ7gnVvEpvI_Bs0yx9t0MGmer9eyb1p4IM,120
8
+ flag_engine/environments/integrations/schemas.py,sha256=7S4Cy8ne8LrG5DHddZC65TPjM71FE6OM4_rCCu0k5-o,389
9
+ flag_engine/features/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ flag_engine/features/constants.py,sha256=oinYCtAUD6jw09wVuBSDC0R2CndEZkjXMUXCck1DuXo,68
11
+ flag_engine/features/models.py,sha256=vMtQES6l-FD1lmNMq2q7w7Z0PvHhgNsZs-EJ0kYRyvE,2313
12
+ flag_engine/features/schemas.py,sha256=MCPbw6azDBCwpBu1k67TkmAuYGsPlJ_7YenKy_1aaz8,2074
13
+ flag_engine/identities/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ flag_engine/identities/builders.py,sha256=tO5Jff8yRKDh7i9GBomZ2m0cjfcvkR4cZi4EHreR8ks,410
15
+ flag_engine/identities/models.py,sha256=i5oK1TKSP5LAU7SvQTEPPYqwiQFE_IujZPN-6oRCT8w,3145
16
+ flag_engine/identities/schemas.py,sha256=dHNapYlugXQTbppy_96kEZfS0Iq66Rq19lfEGFs0WSE,2400
17
+ flag_engine/organisations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ flag_engine/organisations/models.py,sha256=dmVX8POXTLhBYI7ThTYlVjTRGv-xxi1dPcIbaHecsR4,184
19
+ flag_engine/organisations/schemas.py,sha256=GIUuxWUm4G0M5ZFOMs2eqzd-R9CtVGUtZ6LgWnfpCcw,438
20
+ flag_engine/projects/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ flag_engine/projects/models.py,sha256=xY4ZC3B6uq4gNXOb6qv2f3IKDolQFlp225paP0NMOOw,367
22
+ flag_engine/projects/schemas.py,sha256=bdimckd0kSz9ZFtIFFN4yCtZMY4xxg8akMDUNTGW4i0,694
23
+ flag_engine/segments/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ flag_engine/segments/constants.py,sha256=uowQdG53IzuwtfmV1b25xVYxzO1YBRJY6Huy2o0u5r4,644
25
+ flag_engine/segments/models.py,sha256=PGwyY8a05gHKuBvkExhx80aMQV70MiQobmzsmihRP6g,1904
26
+ flag_engine/segments/schemas.py,sha256=K2WW0mJQNF7BBgcZpZM6ekK9MKSFJNo_3xrKBakN_F4,1232
27
+ flag_engine/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
+ flag_engine/utils/hashing.py,sha256=UBVP7cJCq-Hc0n5XkZCpi2ueohbnDl5qvt8UVGBAvuc,1223
29
+ Flagsmith_Flag_Engine-0.1.1.dist-info/LICENSE.txt,sha256=ODfaqV7JJbGSIlIuOA-GHHyc4cGi-QWinwCa2O5nse0,1546
30
+ Flagsmith_Flag_Engine-0.1.1.dist-info/METADATA,sha256=RrTAGu3wVPe7XCp3malMs2pQQgKTSQDiCsMBFs0HuDY,1061
31
+ Flagsmith_Flag_Engine-0.1.1.dist-info/WHEEL,sha256=ewwEueio1C2XeHTvT17n8dZUJgOvyCWCt0WVNLClP9o,92
32
+ Flagsmith_Flag_Engine-0.1.1.dist-info/top_level.txt,sha256=mmD1_GUabsUgkPJ9i9GU5NSOG4dlu9KTViP0ypclpVI,12
33
+ Flagsmith_Flag_Engine-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ flag_engine
File without changes
File without changes
@@ -0,0 +1,14 @@
1
+ import typing
2
+
3
+ from flag_engine.environments.models import EnvironmentModel
4
+ from flag_engine.environments.schemas import EnvironmentSchema
5
+
6
+ environment_schema = EnvironmentSchema()
7
+
8
+
9
+ def build_environment_dict(environment_obj: typing.Any) -> dict:
10
+ return environment_schema.dump(environment_obj)
11
+
12
+
13
+ def build_environment_model(environment_obj: object) -> EnvironmentModel:
14
+ return environment_schema.load(build_environment_dict(environment_obj))
File without changes
@@ -0,0 +1,7 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class IntegrationModel:
6
+ api_key: str = None
7
+ base_url: str = None
@@ -0,0 +1,12 @@
1
+ from marshmallow import Schema, fields, post_load
2
+
3
+ from flag_engine.environments.integrations.models import IntegrationModel
4
+
5
+
6
+ class IntegrationSchema(Schema):
7
+ api_key = fields.Str(required=False, allow_none=True)
8
+ base_url = fields.Str(required=False, allow_none=True)
9
+
10
+ @post_load()
11
+ def make_integration_model(self, data, **kwargs):
12
+ return IntegrationModel(**data)
@@ -0,0 +1,20 @@
1
+ import typing
2
+ from dataclasses import dataclass, field
3
+
4
+ from flag_engine.environments.integrations.models import IntegrationModel
5
+ from flag_engine.features.models import FeatureStateModel
6
+ from flag_engine.projects.models import ProjectModel
7
+ from flag_engine.segments.models import SegmentOverrideModel
8
+
9
+
10
+ @dataclass
11
+ class EnvironmentModel:
12
+ id: int
13
+ api_key: str
14
+ project: ProjectModel
15
+ feature_states: typing.List[FeatureStateModel] = field(default_factory=list)
16
+ segment_overrides: typing.List[SegmentOverrideModel] = field(default_factory=list)
17
+ amplitude_config: IntegrationModel = None
18
+ segment_config: IntegrationModel = None
19
+ mixpanel_config: IntegrationModel = None
20
+ heap_config: IntegrationModel = None
@@ -0,0 +1,26 @@
1
+ from marshmallow import fields
2
+
3
+ from flag_engine.environments.integrations.schemas import IntegrationSchema
4
+ from flag_engine.environments.models import EnvironmentModel
5
+ from flag_engine.features.schemas import FeatureStateSchema
6
+ from flag_engine.projects.schemas import ProjectSchema
7
+ from flag_engine.utils.marshmallow.fields import ListOrDjangoRelatedManagerField
8
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
9
+
10
+
11
+ class EnvironmentSchema(LoadToModelSchema):
12
+ id = fields.Int()
13
+ api_key = fields.Str()
14
+ feature_states = ListOrDjangoRelatedManagerField(
15
+ fields.Nested(FeatureStateSchema),
16
+ metadata={"filter_kwargs": {"feature_segment_id": None, "identity_id": None}},
17
+ )
18
+ project = fields.Nested(ProjectSchema)
19
+
20
+ segment_config = fields.Nested(IntegrationSchema, required=False, allow_none=True)
21
+ heap_config = fields.Nested(IntegrationSchema, required=False, allow_none=True)
22
+ mixpanel_config = fields.Nested(IntegrationSchema, required=False, allow_none=True)
23
+ amplitude_config = fields.Nested(IntegrationSchema, required=False, allow_none=True)
24
+
25
+ class Meta:
26
+ model_class = EnvironmentModel
File without changes
@@ -0,0 +1,3 @@
1
+ # Feature Types
2
+ STANDARD = "STANDARD"
3
+ MULTIVARIATE = "MULTIVARIATE"
@@ -0,0 +1,74 @@
1
+ import typing
2
+ from dataclasses import dataclass, field
3
+
4
+ from flag_engine.utils.hashing import get_hashed_percentage_for_object_ids
5
+
6
+
7
+ @dataclass
8
+ class FeatureModel:
9
+ id: int
10
+ name: str
11
+ type: str
12
+
13
+ def __eq__(self, other):
14
+ return self.id == other.id
15
+
16
+ def __hash__(self):
17
+ return hash(self.id)
18
+
19
+
20
+ @dataclass
21
+ class MultivariateFeatureOptionModel:
22
+ value: typing.Any
23
+
24
+
25
+ @dataclass
26
+ class MultivariateFeatureStateValueModel:
27
+ id: int
28
+ multivariate_feature_option: MultivariateFeatureOptionModel
29
+ percentage_allocation: float
30
+
31
+
32
+ @dataclass
33
+ class FeatureStateModel:
34
+ id: int
35
+ feature: FeatureModel
36
+ enabled: bool
37
+ _value: typing.Any = field(default=None, init=False)
38
+ multivariate_feature_state_values: typing.List[
39
+ MultivariateFeatureStateValueModel
40
+ ] = field(default_factory=list)
41
+
42
+ def set_value(self, value: typing.Any):
43
+ self._value = value
44
+
45
+ def get_value(self, identity_id: int = None):
46
+ if identity_id and len(self.multivariate_feature_state_values) > 0:
47
+ return self._get_multivariate_value(identity_id)
48
+ return self._value
49
+
50
+ def get_feature_state_value(self):
51
+ """Mimick django method name to simplify serialization logic"""
52
+ return self.get_value()
53
+
54
+ def _get_multivariate_value(self, identity_id: int) -> typing.Any:
55
+ percentage_value = get_hashed_percentage_for_object_ids([self.id, identity_id])
56
+
57
+ # Iterate over the mv options in order of id (so we get the same value each
58
+ # time) to determine the correct value to return to the identity based on
59
+ # the percentage allocations of the multivariate options. This gives us a
60
+ # way to ensure that the same value is returned every time we use the same
61
+ # percentage value.
62
+ start_percentage = 0
63
+ for mv_value in sorted(
64
+ self.multivariate_feature_state_values, key=lambda v: v.id
65
+ ):
66
+ limit = mv_value.percentage_allocation + start_percentage
67
+ if start_percentage <= percentage_value < limit:
68
+ return mv_value.multivariate_feature_option.value
69
+
70
+ start_percentage = limit
71
+
72
+ # default to return the control value if no MV values found, although this
73
+ # should never happen
74
+ return self._value
@@ -0,0 +1,69 @@
1
+ import typing
2
+
3
+ from marshmallow import Schema, fields, post_load, validate
4
+
5
+ from flag_engine.features.models import (
6
+ FeatureModel,
7
+ FeatureStateModel,
8
+ MultivariateFeatureOptionModel,
9
+ MultivariateFeatureStateValueModel,
10
+ )
11
+ from flag_engine.utils.marshmallow.fields import ListOrDjangoRelatedManagerField
12
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
13
+
14
+
15
+ class FeatureSchema(LoadToModelSchema):
16
+ id = fields.Int()
17
+ name = fields.Str()
18
+ type = fields.Str()
19
+
20
+ class Meta:
21
+ model_class = FeatureModel
22
+
23
+
24
+ class MultivariateFeatureOptionSchema(LoadToModelSchema):
25
+ value = fields.Field(allow_none=True)
26
+
27
+ class Meta:
28
+ model_class = MultivariateFeatureOptionModel
29
+
30
+
31
+ class MultivariateFeatureStateValueSchema(LoadToModelSchema):
32
+ id = fields.Int()
33
+ multivariate_feature_option = fields.Nested(MultivariateFeatureOptionSchema)
34
+ percentage_allocation = fields.Decimal(validate=[validate.Range(0, 100)])
35
+
36
+ class Meta:
37
+ model_class = MultivariateFeatureStateValueModel
38
+
39
+
40
+ class FeatureStateSchema(Schema):
41
+ id = fields.Int()
42
+ feature = fields.Nested(FeatureSchema)
43
+ enabled = fields.Bool()
44
+ value = fields.Method(
45
+ serialize="serialize_value",
46
+ deserialize="deserialize_value",
47
+ allow_none=True,
48
+ required=False,
49
+ )
50
+ multivariate_feature_state_values = ListOrDjangoRelatedManagerField(
51
+ fields.Nested(MultivariateFeatureStateValueSchema)
52
+ )
53
+
54
+ @post_load()
55
+ def make_feature_state(self, data, **kwargs) -> FeatureStateModel:
56
+ value = data.pop("value", None)
57
+ feature_state = FeatureStateModel(**data)
58
+ feature_state.set_value(value)
59
+ return feature_state
60
+
61
+ def serialize_value(self, instance: object) -> typing.Any:
62
+ if isinstance(instance, dict) and "value" in instance:
63
+ return instance["value"]
64
+
65
+ getter = getattr(instance, "get_feature_state_value", lambda *args: None)
66
+ return getter()
67
+
68
+ def deserialize_value(self, value: typing.Any) -> typing.Any:
69
+ return value
File without changes
@@ -0,0 +1,14 @@
1
+ import typing
2
+
3
+ from flag_engine.identities.models import IdentityModel
4
+ from flag_engine.identities.schemas import IdentitySchema
5
+
6
+ identity_schema = IdentitySchema()
7
+
8
+
9
+ def build_identity_dict(identity_obj: typing.Any) -> dict:
10
+ return identity_schema.dump(identity_obj)
11
+
12
+
13
+ def build_identity_model(identity_obj: typing.Any) -> IdentityModel:
14
+ return identity_schema.load(build_identity_dict(identity_obj))
@@ -0,0 +1,93 @@
1
+ import datetime
2
+ import typing
3
+ from dataclasses import dataclass, field
4
+
5
+ from flag_engine.environments.models import EnvironmentModel
6
+ from flag_engine.features.models import FeatureStateModel
7
+ from flag_engine.segments import constants
8
+ from flag_engine.segments.models import (
9
+ SegmentConditionModel,
10
+ SegmentModel,
11
+ SegmentRuleModel,
12
+ )
13
+ from flag_engine.utils.hashing import get_hashed_percentage_for_object_ids
14
+
15
+
16
+ @dataclass
17
+ class TraitModel:
18
+ trait_key: str
19
+ trait_value: typing.Any
20
+
21
+
22
+ @dataclass
23
+ class IdentityModel:
24
+ id: int
25
+ identifier: str
26
+ environment_api_key: str
27
+ created_date: datetime = field(default_factory=datetime.datetime.now)
28
+ identity_features: typing.List[FeatureStateModel] = field(default_factory=list)
29
+ identity_traits: typing.List[TraitModel] = field(default_factory=list)
30
+
31
+ @property
32
+ def composite_key(self):
33
+ return self.generate_composite_key(self.environment_api_key, self.identifier)
34
+
35
+ def get_all_feature_states(
36
+ self, environment: EnvironmentModel
37
+ ) -> typing.List[FeatureStateModel]:
38
+ all_feature_states = {fs.feature: fs for fs in environment.feature_states}
39
+
40
+ for segment_override in environment.segment_overrides:
41
+ feature_state = segment_override.feature_state
42
+ feature = feature_state.feature
43
+ if self.in_segment(segment_override.segment):
44
+ all_feature_states[feature] = feature_state
45
+
46
+ for feature_state in self.identity_features:
47
+ if feature_state.feature in all_feature_states:
48
+ all_feature_states[feature_state.feature] = feature_state
49
+
50
+ return list(all_feature_states.values())
51
+
52
+ def in_segment(self, segment: SegmentModel) -> bool:
53
+ return len(segment.rules) > 0 and all(
54
+ self._matches_segment_rule(rule=rule, segment_id=segment.id)
55
+ for rule in segment.rules
56
+ )
57
+
58
+ @staticmethod
59
+ def generate_composite_key(env_key: str, identifier: str) -> str:
60
+ return f"{env_key}_{identifier}"
61
+
62
+ def _matches_segment_rule(self, rule: SegmentRuleModel, segment_id: int) -> bool:
63
+ matches_conditions = (
64
+ rule.matching_function(
65
+ [
66
+ self._matches_segment_condition(condition, segment_id)
67
+ for condition in rule.conditions
68
+ ]
69
+ )
70
+ if len(rule.conditions) > 0
71
+ else True
72
+ )
73
+
74
+ return matches_conditions and all(
75
+ [self._matches_segment_rule(rule, segment_id) for rule in rule.rules]
76
+ )
77
+
78
+ def _matches_segment_condition(
79
+ self, condition: SegmentConditionModel, segment_id: int
80
+ ) -> bool:
81
+ if condition.operator == constants.PERCENTAGE_SPLIT:
82
+ return (
83
+ get_hashed_percentage_for_object_ids([segment_id, self.id])
84
+ <= condition.value
85
+ )
86
+
87
+ # TODO: regex
88
+
89
+ trait = next(
90
+ filter(lambda t: t.trait_key == condition.property_, self.identity_traits),
91
+ None,
92
+ )
93
+ return condition.matches_trait_value(trait.trait_value) if trait else False
@@ -0,0 +1,70 @@
1
+ import typing
2
+ from datetime import datetime
3
+
4
+ from marshmallow import EXCLUDE, fields, post_dump, utils
5
+
6
+ from flag_engine.features.schemas import FeatureStateSchema
7
+ from flag_engine.identities.models import IdentityModel, TraitModel
8
+ from flag_engine.utils.marshmallow.fields import ListOrDjangoRelatedManagerField
9
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
10
+
11
+
12
+ class TraitSchema(LoadToModelSchema):
13
+ trait_key = fields.Str()
14
+ trait_value = fields.Str()
15
+
16
+ class Meta:
17
+ model_class = TraitModel
18
+
19
+
20
+ class IdentitySchema(LoadToModelSchema):
21
+ id = fields.Int()
22
+ identifier = fields.Str()
23
+ composite_key = fields.Str(dump_only=True)
24
+ created_date = fields.Method(
25
+ serialize="serialize_created_date",
26
+ deserialize="deserialize_created_date",
27
+ )
28
+ environment_api_key = fields.Method(
29
+ serialize="serialize_environment_api_key",
30
+ deserialize="deserialize_environment_api_key",
31
+ )
32
+ identity_traits = ListOrDjangoRelatedManagerField(
33
+ fields.Nested(TraitSchema), required=False
34
+ )
35
+ identity_features = ListOrDjangoRelatedManagerField(
36
+ fields.Nested(FeatureStateSchema), required=False
37
+ )
38
+
39
+ class Meta:
40
+ # to exclude dump only fields, e.g: composite_key
41
+ unknown = EXCLUDE
42
+ model_class = IdentityModel
43
+
44
+ @post_dump
45
+ def generate_composite_key(self, data: typing.Dict[str, typing.Any], **kwargs):
46
+ data.setdefault(
47
+ "composite_key",
48
+ IdentityModel.generate_composite_key(
49
+ env_key=data["environment_api_key"], identifier=data["identifier"]
50
+ ),
51
+ )
52
+ return data
53
+
54
+ def serialize_environment_api_key(self, obj: typing.Any) -> int:
55
+ if hasattr(obj, "environment"):
56
+ return obj.environment.api_key
57
+
58
+ return getattr(obj, "environment_api_key", None) or obj["environment_api_key"]
59
+
60
+ def deserialize_environment_api_key(self, environment_api_key: int) -> int:
61
+ return environment_api_key
62
+
63
+ def serialize_created_date(self, obj: typing.Any) -> str:
64
+ created_date = getattr(obj, "created_date", None) or obj["created_date"]
65
+ if isinstance(created_date, str):
66
+ return created_date
67
+ return created_date.isoformat()
68
+
69
+ def deserialize_created_date(self, created_date: str) -> datetime:
70
+ return utils.from_iso_datetime(created_date)
File without changes
@@ -0,0 +1,10 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class OrganisationModel:
6
+ id: int
7
+ name: str
8
+ feature_analytics: bool
9
+ stop_serving_flags: bool
10
+ persist_trait_data: bool
@@ -0,0 +1,15 @@
1
+ from marshmallow import fields
2
+
3
+ from flag_engine.organisations.models import OrganisationModel
4
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
5
+
6
+
7
+ class OrganisationSchema(LoadToModelSchema):
8
+ id = fields.Int()
9
+ name = fields.Str()
10
+ stop_serving_flags = fields.Boolean()
11
+ persist_trait_data = fields.Boolean()
12
+ feature_analytics = fields.Boolean()
13
+
14
+ class Meta:
15
+ model_class = OrganisationModel
File without changes
@@ -0,0 +1,14 @@
1
+ import typing
2
+ from dataclasses import dataclass, field
3
+
4
+ from flag_engine.organisations.models import OrganisationModel
5
+ from flag_engine.segments.models import SegmentModel
6
+
7
+
8
+ @dataclass
9
+ class ProjectModel:
10
+ id: int
11
+ name: str
12
+ organisation: OrganisationModel
13
+ hide_disabled_flags: bool
14
+ segments: typing.List[SegmentModel] = field(default_factory=list)
@@ -0,0 +1,20 @@
1
+ from marshmallow import fields
2
+
3
+ from flag_engine.organisations.schemas import OrganisationSchema
4
+ from flag_engine.projects.models import ProjectModel
5
+ from flag_engine.segments.schemas import SegmentSchema
6
+ from flag_engine.utils.marshmallow.fields import ListOrDjangoRelatedManagerField
7
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
8
+
9
+
10
+ class ProjectSchema(LoadToModelSchema):
11
+ id = fields.Int()
12
+ name = fields.Str()
13
+ segments = ListOrDjangoRelatedManagerField(
14
+ fields.Nested(SegmentSchema), required=False
15
+ )
16
+ organisation = fields.Nested(OrganisationSchema)
17
+ hide_disabled_flags = fields.Bool()
18
+
19
+ class Meta:
20
+ model_class = ProjectModel
File without changes
@@ -0,0 +1,31 @@
1
+ # Segment Rules
2
+ ALL_RULE = "ALL"
3
+ ANY_RULE = "ANY"
4
+ NONE_RULE = "NONE"
5
+
6
+ RULE_TYPES = [ALL_RULE, ANY_RULE, NONE_RULE]
7
+
8
+ # Segment Condition Operators
9
+ EQUAL = "EQUAL"
10
+ GREATER_THAN = "GREATER_THAN"
11
+ LESS_THAN = "LESS_THAN"
12
+ LESS_THAN_INCLUSIVE = "LESS_THAN_INCLUSIVE"
13
+ CONTAINS = "CONTAINS"
14
+ GREATER_THAN_INCLUSIVE = "GREATER_THAN_INCLUSIVE"
15
+ NOT_CONTAINS = "NOT_CONTAINS"
16
+ NOT_EQUAL = "NOT_EQUAL"
17
+ REGEX = "REGEX"
18
+ PERCENTAGE_SPLIT = "PERCENTAGE_SPLIT"
19
+
20
+ CONDITION_OPERATORS = [
21
+ EQUAL,
22
+ GREATER_THAN,
23
+ LESS_THAN,
24
+ LESS_THAN_INCLUSIVE,
25
+ CONTAINS,
26
+ GREATER_THAN_INCLUSIVE,
27
+ NOT_CONTAINS,
28
+ NOT_EQUAL,
29
+ REGEX,
30
+ PERCENTAGE_SPLIT,
31
+ ]
@@ -0,0 +1,67 @@
1
+ import typing
2
+ from dataclasses import dataclass, field
3
+
4
+ from flag_engine.features.models import FeatureStateModel
5
+ from flag_engine.segments import constants
6
+
7
+
8
+ @dataclass
9
+ class SegmentConditionModel:
10
+ operator: str
11
+ value: typing.Any
12
+ property_: str = None
13
+
14
+ def matches_trait_value(self, trait_value: typing.Any) -> bool:
15
+ matching_function_name = {
16
+ constants.EQUAL: "__eq__",
17
+ constants.GREATER_THAN: "__gt__",
18
+ constants.GREATER_THAN_INCLUSIVE: "__ge__",
19
+ constants.LESS_THAN: "__lt__",
20
+ constants.LESS_THAN_INCLUSIVE: "__le__",
21
+ constants.NOT_EQUAL: "__ne__",
22
+ constants.CONTAINS: "__contains__",
23
+ constants.NOT_CONTAINS: "__contains__",
24
+ }.get(self.operator)
25
+
26
+ matching_function = getattr(
27
+ trait_value, matching_function_name, lambda v: False
28
+ )
29
+ result = matching_function(self.value)
30
+
31
+ if self.operator == constants.NOT_CONTAINS:
32
+ # negate the contains result as there is no built in method for notcontains
33
+ return not result
34
+
35
+ return result
36
+
37
+
38
+ @dataclass
39
+ class SegmentRuleModel:
40
+ type: str
41
+ rules: typing.List["SegmentRuleModel"] = field(default_factory=list)
42
+ conditions: typing.List[SegmentConditionModel] = field(default_factory=list)
43
+
44
+ @staticmethod
45
+ def none(iterable: typing.Iterable) -> bool:
46
+ return not any(iterable)
47
+
48
+ @property
49
+ def matching_function(self) -> callable:
50
+ return {
51
+ constants.ANY_RULE: any,
52
+ constants.ALL_RULE: all,
53
+ constants.NONE_RULE: SegmentRuleModel.none,
54
+ }.get(self.type)
55
+
56
+
57
+ @dataclass
58
+ class SegmentModel:
59
+ id: int
60
+ name: str
61
+ rules: typing.List[SegmentRuleModel] = field(default_factory=list)
62
+
63
+
64
+ @dataclass
65
+ class SegmentOverrideModel:
66
+ segment: SegmentModel
67
+ feature_state: FeatureStateModel
@@ -0,0 +1,41 @@
1
+ from marshmallow import fields, validate
2
+
3
+ from flag_engine.segments import constants
4
+ from flag_engine.segments.models import (
5
+ SegmentConditionModel,
6
+ SegmentModel,
7
+ SegmentRuleModel,
8
+ )
9
+ from flag_engine.utils.marshmallow.fields import ListOrDjangoRelatedManagerField
10
+ from flag_engine.utils.marshmallow.schemas import LoadToModelSchema
11
+
12
+
13
+ class SegmentConditionSchema(LoadToModelSchema):
14
+ operator = fields.Str(validate=validate.OneOf(constants.CONDITION_OPERATORS))
15
+ property_ = fields.Str(attribute="property")
16
+ value = fields.Field()
17
+
18
+ class Meta:
19
+ model_class = SegmentConditionModel
20
+
21
+
22
+ class SegmentRuleSchema(LoadToModelSchema):
23
+ type = fields.Str(validate=validate.OneOf(constants.RULE_TYPES))
24
+ rules = ListOrDjangoRelatedManagerField(
25
+ fields.Nested("SegmentRuleSchema"), required=False
26
+ )
27
+ conditions = ListOrDjangoRelatedManagerField(
28
+ fields.Nested(SegmentConditionSchema), required=False
29
+ )
30
+
31
+ class Meta:
32
+ model_class = SegmentRuleModel
33
+
34
+
35
+ class SegmentSchema(LoadToModelSchema):
36
+ id = fields.Int()
37
+ name = fields.Str()
38
+ rules = ListOrDjangoRelatedManagerField(fields.Nested(SegmentRuleSchema))
39
+
40
+ class Meta:
41
+ model_class = SegmentModel
File without changes
@@ -0,0 +1,31 @@
1
+ import hashlib
2
+ import typing
3
+
4
+
5
+ def get_hashed_percentage_for_object_ids(
6
+ object_ids: typing.Iterable[int], iterations: int = 1
7
+ ) -> float:
8
+ """
9
+ Given a list of object ids, get a floating point number between 0 and 1 based on
10
+ the hash of those ids. This should give the same value every time for any
11
+ list of ids.
12
+
13
+ :param object_ids: list of object ids to calculate the has for
14
+ :param iterations: num times to include each id in the generated string to hash
15
+ :return: (float) number between 0 (inclusive) and 100 (exclusive)
16
+ """
17
+
18
+ to_hash = ",".join(str(id_) for id_ in list(object_ids) * iterations)
19
+ hashed_value = hashlib.md5(to_hash.encode("utf-8"))
20
+ hashed_value_as_int = int(hashed_value.hexdigest(), base=16)
21
+ value = ((hashed_value_as_int % 9999) / 9998) * 100
22
+
23
+ if value == 100:
24
+ # since we want a number between 0 (inclusive) and 1 (exclusive), in the
25
+ # unlikely case that we get the exact number 1, we call the method again
26
+ # and increase the number of iterations to ensure we get a different result
27
+ return get_hashed_percentage_for_object_ids(
28
+ object_ids=object_ids, iterations=iterations + 1
29
+ )
30
+
31
+ return value