Google Cloud Storage C++ Client  1.19.0
A C++ Client Library for Google Cloud Storage
Classes | Public Member Functions | Static Public Member Functions | Friends | List of all members
google::cloud::storage::v1::Client Class Reference

The Google Cloud Storage (GCS) Client. More...

#include <google/cloud/storage/client.h>

Classes

struct  NoDecorations
 Define a tag to disable automatic decorations of the RawClient. More...
 

Public Member Functions

template<typename... Policies>
 Client (ClientOptions options, Policies &&... policies)
 Creates the default client type given the options. More...
 
template<typename... Policies>
 Client (std::shared_ptr< oauth2::Credentials > credentials, Policies &&... policies)
 Creates the default client type given the credentials and policies. More...
 
template<typename... Policies>
 Client (std::shared_ptr< internal::RawClient > client, Policies &&... policies)
 Builds a client and maybe override the retry, idempotency, and/or backoff policies. More...
 
 Client (std::shared_ptr< internal::RawClient > client, NoDecorations)
 Builds a client with a specific RawClient, without decorations. More...
 
std::shared_ptr< internal::RawClient > raw_client () const
 Access the underlying RawClient. More...
 
template<typename... Options>
StatusOr< PolicyDocumentResultCreateSignedPolicyDocument (PolicyDocument document, Options &&... options)
 Create a signed policy document. More...
 
template<typename... Options>
StatusOr< PolicyDocumentV4ResultGenerateSignedPostPolicyV4 (PolicyDocumentV4 document, Options &&... options)
 Create a signed V4 policy document. More...
 
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 also
https://cloud.google.com/storage/docs/key-terms#buckets for more information about GCS buckets.
template<typename... Options>
ListBucketsReader ListBucketsForProject (std::string const &project_id, Options &&... options)
 Fetches the list of buckets for a given project. More...
 
template<typename... Options>
ListBucketsReader ListBuckets (Options &&... options)
 Fetches the list of buckets for the default project. More...
 
template<typename... Options>
StatusOr< BucketMetadataCreateBucket (std::string bucket_name, BucketMetadata metadata, Options &&... options)
 Creates a new Google Cloud Storage bucket using the default project. More...
 
template<typename... Options>
StatusOr< BucketMetadataCreateBucketForProject (std::string bucket_name, std::string project_id, BucketMetadata metadata, Options &&... options)
 Creates a new Google Cloud Storage Bucket in a given project. More...
 
template<typename... Options>
StatusOr< BucketMetadataGetBucketMetadata (std::string const &bucket_name, Options &&... options)
 Fetches the bucket metadata. More...
 
template<typename... Options>
Status DeleteBucket (std::string const &bucket_name, Options &&... options)
 Deletes a Google Cloud Storage Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataUpdateBucket (std::string bucket_name, BucketMetadata metadata, Options &&... options)
 Updates the metadata in a Google Cloud Storage Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataPatchBucket (std::string bucket_name, BucketMetadata const &original, BucketMetadata const &updated, Options &&... options)
 Computes the difference between two BucketMetadata objects and patches a bucket based on that difference. More...
 
template<typename... Options>
StatusOr< BucketMetadataPatchBucket (std::string bucket_name, BucketMetadataPatchBuilder const &builder, Options &&... options)
 Patches the metadata in a Google Cloud Storage Bucket given a desired set changes. More...
 
template<typename... Options>
StatusOr< IamPolicy > GetBucketIamPolicy (std::string const &bucket_name, Options &&... options)
 Fetches the IAM policy for a Bucket. More...
 
template<typename... Options>
StatusOr< NativeIamPolicyGetNativeBucketIamPolicy (std::string const &bucket_name, Options &&... options)
 Fetches the native IAM policy for a Bucket. More...
 
template<typename... Options>
StatusOr< IamPolicy > SetBucketIamPolicy (std::string const &bucket_name, IamPolicy const &iam_policy, Options &&... options)
 Sets the IAM Policy for a Bucket. More...
 
template<typename... Options>
StatusOr< NativeIamPolicySetNativeBucketIamPolicy (std::string const &bucket_name, NativeIamPolicy const &iam_policy, Options &&... options)
 Sets the native IAM Policy for a Bucket. More...
 
template<typename... Options>
StatusOr< std::vector< std::string > > TestBucketIamPermissions (std::string bucket_name, std::vector< std::string > permissions, Options &&... options)
 Tests the IAM permissions of the caller against a Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataLockBucketRetentionPolicy (std::string const &bucket_name, std::uint64_t metageneration, Options &&... options)
 Locks the retention policy for a bucket. More...
 
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 also
https://cloud.google.com/storage/docs/key-terms#objects for more information about GCS objects.
template<typename... Options>
StatusOr< ObjectMetadataInsertObject (std::string const &bucket_name, std::string const &object_name, std::string contents, Options &&... options)
 Creates an object given its name and contents. More...
 
