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,706 @@
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, Optional
17
+ import json
18
+ import random
19
+ from unicodedata import category
20
+ from ..constants.Constants import Constants
21
+ from ..utils.uuid_util import get_random_uuid, get_uuid
22
+ from ..utils.data_type_util import is_object
23
+ from ..utils.function_util import (
24
+ get_current_unix_timestamp,
25
+ get_current_unix_timestamp_in_millis,
26
+ get_random_number,
27
+ )
28
+ from ..packages.logger.core.log_manager import LogManager
29
+ from ..services.url_service import UrlService
30
+ from ..enums.url_enum import UrlEnum
31
+ from ..models.settings.settings_model import SettingsModel
32
+ from ..utils.log_message_util import debug_messages, error_messages, info_messages
33
+ from ..packages.network_layer.manager.network_manager import NetworkManager
34
+ from ..packages.network_layer.models.request_model import RequestModel
35
+ from ..enums.headers_enum import HeadersEnum
36
+ from ..utils.usage_stats_util import UsageStatsUtil
37
+ from ..services.settings_manager import SettingsManager
38
+ from ..enums.event_enum import EventEnum
39
+ from wingify.models.user.context_model import ContextModel
40
+ from ..enums.api_enum import ApiEnum
41
+ from ..packages.network_layer.models.response_model import ResponseModel
42
+ from ..enums.campaign_type_enum import CampaignTypeEnum
43
+ from ..enums.debug_category_enum import DebugCategoryEnum
44
+ from ..packages.logger.enums.log_level_enum import LogLevelEnum
45
+ from ..utils.debugger_service_util import send_debug_event_to_vwo
46
+
47
+
48
+ def _get_sdk_name() -> str:
49
+ settings = SettingsManager.get_instance()
50
+ if settings is not None:
51
+ return settings.get_sdk_name()
52
+ from ..utils.brand_context import get_is_via_vwo
53
+ from ..utils.brand_util import get_sdk_name
54
+
55
+ return get_sdk_name(get_is_via_vwo())
56
+
57
+
58
+ # Function to construct tracking path for an event
59
+ def get_track_event_path(event: str, account_id: str, user_id: str) -> Dict[str, Any]:
60
+ return {
61
+ "event_type": event,
62
+ "account_id": account_id,
63
+ "uId": user_id,
64
+ "u": get_uuid(user_id, account_id),
65
+ "sdk": _get_sdk_name(),
66
+ "sdk-v": Constants.SDK_VERSION,
67
+ "random": get_random_number(),
68
+ "ap": Constants.AP,
69
+ "sId": get_current_unix_timestamp(),
70
+ "ed": json.dumps({"p": "server"}),
71
+ }
72
+
73
+
74
+ # Function to construct query parameters for event batching
75
+ def get_event_batching_query_params(account_id: str) -> Dict[str, Any]:
76
+ return {"a": account_id, "sd": _get_sdk_name(), "sv": Constants.SDK_VERSION}
77
+
78
+
79
+ # Function to build generic properties for tracking events
80
+ def get_events_base_properties(
81
+ event_name: str,
82
+ visitor_user_agent: str = "",
83
+ ip_address: str = "",
84
+ is_usage_stats_event: bool = False,
85
+ usage_stats_account_id: int = None,
86
+ ) -> Dict[str, Any]:
87
+
88
+ # Get the instance of SettingsManager
89
+ settings = SettingsManager.get_instance()
90
+
91
+ # Fetch SDK key and account ID from the SettingsManager instance
92
+ sdk_key = settings.get_sdk_key()
93
+ account_id = settings.get_account_id()
94
+
95
+ properties = {
96
+ "en": event_name,
97
+ "a": account_id,
98
+ "eTime": get_current_unix_timestamp_in_millis(),
99
+ "random": get_random_number(),
100
+ "p": "FS",
101
+ "visitor_ua": visitor_user_agent,
102
+ "visitor_ip": ip_address,
103
+ "sn": _get_sdk_name(),
104
+ "sv": Constants.SDK_VERSION
105
+ }
106
+
107
+ properties["env"] = sdk_key
108
+ if is_usage_stats_event:
109
+ properties["a"] = str(usage_stats_account_id)
110
+
111
+ return properties
112
+
113
+
114
+ # Function to build payload for tracking events
115
+ def _get_event_base_payload(
116
+ settings: SettingsModel,
117
+ user_id: str,
118
+ event_name: str,
119
+ visitor_user_agent: str = "",
120
+ ip_address: str = "",
121
+ is_usage_stats_event: bool = False,
122
+ usage_stats_account_id: int = None,
123
+ ) -> Dict[str, Any]:
124
+
125
+ account_id = SettingsManager.get_instance().get_account_id()
126
+ if is_usage_stats_event:
127
+ # set account id for internal usage stats event
128
+ account_id = usage_stats_account_id
129
+
130
+ uuid_value = get_uuid(str(user_id), str(account_id))
131
+ sdk_key = SettingsManager.get_instance().get_sdk_key()
132
+
133
+ props = {
134
+ "vwo_sdkName": _get_sdk_name(),
135
+ "vwo_sdkVersion": Constants.SDK_VERSION,
136
+ }
137
+
138
+ if not is_usage_stats_event:
139
+ # set env key for standard sdk events
140
+ props["vwo_envKey"] = sdk_key
141
+
142
+ properties = {
143
+ "d": {
144
+ "msgId": f"{uuid_value}-{get_current_unix_timestamp_in_millis()}",
145
+ "visId": uuid_value,
146
+ "sessionId": get_current_unix_timestamp(),
147
+ "event": {
148
+ "props": props,
149
+ "name": event_name,
150
+ "time": get_current_unix_timestamp_in_millis(),
151
+ },
152
+ }
153
+ }
154
+
155
+ # if visitor_user_agent and ip_address is not null then add to the properties
156
+ if visitor_user_agent is not None:
157
+ properties["d"]["visitor_ua"] = visitor_user_agent
158
+ if ip_address is not None:
159
+ properties["d"]["visitor_ip"] = ip_address
160
+
161
+ if not is_usage_stats_event:
162
+ # set visitor props for standard sdk events
163
+ properties["d"]["visitor"] = {
164
+ "props": {
165
+ Constants.VWO_FS_ENVIRONMENT: sdk_key,
166
+ },
167
+ }
168
+
169
+ return properties
170
+
171
+
172
+ # Function to build payload for tracking user data
173
+ def get_track_user_payload_data(
174
+ settings: SettingsModel,
175
+ event_name: str,
176
+ campaign_id: int,
177
+ variation_id: int,
178
+ context: ContextModel,
179
+ ) -> Dict[str, Any]:
180
+ user_id = context.get_id()
181
+ visitor_user_agent = context.get_user_agent()
182
+ ip_address = context.get_ip_address()
183
+ post_segmentation_variables = context.get_post_segmentation_variables()
184
+ custom_variables = context.get_custom_variables()
185
+
186
+ properties = _get_event_base_payload(
187
+ settings,
188
+ user_id,
189
+ event_name,
190
+ visitor_user_agent,
191
+ ip_address,
192
+ )
193
+
194
+ if context.get_session_id() is not None and context.get_session_id() != 0:
195
+ properties["d"]["sessionId"] = context.get_session_id()
196
+
197
+ # if uuid is provided in the context, use it, otherwise generate a new one
198
+ if context.get_vwo_uuid() is not None and context.get_vwo_uuid() != "":
199
+ properties["d"]["msgId"] = f"{context.get_vwo_uuid()}-{get_current_unix_timestamp_in_millis()}"
200
+ properties["d"]["visId"] = context.get_vwo_uuid()
201
+
202
+ properties["d"]["event"]["props"]["id"] = campaign_id
203
+ properties["d"]["event"]["props"]["variation"] = str(variation_id)
204
+ properties["d"]["event"]["props"]["isFirst"] = 1
205
+
206
+ usage_stats_data = UsageStatsUtil().get_usage_stats()
207
+ if len(usage_stats_data) > 0:
208
+ properties["d"]["event"]["props"]["vwoMeta"] = usage_stats_data
209
+
210
+ # Add post-segmentation variables if they exist in custom variables
211
+ if post_segmentation_variables is not None and custom_variables is not None:
212
+ for key in post_segmentation_variables:
213
+ if key in custom_variables:
214
+ properties["d"]["visitor"]["props"][key] = custom_variables[key]
215
+
216
+ # Add IP address as a standard attribute if available
217
+ if ip_address:
218
+ properties["d"]["visitor"]["props"]["ip"] = ip_address
219
+
220
+ LogManager.get_instance().debug(
221
+ debug_messages.get("IMPRESSION_FOR_TRACK_USER").format(
222
+ accountId=settings.get_account_id(), userId=user_id, campaignId=campaign_id
223
+ )
224
+ )
225
+
226
+ return properties
227
+
228
+
229
+ # Function to build payload for tracking goals with custom event properties
230
+ def get_track_goal_payload_data(
231
+ settings: SettingsModel,
232
+ context: ContextModel,
233
+ event_name: str,
234
+ event_properties: Dict[str, Any],
235
+ ) -> Dict[str, Any]:
236
+ properties = _get_event_base_payload(
237
+ settings, context.get_id(), event_name, context.get_user_agent(), context.get_ip_address()
238
+ )
239
+
240
+ if context.get_session_id() is not None and context.get_session_id() != 0:
241
+ properties["d"]["sessionId"] = context.get_session_id()
242
+
243
+ # if uuid is provided in the context, use it, otherwise generate a new one
244
+ if context.get_vwo_uuid() is not None and context.get_vwo_uuid() != "":
245
+ properties["d"]["msgId"] = f"{context.get_vwo_uuid()}-{get_current_unix_timestamp_in_millis()}"
246
+ properties["d"]["visId"] = context.get_vwo_uuid()
247
+
248
+ properties["d"]["event"]["props"]["isCustomEvent"] = True
249
+ properties["d"]["event"]["props"]["variation"] = 1 # Temporary value for variation
250
+ properties["d"]["event"]["props"]["id"] = 1 # Temporary value for ID
251
+
252
+ if event_properties and is_object(event_properties):
253
+ for prop, value in event_properties.items():
254
+ properties["d"]["event"]["props"][prop] = value
255
+
256
+ LogManager.get_instance().debug(
257
+ debug_messages.get("IMPRESSION_FOR_TRACK_GOAL").format(
258
+ eventName=event_name, accountId=settings.get_account_id(), userId=context.get_id()
259
+ )
260
+ )
261
+
262
+ return properties
263
+
264
+
265
+ # Function to build payload for syncing visitor attributes
266
+ def get_attribute_payload_data(
267
+ settings: SettingsModel,
268
+ context: ContextModel,
269
+ event_name: str,
270
+ attribute_map: Dict
271
+ ) -> Dict[str, Any]:
272
+ properties = _get_event_base_payload(
273
+ settings, context.get_id(), event_name, context.get_user_agent(), context.get_ip_address()
274
+ )
275
+
276
+ if context.get_session_id() is not None and context.get_session_id() != 0:
277
+ properties["d"]["sessionId"] = context.get_session_id()
278
+
279
+ # if uuid is provided in the context, use it, otherwise generate a new one
280
+ if context.get_vwo_uuid() is not None and context.get_vwo_uuid() != "":
281
+ properties["d"]["msgId"] = f"{context.get_vwo_uuid()}-{get_current_unix_timestamp_in_millis()}"
282
+ properties["d"]["visId"] = context.get_vwo_uuid()
283
+
284
+ properties["d"]["event"]["props"]["isCustomEvent"] = True
285
+ properties["d"]["event"]["props"][
286
+ Constants.VWO_FS_ENVIRONMENT
287
+ ] = settings.get_sdk_key()
288
+ properties["d"]["visitor"]["props"].update(attribute_map)
289
+
290
+ LogManager.get_instance().debug(
291
+ debug_messages.get("IMPRESSION_FOR_SYNC_VISITOR_PROP").format(
292
+ eventName=event_name, accountId=settings.get_account_id(), userId=context.get_id()
293
+ )
294
+ )
295
+
296
+ return properties
297
+
298
+
299
+ # Function to send a POST API request without waiting for the response
300
+ def send_post_api_request(
301
+ properties: Dict[str, Any], payload: Dict[str, Any], user_id: str, feature_info: Optional[Dict[str, Any]] = None
302
+ ):
303
+ """
304
+ Sends a POST API request without waiting for the response.
305
+
306
+ :param properties: The properties of the request.
307
+ :param payload: The payload of the request.
308
+ :param user_id: The user ID of the request.
309
+ :param feature_info: The feature information of the request.
310
+ """
311
+ try:
312
+ # Initialize the headers dictionary for the request
313
+ headers = {}
314
+
315
+ # Retrieve 'visitor_ua' and 'visitor_ip' from the payload if they exist
316
+ visitor_ua = payload["d"].get("visitor_ua")
317
+ visitor_ip = payload["d"].get("visitor_ip")
318
+
319
+ # Add headers if they exist
320
+ if visitor_ua and isinstance(visitor_ua, str) and visitor_ua.strip():
321
+ headers[HeadersEnum.USER_AGENT.value] = visitor_ua.strip()
322
+ if visitor_ip and isinstance(visitor_ip, str) and visitor_ip.strip():
323
+ headers[HeadersEnum.IP.value] = visitor_ip.strip()
324
+
325
+ event_name = payload["d"].get("event").get("name")
326
+ api_name = None
327
+ extra_data_for_message = None
328
+ if event_name == EventEnum.VARIATION_SHOWN.value:
329
+ api_name = ApiEnum.GET_FLAG.value
330
+ # if campaign type is rollout or personalize
331
+ if feature_info is not None and feature_info.get("campaign_type") in (CampaignTypeEnum.ROLLOUT.value, CampaignTypeEnum.PERSONALIZE.value):
332
+ extra_data_for_message = f"feature: {feature_info.get('feature_key')}, rule: {feature_info.get('variation_name')}"
333
+ elif feature_info is not None:
334
+ extra_data_for_message = f"feature: {feature_info.get('feature_key')}, rule: {feature_info.get('campaign_key')} and variation: {feature_info.get('variation_name')}"
335
+ else:
336
+ extra_data_for_message = f"event: {event_name}"
337
+ elif event_name == EventEnum.SYNC_VISITOR_PROP.value:
338
+ api_name = ApiEnum.SET_ATTRIBUTE.value
339
+ extra_data_for_message = api_name
340
+ elif event_name != EventEnum.LOG_EVENT.value or event_name != EventEnum.DEBUGGER_EVENT.value or event_name != EventEnum.SDK_INIT_EVENT.value or event_name != EventEnum.USAGE_STATS.value:
341
+ api_name = ApiEnum.TRACK_EVENT.value
342
+ extra_data_for_message = api_name
343
+
344
+ # Create the request model
345
+ is_gateway_service = SettingsManager.get_instance().is_gateway_service_provided
346
+ request = RequestModel(
347
+ SettingsManager.get_instance().get_events_hostname(),
348
+ "POST",
349
+ UrlService.get_endpoint_with_collection_prefix(
350
+ endpoint=UrlEnum.EVENTS.value, is_gateway_service=is_gateway_service
351
+ ),
352
+ properties,
353
+ payload,
354
+ headers,
355
+ SettingsManager.get_instance().protocol,
356
+ SettingsManager.get_instance().port,
357
+ )
358
+
359
+ # Will be used for logging purpose inside post_async method
360
+ request.set_user_id(user_id)
361
+ # Get network instance
362
+ network_instance = NetworkManager.get_instance()
363
+ # Create a background thread to send the request
364
+ def send_request():
365
+ try:
366
+ response = network_instance.post(request)
367
+ if response.get_total_attempts() > 0:
368
+ debug_category = DebugCategoryEnum.RETRY.value
369
+ msg_t = Constants.NETWORK_CALL_SUCCESS_WITH_RETRIES
370
+ msg = info_messages.get(msg_t).format(extraData=extra_data_for_message, attempts=response.get_total_attempts(), err=response.get_error())
371
+ lt = LogLevelEnum.INFO.value
372
+ if response.status_code != 200:
373
+ debug_category = DebugCategoryEnum.NETWORK.value
374
+ msg_t = Constants.NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES
375
+ msg = error_messages.get(msg_t).format(extraData=extra_data_for_message, attempts=response.get_total_attempts(), err=response.get_error())
376
+ lt = LogLevelEnum.ERROR.value
377
+
378
+ debug_event_props = {
379
+ "cg": debug_category,
380
+ "lt": lt,
381
+ "msg_t": msg_t,
382
+ "msg": msg,
383
+ "an": api_name,
384
+ "uuid": request.get_body().get("d").get("visId"),
385
+ "sId": request.get_body().get("d").get("sessionId"),
386
+ }
387
+ # Send the debug event to VWO
388
+ send_debug_event_to_vwo(debug_event_props);
389
+
390
+ if response.status_code == 200:
391
+ # clear the usage stats data
392
+ UsageStatsUtil().clear_usage_stats()
393
+
394
+ request_query = request.get_query()
395
+ LogManager.get_instance().info(
396
+ info_messages.get("NETWORK_CALL_SUCCESS").format(
397
+ event=request_query.get("en"),
398
+ endPoint=request.get_url().split("?")[0],
399
+ accountId=request_query.get("a"),
400
+ userId=request.get_user_id(),
401
+ uuid=request.get_body().get("d").get("visId"),
402
+ )
403
+ )
404
+ except Exception as e:
405
+ LogManager.get_instance().error_log("NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES", data={"extraData": "event: " + event_name, "attempts": 0, "err": str(e)}, debug_data={"an": api_name, "uuid": request.get_body().get("d").get("visId"), "sId": request.get_body().get("d").get("sessionId")})
406
+
407
+ # Start the request in a background thread if threading is enabled
408
+ if network_instance.should_use_threading:
409
+ network_instance.execute_in_background(send_request)
410
+ else:
411
+ send_request()
412
+
413
+ except Exception as err:
414
+ LogManager.get_instance().error_log("NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES", data={"extraData": "event: " + event_name, "attempts": 0, "err": str(err)}, debug_data={"an": api_name, "uuid": payload["d"].get("visId"), "sId": payload["d"].get("sessionId")})
415
+
416
+
417
+ def send_post_batch_request(
418
+ payload: dict, account_id: int, sdk_key: str, flush_callback=None
419
+ ):
420
+
421
+ try:
422
+ # Prepare the batch payload
423
+ batch_payload = {"ev": payload}
424
+
425
+ # Prepare query parameters
426
+ query = {
427
+ "a": str(account_id),
428
+ "env": sdk_key,
429
+ "sn": _get_sdk_name(),
430
+ "sv": Constants.SDK_VERSION,
431
+ }
432
+
433
+ # Create the RequestModel with necessary data
434
+ is_gateway_service = SettingsManager.get_instance().is_gateway_service_provided
435
+ request_model = RequestModel(
436
+ SettingsManager.get_instance().get_events_hostname(),
437
+ "POST",
438
+ UrlService.get_endpoint_with_collection_prefix(
439
+ endpoint=UrlEnum.BATCH_EVENTS.value, is_gateway_service=is_gateway_service
440
+ ),
441
+ query,
442
+ batch_payload,
443
+ {
444
+ "Authorization": sdk_key,
445
+ "Content-Type": "application/json",
446
+ },
447
+ SettingsManager.get_instance().protocol,
448
+ SettingsManager.get_instance().port,
449
+ )
450
+
451
+ request_model.set_user_id("NA")
452
+ # Call PostAsync to send the request asynchronously
453
+ network_manager = NetworkManager.get_instance()
454
+ response = network_manager.post(request_model)
455
+
456
+ # After sending the request, check the response
457
+ if response.status_code == 200:
458
+ LogManager.get_instance().info(
459
+ info_messages.get('BATCH_FLUSH_SUCCESS').format(
460
+ eventCount=len(payload)
461
+ )
462
+ )
463
+ # On success, call the flush callback if defined
464
+ if flush_callback:
465
+ flush_callback(None, payload) # No error, events sent successfully
466
+ return True
467
+ else:
468
+ LogManager.get_instance().error_log("NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES", data={"extraData": "event: " + UrlEnum.BATCH_EVENTS.value, "attempts": response.get_total_attempts(), "err": response.get_error()}, debug_data={"an": ApiEnum.FLUSH_EVENTS.value})
469
+ if flush_callback:
470
+ flush_callback(
471
+ f"Failed with status code: {response.status_code}", payload
472
+ )
473
+ return False
474
+ except Exception as ex:
475
+ LogManager.get_instance().error_log("ERROR_FLUSHING_BATCH_EVENTS", data={"error": str(ex)}, debug_data={"an": ApiEnum.FLUSH_EVENTS.value})
476
+
477
+ # Call flush callback with error
478
+ if flush_callback:
479
+ flush_callback(str(ex), payload)
480
+ return False
481
+
482
+
483
+ # Function to construct the messaging event payload
484
+ def get_messaging_event_payload(
485
+ message_type: str, message: str, event_name: str
486
+ ) -> Dict[str, Any]:
487
+ # Get user ID and properties
488
+ settings = SettingsManager.get_instance()
489
+ user_id = f"{settings.get_account_id()}_{settings.get_sdk_key()}"
490
+ properties = _get_event_base_payload(None, user_id, event_name, None, None)
491
+
492
+ # Set the environment key and product
493
+ properties["d"]["event"]["props"]["vwo_envKey"] = settings.get_sdk_key()
494
+ properties["d"]["event"]["props"]["product"] = Constants.PRODUCT_NAME
495
+
496
+ # Set the message data
497
+ data = {
498
+ "type": message_type,
499
+ "content": {
500
+ "title": message,
501
+ "dateTime": get_current_unix_timestamp_in_millis(),
502
+ },
503
+ }
504
+
505
+ # Add data to the properties
506
+ properties["d"]["event"]["props"]["data"] = data
507
+
508
+ return properties
509
+
510
+
511
+ def get_sdk_init_event_payload(event_name: str) -> Dict[str, Any]:
512
+ """
513
+ Constructs the payload for sdk init called event.
514
+
515
+ Args:
516
+ event_name: The name of the event.
517
+
518
+ Returns:
519
+ The constructed payload with required fields.
520
+ """
521
+ # Get user ID and properties
522
+ settings = SettingsManager.get_instance()
523
+ user_id = f"{settings.get_account_id()}_{settings.get_sdk_key()}"
524
+ properties = _get_event_base_payload(None, user_id, event_name, None, None)
525
+
526
+ # Set the required fields as specified
527
+ properties["d"]["event"]["props"][
528
+ Constants.VWO_FS_ENVIRONMENT
529
+ ] = settings.get_sdk_key()
530
+ properties["d"]["event"]["props"]["product"] = Constants.PRODUCT_NAME
531
+
532
+ data = {
533
+ "isSDKInitialized": True,
534
+ }
535
+ properties["d"]["event"]["props"]["data"] = data
536
+
537
+ return properties
538
+
539
+
540
+ def get_sdk_usage_stats_event_payload(
541
+ event_name: str,
542
+ usage_stats_account_id: int,
543
+ settings_fetch_time: Optional[int] = None,
544
+ sdk_init_time: Optional[int] = None,
545
+ init_config: Optional[Dict[str, Any]] = None,
546
+ ) -> Dict[str, Any]:
547
+ """
548
+ Constructs the payload for sdk usage stats event.
549
+
550
+ Args:
551
+ event_name: The name of the event.
552
+ usage_stats_account_id: Account ID for usage stats event.
553
+ settings_fetch_time: Time taken to fetch settings in milliseconds.
554
+ sdk_init_time: Time taken to initialize the SDK in milliseconds.
555
+ init_config: SDK initialization options.
556
+
557
+ Returns:
558
+ The constructed payload with required fields.
559
+ """
560
+ # Get user ID and properties
561
+ settings = SettingsManager.get_instance()
562
+ user_id = f"{settings.get_account_id()}_{settings.get_sdk_key()}"
563
+ properties = _get_event_base_payload(
564
+ None, user_id, event_name, None, None, True, usage_stats_account_id
565
+ )
566
+
567
+ # Set the required fields as specified
568
+ properties["d"]["event"]["props"]["product"] = Constants.PRODUCT_NAME
569
+ properties["d"]["event"]["props"]["vwoMeta"] = UsageStatsUtil().get_usage_stats()
570
+
571
+ data = {
572
+ "settingsFetchTime": settings_fetch_time,
573
+ "sdkInitTime": sdk_init_time,
574
+ "initConfig": json.loads(
575
+ json.dumps(init_config or {}, default=lambda o: type(o).__name__)
576
+ ),
577
+ }
578
+ properties["d"]["event"]["props"]["data"] = data
579
+
580
+ return properties
581
+
582
+
583
+ def send_event(
584
+ properties: Dict[str, Any], payload: Dict[str, Any], event_name: str
585
+ ) -> Dict[str, Any]:
586
+ try:
587
+ base_url = SettingsManager.get_instance().get_events_hostname()
588
+ protocol = SettingsManager.get_instance().protocol
589
+ port = SettingsManager.get_instance().port
590
+
591
+ is_gateway_service = SettingsManager.get_instance().is_gateway_service_provided
592
+ # Create the request model
593
+ request = RequestModel(
594
+ base_url,
595
+ "POST",
596
+ UrlService.get_endpoint_with_collection_prefix(
597
+ endpoint=UrlEnum.EVENTS.value, is_gateway_service=is_gateway_service
598
+ ),
599
+ properties,
600
+ payload,
601
+ None,
602
+ protocol,
603
+ port,
604
+ )
605
+
606
+ # Get network instance
607
+ network_instance = NetworkManager.get_instance()
608
+
609
+ # Create a background thread to send the request
610
+ def send_request():
611
+ try:
612
+ network_instance.post(request)
613
+ except Exception:
614
+ pass
615
+
616
+ # Start the request in a background thread if threading is enabled
617
+ if network_instance.should_use_threading:
618
+ network_instance.execute_in_background(send_request)
619
+ else:
620
+ send_request()
621
+
622
+ return {"success": True, "message": "Event sent successfully"}
623
+
624
+ except Exception:
625
+ return {"success": False, "message": "Failed to send event"}
626
+
627
+ def get_debugger_event_payload(event_props: Dict[str, Any]) -> Dict[str, Any]:
628
+ """
629
+ Constructs the payload for debugger event.
630
+
631
+ Args:
632
+ event_props: The properties of the event.
633
+
634
+ Returns:
635
+ The constructed payload with required fields.
636
+ """
637
+
638
+ account_id = str(SettingsManager.get_instance().get_account_id())
639
+ sdk_key = SettingsManager.get_instance().get_sdk_key()
640
+
641
+ payload = _get_event_base_payload(None, account_id + "_" + sdk_key, EventEnum.DEBUGGER_EVENT.value)
642
+ uuid = event_props.get("uuid")
643
+
644
+ if uuid is None:
645
+ event_props["uuid"] = payload["d"].get("visId")
646
+ else:
647
+ payload["d"]["msgId"] = f"{uuid}-{get_current_unix_timestamp_in_millis()}"
648
+ payload["d"]["visId"] = uuid
649
+
650
+ session_id = event_props.get("sId")
651
+ if session_id is None:
652
+ event_props["sId"] = payload["d"].get("sessionId")
653
+ else:
654
+ payload["d"]["sessionId"] = session_id
655
+
656
+ payload["d"]["event"]["props"] = {}
657
+ payload["d"]["event"]["props"]["vwoMeta"] = event_props
658
+
659
+ payload["d"]["event"]["props"]["vwoMeta"]["a"] = account_id
660
+ payload["d"]["event"]["props"]["vwoMeta"]["product"] = Constants.PRODUCT_NAME
661
+ payload["d"]["event"]["props"]["vwoMeta"]["sn"] = _get_sdk_name()
662
+ payload["d"]["event"]["props"]["vwoMeta"]["sv"] = Constants.SDK_VERSION
663
+ payload["d"]["event"]["props"]["vwoMeta"]["eventId"] = get_random_uuid(sdk_key)
664
+ return payload
665
+
666
+
667
+ def create_holdout_payload(
668
+ settings: SettingsModel,
669
+ event_name: str,
670
+ holdout_id: int,
671
+ variation_id: int,
672
+ context: ContextModel,
673
+ feature_id: int,
674
+ ) -> Dict[str, Any]:
675
+ """
676
+ Creates payload for holdout variation shown event.
677
+ Similar to get_track_user_payload_data but specifically for holdouts.
678
+
679
+ Args:
680
+ settings: The settings model containing configuration.
681
+ event_name: The event name.
682
+ holdout_id: The holdout ID (used as campaignId/id).
683
+ variation_id: The variation ID (1 if IN holdout, 2 if NOT IN holdout).
684
+ context: The user context model containing user-specific data.
685
+ feature_id: The feature ID.
686
+
687
+ Returns:
688
+ The holdout payload data.
689
+ """
690
+ user_id = context.get_id()
691
+
692
+ properties = _get_event_base_payload(
693
+ settings=settings,
694
+ user_id=user_id,
695
+ event_name=event_name,
696
+ visitor_user_agent=context.get_user_agent(),
697
+ ip_address=context.get_ip_address(),
698
+ )
699
+
700
+ properties["d"]["event"]["props"]["id"] = holdout_id
701
+ properties["d"]["event"]["props"]["variation"] = variation_id
702
+ properties["d"]["event"]["props"]["isFirst"] = 1
703
+ properties["d"]["event"]["props"]["fId"] = feature_id
704
+
705
+ return properties
706
+