-
Notifications
You must be signed in to change notification settings - Fork 370
/
storage.ts
1446 lines (1355 loc) · 46.2 KB
/
storage.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
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 2019 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 {ApiError, Metadata, Service, ServiceOptions} from './nodejs-common';
import {paginator} from '@google-cloud/paginator';
import {promisifyAll} from '@google-cloud/promisify';
import arrify = require('arrify');
import {Readable} from 'stream';
import {Bucket} from './bucket';
import {Channel} from './channel';
import {File} from './file';
import {normalize} from './util';
import {HmacKey, HmacKeyMetadata, HmacKeyOptions} from './hmacKey';
export interface GetServiceAccountOptions {
userProject?: string;
}
export interface ServiceAccount {
emailAddress?: string;
}
export type GetServiceAccountResponse = [ServiceAccount, Metadata];
export interface GetServiceAccountCallback {
(
err: Error | null,
serviceAccount?: ServiceAccount,
apiResponse?: Metadata
): void;
}
export interface CreateBucketQuery {
project: string;
userProject: string;
}
export enum IdempotencyStrategy {
RetryAlways,
RetryConditional,
RetryNever,
}
export interface RetryOptions {
retryDelayMultiplier?: number;
totalTimeout?: number;
maxRetryDelay?: number;
autoRetry?: boolean;
maxRetries?: number;
retryableErrorFn?: (err: ApiError) => boolean;
idempotencyStrategy?: IdempotencyStrategy;
}
export interface PreconditionOptions {
ifGenerationMatch?: number;
ifGenerationNotMatch?: number;
ifMetagenerationMatch?: number;
ifMetagenerationNotMatch?: number;
}
export interface StorageOptions extends ServiceOptions {
retryOptions?: RetryOptions;
/**
* @deprecated Use retryOptions instead.
* @internal
*/
autoRetry?: boolean;
/**
* @deprecated Use retryOptions instead.
* @internal
*/
maxRetries?: number;
/**
* **This option is deprecated.**
* @todo Remove in next major release.
*/
promise?: typeof Promise;
/**
* The API endpoint of the service used to make requests.
* Defaults to `storage.googleapis.com`.
*/
apiEndpoint?: string;
}
export interface BucketOptions {
kmsKeyName?: string;
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export interface Cors {
maxAgeSeconds?: number;
method?: string[];
origin?: string[];
responseHeader?: string[];
}
interface Versioning {
enabled: boolean;
}
export interface CreateBucketRequest {
archive?: boolean;
coldline?: boolean;
cors?: Cors[];
dra?: boolean;
location?: string;
multiRegional?: boolean;
nearline?: boolean;
regional?: boolean;
requesterPays?: boolean;
retentionPolicy?: object;
rpo?: string;
standard?: boolean;
storageClass?: string;
userProject?: string;
versioning?: Versioning;
}
export type CreateBucketResponse = [Bucket, Metadata];
export interface BucketCallback {
(err: Error | null, bucket?: Bucket | null, apiResponse?: Metadata): void;
}
export type GetBucketsResponse = [Bucket[], {}, Metadata];
export interface GetBucketsCallback {
(
err: Error | null,
buckets: Bucket[],
nextQuery?: {},
apiResponse?: Metadata
): void;
}
export interface GetBucketsRequest {
prefix?: string;
project?: string;
autoPaginate?: boolean;
maxApiCalls?: number;
maxResults?: number;
pageToken?: string;
userProject?: string;
}
export interface HmacKeyResourceResponse {
metadata: HmacKeyMetadata;
secret: string;
}
export type CreateHmacKeyResponse = [HmacKey, string, HmacKeyResourceResponse];
export interface CreateHmacKeyOptions {
projectId?: string;
userProject?: string;
}
export interface CreateHmacKeyCallback {
(
err: Error | null,
hmacKey?: HmacKey | null,
secret?: string | null,
apiResponse?: HmacKeyResourceResponse
): void;
}
export interface GetHmacKeysOptions {
projectId?: string;
serviceAccountEmail?: string;
showDeletedKeys?: boolean;
autoPaginate?: boolean;
maxApiCalls?: number;
maxResults?: number;
pageToken?: string;
userProject?: string;
}
export interface GetHmacKeysCallback {
(
err: Error | null,
hmacKeys: HmacKey[] | null,
nextQuery?: {},
apiResponse?: Metadata
): void;
}
export enum ExceptionMessages {
EXPIRATION_DATE_INVALID = 'The expiration date provided was invalid.',
EXPIRATION_DATE_PAST = 'An expiration date cannot be in the past.',
INVALID_ACTION = 'The action is not provided or invalid.',
}
export enum StorageExceptionMessages {
AUTO_RETRY_DEPRECATED = 'autoRetry is deprecated. Use retryOptions.autoRetry instead.',
MAX_RETRIES_DEPRECATED = 'maxRetries is deprecated. Use retryOptions.maxRetries instead.',
BUCKET_NAME_REQUIRED = 'A bucket name is needed to use Cloud Storage.',
BUCKET_NAME_REQUIRED_CREATE = 'A name is required to create a bucket.',
HMAC_SERVICE_ACCOUNT = 'The first argument must be a service account email to create an HMAC key.',
HMAC_ACCESS_ID = 'An access ID is needed to create an HmacKey object.',
}
export type GetHmacKeysResponse = [HmacKey[]];
export const PROTOCOL_REGEX = /^(\w*):\/\//;
/**
* Default behavior: Automatically retry retriable server errors.
*
* @const {boolean}
*/
export const AUTO_RETRY_DEFAULT = true;
/**
* Default behavior: Only attempt to retry retriable errors 3 times.
*
* @const {number}
*/
export const MAX_RETRY_DEFAULT = 3;
/**
* Default behavior: Wait twice as long as previous retry before retrying.
*
* @const {number}
*/
export const RETRY_DELAY_MULTIPLIER_DEFAULT = 2;
/**
* Default behavior: If the operation doesn't succeed after 600 seconds,
* stop retrying.
*
* @const {number}
*/
export const TOTAL_TIMEOUT_DEFAULT = 600;
/**
* Default behavior: Wait no more than 64 seconds between retries.
*
* @const {number}
*/
export const MAX_RETRY_DELAY_DEFAULT = 64;
/**
* Default behavior: Retry conditionally idempotent operations if correct preconditions are set.
*
* @const {enum}
* @private
*/
const IDEMPOTENCY_STRATEGY_DEFAULT = IdempotencyStrategy.RetryConditional;
/**
* Returns true if the API request should be retried, given the error that was
* given the first time the request was attempted.
* @const
* @param {error} err - The API error to check if it is appropriate to retry.
* @return {boolean} True if the API request should be retried, false otherwise.
*/
export const RETRYABLE_ERR_FN_DEFAULT = function (err?: ApiError) {
if (err) {
if ([408, 429, 500, 502, 503, 504].indexOf(err.code!) !== -1) {
return true;
}
if (err.errors) {
for (const e of err.errors) {
const reason = e?.reason?.toString().toLowerCase();
if (
(reason && reason.includes('eai_again')) || //DNS lookup error
reason === 'econnreset' ||
reason === 'unexpected connection closure'
) {
return true;
}
}
}
}
return false;
};
/*! Developer Documentation
*
* Invoke this method to create a new Storage object bound with pre-determined
* configuration options. For each object that can be created (e.g., a bucket),
* there is an equivalent static and instance method. While they are classes,
* they can be instantiated without use of the `new` keyword.
*/
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* This object provides constants to refer to the three permission levels that
* can be granted to an entity:
*
* - `gcs.acl.OWNER_ROLE` - ("OWNER")
* - `gcs.acl.READER_ROLE` - ("READER")
* - `gcs.acl.WRITER_ROLE` - ("WRITER")
*
* See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists}
*
* @name Storage#acl
* @type {object}
* @property {string} OWNER_ROLE
* @property {string} READER_ROLE
* @property {string} WRITER_ROLE
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
*
* //-
* // Make all of the files currently in a bucket publicly readable.
* //-
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* albums.acl.add(options, function(err, aclObject) {});
*
* //-
* // Make any new objects added to a bucket publicly readable.
* //-
* albums.acl.default.add(options, function(err, aclObject) {});
*
* //-
* // Grant a user ownership permissions to a bucket.
* //-
* albums.acl.add({
* entity: '[email protected]',
* role: storage.acl.OWNER_ROLE
* }, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* albums.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
* ```
*/
/**
* Get {@link Bucket} objects for all of the buckets in your project as
* a readable object stream.
*
* @method Storage#getBucketsStream
* @param {GetBucketsRequest} [query] Query object for listing buckets.
* @returns {ReadableStream} A readable stream that emits {@link Bucket}
* instances.
*
* @example
* ```
* storage.getBucketsStream()
* .on('error', console.error)
* .on('data', function(bucket) {
* // bucket is a Bucket object.
* })
* .on('end', function() {
* // All buckets retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* storage.getBucketsStream()
* .on('data', function(bucket) {
* this.end();
* });
* ```
*/
/**
* Get {@link HmacKey} objects for all of the HMAC keys in the project in a
* readable object stream.
*
* @method Storage#getHmacKeysStream
* @param {GetHmacKeysOptions} [options] Configuration options.
* @returns {ReadableStream} A readable stream that emits {@link HmacKey}
* instances.
*
* @example
* ```
* storage.getHmacKeysStream()
* .on('error', console.error)
* .on('data', function(hmacKey) {
* // hmacKey is an HmacKey object.
* })
* .on('end', function() {
* // All HmacKey retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* storage.getHmacKeysStream()
* .on('data', function(bucket) {
* this.end();
* });
* ```
*/
/**
* <h4>ACLs</h4>
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share files with other users
* and allow other users to access your buckets and files.
*
* To learn more about ACLs, read this overview on
* {@link https://cloud.google.com/storage/docs/access-control| Access Control}.
*
* See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview}
* See {@link https://cloud.google.com/storage/docs/access-control| Access Control}
*
* @class
*/
export class Storage extends Service {
/**
* {@link Bucket} class.
*
* @name Storage.Bucket
* @see Bucket
* @type {Constructor}
*/
static Bucket: typeof Bucket = Bucket;
/**
* {@link Channel} class.
*
* @name Storage.Channel
* @see Channel
* @type {Constructor}
*/
static Channel: typeof Channel = Channel;
/**
* {@link File} class.
*
* @name Storage.File
* @see File
* @type {Constructor}
*/
static File: typeof File = File;
/**
* {@link HmacKey} class.
*
* @name Storage.HmacKey
* @see HmacKey
* @type {Constructor}
*/
static HmacKey: typeof HmacKey = HmacKey;
static acl = {
OWNER_ROLE: 'OWNER',
READER_ROLE: 'READER',
WRITER_ROLE: 'WRITER',
};
/**
* Reference to {@link Storage.acl}.
*
* @name Storage#acl
* @see Storage.acl
*/
acl: typeof Storage.acl;
getBucketsStream(): Readable {
// placeholder body, overwritten in constructor
return new Readable();
}
getHmacKeysStream(): Readable {
// placeholder body, overwritten in constructor
return new Readable();
}
retryOptions: RetryOptions;
/**
* @typedef {object} StorageOptions
* @property {string} [projectId] The project ID from the Google Developer's
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
* variable `GCLOUD_PROJECT` for your project ID. If your app is running
* in an environment which supports {@link
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
* Application Default Credentials}, your project ID will be detected
* automatically.
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
* downloaded from the Google Developers Console. If you provide a path to
* a JSON file, the `projectId` option above is not necessary. NOTE: .pem and
* .p12 require you to specify the `email` option as well.
* @property {string} [email] Account email address. Required when using a .pem
* or .p12 keyFilename.
* @property {object} [credentials] Credentials object.
* @property {string} [credentials.client_email]
* @property {string} [credentials.private_key]
* @property {object} [retryOptions] Options for customizing retries. Retriable server errors
* will be retried with exponential delay between them dictated by the formula
* max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout
* has been reached. Retries will only happen if autoRetry is set to true.
* @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the
* response is related to rate limits or certain intermittent server
* errors. We will exponentially backoff subsequent requests by default.
* @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @property {number} [retryOptions.totalTimeout = 600] The total time, starting from
* when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
* @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests.
* When this value is reached, ``retryDelayMultiplier`` will no longer be used to
* increase delay time.
* @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries
* attempted before returning the error.
* @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given
* error should be retried and false otherwise.
* @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration
* controls how conditionally idempotent operations are retried. Possible values are: RetryAlways -
* will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional -
* will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never
* retry a conditionally idempotent operation.
* @property {string} [userAgent] The value to be prepended to the User-Agent
* header in API requests.
* @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one.
* @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out.
* @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned.
* @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests.
* @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint.
*/
/**
* Constructs the Storage client.
*
* @example
* Create a client that uses Application Default Credentials
* (ADC)
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* ```
*
* @example
* Create a client with explicit credentials
* ```
* const storage = new Storage({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
* ```
*
* @example
* Create a client with an `AuthClient` (e.g. `DownscopedClient`)
* ```
* const {DownscopedClient} = require('google-auth-library');
* const authClient = new DownscopedClient({...});
*
* const storage = new Storage({authClient});
* ```
*
* Additional samples:
* - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1
* - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js
*
* @param {StorageOptions} [options] Configuration options.
*/
constructor(options: StorageOptions = {}) {
let apiEndpoint = 'https://storage.googleapis.com';
let customEndpoint = false;
// Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead.
const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST;
if (typeof EMULATOR_HOST === 'string') {
apiEndpoint = Storage.sanitizeEndpoint(EMULATOR_HOST);
customEndpoint = true;
}
if (options.apiEndpoint) {
apiEndpoint = Storage.sanitizeEndpoint(options.apiEndpoint);
customEndpoint = true;
}
options = Object.assign({}, options, {apiEndpoint});
// Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead.
const baseUrl = EMULATOR_HOST || `${options.apiEndpoint}/storage/v1`;
let autoRetryValue = AUTO_RETRY_DEFAULT;
if (
options.autoRetry !== undefined &&
options.retryOptions?.autoRetry !== undefined
) {
throw new ApiError(StorageExceptionMessages.AUTO_RETRY_DEPRECATED);
} else if (options.autoRetry !== undefined) {
autoRetryValue = options.autoRetry;
} else if (options.retryOptions?.autoRetry !== undefined) {
autoRetryValue = options.retryOptions.autoRetry;
}
let maxRetryValue = MAX_RETRY_DEFAULT;
if (options.maxRetries && options.retryOptions?.maxRetries) {
throw new ApiError(StorageExceptionMessages.MAX_RETRIES_DEPRECATED);
} else if (options.maxRetries) {
maxRetryValue = options.maxRetries;
} else if (options.retryOptions?.maxRetries) {
maxRetryValue = options.retryOptions.maxRetries;
}
const config = {
apiEndpoint: options.apiEndpoint!,
retryOptions: {
autoRetry: autoRetryValue,
maxRetries: maxRetryValue,
retryDelayMultiplier: options.retryOptions?.retryDelayMultiplier
? options.retryOptions?.retryDelayMultiplier
: RETRY_DELAY_MULTIPLIER_DEFAULT,
totalTimeout: options.retryOptions?.totalTimeout
? options.retryOptions?.totalTimeout
: TOTAL_TIMEOUT_DEFAULT,
maxRetryDelay: options.retryOptions?.maxRetryDelay
? options.retryOptions?.maxRetryDelay
: MAX_RETRY_DELAY_DEFAULT,
retryableErrorFn: options.retryOptions?.retryableErrorFn
? options.retryOptions?.retryableErrorFn
: RETRYABLE_ERR_FN_DEFAULT,
idempotencyStrategy:
options.retryOptions?.idempotencyStrategy !== undefined
? options.retryOptions?.idempotencyStrategy
: IDEMPOTENCY_STRATEGY_DEFAULT,
},
baseUrl,
customEndpoint,
useAuthWithCustomEndpoint: options?.useAuthWithCustomEndpoint,
projectIdRequired: false,
scopes: [
'https://www.googleapis.com/auth/iam',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/devstorage.full_control',
],
packageJson: require('../../package.json'),
};
super(config, options);
/**
* Reference to {@link Storage.acl}.
*
* @name Storage#acl
* @see Storage.acl
*/
this.acl = Storage.acl;
this.retryOptions = config.retryOptions;
this.getBucketsStream = paginator.streamify('getBuckets');
this.getHmacKeysStream = paginator.streamify('getHmacKeys');
}
private static sanitizeEndpoint(url: string) {
if (!PROTOCOL_REGEX.test(url)) {
url = `https://${url}`;
}
return url.replace(/\/+$/, ''); // Remove trailing slashes
}
/**
* Get a reference to a Cloud Storage bucket.
*
* @param {string} name Name of the bucket.
* @param {object} [options] Configuration object.
* @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to
* encrypt objects inserted into this bucket, if no encryption method is
* specified.
* @param {string} [options.userProject] User project to be billed for all
* requests made from this Bucket object.
* @returns {Bucket}
* @see Bucket
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
* const photos = storage.bucket('photos');
* ```
*/
bucket(name: string, options?: BucketOptions) {
if (!name) {
throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED);
}
return new Bucket(this, name, options);
}
/**
* Reference a channel to receive notifications about changes to your bucket.
*
* @param {string} id The ID of the channel.
* @param {string} resourceId The resource ID of the channel.
* @returns {Channel}
* @see Channel
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const channel = storage.channel('id', 'resource-id');
* ```
*/
channel(id: string, resourceId: string) {
return new Channel(this, id, resourceId);
}
createBucket(
name: string,
metadata?: CreateBucketRequest
): Promise<CreateBucketResponse>;
createBucket(name: string, callback: BucketCallback): void;
createBucket(
name: string,
metadata: CreateBucketRequest,
callback: BucketCallback
): void;
createBucket(
name: string,
metadata: CreateBucketRequest,
callback: BucketCallback
): void;
/**
* @typedef {array} CreateBucketResponse
* @property {Bucket} 0 The new {@link Bucket}.
* @property {object} 1 The full API response.
*/
/**
* @callback CreateBucketCallback
* @param {?Error} err Request error, if any.
* @param {Bucket} bucket The new {@link Bucket}.
* @param {object} apiResponse The full API response.
*/
/**
* Metadata to set for the bucket.
*
* @typedef {object} CreateBucketRequest
* @property {boolean} [archive=false] Specify the storage class as Archive.
* @property {boolean} [coldline=false] Specify the storage class as Coldline.
* @property {Cors[]} [cors=[]] Specify the CORS configuration to use.
* @property {boolean} [dra=false] Specify the storage class as Durable Reduced
* Availability.
* @property {string} [location] Specify the bucket's location(s). If specifying
* a dual-region, can be specified as a string `"US-CENTRAL1+US-WEST1"`.
* For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}.
* @property {boolean} [multiRegional=false] Specify the storage class as
* Multi-Regional.
* @property {boolean} [nearline=false] Specify the storage class as Nearline.
* @property {boolean} [regional=false] Specify the storage class as Regional.
* @property {boolean} [requesterPays=false] **Early Access Testers Only**
* Force the use of the User Project metadata field to assign operational
* costs when an operation is made on a Bucket and its objects.
* @property {string} [rpo] For dual-region buckets, controls whether turbo
* replication is enabled (`ASYNC_TURBO`) or disabled (`DEFAULT`).
* @property {boolean} [standard=true] Specify the storage class as Standard.
* @property {string} [storageClass] The new storage class. (`standard`,
* `nearline`, `coldline`, or `archive`).
* **Note:** The storage classes `multi_regional`, `regional`, and
* `durable_reduced_availability` are now legacy and will be deprecated in
* the future.
* @property {Versioning} [versioning=undefined] Specify the versioning status.
* @property {string} [userProject] The ID of the project which will be billed
* for the request.
*/
/**
* Create a bucket.
*
* Cloud Storage uses a flat namespace, so you can't create a bucket with
* a name that is already in use. For more information, see
* {@link https://cloud.google.com/storage/docs/bucketnaming.html#requirements| Bucket Naming Guidelines}.
*
* See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert| Buckets: insert API Documentation}
* See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes}
*
* @param {string} name Name of the bucket to create.
* @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
* @param {CreateBucketCallback} [callback] Callback function.
* @returns {Promise<CreateBucketResponse>}
* @throws {Error} If a name is not provided.
* @see Bucket#create
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const callback = function(err, bucket, apiResponse) {
* // `bucket` is a Bucket object.
* };
*
* storage.createBucket('new-bucket', callback);
*
* //-
* // Create a bucket in a specific location and region. <em>See the <a
* // href="https://cloud.google.com/storage/docs/json_api/v1/buckets/insert">
* // Official JSON API docs</a> for complete details on the `location`
* option.
* // </em>
* //-
* const metadata = {
* location: 'US-CENTRAL1',
* regional: true
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // Create a bucket with a retention policy of 6 months.
* //-
* const metadata = {
* retentionPolicy: {
* retentionPeriod: 15780000 // 6 months in seconds.
* }
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // Enable versioning on a new bucket.
* //-
* const metadata = {
* versioning: {
* enabled: true
* }
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.createBucket('new-bucket').then(function(data) {
* const bucket = data[0];
* const apiResponse = data[1];
* });
*
* ```
* @example <caption>include:samples/buckets.js</caption>
* region_tag:storage_create_bucket
* Another example:
*/
createBucket(
name: string,
metadataOrCallback?: BucketCallback | CreateBucketRequest,
callback?: BucketCallback
): Promise<CreateBucketResponse> | void {
if (!name) {
throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE);
}
let metadata: CreateBucketRequest;
if (!callback) {
callback = metadataOrCallback as BucketCallback;
metadata = {};
} else {
metadata = metadataOrCallback as CreateBucketRequest;
}
const body = Object.assign({}, metadata, {name}) as {} as {
[index: string]: string | {};
};
const storageClasses = {
archive: 'ARCHIVE',
coldline: 'COLDLINE',
dra: 'DURABLE_REDUCED_AVAILABILITY',
multiRegional: 'MULTI_REGIONAL',
nearline: 'NEARLINE',
regional: 'REGIONAL',
standard: 'STANDARD',
} as {[index: string]: string};
Object.keys(storageClasses).forEach(storageClass => {
if (body[storageClass]) {
if (metadata.storageClass && metadata.storageClass !== storageClass) {
throw new Error(
`Both \`${storageClass}\` and \`storageClass\` were provided.`
);
}
body.storageClass = storageClasses[storageClass];
delete body[storageClass];
}
});
if (body.requesterPays) {
body.billing = {
requesterPays: body.requesterPays,
};
delete body.requesterPays;
}
const query = {
project: this.projectId,
} as CreateBucketQuery;
if (body.userProject) {
query.userProject = body.userProject as string;
delete body.userProject;
}
this.request(
{
method: 'POST',
uri: '/b',
qs: query,
json: body,
},
(err, resp) => {
if (err) {
callback!(err, null, resp);
return;
}
const bucket = this.bucket(name);
bucket.metadata = resp;
callback!(null, bucket, resp);
}
);
}
createHmacKey(
serviceAccountEmail: string,
options?: CreateHmacKeyOptions
): Promise<CreateHmacKeyResponse>;
createHmacKey(
serviceAccountEmail: string,
callback: CreateHmacKeyCallback
): void;
createHmacKey(
serviceAccountEmail: string,
options: CreateHmacKeyOptions,
callback: CreateHmacKeyCallback
): void;
/**
* @typedef {object} CreateHmacKeyOptions
* @property {string} [projectId] The project ID of the project that owns
* the service account of the requested HMAC key. If not provided,
* the project ID used to instantiate the Storage client will be used.
* @property {string} [userProject] This parameter is currently ignored.
*/
/**
* @typedef {object} HmacKeyMetadata
* @property {string} accessId The access id identifies which HMAC key was
* used to sign a request when authenticating with HMAC.
* @property {string} etag Used to perform a read-modify-write of the key.
* @property {string} id The resource name of the HMAC key.
* @property {string} projectId The project ID.
* @property {string} serviceAccountEmail The service account's email this
* HMAC key is created for.
* @property {string} state The state of this HMAC key. One of "ACTIVE",
* "INACTIVE" or "DELETED".
* @property {string} timeCreated The creation time of the HMAC key in
* RFC 3339 format.
* @property {string} [updated] The time this HMAC key was last updated in
* RFC 3339 format.
*/
/**
* @typedef {array} CreateHmacKeyResponse
* @property {HmacKey} 0 The HmacKey instance created from API response.
* @property {string} 1 The HMAC key's secret used to access the XML API.
* @property {object} 3 The raw API response.
*/
/**
* @callback CreateHmacKeyCallback Callback function.
* @param {?Error} err Request error, if any.
* @param {HmacKey} hmacKey The HmacKey instance created from API response.
* @param {string} secret The HMAC key's secret used to access the XML API.
* @param {object} apiResponse The raw API response.
*/
/**
* Create an HMAC key associated with an service account to authenticate
* requests to the Cloud Storage XML API.
*
* See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation}
*
* @param {string} serviceAccountEmail The service account's email address
* with which the HMAC key is created for.
* @param {CreateHmacKeyCallback} [callback] Callback function.
* @return {Promise<CreateHmacKeyResponse>}
*
* @example
* ```
* const {Storage} = require('google-cloud/storage');
* const storage = new Storage();
*
* // Replace with your service account's email address
* const serviceAccountEmail =