@devrev/ts-adaas 1.2.0-beta.1 → 1.2.2

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,10 +12,12 @@ const getAttachmentStream = async ({ item, }) => {
12
12
  }
13
13
  catch (error) {
14
14
  if (axios_client_1.axios.isAxiosError(error)) {
15
- console.error('Error while fetching attachment from URL.', (0, index_1.serializeAxiosError)(error));
15
+ console.warn(`Error while fetching attachment ${id} from URL.`, (0, index_1.serializeAxiosError)(error));
16
+ console.warn('Failed attachment metadata', item);
16
17
  }
17
18
  else {
18
- console.error('Error while fetching attachment from URL.', error);
19
+ console.warn(`Error while fetching attachment ${id} from URL.`, error);
20
+ console.warn('Failed attachment metadata', item);
19
21
  }
20
22
  return {
21
23
  error: {
@@ -26,20 +28,27 @@ const getAttachmentStream = async ({ item, }) => {
26
28
  };
27
29
  (0, index_1.processTask)({
28
30
  task: async ({ adapter }) => {
29
- const { error, delay } = await adapter.streamAttachments({
30
- stream: getAttachmentStream,
31
- });
32
- if (delay) {
33
- await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsDelay, {
34
- delay,
31
+ try {
32
+ const response = await adapter.streamAttachments({
33
+ stream: getAttachmentStream,
35
34
  });
35
+ if (response === null || response === void 0 ? void 0 : response.delay) {
36
+ await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsDelay, {
37
+ delay: response.delay,
38
+ });
39
+ }
40
+ else if (response === null || response === void 0 ? void 0 : response.error) {
41
+ await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsError, {
42
+ error: response.error,
43
+ });
44
+ }
45
+ else {
46
+ await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsDone);
47
+ }
36
48
  }
37
- else if (error) {
38
- await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsError, {
39
- error,
40
- });
49
+ catch (error) {
50
+ console.error('An error occured while processing a task.', error);
41
51
  }
42
- await adapter.emit(index_1.ExtractorEventType.ExtractionAttachmentsDone);
43
52
  },
44
53
  onTimeout: async ({ adapter }) => {
45
54
  await adapter.postState();
@@ -6,8 +6,8 @@ const types_1 = require("../../types");
6
6
  task: async ({ adapter }) => {
7
7
  await adapter.emit(types_1.LoaderEventType.UnknownEventType, {
8
8
  error: {
9
- message: 'Event type ' + adapter.event.payload.event_type + ' not supported.'
10
- }
9
+ message: 'Event type ' + adapter.event.payload.event_type + ' not supported.',
10
+ },
11
11
  });
12
12
  },
13
13
  onTimeout: async ({ adapter }) => {
@@ -22,7 +22,6 @@ function processTask({ task, onTimeout, }) {
22
22
  const adapter = new worker_adapter_1.WorkerAdapter({
23
23
  event,
24
24
  adapterState,
25
- parentPort: node_worker_threads_1.parentPort,
26
25
  options,
27
26
  });
28
27
  node_worker_threads_1.parentPort.on(workers_1.WorkerEvent.WorkerMessage, async (message) => {
@@ -10,16 +10,15 @@ import { SpawnFactoryInterface, SpawnInterface } from '../types/workers';
10
10
  * @param {string} workerPath - The path to the worker file
11
11
  * @returns {Promise<Spawn>} - A new instance of Spawn class
12
12
  */
13
- export declare function spawn<ConnectorState>({ event, initialState, workerPath, options, }: SpawnFactoryInterface<ConnectorState>): Promise<boolean | PromiseLike<boolean>>;
13
+ export declare function spawn<ConnectorState>({ event, initialState, workerPath, options, }: SpawnFactoryInterface<ConnectorState>): Promise<void>;
14
14
  export declare class Spawn {
15
15
  private event;
16
- private hasWorkerEmitted;
16
+ private alreadyEmitted;
17
17
  private defaultLambdaTimeout;
18
18
  private lambdaTimeout;
19
- private worker;
20
- private resolve;
21
19
  private timer;
22
20
  private logger;
21
+ private resolve;
23
22
  constructor({ event, worker, options, resolve }: SpawnInterface);
24
23
  private exitFromMainThread;
25
24
  }
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.Spawn = void 0;
4
7
  exports.spawn = spawn;
8
+ const axios_1 = __importDefault(require("axios"));
5
9
  const extraction_1 = require("../types/extraction");
6
10
  const control_protocol_1 = require("../common/control-protocol");
7
11
  const helpers_1 = require("../common/helpers");
@@ -70,7 +74,6 @@ async function spawn({ event, initialState, workerPath, options, }) {
70
74
  const script = getWorkerPath({
71
75
  event,
72
76
  connectorWorkerPath: workerPath,
73
- options,
74
77
  });
75
78
  if (script) {
76
79
  try {
@@ -90,47 +93,58 @@ async function spawn({ event, initialState, workerPath, options, }) {
90
93
  });
91
94
  }
92
95
  catch (error) {
93
- logger.error('Worker error while processing task.', error);
94
- return false;
96
+ logger.error('Worker error while processing task', error);
95
97
  }
96
98
  }
97
99
  else {
98
- await (0, control_protocol_1.emit)({
99
- event,
100
- eventType: extraction_1.ExtractorEventType.UnknownEventType,
101
- data: {
102
- error: {
103
- message: 'Unrecognized event type in spawn ' +
104
- event.payload.event_type +
105
- '.',
100
+ console.error('Script was not found for event type: ' + event.payload.event_type + '.');
101
+ try {
102
+ await (0, control_protocol_1.emit)({
103
+ event,
104
+ eventType: extraction_1.ExtractorEventType.UnknownEventType,
105
+ data: {
106
+ error: {
107
+ message: 'Unrecognized event type in spawn ' +
108
+ event.payload.event_type +
109
+ '.',
110
+ },
106
111
  },
107
- },
108
- });
109
- return false;
112
+ });
113
+ }
114
+ catch (error) {
115
+ if (axios_1.default.isAxiosError(error)) {
116
+ console.error('Error while emitting event', (0, logger_1.serializeAxiosError)(error));
117
+ }
118
+ else {
119
+ console.error('Error while emitting event', error);
120
+ }
121
+ }
110
122
  }
111
123
  }
112
124
  class Spawn {
113
125
  constructor({ event, worker, options, resolve }) {
114
126
  this.defaultLambdaTimeout = 10 * 60 * 1000; // 10 minutes in milliseconds
115
- this.hasWorkerEmitted = false;
127
+ this.alreadyEmitted = false;
116
128
  this.event = event;
129
+ this.logger = new logger_1.Logger({ event, options });
117
130
  this.lambdaTimeout = (options === null || options === void 0 ? void 0 : options.timeout)
118
131
  ? Math.min(options.timeout, this.defaultLambdaTimeout)
119
132
  : this.defaultLambdaTimeout;
120
133
  this.resolve = resolve;
134
+ // if lambda timeout is reached, then send a message to the worker to gracefully exit
121
135
  this.timer = setTimeout(async () => {
122
- this.logger.log('Lambda timeout reached. Exiting.');
123
- if (this.worker) {
124
- this.worker.postMessage({
136
+ this.logger.log('Lambda timeout reached. Sending a message to the worker to gracefully exit.');
137
+ if (worker) {
138
+ worker.postMessage({
125
139
  subject: workers_1.WorkerMessageSubject.WorkerMessageExit,
126
140
  });
127
141
  }
128
142
  else {
143
+ console.log("Worker doesn't exist. Exiting from main thread.");
129
144
  await this.exitFromMainThread();
130
145
  }
131
146
  }, this.lambdaTimeout);
132
- this.logger = new logger_1.Logger({ event, options });
133
- this.worker = worker;
147
+ // if worker exits with process.exit(code) then we need to clear the timer and exit from main thread
134
148
  worker.on(workers_1.WorkerEvent.WorkerExit, async (code) => {
135
149
  this.logger.info('Worker exited with exit code: ' + code + '.');
136
150
  if (this.timer) {
@@ -139,45 +153,57 @@ class Spawn {
139
153
  await this.exitFromMainThread();
140
154
  });
141
155
  worker.on(workers_1.WorkerEvent.WorkerMessage, async (message) => {
142
- if ((message === null || message === void 0 ? void 0 : message.subject) === workers_1.WorkerMessageSubject.WorkerMessageEmitted) {
143
- this.logger.info('Worker has emitted message to ADaaS.');
144
- this.hasWorkerEmitted = true;
145
- }
146
- if ((message === null || message === void 0 ? void 0 : message.subject) === workers_1.WorkerMessageSubject.WorkerMessageDone) {
147
- this.logger.info('Worker has completed work.');
148
- clearTimeout(this.timer);
149
- await this.exitFromMainThread();
150
- }
151
- });
152
- worker.on(workers_1.WorkerEvent.WorkerMessage, (message) => {
153
156
  var _a, _b;
157
+ // if worker send a log message, then log it from the main thread with logger
154
158
  if ((message === null || message === void 0 ? void 0 : message.subject) === workers_1.WorkerMessageSubject.WorkerMessageLog) {
155
159
  const args = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.args;
156
160
  const level = (_b = message.payload) === null || _b === void 0 ? void 0 : _b.level;
157
161
  this.logger.logFn(args, level);
158
162
  }
163
+ // if worker sends a message that it has completed work, then clear the timer and exit from main thread
164
+ if ((message === null || message === void 0 ? void 0 : message.subject) === workers_1.WorkerMessageSubject.WorkerMessageDone) {
165
+ this.logger.info('Worker has completed with executing the task.');
166
+ if (this.timer) {
167
+ clearTimeout(this.timer);
168
+ }
169
+ await this.exitFromMainThread();
170
+ }
171
+ // if worker sends a message that it has emitted an event, then set alreadyEmitted to true
172
+ if ((message === null || message === void 0 ? void 0 : message.subject) === workers_1.WorkerMessageSubject.WorkerMessageEmitted) {
173
+ this.logger.info('Worker has emitted message to ADaaS.');
174
+ this.alreadyEmitted = true;
175
+ }
159
176
  });
160
177
  }
161
178
  async exitFromMainThread() {
162
- if (this.hasWorkerEmitted) {
163
- this.resolve(true);
179
+ if (this.alreadyEmitted) {
180
+ this.resolve();
164
181
  return;
165
182
  }
183
+ this.alreadyEmitted = true;
166
184
  const timeoutEventType = (0, helpers_1.getTimeoutErrorEventType)(this.event.payload.event_type);
167
- if (timeoutEventType !== null) {
185
+ if (timeoutEventType) {
168
186
  const { eventType } = timeoutEventType;
169
- await (0, control_protocol_1.emit)({
170
- eventType,
171
- event: this.event,
172
- data: {
173
- error: {
174
- message: 'Worker has not emitted anything. Exited.',
187
+ try {
188
+ await (0, control_protocol_1.emit)({
189
+ eventType,
190
+ event: this.event,
191
+ data: {
192
+ error: {
193
+ message: 'Worker has not emitted anything. Exited.',
194
+ },
175
195
  },
176
- },
177
- }).then(() => {
178
- this.logger.error('Worker has not emitted anything. Exited.');
179
- this.resolve(true);
180
- });
196
+ });
197
+ this.resolve();
198
+ }
199
+ catch (error) {
200
+ if (axios_1.default.isAxiosError(error)) {
201
+ console.error('Error while emitting event', (0, logger_1.serializeAxiosError)(error));
202
+ }
203
+ else {
204
+ console.error('Error while emitting event', error);
205
+ }
206
+ }
181
207
  }
182
208
  }
183
209
  }
@@ -1,12 +1,12 @@
1
- import { AirdropEvent, ExtractorEventType, EventData, ExternalSystemAttachmentStreamingFunction } from '../types/extraction';
1
+ import { AirdropEvent, ExtractorEventType, EventData, ExternalSystemAttachmentStreamingFunction, ExternalSystemAttachmentProcessors, ProcessAttachmentReturnType, StreamAttachmentsReturnType } from '../types/extraction';
2
2
  import { ExternalSystemAttachment, ExternalSystemLoadingFunction, FileToLoad, LoaderEventType } from '../types/loading';
3
3
  import { AdapterState } from '../state/state.interfaces';
4
4
  import { Artifact } from '../uploader/uploader.interfaces';
5
5
  import { WorkerAdapterInterface, WorkerAdapterOptions } from '../types/workers';
6
6
  import { Repo } from '../repo/repo';
7
- import { RepoInterface } from '../repo/repo.interfaces';
7
+ import { NormalizedAttachment, RepoInterface } from '../repo/repo.interfaces';
8
8
  import { ExternalSystemItem, ItemTypesToLoadParams, ItemTypeToLoad, LoaderReport, LoadItemResponse, LoadItemTypesResponse } from '../types/loading';
9
- export declare function createWorkerAdapter<ConnectorState>({ event, adapterState, parentPort, options, }: WorkerAdapterInterface<ConnectorState>): WorkerAdapter<ConnectorState>;
9
+ export declare function createWorkerAdapter<ConnectorState>({ event, adapterState, options, }: WorkerAdapterInterface<ConnectorState>): WorkerAdapter<ConnectorState>;
10
10
  /**
11
11
  * WorkerAdapter class is used to interact with Airdrop platform. It is passed to the snap-in
12
12
  * as parameter in processTask and onTimeout functions. The class provides
@@ -27,14 +27,13 @@ export declare class WorkerAdapter<ConnectorState> {
27
27
  private adapterState;
28
28
  private _artifacts;
29
29
  private hasWorkerEmitted;
30
- private parentPort;
31
30
  private isTimeout;
32
31
  private repos;
33
32
  private loaderReports;
34
33
  private _processedFiles;
35
34
  private mappers;
36
35
  private uploader;
37
- constructor({ event, adapterState, parentPort, options, }: WorkerAdapterInterface<ConnectorState>);
36
+ constructor({ event, adapterState, options, }: WorkerAdapterInterface<ConnectorState>);
38
37
  get state(): AdapterState<ConnectorState>;
39
38
  set state(value: AdapterState<ConnectorState>);
40
39
  get reports(): LoaderReport[];
@@ -64,6 +63,7 @@ export declare class WorkerAdapter<ConnectorState> {
64
63
  item: ExternalSystemItem;
65
64
  itemTypeToLoad: ItemTypeToLoad;
66
65
  }): Promise<LoadItemResponse>;
66
+ processAttachment(attachment: NormalizedAttachment, stream: ExternalSystemAttachmentStreamingFunction): Promise<ProcessAttachmentReturnType>;
67
67
  loadAttachment({ item, create, }: {
68
68
  item: ExternalSystemAttachment;
69
69
  create: ExternalSystemLoadingFunction<ExternalSystemAttachment>;
@@ -71,25 +71,12 @@ export declare class WorkerAdapter<ConnectorState> {
71
71
  /**
72
72
  * Streams the attachments to the DevRev platform.
73
73
  * The attachments are streamed to the platform and the artifact information is returned.
74
- * @param {string} attachmentsMetadataArtifactId - The artifact ID of the attachments metadata
75
- * @returns {Promise<UploadResponse>} - The response object containing the ssoAttachment artifact information
74
+ * @param {{ stream, processors }: { stream: ExternalSystemAttachmentStreamingFunction, processors?: ExternalSystemAttachmentProcessors }} Params - The parameters to stream the attachments
75
+ * @returns {Promise<StreamAttachmentsReturnType>} - The response object containing the ssoAttachment artifact information
76
76
  * or error information if there was an error
77
77
  */
78
- streamAttachments({ stream, }: {
78
+ streamAttachments<NewBatch>({ stream, processors, }: {
79
79
  stream: ExternalSystemAttachmentStreamingFunction;
80
- }): Promise<{
81
- report: {};
82
- error?: undefined;
83
- delay?: undefined;
84
- } | {
85
- error: {
86
- message: string;
87
- };
88
- report?: undefined;
89
- delay?: undefined;
90
- } | {
91
- delay: number;
92
- report?: undefined;
93
- error?: undefined;
94
- }>;
80
+ processors?: ExternalSystemAttachmentProcessors<ConnectorState, NormalizedAttachment[], NewBatch>;
81
+ }): Promise<StreamAttachmentsReturnType>;
95
82
  }