diff --git a/google/cloud/storage/internal/connection_impl.cc b/google/cloud/storage/internal/connection_impl.cc index 0f5331211b41d..c3d66ab1ef947 100644 --- a/google/cloud/storage/internal/connection_impl.cc +++ b/google/cloud/storage/internal/connection_impl.cc @@ -14,6 +14,7 @@ #include "google/cloud/internal/disable_deprecation_warnings.inc" #include "google/cloud/storage/internal/connection_impl.h" +#include "google/cloud/storage/internal/hash_values.h" #include "google/cloud/storage/internal/hedged_object_read_source.h" #include "google/cloud/storage/internal/hedged_read_metrics.h" #include "google/cloud/storage/internal/retry_logging.h" @@ -33,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +55,17 @@ using ::google::cloud::storage_internal::AddFeaturesHeader; using ::google::cloud::storage_internal::FeatureBit; using ::google::cloud::storage_internal::TrackedFeature; +void AppendUploadChunkDiagnostics( + std::ostream& os, UploadChunkRequest const& request, + QueryResumableUploadResponse const& response) { + os << " session_id=" + << (request.upload_session_url().empty() ? "" : "[censored]") + << ", result=" << response << ", offset=" << request.offset() + << ", range=<" << request.RangeHeader() << ">" + << ", payload_size=" << request.payload_size() << ", known_object_hashes={" + << Format(request.known_object_hashes()) << "}"; +} + // Returns an error if the response contains an unexpected (or invalid) // committed size. Status ValidateCommittedSize(UploadChunkRequest const& request, @@ -72,9 +85,7 @@ Status ValidateCommittedSize(UploadChunkRequest const& request, << " (https://github.com/googleapis/google-cloud-cpp/issues/new)." << " Please include as much information as you can including this" << " message and the following details:"; - os << " session_id=" << request.upload_session_url(); - os << ", result=" << response; - os << ", request=" << request; + AppendUploadChunkDiagnostics(os, request, response); return google::cloud::internal::InternalError(std::move(os).str(), GCP_ERROR_INFO()); } @@ -100,9 +111,7 @@ Status ValidateCommittedSize(UploadChunkRequest const& request, << " (https://github.com/googleapis/google-cloud-cpp/issues/new)." << " Please include as much information as you can including this" << " message and the following details:"; - os << " session_id=" << request.upload_session_url(); - os << ", result=" << response; - os << ", request=" << request; + AppendUploadChunkDiagnostics(os, request, response); return google::cloud::internal::InternalError(std::move(os).str(), GCP_ERROR_INFO()); } diff --git a/google/cloud/storage/internal/connection_impl_file_upload_test.cc b/google/cloud/storage/internal/connection_impl_file_upload_test.cc index f2f5eec97c8ca..8f9d048ed8195 100644 --- a/google/cloud/storage/internal/connection_impl_file_upload_test.cc +++ b/google/cloud/storage/internal/connection_impl_file_upload_test.cc @@ -213,6 +213,53 @@ TEST_F(ConnectionImplFileUploadTest, UploadFileErrorsFormatEncryptionKey) { Not(HasSubstr(kKeyBase64))))); } +/// @test Verify `UseResumableUploadSession` option formatting in resumable +/// file-upload error statuses. +TEST_F(ConnectionImplFileUploadTest, UploadFileResumableFormatsSessionOption) { + constexpr std::string_view kSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/test-bucket/" + "o?uploadType=resumable&upload_id=xa298sd_sdlkj2"; + constexpr std::string_view kSessionToken = "xa298sd_sdlkj2"; + + std::shared_ptr connection = MakeConnection(); + std::string const contents = "0123456789"; + TempFile temp(contents); + + ResumableUploadRequest resumable_missing("test-bucket", "test-object"); + resumable_missing.set_option( + RestoreResumableUploadSession(std::string{kSessionUrl})); + StatusOr> const missing_result = + connection->UploadFileResumable("/no/such/file/exists.txt", + resumable_missing); + EXPECT_THAT(missing_result, + StatusIs(StatusCode::kNotFound, + AllOf(HasSubstr("resumable-upload=[censored]"), + Not(HasSubstr(kSessionUrl)), + Not(HasSubstr(kSessionToken))))); + + ResumableUploadRequest resumable_offset("test-bucket", "test-object"); + resumable_offset.set_multiple_options( + RestoreResumableUploadSession(std::string{kSessionUrl}), + UploadFromOffset(contents.size() + 1)); + StatusOr> const offset_result = + connection->UploadFileResumable(temp.name(), resumable_offset); + EXPECT_THAT(offset_result, + StatusIs(StatusCode::kInvalidArgument, + AllOf(HasSubstr("resumable-upload=[censored]"), + Not(HasSubstr(kSessionUrl)), + Not(HasSubstr(kSessionToken))))); + + ResumableUploadRequest new_session_missing("test-bucket", "test-object"); + new_session_missing.set_option(NewResumableUploadSession()); + StatusOr> const new_session_result = + connection->UploadFileResumable("/no/such/file/exists.txt", + new_session_missing); + EXPECT_THAT(new_session_result, + StatusIs(StatusCode::kNotFound, + AllOf(HasSubstr("resumable-upload=,"), + Not(HasSubstr("resumable-upload=[censored]"))))); +} + } // namespace } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/connection_impl_test.cc b/google/cloud/storage/internal/connection_impl_test.cc index 0f59b5d082378..135c1644241e3 100644 --- a/google/cloud/storage/internal/connection_impl_test.cc +++ b/google/cloud/storage/internal/connection_impl_test.cc @@ -32,7 +32,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -53,6 +55,7 @@ using ::google::cloud::testing_util::MockMeter; using ::google::cloud::testing_util::MockMeterProvider; using ::google::cloud::testing_util::StatusIs; using ::testing::_; +using ::testing::AllOf; using ::testing::AtLeast; using ::testing::ByMove; using ::testing::ElementsAre; @@ -468,6 +471,189 @@ TEST(RetryClientTest, UploadChunkHandleOvercommit) { HasSubstr("If you believe this is a bug in the client library"))); } +struct UploadChunkStatusFormatCase { + std::string_view name; + std::string_view session_id; + std::string_view session_marker; +}; + +class RetryClientUploadChunkFormatTest + : public ::testing::TestWithParam {}; + +/// @test Verify `UploadChunk` rollback errors format `session_id` and chunk +/// metadata fields. +TEST_P(RetryClientUploadChunkFormatTest, UploadChunkRollbackFormatsStatus) { + UploadChunkStatusFormatCase const& param = GetParam(); + constexpr std::uint64_t kOffset = 1024; + constexpr std::uint64_t kRollback = 512; + std::string const payload = + "chunk-payload-marker-one" + std::string(200, 'A'); + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, options); // Required in StorageConnectionImpl::Create() + EXPECT_CALL(*mock, UploadChunk) + .WillOnce(Return(QueryResumableUploadResponse{kRollback, std::nullopt})); + + std::shared_ptr client = + StorageConnectionImpl::Create(std::move(mock)); + google::cloud::internal::OptionsSpan const span( + BasicTestPolicies().set( + StrictIdempotencyPolicy().clone())); + + UploadChunkRequest request(std::string{param.session_id}, kOffset, + {{payload}}, CreateNullHashFunction(), + HashValues{"crc32c-val", "md5-val"}); + request.set_option(CustomHeader("x-custom-header", "custom-header-value")); + + StatusOr const response = + client->UploadChunk(request); + EXPECT_THAT( + response, + StatusIs( + StatusCode::kInternal, + AllOf(HasSubstr("session_id=[censored]"), + HasSubstr("result=UploadChunkResponse={committed_size=512, " + "payload={}}"), + HasSubstr("offset=1024"), + HasSubstr("range="), + HasSubstr("payload_size=224"), + HasSubstr("known_object_hashes={crc32c=crc32c-val, " + "md5=md5-val}"), + Not(HasSubstr(param.session_id)), + Not(HasSubstr(param.session_marker)), + Not(HasSubstr("chunk-payload-marker-one")), + Not(HasSubstr("AAAA")), Not(HasSubstr("x-custom-header")), + Not(HasSubstr("custom-header-value")), + Not(HasSubstr("request="))))); +} + +/// @test Verify `UploadChunk` overcommit errors format `session_id` and chunk +/// metadata fields across multi-buffer payloads. +TEST_P(RetryClientUploadChunkFormatTest, UploadChunkOvercommitFormatsStatus) { + UploadChunkStatusFormatCase const& param = GetParam(); + constexpr std::uint64_t kExcess = 1024; + std::string const buffer_one = + "chunk-payload-marker-one" + std::string(200, 'A'); + std::string const buffer_two = + "chunk-payload-marker-two" + std::string(250, 'B'); + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, options); // Required in StorageConnectionImpl::Create() + EXPECT_CALL(*mock, UploadChunk) + .WillOnce(Return(QueryResumableUploadResponse{kExcess, std::nullopt})); + + std::shared_ptr client = + StorageConnectionImpl::Create(std::move(mock)); + google::cloud::internal::OptionsSpan const span( + BasicTestPolicies().set( + StrictIdempotencyPolicy().clone())); + + UploadChunkRequest request( + std::string{param.session_id}, 0, {{buffer_one, buffer_two}}, + CreateNullHashFunction(), HashValues{"crc32c-val", "md5-val"}); + request.set_option(CustomHeader("x-custom-header", "custom-header-value")); + + StatusOr const response = + client->UploadChunk(request); + EXPECT_THAT( + response, + StatusIs( + StatusCode::kInternal, + AllOf(HasSubstr("session_id=[censored]"), + HasSubstr("result=UploadChunkResponse={committed_size=1024, " + "payload={}}"), + HasSubstr("offset=0"), + HasSubstr("range="), + HasSubstr("payload_size=498"), + HasSubstr("known_object_hashes={crc32c=crc32c-val, " + "md5=md5-val}"), + Not(HasSubstr(param.session_id)), + Not(HasSubstr(param.session_marker)), + Not(HasSubstr("chunk-payload-marker-one")), + Not(HasSubstr("chunk-payload-marker-two")), + Not(HasSubstr("AAAA")), Not(HasSubstr("BBBB")), + Not(HasSubstr("x-custom-header")), + Not(HasSubstr("custom-header-value")), + Not(HasSubstr("request="))))); +} + +INSTANTIATE_TEST_SUITE_P( + SessionShapes, RetryClientUploadChunkFormatTest, + ::testing::Values( + UploadChunkStatusFormatCase{ + "RestUrl", + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=xa298sd_sdlkj2", + "xa298sd_sdlkj2"}, + UploadChunkStatusFormatCase{ + "GrpcResourceId", + "projects/_/buckets/my-bucket/uploads/grpc-upload-token-42", + "grpc-upload-token-42"}, + UploadChunkStatusFormatCase{"OpaqueToken", "opaque-upload-token-99", + "opaque-upload-token-99"}), + [](::testing::TestParamInfo const& info) { + return std::string{info.param.name}; + }); + +/// @test Verify `UploadChunk` mismatch errors preserve an empty `session_id`. +TEST(RetryClientTest, UploadChunkFormatsEmptySessionId) { + constexpr std::uint64_t kRollbackOffset = 1024; + constexpr std::uint64_t kRollbackCommitted = 512; + constexpr std::uint64_t kOvercommitCommitted = 1024; + std::string const payload = + "chunk-payload-marker-one" + std::string(200, 'A'); + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, options); // Required in StorageConnectionImpl::Create() + EXPECT_CALL(*mock, UploadChunk) + .WillOnce(Return( + QueryResumableUploadResponse{kRollbackCommitted, std::nullopt})) + .WillOnce(Return( + QueryResumableUploadResponse{kOvercommitCommitted, std::nullopt})); + + std::shared_ptr client = + StorageConnectionImpl::Create(std::move(mock)); + google::cloud::internal::OptionsSpan const span( + BasicTestPolicies().set( + StrictIdempotencyPolicy().clone())); + + UploadChunkRequest const rollback_request( + "", kRollbackOffset, {{payload}}, CreateNullHashFunction(), + HashValues{"crc32c-val", "md5-val"}); + StatusOr const rollback_response = + client->UploadChunk(rollback_request); + EXPECT_THAT( + rollback_response, + StatusIs( + StatusCode::kInternal, + AllOf(HasSubstr("session_id=, " + "result=UploadChunkResponse={committed_size=512, " + "payload={}}, offset=1024, " + "range=, " + "payload_size=224, " + "known_object_hashes={crc32c=crc32c-val, " + "md5=md5-val}"), + Not(HasSubstr("[censored]"))))); + + UploadChunkRequest const overcommit_request( + "", 0, {{payload}}, CreateNullHashFunction(), + HashValues{"crc32c-val", "md5-val"}); + StatusOr const overcommit_response = + client->UploadChunk(overcommit_request); + EXPECT_THAT( + overcommit_response, + StatusIs( + StatusCode::kInternal, + AllOf(HasSubstr("session_id=, " + "result=UploadChunkResponse={committed_size=1024, " + "payload={}}, offset=0, " + "range=, " + "payload_size=224, " + "known_object_hashes={crc32c=crc32c-val, " + "md5=md5-val}"), + Not(HasSubstr("[censored]"))))); +} + /// @test Verify that retry exhaustion following a short write fails. TEST(RetryClientTest, UploadChunkExhausted) { auto const quantum = UploadChunkRequest::kChunkSizeQuantum; diff --git a/google/cloud/storage/internal/logging_stub_test.cc b/google/cloud/storage/internal/logging_stub_test.cc index 6c8c09f23d386..3c50b0f371c8d 100644 --- a/google/cloud/storage/internal/logging_stub_test.cc +++ b/google/cloud/storage/internal/logging_stub_test.cc @@ -22,8 +22,10 @@ #include "google/cloud/common_options.h" #include "google/cloud/log.h" #include "google/cloud/testing_util/scoped_environment.h" +#include "google/cloud/testing_util/status_matchers.h" #include #include +#include #include #include #include @@ -38,7 +40,9 @@ namespace { using ::google::cloud::storage::testing::MockGenericStub; using ::google::cloud::storage::testing::canonical_errors::TransientError; +using ::google::cloud::testing_util::IsOk; using ::google::cloud::testing_util::ScopedEnvironment; +using ::testing::AllOf; using ::testing::HasSubstr; using ::testing::Not; using ::testing::Return; @@ -292,6 +296,162 @@ TEST_F(LoggingStubTest, ReadObjectSuccessLogsOnlyTheRequest) { ReadObjectRangeRequest("my-bucket", "my-object")); } +/// @test Verify `LoggingStub::CreateResumableUpload` formats session options +/// and response identifiers while returning the response unchanged. +TEST_F(LoggingStubTest, CreateResumableUpload) { + constexpr std::string_view kRequestSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=req-session-token-1"; + constexpr std::string_view kRequestToken = "req-session-token-1"; + constexpr std::string_view kResponseSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=resp-session-token-2"; + constexpr std::string_view kResponseToken = "resp-session-token-2"; + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, CreateResumableUpload) + .WillOnce(Return( + CreateResumableUploadResponse{std::string{kResponseSessionUrl}})); + + EXPECT_CALL(*log_backend_, ProcessWithOwnership) + .WillOnce([kRequestSessionUrl, kRequestToken](LogRecord const& lr) { + EXPECT_THAT(lr.message, AllOf(HasSubstr(" << "), + HasSubstr("ResumableUploadRequest={"), + HasSubstr("resumable-upload=[censored]"), + Not(HasSubstr(kRequestSessionUrl)), + Not(HasSubstr(kRequestToken)))); + }) + .WillOnce([kResponseSessionUrl, kResponseToken](LogRecord const& lr) { + EXPECT_THAT( + lr.message, + AllOf(HasSubstr(" >> "), + HasSubstr( + "CreateResumableUploadResponse={upload_id=[censored]}"), + Not(HasSubstr(kResponseSessionUrl)), + Not(HasSubstr(kResponseToken)))); + }); + + LoggingStub client(std::move(mock)); + rest_internal::RestContext context; + ResumableUploadRequest request("my-bucket", "my-object"); + request.set_option( + RestoreResumableUploadSession(std::string{kRequestSessionUrl})); + StatusOr const actual = + client.CreateResumableUpload(context, Options{}, request); + ASSERT_THAT(actual, IsOk()); + EXPECT_EQ(actual->upload_id, kResponseSessionUrl); +} + +/// @test Verify `LoggingStub::QueryResumableUpload` formats session +/// identifiers while returning the response unchanged. +TEST_F(LoggingStubTest, QueryResumableUpload) { + constexpr std::string_view kSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=query-session-token-3"; + constexpr std::string_view kSessionToken = "query-session-token-3"; + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, QueryResumableUpload) + .WillOnce(Return(QueryResumableUploadResponse{1024, std::nullopt})); + + EXPECT_CALL(*log_backend_, ProcessWithOwnership) + .WillOnce([kSessionUrl, kSessionToken](LogRecord const& lr) { + EXPECT_THAT( + lr.message, + AllOf(HasSubstr(" << "), + HasSubstr("QueryResumableUploadRequest={upload_session_url=[" + "censored]"), + Not(HasSubstr(kSessionUrl)), Not(HasSubstr(kSessionToken)))); + }) + .WillOnce([](LogRecord const& lr) { + EXPECT_THAT(lr.message, + AllOf(HasSubstr(" >> "), HasSubstr("committed_size=1024"))); + }); + + LoggingStub client(std::move(mock)); + rest_internal::RestContext context; + StatusOr const actual = + client.QueryResumableUpload( + context, Options{}, + QueryResumableUploadRequest(std::string{kSessionUrl})); + ASSERT_THAT(actual, IsOk()); + EXPECT_EQ(actual->committed_size, 1024); +} + +/// @test Verify `LoggingStub::DeleteResumableUpload` formats session +/// identifiers while returning the response unchanged. +TEST_F(LoggingStubTest, DeleteResumableUpload) { + constexpr std::string_view kSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=delete-session-token-4"; + constexpr std::string_view kSessionToken = "delete-session-token-4"; + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, DeleteResumableUpload).WillOnce(Return(EmptyResponse{})); + + EXPECT_CALL(*log_backend_, ProcessWithOwnership) + .WillOnce([kSessionUrl, kSessionToken](LogRecord const& lr) { + EXPECT_THAT( + lr.message, + AllOf(HasSubstr(" << "), + HasSubstr("DeleteResumableUploadRequest={" + "upload_session_url=[censored]"), + Not(HasSubstr(kSessionUrl)), Not(HasSubstr(kSessionToken)))); + }) + .WillOnce([](LogRecord const& lr) { + EXPECT_THAT(lr.message, + AllOf(HasSubstr(" >> "), HasSubstr("payload={"))); + }); + + LoggingStub client(std::move(mock)); + rest_internal::RestContext context; + StatusOr const actual = client.DeleteResumableUpload( + context, Options{}, + DeleteResumableUploadRequest(std::string{kSessionUrl})); + EXPECT_THAT(actual, IsOk()); +} + +/// @test Verify `LoggingStub::UploadChunk` formats session identifiers and +/// payload size while returning the response unchanged. +TEST_F(LoggingStubTest, UploadChunk) { + constexpr std::string_view kSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/" + "o?uploadType=resumable&upload_id=chunk-session-token-5"; + constexpr std::string_view kSessionToken = "chunk-session-token-5"; + std::string const payload = "chunk-payload-marker" + std::string(200, 'A'); + + auto mock = std::make_unique(); + EXPECT_CALL(*mock, UploadChunk) + .WillOnce( + Return(QueryResumableUploadResponse{payload.size(), std::nullopt})); + + EXPECT_CALL(*log_backend_, ProcessWithOwnership) + .WillOnce([kSessionUrl, kSessionToken](LogRecord const& lr) { + EXPECT_THAT( + lr.message, + AllOf( + HasSubstr(" << "), + HasSubstr("UploadChunkRequest={upload_session_url=[censored]"), + HasSubstr("payload_size=220"), Not(HasSubstr(kSessionUrl)), + Not(HasSubstr(kSessionToken)), + Not(HasSubstr("chunk-payload-marker")), + Not(HasSubstr("AAAA")))); + }) + .WillOnce([](LogRecord const& lr) { + EXPECT_THAT(lr.message, + AllOf(HasSubstr(" >> "), HasSubstr("committed_size=220"))); + }); + + LoggingStub client(std::move(mock)); + rest_internal::RestContext context; + UploadChunkRequest const request(std::string{kSessionUrl}, 0, {{payload}}, + CreateNullHashFunction()); + StatusOr const actual = + client.UploadChunk(context, Options{}, request); + ASSERT_THAT(actual, IsOk()); + EXPECT_EQ(actual->committed_size, payload.size()); +} + class LoggingStubComponentTest : public LoggingStubTest, public ::testing::WithParamInterface {}; diff --git a/google/cloud/storage/internal/object_requests.cc b/google/cloud/storage/internal/object_requests.cc index 137986a0667e9..d282a68b506aa 100644 --- a/google/cloud/storage/internal/object_requests.cc +++ b/google/cloud/storage/internal/object_requests.cc @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -42,6 +43,11 @@ namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { +std::string_view FormatSessionId(std::string_view session_id) { + if (session_id.empty()) return ""; + return "[censored]"; +} + void DiffMetadata(ObjectMetadata const& original, ObjectMetadata const& updated, ObjectMetadataPatchBuilder& builder) { if (original.metadata() == updated.metadata()) return; @@ -476,7 +482,7 @@ std::ostream& operator<<(std::ostream& os, ResumableUploadRequest const& r) { std::ostream& operator<<(std::ostream& os, DeleteResumableUploadRequest const& r) { os << "DeleteResumableUploadRequest={upload_session_url=" - << r.upload_session_url(); + << FormatSessionId(r.upload_session_url()); r.DumpOptions(os, ", "); return os << "}"; } @@ -498,8 +504,8 @@ bool operator==(CreateResumableUploadResponse const& lhs, std::ostream& operator<<(std::ostream& os, CreateResumableUploadResponse const& r) { - return os << "CreateResumableUploadResponse={upload_id=" << r.upload_id - << "}"; + return os << "CreateResumableUploadResponse={upload_id=" + << FormatSessionId(r.upload_id) << "}"; } UploadChunkRequest::UploadChunkRequest( @@ -573,25 +579,18 @@ HashValues FinishHashes(UploadChunkRequest const& request) { } std::ostream& operator<<(std::ostream& os, UploadChunkRequest const& r) { - os << "UploadChunkRequest={upload_session_url=" << r.upload_session_url() - << ", range=<" << r.RangeHeader() << ">" << ", known_object_hashes={" - << Format(r.known_object_hashes()) << "}"; + os << "UploadChunkRequest={upload_session_url=" + << FormatSessionId(r.upload_session_url()) << ", range=<" + << r.RangeHeader() << ">" + << ", known_object_hashes={" << Format(r.known_object_hashes()) << "}"; r.DumpOptions(os, ", "); - os << ", payload={"; - auto constexpr kMaxOutputBytes = 128; - char const* sep = ""; - for (auto const& b : r.payload()) { - os << sep << "{" - << BinaryDataAsDebugString(b.data(), b.size(), kMaxOutputBytes) << "}"; - sep = ", "; - } - return os << "}}"; + return os << ", payload_size=" << r.payload_size() << "}"; } std::ostream& operator<<(std::ostream& os, QueryResumableUploadRequest const& r) { os << "QueryResumableUploadRequest={upload_session_url=" - << r.upload_session_url(); + << FormatSessionId(r.upload_session_url()); r.DumpOptions(os, ", "); return os << "}"; } diff --git a/google/cloud/storage/internal/object_requests_test.cc b/google/cloud/storage/internal/object_requests_test.cc index f20c815bcfa75..191b25c2d656f 100644 --- a/google/cloud/storage/internal/object_requests_test.cc +++ b/google/cloud/storage/internal/object_requests_test.cc @@ -21,8 +21,11 @@ #include "google/cloud/testing_util/status_matchers.h" #include #include +#include +#include #include #include +#include #include #include @@ -35,7 +38,9 @@ namespace { using ::google::cloud::testing_util::IsOk; using ::google::cloud::testing_util::StatusIs; +using ::testing::AllOf; using ::testing::ElementsAre; +using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Not; using ::testing::Pair; @@ -599,7 +604,8 @@ TEST(ObjectRequestsTest, DeleteResumableUpload) { std::ostringstream os; os << request; std::string actual = os.str(); - EXPECT_THAT(actual, HasSubstr("source-upload-session-url")); + EXPECT_THAT(actual, AllOf(HasSubstr("upload_session_url=[censored]"), + Not(HasSubstr("source-upload-session-url")))); } TEST(ObjectRequestsTest, UploadChunk) { @@ -618,8 +624,11 @@ TEST(ObjectRequestsTest, UploadChunk) { std::ostringstream os; os << request; std::string actual = os.str(); - EXPECT_THAT(actual, HasSubstr(url)); - EXPECT_THAT(actual, HasSubstr("")); + EXPECT_THAT(actual, + AllOf(HasSubstr("upload_session_url=[censored]"), + HasSubstr(""), + HasSubstr("payload_size=2048"), Not(HasSubstr(url)), + Not(HasSubstr("xa298sd_sdlkj2")), Not(HasSubstr("AAAA")))); } TEST(ObjectRequestsTest, UploadChunkRemainingChunk) { @@ -686,7 +695,9 @@ TEST(ObjectRequestsTest, QueryResumableUpload) { std::ostringstream os; os << request; std::string actual = os.str(); - EXPECT_THAT(actual, HasSubstr(url)); + EXPECT_THAT(actual, + AllOf(HasSubstr("upload_session_url=[censored]"), + Not(HasSubstr(url)), Not(HasSubstr("xa298sd_sdlkj2")))); } ObjectMetadata CreateObjectMetadataForTest() { @@ -1142,7 +1153,8 @@ TEST(CreateResumableUploadResponseTest, Base) { std::ostringstream os; os << actual; auto actual_str = os.str(); - EXPECT_THAT(actual_str, HasSubstr("upload_id=location-value")); + EXPECT_THAT(actual_str, + Eq("CreateResumableUploadResponse={upload_id=[censored]}")); } TEST(CreateResumableUploadResponseTest, NoLocation) { @@ -1226,6 +1238,232 @@ TEST(QueryResumableUploadResponseTest, NegativeEnd) { EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0--7"))); } +struct ResumableSessionFormatCase { + std::string_view name; + std::string_view session_id; +}; + +class ResumableSessionFormatTest + : public ::testing::TestWithParam {}; + +/// @test Verify resumable upload request and response stream operators format +/// session identifiers consistently while keeping accessors unchanged. +TEST_P(ResumableSessionFormatTest, FormatsSessionOutput) { + std::string const session_id{GetParam().session_id}; + + DeleteResumableUploadRequest delete_request(session_id); + delete_request.set_option(UserProject("my-project")); + EXPECT_EQ(delete_request.upload_session_url(), session_id); + std::ostringstream delete_os; + delete_os << delete_request; + EXPECT_THAT(delete_os.str(), + Eq("DeleteResumableUploadRequest={upload_session_url=[censored], " + "userProject=my-project}")); + + QueryResumableUploadRequest query_request(session_id); + query_request.set_option(QuotaUser("test-quota-user")); + EXPECT_EQ(query_request.upload_session_url(), session_id); + std::ostringstream query_os; + query_os << query_request; + EXPECT_THAT(query_os.str(), + Eq("QueryResumableUploadRequest={upload_session_url=[censored], " + "quotaUser=test-quota-user}")); + + CreateResumableUploadResponse const create_response{session_id}; + EXPECT_EQ(create_response.upload_id, session_id); + std::ostringstream create_os; + create_os << create_response; + EXPECT_THAT(create_os.str(), + Eq("CreateResumableUploadResponse={upload_id=[censored]}")); + + std::string const payload(128, 'Z'); + UploadChunkRequest chunk_request(session_id, 0, {{payload}}, + CreateNullHashFunction(), HashValues{}); + chunk_request.set_option(UserProject("my-project")); + EXPECT_EQ(chunk_request.upload_session_url(), session_id); + std::ostringstream chunk_os; + chunk_os << chunk_request; + EXPECT_THAT(chunk_os.str(), + Eq("UploadChunkRequest={upload_session_url=[censored], " + "range=, " + "known_object_hashes={}, userProject=my-project, " + "payload_size=128}")); + + UseResumableUploadSession const option = + RestoreResumableUploadSession(session_id); + EXPECT_TRUE(option.has_value()); + EXPECT_EQ(option.value(), session_id); + std::ostringstream option_os; + option_os << option; + EXPECT_THAT(option_os.str(), Eq("resumable-upload=[censored]")); + + ResumableUploadRequest resumable_request("source-bucket", "source-object"); + resumable_request.set_option(option); + std::ostringstream resumable_os; + resumable_os << resumable_request; + EXPECT_THAT(resumable_os.str(), + Eq("ResumableUploadRequest={bucket_name=source-bucket, " + "object_name=source-object, resumable-upload=[censored], " + "auto-finalize=enabled}")); +} + +INSTANTIATE_TEST_SUITE_P( + SessionShapes, ResumableSessionFormatTest, + ::testing::Values( + ResumableSessionFormatCase{ + "RestUrl", + "https://storage.googleapis.com/upload/storage/v1/b/myBucket/" + "o?uploadType=resumable&upload_id=xa298sd_sdlkj2"}, + ResumableSessionFormatCase{ + "GrpcResourceId", + "projects/_/buckets/myBucket/tokens/grpc-tok-123"}), + [](::testing::TestParamInfo const& info) { + return std::string{info.param.name}; + }); + +/// @test Verify resumable upload request and response stream operators preserve +/// empty session identifiers. +TEST(ObjectRequestsTest, ResumableUploadFormatsEmptySessionId) { + DeleteResumableUploadRequest delete_request(""); + delete_request.set_option(UserProject("my-project")); + EXPECT_EQ(delete_request.upload_session_url(), ""); + std::ostringstream delete_os; + delete_os << delete_request; + EXPECT_THAT(delete_os.str(), + Eq("DeleteResumableUploadRequest={upload_session_url=, " + "userProject=my-project}")); + + QueryResumableUploadRequest query_request(""); + query_request.set_option(QuotaUser("test-quota-user")); + EXPECT_EQ(query_request.upload_session_url(), ""); + std::ostringstream query_os; + query_os << query_request; + EXPECT_THAT(query_os.str(), + Eq("QueryResumableUploadRequest={upload_session_url=, " + "quotaUser=test-quota-user}")); + + CreateResumableUploadResponse const create_response{""}; + EXPECT_EQ(create_response.upload_id, ""); + std::ostringstream create_os; + create_os << create_response; + EXPECT_THAT(create_os.str(), + Eq("CreateResumableUploadResponse={upload_id=}")); + + std::string const payload(128, 'Z'); + UploadChunkRequest chunk_request("", 0, {{payload}}, CreateNullHashFunction(), + HashValues{}); + chunk_request.set_option(UserProject("my-project")); + EXPECT_EQ(chunk_request.upload_session_url(), ""); + std::ostringstream chunk_os; + chunk_os << chunk_request; + EXPECT_THAT(chunk_os.str(), + Eq("UploadChunkRequest={upload_session_url=, " + "range=, " + "known_object_hashes={}, userProject=my-project, " + "payload_size=128}")); +} + +struct UploadChunkPayloadFormatCase { + std::string_view name; + std::uint64_t offset; + std::vector buffers; + bool final_chunk; + std::string_view expected_range; + std::size_t expected_size; +}; + +class UploadChunkPayloadFormatTest + : public ::testing::TestWithParam {}; + +/// @test Verify `UploadChunkRequest` stream formatting reports `payload_size` +/// across empty and multi-buffer payloads. +TEST_P(UploadChunkPayloadFormatTest, FormatsPayloadSize) { + UploadChunkPayloadFormatCase const& param = GetParam(); + ConstBufferSequence sequence; + sequence.reserve(param.buffers.size()); + for (std::string const& buffer : param.buffers) { + sequence.emplace_back(buffer.data(), buffer.size()); + } + + constexpr std::string_view kSessionUrl = + "https://storage.googleapis.com/upload/storage/v1/b/myBucket/" + "o?uploadType=resumable&upload_id=xa298sd_sdlkj2"; + UploadChunkRequest const request = + param.final_chunk + ? UploadChunkRequest(std::string{kSessionUrl}, param.offset, sequence, + CreateNullHashFunction(), HashValues{}) + : UploadChunkRequest(std::string{kSessionUrl}, param.offset, sequence, + CreateNullHashFunction()); + + std::ostringstream os; + os << request; + std::ostringstream expected; + expected << "UploadChunkRequest={upload_session_url=[censored], range=<" + << param.expected_range + << ">, known_object_hashes={}, payload_size=" << param.expected_size + << "}"; + EXPECT_THAT(os.str(), Eq(expected.str())); +} + +INSTANTIATE_TEST_SUITE_P( + PayloadBoundaries, UploadChunkPayloadFormatTest, + ::testing::Values( + UploadChunkPayloadFormatCase{"EmptyFinalChunk", + 1024, + {}, + true, + "Content-Range: bytes */1024", + 0}, + UploadChunkPayloadFormatCase{"EmptyNonFinalChunk", + 1024, + {}, + false, + "Content-Range: bytes */*", + 0}, + UploadChunkPayloadFormatCase{"SingleEmptyBuffer", + 1024, + {""}, + false, + "Content-Range: bytes */*", + 0}, + UploadChunkPayloadFormatCase{ + "MultiBufferLarge", + 0, + {"chunk-one-marker" + std::string(200, 'A'), + "chunk-two-marker" + std::string(250, 'B')}, + true, + "Content-Range: bytes 0-481/482", + 482}), + [](::testing::TestParamInfo const& info) { + return std::string{info.param.name}; + }); + +/// @test Verify `UseResumableUploadSession` stream formatting for unset and +/// new-session states. +TEST(ObjectRequestsTest, ResumableUploadFormatsSessionOption) { + UseResumableUploadSession const unset; + EXPECT_FALSE(unset.has_value()); + std::ostringstream unset_os; + unset_os << unset; + EXPECT_THAT(unset_os.str(), Eq("resumable-upload=")); + + UseResumableUploadSession const new_session = NewResumableUploadSession(); + EXPECT_TRUE(new_session.has_value()); + EXPECT_EQ(new_session.value(), ""); + std::ostringstream new_os; + new_os << new_session; + EXPECT_THAT(new_os.str(), Eq("resumable-upload=")); + + ResumableUploadRequest request("source-bucket", "source-object"); + request.set_option(new_session); + std::ostringstream request_os; + request_os << request; + EXPECT_THAT(request_os.str(), + Eq("ResumableUploadRequest={bucket_name=source-bucket, " + "object_name=source-object, resumable-upload=, " + "auto-finalize=enabled}")); +} + } // namespace } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/upload_options.h b/google/cloud/storage/upload_options.h index fd21da515f294..1eb710ea56741 100644 --- a/google/cloud/storage/upload_options.h +++ b/google/cloud/storage/upload_options.h @@ -18,6 +18,7 @@ #include "google/cloud/storage/internal/complex_option.h" #include "google/cloud/storage/version.h" #include "google/cloud/storage/well_known_headers.h" +#include #include namespace google { @@ -44,6 +45,16 @@ struct UseResumableUploadSession static char const* name() { return "resumable-upload"; } }; +/// Formats a `UseResumableUploadSession` option for stream output: +/// `` when unset, an empty value for a new session, and `[censored]` +/// when a session identifier is set. +inline std::ostream& operator<<(std::ostream& os, + UseResumableUploadSession const& rhs) { + if (!rhs.has_value()) return os << rhs.option_name() << "="; + if (rhs.value().empty()) return os << rhs.option_name() << "="; + return os << rhs.option_name() << "=[censored]"; +} + /// Create a UseResumableUploadSession option that restores previous sessions. inline UseResumableUploadSession RestoreResumableUploadSession( std::string session_id) {