-
Notifications
You must be signed in to change notification settings - Fork 48
/
upchunk.ts
363 lines (316 loc) · 10.1 KB
/
upchunk.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import { EventTarget, Event } from 'event-target-shim';
import xhr, { XhrUrlConfig, XhrHeaders, XhrResponse } from 'xhr';
const SUCCESSFUL_CHUNK_UPLOAD_CODES = [200, 201, 202, 204, 308];
const TEMPORARY_ERROR_CODES = [408, 502, 503, 504]; // These error codes imply a chunk may be retried
type EventName =
| 'attempt'
| 'attemptFailure'
| 'chunkSuccess'
| 'error'
| 'offline'
| 'online'
| 'progress'
| 'success';
// NOTE: This and the EventTarget definition below could be more precise
// by e.g. typing the detail of the CustomEvent per EventName.
type UpchunkEvent = CustomEvent & Event<EventName>;
type AllowedMethods =
| 'PUT'
| 'POST'
| 'PATCH';
export interface UpChunkOptions {
endpoint: string | ((file?: File) => Promise<string>);
file: File;
method?: AllowedMethods;
headers?: XhrHeaders;
maxFileSize?: number;
chunkSize?: number;
attempts?: number;
delayBeforeAttempt?: number;
}
export class UpChunk {
public endpoint: string | ((file?: File) => Promise<string>);
public file: File;
public headers: XhrHeaders;
public method: AllowedMethods;
public chunkSize: number;
public attempts: number;
public delayBeforeAttempt: number;
private chunk: Blob;
private chunkCount: number;
private chunkByteSize: number;
private maxFileBytes: number;
private endpointValue: string;
private totalChunks: number;
private attemptCount: number;
private offline: boolean;
private paused: boolean;
private success: boolean;
private currentXhr?: XMLHttpRequest;
private reader: FileReader;
private eventTarget: EventTarget<Record<EventName,UpchunkEvent>>;
constructor(options: UpChunkOptions) {
this.endpoint = options.endpoint;
this.file = options.file;
this.headers = options.headers || ({} as XhrHeaders);
this.method = options.method || 'PUT';
this.chunkSize = options.chunkSize || 30720;
this.attempts = options.attempts || 5;
this.delayBeforeAttempt = options.delayBeforeAttempt || 1;
this.maxFileBytes = (options.maxFileSize || 0) * 1024;
this.chunkCount = 0;
this.chunkByteSize = this.chunkSize * 1024;
this.totalChunks = Math.ceil(this.file.size / this.chunkByteSize);
this.attemptCount = 0;
this.offline = false;
this.paused = false;
this.success = false;
this.reader = new FileReader();
this.eventTarget = new EventTarget();
this.validateOptions();
this.getEndpoint().then(() => this.sendChunks());
// restart sync when back online
// trigger events when offline/back online
if (typeof(window) !== 'undefined') {
window.addEventListener('online', () => {
if (!this.offline) {
return;
}
this.offline = false;
this.dispatch('online');
this.sendChunks();
});
window.addEventListener('offline', () => {
this.offline = true;
this.dispatch('offline');
});
}
}
/**
* Subscribe to an event
*/
public on(eventName: EventName, fn: (event: CustomEvent) => void) {
this.eventTarget.addEventListener(eventName, fn as EventListener);
}
public abort() {
this.pause();
this.currentXhr?.abort();
}
public pause() {
this.paused = true;
}
public resume() {
if (this.paused) {
this.paused = false;
this.sendChunks();
}
}
/**
* Dispatch an event
*/
private dispatch(eventName: EventName, detail?: any) {
const event: UpchunkEvent = new CustomEvent(eventName, { detail }) as UpchunkEvent;
this.eventTarget.dispatchEvent(event);
}
/**
* Validate options and throw errors if expectations are violated.
*/
private validateOptions() {
if (
!this.endpoint ||
(typeof this.endpoint !== 'function' && typeof this.endpoint !== 'string')
) {
throw new TypeError(
'endpoint must be defined as a string or a function that returns a promise'
);
}
if (!(this.file instanceof File)) {
throw new TypeError('file must be a File object');
}
if (this.headers && typeof this.headers !== 'object') {
throw new TypeError('headers must be null or an object');
}
if (
this.chunkSize &&
(typeof this.chunkSize !== 'number' ||
this.chunkSize <= 0 ||
this.chunkSize % 256 !== 0)
) {
throw new TypeError(
'chunkSize must be a positive number in multiples of 256'
);
}
if (this.maxFileBytes > 0 && this.maxFileBytes < this.file.size) {
throw new Error(
`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`
);
}
if (
this.attempts &&
(typeof this.attempts !== 'number' || this.attempts <= 0)
) {
throw new TypeError('retries must be a positive number');
}
if (
this.delayBeforeAttempt &&
(typeof this.delayBeforeAttempt !== 'number' ||
this.delayBeforeAttempt < 0)
) {
throw new TypeError('delayBeforeAttempt must be a positive number');
}
}
/**
* Endpoint can either be a URL or a function that returns a promise that resolves to a string.
*/
private getEndpoint() {
if (typeof this.endpoint === 'string') {
this.endpointValue = this.endpoint;
return Promise.resolve(this.endpoint);
}
return this.endpoint(this.file).then((value) => {
this.endpointValue = value;
return this.endpointValue;
});
}
/**
* Get portion of the file of x bytes corresponding to chunkSize
*/
private getChunk() {
return new Promise<void> ((resolve) => {
// Since we start with 0-chunkSize for the range, we need to subtract 1.
const length =
this.totalChunks === 1 ? this.file.size : this.chunkByteSize;
const start = length * this.chunkCount;
this.reader.onload = () => {
if (this.reader.result !== null) {
this.chunk = new Blob([this.reader.result], {
type: 'application/octet-stream',
});
}
resolve();
};
this.reader.readAsArrayBuffer(this.file.slice(start, start + length));
});
}
private xhrPromise(options: XhrUrlConfig): Promise<XhrResponse> {
const beforeSend = (xhrObject: XMLHttpRequest) => {
xhrObject.upload.onprogress = (event: ProgressEvent) => {
const percentagePerChunk = 100 / this.totalChunks;
const sizePerChunk = percentagePerChunk * this.file.size;
const successfulPercentage = percentagePerChunk * this.chunkCount;
const currentChunkProgress = event.loaded / (event.total ?? sizePerChunk);
const chunkPercentage = currentChunkProgress * percentagePerChunk;
this.dispatch('progress', Math.min(successfulPercentage + chunkPercentage, 100));
};
};
return new Promise((resolve, reject) => {
this.currentXhr = xhr({ ...options, beforeSend }, (err, resp) => {
this.currentXhr = undefined;
if (err) {
return reject(err);
}
return resolve(resp);
});
});
}
/**
* Send chunk of the file with appropriate headers
*/
protected async sendChunk() {
const rangeStart = this.chunkCount * this.chunkByteSize;
const rangeEnd = rangeStart + this.chunk.size - 1;
const headers = {
...this.headers,
'Content-Type': this.file.type,
'Content-Range': `bytes ${rangeStart}-${rangeEnd}/${this.file.size}`,
};
this.dispatch('attempt', {
chunkNumber: this.chunkCount,
chunkSize: this.chunk.size,
});
return this.xhrPromise({
headers,
url: this.endpointValue,
method: this.method,
body: this.chunk,
});
}
/**
* Called on net failure. If retry counter !== 0, retry after delayBeforeAttempt
*/
private manageRetries() {
if (this.attemptCount < this.attempts) {
setTimeout(() => this.sendChunks(), this.delayBeforeAttempt * 1000);
this.dispatch('attemptFailure', {
message: `An error occured uploading chunk ${this.chunkCount}. ${
this.attempts - this.attemptCount
} retries left.`,
chunkNumber: this.chunkCount,
attemptsLeft: this.attempts - this.attemptCount,
});
return;
}
this.dispatch('error', {
message: `An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,
chunk: this.chunkCount,
attempts: this.attemptCount,
});
}
/**
* Manage the whole upload by calling getChunk & sendChunk
* handle errors & retries and dispatch events
*/
private sendChunks() {
if (this.paused || this.offline || this.success) {
return;
}
this.getChunk()
.then(() => {
this.attemptCount = this.attemptCount + 1;
return this.sendChunk()
})
.then((res) => {
if (SUCCESSFUL_CHUNK_UPLOAD_CODES.includes(res.statusCode)) {
this.dispatch('chunkSuccess', {
chunk: this.chunkCount,
attempts: this.attemptCount,
response: res,
});
this.attemptCount = 0;
this.chunkCount = this.chunkCount + 1;
if (this.chunkCount < this.totalChunks) {
this.sendChunks();
} else {
this.success = true;
this.dispatch('success');
}
const chunkFraction = this.chunkCount / this.totalChunks;
const uploadedBytes = chunkFraction * this.file.size;
const percentProgress = (100 * uploadedBytes) / this.file.size;
this.dispatch('progress', percentProgress);
} else if (TEMPORARY_ERROR_CODES.includes(res.statusCode)) {
if (this.paused || this.offline) {
return;
}
this.manageRetries();
} else {
if (this.paused || this.offline) {
return;
}
this.dispatch('error', {
message: `Server responded with ${res.statusCode}. Stopping upload.`,
chunkNumber: this.chunkCount,
attempts: this.attemptCount,
});
}
})
.catch((err) => {
if (this.paused || this.offline) {
return;
}
// this type of error can happen after network disconnection on CORS setup
this.manageRetries();
});
}
}
export const createUpload = (options: UpChunkOptions) => new UpChunk(options);