/
Upload.ts
273 lines (232 loc) · 8.06 KB
/
Upload.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
import { AbortController, AbortSignal } from "@aws-sdk/abort-controller";
import {
CompletedPart,
CompleteMultipartUploadCommand,
CreateMultipartUploadCommand,
CreateMultipartUploadCommandOutput,
PutObjectCommand,
PutObjectCommandInput,
PutObjectCommandOutput,
PutObjectTaggingCommand,
ServiceOutputTypes,
Tag,
UploadPartCommand,
} from "@aws-sdk/client-s3";
import { EventEmitter } from "events";
import { byteLength } from "./bytelength";
import { getChunk } from "./chunker";
import { BodyDataTypes, Options, Progress, ServiceClients } from "./types";
export interface RawDataPart {
partNumber: number;
data: BodyDataTypes;
lastPart?: boolean;
}
const MIN_PART_SIZE = 1024 * 1024 * 5;
export class Upload extends EventEmitter {
/**
* S3 multipart upload does not allow more than 10000 parts.
*/
private MAX_PARTS = 10000;
// Defaults.
private queueSize = 4;
private partSize = MIN_PART_SIZE;
private leavePartsOnError = false;
private tags: Tag[] = [];
private client: ServiceClients;
private params: PutObjectCommandInput;
// used for reporting progress.
private totalBytes?: number;
private bytesUploadedSoFar: number;
// used in the upload.
private abortController: AbortController;
private concurrentUploaders: Promise<void>[] = [];
private createMultiPartPromise?: Promise<CreateMultipartUploadCommandOutput>;
private uploadedParts: CompletedPart[] = [];
private uploadId?: string;
uploadEvent?: string;
private isMultiPart = true;
private putResponse?: PutObjectCommandOutput;
constructor(options: Options) {
super();
// set defaults from options.
this.queueSize = options.queueSize || this.queueSize;
this.partSize = options.partSize || this.partSize;
this.leavePartsOnError = options.leavePartsOnError || this.leavePartsOnError;
this.tags = options.tags || this.tags;
this.client = options.client;
this.params = options.params;
this.__validateInput();
// set progress defaults
this.totalBytes = byteLength(this.params.Body);
this.bytesUploadedSoFar = 0;
this.abortController = new AbortController();
}
async abort(): Promise<void> {
/**
* Abort stops all new uploads and immediately exists the top level promise on this.done()
* Concurrent threads in flight clean up eventually.
*/
this.abortController.abort();
}
async done(): Promise<ServiceOutputTypes> {
return await Promise.race([this.__doMultipartUpload(), this.__abortTimeout(this.abortController.signal)]);
}
on(event: "httpUploadProgress", listener: (progress: Progress) => void): any {
this.uploadEvent = event;
super.on(event, listener);
}
async __uploadUsingPut(dataPart: RawDataPart) {
this.isMultiPart = false;
const params = { ...this.params, Body: dataPart.data };
const putResult = await this.client.send(new PutObjectCommand(params));
this.putResponse = putResult;
const totalSize = byteLength(dataPart.data);
this.__notifyProgress({
loaded: totalSize,
total: totalSize,
part: 1,
Key: this.params.Key,
Bucket: this.params.Bucket,
});
}
async __createMultipartUpload() {
if (!this.createMultiPartPromise) {
const createCommandParams = { ...this.params, Body: undefined };
this.createMultiPartPromise = this.client.send(new CreateMultipartUploadCommand(createCommandParams));
}
const createMultipartUploadResult = await this.createMultiPartPromise;
this.uploadId = createMultipartUploadResult.UploadId;
}
async __doConcurrentUpload(dataFeeder: AsyncGenerator<RawDataPart, void, undefined>): Promise<void> {
for await (const dataPart of dataFeeder) {
if (this.uploadedParts.length > this.MAX_PARTS) {
throw new Error(
`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.params.Key} and ${this.params.Bucket}.`
);
}
try {
if (this.abortController.signal.aborted) {
return;
}
// Use put instead of multi-part for one chunk uploads.
if (dataPart.partNumber === 1 && dataPart.lastPart) {
return await this.__uploadUsingPut(dataPart);
}
if (!this.uploadId) {
await this.__createMultipartUpload();
if (this.abortController.signal.aborted) {
return;
}
}
const partResult = await this.client.send(
new UploadPartCommand({
...this.params,
UploadId: this.uploadId,
Body: dataPart.data,
PartNumber: dataPart.partNumber,
})
);
if (this.abortController.signal.aborted) {
return;
}
this.uploadedParts.push({
PartNumber: dataPart.partNumber,
ETag: partResult.ETag,
...(partResult.ChecksumCRC32 && { ChecksumCRC32: partResult.ChecksumCRC32 }),
...(partResult.ChecksumCRC32C && { ChecksumCRC32C: partResult.ChecksumCRC32C }),
...(partResult.ChecksumSHA1 && { ChecksumSHA1: partResult.ChecksumSHA1 }),
...(partResult.ChecksumSHA256 && { ChecksumSHA256: partResult.ChecksumSHA256 }),
});
this.bytesUploadedSoFar += byteLength(dataPart.data);
this.__notifyProgress({
loaded: this.bytesUploadedSoFar,
total: this.totalBytes,
part: dataPart.partNumber,
Key: this.params.Key,
Bucket: this.params.Bucket,
});
} catch (e) {
// Failed to create multi-part or put
if (!this.uploadId) {
throw e;
}
// on leavePartsOnError throw an error so users can deal with it themselves,
// otherwise swallow the error.
if (this.leavePartsOnError) {
throw e;
}
}
}
}
async __doMultipartUpload(): Promise<ServiceOutputTypes> {
// Set up data input chunks.
const dataFeeder = getChunk(this.params.Body, this.partSize);
// Create and start concurrent uploads.
for (let index = 0; index < this.queueSize; index++) {
const currentUpload = this.__doConcurrentUpload(dataFeeder);
this.concurrentUploaders.push(currentUpload);
}
// Create and start concurrent uploads.
await Promise.all(this.concurrentUploaders);
if (this.abortController.signal.aborted) {
throw Object.assign(new Error("Upload aborted."), { name: "AbortError" });
}
let result;
if (this.isMultiPart) {
this.uploadedParts.sort((a, b) => a.PartNumber! - b.PartNumber!);
const uploadCompleteParams = {
...this.params,
Body: undefined,
UploadId: this.uploadId,
MultipartUpload: {
Parts: this.uploadedParts,
},
};
result = await this.client.send(new CompleteMultipartUploadCommand(uploadCompleteParams));
} else {
result = this.putResponse!;
}
// Add tags to the object after it's completed the upload.
if (this.tags.length) {
await this.client.send(
new PutObjectTaggingCommand({
...this.params,
Tagging: {
TagSet: this.tags,
},
})
);
}
return result;
}
__notifyProgress(progress: Progress) {
if (this.uploadEvent) {
this.emit(this.uploadEvent, progress);
}
}
async __abortTimeout(abortSignal: AbortSignal): Promise<ServiceOutputTypes> {
return new Promise((resolve, reject) => {
abortSignal.onabort = () => {
const abortError = new Error("Upload aborted.");
abortError.name = "AbortError";
reject(abortError);
};
});
}
__validateInput() {
if (!this.params) {
throw new Error(`InputError: Upload requires params to be passed to upload.`);
}
if (!this.client) {
throw new Error(`InputError: Upload requires a AWS client to do uploads with.`);
}
if (this.partSize < MIN_PART_SIZE) {
throw new Error(
`EntityTooSmall: Your proposed upload partsize [${this.partSize}] is smaller than the minimum allowed size [${MIN_PART_SIZE}] (5MB)`
);
}
if (this.queueSize < 1) {
throw new Error(`Queue size: Must have at least one uploading queue.`);
}
}
}