-
Notifications
You must be signed in to change notification settings - Fork 374
/
client.h
2807 lines (2722 loc) · 123 KB
/
client.h
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 2018 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.
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_CLIENT_H_
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_CLIENT_H_
#include "google/cloud/internal/disjunction.h"
#include "google/cloud/internal/throw_delegate.h"
#include "google/cloud/status.h"
#include "google/cloud/status_or.h"
#include "google/cloud/storage/hmac_key_metadata.h"
#include "google/cloud/storage/internal/logging_client.h"
#include "google/cloud/storage/internal/retry_client.h"
#include "google/cloud/storage/internal/signed_url_requests.h"
#include "google/cloud/storage/list_buckets_reader.h"
#include "google/cloud/storage/list_hmac_keys_reader.h"
#include "google/cloud/storage/list_objects_reader.h"
#include "google/cloud/storage/notification_event_type.h"
#include "google/cloud/storage/notification_payload_format.h"
#include "google/cloud/storage/oauth2/google_credentials.h"
#include "google/cloud/storage/object_rewriter.h"
#include "google/cloud/storage/object_stream.h"
#include "google/cloud/storage/retry_policy.h"
#include "google/cloud/storage/upload_options.h"
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
/**
* The Google Cloud Storage (GCS) Client.
*
* This is the main class to interact with GCS. It provides member functions to
* invoke all the APIs in the service.
*
* @par Performance
* Creating an object of this type is a relatively low-cost operation.
* Connections to the service are created on demand. Copy-assignment and
* copy-construction are also relatively low-cost operations, they should be
* comparable to copying a few shared pointers. The first request (or any
* request that requires a new connection) incurs the cost of creating the
* connection and authenticating with the service. Note that the library may
* need to perform other bookeeping operations that may impact performance.
* For example, access tokens need to be refreshed from time to time, and this
* may impact the performance of some operations.
*
* @par Thread-safety
* Instances of this class created via copy-construction or copy-assignment
* share the underlying pool of connections. Access to these copies via multiple
* threads is guaranteed to work. Two threads operating on the same instance of
* this class is not guaranteed to work.
*
* @par Credentials
* The default approach for creating a Client uses Google Application Default
* %Credentials (ADCs). Because finding or loading ADCs can fail, the returned
* `StatusOr<Client>` from `CreateDefaultClient()` should be verified before
* using it. However, explicitly passing `Credentials` when creating a Client
* does not have the same potential to fail, so the resulting `Client` is not
* wrapped in a `StatusOr`. If you wish to use `AnonymousCredentials` or to
* supply a specific `Credentials` type, you can use the functions declared in
* google_credentials.h:
* @code
* namespace gcs = google::cloud::storage;
*
* // Implicitly use ADCs:
* StatusOr<gcs::Client> client = gcs::Client::CreateDefaultClient();
* if (!client) {
* // Handle failure and return.
* }
*
* // Or explicitly use ADCs:
* auto creds = gcs::oauth2::GoogleDefaultCredentials();
* if (!creds) {
* // Handle failure and return.
* }
* // Status was OK, so create a Client with the given Credentials.
* gcs::Client client(gcs::ClientOptions(*creds));
*
* // Use service account credentials from a JSON keyfile:
* std::string path = "/path/to/keyfile.json";
* auto creds =
* gcs::oauth2::CreateServiceAccountCredentialsFromJsonFilePath(path);
* if (!creds) {
* // Handle failure and return.
* }
* gcs::Client client(gcs::ClientOptions(*creds));
*
* // Use Compute Engine credentials for the instance's default service account.
* gcs::Client client(
* gcs::ClientOptions(gcs::oauth2::CreateComputeEngineCredentials()));
*
* // Use no credentials:
* gcs::Client client(
* gcs::ClientOptions(gcs::oauth2::CreateAnonymousCredentials()));
* @endcode
*
* @par Error Handling
* This class uses `StatusOr<T>` to report errors. When an operation fails to
* perform its work the returned `StatusOr<T>` contains the error details. If
* the `ok()` member function in the `StatusOr<T>` returns `true` then it
* contains the expected result. Please consult the
* [`StatusOr<T>` documentation](#google::cloud::v0::StatusOr) for more details.
*
* @code
* namespace gcs = google::cloud::storage;
* gcs::Client client = ...;
* google::cloud::StatusOr<gcs::BucketMetadata> bucket_metadata =
* client.GetBucketMetadata("my-bucket");
*
* if (!bucket_metadata) {
* std::cerr << "Error getting metadata for my-bucket: "
* << bucket_metadata.status() << "\n";
* return;
* }
*
* // Use bucket_metadata as a smart pointer here, e.g.:
* std::cout << "The generation for " << bucket_metadata->name() " is "
* << bucket_metadata->generation() << "\n";
* @endcode
*
* In addition, the @ref index "main page" contains examples using `StatusOr<T>`
* to handle errors.
*
* @par Retry, Backoff, and Idempotency Policies
*
* The library automatically retries requests that fail with transient errors,
* and follows the
* [recommended
* practice](https://cloud.google.com/storage/docs/exponential-backoff) to
* backoff between retries.
*
* The default policies are to continue retrying for up to 15 minutes, and to
* use truncated (at 5 minutes) exponential backoff, doubling the maximum
* backoff period between retries. Likewise, the idempotency policy is
* configured to retry all operations.
*
* The application can override these policies when constructing objects of this
* class. The documentation for the constructors show examples of this in
* action.
*
* @see https://cloud.google.com/storage/ for an overview of GCS.
*
* @see https://cloud.google.com/storage/docs/key-terms for an introduction of
* the key terms used in GCS.
*
* @see https://cloud.google.com/storage/docs/json_api/ for an overview of the
* underlying API.
*
* @see https://cloud.google.com/docs/authentication/production for details
* about Application Default %Credentials.
*
* @see #google::cloud::v0::StatusOr.
*
* @see `LimitedTimeRetryPolicy` and `LimitedErrorCountRetryPolicy` for
* alternative retry policies.
*
* @see `ExponentialBackoffPolicy` to configure different parameters for the
* exponential backoff policy.
*
* @see `AlwaysRetryIdempotencyPolicy` and `StrictIdempotencyPolicy` for
* alternative idempotency policies.
*/
class Client {
public:
/**
* Creates the default client type given the options.
*
* @param options the client options, these are used to control credentials,
* buffer sizes, etc.
* @param policies the client policies, these control the behavior of the
* client, for example, how to backoff when an operation needs to be
* retried, or what operations cannot be retried because they are not
* idempotent.
*
* @par Idempotency Policy Example
* @snippet storage_object_samples.cc insert object strict idempotency
*
* @par Modified Retry Policy Example
* @snippet storage_object_samples.cc insert object modified retry
*/
template <typename... Policies>
explicit Client(ClientOptions options, Policies&&... policies)
: Client(CreateDefaultInternalClient(std::move(options)),
std::forward<Policies>(policies)...) {}
/**
* Creates the default client type given the credentials and policies.
*
* @param credentials a set of credentials to initialize the `ClientOptions`.
* @param policies the client policies, these control the behavior of the
* client, for example, how to backoff when an operation needs to be
* retried, or what operations cannot be retried because they are not
* idempotent.
*
* @par Idempotency Policy Example
* @snippet storage_object_samples.cc insert object strict idempotency
*
* @par Modified Retry Policy Example
* @snippet storage_object_samples.cc insert object modified retry
*/
template <typename... Policies>
explicit Client(std::shared_ptr<oauth2::Credentials> credentials,
Policies&&... policies)
: Client(ClientOptions(std::move(credentials)),
std::forward<Policies>(policies)...) {}
/// Builds a client and maybe override the retry, idempotency, and/or backoff
/// policies.
template <typename... Policies>
explicit Client(std::shared_ptr<internal::RawClient> client,
Policies&&... policies)
: raw_client_(
Decorate(std::move(client), std::forward<Policies>(policies)...)) {}
/// Define a tag to disable automatic decorations of the RawClient.
struct NoDecorations {};
/// Builds a client with a specific RawClient, without decorations.
explicit Client(std::shared_ptr<internal::RawClient> client, NoDecorations)
: raw_client_(std::move(client)) {}
/// Create a Client using ClientOptions::CreateDefaultClientOptions().
static StatusOr<Client> CreateDefaultClient();
/// Access the underlying `RawClient`.
std::shared_ptr<internal::RawClient> raw_client() const {
return raw_client_;
}
//@{
/**
* @name Bucket operations.
*
* Buckets are the basic containers that hold your data. Everything that you
* store in GCS must be contained in a bucket. You can use buckets to organize
* your data and control access to your data, but unlike directories and
* folders, you cannot nest buckets.
*
* @see https://cloud.google.com/storage/docs/key-terms#buckets for more
* information about GCS buckets.
*/
/**
* Fetches the list of buckets for a given project.
*
* @param project_id the project to query.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `MaxResults`, `Prefix`,
* `UserProject`, and `Projection`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_samples.cc list buckets for project
*/
template <typename... Options>
ListBucketsReader ListBucketsForProject(std::string const& project_id,
Options&&... options) {
internal::ListBucketsRequest request(project_id);
request.set_multiple_options(std::forward<Options>(options)...);
auto client = raw_client_;
return ListBucketsReader(request,
[client](internal::ListBucketsRequest const& r) {
return client->ListBuckets(r);
});
}
/**
* Fetches the list of buckets for the default project.
*
* The default project is required to be configured in the `ClientOptions`
* used to construct this object. If the application does not set the project
* id in the `ClientOptions`, the value of the `GOOGLE_CLOUD_PROJECT` is
* used. If neither the environment variable is set, nor a value is set
* explicitly by the application, the returned `ListBucketsReader` will
* return an error status when used.
*
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `MaxResults`, `Prefix`,
* `UserProject`, and `Projection`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_samples.cc list buckets
*/
template <typename... Options>
ListBucketsReader ListBuckets(Options&&... options) {
auto const& project_id = raw_client_->client_options().project_id();
return ListBucketsForProject(project_id, std::forward<Options>(options)...);
}
/**
* Creates a new Google Cloud Storage bucket using the default project. If
* the default project is not configured the server will reject the request,
* and this function returns the error status.
*
* @param bucket_name the name of the new bucket.
* @param metadata the metadata for the new Bucket. The `name` field is
* ignored in favor of @p bucket_name.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `PredefinedAcl`,
* `PredefinedDefaultObjectAcl`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This operation is always idempotent. It fails if the bucket already exists.
*
* @par Example
* @snippet storage_bucket_samples.cc create bucket
*/
template <typename... Options>
StatusOr<BucketMetadata> CreateBucket(std::string bucket_name,
BucketMetadata metadata,
Options&&... options) {
auto const& project_id = raw_client_->client_options().project_id();
return CreateBucketForProject(std::move(bucket_name), project_id,
std::move(metadata),
std::forward<Options>(options)...);
}
/**
* Creates a new Google Cloud Storage Bucket in a given project.
*
* @param bucket_name the name of the new bucket.
* @param project_id the id of the project that will host the new bucket.
* @param metadata the metadata for the new Bucket. The `name` field is
* ignored in favor of @p bucket_name.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `PredefinedAcl`,
* `PredefinedDefaultObjectAcl`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This operation is always idempotent. It fails if the bucket already exists.
*
* @par Example
* @snippet storage_bucket_samples.cc create bucket for project
*/
template <typename... Options>
StatusOr<BucketMetadata> CreateBucketForProject(std::string bucket_name,
std::string project_id,
BucketMetadata metadata,
Options&&... options) {
metadata.set_name(std::move(bucket_name));
internal::CreateBucketRequest request(std::move(project_id),
std::move(metadata));
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->CreateBucket(request);
}
/**
* Fetches the bucket metadata.
*
* @param bucket_name query metadata information about this bucket.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `UserProject`, and `Projection`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_samples.cc get bucket metadata
*/
template <typename... Options>
StatusOr<BucketMetadata> GetBucketMetadata(std::string const& bucket_name,
Options&&... options) {
internal::GetBucketMetadataRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->GetBucketMetadata(request);
}
/**
* Deletes a Google Cloud Storage Bucket.
*
* @param bucket_name the bucket to be deleted.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, and `UserProject`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfMetagenerationMatch`.
*
* @par Example
* @snippet storage_bucket_samples.cc delete bucket
*/
template <typename... Options>
Status DeleteBucket(std::string const& bucket_name, Options&&... options) {
internal::DeleteBucketRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->DeleteBucket(request).status();
}
/**
* Updates the metadata in a Google Cloud Storage Bucket.
*
* A `Buckets: update` request changes *all* the writeable attributes of a
* bucket, in contrast, a `Buckets: patch` request only changes the subset of
* the attributes included in the request. This function creates a
* `Buckets: update` request to change the writable attributes in
* `BucketMetadata`.
*
* @param bucket_name the name of the new bucket.
* @param metadata the new metadata for the Bucket. The `name` field is
* ignored in favor of @p bucket_name.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `PredefinedAcl`,
* `PredefinedDefaultObjectAcl`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case,`IfMetagenerationMatch`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_samples.cc update bucket
*/
template <typename... Options>
StatusOr<BucketMetadata> UpdateBucket(std::string bucket_name,
BucketMetadata metadata,
Options&&... options) {
metadata.set_name(std::move(bucket_name));
internal::UpdateBucketRequest request(std::move(metadata));
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->UpdateBucket(request);
}
/**
* Computes the difference between two BucketMetadata objects and patches a
* bucket based on that difference.
*
* A `Buckets: update` request changes *all* the writeable attributes of a
* bucket, in contrast, a `Buckets: patch` request only changes the subset of
* the attributes included in the request.
*
* This function creates a patch request to change the writeable attributes in
* @p original to the values in @p updated. Non-writeable attributes are
* ignored, and attributes not present in @p updated are removed. Typically
* this function is used after the application obtained a value with
* `GetBucketMetadata` and has modified these parameters.
*
* @param bucket_name the bucket to be updated.
* @param original the initial value of the bucket metadata.
* @param updated the updated value for the bucket metadata.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfMetagenerationMatch`.
*
* @par Example
* @snippet storage_bucket_samples.cc patch bucket storage class
*/
template <typename... Options>
StatusOr<BucketMetadata> PatchBucket(std::string bucket_name,
BucketMetadata const& original,
BucketMetadata const& updated,
Options&&... options) {
internal::PatchBucketRequest request(std::move(bucket_name), original,
updated);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->PatchBucket(request);
}
/**
* Patches the metadata in a Google Cloud Storage Bucket given a desired set
* changes.
*
* A `Buckets: update` request changes *all* the writeable attributes of a
* bucket, in contrast, a `Buckets: patch` request only changes the subset of
* the attributes included in the request. This function creates a patch
* request based on the given `BucketMetadataPatchBuilder` which represents
* the desired set of changes.
*
* @param bucket_name the bucket to be updated.
* @param builder the set of updates to perform in the Bucket.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfMetagenerationMatch`.
*
* @par Example
* @snippet storage_bucket_samples.cc patch bucket storage class with builder
*/
template <typename... Options>
StatusOr<BucketMetadata> PatchBucket(
std::string bucket_name, BucketMetadataPatchBuilder const& builder,
Options&&... options) {
internal::PatchBucketRequest request(std::move(bucket_name), builder);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->PatchBucket(request);
}
/**
* Fetches the [IAM policy](@ref google::cloud::v0::IamPolicy) for a Bucket.
*
* Google Cloud Identity & Access Management (IAM) lets administrators
* authorize who can take action on specific resources, including Google
* Cloud Storage Buckets. This operation allows you to query the IAM policies
* for a Bucket. IAM policies are a superset of the Bucket ACL, changes
* to the Bucket ACL are reflected in the IAM policy, and vice-versa. The
* documentation describes
* [the
* mapping](https://cloud.google.com/storage/docs/access-control/iam#acls)
* between legacy Bucket ACLs and IAM policies.
*
* Consult
* [the
* documentation](https://cloud.google.com/storage/docs/access-control/iam)
* for a more detailed description of IAM policies and their use in
* Google Cloud Storage.
*
* @param bucket_name query metadata information about this bucket.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `UserProject`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_iam_samples.cc get bucket iam policy
*
* @see #google::cloud::v0::IamPolicy for details about the `IamPolicy` class.
*/
template <typename... Options>
StatusOr<IamPolicy> GetBucketIamPolicy(std::string const& bucket_name,
Options&&... options) {
internal::GetBucketIamPolicyRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->GetBucketIamPolicy(request);
}
/**
* Sets the [IAM Policy](@ref google::cloud::v0::IamPolicy) for a Bucket.
*
* Google Cloud Identity & Access Management (IAM) lets administrators
* authorize who can take action on specific resources, including Google
* Cloud Storage Buckets. This operation allows you to set the IAM policies
* for a Bucket. IAM policies are a superset of the Bucket ACL, changes
* to the Bucket ACL are reflected in the IAM policy, and vice-versa. The
* documentation describes
* [the
* mapping](https://cloud.google.com/storage/docs/access-control/iam#acls)
* between legacy Bucket ACLs and IAM policies.
*
* Consult
* [the
* documentation](https://cloud.google.com/storage/docs/access-control/iam)
* for a more detailed description of IAM policies their use in
* Google Cloud Storage.
*
* @note The server rejects requests where the ETag value of the policy does
* not match the current ETag. Effectively this means that applications must
* use `GetBucketIamPolicy()` to fetch the current value and ETag before
* calling `SetBucketIamPolicy()`. Applications should use optimistic
* concurrency control techniques to retry changes in case some other
* application modified the IAM policy between the `GetBucketIamPolicy`
* and `SetBucketIamPolicy` calls.
*
* @param bucket_name query metadata information about this bucket.
* @param iam_policy the new IAM policy.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `UserProject`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfMetagenerationMatch`.
*
* @par Example: adding a new member
* @snippet storage_bucket_iam_samples.cc add bucket iam member
*
* @par Example: removing a IAM member
* @snippet storage_bucket_iam_samples.cc remove bucket iam member
*
* @see #google::cloud::v0::IamPolicy for details about the `IamPolicy` class.
*/
template <typename... Options>
StatusOr<IamPolicy> SetBucketIamPolicy(std::string const& bucket_name,
IamPolicy const& iam_policy,
Options&&... options) {
internal::SetBucketIamPolicyRequest request(bucket_name, iam_policy);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->SetBucketIamPolicy(request);
}
/**
* Tests the IAM permissions of the caller against a Bucket.
*
* Google Cloud Identity & Access Management (IAM) lets administrators
* authorize who can take action on specific resources, including Google
* Cloud Storage Buckets. This operation tests the permissions of the caller
* for a Bucket. You must provide a list of permissions, this API will return
* the subset of those permissions that the current caller has in the given
* Bucket.
*
* Consult
* [the
* documentation](https://cloud.google.com/storage/docs/access-control/iam)
* for a more detailed description of IAM policies their use in
* Google Cloud Storage.
*
* @param bucket_name query metadata information about this bucket.
* @param permissions the list of permissions to check.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `UserProject`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_bucket_iam_samples.cc test bucket iam permissions
*/
template <typename... Options>
StatusOr<std::vector<std::string>> TestBucketIamPermissions(
std::string bucket_name, std::vector<std::string> permissions,
Options&&... options) {
internal::TestBucketIamPermissionsRequest request(std::move(bucket_name),
std::move(permissions));
request.set_multiple_options(std::forward<Options>(options)...);
auto result = raw_client_->TestBucketIamPermissions(request);
if (!result) {
return std::move(result).status();
}
return std::move(result.value().permissions);
}
/**
* Locks the retention policy for a bucket.
*
* @warning Locking a retention policy is an irreversible action. Once locked,
* you must delete the entire bucket in order to "remove" the bucket's
* retention policy. However, before you can delete the bucket, you must
* be able to delete all the objects in the bucket, which itself is only
* possible if all the objects have reached the retention period set by
* the retention policy.
*
* The [Bucket Lock
* feature](https://cloud.google.com/storage/docs/bucket-lock) allows you to
* configure a data retention policy for a Cloud Storage bucket that governs
* how long objects in the bucket must be retained. The feature also allows
* you to lock the data retention policy, permanently preventing the policy
* from being reduced or removed.
*
* @param bucket_name the name of the bucket.
* @param metageneration the expected value of the metageneration on the
* bucket. The request will fail if the metageneration does not match the
* current value.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `UserProject`.
*
* @par Idempotency
* This operation is always idempotent because the `metageneration` parameter
* is always required, and it acts as a pre-condition on the operation.
*
* @par Example: lock the retention policy
* @snippet storage_bucket_samples.cc lock retention policy
*
* @par Example: get the current retention policy
* @snippet storage_bucket_samples.cc get retention policy
*
* @par Example: set the current retention policy
* @snippet storage_bucket_samples.cc set retention policy
*
* @par Example: remove the retention policy
* @snippet storage_bucket_samples.cc remove retention policy
*
* @see https://cloud.google.com/storage/docs/bucket-lock for a description of
* the Bucket Lock feature.
*
* @see https://cloud.google.com/storage/docs/using-bucket-lock for examples
* of how to use the Bucket Lock and retention policy features.
*/
template <typename... Options>
StatusOr<BucketMetadata> LockBucketRetentionPolicy(
std::string const& bucket_name, std::uint64_t metageneration,
Options&&... options) {
internal::LockBucketRetentionPolicyRequest request(bucket_name,
metageneration);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->LockBucketRetentionPolicy(request);
}
//@}
//@{
/**
* @name Object operations
*
* Objects are the individual pieces of data that you store in GCS. Objects
* have two components: *object data* and *object metadata*. Object data
* (sometimes referred to as *media*) is typically a file that you want
* to store in GCS. Object metadata is information that describe various
* object qualities.
*
* @see https://cloud.google.com/storage/docs/key-terms#objects for more
* information about GCS objects.
*/
/**
* Creates an object given its name and contents.
*
* @param bucket_name the name of the bucket that will contain the object.
* @param object_name the name of the object to be created.
* @param contents the contents (media) for the new object.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `ContentEncoding`,
* `ContentType`, `Crc32cChecksumValue`, `DisableCrc32cChecksum`,
* `DisableMD5Hash`, `EncryptionKey`, `IfGenerationMatch`,
* `IfGenerationNotMatch`, `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `KmsKeyName`, `MD5HashValue`,
* `PredefinedAcl`, `Projection`, `UserProject`, and `WithObjectMetadata`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfGenerationMatch`.
*
* @par Example
* @snippet storage_object_samples.cc insert object
*
* @par Example
* @snippet storage_object_samples.cc insert object multipart
*/
template <typename... Options>
StatusOr<ObjectMetadata> InsertObject(std::string const& bucket_name,
std::string const& object_name,
std::string contents,
Options&&... options) {
internal::InsertObjectMediaRequest request(bucket_name, object_name,
std::move(contents));
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->InsertObjectMedia(request);
}
/**
* Copies an existing object.
*
* Use `CopyObject` to copy between objects in the same location and storage
* class. Copying objects across locations or storage classes can fail for
* large objects and retrying the operation will not succeed.
*
* @note Prefer using `RewriteObject()` to copy objects, `RewriteObject()` can
* copy objects to different locations, with different storage class,
* and/or with different encryption keys.
*
* @param source_bucket_name the name of the bucket that contains the object
* to be copied.
* @param source_object_name the name of the object to copy.
* @param destination_bucket_name the name of the bucket that will contain the
* new object.
* @param destination_object_name the name of the new object.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `DestinationPredefinedAcl`,
* `EncryptionKey`, `IfGenerationMatch`, `IfGenerationNotMatch`,
* `IfMetagenerationMatch`, `IfMetagenerationNotMatch`,
* `IfSourceGenerationMatch`, `IfSourceGenerationNotMatch`,
* `IfSourceMetagenerationMatch`, `IfSourceMetagenerationNotMatch`,
* `Projection`, `SourceGeneration`, `UserProject`, and
* `WithObjectMetadata`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfGenerationMatch`.
*
* @par Example
* @snippet storage_object_samples.cc copy object
*
* @par Example: copy an encrypted object
* @snippet storage_object_samples.cc copy encrypted object
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/copy for
* a full description of the advantages of `Objects: rewrite` over
* `Objects: copy`.
*/
template <typename... Options>
StatusOr<ObjectMetadata> CopyObject(std::string source_bucket_name,
std::string source_object_name,
std::string destination_bucket_name,
std::string destination_object_name,
Options&&... options) {
internal::CopyObjectRequest request(
std::move(source_bucket_name), std::move(source_object_name),
std::move(destination_bucket_name), std::move(destination_object_name));
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->CopyObject(request);
}
/**
* Fetches the object metadata.
*
* @param bucket_name the bucket containing the object.
* @param object_name the object name.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `Generation`,
* `IfGenerationMatch`, `IfGenerationNotMatch`, `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `Projection`, and `UserProject`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_object_samples.cc get object metadata
*/
template <typename... Options>
StatusOr<ObjectMetadata> GetObjectMetadata(std::string const& bucket_name,
std::string const& object_name,
Options&&... options) {
internal::GetObjectMetadataRequest request(bucket_name, object_name);
request.set_multiple_options(std::forward<Options>(options)...);
return raw_client_->GetObjectMetadata(request);
}
/**
* Lists the objects in a bucket.
*
* @param bucket_name the name of the bucket to list.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include
* `IfMetagenerationMatch`, `IfMetagenerationNotMatch`, `UserProject`,
* `Projection`, `Prefix`, and `Versions`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_object_samples.cc list objects
*/
template <typename... Options>
ListObjectsReader ListObjects(std::string const& bucket_name,
Options&&... options) {
internal::ListObjectsRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
auto client = raw_client_;
return ListObjectsReader(request,
[client](internal::ListObjectsRequest const& r) {
return client->ListObjects(r);
});
}
/**
* Reads the contents of an object.
*
* Returns an object derived from `std::istream` which can be used to read the
* contents of the GCS blob. The application should check the `badbit` (e.g.
* by calling `stream.bad()`) on the returned object to detect if there was
* an error reading from the blob. If `badbit` is set, the application can
* check the `status()` variable to get details about the failure.
* Applications can also set the exception mask on the returned stream, in
* which case an exception is thrown if an error is detected.
*
* @param bucket_name the name of the bucket that contains the object.
* @param object_name the name of the object to be read.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `DisableCrc32cChecksum`,
* `DisableMD5Hash`, `IfGenerationMatch`, `EncryptionKey`, `Generation`,
* `IfGenerationMatch`, `IfGenerationNotMatch`, `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `ReadRange`, and `UserProject`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.
*
* @par Example
* @snippet storage_object_samples.cc read object
*
* @par Example
* @snippet storage_object_samples.cc read object range
*
* @par Example: read a object encrypted with a CSEK.
* @snippet storage_object_samples.cc read encrypted object
*/
template <typename... Options>
ObjectReadStream ReadObject(std::string const& bucket_name,
std::string const& object_name,
Options&&... options) {
internal::ReadObjectRangeRequest request(bucket_name, object_name);
request.set_multiple_options(std::forward<Options>(options)...);
return ObjectReadStream(raw_client_->ReadObject(request).value());
}
/**
* Writes contents into an object.
*
* This creates a `std::ostream` object to upload contents. The application
* can use either the regular `operator<<()`, or `std::ostream::write()` to
* upload data.
*
* The application can explicitly request a new resumable upload using the
* result of `#NewResumableUploadSession()`. To restore a previously created
* resumable session use `#RestoreResumableUploadSession()`.
*
* @note It is the application's responsibility to query the stream to find
* the latest committed byte and to upload data starting from the next
* byte expected by the upload session.
*
* @note Using the `WithObjectMetadata` option implicitly creates a resumable
* upload.
*
* Without resumable uploads an interrupted upload has to be restarted from
* the beginning. Therefore, applications streaming large objects should try
* to use resumable uploads, and save the session id to restore them if
* needed.
*
* Non-resumable uploads may be more efficient for small and medium sized
* uploads, as they require fewer roundtrips to the service.
*
* For small uploads we recommend using `InsertObject`, consult
* [the
* documentation](https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload)
* for details.
*
* @param bucket_name the name of the bucket that contains the object.
* @param object_name the name of the object to be read.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `ContentEncoding`, `ContentType`,
* `Crc32cChecksumValue`, `DisableCrc32cChecksum`, `DisableMD5Hash`,
* `EncryptionKey`, `IfGenerationMatch`, `IfGenerationNotMatch`,
* `IfMetagenerationMatch`, `IfMetagenerationNotMatch`, `KmsKeyName`,
* `MD5HashValue`, `PredefinedAcl`, `Projection`,
* `UseResumableUploadSession`, `UserProject`, and `WithObjectMetadata`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfGenerationMatch`.
*
* @par Example
* @snippet storage_object_samples.cc write object
*
* @par Example: write an object with a CMEK.
* @snippet storage_object_samples.cc write object with kms key
*
* @par Example: starting a resumable upload.
* @snippet storage_object_samples.cc start resumable upload
*
* @par Example: resuming a resumable upload.
* @snippet storage_object_samples.cc resume resumable upload
*/
template <typename... Options>
ObjectWriteStream WriteObject(std::string const& bucket_name,
std::string const& object_name,
Options&&... options) {
internal::InsertObjectStreamingRequest request(bucket_name, object_name);
request.set_multiple_options(std::forward<Options>(options)...);
return ObjectWriteStream(raw_client_->WriteObject(request).value());
}
/**
* Uploads a file to an object.
*
* @note
* Only regular files are supported. If you need to upload the results of
* reading a device, Named Pipe, FIFO, or other type of file system object
* that is **not** a regular file then `WriteObject()` is probably a better
* alternative.
*
* @param file_name the name of the file to be uploaded.
* @param bucket_name the name of the bucket that contains the object.
* @param object_name the name of the object to be read.
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `ContentEncoding`, `ContentType`,
* `Crc32cChecksumValue`, `DisableCrc32cChecksum`, `DisableMD5Hash`,
* `EncryptionKey`, `IfGenerationMatch`, `IfGenerationNotMatch`,
* `IfMetagenerationMatch`, `IfMetagenerationNotMatch`, `KmsKeyName`,
* `MD5HashValue`, `PredefinedAcl`, `Projection`, `UserProject`, and
* `WithObjectMetadata`.
*
* @par Idempotency
* This operation is only idempotent if restricted by pre-conditions, in this
* case, `IfGenerationMatch`.
*
* @par Example
* @snippet storage_object_samples.cc upload file
*
* @par Example: manually selecting a resumable upload
* @snippet storage_object_samples.cc upload file resumable
*/
template <typename... Options>
StatusOr<ObjectMetadata> UploadFile(std::string const& file_name,
std::string const& bucket_name,
std::string const& object_name,
Options&&... options) {
// Determine, at compile time, which version of UploadFileImpl we should
// call. This needs to be done at compile time because ObjectInsertMedia
// does not support (nor should it support) the UseResumableUploadSession