@natlibfi/melinda-rest-api-commons 2.2.0-alpha.1 → 2.2.0-alpha.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.
package/README.md CHANGED
@@ -10,27 +10,30 @@ Shared modules for microservices of Melinda rest api import system
10
10
 
11
11
  #### QueueItemState flow for bulk jobs (multiple records, no validations):
12
12
 
13
- |microservice | states |
14
- |-------------| -------------------------------------------------------------------------|
15
- |`http` | -> VALIDATOR.UPLOADING -> VALIDATOR.PENDING_QUEUING -> |
16
- |`validator` | VALIDATOR.QUEUING_IN_PROGRESS -> IMPORTER.IN_QUEUE -> |
17
- |`importer` | IMPORTER.IMPORTING -> IMPORTER.IN_PROCESS -> IMPORTER.IMPORTING -> DONE |
18
- | | |
19
- |any | any -> ERROR if errored
13
+ | microservice | states |
14
+ |--------------|--------------------------------------------------------|
15
+ | `http` | -> VALIDATOR.UPLOADING -> VALIDATOR.PENDING_QUEUING -> |
16
+ | `validator` | VALIDATOR.QUEUING_IN_PROGRESS -> IMPORTER.IN_QUEUE -> |
17
+ | `importer` | IMPORTER.IMPORTING -> IMPORT_JOB_STATEs* -> DONE |
18
+ | | |
19
+ | any | any -> ERROR if errored |
20
20
 
21
+ *IMPORT_JOB_STATEs: EMPTY or IN_QUEUE, PROCESSING -> final: DONE, ERROR, ABORT
21
22
 
22
23
  #### QueueItemState flow for prio jobs (single record):
23
24
 
24
- |microservice | states |
25
- |-------------| -------------------------------------------------------------------------|
26
- |`http` | -> VALIDATOR.PENDING_VALIDATION -> |
27
- |`validator` | VALIDATOR.VALIDATING -> IMPORTER.IN_QUEUE -> |
28
- |`importer` | IMPORTER.IMPORTING -> IMPORTER.IN_PROCESS -> DONE |
29
- | | |
30
- |`http` | any -> ABORT if job has stayed in an active state too long |
31
- |`validator` | VALIDATOR.VALIDATING -> DONE for noop (no-operation) jobs |
32
- | | |
33
- | any | any -> ERROR if errored |
25
+ | microservice | states |
26
+ |--------------|------------------------------------------------------------|
27
+ | `http` | -> VALIDATOR.PENDING_VALIDATION -> |
28
+ | `validator` | VALIDATOR.VALIDATING -> IMPORTER.IN_QUEUE -> |
29
+ | `importer` | IMPORTER.IMPORTING -> IMPORT_JOB_STATEs* -> DONE |
30
+ | | |
31
+ | `http` | any -> ABORT if job has stayed in an active state too long |
32
+ | `validator` | VALIDATOR.VALIDATING -> DONE for noop (no-operation) jobs |
33
+ | | |
34
+ | any | any -> ERROR if errored |
35
+
36
+ *IMPORT_JOB_STATEs: EMPTY or IN_QUEUE, PROCESSING -> final: DONE, ERROR, ABORT
34
37
 
35
38
  ### CHUNK_SIZE
36
39
  Chunck size to execution time ratio (From file to queue: ~450 records in 15sec)
package/dist/constants.js CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.conversionFormats = exports.QUEUE_ITEM_STATE = exports.OPERATIONS = exports.CHUNK_SIZE = void 0;
6
+ exports.conversionFormats = exports.QUEUE_ITEM_STATE = exports.OPERATIONS = exports.IMPORT_JOB_STATE = exports.CHUNK_SIZE = void 0;
7
7
 