template<typename... Options>
StatusOr< ObjectMetadataCopyObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Copies an existing object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataGetObjectMetadata (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Fetches the object metadata. More...
 
template<typename... Options>
ListObjectsReader ListObjects (std::string const &bucket_name, Options &&... options)
 Lists the objects in a bucket. More...
 
template<typename... Options>
ListObjectsAndPrefixesReader ListObjectsAndPrefixes (std::string const &bucket_name, Options &&... options)
 Lists the objects and prefixes in a bucket. More...
 
template<typename... Options>
ObjectReadStream ReadObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Reads the contents of an object. More...
 
template<typename... Options>
ObjectWriteStream WriteObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Writes contents into an object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataUploadFile (std::string const &file_name, std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Uploads a file to an object. More...
 
template<typename... Options>
Status DeleteResumableUpload (std::string const &upload_session_url, Options &&... options)
 Cancel a resumable upload. More...
 
template<typename... Options>
Status DownloadToFile (std::string const &bucket_name, std::string const &object_name, std::string const &file_name, Options &&... options)
 Downloads a Cloud Storage object to a file. More...
 
template<typename... Options>
Status DeleteObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Deletes an object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataUpdateObject (std::string bucket_name, std::string object_name, ObjectMetadata metadata, Options &&... options)
 Updates the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataPatchObject (std::string bucket_name, std::string object_name, ObjectMetadata const &original, ObjectMetadata const &updated, Options &&... options)
 Patches the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataPatchObject (std::string bucket_name, std::string object_name, ObjectMetadataPatchBuilder const &builder, Options &&... options)
 Patches the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataComposeObject (std::string bucket_name, std::vector< ComposeSourceObject > source_objects, std::string destination_object_name, Options &&... options)
 Composes existing objects into a new object in the same bucket. More...
 
template<typename... Options>
ObjectRewriter RewriteObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Creates an ObjectRewriter to copy the source object. More...
 
template<typename... Options>
ObjectRewriter ResumeRewriteObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, std::string rewrite_token, Options &&... options)
 Creates an ObjectRewriter to resume a previously created rewrite. More...
 
template<typename... Options>
StatusOr< ObjectMetadataRewriteObjectBlocking (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Rewrites the object, blocking until the rewrite completes, and returns the resulting ObjectMetadata. More...
 
Bucket Access Control List operations.

You can control who has access to your GCS buckets and objects as well as what level of access they have.

Note
In most cases, you should use IAM permissions instead of ACLs to control access to buckets.
All buckets are owned by the project owners group. Project owners are granted OWNER permissions to all buckets inside their project. Bucket and object ownership cannot be changed by modifying ACLs.
When you apply a new ACL to a bucket, GCS adds OWNER permission to the bucket if you omit the grants. You cannot remove the project owners group from a bucket ACL. Attempts to do so will appear to succeed, but the service will add the project owners group into the new ACL before applying it.
See also
https://cloud.google.com/storage/docs/access-control/ for more information about access control in GCS.
https://cloud.google.com/storage/docs/access-control/lists#defaultbuckets for more details about the default owners for a bucket.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< BucketAccessControl > > ListBucketAcl (std::string const &bucket_name, Options &&... options)
 Retrieves the list of BucketAccessControl items for a bucket. More...
 
template<typename... Options>
StatusOr< BucketAccessControlCreateBucketAcl (std::string const &bucket_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in a bucket ACL. More...
 
template<typename... Options>
Status DeleteBucketAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Deletes an entry from a bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlGetBucketAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Gets the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlUpdateBucketAcl (std::string const &bucket_name, BucketAccessControl const &acl, Options &&... options)
 Updates the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlPatchBucketAcl (std::string const &bucket_name, std::string const &entity, BucketAccessControl const &original_acl, BucketAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlPatchBucketAcl (std::string const &bucket_name, std::string const &entity, BucketAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing bucket ACL. More...
 
Object Access Control List operations.

You can control who has access to your GCS buckets and objects as well as what level of access they have.

Note
When you upload (create) an object the entity that uploads the object is listed as the object owner. This can be a user or a service account, depending on what credentials are used to authenticate with GCS. Object ownership cannot be changed by modifying ACLs. You can change object ownership only by overwriting the object while authenticated as the desired owner.
When you apply a new ACL to an object, GCS adds OWNER permission to the object if you omit the grants.
See also
https://cloud.google.com/storage/docs/access-control/ for more information about access control in GCS.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > ListObjectAcl (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Retrieves the list of ObjectAccessControl items for an object. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlCreateObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in the object ACL. More...
 
template<typename... Options>
Status DeleteObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, Options &&... options)
 Deletes one access control entry in one object. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlGetObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, Options &&... options)
 Gets the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlUpdateObjectAcl (std::string const &bucket_name, std::string const &object_name, ObjectAccessControl const &acl, Options &&... options)
 Updates the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, ObjectAccessControl const &original_acl, ObjectAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, ObjectAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing object ACL. More...
 
Bucket Default Object Access Control List operations.

When you upload an object to GCS without specifying an ACL, the object is created with the Default Object ACL for its bucket.

These operations are used to query and modify the Default Object ACL of a bucket.

See also
https://cloud.google.com/storage/docs/access-control/lists#defaultobjects for more information on default object ACLs.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > ListDefaultObjectAcl (std::string const &bucket_name, Options &&... options)
 Retrieves the default object ACL for a bucket as a vector of ObjectAccessControl items. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlCreateDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in the default object ACL for a bucket. More...
 
template<typename... Options>
Status DeleteDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Deletes an entry from the default object ACL in a bucket. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlGetDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Gets the value of a default object ACL in a bucket. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlUpdateDefaultObjectAcl (std::string const &bucket_name, ObjectAccessControl const &acl, Options &&... options)
 Updates the value of an existing default object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, ObjectAccessControl const &original_acl, ObjectAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing default object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, ObjectAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing default object ACL. More...
 
Service account operations.

Service accounts allow applications to authenticate and access GCP resources and services.

When acting on your behalf, GCS uses such a service account. GCS creates one service account per project. These operations allow you to query the GCS service account for a project.

See also
https://cloud.google.com/storage/docs/projects#service-accounts for more information on service accounts.
template<typename... Options>
StatusOr< ServiceAccountGetServiceAccountForProject (std::string const &project_id, Options &&... options)
 Gets the GCS service account for a given project. More...
 
template<typename... Options>
StatusOr< ServiceAccountGetServiceAccount (Options &&... options)
 Gets the GCS service account for the default project. More...
 
template<typename... Options>
ListHmacKeysReader ListHmacKeys (Options &&... options)
 List the available HMAC keys. More...
 
template<typename... Options>
StatusOr< std::pair< HmacKeyMetadata, std::string > > CreateHmacKey (std::string service_account, Options &&... options)
 Create a new HMAC key. More...
 
template<typename... Options>
Status DeleteHmacKey (std::string access_id, Options &&... options)
 Delete a HMAC key in a given project. More...
 
template<typename... Options>
StatusOr< HmacKeyMetadataGetHmacKey (std::string access_id, Options &&... options)
 Get an existing HMAC key in a given project. More...
 
template<typename... Options>
StatusOr< HmacKeyMetadataUpdateHmacKey (std::string access_id, HmacKeyMetadata resource, Options &&... options)
 Update an existing HMAC key in a given project. More...
 
Signed URL support operations.
template<typename... Options>
StatusOr< std::string > CreateV2SignedUrl (std::string verb, std::string bucket_name, std::string object_name, Options &&... options)
 Create a V2 signed URL for the given parameters. More...
 
template<typename... Options>
StatusOr< std::string > CreateV4SignedUrl (std::string verb, std::string bucket_name, std::string object_name, Options &&... options)
 Create a V4 signed URL for the given parameters. More...
 
Pub/Sub operations.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Cloud Pub/Sub, where the information is added to a Cloud Pub/Sub topic of your choice in the form of messages.

See also
https://cloud.google.com/storage/docs/pubsub-notifications for more information about Cloud Pub/Sub in the context of GCS.
template<typename... Options>
StatusOr< std::vector< NotificationMetadata > > ListNotifications (std::string const &bucket_name, Options &&... options)
 Retrieves the list of Notifications for a Bucket. More...
 
template<typename... Options>
StatusOr< NotificationMetadataCreateNotification (std::string const &bucket_name, std::string const &topic_name, std::string const &payload_format, NotificationMetadata metadata, Options &&... options)
 Creates a new notification config for a Bucket. More...
 
template<typename... Options>
StatusOr< NotificationMetadataGetNotification (std::string const &bucket_name, std::string const &notification_id, Options &&... options)
 Gets the details about a notification config in a given Bucket. More...
 
template<typename... Options>
Status DeleteNotification (std::string const &bucket_name, std::string const &notification_id, Options &&... options)
 Delete an existing notification config in a given Bucket. More...
 

Static Public Member Functions

static StatusOr< ClientCreateDefaultClient ()
 Create a Client using ClientOptions::CreateDefaultClientOptions(). More...
 

Friends

class testing::ClientTester
 

Detailed Description

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.

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.
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.
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:
// Implicitly use ADCs:
StatusOr<gcs::Client> client = gcs::Client::CreateDefaultClient();
if (!client) {
// Handle failure and return.
}
// Or explicitly use ADCs:
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 =
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(
// Use no credentials:
gcs::Client client(
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 for more details.
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";

In addition, the main page contains examples using StatusOr<T> to handle errors.

Retry, Backoff, and Idempotency Policies

The library automatically retries requests that fail with transient errors, and follows the recommended practice 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 also
https://cloud.google.com/storage/ for an overview of GCS.
https://cloud.google.com/storage/docs/key-terms for an introduction of the key terms used in GCS.
https://cloud.google.com/storage/docs/json_api/ for an overview of the underlying API.
https://cloud.google.com/docs/authentication/production for details about Application Default Credentials.
google::cloud::v1::StatusOr.
LimitedTimeRetryPolicy and LimitedErrorCountRetryPolicy for alternative retry policies.
ExponentialBackoffPolicy to configure different parameters for the exponential backoff policy.
AlwaysRetryIdempotencyPolicy and StrictIdempotencyPolicy for alternative idempotency policies.

Definition at line 187 of file client.h.

Constructor & Destructor Documentation

◆ Client() [1/4]

template<typename... Policies>
google::cloud::storage::v1::Client::Client ( ClientOptions  options,
Policies &&...  policies 
)
inlineexplicit

Creates the default client type given the options.

Parameters
optionsthe client options, these are used to control credentials, buffer sizes, etc.
policiesthe 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.
Idempotency Policy Example
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only retries idempotent operations, the default is
// to retry all operations.
StatusOr<gcs::ClientOptions> options =
gcs::ClientOptions::CreateDefaultClientOptions();
if (!options) throw std::runtime_error(options.status().message());
gcs::Client client{*options, gcs::StrictIdempotencyPolicy()};
StatusOr<gcs::ObjectMetadata> object_metadata =
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Modified Retry Policy Example
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only gives up on the third error. The default policy
// is to retry for several minutes.
StatusOr<gcs::ClientOptions> options =
gcs::ClientOptions::CreateDefaultClientOptions();
if (!options) throw std::runtime_error(options.status().message());
gcs::Client client{*options, gcs::LimitedErrorCountRetryPolicy(3)};
StatusOr<gcs::ObjectMetadata> object_metadata =
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}

Definition at line 206 of file client.h.

◆ Client() [2/4]

template<typename... Policies>
google::cloud::storage::v1::Client::Client ( std::shared_ptr< oauth2::Credentials credentials,
Policies &&...  policies 
)
inlineexplicit

Creates the default client type given the credentials and policies.

Parameters
credentialsa set of credentials to initialize the ClientOptions.
policiesthe 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.
Idempotency Policy Example
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only retries idempotent operations, the default is
// to retry all operations.
StatusOr<gcs::ClientOptions> options =
gcs::ClientOptions::CreateDefaultClientOptions();
if (!options) throw std::runtime_error(options.status().message());
gcs::Client client{*options, gcs::StrictIdempotencyPolicy()};
StatusOr<gcs::ObjectMetadata> object_metadata =
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Modified Retry Policy Example
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only gives up on the third error. The default policy
// is to retry for several minutes.
StatusOr<gcs::ClientOptions> options =
gcs::ClientOptions::CreateDefaultClientOptions();
if (!options) throw std::runtime_error(options.status().message());
gcs::Client client{*options, gcs::LimitedErrorCountRetryPolicy(3)};
StatusOr<gcs::ObjectMetadata> object_metadata =
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}

Definition at line 226 of file client.h.

◆ Client() [3/4]

template<typename... Policies>
google::cloud::storage::v1::Client::Client ( std::shared_ptr< internal::RawClient >  client,
Policies &&...  policies 
)
inlineexplicit

Builds a client and maybe override the retry, idempotency, and/or backoff policies.

Definition at line 234 of file client.h.

◆ Client() [4/4]

google::cloud::storage::v1::Client::Client ( std::shared_ptr< internal::RawClient >  client,
NoDecorations   
)
inlineexplicit

Builds a client with a specific RawClient, without decorations.

Definition at line 243 of file client.h.

Member Function Documentation

◆ ComposeObject()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::ComposeObject ( std::string  bucket_name,
std::vector< ComposeSourceObject source_objects,
std::string  destination_object_name,
Options &&...  options 
)
inline

Composes existing objects into a new object in the same bucket.

Parameters
bucket_namethe name of the bucket used for source object and destination object.
source_objectsobjects used to compose destination_object_name.
destination_object_namethe composed object name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfMetagenerationMatch, KmsKeyName, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& destination_object_name,
std::vector<gcs::ComposeSourceObject> const& compose_objects) {
StatusOr<gcs::ObjectMetadata> composed_object = client.ComposeObject(
bucket_name, compose_objects, destination_object_name);
if (!composed_object) {
throw std::runtime_error(composed_object.status().message());
}
std::cout << "Composed new object " << composed_object->name()
<< " in bucket " << composed_object->bucket()
<< "\nFull metadata: " << *composed_object << "\n";
}
Example: using encrypted objects with CSEK
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& destination_object_name,
std::string const& base64_aes256_key,
std::vector<gcs::ComposeSourceObject> const& compose_objects) {
StatusOr<gcs::ObjectMetadata> composed_object = client.ComposeObject(
bucket_name, compose_objects, destination_object_name,
gcs::EncryptionKey::FromBase64Key(base64_aes256_key));
if (!composed_object) {
throw std::runtime_error(composed_object.status().message());
}
std::cout << "Composed new object " << composed_object->name()
<< " in bucket " << composed_object->bucket()
<< "\nFull metadata: " << *composed_object << "\n";
}

Definition at line 1449 of file client.h.

◆ CopyObject()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::CopyObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

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.
Parameters
source_bucket_namethe name of the bucket that contains the object to be copied.
source_object_namethe name of the object to copy.
destination_bucket_namethe name of the bucket that will contain the new object.
destination_object_namethe name of the new object.
optionsa 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.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
StatusOr<gcs::ObjectMetadata> new_copy_meta =
client.CopyObject(source_bucket_name, source_object_name,
destination_bucket_name, destination_object_name);
if (!new_copy_meta) {
throw std::runtime_error(new_copy_meta.status().message());
}
std::cout << "Successfully copied " << source_object_name << " in bucket "
<< source_bucket_name << " to bucket " << new_copy_meta->bucket()
<< " with name " << new_copy_meta->name()
<< ".\nThe full metadata after the copy is: " << *new_copy_meta
<< "\n";
}
Example: copy an encrypted object
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& key_base64) {
StatusOr<gcs::ObjectMetadata> new_copy_meta = client.CopyObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, gcs::EncryptionKey::FromBase64Key(key_base64));
if (!new_copy_meta) {
throw std::runtime_error(new_copy_meta.status().message());
}
std::cout << "Successfully copied " << source_object_name << " in bucket "
<< source_bucket_name << " to bucket " << new_copy_meta->bucket()
<< " with name " << new_copy_meta->name()
<< ".\nThe full metadata after the copy is: " << *new_copy_meta
<< "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/objects/copy for a full description of the advantages of Objects: rewrite over Objects: copy.

