@izara_project/izara-market-library-service-schemas 1.0.55 → 1.0.56

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 (52) hide show
  1. package/package.json +1 -1
  2. package/src/GenerateCodeLibs/src/GenerateCodeLibs.js +1 -0
  3. package/src/reStructure/TemplateData/EndpointPerService/handler/api/template.ejs +13 -14
  4. package/src/reStructure/TemplateData/EndpointPerService/handler/dsq/template.ejs +14 -11
  5. package/src/reStructure/TemplateData/EndpointPerService/handler/inv/template.ejs +9 -11
  6. package/src/reStructure/TemplateData/EndpointPerService/handler/sqs/template.ejs +16 -13
  7. package/src/reStructure/TemplateData/EndpointPerService/mainFunction/create/template.ejs +15 -4
  8. package/src/reStructure/TemplateData/EndpointPerService/yaml/data.js +18 -15
  9. package/src/reStructure/TemplateData/flowSchema/components/upload/confirmReserved/handler/template.ejs +2 -0
  10. package/src/reStructure/TemplateData/flowSchema/components/upload/confirmReserved/mainFunction/template.ejs +14 -10
  11. package/src/reStructure/TemplateData/flowSchema/components/upload/createObject/mainFunction/data.js +20 -3
  12. package/src/reStructure/TemplateData/flowSchema/components/upload/createObject/mainFunction/template.ejs +8 -14
  13. package/src/reStructure/TemplateData/flowSchema/components/upload/preSignUrl/createPresignUrl/handler/template.ejs +2 -0
  14. package/src/reStructure/TemplateData/flowSchema/components/upload/preSignUrl/createPresignUrl/mainFunction/template.ejs +45 -55
  15. package/src/reStructure/TemplateData/flowSchema/components/upload/preSignUrl/reservedLimit/handler/template.ejs +5 -3
  16. package/src/reStructure/TemplateData/flowSchema/components/upload/preSignUrl/reservedLimit/mainFunction/data.js +4 -3
  17. package/src/reStructure/TemplateData/flowSchema/components/upload/preSignUrl/reservedLimit/mainFunction/template.ejs +31 -40
  18. package/src/reStructure/TemplateData/flowSchema/components/upload/processFile/handler/handlerS3/template.ejs +3 -17
  19. package/src/reStructure/TemplateData/flowSchema/components/upload/processFile/mainFunction/ProcessCsvtemplate.ejs +391 -0
  20. package/src/reStructure/TemplateData/flowSchema/components/upload/processFile/mainFunction/template.ejs +9 -317
  21. package/src/reStructure/TemplateData/flowSchema/components/upload/relate/libs/template.ejs +5 -5
  22. package/src/reStructure/TemplateData/flowSchema/flowSchemaOwnTopic/EndpointComponent/functionYaml/data.js +1 -1
  23. package/src/reStructure/TemplateData/flowSchema/flowSchemaOwnTopic/FlowSchemaComponent/handler/template.ejs +28 -5
  24. package/src/reStructure/TemplateData/flowSchema/flowSchemaOwnTopic/sns-in/data.js +11 -11
  25. package/src/reStructure/TemplateData/flowSchema/generateTemplateData.js +16 -16
  26. package/src/reStructure/TemplateData/flowSchema/register/complete/handler/template.ejs +3 -0
  27. package/src/reStructure/TemplateData/flowSchema/register/complete/mainFunction/template.ejs +1 -1
  28. package/src/reStructure/TemplateData/flowSchema/webSocketComplete/handler/template.ejs +4 -0
  29. package/src/reStructure/TemplateData/flowSchema/webSocketComplete/mainFunction/template.ejs +36 -7
  30. package/src/reStructure/TemplateData/perActionEndpoint/handler/api/template.ejs +2 -2
  31. package/src/reStructure/TemplateData/perActionEndpoint/handler/dsq/template.ejs +2 -2
  32. package/src/reStructure/TemplateData/perActionEndpoint/handler/sqs/template.ejs +2 -2
  33. package/src/reStructure/TemplateData/propertyValueSchema/relationshipPropertyValueSchema/data.js +1 -2
  34. package/src/reStructure/TemplateData/relationshipPerAction/create/action/handler/api/template.ejs +2 -2
  35. package/src/reStructure/TemplateData/relationshipPerAction/create/action/handler/dsq/template.ejs +2 -2
  36. package/src/reStructure/TemplateData/relationshipPerAction/create/action/handler/sqs/template.ejs +2 -2
  37. package/src/reStructure/TemplateData/relationshipPerAction/create/complete/mainFunction/template.ejs +6 -0
  38. package/src/reStructure/TemplateData/relationshipPerAction/delete/action/handler/api/template.ejs +2 -2
  39. package/src/reStructure/TemplateData/relationshipPerAction/delete/action/handler/dsq/template.ejs +2 -2
  40. package/src/reStructure/TemplateData/relationshipPerAction/delete/action/handler/sqs/template.ejs +2 -2
  41. package/src/reStructure/TemplateData/relationshipPerAction/get/action/handler/api/template.ejs +23 -23
  42. package/src/reStructure/TemplateData/relationshipPerAction/get/action/handler/dsq/template.ejs +18 -16
  43. package/src/reStructure/TemplateData/relationshipPerAction/get/action/handler/inv/template.ejs +14 -12
  44. package/src/reStructure/TemplateData/relationshipPerAction/get/action/handler/sqs/template.ejs +21 -19
  45. package/src/reStructure/TemplateData/relationshipPerAction/get/action/mainFunction/template.ejs +2 -0
  46. package/src/reStructure/TemplateData/relationshipPerAction/get/complete/handler/sqs/template.ejs +3 -1
  47. package/src/reStructure/TemplateData/relationshipPerAction/update/action/handler/api/template.ejs +24 -22
  48. package/src/reStructure/TemplateData/relationshipPerAction/update/action/handler/dsq/template.ejs +21 -17
  49. package/src/reStructure/TemplateData/relationshipPerAction/update/action/handler/inv/template.ejs +21 -19
  50. package/src/reStructure/TemplateData/relationshipPerAction/update/action/handler/sqs/template.ejs +20 -20
  51. package/src/reStructure/TemplateData/relationshipPerAction/update/action/mainFunction/template.ejs +1 -1
  52. package/src/reStructure/TemplateData/relationshipPerAction/update/complete/handler/sqs/template.ejs +1 -1
