-
Notifications
You must be signed in to change notification settings - Fork 128
/
BasePersistenceLayer.ts
383 lines (336 loc) · 12.8 KB
/
BasePersistenceLayer.ts
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
import { createHash, Hash } from 'node:crypto';
import { search } from '@aws-lambda-powertools/jmespath';
import type { JMESPathParsingOptions } from '@aws-lambda-powertools/jmespath/types';
import type {
BasePersistenceLayerOptions,
BasePersistenceLayerInterface,
} from '../types/BasePersistenceLayer.js';
import { IdempotencyRecordStatus } from '../constants.js';
import { EnvironmentVariablesService } from '../config/EnvironmentVariablesService.js';
import { IdempotencyRecord } from './IdempotencyRecord.js';
import {
IdempotencyItemAlreadyExistsError,
IdempotencyKeyError,
IdempotencyValidationError,
} from '../errors.js';
import { LRUCache } from './LRUCache.js';
import type { JSONValue } from '@aws-lambda-powertools/commons/types';
/**
* Base class for all persistence layers. This class provides the basic functionality for
* saving, retrieving, and deleting idempotency records. It also provides the ability to
* configure the persistence layer from the idempotency config.
* @abstract
* @class
* @implements {BasePersistenceLayerInterface}
*/
abstract class BasePersistenceLayer implements BasePersistenceLayerInterface {
public idempotencyKeyPrefix: string;
private cache?: LRUCache<string, IdempotencyRecord>;
private configured = false;
// envVarsService is always initialized in the constructor
private envVarsService!: EnvironmentVariablesService;
private eventKeyJmesPath?: string;
private expiresAfterSeconds: number = 60 * 60; // 1 hour default
private hashFunction = 'md5';
private payloadValidationEnabled = false;
private throwOnNoIdempotencyKey = false;
private useLocalCache = false;
private validationKeyJmesPath?: string;
#jmesPathOptions?: JMESPathParsingOptions;
public constructor() {
this.envVarsService = new EnvironmentVariablesService();
this.idempotencyKeyPrefix = this.getEnvVarsService().getFunctionName();
}
/**
* Initialize the base persistence layer from the configuration settings
*
* @param {BasePersistenceLayerConfigureOptions} config - configuration object for the persistence layer
*/
public configure(config: BasePersistenceLayerOptions): void {
// Extracting the idempotency config from the config object for easier access
const { config: idempotencyConfig } = config;
if (config?.functionName && config.functionName.trim() !== '') {
this.idempotencyKeyPrefix = `${this.idempotencyKeyPrefix}.${config.functionName}`;
}
// Prevent reconfiguration
if (this.configured) {
return;
}
this.configured = true;
this.eventKeyJmesPath = idempotencyConfig?.eventKeyJmesPath;
this.validationKeyJmesPath = idempotencyConfig?.payloadValidationJmesPath;
this.#jmesPathOptions = idempotencyConfig.jmesPathOptions;
this.payloadValidationEnabled =
this.validationKeyJmesPath !== undefined || false;
this.throwOnNoIdempotencyKey =
idempotencyConfig?.throwOnNoIdempotencyKey || false;
this.eventKeyJmesPath = idempotencyConfig.eventKeyJmesPath;
this.expiresAfterSeconds = idempotencyConfig.expiresAfterSeconds; // 1 hour default
this.useLocalCache = idempotencyConfig.useLocalCache;
if (this.useLocalCache) {
this.cache = new LRUCache({
maxSize: idempotencyConfig.maxLocalCacheSize,
});
}
this.hashFunction = idempotencyConfig.hashFunction;
}
/**
* Deletes a record from the persistence store for the persistence key generated from the data passed in.
*
* @param data - the data payload that will be hashed to create the hash portion of the idempotency key
*/
public async deleteRecord(data: JSONValue): Promise<void> {
const idempotencyRecord = new IdempotencyRecord({
idempotencyKey: this.getHashedIdempotencyKey(data),
status: IdempotencyRecordStatus.EXPIRED,
});
await this._deleteRecord(idempotencyRecord);
this.deleteFromCache(idempotencyRecord.idempotencyKey);
}
/**
* Retrieve the number of seconds that records will be kept in the persistence store
*/
public getExpiresAfterSeconds(): number {
return this.expiresAfterSeconds;
}
/**
* Retrieves idempotency key for the provided data and fetches data for that key from the persistence store
*
* @param data - the data payload that will be hashed to create the hash portion of the idempotency key
*/
public async getRecord(data: JSONValue): Promise<IdempotencyRecord> {
const idempotencyKey = this.getHashedIdempotencyKey(data);
const cachedRecord = this.getFromCache(idempotencyKey);
if (cachedRecord) {
this.validatePayload(data, cachedRecord);
return cachedRecord;
}
const record = await this._getRecord(idempotencyKey);
this.processExistingRecord(record, data);
return record;
}
/**
* Check whether payload validation is enabled or not
*/
public isPayloadValidationEnabled(): boolean {
return this.payloadValidationEnabled;
}
/**
* Validates an existing record against the data payload being processed.
* If the payload does not match the stored record, an `IdempotencyValidationError` error is thrown.
*
* Whenever a record is retrieved from the persistence layer, it should be validated against the data payload
* being processed. This is to ensure that the data payload being processed is the same as the one that was
* used to create the record in the first place.
*
* The record is also saved to the local cache if local caching is enabled.
*
* @param record - the stored record to validate against
* @param data - the data payload being processed and to be validated against the stored record
*/
public processExistingRecord(
storedDataRecord: IdempotencyRecord,
processedData: JSONValue | IdempotencyRecord
): IdempotencyRecord {
this.validatePayload(processedData, storedDataRecord);
this.saveToCache(storedDataRecord);
return storedDataRecord;
}
/**
* Saves a record indicating that the function's execution is currently in progress
*
* @param data - the data payload that will be hashed to create the hash portion of the idempotency key
* @param remainingTimeInMillis - the remaining time left in the lambda execution context
*/
public async saveInProgress(
data: JSONValue,
remainingTimeInMillis?: number
): Promise<void> {
const idempotencyRecord = new IdempotencyRecord({
idempotencyKey: this.getHashedIdempotencyKey(data),
status: IdempotencyRecordStatus.INPROGRESS,
expiryTimestamp: this.getExpiryTimestamp(),
payloadHash: this.getHashedPayload(data),
});
if (remainingTimeInMillis) {
idempotencyRecord.inProgressExpiryTimestamp =
new Date().getTime() + remainingTimeInMillis;
} else {
console.warn(
'Could not determine remaining time left. Did you call registerLambdaContext on IdempotencyConfig?'
);
}
const cachedRecord = this.getFromCache(idempotencyRecord.idempotencyKey);
if (cachedRecord) {
throw new IdempotencyItemAlreadyExistsError(
`Failed to put record for already existing idempotency key: ${idempotencyRecord.idempotencyKey}`,
cachedRecord
);
}
await this._putRecord(idempotencyRecord);
}
/**
* Saves a record of the function completing successfully. This will create a record with a COMPLETED status
* and will save the result of the completed function in the idempotency record.
*
* @param data - the data payload that will be hashed to create the hash portion of the idempotency key
* @param result - the result of the successfully completed function
*/
public async saveSuccess(data: JSONValue, result: JSONValue): Promise<void> {
const idempotencyRecord = new IdempotencyRecord({
idempotencyKey: this.getHashedIdempotencyKey(data),
status: IdempotencyRecordStatus.COMPLETED,
expiryTimestamp: this.getExpiryTimestamp(),
responseData: result,
payloadHash: this.getHashedPayload(data),
});
await this._updateRecord(idempotencyRecord);
this.saveToCache(idempotencyRecord);
}
protected abstract _deleteRecord(record: IdempotencyRecord): Promise<void>;
protected abstract _getRecord(
idempotencyKey: string
): Promise<IdempotencyRecord>;
protected abstract _putRecord(record: IdempotencyRecord): Promise<void>;
protected abstract _updateRecord(record: IdempotencyRecord): Promise<void>;
private deleteFromCache(idempotencyKey: string): void {
if (!this.useLocalCache) return;
// Delete from local cache if it exists
if (this.cache?.has(idempotencyKey)) {
this.cache?.remove(idempotencyKey);
}
}
/**
* Generates a hash of the data and returns the digest of that hash
*
* @param data the data payload that will generate the hash
* @returns the digest of the generated hash
*/
private generateHash(data: string): string {
const hash: Hash = createHash(this.hashFunction);
hash.update(data);
return hash.digest('base64');
}
/**
* Getter for `envVarsService`.
* Used internally during initialization.
*/
private getEnvVarsService(): EnvironmentVariablesService {
return this.envVarsService;
}
/**
* Creates the expiry timestamp for the idempotency record
*
* @returns the expiry time for the record expressed as number of seconds past the UNIX epoch
*/
private getExpiryTimestamp(): number {
const currentTime: number = Date.now() / 1000;
return currentTime + this.expiresAfterSeconds;
}
private getFromCache(idempotencyKey: string): IdempotencyRecord | undefined {
if (!this.useLocalCache) return undefined;
const cachedRecord = this.cache?.get(idempotencyKey);
if (cachedRecord) {
// if record is not expired, return it
if (!cachedRecord.isExpired()) return cachedRecord;
// if record is expired, delete it from cache
this.deleteFromCache(idempotencyKey);
}
}
/**
* Generates the idempotency key used to identify records in the persistence store.
*
* @param data the data payload that will be hashed to create the hash portion of the idempotency key
* @returns the idempotency key
*/
private getHashedIdempotencyKey(data: JSONValue): string {
if (this.eventKeyJmesPath) {
data = search(
this.eventKeyJmesPath,
data,
this.#jmesPathOptions
) as JSONValue;
}
if (BasePersistenceLayer.isMissingIdempotencyKey(data)) {
if (this.throwOnNoIdempotencyKey) {
throw new IdempotencyKeyError(
'No data found to create a hashed idempotency_key'
);
}
console.warn(
`No value found for idempotency_key. jmespath: ${this.eventKeyJmesPath}`
);
}
return `${this.idempotencyKeyPrefix}#${this.generateHash(
JSON.stringify(data)
)}`;
}
/**
* Extract payload using validation key jmespath and return a hashed representation
*
* @param data payload
*/
private getHashedPayload(data: JSONValue): string {
if (this.isPayloadValidationEnabled() && this.validationKeyJmesPath) {
data = search(
this.validationKeyJmesPath,
data,
this.#jmesPathOptions
) as JSONValue;
return this.generateHash(JSON.stringify(data));
} else {
return '';
}
}
private static isMissingIdempotencyKey(data: JSONValue): boolean {
if (Array.isArray(data) || typeof data === 'object') {
if (data === null) return true;
for (const value of Object.values(data)) {
if (value) {
return false;
}
}
return true;
}
return !data;
}
/**
* Save record to local cache except for when status is `INPROGRESS`.
*
* Records with `INPROGRESS` status are not cached because we have no way to
* reflect updates that might happen to the record outside the execution
* context of the function.
*
* @param record - record to save
*/
private saveToCache(record: IdempotencyRecord): void {
if (!this.useLocalCache) return;
if (record.getStatus() === IdempotencyRecordStatus.INPROGRESS) return;
this.cache?.add(record.idempotencyKey, record);
}
/**
* Validates the payload against the stored record. If the payload does not match the stored record,
* an `IdempotencyValidationError` error is thrown.
*
* @param data - The data payload to validate against the stored record
* @param storedDataRecord - The stored record to validate against
*/
private validatePayload(
data: JSONValue | IdempotencyRecord,
storedDataRecord: IdempotencyRecord
): void {
if (this.payloadValidationEnabled) {
const hashedPayload =
data instanceof IdempotencyRecord
? data.payloadHash
: this.getHashedPayload(data);
if (hashedPayload !== storedDataRecord.payloadHash) {
throw new IdempotencyValidationError(
'Payload does not match stored record for this event key',
storedDataRecord
);
}
}
}
}
export { BasePersistenceLayer };