Definition at line 947 of file client.h.

◆ CreateBucket()

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::CreateBucket ( std::string  bucket_name,
BucketMetadata  metadata,
Options &&...  options 
)
inline

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.

Parameters
bucket_namethe name of the new bucket.
metadatathe metadata for the new Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is always idempotent. It fails if the bucket already exists.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> bucket_metadata =
client.CreateBucket(bucket_name, gcs::BucketMetadata());
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
std::cout << "Bucket " << bucket_metadata->name() << " created."
<< "\nFull Metadata: " << *bucket_metadata << "\n";
}
See also
Before enabling Bucket Policy Only please review the feature documentation, as well as "Should you use Bucket Policy Only?".

Definition at line 345 of file client.h.

◆ CreateBucketAcl()

template<typename... Options>
StatusOr<BucketAccessControl> google::cloud::storage::v1::Client::CreateBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in a bucket ACL.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::BucketAccessControl> bucket_acl =
client.CreateBucketAcl(bucket_name, entity, role);
if (!bucket_acl) throw std::runtime_error(bucket_acl.status().message());
std::cout << "Role " << bucket_acl->role() << " granted to "
<< bucket_acl->entity() << " on bucket " << bucket_acl->bucket()
<< "\n"
<< "Full attributes: " << *bucket_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 1699 of file client.h.

◆ CreateBucketForProject()

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::CreateBucketForProject ( std::string  bucket_name,
std::string  project_id,
BucketMetadata  metadata,
Options &&...  options 
)
inline

Creates a new Google Cloud Storage Bucket in a given project.

Parameters
bucket_namethe name of the new bucket.
project_idthe id of the project that will host the new bucket.
metadatathe metadata for the new Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is always idempotent. It fails if the bucket already exists.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& project_id) {
StatusOr<gcs::BucketMetadata> bucket_metadata =
client.CreateBucketForProject(bucket_name, project_id,
gcs::BucketMetadata{});
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
std::cout << "Bucket " << bucket_metadata->name() << " created for project "
<< project_id << " [" << bucket_metadata->project_number() << "]"
<< "\nFull Metadata: " << *bucket_metadata << "\n";
}
See also
Before enabling Bucket Policy Only please review the feature documentation, as well as "Should you use Bucket Policy Only?".

Definition at line 380 of file client.h.

◆ CreateDefaultClient()

StatusOr< Client > google::cloud::storage::v1::Client::CreateDefaultClient ( )
static

Create a Client using ClientOptions::CreateDefaultClientOptions().

Definition at line 41 of file client.cc.

◆ CreateDefaultObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::CreateDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in the default object ACL for a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::ObjectAccessControl> default_object_acl =
client.CreateDefaultObjectAcl(bucket_name, entity, role);
if (!default_object_acl) {
throw std::runtime_error(default_object_acl.status().message());
}
std::cout << "Role " << default_object_acl->role()
<< " will be granted default to " << default_object_acl->entity()
<< " on any new object created on bucket "
<< default_object_acl->bucket() << "\n"
<< "Full attributes: " << *default_object_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 2239 of file client.h.

◆ CreateHmacKey()

template<typename... Options>
StatusOr<std::pair<HmacKeyMetadata, std::string> > google::cloud::storage::v1::Client::CreateHmacKey ( std::string  service_account,
Options &&...  options 
)
inline

Create a new HMAC key.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
service_accountthe service account email where you want to create the new HMAC key.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata and the HMAC key secret (encoded as a base64 string). This is the only request that returns the secret.
Idempotency
This operation is not idempotent. Retrying the operation will create a new key each time.
Example
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> key_info =
client.CreateHmacKey(service_account_email);
if (!key_info) throw std::runtime_error(key_info.status().message());
std::cout << "The base64 encoded secret is: " << key_info->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << key_info->first << "\n";
return key_info->first.access_id();
}
Example
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& project_id,
std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> hmac_key_details =
client.CreateHmacKey(service_account_email,
gcs::OverrideDefaultProject(project_id));
if (!hmac_key_details) {
throw std::runtime_error(hmac_key_details.status().message());
}
std::cout << "The base64 encoded secret is: " << hmac_key_details->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << hmac_key_details->first
<< "\n";
return hmac_key_details->first.access_id();
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

Definition at line 2600 of file client.h.

◆ CreateNotification()

template<typename... Options>
StatusOr<NotificationMetadata> google::cloud::storage::v1::Client::CreateNotification ( std::string const &  bucket_name,
std::string const &  topic_name,
std::string const &  payload_format,
NotificationMetadata  metadata,
Options &&...  options 
)
inline

Creates a new notification config for a Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options.

Parameters
bucket_namethe name of the bucket.
topic_namethe Google Cloud Pub/Sub topic that will receive the notifications. This requires the full name of the topic, i.e.: projects/<PROJECT_ID>/topics/<TOPIC_ID>.
payload_formathow will the data be formatted in the notifications, consider using the helpers in the payload_format namespace, or specify one of the valid formats defined in: https://cloud.google.com/storage/docs/json_api/v1/notifications
metadatadefine any optional parameters for the notification, such as the list of event types, or any custom attributes.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& topic_name) {
StatusOr<gcs::NotificationMetadata> notification =
client.CreateNotification(bucket_name, topic_name,
gcs::NotificationMetadata());
if (!notification) {
throw std::runtime_error(notification.status().message());
}
std::cout << "Successfully created notification " << notification->id()
<< " for bucket " << bucket_name << "\n";
std::cout << "Full details for the notification:\n"
<< *notification << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

Definition at line 3012 of file client.h.

◆ CreateObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::CreateObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in the object ACL.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
StatusOr<gcs::ObjectAccessControl> object_acl =
client.CreateObjectAcl(bucket_name, object_name, entity, role);
if (!object_acl) throw std::runtime_error(object_acl.status().message());
std::cout << "Role " << object_acl->role() << " granted to "
<< object_acl->entity() << " on " << object_acl->object()
<< "\nFull attributes: " << *object_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 1963 of file client.h.

◆ CreateSignedPolicyDocument()

template<typename... Options>
StatusOr<PolicyDocumentResult> google::cloud::storage::v1::Client::CreateSignedPolicyDocument ( PolicyDocument  document,
Options &&...  options 
)
inline

Create a signed policy document.

Note
The application must ensure that any document created with this function contains valid conditions. This function does not do any error checking, e.g. that a ExactMatchObject() condition contains two elements. Using the provided helper functions can prevent errors.
It is the application's responsibility to construct a POST request based on the value returned by this function. For example, a web application can create a HTML form containing these fields, the result of which is a POST request to GCS.
Parameters
documentthe policy document.
optionsa list of optional parameters, this includes: SigningAccount, and SigningAccountDelegates.
Helper Functions
The following functions create a PolicyDocumentCondition with less opportunities for typos: StartsWith(), ExactMatchObject(), ExactMatch(), ContentLengthRange().
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::PolicyDocumentResult> document =
client.CreateSignedPolicyDocument(gcs::PolicyDocument{
std::chrono::system_clock::now() + std::chrono::minutes(15),
{
gcs::PolicyDocumentCondition::StartsWith("key", ""),
gcs::PolicyDocumentCondition::ExactMatchObject(
"acl", "bucket-owner-read"),
gcs::PolicyDocumentCondition::ExactMatchObject(
"bucket", std::move(bucket_name)),
gcs::PolicyDocumentCondition::ExactMatch("Content-Type",
"image/jpeg"),
gcs::PolicyDocumentCondition::ContentLengthRange(0, 1000000),
}});
if (!document) throw std::runtime_error(document.status().message());
std::cout << "The signed document is: " << *document << "\n\n"
<< "You can use this with an HTML form.\n";
}
See also
https://cloud.google.com/storage/docs/xml-api/post-object#policydocument for a general description of policy documents and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

Definition at line 2891 of file client.h.

◆ CreateV2SignedUrl()

template<typename... Options>
StatusOr<std::string> google::cloud::storage::v1::Client::CreateV2SignedUrl ( std::string  verb,
std::string  bucket_name,
std::string  object_name,
Options &&...  options 
)
inline

Create a V2 signed URL for the given parameters.

Note
By default URLs created with this function expire after 7 days.
The application must ensure that any URL created with this function is a valid request via the XML API. For example, the options for bucket requests may include a sub-resource (e.g. WithBilling()) but not all sub-resources are valid for objects. Likewise, only a single sub-resource may be retrieved in each request.
Parameters
verbthe operation allowed through this signed URL, GET, POST, PUT, HEAD, etc. are valid values.
bucket_namethe name of the bucket.
object_namethe name of the object, note that the object may not exist for signed URLs that upload new objects. Use an empty string for requests that only affect a bucket.
optionsa list of optional parameters for the signed URL, this include: ExpirationTime, MD5HashValue, ContentType, SigningAccount, SigningAccountDelegates, AddExtensionHeaderOption, AddQueryParameterOption, and AddSubResourceOption. Note that only the last AddSubResourceOption option has any effect.
Helper Functions

The following functions create a AddSubResourceOption with less opportunities for typos in the sub-resource name: WithAcl(), WithBilling(), WithCompose(), WithCors(), WithEncryption(), WithEncryptionConfig(), WithLifecycle(), WithLocation(), WithLogging(), WithStorageClass(), and WithTagging().

Likewise, the following helper functions can create properly formatted AddExtensionHeaderOption objects: WithGeneration(), WithGenerationMarker(), WithMarker(), WithResponseContentDisposition(), WithResponseContentType(), and WithUserProject().

Returns
the signed URL.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<std::string> signed_url = client.CreateV2SignedUrl(
"GET", std::move(bucket_name), std::move(object_name),
gcs::ExpirationTime(std::chrono::system_clock::now() +
std::chrono::minutes(15)));
if (!signed_url) throw std::runtime_error(signed_url.status().message());
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl '" << *signed_url << "'\n";
}
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<std::string> signed_url = client.CreateV2SignedUrl(
"PUT", std::move(bucket_name), std::move(object_name),
gcs::ExpirationTime(std::chrono::system_clock::now() +
std::chrono::minutes(15)),
gcs::ContentType("application/octet-stream"));
if (!signed_url) throw std::runtime_error(signed_url.status().message());
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl -X PUT -H 'Content-Type: application/octet-stream'"
<< " --upload-file my-file '" << *signed_url << "'\n";
}
See also
https://cloud.google.com/storage/docs/access-control/signed-urls for a general description of signed URLs and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

Definition at line 2784 of file client.h.

