forked from googleapis/google-cloud-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.h
3923 lines (3776 loc) · 173 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
//
// https://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/storage/hmac_key_metadata.h"
#include "google/cloud/storage/internal/policy_document_request.h"
#include "google/cloud/storage/internal/request_project_id.h"
#include "google/cloud/storage/internal/signed_url_requests.h"
#include "google/cloud/storage/internal/storage_connection.h"
#include "google/cloud/storage/internal/tuple_filter.h"
#include "google/cloud/storage/list_buckets_reader.h"
#include "google/cloud/storage/list_hmac_keys_reader.h"
#include "google/cloud/storage/list_objects_and_prefixes_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"
#include "google/cloud/storage/version.h"
#include "google/cloud/internal/group_options.h"
#include "google/cloud/internal/throw_delegate.h"
#include "google/cloud/options.h"
#include "google/cloud/status.h"
#include "google/cloud/status_or.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/string_view.h"
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
class NonResumableParallelUploadState;
class ResumableParallelUploadState;
struct ClientImplDetails;
} // namespace internal
/**
* 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 bookkeeping 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 Connection Pool
* By default this class uses HTTPS to communicate with the service. Creating a
* new HTTPS session is relatively expensive, as it must go through the TCP/IP
* and SSL handshakes. To minimize this overhead the class maintains a
* connection pool to the service. After each request completes the connection
* is returned to the pool, and reused in future requests. Note that for
* downloads (implemented by the ReadObject() member function) the connection
* remains in use until the download completes. Therefore, having multiple
* downloads open at the same time requires multiple connections.
*
* The application can limit the maximum size of this connection pool using
* `storage::ConnectionPoolSizeOption`. If returning a connection to the pool
* would make the pool larger than this limit then the oldest connection in the
* pool is closed (recall that all connections in the pool are inactive). Note
* that this is the maximum size of the pool, the client library does not create
* connections until needed.
*
* Note that the application may (at times) use more connections than the
* maximum size of the pool. For example if N downloads are in progress the
* library may need N connections, even if the pool size is smaller.
*
* Two clients that compare equal share the same connection pool. Two clients
* created with the default constructor or with the constructor from a
* `google::cloud::Options` are never equal and do not share connection pools.
* Clients created via copy (or move) construction compare equal and share the
* connection pool.
*
* @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). Note that a default-constructed client uses the ADCs:
*
* @snippet storage_client_initialization_samples.cc default-client
*
* Finding or loading the ADCs can fail. This will result in run-time errors
* when making requests.
*
* If you prefer to explicitly load the ADCs use:
*
* @snippet storage_client_initialization_samples.cc explicit-adcs
*
* To load a service account credentials key file use:
*
* @snippet storage_client_initialization_samples.cc service-account-keyfile
*
* Other credential types are available, including:
*
* - `google::cloud::MakeInsecureCredentials()` for anonymous access to public
* GCS buckets or objects.
* - `google::cloud::MakeAccessTokenCredentials()` to use an access token
* obtained through any out-of-band mechanism.
* - `google::cloud::MakeImpersonateServiceAccountCredentials()` to use the IAM
* credentials service and [impersonate a service account].
* - `google::cloud::MakeServiceAccountCredentials()` to use a service account
* key file.
*
* [impersonate service account]:
* https://cloud.google.com/iam/docs/impersonating-service-accounts
*
* @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::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 Optional Request Options
* Most of the member functions in this class can receive optional request
* options. For example, the default when reading multi-version objects is to
* retrieve the latest version:
*
* @code
* auto stream = gcs.ReadObject("my-bucket", "my-object");
* @endcode
*
* Some applications may want to retrieve specific versions. In this case
* just provide the `Generation` request option:
*
* @code
* auto stream = gcs.ReadObject(
* "my-bucket", "my-object", gcs::Generation(generation));
* @endcode
*
* Each function documents the types accepted as optional request options. These
* parameters can be specified in any order. Specifying a request option that is
* not applicable to a member function results in a compile-time error.
*
* All operations support the following common request options:
*
* - `Fields`: return a [partial response], which includes only the desired
* fields.
* - `QuotaUser`: attribute the request to this specific label for quota
* purposes.
* - `UserProject`: change the request costs (if applicable) to this GCP
* project.
* - `CustomHeader`: include a custom header with the request. These are
* typically used for testing, though they are sometimes helpful if
* environments where HTTPS traffic is mediated by a proxy.
* - `IfMatchEtag`: a pre-condition, the operation succeeds only if the resource
* ETag matches. Typically used in OCC loops ("change X only if its Etag is
* still Y"). Note that GCS sometimes ignores this header, we recommend you
* use the GCS specific pre-conditions (e.g., `IfGenerationMatch`,
* `IfMetagenerationMatch` and their `*NotMatch` counterparts) instead.
* - `IfNoneMatchEtag`: a pre-condition, abort the operation if the resource
* ETag has not changed. Typically used in caching ("return the contents of X
* only if the Etag is different from the last value I got, which was Y").
* Note that GCS sometimes ignores this header, we recommend you use the GCS
* specific pre-conditions (e.g., `IfGenerationMatch`, `IfMetagenerationMatch`
* and their `*NotMatch` counterparts) instead.
* - `UserIp`: attribute the request to this specific IP address for quota
* purpose. Not recommended, prefer `QuotaUser` instead.
*
* [partial response]:
* https://cloud.google.com/storage/docs/json_api#partial-response
*
* @par Per-operation Overrides
*
* In addition to the request options, which are passed on to the service to
* modify the request, you can specify options that override the local behavior
* of the library. For example, you can override the local retry policy:
*
* @snippet storage_client_per_operation_samples.cc change-retry-policy
*
* @par Retry, Backoff, and Idempotency Policies
*
* The library automatically retries requests that fail with transient errors,
* and follows the [recommended practice][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.
*
* [exponential-backoff]:
* https://cloud.google.com/storage/docs/exponential-backoff
*
* @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::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:
/**
* Build a new client.
*
* @param opts the configuration parameters for the `Client`.
*
* @see #ClientOptionList for a list of useful options.
*
* @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
*
* @par Change Credentials Example
* @snippet storage_client_initialization_samples.cc service-account-keyfile
*/
explicit Client(Options opts = {});
/// @name Equality
///@{
friend bool operator==(Client const& a, Client const& b) {
return a.connection_ == b.connection_;
}
friend bool operator!=(Client const& a, Client const& b) { return !(a == b); }
///@}
/**
* @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`,
* `Projection`, and `UserProject`. `OverrideDefaultProject` is accepted,
* but has no effect.
*
* @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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::ListBucketsRequest request(project_id);
request.set_multiple_options(std::forward<Options>(options)...);
auto& client = connection_;
return google::cloud::internal::MakePaginationRange<ListBucketsReader>(
request,
[client](internal::ListBucketsRequest const& r) {
return client->ListBuckets(r);
},
[](internal::ListBucketsResponse r) { return std::move(r.items); });
}
/**
* Fetches the list of buckets for the default project.
*
* This function will return an error if it cannot determine the "default"
* project. The default project is found by looking, in order, for:
* - Any parameters of type `OverrideDefaultProject`, with a value.
* - Any `google::cloud::storage::ProjectIdOption` value in any parameters of
* type `google::cloud::Options{}`.
* - Any `google::cloud::storage::ProjectIdOption` value provided in the
* `google::cloud::Options{}` passed to the constructor.
* - The value from the `GOOGLE_CLOUD_PROJECT` environment variable.
*
* @param options a list of optional query parameters and/or request headers.
* Valid types for this operation include `MaxResults`, `Prefix`,
* `Projection`, `UserProject`, and `OverrideDefaultProject`.
*
* @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 opts = SpanOptions(std::forward<Options>(options)...);
auto project_id = storage_internal::RequestProjectId(
GCP_ERROR_INFO(), opts, std::forward<Options>(options)...);
if (!project_id) {
return google::cloud::internal::MakeErrorPaginationRange<
ListBucketsReader>(std::move(project_id).status());
}
google::cloud::internal::OptionsSpan const span(std::move(opts));
return ListBucketsForProject(*std::move(project_id),
std::forward<Options>(options)...);
}
/**
* Creates a new Google Cloud Storage bucket using the default project.
*
* This function will return an error if it cannot determine the "default"
* project. The default project is found by looking, in order, for:
* - Any parameters of type `OverrideDefaultProject`, with a value.
* - Any `google::cloud::storage::ProjectIdOption` value in any parameters of
* type `google::cloud::Options{}`.
* - Any `google::cloud::storage::ProjectIdOption` value provided in the
* `google::cloud::Options{}` passed to the constructor.
* - The value from the `GOOGLE_CLOUD_PROJECT` environment variable.
*
* @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 `EnableObjectRetention`,
* `PredefinedAcl`, `PredefinedDefaultObjectAcl`, `Projection`,
* `UserProject`, and `OverrideDefaultProject`.
*
* @par Idempotency
* This operation is always idempotent. It fails if the bucket already exists.
*
* @par Example
* @snippet storage_bucket_samples.cc create bucket
*
* @see Before enabling Uniform Bucket Level Access please review the
* [feature documentation][ubla-link], as well as
* ["Should you use uniform bucket-level access ?"][ubla-should-link].
*
* [ubla-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access
* [ubla-should-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use
*/
template <typename... Options>
StatusOr<BucketMetadata> CreateBucket(std::string bucket_name,
BucketMetadata metadata,
Options&&... options) {
auto opts = SpanOptions(std::forward<Options>(options)...);
auto project_id = storage_internal::RequestProjectId(
GCP_ERROR_INFO(), opts, std::forward<Options>(options)...);
if (!project_id) return std::move(project_id).status();
google::cloud::internal::OptionsSpan const span(std::move(opts));
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 connection_->CreateBucket(request);
}
/**
* 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 `EnableObjectRetention`,
* `PredefinedAcl`, `PredefinedDefaultObjectAcl`, `Projection`, and
* `UserProject`. The function also accepts `OverrideDefaultProject`, but
* this option has no effect.
*
* @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
*
* @see Before enabling Uniform Bucket Level Access please review the
* [feature documentation][ubla-link], as well as
* ["Should you use uniform bucket-level access ?"][ubla-should-link].
*
* [ubla-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access
* [ubla-should-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use
*/
template <typename... Options>
StatusOr<BucketMetadata> CreateBucketForProject(std::string bucket_name,
std::string project_id,
BucketMetadata metadata,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<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 connection_->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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::GetBucketMetadataRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::DeleteBucketRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->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 Example
* @snippet storage_bucket_samples.cc update bucket
*
* @see Before enabling Uniform Bucket Level Access please review the
* [feature documentation][ubla-link], as well as
* ["Should you use uniform bucket-level access ?"][ubla-should-link].
*
* [ubla-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access
* [ubla-should-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use
*/
template <typename... Options>
StatusOr<BucketMetadata> UpdateBucket(std::string bucket_name,
BucketMetadata metadata,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
metadata.set_name(std::move(bucket_name));
internal::UpdateBucketRequest request(std::move(metadata));
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->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`, `PredefinedAcl`,
* `PredefinedDefaultObjectAcl`, `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
*
* @see Before enabling Uniform Bucket Level Access please review the
* [feature documentation][ubla-link], as well as
* ["Should you use uniform bucket-level access?"][ubla-should-link].
*
* [ubla-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access
* [ubla-should-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use
*/
template <typename... Options>
StatusOr<BucketMetadata> PatchBucket(std::string bucket_name,
BucketMetadata const& original,
BucketMetadata const& updated,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::PatchBucketRequest request(std::move(bucket_name), original,
updated);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->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`, `PredefinedAcl`,
* `PredefinedDefaultObjectAcl`, `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
*
* @see Before enabling Uniform Bucket Level Access please review the
* [feature documentation][ubla-link], as well as
* ["Should you use uniform bucket-level access ?"][ubla-should-link].
*
* [ubla-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access
* [ubla-should-link]:
* https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use
*/
template <typename... Options>
StatusOr<BucketMetadata> PatchBucket(
std::string bucket_name, BucketMetadataPatchBuilder const& builder,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::PatchBucketRequest request(std::move(bucket_name), builder);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->PatchBucket(request);
}
/**
* Fetches the native
* [IAM policy](@ref google::cloud::storage::NativeIamPolicy) 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 native get bucket iam policy
*
* @see #google::cloud::storage::NativeIamPolicy for details about the
* `NativeIamPolicy` class.
*/
template <typename... Options>
StatusOr<NativeIamPolicy> GetNativeBucketIamPolicy(
std::string const& bucket_name, Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::GetBucketIamPolicyRequest request(bucket_name);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->GetNativeBucketIamPolicy(request);
}
/**
* Sets the native
* [IAM Policy](@ref google::cloud::storage::NativeIamPolicy) 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 `GetNativeBucketIamPolicy()` to fetch the current value and ETag
* before calling `SetNativeBucketIamPolicy()`. Applications should use
* optimistic concurrency control techniques to retry changes in case some
* other application modified the IAM policy between the
* `GetNativeBucketIamPolicy` and `SetNativeBucketIamPolicy` 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 native add bucket iam member
*
* @par Example: removing a IAM member
* @snippet storage_bucket_iam_samples.cc native remove bucket iam member
*
* @see #google::cloud::storage::NativeIamPolicy for details about the
* `NativeIamPolicy` class.
*/
template <typename... Options>
StatusOr<NativeIamPolicy> SetNativeBucketIamPolicy(
std::string const& bucket_name, NativeIamPolicy const& iam_policy,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::SetNativeBucketIamPolicyRequest request(bucket_name, iam_policy);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->SetNativeBucketIamPolicy(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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::TestBucketIamPermissionsRequest request(std::move(bucket_name),
std::move(permissions));
request.set_multiple_options(std::forward<Options>(options)...);
auto result = connection_->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_retention_policy_samples.cc lock retention policy
*
* @par Example: get the current retention policy
* @snippet storage_retention_policy_samples.cc get retention policy
*
* @par Example: set the current retention policy
* @snippet storage_retention_policy_samples.cc set retention policy
*
* @par Example: remove the retention policy
* @snippet storage_retention_policy_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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::LockBucketRetentionPolicyRequest request(bucket_name,
metageneration);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->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.
*
* If you need to perform larger uploads or uploads where the data is not
* contiguous in memory, use `WriteObject()`. This function always performs a
* single-shot upload, while `WriteObject()` always uses resumable uploads.
* The [service documentation] has recommendations on the upload size vs.
* single-shot or resumable uploads.
*
* @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
*
* [service documentation]:
* https://cloud.google.com/storage/docs/uploads-downloads#size
*/
template <typename... Options>
StatusOr<ObjectMetadata> InsertObject(std::string const& bucket_name,
std::string const& object_name,
absl::string_view contents,
Options&&... options) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<Options>(options)...));
internal::InsertObjectMediaRequest request(bucket_name, object_name,
contents);
request.set_multiple_options(std::forward<Options>(options)...);
return connection_->InsertObjectMedia(request);
}
/// @overload InsertObject(std::string const& bucket_name, std::string const& object_name, absl::string_view contents, Options&&... options)
template <typename... Options>
StatusOr<ObjectMetadata> InsertObject(std::string const& bucket_name,
std::string const& object_name,
std::string const& contents,
Options&&... options) {
return InsertObject(bucket_name, object_name, absl::string_view(contents),
std::forward<Options>(options)...);
}
/// @overload InsertObject(std::string const& bucket_name, std::string const& object_name, absl::string_view contents, Options&&... options)
template <typename... Options>
StatusOr<ObjectMetadata> InsertObject(std::string const& bucket_name,
std::string const& object_name,
char const* contents,
Options&&... options) {
auto c =
contents == nullptr ? absl::string_view{} : absl::string_view{contents};
return InsertObject(bucket_name, object_name, c,
std::forward<Options>(options)...);
}
/**
* 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 `DestinationKmsKeyName`,
* `DestinationPredefinedAcl`,`EncryptionKey`,`IfGenerationMatch`,
* `IfGenerationNotMatch`, `IfMetagenerationMatch`,
* `IfMetagenerationNotMatch`, `IfSourceGenerationMatch`,
* `IfSourceGenerationNotMatch`, `IfSourceMetagenerationMatch`,
* `IfSourceMetagenerationNotMatch`, `Projection`, `SourceGeneration`,
* `SourceEncryptionKey`, `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_csek_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) {
google::cloud::internal::OptionsSpan const span(
SpanOptions(std::forward<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 connection_->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`, `SoftDeleted`, `Projection`, and
* `UserProject`.
*
* @par Idempotency
* This is a read-only operation and is always idempotent.