@ductape/sdk 0.0.4-v3 → 0.0.4-v30

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 (169) hide show
  1. package/dist/api/services/appApi.service.d.ts +2 -2
  2. package/dist/api/services/appApi.service.js +1 -2
  3. package/dist/api/services/appApi.service.js.map +1 -1
  4. package/dist/api/services/pricingApi.service.d.ts +10 -0
  5. package/dist/api/services/pricingApi.service.js +34 -0
  6. package/dist/api/services/pricingApi.service.js.map +1 -0
  7. package/dist/api/services/processorApi.service.d.ts +12 -2
  8. package/dist/api/services/processorApi.service.js +12 -2
  9. package/dist/api/services/processorApi.service.js.map +1 -1
  10. package/dist/api/services/productsApi.service.d.ts +5 -1
  11. package/dist/api/services/productsApi.service.js +22 -0
  12. package/dist/api/services/productsApi.service.js.map +1 -1
  13. package/dist/api/services/userApi.service.js +1 -0
  14. package/dist/api/services/userApi.service.js.map +1 -1
  15. package/dist/api/services/workspaceApi.service.js +1 -0
  16. package/dist/api/services/workspaceApi.service.js.map +1 -1
  17. package/dist/api/urls.d.ts +6 -1
  18. package/dist/api/urls.js +12 -2
  19. package/dist/api/urls.js.map +1 -1
  20. package/dist/api/utils/strings.utils.d.ts +2 -0
  21. package/dist/api/utils/strings.utils.js +14 -0
  22. package/dist/api/utils/strings.utils.js.map +1 -1
  23. package/dist/apps/services/app.service.d.ts +8 -1
  24. package/dist/apps/services/app.service.js +174 -25
  25. package/dist/apps/services/app.service.js.map +1 -1
  26. package/dist/apps/validators/joi-validators/create.appAction.validator.d.ts +1 -2
  27. package/dist/apps/validators/joi-validators/create.appAction.validator.js +21 -2
  28. package/dist/apps/validators/joi-validators/create.appAction.validator.js.map +1 -1
  29. package/dist/apps/validators/joi-validators/update.appAction.validator.js +11 -1
  30. package/dist/apps/validators/joi-validators/update.appAction.validator.js.map +1 -1
  31. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.d.ts +1 -1
  32. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js +34 -1
  33. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js.map +1 -1
  34. package/dist/clients/apps.client.js +1 -1
  35. package/dist/clients/apps.client.js.map +1 -1
  36. package/dist/clients/pricing.client.d.ts +3 -0
  37. package/dist/clients/pricing.client.js +33 -0
  38. package/dist/clients/pricing.client.js.map +1 -0
  39. package/dist/imports/imports.service.d.ts +3 -3
  40. package/dist/imports/imports.service.js +7 -7
  41. package/dist/imports/imports.service.js.map +1 -1
  42. package/dist/imports/imports.types.d.ts +8 -0
  43. package/dist/imports/repos/openApi.repo.d.ts +1 -2
  44. package/dist/imports/repos/openApi.repo.js +43 -71
  45. package/dist/imports/repos/openApi.repo.js.map +1 -1
  46. package/dist/imports/repos/postmanV21.repo.d.ts +1 -1
  47. package/dist/imports/repos/postmanV21.repo.js +29 -2
  48. package/dist/imports/repos/postmanV21.repo.js.map +1 -1
  49. package/dist/index.d.ts +965 -47
  50. package/dist/index.js +924 -81
  51. package/dist/index.js.map +1 -1
  52. package/dist/inputs/inputs.service.js +2 -2
  53. package/dist/inputs/inputs.service.js.map +1 -1
  54. package/dist/inputs/utils/inputs.utils.create.js +1 -1
  55. package/dist/inputs/utils/inputs.utils.create.js.map +1 -1
  56. package/dist/logs/logs.service.js +1 -0
  57. package/dist/logs/logs.service.js.map +1 -1
  58. package/dist/logs/logs.types.d.ts +5 -0
  59. package/dist/logs/logs.types.js.map +1 -1
  60. package/dist/parsers/index.d.ts +3 -0
  61. package/dist/parsers/index.js +27 -0
  62. package/dist/parsers/index.js.map +1 -0
  63. package/dist/parsers/pipelines/postman.pipelines.d.ts +15 -0
  64. package/dist/parsers/pipelines/postman.pipelines.js +103 -0
  65. package/dist/parsers/pipelines/postman.pipelines.js.map +1 -0
  66. package/dist/parsers/types/postman.types.d.ts +200 -0
  67. package/dist/parsers/types/postman.types.js +3 -0
  68. package/dist/parsers/types/postman.types.js.map +1 -0
  69. package/dist/parsers/utils/postman.utils.d.ts +12 -0
  70. package/dist/parsers/utils/postman.utils.js +116 -0
  71. package/dist/parsers/utils/postman.utils.js.map +1 -0
  72. package/dist/parsers/validators/postman-auth.validators.d.ts +10 -0
  73. package/dist/parsers/validators/postman-auth.validators.js +127 -0
  74. package/dist/parsers/validators/postman-auth.validators.js.map +1 -0
  75. package/dist/parsers/validators/postman-request.validators.d.ts +13 -0
  76. package/dist/parsers/validators/postman-request.validators.js +139 -0
  77. package/dist/parsers/validators/postman-request.validators.js.map +1 -0
  78. package/dist/parsers/validators/postman-response.validators.d.ts +13 -0
  79. package/dist/parsers/validators/postman-response.validators.js +150 -0
  80. package/dist/parsers/validators/postman-response.validators.js.map +1 -0
  81. package/dist/parsers/validators/postman-variable.validators.d.ts +14 -0
  82. package/dist/parsers/validators/postman-variable.validators.js +163 -0
  83. package/dist/parsers/validators/postman-variable.validators.js.map +1 -0
  84. package/dist/pricing/pricing.repo.d.ts +0 -0
  85. package/dist/pricing/pricing.repo.js +1 -0
  86. package/dist/pricing/pricing.repo.js.map +1 -0
  87. package/dist/pricing/pricing.service.d.ts +24 -0
  88. package/dist/pricing/pricing.service.js +51 -0
  89. package/dist/pricing/pricing.service.js.map +1 -0
  90. package/dist/pricing/pricing.types.d.ts +76 -0
  91. package/dist/pricing/pricing.types.js +21 -0
  92. package/dist/pricing/pricing.types.js.map +1 -0
  93. package/dist/pricing/utils/string.utils.d.ts +1 -0
  94. package/dist/pricing/utils/string.utils.js +9 -0
  95. package/dist/pricing/utils/string.utils.js.map +1 -0
  96. package/dist/processor/repos/sms.repo.d.ts +4 -4
  97. package/dist/processor/repos/sms.repo.js +23 -10
  98. package/dist/processor/repos/sms.repo.js.map +1 -1
  99. package/dist/processor/services/processor.service.d.ts +36 -5
  100. package/dist/processor/services/processor.service.js +568 -201
  101. package/dist/processor/services/processor.service.js.map +1 -1
  102. package/dist/processor/services/request.service.d.ts +36 -0
  103. package/dist/processor/services/request.service.js +304 -0
  104. package/dist/processor/services/request.service.js.map +1 -0
  105. package/dist/processor/types/request.types.d.ts +14 -0
  106. package/dist/processor/types/request.types.js +3 -0
  107. package/dist/processor/types/request.types.js.map +1 -0
  108. package/dist/processor/utils/processor.utils.d.ts +3 -0
  109. package/dist/processor/utils/processor.utils.js +88 -5
  110. package/dist/processor/utils/processor.utils.js.map +1 -1
  111. package/dist/processor/utils/request.utils.d.ts +20 -0
  112. package/dist/processor/utils/request.utils.js +113 -0
  113. package/dist/processor/utils/request.utils.js.map +1 -0
  114. package/dist/processor/utils/storage.util.js +54 -40
  115. package/dist/processor/utils/storage.util.js.map +1 -1
  116. package/dist/products/services/products.service.d.ts +20 -7
  117. package/dist/products/services/products.service.js +269 -43
  118. package/dist/products/services/products.service.js.map +1 -1
  119. package/dist/products/utils/string.utils.d.ts +1 -1
  120. package/dist/products/utils/string.utils.js +14 -2
  121. package/dist/products/utils/string.utils.js.map +1 -1
  122. package/dist/products/validators/index.d.ts +2 -1
  123. package/dist/products/validators/index.js +3 -1
  124. package/dist/products/validators/index.js.map +1 -1
  125. package/dist/products/validators/joi-validators/create.productEnv.validator.js +1 -0
  126. package/dist/products/validators/joi-validators/create.productEnv.validator.js.map +1 -1
  127. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.d.ts +4 -0
  128. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js +58 -0
  129. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js.map +1 -0
  130. package/dist/products/validators/joi-validators/create.userAuth.validator.js +1 -0
  131. package/dist/products/validators/joi-validators/create.userAuth.validator.js.map +1 -1
  132. package/dist/products/validators/joi-validators/update.dataValue.validator.js +1 -0
  133. package/dist/products/validators/joi-validators/update.dataValue.validator.js.map +1 -1
  134. package/dist/products/validators/joi-validators/update.productEnv.validator.js +3 -0
  135. package/dist/products/validators/joi-validators/update.productEnv.validator.js.map +1 -1
  136. package/dist/products/validators/joi-validators/update.userAuth.validator.js +1 -0
  137. package/dist/products/validators/joi-validators/update.userAuth.validator.js.map +1 -1
  138. package/dist/test/test.health.d.ts +1 -0
  139. package/dist/test/test.health.js +49 -0
  140. package/dist/test/test.health.js.map +1 -0
  141. package/dist/test/test.import.js +51 -4
  142. package/dist/test/test.import.js.map +1 -1
  143. package/dist/test/test.imports.js +22 -7
  144. package/dist/test/test.imports.js.map +1 -1
  145. package/dist/test/test.processor.js +32 -115
  146. package/dist/test/test.processor.js.map +1 -1
  147. package/dist/test/test.products.d.ts +1 -0
  148. package/dist/test/test.products.js +49 -0
  149. package/dist/test/test.products.js.map +1 -0
  150. package/dist/types/appBuilder.types.d.ts +4 -11
  151. package/dist/types/enums.d.ts +3 -1
  152. package/dist/types/enums.js +2 -0
  153. package/dist/types/enums.js.map +1 -1
  154. package/dist/types/index.types.d.ts +4 -0
  155. package/dist/types/pricing.types.d.ts +4 -0
  156. package/dist/types/pricing.types.js +3 -0
  157. package/dist/types/pricing.types.js.map +1 -0
  158. package/dist/types/processor.types.d.ts +66 -9
  159. package/dist/types/processor.types.js.map +1 -1
  160. package/dist/types/productsBuilder.types.d.ts +52 -5
  161. package/dist/types/productsBuilder.types.js +9 -1
  162. package/dist/types/productsBuilder.types.js.map +1 -1
  163. package/dist/types/request-tracker.interface.d.ts +0 -0
  164. package/dist/types/request-tracker.interface.js +1 -0
  165. package/dist/types/request-tracker.interface.js.map +1 -0
  166. package/dist/utils/constants.d.ts +1 -0
  167. package/dist/utils/constants.js +5 -0
  168. package/dist/utils/constants.js.map +1 -0
  169. package/package.json +14 -3
@@ -69,6 +69,9 @@ const postgres_repo_1 = require("../repos/postgres.repo");
69
69
  const storage_util_1 = require("../utils/storage.util");
70
70
  const sms_repo_1 = require("../repos/sms.repo");
71
71
  const quota_service_1 = __importDefault(require("./quota.service"));
