1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
16 | if (k2 === undefined) k2 = k;
|
17 | var desc = Object.getOwnPropertyDescriptor(m, k);
|
18 | if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
19 | desc = { enumerable: true, get: function() { return m[k]; } };
|
20 | }
|
21 | Object.defineProperty(o, k2, desc);
|
22 | }) : (function(o, m, k, k2) {
|
23 | if (k2 === undefined) k2 = k;
|
24 | o[k2] = m[k];
|
25 | }));
|
26 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
27 | Object.defineProperty(o, "default", { enumerable: true, value: v });
|
28 | }) : function(o, v) {
|
29 | o["default"] = v;
|
30 | });
|
31 | var __importStar = (this && this.__importStar) || function (mod) {
|
32 | if (mod && mod.__esModule) return mod;
|
33 | var result = {};
|
34 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
35 | __setModuleDefault(result, mod);
|
36 | return result;
|
37 | };
|
38 | var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
39 | if (kind === "m") throw new TypeError("Private method is not writable");
|
40 | if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
41 | if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
42 | return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
43 | };
|
44 | var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
45 | if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
46 | if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
47 | return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
48 | };
|
49 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
50 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
51 | };
|
52 | var _Upload_instances, _Upload_gcclGcsCmd, _Upload_resetLocalBuffersCache, _Upload_addLocalBufferCache;
|
53 | Object.defineProperty(exports, "__esModule", { value: true });
|
54 | exports.Upload = exports.PROTOCOL_REGEX = void 0;
|
55 | exports.upload = upload;
|
56 | exports.createURI = createURI;
|
57 | exports.checkUploadStatus = checkUploadStatus;
|
58 | const abort_controller_1 = __importDefault(require("abort-controller"));
|
59 | const crypto_1 = require("crypto");
|
60 | const gaxios = __importStar(require("gaxios"));
|
61 | const google_auth_library_1 = require("google-auth-library");
|
62 | const stream_1 = require("stream");
|
63 | const async_retry_1 = __importDefault(require("async-retry"));
|
64 | const uuid = __importStar(require("uuid"));
|
65 | const util_js_1 = require("./util.js");
|
66 | const util_js_2 = require("./nodejs-common/util.js");
|
67 |
|
68 |
|
69 | const package_json_helper_cjs_1 = require("./package-json-helper.cjs");
|
70 | const NOT_FOUND_STATUS_CODE = 404;
|
71 | const RESUMABLE_INCOMPLETE_STATUS_CODE = 308;
|
72 | const packageJson = (0, package_json_helper_cjs_1.getPackageJSON)();
|
73 | exports.PROTOCOL_REGEX = /^(\w*):\/\//;
|
74 | class Upload extends stream_1.Writable {
|
75 | constructor(cfg) {
|
76 | var _a;
|
77 | super(cfg);
|
78 | _Upload_instances.add(this);
|
79 | this.numBytesWritten = 0;
|
80 | this.numRetries = 0;
|
81 | this.currentInvocationId = {
|
82 | checkUploadStatus: uuid.v4(),
|
83 | chunk: uuid.v4(),
|
84 | uri: uuid.v4(),
|
85 | };
|
86 | |
87 |
|
88 |
|
89 | this.writeBuffers = [];
|
90 | this.numChunksReadInRequest = 0;
|
91 | |
92 |
|
93 |
|
94 |
|
95 |
|
96 | this.localWriteCache = [];
|
97 | this.localWriteCacheByteLength = 0;
|
98 | this.upstreamEnded = false;
|
99 | _Upload_gcclGcsCmd.set(this, void 0);
|
100 | cfg = cfg || {};
|
101 | if (!cfg.bucket || !cfg.file) {
|
102 | throw new Error('A bucket and file name are required');
|
103 | }
|
104 | if (cfg.offset && !cfg.uri) {
|
105 | throw new RangeError('Cannot provide an `offset` without providing a `uri`');
|
106 | }
|
107 | if (cfg.isPartialUpload && !cfg.chunkSize) {
|
108 | throw new RangeError('Cannot set `isPartialUpload` without providing a `chunkSize`');
|
109 | }
|
110 | cfg.authConfig = cfg.authConfig || {};
|
111 | cfg.authConfig.scopes = [
|
112 | 'https://www.googleapis.com/auth/devstorage.full_control',
|
113 | ];
|
114 | this.authClient = cfg.authClient || new google_auth_library_1.GoogleAuth(cfg.authConfig);
|
115 | const universe = cfg.universeDomain || google_auth_library_1.DEFAULT_UNIVERSE;
|
116 | this.apiEndpoint = `https://storage.${universe}`;
|
117 | if (cfg.apiEndpoint && cfg.apiEndpoint !== this.apiEndpoint) {
|
118 | this.apiEndpoint = this.sanitizeEndpoint(cfg.apiEndpoint);
|
119 | const hostname = new URL(this.apiEndpoint).hostname;
|
120 |
|
121 | const isDomain = hostname === universe;
|
122 | const isDefaultUniverseDomain = hostname === google_auth_library_1.DEFAULT_UNIVERSE;
|
123 |
|
124 |
|
125 | const isSubDomainOfUniverse = hostname.slice(-(universe.length + 1)) === `.${universe}`;
|
126 | const isSubDomainOfDefaultUniverse = hostname.slice(-(google_auth_library_1.DEFAULT_UNIVERSE.length + 1)) ===
|
127 | `.${google_auth_library_1.DEFAULT_UNIVERSE}`;
|
128 | if (!isDomain &&
|
129 | !isDefaultUniverseDomain &&
|
130 | !isSubDomainOfUniverse &&
|
131 | !isSubDomainOfDefaultUniverse) {
|
132 |
|
133 |
|
134 | this.authClient = gaxios;
|
135 | }
|
136 | }
|
137 | this.baseURI = `${this.apiEndpoint}/upload/storage/v1/b`;
|
138 | this.bucket = cfg.bucket;
|
139 | const cacheKeyElements = [cfg.bucket, cfg.file];
|
140 | if (typeof cfg.generation === 'number') {
|
141 | cacheKeyElements.push(`${cfg.generation}`);
|
142 | }
|
143 | this.cacheKey = cacheKeyElements.join('/');
|
144 | this.customRequestOptions = cfg.customRequestOptions || {};
|
145 | this.file = cfg.file;
|
146 | this.generation = cfg.generation;
|
147 | this.kmsKeyName = cfg.kmsKeyName;
|
148 | this.metadata = cfg.metadata || {};
|
149 | this.offset = cfg.offset;
|
150 | this.origin = cfg.origin;
|
151 | this.params = cfg.params || {};
|
152 | this.userProject = cfg.userProject;
|
153 | this.chunkSize = cfg.chunkSize;
|
154 | this.retryOptions = cfg.retryOptions;
|
155 | this.isPartialUpload = (_a = cfg.isPartialUpload) !== null && _a !== void 0 ? _a : false;
|
156 | if (cfg.key) {
|
157 | const base64Key = Buffer.from(cfg.key).toString('base64');
|
158 | this.encryption = {
|
159 | key: base64Key,
|
160 | hash: (0, crypto_1.createHash)('sha256').update(cfg.key).digest('base64'),
|
161 | };
|
162 | }
|
163 | this.predefinedAcl = cfg.predefinedAcl;
|
164 | if (cfg.private)
|
165 | this.predefinedAcl = 'private';
|
166 | if (cfg.public)
|
167 | this.predefinedAcl = 'publicRead';
|
168 | const autoRetry = cfg.retryOptions.autoRetry;
|
169 | this.uriProvidedManually = !!cfg.uri;
|
170 | this.uri = cfg.uri;
|
171 | if (this.offset) {
|
172 |
|
173 | this.numBytesWritten = this.offset;
|
174 | }
|
175 | this.numRetries = 0;
|
176 | if (!autoRetry) {
|
177 | cfg.retryOptions.maxRetries = 0;
|
178 | }
|
179 | this.timeOfFirstRequest = Date.now();
|
180 | const contentLength = cfg.metadata
|
181 | ? Number(cfg.metadata.contentLength)
|
182 | : NaN;
|
183 | this.contentLength = isNaN(contentLength) ? '*' : contentLength;
|
184 | __classPrivateFieldSet(this, _Upload_gcclGcsCmd, cfg[util_js_2.GCCL_GCS_CMD_KEY], "f");
|
185 | this.once('writing', () => {
|
186 | if (this.uri) {
|
187 | this.continueUploading();
|
188 | }
|
189 | else {
|
190 | this.createURI(err => {
|
191 | if (err) {
|
192 | return this.destroy(err);
|
193 | }
|
194 | this.startUploading();
|
195 | return;
|
196 | });
|
197 | }
|
198 | });
|
199 | }
|
200 | |
201 |
|
202 |
|
203 |
|
204 |
|
205 | _final(fireFinishEvent = () => { }) {
|
206 | this.upstreamEnded = true;
|
207 | this.once('uploadFinished', fireFinishEvent);
|
208 | process.nextTick(() => {
|
209 | this.emit('upstreamFinished');
|
210 |
|
211 | this.emit('writing');
|
212 | });
|
213 | }
|
214 | |
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 | _write(chunk, encoding, readCallback = () => { }) {
|
222 |
|
223 | this.emit('writing');
|
224 | this.writeBuffers.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
|
225 | this.once('readFromChunkBuffer', readCallback);
|
226 | process.nextTick(() => this.emit('wroteToChunkBuffer'));
|
227 | }
|
228 | |
229 |
|
230 |
|
231 |
|
232 |
|
233 | prependLocalBufferToUpstream(keepLastBytes) {
|
234 |
|
235 |
|
236 |
|
237 | let initialBuffers = [];
|
238 | if (keepLastBytes) {
|
239 |
|
240 | let bytesKept = 0;
|
241 | while (keepLastBytes > bytesKept) {
|
242 |
|
243 |
|
244 | let buf = this.localWriteCache.pop();
|
245 | if (!buf)
|
246 | break;
|
247 | bytesKept += buf.byteLength;
|
248 | if (bytesKept > keepLastBytes) {
|
249 |
|
250 |
|
251 | const diff = bytesKept - keepLastBytes;
|
252 | buf = buf.subarray(diff);
|
253 | bytesKept -= diff;
|
254 | }
|
255 | initialBuffers.unshift(buf);
|
256 | }
|
257 | }
|
258 | else {
|
259 |
|
260 | initialBuffers = this.localWriteCache;
|
261 | }
|
262 |
|
263 | const append = this.writeBuffers;
|
264 | this.writeBuffers = initialBuffers;
|
265 | for (const buf of append) {
|
266 | this.writeBuffers.push(buf);
|
267 | }
|
268 |
|
269 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this);
|
270 | }
|
271 | |
272 |
|
273 |
|
274 |
|
275 |
|
276 | *pullFromChunkBuffer(limit) {
|
277 | while (limit) {
|
278 | const buf = this.writeBuffers.shift();
|
279 | if (!buf)
|
280 | break;
|
281 | let bufToYield = buf;
|
282 | if (buf.byteLength > limit) {
|
283 | bufToYield = buf.subarray(0, limit);
|
284 | this.writeBuffers.unshift(buf.subarray(limit));
|
285 | limit = 0;
|
286 | }
|
287 | else {
|
288 | limit -= buf.byteLength;
|
289 | }
|
290 | yield bufToYield;
|
291 |
|
292 |
|
293 |
|
294 | this.emit('readFromChunkBuffer');
|
295 | }
|
296 | }
|
297 | |
298 |
|
299 |
|
300 |
|
301 |
|
302 | async waitForNextChunk() {
|
303 | const willBeMoreChunks = await new Promise(resolve => {
|
304 |
|
305 | if (this.writeBuffers.length) {
|
306 | return resolve(true);
|
307 | }
|
308 |
|
309 | if (this.upstreamEnded) {
|
310 | return resolve(false);
|
311 | }
|
312 |
|
313 |
|
314 | const wroteToChunkBufferCallback = () => {
|
315 | removeListeners();
|
316 | return resolve(true);
|
317 | };
|
318 | const upstreamFinishedCallback = () => {
|
319 | removeListeners();
|
320 |
|
321 | if (this.writeBuffers.length)
|
322 | return resolve(true);
|
323 | return resolve(false);
|
324 | };
|
325 |
|
326 | const removeListeners = () => {
|
327 | this.removeListener('wroteToChunkBuffer', wroteToChunkBufferCallback);
|
328 | this.removeListener('upstreamFinished', upstreamFinishedCallback);
|
329 | };
|
330 |
|
331 | this.once('wroteToChunkBuffer', wroteToChunkBufferCallback);
|
332 |
|
333 | this.once('upstreamFinished', upstreamFinishedCallback);
|
334 | });
|
335 | return willBeMoreChunks;
|
336 | }
|
337 | |
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 | async *upstreamIterator(limit = Infinity) {
|
344 |
|
345 | while (limit && (await this.waitForNextChunk())) {
|
346 |
|
347 | for (const chunk of this.pullFromChunkBuffer(limit)) {
|
348 | limit -= chunk.byteLength;
|
349 | yield chunk;
|
350 | }
|
351 | }
|
352 | }
|
353 | createURI(callback) {
|
354 | if (!callback) {
|
355 | return this.createURIAsync();
|
356 | }
|
357 | this.createURIAsync().then(r => callback(null, r), callback);
|
358 | }
|
359 | async createURIAsync() {
|
360 | const metadata = { ...this.metadata };
|
361 | const headers = {};
|
362 |
|
363 |
|
364 | if (metadata.contentLength) {
|
365 | headers['X-Upload-Content-Length'] = metadata.contentLength.toString();
|
366 | delete metadata.contentLength;
|
367 | }
|
368 | if (metadata.contentType) {
|
369 | headers['X-Upload-Content-Type'] = metadata.contentType;
|
370 | delete metadata.contentType;
|
371 | }
|
372 | let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.uri}`;
|
373 | if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) {
|
374 | googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`;
|
375 | }
|
376 |
|
377 | const reqOpts = {
|
378 | method: 'POST',
|
379 | url: [this.baseURI, this.bucket, 'o'].join('/'),
|
380 | params: Object.assign({
|
381 | name: this.file,
|
382 | uploadType: 'resumable',
|
383 | }, this.params),
|
384 | data: metadata,
|
385 | headers: {
|
386 | 'User-Agent': (0, util_js_1.getUserAgentString)(),
|
387 | 'x-goog-api-client': googAPIClient,
|
388 | ...headers,
|
389 | },
|
390 | };
|
391 | if (metadata.contentLength) {
|
392 | reqOpts.headers['X-Upload-Content-Length'] =
|
393 | metadata.contentLength.toString();
|
394 | }
|
395 | if (metadata.contentType) {
|
396 | reqOpts.headers['X-Upload-Content-Type'] = metadata.contentType;
|
397 | }
|
398 | if (typeof this.generation !== 'undefined') {
|
399 | reqOpts.params.ifGenerationMatch = this.generation;
|
400 | }
|
401 | if (this.kmsKeyName) {
|
402 | reqOpts.params.kmsKeyName = this.kmsKeyName;
|
403 | }
|
404 | if (this.predefinedAcl) {
|
405 | reqOpts.params.predefinedAcl = this.predefinedAcl;
|
406 | }
|
407 | if (this.origin) {
|
408 | reqOpts.headers.Origin = this.origin;
|
409 | }
|
410 | const uri = await (0, async_retry_1.default)(async (bail) => {
|
411 | var _a, _b, _c;
|
412 | try {
|
413 | const res = await this.makeRequest(reqOpts);
|
414 |
|
415 | this.currentInvocationId.uri = uuid.v4();
|
416 | return res.headers.location;
|
417 | }
|
418 | catch (err) {
|
419 | const e = err;
|
420 | const apiError = {
|
421 | code: (_a = e.response) === null || _a === void 0 ? void 0 : _a.status,
|
422 | name: (_b = e.response) === null || _b === void 0 ? void 0 : _b.statusText,
|
423 | message: (_c = e.response) === null || _c === void 0 ? void 0 : _c.statusText,
|
424 | errors: [
|
425 | {
|
426 | reason: e.code,
|
427 | },
|
428 | ],
|
429 | };
|
430 | if (this.retryOptions.maxRetries > 0 &&
|
431 | this.retryOptions.retryableErrorFn(apiError)) {
|
432 | throw e;
|
433 | }
|
434 | else {
|
435 | return bail(e);
|
436 | }
|
437 | }
|
438 | }, {
|
439 | retries: this.retryOptions.maxRetries,
|
440 | factor: this.retryOptions.retryDelayMultiplier,
|
441 | maxTimeout: this.retryOptions.maxRetryDelay * 1000,
|
442 | maxRetryTime: this.retryOptions.totalTimeout * 1000,
|
443 | });
|
444 | this.uri = uri;
|
445 | this.offset = 0;
|
446 |
|
447 | this.emit('uri', uri);
|
448 | return uri;
|
449 | }
|
450 | async continueUploading() {
|
451 | var _a;
|
452 | (_a = this.offset) !== null && _a !== void 0 ? _a : (await this.getAndSetOffset());
|
453 | return this.startUploading();
|
454 | }
|
455 | async startUploading() {
|
456 | const multiChunkMode = !!this.chunkSize;
|
457 | let responseReceived = false;
|
458 | this.numChunksReadInRequest = 0;
|
459 | if (!this.offset) {
|
460 | this.offset = 0;
|
461 | }
|
462 |
|
463 | if (this.offset < this.numBytesWritten) {
|
464 | const delta = this.numBytesWritten - this.offset;
|
465 | const message = `The offset is lower than the number of bytes written. The server has ${this.offset} bytes and while ${this.numBytesWritten} bytes has been uploaded - thus ${delta} bytes are missing. Stopping as this could result in data loss. Initiate a new upload to continue.`;
|
466 | this.emit('error', new RangeError(message));
|
467 | return;
|
468 | }
|
469 |
|
470 | if (this.numBytesWritten < this.offset) {
|
471 |
|
472 |
|
473 | const fastForwardBytes = this.offset - this.numBytesWritten;
|
474 | for await (const _chunk of this.upstreamIterator(fastForwardBytes)) {
|
475 | _chunk;
|
476 | }
|
477 | this.numBytesWritten = this.offset;
|
478 | }
|
479 | let expectedUploadSize = undefined;
|
480 |
|
481 | if (typeof this.contentLength === 'number') {
|
482 | expectedUploadSize = this.contentLength - this.numBytesWritten;
|
483 | }
|
484 |
|
485 |
|
486 |
|
487 | if (this.chunkSize) {
|
488 | expectedUploadSize = expectedUploadSize
|
489 | ? Math.min(this.chunkSize, expectedUploadSize)
|
490 | : this.chunkSize;
|
491 | }
|
492 |
|
493 | const upstreamQueue = this.upstreamIterator(expectedUploadSize);
|
494 |
|
495 |
|
496 | const requestStream = new stream_1.Readable({
|
497 | read: async () => {
|
498 |
|
499 | if (responseReceived)
|
500 | requestStream.push(null);
|
501 | const result = await upstreamQueue.next();
|
502 | if (result.value) {
|
503 | this.numChunksReadInRequest++;
|
504 | if (multiChunkMode) {
|
505 |
|
506 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value);
|
507 | }
|
508 | else {
|
509 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this);
|
510 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value);
|
511 | }
|
512 | this.numBytesWritten += result.value.byteLength;
|
513 | this.emit('progress', {
|
514 | bytesWritten: this.numBytesWritten,
|
515 | contentLength: this.contentLength,
|
516 | });
|
517 | requestStream.push(result.value);
|
518 | }
|
519 | if (result.done) {
|
520 | requestStream.push(null);
|
521 | }
|
522 | },
|
523 | });
|
524 | let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.chunk}`;
|
525 | if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) {
|
526 | googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`;
|
527 | }
|
528 | const headers = {
|
529 | 'User-Agent': (0, util_js_1.getUserAgentString)(),
|
530 | 'x-goog-api-client': googAPIClient,
|
531 | };
|
532 |
|
533 | if (multiChunkMode) {
|
534 |
|
535 |
|
536 | for await (const chunk of this.upstreamIterator(expectedUploadSize)) {
|
537 |
|
538 |
|
539 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, chunk);
|
540 | }
|
541 |
|
542 | const bytesToUpload = this.localWriteCacheByteLength;
|
543 |
|
544 |
|
545 | const isLastChunkOfUpload = !(await this.waitForNextChunk());
|
546 |
|
547 | this.prependLocalBufferToUpstream();
|
548 | let totalObjectSize = this.contentLength;
|
549 | if (typeof this.contentLength !== 'number' &&
|
550 | isLastChunkOfUpload &&
|
551 | !this.isPartialUpload) {
|
552 |
|
553 | totalObjectSize = bytesToUpload + this.numBytesWritten;
|
554 | }
|
555 |
|
556 | const endingByte = bytesToUpload + this.numBytesWritten - 1;
|
557 |
|
558 |
|
559 | headers['Content-Length'] = bytesToUpload;
|
560 | headers['Content-Range'] =
|
561 | `bytes ${this.offset}-${endingByte}/${totalObjectSize}`;
|
562 | }
|
563 | else {
|
564 | headers['Content-Range'] = `bytes ${this.offset}-*/${this.contentLength}`;
|
565 | }
|
566 | const reqOpts = {
|
567 | method: 'PUT',
|
568 | url: this.uri,
|
569 | headers,
|
570 | body: requestStream,
|
571 | };
|
572 | try {
|
573 | const resp = await this.makeRequestStream(reqOpts);
|
574 | if (resp) {
|
575 | responseReceived = true;
|
576 | await this.responseHandler(resp);
|
577 | }
|
578 | }
|
579 | catch (e) {
|
580 | const err = e;
|
581 | if (this.retryOptions.retryableErrorFn(err)) {
|
582 | this.attemptDelayedRetry({
|
583 | status: NaN,
|
584 | data: err,
|
585 | });
|
586 | return;
|
587 | }
|
588 | this.destroy(err);
|
589 | }
|
590 | }
|
591 |
|
592 |
|
593 | async responseHandler(resp) {
|
594 | if (resp.data.error) {
|
595 | this.destroy(resp.data.error);
|
596 | return;
|
597 | }
|
598 |
|
599 | this.currentInvocationId.chunk = uuid.v4();
|
600 | const moreDataToUpload = await this.waitForNextChunk();
|
601 | const shouldContinueWithNextMultiChunkRequest = this.chunkSize &&
|
602 | resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE &&
|
603 | resp.headers.range &&
|
604 | moreDataToUpload;
|
605 | |
606 |
|
607 |
|
608 |
|
609 | const shouldContinueUploadInAnotherRequest = this.isPartialUpload &&
|
610 | resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE &&
|
611 | !moreDataToUpload;
|
612 | if (shouldContinueWithNextMultiChunkRequest) {
|
613 |
|
614 |
|
615 |
|
616 | const range = resp.headers.range;
|
617 | this.offset = Number(range.split('-')[1]) + 1;
|
618 |
|
619 |
|
620 | const missingBytes = this.numBytesWritten - this.offset;
|
621 | if (missingBytes) {
|
622 |
|
623 |
|
624 |
|
625 | this.prependLocalBufferToUpstream(missingBytes);
|
626 | this.numBytesWritten -= missingBytes;
|
627 | }
|
628 | else {
|
629 |
|
630 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this);
|
631 | }
|
632 |
|
633 | this.continueUploading();
|
634 | }
|
635 | else if (!this.isSuccessfulResponse(resp.status) &&
|
636 | !shouldContinueUploadInAnotherRequest) {
|
637 | const err = new Error('Upload failed');
|
638 | err.code = resp.status;
|
639 | err.name = 'Upload failed';
|
640 | if (resp === null || resp === void 0 ? void 0 : resp.data) {
|
641 | err.errors = [resp === null || resp === void 0 ? void 0 : resp.data];
|
642 | }
|
643 | this.destroy(err);
|
644 | }
|
645 | else {
|
646 |
|
647 | __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this);
|
648 | if (resp && resp.data) {
|
649 | resp.data.size = Number(resp.data.size);
|
650 | }
|
651 | this.emit('metadata', resp.data);
|
652 |
|
653 |
|
654 | this.emit('uploadFinished');
|
655 | }
|
656 | }
|
657 | |
658 |
|
659 |
|
660 |
|
661 |
|
662 |
|
663 | async checkUploadStatus(config = {}) {
|
664 | let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.checkUploadStatus}`;
|
665 | if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) {
|
666 | googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`;
|
667 | }
|
668 | const opts = {
|
669 | method: 'PUT',
|
670 | url: this.uri,
|
671 | headers: {
|
672 | 'Content-Length': 0,
|
673 | 'Content-Range': 'bytes */*',
|
674 | 'User-Agent': (0, util_js_1.getUserAgentString)(),
|
675 | 'x-goog-api-client': googAPIClient,
|
676 | },
|
677 | };
|
678 | try {
|
679 | const resp = await this.makeRequest(opts);
|
680 |
|
681 | this.currentInvocationId.checkUploadStatus = uuid.v4();
|
682 | return resp;
|
683 | }
|
684 | catch (e) {
|
685 | if (config.retry === false ||
|
686 | !(e instanceof Error) ||
|
687 | !this.retryOptions.retryableErrorFn(e)) {
|
688 | throw e;
|
689 | }
|
690 | const retryDelay = this.getRetryDelay();
|
691 | if (retryDelay <= 0) {
|
692 | throw e;
|
693 | }
|
694 | await new Promise(res => setTimeout(res, retryDelay));
|
695 | return this.checkUploadStatus(config);
|
696 | }
|
697 | }
|
698 | async getAndSetOffset() {
|
699 | try {
|
700 |
|
701 | const resp = await this.checkUploadStatus({ retry: false });
|
702 | if (resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE) {
|
703 | if (typeof resp.headers.range === 'string') {
|
704 | this.offset = Number(resp.headers.range.split('-')[1]) + 1;
|
705 | return;
|
706 | }
|
707 | }
|
708 | this.offset = 0;
|
709 | }
|
710 | catch (e) {
|
711 | const err = e;
|
712 | if (this.retryOptions.retryableErrorFn(err)) {
|
713 | this.attemptDelayedRetry({
|
714 | status: NaN,
|
715 | data: err,
|
716 | });
|
717 | return;
|
718 | }
|
719 | this.destroy(err);
|
720 | }
|
721 | }
|
722 | async makeRequest(reqOpts) {
|
723 | if (this.encryption) {
|
724 | reqOpts.headers = reqOpts.headers || {};
|
725 | reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256';
|
726 | reqOpts.headers['x-goog-encryption-key'] = this.encryption.key.toString();
|
727 | reqOpts.headers['x-goog-encryption-key-sha256'] =
|
728 | this.encryption.hash.toString();
|
729 | }
|
730 | if (this.userProject) {
|
731 | reqOpts.params = reqOpts.params || {};
|
732 | reqOpts.params.userProject = this.userProject;
|
733 | }
|
734 |
|
735 | reqOpts.validateStatus = (status) => {
|
736 | return (this.isSuccessfulResponse(status) ||
|
737 | status === RESUMABLE_INCOMPLETE_STATUS_CODE);
|
738 | };
|
739 | const combinedReqOpts = {
|
740 | ...this.customRequestOptions,
|
741 | ...reqOpts,
|
742 | headers: {
|
743 | ...this.customRequestOptions.headers,
|
744 | ...reqOpts.headers,
|
745 | },
|
746 | };
|
747 | const res = await this.authClient.request(combinedReqOpts);
|
748 | if (res.data && res.data.error) {
|
749 | throw res.data.error;
|
750 | }
|
751 | return res;
|
752 | }
|
753 | async makeRequestStream(reqOpts) {
|
754 | const controller = new abort_controller_1.default();
|
755 | const errorCallback = () => controller.abort();
|
756 | this.once('error', errorCallback);
|
757 | if (this.userProject) {
|
758 | reqOpts.params = reqOpts.params || {};
|
759 | reqOpts.params.userProject = this.userProject;
|
760 | }
|
761 | reqOpts.signal = controller.signal;
|
762 | reqOpts.validateStatus = () => true;
|
763 | const combinedReqOpts = {
|
764 | ...this.customRequestOptions,
|
765 | ...reqOpts,
|
766 | headers: {
|
767 | ...this.customRequestOptions.headers,
|
768 | ...reqOpts.headers,
|
769 | },
|
770 | };
|
771 | const res = await this.authClient.request(combinedReqOpts);
|
772 | const successfulRequest = this.onResponse(res);
|
773 | this.removeListener('error', errorCallback);
|
774 | return successfulRequest ? res : null;
|
775 | }
|
776 | |
777 |
|
778 |
|
779 | onResponse(resp) {
|
780 | if (resp.status !== 200 &&
|
781 | this.retryOptions.retryableErrorFn({
|
782 | code: resp.status,
|
783 | message: resp.statusText,
|
784 | name: resp.statusText,
|
785 | })) {
|
786 | this.attemptDelayedRetry(resp);
|
787 | return false;
|
788 | }
|
789 | this.emit('response', resp);
|
790 | return true;
|
791 | }
|
792 | |
793 |
|
794 |
|
795 | attemptDelayedRetry(resp) {
|
796 | if (this.numRetries < this.retryOptions.maxRetries) {
|
797 | if (resp.status === NOT_FOUND_STATUS_CODE &&
|
798 | this.numChunksReadInRequest === 0) {
|
799 | this.startUploading();
|
800 | }
|
801 | else {
|
802 | const retryDelay = this.getRetryDelay();
|
803 | if (retryDelay <= 0) {
|
804 | this.destroy(new Error(`Retry total time limit exceeded - ${JSON.stringify(resp.data)}`));
|
805 | return;
|
806 | }
|
807 |
|
808 | this.numBytesWritten -= this.localWriteCacheByteLength;
|
809 | this.prependLocalBufferToUpstream();
|
810 |
|
811 |
|
812 |
|
813 |
|
814 |
|
815 |
|
816 | this.offset = undefined;
|
817 | setTimeout(this.continueUploading.bind(this), retryDelay);
|
818 | }
|
819 | this.numRetries++;
|
820 | }
|
821 | else {
|
822 | this.destroy(new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`));
|
823 | }
|
824 | }
|
825 | |
826 |
|
827 |
|
828 |
|
829 |
|
830 |
|
831 | getRetryDelay() {
|
832 | const randomMs = Math.round(Math.random() * 1000);
|
833 | const waitTime = Math.pow(this.retryOptions.retryDelayMultiplier, this.numRetries) *
|
834 | 1000 +
|
835 | randomMs;
|
836 | const maxAllowableDelayMs = this.retryOptions.totalTimeout * 1000 -
|
837 | (Date.now() - this.timeOfFirstRequest);
|
838 | const maxRetryDelayMs = this.retryOptions.maxRetryDelay * 1000;
|
839 | return Math.min(waitTime, maxRetryDelayMs, maxAllowableDelayMs);
|
840 | }
|
841 | |
842 |
|
843 |
|
844 | sanitizeEndpoint(url) {
|
845 | if (!exports.PROTOCOL_REGEX.test(url)) {
|
846 | url = `https://${url}`;
|
847 | }
|
848 | return url.replace(/\/+$/, '');
|
849 | }
|
850 | |
851 |
|
852 |
|
853 |
|
854 |
|
855 |
|
856 | isSuccessfulResponse(status) {
|
857 | return status >= 200 && status < 300;
|
858 | }
|
859 | }
|
860 | exports.Upload = Upload;
|
861 | _Upload_gcclGcsCmd = new WeakMap(), _Upload_instances = new WeakSet(), _Upload_resetLocalBuffersCache = function _Upload_resetLocalBuffersCache() {
|
862 | this.localWriteCache = [];
|
863 | this.localWriteCacheByteLength = 0;
|
864 | }, _Upload_addLocalBufferCache = function _Upload_addLocalBufferCache(buf) {
|
865 | this.localWriteCache.push(buf);
|
866 | this.localWriteCacheByteLength += buf.byteLength;
|
867 | };
|
868 | function upload(cfg) {
|
869 | return new Upload(cfg);
|
870 | }
|
871 | function createURI(cfg, callback) {
|
872 | const up = new Upload(cfg);
|
873 | if (!callback) {
|
874 | return up.createURI();
|
875 | }
|
876 | up.createURI().then(r => callback(null, r), callback);
|
877 | }
|
878 |
|
879 |
|
880 |
|
881 |
|
882 |
|
883 |
|
884 | function checkUploadStatus(cfg) {
|
885 | const up = new Upload(cfg);
|
886 | return up.checkUploadStatus();
|
887 | }
|