@devrev/ts-adaas 1.13.4-beta.3 → 1.13.4-beta.4

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.
@@ -12,6 +12,7 @@ const constants_1 = require("../../common/constants");
12
12
  const control_protocol_1 = require("../../common/control-protocol");
13
13
  const worker_adapter_helpers_1 = require("./worker-adapter.helpers");
14
14
  const logger_1 = require("../../logger/logger");
15
+ const logger_context_1 = require("../../logger/logger.context");
15
16
  const mappers_1 = require("../../mappers/mappers");
16
17
  const mappers_interface_1 = require("../../mappers/mappers.interface");
17
18
  const repo_1 = require("../../repo/repo");
@@ -94,15 +95,19 @@ class WorkerAdapter {
94
95
  });
95
96
  }
96
97
  getRepo(itemType) {
97
- const repo = this.repos.find((repo) => repo.itemType === itemType);
98
- if (!repo) {
99
- console.error(`Repo for item type ${itemType} not found.`);
100
- return;
101
- }
102
- return repo;
98
+ return (0, logger_context_1.runWithSdkLogContext)(() => {
99
+ const repo = this.repos.find((repo) => repo.itemType === itemType);
100
+ if (!repo) {
101
+ console.error(`Repo for item type ${itemType} not found.`);
102
+ return;
103
+ }
104
+ return repo;
105
+ });
103
106
  }
104
107
  async postState() {
105
- await this.adapterState.postState();
108
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
109
+ await this.adapterState.postState();
110
+ });
106
111
  }