◆ CreateV4SignedUrl()

template<typename... Options>
StatusOr<std::string> google::cloud::storage::v1::Client::CreateV4SignedUrl ( std::string  verb,
std::string  bucket_name,
std::string  object_name,
Options &&...  options 
)
inline

Create a V4 signed URL for the given parameters.

Note
By default URLs created with this function expire after 7 days.
The application must ensure that any URL created with this function is a valid request via the XML API. For example, the options for bucket requests may include a sub-resource (e.g. WithBilling()) but not all sub-resources are valid for objects. Likewise, only a single sub-resource may be retrieved in each request.
Parameters
verbthe operation allowed through this signed URL, GET, POST, PUT, HEAD, etc. are valid values.
bucket_namethe name of the bucket.
object_namethe name of the object, note that the object may not exist for signed URLs that upload new objects. Use an empty string for requests that only affect a bucket.
optionsa list of optional parameters for the signed URL, this include: SignedUrlTimestamp, SignedUrlDuration, MD5HashValue, ContentType, SigningAccount, SigningAccountDelegates, AddExtensionHeaderOption, AddQueryParameterOption, and AddSubResourceOption. Note that only the last AddSubResourceOption option has any effect.
Helper Functions

The following functions create a AddSubResourceOption with less opportunities for typos in the sub-resource name: WithAcl(), WithBilling(), WithCompose(), WithCors(), WithEncryption(), WithEncryptionConfig(), WithLifecycle(), WithLocation(), WithLogging(), WithStorageClass(), and WithTagging().

Likewise, the following helper functions can create properly formatted AddExtensionHeaderOption objects: WithGeneration(), WithGenerationMarker(), WithMarker(), WithResponseContentDisposition(), WithResponseContentType(), and WithUserProject().

Returns
the signed URL.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<std::string> signed_url = client.CreateV4SignedUrl(
"GET", std::move(bucket_name), std::move(object_name),
gcs::SignedUrlDuration(std::chrono::minutes(15)));
if (!signed_url) throw std::runtime_error(signed_url.status().message());
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl '" << *signed_url << "'\n";
}
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<std::string> signed_url = client.CreateV4SignedUrl(
"PUT", std::move(bucket_name), std::move(object_name),
gcs::SignedUrlDuration(std::chrono::minutes(15)),
gcs::AddExtensionHeader("content-type", "application/octet-stream"));
if (!signed_url) throw std::runtime_error(signed_url.status().message());
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl -X PUT -H 'Content-Type: application/octet-stream'"
<< " --upload-file my-file '" << *signed_url << "'\n";
}
See also
https://cloud.google.com/storage/docs/access-control/signed-urls for a general description of signed URLs and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

Definition at line 2847 of file client.h.

◆ DeleteBucket()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteBucket ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Deletes a Google Cloud Storage Bucket.

Parameters
bucket_namethe bucket to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
[](gcs::Client client, std::string const& bucket_name) {
google::cloud::Status status = client.DeleteBucket(bucket_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The bucket " << bucket_name << " was deleted successfully.\n";
}

Definition at line 429 of file client.h.

◆ DeleteBucketAcl()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes an entry from a bucket ACL.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
google::cloud::Status status = client.DeleteBucketAcl(bucket_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in bucket "
<< bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

Definition at line 1727 of file client.h.

◆ DeleteDefaultObjectAcl()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes an entry from the default object ACL in a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
google::cloud::Status status =
client.DeleteDefaultObjectAcl(bucket_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in bucket "
<< bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

Definition at line 2271 of file client.h.

◆ DeleteHmacKey()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteHmacKey ( std::string  access_id,
Options &&...  options 
)
inline

Delete a HMAC key in a given project.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This operation is always idempotent. An access id identifies a single HMAC key, calling the operation multiple times can succeed only once.
Example
[](gcs::Client client, std::string const& access_id) {
google::cloud::Status status = client.DeleteHmacKey(access_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The key is deleted, though it may still appear"
<< " in ListHmacKeys() results.\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

Definition at line 2643 of file client.h.

◆ DeleteNotification()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteNotification ( std::string const &  bucket_name,
std::string const &  notification_id,
Options &&...  options 
)
inline

Delete an existing notification config in a given Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options. This function deletes one of the notification configs.

Parameters
bucket_namethe name of the bucket.
notification_idthe id of the notification config.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because it only acts on a specific notification_id, the state after calling this function multiple times is to delete that notification. New notifications get different ids.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& notification_id) {
google::cloud::Status status =
client.DeleteNotification(bucket_name, notification_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Successfully deleted notification " << notification_id
<< " on bucket " << bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

Definition at line 3084 of file client.h.

◆ DeleteObject()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Deletes an object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, and UserProject.
Idempotency
This operation is only idempotent if:
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
google::cloud::Status status =
client.DeleteObject(bucket_name, object_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted " << object_name << " in bucket " << bucket_name
<< "\n";
}

Definition at line 1313 of file client.h.

◆ DeleteObjectAcl()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes one access control entry in one object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
entitythe name of the entity (user, team, group) to be removed from the Object's ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity) {
google::cloud::Status status =
client.DeleteObjectAcl(bucket_name, object_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in object "
<< object_name << " in bucket " << bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

Definition at line 1995 of file client.h.

◆ DeleteResumableUpload()

template<typename... Options>
Status google::cloud::storage::v1::Client::DeleteResumableUpload ( std::string const &  upload_session_url,
Options &&...  options 
)
inline

Cancel a resumable upload.

Parameters
upload_session_urlthe url of the upload session. Returned by ObjectWriteStream::resumable_session_id.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because it only acts on a specific upload_session_url.

Definition at line 1259 of file client.h.

◆ DownloadToFile()

template<typename... Options>
Status google::cloud::storage::v1::Client::DownloadToFile ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  file_name,
Options &&...  options 
)
inline

Downloads a Cloud Storage object to a file.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be downloaded.
file_namethe name of the destination file that will have the object media.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, Generation, ReadFromOffset, ReadRange, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& file_name) {
google::cloud::Status status =
client.DownloadToFile(bucket_name, object_name, file_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Downloaded " << object_name << " to " << file_name << "\n";
}

Definition at line 1286 of file client.h.

◆ GenerateSignedPostPolicyV4()

template<typename... Options>
StatusOr<PolicyDocumentV4Result> google::cloud::storage::v1::Client::GenerateSignedPostPolicyV4 ( PolicyDocumentV4  document,
Options &&...  options 
)
inline

Create a signed V4 policy document.

Note
The application must ensure that any document created with this function contains valid conditions. This function does not do any error checking, e.g. that a ExactMatchObject() condition contains two elements. Using the provided helper functions can prevent errors.
It is the application's responsibility to construct a POST request based on the value returned by this function. For example, a web application can create a HTML form containing these fields, the result of which is a POST request to GCS.
Parameters
documentthe policy document.
optionsa list of optional parameters, this includes: AddExtensionFieldOption, BucketBoundHostname, PredefinedAcl, Scheme, SigningAccountDelegates, SigningAccount, VirtualHostname
Helper Functions
The following functions create a PolicyDocumentCondition with less opportunities for typos: StartsWith(), ExactMatchObject(), ExactMatch(), ContentLengthRange().
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::PolicyDocumentV4Result> document =
client.GenerateSignedPostPolicyV4(gcs::PolicyDocumentV4{
std::move(bucket_name),
"scan_0001.jpg",
std::chrono::minutes(15),
std::chrono::system_clock::now(),
{
gcs::PolicyDocumentCondition::StartsWith("key", ""),
gcs::PolicyDocumentCondition::ExactMatchObject(
"acl", "bucket-owner-read"),
gcs::PolicyDocumentCondition::ExactMatch("Content-Type",
"image/jpeg"),
gcs::PolicyDocumentCondition::ContentLengthRange(0, 1000000),
}});
if (!document) throw std::runtime_error(document.status().message());
std::cout << "The signed document is: " << *document << "\n\n"
<< "You can use this with an HTML form.\n";
}
See also
https://cloud.google.com/storage/docs/xml-api/post-object#policydocument for a general description of policy documents and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

Definition at line 2932 of file client.h.

◆ GetBucketAcl()

template<typename... Options>
StatusOr<BucketAccessControl> google::cloud::storage::v1::Client::GetBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of an existing bucket ACL.

Parameters
bucket_namethe name of the bucket to query.
entitythe name of the entity to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
StatusOr<gcs::BucketAccessControl> acl =
client.GetBucketAcl(bucket_name, entity);
if (!acl) throw std::runtime_error(acl.status().message());
std::cout << "ACL entry for " << acl->entity() << " in bucket "
<< acl->bucket() << " is " << *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

Definition at line 1752 of file client.h.

◆ GetBucketIamPolicy()

template<typename... Options>
StatusOr<IamPolicy> google::cloud::storage::v1::Client::GetBucketIamPolicy ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Fetches the IAM policy 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 between legacy Bucket ACLs and IAM policies.

Consult the documentation for a more detailed description of IAM policies and their use in Google Cloud Storage.

Parameters
bucket_namequery metadata information about this bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Deprecated:
this function is deprecated; it doesn't support conditional bindings and will not support any other features to come; please use GetNativeBucketIamPolicy instead. TODO(#2857): Use proper deprecation attributes.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<google::cloud::IamPolicy> policy =
client.GetBucketIamPolicy(bucket_name);
if (!policy) throw std::runtime_error(policy.status().message());
std::cout << "The IAM policy for bucket " << bucket_name << " is "
<< *policy << "\n";
}
See also
google::cloud::v1::IamPolicy for details about the IamPolicy class.

Definition at line 601 of file client.h.

◆ GetBucketMetadata()

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::GetBucketMetadata ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Fetches the bucket metadata.

Parameters
bucket_namequery metadata information about this bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, UserProject, and Projection.
Idempotency
This is a read-only operation and is always idempotent.
Example
// [START storage_get_bucket_metadata]
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> bucket_metadata =
client.GetBucketMetadata(bucket_name);
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
<< *bucket_metadata << "\n";
}
// [END storage_get_bucket_metadata]

Definition at line 406 of file client.h.

◆ GetDefaultObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::GetDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of a default object ACL in a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
StatusOr<gcs::ObjectAccessControl> acl =
client.GetDefaultObjectAcl(bucket_name, entity);
if (!acl) throw std::runtime_error(acl.status().message());
std::cout << "Default Object ACL entry for " << acl->entity()
<< " in bucket " << acl->bucket() << " is " << *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

Definition at line 2302 of file client.h.

◆ GetHmacKey()

template<typename... Options>
StatusOr<HmacKeyMetadata> google::cloud::storage::v1::Client::GetHmacKey ( std::string  access_id,
Options &&...  options 
)
inline

Get an existing HMAC key in a given project.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This is a read-only operation and therefore it is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> hmac_key = client.GetHmacKey(access_id);
if (!hmac_key) throw std::runtime_error(hmac_key.status().message());
std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

Definition at line 2678 of file client.h.

◆ GetNativeBucketIamPolicy()

template<typename... Options>
StatusOr<NativeIamPolicy> google::cloud::storage::v1::Client::GetNativeBucketIamPolicy ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Fetches the native IAM policy 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 between legacy Bucket ACLs and IAM policies.

Consult the documentation for a more detailed description of IAM policies and their use in Google Cloud Storage.

Parameters
bucket_namequery metadata information about this bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::runtime_error(policy.status().message());
std::cout << "The IAM policy for bucket " << bucket_name << " is "
<< *policy << "\n";
}
See also
google::cloud::v1::IamPolicy for details about the IamPolicy class.

Definition at line 641 of file client.h.

◆ GetNotification()

template<typename... Options>
StatusOr<NotificationMetadata> google::cloud::storage::v1::Client::GetNotification ( std::string const &  bucket_name,
std::string const &  notification_id,
Options &&...  options 
)
inline

Gets the details about a notification config in a given Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options. This function fetches the detailed information for a given notification config.

Parameters
bucket_namethe name of the bucket.
notification_idthe id of the notification config.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& notification_id) {
StatusOr<gcs::NotificationMetadata> notification =
client.GetNotification(bucket_name, notification_id);
if (!notification) {
throw std::runtime_error(notification.status().message());
}
std::cout << "Notification " << notification->id() << " for bucket "
<< bucket_name << "\n";
if (notification->object_name_prefix().empty()) {
std::cout << "This notification is sent for all objects in the bucket\n";
} else {
std::cout << "This notification is sent only for objects starting with"
<< " the prefix " << notification->object_name_prefix() << "\n";
}
std::cout << "Full details for the notification:\n"
<< *notification << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

Definition at line 3048 of file client.h.

◆ GetObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::GetObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of an existing object ACL.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity) {
StatusOr<gcs::ObjectAccessControl> acl =
client.GetObjectAcl(bucket_name, object_name, entity);
if (!acl) throw std::runtime_error(acl.status().message());
std::cout << "ACL entry for " << acl->entity() << " in object "
<< acl->object() << " in bucket " << acl->bucket() << " is "
<< *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

Definition at line 2022 of file client.h.

◆ GetObjectMetadata()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::GetObjectMetadata ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Fetches the object metadata.

Parameters
bucket_namethe bucket containing the object.
object_namethe object name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, Projection, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<gcs::ObjectMetadata> object_metadata =
client.GetObjectMetadata(bucket_name, object_name);
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The metadata for object " << object_metadata->name()
<< " in bucket " << object_metadata->bucket() << " is "
<< *object_metadata << "\n";
}

Definition at line 976 of file client.h.

◆ GetServiceAccount()

template<typename... Options>
StatusOr<ServiceAccount> google::cloud::storage::v1::Client::GetServiceAccount ( Options &&...  options)
inline

Gets the GCS service account for the default project.

A service account is a special Google account that belongs to your application, virtual machine, or to a Google service when acting on your behalf. This API allows you to discover the GCS service account for the default project associated with this object.

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 server will reject the request and this function will return the error status.

Parameters
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client) {
StatusOr<gcs::ServiceAccount> account = client.GetServiceAccount();
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details are " << *account << "\n";
}
See also
https://cloud.google.com/iam/docs/service-accounts for general information on Google Cloud Platform service accounts.

