wingify-fme-python-sdk 1.70.0__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.
Files changed (186) hide show
  1. tests/data/__init__.py +13 -0
  2. tests/data/dummy_test_data_reader.py +63 -0
  3. tests/data/user_storage.py +48 -0
  4. tests/e2e/__init__.py +13 -0
  5. tests/e2e/custom_bucketing_test.py +514 -0
  6. tests/e2e/force_users_test.py +368 -0
  7. tests/e2e/get_flag_test.py +195 -0
  8. tests/unit/__init__.py +13 -0
  9. tests/unit/packages/__init__.py +13 -0
  10. tests/unit/packages/decision_maker/__init__.py +13 -0
  11. tests/unit/packages/decision_maker/decision_maker_test.py +83 -0
  12. tests/unit/packages/segmentation_evaluator/__init__.py +13 -0
  13. tests/unit/packages/segmentation_evaluator/segmentation_evaluator_test.py +284 -0
  14. tests/unit/packages/segmentation_evaluator/segmentation_manager_test.py +215 -0
  15. tests/unit/packages/segmentation_evaluator/web_testing_segment_test.py +216 -0
  16. tests/unit/services/__init__.py +0 -0
  17. tests/unit/services/hooks_manager_test.py +80 -0
  18. tests/unit/services/internal_events_sampling_service_test.py +160 -0
  19. tests/unit/settings/__init__.py +13 -0
  20. tests/unit/settings/settings_schema_validation_test.py +67 -0
  21. tests/unit/utils/__init__.py +0 -0
  22. tests/unit/utils/campaign_util_test.py +248 -0
  23. tests/unit/utils/decision_util_force_users_test.py +790 -0
  24. tests/unit/utils/log_message_test.py +65 -0
  25. tests/unit/vwo_wingify_test.py +175 -0
  26. tests/unit/wingify_client_validation_test.py +72 -0
  27. vwo/__init__.py +35 -0
  28. vwo/models/__init__.py +13 -0
  29. vwo/models/batch_event_data.py +19 -0
  30. vwo/models/user/__init__.py +13 -0
  31. vwo/models/user/context_vwo_model.py +21 -0
  32. vwo/models/user/get_flag.py +19 -0
  33. vwo/models/vwo_options_model.py +21 -0
  34. vwo/packages/__init__.py +13 -0
  35. vwo/packages/logger/__init__.py +13 -0
  36. vwo/packages/logger/enums/__init__.py +13 -0
  37. vwo/packages/logger/enums/log_level_enum.py +19 -0
  38. vwo/packages/storage/__init__.py +13 -0
  39. vwo/packages/storage/connector.py +19 -0
  40. vwo/vwo.py +58 -0
  41. vwo/vwo_builder.py +21 -0
  42. vwo/vwo_client.py +22 -0
  43. wingify/__init__.py +36 -0
  44. wingify/api/__init__.py +13 -0
  45. wingify/api/get_flag_api.py +727 -0
  46. wingify/api/set_attribute_api.py +60 -0
  47. wingify/api/track_api.py +99 -0
  48. wingify/constants/Constants.py +94 -0
  49. wingify/constants/__init__.py +13 -0
  50. wingify/constants/sampled_debug_error_template_keys.py +34 -0
  51. wingify/decorators/__init__.py +13 -0
  52. wingify/decorators/storage_decorator.py +92 -0
  53. wingify/enums/__init__.py +13 -0
  54. wingify/enums/api_enum.py +26 -0
  55. wingify/enums/campaign_type_enum.py +22 -0
  56. wingify/enums/debug_category_enum.py +24 -0
  57. wingify/enums/event_enum.py +26 -0
  58. wingify/enums/headers_enum.py +21 -0
  59. wingify/enums/hooks_enum.py +24 -0
  60. wingify/enums/status_enum.py +21 -0
  61. wingify/enums/storage_enum.py +25 -0
  62. wingify/enums/url_enum.py +29 -0
  63. wingify/models/Alias.py +60 -0
  64. wingify/models/AliasSetResponse.py +43 -0
  65. wingify/models/__init__.py +13 -0
  66. wingify/models/batch_event_data.py +68 -0
  67. wingify/models/campaign/__init__.py +13 -0
  68. wingify/models/campaign/campaign_model.py +140 -0
  69. wingify/models/campaign/feature_model.py +95 -0
  70. wingify/models/campaign/holdout_model.py +94 -0
  71. wingify/models/campaign/impact_campaign_model.py +60 -0
  72. wingify/models/campaign/metric_model.py +42 -0
  73. wingify/models/campaign/rule_model.py +42 -0
  74. wingify/models/campaign/variable_model.py +44 -0
  75. wingify/models/campaign/variation_model.py +109 -0
  76. wingify/models/gateway_service_model.py +48 -0
  77. wingify/models/schemas/__init__.py +13 -0
  78. wingify/models/schemas/campaign_group_schema.py +19 -0
  79. wingify/models/schemas/campaign_metric_schema.py +26 -0
  80. wingify/models/schemas/campaign_schema.py +37 -0
  81. wingify/models/schemas/campaign_variation_schema.py +34 -0
  82. wingify/models/schemas/empty_object_schema.py +15 -0
  83. wingify/models/schemas/feature_schema.py +38 -0
  84. wingify/models/schemas/group_schema.py +37 -0
  85. wingify/models/schemas/holdout_schema.py +29 -0
  86. wingify/models/schemas/rule_schema.py +24 -0
  87. wingify/models/schemas/settings_schema.py +47 -0
  88. wingify/models/schemas/variable_schema.py +24 -0
  89. wingify/models/settings/__init__.py +13 -0
  90. wingify/models/settings/internal_event_sampling_settings_model.py +53 -0
  91. wingify/models/settings/settings_model.py +127 -0
  92. wingify/models/storage/__init__.py +13 -0
  93. wingify/models/storage/storage_model.py +84 -0
  94. wingify/models/user/__init__.py +13 -0
  95. wingify/models/user/context_model.py +113 -0
  96. wingify/models/user/context_vwo_model.py +34 -0
  97. wingify/models/user/get_flag.py +47 -0
  98. wingify/models/vwo_options_model.py +21 -0
  99. wingify/models/wingify_options_model.py +129 -0
  100. wingify/packages/__init__.py +13 -0
  101. wingify/packages/decision_maker/__init__.py +13 -0
  102. wingify/packages/decision_maker/decision_maker.py +89 -0
  103. wingify/packages/logger/__init__.py +13 -0
  104. wingify/packages/logger/core/__init__.py +13 -0
  105. wingify/packages/logger/core/log_manager.py +123 -0
  106. wingify/packages/logger/core/log_transport_manager.py +57 -0
  107. wingify/packages/logger/enums/__init__.py +13 -0
  108. wingify/packages/logger/enums/log_level_enum.py +24 -0
  109. wingify/packages/logger/enums/log_level_number_enum.py +21 -0
  110. wingify/packages/logger/log_message_builder.py +70 -0
  111. wingify/packages/logger/logger.py +38 -0
  112. wingify/packages/logger/transports/__init__.py +13 -0
  113. wingify/packages/logger/transports/console_transport.py +43 -0
  114. wingify/packages/network_layer/__init__.py +13 -0
  115. wingify/packages/network_layer/client/__init__.py +13 -0
  116. wingify/packages/network_layer/client/network_client.py +167 -0
  117. wingify/packages/network_layer/handlers/__init__.py +13 -0
  118. wingify/packages/network_layer/handlers/request_handler.py +40 -0
  119. wingify/packages/network_layer/manager/__init__.py +13 -0
  120. wingify/packages/network_layer/manager/network_manager.py +79 -0
  121. wingify/packages/network_layer/models/__init__.py +13 -0
  122. wingify/packages/network_layer/models/global_request_model.py +70 -0
  123. wingify/packages/network_layer/models/request_model.py +133 -0
  124. wingify/packages/network_layer/models/response_model.py +55 -0
  125. wingify/packages/segmentation_evaluator/__init__.py +13 -0
  126. wingify/packages/segmentation_evaluator/core/__init__.py +13 -0
  127. wingify/packages/segmentation_evaluator/core/segmentation_manager.py +140 -0
  128. wingify/packages/segmentation_evaluator/enums/__init__.py +13 -0
  129. wingify/packages/segmentation_evaluator/enums/segment_operand_regex_enum.py +31 -0
  130. wingify/packages/segmentation_evaluator/enums/segment_operand_value_enum.py +29 -0
  131. wingify/packages/segmentation_evaluator/enums/segment_operator_value_enum.py +37 -0
  132. wingify/packages/segmentation_evaluator/evaluators/__init__.py +13 -0
  133. wingify/packages/segmentation_evaluator/evaluators/segment_evaluator.py +237 -0
  134. wingify/packages/segmentation_evaluator/evaluators/segment_operand_evaluator.py +518 -0
  135. wingify/packages/segmentation_evaluator/utils/__init__.py +13 -0
  136. wingify/packages/segmentation_evaluator/utils/segment_util.py +33 -0
  137. wingify/packages/segmentation_evaluator/utils/web_testing_segment_util.py +295 -0
  138. wingify/packages/storage/__init__.py +13 -0
  139. wingify/packages/storage/connector.py +25 -0
  140. wingify/packages/storage/storage.py +39 -0
  141. wingify/resources/__init__.py +13 -0
  142. wingify/resources/debug-messages.json +21 -0
  143. wingify/resources/error-messages.json +62 -0
  144. wingify/resources/info-message.json +47 -0
  145. wingify/resources/trace-messages.json +1 -0
  146. wingify/resources/warn-messages.json +1 -0
  147. wingify/services/__init__.py +13 -0
  148. wingify/services/batch_event_queue.py +140 -0
  149. wingify/services/campaign_decision_service.py +268 -0
  150. wingify/services/hooks_manager.py +65 -0
  151. wingify/services/internal_events_sampling_service.py +62 -0
  152. wingify/services/settings_manager.py +293 -0
  153. wingify/services/storage_service.py +58 -0
  154. wingify/services/url_service.py +51 -0
  155. wingify/utils/__init__.py +13 -0
  156. wingify/utils/aliasing_util.py +108 -0
  157. wingify/utils/brand_context.py +26 -0
  158. wingify/utils/brand_util.py +37 -0
  159. wingify/utils/campaign_util.py +592 -0
  160. wingify/utils/data_type_util.py +125 -0
  161. wingify/utils/debugger_service_util.py +58 -0
  162. wingify/utils/decision_util.py +589 -0
  163. wingify/utils/event_util.py +85 -0
  164. wingify/utils/function_util.py +188 -0
  165. wingify/utils/gateway_service_util.py +179 -0
  166. wingify/utils/holdout_util.py +264 -0
  167. wingify/utils/impression_util.py +151 -0
  168. wingify/utils/internal_events_sampling_util.py +106 -0
  169. wingify/utils/log_message_util.py +95 -0
  170. wingify/utils/meg_util.py +561 -0
  171. wingify/utils/model_utils.py +136 -0
  172. wingify/utils/network_util.py +706 -0
  173. wingify/utils/rule_evaluation_util.py +102 -0
  174. wingify/utils/settings_util.py +39 -0
  175. wingify/utils/usage_stats_util.py +116 -0
  176. wingify/utils/uuid_util.py +81 -0
  177. wingify/vwo_client.py +21 -0
  178. wingify/wingify.py +159 -0
  179. wingify/wingify_builder.py +282 -0
  180. wingify/wingify_client.py +520 -0
  181. wingify_fme_python_sdk-1.70.0.dist-info/METADATA +1415 -0
  182. wingify_fme_python_sdk-1.70.0.dist-info/RECORD +186 -0
  183. wingify_fme_python_sdk-1.70.0.dist-info/WHEEL +5 -0
  184. wingify_fme_python_sdk-1.70.0.dist-info/licenses/LICENSE +202 -0
  185. wingify_fme_python_sdk-1.70.0.dist-info/licenses/NOTICE +18 -0
  186. wingify_fme_python_sdk-1.70.0.dist-info/top_level.txt +3 -0
