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,188 @@
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
+ import json
17
+ from typing import Any, List, Optional, Dict
18
+ import time
19
+ import random
20
+ from ..models.campaign.campaign_model import CampaignModel
21
+ from ..models.campaign.feature_model import FeatureModel
22
+ from ..models.campaign.campaign_model import CampaignModel
23
+ from ..models.campaign.holdout_model import HoldoutModel
24
+ from ..models.settings.settings_model import SettingsModel
25
+ from ..enums.campaign_type_enum import CampaignTypeEnum
26
+ import copy
27
+
28
+
29
+ def clone_object(obj: Any) -> Any:
30
+ if obj is None:
31
+ return obj
32
+ return copy.deepcopy(obj)
33
+
34
+
35
+ def get_current_unix_timestamp() -> int:
36
+ return int(time.time())
37
+
38
+
39
+ def get_current_unix_timestamp_in_millis() -> int:
40
+ return int(time.time() * 1000)
41
+
42
+
43
+ def get_random_number() -> float:
44
+ return random.random()
45
+
46
+
47
+ def get_specific_rules_based_on_type(
48
+ feature: FeatureModel, type: Optional[str] = None
49
+ ) -> List[CampaignModel]:
50
+ if not feature or not feature.get_rules_linked_campaign():
51
+ return []
52
+
53
+ if type:
54
+ return [
55
+ rule
56
+ for rule in feature.get_rules_linked_campaign()
57
+ if rule.get_type() == type
58
+ ]
59
+
60
+ return feature.get_rules_linked_campaign()
61
+
62
+
63
+ def get_all_experiment_rules(feature: FeatureModel) -> List[CampaignModel]:
64
+ if not feature:
65
+ return []
66
+
67
+ return [
68
+ rule
69
+ for rule in feature.get_rules_linked_campaign()
70
+ if rule.get_type()
71
+ in [CampaignTypeEnum.AB.value, CampaignTypeEnum.PERSONALIZE.value]
72
+ ]
73
+
74
+
75
+ def get_feature_from_key(
76
+ settings: SettingsModel, feature_key: str
77
+ ) -> Optional[FeatureModel]:
78
+ if not settings or not settings.get_features():
79
+ return None
80
+
81
+ for feature in settings.get_features():
82
+ if feature.get_key() == feature_key:
83
+ return feature
84
+
85
+ return None
86
+
87
+
88
+ def does_event_belong_to_any_feature(event_name: str, settings: SettingsModel) -> bool:
89
+ if not settings or not settings.get_features():
90
+ return False
91
+
92
+ return any(
93
+ any(metric.get_identifier() == event_name for metric in feature.get_metrics())
94
+ for feature in settings.get_features()
95
+ )
96
+
97
+
98
+ def does_event_belong_to_any_holdout(
99
+ event_name: str, settings: SettingsModel
100
+ ) -> bool:
101
+ """
102
+ Checks if an event exists within any holdout's metrics.
103
+
104
+ Args:
105
+ event_name: The name of the event to check.
106
+ settings: The settings containing holdouts.
107
+
108
+ Returns:
109
+ True if the event exists in any holdout's metrics, otherwise False.
110
+ """
111
+ if not settings:
112
+ return False
113
+
114
+ get_holdouts = getattr(settings, "get_holdouts", None)
115
+ if not callable(get_holdouts):
116
+ return False
117
+
118
+ holdouts: List[HoldoutModel] = get_holdouts() or []
119
+ if not holdouts:
120
+ return False
121
+
122
+ return any(
123
+ any(metric.get_identifier() == event_name for metric in holdout.get_metrics())
124
+ for holdout in holdouts
125
+ )
126
+
127
+
128
+ def add_linked_campaigns_to_settings(settings: SettingsModel):
129
+ """
130
+ Add linked campaigns to the settings object.
131
+
132
+ :param settings: The settings object containing campaigns and features.
133
+ """
134
+ # Create a dictionary for quick access to campaigns by ID
135
+ campaign_map = {
136
+ campaign.get_id(): campaign for campaign in settings.get_campaigns()
137
+ }
138
+
139
+ # Loop over all features
140
+ for feature in settings.get_features():
141
+ rules_linked_campaign_model = []
142
+
143
+ for rule in feature.get_rules():
144
+ original_campaign = campaign_map.get(rule.get_campaign_id())
145
+ if original_campaign is None:
146
+ continue
147
+
148
+ # Copy original campaign to a new campaign object
149
+ campaign = CampaignModel(
150
+ id=original_campaign.get_id(),
151
+ isForcedVariationEnabled=original_campaign.get_is_forced_variation_enabled(),
152
+ segments=original_campaign.get_segments(),
153
+ variations=original_campaign.get_variations(),
154
+ status=original_campaign.get_status(),
155
+ type=original_campaign.get_type(),
156
+ key=original_campaign.get_key(),
157
+ isAlwaysCheckSegment=original_campaign.get_is_always_check_segment(),
158
+ name=original_campaign.get_name(),
159
+ percentTraffic=original_campaign.get_percent_traffic(),
160
+ is_user_list_enabled=original_campaign.get_is_user_list_enabled(),
161
+ metrics=original_campaign.get_metrics(),
162
+ variables=original_campaign.get_variables(),
163
+ variation_id=original_campaign.get_variation_id(),
164
+ campaign_id=original_campaign.get_campaign_id(),
165
+ rule_key=original_campaign.get_rule_key(),
166
+ salt=original_campaign.get_salt(),
167
+ )
168
+
169
+ # Set the rule key for the campaign
170
+ campaign.set_rule_key(rule.get_rule_key())
171
+
172
+ # If a variationId is specified, find and add the variation
173
+ if rule.get_variation_id() is not None:
174
+ variation = next(
175
+ (
176
+ v
177
+ for v in campaign.get_variations()
178
+ if v.get_id() == rule.get_variation_id()
179
+ ),
180
+ None,
181
+ )
182
+ if variation is not None:
183
+ campaign.set_variations([variation])
184
+
185
+ rules_linked_campaign_model.append(campaign)
186
+
187
+ # Assign the linked campaigns to the feature
188
+ feature.set_rules_linked_campaign(rules_linked_campaign_model)
@@ -0,0 +1,179 @@
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 typing import Any, Dict
17
+ from ..packages.network_layer.manager.network_manager import NetworkManager
18
+ from ..services.settings_manager import SettingsManager
19
+ from ..packages.logger.core.log_manager import LogManager
20
+ from ..packages.network_layer.models.request_model import RequestModel
21
+ from ..services.url_service import UrlService
22
+ from urllib.parse import urlencode
23
+ import json
24
+ import re
25
+ from ..models.settings.settings_model import SettingsModel
26
+ from ..enums.campaign_type_enum import CampaignTypeEnum
27
+ from ..enums.api_enum import ApiEnum
28
+ from ..models.user.context_model import ContextModel
29
+
30
+
31
+ def get_from_gateway_service(query_params: Dict[str, Any], endpoint: str, context: ContextModel) -> Any:
32
+ """
33
+ Get the data from the gateway service.
34
+
35
+ :param query_params: The query parameters to send to the gateway service.
36
+ :param endpoint: The endpoint to send the request to.
37
+ :param context: The context to send to the gateway service.
38
+ :return: The data from the gateway service.
39
+ """
40
+ network_instance = NetworkManager.get_instance()
41
+
42
+ is_gateway_service = SettingsManager.get_instance().is_gateway_service_provided
43
+
44
+ # Check if the base URL is correctly set
45
+ if not SettingsManager.get_instance().is_gateway_service_provided:
46
+ LogManager.get_instance().error_log("INVALID_GATEWAY_URL", debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": context.get_vwo_uuid(), "sId": context.get_session_id()})
47
+ return False
48
+
49
+ try:
50
+ # Create a new request model instance with the provided parameters
51
+ request = RequestModel(
52
+ url=SettingsManager.get_instance().get_settings_hostname(),
53
+ method="GET",
54
+ path=UrlService.get_endpoint_with_collection_prefix(
55
+ endpoint=endpoint, is_gateway_service=is_gateway_service
56
+ ),
57
+ query=query_params,
58
+ scheme=SettingsManager.get_instance().protocol,
59
+ port=SettingsManager.get_instance().port,
60
+ )
61
+
62
+ # Perform the network GET request synchronously
63
+ response = network_instance.get(request)
64
+
65
+ # Return the data from the response
66
+ return response.get_data() if response else False
67
+ except Exception as e:
68
+ LogManager.get_instance().error_log("ERROR_FETCHING_DATA_FROM_GATEWAY", data={"err": str(e)}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": context.get_vwo_uuid(), "sId": context.get_session_id()})
69
+ return False
70
+
71
+ def post_to_gateway_service(query_params: Dict[str, Any], payload: Dict[str, Any], endpoint: str) -> Any:
72
+ """
73
+ Post the data to the gateway service.
74
+
75
+ :param query_params: The query parameters to send to the gateway service.
76
+ :param payload: The payload to send to the gateway service.
77
+ :param endpoint: The endpoint to send the request to.
78
+ :return: The data to the gateway service.
79
+ """
80
+ network_instance = NetworkManager.get_instance()
81
+
82
+ is_gateway_service = SettingsManager.get_instance().is_gateway_service_provided
83
+
84
+ # Check if the base URL is correctly set
85
+ if not SettingsManager.get_instance().is_gateway_service_provided:
86
+ LogManager.get_instance().error_log("INVALID_GATEWAY_URL", debug_data={"an": ApiEnum.GET_FLAG.value})
87
+ return False
88
+
89
+ try:
90
+ # Create a new request model instance with the provided parameters
91
+ request = RequestModel(
92
+ url=SettingsManager.get_instance().get_settings_hostname(),
93
+ method="POST",
94
+ path=UrlService.get_endpoint_with_collection_prefix(endpoint=endpoint, is_gateway_service=is_gateway_service),
95
+ query=query_params,
96
+ body=payload,
97
+ scheme=SettingsManager.get_instance().protocol,
98
+ port=SettingsManager.get_instance().port,
99
+ )
100
+
101
+ # Perform the network GET request synchronously
102
+ response = network_instance.post(request)
103
+
104
+ # Return the data from the response
105
+ return response.get_data() if response else False
106
+ except Exception as e:
107
+ LogManager.get_instance().error_log("ERROR_SENDING_DATA_TO_GATEWAY", data={"err": str(e)}, debug_data={"an": ApiEnum.GET_FLAG.value})
108
+ return False
109
+
110
+ def get_query_params(query_params: Dict[str, Any]) -> Dict[str, str]:
111
+ """
112
+ Get the query parameters for the gateway service.
113
+
114
+ :param query_params: The query parameters to send to the gateway service.
115
+ :return: The query parameters for the gateway service.
116
+ """
117
+ encoded_params = {
118
+ key: urlencode({key: str(value)})[len(key) + 1 :]
119
+ for key, value in query_params.items()
120
+ }
121
+ return encoded_params
122
+
123
+
124
+ def add_is_gateway_service_required_flag(settings: SettingsModel) -> None:
125
+ """
126
+ Add the is gateway service required flag to the settings.
127
+
128
+ :param settings: The settings to add the is gateway service required flag to.
129
+ """
130
+ # Regex pattern to match the specified fields
131
+ main_pattern = re.compile(
132
+ r"\b(country|region|city|os|device_type|browser_string|ua|os_version|browser_version)\b", re.IGNORECASE
133
+ )
134
+ # Regex pattern to match inlist(...) under custom_variable
135
+ custom_variable_pattern = re.compile(r"inlist\([^)]*\)", re.IGNORECASE)
136
+
137
+ for feature in settings.get_features():
138
+ rules = feature.get_rules_linked_campaign()
139
+ for rule in rules:
140
+ segments = {}
141
+ if rule.get_type() in [
142
+ CampaignTypeEnum.PERSONALIZE.value,
143
+ CampaignTypeEnum.ROLLOUT.value,
144
+ ]:
145
+ segments = rule.get_variations()[0].get_segments()
146
+ else:
147
+ segments = rule.get_segments()
148
+
149
+ if segments:
150
+ json_segments = json.dumps(segments)
151
+
152
+ # Check if the json_segments contain the specified fields
153
+ matches = main_pattern.findall(json_segments)
154
+
155
+ # Check if json_segments contain "custom_variable"
156
+ if '"custom_variable"' in json_segments:
157
+ custom_matches = custom_variable_pattern.findall(json_segments)
158
+ else:
159
+ custom_matches = []
160
+
161
+ # If there are matches in either the main or custom variable patterns, set the flag
162
+ if matches or custom_matches:
163
+ feature.set_is_gateway_service_required(True)
164
+ break
165
+
166
+ for holdout in settings.get_holdouts():
167
+ segments = holdout.get_segments()
168
+ if segments:
169
+ json_segments = json.dumps(segments)
170
+ matches = main_pattern.findall(json_segments)
171
+
172
+ if '"custom_variable"' in json_segments:
173
+ custom_matches = custom_variable_pattern.findall(json_segments)
174
+ else:
175
+ custom_matches = []
176
+
177
+ if matches or custom_matches:
178
+ holdout.set_is_gateway_service_required(True)
179
+ break
@@ -0,0 +1,264 @@
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
+ from typing import Any, Dict, List, Optional, Tuple
16
+
17
+ from ..models.settings.settings_model import SettingsModel
18
+ from ..models.campaign.holdout_model import HoldoutModel
19
+ from ..models.campaign.feature_model import FeatureModel
20
+ from ..models.user.context_model import ContextModel
21
+ from ..packages.decision_maker.decision_maker import DecisionMaker
22
+ from ..packages.logger.core.log_manager import LogManager
23
+ from ..utils.log_message_util import debug_messages, info_messages
24
+ from ..utils.network_util import create_holdout_payload
25
+ from ..enums.event_enum import EventEnum
26
+ from ..constants.Constants import Constants
27
+ from ..services.storage_service import StorageService
28
+ from ..decorators.storage_decorator import StorageDecorator
29
+ from ..utils.impression_util import (
30
+ send_impression_for_variation_shown,
31
+ send_impression_for_variation_shown_batch,
32
+ )
33
+ from ..services.settings_manager import SettingsManager
34
+ from ..packages.segmentation_evaluator.core.segmentation_manager import (
35
+ SegmentationManager,
36
+ )
37
+
38
+
39
+ def get_applicable_holdouts(settings: SettingsModel, feature_id: int) -> List[HoldoutModel]:
40
+ """
41
+ Gets the applicable holdouts for a given feature ID.
42
+
43
+ Args:
44
+ settings: The settings object.
45
+ feature_id: The feature ID.
46
+
47
+ Returns:
48
+ The applicable holdouts.
49
+ """
50
+ # Fallback to empty list if holdouts are not present or accessor not yet implemented
51
+ holdouts: List[HoldoutModel] = []
52
+ get_holdouts = getattr(settings, "get_holdouts", None)
53
+ if callable(get_holdouts):
54
+ holdouts = get_holdouts() or []
55
+
56
+ # Filter the holdouts to only include global holdouts and holdouts that have the given feature ID
57
+ return [
58
+ holdout
59
+ for holdout in holdouts
60
+ if holdout.get_is_global() or feature_id in holdout.get_feature_ids()
61
+ ]
62
+
63
+
64
+ def get_matched_holdouts(
65
+ settings: SettingsModel,
66
+ feature: FeatureModel,
67
+ context: ContextModel,
68
+ stored_data: Optional[Dict[str, Any]] = None,
69
+ ) -> Optional[Dict[str, Any]]:
70
+ """
71
+ Gets the matched holdout(s) for a given feature ID and context.
72
+ Evaluates all applicable holdouts, creates batched impressions for all of them,
73
+ and returns all matched holdouts (i.e. holdouts the user is part of).
74
+
75
+ Args:
76
+ settings: The settings object.
77
+ feature: The feature object.
78
+ context: The context object.
79
+ stored_data: Previously stored holdout data.
80
+
81
+ Returns:
82
+ A dict with matchedHoldouts, notMatchedHoldouts and holdoutPayloads, or None.
83
+ """
84
+ stored_data = stored_data or {}
85
+
86
+ # stored_data has isInHoldoutId and notInHoldoutId, we need to use these to check if the holdout is already evaluated
87
+ is_in_holdout_ids: List[int] = stored_data.get("isInHoldoutId") or []
88
+ not_in_holdout_ids: List[int] = stored_data.get("notInHoldoutId") or []
89
+ already_evaluated_holdout_ids = set(is_in_holdout_ids + not_in_holdout_ids)
90
+
91
+ feature_id = feature.get_id()
92
+ applicable_holdouts = get_applicable_holdouts(settings, feature_id)
93
+
94
+ not_matched_holdouts: List[HoldoutModel] = []
95
+
96
+ if not applicable_holdouts:
97
+ return {"matchedHoldouts": [], "notMatchedHoldouts": [], "holdoutPayloads": []}
98
+
99
+ matched_holdouts: List[HoldoutModel] = []
100
+ holdout_payloads: List[Dict[str, Any]] = []
101
+
102
+ log_manager = LogManager.get_instance()
103
+ segmentation_manager = SegmentationManager.get_instance()
104
+
105
+ for holdout in applicable_holdouts:
106
+ if holdout.get_id() in already_evaluated_holdout_ids:
107
+ log_manager.debug(
108
+ debug_messages.get("HOLDOUT_SKIP_EVALUATION").format(
109
+ holdoutId=holdout.get_id(),
110
+ reason=f"user {context.get_id()} was already evaluated for feature with id: {feature_id}; SKIP decision making altogether.",
111
+ )
112
+ )
113
+ continue
114
+
115
+ segments = holdout.get_segments()
116
+ segment_pass = True
117
+
118
+ if segments and len(segments.keys()) > 0:
119
+ segment_pass = segmentation_manager.validate_segmentation(
120
+ segments, context.get_custom_variables()
121
+ )
122
+ else:
123
+ log_manager.info(
124
+ info_messages.get("HOLDOUT_SEGMENTATION_SKIP").format(
125
+ holdoutId=holdout.get_id(), userId=context.get_id()
126
+ )
127
+ )
128
+
129
+ variation_id: int
130
+ is_in_holdout = False
131
+
132
+ if not segment_pass:
133
+ log_manager.info(
134
+ debug_messages.get("HOLDOUT_SEGMENTATION_FAIL").format(
135
+ userId=context.get_id(), holdoutGroupName=holdout.get_name()
136
+ )
137
+ )
138
+ variation_id = Constants.VARIATION_NOT_PART_OF_HOLDOUT
139
+ not_matched_holdouts.append(holdout)
140
+ else:
141
+ hash_key = f"{settings.get_account_id()}_{holdout.get_id()}_{context.get_id()}"
142
+ bucket = DecisionMaker().get_bucket_value_for_user(hash_key, 100)
143
+
144
+ is_in_holdout = bucket != 0 and bucket <= holdout.get_percent_traffic()
145
+ variation_id = (
146
+ Constants.VARIATION_IS_PART_OF_HOLDOUT
147
+ if is_in_holdout
148
+ else Constants.VARIATION_NOT_PART_OF_HOLDOUT
149
+ )
150
+
151
+ if is_in_holdout:
152
+ log_manager.info(
153
+ info_messages.get("HOLDOUT_SHOULD_EXCLUDE_USER").format(
154
+ userId=context.get_id(),
155
+ bucketValue=bucket,
156
+ holdoutGroupName=holdout.get_name(),
157
+ percentTraffic=holdout.get_percent_traffic(),
158
+ featureKey=feature.get_key(),
159
+ )
160
+ )
161
+ matched_holdouts.append(holdout)
162
+ else:
163
+ log_manager.debug(
164
+ debug_messages.get("HOLDOUT_SHOULD_NOT_EXCLUDE_USER").format(
165
+ userId=context.get_id(),
166
+ holdoutGroupName=holdout.get_name(),
167
+ featureKey=feature.get_key(),
168
+ )
169
+ )
170
+ not_matched_holdouts.append(holdout)
171
+
172
+ payload = create_holdout_payload(
173
+ settings=settings,
174
+ event_name=EventEnum.VARIATION_SHOWN.value,
175
+ holdout_id=holdout.get_id(),
176
+ variation_id=variation_id,
177
+ context=context,
178
+ feature_id=feature_id,
179
+ )
180
+ holdout_payloads.append(payload)
181
+
182
+ return {
183
+ "matchedHoldouts": matched_holdouts,
184
+ "notMatchedHoldouts": not_matched_holdouts,
185
+ "holdoutPayloads": holdout_payloads,
186
+ }
187
+
188
+
189
+ def send_network_calls_for_not_in_holdouts(
190
+ settings: SettingsModel,
191
+ feature: FeatureModel,
192
+ context: ContextModel,
193
+ decision: Dict[str, Any],
194
+ stored_data: Optional[Dict[str, Any]],
195
+ storage_service: StorageService,
196
+ ) -> List[Any]:
197
+ """
198
+ Sends network calls for not-in holdouts that are applicable but not stored in storage.
199
+
200
+ Args:
201
+ settings: The settings object.
202
+ feature: The feature model.
203
+ context: The context model.
204
+ decision: The decision object (mutated to indicate if holdouts are present).
205
+ stored_data: The stored data.
206
+ storage_service: The storage service.
207
+
208
+ Returns:
209
+ Updated list of not-in holdout IDs.
210
+ """
211
+ stored_data = stored_data or {}
212
+
213
+ applicable_holdouts = get_applicable_holdouts(settings, feature.get_id())
214
+ updated_not_in_holdout_ids: List[Any] = list(stored_data.get("notInHoldoutId") or [])
215
+ is_in_holdout_ids: List[Any] = list(stored_data.get("isInHoldoutId") or [])
216
+ batch_payload: List[Dict[str, Any]] = []
217
+ initial_not_in_holdout_count = len(updated_not_in_holdout_ids)
218
+
219
+ if applicable_holdouts:
220
+ decision["isHoldoutPresent"] = True
221
+
222
+ for holdout in applicable_holdouts:
223
+ if holdout.get_id() not in updated_not_in_holdout_ids and holdout.get_id() not in is_in_holdout_ids:
224
+ updated_not_in_holdout_ids.append(holdout.get_id())
225
+
226
+ payload = create_holdout_payload(
227
+ settings=settings,
228
+ event_name=EventEnum.VARIATION_SHOWN.value,
229
+ holdout_id=holdout.get_id(),
230
+ variation_id=Constants.VARIATION_NOT_PART_OF_HOLDOUT,
231
+ context=context,
232
+ feature_id=feature.get_id(),
233
+ )
234
+
235
+ if (
236
+ SettingsManager.get_instance().is_gateway_service_provided
237
+ and payload is not None
238
+ ):
239
+ send_impression_for_variation_shown(payload, context)
240
+ else:
241
+ if payload is not None:
242
+ batch_payload.append(payload)
243
+
244
+ if len(updated_not_in_holdout_ids) > initial_not_in_holdout_count:
245
+ StorageDecorator().set_data_in_storage(
246
+ {
247
+ "featureKey": feature.get_key(),
248
+ "context": context,
249
+ "notInHoldoutId": updated_not_in_holdout_ids,
250
+ },
251
+ storage_service,
252
+ )
253
+
254
+ if batch_payload:
255
+ if SettingsManager.get_instance().is_gateway_service_provided:
256
+ for payload in batch_payload:
257
+ send_impression_for_variation_shown(payload, context)
258
+ else:
259
+ send_impression_for_variation_shown_batch(
260
+ batch_payload, settings.get_account_id(), settings.get_sdk_key()
261
+ )
262
+
263
+ return updated_not_in_holdout_ids
264
+