Definition at line 2519 of file client.h.

◆ GetServiceAccountForProject()

template<typename... Options>
StatusOr<ServiceAccount> google::cloud::storage::v1::Client::GetServiceAccountForProject ( std::string const &  project_id,
Options &&...  options 
)
inline

Gets the GCS service account for a given project.

A service account is a special Google account that belongs to your application, virtual machine, or to a Google service when acting on your behalf. This API allows you to discover the GCS service account for the project_id project.

Parameters
project_idthe project to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id) {
StatusOr<gcs::ServiceAccount> account =
client.GetServiceAccountForProject(project_id);
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details for project " << project_id
<< " are " << *account << "\n";
}
See also
https://cloud.google.com/iam/docs/service-accounts for general information on Google Cloud Platform service accounts.

Definition at line 2484 of file client.h.

◆ InsertObject()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::InsertObject ( std::string const &  bucket_name,
std::string const &  object_name,
std::string  contents,
Options &&...  options 
)
inline

Creates an object given its name and contents.

Parameters
bucket_namethe name of the bucket that will contain the object.
object_namethe name of the object to be created.
contentsthe contents (media) for the new object.
optionsa 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.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& contents) {
StatusOr<gcs::ObjectMetadata> object_metadata =
client.InsertObject(bucket_name, object_name, std::move(contents));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type,
std::string const& contents) {
// Setting the object metadata (via the `gcs::WithObjectMadata` option)
// requires a multipart upload, the library prefers simple uploads unless
// required as in this case.
StatusOr<gcs::ObjectMetadata> object_metadata = client.InsertObject(
bucket_name, object_name, std::move(contents),
gcs::WithObjectMetadata(
gcs::ObjectMetadata().set_content_type(content_type)));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nThe contentType was set to "
<< object_metadata->content_type()
<< "\nFull metadata: " << *object_metadata << "\n";
}

Definition at line 896 of file client.h.

◆ ListBucketAcl()

template<typename... Options>
StatusOr<std::vector<BucketAccessControl> > google::cloud::storage::v1::Client::ListBucketAcl ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the list of BucketAccessControl items for a bucket.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<std::vector<gcs::BucketAccessControl>> items =
client.ListBucketAcl(bucket_name);
if (!items) throw std::runtime_error(items.status().message());
std::cout << "ACLs for bucket=" << bucket_name << "\n";
for (gcs::BucketAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}

Definition at line 1666 of file client.h.

◆ ListBuckets()

template<typename... Options>
ListBucketsReader google::cloud::storage::v1::Client::ListBuckets ( Options &&...  options)
inline

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.

Parameters
optionsa list of optional query parameters and/or request headers. Valid types for this operation include MaxResults, Prefix, UserProject, and Projection.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListBucketsReader bucket_list = client.ListBuckets();
for (auto&& bucket_metadata : bucket_list) {
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
std::cout << bucket_metadata->name() << "\n";
++count;
}
if (count == 0) {
std::cout << "No buckets in default project\n";
}
}

Definition at line 313 of file client.h.

◆ ListBucketsForProject()

template<typename... Options>
ListBucketsReader google::cloud::storage::v1::Client::ListBucketsForProject ( std::string const &  project_id,
Options &&...  options 
)
inline

Fetches the list of buckets for a given project.

Parameters
project_idthe project to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include MaxResults, Prefix, UserProject, and Projection.
Idempotency
This is a read-only operation and is always idempotent.
Example
[](gcs::Client client, std::string const& project_id) {
int count = 0;
for (auto&& bucket_metadata : client.ListBucketsForProject(project_id)) {
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
std::cout << bucket_metadata->name() << "\n";
++count;
}
if (count == 0) {
std::cout << "No buckets in project " << project_id << "\n";
}
}

Definition at line 281 of file client.h.

◆ ListDefaultObjectAcl()

template<typename... Options>
StatusOr<std::vector<ObjectAccessControl> > google::cloud::storage::v1::Client::ListDefaultObjectAcl ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the default object ACL for a bucket as a vector of ObjectAccessControl items.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<std::vector<gcs::ObjectAccessControl>> items =
client.ListDefaultObjectAcl(bucket_name);
if (!items) throw std::runtime_error(items.status().message());
std::cout << "ACLs for bucket=" << bucket_name << "\n";
for (gcs::ObjectAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects

Definition at line 2201 of file client.h.

◆ ListHmacKeys()

template<typename... Options>
ListHmacKeysReader google::cloud::storage::v1::Client::ListHmacKeys ( Options &&...  options)
inline

List the available HMAC keys.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts Deleted MaxResults, OverrideDefaultProject, ServiceAccountFilter, and UserProject.
Returns
A range to iterate over the available HMAC keys.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys();
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys in default project\n";
}
}
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& service_account) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list =
client.ListHmacKeys(gcs::ServiceAccountFilter(service_account));
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys for service account " << service_account
<< " in default project\n";
}
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

Definition at line 2555 of file client.h.

◆ ListNotifications()

template<typename... Options>
StatusOr<std::vector<NotificationMetadata> > google::cloud::storage::v1::Client::ListNotifications ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the list of Notifications for a Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<std::vector<gcs::NotificationMetadata>> items =
client.ListNotifications(bucket_name);
if (!items) throw std::runtime_error(items.status().message());
std::cout << "Notifications for bucket=" << bucket_name << "\n";
for (gcs::NotificationMetadata const& notification : *items) {
std::cout << notification << "\n";
}
}

Definition at line 2967 of file client.h.

◆ ListObjectAcl()

template<typename... Options>
StatusOr<std::vector<ObjectAccessControl> > google::cloud::storage::v1::Client::ListObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Retrieves the list of ObjectAccessControl items for an object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
StatusOr<std::vector<gcs::ObjectAccessControl>> items =
client.ListObjectAcl(bucket_name, object_name);
if (!items) throw std::runtime_error(items.status().message());
std::cout << "ACLs for object=" << object_name << " in bucket "
<< bucket_name << "\n";
for (gcs::ObjectAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}

Definition at line 1928 of file client.h.

◆ ListObjects()

template<typename... Options>
ListObjectsReader google::cloud::storage::v1::Client::ListObjects ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Lists the objects in a bucket.

Parameters
bucket_namethe name of the bucket to list.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, UserProject, Projection, Prefix, Delimiter, StartOffset, EndOffset, and Versions.
Idempotency
This is a read-only operation and is always idempotent.
Example
[](gcs::Client client, std::string const& bucket_name) {
for (auto&& object_metadata : client.ListObjects(bucket_name)) {
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "bucket_name=" << object_metadata->bucket()
<< ", object_name=" << object_metadata->name() << "\n";
}
}

Definition at line 1001 of file client.h.

◆ ListObjectsAndPrefixes()

template<typename... Options>
ListObjectsAndPrefixesReader google::cloud::storage::v1::Client::ListObjectsAndPrefixes ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Lists the objects and prefixes in a bucket.

