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,561 @@
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, List, Tuple, Optional
17
+ from ..enums.campaign_type_enum import CampaignTypeEnum
18
+ from ..models.settings.settings_model import SettingsModel
19
+ from ..models.campaign.campaign_model import CampaignModel
20
+ from ..models.campaign.feature_model import FeatureModel
21
+ from ..models.campaign.variation_model import VariationModel
22
+ from ..models.user.context_model import ContextModel
23
+ from ..packages.logger.core.log_manager import LogManager
24
+ from ..services.campaign_decision_service import CampaignDecisionService
25
+ from ..utils.log_message_util import info_messages, debug_messages
26
+ from ..models.vwo_options_model import VWOOptionsModel
27
+ from ..utils.log_message_util import info_messages
28
+ from ..utils.campaign_util import (
29
+ get_bucketing_seed,
30
+ get_campaign_ids_from_feature_key,
31
+ get_campaigns_by_group_id,
32
+ get_experiment_key,
33
+ get_rollout_key,
34
+ get_feature_keys_from_campaign_ids,
35
+ set_campaign_allocation,
36
+ get_variation_from_campaign_key,
37
+ get_bucketing_id_for_user,
38
+ )
39
+ from ..utils.function_util import (
40
+ clone_object,
41
+ get_feature_from_key,
42
+ get_specific_rules_based_on_type,
43
+ )
44
+ from ..packages.decision_maker.decision_maker import DecisionMaker
45
+ from ..utils.rule_evaluation_util import evaluate_rule
46
+ from ..utils.decision_util import evaluate_traffic_and_get_variation
47
+ from ..constants.Constants import Constants
48
+ from ..utils.model_utils import convert_campaign_to_variation_model
49
+ from ..services.storage_service import StorageService
50
+ from ..decorators.storage_decorator import StorageDecorator
51
+ from ..utils.holdout_util import get_matched_holdouts
52
+
53
+
54
+ def evaluate_groups(
55
+ settings: SettingsModel,
56
+ feature: FeatureModel,
57
+ group_id: int,
58
+ evaluated_feature_map: Dict[str, Any],
59
+ context: ContextModel,
60
+ storage_service: StorageService,
61
+ ) -> Optional[VariationModel]:
62
+ feature_to_skip = []
63
+ campaign_map: Dict[str, List[CampaignModel]] = {}
64
+
65
+ # Get all feature keys and all campaign IDs from the group ID
66
+ result = get_feature_keys_from_group(settings, group_id)
67
+ feature_keys = result["featureKeys"]
68
+ group_campaign_ids = result["groupCampaignIds"]
69
+
70
+ for feature_key in feature_keys:
71
+ featureToEvaluate = get_feature_from_key(settings, feature_key)
72
+
73
+ # Skip if the feature is already evaluated
74
+ if feature_key in feature_to_skip:
75
+ continue
76
+
77
+ stored_data = StorageDecorator().get_feature_from_storage(
78
+ feature_key, context, storage_service
79
+ )
80
+
81
+
82
+ stored_is_in_holdout_id = (stored_data.get("isInHoldoutId") or stored_data.get("holdoutGroupId")) if stored_data else None
83
+ if stored_is_in_holdout_id and (len(stored_is_in_holdout_id) > 0 if isinstance(stored_is_in_holdout_id, list) else True):
84
+ feature_to_skip.append(feature_key)
85
+ LogManager.get_instance().debug(
86
+ debug_messages.get("PART_OF_HOLDOUT_IN_MEG").format(
87
+ featureKey=feature_key,
88
+ holdoutId=stored_is_in_holdout_id,
89
+ userId=context.get_id(),
90
+ )
91
+ )
92
+ continue
93
+ holdout_result = get_matched_holdouts(settings, featureToEvaluate, context, stored_data) or {}
94
+ matched_holdouts = holdout_result.get("matchedHoldouts", [])
95
+ not_matched_holdouts = holdout_result.get("notMatchedHoldouts", [])
96
+ holdout_payloads = holdout_result.get("holdoutPayloads", [])
97
+
98
+ if matched_holdouts and len(matched_holdouts) > 0:
99
+ feature_to_skip.append(feature_key)
100
+
101
+ qualified_holdout_ids = [holdout.get_id() for holdout in matched_holdouts]
102
+
103
+ StorageDecorator().set_data_in_storage(
104
+ {
105
+ "featureKey": feature_key,
106
+ "context": context,
107
+ "isInHoldoutId": [holdout.get_id() for holdout in matched_holdouts],
108
+ "context": context,
109
+ },
110
+ storage_service,
111
+ )
112
+ LogManager.get_instance().debug(
113
+ debug_messages.get("PART_OF_HOLDOUT_IN_MEG").format(
114
+ featureKey=feature_key,
115
+ holdoutId=qualified_holdout_ids,
116
+ userId=context.get_id(),
117
+ )
118
+ )
119
+ else:
120
+ # Evaluate the feature rollout rules
121
+ is_rollout_rule_passed = _is_rollout_rule_for_feature_passed(
122
+ settings,
123
+ featureToEvaluate,
124
+ evaluated_feature_map,
125
+ feature_to_skip,
126
+ storage_service,
127
+ context,
128
+ )
129
+
130
+ if is_rollout_rule_passed:
131
+ for temp_feature in settings.get_features():
132
+ if temp_feature.get_key() == feature_key:
133
+ for rule in temp_feature.get_rules_linked_campaign():
134
+ if (
135
+ str(rule.get_id()) in group_campaign_ids
136
+ or f"{rule.get_id()}_{rule.get_variations()[0].get_id()}"
137
+ in group_campaign_ids
138
+ ):
139
+ if feature_key not in campaign_map:
140
+ campaign_map[feature_key] = []
141
+ if not any(
142
+ item.get_rule_key() == rule.get_rule_key()
143
+ for item in campaign_map[feature_key]
144
+ ):
145
+ campaign_map[feature_key].append(rule)
146
+
147
+ eligible_campaigns, eligible_campaigns_with_storage = _get_eligible_campaigns(
148
+ settings, campaign_map, context, storage_service
149
+ )
150
+
151
+ return _find_winner_campaign_among_eligible_campaigns(
152
+ settings,
153
+ feature.get_key(),
154
+ eligible_campaigns,
155
+ eligible_campaigns_with_storage,
156
+ group_id,
157
+ context,
158
+ storage_service,
159
+ )
160
+
161
+
162
+ # Helper Functions
163
+
164
+
165
+ def get_feature_keys_from_group(
166
+ settings: SettingsModel, group_id: int
167
+ ) -> Dict[str, Any]:
168
+ group_campaign_ids = get_campaigns_by_group_id(settings, group_id)
169
+ feature_keys = get_feature_keys_from_campaign_ids(settings, group_campaign_ids)
170
+
171
+ return {"featureKeys": feature_keys, "groupCampaignIds": group_campaign_ids}
172
+
173
+
174
+ def _is_rollout_rule_for_feature_passed(
175
+ settings: SettingsModel,
176
+ feature: FeatureModel,
177
+ evaluated_feature_map: Dict[str, Any],
178
+ feature_to_skip: List[str],
179
+ storage_service: StorageService,
180
+ context: ContextModel,
181
+ ) -> bool:
182
+ if (
183
+ feature.get_key() in evaluated_feature_map
184
+ and "rolloutId" in evaluated_feature_map[feature.get_key()]
185
+ ):
186
+ return True
187
+
188
+ roll_out_rules = get_specific_rules_based_on_type(
189
+ feature, CampaignTypeEnum.ROLLOUT.value
190
+ )
191
+ if roll_out_rules:
192
+ for rule in roll_out_rules:
193
+ pre_segmentation_result, whitelisted_object, updated_decision, payload = (
194
+ evaluate_rule(
195
+ settings,
196
+ feature,
197
+ rule,
198
+ context,
199
+ evaluated_feature_map,
200
+ {},
201
+ storage_service,
202
+ {},
203
+ )
204
+ )
205
+ if pre_segmentation_result:
206
+ variation = evaluate_traffic_and_get_variation(
207
+ settings, rule, context
208
+ )
209
+ if isinstance(variation, VariationModel) and not None:
210
+ evaluated_feature_map[feature.get_key()] = {
211
+ "rolloutId": rule.get_id(),
212
+ "rolloutKey": get_rollout_key(rule, feature.get_key()),
213
+ "rolloutVariationId": rule.get_variations()[0].get_id(),
214
+ }
215
+ return True
216
+
217
+ # No rollout rule passed
218
+ feature_to_skip.append(feature.get_key())
219
+ return False
220
+
221
+ # No rollout rule, evaluate experiments
222
+ LogManager.get_instance().info(
223
+ info_messages.get("MEG_SKIP_ROLLOUT_EVALUATE_EXPERIMENTS").format(
224
+ featureKey=feature.get_key()
225
+ )
226
+ )
227
+ return True
228
+
229
+
230
+ def _get_eligible_campaigns(
231
+ settings: SettingsModel,
232
+ campaign_map: Dict[str, List[CampaignModel]],
233
+ context: ContextModel,
234
+ storage_service: StorageService,
235
+ ) -> Tuple[List[CampaignModel], List[CampaignModel]]:
236
+ eligible_campaigns: List[CampaignModel] = []
237
+ eligible_campaigns_with_storage: List[CampaignModel] = []
238
+
239
+ for feature_key, campaigns in campaign_map.items():
240
+ for campaign in campaigns:
241
+ stored_data = StorageDecorator().get_feature_from_storage(
242
+ feature_key, context, storage_service
243
+ )
244
+
245
+ if stored_data and stored_data.get("experimentVariationId"):
246
+ campaign_experiment_key = get_experiment_key(campaign, feature_key)
247
+ if stored_data.get("experimentKey") == campaign_experiment_key:
248
+ variation = get_variation_from_campaign_key(
249
+ settings,
250
+ stored_data["experimentKey"],
251
+ stored_data["experimentVariationId"],
252
+ )
253
+ if variation:
254
+ LogManager.get_instance().info(
255
+ info_messages.get("MEG_CAMPAIGN_FOUND_IN_STORAGE").format(
256
+ campaignKey=(
257
+ campaign.get_rule_key()
258
+ if campaign.get_type() == CampaignTypeEnum.AB.value
259
+ else campaign.get_name()
260
+ + "_"
261
+ + campaign.get_rule_key()
262
+ ),
263
+ userId=context.get_id(),
264
+ )
265
+ )
266
+ if not any(
267
+ get_experiment_key(item, feature_key)
268
+ == campaign_experiment_key
269
+ for item in eligible_campaigns_with_storage
270
+ ):
271
+ eligible_campaigns_with_storage.append(
272
+ clone_object(campaign)
273
+ )
274
+ continue
275
+
276
+ if CampaignDecisionService().get_pre_segmentation_decision(
277
+ campaign, context
278
+ ) and CampaignDecisionService().is_user_part_of_campaign(
279
+ context, campaign
280
+ ):
281
+ LogManager.get_instance().info(
282
+ info_messages.get("MEG_CAMPAIGN_ELIGIBLE").format(
283
+ campaignKey=campaign.get_rule_key(), userId=context.get_id()
284
+ )
285
+ )
286
+ eligible_campaigns.append(clone_object(campaign))
287
+ continue
288
+
289
+ return eligible_campaigns, eligible_campaigns_with_storage
290
+
291
+
292
+ def _find_winner_campaign_among_eligible_campaigns(
293
+ settings: SettingsModel,
294
+ feature_key: str,
295
+ eligible_campaigns: List[CampaignModel],
296
+ eligible_campaigns_with_storage: List[CampaignModel],
297
+ group_id: int,
298
+ context: ContextModel,
299
+ storage_service: StorageService,
300
+ ) -> Optional[VariationModel]:
301
+ winner_campaign = None
302
+ campaign_ids = get_campaign_ids_from_feature_key(settings, feature_key)
303
+ meg_algo_number = (
304
+ settings.get_groups().get(group_id, {}).get("et", Constants.RANDOM_ALGO)
305
+ )
306
+
307
+ if len(eligible_campaigns_with_storage) == 1:
308
+ winner_campaign_found = eligible_campaigns_with_storage[0]
309
+ LogManager.get_instance().info(
310
+ info_messages.get("MEG_WINNER_CAMPAIGN").format(
311
+ campaignKey=(
312
+ winner_campaign_found.get_key()
313
+ if winner_campaign_found.get_type() == CampaignTypeEnum.AB.value
314
+ else winner_campaign_found.get_name()
315
+ + "_"
316
+ + winner_campaign_found.get_rule_key()
317
+ ),
318
+ groupId=group_id,
319
+ userId=context.get_id(),
320
+ algo="",
321
+ )
322
+ )
323
+ winner_campaign = convert_campaign_to_variation_model(winner_campaign_found)
324
+ elif (
325
+ len(eligible_campaigns_with_storage) > 1
326
+ and meg_algo_number == Constants.RANDOM_ALGO
327
+ ):
328
+ winner_campaign = _normalize_weights_and_find_winning_campaign(
329
+ eligible_campaigns_with_storage,
330
+ context,
331
+ campaign_ids,
332
+ group_id,
333
+ storage_service,
334
+ )
335
+ elif len(eligible_campaigns_with_storage) > 1:
336
+ winner_campaign = _get_campaign_using_advanced_algo(
337
+ settings,
338
+ eligible_campaigns_with_storage,
339
+ context,
340
+ campaign_ids,
341
+ group_id,
342
+ storage_service,
343
+ )
344
+
345
+ if not eligible_campaigns_with_storage:
346
+ if len(eligible_campaigns) == 1:
347
+ winner_campaign_found = eligible_campaigns[0]
348
+ LogManager.get_instance().info(
349
+ info_messages.get("MEG_WINNER_CAMPAIGN").format(
350
+ campaignKey=(
351
+ winner_campaign_found.get_key()
352
+ if winner_campaign_found.get_type() == CampaignTypeEnum.AB.value
353
+ else winner_campaign_found.get_name()
354
+ + "_"
355
+ + winner_campaign_found.get_rule_key()
356
+ ),
357
+ groupId=group_id,
358
+ userId=context.get_id(),
359
+ algo="",
360
+ )
361
+ )
362
+ winner_campaign = convert_campaign_to_variation_model(winner_campaign_found)
363
+ elif len(eligible_campaigns) > 1 and meg_algo_number == Constants.RANDOM_ALGO:
364
+ winner_campaign = _normalize_weights_and_find_winning_campaign(
365
+ eligible_campaigns, context, campaign_ids, group_id, storage_service
366
+ )
367
+ elif len(eligible_campaigns) > 1:
368
+ winner_campaign = _get_campaign_using_advanced_algo(
369
+ settings,
370
+ eligible_campaigns,
371
+ context,
372
+ campaign_ids,
373
+ group_id,
374
+ storage_service,
375
+ )
376
+
377
+ return winner_campaign
378
+
379
+
380
+ def _normalize_weights_and_find_winning_campaign(
381
+ shortlisted_campaigns: List[CampaignModel],
382
+ context: ContextModel,
383
+ called_campaign_ids: List[int],
384
+ group_id: int,
385
+ storage_service: StorageService,
386
+ ) -> Optional[VariationModel]:
387
+
388
+ # Normalize weights and convert to VariationModel
389
+ variation_models: List[VariationModel] = []
390
+ for campaign in shortlisted_campaigns:
391
+ # Example of weight normalization, to keep the result with four decimal places
392
+ weight = round(100 / len(shortlisted_campaigns) * 10000) / 10000
393
+ campaign.set_weight(weight)
394
+
395
+ # Convert CampaignModel to VariationModel
396
+ variation = convert_campaign_to_variation_model(campaign)
397
+
398
+ # Append the created VariationModel to the new List
399
+ variation_models.append(variation)
400
+
401
+ set_campaign_allocation(variation_models)
402
+
403
+ # Resolve bucketing ID for MEG random algorithm
404
+
405
+ bucketing_id = get_bucketing_id_for_user(context)
406
+
407
+ winner_campaign = CampaignDecisionService().get_variation(
408
+ variation_models,
409
+ DecisionMaker().calculate_bucket_value(
410
+ get_bucketing_seed(bucketing_id, None, group_id)
411
+ ),
412
+ )
413
+
414
+ if winner_campaign:
415
+ LogManager.get_instance().info(
416
+ info_messages.get("MEG_WINNER_CAMPAIGN").format(
417
+ campaignKey=(
418
+ winner_campaign.get_key()
419
+ if winner_campaign.get_type() == CampaignTypeEnum.AB.value
420
+ else winner_campaign.get_name()
421
+ + "_"
422
+ + winner_campaign.get_rule_key()
423
+ ),
424
+ groupId=group_id,
425
+ userId=f"{context.get_id()} (Seed: {bucketing_id})" if (bucketing_id != context.get_id()) else context.get_id(),
426
+ algo="using random algorithm",
427
+ )
428
+ )
429
+
430
+ StorageDecorator().set_data_in_storage(
431
+ {
432
+ "featureKey": Constants.VWO_META_MEG_KEY + str(group_id),
433
+ "context": context,
434
+ "experimentId": winner_campaign.get_id(),
435
+ "experimentKey": get_experiment_key(winner_campaign),
436
+ "experimentVariationId": (
437
+ winner_campaign.get_variations()[0].get_id()
438
+ if winner_campaign.get_type() == CampaignTypeEnum.PERSONALIZE.value
439
+ else -1
440
+ ),
441
+ },
442
+ storage_service,
443
+ )
444
+
445
+ if winner_campaign.get_id() in called_campaign_ids:
446
+ return winner_campaign
447
+ else:
448
+ LogManager.get_instance().info(
449
+ f"No winner campaign found for group_id: {group_id} and user_id: {context.get_id()}"
450
+ )
451
+ return None
452
+
453
+
454
+ def _get_campaign_using_advanced_algo(
455
+ settings: SettingsModel,
456
+ shortlisted_campaigns: List[CampaignModel],
457
+ context: ContextModel,
458
+ called_campaign_ids: List[int],
459
+ group_id: int,
460
+ storage_service: StorageService,
461
+ ) -> Optional[VariationModel]:
462
+ winner_campaign = None
463
+ found = False
464
+
465
+ priority_order = settings.get_groups().get(group_id, {}).get("p", [])
466
+ wt = settings.get_groups().get(group_id, {}).get("wt", {})
467
+
468
+ bucketing_id = get_bucketing_id_for_user(context)
469
+
470
+ for priority_id in priority_order:
471
+ for campaign in shortlisted_campaigns:
472
+ if str(campaign.get_id()) == priority_id:
473
+ winner_campaign = convert_campaign_to_variation_model(campaign)
474
+ found = True
475
+ break
476
+ elif (
477
+ str(campaign.get_id())
478
+ + "_"
479
+ + str(campaign.get_variations()[0].get_id())
480
+ == priority_id
481
+ ):
482
+ winner_campaign = convert_campaign_to_variation_model(campaign)
483
+ found = True
484
+ break
485
+ if found:
486
+ break
487
+
488
+ if winner_campaign is None:
489
+ participating_campaign_list: List[VariationModel] = []
490
+ for campaign in shortlisted_campaigns:
491
+ if str(campaign.get_id()) in wt:
492
+ cloned_campaign = convert_campaign_to_variation_model(campaign)
493
+ cloned_campaign.set_weight(wt[str(campaign.get_id())])
494
+ participating_campaign_list.append(cloned_campaign)
495
+ elif (
496
+ str(campaign.get_id())
497
+ + "_"
498
+ + str(campaign.get_variations()[0].get_id())
499
+ in wt
500
+ ):
501
+ cloned_campaign = convert_campaign_to_variation_model(campaign)
502
+ cloned_campaign.set_weight(
503
+ wt[
504
+ str(campaign.get_id())
505
+ + "_"
506
+ + str(campaign.get_variations()[0].get_id())
507
+ ]
508
+ )
509
+ participating_campaign_list.append(cloned_campaign)
510
+
511
+ set_campaign_allocation(participating_campaign_list)
512
+
513
+ # Resolve bucketing ID for MEG advanced algorithm
514
+
515
+ bucketing_id = get_bucketing_id_for_user(context)
516
+
517
+ winner_campaign = CampaignDecisionService().get_variation(
518
+ participating_campaign_list,
519
+ DecisionMaker().calculate_bucket_value(
520
+ get_bucketing_seed(bucketing_id, None, group_id)
521
+ ),
522
+ )
523
+
524
+ if winner_campaign:
525
+ LogManager.get_instance().info(
526
+ info_messages.get("MEG_WINNER_CAMPAIGN").format(
527
+ campaignKey=(
528
+ winner_campaign.get_key()
529
+ if winner_campaign.get_type() == CampaignTypeEnum.AB.value
530
+ else winner_campaign.get_name()
531
+ + "_"
532
+ + winner_campaign.get_rule_key()
533
+ ),
534
+ groupId=group_id,
535
+ userId=f"{context.get_id()} (Seed: {bucketing_id})" if (bucketing_id != context.get_id()) else context.get_id(),
536
+ algo="using advanced algorithm",
537
+ )
538
+ )
539
+
540
+ StorageDecorator().set_data_in_storage(
541
+ {
542
+ "featureKey": Constants.VWO_META_MEG_KEY + str(group_id),
543
+ "context": context,
544
+ "experimentId": winner_campaign.get_id(),
545
+ "experimentKey": get_experiment_key(winner_campaign),
546
+ "experimentVariationId": (
547
+ winner_campaign.get_variations()[0].get_id()
548
+ if winner_campaign.get_type() == CampaignTypeEnum.PERSONALIZE.value
549
+ else -1
550
+ ),
551
+ },
552
+ storage_service,
553
+ )
554
+
555
+ if winner_campaign.get_id() in called_campaign_ids:
556
+ return winner_campaign
557
+ else:
558
+ LogManager.get_instance().info(
559
+ f"No winner campaign found for group_id: {group_id} and user_id: {context.get_id()}"
560
+ )
561
+ return None
@@ -0,0 +1,136 @@
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 ..models.campaign.campaign_model import CampaignModel
17
+ from ..models.campaign.rule_model import RuleModel
18
+ from ..models.campaign.metric_model import MetricModel
19
+ from ..models.campaign.feature_model import FeatureModel
20
+ from ..models.campaign.variable_model import VariableModel
21
+ from ..models.campaign.variation_model import VariationModel
22
+ from ..models.campaign.impact_campaign_model import ImpactCampaignModel
23
+ from typing import Dict, Any
24
+
25
+
26
+ def _parse_feature(feature_data: Dict[str, Any]) -> FeatureModel:
27
+ rules = [_parse_rule(rule) for rule in feature_data["rules"]]
28
+ metrics = [_parse_metric(metric) for metric in feature_data["metrics"]]
29
+ return FeatureModel(
30
+ id=feature_data["id"],
31
+ rules=rules,
32
+ status=feature_data.get("status", None),
33
+ key=feature_data["key"],
34
+ metrics=metrics,
35
+ impactCampaign=ImpactCampaignModel(feature_data.get("impactCampaign", {})),
36
+ type=feature_data["type"],
37
+ name=feature_data["name"],
38
+ rules_linked_campaign=[
39
+ _parse_campaign(c) for c in feature_data.get("rulesLinkedCampaign", [])
40
+ ],
41
+ is_gateway_service_required=feature_data.get(
42
+ "isgateway_serviceRequired", False
43
+ ),
44
+ isDebuggerEnabled=feature_data.get("isDebuggerEnabled", False),
45
+ )
46
+
47
+
48
+ def _parse_rule(rule_data: Dict[str, Any]) -> RuleModel:
49
+ return RuleModel(
50
+ type=rule_data["type"],
51
+ ruleKey=rule_data.get("ruleKey"),
52
+ variationId=rule_data.get("variationId", None),
53
+ campaignId=rule_data["campaignId"],
54
+ )
55
+
56
+
57
+ def _parse_metric(metric_data: Dict[str, Any]) -> MetricModel:
58
+ return MetricModel(
59
+ id=metric_data["id"],
60
+ hasProps=metric_data.get("hasProps", None),
61
+ type=metric_data["type"],
62
+ identifier=metric_data["identifier"],
63
+ )
64
+
65
+
66
+ def _parse_variable(variable_data: Dict[str, Any]) -> VariableModel:
67
+ return VariableModel(
68
+ id=variable_data["id"],
69
+ value=variable_data["value"],
70
+ type=variable_data["type"],
71
+ key=variable_data["key"],
72
+ )
73
+
74
+
75
+ def _parse_variation(variation_data: Dict[str, Any]) -> VariationModel:
76
+ variables = [_parse_variable(var) for var in variation_data.get("variables", [])]
77
+ return VariationModel(
78
+ id=variation_data.get("id", None),
79
+ segments=variation_data.get("segments", {}),
80
+ weight=variation_data.get("weight", None),
81
+ name=variation_data.get("name", None),
82
+ variables=variables,
83
+ start_range_variation=variation_data.get("startRangeVariation", None),
84
+ end_range_variation=variation_data.get("endRangeVariation", None),
85
+ key=variation_data.get("key", None),
86
+ rule_key=variation_data.get("ruleKey", None),
87
+ type=variation_data.get("type", None),
88
+ variations=[
89
+ _parse_variation(var) for var in variation_data.get("variations", [])
90
+ ],
91
+ salt=variation_data.get("salt", None),
92
+ whitelisted_segments=variation_data.get("whitelistedSegments", None),
93
+ )
94
+
95
+
96
+ def _parse_campaign(campaign_data: Dict[str, Any]) -> CampaignModel:
97
+ variations = [_parse_variation(var) for var in campaign_data.get("variations", [])]
98
+ return CampaignModel(
99
+ id=campaign_data["id"],
100
+ isForcedVariationEnabled=campaign_data.get("isForcedVariationEnabled", False),
101
+ segments=campaign_data.get("segments", {}),
102
+ variations=variations,
103
+ status=campaign_data["status"],
104
+ type=campaign_data["type"],
105
+ key=campaign_data["key"],
106
+ isAlwaysCheckSegment=campaign_data.get("isAlwaysCheckSegment", False),
107
+ name=campaign_data["name"],
108
+ percentTraffic=campaign_data.get("percentTraffic", None),
109
+ is_user_list_enabled=campaign_data.get("isUserListEnabled", False),
110
+ metrics=campaign_data.get("metrics", []),
111
+ variables=campaign_data.get("variables", []),
112
+ variation_id=campaign_data.get("variationId", None),
113
+ campaign_id=campaign_data.get("campaignId", None),
114
+ rule_key=campaign_data.get("ruleKey", None),
115
+ weight=campaign_data.get("weight", None),
116
+ start_range_variation=campaign_data.get("startRangeVariation", None),
117
+ end_range_variation=campaign_data.get("endRangeVariation", None),
118
+ salt=campaign_data.get("salt", None),
119
+ )
120
+
121
+
122
+ def convert_campaign_to_variation_model(campaign: CampaignModel):
123
+ return VariationModel(
124
+ campaign.get_id(),
125
+ campaign.get_segments(),
126
+ campaign.get_weight(),
127
+ campaign.get_name(),
128
+ campaign.get_variables(),
129
+ campaign.get_start_range_variation(),
130
+ campaign.get_end_range_variation(),
131
+ campaign.get_key(),
132
+ campaign.get_rule_key(),
133
+ campaign.get_type(),
134
+ campaign.get_variations(),
135
+ campaign.get_salt(),
136
+ )