@@ -0,0 +1,391 @@
1
+ /*
2
+ Copyright (C) 2021 Sven Mason <http://izara.io>
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ 'use strict';
19
+
20
+ const callingFlowSharedLib = require('@izara_project/izara-core-library-calling-flow');
21
+ const snsSharedLib = require('@izara_project/izara-core-library-sns');
22
+ const dynamodbSharedLib = require('@izara_project/izara-core-library-dynamodb');
23
+ const lambdaSharedLib = require('@izara_project/izara-core-library-lambda');
24
+
25
+ const externalRequest = require('@izara_project/izara-core-library-external-request')
26
+ const lambda = externalRequest.lambda;
27
+ const sns = externalRequest.sns;
28
+ const NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError;
29
+ const utils = require('@izara_project/izara-market-library-service-schemas/src/MainLibs/src/Utils');
30
+
31
+ const { S3Client, GetObjectCommand, DeleteObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
32
+ const s3 = new S3Client({ region: 'us-east-2' });
33
+
34
+ const hash = require('@izara_project/izara-shared-core').objectHash;
35
+ const Readable = require('stream');
36
+ const { isValidCsv, getNestObject } = require('../../../../libs/source/GenerateCodeLibs');
37
+ const consts = require('@izara_project/izara-market-library-service-schemas/src/GenerateCodeLibs/src/Consts')
38
+ const coreConsts = require('@izara_project/izara-core-library-core/src/Consts');
39
+
40
+
41
+ /**
42
+ * description of function.
43
+ * @param {Object} _izContext
44
+ * @param {CorrelationIds} _izContext.correlationIds - property of _izContext
45
+ * @param {Logger} _izContext.logger - property of _izContext
46
+ * @param {Logger} _izContext.logger.debug - property of _izContext
47
+ * @param {Object} bucket - bucket's data
48
+ * @param {Array} field - image's data
49
+ * @param {Array} importBy - 'webSocket' || 'importData'
50
+ * @param {Array} imageImportId - from importData
51
+ * @param {Array} realImageSize - from importData
52
+ * @param {Array} passBackProperties - from importData
53
+ *
54
+ * @returns {object} returnResponse
55
+ */
56
+
57
+ module.exports.processAfterUpload = async (
58
+ _izContext,
59
+ bucket,
60
+ field,
61
+ importBy = '',
62
+ importBatchId = '',
63
+ realImageSize = 0,
64
+ passBackProperties = {}
65
+ ) => {
66
+
67
+ try {
68
+
69
+ _izContext.logger.debug('----- processImageFile event params ----- ', {
70
+ bucket: bucket,
71
+ field: field,
72
+ importBy: importBy,
73
+ importBatchId: importBatchId,
74
+ realImageSize: realImageSize,
75
+ passBackProperties: passBackProperties
76
+ })
77
+
78
+ let errorsFound = [];
79
+
80
+ const objectS3Param = {
81
+ Bucket: bucket.name,
82
+ Key: field.key
83
+ }
84
+ _izContext.logger.debug("params before getObjectParam::", objectS3Param)
85
+
86
+ const fileObjectS3 = await s3.send(new GetObjectCommand(objectS3Param));
87
+ _izContext.logger.debug("get fileObjectS3", fileObjectS3);
88
+
89
+ importBatchId = fileObjectS3.Metadata.importbatchid
90
+
91
+ let getImportBatchMain = await lambda.invokeSync(_izContext,
92
+ await lambdaSharedLib.lambdaFunctionName(_izContext, "ImportBatchMainGetHdrInv"),
93
+ {
94
+ identifiers: {
95
+ importBatchId: importBatchId
96
+ }
97
+ }
98
+ )
99
+
100
+ _izContext.logger.debug("getImportBatchMain", getImportBatchMain)
101
+ _izContext.correlationIds.set(coreConsts.BASE_USER_ID, getImportBatchMain.fields.userId);
102
+ _izContext.correlationIds.set(coreConsts.TARGET_ID, getImportBatchMain.fields.submittedByUserId);
103
+
104
+ let userId = _izContext.correlationIds.get(coreConsts.BASE_USER_ID);
105
+ let targetId = _izContext.correlationIds.get(coreConsts.TARGET_ID);
106
+
107
+ if (Date.now() > getImportBatchMain.fields.expiryTimestamp) {
108
+ errorsFound.push("url expired can't upload")
109
+ let sendMessageUpdateUrlExpired = {
110
+ objInstanceFull: {
111
+ identifiers: {
112
+ importBatchId: importBatchId
113
+ },
114
+ fields: {
115
+ importBatchStatus: "urlExpired",
116
+ errorsFound: "url expired can't upload",
117
+ processingError: true
118
+ }
119
+ }
120
+ }
121
+
122
+ let sendMessageToInImportBatchUpdate = {
123
+ Message: JSON.stringify(sendMessageUpdateUrlExpired),
124
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, "InImportBatchMainUpdate")
125
+ };
126
+
127
+ _izContext.logger.debug("message param before send to updateImportBatchMain", sendMessageToInImportBatchUpdate);
128
+ await sns.publishAsync(_izContext, sendMessageToInImportBatchUpdate);
129
+
130
+ let deleteFileObjectS3 = await s3.send(new DeleteObjectCommand(objectS3Param));
131
+ _izContext.logger.debug("Delete object response: ", deleteFileObjectS3)
132
+
133
+ return
134
+ }
135
+
136
+ if (fileObjectS3) {
137
+ if (!importBatchId) {
138
+ errorsFound.push("cant't get importBatchId from S3 uploaded file");
139
+ }
140
+ } else {
141
+ errorsFound.push("cant't get fileObjectS3 from S3 uploaded file");
142
+ };
143
+
144
+ let fileS3Body = fileObjectS3.Body;
145
+ _izContext.logger.debug("fileS3Body", fileS3Body);
146
+
147
+ let fileS3Buffer = null;
148
+
149
+ if (fileS3Body instanceof Readable) {
150
+ fileS3Buffer = Buffer.concat(await fileS3Body.toArray());
151
+ _izContext.logger.debug("fileS3Buffer", fileS3Buffer)
152
+ } else {
153
+ errorsFound.push('unknown object stream type');
154
+ }
155
+
156
+ // check file type
157
+ // can be strict in function.yml that only trigger if it specific type of file
158
+ const srcKey = field.key;
159
+ const importFieldType = srcKey.match(/\.([^.]*)$/);
160
+ _izContext.logger.debug("importFieldType", importFieldType);
161
+ if (!importFieldType) {
162
+ throw new NoRetryError("error fileType")
163
+ };
164
+
165
+ const importKeyType = utils.firstLetterLowerCase(importFieldType[1]);
166
+ _izContext.logger.debug("importKeyType", importKeyType);
167
+
168
+ if (importKeyType === "csv") {
169
+ // check valid CSV file
170
+ let [validCsv, errorCheckCsv] = await isValidCsv(_izContext, fileObjectS3)
171
+ _izContext.logger.debug("validCsv check::", { validCsv, errorsFound })
172
+ if (errorCheckCsv.length) {
173
+ errorsFound.push(errorCheckCsv[0])
174
+ }
175
+
176
+ // check file size
177
+ let reservedFileSize = getImportBatchMain.fields.fileSize;
178
+ _izContext.logger.debug("initialFileSize::", reservedFileSize)
179
+ let s3FileSize = fileObjectS3.ContentLength / 1048576 // convert back to byte unit
180
+ _izContext.logger.debug("s3FileSize in MiB::", s3FileSize)
181
+
182
+ if (s3FileSize < 0.5) { // round up to 1
183
+ s3FileSize = 1
184
+ }
185
+
186
+ let reservedData = await dynamodbSharedLib.getItem(_izContext,
187
+ await dynamodbSharedLib.tableName(_izContext, "ReservedDataMain"),
188
+ {
189
+ servicePendingId: importBatchId,
190
+ reservedDataId: `${consts.ACCOUNTLIMIT_TAG.reservedDynamic}_${getImportBatchMain.fields.userId}_${consts.LIMIT_TAG.uploadData}`
191
+ }
192
+ )
193
+ _izContext.logger.debug("reservedData::", reservedData);
194
+
195
+ let sizeDiff;
196
+
197
+ if (s3FileSize > reservedFileSize) {
198
+ sizeDiff = s3FileSize - reservedFileSize;
199
+
200
+
201
+ if (sizeDiff < 1) {
202
+
203
+ // send message to confirmUsage
204
+ let confirmUsageMessage = {
205
+ userId: userId,
206
+ limitTag: consts.LIMIT_TAG.uploadData,
207
+ uniqueIdentify: reservedData.uniqueIdentify,
208
+ }
209
+
210
+ let sendMessageToConfirmUsage = {
211
+ Message: JSON.stringify(confirmUsageMessage),
212
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, 'InConfirmUsage', consts.EXTERNAL_SERVICE_NAME.accountLimits)
213
+ };
214
+ _izContext.logger.debug("sendMessageToConfirmUsage", sendMessageToConfirmUsage);
215
+ await sns.publishAsync(_izContext, sendMessageToConfirmUsage);
216
+
217
+ let sendMessageToUpdateImportBatchStatus = {
218
+ objInstanceFull: {
219
+ identifiers: {
220
+ importBatchId: servicePendingId
221
+ },
222
+ fields: {
223
+ importBatchStatus: 'uploadComplete'
224
+ }
225
+ }
226
+ }
227
+
228
+ let sendMessageToUpdateImportBatch = {
229
+ Message: JSON.stringify(sendMessageToUpdateImportBatchStatus),
230
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, `InImportBatchMainUpdate`)
231
+ };
232
+ _izContext.logger.debug("sendMessageToUpdateImportBatch", sendMessageToUpdateImportBatch);
233
+ await sns.publishAsync(_izContext, sendMessageToUpdateImportBatch);
234
+
235
+ }
236
+ } else if (s3FileSize < reservedFileSize) {
237
+ sizeDiff = reservedFileSize - s3FileSize;
238
+
239
+ if (sizeDiff < 1) {
240
+ let confirmUsageMessage = {
241
+ userId: userId,
242
+ limitTag: consts.LIMIT_TAG.uploadData,
243
+ uniqueIdentify: reservedData.uniqueIdentify,
244
+ }
245
+
246
+ let sendMessageToConfirmUsage = {
247
+ Message: JSON.stringify(confirmUsageMessage),
248
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, 'InConfirmUsage', consts.EXTERNAL_SERVICE_NAME.accountLimits)
249
+ };
250
+ _izContext.logger.debug("sendMessageToConfirmUsage", sendMessageToConfirmUsage);
251
+ await sns.publishAsync(_izContext, sendMessageToConfirmUsage);
252
+
253
+ let sendMessageToUpdateImportBatchStatus = {
254
+ objInstanceFull: {
255
+ identifiers: {
256
+ importBatchId: servicePendingId
257
+ },
258
+ fields: {
259
+ importBatchStatus: 'uploadComplete'
260
+ }
261
+ }
262
+ }
263
+
264
+ let sendMessageToUpdateImportBatch = {
265
+ Message: JSON.stringify(sendMessageToUpdateImportBatchStatus),
266
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, `InImportBatchMainUpdate`)
267
+ };
268
+ _izContext.logger.debug("sendMessageToUpdateImportBatch", sendMessageToUpdateImportBatch);
269
+ await sns.publishAsync(_izContext, sendMessageToUpdateImportBatch);
270
+
271
+ } else {
272
+ let realFileSize = Math.round(s3FileSize);
273
+ // cancel reserved -> new reserved -> confirm
274
+ // cancel
275
+ let sendMessageToCancelReserved = {
276
+ Message: JSON.stringify({
277
+ userId: userId,
278
+ limitTag: consts.LIMIT_TAG.uploadData,
279
+ uniqueIdentify: reservedData.uniqueIdentify
280
+ }),
281
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, 'InCancelUsage', consts.EXTERNAL_SERVICE_NAME.accountLimits)
282
+ };
283
+ _izContext.logger.debug("sendMessageToCancelReserved", sendMessageToCancelReserved);
284
+ await sns.publishAsync(_izContext, sendMessageToCancelReserved);
285
+
286
+ // new reserved
287
+ let originTimestamp = Date.now();
288
+ let messageObjReserved = {
289
+ userId: userId,
290
+ limitTag: consts.LIMIT_TAG.uploadData,
291
+ value: realFileSize,
292
+ rbacType: consts.RBAC_TYPE.appLevel,
293
+ usedTimestamp: originTimestamp,
294
+ targetUserId: targetId
295
+ }
296
+
297
+ let callingFlowProperties = {
298
+ identifier: {
299
+ servicePendingId: importBatchId,
300
+ reservedDataId: `${consts.ACCOUNTLIMIT_TAG.reservedDynamic}_${getImportBatchMain.fields.userId}_${consts.LIMIT_TAG.uploadData}`,
301
+ userId: getImportBatchMain.fields.userId,
302
+ realSize: realFileSize
303
+ }
304
+ }
305
+
306
+ messageObjReserved = callingFlowSharedLib.addCallingFlowToSnsRequestMessageObject(
307
+ messageObjReserved,
308
+ callingFlowSharedLib.createCallingFlowConfig(
309
+ await lambdaSharedLib.lambdaFunctionName(_izContext, "ConfirmNewReservedHdrSqs"),
310
+ callingFlowProperties
311
+ )
312
+ )
313
+ _izContext.logger.debug('after add callingFlow: ', messageObjReserved)
314
+
315
+ let sendMessageToReservedDynamic = {
316
+ Message: JSON.stringify(messageObjReserved),
317
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, 'InReservedDynamicUsage', consts.EXTERNAL_SERVICE_NAME.accountLimits)
318
+ };
319
+
320
+ _izContext.logger.debug("sendMessageToReservedDynamic", sendMessageToReservedDynamic);
321
+ await sns.publishAsync(_izContext, sendMessageToReservedDynamic);
322
+ };
323
+ } else if (s3FileSize === reservedFileSize) {
324
+ let confirmUsageMessage = {
325
+ userId: getImportBatchMain.fields.userId,
326
+ limitTag: consts.LIMIT_TAG.uploadData,
327
+ uniqueIdentify: reservedData.uniqueIdentify,
328
+ }
329
+
330
+ let sendMessageToConfirmUsage = {
331
+ Message: JSON.stringify(confirmUsageMessage),
332
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, 'InConfirmUsage', consts.EXTERNAL_SERVICE_NAME.accountLimits)
333
+ };
334
+ _izContext.logger.debug("sendMessageToConfirmUsage", sendMessageToConfirmUsage);
335
+ await sns.publishAsync(_izContext, sendMessageToConfirmUsage);
336
+
337
+ let sendMessageToUpdateImportBatchStatus = {
338
+ objInstanceFull: {
339
+ identifiers: {
340
+ importBatchId: servicePendingId
341
+ },
342
+ fields: {
343
+ importBatchStatus: 'uploadComplete'
344
+ }
345
+ }
346
+ }
347
+
348
+ let sendMessageToUpdateImportBatch = {
349
+ Message: JSON.stringify(sendMessageToUpdateImportBatchStatus),
350
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, `InImportBatchMainUpdate`)
351
+ };
352
+ _izContext.logger.debug("sendMessageToUpdateImportBatch", sendMessageToUpdateImportBatch);
353
+ await sns.publishAsync(_izContext, sendMessageToUpdateImportBatch);
354
+
355
+ }
356
+
357
+ } else {
358
+ errorsFound.push("error importKeyType")
359
+ }
360
+
361
+ if (errorsFound.length) { // if error send message to update error in importBatchMain
362
+ let updateImportBatchMainError = {
363
+ objInstanceFull: {
364
+ identifiers: {
365
+ importBatchId: importBatchId
366
+ },
367
+ fields: {
368
+ importBatchStatus: "errorToUpload",
369
+ errorsFound: errorsFound,
370
+ processingError: true
371
+ }
372
+ }
373
+ }
374
+
375
+ let sendMessageToUpdateImportBatchMain = {
376
+ Message: JSON.stringify(updateImportBatchMainError),
377
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, "InImportBatchMainUpdate")
378
+ };
379
+ _izContext.logger.debug('sendMessageToUpdateImportBatchMain::', sendMessageToUpdateImportBatchMain);
380
+ await sns.publishAsync(_izContext, sendMessageToUpdateImportBatchMain);
381
+
382
+ let deleteFileObjectS3 = await s3.send(new DeleteObjectCommand(objectS3Param));
383
+ _izContext.logger.debug("Delete object response: ", deleteFileObjectS3)
384
+
385
+ }
386
+
387
+ } catch (err) {
388
+ _izContext.logger.error('error ProcessImageAfterUploadMain: ', err)
389
+ throw (err)
390
+ }
391
+ }