Parameters
bucket_namethe name of the bucket to list.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, UserProject, Projection, Prefix, Delimiter, StartOffset, EndOffset, and Versions.
Idempotency
This is a read-only operation and is always idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& bucket_prefix) {
for (auto&& item : client.ListObjectsAndPrefixes(
bucket_name, gcs::Prefix(bucket_prefix), gcs::Delimiter("/"))) {
if (!item) throw std::runtime_error(item.status().message());
auto result = *std::move(item);
if (absl::holds_alternative<gcs::ObjectMetadata>(result)) {
std::cout << "object_name="
<< absl::get<gcs::ObjectMetadata>(result).name() << "\n";
} else if (absl::holds_alternative<std::string>(result)) {
std::cout << "prefix =" << absl::get<std::string>(result) << "\n";
}
}
}

Definition at line 1029 of file client.h.

◆ LockBucketRetentionPolicy()

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::LockBucketRetentionPolicy ( std::string const &  bucket_name,
std::uint64_t  metageneration,
Options &&...  options 
)
inline

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 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.

Parameters
bucket_namethe name of the bucket.
metagenerationthe expected value of the metageneration on the bucket. The request will fail if the metageneration does not match the current value.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because the metageneration parameter is always required, and it acts as a pre-condition on the operation.
Example: lock the retention policy
// [START storage_lock_retention_policy]
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> updated_metadata =
client.LockBucketRetentionPolicy(bucket_name,
original->metageneration());
if (!updated_metadata) {
throw std::runtime_error(updated_metadata.status().message());
}
if (!updated_metadata->has_retention_policy()) {
std::cerr << "The bucket " << updated_metadata->name()
<< " does not have a retention policy, even though the"
<< " operation to set it was successful.\n"
<< "This is unexpected, and may indicate that another"
<< " application has modified the bucket concurrently.\n";
return;
}
std::cout << "Retention policy successfully locked for bucket "
<< updated_metadata->name() << "\nNew retention policy is: "
<< updated_metadata->retention_policy()
<< "\nFull metadata: " << *updated_metadata << "\n";
}
// [END storage_lock_retention_policy]
Example: get the current retention policy
// [START storage_get_retention_policy]
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> bucket_metadata =
client.GetBucketMetadata(bucket_name);
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.status().message());
}
if (!bucket_metadata->has_retention_policy()) {
std::cout << "The bucket " << bucket_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << bucket_metadata->name()
<< " retention policy is set to "
<< bucket_metadata->retention_policy() << "\n";
}
// [END storage_get_retention_policy]
Example: set the current retention policy
// [START storage_set_retention_policy]
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::chrono::seconds period) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.status().message());
}
if (!patched_metadata->has_retention_policy()) {
std::cout << "The bucket " << patched_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched_metadata->name()
<< " retention policy is set to "
<< patched_metadata->retention_policy() << "\n";
}
// [END storage_set_retention_policy]
Example: remove the retention policy
// [START storage_remove_retention_policy]
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.status().message());
}
if (!patched_metadata->has_retention_policy()) {
std::cout << "The bucket " << patched_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched_metadata->name()
<< " retention policy is set to "
<< patched_metadata->retention_policy()
<< ". This is unexpected, maybe a concurrent change by another"
<< " application?\n";
}
// [END storage_remove_retention_policy]
See also
https://cloud.google.com/storage/docs/bucket-lock for a description of the Bucket Lock feature.
https://cloud.google.com/storage/docs/using-bucket-lock for examples of how to use the Bucket Lock and retention policy features.

Definition at line 848 of file client.h.

◆ PatchBucket() [1/2]

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::PatchBucket ( std::string  bucket_name,
BucketMetadata const &  original,
BucketMetadata const &  updated,
Options &&...  options 
)
inline

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 original to the values in updated. Non-writeable attributes are ignored, and attributes not present in updated are removed. Typically this function is used after the application obtained a value with GetBucketMetadata and has modified these parameters.

Parameters
bucket_namethe bucket to be updated.
originalthe initial value of the bucket metadata.
updatedthe updated value for the bucket metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
gcs::BucketMetadata desired = *original;
desired.set_storage_class(storage_class);
StatusOr<gcs::BucketMetadata> patched =
client.PatchBucket(bucket_name, *original, desired);
if (!patched) throw std::runtime_error(patched.status().message());
std::cout << "Storage class for bucket " << patched->name()
<< " has been patched to " << patched->storage_class() << "."
<< "\nFull metadata: " << *patched << "\n";
}
See also
Before enabling Bucket Policy Only please review the feature documentation, as well as "Should you use Bucket Policy Only?".

Definition at line 514 of file client.h.

◆ PatchBucket() [2/2]

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::PatchBucket ( std::string  bucket_name,
BucketMetadataPatchBuilder const &  builder,
Options &&...  options 
)
inline

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.

Parameters
bucket_namethe bucket to be updated.
builderthe set of updates to perform in the Bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetStorageClass(storage_class));
if (!patched) throw std::runtime_error(patched.status().message());
std::cout << "Storage class for bucket " << patched->name()
<< " has been patched to " << patched->storage_class() << "."
<< "\nFull metadata: " << *patched << "\n";
}
See also
Before enabling Bucket Policy Only please review the feature documentation, as well as "Should you use Bucket Policy Only?".

Definition at line 556 of file client.h.

◆ PatchBucketAcl() [1/2]

template<typename... Options>
StatusOr<BucketAccessControl> google::cloud::storage::v1::Client::PatchBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
BucketAccessControl const &  original_acl,
BucketAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing bucket ACL.

Computes the delta between a previous value for an BucketAccessControl and the new value for an BucketAccessControl and apply that delta.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, and the standard options available to all operations.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::BucketAccessControl> original_acl =
client.GetBucketAcl(bucket_name, entity);
if (!original_acl) {
throw std::runtime_error(original_acl.status().message());
}
auto new_acl = *original_acl;
new_acl.set_role(role);
StatusOr<gcs::BucketAccessControl> patched_acl =
client.PatchBucketAcl(bucket_name, entity, *original_acl, new_acl);
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "ACL entry for " << patched_acl->entity() << " in bucket "
<< patched_acl->bucket() << " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

Definition at line 1836 of file client.h.

◆ PatchBucketAcl() [2/2]

template<typename... Options>
StatusOr<BucketAccessControl> google::cloud::storage::v1::Client::PatchBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
BucketAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing bucket ACL.

This API allows the application to patch an BucketAccessControl without having to read the current value.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::BucketAccessControl> patched_acl = client.PatchBucketAcl(
bucket_name, entity,
gcs::BucketAccessControlPatchBuilder().set_role(role));
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "ACL entry for " << patched_acl->entity() << " in bucket "
<< patched_acl->bucket() << " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

Definition at line 1880 of file client.h.

◆ PatchDefaultObjectAcl() [1/2]

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::PatchDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
ObjectAccessControl const &  original_acl,
ObjectAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing default object ACL.

Compute the delta between a previous and new values for a default object access control, and apply that delta.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, as well as the standard parameters, such as IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::ObjectAccessControl> original_acl =
client.GetDefaultObjectAcl(bucket_name, entity);
if (!original_acl) {
throw std::runtime_error(original_acl.status().message());
}
auto new_acl = *original_acl;
new_acl.set_role(role);
StatusOr<gcs::ObjectAccessControl> patched_acl =
client.PatchDefaultObjectAcl(bucket_name, entity, *original_acl,
new_acl);
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "Default Object ACL entry for " << patched_acl->entity()
<< " in bucket " << patched_acl->bucket() << " is now "
<< *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 2392 of file client.h.

◆ PatchDefaultObjectAcl() [2/2]

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::PatchDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
ObjectAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing default object ACL.

This API allows the application to patch an ObjectAccessControl without having to read the current value.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, as well as the standard parameters, such as IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::ObjectAccessControl> original_acl =
client.GetDefaultObjectAcl(bucket_name, entity);
if (!original_acl) {
throw std::runtime_error(original_acl.status().message());
}
auto new_acl = *original_acl;
new_acl.set_role(role);
StatusOr<gcs::ObjectAccessControl> patched_acl =
client.PatchDefaultObjectAcl(bucket_name, entity, *original_acl,
new_acl);
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "Default Object ACL entry for " << patched_acl->entity()
<< " in bucket " << patched_acl->bucket() << " is now "
<< *patched_acl << "\n";
}
no-read
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 2440 of file client.h.

◆ PatchObject() [1/2]

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::PatchObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadata const &  original,
ObjectMetadata const &  updated,
Options &&...  options 
)
inline

Patches the metadata in a Google Cloud Storage Object.

This function creates a patch request to change the writeable attributes in original to the values in updated. Non-writeable attributes are ignored, and attributes not present in updated are removed. Typically this function is used after the application obtained a value with GetObjectMetadata and has modified these parameters.

Parameters
bucket_namethe bucket that contains the object to be updated.
object_namethe object to be updated.
originalthe initial value of the object metadata.
updatedthe updated value for the object metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& key) {
StatusOr<gcs::ObjectMetadata> original =
client.GetObjectMetadata(bucket_name, object_name);
if (!original) throw std::runtime_error(original.status().message());
gcs::ObjectMetadata desired = *original;
desired.mutable_metadata().erase(key);
StatusOr<gcs::ObjectMetadata> updated =
client.PatchObject(bucket_name, object_name, *original, desired);
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

Definition at line 1380 of file client.h.

◆ PatchObject() [2/2]

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::PatchObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadataPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the metadata in a Google Cloud Storage Object.

This function creates a patch request based on the given builder. Typically this function is used when the application needs to set an object's metadata fields regardless of their previous value (i.e. when calling GetObjectMetadata first is not necessary).

Parameters
bucket_namethe bucket that contains the object to be updated.
object_namethe object to be updated.
builderthe set of updates to perform in the Object metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type) {
StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
bucket_name, object_name,
gcs::ObjectMetadataPatchBuilder().SetContentType(content_type));
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

Definition at line 1416 of file client.h.

◆ PatchObjectAcl() [1/2]

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::PatchObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
ObjectAccessControl const &  original_acl,
ObjectAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing object ACL.

