-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathIdempotencyHandler.ts
186 lines (172 loc) · 5.75 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
import type { AnyFunctionWithRecord, 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
*/
export class IdempotencyHandler<U> {
private readonly fullFunctionPayload: Record<string, unknown>;
private readonly functionPayloadToBeHashed: Record<string, unknown>;
private readonly functionToMakeIdempotent: AnyFunctionWithRecord<U>;
private readonly idempotencyConfig: IdempotencyConfig;
private readonly persistenceStore: BasePersistenceLayer;
public constructor(options: IdempotencyHandlerOptions<U>) {
const {
functionToMakeIdempotent,
functionPayloadToBeHashed,
idempotencyConfig,
fullFunctionPayload,
persistenceStore,
} = options;
this.functionToMakeIdempotent = functionToMakeIdempotent;
this.functionPayloadToBeHashed = functionPayloadToBeHashed;
this.idempotencyConfig = idempotencyConfig;
this.fullFunctionPayload = fullFunctionPayload;
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<U> {
let result: U;
try {
result = await this.functionToMakeIdempotent(this.fullFunctionPayload);
} 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 as Record<string, unknown>
);
} 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<U> {
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<U> {
// early return if we should skip idempotency completely
if (
IdempotencyHandler.shouldSkipIdempotency(
this.idempotencyConfig.eventKeyJmesPath,
this.idempotencyConfig.throwOnNoIdempotencyKey,
this.fullFunctionPayload
)
) {
return await this.functionToMakeIdempotent(this.fullFunctionPayload);
}
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 U;
} else {
throw new IdempotencyPersistenceLayerError(
'Failed to save record in progress',
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: Record<string, unknown>
): boolean {
return (eventKeyJmesPath &&
!throwOnNoIdempotencyKey &&
!search(fullFunctionPayload, eventKeyJmesPath)) as boolean;
}
}