This repository was archived by the owner on Mar 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathresumable-upload.ts
More file actions
1488 lines (1270 loc) · 44 KB
/
Copy pathresumable-upload.ts
File metadata and controls
1488 lines (1270 loc) · 44 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AbortController from 'abort-controller';
import {createHash} from 'crypto';
import {
GaxiosOptions,
GaxiosPromise,
GaxiosResponse,
GaxiosError,
} from 'gaxios';
import * as gaxios from 'gaxios';
import {
DEFAULT_UNIVERSE,
GoogleAuth,
GoogleAuthOptions,
} from 'google-auth-library';
import {Readable, Writable, WritableOptions} from 'stream';
import AsyncRetry from 'async-retry';
import {RetryOptions, PreconditionOptions} from './storage.js';
import * as uuid from 'uuid';
import {
getRuntimeTrackingString,
getModuleFormat,
getUserAgentString,
} from './util.js';
import {GCCL_GCS_CMD_KEY} from './nodejs-common/util.js';
import {FileExceptionMessages, FileMetadata, RequestError} from './file.js';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import {getPackageJSON} from './package-json-helper.cjs';
import {HashStreamValidator} from './hash-stream-validator.js';
const NOT_FOUND_STATUS_CODE = 404;
const RESUMABLE_INCOMPLETE_STATUS_CODE = 308;
const packageJson = getPackageJSON();
export const PROTOCOL_REGEX = /^(\w*):\/\//;
export interface ErrorWithCode extends Error {
code: number;
status?: number | string;
}
export type CreateUriCallback = (err: Error | null, uri?: string) => void;
export interface Encryption {
key: {};
hash: {};
}
export type PredefinedAcl =
| 'authenticatedRead'
| 'bucketOwnerFullControl'
| 'bucketOwnerRead'
| 'private'
| 'projectPrivate'
| 'publicRead';
export interface QueryParameters extends PreconditionOptions {
contentEncoding?: string;
kmsKeyName?: string;
predefinedAcl?: PredefinedAcl;
projection?: 'full' | 'noAcl';
userProject?: string;
}
export interface UploadConfig extends Pick<WritableOptions, 'highWaterMark'> {
/**
* The API endpoint used for the request.
* Defaults to `storage.googleapis.com`.
*
* **Warning**:
* If this value does not match the current GCP universe an emulator context
* will be assumed and authentication will be bypassed.
*/
apiEndpoint?: string;
/**
* The name of the destination bucket.
*/
bucket: string;
/**
* The name of the destination file.
*/
file: string;
/**
* The GoogleAuthOptions passed to google-auth-library
*/
authConfig?: GoogleAuthOptions;
/**
* If you want to re-use an auth client from google-auto-auth, pass an
* instance here.
* Defaults to GoogleAuth and gets automatically overridden if an
* emulator context is detected.
*/
authClient?: {
request: <T>(
opts: GaxiosOptions
) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
};
/**
* Create a separate request per chunk.
*
* This value is in bytes and should be a multiple of 256 KiB (2^18).
* We recommend using at least 8 MiB for the chunk size.
*
* @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
*/
chunkSize?: number;
/**
* For each API request we send, you may specify custom request options that
* we'll add onto the request. The request options follow the gaxios API:
* https://github.com/googleapis/gaxios#request-options.
*/
customRequestOptions?: GaxiosOptions;
/**
* This will cause the upload to fail if the current generation of the remote
* object does not match the one provided here.
*/
generation?: number;
/**
* Set to `true` if the upload is only a subset of the overall object to upload.
* This can be used when planning to continue the upload an object in another
* session.
*
* **Must be used with {@link UploadConfig.chunkSize} != `0`**.
*
* If this is a continuation of a previous upload, {@link UploadConfig.offset}
* should be set.
*
* @see {@link checkUploadStatus} for checking the status of an existing upload.
*/
isPartialUpload?: boolean;
clientCrc32c?: string;
clientMd5Hash?: string;
/**
* Enables CRC32C calculation on the client side.
* The calculated hash will be sent in the final PUT request if `clientCrc32c` is not provided.
*/
crc32c?: boolean;
/**
* Enables MD5 calculation on the client side.
* The calculated hash will be sent in the final PUT request if `clientMd5Hash` is not provided.
*/
md5?: boolean;
/**
* A customer-supplied encryption key. See
* https://cloud.google.com/storage/docs/encryption#customer-supplied.
*/
key?: string | Buffer;
/**
* Resource name of the Cloud KMS key, of the form
* `projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key`,
* that will be used to encrypt the object. Overrides the object metadata's
* `kms_key_name` value, if any.
*/
kmsKeyName?: string;
/**
* Any metadata you wish to set on the object.
*/
metadata?: ConfigMetadata;
/**
* The starting byte in relation to the final uploaded object.
* **Must be used with {@link UploadConfig.uri}**.
*
* If resuming an interrupted stream, do not supply this argument unless you
* know the exact number of bytes the service has AND the provided stream's
* first byte is a continuation from that provided offset. If resuming an
* interrupted stream and this option has not been provided, we will treat
* the provided upload stream as the object to upload - where the first byte
* of the upload stream is the first byte of the object to upload; skipping
* any bytes that are already present on the server.
*
* @see {@link checkUploadStatus} for checking the status of an existing upload.
* @see {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.}
*/
offset?: number;
/**
* Set an Origin header when creating the resumable upload URI.
*/
origin?: string;
/**
* Specify query parameters that go along with the initial upload request. See
* https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters
*/
params?: QueryParameters;
/**
* Apply a predefined set of access controls to the created file.
*/
predefinedAcl?: PredefinedAcl;
/**
* Make the uploaded file private. (Alias for config.predefinedAcl =
* 'private')
*/
private?: boolean;
/**
* Make the uploaded file public. (Alias for config.predefinedAcl =
* 'publicRead')
*/
public?: boolean;
/**
* The service domain for a given Cloud universe.
*/
universeDomain?: string;
/**
* If you already have a resumable URI from a previously-created resumable
* upload, just pass it in here and we'll use that.
*
* If resuming an interrupted stream and the {@link UploadConfig.offset}
* option has not been provided, we will treat the provided upload stream as
* the object to upload - where the first byte of the upload stream is the
* first byte of the object to upload; skipping any bytes that are already
* present on the server.
*
* @see {@link checkUploadStatus} for checking the status of an existing upload.
*/
uri?: string;
/**
* If the bucket being accessed has requesterPays functionality enabled, this
* can be set to control which project is billed for the access of this file.
*/
userProject?: string;
/**
* Configuration options for retrying retryable errors.
*/
retryOptions: RetryOptions;
/**
* Controls whether or not to use authentication when using a custom endpoint.
*/
useAuthWithCustomEndpoint?: boolean;
[GCCL_GCS_CMD_KEY]?: string;
}
export interface ConfigMetadata {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
/**
* Set the length of the object being uploaded. If uploading a partial
* object, this is the overall size of the finalized object.
*/
contentLength?: number;
/**
* Set the content type of the incoming data.
*/
contentType?: string;
}
export interface GoogleInnerError {
reason?: string;
}
export interface ApiError extends Error {
code?: number;
errors?: GoogleInnerError[];
}
export interface CheckUploadStatusConfig {
/**
* Set to `false` to disable retries within this method.
*
* @defaultValue `true`
*/
retry?: boolean;
}
export class Upload extends Writable {
bucket: string;
file: string;
apiEndpoint: string;
baseURI: string;
authConfig?: {scopes?: string[]};
/*
* Defaults to GoogleAuth and gets automatically overridden if an
* emulator context is detected.
*/
authClient: {
request: <T>(
opts: GaxiosOptions
) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
};
cacheKey: string;
chunkSize?: number;
customRequestOptions: GaxiosOptions;
generation?: number;
key?: string | Buffer;
kmsKeyName?: string;
metadata: ConfigMetadata;
offset?: number;
origin?: string;
params: QueryParameters;
predefinedAcl?: PredefinedAcl;
private?: boolean;
public?: boolean;
uri?: string;
userProject?: string;
encryption?: Encryption;
uriProvidedManually: boolean;
numBytesWritten = 0;
numRetries = 0;
contentLength: number | '*';
retryOptions: RetryOptions;
timeOfFirstRequest: number;
isPartialUpload: boolean;
private currentInvocationId = {
checkUploadStatus: uuid.v4(),
chunk: uuid.v4(),
uri: uuid.v4(),
};
/**
* A cache of buffers written to this instance, ready for consuming
*/
private writeBuffers: Buffer[] = [];
private numChunksReadInRequest = 0;
#hashValidator?: HashStreamValidator;
#clientCrc32c?: string;
#clientMd5Hash?: string;
/**
* An array of buffers used for caching the most recent upload chunk.
* We should not assume that the server received all bytes sent in the request.
* - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
*/
private localWriteCache: Buffer[] = [];
private localWriteCacheByteLength = 0;
private upstreamEnded = false;
#gcclGcsCmd?: string;
constructor(cfg: UploadConfig) {
super(cfg);
cfg = cfg || {};
if (!cfg.bucket || !cfg.file) {
throw new Error('A bucket and file name are required');
}
if (cfg.offset && !cfg.uri) {
throw new RangeError(
'Cannot provide an `offset` without providing a `uri`'
);
}
if (cfg.isPartialUpload && !cfg.chunkSize) {
throw new RangeError(
'Cannot set `isPartialUpload` without providing a `chunkSize`'
);
}
cfg.authConfig = cfg.authConfig || {};
cfg.authConfig.scopes = [
'https://www.googleapis.com/auth/devstorage.full_control',
];
this.authClient = cfg.authClient || new GoogleAuth(cfg.authConfig);
const universe = cfg.universeDomain || DEFAULT_UNIVERSE;
this.apiEndpoint = `https://storage.${universe}`;
if (cfg.apiEndpoint && cfg.apiEndpoint !== this.apiEndpoint) {
this.apiEndpoint = this.sanitizeEndpoint(cfg.apiEndpoint);
const hostname = new URL(this.apiEndpoint).hostname;
// check if it is a domain of a known universe
const isDomain = hostname === universe;
const isDefaultUniverseDomain = hostname === DEFAULT_UNIVERSE;
// check if it is a subdomain of a known universe
// by checking a last (universe's length + 1) of a hostname
const isSubDomainOfUniverse =
hostname.slice(-(universe.length + 1)) === `.${universe}`;
const isSubDomainOfDefaultUniverse =
hostname.slice(-(DEFAULT_UNIVERSE.length + 1)) ===
`.${DEFAULT_UNIVERSE}`;
if (
!isDomain &&
!isDefaultUniverseDomain &&
!isSubDomainOfUniverse &&
!isSubDomainOfDefaultUniverse
) {
// Check if we should use auth with custom endpoint
if (cfg.useAuthWithCustomEndpoint !== true) {
// Only bypass auth if explicitly not requested
this.authClient = gaxios;
}
// Otherwise keep the authenticated client
}
}
this.baseURI = `${this.apiEndpoint}/upload/storage/v1/b`;
this.bucket = cfg.bucket;
const cacheKeyElements = [cfg.bucket, cfg.file];
if (typeof cfg.generation === 'number') {
cacheKeyElements.push(`${cfg.generation}`);
}
this.cacheKey = cacheKeyElements.join('/');
this.customRequestOptions = cfg.customRequestOptions || {};
this.file = cfg.file;
this.generation = cfg.generation;
this.kmsKeyName = cfg.kmsKeyName;
this.metadata = cfg.metadata || {};
this.offset = cfg.offset;
this.origin = cfg.origin;
this.params = cfg.params || {};
this.userProject = cfg.userProject;
this.chunkSize = cfg.chunkSize;
this.retryOptions = cfg.retryOptions;
this.isPartialUpload = cfg.isPartialUpload ?? false;
this.#clientCrc32c = cfg.clientCrc32c;
this.#clientMd5Hash = cfg.clientMd5Hash;
const calculateCrc32c = !cfg.clientCrc32c && cfg.crc32c;
const calculateMd5 = !cfg.clientMd5Hash && cfg.md5;
if (calculateCrc32c || calculateMd5) {
this.#hashValidator = new HashStreamValidator({
crc32c: calculateCrc32c,
md5: calculateMd5,
updateHashesOnly: true,
});
}
if (cfg.key) {
if (typeof cfg.key === 'string') {
const base64Key = Buffer.from(cfg.key).toString('base64');
this.encryption = {
key: base64Key,
hash: createHash('sha256').update(cfg.key).digest('base64'),
};
} else {
const base64Key = cfg.key.toString('base64');
this.encryption = {
key: base64Key,
hash: createHash('sha256').update(cfg.key).digest('base64'),
};
}
}
this.predefinedAcl = cfg.predefinedAcl;
if (cfg.private) this.predefinedAcl = 'private';
if (cfg.public) this.predefinedAcl = 'publicRead';
const autoRetry = cfg.retryOptions.autoRetry;
this.uriProvidedManually = !!cfg.uri;
this.uri = cfg.uri;
if (this.offset) {
// we're resuming an incomplete upload
this.numBytesWritten = this.offset;
}
this.numRetries = 0; // counter for number of retries currently executed
if (!autoRetry) {
cfg.retryOptions.maxRetries = 0;
}
this.timeOfFirstRequest = Date.now();
const contentLength = cfg.metadata
? Number(cfg.metadata.contentLength)
: NaN;
this.contentLength = isNaN(contentLength) ? '*' : contentLength;
this.#gcclGcsCmd = cfg[GCCL_GCS_CMD_KEY];
this.once('writing', () => {
if (this.uri) {
this.continueUploading();
} else {
this.createURI(err => {
if (err) {
return this.destroy(err);
}
this.startUploading();
return;
});
}
});
}
/**
* Prevent 'finish' event until the upload has succeeded.
*
* @param fireFinishEvent The finish callback
*/
_final(fireFinishEvent = () => {}) {
this.upstreamEnded = true;
this.once('uploadFinished', fireFinishEvent);
process.nextTick(() => {
this.emit('upstreamFinished');
// it's possible `_write` may not be called - namely for empty object uploads
this.emit('writing');
});
}
/**
* Handles incoming data from upstream
*
* @param chunk The chunk to append to the buffer
* @param encoding The encoding of the chunk
* @param readCallback A callback for when the buffer has been read downstream
*/
_write(
chunk: Buffer | string,
encoding: BufferEncoding,
readCallback = () => {}
) {
// Backwards-compatible event
this.emit('writing');
const bufferChunk =
typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk;
if (this.#hashValidator) {
try {
this.#hashValidator.write(bufferChunk);
} catch (e) {
this.destroy(e as Error);
return;
}
}
this.writeBuffers.push(bufferChunk);
this.once('readFromChunkBuffer', readCallback);
process.nextTick(() => this.emit('wroteToChunkBuffer'));
}
#resetLocalBuffersCache() {
this.localWriteCache = [];
this.localWriteCacheByteLength = 0;
}
#addLocalBufferCache(buf: Buffer) {
this.localWriteCache.push(buf);
this.localWriteCacheByteLength += buf.byteLength;
}
/**
* Compares the client's calculated or provided hash against the server's
* returned hash for a specific checksum type. Destroys the stream on mismatch.
* @param clientHash The client's calculated or provided hash (Base64).
* @param serverHash The hash returned by the server (Base64).
* @param hashType The type of hash ('CRC32C' or 'MD5').
*/
#validateChecksum(
clientHash: string | undefined,
serverHash: string | undefined,
hashType: 'CRC32C' | 'MD5'
): boolean {
// Only validate if both client and server hashes are present.
if (clientHash && serverHash) {
if (clientHash !== serverHash) {
const detailMessage = `${hashType} checksum mismatch. Client calculated: ${clientHash}, Server returned: ${serverHash}`;
const detailError = new Error(detailMessage);
const error = new RequestError(FileExceptionMessages.UPLOAD_MISMATCH);
error.code = 'FILE_NO_UPLOAD';
error.errors = [detailError];
this.destroy(error);
return true;
}
}
return false;
}
/**
* Builds and applies the X-Goog-Hash header to the request options
* using either calculated hashes from #hashValidator or pre-calculated
* client-side hashes. This should only be called on the final request.
*
* @param headers The headers object to modify.
*/
#applyChecksumHeaders(headers: GaxiosOptions['headers']) {
const checksums: string[] = [];
if (this.#hashValidator?.crc32cEnabled) {
checksums.push(`crc32c=${this.#hashValidator.crc32c!}`);
} else if (this.#clientCrc32c) {
checksums.push(`crc32c=${this.#clientCrc32c}`);
}
if (this.#hashValidator?.md5Enabled) {
checksums.push(`md5=${this.#hashValidator.md5Digest!}`);
} else if (this.#clientMd5Hash) {
checksums.push(`md5=${this.#clientMd5Hash}`);
}
if (checksums.length > 0) {
headers!['X-Goog-Hash'] = checksums.join(',');
}
}
/**
* Prepends the local buffer to write buffer and resets it.
*
* @param keepLastBytes number of bytes to keep from the end of the local buffer.
*/
private prependLocalBufferToUpstream(keepLastBytes?: number) {
// Typically, the upstream write buffers should be smaller than the local
// cache, so we can save time by setting the local cache as the new
// upstream write buffer array and appending the old array to it
let initialBuffers: Buffer[] = [];
if (keepLastBytes) {
// we only want the last X bytes
let bytesKept = 0;
while (keepLastBytes > bytesKept) {
// load backwards because we want the last X bytes
// note: `localWriteCacheByteLength` is reset below
let buf = this.localWriteCache.pop();
if (!buf) break;
bytesKept += buf.byteLength;
if (bytesKept > keepLastBytes) {
// we have gone over the amount desired, let's keep the last X bytes
// of this buffer
const diff = bytesKept - keepLastBytes;
buf = buf.subarray(diff);
bytesKept -= diff;
}
initialBuffers.unshift(buf);
}
} else {
// we're keeping all of the local cache, simply use it as the initial buffer
initialBuffers = this.localWriteCache;
}
// Append the old upstream to the new
const append = this.writeBuffers;
this.writeBuffers = initialBuffers;
for (const buf of append) {
this.writeBuffers.push(buf);
}
// reset last buffers sent
this.#resetLocalBuffersCache();
}
/**
* Retrieves data from upstream's buffer.
*
* @param limit The maximum amount to return from the buffer.
*/
private *pullFromChunkBuffer(limit: number) {
while (limit) {
const buf = this.writeBuffers.shift();
if (!buf) break;
let bufToYield = buf;
if (buf.byteLength > limit) {
bufToYield = buf.subarray(0, limit);
this.writeBuffers.unshift(buf.subarray(limit));
limit = 0;
} else {
limit -= buf.byteLength;
}
yield bufToYield;
// Notify upstream we've read from the buffer and we're able to consume
// more. It can also potentially send more data down as we're currently
// iterating.
this.emit('readFromChunkBuffer');
}
}
/**
* A handler for determining if data is ready to be read from upstream.
*
* @returns If there will be more chunks to read in the future
*/
private async waitForNextChunk(): Promise<boolean> {
const willBeMoreChunks = await new Promise<boolean>(resolve => {
// There's data available - it should be digested
if (this.writeBuffers.length) {
return resolve(true);
}
// The upstream writable ended, we shouldn't expect any more data.
if (this.upstreamEnded) {
return resolve(false);
}
// Nothing immediate seems to be determined. We need to prepare some
// listeners to determine next steps...
const wroteToChunkBufferCallback = () => {
removeListeners();
return resolve(true);
};
const upstreamFinishedCallback = () => {
removeListeners();
// this should be the last chunk, if there's anything there
if (this.writeBuffers.length) return resolve(true);
return resolve(false);
};
// Remove listeners when we're ready to callback.
const removeListeners = () => {
this.removeListener('wroteToChunkBuffer', wroteToChunkBufferCallback);
this.removeListener('upstreamFinished', upstreamFinishedCallback);
};
// If there's data recently written it should be digested
this.once('wroteToChunkBuffer', wroteToChunkBufferCallback);
// If the upstream finishes let's see if there's anything to grab
this.once('upstreamFinished', upstreamFinishedCallback);
});
return willBeMoreChunks;
}
/**
* Reads data from upstream up to the provided `limit`.
* Ends when the limit has reached or no data is expected to be pushed from upstream.
*
* @param limit The most amount of data this iterator should return. `Infinity` by default.
*/
private async *upstreamIterator(limit = Infinity) {
// read from upstream chunk buffer
while (limit && (await this.waitForNextChunk())) {
// read until end or limit has been reached
for (const chunk of this.pullFromChunkBuffer(limit)) {
limit -= chunk.byteLength;
yield chunk;
}
}
}
createURI(): Promise<string>;
createURI(callback: CreateUriCallback): void;
createURI(callback?: CreateUriCallback): void | Promise<string> {
if (!callback) {
return this.createURIAsync();
}
this.createURIAsync().then(r => callback(null, r), callback);
}
protected async createURIAsync(): Promise<string> {
const metadata = {...this.metadata};
const headers: gaxios.Headers = {};
// Delete content length and content type from metadata if they exist.
// These are headers and should not be sent as part of the metadata.
if (metadata.contentLength) {
headers['X-Upload-Content-Length'] = metadata.contentLength.toString();
delete metadata.contentLength;
}
if (metadata.contentType) {
headers!['X-Upload-Content-Type'] = metadata.contentType;
delete metadata.contentType;
}
let googAPIClient = `${getRuntimeTrackingString()} gccl/${
packageJson.version
}-${getModuleFormat()} gccl-invocation-id/${this.currentInvocationId.uri}`;
if (this.#gcclGcsCmd) {
googAPIClient += ` gccl-gcs-cmd/${this.#gcclGcsCmd}`;
}
// Check if headers already exist before creating new ones
const reqOpts: GaxiosOptions = {
method: 'POST',
url: [this.baseURI, this.bucket, 'o'].join('/'),
params: Object.assign(
{
name: this.file,
uploadType: 'resumable',
},
this.params
),
data: metadata,
headers: {
'User-Agent': getUserAgentString(),
'x-goog-api-client': googAPIClient,
...headers,
},
};
if (metadata.contentLength) {
reqOpts.headers!['X-Upload-Content-Length'] =
metadata.contentLength.toString();
}
if (metadata.contentType) {
reqOpts.headers!['X-Upload-Content-Type'] = metadata.contentType;
}
if (typeof this.generation !== 'undefined') {
reqOpts.params.ifGenerationMatch = this.generation;
}
if (this.kmsKeyName) {
reqOpts.params.kmsKeyName = this.kmsKeyName;
}
if (this.predefinedAcl) {
reqOpts.params.predefinedAcl = this.predefinedAcl;
}
if (this.origin) {
reqOpts.headers!.Origin = this.origin;
}
const uri = await AsyncRetry(
async (bail: (err: Error) => void) => {
try {
const res = await this.makeRequest(reqOpts);
// We have successfully got a URI we can now create a new invocation id
this.currentInvocationId.uri = uuid.v4();
return res.headers.location;
} catch (err) {
const e = err as GaxiosError;
const apiError = {
code: e.response?.status,
name: e.response?.statusText,
message: e.response?.statusText,
errors: [
{
reason: e.code as string,
},
],
};
if (
this.retryOptions.maxRetries! > 0 &&
this.retryOptions.retryableErrorFn!(apiError as ApiError)
) {
throw e;
} else {
return bail(e);
}
}
},
{
retries: this.retryOptions.maxRetries,
factor: this.retryOptions.retryDelayMultiplier,
maxTimeout: this.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds
maxRetryTime: this.retryOptions.totalTimeout! * 1000, //convert to milliseconds
}
);
this.uri = uri;
this.offset = 0;
// emit the newly generated URI for future reuse, if necessary.
this.emit('uri', uri);
return uri;
}
private async continueUploading() {
this.offset ?? (await this.getAndSetOffset());
return this.startUploading();
}
async startUploading() {
const multiChunkMode = !!this.chunkSize;
let responseReceived = false;
this.numChunksReadInRequest = 0;
if (!this.offset) {
this.offset = 0;
}
// Check if the offset (server) is too far behind the current stream
if (this.offset < this.numBytesWritten) {
const delta = this.numBytesWritten - this.offset;
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.`;
this.emit('error', new RangeError(message));
return;
}
// Check if we should 'fast-forward' to the relevant data to upload
if (this.numBytesWritten < this.offset) {
// 'fast-forward' to the byte where we need to upload.
// only push data from the byte after the one we left off on
const fastForwardBytes = this.offset - this.numBytesWritten;
for await (const _chunk of this.upstreamIterator(fastForwardBytes)) {
_chunk; // discard the data up until the point we want
}
this.numBytesWritten = this.offset;
}
let expectedUploadSize: number | undefined = undefined;
// Set `expectedUploadSize` to `contentLength - this.numBytesWritten`, if available
if (typeof this.contentLength === 'number') {
expectedUploadSize = this.contentLength - this.numBytesWritten;
}
// `expectedUploadSize` should be no more than the `chunkSize`.
// It's possible this is the last chunk request for a multiple
// chunk upload, thus smaller than the chunk size.
if (this.chunkSize) {
expectedUploadSize = expectedUploadSize
? Math.min(this.chunkSize, expectedUploadSize)
: this.chunkSize;
}
// A queue for the upstream data
const upstreamQueue = this.upstreamIterator(expectedUploadSize);
// The primary read stream for this request. This stream retrieves no more
// than the exact requested amount from upstream.
const requestStream = new Readable({
read: async () => {
// Don't attempt to retrieve data upstream if we already have a response
if (responseReceived) requestStream.push(null);
const result = await upstreamQueue.next();
if (result.value) {
this.numChunksReadInRequest++;
if (multiChunkMode) {
// save ever buffer used in the request in multi-chunk mode
this.#addLocalBufferCache(result.value);
} else {
this.#resetLocalBuffersCache();
this.#addLocalBufferCache(result.value);
}
this.numBytesWritten += result.value.byteLength;
this.emit('progress', {
bytesWritten: this.numBytesWritten,
contentLength: this.contentLength,
});
requestStream.push(result.value);
}
if (result.done) {
requestStream.push(null);
}
},
});
let googAPIClient = `${getRuntimeTrackingString()} gccl/${
packageJson.version
}-${getModuleFormat()} gccl-invocation-id/${