-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathIdempotencyHandler.ts
146 lines (134 loc) · 4.47 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
import type { AnyFunctionWithRecord, IdempotencyHandlerOptions } from './types';
import { IdempotencyRecordStatus } from './types';
import {
IdempotencyAlreadyInProgressError,
IdempotencyInconsistentStateError,
IdempotencyItemAlreadyExistsError,
IdempotencyPersistenceLayerError,
} from './Exceptions';
import { BasePersistenceLayer, IdempotencyRecord } from './persistence';
import { IdempotencyConfig } from './IdempotencyConfig';
import { MAX_RETRIES } from './constants';
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'
);
}
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'
);
}
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> {
try {
await this.persistenceStore.saveInProgress(
this.functionPayloadToBeHashed
);
} 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();
}
}
return this.getFunctionResult();
}
}