Compute the delta between a previous value for an ObjectAccessControl and the new value for an ObjectAccessControl and apply that delta.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
StatusOr<gcs::ObjectAccessControl> original_acl =
client.GetObjectAcl(bucket_name, object_name, entity);
if (!original_acl) {
throw std::runtime_error(original_acl.status().message());
}
gcs::ObjectAccessControl new_acl = *original_acl;
new_acl.set_role(role);
StatusOr<gcs::ObjectAccessControl> patched_acl = client.PatchObjectAcl(
bucket_name, object_name, entity, *original_acl, new_acl);
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "ACL entry for " << patched_acl->entity() << " in object "
<< patched_acl->object() << " in bucket " << patched_acl->bucket()
<< " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

Definition at line 2108 of file client.h.

◆ PatchObjectAcl() [2/2]

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::PatchObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
ObjectAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing object ACL.

This API allows the application to patch an ObjectAccessControl without having to read the current value.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
StatusOr<gcs::ObjectAccessControl> patched_acl = client.PatchObjectAcl(
bucket_name, object_name, entity,
gcs::ObjectAccessControlPatchBuilder().set_role(role));
if (!patched_acl) throw std::runtime_error(patched_acl.status().message());
std::cout << "ACL entry for " << patched_acl->entity() << " in object "
<< patched_acl->object() << " in bucket " << patched_acl->bucket()
<< " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

Definition at line 2153 of file client.h.

◆ raw_client()

std::shared_ptr<internal::RawClient> google::cloud::storage::v1::Client::raw_client ( ) const
inline

Access the underlying RawClient.

Definition at line 250 of file client.h.

◆ ReadObject()

template<typename... Options>
ObjectReadStream google::cloud::storage::v1::Client::ReadObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

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.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DisableCrc32cChecksum, DisableMD5Hash, IfGenerationMatch, EncryptionKey, Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, ReadFromOffset, ReadRange, ReadLast and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
int count = 0;
std::string line;
while (std::getline(stream, line, '\n')) {
++count;
}
std::cout << "The object has " << count << " lines\n";
}
Example
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::int64_t start, std::int64_t end) {
gcs::ObjectReadStream stream =
client.ReadObject(bucket_name, object_name, gcs::ReadRange(start, end));
int count = 0;
std::string line;
while (std::getline(stream, line, '\n')) {
std::cout << line << "\n";
++count;
}
std::cout << "The requested range has " << count << " lines\n";
}
Example: read a object encrypted with a CSEK.
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& base64_aes256_key) {
gcs::ObjectReadStream stream =
client.ReadObject(bucket_name, object_name,
gcs::EncryptionKey::FromBase64Key(base64_aes256_key));
std::string data(std::istreambuf_iterator<char>{stream}, {});
std::cout << "The object contents are: " << data << "\n";
}

Definition at line 1085 of file client.h.

◆ ResumeRewriteObject()

template<typename... Options>
ObjectRewriter google::cloud::storage::v1::Client::ResumeRewriteObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
std::string  rewrite_token,
Options &&...  options 
)
inline

Creates an ObjectRewriter to resume a previously created rewrite.

Applications use this function to resume a rewrite operation, possibly created with RewriteObject(). Rewrite can reliably copy objects across location boundaries, and can rewrite objects with different encryption keys. For large objects this operation can take a long time, thus applications should consider checkpointing the rewrite token (accessible in the ObjectRewriter) and restarting the operation in the event the program is terminated.

Note
Application developers should be aware that rewriting large objects may take multiple hours. Multiple calls to ObjectRewriter::Iterate() may be required to completely rewrite an object.
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
rewrite_tokenthe token from a previous successful rewrite iteration. Can be the empty string, in which case this starts a new rewrite operation.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& rewrite_token) {
gcs::ObjectRewriter rewriter = client.ResumeRewriteObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, rewrite_token,
gcs::MaxBytesRewrittenPerCall(1024 * 1024));
auto callback = [](StatusOr<gcs::RewriteProgress> const& progress) {
if (!progress) throw std::runtime_error(progress.status().message());
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
StatusOr<gcs::ObjectMetadata> metadata =
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}

Definition at line 1550 of file client.h.

◆ RewriteObject()

template<typename... Options>
ObjectRewriter google::cloud::storage::v1::Client::RewriteObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

Creates an ObjectRewriter to copy the source object.

Applications use this function to reliably copy objects across location boundaries, and to rewrite objects with different encryption keys. The operation returns a ObjectRewriter, which the application can use to initiate the copy and to iterate if the copy requires more than one call to complete.

Note
Application developers should be aware that rewriting large objects may take multiple hours. Multiple calls to ObjectRewriter::Iterate() may be required to completely rewrite an object.
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
gcs::ObjectRewriter rewriter =
client.RewriteObject(source_bucket_name, source_object_name,
destination_bucket_name, destination_object_name);
auto callback = [](StatusOr<gcs::RewriteProgress> const& progress) {
if (!progress) throw std::runtime_error(progress.status().message());
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
StatusOr<gcs::ObjectMetadata> metadata =
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& rewrite_token) {
gcs::ObjectRewriter rewriter = client.ResumeRewriteObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, rewrite_token,
gcs::MaxBytesRewrittenPerCall(1024 * 1024));
auto callback = [](StatusOr<gcs::RewriteProgress> const& progress) {
if (!progress) throw std::runtime_error(progress.status().message());
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
StatusOr<gcs::ObjectMetadata> metadata =
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}

Definition at line 1498 of file client.h.

◆ RewriteObjectBlocking()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::RewriteObjectBlocking ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

Rewrites the object, blocking until the rewrite completes, and returns the resulting ObjectMetadata.

Applications use this function to reliably copy objects across location boundaries, and to rewrite objects with different encryption keys. The operation blocks until the rewrite completes, and returns the resulting ObjectMetadata.

Note
Application developers should be aware that rewriting large objects may take multiple hours. In such cases the application should consider using RewriteObject() or ResumeRewriteObject().
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Returns
The metadata of the newly created object.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name);
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Rewrote object " << destination_object_name
<< " Metadata: " << *metadata << "\n";
}
Example: using rewrite object to rotate the encryption key
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& old_key_base64,
std::string const& new_key_base64) {
StatusOr<gcs::ObjectMetadata> object_metadata =
client.RewriteObjectBlocking(
bucket_name, object_name, bucket_name, object_name,
gcs::SourceEncryptionKey::FromBase64Key(old_key_base64),
gcs::EncryptionKey::FromBase64Key(new_key_base64));
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
std::cout << "Rotated key on object " << object_metadata->name()
<< " in bucket " << object_metadata->bucket()
<< "\nFull Metadata: " << *object_metadata << "\n";
}
Example: using rewrite object to rename an object
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& old_object_name, std::string const& new_object_name) {
StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
bucket_name, old_object_name, bucket_name, new_object_name);
if (!metadata) throw std::runtime_error(metadata.status().message());
google::cloud::Status status =
client.DeleteObject(bucket_name, old_object_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Renamed " << old_object_name << " to " << new_object_name
<< " in bucket " << bucket_name << "\n";
}

Definition at line 1608 of file client.h.

◆ SetBucketIamPolicy()

template<typename... Options>
StatusOr<IamPolicy> google::cloud::storage::v1::Client::SetBucketIamPolicy ( std::string const &  bucket_name,
IamPolicy const &  iam_policy,
Options &&...  options 
)
inline

Sets the IAM Policy 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 between legacy Bucket ACLs and IAM policies.

Consult the documentation 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.
Parameters
bucket_namequery metadata information about this bucket.
iam_policythe new IAM policy.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Deprecated:
this function is deprecated; it doesn't support conditional bindings and will not support any other features to come; please use SetNativeBucketIamPolicy instead. TODO(#2857): Use proper deprecation attributes.
Example: adding a new member
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
StatusOr<google::cloud::IamPolicy> policy =
client.GetBucketIamPolicy(bucket_name);
if (!policy) throw std::runtime_error(policy.status().message());
policy->bindings.AddMember(role, member);
StatusOr<google::cloud::IamPolicy> updated =
client.SetBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
Example: removing a IAM member
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
StatusOr<google::cloud::IamPolicy> policy =
client.GetBucketIamPolicy(bucket_name);
if (!policy) throw std::runtime_error(policy.status().message());
policy->bindings.RemoveMember(role, member);
StatusOr<google::cloud::IamPolicy> updated =
client.SetBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
See also
google::cloud::v1::IamPolicy for details about the IamPolicy class.

Definition at line 698 of file client.h.

◆ SetNativeBucketIamPolicy()

template<typename... Options>
StatusOr<NativeIamPolicy> google::cloud::storage::v1::Client::SetNativeBucketIamPolicy ( std::string const &  bucket_name,
NativeIamPolicy const &  iam_policy,
Options &&...  options 
)
inline

Sets the native IAM Policy 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 between legacy Bucket ACLs and IAM policies.

Consult the documentation 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.
Parameters
bucket_namequery metadata information about this bucket.
iam_policythe new IAM policy.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example: adding a new member
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::runtime_error(policy.status().message());
policy->set_version(3);
for (auto& binding : policy->bindings()) {
if (binding.role() != role || binding.has_condition()) {
continue;
}
auto& members = binding.members();
if (std::find(members.begin(), members.end(), member) == members.end()) {
members.emplace_back(member);
}
}
auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
Example: removing a IAM member
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::runtime_error(policy.status().message());
policy->set_version(3);
std::vector<google::cloud::storage::NativeIamBinding> updated_bindings;
for (auto& binding : policy->bindings()) {
auto& members = binding.members();
if (binding.role() == role && !binding.has_condition()) {
members.erase(std::remove(members.begin(), members.end(), member),
members.end());
}
if (!members.empty()) {
updated_bindings.emplace_back(std::move(binding));
}
}
policy->bindings() = std::move(updated_bindings);
auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
See also
google::cloud::v1::IamPolicy for details about the IamPolicy class.

Definition at line 752 of file client.h.

◆ TestBucketIamPermissions()

template<typename... Options>
StatusOr<std::vector<std::string> > google::cloud::storage::v1::Client::TestBucketIamPermissions ( std::string  bucket_name,
std::vector< std::string >  permissions,
Options &&...  options 
)
inline

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 for a more detailed description of IAM policies their use in Google Cloud Storage.

Parameters
bucket_namequery metadata information about this bucket.
permissionsthe list of permissions to check.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::vector<std::string> const& permissions) {
StatusOr<std::vector<std::string>> actual_permissions =
client.TestBucketIamPermissions(bucket_name, permissions);
if (!actual_permissions) {
throw std::runtime_error(actual_permissions.status().message());
}
if (actual_permissions->empty()) {
std::cout << "The caller does not hold any of the tested permissions the"
<< " bucket " << bucket_name << "\n";
return;
}
std::cout << "The caller is authorized for the following permissions on "
<< bucket_name << ": ";
for (auto const& permission : *actual_permissions) {
std::cout << "\n " << permission;
}
std::cout << "\n";
}

