@natlibfi/melinda-rest-api-commons 2.1.3 → 2.2.0-alpha.3

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
  *
@@ -38,8 +38,9 @@ const QUEUE_ITEM_STATE = {
38
38
  PENDING_QUEUING: 'PENDING_QUEUING',
39
39
  PENDING_VALIDATION: 'PENDING_VALIDATION',
40
40
  QUEUING_IN_PROGRESS: 'QUEUING_IN_PROGRESS',
41
+ UPLOADING: 'UPLOADING',
41
42
  VALIDATING: 'VALIDATING',
42
- UPLOADING: 'UPLOADING'
43
+ WAITING_FOR_RECORDS: 'WAITING_FOR_RECORDS'
43
44
  },
44
45
  IMPORTER: {
45
46
  IMPORTING: 'IMPORTING',
@@ -51,6 +52,16 @@ const QUEUE_ITEM_STATE = {
51
52
  ABORT: 'ABORT'
52
53
  };
53
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;
54
65
  const OPERATIONS = {
55
66
  CREATE: 'CREATE',
56
67
  UPDATE: 'UPDATE'
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.js"],"names":["QUEUE_ITEM_STATE","VALIDATOR","PENDING_QUEUING","PENDING_VALIDATION","QUEUING_IN_PROGRESS","VALIDATING","UPLOADING","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,UAAU,EAAE,YAJH;AAKTC,IAAAA,SAAS,EAAE;AALF,GADmB;AAQ9BC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,SAAS,EAAE,WADH;AAERC,IAAAA,UAAU,EAAE,YAFJ;AAGRC,IAAAA,QAAQ,EAAE;AAHF,GARoB;AAa9BC,EAAAA,IAAI,EAAE,MAbwB;AAc9BC,EAAAA,KAAK,EAAE,OAduB;AAe9BC,EAAAA,KAAK,EAAE;AAfuB,CAAzB;;AAkBA,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 VALIDATING: 'VALIDATING',\n UPLOADING: 'UPLOADING'\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_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,gBAAgB,GAAG;AAC9BC,EAAAA,KAAK,EAAE,OADuB;AAE9BC,EAAAA,OAAO,EAAE,SAFqB;AAG9BN,EAAAA,QAAQ,EAAE,UAHoB;AAI9BO,EAAAA,UAAU,EAAE,YAJkB;AAK9BN,EAAAA,IAAI,EAAE,MALwB;AAM9BC,EAAAA,KAAK,EAAE,OANuB;AAO9BC,EAAAA,KAAK,EAAE;AAPuB,CAAzB;;AAUA,MAAMK,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 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,45 +173,75 @@ 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
- queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.UPLOADING,
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
 
180
- return new Promise((resolve, reject) => {
181
- const outputStream = gridFSBucket.openUploadStream(correlationId);
182
- stream.on('error', reject).on('data', chunk => outputStream.write(chunk)).on('end', () => outputStream.end(undefined, undefined, () => {
183
- resolve(correlationId);
184
- }));
185
- });
211
+ logger.debug(`No stream`); // eslint-disable-next-line functional/no-conditional-statement
212
+
213
+ if (!stream) {
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
+ }
224
+
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
+ }
186
231
  } // Check state that the queueItem has not waited too long and set state
187
232
 
188
233
 