107
112
  get artifacts() {
108
113
  return this._artifacts;
@@ -119,64 +124,66 @@ class WorkerAdapter {
119
124
  * @param data - The data to be sent with the event
120
125
  */
121
126
  async emit(newEventType, data) {
122
- newEventType = (0, event_type_translation_1.translateOutgoingEventType)(newEventType);
123
- if (this.hasWorkerEmitted) {
124
- console.warn(`Trying to emit event with event type: ${newEventType}. Ignoring emit request because it has already been emitted.`);
125
- return;
126
- }
127
- // We want to upload all the repos before emitting the event, except for the external sync units done event
128
- if (newEventType !== extraction_1.ExtractorEventType.ExternalSyncUnitExtractionDone) {
129
- console.log(`Uploading all repos before emitting event with event type: ${newEventType}.`);
130
- try {
131
- await this.uploadAllRepos();
132
- }
133
- catch (error) {
134
- console.error('Error while uploading repos', error);
135
- node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(workers_1.WorkerMessageSubject.WorkerMessageExit);
136
- this.hasWorkerEmitted = true;
127
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
128
+ newEventType = (0, event_type_translation_1.translateOutgoingEventType)(newEventType);
129
+ if (this.hasWorkerEmitted) {
130
+ console.warn(`Trying to emit event with event type: ${newEventType}. Ignoring emit request because it has already been emitted.`);
137
131
  return;
138
132
  }
139
- }
140
- // If the extraction is done, we want to save the timestamp of the last successful sync
141
- if (newEventType === extraction_1.ExtractorEventType.AttachmentExtractionDone) {
142
- console.log(`Overwriting lastSuccessfulSyncStarted with lastSyncStarted (${this.state.lastSyncStarted}).`);
143
- this.state.lastSuccessfulSyncStarted = this.state.lastSyncStarted;
144
- this.state.lastSyncStarted = '';
145
- }
146
- // We want to save the state every time we emit an event, except for the start and delete events
147
- if (!constants_1.STATELESS_EVENT_TYPES.includes(this.event.payload.event_type)) {
148
- console.log(`Saving state before emitting event with event type: ${newEventType}.`);
133
+ // We want to upload all the repos before emitting the event, except for the external sync units done event
134
+ if (newEventType !== extraction_1.ExtractorEventType.ExternalSyncUnitExtractionDone) {
135
+ console.log(`Uploading all repos before emitting event with event type: ${newEventType}.`);
136
+ try {
137
+ await this.uploadAllRepos();
138
+ }
139
+ catch (error) {
140
+ console.error('Error while uploading repos', error);
141
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(workers_1.WorkerMessageSubject.WorkerMessageExit);
142
+ this.hasWorkerEmitted = true;
143
+ return;
144
+ }
145
+ }
146
+ // If the extraction is done, we want to save the timestamp of the last successful sync
147
+ if (newEventType === extraction_1.ExtractorEventType.AttachmentExtractionDone) {
148
+ console.log(`Overwriting lastSuccessfulSyncStarted with lastSyncStarted (${this.state.lastSyncStarted}).`);
149
+ this.state.lastSuccessfulSyncStarted = this.state.lastSyncStarted;
150
+ this.state.lastSyncStarted = '';
151
+ }
152
+ // We want to save the state every time we emit an event, except for the start and delete events
153
+ if (!constants_1.STATELESS_EVENT_TYPES.includes(this.event.payload.event_type)) {
154
+ console.log(`Saving state before emitting event with event type: ${newEventType}.`);
155
+ try {
156
+ await this.adapterState.postState(this.state);
157
+ }
158
+ catch (error) {
159
+ console.error('Error while posting state', error);
160
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(workers_1.WorkerMessageSubject.WorkerMessageExit);
161
+ this.hasWorkerEmitted = true;
162
+ return;
163
+ }
164
+ }
149
165
  try {
150
- await this.adapterState.postState(this.state);
166
+ await (0, control_protocol_1.emit)({
167
+ eventType: newEventType,
168
+ event: this.event,
169
+ data: Object.assign(Object.assign({}, data), (constants_1.ALLOWED_EXTRACTION_EVENT_TYPES.includes(this.event.payload.event_type)
170
+ ? { artifacts: this.artifacts }
171
+ : {})),
172
+ });
173
+ const message = {
174
+ subject: workers_1.WorkerMessageSubject.WorkerMessageEmitted,
175
+ payload: { eventType: newEventType },
176
+ };
177
+ this.artifacts = [];
178
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(message);
179
+ this.hasWorkerEmitted = true;
151
180
  }
152
181
  catch (error) {
153
- console.error('Error while posting state', error);
182
+ console.error(`Error while emitting event with event type: ${newEventType}.`, (0, logger_1.serializeError)(error));
154
183
  node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(workers_1.WorkerMessageSubject.WorkerMessageExit);
155
184
  this.hasWorkerEmitted = true;
156
- return;
157
185
  }
158
- }
159
- try {
160
- await (0, control_protocol_1.emit)({
161
- eventType: newEventType,
162
- event: this.event,
163
- data: Object.assign(Object.assign({}, data), (constants_1.ALLOWED_EXTRACTION_EVENT_TYPES.includes(this.event.payload.event_type)
164
- ? { artifacts: this.artifacts }
165
- : {})),
166
- });
167
- const message = {
168
- subject: workers_1.WorkerMessageSubject.WorkerMessageEmitted,
169
- payload: { eventType: newEventType },
170
- };
171
- this.artifacts = [];
172
- node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(message);
173
- this.hasWorkerEmitted = true;
174
- }
175
- catch (error) {
176
- console.error(`Error while emitting event with event type: ${newEventType}.`, (0, logger_1.serializeError)(error));
177
- node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage(workers_1.WorkerMessageSubject.WorkerMessageExit);
178
- this.hasWorkerEmitted = true;
179
- }
186
+ });
180
187
  }
181
188
  async uploadAllRepos() {
182
189
  for (const repo of this.repos) {
@@ -191,383 +198,393 @@ class WorkerAdapter {
191
198
  this.isTimeout = true;
192
199
  }
193
200
  async loadItemTypes({ itemTypesToLoad, }) {
194
- var _a;
195
- if (this.event.payload.event_type === extraction_1.EventType.StartLoadingData) {
196
- const itemTypes = itemTypesToLoad.map((itemTypeToLoad) => itemTypeToLoad.itemType);
197
- if (!itemTypes.length) {
198
- console.warn('No item types to load, returning.');
201
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
202
+ var _a;
203
+ if (this.event.payload.event_type === extraction_1.EventType.StartLoadingData) {
204
+ const itemTypes = itemTypesToLoad.map((itemTypeToLoad) => itemTypeToLoad.itemType);
205
+ if (!itemTypes.length) {
206
+ console.warn('No item types to load, returning.');
207
+ return {
208
+ reports: this.reports,
209
+ processed_files: this.processedFiles,
210
+ };
211
+ }
212
+ const filesToLoad = await this.getLoaderBatches({
213
+ supportedItemTypes: itemTypes,
214
+ });
215
+ this.adapterState.state.fromDevRev = {
216
+ filesToLoad,
217
+ };
218
+ }
219
+ if (!this.adapterState.state.fromDevRev ||
220
+ !this.adapterState.state.fromDevRev.filesToLoad.length) {
221
+ console.warn('No files to load, returning.');
199
222
  return {
200
223
  reports: this.reports,
201
224
  processed_files: this.processedFiles,
202
225
  };
203
226
  }
204
- const filesToLoad = await this.getLoaderBatches({
205
- supportedItemTypes: itemTypes,
206
- });
207
- this.adapterState.state.fromDevRev = {
208
- filesToLoad,
209
- };
210
- }
211
- if (!this.adapterState.state.fromDevRev ||
212
- !this.adapterState.state.fromDevRev.filesToLoad.length) {
213
- console.warn('No files to load, returning.');
214
- return {
215
- reports: this.reports,
216
- processed_files: this.processedFiles,
217
- };
218
- }
219
- console.log('Files to load in state', (_a = this.adapterState.state.fromDevRev) === null || _a === void 0 ? void 0 : _a.filesToLoad);
220
- outerloop: for (const fileToLoad of this.adapterState.state.fromDevRev
221
- .filesToLoad) {
222
- const itemTypeToLoad = itemTypesToLoad.find((itemTypeToLoad) => itemTypeToLoad.itemType === fileToLoad.itemType);
223
- if (!itemTypeToLoad) {
224
- console.error(`Item type to load not found for item type: ${fileToLoad.itemType}.`);
225
- await this.emit(loading_1.LoaderEventType.DataLoadingError, {
226
- error: {
227
- message: `Item type to load not found for item type: ${fileToLoad.itemType}.`,
228
- },
229
- });
230
- break;
231
- }
232
- if (!fileToLoad.completed) {
233
- const { response, error: transformerFileError } = await this.uploader.getJsonObjectByArtifactId({
234
- artifactId: fileToLoad.id,
235
- isGzipped: true,
236
- });
237
- if (transformerFileError) {
238
- console.error(`Transformer file not found for artifact ID: ${fileToLoad.id}.`);
227
+ console.log('Files to load in state', (_a = this.adapterState.state.fromDevRev) === null || _a === void 0 ? void 0 : _a.filesToLoad);
228
+ outerloop: for (const fileToLoad of this.adapterState.state.fromDevRev
229
+ .filesToLoad) {
230
+ const itemTypeToLoad = itemTypesToLoad.find((itemTypeToLoad) => itemTypeToLoad.itemType === fileToLoad.itemType);
231
+ if (!itemTypeToLoad) {
232
+ console.error(`Item type to load not found for item type: ${fileToLoad.itemType}.`);
239
233
  await this.emit(loading_1.LoaderEventType.DataLoadingError, {
240
234
  error: {
241
- message: `Transformer file not found for artifact ID: ${fileToLoad.id}.`,
235
+ message: `Item type to load not found for item type: ${fileToLoad.itemType}.`,
242
236
  },
243
237
  });
238
+ break;
244
239
  }
245
- const transformerFile = response;
246
- for (let i = fileToLoad.lineToProcess; i < fileToLoad.count; i++) {
247
- const { report, rateLimit } = await this.loadItem({
248
- item: transformerFile[i],
249
- itemTypeToLoad,
240
+ if (!fileToLoad.completed) {
241
+ const { response, error: transformerFileError } = await this.uploader.getJsonObjectByArtifactId({
242
+ artifactId: fileToLoad.id,
243
+ isGzipped: true,
250
244
  });
251
- if (rateLimit === null || rateLimit === void 0 ? void 0 : rateLimit.delay) {
252
- await this.emit(loading_1.LoaderEventType.DataLoadingDelayed, {
253
- delay: rateLimit.delay,
254
- reports: this.reports,
255
- processed_files: this.processedFiles,
245
+ if (transformerFileError) {
246
+ console.error(`Transformer file not found for artifact ID: ${fileToLoad.id}.`);
247
+ await this.emit(loading_1.LoaderEventType.DataLoadingError, {
248
+ error: {
249
+ message: `Transformer file not found for artifact ID: ${fileToLoad.id}.`,
250
+ },
256
251
  });
257
- break outerloop;
258
252
  }
259
- if (report) {
260
- (0, worker_adapter_helpers_1.addReportToLoaderReport)({
261
- loaderReports: this.loaderReports,
262
- report,
253
+ const transformerFile = response;
254
+ for (let i = fileToLoad.lineToProcess; i < fileToLoad.count; i++) {
255
+ const { report, rateLimit } = await this.loadItem({
256
+ item: transformerFile[i],
257
+ itemTypeToLoad,
263
258
  });
264
- fileToLoad.lineToProcess = fileToLoad.lineToProcess + 1;
259
+ if (rateLimit === null || rateLimit === void 0 ? void 0 : rateLimit.delay) {
260
+ await this.emit(loading_1.LoaderEventType.DataLoadingDelayed, {
261
+ delay: rateLimit.delay,
262
+ reports: this.reports,
263
+ processed_files: this.processedFiles,
264
+ });
265
+ break outerloop;
266
+ }
267
+ if (report) {
268
+ (0, worker_adapter_helpers_1.addReportToLoaderReport)({
269
+ loaderReports: this.loaderReports,
270
+ report,
271
+ });
272
+ fileToLoad.lineToProcess = fileToLoad.lineToProcess + 1;
273
+ }
265
274
  }
275
+ fileToLoad.completed = true;
276
+ this._processedFiles.push(fileToLoad.id);
266
277
  }
267
- fileToLoad.completed = true;
268
- this._processedFiles.push(fileToLoad.id);
269
- }
270
- }
271
- return {
272
- reports: this.reports,
273
- processed_files: this.processedFiles,
274
- };
275
- }
276
- async getLoaderBatches({ supportedItemTypes, }) {
277
- var _a;
278
- const statsFileArtifactId = (_a = this.event.payload.event_data) === null || _a === void 0 ? void 0 : _a.stats_file;
279
- if (statsFileArtifactId) {
280
- const { response, error: statsFileError } = await this.uploader.getJsonObjectByArtifactId({
281
- artifactId: statsFileArtifactId,
282
- });
283
- const statsFile = response;
284
- if (statsFileError || statsFile.length === 0) {
285
- return [];
286
278
  }
287
- const filesToLoad = (0, worker_adapter_helpers_1.getFilesToLoad)({
288
- supportedItemTypes,
289
- statsFile,
290
- });
291
- return filesToLoad;
292
- }
293
- return [];
294
- }
295
- async loadAttachments({ create, }) {
296
- var _a, _b;
297
- if (this.event.payload.event_type === extraction_1.EventType.StartLoadingAttachments) {
298
- this.adapterState.state.fromDevRev = {
299
- filesToLoad: await this.getLoaderBatches({
300
- supportedItemTypes: ['attachment'],
301
- }),
302
- };
303
- }
304
- if (!this.adapterState.state.fromDevRev ||
305
- ((_a = this.adapterState.state.fromDevRev) === null || _a === void 0 ? void 0 : _a.filesToLoad.length) === 0) {
306
- console.log('No files to load, returning.');
307
279
  return {
308
280
  reports: this.reports,
309
281
  processed_files: this.processedFiles,
310
282
  };
311
- }
312
- const filesToLoad = (_b = this.adapterState.state.fromDevRev) === null || _b === void 0 ? void 0 : _b.filesToLoad;
313
- outerloop: for (const fileToLoad of filesToLoad) {
314
- if (!fileToLoad.completed) {
315
- const { response, error: transformerFileError } = await this.uploader.getJsonObjectByArtifactId({
316
- artifactId: fileToLoad.id,
317
- isGzipped: true,
283
+ });
284
+ }
285
+ async getLoaderBatches({ supportedItemTypes, }) {
286
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
287
+ var _a;
288
+ const statsFileArtifactId = (_a = this.event.payload.event_data) === null || _a === void 0 ? void 0 : _a.stats_file;
289
+ if (statsFileArtifactId) {
290
+ const { response, error: statsFileError } = await this.uploader.getJsonObjectByArtifactId({
291
+ artifactId: statsFileArtifactId,
318
292
  });
319
- const transformerFile = response;
320
- if (transformerFileError) {
321
- console.error(`Transformer file not found for artifact ID: ${fileToLoad.id}.`);
322
- break outerloop;
293
+ const statsFile = response;
294
+ if (statsFileError || statsFile.length === 0) {
295
+ return [];
323
296
  }
324
- for (let i = fileToLoad.lineToProcess; i < fileToLoad.count; i++) {
325
- const { report, rateLimit } = await this.loadAttachment({
326
- item: transformerFile[i],
327
- create,
297
+ const filesToLoad = (0, worker_adapter_helpers_1.getFilesToLoad)({
298
+ supportedItemTypes,
299
+ statsFile,
300
+ });
301
+ return filesToLoad;
302
+ }
303
+ return [];
304
+ });
305
+ }
306
+ async loadAttachments({ create, }) {
307
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
308
+ var _a, _b;
309
+ if (this.event.payload.event_type === extraction_1.EventType.StartLoadingAttachments) {
310
+ this.adapterState.state.fromDevRev = {
311
+ filesToLoad: await this.getLoaderBatches({
312
+ supportedItemTypes: ['attachment'],
313
+ }),
314
+ };
315
+ }
316
+ if (!this.adapterState.state.fromDevRev ||
317
+ ((_a = this.adapterState.state.fromDevRev) === null || _a === void 0 ? void 0 : _a.filesToLoad.length) === 0) {
318
+ console.log('No files to load, returning.');
319
+ return {
320
+ reports: this.reports,
321
+ processed_files: this.processedFiles,
322
+ };
323
+ }
324
+ const filesToLoad = (_b = this.adapterState.state.fromDevRev) === null || _b === void 0 ? void 0 : _b.filesToLoad;
325
+ outerloop: for (const fileToLoad of filesToLoad) {
326
+ if (!fileToLoad.completed) {
327
+ const { response, error: transformerFileError } = await this.uploader.getJsonObjectByArtifactId({
328
+ artifactId: fileToLoad.id,
329
+ isGzipped: true,
328
330
  });
329
- if (rateLimit === null || rateLimit === void 0 ? void 0 : rateLimit.delay) {
330
- await this.emit(loading_1.LoaderEventType.DataLoadingDelayed, {
331
- delay: rateLimit.delay,
332
- reports: this.reports,
333
- processed_files: this.processedFiles,
334
- });
331
+ const transformerFile = response;
332
+ if (transformerFileError) {
333
+ console.error(`Transformer file not found for artifact ID: ${fileToLoad.id}.`);
335
334
  break outerloop;
336
335
  }
337
- if (report) {
338
- (0, worker_adapter_helpers_1.addReportToLoaderReport)({
339
- loaderReports: this.loaderReports,
340
- report,
336
+ for (let i = fileToLoad.lineToProcess; i < fileToLoad.count; i++) {
337
+ const { report, rateLimit } = await this.loadAttachment({
338
+ item: transformerFile[i],
339
+ create,
341
340
  });
342
- fileToLoad.lineToProcess = fileToLoad.lineToProcess + 1;
341
+ if (rateLimit === null || rateLimit === void 0 ? void 0 : rateLimit.delay) {
342
+ await this.emit(loading_1.LoaderEventType.DataLoadingDelayed, {
343
+ delay: rateLimit.delay,
344
+ reports: this.reports,
345
+ processed_files: this.processedFiles,
346
+ });
347
+ break outerloop;
348
+ }
349
+ if (report) {
350
+ (0, worker_adapter_helpers_1.addReportToLoaderReport)({
351
+ loaderReports: this.loaderReports,
352
+ report,
353
+ });
354
+ fileToLoad.lineToProcess = fileToLoad.lineToProcess + 1;
355
+ }
343
356
  }
357
+ fileToLoad.completed = true;
358
+ this._processedFiles.push(fileToLoad.id);
344
359
  }
345
- fileToLoad.completed = true;
346
- this._processedFiles.push(fileToLoad.id);
347
360
  }
348
- }
349
- return {
350
- reports: this.reports,
351
- processed_files: this.processedFiles,
352
- };
361
+ return {
362
+ reports: this.reports,
363
+ processed_files: this.processedFiles,
364
+ };
365
+ });
353
366
  }
354
367
  async loadItem({ item, itemTypeToLoad, }) {
355
- var _a;
356
- const devrevId = item.id.devrev;
357
- try {
358
- const syncMapperRecordResponse = await this._mappers.getByTargetId({
359
- sync_unit: this.event.payload.event_context.sync_unit,
360
- target: devrevId,
361
- });
362
- const syncMapperRecord = syncMapperRecordResponse.data;
363
- if (!syncMapperRecord) {
364
- console.warn('Failed to get sync mapper record from response.');
365
- return {
366
- error: {
367
- message: 'Failed to get sync mapper record from response.',
368
- },
369
- };
370
- }
371
- // Update item in external system
372
- const { id, modifiedDate, delay, error } = await itemTypeToLoad.update({
373
- item,
374
- mappers: this._mappers,
375
- event: this.event,
376
- });
377
- if (id) {
378
- try {
379
- const syncMapperRecordUpdateResponse = await this._mappers.update(Object.assign(Object.assign({ id: syncMapperRecord.sync_mapper_record.id, sync_unit: this.event.payload.event_context.sync_unit, status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL }, (modifiedDate && {
380
- external_versions: {
381
- add: [
382
- {
383
- modified_date: modifiedDate,
384
- recipe_version: 0,
385
- },
386
- ],
387
- },
388
- })), { external_ids: {
389
- add: [id],
390
- }, targets: {
391
- add: [devrevId],
392
- } }));
393
- console.log('Successfully updated sync mapper record.', syncMapperRecordUpdateResponse.data);
394
- }
395
- catch (error) {
396
- console.warn('Failed to update sync mapper record.', (0, logger_1.serializeError)(error));
368
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
369
+ var _a;
370
+ const devrevId = item.id.devrev;
371
+ try {
372
+ const syncMapperRecordResponse = await this._mappers.getByTargetId({
373
+ sync_unit: this.event.payload.event_context.sync_unit,
374
+ target: devrevId,
375
+ });
376
+ const syncMapperRecord = syncMapperRecordResponse.data;
377
+ if (!syncMapperRecord) {
378
+ console.warn('Failed to get sync mapper record from response.');
397
379
  return {
398
380
  error: {
399
- message: 'Failed to update sync mapper record' + (0, logger_1.serializeError)(error),
381
+ message: 'Failed to get sync mapper record from response.',
400
382
  },
401
383
  };
402
384
  }
403
- return {
404
- report: {
405
- item_type: itemTypeToLoad.itemType,
406
- [loading_1.ActionType.UPDATED]: 1,
407
- },
408
- };
409
- }
410
- else if (delay) {
411
- console.log(`Rate limited while updating item in external system, delaying for ${delay} seconds.`);
412
- return {
413
- rateLimit: {
414
- delay,
415
- },
416
- };
417
- }
418
- else {
419
- console.warn('Failed to update item in external system', error);
420
- return {
421
- report: {
422
- item_type: itemTypeToLoad.itemType,
423
- [loading_1.ActionType.FAILED]: 1,
424
- },
425
- };
426
- }
427
- // TODO: Update mapper (optional)
428
- }
429
- catch (error) {
430
- if (axios_1.default.isAxiosError(error)) {
431
- if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
432
- // Create item in external system if mapper record not found
433
- const { id, modifiedDate, delay, error } = await itemTypeToLoad.create({
434
- item,
435
- mappers: this._mappers,
436
- event: this.event,
437
- });
438
- if (id) {
439
- // Create mapper
440
- try {
441
- const syncMapperRecordCreateResponse = await this._mappers.create(Object.assign({ sync_unit: this.event.payload.event_context.sync_unit, status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL, external_ids: [id], targets: [devrevId] }, (modifiedDate && {
442
- external_versions: [
385
+ // Update item in external system
386
+ const { id, modifiedDate, delay, error } = await itemTypeToLoad.update({
387
+ item,
388
+ mappers: this._mappers,
389
+ event: this.event,
390
+ });
391
+ if (id) {
392
+ try {
393
+ const syncMapperRecordUpdateResponse = await this._mappers.update(Object.assign(Object.assign({ id: syncMapperRecord.sync_mapper_record.id, sync_unit: this.event.payload.event_context.sync_unit, status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL }, (modifiedDate && {
394
+ external_versions: {
395
+ add: [
443
396
  {
444
397
  modified_date: modifiedDate,
445
398
  recipe_version: 0,
446
399
  },
447
400
  ],
448
- })));
449
- console.log('Successfully created sync mapper record.', syncMapperRecordCreateResponse.data);
401
+ },
402
+ })), { external_ids: {
403
+ add: [id],
404
+ }, targets: {
405
+ add: [devrevId],
406
+ } }));
407
+ console.log('Successfully updated sync mapper record.', syncMapperRecordUpdateResponse.data);
408
+ }
409
+ catch (error) {
410
+ console.warn('Failed to update sync mapper record.', (0, logger_1.serializeError)(error));
411
+ return {
412
+ error: {
413
+ message: 'Failed to update sync mapper record' + (0, logger_1.serializeError)(error),
414
+ },
415
+ };
416
+ }
417
+ return {
418
+ report: {
419
+ item_type: itemTypeToLoad.itemType,
420
+ [loading_1.ActionType.UPDATED]: 1,
421
+ },
422
+ };
423
+ }
424
+ else if (delay) {
425
+ console.log(`Rate limited while updating item in external system, delaying for ${delay} seconds.`);
426
+ return {
427
+ rateLimit: {
428
+ delay,
429
+ },
430
+ };
431
+ }
432
+ else {
433
+ console.warn('Failed to update item in external system', error);
434
+ return {
435
+ report: {
436
+ item_type: itemTypeToLoad.itemType,
437
+ [loading_1.ActionType.FAILED]: 1,
438
+ },
439
+ };
440
+ }
441
+ // TODO: Update mapper (optional)
442
+ }
443
+ catch (error) {
444
+ if (axios_1.default.isAxiosError(error)) {
445
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
446
+ // Create item in external system if mapper record not found
447
+ const { id, modifiedDate, delay, error } = await itemTypeToLoad.create({
448
+ item,
449
+ mappers: this._mappers,
450
+ event: this.event,
451
+ });
452
+ if (id) {
453
+ // Create mapper
454
+ try {
455
+ const syncMapperRecordCreateResponse = await this._mappers.create(Object.assign({ sync_unit: this.event.payload.event_context.sync_unit, status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL, external_ids: [id], targets: [devrevId] }, (modifiedDate && {
456
+ external_versions: [
457
+ {
458
+ modified_date: modifiedDate,
459
+ recipe_version: 0,
460
+ },
461
+ ],
462
+ })));
463
+ console.log('Successfully created sync mapper record.', syncMapperRecordCreateResponse.data);
464
+ return {
465
+ report: {
466
+ item_type: itemTypeToLoad.itemType,
467
+ [loading_1.ActionType.CREATED]: 1,
468
+ },
469
+ };
470
+ }
471
+ catch (error) {
472
+ console.warn('Failed to create sync mapper record.', (0, logger_1.serializeError)(error));
473
+ return {
474
+ error: {
475
+ message: 'Failed to create sync mapper record. ' +
476
+ (0, logger_1.serializeError)(error),
477
+ },
478
+ };
479
+ }
480
+ }
481
+ else if (delay) {
450
482
  return {
451
- report: {
452
- item_type: itemTypeToLoad.itemType,
453
- [loading_1.ActionType.CREATED]: 1,
483
+ rateLimit: {
484
+ delay,
454
485
  },
455
486
  };
456
487
  }
457
- catch (error) {
458
- console.warn('Failed to create sync mapper record.', (0, logger_1.serializeError)(error));
488
+ else {
489
+ console.warn('Failed to create item in external system.', (0, logger_1.serializeError)(error));
459
490
  return {
460
- error: {
461
- message: 'Failed to create sync mapper record. ' +
462
- (0, logger_1.serializeError)(error),
491
+ report: {
492
+ item_type: itemTypeToLoad.itemType,
493
+ [loading_1.ActionType.FAILED]: 1,
463
494
  },
464
495
  };
465
496
  }
466
497
  }
467
- else if (delay) {
468
- return {
469
- rateLimit: {
470
- delay,
471
- },
472
- };
473
- }
474
498
  else {
475
- console.warn('Failed to create item in external system.', (0, logger_1.serializeError)(error));
499
+ console.warn('Failed to get sync mapper record.', (0, logger_1.serializeError)(error));
476
500
  return {
477
- report: {
478
- item_type: itemTypeToLoad.itemType,
479
- [loading_1.ActionType.FAILED]: 1,
501
+ error: {
502
+ message: error.message,
480
503
  },
481
504
  };
482
505
  }
483
506
  }
484
- else {
485
- console.warn('Failed to get sync mapper record.', (0, logger_1.serializeError)(error));
486
- return {
487
- error: {
488
- message: error.message,
489
- },
490
- };
491
- }
507
+ console.warn('Failed to get sync mapper record.', (0, logger_1.serializeError)(error));
508
+ return {
509
+ error: {
510
+ message: 'Failed to get sync mapper record. ' + (0, logger_1.serializeError)(error),
511
+ },
512
+ };
492
513
  }
493
- console.warn('Failed to get sync mapper record.', (0, logger_1.serializeError)(error));
494
- return {
495
- error: {
496
- message: 'Failed to get sync mapper record. ' + (0, logger_1.serializeError)(error),
497
- },
498
- };
499
- }
514
+ });
500
515
  }
501
516
  async processAttachment(attachment, stream) {
502
- var _a;
503
- const { httpStream, delay, error } = await stream({
504
- item: attachment,
505
- event: this.event,
506
- });
507
- if (error) {
508
- return { error };
509
- }
510
- else if (delay) {
511
- return { delay };
512
- }
513
- if (httpStream) {
514
- const fileType = httpStream.headers['content-type'] || 'application/octet-stream';
515
- const fileSize = httpStream.headers['content-length']
516
- ? parseInt(httpStream.headers['content-length'])
517
- : undefined;
518
- // Get upload URL
519
- const { error: artifactUrlError, response: artifactUrlResponse } = await this.uploader.getArtifactUploadUrl(attachment.file_name, fileType, fileSize);
520
- if (artifactUrlError) {
521
- console.warn(`Error while preparing artifact for attachment ID ${attachment.id}. Skipping attachment. ` +
522
- (0, logger_1.serializeError)(artifactUrlError));
523
- this.destroyHttpStream(httpStream);
524
- return;
525
- }
526
- if (this.isTimeout) {
527
- this.destroyHttpStream(httpStream);
528
- return;
529
- }
530
- // Stream attachment
531
- const { error: uploadedArtifactError } = await this.uploader.streamArtifact(artifactUrlResponse, httpStream);
532
- if (uploadedArtifactError) {
533
- console.warn(`Error while streaming to artifact for attachment ID ${attachment.id}. Skipping attachment. ` +
534
- (0, logger_1.serializeError)(uploadedArtifactError));
535
- this.destroyHttpStream(httpStream);
536
- return;
517
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
518
+ var _a;
519
+ const { httpStream, delay, error } = await stream({
520
+ item: attachment,
521
+ event: this.event,
522
+ });
523
+ if (error) {
524
+ return { error };
537
525
  }
538
- // Confirm attachment upload
539
- const { error: confirmArtifactUploadError } = await this.uploader.confirmArtifactUpload(artifactUrlResponse.artifact_id);
540
- if (confirmArtifactUploadError) {
541
- console.warn('Error while confirming upload for attachment ID ' +
542
- attachment.id +
543
- '.', confirmArtifactUploadError);
544
- return;
526
+ else if (delay) {
527
+ return { delay };
545
528
  }
546
- const ssorAttachment = {
547
- id: {
548
- devrev: artifactUrlResponse.artifact_id,
549
- external: attachment.id,
550
- },
551
- parent_id: {
552
- external: attachment.parent_id,
553
- },
554
- };
555
- if (attachment.author_id) {
556
- ssorAttachment.actor_id = {
557
- external: attachment.author_id,
529
+ if (httpStream) {
530
+ const fileType = httpStream.headers['content-type'] || 'application/octet-stream';
531
+ const fileSize = httpStream.headers['content-length']
532
+ ? parseInt(httpStream.headers['content-length'])
533
+ : undefined;
534
+ // Get upload URL
535
+ const { error: artifactUrlError, response: artifactUrlResponse } = await this.uploader.getArtifactUploadUrl(attachment.file_name, fileType, fileSize);
536
+ if (artifactUrlError) {
537
+ console.warn(`Error while preparing artifact for attachment ID ${attachment.id}. Skipping attachment. ` +
538
+ (0, logger_1.serializeError)(artifactUrlError));
539
+ this.destroyHttpStream(httpStream);
540
+ return;
541
+ }
542
+ if (this.isTimeout) {
543
+ this.destroyHttpStream(httpStream);
544
+ return;
545
+ }
546
+ // Stream attachment
547
+ const { error: uploadedArtifactError } = await this.uploader.streamArtifact(artifactUrlResponse, httpStream);
548
+ if (uploadedArtifactError) {
549
+ console.warn(`Error while streaming to artifact for attachment ID ${attachment.id}. Skipping attachment. ` +
550
+ (0, logger_1.serializeError)(uploadedArtifactError));
551
+ this.destroyHttpStream(httpStream);
552
+ return;
553
+ }
554
+ // Confirm attachment upload
555
+ const { error: confirmArtifactUploadError } = await this.uploader.confirmArtifactUpload(artifactUrlResponse.artifact_id);
556
+ if (confirmArtifactUploadError) {
557
+ console.warn('Error while confirming upload for attachment ID ' +
558
+ attachment.id +
559
+ '.', confirmArtifactUploadError);
560
+ return;
561
+ }
562
+ const ssorAttachment = {
563
+ id: {
564
+ devrev: artifactUrlResponse.artifact_id,
565
+ external: attachment.id,
566
+ },
567
+ parent_id: {
568
+ external: attachment.parent_id,
569
+ },
558
570
  };
571
+ if (attachment.author_id) {
572
+ ssorAttachment.actor_id = {
573
+ external: attachment.author_id,
574
+ };
575
+ }
576
+ // This will set inline flag in ssor_attachment only if it is explicity
577
+ // set in the attachment object.
578
+ if (attachment.inline === true) {
579
+ ssorAttachment.inline = true;
580
+ }
581
+ else if (attachment.inline === false) {
582
+ ssorAttachment.inline = false;
583
+ }
584
+ await ((_a = this.getRepo('ssor_attachment')) === null || _a === void 0 ? void 0 : _a.push([ssorAttachment]));
559
585
  }
560
- // This will set inline flag in ssor_attachment only if it is explicity
561
- // set in the attachment object.
562
- if (attachment.inline === true) {
563
- ssorAttachment.inline = true;
564
- }
565
- else if (attachment.inline === false) {
566
- ssorAttachment.inline = false;
567
- }
568
- await ((_a = this.getRepo('ssor_attachment')) === null || _a === void 0 ? void 0 : _a.push([ssorAttachment]));
569
- }
570
- return;
586
+ return;
587
+ });
571
588
  }
572
589
  /**
573
590
  * Destroys a stream to prevent memory leaks.
@@ -589,48 +606,50 @@ class WorkerAdapter {
589
606
  }
590
607
  }
591
608
  async loadAttachment({ item, create, }) {
592
- // Create item
593
- const { id, delay, error } = await create({
594
- item,
595
- mappers: this._mappers,
596
- event: this.event,
597
- });
598
- if (delay) {
599
- return {
600
- rateLimit: {
601
- delay,
602
- },
603
- };
604
- }
605
- else if (id) {
606
- try {
607
- const syncMapperRecordCreateResponse = await this._mappers.create({
608
- sync_unit: this.event.payload.event_context.sync_unit,
609
- external_ids: [id],
610
- targets: [item.reference_id],
611
- status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL,
612
- });
613
- console.log('Successfully created sync mapper record.', syncMapperRecordCreateResponse.data);
609
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
610
+ // Create item
611
+ const { id, delay, error } = await create({
612
+ item,
613
+ mappers: this._mappers,
614
+ event: this.event,
615
+ });
616
+ if (delay) {
617
+ return {
618
+ rateLimit: {
619
+ delay,
620
+ },
621
+ };
614
622
  }
615
- catch (error) {
616
- console.warn('Failed to create sync mapper record.', (0, logger_1.serializeError)(error));
623
+ else if (id) {
624
+ try {
625
+ const syncMapperRecordCreateResponse = await this._mappers.create({
626
+ sync_unit: this.event.payload.event_context.sync_unit,
627
+ external_ids: [id],
628
+ targets: [item.reference_id],
629
+ status: mappers_interface_1.SyncMapperRecordStatus.OPERATIONAL,
630
+ });
631
+ console.log('Successfully created sync mapper record.', syncMapperRecordCreateResponse.data);
632
+ }
633
+ catch (error) {
634
+ console.warn('Failed to create sync mapper record.', (0, logger_1.serializeError)(error));
635
+ }
636
+ return {
637
+ report: {
638
+ item_type: 'attachment',
639
+ [loading_1.ActionType.CREATED]: 1,
640
+ },
641
+ };
617
642
  }
618
- return {
619
- report: {
620
- item_type: 'attachment',
621
- [loading_1.ActionType.CREATED]: 1,
622
- },
623
- };
624
- }
625
- else {
626
- console.warn('Failed to create attachment in external system', error);
627
- return {
628
- report: {
629
- item_type: 'attachment',
630
- [loading_1.ActionType.FAILED]: 1,
631
- },
632
- };
633
- }
643
+ else {
644
+ console.warn('Failed to create attachment in external system', error);
645
+ return {
646
+ report: {
647
+ item_type: 'attachment',
648
+ [loading_1.ActionType.FAILED]: 1,
649
+ },
650
+ };
651
+ }
652
+ });
634
653
  }
635
654
  /**
636
655
  * Streams the attachments to the DevRev platform.
@@ -641,86 +660,88 @@ class WorkerAdapter {
641
660
  */
642
661
  async streamAttachments({ stream, processors, batchSize = 1, // By default, we want to stream one attachment at a time
643
662
  }) {
644
- var _a, _b;
645
- if (batchSize <= 0) {
646
- console.warn(`The specified batch size (${batchSize}) is invalid. Using 1 instead.`);
647
- batchSize = 1;
648
- }
649
- if (batchSize > 50) {
650
- console.warn(`The specified batch size (${batchSize}) is too large. Using 50 instead.`);
651
- batchSize = 50;
652
- }
653
- const repos = [
654
- {
655
- itemType: 'ssor_attachment',
656
- },
657
- ];
658
- this.initializeRepos(repos);
659
- const attachmentsMetadata = (_a = this.state.toDevRev) === null || _a === void 0 ? void 0 : _a.attachmentsMetadata;
660
- // If there are no attachments metadata artifact IDs in state, finish here
661
- if (!((_b = attachmentsMetadata === null || attachmentsMetadata === void 0 ? void 0 : attachmentsMetadata.artifactIds) === null || _b === void 0 ? void 0 : _b.length)) {
662
- console.log(`No attachments metadata artifact IDs found in state.`);
663
- return;
664
- }
665
- else {
666
- console.log(`Found ${attachmentsMetadata.artifactIds.length} attachments metadata artifact IDs in state.`);
667
- }
668
- // Loop through the attachments metadata artifact IDs
669
- while (attachmentsMetadata.artifactIds.length > 0) {
670
- const attachmentsMetadataArtifactId = attachmentsMetadata.artifactIds[0];
671
- console.log(`Started processing attachments for attachments metadata artifact ID: ${attachmentsMetadataArtifactId}.`);
672
- const { attachments, error } = await this.uploader.getAttachmentsFromArtifactId({
673
- artifact: attachmentsMetadataArtifactId,
674
- });
675
- if (error) {
676
- console.error(`Failed to get attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
677
- return { error };
663
+ return (0, logger_context_1.runWithSdkLogContext)(async () => {
664
+ var _a, _b;
665
+ if (batchSize <= 0) {
666
+ console.warn(`The specified batch size (${batchSize}) is invalid. Using 1 instead.`);
667
+ batchSize = 1;
678
668
  }
679
- if (!attachments || attachments.length === 0) {
680
- console.warn(`No attachments found for artifact ID: ${attachmentsMetadataArtifactId}.`);
681
- // Remove empty artifact and reset lastProcessed
682
- attachmentsMetadata.artifactIds.shift();
683
- attachmentsMetadata.lastProcessed = 0;
684
- continue;
669
+ if (batchSize > 50) {
670
+ console.warn(`The specified batch size (${batchSize}) is too large. Using 50 instead.`);
671
+ batchSize = 50;
685
672
  }
686
- console.log(`Found ${attachments.length} attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
687
- let response;
688
- if (processors) {
689
- console.log(`Using custom processors for attachments.`);
690
- const reducer = processors.reducer;
691
- const iterator = processors.iterator;
692
- const reducedAttachments = reducer({
693
- attachments,
694
- adapter: this,
695
- batchSize,
696
- });
697
- response = await iterator({
698
- reducedAttachments,
699
- adapter: this,
700
- stream,
701
- });
673
+ const repos = [
674
+ {
675
+ itemType: 'ssor_attachment',
676
+ },
677
+ ];
678
+ this.initializeRepos(repos);
679
+ const attachmentsMetadata = (_a = this.state.toDevRev) === null || _a === void 0 ? void 0 : _a.attachmentsMetadata;
680
+ // If there are no attachments metadata artifact IDs in state, finish here
681
+ if (!((_b = attachmentsMetadata === null || attachmentsMetadata === void 0 ? void 0 : attachmentsMetadata.artifactIds) === null || _b === void 0 ? void 0 : _b.length)) {
682
+ console.log(`No attachments metadata artifact IDs found in state.`);
683
+ return;
702
684
  }
703
685
  else {
704
- console.log(`Using attachments streaming pool for attachments streaming.`);
705
- const attachmentsPool = new attachments_streaming_pool_1.AttachmentsStreamingPool({
706
- adapter: this,
707
- attachments,
708
- batchSize,
709
- stream,
710
- });
711
- response = await attachmentsPool.streamAll();
712
- }
713
- if ((response === null || response === void 0 ? void 0 : response.delay) || (response === null || response === void 0 ? void 0 : response.error)) {
714
- return response;
686
+ console.log(`Found ${attachmentsMetadata.artifactIds.length} attachments metadata artifact IDs in state.`);
715
687
  }
716
- console.log(`Finished processing all attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
717
- attachmentsMetadata.artifactIds.shift();
718
- attachmentsMetadata.lastProcessed = 0;
719
- if (attachmentsMetadata.lastProcessedAttachmentsIdsList) {
720
- attachmentsMetadata.lastProcessedAttachmentsIdsList.length = 0;
688
+ // Loop through the attachments metadata artifact IDs
689
+ while (attachmentsMetadata.artifactIds.length > 0) {
690
+ const attachmentsMetadataArtifactId = attachmentsMetadata.artifactIds[0];
691
+ console.log(`Started processing attachments for attachments metadata artifact ID: ${attachmentsMetadataArtifactId}.`);
692
+ const { attachments, error } = await this.uploader.getAttachmentsFromArtifactId({
693
+ artifact: attachmentsMetadataArtifactId,
694
+ });
695
+ if (error) {
696
+ console.error(`Failed to get attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
697
+ return { error };
698
+ }
699
+ if (!attachments || attachments.length === 0) {
700
+ console.warn(`No attachments found for artifact ID: ${attachmentsMetadataArtifactId}.`);
701
+ // Remove empty artifact and reset lastProcessed
702
+ attachmentsMetadata.artifactIds.shift();
703
+ attachmentsMetadata.lastProcessed = 0;
704
+ continue;
705
+ }
706
+ console.log(`Found ${attachments.length} attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
707
+ let response;
708
+ if (processors) {
709
+ console.log(`Using custom processors for attachments.`);
710
+ const reducer = processors.reducer;
711
+ const iterator = processors.iterator;
712
+ const reducedAttachments = reducer({
713
+ attachments,
714
+ adapter: this,
715
+ batchSize,
716
+ });
717
+ response = await iterator({
718
+ reducedAttachments,
719
+ adapter: this,
720
+ stream,
721
+ });
722
+ }
723
+ else {
724
+ console.log(`Using attachments streaming pool for attachments streaming.`);
725
+ const attachmentsPool = new attachments_streaming_pool_1.AttachmentsStreamingPool({
726
+ adapter: this,
727
+ attachments,
728
+ batchSize,
729
+ stream,
730
+ });
731
+ response = await attachmentsPool.streamAll();
732
+ }
733
+ if ((response === null || response === void 0 ? void 0 : response.delay) || (response === null || response === void 0 ? void 0 : response.error)) {
734
+ return response;
735
+ }
736
+ console.log(`Finished processing all attachments for artifact ID: ${attachmentsMetadataArtifactId}.`);
737
+ attachmentsMetadata.artifactIds.shift();
738
+ attachmentsMetadata.lastProcessed = 0;
739
+ if (attachmentsMetadata.lastProcessedAttachmentsIdsList) {
740
+ attachmentsMetadata.lastProcessedAttachmentsIdsList.length = 0;
741
+ }
721
742
  }
722
- }
723
- return;
743
+ return;
744
+ });
724
745
  }
725
746
  }
726
747
  exports.WorkerAdapter = WorkerAdapter;