Definition at line 788 of file client.h.

◆ UpdateBucket()

template<typename... Options>
StatusOr<BucketMetadata> google::cloud::storage::v1::Client::UpdateBucket ( std::string  bucket_name,
BucketMetadata  metadata,
Options &&...  options 
)
inline

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.

Parameters
bucket_namethe name of the new bucket.
metadatathe new metadata for the Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case,IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
StatusOr<gcs::BucketMetadata> meta = client.GetBucketMetadata(bucket_name);
if (!meta) throw std::runtime_error(meta.status().message());
meta->set_storage_class(storage_class);
StatusOr<gcs::BucketMetadata> updated_meta =
client.UpdateBucket(bucket_name, *meta);
if (!updated_meta) {
throw std::runtime_error(updated_meta.status().message());
}
std::cout << "Updated the storage class in " << updated_meta->name()
<< " to " << updated_meta->storage_class() << "."
<< "\nFull metadata:" << *updated_meta << "\n";
}
See also
Before enabling Bucket Policy Only please review the feature documentation, as well as "Should you use Bucket Policy Only?".

Definition at line 468 of file client.h.

◆ UpdateBucketAcl()

template<typename... Options>
StatusOr<BucketAccessControl> google::cloud::storage::v1::Client::UpdateBucketAcl ( std::string const &  bucket_name,
BucketAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing bucket ACL.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
gcs::BucketAccessControl desired_acl =
gcs::BucketAccessControl().set_entity(entity).set_role(role);
StatusOr<gcs::BucketAccessControl> updated_acl =
client.UpdateBucketAcl(bucket_name, desired_acl);
if (!updated_acl) throw std::runtime_error(updated_acl.status().message());
std::cout << "Bucket ACL updated. The ACL entry for "
<< updated_acl->entity() << " in bucket " << updated_acl->bucket()
<< " is " << *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 1791 of file client.h.

◆ UpdateDefaultObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::UpdateDefaultObjectAcl ( std::string const &  bucket_name,
ObjectAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing default object ACL.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::ObjectAccessControl> original_acl =
client.GetDefaultObjectAcl(bucket_name, entity);
if (!original_acl) {
throw std::runtime_error(original_acl.status().message());
}
original_acl->set_role(role);
StatusOr<gcs::ObjectAccessControl> updated_acl =
client.UpdateDefaultObjectAcl(bucket_name, *original_acl);
if (!updated_acl) {
throw std::runtime_error(updated_acl.status().message());
}
std::cout << "Default Object ACL entry for " << updated_acl->entity()
<< " in bucket " << updated_acl->bucket() << " is now "
<< *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

Definition at line 2344 of file client.h.

◆ UpdateHmacKey()

template<typename... Options>
StatusOr<HmacKeyMetadata> google::cloud::storage::v1::Client::UpdateHmacKey ( std::string  access_id,
HmacKeyMetadata  resource,
Options &&...  options 
)
inline

Update an existing HMAC key in a given project.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
resourcethe desired changes to the HMAC key resource. Only the state field may be changed. The etag field may be set but it is only used as a pre-condition, the application cannot set the etag.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This operation is only idempotent if the etag attribute in resource is set, or if the IfMatchEtag option is set.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id,
std::string const& state) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(std::move(state)));
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "The updated HMAC key metadata is: " << *updated << "\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

Definition at line 2718 of file client.h.

◆ UpdateObject()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::UpdateObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadata  metadata,
Options &&...  options 
)
inline

Updates the metadata in a Google Cloud Storage Object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
metadatathe new metadata for the Object. Only the writeable fields accepted by the Objects: update API are used, all other fields are ignored. In particular, note that bucket and name are ignored in favor of bucket_name and object_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& key,
std::string const& value) {
StatusOr<gcs::ObjectMetadata> object_metadata =
client.GetObjectMetadata(bucket_name, object_name);
if (!object_metadata) {
throw std::runtime_error(object_metadata.status().message());
}
gcs::ObjectMetadata desired = *object_metadata;
desired.mutable_metadata().emplace(key, value);
StatusOr<gcs::ObjectMetadata> updated =
client.UpdateObject(bucket_name, object_name, desired,
gcs::Generation(object_metadata->generation()));
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

Definition at line 1343 of file client.h.

◆ UpdateObjectAcl()

template<typename... Options>
StatusOr<ObjectAccessControl> google::cloud::storage::v1::Client::UpdateObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
ObjectAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing object ACL.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
StatusOr<gcs::ObjectAccessControl> current_acl =
client.GetObjectAcl(bucket_name, object_name, entity);
if (!current_acl) throw std::runtime_error(current_acl.status().message());
current_acl->set_role(role);
StatusOr<gcs::ObjectAccessControl> updated_acl =
client.UpdateObjectAcl(bucket_name, object_name, *current_acl);
if (!updated_acl) throw std::runtime_error(updated_acl.status().message());
std::cout << "ACL entry for " << updated_acl->entity() << " in object "
<< updated_acl->object() << " in bucket " << updated_acl->bucket()
<< " is now " << *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

Definition at line 2061 of file client.h.

◆ UploadFile()

template<typename... Options>
StatusOr<ObjectMetadata> google::cloud::storage::v1::Client::UploadFile ( std::string const &  file_name,
std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

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.
Parameters
file_namethe name of the file to be uploaded.
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa 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, UploadFromOffset, UploadLimit and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
std::string const& bucket_name, std::string const& object_name) {
// Note that the client library automatically computes a hash on the
// client-side to verify data integrity during transmission.
StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
file_name, bucket_name, object_name, gcs::IfGenerationMatch(0));
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Uploaded " << file_name << " to object " << metadata->name()
<< " in bucket " << metadata->bucket()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: manually selecting a resumable upload
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
std::string const& bucket_name, std::string const& object_name) {
// Note that the client library automatically computes a hash on the
// client-side to verify data integrity during transmission.
StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
file_name, bucket_name, object_name, gcs::IfGenerationMatch(0),
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Uploaded " << file_name << " to object " << metadata->name()
<< " in bucket " << metadata->bucket()
<< "\nFull metadata: " << *metadata << "\n";
}

Definition at line 1231 of file client.h.

◆ WriteObject()

template<typename... Options>
ObjectWriteStream google::cloud::storage::v1::Client::WriteObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

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.

This function always uses resumable uploads. The application can provide a RestoreResumableUploadSession() option to resume a previously created upload. The returned object has accessors to query the session id and the next byte expected by GCS.

Note
When resuming uploads it is the application's responsibility to save the session id to restart the upload later. Likewise, it is the application's responsibility to query the next expected byte and send the remaining data without gaps or duplications.

For small uploads we recommend using InsertObject, consult the documentation for details.

If the application does not provide a RestoreResumableUploadSession() option, or it provides the NewResumableUploadSession() option then a new resumable upload session is created.

To perform efficient uploads applications should consider using unbuffered I/O operations on the returned stream (aka std::ostream::write()). Application developers should consider the following properties of resumable uploads to use this API efficiently:

  • Resumable uploads are performed in "chunks" sent to GCS, these chunks are committed and saved at least until the session is deleted (or garbage collected, approximately after 7 days.)
  • The size of these chunks (except the last one) must be a multiple of the upload quantum (256KiB).
  • Uploading a chunk that is not a multiple of the quantum implicitly finalizes the upload.

The library, therefore, must buffer any data that does not fill a full quantum. If you are interested in avoiding data copies you should always provide the library with buffers that fit in this quantum.

In addition, applications should consider providing large buffers as the library waits until GCS confirms that the chunk is uploaded before returning control to the application. Naturally there is a tradeoff between copying data to prepare large buffers vs. sending many small buffers and paying the network costs for each. We recommend that you use buffers in the 16MiB to 64MiB range for best performance.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa 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, WithObjectMetadata and UploadContentLength.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, int desired_line_count) {
std::string const text = "Lorem ipsum dolor sit amet";
gcs::ObjectWriteStream stream =
client.WriteObject(bucket_name, object_name);
for (int lineno = 0; lineno != desired_line_count; ++lineno) {
// Add 1 to the counter, because it is conventional to number lines
// starting at 1.
stream << (lineno + 1) << ": " << text << "\n";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = std::move(stream).metadata();
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Successfully wrote to object " << metadata->name()
<< " its size is: " << metadata->size()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: write an object with a CMEK.
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& kms_key_name) {
gcs::ObjectWriteStream stream = client.WriteObject(
bucket_name, object_name, gcs::KmsKeyName(kms_key_name));
// Line numbers start at 1.
for (int lineno = 1; lineno <= 10; ++lineno) {
stream << lineno << ": placeholder text for CMEK example.\n";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = std::move(stream).metadata();
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Successfully wrote to object " << metadata->name()
<< " its size is: " << metadata->size()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: starting a resumable upload.
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
gcs::ObjectWriteStream stream = client.WriteObject(
bucket_name, object_name, gcs::NewResumableUploadSession());
std::cout << "Created resumable upload: " << stream.resumable_session_id()
<< "\n";
// As it is customary in C++, the destructor automatically closes the
// stream, that would finish the upload and create the object. For this
// example we want to restore the session as-if the application had crashed,
// where no destructors get called.
stream << "This data will not get uploaded, it is too small\n";
std::move(stream).Suspend();
}
Example: resuming a resumable upload.
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& session_id) {
// Restore a resumable upload stream, the library automatically queries the
// state of the upload and discovers the next expected byte.
gcs::ObjectWriteStream stream =
client.WriteObject(bucket_name, object_name,
if (!stream.IsOpen() && stream.metadata().ok()) {
std::cout << "The upload has already been finalized. The object "
<< "metadata is: " << *stream.metadata() << "\n";
}
if (stream.next_expected_byte() == 0) {
// In this example we create a small object, smaller than the resumable
// upload quantum (256 KiB), so either all the data is there or not.
// Applications use `next_expected_byte()` to find the position in their
// input where they need to start uploading.
stream << R"""(
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
)""";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = stream.metadata();
if (!metadata) throw std::runtime_error(metadata.status().message());
std::cout << "Upload completed, the new object metadata is: " << *metadata
<< "\n";
}
See also
Resumable Uploads for more information about resumable uploads.

Definition at line 1192 of file client.h.

Friends And Related Function Documentation

◆ testing::ClientTester

friend class testing::ClientTester
friend

Definition at line 3190 of file client.h.