72
+ const pricing_service_1 = __importDefault(require("../../pricing/pricing.service"));
73
+ const request_utils_1 = require("../utils/request.utils");
74
+ const request_service_1 = __importDefault(require("./request.service"));
72
75
  async function loadBrokerService() {
73
76
  if (typeof window === 'undefined') {
74
77
  const { createBrokerService } = await Promise.resolve().then(() => __importStar(require('./messagebrokers')));
@@ -77,14 +80,14 @@ async function loadBrokerService() {
77
80
  return null;
78
81
  }
79
82
  async function loadJWT() {
80
- if (typeof window === undefined) {
83
+ if (typeof window === 'undefined') {
81
84
  const JWT = await Promise.resolve().then(() => __importStar(require("jsonwebtoken")));
82
85
  return JWT;
83
86
  }
84
87
  return null;
85
88
  }
86
89
  class ProcessorService {
87
- constructor({ workspace_id, public_key, user_id, token, env_type, redis_client }) {
90
+ constructor({ workspace_id, public_key, user_id, token, env_type, redis_client, queues }) {
88
91
  this.workspace_id = workspace_id;
89
92
  this.public_key = public_key;
90
93
  this.user_id = user_id;
@@ -98,6 +101,14 @@ class ProcessorService {
98
101
  env_type,
99
102
  redis_client
100
103
  });
104
+ this.pricingService = new pricing_service_1.default({
105
+ workspace_id,
106
+ public_key,
107
+ user_id,
108
+ token,
109
+ env_type,
110
+ redis_client,
111
+ });
101
112
  this.inputService = new inputs_service_1.default();
102
113
  this.requestTime = 0;
103
114
  this.totalRequests = 0;
@@ -108,10 +119,91 @@ class ProcessorService {
108
119
  skipped: [],
109
120
  };
110
121
  this.apps = [];
122
+ this.requestTrackerService = request_service_1.default.getInstance(redis_client);
111
123
  this.processorApiService = new processorApi_service_1.ProcessorApiService(env_type);
112
124
  this.environment = env_type;
113
- if (redis_client) {
125
+ if (redis_client && this.productTag) {
114
126
  this.redisClient = redis_client;
127
+ // Start healthcheck workers automatically
128
+ this.startHealthcheckWorkers();
129
+ }
130
+ if (queues) {
131
+ this.queues = queues;
132
+ }
133
+ }
134
+ /**
135
+ * Start healthcheck workers for all products/environments after Redis is connected.
136
+ * This is called automatically in the constructor if redisClient is present.
137
+ */
138
+ async startHealthcheckWorkers() {
139
+ // Fetch all products (or the current product if context is single-tenant)
140
+ // For demo, we use the current product only
141
+ await this.productBuilderService.initializeProductByTag(this.productTag);
142
+ const product = this.productBuilderService.fetchProduct();
143
+ const healthchecks = product.healthchecks || [];
144
+ const privateKey = product.private_key;
145
+ for (const healthcheck of healthchecks) {
146
+ for (const env of healthcheck.envs) {
147
+ // Each env gets its own worker (setInterval)
148
+ const interval = healthcheck.interval || 60000; // default 60s
149
+ setInterval(async () => {
150
+ try {
151
+ // Decrypt input for this env
152
+ let decryptedInput = env.input;
153
+ if (typeof decryptedInput === 'string') {
154
+ decryptedInput = JSON.parse((0, processor_utils_1.decrypt)(decryptedInput, privateKey));
155
+ }
156
+ // Prepare action input
157
+ const actionInput = {
158
+ env: env.slug,
159
+ product: product.tag,
160
+ app: healthcheck.app,
161
+ input: decryptedInput,
162
+ event: healthcheck.event,
163
+ retries: healthcheck.retries || 0,
164
+ };
165
+ // Process the action
166
+ const result = await this.processAction(actionInput);
167
+ // Log result (success/failure)
168
+ this.logService.add(Object.assign(Object.assign({}, this.baseLogs), { message: `Healthcheck processed for ${healthcheck.tag} in env ${env.slug}`, data: { result }, status: types_1.LogEventStatus.SUCCESS }));
169
+ }
170
+ catch (e) {
171
+ this.logService.add(Object.assign(Object.assign({}, this.baseLogs), { message: `Healthcheck failed for ${healthcheck.tag} in env ${env.slug}`, data: { error: e.toString() }, status: types_1.LogEventStatus.FAIL }));
172
+ }
173
+ }, interval);
174
+ }
175
+ }
176
+ }
177
+ /**
178
+ * Manually trigger healthcheck processing for all healthchecks (can be called externally if needed)
179
+ */
180
+ async processAllHealthchecksForProduct(productTag) {
181
+ await this.productBuilderService.initializeProductByTag(productTag);
182
+ const product = this.productBuilderService.fetchProduct();
183
+ const healthchecks = product.healthchecks || [];
184
+ const privateKey = product.private_key;
185
+ for (const healthcheck of healthchecks) {
186
+ for (const env of healthcheck.envs) {
187
+ try {
188
+ let decryptedInput = env.input;
189
+ if (typeof decryptedInput === 'string') {
190
+ decryptedInput = JSON.parse((0, processor_utils_1.decrypt)(decryptedInput, privateKey));
191
+ }
192
+ const actionInput = {
193
+ env: env.slug,
194
+ product: product.tag,
195
+ app: healthcheck.app,
196
+ input: decryptedInput,
197
+ event: healthcheck.event,
198
+ retries: healthcheck.retries || 0,
199
+ };
200
+ const result = await this.processAction(actionInput);
201
+ this.logService.add(Object.assign(Object.assign({}, this.baseLogs), { message: `Manual healthcheck processed for ${healthcheck.tag} in env ${env.slug}`, data: { result }, status: types_1.LogEventStatus.SUCCESS }));
202
+ }
203
+ catch (e) {
204
+ this.logService.add(Object.assign(Object.assign({}, this.baseLogs), { message: `Manual healthcheck failed for ${healthcheck.tag} in env ${env.slug}`, data: { error: e.toString() }, status: types_1.LogEventStatus.FAIL }));
205
+ }
206
+ }
115
207
  }
116
208
  }
117
209
  async generateSession(payload) {
@@ -132,13 +224,27 @@ class ProcessorService {
132
224
  throw new Error(`Env with slug ${slug} does not exist`);
133
225
  }
134
226
  await this.inputService.validateInput(input, session.schema_data);
135
- const expiry = (0, processor_utils_1.calculateExpiry)(session.expiry, session.period);
227
+ const stages = (0, string_utils_1.extractStages)(session.selector);
228
+ // Convert stages to string[] for functions expecting string[]
229
+ const stringStages = stages.map(stage => String(stage));
230
+ const user = (0, processor_utils_1.extractSelectorValue)(data, stringStages, session.selector);
231
+ const expiry = (0, processor_utils_1.calculateJWTExpiry)(session.expiry, session.period);
232
+ const end_at = (0, processor_utils_1.calculateExpiry)(session.expiry, session.period);
136
233
  const JWT = await loadJWT();
137
234
  if (JWT) {
138
- const token = JWT.sign(JSON.stringify(Object.assign({ type: "token" }, data)), this.productBuilderService.fetchProduct().private_key, { expiresIn: expiry });
235
+ const session_id = (0, uuid_1.v4)();
236
+ const token = JWT.sign({ session: payload.tag, env: payload.env, session_id, data }, this.productBuilderService.fetchProduct().private_key, { expiresIn: expiry });
139
237
  const refreshToken = (0, processor_utils_1.encrypt)(JSON.stringify(data), this.productBuilderService.fetchProduct().private_key);
140
238
  // WRITE REFRESH TOKEN TO DATABASE... TO INVALIDATE DELETE FROM DATABASE
141
- await this.processorApiService.createRefreshToken({ product_tag, env: slug, refreshToken }, this.getUserAccess());
239
+ const details = {
240
+ identifier: user,
241
+ start_at: Date.now(),
242
+ end_at,
243
+ session_tag: tag,
244
+ data: (0, processor_utils_1.encrypt)(JSON.stringify(JSON.stringify(data)), this.productBuilderService.fetchProduct().private_key),
245
+ session_id
246
+ };
247
+ await this.processorApiService.createSessionInfo(Object.assign({ product_tag, env: slug, refreshToken }, details), this.getUserAccess());
142
248
  return {
143
249
  token,
144
250
  refreshToken,
@@ -152,6 +258,40 @@ class ProcessorService {
152
258
  throw e;
153
259
  }
154
260
  }
261
+ async refreshSession(payload) {
262
+ await this.productBuilderService.initializeProductByTag(payload.product);
263
+ // validate token validity
264
+ const { refreshToken } = payload, payloadData = __rest(payload, ["refreshToken"]);
265
+ const valid = await this.processorApiService.validateRefreshToken({ refreshToken, product: payload.product, env: payload.env }, this.getUserAccess());
266
+ if (valid) {
267
+ const data = JSON.parse((0, processor_utils_1.decrypt)(refreshToken, this.productBuilderService.fetchProduct().private_key));
268
+ return await this.generateSession(Object.assign(Object.assign({}, payloadData), { data }));
269
+ }
270
+ else {
271
+ throw new Error(`Invalid refresh token`);
272
+ }
273
+ }
274
+ async decryptSession(data) {
275
+ await this.productBuilderService.initializeProductByTag(data.product);
276
+ const JWT = await loadJWT();
277
+ if (!JWT) {
278
+ throw new Error(`Running in browser, token service not loaded.`);
279
+ }
280
+ try {
281
+ const res = await JWT.verify(data.token, this.productBuilderService.fetchProduct().private_key);
282
+ if (res.session !== data.tag) {
283
+ throw new Error(`Invalid token for session ${data.tag}`);
284
+ }
285
+ if (res.env !== data.env) {
286
+ throw new Error(`Invalid session env`);
287
+ }
288
+ return res.data;
289
+ }
290
+ catch (e) {
291
+ console.log(e);
292
+ throw new Error("Invalid/Expired token");
293
+ }
294
+ }
155
295
  async registerWebhook(data) {
156
296
  const { product: product_tag, access_tag, webhook_tag, envs } = data;
157
297
  await this.productBuilderService.initializeProductByTag(product_tag);
@@ -301,7 +441,6 @@ class ProcessorService {
301
441
  throw new Error(`Quota ${quota_tag} not found`);
302
442
  }
303
443
  this.logService.setFeatureId(this.quota._id);
304
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process quota initiated', data: Object.assign(Object.assign({}, data), { input: (0, processor_utils_1.anonymizeObject)(data.input) }), status: types_1.LogEventStatus.PROCESSING }));
305
444
  this.processEnv = this.fetchEnv(env, additional_logs);
306
445
  if (!this.processEnv.active) {
307
446
  throw new Error(`Environment ${data.env} is not active`);
@@ -311,6 +450,7 @@ class ProcessorService {
311
450
  this.validateJSONFeatureInput(input, quotaInput, additional_logs);
312
451
  // split processes
313
452
  //this.sequenceLevels = this.splitSequenceIntoLevels(sequence, additional_logs);
453
+ await this.logService.publish();
314
454
  return await this.runQuotaOptions(options, input, additional_logs);
315
455
  }
316
456
  catch (e) {
@@ -320,17 +460,25 @@ class ProcessorService {
320
460
  }
321
461
  }
322
462
  async runQuotaOptions(options, input, additional_logs) {
323
- const quotaManager = new quota_service_1.default(options, this.redisClient);
324
- const getNextProvider = quotaManager.getNextProvider();
325
- const quotaInput = await this.mapQuotaFallbackInput(getNextProvider.input, input, getNextProvider.app);
326
- return await this.processEvent({
327
- app: getNextProvider.app,
328
- type: getNextProvider.type,
329
- event: getNextProvider.event,
330
- input: quotaInput,
331
- retries: getNextProvider.retries,
332
- allow_fail: false
333
- });
463
+ try {
464
+ const quotaManager = new quota_service_1.default(options, this.redisClient);
465
+ const getNextProvider = quotaManager.getNextProvider();
466
+ const quotaInput = await this.mapQuotaFallbackInput(getNextProvider.input, input, getNextProvider.app);
467
+ const result = await this.processEvent({
468
+ app: getNextProvider.app,
469
+ type: getNextProvider.type,
470
+ event: getNextProvider.event,
471
+ input: quotaInput,
472
+ retries: getNextProvider.retries,
473
+ allow_fail: false
474
+ });
475
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process quota successful', successful_execution: true, data: { result: (0, processor_utils_1.anonymizeObject)(result) }, status: types_1.LogEventStatus.PROCESSING }));
476
+ return result;
477
+ }
478
+ catch (e) {
479
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process quota failed', failed_execution: true, data: { e }, status: types_1.LogEventStatus.PROCESSING }));
480
+ throw e;
481
+ }
334
482
  }
335
483
  async mapQuotaFallbackInput(providerInput, quotaInput, app) {
336
484
  if (Array.isArray(providerInput)) {
@@ -350,10 +498,14 @@ class ProcessorService {
350
498
  }
351
499
  async overrideQuotaFallbackInput(value, quotaInput, app) {
352
500
  if (value.startsWith('$Input{')) {
353
- return quotaInput[(0, string_utils_1.extractStages)(value)[0]];
501
+ const stages = (0, string_utils_1.extractStages)(value);
502
+ return quotaInput[String(stages[0])];
354
503
  }
355
504
  else if (value.startsWith('$Auth')) {
356
- return await this.generateAuthValue((0, string_utils_1.extractStages)(value), app, [], {});
505
+ const stages = (0, string_utils_1.extractStages)(value);
506
+ // Convert stages to string[] for functions expecting string[]
507
+ const stringStages = stages.map(stage => String(stage));
508
+ return await this.generateAuthValue(stringStages, app, [], {});
357
509
  }
358
510
  else if (value.startsWith('$')) {
359
511
  this.input = Object.assign(Object.assign({}, this.input), { input: quotaInput });
@@ -420,7 +572,6 @@ class ProcessorService {
420
572
  throw new Error(`Fallback "${fallback_tag}" not found`);
421
573
  }
422
574
  this.logService.setFeatureId(this.fallback._id);
423
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process fallback initiated', data: Object.assign(Object.assign({}, data), { input: (0, processor_utils_1.anonymizeObject)(data.input) }), status: types_1.LogEventStatus.PROCESSING }));
424
575
  this.processEnv = this.fetchEnv(env, additional_logs);
425
576
  if (!this.processEnv.active) {
426
577
  throw new Error(`Environment ${data.env} is not active`);
@@ -470,7 +621,6 @@ class ProcessorService {
470
621
  feature_id: this.feature._id,
471
622
  };
472
623
  this.logService.setFeatureId(this.feature._id);
473
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process feature initiated', data: Object.assign(Object.assign({}, data), { input: (0, processor_utils_1.anonymizeObject)(data.input) }), status: types_1.LogEventStatus.PROCESSING }));
474
624
  this.processEnv = this.fetchEnv(env, additional_logs);
475
625
  if (!this.processEnv.active) {
476
626
  throw new Error(`Environment ${data.env} is not active`);
@@ -502,13 +652,7 @@ class ProcessorService {
502
652
  }
503
653
  }
504
654
  async intializeProduct(additional_logs) {
505
- try {
506
- if (this.productTag) {
507
- await this.productBuilderService.initializeProductByTag(this.productTag); // validate product_exists
508
- }
509
- else {
510
- await this.productBuilderService.initializeProduct(this.productId);
511
- }
655
+ if (!this.logService) {
512
656
  this.logService = new logs_service_1.default({
513
657
  product_id: this.productId,
514
658
  workspace_id: this.workspace_id,
@@ -517,6 +661,14 @@ class ProcessorService {
517
661
  token: this.token,
518
662
  env_type: this.environment,
519
663
  });
664
+ }
665
+ try {
666
+ if (this.productTag) {
667
+ await this.productBuilderService.initializeProductByTag(this.productTag); // validate product_exists
668
+ }
669
+ else {
670
+ await this.productBuilderService.initializeProduct(this.productId);
671
+ }
520
672
  const { _id: product_id, workspace_id } = this.productBuilderService.fetchProduct();
521
673
  this.productId = product_id;
522
674
  if (workspace_id !== this.workspace_id) {
@@ -529,9 +681,34 @@ class ProcessorService {
529
681
  throw e;
530
682
  }
531
683
  }
684
+ async initializePricing(additional_logs, access_tag) {
685
+ if (!this.logService) {
686
+ this.logService = new logs_service_1.default({
687
+ product_id: this.productId,
688
+ workspace_id: this.workspace_id,
689
+ public_key: this.public_key,
690
+ user_id: this.user_id,
691
+ token: this.token,
692
+ env_type: this.environment,
693
+ });
694
+ }
695
+ try {
696
+ console.log(`Initializing pricing for access tag: ${access_tag}`);
697
+ const product_app = this.productBuilderService.fetchApp(access_tag); // validate app exists
698
+ console.log(`Found product app: ${JSON.stringify(product_app)}`);
699
+ const app = await this.productBuilderService.fetchThirdPartyAppByAccessTag(product_app.access_tag);
700
+ await this.pricingService.initializePricingByTag(product_app.pricing_tag, app._id);
701
+ const { pricing_tag } = this.pricingService.fetchPricing();
702
+ this.pricingTag = pricing_tag;
703
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Pricing initialize - success', data: { pricing_tag: this.pricingTag }, status: types_1.LogEventStatus.SUCCESS }));
704
+ }
705
+ catch (e) {
706
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Pricing initialize - failed', data: e, status: types_1.LogEventStatus.FAIL }));
707
+ throw e;
708
+ }
709
+ }
532
710
  fetchFeature(tag, additional_logs) {
533
711
  try {
534
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch feature - initiated', data: { tag }, status: types_1.LogEventStatus.PROCESSING }));
535
712
  const feature = this.productBuilderService.fetchFeature(tag); // validate feature exists
536
713
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch feature - success', data: { tag, feature }, status: types_1.LogEventStatus.SUCCESS }));
537
714
  return feature;
@@ -543,7 +720,6 @@ class ProcessorService {
543
720
  }
544
721
  fetchQuota(tag, additional_logs) {
545
722
  try {
546
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch quota - initiated', data: { tag }, status: types_1.LogEventStatus.PROCESSING }));
547
723
  const quota = this.productBuilderService.fetchQuota(tag); // validate feature exists
548
724
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch quota - success', data: { tag, quota }, status: types_1.LogEventStatus.SUCCESS }));
549
725
  return quota;
@@ -555,7 +731,6 @@ class ProcessorService {
555
731
  }
556
732
  fetchFallback(tag, additional_logs) {
557
733
  try {
558
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch fallback - initiated', data: { tag }, status: types_1.LogEventStatus.PROCESSING }));
559
734
  const fallback = this.productBuilderService.fetchFallback(tag); // validate feature exists
560
735
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch fallback - success', data: { tag, fallback }, status: types_1.LogEventStatus.SUCCESS }));
561
736
  return fallback;
@@ -567,7 +742,6 @@ class ProcessorService {
567
742
  }
568
743
  fetchEnv(env, additional_logs) {
569
744
  try {
570
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch environment - initiated', data: { slug: env }, status: types_1.LogEventStatus.PROCESSING }));
571
745
  const product_env = this.productBuilderService.fetchEnv(env); // validate env exists
572
746
  if (!product_env) {
573
747
  throw new Error(`Env ${env} not found`);
@@ -582,7 +756,6 @@ class ProcessorService {
582
756
  }
583
757
  validateJSONFeatureInput(input, feature_input, additional_logs) {
584
758
  try {
585
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Input validation - initiated', data: { input: (0, processor_utils_1.anonymizeObject)(input), feature_input }, status: types_1.LogEventStatus.PROCESSING }));
586
759
  (0, processor_utils_1.validateFeatureJSONInput)(input, feature_input);
587
760
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Input validation - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
588
761
  }
@@ -593,7 +766,6 @@ class ProcessorService {
593
766
  }
594
767
  async splitSequenceIntoLevels(data, additional_logs) {
595
768
  try {
596
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Split sequence - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
597
769
  const levels = {};
598
770
  const tagMap = new Map(data.map((seq) => [seq.tag, seq]));
599
771
  const assignedLevels = new Map();
@@ -630,7 +802,6 @@ class ProcessorService {
630
802
  }
631
803
  async processSequenceLevels(additional_logs) {
632
804
  try {
633
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process levels - initiated', data: { levels: this.sequenceLevels }, status: types_1.LogEventStatus.PROCESSING }));
634
805
  const levelEvents = {};
635
806
  Object.entries(this.sequenceLevels).forEach(([level, sequences]) => {
636
807
  levelEvents[parseInt(level)] = this.fetchLevelEvents(sequences, parseInt(level));
@@ -658,7 +829,6 @@ class ProcessorService {
658
829
  successful_feature_execution = true;
659
830
  }
660
831
  else if (this.processingFailure) {
661
- console.log("PROCESSING FAILURE", this.processingFailure);
662
832
  message = 'Process feature - processing';
663
833
  status = types_1.LogEventStatus.PROCESSING;
664
834
  successful_feature_execution = false;
@@ -674,7 +844,7 @@ class ProcessorService {
674
844
  return true;
675
845
  }
676
846
  catch (e) {
677
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process levels - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
847
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process sequence levels - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
678
848
  throw e;
679
849
  }
680
850
  }
@@ -702,7 +872,6 @@ class ProcessorService {
702
872
  const { failure } = this.processingOutput;
703
873
  const promises = failure.map((failed) => {
704
874
  if (failed.retries_left > 0 && new Date().getTime() > failed.retry_at) {
705
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Reprocess failed events - initiated', data: Object.assign({}, failed), status: types_1.LogEventStatus.PROCESSING }));
706
875
  return this.processEvent(failed.event); // process events should also take care of this.processingOutput
707
876
  }
708
877
  if (failed.retries_left === 0 && !failed.allow_fail) {
@@ -747,7 +916,6 @@ class ProcessorService {
747
916
  }
748
917
  fetchActionRequestDependents(input, additional_logs) {
749
918
  try {
750
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch request dependencies - initialized', data: input, status: types_1.LogEventStatus.PROCESSING }));
751
919
  const dependents = [];
752
920
  if (input.query) {
753
921
  dependents.push(...this.fetchDependents(input.query, additional_logs));
@@ -779,7 +947,6 @@ class ProcessorService {
779
947
  }
780
948
  fetchDependents(obj, additional_logs) {
781
949
  try {
782
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch dependents - initiated', data: obj, status: types_1.LogEventStatus.PROCESSING }));
783
950
  const dependants = [];
784
951
  for (const key in obj) {
785
952
  const value = obj[key];
@@ -790,8 +957,8 @@ class ProcessorService {
790
957
  if (values[i].startsWith('$Sequence')) {
791
958
  const stages = this.productBuilderService.extractStages(values[i]);
792
959
  dependants.push({
793
- sequence_tag: stages[0],
794
- event_tag: stages[1],
960
+ sequence_tag: String(stages[0]),
961
+ event_tag: String(stages[1]),
795
962
  });
796
963
  }
797
964
  else if (values[i].startsWith('$')) {
@@ -801,8 +968,8 @@ class ProcessorService {
801
968
  if (arg.startsWith('$Sequence')) {
802
969
  const stages = this.productBuilderService.extractStages(arg);
803
970
  dependants.push({
804
- sequence_tag: stages[0],
805
- event_tag: stages[1],
971
+ sequence_tag: String(stages[0]),
972
+ event_tag: String(stages[1]),
806
973
  });
807
974
  }
808
975
  });
@@ -821,7 +988,6 @@ class ProcessorService {
821
988
  return dependants;
822
989
  }
823
990
  catch (e) {
824
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch dependents - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
825
991
  throw e;
826
992
  }
827
993
  }
@@ -829,7 +995,7 @@ class ProcessorService {
829
995
  const dependants = [];
830
996
  if (value.startsWith('$Sequence')) {
831
997
  const stages = this.productBuilderService.extractStages(value);
832
- dependants.push({ sequence_tag: stages[0], event_tag: stages[1] });
998
+ dependants.push({ sequence_tag: String(stages[0]), event_tag: String(stages[1]) });
833
999
  }
834
1000
  else if (value.startsWith('$')) {
835
1001
  const funcArgs = (0, functions_utils_1.extractFunctionAndArgs)(value);
@@ -838,8 +1004,8 @@ class ProcessorService {
838
1004
  if (arg.startsWith('$Sequence')) {
839
1005
  const stages = this.productBuilderService.extractStages(arg);
840
1006
  dependants.push({
841
- sequence_tag: stages[0],
842
- event_tag: stages[1],
1007
+ sequence_tag: String(stages[0]),
1008
+ event_tag: String(stages[1]),
843
1009
  });
844
1010
  }
845
1011
  else {
@@ -855,7 +1021,6 @@ class ProcessorService {
855
1021
  }
856
1022
  async constructJSONDataPayloads(object, additional_logs, samples, event, loopIndex = 0) {
857
1023
  try {
858
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Construct JSON payloads - initiated', data: { object, samples }, status: types_1.LogEventStatus.PROCESSING }));
859
1024
  const payload = {};
860
1025
  const { body: actionBody, query: actionQuery, headers: actionHeaders, params: actionParams } = object;
861
1026
  if (actionBody) {
@@ -912,8 +1077,8 @@ class ProcessorService {
912
1077
  }
913
1078
  async generatePayload(obj, event, additional_logs, sample = [], index = {}, loopIndex = null) {
914
1079
  try {
915
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate payload - initiated', data: { obj, event, sample }, status: types_1.LogEventStatus.PROCESSING }));
916
1080
  const payload = {};
1081
+ console.log("Payload Construction", { obj, event, sample, index, loopIndex });
917
1082
  const keys = Object.keys(obj);
918
1083
  for (let i = 0; i < keys.length; i++) {
919
1084
  const key = keys[i];
@@ -959,22 +1124,32 @@ class ProcessorService {
959
1124
  const locatorFor$Index = (0, string_utils_1.validateAndLocateTag)(value);
960
1125
  if (value.startsWith('$Auth{') && value.endsWith('}')) {
961
1126
  // should only be allowed in apps
962
- return await this.generateAuthValue(stages, app, sample, additional_logs);
1127
+ // Convert stages to string[] for functions expecting string[]
1128
+ const stringStages = stages.map(stage => String(stage));
1129
+ return await this.generateAuthValue(stringStages, app, sample, additional_logs);
963
1130
  }
964
1131
  else if (value.startsWith('$Sequence{') && value.endsWith('}')) {
965
- return await this.generateSequenceValue(stages, locatorFor$Index, loopIndex); // pass
1132
+ // Convert stages to string[] for functions expecting string[]
1133
+ const stringStages = stages.map(stage => String(stage));
1134
+ return await this.generateSequenceValue(stringStages, locatorFor$Index, loopIndex); // pass
966
1135
  }
967
1136
  else if (value.startsWith('$Input{') && value.endsWith('}')) {
968
- return await this.generateInputValue(this.input.input, stages);
1137
+ // Convert stages to string[] for functions expecting string[]
1138
+ const stringStages = stages.map(stage => String(stage));
1139
+ return await this.generateInputValue(this.input.input, stringStages);
969
1140
  }
970
1141
  else if (value === '$Default') {
971
1142
  return await this.generateDefaultValue(sample, Object.assign(Object.assign({}, index), { key }));
972
1143
  }
973
1144
  else if (value.startsWith('$Variable{') && value.endsWith('}')) {
974
- return await this.generateVariableValue(stages);
1145
+ // Convert stages to string[] for functions expecting string[]
1146
+ const stringStages = stages.map(stage => String(stage));
1147
+ return await this.generateVariableValue(stringStages);
975
1148
  }
976
1149
  else if (value.startsWith('$Constant{') && value.endsWith('}')) {
977
- return await this.generateConstantValue(stages);
1150
+ // Convert stages to string[] for functions expecting string[]
1151
+ const stringStages = stages.map(stage => String(stage));
1152
+ return await this.generateConstantValue(stringStages);
978
1153
  }
979
1154
  else if (value.startsWith('$Size{') || value.startsWith('$Length{')) {
980
1155
  const { matchLength, matchSize } = (0, string_utils_1.checkLengthAndSizeMatches)(value);
@@ -1099,6 +1274,7 @@ class ProcessorService {
1099
1274
  const placeholdersStr = match[1];
1100
1275
  const separator = match[2];
1101
1276
  const placeHolders = placeholdersStr.split(',').map((data) => data.trim());
1277
+ console.log('placeHolders', { placeHolders, separator });
1102
1278
  const values = await Promise.all(placeHolders.map(async (holder) => {
1103
1279
  return await this.generateStringValues(holder, app, additional_logs, sample, index, key, loopIndex);
1104
1280
  }));
@@ -1417,6 +1593,7 @@ class ProcessorService {
1417
1593
  }
1418
1594
  async generateAuthValue(stages, app, sample, additional_logs) {
1419
1595
  try {
1596
+ console.log("Generate Auth Data", { stages, app, sample });
1420
1597
  let auth_data = await this.fetchAuthData(app, additional_logs); //TODO: should use stages[0]
1421
1598
  // take the app tag in index 0..
1422
1599
  if (!auth_data) {
@@ -1432,7 +1609,6 @@ class ProcessorService {
1432
1609
  }
1433
1610
  async fetchAuthData(app_tag, additional_logs) {
1434
1611
  try {
1435
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetching auth data - initiated', data: { app_tag, env: this.processEnv.slug }, status: types_1.LogEventStatus.PROCESSING }));
1436
1612
  const app = this.productBuilderService.fetchApp(app_tag);
1437
1613
  if (!app) {
1438
1614
  throw new Error(`App ${app_tag} not found in $Auth value`);
@@ -1444,6 +1620,7 @@ class ProcessorService {
1444
1620
  if (!env.auth) {
1445
1621
  throw new Error(`App ${app_tag} in auth needs to have a definition for auth in env: ${this.processEnv.slug}`);
1446
1622
  }
1623
+ console.log("Envroment", env.auth);
1447
1624
  let values = env.auth.values;
1448
1625
  if (!values) {
1449
1626
  // no auth values
@@ -1451,6 +1628,7 @@ class ProcessorService {
1451
1628
  }
1452
1629
  if (!env.auth.expiry || (env.auth.expiry && Date.now() > new Date(env.auth.expiry).getTime())) {
1453
1630
  // refresh
1631
+ console.log("REFRESH DATA", env, app_tag);
1454
1632
  values = await this.getAndStoreAuth(env, app_tag);
1455
1633
  }
1456
1634
  const decrypted = (0, processor_utils_1.decrypt)(values, this.productBuilderService.fetchProduct().private_key);
@@ -1563,7 +1741,18 @@ class ProcessorService {
1563
1741
  parent_tag: event.event,
1564
1742
  name: 'Process feature job',
1565
1743
  };
1566
- return this.runJob(event, additional_logs);
1744
+ const input = {
1745
+ env: event.env.slug,
1746
+ product: this.productTag,
1747
+ event: event.event,
1748
+ retries: event.retries,
1749
+ input: event.input,
1750
+ start_at: event.start_at || 0,
1751
+ cache: event.cache,
1752
+ session: this.input.session
1753
+ };
1754
+ // TODO: fix this
1755
+ return this.processJob(input, additional_logs);
1567
1756
  }
1568
1757
  }
1569
1758
  catch (e) {
@@ -1587,16 +1776,25 @@ class ProcessorService {
1587
1776
  }
1588
1777
  return output;
1589
1778
  }
1590
- runJob(event, additional_logs) {
1591
- throw new Error('Method not implemented.');
1779
+ async runJobs(job, additional_logs = {}) {
1780
+ if (job.name === types_1.FeatureEventTypes.ACTION) {
1781
+ await this.processAction(job.data);
1782
+ }
1592
1783
  }
1593
1784
  async processFailedAndWaiting() { }
1594
- async generateOutput(process_id) {
1595
- var _a, _b, _c, _d;
1785
+ async fetchResult(process_id) {
1596
1786
  const result = await this.processorApiService.fetchResult(process_id, this.getUserAccess());
1597
1787
  if (!result) {
1598
1788
  throw new Error(`Invalid process id ${process_id}`);
1599
1789
  }
1790
+ await this.productBuilderService.initializeProduct(result.product_id);
1791
+ result.result = JSON.parse((0, processor_utils_1.decrypt)(String(result.result), this.productBuilderService.fetchProduct().private_key));
1792
+ result.input = JSON.parse((0, processor_utils_1.decrypt)(String(result.input), this.productBuilderService.fetchProduct().private_key));
1793
+ return result;
1794
+ }
1795
+ async generateOutput(process_id) {
1796
+ var _a, _b, _c, _d;
1797
+ const result = await this.fetchResult(process_id);
1600
1798
  if (result.component === types_1.LogEventTypes.FEATURE) {
1601
1799
  const additional_logs = {
1602
1800
  parent_tag: result.input.tag,
@@ -1635,7 +1833,7 @@ class ProcessorService {
1635
1833
  }
1636
1834
  }
1637
1835
  async resumeProcess(process_id) {
1638
- const result = (await this.processorApiService.fetchResult(process_id, this.getUserAccess()));
1836
+ const result = await this.fetchResult(process_id);
1639
1837
  if (!result) {
1640
1838
  throw new Error(`Invalid process id ${process_id}`);
1641
1839
  }
@@ -1677,7 +1875,7 @@ class ProcessorService {
1677
1875
  }
1678
1876
  async replayProcess(process_id) {
1679
1877
  var _a, _b, _c;
1680
- const result = (await this.processorApiService.fetchResult(process_id, this.getUserAccess()));
1878
+ const result = await this.fetchResult(process_id);
1681
1879
  if (!result) {
1682
1880
  throw new Error(`Invalid process id ${process_id}`);
1683
1881
  }
@@ -1740,9 +1938,10 @@ class ProcessorService {
1740
1938
  async getAndStoreAuth(appEnv, access_tag) {
1741
1939
  try {
1742
1940
  // const payload = JSON.parse(decrypt(env.auth.data, this.productBuilderService.fetchProduct().private_key));
1743
- const payload = appEnv.auth.data;
1941
+ const payload = JSON.parse((0, processor_utils_1.decrypt)(String(appEnv.auth.data), this.productBuilderService.fetchProduct().private_key));
1744
1942
  let app = await this.fetchThirdPartyApp(access_tag);
1745
1943
  const auth = app.auths.find((item) => item.tag === appEnv.auth.auth_tag);
1944
+ console.log("JAMESY", auth);
1746
1945
  if (!auth) {
1747
1946
  // throw an error
1748
1947
  throw new Error(`Cannot find auth ${appEnv.auth.auth_tag} on environment ${appEnv.product_env_slug}`);
@@ -1757,6 +1956,13 @@ class ProcessorService {
1757
1956
  if (env.base_url) {
1758
1957
  request_base_url = env.base_url;
1759
1958
  }
1959
+ if (action.envs && action.envs.length) {
1960
+ const env = action.envs.find((item) => item.slug === appEnv.app_env_slug);
1961
+ if (env && env.base_url) {
1962
+ request_base_url = env.base_url;
1963
+ }
1964
+ }
1965
+ console.log("payloadabi!!!!", payload);
1760
1966
  const results = await this.sendActionRequest(request_base_url, url, payload, method, appEnv.app_env_slug);
1761
1967
  const values = (0, processor_utils_1.encrypt)(JSON.stringify(results), this.productBuilderService.fetchProduct().private_key);
1762
1968
  const productApp = this.productBuilderService.fetchApp(access_tag);
@@ -1805,7 +2011,6 @@ class ProcessorService {
1805
2011
  }
1806
2012
  async processConditionalCheck(event, additional_logs = {}) {
1807
2013
  const parts = (0, string_utils_1.extractConditionalParts)(event.condition.check);
1808
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Check conditional - initiated', data: { condition: event.condition, parts }, status: types_1.LogEventStatus.PROCESSING, action: event.event }));
1809
2014
  const [, initiator, operator, value] = parts;
1810
2015
  const initiatorValue = await this.generateStringValues(initiator, event.app, additional_logs);
1811
2016
  let valueValue;
@@ -1817,7 +2022,6 @@ class ProcessorService {
1817
2022
  else {
1818
2023
  valueValue = value;
1819
2024
  }
1820
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate check conditional - initiated', data: { condition: { initiatorValue, operator, valueValue } }, status: types_1.LogEventStatus.PROCESSING, action: event.event }));
1821
2025
  const pass = (0, processor_utils_1.compareValues)(initiatorValue, operator, valueValue);
1822
2026
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate check condition - success', data: { condition: { initiatorValue, operator, valueValue }, pass }, status: types_1.LogEventStatus.SUCCESS, action: event.event }));
1823
2027
  if (!pass) {
@@ -1842,7 +2046,6 @@ class ProcessorService {
1842
2046
  }
1843
2047
  async extractLoopIndexes(event, additional_logs = {}) {
1844
2048
  const parts = (0, string_utils_1.extractConditionalParts)(event.condition.check);
1845
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Loop conditional - initiated', data: { condition: event.condition, parts }, status: types_1.LogEventStatus.PROCESSING, action: event.event }));
1846
2049
  const [, initiator, operator, value] = parts;
1847
2050
  let valueValue;
1848
2051
  if (!(0, string_utils_1.isNumeric)(value)) {
@@ -1877,8 +2080,9 @@ class ProcessorService {
1877
2080
  const { envs: productEnvs, version } = productApp;
1878
2081
  const { app_env_slug } = productEnvs.find((item) => item.product_env_slug === this.processEnv.slug);
1879
2082
  additional_logs.app_env = app_env_slug;
2083
+ console.log(app, appEnvs);
1880
2084
  const env = appEnvs.find((item) => item.slug === app_env_slug); // fetch the actuall app Environment variable
1881
- if (!active) {
2085
+ if (!active && recipient_workspace_id !== this.baseLogs.workspace_id) {
1882
2086
  throw new Error(`App ${event.app} version ${app.version} is not active`);
1883
2087
  }
1884
2088
  if (!env.active) {
@@ -1893,6 +2097,12 @@ class ProcessorService {
1893
2097
  if (env.base_url) {
1894
2098
  request_base_url = env.base_url;
1895
2099
  }
2100
+ if (action.envs && action.envs.length) {
2101
+ const env = action.envs.find((item) => item.slug === app_env_slug);
2102
+ if (env && env.base_url) {
2103
+ request_base_url = env.base_url;
2104
+ }
2105
+ }
1896
2106
  const samples = {
1897
2107
  query: (query === null || query === void 0 ? void 0 : query.data) || [],
1898
2108
  headers: (headers === null || headers === void 0 ? void 0 : headers.data) || [],
@@ -1913,10 +2123,10 @@ class ProcessorService {
1913
2123
  input: inputString,
1914
2124
  privateKey: product.private_key,
1915
2125
  expiry: productCache.expiry,
1916
- });
2126
+ }, additional_logs);
1917
2127
  if (check) {
1918
2128
  result = JSON.parse(check);
1919
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Run action - return from cache', data: { result }, status: types_1.LogEventStatus.PROCESSING }));
2129
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Run action - response from cache', data: { result: (0, processor_utils_1.anonymizeObject)(result) }, status: types_1.LogEventStatus.SUCCESS, cache_tag, action: event.event }));
1920
2130
  if (returnValue) {
1921
2131
  return result;
1922
2132
  }
@@ -1955,18 +2165,18 @@ class ProcessorService {
1955
2165
  component_tag: action_tag,
1956
2166
  component_type: types_1.ProductComponents.ACTION,
1957
2167
  product_tag: this.productTag,
1958
- });
2168
+ }, additional_logs);
1959
2169
  }
1960
2170
  return result;
1961
2171
  }
1962
2172
  catch (e) {
1963
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Run Action - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2173
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Run Action - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
1964
2174
  throw e;
1965
2175
  }
1966
2176
  }
1967
2177
  async processRequest(payload, event, retries, additional_logs, returnValue = false) {
2178
+ var _a;
1968
2179
  const { request_base_url, resource, payloads, method, env, app_id } = payload;
1969
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process http request - initiated', data: { request: (0, processor_utils_1.anonymizeObject)(payload) }, status: types_1.LogEventStatus.PROCESSING, app_id, action: event.event }));
1970
2180
  const start = Date.now();
1971
2181
  try {
1972
2182
  let results = (0, processor_utils_1.generateMockData)(resource, env.slug, payloads);
@@ -1976,7 +2186,11 @@ class ProcessorService {
1976
2186
  const end = Date.now();
1977
2187
  this.requestTime += end - start;
1978
2188
  this.totalRequests += 1;
1979
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process http request - success', successful_execution: true, data: { response: (0, processor_utils_1.anonymizeObject)(results) }, status: types_1.LogEventStatus.SUCCESS, app_id, action: event.event, start,
2189
+ const { pricing_tag, pricing_cost, is_overage, currency } = await this.processPricingCost(Object.assign(Object.assign({}, additional_logs), { app_id, workspace_id: this.workspace_id }));
2190
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { pricing_tag,
2191
+ pricing_cost,
2192
+ currency,
2193
+ is_overage, message: 'Process http request - success', successful_execution: true, data: { response: (0, processor_utils_1.anonymizeObject)(results) }, status: types_1.LogEventStatus.SUCCESS, app_id, action: event.event, start,
1980
2194
  end }));
1981
2195
  await this.addToSuccessOutput(event, results, additional_logs);
1982
2196
  if (returnValue) {
@@ -1988,11 +2202,16 @@ class ProcessorService {
1988
2202
  }
1989
2203
  catch (e) {
1990
2204
  const end = Date.now();
2205
+ let error = e;
2206
+ if ((_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.data) {
2207
+ error = e.response.data;
2208
+ }
1991
2209
  this.requestTime += end - start;
1992
2210
  this.totalRequests += 1;
1993
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process http request - failed', failed_execution: true, data: { e }, status: types_1.LogEventStatus.FAIL, app_id, action: event.event, start,
2211
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process http request - failed', failed_execution: true, data: { e: error, input: (0, processor_utils_1.anonymizeObject)(payloads) }, status: types_1.LogEventStatus.FAIL, app_id, action: event.event, start,
1994
2212
  end }));
1995
2213
  try {
2214
+ console.log(e);
1996
2215
  const value = await this.addToFailureOutput(e, event, {
1997
2216
  request_base_url,
1998
2217
  resource,
@@ -2017,11 +2236,75 @@ class ProcessorService {
2017
2236
  }
2018
2237
  }
2019
2238
  }
2239
+ async processPricingCost(additional_logs) {
2240
+ try {
2241
+ const { app_id, workspace_id } = additional_logs;
2242
+ if (!app_id || !workspace_id) {
2243
+ throw new Error('app_id and workspace_id are required in additional_logs');
2244
+ }
2245
+ const primaryPricing = this.pricingService.fetchPricing();
2246
+ const overagePricing = this.pricingService.fetchOveragePricing();
2247
+ const requests = await this.requestTrackerService.incrementRequest(app_id, workspace_id);
2248
+ const limitCheck = (0, request_utils_1.checkLimitExceeded)(requests, primaryPricing.limits);
2249
+ let finalCost = 0;
2250
+ let usedPricing = primaryPricing;
2251
+ let isOverage = false;
2252
+ let finalCurrency = primaryPricing.currency;
2253
+ if ((0, request_utils_1.isFreeTag)(primaryPricing.pricing_tag)) {
2254
+ if (limitCheck.exceeded) {
2255
+ const overageRequests = (0, request_utils_1.calculateOverageRequests)(requests, primaryPricing.limits);
2256
+ finalCost = (0, request_utils_1.calculateCost)(overagePricing.pricing_mode, overagePricing.unit_price, overageRequests);
2257
+ usedPricing = overagePricing;
2258
+ isOverage = true;
2259
+ finalCurrency = overagePricing.currency;
2260
+ }
2261
+ else {
2262
+ finalCost = 0;
2263
+ }
2264
+ }
2265
+ else {
2266
+ if (limitCheck.exceeded) {
2267
+ const overageRequests = (0, request_utils_1.calculateOverageRequests)(requests, primaryPricing.limits);
2268
+ const overageCost = (0, request_utils_1.calculateCost)(overagePricing.pricing_mode, overagePricing.unit_price, overageRequests);
2269
+ finalCost = overageCost;
2270
+ isOverage = true;
2271
+ }
2272
+ else {
2273
+ const pricingRequests = (0, request_utils_1.calculateRequests)(requests);
2274
+ finalCost = (0, request_utils_1.calculateCost)(primaryPricing.pricing_mode, primaryPricing.unit_price, pricingRequests);
2275
+ }
2276
+ }
2277
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process Pricing Cost - success', data: {
2278
+ pricing_tag: usedPricing.pricing_tag,
2279
+ cost: finalCost,
2280
+ currency: finalCurrency,
2281
+ is_overage: isOverage,
2282
+ requests: requests,
2283
+ limit_exceeded: limitCheck.exceeded
2284
+ }, status: types_1.LogEventStatus.SUCCESS }));
2285
+ return {
2286
+ pricing_tag: usedPricing.pricing_tag,
2287
+ pricing_cost: Math.round(finalCost * 100) / 100,
2288
+ currency: finalCurrency,
2289
+ is_overage: isOverage,
2290
+ requests_made: requests,
2291
+ limit_exceeded: limitCheck.exceeded,
2292
+ exceeded_limits: limitCheck.exceededLimits
2293
+ };
2294
+ }
2295
+ catch (e) {
2296
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process Pricing Cost - failed', data: { error: e }, status: types_1.LogEventStatus.FAIL }));
2297
+ throw e;
2298
+ }
2299
+ }
2020
2300
  async addToSuccessOutput(event, output, additional_logs) {
2021
2301
  // Remove event from failed, skipped, and waiting arrays
2022
2302
  this.processingOutput.failure = this.processingOutput.failure.filter((data) => !(data.event.sequence_tag === event.sequence_tag && data.event.event === event.event));
2023
2303
  this.processingOutput.skipped = this.processingOutput.skipped.filter((data) => !(data.event.sequence_tag === event.sequence_tag && data.event.event === event.event));
2024
2304
  this.processingOutput.waiting = this.processingOutput.waiting.filter((data) => !(data.event.sequence_tag === event.sequence_tag && data.event.event === event.event));
2305
+ if (event.type === types_1.FeatureEventTypes.STORAGE) {
2306
+ event = (0, processor_utils_1.cleanBlob)(event);
2307
+ }
2025
2308
  this.processingOutput.success.push({ event, output });
2026
2309
  await this.processWaitingEvents(additional_logs);
2027
2310
  if (this.checkIsSuccessful() && this.doneWithProcessing) {
@@ -2076,6 +2359,12 @@ class ProcessorService {
2076
2359
  max = metrices.max;
2077
2360
  }
2078
2361
  const { allow_fail, retries } = event;
2362
+ let retryable = true;
2363
+ if (event.type === types_1.FeatureEventTypes.STORAGE) {
2364
+ event = (0, processor_utils_1.cleanBlob)(event);
2365
+ if (!this.feature || (this.feature && !event.allow_fail))
2366
+ retryable = false;
2367
+ }
2079
2368
  let retries_left = retries || max;
2080
2369
  if (exists > -1) {
2081
2370
  retries_left = this.processingOutput.failure[exists].retries_left - 1;
@@ -2122,7 +2411,7 @@ class ProcessorService {
2122
2411
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Ran out of retries - failed', data: Object.assign(Object.assign({}, output), { payload: (0, processor_utils_1.anonymizeObject)(output.payload) }), status: types_1.LogEventStatus.FAIL }));
2123
2412
  //throw new Error("Run out of retries")
2124
2413
  this.end = Date.now();
2125
- await this.writeResult(types_1.LogEventStatus.FAIL);
2414
+ await this.writeResult(types_1.LogEventStatus.FAIL, retryable);
2126
2415
  await this.logService.publish();
2127
2416
  //throw new Error("Terminate Process")
2128
2417
  }
@@ -2133,52 +2422,15 @@ class ProcessorService {
2133
2422
  }
2134
2423
  }
2135
2424
  generateRetryMetrices(error_code, retries) {
2136
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
2137
- let allow_fail = true;
2138
- let retry_at = 5000;
2139
- let max = (retries === null || retries === void 0 ? void 0 : retries.max) || 0;
2140
- switch (error_code) {
2141
- case '500':
2142
- allow_fail = ((_a = retries === null || retries === void 0 ? void 0 : retries.policy[500]) === null || _a === void 0 ? void 0 : _a.available) || false;
2143
- retry_at = ((_b = retries === null || retries === void 0 ? void 0 : retries.policy[500]) === null || _b === void 0 ? void 0 : _b.lag) || 0;
2144
- break;
2145
- case '502':
2146
- allow_fail = ((_c = retries === null || retries === void 0 ? void 0 : retries.policy[502]) === null || _c === void 0 ? void 0 : _c.available) || false;
2147
- retry_at = ((_d = retries === null || retries === void 0 ? void 0 : retries.policy[502]) === null || _d === void 0 ? void 0 : _d.lag) || 0;
2148
- break;
2149
- case '503':
2150
- allow_fail = ((_e = retries === null || retries === void 0 ? void 0 : retries.policy[503]) === null || _e === void 0 ? void 0 : _e.available) || false;
2151
- retry_at = ((_f = retries === null || retries === void 0 ? void 0 : retries.policy[503]) === null || _f === void 0 ? void 0 : _f.lag) || 0;
2152
- break;
2153
- case '504':
2154
- allow_fail = ((_g = retries === null || retries === void 0 ? void 0 : retries.policy[504]) === null || _g === void 0 ? void 0 : _g.available) || false;
2155
- retry_at = ((_h = retries === null || retries === void 0 ? void 0 : retries.policy[504]) === null || _h === void 0 ? void 0 : _h.lag) || 0;
2156
- break;
2157
- case '400':
2158
- allow_fail = ((_j = retries === null || retries === void 0 ? void 0 : retries.policy[400]) === null || _j === void 0 ? void 0 : _j.available) || false;
2159
- retry_at = ((_k = retries === null || retries === void 0 ? void 0 : retries.policy[400]) === null || _k === void 0 ? void 0 : _k.lag) || 0;
2160
- break;
2161
- case '401':
2162
- allow_fail = ((_l = retries === null || retries === void 0 ? void 0 : retries.policy[401]) === null || _l === void 0 ? void 0 : _l.available) || false;
2163
- retry_at = ((_m = retries === null || retries === void 0 ? void 0 : retries.policy[401]) === null || _m === void 0 ? void 0 : _m.lag) || 0;
2164
- break;
2165
- case '403':
2166
- allow_fail = ((_o = retries === null || retries === void 0 ? void 0 : retries.policy[403]) === null || _o === void 0 ? void 0 : _o.available) || false;
2167
- retry_at = ((_p = retries === null || retries === void 0 ? void 0 : retries.policy[403]) === null || _p === void 0 ? void 0 : _p.lag) || 0;
2168
- break;
2169
- case '404':
2170
- allow_fail = ((_q = retries === null || retries === void 0 ? void 0 : retries.policy[404]) === null || _q === void 0 ? void 0 : _q.available) || false;
2171
- retry_at = ((_r = retries === null || retries === void 0 ? void 0 : retries.policy[404]) === null || _r === void 0 ? void 0 : _r.lag) || 0;
2172
- break;
2173
- case '1000': // all non http errors
2174
- allow_fail = true;
2175
- retry_at = 500;
2176
- default:
2177
- allow_fail = true;
2178
- retry_at = 0;
2179
- max = 0;
2180
- break;
2181
- }
2425
+ var _a;
2426
+ const isSpecial = error_code === '1000';
2427
+ if (isSpecial) {
2428
+ return { allow_fail: true, max: (retries === null || retries === void 0 ? void 0 : retries.max) || 0, retry_at: 500 };
2429
+ }
2430
+ const policy = (_a = retries === null || retries === void 0 ? void 0 : retries.policy) === null || _a === void 0 ? void 0 : _a[error_code];
2431
+ const allow_fail = policy ? policy.available : true;
2432
+ const retry_at = policy ? policy.lag : 0;
2433
+ const max = (retries === null || retries === void 0 ? void 0 : retries.max) || 0;
2182
2434
  return { allow_fail, max, retry_at };
2183
2435
  }
2184
2436
  async sendActionRequest(base_url, resource, payload, method, env) {
@@ -2204,6 +2456,7 @@ class ProcessorService {
2204
2456
  timeout: 15000,
2205
2457
  withCredentials: false
2206
2458
  };
2459
+ console.log("REQUEST!!!!", request);
2207
2460
  const response = await axios_1.default.request(request);
2208
2461
  return response.data;
2209
2462
  }
@@ -2221,7 +2474,7 @@ class ProcessorService {
2221
2474
  name: 'Process Storage',
2222
2475
  };
2223
2476
  try {
2224
- this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.STORAGE);
2477
+ await this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.STORAGE);
2225
2478
  this.input = input;
2226
2479
  this.start = Date.now();
2227
2480
  this.component = types_1.LogEventTypes.STORAGE;
@@ -2239,7 +2492,6 @@ class ProcessorService {
2239
2492
  if (!productEnv.active) {
2240
2493
  throw new Error(`Environment ${env} is not active`);
2241
2494
  }
2242
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Storing file - initiated', status: types_1.LogEventStatus.PROCESSING, storage: new Blob([action.input.buffer]).size }));
2243
2495
  const payload = {
2244
2496
  type: types_1.FeatureEventTypes.STORAGE,
2245
2497
  event,
@@ -2254,7 +2506,7 @@ class ProcessorService {
2254
2506
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Storing file - success', data: { input: this.clone, result }, status: types_1.LogEventStatus.SUCCESS }));
2255
2507
  await this.writeResult(types_1.LogEventStatus.SUCCESS);
2256
2508
  await this.logService.publish();
2257
- return result;
2509
+ return Object.assign(Object.assign({}, result), { process_id: this.process_id });
2258
2510
  }
2259
2511
  catch (e) {
2260
2512
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Storing file - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
@@ -2275,7 +2527,7 @@ class ProcessorService {
2275
2527
  name: `Subscribe to broker topic`,
2276
2528
  };
2277
2529
  try {
2278
- this.validateActionDataMappingInput(data.input, types_1.FeatureEventTypes.STORAGE);
2530
+ await this.validateActionDataMappingInput(data.input, types_1.FeatureEventTypes.STORAGE);
2279
2531
  this.start = Date.now();
2280
2532
  this.productTag = data.product;
2281
2533
  const process_id = (0, processor_utils_1.generateObjectId)();
@@ -2324,7 +2576,7 @@ class ProcessorService {
2324
2576
  name: 'Publish to broker topic',
2325
2577
  };
2326
2578
  try {
2327
- this.validateActionDataMappingInput(data.input, types_1.FeatureEventTypes.PUBLISH);
2579
+ await this.validateActionDataMappingInput(data.input, types_1.FeatureEventTypes.PUBLISH);
2328
2580
  this.start = Date.now();
2329
2581
  // clone
2330
2582
  this.clone = (0, processor_utils_1.structuredClone)(data.input);
@@ -2341,7 +2593,6 @@ class ProcessorService {
2341
2593
  if (!productEnv.active) {
2342
2594
  throw new Error(`Environment ${data.env} is not active`);
2343
2595
  }
2344
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Publish to topic - initiated', data: Object.assign(Object.assign({}, data), { input: (0, processor_utils_1.anonymizeObject)(data.input) }), status: types_1.LogEventStatus.PROCESSING }));
2345
2596
  const payload = {
2346
2597
  type: types_1.FeatureEventTypes.PUBLISH,
2347
2598
  event: data.event,
@@ -2365,7 +2616,113 @@ class ProcessorService {
2365
2616
  return { process_id: this.process_id };
2366
2617
  }
2367
2618
  }
2368
- async processJob(job) { }
2619
+ async processJob(job, additional_logs = {}) {
2620
+ var _a;
2621
+ const productJob = this.productBuilderService.fetchJob(job.event);
2622
+ if (!productJob) {
2623
+ throw new Error(`Job ${job.event} not found`);
2624
+ }
2625
+ await this.validateActionDataMappingInput(job.input, productJob.type);
2626
+ const NOW = Date.now();
2627
+ // Treat anything above Jan 1, 2023 as a timestamp (to be safe and future-proof)
2628
+ const IS_PROBABLY_TIMESTAMP = job.start_at > 1672531200000;
2629
+ const delay = Math.max(0, IS_PROBABLY_TIMESTAMP ? job.start_at - NOW : job.start_at);
2630
+ let jobInput;
2631
+ if (productJob.type === types_1.JobEventTypes.ACTION) {
2632
+ const input = {
2633
+ env: job.env,
2634
+ product: job.product,
2635
+ app: productJob.app,
2636
+ cache: job.cache,
2637
+ input: job.input,
2638
+ event: job.event,
2639
+ session: job.session
2640
+ };
2641
+ jobInput = input;
2642
+ }
2643
+ else if (productJob.type === types_1.JobEventTypes.DATABASE_ACTION) {
2644
+ const input = {
2645
+ env: job.env,
2646
+ product: job.product,
2647
+ cache: job.cache,
2648
+ input: job.input,
2649
+ event: job.event,
2650
+ session: job.session,
2651
+ };
2652
+ jobInput = input;
2653
+ }
2654
+ else if (productJob.type === types_1.JobEventTypes.FALLBACK || productJob.type === types_1.JobEventTypes.QUOTA || productJob.type === types_1.JobEventTypes.FEATURE) {
2655
+ const input = {
2656
+ input: job.input,
2657
+ product: job.product,
2658
+ env: job.env,
2659
+ tag: job.event,
2660
+ session: job.session,
2661
+ cache: job.cache,
2662
+ };
2663
+ jobInput = input;
2664
+ }
2665
+ else if (productJob.type === types_1.JobEventTypes.NOTIFICATION) {
2666
+ const input = {
2667
+ env: job.env,
2668
+ product: job.product,
2669
+ event: job.event,
2670
+ input: job.input,
2671
+ session: job.session,
2672
+ cache: job.cache
2673
+ };
2674
+ jobInput = input;
2675
+ }
2676
+ else if (productJob.type === types_1.JobEventTypes.PUBLISH) {
2677
+ const input = {
2678
+ env: job.env,
2679
+ product: job.product,
2680
+ event: job.event,
2681
+ cache: job.cache,
2682
+ session: job.session,
2683
+ input: job.input
2684
+ };
2685
+ jobInput = input;
2686
+ }
2687
+ else if (productJob.type === types_1.JobEventTypes.STORAGE) {
2688
+ const input = {
2689
+ env: job.env,
2690
+ product: job.product,
2691
+ event: job.event,
2692
+ cache: job.cache,
2693
+ session: job.session,
2694
+ input: job.input
2695
+ };
2696
+ jobInput = input;
2697
+ }
2698
+ else {
2699
+ throw new Error(`Job type ${productJob.type} not supported`);
2700
+ }
2701
+ const options = {};
2702
+ // Handle `delay` only if repeat.every is not defined
2703
+ if (!((_a = job.repeat) === null || _a === void 0 ? void 0 : _a.every)) {
2704
+ options.delay = delay;
2705
+ }
2706
+ // Add repeat config if defined
2707
+ if (job.repeat) {
2708
+ const { every, cron, tz, limit, endDate } = job.repeat;
2709
+ options.repeat = cron
2710
+ ? {
2711
+ cron,
2712
+ tz,
2713
+ limit,
2714
+ endDate,
2715
+ }
2716
+ : every
2717
+ ? {
2718
+ every,
2719
+ limit,
2720
+ endDate,
2721
+ }
2722
+ : undefined;
2723
+ }
2724
+ await this.queues.jobs.add(productJob.type, jobInput, options);
2725
+ }
2369
2726
  async sendExpoNotification(payload, device_tokens) {
2370
2727
  const message = {
2371
2728
  to: device_tokens,
@@ -2404,24 +2761,18 @@ class ProcessorService {
2404
2761
  }
2405
2762
  }
2406
2763
  async ProcessExpoNotification(notification, template, payload, additional_logs) {
2407
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate notification payload - initiated', data: { notification, payload: (0, processor_utils_1.anonymizeObject)(payload) }, status: types_1.LogEventStatus.PROCESSING }));
2408
2764
  (0, processor_utils_1.validateNotification)(template, payload);
2409
2765
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate notification payload - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2410
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate notification template - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2411
2766
  const { title, body, data } = (0, processor_utils_1.generateNotificationTemplate)(template, payload);
2412
2767
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate notification template - success', data: { title, body, data: (0, processor_utils_1.anonymizeObject)(data) }, status: types_1.LogEventStatus.SUCCESS }));
2413
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send Expo notification - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2414
2768
  await this.sendExpoNotification({ title, body, data }, payload.device_tokens);
2415
2769
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send Expo notification - success', data: { title, body, data: (0, processor_utils_1.anonymizeObject)(data) }, status: types_1.LogEventStatus.SUCCESS }));
2416
2770
  }
2417
2771
  async ProcessFirebaseNotification(notification, template, payload, additional_logs) {
2418
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate Firebase notification payload - initiated', data: { notification, payload: (0, processor_utils_1.anonymizeObject)(payload) }, status: types_1.LogEventStatus.PROCESSING }));
2419
2772
  (0, processor_utils_1.validateNotification)(template, payload);
2420
2773
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate Firebase notification payload - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2421
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate Firebase notification template - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2422
2774
  const { title, body, data } = (0, processor_utils_1.generateNotificationTemplate)(template, payload);
2423
2775
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate Firebase notification template - success', data: { title, body: (0, processor_utils_1.anonymizeObject)(data), data: (0, processor_utils_1.anonymizeObject)(data) }, status: types_1.LogEventStatus.SUCCESS }));
2424
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send Firebase notification - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2425
2776
  await this.sendFirebaseNotification({ title, body, data }, payload.device_tokens, notification.credentials);
2426
2777
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send Firebase notification - success', data: { title, body: (0, processor_utils_1.anonymizeObject)(data), data: (0, processor_utils_1.anonymizeObject)(data) }, status: types_1.LogEventStatus.SUCCESS }));
2427
2778
  }
@@ -2431,8 +2782,6 @@ class ProcessorService {
2431
2782
  const input = notification.input;
2432
2783
  try {
2433
2784
  //await this.intializeProduct(additional_logs);
2434
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempting notification', data: { notification }, status: types_1.LogEventStatus.PROCESSING }));
2435
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetching notification details', data: { notification }, status: types_1.LogEventStatus.PROCESSING }));
2436
2785
  const notificationEvent = this.productBuilderService.fetchNotification(event.split(":")[0]);
2437
2786
  const message = this.productBuilderService.fetchNotificationMessage(event);
2438
2787
  if (!message) {
@@ -2452,15 +2801,23 @@ class ProcessorService {
2452
2801
  expected: types_1.ExpectedValues.PARSEINPUT,
2453
2802
  }));
2454
2803
  //await this.inputService.validateInput(validationPayload, message.push_notification_data, "Push Notifications");
2455
- if (push && notifications.type === types_1.Notifiers.FIREBASE) {
2456
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Processing Expo notification - initiated', data: { notification, input: (0, processor_utils_1.anonymizeObject)(input.push_notification) }, status: types_1.LogEventStatus.PROCESSING }));
2457
- await this.ProcessExpoNotification(notifications, message, input.push_notification, additional_logs);
2458
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Processing Expo notification - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2459
- }
2460
2804
  if (push && notifications.type === types_1.Notifiers.EXPO) {
2461
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Processing Firebase notification - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2462
- await this.ProcessFirebaseNotification(notifications, message, input.push_notification, additional_logs);
2463
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Processing Firebase notification - success', data: { notification, input: (0, processor_utils_1.anonymizeObject)(input.push_notification) }, status: types_1.LogEventStatus.SUCCESS }));
2805
+ try {
2806
+ await this.ProcessExpoNotification(notifications, message, input.push_notification, additional_logs);
2807
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Processing Expo notification - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2808
+ }
2809
+ catch (e) {
2810
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Processing Expo notification - failed', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2811
+ }
2812
+ }
2813
+ if (push && notifications.type === types_1.Notifiers.FIREBASE) {
2814
+ try {
2815
+ await this.ProcessFirebaseNotification(notifications, message, input.push_notification, additional_logs);
2816
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Processing Firebase notification - success', data: { notification, input: (0, processor_utils_1.anonymizeObject)(input.push_notification) }, status: types_1.LogEventStatus.SUCCESS }));
2817
+ }
2818
+ catch (e) {
2819
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Processing Firebase notification - failed', data: { notification, input: (0, processor_utils_1.anonymizeObject)(input.push_notification) }, status: types_1.LogEventStatus.FAIL }));
2820
+ }
2464
2821
  }
2465
2822
  if (email && emails) {
2466
2823
  input.email.subject = await this.generatePayload(input.email.subject, notification, additional_logs, message.email_data.filter((data) => data.parent_key === 'subject'));
@@ -2472,37 +2829,28 @@ class ProcessorService {
2472
2829
  }));
2473
2830
  //await this.inputService.validateInput(validationPayload, message.email_data);
2474
2831
  input.email.recipients.map((email) => this.inputService.validateEmailString({ key: 'to', value: email }));
2475
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process email - initiated', data: { email: (0, processor_utils_1.anonymizeObject)(email), input: (0, processor_utils_1.anonymizeObject)(input.email) }, status: types_1.LogEventStatus.PROCESSING }));
2476
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt email auth fetch - initiated', data: { emails: (0, processor_utils_1.anonymizeObject)(emails) }, status: types_1.LogEventStatus.PROCESSING }));
2477
2832
  const { sender_email: from } = emails, auth = __rest(emails, ["sender_email"]);
2478
2833
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt email auth fetch - success', data: { from: (0, processor_utils_1.anonymizeValue)(from), host: (0, processor_utils_1.anonymizeValue)(auth.host), port: (0, processor_utils_1.anonymizeValue)(auth.port) }, status: types_1.LogEventStatus.SUCCESS }));
2479
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate email template - initiated', data: {
2480
- template: (0, processor_utils_1.anonymizeValue)(email.template),
2481
- subject: (0, processor_utils_1.anonymizeValue)(email.subject),
2482
- input: (0, processor_utils_1.anonymizeObject)(input.email),
2483
- }, status: types_1.LogEventStatus.PROCESSING }));
2484
2834
  const templateMaker = (0, handlebars_1.compile)(email.template);
2485
2835
  const template = templateMaker(input.email.template);
2486
2836
  const subject = (0, processor_utils_1.replacePlaceholderString)(email.subject, input.email.subject || {});
2487
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate email template - success', data: { template: (0, processor_utils_1.anonymizeValue)(template), subject: (0, processor_utils_1.anonymizeValue)(subject) }, status: types_1.LogEventStatus.SUCCESS }));
2837
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate email template - success', data: { template: (0, processor_utils_1.anonymizeValue)(template), subject: (0, processor_utils_1.anonymizeValue)(subject), input: (0, processor_utils_1.anonymizeObject)(input.email), }, status: types_1.LogEventStatus.SUCCESS }));
2488
2838
  const mailOptions = {
2489
2839
  from,
2490
2840
  to: input.email.recipients,
2491
2841
  subject,
2492
2842
  template,
2493
2843
  };
2494
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send email - initiated', data: { template: (0, processor_utils_1.anonymizeValue)(template), subject: (0, processor_utils_1.anonymizeValue)(subject), to: input.email.recipients.map((data) => (0, processor_utils_1.anonymizeValue)(data)) }, status: types_1.LogEventStatus.PROCESSING }));
2495
2844
  try {
2496
2845
  const transporter = await (0, processor_utils_1.mailerClient)(auth);
2497
2846
  const response = await transporter.sendMail(mailOptions);
2498
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send email - success', data: { response }, status: types_1.LogEventStatus.SUCCESS }));
2847
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send email - success', successful_execution: true, data: { response }, status: types_1.LogEventStatus.SUCCESS }));
2499
2848
  }
2500
2849
  catch (e) {
2501
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send email - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2850
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Send email - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2502
2851
  }
2503
2852
  }
2504
2853
  if (callback && callbacks) {
2505
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process callback - initiated', data: Object.assign(Object.assign({}, callbacks), { data: (0, processor_utils_1.anonymizeObject)(callback) }), status: types_1.LogEventStatus.PROCESSING }));
2506
2854
  const payload = {
2507
2855
  query: Object.assign(Object.assign({}, (_a = input.callback) === null || _a === void 0 ? void 0 : _a.query), (_b = callbacks.auth) === null || _b === void 0 ? void 0 : _b.query),
2508
2856
  headers: Object.assign(Object.assign({}, (_c = input.callback) === null || _c === void 0 ? void 0 : _c.headers), (_d = callbacks.auth) === null || _d === void 0 ? void 0 : _d.headers),
@@ -2518,32 +2866,29 @@ class ProcessorService {
2518
2866
  expected: types_1.ExpectedValues.PARSEINPUT,
2519
2867
  }));
2520
2868
  //this.inputService.validateInput(validationPayload, message.callback_data);
2521
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Generate callback payload - initiated', data: Object.assign(Object.assign({}, callbacks), { data: (0, processor_utils_1.anonymizeObject)(payload) }), status: types_1.LogEventStatus.PROCESSING }));
2522
2869
  const url = new URL(callbacks.url);
2523
2870
  try {
2524
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send callback - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2525
2871
  await this.sendActionRequest(url.origin, url.pathname, payload, callbacks.method, '');
2526
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { name: 'Send callback - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2872
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, name: 'Send callback - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2527
2873
  }
2528
2874
  catch (e) {
2529
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send callback - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2875
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Send callback - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2530
2876
  }
2531
2877
  }
2532
2878
  if (sms && smses) {
2533
2879
  try {
2534
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process sms - initiated', data: { data: sms, config: (0, processor_utils_1.anonymizeObject)(smses) }, status: types_1.LogEventStatus.PROCESSING }));
2535
2880
  input.sms.body = await (0, processor_utils_1.replacePlaceholderString)(sms, input.sms.body);
2536
2881
  const SmsClient = await (0, sms_repo_1.loadSMSClient)();
2537
2882
  const smsClient = new SmsClient(smses);
2538
2883
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { name: 'Send sms - initiated', data: { message: input.sms.body, config: (0, processor_utils_1.anonymizeObject)(smses) }, status: types_1.LogEventStatus.SUCCESS }));
2539
2884
  const res = await smsClient.sendMessage(input.sms.body, input.sms.recipients);
2540
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { name: 'Send sms - success', data: res, status: types_1.LogEventStatus.SUCCESS }));
2885
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { name: 'Send sms - success', successful_execution: true, data: res, status: types_1.LogEventStatus.SUCCESS }));
2541
2886
  }
2542
2887
  catch (e) {
2543
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Process sms - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2888
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Process sms - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2544
2889
  }
2545
2890
  }
2546
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Attempt notification - success', data: notification, status: types_1.LogEventStatus.SUCCESS }));
2891
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt notification - success', data: notification, status: types_1.LogEventStatus.SUCCESS }));
2547
2892
  }
2548
2893
  catch (e) {
2549
2894
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Attempt notification - failed', data: { e: e.toString() }, status: types_1.LogEventStatus.FAIL }));
@@ -2728,8 +3073,6 @@ class ProcessorService {
2728
3073
  const input = data.input;
2729
3074
  try {
2730
3075
  await this.intializeProduct(additional_logs);
2731
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt storage - initiated', data: this.clone, status: types_1.LogEventStatus.PROCESSING }));
2732
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch storage details - initiated', data: this.clone, status: types_1.LogEventStatus.PROCESSING }));
2733
3076
  const storage = await this.productBuilderService.fetchStorage(event);
2734
3077
  const storageEnv = storage.envs.find((el) => el.slug === env.slug);
2735
3078
  if (!storageEnv) {
@@ -2749,19 +3092,17 @@ class ProcessorService {
2749
3092
  input: inputString,
2750
3093
  privateKey: product.private_key,
2751
3094
  expiry: productCache.expiry,
2752
- });
3095
+ }, additional_logs);
2753
3096
  if (check) {
2754
3097
  result = JSON.parse(check);
2755
3098
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Store file - return from cache', data: { result }, status: types_1.LogEventStatus.PROCESSING }));
2756
3099
  return result;
2757
3100
  }
2758
3101
  }
2759
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Store file - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2760
3102
  input.buffer = input.buffer ? await this.generateStringValues(input.buffer, '', additional_logs, []) : undefined;
2761
3103
  input.fileName = input.fileName ? await this.generateStringValues(input.fileName, '', additional_logs, []) : undefined;
2762
3104
  input.mimeType = input.mimeType ? await this.generateStringValues(input.mimeType, '', additional_logs, []) : undefined;
2763
3105
  result = await this.processStorageRequest(data, input, storageEnv, additional_logs);
2764
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Store file - success', data: { result }, status: types_1.LogEventStatus.PROCESSING }));
2765
3106
  if (cache_tag && this.redisClient) {
2766
3107
  const productCache = this.productBuilderService.fetchCache(cache_tag);
2767
3108
  if (!productCache) {
@@ -2777,12 +3118,11 @@ class ProcessorService {
2777
3118
  component_tag: event,
2778
3119
  component_type: types_1.ProductComponents.STORAGE,
2779
3120
  product_tag: this.productTag,
2780
- });
3121
+ }, additional_logs);
2781
3122
  }
2782
3123
  return result;
2783
3124
  }
2784
3125
  catch (e) {
2785
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { failed_execution: true, message: 'Attempt storage - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
2786
3126
  throw e;
2787
3127
  }
2788
3128
  }
@@ -2791,8 +3131,6 @@ class ProcessorService {
2791
3131
  const input = db_action.input;
2792
3132
  try {
2793
3133
  //await this.intializeProduct(additional_logs);
2794
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt database action - initiated', data: db_action, status: types_1.LogEventStatus.PROCESSING }));
2795
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch database action - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2796
3134
  const [database_tag, action_tag] = event.split(':');
2797
3135
  const product = this.productBuilderService.fetchProduct();
2798
3136
  const database = await this.productBuilderService.fetchDatabase(database_tag);
@@ -2802,7 +3140,6 @@ class ProcessorService {
2802
3140
  throw new Error(`Database env for ${env.slug} not found`);
2803
3141
  }
2804
3142
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch database action - success', data: databaseAction, status: types_1.LogEventStatus.SUCCESS }));
2805
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate database action payload - initiated', data: { payload: (0, processor_utils_1.anonymizeObject)(input.data) }, status: types_1.LogEventStatus.PROCESSING }));
2806
3143
  input.data = await this.generatePayload(input.data, db_action, additional_logs, databaseAction.data);
2807
3144
  if (Array.isArray(input.data)) {
2808
3145
  await Promise.all(input.data.map(async (d) => {
@@ -2830,11 +3167,9 @@ class ProcessorService {
2830
3167
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate database action payload - success', data: { db_action, payload: (0, processor_utils_1.anonymizeObject)(input.data) }, status: types_1.LogEventStatus.SUCCESS }));
2831
3168
  if (database.type === types_1.DatabaseTypes.MONGODB) {
2832
3169
  if (databaseAction.type === types_1.DatabaseActionTypes.UPDATE) {
2833
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate database update action filter - initiated', data: { filter: (0, processor_utils_1.anonymizeObject)(input.filter) }, status: types_1.LogEventStatus.PROCESSING }));
2834
3170
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Validate database update action filter - success', data: {}, status: types_1.LogEventStatus.SUCCESS }));
2835
3171
  }
2836
3172
  }
2837
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Run database action query - initiated', data: { payload: (0, processor_utils_1.anonymizeObject)(input) }, status: types_1.LogEventStatus.PROCESSING }));
2838
3173
  let result;
2839
3174
  if (cache_tag && this.redisClient) {
2840
3175
  const productCache = this.productBuilderService.fetchCache(cache_tag);
@@ -2847,7 +3182,7 @@ class ProcessorService {
2847
3182
  input: inputString,
2848
3183
  privateKey: product.private_key,
2849
3184
  expiry: productCache.expiry,
2850
- });
3185
+ }, additional_logs);
2851
3186
  if (check) {
2852
3187
  result = JSON.parse(check);
2853
3188
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Run database action query - return from cache', data: { result: (0, processor_utils_1.anonymizeObject)(result) }, status: types_1.LogEventStatus.SUCCESS }));
@@ -2883,7 +3218,6 @@ class ProcessorService {
2883
3218
  }
2884
3219
  //await this.logService.publish();
2885
3220
  // const result = this.processDBRequest(db_action, input, database_tag, databaseEnv, action_tag, additional_logs);
2886
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Run database action query - success', data: { result: (0, processor_utils_1.anonymizeObject)(result) }, status: types_1.LogEventStatus.SUCCESS }));
2887
3221
  await this.addToSuccessOutput(db_action, result, additional_logs);
2888
3222
  if (cache_tag && this.redisClient) {
2889
3223
  const productCache = this.productBuilderService.fetchCache(cache_tag);
@@ -2900,8 +3234,9 @@ class ProcessorService {
2900
3234
  product_tag: this.productTag,
2901
3235
  component_tag: database_tag,
2902
3236
  component_type: types_1.ProductComponents.DATABASE_ACTION,
2903
- });
3237
+ }, additional_logs);
2904
3238
  }
3239
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Attempt database action - successful', data: { result: (0, processor_utils_1.anonymizeObject)(result) }, status: types_1.LogEventStatus.SUCCESS }));
2905
3240
  return result;
2906
3241
  }
2907
3242
  catch (e) {
@@ -2914,8 +3249,6 @@ class ProcessorService {
2914
3249
  const input = data.input;
2915
3250
  try {
2916
3251
  await this.intializeProduct(additional_logs);
2917
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt broker topic subscription - initiated', data: { event }, status: types_1.LogEventStatus.PROCESSING }));
2918
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch broker details - initiated', data: { event }, status: types_1.LogEventStatus.PROCESSING }));
2919
3252
  const [brokerTag, topicTag] = event.split(':');
2920
3253
  const broker = this.productBuilderService.fetchMessageBroker(brokerTag);
2921
3254
  if (!broker) {
@@ -2941,12 +3274,13 @@ class ProcessorService {
2941
3274
  url = queueUrl.url;
2942
3275
  }
2943
3276
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch broker details - success', data: { event, broker }, status: types_1.LogEventStatus.SUCCESS }));
2944
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Subscribe to broker topic - initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2945
3277
  const createBrokerService = await loadBrokerService();
2946
3278
  if (createBrokerService) {
2947
3279
  const brokerService = createBrokerService(brokerEnv.type, brokerEnv.config);
2948
3280
  await brokerService.subscribe(url, input.callback);
2949
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Subscribe to broker topic - success', data: { event }, status: types_1.LogEventStatus.SUCCESS }));
3281
+ if (this.feature) {
3282
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { successful_execution: true, message: 'Subscribe to broker topic - success', data: { event }, status: types_1.LogEventStatus.SUCCESS }));
3283
+ }
2950
3284
  return;
2951
3285
  }
2952
3286
  else {
@@ -2964,8 +3298,6 @@ class ProcessorService {
2964
3298
  const input = data.input;
2965
3299
  try {
2966
3300
  await this.intializeProduct(additional_logs);
2967
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Attempt publish to broker topic - initiated', data: { event }, status: types_1.LogEventStatus.PROCESSING }));
2968
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch broker details - initiated', data: { event }, status: types_1.LogEventStatus.PROCESSING }));
2969
3301
  const [brokerTag, topicTag] = event.split(':');
2970
3302
  const broker = this.productBuilderService.fetchMessageBroker(brokerTag);
2971
3303
  if (!broker) {
@@ -2991,12 +3323,13 @@ class ProcessorService {
2991
3323
  url = queueUrl.url;
2992
3324
  }
2993
3325
  this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetch broker details - success', data: { event, broker }, status: types_1.LogEventStatus.SUCCESS }));
2994
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Publish to broker topic initiated', data: {}, status: types_1.LogEventStatus.PROCESSING }));
2995
3326
  const createBrokerService = await loadBrokerService();
2996
3327
  if (createBrokerService) {
2997
3328
  const brokerService = createBrokerService(brokerEnv.type, brokerEnv.config);
2998
3329
  await brokerService.publish(url, input.message);
2999
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Publish to broker topic - success', successful_execution: true, data: { event }, status: types_1.LogEventStatus.SUCCESS }));
3330
+ if (this.feature) {
3331
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Publish to broker topic - success', successful_execution: true, data: { event }, status: types_1.LogEventStatus.SUCCESS }));
3332
+ }
3000
3333
  return;
3001
3334
  }
3002
3335
  else {
@@ -3041,6 +3374,7 @@ class ProcessorService {
3041
3374
  url: (0, processor_utils_1.encrypt)(result.url, this.productBuilderService.fetchProduct().private_key),
3042
3375
  provider: storageEnv.type,
3043
3376
  product: this.productTag,
3377
+ process_id: this.process_id,
3044
3378
  workspace_id: this.workspace_id,
3045
3379
  type: input.mimeType,
3046
3380
  event: data.event,
@@ -3091,18 +3425,19 @@ class ProcessorService {
3091
3425
  return value;
3092
3426
  }
3093
3427
  }
3094
- async writeResult(status) {
3428
+ async writeResult(status, retryable = true) {
3095
3429
  this.processorApiService.saveResult({
3096
3430
  status,
3097
3431
  component: this.component,
3098
3432
  start: this.start,
3099
3433
  end: this.end,
3100
- result: this.processingOutput,
3434
+ retryable,
3435
+ result: (0, processor_utils_1.encrypt)(JSON.stringify(this.processingOutput), this.productBuilderService.fetchProduct().private_key),
3101
3436
  process_id: this.process_id,
3102
3437
  feature_id: this.feature ? this.feature._id : null,
3103
3438
  product_id: this.productId,
3104
3439
  env: this.processEnv.slug,
3105
- input: this.input,
3440
+ input: (0, processor_utils_1.encrypt)(JSON.stringify(this.input), this.productBuilderService.fetchProduct().private_key),
3106
3441
  }, this.getUserAccess());
3107
3442
  }
3108
3443
  async validateActionDataMappingInput(input, type) {
@@ -3134,7 +3469,7 @@ class ProcessorService {
3134
3469
  this.component = types_1.LogEventTypes.ACTION;
3135
3470
  try {
3136
3471
  // validate input do not allow $Sequence or $Length and $Size of $Input
3137
- this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.ACTION);
3472
+ await this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.ACTION);
3138
3473
  this.input = action;
3139
3474
  this.start = Date.now();
3140
3475
  this.productTag = product_tag;
@@ -3148,6 +3483,7 @@ class ProcessorService {
3148
3483
  data: input,
3149
3484
  };
3150
3485
  await this.intializeProduct(additional_logs);
3486
+ await this.initializePricing(additional_logs, app);
3151
3487
  this.process_id = process_id;
3152
3488
  this.baseLogs.product_id = this.productId;
3153
3489
  const productEnv = this.fetchEnv(env, additional_logs);
@@ -3155,7 +3491,6 @@ class ProcessorService {
3155
3491
  if (!productEnv.active) {
3156
3492
  throw new Error(`Environment ${env} is not active`);
3157
3493
  }
3158
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Execute action initiated', status: types_1.LogEventStatus.PROCESSING }));
3159
3494
  const result = await this.runAction({
3160
3495
  type: types_1.FeatureEventTypes.ACTION,
3161
3496
  event,
@@ -3173,7 +3508,8 @@ class ProcessorService {
3173
3508
  return result;
3174
3509
  }
3175
3510
  catch (e) {
3176
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Execute action - failed', data: { e }, status: types_1.LogEventStatus.FAIL }));
3511
+ console.log("ERRRRROORRRRR!!!!!!", e);
3512
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Execute action - failed', data: { e: e.toString() }, status: types_1.LogEventStatus.FAIL }));
3177
3513
  this.end = Date.now();
3178
3514
  await this.writeResult(types_1.LogEventStatus.FAIL);
3179
3515
  await this.logService.publish();
@@ -3195,7 +3531,7 @@ class ProcessorService {
3195
3531
  name: 'Process database action',
3196
3532
  };
3197
3533
  try {
3198
- this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.DB_ACTION);
3534
+ await this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.DB_ACTION);
3199
3535
  this.input = action;
3200
3536
  this.start = Date.now();
3201
3537
  this.productTag = product_tag;
@@ -3210,7 +3546,6 @@ class ProcessorService {
3210
3546
  if (!productEnv.active) {
3211
3547
  throw new Error(`Environment ${env} is not active`);
3212
3548
  }
3213
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Execute database action', data: { action: (0, processor_utils_1.anonymizeObject)(action) }, status: types_1.LogEventStatus.PROCESSING }));
3214
3549
  const payload = {
3215
3550
  type: types_1.FeatureEventTypes.DB_ACTION,
3216
3551
  event,
@@ -3250,7 +3585,7 @@ class ProcessorService {
3250
3585
  name: 'Process Notification',
3251
3586
  };
3252
3587
  try {
3253
- this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.NOTIFICATION);
3588
+ await this.validateActionDataMappingInput(input, types_1.FeatureEventTypes.NOTIFICATION);
3254
3589
  this.input = action;
3255
3590
  this.start = Date.now();
3256
3591
  this.productTag = product_tag;
@@ -3265,7 +3600,6 @@ class ProcessorService {
3265
3600
  if (!productEnv.active) {
3266
3601
  throw new Error(`Environment ${env} is not active`);
3267
3602
  }
3268
- this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Send notification - initiated', data: { action: (0, processor_utils_1.anonymizeObject)(action) }, status: types_1.LogEventStatus.PROCESSING }));
3269
3603
  const payload = {
3270
3604
  type: types_1.FeatureEventTypes.NOTIFICATION,
3271
3605
  event,
@@ -3309,7 +3643,7 @@ class ProcessorService {
3309
3643
  public_key: this.public_key,
3310
3644
  };
3311
3645
  }
3312
- async addToCache(payload) {
3646
+ async addToCache(payload, additional_logs) {
3313
3647
  if (!this.redisClient) {
3314
3648
  throw 'redis client not setup';
3315
3649
  }
@@ -3325,13 +3659,15 @@ class ProcessorService {
3325
3659
  product_tag,
3326
3660
  component_tag,
3327
3661
  component_type }), this.getUserAccess());
3662
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Renewing expired Cache Value', data: { key }, successful_execution: true, status: types_1.LogEventStatus.SUCCESS, cache_tag }));
3328
3663
  await this.redisClient.hSet(key, 'data', encryptedData);
3329
3664
  await this.redisClient.hSet(key, 'lastUpdated', timestamp);
3330
3665
  }
3331
- async fetchFromCache(payload) {
3666
+ async fetchFromCache(payload, additional_logs) {
3332
3667
  var _a;
3333
3668
  const { input, privateKey, cache_tag, expiry } = payload;
3334
3669
  const key = `${cache_tag}-${CryptoJS.SHA512(input)}`;
3670
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Fetching from Cache', data: { key }, status: types_1.LogEventStatus.PROCESSING, cache_tag }));
3335
3671
  if (!this.redisClient) {
3336
3672
  return null;
3337
3673
  }
@@ -3339,8 +3675,10 @@ class ProcessorService {
3339
3675
  if (!record || !record.data || !record.lastUpdated) {
3340
3676
  const checkRemote = await this.processorApiService.fetchRemoteCacheByKey(key, this.getUserAccess());
3341
3677
  if (!checkRemote) {
3678
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Remote Cache Not Found', data: { key }, successful_execution: true, status: types_1.LogEventStatus.FAIL, cache_tag }));
3342
3679
  return null;
3343
3680
  }
3681
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Remote Cache Found', data: { key }, successful_execution: true, status: types_1.LogEventStatus.SUCCESS, cache_tag }));
3344
3682
  record = { data: checkRemote.value, expiresAt: (_a = checkRemote.expiry) === null || _a === void 0 ? void 0 : _a.getTime().toString() };
3345
3683
  }
3346
3684
  if (record.lastUpdated) {
@@ -3348,13 +3686,42 @@ class ProcessorService {
3348
3686
  if (expiry) {
3349
3687
  const expiryTime = lastUpdated + expiry;
3350
3688
  if (Date.now() > expiryTime) {
3689
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Deleting expired Cache Value', data: { key }, successful_execution: true, status: types_1.LogEventStatus.SUCCESS, cache_tag }));
3351
3690
  await this.redisClient.del(key);
3352
3691
  return null;
3353
3692
  }
3354
3693
  }
3355
3694
  }
3695
+ this.logService.add(Object.assign(Object.assign(Object.assign({}, this.baseLogs), additional_logs), { message: 'Cache Found', data: { key }, successful_execution: true, status: types_1.LogEventStatus.SUCCESS, cache_tag }));
3356
3696
  return (0, processor_utils_1.decrypt)(record.data, privateKey);
3357
3697
  }
3698
+ /**
3699
+ * Writes the healthcheck result to Redis cache for fast status retrieval.
3700
+ */
3701
+ async writeHealthcheckResultToCache(data, result) {
3702
+ if (!this.redisClient)
3703
+ return;
3704
+ const key = `healthcheck:${data.product}:${data.healthcheck}:${data.env}`;
3705
+ console.log("LOG TO CACHE", key, JSON.stringify(result));
3706
+ await this.redisClient.set(key, JSON.stringify(result));
3707
+ console.log();
3708
+ }
3709
+ /**
3710
+ * Fetches the latest healthcheck status for a product/env from Redis cache.
3711
+ */
3712
+ async getHealthcheckStatusFromCache(productTag, envSlug) {
3713
+ if (!this.redisClient)
3714
+ return null;
3715
+ const key = `healthcheck:${productTag}:${envSlug}`;
3716
+ const cached = await this.redisClient.get(key);
3717
+ return cached ? JSON.parse(cached) : null;
3718
+ }
3719
+ /**
3720
+ * Updates the healthcheck in the remote DB for a product with all envs' results.
3721
+ */
3722
+ async updateHealthcheckOnProcessor(productTag, envs) {
3723
+ return this.productBuilderService.updateHealthcheck(productTag, { envs });
3724
+ }
3358
3725
  }
3359
3726
  exports.default = ProcessorService;
3360
3727
  //# sourceMappingURL=processor.service.js.map