-
Notifications
You must be signed in to change notification settings - Fork 9
/
async.ts
192 lines (177 loc) · 6.2 KB
/
async.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
import type { TurnkeyClient } from ".";
import { PublicApiService as TurnkeyApi } from "./__generated__/barrel";
import { TActivity, TActivityResponse, TurnkeyActivityError } from "./shared";
const DEFAULT_REFRESH_INTERVAL_MS = 500;
/**
* Wraps a request to create a fetcher with built-in async polling support.
*
* @deprecated this function only works with {@link TurnkeyApi}.
* Use {@link TurnkeyClient} and {@link createActivityPoller} instead.
*/
export function withAsyncPolling<
O extends TActivityResponse,
I extends { body: unknown }
>(params: {
request: (input: I) => Promise<O>;
refreshIntervalMs?: number;
}): (input: I) => Promise<O["activity"]> {
const { request, refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS } = params;
return async (input: I) => {
const initialResponse: TActivityResponse = await request(input);
let activity: TActivity = initialResponse.activity;
while (true) {
switch (activity.status) {
case "ACTIVITY_STATUS_COMPLETED": {
return activity;
}
case "ACTIVITY_STATUS_CREATED": {
// Async pending state -- keep polling
break;
}
case "ACTIVITY_STATUS_PENDING": {
// Async pending state -- keep polling
break;
}
case "ACTIVITY_STATUS_CONSENSUS_NEEDED": {
// If the activity requires consensus, we shouldn't be polling forever.
// You can read the `TurnkeyActivityError` thrown to get the `activityId`,
// store it somewhere, then re-fetch the activity via `.postGetActivity(...)`
// when the required approvals/rejections are in place.
throw new TurnkeyActivityError({
message: `Consensus needed for activity ${activity.id}`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
case "ACTIVITY_STATUS_FAILED": {
// Activity failed
throw new TurnkeyActivityError({
message: `Activity ${activity.id} failed`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
case "ACTIVITY_STATUS_REJECTED": {
// Activity was rejected
throw new TurnkeyActivityError({
message: `Activity ${activity.id} was rejected`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
default: {
// Make sure the switch block is exhaustive
assertNever(activity.status);
}
}
await sleep(refreshIntervalMs);
const pollingResponse: TActivityResponse = await TurnkeyApi.getActivity({
body: {
activityId: activity.id,
organizationId: activity.organizationId,
},
});
activity = pollingResponse.activity;
}
};
}
/**
* Wraps a client request function (e.g. `client.createPrivateKeys`) in a poller.
* The default refresh interval is 500ms.
*
* The returned poller will poll until the activity becomes `COMPLETED`.
* If the activity becomes `FAILED` or `REJECTED` or is flagged as `NEEDS_CONSENSUS`, an error is thrown.
*
* @example
* const activityPoller = createActivityPoller(client, client.createPrivateKeys);
* const activity = await activityPoller(input);
* console.log(activity.result); // activity is completed
*/
export function createActivityPoller<
O extends TActivityResponse,
I extends {}
>(params: {
client: TurnkeyClient;
requestFn: (input: I) => Promise<O>;
refreshIntervalMs?: number;
}): (input: I) => Promise<O["activity"]> {
const {
client,
requestFn,
refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS,
} = params;
return async (input: I) => {
const initialResponse: TActivityResponse = await requestFn(input);
let activity: TActivity = initialResponse.activity;
while (true) {
switch (activity.status) {
case "ACTIVITY_STATUS_COMPLETED": {
return activity;
}
case "ACTIVITY_STATUS_CREATED": {
// Async pending state -- keep polling
break;
}
case "ACTIVITY_STATUS_PENDING": {
// Async pending state -- keep polling
break;
}
case "ACTIVITY_STATUS_CONSENSUS_NEEDED": {
// If the activity requires consensus, we shouldn't be polling forever.
// You can read the `TurnkeyActivityError` thrown to get the `activityId`,
// store it somewhere, then re-fetch the activity via `.postGetActivity(...)`
// when the required approvals/rejections are in place.
throw new TurnkeyActivityError({
message: `Consensus needed for activity ${activity.id}`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
case "ACTIVITY_STATUS_FAILED": {
// Activity failed
throw new TurnkeyActivityError({
message: `Activity ${activity.id} failed`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
case "ACTIVITY_STATUS_REJECTED": {
// Activity was rejected
throw new TurnkeyActivityError({
message: `Activity ${activity.id} was rejected`,
activityId: activity.id,
activityStatus: activity.status,
activityType: activity.type,
});
}
default: {
// Make sure the switch block is exhaustive
assertNever(activity.status);
}
}
await sleep(refreshIntervalMs);
const pollingResponse: TActivityResponse = await client.getActivity({
activityId: activity.id,
organizationId: activity.organizationId,
});
activity = pollingResponse.activity;
}
};
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
}
function assertNever(input: never, message?: string): never {
throw new Error(
message != null ? message : `Unexpected case: ${JSON.stringify(input)}`
);
}