189
234
  async function checkAndSetState({
190
235
  correlationId,
191
236
  state,
192
- errorMessage = '',
193
- errorStatus = ''
237
+ errorMessage = undefined,
238
+ errorStatus = undefined
194
239
  }) {
195
240
  // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR
196
241
  // otherwise it sets queueItem to state ABORT (408, 'Timeout')
197
- const timeOut = await checkTimeOut(correlationId);
242
+ const timeOut = await checkTimeOut({
243
+ correlationId
244
+ });
198
245
 
199
246
  if (timeOut) {
200
247
  return setState({
@@ -205,6 +252,36 @@ async function _default(MONGO_URI, collection) {
205
252
  });
206
253
  }
207
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
+
208
285
  return false;
209
286
  }
210
287
 
@@ -218,16 +295,23 @@ async function _default(MONGO_URI, collection) {
218
295
  return result;
219
296
  }
220
297
 
221
- async function queryById(correlationId, checkModTime) {
298
+ async function queryById({
299
+ correlationId,
300
+ checkModTime = false
301
+ }) {
222
302
  const result = await db.collection(collection).findOne({
223
303
  correlationId
224
304
  });
225
305
 
226
306
  if (checkModTime) {
227
- const timeOut = await checkTimeOut(correlationId);
307
+ const timeOut = await checkTimeOut({
308
+ correlationId
309
+ });
228
310
 
229
311
  if (timeOut) {
230
- return queryById(correlationId);
312
+ return queryById({
313
+ correlationId
314
+ });
231
315
  }
232
316
 
233
317
  return result;
@@ -240,15 +324,18 @@ async function _default(MONGO_URI, collection) {
240
324
  // If the state is already ABORT or ERROR return false
241
325
 
242
326
 
243
- async function checkTimeOut(correlationId) {
327
+ async function checkTimeOut({
328
+ correlationId
329
+ }) {
244
330
  const {
245
331
  modificationTime,
246
- queueitemState: oldState
332
+ queueitemState: oldState,
333
+ importJobState
247
334
  } = await db.collection(collection).findOne({
248
335
  correlationId
249
- });
336
+ }); // should we check for DONE too?
250
337
 
251
- 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)) {
252
339
  logger.silly(`${correlationId} has already state: ${oldState}`);
253
340
  return false;
254
341
  }
@@ -257,6 +344,26 @@ async function _default(MONGO_URI, collection) {
257
344
  logger.silly(`timeOut @ ${timeoutTime}`);
258
345
 
259
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
+
260
367
  await setState({
261
368
  correlationId,
262
369
  state: _constants.QUEUE_ITEM_STATE.ABORT,
@@ -336,30 +443,43 @@ async function _default(MONGO_URI, collection) {
336
443
  }
337
444
 
338
445
  return true;
339
- }
446
+ } // eslint-disable-next-line max-statements
447
+
340
448
 
341
449
  function getOne({
342
- operation,
343
- queueItemState
450
+ queueItemState,
451
+ importJobState = undefined
344
452
  }) {
345
- const clean = {
453
+ logger.silly(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
454
+ const cleanQueueItemState = queueItemState ? {
346
455
  queueItemState: (0, _mongoSanitize.default)(queueItemState)
347
- };
456
+ } : undefined;
348
457
 
349
458
  try {
350
- if (operation === undefined) {
351
- logger.silly(`Checking DB ${collection} for ${JSON.stringify(clean.queueItemState)}`);
352
- 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
353
478
  });
354
479
  }
355
480
 
356
- const clean2 = {
357
- operation: (0, _mongoSanitize.default)(operation)
358
- };
359
- logger.silly(`Checking DB ${collection} for ${clean.queueItemState} + ${clean2.operation}`);
360
- return db.collection(collection).findOne({ ...clean,
361
- ...clean2
362
- });
481
+ logger.debug(`getOne not working!`);
482
+ throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');
363
483
  } catch (error) {
364
484
  (0, _utils.logError)(error);
365
485
  }
@@ -428,20 +548,128 @@ async function _default(MONGO_URI, collection) {
428
548
  function setState({
429
549
  correlationId,
430
550
  state,
431
- errorMessage = '',
432
- errorStatus = ''
551
+ errorMessage = undefined,
552
+ errorStatus = undefined
433
553
  }) {
434
- const errorString = errorMessage || errorStatus ? `, Error message: '${errorMessage}', Error status: '${errorStatus}'` : '';
554
+ const errorString = errorMessage || errorStatus ? `, Error message: '${errorMessage || ''}', Error status: '${errorStatus || ''}'` : '';
435
555
  logger.info(`Setting queue-item state ${state} for ${correlationId}${errorString} to ${collection}`);
556
+ const stateInQueueItemStates = Object.values(_constants.QUEUE_ITEM_STATE).indexOf(state) > -1;
557
+ const stateInQueueItemStatesValidator = Object.values(_constants.QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;
558
+ const stateInQueueItemStatesImporter = Object.values(_constants.QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;
559
+
560
+ if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {
561
+ throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Trying to set invalid state');
562
+ }
563
+
436
564
  const clean = (0, _mongoSanitize.default)(correlationId);
565
+ const updateValues = {
566
+ queueItemState: state,
567
+ modificationTime: (0, _moment.default)().toDate(),
568
+ errorMessage,
569
+ errorStatus
570
+ }; // Do not update value that are undefined
571
+ // eslint-disable-next-line functional/immutable-data
572
+
573
+ Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);
437
574
  return db.collection(collection).findOneAndUpdate({
438
575
  correlationId: clean
576
+ }, {
577
+ $set: updateValues
578
+ }, {
579
+ projection: {
580
+ _id: 0
581
+ },
582
+ returnNewDocument: true
583
+ });
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
439
638
  }, {
440
639
  $set: {
441
- queueItemState: state,
442
- modificationTime: (0, _moment.default)().toDate(),
443
- errorMessage,
444
- errorStatus
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()
445
673
  }
446
674
  }, {
447
675
  projection: {
@@ -449,6 +677,7 @@ async function _default(MONGO_URI, collection) {
449
677
  },
450
678
  returnNewDocument: true
451
679
  });
680
+ return result.ok; // logger.debug(JSON.stringify(result));
452
681
  }
453
682
  }
454
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","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","findOneAndUpdate","returnNewDocument"],"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;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;AAAyBC,IAAAA,gBAAzB;AAA2CC,IAAAA,KAA3C;AAAkDC,IAAAA,SAAlD;AAA6DC,IAAAA,MAA7D;AAAqEC,IAAAA,WAArE;AAAkFC,IAAAA,aAAlF;AAAiGC,IAAAA,MAAjG;AAAyGC,IAAAA,SAAzG;AAAoHC,IAAAA,QAApH;AAA8HC,IAAAA,OAA9H;AAAuIC,IAAAA;AAAvI,GAAP;;AAEA,iBAAeZ,UAAf,CAA0B;AAACa,IAAAA,aAAD;AAAgBC,IAAAA,SAAhB;AAA2BC,IAAAA,YAA3B;AA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AAAA,aAAD;AAAgByC,IAAAA,KAAhB;AAAuBC,IAAAA,YAAY,GAAG,EAAtC;AAA0CC,IAAAA,WAAW,GAAG;AAAxD,GAAlB,EAA+E;AAC7E,UAAM4C,WAAW,GAAG7C,YAAY,IAAIC,WAAhB,GAA+B,qBAAoBD,YAAa,qBAAoBC,WAAY,GAAhG,GAAqG,EAAzH;AACAlE,IAAAA,MAAM,CAAC8C,IAAP,CAAa,4BAA2BkB,KAAM,QAAOzC,aAAc,GAAEuF,WAAY,OAAM/G,UAAW,EAAlG;AACA,UAAM2F,KAAK,GAAG,4BAASnE,aAAT,CAAd;AACA,WAAOjB,EAAE,CAACP,UAAH,CAAcA,UAAd,EAA0BgH,gBAA1B,CAA2C;AAChDxF,MAAAA,aAAa,EAAEmE;AADiC,KAA3C,EAEJ;AACDc,MAAAA,IAAI,EAAE;AACJrE,QAAAA,cAAc,EAAE6B,KADZ;AAEJxB,QAAAA,gBAAgB,EAAE,uBAASR,MAAT,EAFd;AAGJiC,QAAAA,YAHI;AAIJC,QAAAA;AAJI;AADL,KAFI,EASJ;AAACK,MAAAA,UAAU,EAAE;AAACC,QAAAA,GAAG,EAAE;AAAN,OAAb;AAAuBwC,MAAAA,iBAAiB,EAAE;AAA1C,KATI,CAAP;AAUD;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: QUEUE_ITEM_STATE.VALIDATOR.UPLOADING,\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 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 = '', 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 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 = '', errorStatus = ''}) {\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 const clean = sanitize(correlationId);\n return db.collection(collection).findOneAndUpdate({\n correlationId: clean\n }, {\n $set: {\n queueItemState: state,\n modificationTime: moment().toDate(),\n errorMessage,\n errorStatus\n }\n }, {projection: {_id: 0}, returnNewDocument: true});\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;AAAyBC,IAAAA,gBAAzB;AAA2CC,IAAAA,yBAA3C;AAAsEC,IAAAA,KAAtE;AAA6EC,IAAAA,SAA7E;AAAwF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,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,16 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.createImportJobState = createImportJobState;
7
+ exports.createImportJobStateForQuery = createImportJobStateForQuery;
6
8
  exports.logError = logError;
7
9
 
8
10
  var _melindaBackendCommons = require("@natlibfi/melinda-backend-commons");
9
11
 
10
12
  var _melindaCommons = require("@natlibfi/melinda-commons");
11
13
 
14
+ var _constants = require("./constants");
15
+
12
16
  /**
13
17
  *
14
18
  * @licstart The following is the entire license notice for the JavaScript code in this file.
@@ -51,4 +55,41 @@ function logError(err) {
51
55
 
52
56
  logger.error(err.stack === undefined ? err : err.stack);
53
57
  }
58
+
59
+ function createImportJobState(operation, state) {
60
+ if (!(state in _constants.IMPORT_JOB_STATE)) {
61
+ throw new Error('Invalid IMPORT_JOB_STATE');
62
+ }
63
+
64
+ if (!(operation in _constants.OPERATIONS)) {
65
+ throw new Error('Invalid operation');
66
+ }
67
+
68
+ return {
69
+ [operation]: state
70
+ };
71
+ /*
72
+ if (operation === OPERATIONS.CREATE) {
73
+ return {CREATE: state};
74
+ }
75
+
76
+ return {UPDATE: state};
77
+ */
78
+ }
79
+
80
+ function createImportJobStateForQuery(operation, state) {
81
+ if (!(state in _constants.IMPORT_JOB_STATE)) {
82
+ throw new Error('Invalid IMPORT_JOB_STATE');
83
+ }
84
+
85
+ if (!(operation in _constants.OPERATIONS)) {
86
+ throw new Error('Invalid operation');
87
+ }
88
+
89
+ const importJobStateWithOperation = `importJobState.${operation}`;
90
+ const importJobStateForQuery = {
91
+ [importJobStateWithOperation]: state
92
+ };
93
+ return importJobStateForQuery;
94
+ }
54
95
  //# 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","IMPORT_JOB_STATE","Error","OPERATIONS","createImportJobStateForQuery","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,EAAgD;AACrD,MAAI,EAAEA,KAAK,IAAIC,2BAAX,CAAJ,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,0BAAV,CAAN;AACD;;AAED,MAAI,EAAEH,SAAS,IAAII,qBAAf,CAAJ,EAAgC;AAC9B,UAAM,IAAID,KAAJ,CAAU,mBAAV,CAAN;AACD;;AAED,SAAO;AAAC,KAACH,SAAD,GAAaC;AAAd,GAAP;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACC;;AAEM,SAASI,4BAAT,CAAsCL,SAAtC,EAAiDC,KAAjD,EAAwD;AAC7D,MAAI,EAAEA,KAAK,IAAIC,2BAAX,CAAJ,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,0BAAV,CAAN;AACD;;AACD,MAAI,EAAEH,SAAS,IAAII,qBAAf,CAAJ,EAAgC;AAC9B,UAAM,IAAID,KAAJ,CAAU,mBAAV,CAAN;AACD;;AAED,QAAMG,2BAA2B,GAAI,kBAAiBN,SAAU,EAAhE;AACA,QAAMO,sBAAsB,GAAG;AAAC,KAACD,2BAAD,GAA+BL;AAAhC,GAA/B;AAEA,SAAOM,sBAAP;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) {\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 return {[operation]: state};\n\n/*\n if (operation === OPERATIONS.CREATE) {\n return {CREATE: state};\n }\n\n return {UPDATE: state};\n*/\n}\n\nexport function createImportJobStateForQuery(operation, state) {\n if (!(state in IMPORT_JOB_STATE)) {\n throw new Error('Invalid IMPORT_JOB_STATE');\n }\n if (!(operation in OPERATIONS)) {\n throw new Error('Invalid operation');\n }\n\n const importJobStateWithOperation = `importJobState.${operation}`;\n const importJobStateForQuery = {[importJobStateWithOperation]: state};\n\n return importJobStateForQuery;\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.1.3",
17
+ "version": "2.2.0-alpha.3",
18
18
  "main": "./dist/index.js",
19
19
  "engines": {
20
20
  "node": ">=14"
@@ -33,11 +33,10 @@
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",
40
- "@natlibfi/marc-record-validators-melinda": "^9.0.2",
39
+ "@natlibfi/marc-record-validators-melinda": "^9.0.4",
41
40
  "@natlibfi/melinda-backend-commons": "^2.0.5",
42
41
  "@natlibfi/melinda-commons": "^12.0.3",
43
42
  "amqplib": ">=0.8.0 <1.0.0",
@@ -47,20 +46,20 @@
47
46
  "mongodb": "^4.1.3"
48
47
  },
49
48
  "devDependencies": {
50
- "@babel/cli": "^7.16.8",
51
- "@babel/core": "^7.16.2",
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
53
  "@babel/preset-env": "^7.16.11",
54
54
  "@natlibfi/eslint-config-melinda-backend": "^2.0.0",
55
- "@babel/eslint-parser": "^7.16.5",
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
59
  "chai": "^4.3.6",
60
60
  "cross-env": "^7.0.3",
61
- "eslint": "^8.8.0",
62
- "eslint-plugin-import": "^2.25.4",
63
- "mocha": "^9.2.0",
61
+ "eslint": "^8.10.0",
62
+ "mocha": "^9.2.1",
64
63
  "nodemon": "^2.0.15",
65
64
  "nyc": "^15.1.0"
66
65
  },