-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
263 lines (260 loc) · 7.78 KB
/
index.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
import { ProgressBar } from './ProgressBar.js';
/**
* the arguments for the waitForCompletion function, which is the
* main entry point for the library
*/
export type WaitForCompletionArgs = {
/**
* the name of the progress bar to wait for completion of
*/
pbarName: string;
/**
* the uid of the trace to watch
*/
uid: string;
/**
* the identifier for the account the progress bar belongs to
*/
sub: string;
/**
* checks if your backend is finished processing the trace;
* used as a fallback if ezpbars is not available.
*
* typically, this is implemented using a fetch to your backend,
* in the same way that you would normally get the result after
* this library notifies you that the result is ready
*/
pollResult: () => Promise<boolean>;
/**
* the progress bar that's being rendered
*
* @default null
*/
pbar: ProgressBar | null;
/**
* the domain to make the websocket connection to
*
* @default "ezpbars.com"
*/
domain: string | null;
/**
* indicates the scheme for the url where true is wss and false is ws
*
* @default true
*/
ssl: boolean;
};
/**
* handles receiving a trace from the websocket
*/
class TraceHandler {
/**
* the identifier for the account the progress bar belongs to
*/
readonly sub: string;
/**
* the name of the progress bar to wait for completion of
*/
readonly pbarName: string;
/**
* the uid of the trace to watch
*/
readonly uid: string;
/**
* the domain to make the websocket connection to
*/
readonly domain: string;
/**
* indicates the scheme for the url where true is wss and false is ws
*/
readonly ssl: boolean;
/**
* the connection to ezpbars.com if open
*/
ws: WebSocket | null;
/**
* the progress bar that's being rendered
*/
pbar: ProgressBar | null;
/**
* the number of times the connection has failed in the last minute
*/
failures: number;
/**
* called whenever this has finished, whether from an error, or because the trace has completed
* @param error the error that occurred, if any
*/
onComplete: (error: string | null) => void;
/**
* same as WaitForCompletionArgs#pollResult
*/
pollResult: () => Promise<boolean>;
constructor(args: WaitForCompletionArgs, onComplete: (error: string | null) => void) {
this.sub = args.sub;
this.pbarName = args.pbarName;
this.uid = args.uid;
this.domain = args.domain || 'ezpbars.com';
this.ssl = args.ssl || true;
this.onComplete = onComplete;
this.pollResult = args.pollResult;
this.onAuthResponse = this.onAuthResponse.bind(this);
this.onCloseEvent = this.onCloseEvent.bind(this);
this.onTraceMessage = this.onTraceMessage.bind(this);
this.sendAuthRequest = this.sendAuthRequest.bind(this);
this.connect = this.connect.bind(this);
this.connect();
}
/**
* builds a url for the websocket connection
* @returns the url to make the websocket connection to
*/
url(): string {
return `${'wss' ? this.ssl : 'ws'}://${this.domain}/api/2/progress_bars/traces/`;
}
/**
* opens the websocket and sets the initial listeners
* @private
*/
connect() {
this.ws = new WebSocket(this.url());
this.ws.addEventListener('open', this.sendAuthRequest);
this.ws.addEventListener('message', this.onAuthResponse);
this.ws.addEventListener('close', this.onCloseEvent);
}
/**
* called when the connection to the websocket is closed
* @param closeEvent the close event received from the websocket
*/
private onCloseEvent(closeEvent: CloseEvent) {
this.failures++;
setTimeout(
(() => {
this.failures--;
}).bind(this),
60 * 1000
);
this.retryConnection(this.failures);
}
/**
* handles receiving the authentication response from the websocket
* @param messageEvent the message event received from the websocket
*/
private onAuthResponse(messageEvent: MessageEvent) {
const data = JSON.parse(messageEvent.data);
if (!data.success) {
this.pbar.onError(new Error(data.error_message));
this.ws.removeEventListener('close', this.onCloseEvent);
this.ws.close();
return this.onComplete(data.error_message);
}
this.ws.removeEventListener('message', this.onAuthResponse);
this.ws.addEventListener('message', this.onTraceMessage);
}
/**
* handles receiving a trace message from the websocket
* @param messageEvent the message event received from the websocket
*/
private onTraceMessage(messageEvent: MessageEvent) {
const data = JSON.parse(messageEvent.data);
if (data.type === 'update') {
this.pbar.overallEtaSeconds = data.data.overall_eta_seconds;
this.pbar.remainingEtaSeconds = data.data.remaining_eta_seconds;
this.pbar.stepName = data.data.step_name;
this.pbar.stepOverallEtaSeconds = data.data.step_overall_eta_seconds;
this.pbar.stepRemainingEtaSeconds = data.data.step_remaining_eta_seconds;
}
if (data.done) {
this.ws.removeEventListener('close', this.onCloseEvent);
this.ws.close();
return this.onComplete(null);
}
}
/**
* sends the authentication request to the websocket
*/
private sendAuthRequest() {
this.ws.addEventListener('message', this.onAuthResponse);
this.ws.send(
JSON.stringify({
sub: this.sub,
uid: this.uid,
pbar_name: this.pbarName,
})
);
}
/**
* tries to reconnect to the websocket after the connection has been closed.
* waits up to 15 seconds before trying to reconnect based on how many times it's already tried
* @param failures the number of times the websocket has failed to connect in the past minute
*/
private async retryConnection(failures: number) {
let delay = 0;
if (failures === 3) {
delay = 1;
}
if (failures === 4) {
delay = 4;
}
if (failures >= 5) {
delay = 15;
const polledResult = await this.pollResult();
if (polledResult) {
return this.onComplete(null);
}
}
setTimeout(this.connect, delay * 1000);
}
}
/**
* waits for the given trace to complete, sending progress information to the
* given progress bar. typically, the progress bar would react to the changes by
* updating the UI, such as by literally drawing a progress bar, or just using a
* spinner, or some combination based on context
*
* For an implementation of a progress bar, you can try SimpleProgressBar, SimpleSpinner,
* or StandardProgressDisplay
*
* ```ts
* import { waitForCompletion, StandardProgressDisplay } from 'ezpbarsjs';
*
* const pbar = new StandardProgressDisplay();
* document.body.appendChild(pbar.element);
* const response = await fetch(
* 'https://ezpbars.com/api/1/examples/job',
* {
* method: 'POST',
* headers: { "content-type": "application/json; charset=UTF-8" },
* body: JSON.stringify({
* duration: 5,
* stdev: 1,
* }),
* }
* )
* /** @type {{uid: str, sub: str, pbar_name: str}} * /
* const data = await response.json();
* const getResult = async () => {
* const response = await fetch(`https://ezpbars.com/api/1/examples/job?uid=${data.uid}`)
* const result = await response.json();
* if (result.status === 'complete') {
* return result.data;
* }
* return null;
* }
* const pollResult = async () => (await getResult()) !== null;
* await waitForCompletion({sub: data.sub, pbarName: data.pbar_name, uid: data.uid, pbar, pollResult});
* console.log(await getResult());
* ```
*
* @param args the arguments to use when waiting for completion of the progress
* bar
*/
export function waitForCompletion(args: WaitForCompletionArgs): Promise<void> {
return new Promise((resolve, reject) => {
new TraceHandler(args, (error: string | null) => {
if (error) {
return reject(error);
}
resolve();
});
});
}