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,293 @@
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
+ import random
18
+
19
+ from wingify.packages.logger.enums.log_level_enum import LogLevelEnum
20
+ from ..packages.network_layer.manager.network_manager import NetworkManager
21
+ from ..packages.network_layer.models.request_model import RequestModel
22
+ from ..constants.Constants import Constants
23
+ from ..utils.brand_util import (
24
+ get_events_hostname,
25
+ get_sdk_name,
26
+ get_settings_hostname,
27
+ )
28
+ from ..packages.logger.core.log_manager import LogManager
29
+ from ..utils.log_message_util import debug_messages, info_messages, error_messages
30
+ from ..models.schemas.settings_schema import SETTINGS_FILE_SCHEMA
31
+ import json
32
+ import requests
33
+ import jsonschema
34
+ import time
35
+ from ..enums.api_enum import ApiEnum
36
+ from ..enums.debug_category_enum import DebugCategoryEnum
37
+ from ..utils.debugger_service_util import send_debug_event_to_vwo
38
+
39
+
40
+ class SettingsManager:
41
+ _instance = None
42
+
43
+ def __init__(self, options):
44
+ self.sdk_key = options["sdk_key"]
45
+ self.account_id = options["account_id"]
46
+ self.expiry = Constants.SETTINGS_EXPIRY
47
+ self.network_timeout = Constants.SETTINGS_TIMEOUT
48
+ self.is_gateway_service_provided = False
49
+ self.settings_fetch_time = None # time taken to fetch the settings
50
+ self.is_settings_valid_on_init = False
51
+ self.is_proxy_url_provided = False
52
+ self.proxy_url = None
53
+ self.is_via_vwo = bool(options.get("is_via_vwo", False))
54
+ self.sdk_name = get_sdk_name(self.is_via_vwo)
55
+
56
+ # Hosts depend on init path: vwo.init() vs wingify.init()
57
+ self.settings_hostname = get_settings_hostname(self.is_via_vwo)
58
+ self.events_hostname = get_events_hostname(self.is_via_vwo)
59
+ self.protocol = Constants.HTTPS_PROTOCOL
60
+ self.port = None
61
+
62
+ # Backward-compatible alias — settings traffic uses settings_hostname
63
+ self.hostname = self.settings_hostname
64
+
65
+ if ("proxy_url" in options and options["proxy_url"] is not None ) and ("gateway_service" in options and "url" in options["gateway_service"]):
66
+ LogManager.get_instance().info(
67
+ info_messages.get("PROXY_AND_GATEWAY_SERVICE_PROVIDED").format()
68
+ )
69
+ self.is_gateway_service_provided = True
70
+
71
+
72
+ if ("proxy_url" in options and options["proxy_url"] is not None ) and not self.is_gateway_service_provided:
73
+ self.is_proxy_url_provided = True
74
+ parsed_url = requests.utils.urlparse(options["proxy_url"])
75
+
76
+ self.settings_hostname = parsed_url.hostname
77
+ self.events_hostname = parsed_url.hostname
78
+ self.hostname = self.settings_hostname
79
+ self.protocol = parsed_url.scheme
80
+ if parsed_url.port:
81
+ self.port = parsed_url.port
82
+
83
+ if "gateway_service" in options and "url" in options["gateway_service"]:
84
+ self.is_gateway_service_provided = True
85
+
86
+ # check if url start if https:// or http://
87
+ if options["gateway_service"]["url"].startswith("http://") or options[
88
+ "gateway_service"
89
+ ]["url"].startswith("https://"):
90
+ parsed_url = requests.utils.urlparse(options["gateway_service"]["url"])
91
+ elif "protocol" in options["gateway_service"] and options[
92
+ "gateway_service"
93
+ ]["protocol"] in ["http", "https"]:
94
+ parsed_url = requests.utils.urlparse(
95
+ options["gateway_service"]["protocol"]
96
+ + "://"
97
+ + options["gateway_service"]["url"]
98
+ )
99
+ else:
100
+ parsed_url = requests.utils.urlparse(
101
+ "https://" + options["gateway_service"]["url"]
102
+ )
103
+
104
+ self.settings_hostname = parsed_url.hostname
105
+ self.events_hostname = parsed_url.hostname
106
+ self.hostname = self.settings_hostname
107
+ self.protocol = parsed_url.scheme
108
+ if parsed_url.port:
109
+ self.port = parsed_url.port
110
+ elif "port" in options["gateway_service"]:
111
+ self.port = options["gateway_service"]["port"]
112
+
113
+ LogManager.get_instance().debug(
114
+ debug_messages.get("SERVICE_INITIALIZED").format(service="Settings Manager")
115
+ )
116
+ SettingsManager._instance = self
117
+
118
+ @classmethod
119
+ def get_instance(cls):
120
+ return cls._instance
121
+
122
+ def get_settings_hostname(self):
123
+ """Host used for settings, pull, location, and gateway requests."""
124
+ return self.settings_hostname
125
+
126
+ def get_events_hostname(self):
127
+ """Host used for event and batch-event requests."""
128
+ return self.events_hostname
129
+
130
+ def is_on_platform_host(self) -> bool:
131
+ """
132
+ True when requests target the baked-in platform host (not a custom proxy/gateway).
133
+ Used to decide whether segmentation should call the gateway service.
134
+ """
135
+ host = self.settings_hostname or ""
136
+ return (
137
+ Constants.VWO_HOST_NAME in host
138
+ or Constants.WINGIFY_SETTINGS_HOST_NAME in host
139
+ or Constants.WINGIFY_COLLECTION_HOST_NAME in host
140
+ )
141
+
142
+ def get_sdk_name(self):
143
+ return self.sdk_name
144
+
145
+ def get_account_id(self):
146
+ return self.account_id
147
+
148
+ def get_sdk_key(self):
149
+ return self.sdk_key
150
+
151
+ def fetch_settings_and_cache_in_storage(self, is_via_webhook=False):
152
+ try:
153
+ settings = self.fetch_settings(is_via_webhook)
154
+ # Simulate storing settings in a cache (memory, file, etc.)
155
+ # For demonstration, we'll skip actual caching
156
+ return settings
157
+ except Exception as err:
158
+ LogManager.get_instance().error(
159
+ error_messages.get("SETTINGS_FETCH_ERROR").format(err=str(err))
160
+ )
161
+ return None
162
+
163
+
164
+ def get_settings_path(self) -> Dict[str, Any]:
165
+ path = {
166
+ "i": self.sdk_key, # Inject API key
167
+ "r": random.random(), # Random number for cache busting
168
+ "a": self.account_id, # Account ID
169
+ }
170
+ return path
171
+
172
+ def fetch_settings(self, is_via_webhook=False, api_name=ApiEnum.INIT.value):
173
+ if not self.sdk_key or not self.account_id:
174
+ raise ValueError(
175
+ "sdk_key is required for fetching account settings. Aborting!"
176
+ )
177
+
178
+ network_instance = NetworkManager.get_instance()
179
+ options = self.get_settings_path()
180
+ options["platform"] = "server"
181
+ options["api-version"] = 1
182
+ options["sn"] = self.sdk_name
183
+ options["sv"] = Constants.SDK_VERSION
184
+
185
+ if not network_instance.get_config().get_development_mode():
186
+ options["s"] = "prod"
187
+
188
+ endpoint = (
189
+ Constants.SETTINGS_ENDPOINT
190
+ if not is_via_webhook
191
+ else Constants.WEBHOOK_SETTINTS_ENDPOINT
192
+ )
193
+ # Start timer for settings fetch
194
+ settings_fetch_start_time = time.time() * 1000 # Convert to milliseconds
195
+ response = None
196
+ try:
197
+ request = RequestModel(
198
+ self.settings_hostname,
199
+ "GET",
200
+ endpoint,
201
+ options,
202
+ None,
203
+ None,
204
+ self.protocol,
205
+ self.port,
206
+ )
207
+ request.set_timeout(self.network_timeout)
208
+ response = network_instance.get(request)
209
+ response_data = response.get_data()
210
+
211
+ if response.get_total_attempts() > 0 or response.status_code == 400:
212
+ lt = LogLevelEnum.INFO.value
213
+ debug_category = DebugCategoryEnum.RETRY.value
214
+ msg_t = Constants.NETWORK_CALL_SUCCESS_WITH_RETRIES
215
+ msg = info_messages.get(msg_t).format(extraData=endpoint, attempts=response.get_total_attempts(), err=response.get_error())
216
+
217
+ if response.status_code != 200:
218
+ lt = LogLevelEnum.ERROR.value
219
+ debug_category = DebugCategoryEnum.NETWORK.value
220
+ msg_t = Constants.NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES
221
+ msg = error_messages.get(msg_t).format(extraData=endpoint, attempts=response.get_total_attempts(), err=response.get_error())
222
+
223
+ debug_event_props = {
224
+ "cg": debug_category,
225
+ "lt": lt,
226
+ "msg_t": msg_t,
227
+ "msg": msg,
228
+ "an": ApiEnum.UPDATE_SETTINGS.value if is_via_webhook else api_name
229
+ }
230
+ send_debug_event_to_vwo(debug_event_props)
231
+
232
+ # Calculate settings fetch time
233
+ self.settings_fetch_time = int((time.time() * 1000) - settings_fetch_start_time)
234
+ return response_data
235
+
236
+ except Exception as err:
237
+ debug_event_props = {
238
+ "cg": DebugCategoryEnum.NETWORK.value,
239
+ "lt": LogLevelEnum.ERROR.value,
240
+ "msg_t": Constants.NETWORK_CALL_FAILURE_AFTER_MAX_RETRIES,
241
+ "msg": error_messages.get(msg_t).format(extraData=endpoint, attempts=0, err=str(err)),
242
+ "an": ApiEnum.UPDATE_SETTINGS.value if is_via_webhook else api_name
243
+ }
244
+ send_debug_event_to_vwo(debug_event_props)
245
+ raise err
246
+
247
+ def get_settings(self, force_fetch=False):
248
+ """
249
+ Get the settings from the cache or fetch them from the server.
250
+ :param force_fetch: Whether to force fetch the settings from the server.
251
+ :return: The settings.
252
+ """
253
+ if force_fetch:
254
+ return self.fetch_settings_and_cache_in_storage(True)
255
+ else:
256
+ # Simulate fetching settings from a cache
257
+ # For demonstration, we'll skip actual caching
258
+ fetched_settings = self.fetch_settings_and_cache_in_storage()
259
+ if self.is_settings_valid(fetched_settings):
260
+ self.is_settings_valid_on_init = True
261
+ LogManager.get_instance().info(
262
+ info_messages.get("SETTINGS_FETCH_SUCCESS").format()
263
+ )
264
+ return fetched_settings
265
+ else:
266
+ LogManager.get_instance().error(
267
+ error_messages.get("INVALID_SETTINGS_SCHEMA")
268
+ )
269
+ return {}
270
+
271
+ @staticmethod
272
+ def is_settings_valid(settings):
273
+ try:
274
+ # Attempt to load the settings as JSON if it's in string format
275
+ if isinstance(settings, str):
276
+ settings_file = json.loads(settings)
277
+ else:
278
+ settings_file = settings
279
+ except json.JSONDecodeError:
280
+ return False
281
+
282
+ # Validate the loaded JSON data against the schema
283
+ validator = jsonschema.Draft7Validator(SETTINGS_FILE_SCHEMA)
284
+ errors = sorted(validator.iter_errors(settings_file), key=lambda e: e.path)
285
+
286
+ if errors:
287
+ for error in errors:
288
+ error_path = " -> ".join([str(p) for p in error.path])
289
+ # print(f"Error at {error_path}: {error.message}")
290
+ return False
291
+ else:
292
+ # print("Validation succeeded")
293
+ return True
@@ -0,0 +1,58 @@
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.user.context_model import ContextModel
17
+ from typing import Any, Dict
18
+ from ..enums.storage_enum import StorageEnum
19
+ from ..packages.storage.storage import Storage
20
+ from ..utils.data_type_util import is_null, is_undefined
21
+ from ..packages.logger.core.log_manager import LogManager
22
+ from ..utils.log_message_util import error_messages
23
+ from ..enums.api_enum import ApiEnum
24
+
25
+
26
+ class StorageService:
27
+ def __init__(self):
28
+ self.storage_data: Dict[str, Any] = {}
29
+
30
+ def get_data_in_storage(
31
+ self, feature_key: Any, context: ContextModel
32
+ ) -> Dict[Any, Any]:
33
+ storage_instance = Storage.get_instance().get_connector()
34
+
35
+ if is_null(storage_instance) or is_undefined(storage_instance):
36
+ return {"status": StorageEnum.STORAGE_UNDEFINED.value}
37
+
38
+ try:
39
+ data = storage_instance.get(feature_key, context.get_id())
40
+ if data is None:
41
+ return {"status": StorageEnum.NO_DATA_FOUND.value}
42
+ return data
43
+ except Exception as err:
44
+ LogManager.get_instance().error_log("ERROR_READING_STORED_DATA_IN_STORAGE", data={"err": str(err)}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": context.get_vwo_uuid(), "sId": context.get_session_id()})
45
+ return {"status": StorageEnum.NO_DATA_FOUND.value}
46
+
47
+ def set_data_in_storage(self, data: Dict[Any, Any], context: ContextModel) -> bool:
48
+ storage_instance = Storage.get_instance().get_connector()
49
+
50
+ if is_null(storage_instance) or is_undefined(storage_instance):
51
+ return False
52
+
53
+ try:
54
+ storage_instance.set(data)
55
+ return True
56
+ except Exception as err:
57
+ LogManager.get_instance().error_log("ERROR_STORING_DATA_IN_STORAGE", data={"err": str(err)}, debug_data={"an": ApiEnum.GET_FLAG.value, "uuid": context.get_vwo_uuid(), "sId": context.get_session_id()})
58
+ return False
@@ -0,0 +1,51 @@
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 Optional
17
+
18
+
19
+ class UrlService:
20
+ def __init__(self, collection_prefix=None):
21
+ """
22
+ Initializes the UrlService with an optional collection_prefix.
23
+ If provided, this value is set after validation.
24
+
25
+ :param collection_prefix: Optional prefix for URL collections.
26
+ """
27
+ if self._is_valid_string(collection_prefix):
28
+ UrlService.collection_prefix = collection_prefix
29
+ else:
30
+ UrlService.collection_prefix = None
31
+
32
+ @staticmethod
33
+ def _is_valid_string(value):
34
+ """
35
+ Validates if the provided value is a valid string.
36
+
37
+ :param value: The value to validate.
38
+ :return: True if valid string, False otherwise.
39
+ """
40
+ return isinstance(value, str) and bool(value.strip())
41
+
42
+ @staticmethod
43
+ def get_endpoint_with_collection_prefix(endpoint: str, is_gateway_service: bool = False):
44
+ """
45
+ Retrieves the endpoint with collection prefix.
46
+ """
47
+ if is_gateway_service:
48
+ return f"{endpoint}"
49
+ elif hasattr(UrlService, "collection_prefix") and UrlService.collection_prefix:
50
+ return f"/{UrlService.collection_prefix}{endpoint}"
51
+ return endpoint
@@ -0,0 +1,13 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,108 @@
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
17
+ import json
18
+
19
+ from ..enums.url_enum import UrlEnum
20
+ from ..services.settings_manager import SettingsManager
21
+ from ..utils.log_message_util import error_messages
22
+ from ..models.Alias import Alias
23
+ from ..models.AliasSetResponse import AliasSetResponse
24
+ from ..constants.Constants import Constants
25
+ from ..utils.gateway_service_util import get_from_gateway_service, post_to_gateway_service
26
+ from ..models.user.context_model import ContextModel
27
+
28
+ def get_alias(context: ContextModel) -> str:
29
+ """
30
+ Get the alias for the given user ID.
31
+
32
+ :param context: The context to get the alias for.
33
+ :return: The alias for the given user ID.
34
+ """
35
+ params: Dict[str, Any] = {
36
+ "accountId": str(SettingsManager.get_instance().get_account_id()),
37
+ "sdkKey": SettingsManager.get_instance().get_sdk_key(),
38
+ }
39
+
40
+ # gateway expects JSON array for userId
41
+ user_id_json = json.dumps([context.get_id()])
42
+ params[Constants.KEY_USER_ID] = user_id_json
43
+
44
+ response = get_from_gateway_service(params, UrlEnum.GET_ALIAS.value, context)
45
+ if not response:
46
+ raise RuntimeError(
47
+ error_messages.get("ERROR_GETTING_ALIAS").format(userId=context.get_id(), err="Response is null")
48
+ )
49
+
50
+ try:
51
+ data_list: List[Dict[str, Any]] = json.loads(response) if isinstance(response, str) else response
52
+ except Exception as exc:
53
+ raise RuntimeError(
54
+ error_messages.get("ERROR_GETTING_ALIAS").format(userId=context.get_id(), err="Invalid JSON response")
55
+ ) from exc
56
+
57
+ alias_objects = [Alias(item) for item in data_list or []]
58
+ for item in alias_objects:
59
+ if item.get_alias() == context.get_id():
60
+ return item.get_user_id() or context.get_id()
61
+
62
+ return context.get_id()
63
+
64
+
65
+ def set_alias(user_id: str, alias_id: str) -> bool:
66
+ """
67
+ Set the alias for the given user ID.
68
+
69
+ :param user_id: The user ID to set the alias for.
70
+ :param alias_id: The alias ID to set for the given user ID.
71
+ :return: True if the alias is set successfully, False otherwise.
72
+ """
73
+ params: Dict[str, Any] = {
74
+ "accountId": str(SettingsManager.get_instance().get_account_id()),
75
+ "sdkKey": SettingsManager.get_instance().get_sdk_key(),
76
+ Constants.KEY_USER_ID: user_id,
77
+ Constants.KEY_ALIAS_ID: alias_id,
78
+ }
79
+
80
+ payload: Dict[str, Any] = {Constants.KEY_USER_ID: user_id, Constants.KEY_ALIAS_ID: alias_id}
81
+
82
+ response = post_to_gateway_service(params, payload, UrlEnum.SET_ALIAS.value)
83
+ if not response:
84
+ raise RuntimeError(error_messages.get("ERROR_SETTING_ALIAS").format(userId=user_id))
85
+
86
+ try:
87
+ data = json.loads(response) if isinstance(response, str) else response
88
+ except Exception as exc:
89
+ raise RuntimeError(error_messages.get("ERROR_SETTING_ALIAS").format(userId=user_id)) from exc
90
+
91
+ alias_set_response = AliasSetResponse(data)
92
+ if alias_set_response.get_is_alias_set():
93
+ return True
94
+
95
+ raise RuntimeError(error_messages.get("ERROR_SETTING_ALIAS").format(userId=user_id))
96
+
97
+ def get_alias_user_id(context: ContextModel) -> str:
98
+ """
99
+ Get the user id from the gateway service when aliasing is enabled.
100
+
101
+ :param context: The context to get the user id from.
102
+ :return: The resolved user id (alias mapping applied if available).
103
+ :raises RuntimeError: If gateway service is not provided when aliasing is enabled.
104
+ """
105
+ settings = SettingsManager.get_instance()
106
+ if settings and settings.is_gateway_service_provided:
107
+ return get_alias(context)
108
+ raise RuntimeError("Valid Gateway service is required when aliasing is enabled")
@@ -0,0 +1,26 @@
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
+ """Runtime brand flag set during init."""
16
+
17
+ _is_via_vwo = False
18
+
19
+
20
+ def set_is_via_vwo(is_via_vwo: bool) -> None:
21
+ global _is_via_vwo
22
+ _is_via_vwo = bool(is_via_vwo)
23
+
24
+
25
+ def get_is_via_vwo() -> bool:
26
+ return _is_via_vwo
@@ -0,0 +1,37 @@
1
+ # Copyright 2024-2026 Wingify Software Pvt. Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Brand-specific runtime values"""
16
+
17
+ from wingify.constants.Constants import Constants
18
+
19
+
20
+ def get_brand(is_via_vwo: bool) -> str:
21
+ return Constants.VWO_BRAND_DISPLAY_NAME if is_via_vwo else Constants.WINGIFY_BRAND_DISPLAY_NAME
22
+
23
+
24
+ def get_log_prefix(is_via_vwo: bool) -> str:
25
+ return Constants.VWO_LOG_PREFIX if is_via_vwo else Constants.WINGIFY_LOG_PREFIX
26
+
27
+
28
+ def get_sdk_name(is_via_vwo: bool) -> str:
29
+ return Constants.VWO_SDK_NAME if is_via_vwo else Constants.WINGIFY_SDK_NAME
30
+
31
+
32
+ def get_settings_hostname(is_via_vwo: bool) -> str:
33
+ return Constants.VWO_HOST_NAME if is_via_vwo else Constants.WINGIFY_SETTINGS_HOST_NAME
34
+
35
+
36
+ def get_events_hostname(is_via_vwo: bool) -> str:
37
+ return Constants.VWO_HOST_NAME if is_via_vwo else Constants.WINGIFY_COLLECTION_HOST_NAME