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,589 @@
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 ..enums.status_enum import StatusEnum
18
+ from ..enums.campaign_type_enum import CampaignTypeEnum
19
+ from ..models.settings.settings_model import SettingsModel
20
+ from ..models.campaign.campaign_model import CampaignModel
21
+ from ..models.campaign.feature_model import FeatureModel
22
+ from ..models.user.context_model import ContextModel
23
+ from ..models.vwo_options_model import VWOOptionsModel
24
+ from ..packages.logger.core.log_manager import LogManager
25
+ from ..services.campaign_decision_service import CampaignDecisionService
26
+ from ..utils.log_message_util import info_messages
27
+ from ..utils.uuid_util import get_uuid
28
+ from ..utils.campaign_util import (
29
+ get_group_details_if_campaign_part_of_it,
30
+ scale_variation_weights,
31
+ assign_range_values,
32
+ get_bucketing_seed,
33
+ get_bucketing_id_for_user,
34
+ )
35
+ from ..utils.data_type_util import is_object
36
+ from ..utils.function_util import clone_object
37
+ from ..packages.segmentation_evaluator.core.segmentation_manager import (
38
+ SegmentationManager,
39
+ )
40
+ from ..packages.decision_maker.decision_maker import DecisionMaker
41
+ from ..services.storage_service import StorageService
42
+ from ..decorators.storage_decorator import StorageDecorator
43
+ from ..constants.Constants import Constants
44
+
45
+
46
+ def check_whitelisting_and_pre_seg(
47
+ settings: SettingsModel,
48
+ feature: FeatureModel,
49
+ campaign: CampaignModel,
50
+ context: ContextModel,
51
+ evaluated_feature_map: Dict[str, Any],
52
+ meg_group_winner_campaigns: Dict,
53
+ storage_service: StorageService,
54
+ decision: Any,
55
+ ):
56
+ """
57
+ Check whitelisting and pre-segmentation.
58
+
59
+ :param settings: SettingsModel object containing configuration.
60
+ :param feature: FeatureModel object representing the feature.
61
+ :param campaign: CampaignModel object representing the campaign.
62
+ :param context: ContextModel object containing user context.
63
+ :param evaluated_feature_map: Map of evaluated features.
64
+ :param meg_group_winner_campaigns: Map of winner campaigns for mutually exclusive groups.
65
+ :param storage_service: StorageService object for storage operations.
66
+ :param decision: Dictionary to store decision details.
67
+ :return: Tuple (boolean indicating success, any result data).
68
+ """
69
+ vwo_user_id = get_uuid(context.get_id(), settings.get_account_id())
70
+ campaign_id = campaign.get_id()
71
+ if _is_force_whitelisting_eligible(campaign):
72
+ context.set_variation_targeting_variables(
73
+ {
74
+ **context.get_variation_targeting_variables(),
75
+ "_vwoUserId": _force_match_user_id(
76
+ campaign, context.get_id(), vwo_user_id
77
+ ),
78
+ }
79
+ )
80
+ decision["variation_targeting_variables"] = (
81
+ context.get_variation_targeting_variables()
82
+ )
83
+ if campaign.get_is_forced_variation_enabled():
84
+ if _is_rollout_campaign(campaign) and _is_user_on_rollout_force_off_list(
85
+ campaign, context
86
+ ):
87
+ LogManager.get_instance().info(
88
+ info_messages.get("WHITELISTING_FORCED_OFF").format(
89
+ userId=context.get_id(),
90
+ ruleType=_force_rule_type_label(campaign),
91
+ campaignKey=_force_campaign_key(campaign),
92
+ )
93
+ )
94
+ return False, None
95
+
96
+ whitelisted_variation = _check_campaign_whitelisting(campaign, context)
97
+ if whitelisted_variation and whitelisted_variation:
98
+ return True, whitelisted_variation
99
+ else:
100
+ LogManager.get_instance().info(
101
+ info_messages.get("WHITELISTING_SKIP").format(
102
+ ruleType=_force_rule_type_label(campaign),
103
+ campaignKey=_force_campaign_key(campaign),
104
+ userId=context.get_id(),
105
+ variation="",
106
+ )
107
+ )
108
+ # Force-list matching uses _force_match_user_id only on variation targeting variables above.
109
+ context.set_custom_variables(
110
+ {
111
+ **context.get_custom_variables(),
112
+ "_vwoUserId": (
113
+ vwo_user_id
114
+ if campaign.get_is_user_list_enabled()
115
+ else context.get_id()
116
+ ),
117
+ }
118
+ )
119
+
120
+ decision["custom_variables"] = context.get_custom_variables()
121
+ group_details = get_group_details_if_campaign_part_of_it(
122
+ settings,
123
+ str(campaign_id),
124
+ (
125
+ campaign.get_variations()[0].get_id()
126
+ if campaign.get_type() == CampaignTypeEnum.PERSONALIZE.value
127
+ else None
128
+ ),
129
+ )
130
+ group_id = group_details.get("groupId")
131
+ group_winner_campaign_id = meg_group_winner_campaigns.get(group_id)
132
+
133
+ if group_winner_campaign_id:
134
+ if campaign.get_type() == CampaignTypeEnum.AB.value:
135
+ # check if the campaign is the winner of the group
136
+ if group_winner_campaign_id == campaign_id:
137
+ return True, None
138
+ elif campaign.get_type() == CampaignTypeEnum.PERSONALIZE.value:
139
+ # check if the campaign is the winner of the group
140
+ if group_winner_campaign_id == str(campaign_id) + "_" + str(
141
+ campaign.get_variations()[0].get_id()
142
+ ):
143
+ return True, None
144
+ # as group is already evaluated, no need to check again, return false directly
145
+ return False, None
146
+ elif group_id:
147
+ # check in storage if the group is already evaluated for the user
148
+ stored_data = StorageDecorator().get_feature_from_storage(
149
+ Constants.VWO_META_MEG_KEY + group_id, context, storage_service
150
+ )
151
+ if (
152
+ stored_data
153
+ and stored_data.get("experimentKey")
154
+ and stored_data.get("experimentId")
155
+ ):
156
+ LogManager.get_instance().info(
157
+ info_messages.get("MEG_CAMPAIGN_FOUND_IN_STORAGE").format(
158
+ campaignKey=stored_data.get("experimentKey"),
159
+ userId=context.get_id(),
160
+ )
161
+ )
162
+ if stored_data.get("experimentId") == campaign_id:
163
+ # return the campaign if the called campaignId matches
164
+ if campaign.get_type() == CampaignTypeEnum.PERSONALIZE.value:
165
+ if (
166
+ stored_data.get("experimentVariationId")
167
+ == campaign.get_variations()[0].get_id()
168
+ ):
169
+ # if personalise then check if the reqeusted variation is the winner
170
+ return True, None
171
+ else:
172
+ # if requested variation is not the winner then set the winner campaign in the map and return
173
+ meg_group_winner_campaigns[group_id] = (
174
+ str(stored_data.get("experimentId"))
175
+ + "_"
176
+ + str(campaign.get_variations()[0].get_id())
177
+ )
178
+ return False, None
179
+ else:
180
+ return True, None
181
+ if stored_data.get("experimentVariationId") != -1:
182
+ meg_group_winner_campaigns[group_id] = (
183
+ str(stored_data.get("experimentId"))
184
+ + "_"
185
+ + str(stored_data.get("experimentVariationId"))
186
+ )
187
+ else:
188
+ meg_group_winner_campaigns[group_id] = stored_data.get("experimentId")
189
+ return False, None
190
+
191
+ is_pre_segmentation_passed = (
192
+ CampaignDecisionService().get_pre_segmentation_decision(campaign, context)
193
+ )
194
+
195
+ from ..utils.meg_util import evaluate_groups
196
+
197
+ if is_pre_segmentation_passed and group_id:
198
+ winner_campaign = evaluate_groups(
199
+ settings, feature, group_id, evaluated_feature_map, context, storage_service
200
+ )
201
+ if winner_campaign and winner_campaign.get_id() == campaign_id:
202
+ if winner_campaign.get_type() == CampaignTypeEnum.AB.value:
203
+ return True, None
204
+ else:
205
+ # if personalise then check if the reqeusted variation is the winner
206
+ if (
207
+ winner_campaign.get_variations()[0].get_id()
208
+ == campaign.get_variations()[0].get_id()
209
+ ):
210
+ return True, None
211
+ else:
212
+ meg_group_winner_campaigns[group_id] = (
213
+ str(winner_campaign.get_id())
214
+ + "_"
215
+ + str(winner_campaign.get_variations()[0].get_id())
216
+ )
217
+ return False, None
218
+ elif winner_campaign:
219
+ if winner_campaign.get_type() == CampaignTypeEnum.AB.value:
220
+ meg_group_winner_campaigns[group_id] = winner_campaign.get_id()
221
+ else:
222
+ meg_group_winner_campaigns[group_id] = (
223
+ str(winner_campaign.get_id())
224
+ + "_"
225
+ + str(winner_campaign.get_variations()[0].get_id())
226
+ )
227
+ return False, None
228
+ meg_group_winner_campaigns[group_id] = -1
229
+ return False, None
230
+
231
+ return is_pre_segmentation_passed, None
232
+
233
+
234
+ def evaluate_traffic_and_get_variation(
235
+ settings: SettingsModel, campaign: CampaignModel, context: ContextModel
236
+ ):
237
+ """
238
+ Evaluate the traffic and get the variation for the user.
239
+
240
+ :param settings: SettingsModel object containing configuration.
241
+ :param campaign: CampaignModel object representing the campaign.
242
+ :param context: ContextModel object containing user context.
243
+ :return: VariationModel object if a variation is allocated, None otherwise.
244
+ """
245
+ user_id = context.get_id()
246
+ bucketing_id = get_bucketing_id_for_user(context)
247
+
248
+ variation = CampaignDecisionService().get_variation_alloted(
249
+ context, settings.get_account_id(), campaign
250
+ )
251
+
252
+ if not variation:
253
+ LogManager.get_instance().info(
254
+ info_messages.get("USER_CAMPAIGN_BUCKET_INFO").format(
255
+ campaignKey=(
256
+ campaign.get_rule_key()
257
+ if campaign.get_type() == CampaignTypeEnum.AB.value
258
+ else campaign.get_name() + "_" + campaign.get_rule_key()
259
+ ),
260
+ userId=f"{user_id} (Seed: {bucketing_id})" if (bucketing_id != user_id) else user_id,
261
+ status="did not get any variation",
262
+ )
263
+ )
264
+ return None
265
+
266
+ LogManager.get_instance().info(
267
+ info_messages.get("USER_CAMPAIGN_BUCKET_INFO").format(
268
+ campaignKey=(
269
+ campaign.get_rule_key()
270
+ if campaign.get_type() == CampaignTypeEnum.AB.value
271
+ else campaign.get_name() + "_" + campaign.get_rule_key()
272
+ ),
273
+ userId=f"{user_id} (Seed: {bucketing_id})" if (bucketing_id != user_id) else user_id,
274
+ status=f"got variation: {variation.get_name()}",
275
+ )
276
+ )
277
+
278
+ return variation
279
+
280
+
281
+ def _check_campaign_whitelisting(campaign: CampaignModel, context: ContextModel):
282
+ """
283
+ Check for whitelisting in the campaign.
284
+
285
+ For Rollout/Personalize campaigns, evaluates whitelistedSegments on the first variation.
286
+ For AB campaigns, evaluates variation-level segments as before.
287
+
288
+ :param campaign: CampaignModel object.
289
+ :param context: ContextModel object.
290
+ :return: Whitelisting result.
291
+ """
292
+ if campaign.get_type() in [
293
+ CampaignTypeEnum.ROLLOUT.value,
294
+ CampaignTypeEnum.PERSONALIZE.value,
295
+ ]:
296
+ whitelisting_result = _evaluate_variation_whitelisted_segments(
297
+ campaign, context
298
+ )
299
+ else:
300
+ whitelisting_result = _evaluate_whitelisting(campaign, context)
301
+
302
+ status = StatusEnum.PASSED.value if whitelisting_result else StatusEnum.FAILED.value
303
+ variation_string = (
304
+ whitelisting_result["variation"].get_name() if whitelisting_result else ""
305
+ )
306
+
307
+ LogManager.get_instance().info(
308
+ info_messages.get("WHITELISTING_STATUS").format(
309
+ userId=context.get_id(),
310
+ ruleType=_force_rule_type_label(campaign),
311
+ campaignKey=_force_campaign_key(campaign),
312
+ status=status,
313
+ variationString=variation_string,
314
+ )
315
+ )
316
+
317
+ return whitelisting_result
318
+
319
+
320
+ def _evaluate_whitelisting(campaign: CampaignModel, context: ContextModel):
321
+ """
322
+ Evaluate whitelisting for the campaign.
323
+
324
+ :param campaign: CampaignModel object.
325
+ :param context: ContextModel object.
326
+ :return: Whitelisted variation result.
327
+ """
328
+ targeted_variations = []
329
+
330
+ for variation in campaign.get_variations():
331
+ if is_object(variation.get_segments()) and not variation.get_segments():
332
+ LogManager.get_instance().info(
333
+ info_messages.get("WHITELISTING_SKIP").format(
334
+ ruleType=_force_rule_type_label(campaign),
335
+ campaignKey=_force_campaign_key(campaign),
336
+ userId=context.get_id(),
337
+ variation=(
338
+ f"for variation: {variation.get_name()}"
339
+ if variation.get_name()
340
+ else ""
341
+ ),
342
+ )
343
+ )
344
+ continue
345
+
346
+ if is_object(variation.get_segments()):
347
+ segment_evaluator_result = (
348
+ SegmentationManager.get_instance().validate_segmentation(
349
+ variation.get_segments(),
350
+ context.get_variation_targeting_variables(),
351
+ )
352
+ )
353
+
354
+ if segment_evaluator_result:
355
+ targeted_variations.append(clone_object(variation))
356
+
357
+ if len(targeted_variations) > 1:
358
+ # Resolve bucketing ID for whitelisting
359
+ bucketing_id = get_bucketing_id_for_user(context)
360
+
361
+ scale_variation_weights(targeted_variations)
362
+ current_allocation = 0
363
+ for i, variation in enumerate(targeted_variations):
364
+ step_factor = assign_range_values(variation, current_allocation)
365
+ current_allocation += step_factor
366
+
367
+ whitelisted_variation = CampaignDecisionService().get_variation(
368
+ targeted_variations,
369
+ DecisionMaker().calculate_bucket_value(
370
+ get_bucketing_seed(bucketing_id, campaign, None)
371
+ ),
372
+ )
373
+ else:
374
+ whitelisted_variation = targeted_variations[0] if targeted_variations else None
375
+
376
+ if whitelisted_variation:
377
+ return _whitelisting_result_map(whitelisted_variation)
378
+ return None
379
+
380
+
381
+ def _is_force_whitelisting_eligible(campaign: CampaignModel) -> bool:
382
+ """
383
+ Checks if the campaign type supports force/whitelisting.
384
+
385
+ :param campaign: CampaignModel object.
386
+ :return: True if the campaign type supports force whitelisting.
387
+ """
388
+ return campaign.get_type() in [
389
+ CampaignTypeEnum.AB.value,
390
+ CampaignTypeEnum.ROLLOUT.value,
391
+ CampaignTypeEnum.PERSONALIZE.value,
392
+ ]
393
+
394
+
395
+ def _force_match_user_id(campaign: CampaignModel, user_id: str, hashed_user_id: str) -> str:
396
+ """
397
+ Determines the user ID to use for force list matching based on campaign type.
398
+
399
+ For AB campaigns, uses the hashed UUID only when isUserListEnabled is True.
400
+ For Rollout/Personalize campaigns, always uses the hashed UUID.
401
+
402
+ :param campaign: CampaignModel object.
403
+ :param user_id: The raw user ID.
404
+ :param hashed_user_id: The hashed (UUID) user ID.
405
+ :return: The user ID to use for matching.
406
+ """
407
+ if campaign.get_type() == CampaignTypeEnum.AB.value:
408
+ return hashed_user_id if campaign.get_is_user_list_enabled() else user_id
409
+ return hashed_user_id
410
+
411
+
412
+ def _is_rollout_campaign(campaign: CampaignModel) -> bool:
413
+ """
414
+ Helper to identify if a campaign is a Rollout type.
415
+
416
+ :param campaign: CampaignModel object.
417
+ :return: True if campaign is a Rollout type.
418
+ """
419
+ return campaign.get_type() == CampaignTypeEnum.ROLLOUT.value
420
+
421
+
422
+ def _force_rule_type_label(campaign: CampaignModel) -> str:
423
+ """
424
+ Returns a human-readable label for the rule type.
425
+
426
+ :param campaign: CampaignModel object.
427
+ :return: Rule type label string.
428
+ """
429
+ type_map = {
430
+ CampaignTypeEnum.ROLLOUT.value: "rollout",
431
+ CampaignTypeEnum.PERSONALIZE.value: "personalize",
432
+ CampaignTypeEnum.AB.value: "experiment",
433
+ }
434
+ return type_map.get(campaign.get_type(), "experiment")
435
+
436
+
437
+ def _force_campaign_key(campaign: CampaignModel) -> str:
438
+ """
439
+ Returns the campaign key for log messages.
440
+
441
+ :param campaign: CampaignModel object.
442
+ :return: Campaign key string.
443
+ """
444
+ if campaign.get_type() == CampaignTypeEnum.AB.value:
445
+ return campaign.get_rule_key()
446
+ return campaign.get_name() + "_" + campaign.get_rule_key()
447
+
448
+
449
+ def _is_user_on_rollout_force_off_list(
450
+ campaign: CampaignModel, context: ContextModel
451
+ ) -> bool:
452
+ """
453
+ Checks if a user is on the Forced OUT list for a Rollout campaign.
454
+
455
+ Extracts 'not' operands from the whitelistedSegments DSL tree,
456
+ evaluates their content against the user, and returns True if matched.
457
+
458
+ :param campaign: CampaignModel object (Rollout type).
459
+ :param context: ContextModel object.
460
+ :return: True if the user is force-off.
461
+ """
462
+ variations = campaign.get_variations()
463
+ if not variations:
464
+ return False
465
+
466
+ whitelisted_segments = variations[0].get_whitelisted_segments()
467
+ if not whitelisted_segments or not isinstance(whitelisted_segments, dict):
468
+ return False
469
+
470
+ not_operands = []
471
+ _collect_rollout_force_off_not_operands(whitelisted_segments, not_operands)
472
+
473
+ for operand in not_operands:
474
+ result = SegmentationManager.get_instance().validate_segmentation(
475
+ operand, context.get_variation_targeting_variables()
476
+ )
477
+ if result:
478
+ return True
479
+ return False
480
+
481
+
482
+ def _collect_rollout_force_off_not_operands(node, results):
483
+ """
484
+ Recursively collects 'not' operands from the DSL tree for Rollout force-off lists.
485
+
486
+ :param node: Current DSL node to process.
487
+ :param results: List to collect the content of 'not' operands.
488
+ """
489
+ if not isinstance(node, dict):
490
+ return
491
+
492
+ if "not" in node:
493
+ results.append(node["not"])
494
+
495
+ if "or" in node:
496
+ for child in node["or"]:
497
+ _collect_rollout_force_off_not_operands(child, results)
498
+
499
+ if "and" in node:
500
+ for child in node["and"]:
501
+ _collect_rollout_force_off_not_operands(child, results)
502
+
503
+
504
+ def _force_on_segments_only(node):
505
+ """
506
+ Drop Forced OUT (``not``) nodes so a force-off-only list is not treated as Force On.
507
+
508
+ Personalize has no Force Off. A ``not`` there is ignored rather than inverted.
509
+ Returns None when nothing but Forced OUT remains.
510
+
511
+ :param node: Current DSL node (dict, list, or leaf).
512
+ :return: DSL with ``not`` nodes removed, or None when empty.
513
+ """
514
+ if isinstance(node, list):
515
+ kept = []
516
+ for item in node:
517
+ stripped = _force_on_segments_only(item)
518
+ if stripped is not None:
519
+ kept.append(stripped)
520
+ return kept or None
521
+
522
+ if not isinstance(node, dict):
523
+ return node
524
+
525
+ result = {}
526
+ for key, value in node.items():
527
+ if key == "not":
528
+ continue
529
+ stripped = _force_on_segments_only(value)
530
+ if stripped is not None:
531
+ result[key] = stripped
532
+ return result or None
533
+
534
+
535
+ def _evaluate_variation_whitelisted_segments(
536
+ campaign: CampaignModel, context: ContextModel
537
+ ):
538
+ """
539
+ Evaluates whitelistedSegments for Rollout/Personalize campaigns.
540
+
541
+ Uses the whitelistedSegments from the first variation to determine
542
+ if the user should be force-on. Forced OUT (``not``) clauses are removed
543
+ first so they cannot pass every user who is not on that list.
544
+
545
+ :param campaign: CampaignModel object.
546
+ :param context: ContextModel object.
547
+ :return: Whitelisting result dict or None.
548
+ """
549
+ variations = campaign.get_variations()
550
+ if not variations:
551
+ return None
552
+
553
+ whitelisted_segments = variations[0].get_whitelisted_segments()
554
+ if not whitelisted_segments or not isinstance(whitelisted_segments, dict):
555
+ LogManager.get_instance().info(
556
+ info_messages.get("WHITELISTING_SKIP").format(
557
+ userId=context.get_id(),
558
+ ruleType=_force_rule_type_label(campaign),
559
+ campaignKey=_force_campaign_key(campaign),
560
+ variation="",
561
+ )
562
+ )
563
+ return None
564
+
565
+ force_on_segments = _force_on_segments_only(whitelisted_segments)
566
+ if not isinstance(force_on_segments, dict) or not force_on_segments:
567
+ return None
568
+
569
+ result = SegmentationManager.get_instance().validate_segmentation(
570
+ force_on_segments, context.get_variation_targeting_variables()
571
+ )
572
+
573
+ if result:
574
+ return _whitelisting_result_map(variations[0])
575
+ return None
576
+
577
+
578
+ def _whitelisting_result_map(whitelisted_variation):
579
+ """
580
+ Builds a standard whitelisting result map.
581
+
582
+ :param whitelisted_variation: The whitelisted variation.
583
+ :return: Dictionary with variation, variationName, and variationId.
584
+ """
585
+ return {
586
+ "variation": whitelisted_variation,
587
+ "variationName": whitelisted_variation.get_name(),
588
+ "variationId": whitelisted_variation.get_id(),
589
+ }
@@ -0,0 +1,85 @@
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, Optional
16
+ from .network_util import get_events_base_properties, get_sdk_init_event_payload, get_sdk_usage_stats_event_payload, send_event
17
+ from ..enums.event_enum import EventEnum
18
+ from ..wingify_client import WingifyClient as VWOClient
19
+ from ..packages.logger.core.log_manager import LogManager
20
+ from ..enums.api_enum import ApiEnum
21
+
22
+ def send_sdk_init_event() -> None:
23
+ """
24
+ Sends an init called event to VWO.
25
+ This event is triggered when the init function is called.
26
+ """
27
+ # Create the query parameters
28
+ properties = get_events_base_properties(EventEnum.SDK_INIT_EVENT.value)
29
+
30
+ # Create the payload with required fields
31
+ payload = get_sdk_init_event_payload(EventEnum.SDK_INIT_EVENT.value)
32
+
33
+ # Send the constructed payload via POST request
34
+ try:
35
+ vwo_instance = VWOClient.get_instance()
36
+
37
+ # Check if batch events are enabled
38
+ if vwo_instance.batch_event_queue is not None:
39
+ # Enqueue the event to the batch queue
40
+ vwo_instance.batch_event_queue.enqueue(payload)
41
+ else:
42
+ # Send the event immediately if batch events are not enabled
43
+ send_event(properties, payload, EventEnum.SDK_INIT_EVENT.value)
44
+ except Exception as e:
45
+ LogManager.get_instance().error_log("SDK_INIT_EVENT_FAILED", data={"err": str(e)}, debug_data={"an": ApiEnum.INIT.value})
46
+ pass
47
+
48
+
49
+ def send_sdk_usage_stats_event(
50
+ usage_stats_account_id: int,
51
+ settings_fetch_time: Optional[int] = None,
52
+ sdk_init_time: Optional[int] = None,
53
+ init_config: Optional[Dict[str, Any]] = None,
54
+ ) -> None:
55
+ """
56
+ Sends a usage stats event to VWO.
57
+ This event is triggered when the SDK is initialized.
58
+
59
+ :param usage_stats_account_id: Account ID for usage stats event
60
+ :param settings_fetch_time: Time taken to fetch settings in milliseconds
61
+ :param sdk_init_time: Time taken to initialize the SDK in milliseconds
62
+ :param init_config: SDK initialization options
63
+ """
64
+ # Create the query parameters
65
+ properties = get_events_base_properties(EventEnum.USAGE_STATS.value, "", "", True, usage_stats_account_id)
66
+
67
+ # Create the payload with required fields
68
+ payload = get_sdk_usage_stats_event_payload(
69
+ EventEnum.USAGE_STATS.value,
70
+ usage_stats_account_id,
71
+ settings_fetch_time,
72
+ sdk_init_time,
73
+ init_config,
74
+ )
75
+
76
+ vwo_instance = VWOClient.get_instance()
77
+
78
+ # Check if batch events are enabled
79
+ if vwo_instance.batch_event_queue is not None:
80
+ # Enqueue the event to the batch queue
81
+ vwo_instance.batch_event_queue.enqueue(payload)
82
+ else:
83
+ # Send the event immediately if batch events are not enabled
84
+ send_event(properties, payload, EventEnum.USAGE_STATS.value)
85
+