-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathIdempotencyHandler.ts
215 lines (201 loc) · 6.6 KB
/
IdempotencyHandler.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
import type { JSONValue } from '@aws-lambda-powertools/commons';
import type { AnyFunction, IdempotencyHandlerOptions } from './types';
import { IdempotencyRecordStatus } from './types';
import {
IdempotencyAlreadyInProgressError,
IdempotencyInconsistentStateError,
IdempotencyItemAlreadyExistsError,
IdempotencyPersistenceLayerError,
} from './errors';
import { BasePersistenceLayer, IdempotencyRecord } from './persistence';
import { IdempotencyConfig } from './IdempotencyConfig';
import { MAX_RETRIES } from './constants';
import { search } from 'jmespath';
/**
* @internal
*
* Class that handles the idempotency lifecycle.
*
* This class is used under the hood by the Idempotency utility
* and provides several methods that are called at different stages
* to orchestrate the idempotency logic.
*/
export class IdempotencyHandler<Func extends AnyFunction> {
/**
* The arguments passed to the function.
*
* For example, if the function is `foo(a, b)`, then `functionArguments` will be `[a, b]`.
* We need to keep track of the arguments so that we can pass them to the function when we call it.
*/
readonly #functionArguments: unknown[];
/**
* The payload to be hashed.
*
* This is the argument that is used for the idempotency.
*/
readonly #functionPayloadToBeHashed: JSONValue;
/**
* Reference to the function to be made idempotent.
*/
readonly #functionToMakeIdempotent: AnyFunction;
/**
* Idempotency configuration options.
*/
readonly #idempotencyConfig: IdempotencyConfig;
/**
* Persistence layer used to store the idempotency records.
*/
readonly #persistenceStore: BasePersistenceLayer;
public constructor(options: IdempotencyHandlerOptions) {
const {
functionToMakeIdempotent,
functionPayloadToBeHashed,
idempotencyConfig,
functionArguments,
persistenceStore,
} = options;
this.#functionToMakeIdempotent = functionToMakeIdempotent;
this.#functionPayloadToBeHashed = functionPayloadToBeHashed;
this.#idempotencyConfig = idempotencyConfig;
this.#functionArguments = functionArguments;
this.#persistenceStore = persistenceStore;
this.#persistenceStore.configure({
config: this.#idempotencyConfig,
});
}
public static determineResultFromIdempotencyRecord(
idempotencyRecord: IdempotencyRecord
): Promise<unknown> | unknown {
if (idempotencyRecord.getStatus() === IdempotencyRecordStatus.EXPIRED) {
throw new IdempotencyInconsistentStateError(
'Item has expired during processing and may not longer be valid.'
);
} else if (
idempotencyRecord.getStatus() === IdempotencyRecordStatus.INPROGRESS
) {
if (
idempotencyRecord.inProgressExpiryTimestamp &&
idempotencyRecord.inProgressExpiryTimestamp <
new Date().getUTCMilliseconds()
) {
throw new IdempotencyInconsistentStateError(
'Item is in progress but the in progress expiry timestamp has expired.'
);
} else {
throw new IdempotencyAlreadyInProgressError(
`There is already an execution in progress with idempotency key: ${idempotencyRecord.idempotencyKey}`
);
}
}
return idempotencyRecord.getResponse();
}
public async getFunctionResult(): Promise<ReturnType<Func>> {
let result;
try {
result = await this.#functionToMakeIdempotent(...this.#functionArguments);
} catch (e) {
try {
await this.#persistenceStore.deleteRecord(
this.#functionPayloadToBeHashed
);
} catch (e) {
throw new IdempotencyPersistenceLayerError(
'Failed to delete record from idempotency store',
e as Error
);
}
throw e;
}
try {
await this.#persistenceStore.saveSuccess(
this.#functionPayloadToBeHashed,
result
);
} catch (e) {
throw new IdempotencyPersistenceLayerError(
'Failed to update success record to idempotency store',
e as Error
);
}
return result;
}
/**
* Main entry point for the handler
*
* In some rare cases, when the persistent state changes in small time
* window, we might get an `IdempotencyInconsistentStateError`. In such
* cases we can safely retry the handling a few times.
*/
public async handle(): Promise<ReturnType<Func>> {
let e;
for (let retryNo = 0; retryNo <= MAX_RETRIES; retryNo++) {
try {
return await this.processIdempotency();
} catch (error) {
if (
error instanceof IdempotencyInconsistentStateError &&
retryNo < MAX_RETRIES
) {
// Retry
continue;
}
// Retries exhausted or other error
e = error;
break;
}
}
throw e;
}
public async processIdempotency(): Promise<ReturnType<Func>> {
// early return if we should skip idempotency completely
if (
IdempotencyHandler.shouldSkipIdempotency(
this.#idempotencyConfig.eventKeyJmesPath,
this.#idempotencyConfig.throwOnNoIdempotencyKey,
this.#functionPayloadToBeHashed
)
) {
return await this.#functionToMakeIdempotent(...this.#functionArguments);
}
try {
await this.#persistenceStore.saveInProgress(
this.#functionPayloadToBeHashed,
this.#idempotencyConfig.lambdaContext?.getRemainingTimeInMillis()
);
} catch (e) {
if (e instanceof IdempotencyItemAlreadyExistsError) {
const idempotencyRecord: IdempotencyRecord =
await this.#persistenceStore.getRecord(
this.#functionPayloadToBeHashed
);
return IdempotencyHandler.determineResultFromIdempotencyRecord(
idempotencyRecord
) as ReturnType<Func>;
} else {
throw new IdempotencyPersistenceLayerError(
'Failed to save in progress record to idempotency store',
e as Error
);
}
}
return this.getFunctionResult();
}
/**
* avoid idempotency if the eventKeyJmesPath is not present in the payload and throwOnNoIdempotencyKey is false
* static so {@link makeHandlerIdempotent} middleware can use it
* TOOD: refactor so middy uses IdempotencyHandler internally wihtout reimplementing the logic
* @param eventKeyJmesPath
* @param throwOnNoIdempotencyKey
* @param fullFunctionPayload
* @private
*/
public static shouldSkipIdempotency(
eventKeyJmesPath: string,
throwOnNoIdempotencyKey: boolean,
fullFunctionPayload: JSONValue
): boolean {
return (eventKeyJmesPath &&
!throwOnNoIdempotencyKey &&
!search(fullFunctionPayload, eventKeyJmesPath)) as boolean;
}
}