8
8
  /**
9
9
  *
@@ -52,6 +52,16 @@ const QUEUE_ITEM_STATE = {
52
52
  ABORT: 'ABORT'
53
53
  };
54
54
  exports.QUEUE_ITEM_STATE = QUEUE_ITEM_STATE;
55
+ const IMPORT_JOB_STATE = {
56
+ EMPTY: 'EMPTY',
57
+ QUEUING: 'QUEUING',
58
+ IN_QUEUE: 'IN_QUEUE',
59
+ PROCESSING: 'PROCESSING',
60
+ DONE: 'DONE',
61
+ ERROR: 'ERROR',
62
+ ABORT: 'ABORT'
63
+ };
64
+ exports.IMPORT_JOB_STATE = IMPORT_JOB_STATE;
55
65
  const OPERATIONS = {
56
66
  CREATE: 'CREATE',
57
67
  UPDATE: 'UPDATE'
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.js"],"names":["QUEUE_ITEM_STATE","VALIDATOR","PENDING_QUEUING","PENDING_VALIDATION","QUEUING_IN_PROGRESS","UPLOADING","VALIDATING","WAITING_FOR_RECORDS","IMPORTER","IMPORTING","IN_PROCESS","IN_QUEUE","DONE","ERROR","ABORT","OPERATIONS","CREATE","UPDATE","CHUNK_SIZE","conversionFormats","MARCXML","ISO2709","JSON"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEO,MAAMA,gBAAgB,GAAG;AAC9BC,EAAAA,SAAS,EAAE;AACTC,IAAAA,eAAe,EAAE,iBADR;AAETC,IAAAA,kBAAkB,EAAE,oBAFX;AAGTC,IAAAA,mBAAmB,EAAE,qBAHZ;AAITC,IAAAA,SAAS,EAAE,WAJF;AAKTC,IAAAA,UAAU,EAAE,YALH;AAMTC,IAAAA,mBAAmB,EAAE;AANZ,GADmB;AAS9BC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,SAAS,EAAE,WADH;AAERC,IAAAA,UAAU,EAAE,YAFJ;AAGRC,IAAAA,QAAQ,EAAE;AAHF,GAToB;AAc9BC,EAAAA,IAAI,EAAE,MAdwB;AAe9BC,EAAAA,KAAK,EAAE,OAfuB;AAgB9BC,EAAAA,KAAK,EAAE;AAhBuB,CAAzB;;AAmBA,MAAMC,UAAU,GAAG;AACxBC,EAAAA,MAAM,EAAE,QADgB;AAExBC,EAAAA,MAAM,EAAE;AAFgB,CAAnB;;AAKA,MAAMC,UAAU,GAAG,GAAnB;;AAEA,MAAMC,iBAAiB,GAAG;AAC/BC,EAAAA,OAAO,EAAE,CADsB;AAE/BC,EAAAA,OAAO,EAAE,CAFsB;AAG/BC,EAAAA,IAAI,EAAE;AAHyB,CAA1B","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\n// QueueItemState flows: see README.md\n\nexport const QUEUE_ITEM_STATE = {\n VALIDATOR: {\n PENDING_QUEUING: 'PENDING_QUEUING',\n PENDING_VALIDATION: 'PENDING_VALIDATION',\n QUEUING_IN_PROGRESS: 'QUEUING_IN_PROGRESS',\n UPLOADING: 'UPLOADING',\n VALIDATING: 'VALIDATING',\n WAITING_FOR_RECORDS: 'WAITING_FOR_RECORDS'\n },\n IMPORTER: {\n IMPORTING: 'IMPORTING',\n IN_PROCESS: 'IN_PROCESS',\n IN_QUEUE: 'IN_QUEUE'\n },\n DONE: 'DONE',\n ERROR: 'ERROR',\n ABORT: 'ABORT'\n};\n\nexport const OPERATIONS = {\n CREATE: 'CREATE',\n UPDATE: 'UPDATE'\n};\n\nexport const CHUNK_SIZE = 100;\n\nexport const conversionFormats = {\n MARCXML: 1,\n ISO2709: 2,\n JSON: 3\n};\n"],"file":"constants.js"}
1
+ {"version":3,"sources":["../src/constants.js"],"names":["QUEUE_ITEM_STATE","VALIDATOR","PENDING_QUEUING","PENDING_VALIDATION","QUEUING_IN_PROGRESS","UPLOADING","VALIDATING","WAITING_FOR_RECORDS","IMPORTER","IMPORTING","IN_PROCESS","IN_QUEUE","DONE","ERROR","ABORT","IMPORT_JOB_STATE","EMPTY","QUEUING","PROCESSING","OPERATIONS","CREATE","UPDATE","CHUNK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;AAHyB,CAA1B","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\n// QueueItemState flows: see README.md\n\nexport const QUEUE_ITEM_STATE = {\n VALIDATOR: {\n PENDING_QUEUING: 'PENDING_QUEUING',\n PENDING_VALIDATION: 'PENDING_VALIDATION',\n QUEUING_IN_PROGRESS: 'QUEUING_IN_PROGRESS',\n UPLOADING: 'UPLOADING',\n VALIDATING: 'VALIDATING',\n WAITING_FOR_RECORDS: 'WAITING_FOR_RECORDS'\n },\n IMPORTER: {\n IMPORTING: 'IMPORTING',\n IN_PROCESS: 'IN_PROCESS',\n IN_QUEUE: 'IN_QUEUE'\n },\n DONE: 'DONE',\n ERROR: 'ERROR',\n ABORT: 'ABORT'\n};\n\nexport const IMPORT_JOB_STATE = {\n EMPTY: 'EMPTY',\n QUEUING: 'QUEUING',\n IN_QUEUE: 'IN_QUEUE',\n PROCESSING: 'PROCESSING',\n DONE: 'DONE',\n ERROR: 'ERROR',\n ABORT: 'ABORT'\n};\n\nexport const OPERATIONS = {\n CREATE: 'CREATE',\n UPDATE: 'UPDATE'\n};\n\nexport const CHUNK_SIZE = 100;\n\nexport const conversionFormats = {\n MARCXML: 1,\n ISO2709: 2,\n JSON: 3\n};\n"],"file":"constants.js"}
package/dist/index.js CHANGED
@@ -9,7 +9,9 @@ var _exportNames = {
9
9
  conversions: true,
10
10
  validations: true,
11
11
  format: true,
12
- logError: true
12
+ logError: true,
13
+ createImportJobState: true,
14
+ createImportJobStateForQuery: true
13
15
  };
14
16
  Object.defineProperty(exports, "amqpFactory", {
15
17
  enumerable: true,
@@ -23,6 +25,18 @@ Object.defineProperty(exports, "conversions", {
23
25
  return _conversion.default;
24
26
  }
25
27
  });
28
+ Object.defineProperty(exports, "createImportJobState", {
29
+ enumerable: true,
30
+ get: function () {
31
+ return _utils.createImportJobState;
32
+ }
33
+ });
34
+ Object.defineProperty(exports, "createImportJobStateForQuery", {
35
+ enumerable: true,
36
+ get: function () {
37
+ return _utils.createImportJobStateForQuery;
38
+ }
39
+ });
26
40
  exports.format = void 0;
27
41
  Object.defineProperty(exports, "logError", {
28
42
  enumerable: true,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA;;AACA;;AACA;;AACA;;AACA;;;;AACA;;AAGA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport mongoFactory from './mongo';\nimport amqpFactory from './amqp';\nimport conversions from './helpers/conversion';\nimport validations from './helpers/validation';\nimport * as format from './helpers/format';\nimport {logError} from './utils';\n\nexport {mongoFactory, amqpFactory, conversions, validations, format, logError};\nexport * from './constants';\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../src/index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA;;AACA;;AACA;;AACA;;AACA;;;;AACA;;AAGA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport mongoFactory from './mongo';\nimport amqpFactory from './amqp';\nimport conversions from './helpers/conversion';\nimport validations from './helpers/validation';\nimport * as format from './helpers/format';\nimport {logError, createImportJobState, createImportJobStateForQuery} from './utils';\n\nexport {mongoFactory, amqpFactory, conversions, validations, format, logError, createImportJobState, createImportJobStateForQuery};\nexport * from './constants';\n"],"file":"index.js"}
package/dist/mongo.js CHANGED
@@ -57,6 +57,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
57
57
  "cataloger":"xxx0000",
58
58
  "oCatalogerIn":"xxx0000"
59
59
  "operation":"UPDATE",
60
+ "operations":["UPDATE", "CREATE"]
60
61
  "contentType":"application/json",
61
62
  "recordLoadParams": {
62
63
  "pActiveLibrary": "XXX00",
@@ -66,6 +67,10 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
66
67
  "pOldNew": "NEW"
67
68
  },
68
69
  "queueItemState":"PENDING_QUEUING",
70
+ "importJobState": {
71
+ "CREATE": "EMPTY",
72
+ "UPDATE": "EMPTY"
73
+ },
69
74
  "creationTime":"2020-01-01T00:00:00.000Z",
70
75
  "modificationTime":"2020-01-01T00:00:01.000Z",
71
76
  "handledIds": []
@@ -86,6 +91,7 @@ async function _default(MONGO_URI, collection) {
86
91
  createPrio,
87
92
  createBulk,
88
93
  checkAndSetState,
94
+ checkAndSetImportJobState,
89
95
  query,
90
96
  queryById,
91
97
  remove,
@@ -94,8 +100,11 @@ async function _default(MONGO_URI, collection) {
94
100
  getOne,
95
101
  getStream,
96
102
  setState,
103
+ setImportJobState,
97
104
  pushIds,
98
- pushMessages
105
+ pushMessages,
106
+ setOperation,
107
+ setOperations
99
108
  };
100
109
 
101
110
  async function createPrio({
@@ -105,6 +114,7 @@ async function _default(MONGO_URI, collection) {
105
114
  operation,
106
115
  noop = undefined,
107
116
  unique = undefined,
117
+ merge = undefined,
108
118
  prio = true
109
119
  }) {
110
120
  const time = (0, _moment.default)().toDate();
@@ -112,13 +122,20 @@ async function _default(MONGO_URI, collection) {
112
122
  correlationId,
113
123
  cataloger,
114
124
  operation,
125
+ operations: [operation],
115
126
  oCatalogerIn,
116
127
  operationSettings: {
117
128
  unique,
118
129
  noop,
119
- prio
130
+ prio,
131
+ merge,
132
+ originalOperation: operation
120
133
  },
121
134
  queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.PENDING_VALIDATION,
135
+ importJobState: {
136
+ CREATE: _constants.IMPORT_JOB_STATE.EMPTY,
137
+ UPDATE: _constants.IMPORT_JOB_STATE.EMPTY
138
+ },
122
139
  creationTime: time,
123
140
  modificationTime: time,
124
141
  handledIds: [],
@@ -140,7 +157,7 @@ async function _default(MONGO_URI, collection) {
140
157
  }
141
158
  }
142
159
 
143
- function createBulk({
160
+ async function createBulk({
144
161
  correlationId,
145
162
  cataloger,
146
163
  oCatalogerIn,
@@ -156,37 +173,61 @@ async function _default(MONGO_URI, collection) {
156
173
  cataloger,
157
174
  oCatalogerIn,
158
175
  operation,
176
+ operations: [operation],
159
177
  operationSettings: {
160
- prio
178
+ prio,
179
+ originalOperation: operation
161
180
  },
162
181
  contentType,
163
182
  recordLoadParams,
164
183
  queueItemState: stream ? _constants.QUEUE_ITEM_STATE.VALIDATOR.UPLOADING : _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS,
184
+ importJobState: {
185
+ CREATE: _constants.IMPORT_JOB_STATE.EMPTY,
186
+ UPDATE: _constants.IMPORT_JOB_STATE.EMPTY
187
+ },
165
188
  creationTime: time,
166
189
  modificationTime: time,
167
190
  handledIds: [],
168
191
  rejectedIds: []
169
- };
170
-
171
- try {
172
- // No await here, promises later
173
- db.collection(collection).insertOne(newQueueItem);
174
- logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
175
- } catch (error) {
176
- (0, _utils.logError)(error);
177
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
192
+ }; // eslint-disable-next-line functional/no-conditional-statement
193
+
194
+ if (stream) {
195
+ try {
196
+ // No await here, promises later
197
+ db.collection(collection).insertOne(newQueueItem);
198
+ logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
199
+ return new Promise((resolve, reject) => {
200
+ const outputStream = gridFSBucket.openUploadStream(correlationId);
201
+ stream.on('error', reject).on('data', chunk => outputStream.write(chunk)).on('end', () => outputStream.end(undefined, undefined, () => {
202
+ resolve(correlationId);
203
+ }));
204
+ });
205
+ } catch (error) {
206
+ (0, _utils.logError)(error);
207
+ throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
208
+ }
178
209
  }
179
210
 
211
+ logger.debug(`No stream`); // eslint-disable-next-line functional/no-conditional-statement
212
+
180
213
  if (!stream) {
181
- return correlationId;
182
- }
214
+ try {
215
+ const result = await db.collection(collection).insertOne(newQueueItem);
216
+
217
+ if (result.acknowledged) {
218
+ logger.info(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
219
+ return {
220
+ correlationId,
221
+ queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
222
+ };
223
+ }
183
224
 
184
- return new Promise((resolve, reject) => {
185
- const outputStream = gridFSBucket.openUploadStream(correlationId);
186
- stream.on('error', reject).on('data', chunk => outputStream.write(chunk)).on('end', () => outputStream.end(undefined, undefined, () => {
187
- resolve(correlationId);
188
- }));
189
- });
225
+ throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
226
+ } catch (error) {
227
+ (0, _utils.logError)(error);
228
+ throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
229
+ }
230
+ }
190
231
  } // Check state that the queueItem has not waited too long and set state
191
232
 
192
233
 
@@ -198,7 +239,9 @@ async function _default(MONGO_URI, collection) {
198
239
  }) {
199
240
  // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR
200
241
  // otherwise it sets queueItem to state ABORT (408, 'Timeout')
201
- const timeOut = await checkTimeOut(correlationId);
242
+ const timeOut = await checkTimeOut({
243
+ correlationId
244
+ });
202
245
 
203
246
  if (timeOut) {
204
247
  return setState({
@@ -209,6 +252,36 @@ async function _default(MONGO_URI, collection) {
209
252
  });
210
253
  }
211
254
 
255
+ return false;
256
+ } // Check state that the queueItem has not waited too long and set state
257
+
258
+
259
+ async function checkAndSetImportJobState({
260
+ correlationId,
261
+ operation,
262
+ importJobState,
263
+ errorMessage = '',
264
+ errorStatus = ''
265
+ }) {
266
+ // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR
267
+ // otherwise it sets queueItem to state ABORT (408, 'Timeout')
268
+ logger.debug(`${correlationId}, ${importJobState}, ${operation}`);
269
+ const timeOut = await checkTimeOut({
270
+ correlationId,
271
+ operation,
272
+ importJobState
273
+ });
274
+
275
+ if (timeOut) {
276
+ return setImportJobState({
277
+ correlationId,
278
+ operation,
279
+ importJobState,
280
+ errorMessage,
281
+ errorStatus
282
+ });
283
+ }
284
+
212
285
  return false;
213
286
  }
214
287
 
@@ -222,16 +295,23 @@ async function _default(MONGO_URI, collection) {
222
295
  return result;
223
296
  }
224
297
 
225
- async function queryById(correlationId, checkModTime) {
298
+ async function queryById({
299
+ correlationId,
300
+ checkModTime = false
301
+ }) {
226
302
  const result = await db.collection(collection).findOne({
227
303
  correlationId
228
304
  });
229
305
 
230
306
  if (checkModTime) {
231
- const timeOut = await checkTimeOut(correlationId);
307
+ const timeOut = await checkTimeOut({
308
+ correlationId
309
+ });
232
310
 
233
311
  if (timeOut) {
234
- return queryById(correlationId);
312
+ return queryById({
313
+ correlationId
314
+ });
235
315
  }
236
316
 
237
317
  return result;
@@ -244,15 +324,18 @@ async function _default(MONGO_URI, collection) {
244
324
  // If the state is already ABORT or ERROR return false
245
325
 
246
326
 
247
- async function checkTimeOut(correlationId) {
327
+ async function checkTimeOut({
328
+ correlationId
329
+ }) {
248
330
  const {
249
331
  modificationTime,
250
- queueitemState: oldState
332
+ queueitemState: oldState,
333
+ importJobState
251
334
  } = await db.collection(collection).findOne({
252
335
  correlationId
253
- });
336
+ }); // should we check for DONE too?
254
337
 
255
- if ([_constants.QUEUE_ITEM_STATE.ABORT, _constants.QUEUE_ITEM_STATE.ERROR].includes(oldState)) {
338
+ if ([_constants.QUEUE_ITEM_STATE.ABORT, _constants.QUEUE_ITEM_STATE.ERROR, _constants.QUEUE_ITEM_STATE.DONE].includes(oldState)) {
256
339
  logger.silly(`${correlationId} has already state: ${oldState}`);
257
340
  return false;
258
341
  }
@@ -261,6 +344,26 @@ async function _default(MONGO_URI, collection) {
261
344
  logger.silly(`timeOut @ ${timeoutTime}`);
262
345
 
263
346
  if (timeoutTime.isBefore()) {
347
+ const finalImportJobStates = [_constants.IMPORT_JOB_STATE.ABORT, _constants.IMPORT_JOB_STATE.DONE, _constants.IMPORT_JOB_STATE.EMPTY, _constants.IMPORT_JOB_STATE.ERROR];
348
+
349
+ if (!finalImportJobStates.includes(importJobState.CREATE)) {
350
+ // eslint-disable-line
351
+ await setImportJobState({
352
+ correlationId,
353
+ operation: 'CREATE',
354
+ importJobState: _constants.IMPORT_JOB_STATE.ABORT
355
+ });
356
+ }
357
+
358
+ if (!finalImportJobStates.includes(importJobState.UPDATE)) {
359
+ // eslint-disable-line
360
+ await setImportJobState({
361
+ correlationId,
362
+ operation: 'UPDATE',
363
+ importJobState: _constants.IMPORT_JOB_STATE.ABORT
364
+ });
365
+ }
366
+
264
367
  await setState({
265
368
  correlationId,
266
369
  state: _constants.QUEUE_ITEM_STATE.ABORT,
@@ -340,30 +443,43 @@ async function _default(MONGO_URI, collection) {
340
443
  }
341
444
 
342
445
  return true;
343
- }
446
+ } // eslint-disable-next-line max-statements
447
+
344
448
 
345
449
  function getOne({
346
- operation,
347
- queueItemState
450
+ queueItemState,
451
+ importJobState = undefined
348
452
  }) {
349
- const clean = {
453
+ logger.silly(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
454
+ const cleanQueueItemState = queueItemState ? {
350
455
  queueItemState: (0, _mongoSanitize.default)(queueItemState)
351
- };
456
+ } : undefined;
352
457
 
353
458
  try {
354
- if (operation === undefined) {
355
- logger.silly(`Checking DB ${collection} for ${JSON.stringify(clean.queueItemState)}`);
356
- return db.collection(collection).findOne({ ...clean
459
+ // Just queueItemState
460
+ if (queueItemState && importJobState === undefined) {
461
+ logger.silly(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
462
+ return db.collection(collection).findOne({ ...cleanQueueItemState
463
+ });
464
+ } // importJobState
465
+
466
+
467
+ if (importJobState && queueItemState === undefined) {
468
+ logger.silly(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
469
+ return db.collection(collection).findOne({ ...importJobState
470
+ });
471
+ } // importJobState and queueItemState
472
+
473
+
474
+ if (importJobState && queueItemState) {
475
+ logger.silly(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
476
+ return db.collection(collection).findOne({ ...cleanQueueItemState,
477
+ ...importJobState
357
478
  });
358
479
  }
359
480
 
360
- const clean2 = {
361
- operation: (0, _mongoSanitize.default)(operation)
362
- };
363
- logger.silly(`Checking DB ${collection} for ${clean.queueItemState} + ${clean2.operation}`);
364
- return db.collection(collection).findOne({ ...clean,
365
- ...clean2
366
- });
481
+ logger.debug(`getOne not working!`);
482
+ throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');
367
483
  } catch (error) {
368
484
  (0, _utils.logError)(error);
369
485
  }
@@ -466,5 +582,102 @@ async function _default(MONGO_URI, collection) {
466
582
  returnNewDocument: true
467
583
  });
468
584
  }
585
+
586
+ function setImportJobState({
587
+ correlationId,
588
+ operation,
589
+ importJobState
590
+ }) {
591
+ // should this also get importJobState as previously created object? {}
592
+ logger.info(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
593
+ const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
594
+ const cleanImportJobState = (0, _mongoSanitize.default)(importJobState);
595
+
596
+ if (!(operation in _constants.OPERATIONS)) {
597
+ throw new _melindaCommons.Error('400', 'Invalid operation for import job state');
598
+ }
599
+
600
+ if (!(cleanImportJobState in _constants.IMPORT_JOB_STATE)) {
601
+ throw new _melindaCommons.Error('400', 'Invalid import job state');
602
+ }
603
+
604
+ const newJobState = operation === _constants.OPERATIONS.CREATE ? {
605
+ 'importJobState.CREATE': cleanImportJobState
606
+ } : {
607
+ 'importJobState.UPDATE': cleanImportJobState
608
+ };
609
+ return db.collection(collection).findOneAndUpdate({
610
+ correlationId: cleanCorrelationId
611
+ }, {
612
+ $set: { ...newJobState,
613
+ modificationTime: (0, _moment.default)().toDate()
614
+ }
615
+ }, {
616
+ projection: {
617
+ _id: 0
618
+ },
619
+ returnNewDocument: true
620
+ });
621
+ }
622
+
623
+ async function setOperation({
624
+ correlationId,
625
+ operation
626
+ }) {
627
+ const newOperation = operation;
628
+ const {
629
+ operation: oldOperation
630
+ } = await db.collection(collection).findOne({
631
+ correlationId
632
+ });
633
+ logger.info(`Setting queue-item operation from ${oldOperation} to ${newOperation} for ${correlationId} to ${collection}`);
634
+ const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
635
+ const cleanNewOperation = (0, _mongoSanitize.default)(newOperation);
636
+ const result = await db.collection(collection).findOneAndUpdate({
637
+ correlationId: cleanCorrelationId
638
+ }, {
639
+ $set: {
640
+ operation: cleanNewOperation,
641
+ modificationTime: (0, _moment.default)().toDate()
642
+ }
643
+ }, {
644
+ projection: {
645
+ _id: 0
646
+ },
647
+ returnNewDocument: true
648
+ });
649
+ return result.ok; // logger.debug(JSON.stringify(result));
650
+ }
651
+
652
+ async function setOperations({
653
+ correlationId,
654
+ addOperation,
655
+ removeOperation = undefined
656
+ }) {
657
+ const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId); //logger.info(`Setting queue-item operation from ${JSON.stringify(oldOperations)} by adding ${addOperation} and removing ${removeOperation} for ${correlationId} to ${collection}`);
658
+
659
+ const queueItem = await db.collection(collection).findOne({
660
+ correlationId: cleanCorrelationId
661
+ });
662
+ logger.debug(`We fould a queueItem: ${JSON.stringify(queueItem)}`);
663
+ const oldOperations = queueItem.operations;
664
+ logger.info(`Setting queue-item operation from ${JSON.stringify(oldOperations)} by adding ${addOperation} and removing ${removeOperation} for ${correlationId} to ${collection}`);
665
+ const operationsAfterRemove = oldOperations.filter(operation => operation !== removeOperation);
666
+ const operationsAfterRemoveAndAdd = [addOperation, ...operationsAfterRemove];
667
+ const result = await db.collection(collection).findOneAndUpdate({
668
+ correlationId: cleanCorrelationId
669
+ }, {
670
+ $set: {
671
+ operations: operationsAfterRemoveAndAdd,
672
+ modificationTime: (0, _moment.default)().toDate()
673
+ }
674
+ }, {
675
+ projection: {
676
+ _id: 0
677
+ },
678
+ returnNewDocument: true
679
+ });
680
+ return result.ok; // logger.debug(JSON.stringify(result));
681
+ }
469
682
  }
470
683
  //# sourceMappingURL=mongo.js.map
package/dist/mongo.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mongo.js"],"names":["MONGO_URI","collection","logger","client","MongoClient","connect","useNewUrlParser","useUnifiedTopology","db","gridFSBucket","GridFSBucket","bucketName","createPrio","createBulk","checkAndSetState","query","queryById","remove","readContent","removeContent","getOne","getStream","setState","pushIds","pushMessages","correlationId","cataloger","oCatalogerIn","operation","noop","undefined","unique","prio","time","toDate","newQueueItem","operationSettings","queueItemState","QUEUE_ITEM_STATE","VALIDATOR","PENDING_VALIDATION","creationTime","modificationTime","handledIds","rejectedIds","result","insertOne","acknowledged","info","ApiError","httpStatus","INTERNAL_SERVER_ERROR","error","contentType","recordLoadParams","stream","UPLOADING","WAITING_FOR_RECORDS","Promise","resolve","reject","outputStream","openUploadStream","on","chunk","write","end","state","errorMessage","errorStatus","timeOut","checkTimeOut","params","find","projection","_id","toArray","debug","length","checkModTime","findOne","queueitemState","oldState","ABORT","ERROR","includes","silly","timeoutTime","add","isBefore","REQUEST_TIMEOUT","JSON","stringify","clean","noContent","deleteOne","err","MongoDriverError","message","indexOf","readStream","openDownloadStreamByName","NOT_FOUND","delete","clean2","verbose","updateOne","$set","$push","$each","messages","messageField","cleanMessageField","errorString","stateInQueueItemStates","Object","values","stateInQueueItemStatesValidator","stateInQueueItemStatesImporter","IMPORTER","BAD_REQUEST","updateValues","keys","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CC,GAAG,IAAIH,YAAY,CAACG,GAAD,CAAZ,KAAsB9F,SAAtB,IAAmC,OAAO2F,YAAY,CAACG,GAAD,CAA/F;AAEA,WAAOpH,EAAE,CAACP,UAAH,CAAcA,UAAd,EACJ4H,gBADI,CAEH;AAACpG,MAAAA,aAAa,EAAEoE;AAAhB,KAFG,EAGH;AAACc,MAAAA,IAAI,EAAEc;AAAP,KAHG,EAIH;AAAC/C,MAAAA,UAAU,EAAE;AAACC,QAAAA,GAAG,EAAE;AAAN,OAAb;AAAuBmD,MAAAA,iBAAiB,EAAE;AAA1C,KAJG,CAAP;AAMD;AACF","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {MongoClient, GridFSBucket, MongoDriverError} from 'mongodb';\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {QUEUE_ITEM_STATE} from './constants';\nimport {logError} from './utils.js';\nimport moment from 'moment';\nimport httpStatus from 'http-status';\nimport sanitize from 'mongo-sanitize';\n\n/* QueueItem:\n{\n \"correlationId\":\"FOO\",\n \"cataloger\":\"xxx0000\",\n \"oCatalogerIn\":\"xxx0000\"\n \"operation\":\"UPDATE\",\n \"contentType\":\"application/json\",\n \"recordLoadParams\": {\n \"pActiveLibrary\": \"XXX00\",\n \"pInputFile\": \"filename.seq\",\n \"pRejectFile\": \"filename.rej\",\n \"pLogFile\": \"filename.syslog\",\n \"pOldNew\": \"NEW\"\n },\n \"queueItemState\":\"PENDING_QUEUING\",\n \"creationTime\":\"2020-01-01T00:00:00.000Z\",\n \"modificationTime\":\"2020-01-01T00:00:01.000Z\",\n \"handledIds\": []\n}\n*/\n\nexport default async function (MONGO_URI, collection) {\n const logger = createLogger();\n\n // Connect to mongo (MONGO)\n const client = await MongoClient.connect(MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});\n const db = client.db('rest-api');\n const gridFSBucket = new GridFSBucket(db, {bucketName: collection});\n\n return {createPrio, createBulk, checkAndSetState, query, queryById, remove, readContent, removeContent, getOne, getStream, setState, pushIds, pushMessages};\n\n async function createPrio({correlationId, cataloger, oCatalogerIn, operation, noop = undefined, unique = undefined, prio = true}) {\n const time = moment().toDate();\n const newQueueItem = {\n correlationId,\n cataloger,\n operation,\n oCatalogerIn,\n operationSettings: {unique, noop, prio},\n queueItemState: QUEUE_ITEM_STATE.VALIDATOR.PENDING_VALIDATION,\n creationTime: time,\n modificationTime: time,\n handledIds: [],\n rejectedIds: []\n };\n try {\n const result = await db.collection(collection).insertOne(newQueueItem);\n if (result.acknowledged) {\n logger.info(`New PRIO queue item for ${operation} ${correlationId} has been made in ${collection}`);\n return;\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n function createBulk({correlationId, cataloger, oCatalogerIn, operation, contentType, recordLoadParams, stream, prio = false}) {\n const time = moment().toDate();\n const newQueueItem = {\n correlationId,\n cataloger,\n oCatalogerIn,\n operation,\n operationSettings: {prio},\n contentType,\n recordLoadParams,\n queueItemState: stream ? QUEUE_ITEM_STATE.VALIDATOR.UPLOADING : QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS,\n creationTime: time,\n modificationTime: time,\n handledIds: [],\n rejectedIds: []\n };\n try {\n // No await here, promises later\n db.collection(collection).insertOne(newQueueItem);\n logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n\n if (!stream) {\n return correlationId;\n }\n\n return new Promise((resolve, reject) => {\n const outputStream = gridFSBucket.openUploadStream(correlationId);\n\n stream\n .on('error', reject)\n .on('data', chunk => outputStream.write(chunk))\n .on('end', () => outputStream.end(undefined, undefined, () => {\n resolve(correlationId);\n }));\n });\n }\n\n // Check state that the queueItem has not waited too long and set state\n async function checkAndSetState({correlationId, state, errorMessage = undefined, errorStatus = undefined}) {\n // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR\n // otherwise it sets queueItem to state ABORT (408, 'Timeout')\n const timeOut = await checkTimeOut(correlationId);\n if (timeOut) {\n return setState({correlationId, state, errorMessage, errorStatus});\n }\n return false;\n }\n\n async function query(params) {\n const result = await db.collection(collection).find(params, {projection: {_id: 0}})\n .toArray();\n logger.debug(`Query result: ${result.length > 0 ? 'Found!' : 'Not found!'}`);\n return result;\n }\n\n async function queryById(correlationId, checkModTime) {\n const result = await db.collection(collection).findOne({correlationId});\n if (checkModTime) {\n const timeOut = await checkTimeOut(correlationId);\n if (timeOut) {\n return queryById(correlationId);\n }\n return result;\n }\n\n return result;\n }\n\n // Check that if the item has waited too long\n // If the last modification time for the queueItem is older than 1 minute\n // set state to ABORT and return false, otherwise return true\n // If the state is already ABORT or ERROR return false\n\n async function checkTimeOut(correlationId) {\n const {modificationTime, queueitemState: oldState} = await db.collection(collection).findOne({correlationId});\n\n if ([QUEUE_ITEM_STATE.ABORT, QUEUE_ITEM_STATE.ERROR].includes(oldState)) {\n logger.silly(`${correlationId} has already state: ${oldState}`);\n return false;\n }\n\n const timeoutTime = moment(modificationTime).add(1, 'm');\n logger.silly(`timeOut @ ${timeoutTime}`);\n\n if (timeoutTime.isBefore()) {\n await setState({correlationId, state: QUEUE_ITEM_STATE.ABORT, errorStatus: httpStatus.REQUEST_TIMEOUT, errorMessage: `Timeout in ${oldState}`});\n return false;\n }\n\n return true;\n }\n\n async function remove(params) {\n logger.silly(`${JSON.stringify(params)}`);\n logger.info(`Removing from Mongo (${collection}) id: ${params.correlationId}`);\n const clean = sanitize(params.correlationId);\n logger.silly(`mongo/remove: clean: ${JSON.stringify(clean)}`);\n\n try {\n //const metadataResult = await getFileMetadata({filename: clean});\n //logger.debug(`mongo/remove: metadataResult: ${JSON.stringify(metadataResult)}`);\n const noContent = await removeContent(params);\n if (noContent) {\n await db.collection(collection).deleteOne({correlationId: clean});\n return true;\n }\n } catch (err) {\n if (err instanceof MongoDriverError) {\n if (err.message.indexOf('File not found for id') !== -1) {\n logger.silly(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);\n await db.collection(collection).deleteOne({correlationId: clean});\n return true;\n }\n logger.error(err.message);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n\n async function readContent(correlationId) {\n logger.info(`Reading content from mongo for id: ${correlationId} in ${collection}`);\n const clean = sanitize(correlationId);\n const result = await db.collection(collection).findOne({correlationId: clean}); // njsscan-ignore: node_nosqli_injection\n\n if (result) {\n return {\n contentType: result.contentType,\n readStream: gridFSBucket.openDownloadStreamByName(clean)\n };\n }\n\n throw new ApiError(httpStatus.NOT_FOUND);\n }\n\n async function removeContent(params) {\n logger.info(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);\n const clean = sanitize(params.correlationId);\n\n const result = await db.collection(collection).findOne({correlationId: clean}); // njsscan-ignore: node_nosqli_injection\n logger.silly(`mongo/removeContent: result ${JSON.stringify(result)}`);\n\n if (result) {\n await gridFSBucket.delete(clean);\n return true;\n }\n\n return true;\n }\n\n function getOne({operation, queueItemState}) {\n const clean = {queueItemState: sanitize(queueItemState)};\n try {\n if (operation === undefined) {\n logger.silly(`Checking DB ${collection} for ${JSON.stringify(clean.queueItemState)}`);\n return db.collection(collection).findOne({...clean});\n }\n\n const clean2 = {operation: sanitize(operation)};\n logger.silly(`Checking DB ${collection} for ${clean.queueItemState} + ${clean2.operation}`);\n return db.collection(collection).findOne({...clean, ...clean2});\n } catch (error) {\n logError(error);\n }\n }\n\n function getStream(correlationId) {\n logger.info(`Forming stream from mongo for ${correlationId} in ${collection}`);\n const clean = sanitize(correlationId);\n try {\n // Return content stream\n return gridFSBucket.openDownloadStreamByName(clean);\n } catch (error) {\n logError(error);\n }\n }\n\n async function pushIds({correlationId, handledIds, rejectedIds}) {\n logger.verbose(`Push ids (${handledIds.length}) and rejectedIds (${rejectedIds.length}) ${correlationId} to ${collection}`);\n logger.debug(`ids (${handledIds.length}): ${JSON.stringify(handledIds)}, rejectedIds ${rejectedIds.length}: ${JSON.stringify(rejectedIds)}`);\n const clean = sanitize(correlationId);\n await db.collection(collection).updateOne({\n correlationId: clean\n }, {\n $set: {\n modificationTime: moment().toDate()\n },\n $push: {\n handledIds: {$each: handledIds},\n rejectedIds: {$each: rejectedIds}\n }\n });\n }\n\n async function pushMessages({correlationId, messages, messageField = 'messages'}) {\n logger.verbose(`Push messages (${messages.length}) to ${messageField} ${correlationId} to ${collection}`);\n logger.silly(`Messages (${messages.length}): ${JSON.stringify(messages)}}`);\n const clean = sanitize(correlationId);\n const cleanMessageField = sanitize(messageField);\n await db.collection(collection).updateOne({\n correlationId: clean\n }, {\n $set: {\n modificationTime: moment().toDate()\n },\n $push: {\n [cleanMessageField]: {$each: messages}\n }\n });\n }\n\n function setState({correlationId, state, errorMessage = undefined, errorStatus = undefined}) {\n const errorString = errorMessage || errorStatus ? `, Error message: '${errorMessage || ''}', Error status: '${errorStatus || ''}'` : '';\n logger.info(`Setting queue-item state ${state} for ${correlationId}${errorString} to ${collection}`);\n\n const stateInQueueItemStates = Object.values(QUEUE_ITEM_STATE).indexOf(state) > -1;\n const stateInQueueItemStatesValidator = Object.values(QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;\n const stateInQueueItemStatesImporter = Object.values(QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;\n if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {\n throw new ApiError(httpStatus.BAD_REQUEST, 'Trying to set invalid state');\n }\n\n const clean = sanitize(correlationId);\n const updateValues = {\n queueItemState: state,\n modificationTime: moment().toDate(),\n errorMessage,\n errorStatus\n };\n\n // Do not update value that are undefined\n // eslint-disable-next-line functional/immutable-data\n Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);\n\n return db.collection(collection)\n .findOneAndUpdate(\n {correlationId: clean},\n {$set: updateValues},\n {projection: {_id: 0}, returnNewDocument: true}\n );\n }\n}\n"],"file":"mongo.js"}
1
+ {"version":3,"sources":["../src/mongo.js"],"names":["MONGO_URI","collection","logger","client","MongoClient","connect","useNewUrlParser","useUnifiedTopology","db","gridFSBucket","GridFSBucket","bucketName","createPrio","createBulk","checkAndSetState","checkAndSetImportJobState","query","queryById","remove","readContent","removeContent","getOne","getStream","setState","setImportJobState","pushIds","pushMessages","setOperation","setOperations","correlationId","cataloger","oCatalogerIn","operation","noop","undefined","unique","merge","prio","time","toDate","newQueueItem","operations","operationSettings","originalOperation","queueItemState","QUEUE_ITEM_STATE","VALIDATOR","PENDING_VALIDATION","importJobState","CREATE","IMPORT_JOB_STATE","EMPTY","UPDATE","creationTime","modificationTime","handledIds","rejectedIds","result","insertOne","acknowledged","info","ApiError","httpStatus","INTERNAL_SERVER_ERROR","error","contentType","recordLoadParams","stream","UPLOADING","WAITING_FOR_RECORDS","Promise","resolve","reject","outputStream","openUploadStream","on","chunk","write","end","debug","state","errorMessage","errorStatus","timeOut","checkTimeOut","params","find","projection","_id","toArray","length","checkModTime","findOne","queueitemState","oldState","ABORT","ERROR","DONE","includes","silly","timeoutTime","add","isBefore","finalImportJobStates","REQUEST_TIMEOUT","JSON","stringify","clean","noContent","deleteOne","err","MongoDriverError","message","indexOf","readStream","openDownloadStreamByName","NOT_FOUND","delete","cleanQueueItemState","verbose","updateOne","$set","$push","$each","messages","messageField","cleanMessageField","errorString","stateInQueueItemStates","Object","values","stateInQueueItemStatesValidator","stateInQueueItemStatesImporter","IMPORTER","BAD_REQUEST","updateValues","keys","forEach","key","findOneAndUpdate","returnNewDocument","cleanCorrelationId","cleanImportJobState","OPERATIONS","newJobState","newOperation","oldOperation","cleanNewOperation","ok","addOperation","removeOperation","queueItem","oldOperations","operationsAfterRemove","filter","operationsAfterRemoveAndAdd"],"mappings":";;;;;;;AA4BA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;AAnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEe,wBAAgBA,SAAhB,EAA2BC,UAA3B,EAAuC;AACpD,QAAMC,MAAM,GAAG,0CAAf,CADoD,CAGpD;;AACA,QAAMC,MAAM,GAAG,MAAMC,qBAAYC,OAAZ,CAAoBL,SAApB,EAA+B;AAACM,IAAAA,eAAe,EAAE,IAAlB;AAAwBC,IAAAA,kBAAkB,EAAE;AAA5C,GAA/B,CAArB;AACA,QAAMC,EAAE,GAAGL,MAAM,CAACK,EAAP,CAAU,UAAV,CAAX;AACA,QAAMC,YAAY,GAAG,IAAIC,qBAAJ,CAAiBF,EAAjB,EAAqB;AAACG,IAAAA,UAAU,EAAEV;AAAb,GAArB,CAArB;AAEA,SAAO;AAACW,IAAAA,UAAD;AAAaC,IAAAA,UAAb;AA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AAM2G,kBAAkB,GAAG,4BAAShH,aAAT,CAA3B,CADuF,CAGvF;;AAEA,UAAM0H,SAAS,GAAG,MAAM/I,EAAE,CAACP,UAAH,CAAcA,UAAd,EAA0B2F,OAA1B,CAAkC;AAAC/D,MAAAA,aAAa,EAAEgH;AAAhB,KAAlC,CAAxB;AACA3I,IAAAA,MAAM,CAAC6E,KAAP,CAAc,yBAAwB0B,IAAI,CAACC,SAAL,CAAe6C,SAAf,CAA0B,EAAhE;AAEA,UAAMC,aAAa,GAAGD,SAAS,CAAC9G,UAAhC;AAEAvC,IAAAA,MAAM,CAAC0D,IAAP,CAAa,qCAAoC6C,IAAI,CAACC,SAAL,CAAe8C,aAAf,CAA8B,cAAaH,YAAa,iBAAgBC,eAAgB,QAAOzH,aAAc,OAAM5B,UAAW,EAA/K;AAEA,UAAMwJ,qBAAqB,GAAGD,aAAa,CAACE,MAAd,CAAqB1H,SAAS,IAAIA,SAAS,KAAKsH,eAAhD,CAA9B;AACA,UAAMK,2BAA2B,GAAG,CAACN,YAAD,EAAe,GAAGI,qBAAlB,CAApC;AAEA,UAAMhG,MAAM,GAAG,MAAMjD,EAAE,CAACP,UAAH,CAAcA,UAAd,EAA0B0I,gBAA1B,CAA2C;AAC9D9G,MAAAA,aAAa,EAAEgH;AAD+C,KAA3C,EAElB;AACDpB,MAAAA,IAAI,EAAE;AACJhF,QAAAA,UAAU,EAAEkH,2BADR;AAEJrG,QAAAA,gBAAgB,EAAE,uBAASf,MAAT;AAFd;AADL,KAFkB,EAOlB;AAACgD,MAAAA,UAAU,EAAE;AAACC,QAAAA,GAAG,EAAE;AAAN,OAAb;AAAuBoD,MAAAA,iBAAiB,EAAE;AAA1C,KAPkB,CAArB;AASA,WAAOnF,MAAM,CAAC2F,EAAd,CAxBuF,CAyBvF;AACD;AACF","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {MongoClient, GridFSBucket, MongoDriverError} from 'mongodb';\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {QUEUE_ITEM_STATE, IMPORT_JOB_STATE, OPERATIONS} from './constants';\nimport {logError} from './utils.js';\nimport moment from 'moment';\nimport httpStatus from 'http-status';\nimport sanitize from 'mongo-sanitize';\n\n/* QueueItem:\n{\n \"correlationId\":\"FOO\",\n \"cataloger\":\"xxx0000\",\n \"oCatalogerIn\":\"xxx0000\"\n \"operation\":\"UPDATE\",\n \"operations\":[\"UPDATE\", \"CREATE\"]\n \"contentType\":\"application/json\",\n \"recordLoadParams\": {\n \"pActiveLibrary\": \"XXX00\",\n \"pInputFile\": \"filename.seq\",\n \"pRejectFile\": \"filename.rej\",\n \"pLogFile\": \"filename.syslog\",\n \"pOldNew\": \"NEW\"\n },\n \"queueItemState\":\"PENDING_QUEUING\",\n \"importJobState\": {\n \"CREATE\": \"EMPTY\",\n \"UPDATE\": \"EMPTY\"\n },\n \"creationTime\":\"2020-01-01T00:00:00.000Z\",\n \"modificationTime\":\"2020-01-01T00:00:01.000Z\",\n \"handledIds\": []\n}\n*/\n\nexport default async function (MONGO_URI, collection) {\n const logger = createLogger();\n\n // Connect to mongo (MONGO)\n const client = await MongoClient.connect(MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});\n const db = client.db('rest-api');\n const gridFSBucket = new GridFSBucket(db, {bucketName: collection});\n\n return {createPrio, createBulk, checkAndSetState, checkAndSetImportJobState, query, queryById, remove, readContent, removeContent, getOne, getStream, setState, setImportJobState, pushIds, pushMessages, setOperation, setOperations};\n\n async function createPrio({correlationId, cataloger, oCatalogerIn, operation, noop = undefined, unique = undefined, merge = undefined, prio = true}) {\n const time = moment().toDate();\n const newQueueItem = {\n correlationId,\n cataloger,\n operation,\n operations: [operation],\n oCatalogerIn,\n operationSettings: {unique, noop, prio, merge, originalOperation: operation},\n queueItemState: QUEUE_ITEM_STATE.VALIDATOR.PENDING_VALIDATION,\n importJobState: {\n CREATE: IMPORT_JOB_STATE.EMPTY,\n UPDATE: IMPORT_JOB_STATE.EMPTY\n },\n creationTime: time,\n modificationTime: time,\n handledIds: [],\n rejectedIds: []\n };\n try {\n const result = await db.collection(collection).insertOne(newQueueItem);\n if (result.acknowledged) {\n logger.info(`New PRIO queue item for ${operation} ${correlationId} has been made in ${collection}`);\n return;\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n async function createBulk({correlationId, cataloger, oCatalogerIn, operation, contentType, recordLoadParams, stream, prio = false}) {\n const time = moment().toDate();\n const newQueueItem = {\n correlationId,\n cataloger,\n oCatalogerIn,\n operation,\n operations: [operation],\n operationSettings: {prio, originalOperation: operation},\n contentType,\n recordLoadParams,\n queueItemState: stream ? QUEUE_ITEM_STATE.VALIDATOR.UPLOADING : QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS,\n importJobState: {\n CREATE: IMPORT_JOB_STATE.EMPTY,\n UPDATE: IMPORT_JOB_STATE.EMPTY\n },\n creationTime: time,\n modificationTime: time,\n handledIds: [],\n rejectedIds: []\n };\n\n // eslint-disable-next-line functional/no-conditional-statement\n if (stream) {\n try {\n // No await here, promises later\n db.collection(collection).insertOne(newQueueItem);\n logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);\n return new Promise((resolve, reject) => {\n const outputStream = gridFSBucket.openUploadStream(correlationId);\n\n stream\n .on('error', reject)\n .on('data', chunk => outputStream.write(chunk))\n .on('end', () => outputStream.end(undefined, undefined, () => {\n resolve(correlationId);\n }));\n });\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n logger.debug(`No stream`);\n // eslint-disable-next-line functional/no-conditional-statement\n if (!stream) {\n try {\n const result = await db.collection(collection).insertOne(newQueueItem);\n if (result.acknowledged) {\n logger.info(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);\n return {correlationId, queueItemState: QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS};\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n }\n\n // Check state that the queueItem has not waited too long and set state\n async function checkAndSetState({correlationId, state, errorMessage = undefined, errorStatus = undefined}) {\n // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR\n // otherwise it sets queueItem to state ABORT (408, 'Timeout')\n const timeOut = await checkTimeOut({correlationId});\n if (timeOut) {\n return setState({correlationId, state, errorMessage, errorStatus});\n }\n return false;\n }\n\n // Check state that the queueItem has not waited too long and set state\n async function checkAndSetImportJobState({correlationId, operation, importJobState, errorMessage = '', errorStatus = ''}) {\n // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR\n // otherwise it sets queueItem to state ABORT (408, 'Timeout')\n logger.debug(`${correlationId}, ${importJobState}, ${operation}`);\n const timeOut = await checkTimeOut({correlationId, operation, importJobState});\n if (timeOut) {\n return setImportJobState({correlationId, operation, importJobState, errorMessage, errorStatus});\n }\n return false;\n }\n\n async function query(params) {\n const result = await db.collection(collection).find(params, {projection: {_id: 0}})\n .toArray();\n logger.debug(`Query result: ${result.length > 0 ? 'Found!' : 'Not found!'}`);\n return result;\n }\n\n async function queryById({correlationId, checkModTime = false}) {\n const result = await db.collection(collection).findOne({correlationId});\n if (checkModTime) {\n const timeOut = await checkTimeOut({correlationId});\n if (timeOut) {\n return queryById({correlationId});\n }\n return result;\n }\n\n return result;\n }\n\n // Check that if the item has waited too long\n // If the last modification time for the queueItem is older than 1 minute\n // set state to ABORT and return false, otherwise return true\n // If the state is already ABORT or ERROR return false\n\n async function checkTimeOut({correlationId}) {\n const {modificationTime, queueitemState: oldState, importJobState} = await db.collection(collection).findOne({correlationId});\n\n // should we check for DONE too?\n if ([QUEUE_ITEM_STATE.ABORT, QUEUE_ITEM_STATE.ERROR, QUEUE_ITEM_STATE.DONE].includes(oldState)) {\n logger.silly(`${correlationId} has already state: ${oldState}`);\n return false;\n }\n\n const timeoutTime = moment(modificationTime).add(1, 'm');\n logger.silly(`timeOut @ ${timeoutTime}`);\n\n if (timeoutTime.isBefore()) {\n const finalImportJobStates = [IMPORT_JOB_STATE.ABORT, IMPORT_JOB_STATE.DONE, IMPORT_JOB_STATE.EMPTY, IMPORT_JOB_STATE.ERROR];\n if (!finalImportJobStates.includes(importJobState.CREATE)) { // eslint-disable-line\n await setImportJobState({correlationId, operation: 'CREATE', importJobState: IMPORT_JOB_STATE.ABORT});\n }\n\n if (!finalImportJobStates.includes(importJobState.UPDATE)) { // eslint-disable-line\n await setImportJobState({correlationId, operation: 'UPDATE', importJobState: IMPORT_JOB_STATE.ABORT});\n }\n\n await setState({correlationId, state: QUEUE_ITEM_STATE.ABORT, errorStatus: httpStatus.REQUEST_TIMEOUT, errorMessage: `Timeout in ${oldState}`});\n\n return false;\n }\n\n return true;\n }\n\n async function remove(params) {\n logger.silly(`${JSON.stringify(params)}`);\n logger.info(`Removing from Mongo (${collection}) id: ${params.correlationId}`);\n const clean = sanitize(params.correlationId);\n logger.silly(`mongo/remove: clean: ${JSON.stringify(clean)}`);\n\n try {\n //const metadataResult = await getFileMetadata({filename: clean});\n //logger.debug(`mongo/remove: metadataResult: ${JSON.stringify(metadataResult)}`);\n const noContent = await removeContent(params);\n if (noContent) {\n await db.collection(collection).deleteOne({correlationId: clean});\n return true;\n }\n } catch (err) {\n if (err instanceof MongoDriverError) {\n if (err.message.indexOf('File not found for id') !== -1) {\n logger.silly(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);\n await db.collection(collection).deleteOne({correlationId: clean});\n return true;\n }\n logger.error(err.message);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n\n async function readContent(correlationId) {\n logger.info(`Reading content from mongo for id: ${correlationId} in ${collection}`);\n const clean = sanitize(correlationId);\n const result = await db.collection(collection).findOne({correlationId: clean}); // njsscan-ignore: node_nosqli_injection\n\n if (result) {\n return {\n contentType: result.contentType,\n readStream: gridFSBucket.openDownloadStreamByName(clean)\n };\n }\n\n throw new ApiError(httpStatus.NOT_FOUND);\n }\n\n async function removeContent(params) {\n logger.info(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);\n const clean = sanitize(params.correlationId);\n\n const result = await db.collection(collection).findOne({correlationId: clean}); // njsscan-ignore: node_nosqli_injection\n logger.silly(`mongo/removeContent: result ${JSON.stringify(result)}`);\n\n if (result) {\n await gridFSBucket.delete(clean);\n return true;\n }\n\n return true;\n }\n\n // eslint-disable-next-line max-statements\n function getOne({queueItemState, importJobState = undefined}) {\n\n logger.silly(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);\n const cleanQueueItemState = queueItemState ? {queueItemState: sanitize(queueItemState)} : undefined;\n\n try {\n\n // Just queueItemState\n if (queueItemState && importJobState === undefined) {\n logger.silly(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);\n return db.collection(collection).findOne({...cleanQueueItemState});\n }\n\n // importJobState\n if (importJobState && queueItemState === undefined) {\n logger.silly(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);\n return db.collection(collection).findOne({...importJobState});\n }\n\n // importJobState and queueItemState\n if (importJobState && queueItemState) {\n logger.silly(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);\n return db.collection(collection).findOne({...cleanQueueItemState, ...importJobState});\n }\n\n logger.debug(`getOne not working!`);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');\n\n } catch (error) {\n logError(error);\n }\n }\n\n function getStream(correlationId) {\n logger.info(`Forming stream from mongo for ${correlationId} in ${collection}`);\n const clean = sanitize(correlationId);\n try {\n // Return content stream\n return gridFSBucket.openDownloadStreamByName(clean);\n } catch (error) {\n logError(error);\n }\n }\n\n async function pushIds({correlationId, handledIds, rejectedIds}) {\n logger.verbose(`Push ids (${handledIds.length}) and rejectedIds (${rejectedIds.length}) ${correlationId} to ${collection}`);\n logger.debug(`ids (${handledIds.length}): ${JSON.stringify(handledIds)}, rejectedIds ${rejectedIds.length}: ${JSON.stringify(rejectedIds)}`);\n const clean = sanitize(correlationId);\n await db.collection(collection).updateOne({\n correlationId: clean\n }, {\n $set: {\n modificationTime: moment().toDate()\n },\n $push: {\n handledIds: {$each: handledIds},\n rejectedIds: {$each: rejectedIds}\n }\n });\n }\n\n async function pushMessages({correlationId, messages, messageField = 'messages'}) {\n logger.verbose(`Push messages (${messages.length}) to ${messageField} ${correlationId} to ${collection}`);\n logger.silly(`Messages (${messages.length}): ${JSON.stringify(messages)}}`);\n const clean = sanitize(correlationId);\n const cleanMessageField = sanitize(messageField);\n await db.collection(collection).updateOne({\n correlationId: clean\n }, {\n $set: {\n modificationTime: moment().toDate()\n },\n $push: {\n [cleanMessageField]: {$each: messages}\n }\n });\n }\n\n function setState({correlationId, state, errorMessage = undefined, errorStatus = undefined}) {\n const errorString = errorMessage || errorStatus ? `, Error message: '${errorMessage || ''}', Error status: '${errorStatus || ''}'` : '';\n logger.info(`Setting queue-item state ${state} for ${correlationId}${errorString} to ${collection}`);\n\n const stateInQueueItemStates = Object.values(QUEUE_ITEM_STATE).indexOf(state) > -1;\n const stateInQueueItemStatesValidator = Object.values(QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;\n const stateInQueueItemStatesImporter = Object.values(QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;\n if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {\n throw new ApiError(httpStatus.BAD_REQUEST, 'Trying to set invalid state');\n }\n\n const clean = sanitize(correlationId);\n const updateValues = {\n queueItemState: state,\n modificationTime: moment().toDate(),\n errorMessage,\n errorStatus\n };\n\n // Do not update value that are undefined\n // eslint-disable-next-line functional/immutable-data\n Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);\n\n return db.collection(collection)\n .findOneAndUpdate(\n {correlationId: clean},\n {$set: updateValues},\n {projection: {_id: 0}, returnNewDocument: true}\n );\n }\n\n function setImportJobState({correlationId, operation, importJobState}) {\n\n // should this also get importJobState as previously created object? {}\n logger.info(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);\n const cleanCorrelationId = sanitize(correlationId);\n const cleanImportJobState = sanitize(importJobState);\n\n if (!(operation in OPERATIONS)) {\n throw new ApiError('400', 'Invalid operation for import job state');\n }\n\n if (!(cleanImportJobState in IMPORT_JOB_STATE)) {\n throw new ApiError('400', 'Invalid import job state');\n }\n\n const newJobState = operation === OPERATIONS.CREATE ? {'importJobState.CREATE': cleanImportJobState} : {'importJobState.UPDATE': cleanImportJobState};\n return db.collection(collection).findOneAndUpdate({\n correlationId: cleanCorrelationId\n }, {\n $set: {\n ...newJobState,\n modificationTime: moment().toDate()\n }\n }, {projection: {_id: 0}, returnNewDocument: true});\n }\n\n async function setOperation({correlationId, operation}) {\n const newOperation = operation;\n const {operation: oldOperation} = await db.collection(collection).findOne({correlationId});\n logger.info(`Setting queue-item operation from ${oldOperation} to ${newOperation} for ${correlationId} to ${collection}`);\n const cleanCorrelationId = sanitize(correlationId);\n const cleanNewOperation = sanitize(newOperation);\n\n const result = await db.collection(collection).findOneAndUpdate({\n correlationId: cleanCorrelationId\n }, {\n $set: {\n operation: cleanNewOperation,\n modificationTime: moment().toDate()\n }\n }, {projection: {_id: 0}, returnNewDocument: true});\n\n return result.ok;\n // logger.debug(JSON.stringify(result));\n }\n\n async function setOperations({correlationId, addOperation, removeOperation = undefined}) {\n const cleanCorrelationId = sanitize(correlationId);\n\n //logger.info(`Setting queue-item operation from ${JSON.stringify(oldOperations)} by adding ${addOperation} and removing ${removeOperation} for ${correlationId} to ${collection}`);\n\n const queueItem = await db.collection(collection).findOne({correlationId: cleanCorrelationId});\n logger.debug(`We fould a queueItem: ${JSON.stringify(queueItem)}`);\n\n const oldOperations = queueItem.operations;\n\n logger.info(`Setting queue-item operation from ${JSON.stringify(oldOperations)} by adding ${addOperation} and removing ${removeOperation} for ${correlationId} to ${collection}`);\n\n const operationsAfterRemove = oldOperations.filter(operation => operation !== removeOperation);\n const operationsAfterRemoveAndAdd = [addOperation, ...operationsAfterRemove];\n\n const result = await db.collection(collection).findOneAndUpdate({\n correlationId: cleanCorrelationId\n }, {\n $set: {\n operations: operationsAfterRemoveAndAdd,\n modificationTime: moment().toDate()\n }\n }, {projection: {_id: 0}, returnNewDocument: true});\n\n return result.ok;\n // logger.debug(JSON.stringify(result));\n }\n}\n"],"file":"mongo.js"}
package/dist/utils.js CHANGED
@@ -3,12 +3,15 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.createImportJobState = createImportJobState;
6
7
  exports.logError = logError;