@@ -0,0 +1,140 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from ....enums.url_enum import UrlEnum
17
+ from ....models.user.context_vwo_model import ContextVWOModel
18
+ from ....packages.logger.core.log_manager import LogManager
19
+ from ....services.settings_manager import SettingsManager
20
+ from ...segmentation_evaluator.evaluators.segment_evaluator import SegmentEvaluator
21
+ from ....models.settings.settings_model import SettingsModel
22
+ from ....models.campaign.feature_model import FeatureModel
23
+ from ....models.user.context_model import ContextModel
24
+ from ....utils.gateway_service_util import get_query_params, get_from_gateway_service
25
+ from ....constants.Constants import Constants
26
+ from ....enums.api_enum import ApiEnum
27
+ from ..utils.web_testing_segment_util import (
28
+ dsl_contains_campaign_variation_node,
29
+ is_web_testing_campaigns_absent_or_null,
30
+ )
31
+
32
+
33
+ class SegmentationManager:
34
+ _instance = None # Singleton instance of SegmentationManager
35
+ evaluator = None # Holds the instance of SegmentEvaluator
36
+
37
+ def __new__(cls):
38
+ """
39
+ Singleton pattern implementation for creating the instance of SegmentationManager.
40
+ """
41
+ if cls._instance is None:
42
+ cls._instance = super(SegmentationManager, cls).__new__(cls)
43
+ return cls._instance
44
+
45
+ @staticmethod
46
+ def get_instance():
47
+ """
48
+ Singleton pattern implementation for getting the instance of SegmentationManager.
49
+
50
+ :return: The singleton instance.
51
+ """
52
+ if SegmentationManager._instance is None:
53
+ SegmentationManager._instance = SegmentationManager()
54
+ return SegmentationManager._instance
55
+
56
+ def attach_evaluator(self, evaluator=None):
57
+ """
58
+ Attaches an evaluator to the manager, or creates a new one if none is provided.
59
+
60
+ :param evaluator: Optional evaluator to attach.
61
+ """
62
+ if evaluator:
63
+ self.evaluator = evaluator
64
+ else:
65
+ self.evaluator = SegmentEvaluator()
66
+
67
+ def set_contextual_data(
68
+ self, settings: SettingsModel, feature: FeatureModel, context: ContextModel
69
+ ):
70
+ """
71
+ Sets the contextual data for the segmentation process.
72
+
73
+ :param settings: The settings data.
74
+ :param feature: The feature data including segmentation needs.
75
+ :param context: The context data for the evaluation.
76
+ """
77
+ self.attach_evaluator() # Ensure a fresh evaluator instance
78
+ self.evaluator.settings = settings # Set settings in evaluator
79
+ self.evaluator.context = context # Set context in evaluator
80
+ self.evaluator.feature = feature # Set feature in evaluator
81
+
82
+ # if both user agent and ip address is none or empty then return
83
+ if not context.get_user_agent() and not context.get_ip_address():
84
+ return
85
+
86
+ # Check if any holdout requires gateway service
87
+ holdouts = settings.get_holdouts() or []
88
+ is_gateway_service_required_for_holdouts = len(
89
+ list(
90
+ filter(
91
+ lambda holdout: holdout.get_is_gateway_service_required(), holdouts
92
+ )
93
+ )
94
+ ) > 0
95
+ is_segmentation_gateway_required = (
96
+ feature.get_is_gateway_service_required()
97
+ or is_gateway_service_required_for_holdouts
98
+ )
99
+ # Call get-user-details only when gateway_service is configured and
100
+ # segmentation (feature or holdout) requires gateway data.
101
+ # proxy_url alone must never trigger a gateway call.
102
+ should_call_gateway_service = (
103
+ SettingsManager.get_instance().is_gateway_service_provided
104
+ and is_segmentation_gateway_required
105
+ )
106
+
107
+ if should_call_gateway_service and context.get_vwo() is None:
108
+ query_params = {}
109
+ if not context.get_user_agent() and not context.get_ip_address():
110
+ return
111
+
112
+ if context.get_user_agent():
113
+ query_params["userAgent"] = context.get_user_agent()
114
+
115
+ if context.get_ip_address():
116
+ query_params["ipAddress"] = context.get_ip_address()
117
+
118
+ try:
119
+ params = get_query_params(query_params)
120
+ _vwo = get_from_gateway_service(params, UrlEnum.GET_USER_DATA.value, context)
121
+ context.set_vwo(ContextVWOModel(_vwo))
122
+ except Exception as err:
123
+ LogManager.get_instance().error_log("ERROR_SETTING_SEGMENTATION_CONTEXT",data={"err": str(err)}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": context.get_vwo_uuid(), "sId": context.get_session_id()})
124
+
125
+ def validate_segmentation(self, dsl, properties):
126
+ """
127
+ Validates the segmentation against provided DSL and properties.
128
+
129
+ :param dsl: The segmentation DSL.
130
+ :param properties: The properties to validate against.
131
+ :return: True if segmentation is valid, otherwise False.
132
+ """
133
+ # if the dsl contains a campaign variation node, then we need to check if the campaign variation is valid
134
+ if dsl_contains_campaign_variation_node(dsl):
135
+ evaluation_context = getattr(self.evaluator, "context", None)
136
+ if evaluation_context is None or is_web_testing_campaigns_absent_or_null(
137
+ evaluation_context
138
+ ):
139
+ return False
140
+ return self.evaluator.is_segmentation_valid(dsl, properties)
@@ -0,0 +1,13 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,31 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from enum import Enum, auto
17
+
18
+
19
+ class SegmentOperandRegexEnum(Enum):
20
+ LOWER = r"^lower"
21
+ LOWER_MATCH = r"^lower\((.*)\)"
22
+ WILDCARD = r"^wildcard"
23
+ WILDCARD_MATCH = r"^wildcard\((.*)\)"
24
+ REGEX = r"^regex"
25
+ REGEX_MATCH = r"^regex\((.*)\)"
26
+ STARTING_STAR = r"^\*"
27
+ ENDING_STAR = r"\*$"
28
+ GREATER_THAN_MATCH = r"^gt\(([\d.]+)\)$"
29
+ GREATER_THAN_EQUAL_TO_MATCH = r"^gte\(([\d.]+)\)$"
30
+ LESS_THAN_MATCH = r"^lt\(([\d.]+)\)$"
31
+ LESS_THAN_EQUAL_TO_MATCH = r"^lte\(([\d.]+)\)$"
@@ -0,0 +1,29 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from enum import Enum, auto
17
+
18
+
19
+ class SegmentOperandValueEnum(Enum):
20
+ LOWER_VALUE = 1
21
+ STARTING_ENDING_STAR_VALUE = 2
22
+ STARTING_STAR_VALUE = 3
23
+ ENDING_STAR_VALUE = 4
24
+ REGEX_VALUE = 5
25
+ EQUAL_VALUE = 6
26
+ GREATER_THAN_VALUE = 7
27
+ GREATER_THAN_EQUAL_TO_VALUE = 8
28
+ LESS_THAN_VALUE = 9
29
+ LESS_THAN_EQUAL_TO_VALUE = 10
@@ -0,0 +1,37 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from enum import Enum, auto
17
+
18
+
19
+ class SegmentOperatorValueEnum(Enum):
20
+ AND = "and"
21
+ NOT = "not"
22
+ OR = "or"
23
+ CUSTOM_VARIABLE = "custom_variable"
24
+ USER = "user"
25
+ COUNTRY = "country"
26
+ REGION = "region"
27
+ CITY = "city"
28
+ OPERATING_SYSTEM = "os"
29
+ DEVICE_TYPE = "device_type"
30
+ DEVICE = "device"
31
+ BROWSER_AGENT = "browser_string"
32
+ UA = "ua"
33
+ FEATURE_ID = "featureId"
34
+ IP = "ip_address"
35
+ BROWSER_VERSION = "browser_version"
36
+ OS_VERSION = "os_version"
37
+ WEB_CAMPAIGN_VARIATION = "campaignVariation"
@@ -0,0 +1,13 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,237 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from ..utils.segment_util import get_key_value
17
+ from ..enums.segment_operator_value_enum import SegmentOperatorValueEnum
18
+ from ..evaluators.segment_operand_evaluator import SegmentOperandEvaluator
19
+ from ....models.user.context_model import ContextModel
20
+ from ....models.settings.settings_model import SettingsModel
21
+ from ....models.campaign.feature_model import FeatureModel
22
+ from ...logger.core.log_manager import LogManager
23
+ from ....services.storage_service import StorageService
24
+ from ....decorators.storage_decorator import StorageDecorator
25
+ import re
26
+ from typing import Dict, List, Any
27
+ from ....enums.api_enum import ApiEnum
28
+
29
+
30
+ class SegmentEvaluator:
31
+ def __init__(self):
32
+ self.context: ContextModel = None
33
+ self.settings: SettingsModel = None
34
+ self.feature: FeatureModel = None
35
+
36
+ def is_segmentation_valid(self, dsl, properties):
37
+ key, value = get_key_value(dsl)
38
+ operator = key
39
+ sub_dsl = value
40
+
41
+ # Evaluate based on the type of segmentation operator
42
+ if operator == SegmentOperatorValueEnum.NOT.value:
43
+ result = self.is_segmentation_valid(sub_dsl, properties)
44
+ return not result
45
+ elif operator == SegmentOperatorValueEnum.AND.value:
46
+ return self.every(sub_dsl, properties)
47
+ elif operator == SegmentOperatorValueEnum.OR.value:
48
+ return self.some(sub_dsl, properties)
49
+ elif operator == SegmentOperatorValueEnum.CUSTOM_VARIABLE.value:
50
+ return SegmentOperandEvaluator().evaluate_custom_variable_dsl(
51
+ sub_dsl, properties, self.context
52
+ )
53
+ elif operator == SegmentOperatorValueEnum.USER.value:
54
+ return SegmentOperandEvaluator().evaluate_user_dsl(sub_dsl, properties)
55
+ elif operator == SegmentOperatorValueEnum.UA.value:
56
+ return SegmentOperandEvaluator().evaluate_user_agent_dsl(
57
+ sub_dsl, self.context
58
+ )
59
+ elif operator == SegmentOperatorValueEnum.IP.value:
60
+ return SegmentOperandEvaluator().evaluate_string_operand_dsl(
61
+ sub_dsl, self.context, SegmentOperatorValueEnum.IP.value
62
+ )
63
+ elif operator == SegmentOperatorValueEnum.BROWSER_VERSION.value:
64
+ return SegmentOperandEvaluator().evaluate_string_operand_dsl(
65
+ sub_dsl, self.context, SegmentOperatorValueEnum.BROWSER_VERSION.value
66
+ )
67
+ elif operator == SegmentOperatorValueEnum.OS_VERSION.value:
68
+ return SegmentOperandEvaluator().evaluate_string_operand_dsl(
69
+ sub_dsl, self.context, SegmentOperatorValueEnum.OS_VERSION.value
70
+ )
71
+ elif operator == SegmentOperatorValueEnum.WEB_CAMPAIGN_VARIATION.value:
72
+ return SegmentOperandEvaluator().evaluate_campaign_variation_dsl(
73
+ sub_dsl, self.context
74
+ )
75
+ else:
76
+ return False
77
+
78
+ def some(self, dsl_nodes, custom_variables: Dict[str, Any]):
79
+ ua_parser_map: Dict[str, List[str]] = {}
80
+ key_count = 0
81
+ is_ua_parser = False
82
+
83
+ for dsl in dsl_nodes:
84
+ for key in dsl:
85
+ if key in [
86
+ SegmentOperatorValueEnum.OPERATING_SYSTEM.value,
87
+ SegmentOperatorValueEnum.BROWSER_AGENT.value,
88
+ SegmentOperatorValueEnum.DEVICE_TYPE.value,
89
+ SegmentOperatorValueEnum.DEVICE.value,
90
+ ]:
91
+ is_ua_parser = True
92
+ value = dsl[key]
93
+
94
+ if key not in ua_parser_map:
95
+ ua_parser_map[key] = []
96
+
97
+ values_array = value if isinstance(value, List) else [value]
98
+ for val in values_array:
99
+ if isinstance(val, str):
100
+ ua_parser_map[key].append(val)
101
+
102
+ key_count += 1
103
+
104
+ if key == SegmentOperatorValueEnum.FEATURE_ID.value:
105
+ feature_id_object = dsl[key]
106
+ feature_id_key = list(feature_id_object.keys())[0]
107
+ feature_id_value = feature_id_object[feature_id_key]
108
+ if feature_id_value == "on" or feature_id_value == "off":
109
+ features = self.settings.get_features()
110
+ feature = next(
111
+ (f for f in features if f.get_id() == int(feature_id_key)),
112
+ None,
113
+ )
114
+
115
+ if feature:
116
+ feature_key = feature.get_key()
117
+ result = self.check_in_user_storage(
118
+ self.settings, feature_key, self.context
119
+ )
120
+ if feature_id_value == "off":
121
+ return not result
122
+ return result
123
+ else:
124
+ LogManager.get_instance().error_log("FEATURE_NOT_FOUND_WITH_ID",data={"featureId": feature_id_key}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": self.context.get_vwo_uuid(), "sId": self.context.get_session_id()})
125
+ return None
126
+
127
+ if is_ua_parser and key_count == len(dsl_nodes):
128
+ try:
129
+ ua_parser_result = self.check_user_agent_parser(ua_parser_map)
130
+ return ua_parser_result
131
+ except Exception as err:
132
+ LogManager.get_instance().error_log("USER_AGENT_VALIDATION_ERROR",data={"err": str(err)}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": self.context.get_vwo_uuid(), "sId": self.context.get_session_id()})
133
+
134
+ if self.is_segmentation_valid(dsl, custom_variables):
135
+ return True
136
+
137
+ return False
138
+
139
+ def every(self, dsl_nodes, custom_variables: Dict[str, Any]):
140
+ location_map = {}
141
+ for dsl in dsl_nodes:
142
+ if any(
143
+ key in dsl
144
+ for key in [
145
+ SegmentOperatorValueEnum.COUNTRY.value,
146
+ SegmentOperatorValueEnum.REGION.value,
147
+ SegmentOperatorValueEnum.CITY.value,
148
+ ]
149
+ ):
150
+ self.add_location_values_to_map(dsl, location_map)
151
+ if len(location_map) == len(dsl_nodes):
152
+ segment_result = self.check_location_pre_segmentation(location_map)
153
+ return segment_result
154
+ continue
155
+ res = self.is_segmentation_valid(dsl, custom_variables)
156
+ if not res:
157
+ return False
158
+ return True
159
+
160
+ def add_location_values_to_map(self, dsl, location_map: Dict[str, Any]):
161
+ if SegmentOperatorValueEnum.COUNTRY.value in dsl:
162
+ location_map[SegmentOperatorValueEnum.COUNTRY.value] = dsl[
163
+ SegmentOperatorValueEnum.COUNTRY.value
164
+ ]
165
+ if SegmentOperatorValueEnum.REGION.value in dsl:
166
+ location_map[SegmentOperatorValueEnum.REGION.value] = dsl[
167
+ SegmentOperatorValueEnum.REGION.value
168
+ ]
169
+ if SegmentOperatorValueEnum.CITY.value in dsl:
170
+ location_map[SegmentOperatorValueEnum.CITY.value] = dsl[
171
+ SegmentOperatorValueEnum.CITY.value
172
+ ]
173
+
174
+ def check_location_pre_segmentation(self, location_map: Dict[str, Any]):
175
+ if self.context.get_ip_address() is None:
176
+ LogManager.get_instance().error_log("INVALID_IP_ADDRESS_IN_CONTEXT_FOR_PRE_SEGMENTATION", debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": self.context.get_vwo_uuid(), "sId": self.context.get_session_id()})
177
+ return False
178
+ if not self.context.get_vwo() or self.context.get_vwo().get_location() is None:
179
+ return False
180
+ return self.values_match(location_map, self.context.get_vwo().get_location())
181
+
182
+ def check_user_agent_parser(self, ua_parser_map: Dict[str, List[str]]):
183
+ if not self.context.get_user_agent():
184
+ LogManager.get_instance().error_log("INVALID_USER_AGENT_IN_CONTEXT_FOR_PRE_SEGMENTATION", debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": self.context.get_vwo_uuid(), "sId": self.context.get_session_id()})
185
+ return False
186
+ if not self.context.get_vwo() or self.context.get_vwo().get_ua_info() is None:
187
+ return False
188
+ return self.check_value_present(
189
+ ua_parser_map, self.context.get_vwo().get_ua_info()
190
+ )
191
+
192
+ def check_in_user_storage(self, settings, feature_key, context):
193
+ storage_service = StorageService()
194
+ stored_data = StorageDecorator().get_feature_from_storage(
195
+ feature_key, context, storage_service
196
+ )
197
+ if stored_data and len(stored_data) > 0:
198
+ return True
199
+ else:
200
+ return False
201
+
202
+ def check_value_present(
203
+ self, expected_map: Dict[str, List[str]], actual_map: Dict[str, str]
204
+ ):
205
+ for key, actual_value in actual_map.items():
206
+ if key in expected_map:
207
+ expected_values = expected_map[key]
208
+ expected_values = [val.lower() for val in expected_values]
209
+ for val in expected_values:
210
+ if val.startswith("wildcard(") and val.endswith(")"):
211
+ wildcard_pattern = val[9:-1]
212
+ regex = re.compile(
213
+ wildcard_pattern.replace("*", ".*"), re.IGNORECASE
214
+ )
215
+ if regex.match(actual_value):
216
+ return True
217
+ if actual_value.lower() in expected_values:
218
+ return True
219
+ return False
220
+
221
+ def values_match(
222
+ self, expected_location_map: Dict[str, Any], user_location: Dict[str, str]
223
+ ):
224
+ for key, value in expected_location_map.items():
225
+ if key in user_location:
226
+ normalized_value1 = self.normalize_value(value)
227
+ normalized_value2 = self.normalize_value(user_location[key])
228
+ if normalized_value1 != normalized_value2:
229
+ return False
230
+ else:
231
+ return False
232
+ return True
233
+
234
+ def normalize_value(self, value):
235
+ if value is None:
236
+ return None
237
+ return str(value).replace('"', "").strip()