-
Notifications
You must be signed in to change notification settings - Fork 105
/
base.js
489 lines (418 loc) · 13.2 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
'use strict';
const get = require('lodash.get');
const Ajv = require('ajv');
const pWaitFor = require('p-wait-for');
const aws = require('@cumulus/common/aws');
const { deprecate } = require('@cumulus/common/util');
const { inTestMode } = require('@cumulus/common/test-utils');
const { errorify } = require('../lib/utils');
const { RecordDoesNotExist } = require('../lib/errors');
const { search } = require('../lib/search');
async function enableStream(tableName) {
const params = {
TableName: tableName,
StreamSpecification: {
StreamEnabled: true,
StreamViewType: 'NEW_AND_OLD_IMAGES'
}
};
await aws.dynamodb().updateTable(params).promise();
await pWaitFor(
async () =>
aws.dynamodb().describeTable({ TableName: tableName }).promise()
.then((response) => response.TableStatus !== 'UPDATING'),
{ interval: 5 * 1000 }
);
}
/**
* Helper for creating a dynamoDB table
*
* @param {string} tableName - dynamoDB table name
* @param {Object} hash - object describing the dynamodb hash (primary key) field
* @param {string} hash.name - name of the field
* @param {string} hash.type - type of the field (e.g. S for string and N for number)
* @param {Object} range - object describing the dynamodb range field
* @param {string} range.name - name of the field
* @param {string} range.type - type of the field (e.g. S for string and N for number)
* @returns {Promise<Object>} aws dynamodb table creation response
*/
async function createTable(tableName, hash, range = null) {
const params = {
TableName: tableName,
AttributeDefinitions: [{
AttributeName: hash.name,
AttributeType: hash.type
}],
KeySchema: [{
AttributeName: hash.name,
KeyType: 'HASH'
}],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
};
if (range) {
params.KeySchema.push({
AttributeName: range.name,
KeyType: 'RANGE'
});
params.AttributeDefinitions.push({
AttributeName: range.name,
AttributeType: range.type
});
}
const output = await aws.dynamodb().createTable(params).promise();
await aws.dynamodb().waitFor('tableExists', { TableName: tableName }).promise();
if (!inTestMode()) await enableStream(tableName);
return output;
}
async function deleteTable(tableName) {
const output = await aws.dynamodb().deleteTable({
TableName: tableName
}).promise();
await aws.dynamodb().waitFor('tableNotExists', { TableName: tableName }).promise();
return output;
}
/**
* The manager class handles basic operations on a given DynamoDb table
*/
class Manager {
static recordIsValid(item, schema = null, removeAdditional = false) {
if (!schema) {
throw new Error('schema is not defined');
}
const schemaWithAdditionalPropertiesProhibited = JSON.parse(
JSON.stringify(
schema,
(_, value) => {
if (value.type === 'object') {
return {
additionalProperties: false,
...value
};
}
return value;
}
)
);
const ajv = new Ajv({
removeAdditional,
useDefaults: true,
v5: true
});
const validate = ajv.compile(schemaWithAdditionalPropertiesProhibited);
const valid = validate(item);
if (!valid) {
const err = new Error('The record has validation errors');
err.name = 'SchemaValidationError';
err.detail = validate.errors;
throw err;
}
}
static createTable(tableName, hash, range = null) {
deprecate('@cumulus/api/models/base Manager.createTable()', '1.10.3', 'the createTable() instance method');
return createTable(tableName, hash, range);
}
static deleteTable(tableName) {
deprecate('@cumulus/api/models/base Manager.deleteTable()', '1.10.3', 'the deleteTable() instance method');
return deleteTable(tableName);
}
/**
* Constructor of Manager class
*
* @param {Object} params - params
* @param {string} params.tableName - (required) the name of the DynamoDB
* table associated with this model
* @param {Object} params.tableHash - (required) an object containing "name"
* and "type" properties, which specify the partition key of the DynamoDB
* table.
* @param {Object} params.tableRange - an object containing "name" and "type"
* properties, which specify the sort key of the DynamoDB table.
* @param {Object} params.schema - the JSON schema to validate the records
* against.
* @param {boolean} [params.validate=true] - whether items should be validated
* before being written to the database. The _only_ time this should ever
* be set to false is when restoring from a backup, and that code is already
* written. So no other time. Don't even think about it. I know you're
* going to say, "but it's only for this one test case". No.
* Find another way.
*/
constructor(params = {}) {
// Make sure all required parameters are present
if (!params.tableName) throw new TypeError('params.tableName is required');
if (!params.tableHash) throw new TypeError('params.tableHash is required');
this.tableName = params.tableName;
this.tableHash = params.tableHash;
this.tableRange = params.tableRange;
this.schema = params.schema;
this.dynamodbDocClient = aws.dynamodbDocClient({ convertEmptyValues: true });
this.removeAdditional = false;
this.validate = get(params, 'validate', true);
}
/**
* Create the DynamoDB table associated with a model
*
* @returns {Promise} resolves when the table exists
*/
createTable() {
return createTable(this.tableName, this.tableHash, this.tableRange);
}
/**
* Delete the DynamoDB table associated with a model
*
* @returns {Promise} resolves when the table no longer exists
*/
deleteTable() {
return deleteTable(this.tableName);
}
/**
* Check if an item exists
*
* @param {Object} Key - the key to check for
* @returns {boolean}
*/
async exists(Key) {
try {
await this.get(Key);
return true;
}
catch (err) {
if (err instanceof RecordDoesNotExist) return false;
throw err;
}
}
/**
* Enable DynamoDB streams on the table
*
* @returns {Promise} resolves when streams are enabled
*/
enableStream() {
return enableStream(this.tableName);
}
/**
* Gets the item if found. If the record does not exist
* the function throws RecordDoesNotExist error
*
* @param {Object} item - the item to search for
* @returns {Promise} The record found
*/
async get(item) {
const params = {
TableName: this.tableName,
Key: item
};
try {
const getResponse = await this.dynamodbDocClient.get(params).promise();
if (!getResponse.Item) {
throw new RecordDoesNotExist();
}
return getResponse.Item;
}
catch (e) {
throw new RecordDoesNotExist(
`No record found for ${JSON.stringify(item)} in ${this.tableName}`
);
}
}
async batchGet(items, attributes = null) {
const params = {
RequestItems: {
[this.tableName]: {
Keys: items
}
}
};
if (attributes) {
params.RequestItems[this.tableName].AttributesToGet = attributes;
}
return this.dynamodbDocClient.batchGet(params).promise();
}
async batchWrite(deletes, puts = []) {
const deleteRequests = (deletes || []).map((Key) => ({
DeleteRequest: { Key }
}));
const now = Date.now();
const putsWithTimestamps = puts.map((item) => ({
createdAt: now,
...item,
updatedAt: now
}));
if (this.validate) {
putsWithTimestamps.forEach((item) => {
this.constructor.recordIsValid(item, this.schema, this.removeAdditional);
});
}
const putRequests = putsWithTimestamps.map((Item) => ({
PutRequest: { Item }
}));
const requests = deleteRequests.concat(putRequests);
if (requests > 25) {
throw new Error('Batch Write supports 25 or fewer bulk actions at the same time');
}
const params = {
RequestItems: {
[this.tableName]: requests
}
};
return this.dynamodbDocClient.batchWrite(params).promise();
}
/**
* creates record(s)
*
* @param {Object<Array|Object>} items - the Item/Items to be added to the database
* @returns {Promise<Array|Object>} an array of created records or a single
* created record
*/
async create(items) {
// This is confusing because the argument named "items" could either be
// an Array of items or a single item. To make this function a little
// easier to understand, converting the single item case here to an array
// containing one item.
const itemsArray = Array.isArray(items) ? items : [items];
// For each item, set the updatedAt property. If it does not have a
// createdAt property, set that as well. Instead of modifying the original
// item, this returns an updated copy of the item.
const itemsWithTimestamps = itemsArray.map((item) => {
const now = Date.now();
return {
createdAt: now,
...item,
updatedAt: now,
timestamp: now
};
});
if (this.validate) {
// Make sure that all of the items are valid
itemsWithTimestamps.forEach((item) => {
this.constructor.recordIsValid(item, this.schema, this.removeAdditional);
});
}
// Suggested method of handling a loop containing an await, according to
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
for (let i = 0; i < itemsWithTimestamps.length; i += 1) {
await this.dynamodbDocClient.put({ // eslint-disable-line no-await-in-loop
TableName: this.tableName,
Item: itemsWithTimestamps[i]
}).promise();
}
// If the original item was an Array, return an Array. If the original item
// was an Object, return an Object.
return Array.isArray(items) ? itemsWithTimestamps : itemsWithTimestamps[0];
}
async scan(query, fields, limit, select, startKey) {
const params = {
TableName: this.tableName
};
if (query) {
if (query.filter && query.values) {
params.FilterExpression = query.filter;
params.ExpressionAttributeValues = query.values;
}
if (query.names) {
params.ExpressionAttributeNames = query.names;
}
}
if (fields) {
params.ProjectionExpression = fields;
}
if (limit) {
params.Limit = limit;
}
if (select) {
params.Select = select;
}
if (startKey) {
params.ExclusiveStartKey = startKey;
}
const resp = await this.dynamodbDocClient.scan(params).promise();
// recursively go through all the records
if (resp.LastEvaluatedKey) {
const more = await this.scan(query, fields, limit, select, resp.LastEvaluatedKey);
if (more.Items) {
resp.Items = more.Items.concat(more.Items);
}
resp.Count += more.Count;
}
return resp;
}
search(query) {
return search({ q: query, context: this });
}
async delete(item) {
const params = {
TableName: this.tableName,
Key: item
};
return this.dynamodbDocClient.delete(params).promise();
}
async update(itemKeys, updates = {}, fieldsToDelete = []) {
const actualUpdates = {
...updates,
updatedAt: Date.now()
};
// Make sure that we don't update the key fields
const itemKeyNames = Object.keys(itemKeys);
itemKeyNames.forEach((property) => delete actualUpdates[property]);
// Make sure that we don't try to update a field that's being deleted
fieldsToDelete.forEach((property) => delete actualUpdates[property]);
const schemaWithoutRequiredParams = JSON.parse(
JSON.stringify(
this.schema,
(key, value) => (key === 'required' ? [] : value)
)
);
if (this.validate) {
this.constructor.recordIsValid(
actualUpdates,
schemaWithoutRequiredParams,
this.removeAdditional
);
}
// Build the actual update request
const attributeUpdates = {};
Object.keys(actualUpdates).forEach((property) => {
attributeUpdates[property] = {
Action: 'PUT',
Value: actualUpdates[property]
};
});
// Add keys to be deleted
fieldsToDelete.forEach((property) => {
attributeUpdates[property] = { Action: 'DELETE' };
});
// Perform the update
const updateResponse = await this.dynamodbDocClient.update({
TableName: this.tableName,
Key: itemKeys,
ReturnValues: 'ALL_NEW',
AttributeUpdates: attributeUpdates
}).promise();
return updateResponse.Attributes;
}
/**
* Updates the status field
*
* @param {Object} key - the key to update
* @param {string} status - the new status
* @returns {Promise} the updated record
*/
updateStatus(key, status) {
return this.update(key, { status });
}
/**
* Marks the record is failed with proper status
* and error message
*
* @param {Object} key - the key to update
* @param {Object} err - the error object
* @returns {Promise} the updated record
*/
hasFailed(key, err) {
return this.update(
key,
{ status: 'failed', error: errorify(err), isActive: false }
);
}
}
module.exports = Manager;