7
8
 
8
9
  var _melindaBackendCommons = require("@natlibfi/melinda-backend-commons");
9
10
 
10
11
  var _melindaCommons = require("@natlibfi/melinda-commons");
11
12
 
13
+ var _constants = require("./constants");
14
+
12
15
  /**
13
16
  *
14
17
  * @licstart The following is the entire license notice for the JavaScript code in this file.
@@ -51,4 +54,26 @@ function logError(err) {
51
54
 
52
55
  logger.error(err.stack === undefined ? err : err.stack);
53
56
  }
57
+
58
+ function createImportJobState(operation, state, queryImportJobState = false) {
59
+ if (!(state in _constants.IMPORT_JOB_STATE)) {
60
+ throw new Error('Invalid IMPORT_JOB_STATE');
61
+ }
62
+
63
+ if (!(operation in _constants.OPERATIONS)) {
64
+ throw new Error('Invalid operation');
65
+ }
66
+
67
+ if (queryImportJobState) {
68
+ const importJobStateWithOperation = `importJobState.${operation}`;
69
+ const importJobStateForQuery = {
70
+ [importJobStateWithOperation]: state
71
+ };
72
+ return importJobStateForQuery;
73
+ }
74
+
75
+ return {
76
+ [operation]: state
77
+ };
78
+ }
54
79
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils.js"],"names":["logger","logError","err","ApiError","error","JSON","stringify","stack","undefined"],"mappings":";;;;;;;AA4BA;;AACA;;AA7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAKA,MAAMA,MAAM,GAAG,0CAAf;;AAEO,SAASC,QAAT,CAAkBC,GAAlB,EAAuB;AAC5B,MAAIA,GAAG,YAAYC,qBAAnB,EAA6B;AAC3BH,IAAAA,MAAM,CAACI,KAAP,CAAaC,IAAI,CAACC,SAAL,CAAeJ,GAAf,CAAb;AACA;AACD;;AAED,MAAIA,GAAG,KAAK,QAAZ,EAAsB;AACpBF,IAAAA,MAAM,CAACI,KAAP,CAAaF,GAAb;AACA;AACD;;AAEDF,EAAAA,MAAM,CAACI,KAAP,CAAaF,GAAG,CAACK,KAAJ,KAAcC,SAAd,GAA0BN,GAA1B,GAAgCA,GAAG,CAACK,KAAjD;AACD","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\n\nconst logger = createLogger();\n\nexport function logError(err) {\n if (err instanceof ApiError) {\n logger.error(JSON.stringify(err));\n return;\n }\n\n if (err === 'SIGINT') {\n logger.error(err);\n return;\n }\n\n logger.error(err.stack === undefined ? err : err.stack);\n}\n"],"file":"utils.js"}
1
+ {"version":3,"sources":["../src/utils.js"],"names":["logger","logError","err","ApiError","error","JSON","stringify","stack","undefined","createImportJobState","operation","state","queryImportJobState","IMPORT_JOB_STATE","Error","OPERATIONS","importJobStateWithOperation","importJobStateForQuery"],"mappings":";;;;;;;;AA4BA;;AACA;;AACA;;AA9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAMA,MAAMA,MAAM,GAAG,0CAAf;;AAEO,SAASC,QAAT,CAAkBC,GAAlB,EAAuB;AAC5B,MAAIA,GAAG,YAAYC,qBAAnB,EAA6B;AAC3BH,IAAAA,MAAM,CAACI,KAAP,CAAaC,IAAI,CAACC,SAAL,CAAeJ,GAAf,CAAb;AACA;AACD;;AAED,MAAIA,GAAG,KAAK,QAAZ,EAAsB;AACpBF,IAAAA,MAAM,CAACI,KAAP,CAAaF,GAAb;AACA;AACD;;AAEDF,EAAAA,MAAM,CAACI,KAAP,CAAaF,GAAG,CAACK,KAAJ,KAAcC,SAAd,GAA0BN,GAA1B,GAAgCA,GAAG,CAACK,KAAjD;AACD;;AAEM,SAASE,oBAAT,CAA8BC,SAA9B,EAAyCC,KAAzC,EAAgDC,mBAAmB,GAAG,KAAtE,EAA6E;AAClF,MAAI,EAAED,KAAK,IAAIE,2BAAX,CAAJ,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,0BAAV,CAAN;AACD;;AAED,MAAI,EAAEJ,SAAS,IAAIK,qBAAf,CAAJ,EAAgC;AAC9B,UAAM,IAAID,KAAJ,CAAU,mBAAV,CAAN;AACD;;AAED,MAAIF,mBAAJ,EAAyB;AACvB,UAAMI,2BAA2B,GAAI,kBAAiBN,SAAU,EAAhE;AACA,UAAMO,sBAAsB,GAAG;AAAC,OAACD,2BAAD,GAA+BL;AAAhC,KAA/B;AAEA,WAAOM,sBAAP;AACD;;AAED,SAAO;AAAC,KAACP,SAAD,GAAaC;AAAd,GAAP;AACD","sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {IMPORT_JOB_STATE, OPERATIONS} from './constants';\n\nconst logger = createLogger();\n\nexport function logError(err) {\n if (err instanceof ApiError) {\n logger.error(JSON.stringify(err));\n return;\n }\n\n if (err === 'SIGINT') {\n logger.error(err);\n return;\n }\n\n logger.error(err.stack === undefined ? err : err.stack);\n}\n\nexport function createImportJobState(operation, state, queryImportJobState = false) {\n if (!(state in IMPORT_JOB_STATE)) {\n throw new Error('Invalid IMPORT_JOB_STATE');\n }\n\n if (!(operation in OPERATIONS)) {\n throw new Error('Invalid operation');\n }\n\n if (queryImportJobState) {\n const importJobStateWithOperation = `importJobState.${operation}`;\n const importJobStateForQuery = {[importJobStateWithOperation]: state};\n\n return importJobStateForQuery;\n }\n\n return {[operation]: state};\n}\n"],"file":"utils.js"}
package/package.json CHANGED
@@ -14,7 +14,7 @@
14
14
  "url": "git@github.com:natlibfi/melinda-rest-api-commons.git"
15
15
  },
16
16
  "license": "AGPL-3.0+",
17
- "version": "2.2.0-alpha.1",
17
+ "version": "2.2.0-alpha.4",
18
18
  "main": "./dist/index.js",
19
19
  "engines": {
20
20
  "node": ">=14"
@@ -33,7 +33,6 @@
33
33
  "build": "babel src --source-maps --copy-files --delete-dir-on-start --out-dir=dist"
34
34
  },
35
35
  "dependencies": {
36
- "@natlibfi/fixura": "^2.2.1",
37
36
  "@natlibfi/marc-record": "^7.0.0",
38
37
  "@natlibfi/marc-record-serializers": "^8.1.0",
39
38
  "@natlibfi/marc-record-validate": "^7.0.1",
@@ -47,21 +46,21 @@
47
46
  "mongodb": "^4.1.3"
48
47
  },
49
48
  "devDependencies": {
50
- "@babel/cli": "^7.15.7",
51
- "@babel/core": "^7.15.8",
49
+ "@babel/cli": "^7.17.6",
50
+ "@babel/core": "^7.17.5",
51
+ "@babel/eslint-parser": "^7.17.0",
52
52
  "@babel/plugin-syntax-dynamic-import": "^7.8.3",
53
- "@babel/preset-env": "^7.15.8",
53
+ "@babel/preset-env": "^7.16.11",
54
54
  "@natlibfi/eslint-config-melinda-backend": "^2.0.0",
55
- "@babel/eslint-parser": "^7.15.8",
55
+ "@natlibfi/fixura": "^2.2.1",
56
56
  "babel-plugin-dynamic-import-node": "^2.3.3",
57
57
  "babel-plugin-istanbul": "^6.1.1",
58
58
  "babel-plugin-rewire": "^1.2.0",
59
- "chai": "^4.3.4",
59
+ "chai": "^4.3.6",
60
60
  "cross-env": "^7.0.3",
61
61
  "eslint": "^8.10.0",
62
- "eslint-plugin-import": "^2.25.2",
63
62
  "mocha": "^9.2.1",
64
- "nodemon": "^2.0.14",
63
+ "nodemon": "^2.0.15",
65
64
  "nyc": "^15.1.0"
66
65
  },
67
66
  "eslintConfig": {