From 5e029673fbfae37946b1613ce947cb5cfac6243b Mon Sep 17 00:00:00 2001 From: Vaibhav Pratap Date: Tue, 1 Dec 2026 06:05:20 +0000 Subject: [PATCH 1/4] fix(storage): avoid use-after-free in AsyncWriterConnectionImpl Move AsyncWriterConnectionImpl's async state into a shared_ptr inheriting from std::enable_shared_from_this, and capture shared_from_this() in all streaming RPC continuations instead of raw this. Also track in-flight operations so ~AsyncWriterConnectionImpl() cancels the stream and defers impl_->Finish() until all in-flight operations complete, avoiding Finish()-while-op-pending contract violations and keeping State and the underlying StreamingRpc alive until Finish() completes. --- .../async/writer_connection_buffered_test.cc | 74 ++ .../internal/async/writer_connection_impl.cc | 825 +++++++++++------- .../internal/async/writer_connection_impl.h | 47 +- .../async/writer_connection_impl_test.cc | 239 +++++ .../async/writer_connection_resumed_test.cc | 71 ++ 5 files changed, 884 insertions(+), 372 deletions(-) diff --git a/google/cloud/storage/internal/async/writer_connection_buffered_test.cc b/google/cloud/storage/internal/async/writer_connection_buffered_test.cc index 75bead83b00e5..2931a702c1585 100644 --- a/google/cloud/storage/internal/async/writer_connection_buffered_test.cc +++ b/google/cloud/storage/internal/async/writer_connection_buffered_test.cc @@ -3359,6 +3359,80 @@ TEST(WriteConnectionBuffered, ResumeReplaysUnpersistedFlushedData) { EXPECT_STATUS_OK(f2.get()); } +class WriterConnectionBufferedDestroyTest + : public ::testing::TestWithParam {}; + +/// @test Verify that destroying a buffered writer while an underlying +/// `AsyncWriterConnectionImpl` write is still in flight does not cause a +/// use-after-free when the in-flight write later completes (either succeeding +/// or failing). +TEST_P(WriterConnectionBufferedDestroyTest, PendingWriteOutlivesConnection) { + bool const write_succeeds = GetParam(); + using Request = google::storage::v2::BidiWriteObjectRequest; + using Response = google::storage::v2::BidiWriteObjectResponse; + using MockStream = + ::google::cloud::mocks::MockAsyncStreamingReadWriteRpc; + + AsyncSequencer sequencer; + auto mock_stream = std::make_unique(); + EXPECT_CALL(*mock_stream, Cancel).Times(AtLeast(1)); + EXPECT_CALL(*mock_stream, Write) + .WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("StreamWrite"); + }); + EXPECT_CALL(*mock_stream, Finish).WillOnce([&]() { + return sequencer.PushBack("StreamFinish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(::testing::_, ::testing::An(), + ::testing::_)) + .WillRepeatedly(Return(Status{})); + + Request initial_request; + initial_request.set_upload_id("test-upload-id"); + auto impl = std::make_unique( + google::cloud::internal::MakeImmutableOptions(TestOptions()), + std::move(initial_request), std::move(mock_stream), std::move(hash), + /*persisted_size=*/0); + + MockFactory mock_factory; + EXPECT_CALL(mock_factory, Call).Times(0); + std::unique_ptr connection = + MakeWriterConnectionBuffered(mock_factory.AsStdFunction(), + std::move(impl), TestOptions()); + + // Buffer is below the high-water mark, so `Write()` returns immediately while + // the underlying `AsyncWriterConnectionImpl::Write()` is still in flight. + future write = connection->Write(TestPayload(1024)); + ASSERT_TRUE(write.is_ready()); + EXPECT_STATUS_OK(write.get()); + + // Pop the pending stream write, then destroy the buffered writer before the + // stream write completes. + std::pair, std::string> pending_write = + sequencer.PopFrontWithName(); + ASSERT_EQ(pending_write.second, "StreamWrite"); + connection.reset(); + + // Completing the pending write after destruction must not use-after-free. + pending_write.first.set_value(write_succeeds); + + std::pair, std::string> pending_finish = + sequencer.PopFrontWithName(); + ASSERT_EQ(pending_finish.second, "StreamFinish"); + pending_finish.first.set_value(write_succeeds); +} + +INSTANTIATE_TEST_SUITE_P(WriteOutcome, WriterConnectionBufferedDestroyTest, + ::testing::Bool(), + [](::testing::TestParamInfo const& info) { + return info.param ? "WriteSucceeds" : "WriteFails"; + }); + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/writer_connection_impl.cc b/google/cloud/storage/internal/async/writer_connection_impl.cc index 2b6668ab3f0c4..1d72b51642ab6 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl.cc @@ -23,6 +23,11 @@ #include "google/cloud/storage/internal/grpc/object_metadata_parser.h" #include "google/cloud/storage/internal/grpc/object_request_parser.h" #include "google/cloud/internal/make_status.h" +#include +#include +#include +#include +#include #include namespace google { @@ -49,16 +54,478 @@ auto HandleFinishAfterError(Status s) { } // namespace +class AsyncWriterConnectionImpl::State + : public std::enable_shared_from_this { + public: + State(google::cloud::internal::ImmutableOptions options, + google::storage::v2::BidiWriteObjectRequest request, + std::unique_ptr impl, + std::shared_ptr hash_function, + PersistedStateType persisted_state, std::int64_t offset, + bool first_request) + : options_(std::move(options)), + impl_(std::move(impl)), + request_(std::move(request)), + hash_function_(std::move(hash_function)), + persisted_state_(std::move(persisted_state)), + offset_(offset), + first_request_(first_request) { + request_.clear_object_checksums(); + request_.set_state_lookup(false); + request_.set_flush(false); + request_.set_finish_write(false); + } + + void Shutdown() { + std::unique_lock lk(mu_); + shutdown_ = true; + bool const can_finish = (in_flight_ == 0); + lk.unlock(); + + // Cancel the streaming RPC. + impl_->Cancel(); + // It is safe to call Finish() only when no `Write()`, `Finalize()`, + // `Flush()`, or `Close()` operation is currently in flight. If an + // operation is still in flight, its completion handler will call + // `Finish()` once `in_flight_` reaches 0. + if (can_finish) { + (void)Finish(); + } + } + + void Cancel() { impl_->Cancel(); } + + std::string UploadId() const { return request_.upload_id(); } + + std::optional WriteHandle() const { + std::unique_lock lk(mu_); + return latest_write_handle_; + } + + PersistedStateType PersistedState() const { + std::unique_lock lk(mu_); + return persisted_state_; + } + + future Write(storage::WritePayload payload) { + std::unique_lock lk(mu_); + auto write = MakeRequestLocked(); + ++in_flight_; + lk.unlock(); + + auto p = WritePayloadImpl::GetImpl(payload); + auto size = p.size(); + auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), PartialUpload::kNone); + + return coro->Start().then([coro, size, + self = shared_from_this()](auto f) mutable { + coro.reset(); // breaks the cycle between the completion queue and coro + return self->OnPartialUpload(size, f.get()); + }); + } + + future> Finalize( + storage::WritePayload payload) { + std::unique_lock lk(mu_); + auto write = MakeRequestLocked(); + ++in_flight_; + lk.unlock(); + + write.set_finish_write(true); + + auto p = WritePayloadImpl::GetImpl(payload); + auto size = p.size(); + auto is_append = request_.has_append_object_spec() || + request_.write_object_spec().appendable(); + auto const& current_options = google::cloud::internal::CurrentOptions(); + auto merged = google::cloud::internal::MergeOptions( + current_options, options_ ? *options_ : google::cloud::Options{}); + + // Default to letting the internal hash function compute and send the + // checksum. + auto action = PartialUpload::kFinalizeWithChecksum; + + if (is_append) { + // For appendable uploads, the internal hash function only sees the chunks + // uploaded in this stream, not the full object. We use `kFinalize` to + // avoid sending this partial hash, which would otherwise fail validation. + if (merged.has()) { + write.mutable_object_checksums()->set_crc32c( + merged.get()); + } + action = PartialUpload::kFinalize; + } else if (current_options + .has() || + current_options + .has()) { + // If the user specified a manual expected checksum dynamically at + // Finalize() via current_options, we manually inject it and use + // `kFinalize` so the internal hash function doesn't overwrite it with its + // own computed hash. + if (current_options.has()) { + write.mutable_object_checksums()->set_crc32c( + current_options + .get()); + } + if (current_options.has()) { + write.mutable_object_checksums()->set_md5_hash( + current_options.get()); + } + action = PartialUpload::kFinalize; + } + + auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), std::move(action)); + return coro->Start().then([coro, size, + self = shared_from_this()](auto f) mutable { + coro.reset(); // breaks the cycle between the completion queue and coro + return self->OnFinalUpload(size, f.get()); + }); + } + + future Flush(storage::WritePayload payload) { + std::unique_lock lk(mu_); + auto write = MakeRequestLocked(); + ++in_flight_; + lk.unlock(); + + auto p = WritePayloadImpl::GetImpl(payload); + auto size = p.size(); + auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), PartialUpload::kFlush); + + return coro->Start().then([coro, size, + self = shared_from_this()](auto f) mutable { + coro.reset(); // breaks the cycle between the completion queue and coro + return self->OnFlush(size, f.get()); + }); + } + + future Close(storage::WritePayload payload) { + std::unique_lock lk(mu_); + auto write = MakeRequestLocked(); + ++in_flight_; + lk.unlock(); + + auto p = WritePayloadImpl::GetImpl(payload); + auto size = p.size(); + auto coro = + PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), PartialUpload::kFlushAndClose); + + return coro->Start().then([coro, size, + self = shared_from_this()](auto f) mutable { + coro.reset(); // breaks the cycle between the completion queue and coro + return self->OnClose(size, f.get()); + }); + } + + future> Query() { + std::unique_lock lk(mu_); + if (auto* size = std::get_if(&persisted_state_)) { + return make_ready_future(make_status_or(*size)); + } + if (auto* meta = + std::get_if(&persisted_state_)) { + return make_ready_future( + make_status_or(static_cast(meta->size()))); + } + return make_ready_future(make_status_or(static_cast(0))); + } + + RpcMetadata GetRequestMetadata() { return impl_->GetRequestMetadata(); } + + private: + google::storage::v2::BidiWriteObjectRequest MakeRequestLocked() { + auto request = request_; + if (first_request_) { + first_request_ = false; + if (latest_write_handle_.has_value() && + request.has_append_object_spec()) { + *request.mutable_append_object_spec()->mutable_write_handle() = + *latest_write_handle_; + } + } else { + request.clear_upload_id(); + request.clear_write_object_spec(); + request.clear_append_object_spec(); + } + request.set_write_offset(offset_); + return request; + } + + future OnPartialUpload(std::size_t upload_size, + StatusOr success) { + if (!success) { + return FinishAndCompleteOp().then( + HandleFinishAfterError(std::move(success).status())); + } + if (!*success) { + return FinishAndCompleteOp().then(HandleFinishAfterError( + "Expected Finish() error after non-ok Write()")); + } + std::unique_lock lk(mu_); + offset_ += upload_size; + CompleteOpLocked(std::move(lk)); + return make_ready_future(Status{}); + } + + future OnFlush(std::size_t upload_size, StatusOr success) { + if (!success) { + return FinishAndCompleteOp().then( + HandleFinishAfterError(std::move(success).status())); + } + if (!*success) { + return FinishAndCompleteOp().then(HandleFinishAfterError( + "Expected Finish() error after non-ok Write()")); + } + std::unique_lock lk(mu_); + offset_ += upload_size; + if (shutdown_) { + --in_flight_; + if (in_flight_ == 0) { + return FinishLocked(std::move(lk)); + } + lk.unlock(); + return make_ready_future( + internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + } + lk.unlock(); + + // The service answers a `state_lookup` with one response carrying the + // persisted size (or the object resource), possibly preceded by responses + // that only refresh the write handle. The persisted size "might lag behind + // the number of bytes written by the client" (`BidiWriteObjectRequest` in + // `google/storage/v2/storage.proto`), e.g., regular buckets only persist + // 256 KiB multiples until the upload is finalized. The service sends no + // further response, so waiting for a size that covers `offset_` would block + // until the stream is cancelled. + struct ConsumeLoop { + std::shared_ptr self; + + future operator()( + future> + f) { + auto response = std::move(f).get(); + if (!response.has_value()) { + return self->FinishAndCompleteOp().then(HandleFinishAfterError( + "Expected error in Finish() after non-ok Read()")); + } + std::unique_lock lk(self->mu_); + if (response->has_write_handle()) { + self->latest_write_handle_ = response->write_handle(); + } + if (response->has_persisted_size()) { + self->persisted_state_ = response->persisted_size(); + self->CompleteOpLocked(std::move(lk)); + return make_ready_future(Status{}); + } + if (response->has_resource()) { + self->persisted_state_ = response->resource(); + self->CompleteOpLocked(std::move(lk)); + return make_ready_future(Status{}); + } + if (self->shutdown_) { + --self->in_flight_; + if (self->in_flight_ == 0) { + return self->FinishLocked(std::move(lk)); + } + lk.unlock(); + return make_ready_future( + internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + } + lk.unlock(); + auto impl = self->impl_; + return impl->Read().then(std::move(*this)); + } + }; + return impl_->Read().then(ConsumeLoop{shared_from_this()}); + } + + future OnClose(std::size_t upload_size, StatusOr success) { + if (!success) { + return FinishAndCompleteOp().then( + HandleFinishAfterError(std::move(success).status())); + } + if (!*success) { + return FinishAndCompleteOp().then(HandleFinishAfterError( + "Expected Finish() error after non-ok Write()")); + } + std::unique_lock lk(mu_); + offset_ += upload_size; + if (shutdown_) { + --in_flight_; + if (in_flight_ == 0) { + return FinishLocked(std::move(lk)); + } + lk.unlock(); + return make_ready_future( + internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + } + lk.unlock(); + + struct ConsumeLoop { + std::shared_ptr impl; + + future operator()( + future> + f) { + auto response = std::move(f).get(); + if (!response.has_value()) return make_ready_future(); + return impl->Read().then(*this); + } + }; + + return impl_->Read() + .then(ConsumeLoop{impl_}) + .then([self = shared_from_this()](auto f) { + f.get(); + return self->FinishAndCompleteOp(); + }); + } + + future> OnFinalUpload( + std::size_t upload_size, StatusOr success) { + auto transform = [](future f) { + return StatusOr(f.get()); + }; + if (!success) { + return FinishAndCompleteOp() + .then(HandleFinishAfterError(std::move(success).status())) + .then(transform); + } + if (!*success) { + return FinishAndCompleteOp() + .then(HandleFinishAfterError( + "Expected error in Finish() after non-ok Write()")) + .then(transform); + } + std::unique_lock lk(mu_); + offset_ += upload_size; + if (shutdown_) { + --in_flight_; + if (in_flight_ == 0) { + return FinishLocked(std::move(lk)).then(transform); + } + lk.unlock(); + return make_ready_future(StatusOr( + internal::CancelledError("writer destroyed", GCP_ERROR_INFO()))); + } + lk.unlock(); + + struct ConsumeLoop { + std::shared_ptr self; + + future operator()( + future> + f) { + auto response = std::move(f).get(); + if (!response.has_value()) return make_ready_future(); + { + std::unique_lock lk(self->mu_); + if (response->has_write_handle()) { + self->latest_write_handle_ = response->write_handle(); + } + if (response->has_persisted_size()) { + self->persisted_state_ = response->persisted_size(); + } + if (response->has_resource()) { + self->persisted_state_ = response->resource(); + } + } + auto impl = self->impl_; + return impl->Read().then(std::move(*this)); + } + }; + + return impl_->Read() + .then(ConsumeLoop{shared_from_this()}) + .then([self = shared_from_this()](auto f) { + std::move(f).get(); + return self->FinishAndCompleteOp().then( + [self](auto f2) -> StatusOr { + auto status = f2.get(); + if (!status.ok()) return status; + std::unique_lock lk(self->mu_); + if (!std::holds_alternative( + self->persisted_state_)) { + return internal::InternalError( + "no object metadata returned after finalizing upload", + GCP_ERROR_INFO()); + } + return std::get( + self->persisted_state_); + }); + }); + } + + void CompleteOpLocked(std::unique_lock lk) { + --in_flight_; + if (shutdown_ && in_flight_ == 0) { + (void)FinishLocked(std::move(lk)); + } + } + + future FinishAndCompleteOp() { + std::unique_lock lk(mu_); + --in_flight_; + return FinishLocked(std::move(lk)); + } + + future Finish() { + std::unique_lock lk(mu_); + return FinishLocked(std::move(lk)); + } + + future FinishLocked(std::unique_lock lk) { + if (std::exchange(finish_called_, true)) { + return make_ready_future( + internal::CancelledError("already finished", GCP_ERROR_INFO())); + } + lk.unlock(); + + // Extend the lifetime of `*this` (and therefore `impl_`) until + // `impl_->Finish()` completes. + return impl_->Finish().then([self = shared_from_this()](auto f) mutable { + // Break any ownership cycle between the completion queue and this + // callback. + self.reset(); + return f.get(); + }); + } + + google::cloud::internal::ImmutableOptions const options_; + std::shared_ptr const impl_; + google::storage::v2::BidiWriteObjectRequest request_; + std::shared_ptr const hash_function_; + PersistedStateType persisted_state_; + std::int64_t offset_ = 0; + bool first_request_; + + // `Finish()` must be called exactly once. If it has not been called by the + // time the destructor is reached, then `Shutdown()` (or the last in-flight + // operation to complete after `Shutdown()`) will arrange for a call. + bool finish_called_ = false; + bool shutdown_ = false; + std::size_t in_flight_ = 0; + + // Track the latest write handle seen in responses. + std::optional latest_write_handle_; + + mutable std::mutex mu_; +}; + AsyncWriterConnectionImpl::AsyncWriterConnectionImpl( google::cloud::internal::ImmutableOptions options, google::storage::v2::BidiWriteObjectRequest request, std::unique_ptr impl, std::shared_ptr hash_function, std::int64_t persisted_size, bool first_request) - : AsyncWriterConnectionImpl( - std::move(options), std::move(request), std::move(impl), - std::move(hash_function), PersistedStateType(persisted_size), - /*offset=*/persisted_size, std::move(first_request)) {} + : AsyncWriterConnectionImpl(std::move(options), std::move(request), + std::move(impl), std::move(hash_function), + PersistedStateType(persisted_size), + /*offset=*/persisted_size, first_request) {} AsyncWriterConnectionImpl::AsyncWriterConnectionImpl( google::cloud::internal::ImmutableOptions options, @@ -66,10 +533,10 @@ AsyncWriterConnectionImpl::AsyncWriterConnectionImpl( std::unique_ptr impl, std::shared_ptr hash_function, google::storage::v2::Object metadata, bool first_request) - : AsyncWriterConnectionImpl( - std::move(options), std::move(request), std::move(impl), - std::move(hash_function), PersistedStateType(metadata), - /*offset=*/metadata.size(), std::move(first_request)) {} + : AsyncWriterConnectionImpl(std::move(options), std::move(request), + std::move(impl), std::move(hash_function), + PersistedStateType(metadata), + /*offset=*/metadata.size(), first_request) {} AsyncWriterConnectionImpl::AsyncWriterConnectionImpl( google::cloud::internal::ImmutableOptions options, @@ -77,354 +544,52 @@ AsyncWriterConnectionImpl::AsyncWriterConnectionImpl( std::unique_ptr impl, std::shared_ptr hash_function, PersistedStateType persisted_state, std::int64_t offset, bool first_request) - : options_(std::move(options)), - impl_(std::move(impl)), - request_(std::move(request)), - hash_function_(std::move(hash_function)), - persisted_state_(std::move(persisted_state)), - offset_(offset), - first_request_(std::move(first_request)), - finished_(on_finish_.get_future()) { - request_.clear_object_checksums(); - request_.set_state_lookup(false); - request_.set_flush(false); - request_.set_finish_write(false); -} + : state_(std::make_shared(std::move(options), std::move(request), + std::move(impl), std::move(hash_function), + std::move(persisted_state), offset, + first_request)) {} -AsyncWriterConnectionImpl::~AsyncWriterConnectionImpl() { - // Cancel the streaming RPC. - impl_->Cancel(); - // It is safe to call Finish() because: - // (1) this is a no-op if it was already called. - // (2) calls to `Write()`, `Finalize()`, and `Query()` must have completed - // by the time the destructor is called - Finish(); - - // We use a local copy of `impl` moved under lock to avoid - // data races with concurrent calls to `Finish()` from callbacks. - std::unique_lock lk(mu_); - auto impl = std::move(impl_); - lk.unlock(); - - // When `impl_->Finish()` is satisfied then `finished_` is satisfied too. - // This extends the lifetime of `impl_` until it is safe to delete. - finished_.then([impl = std::move(impl)](auto) mutable { - // Break the ownership cycle between the completion queue and this callback. - impl.reset(); - }); -} +AsyncWriterConnectionImpl::~AsyncWriterConnectionImpl() { state_->Shutdown(); } + +void AsyncWriterConnectionImpl::Cancel() { state_->Cancel(); } std::string AsyncWriterConnectionImpl::UploadId() const { - return request_.upload_id(); + return state_->UploadId(); +} + +std::optional +AsyncWriterConnectionImpl::WriteHandle() const { + return state_->WriteHandle(); } std::variant AsyncWriterConnectionImpl::PersistedState() const { - std::unique_lock lk(mu_); - return persisted_state_; + return state_->PersistedState(); } future AsyncWriterConnectionImpl::Write(storage::WritePayload payload) { - auto write = MakeRequest(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), PartialUpload::kNone); - - return coro->Start().then([coro, size, this](auto f) mutable { - coro.reset(); // breaks the cycle between the completion queue and coro - return OnPartialUpload(size, f.get()); - }); + return state_->Write(std::move(payload)); } future> AsyncWriterConnectionImpl::Finalize(storage::WritePayload payload) { - auto write = MakeRequest(); - write.set_finish_write(true); - - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto is_append = request_.has_append_object_spec() || - request_.write_object_spec().appendable(); - auto const& current_options = google::cloud::internal::CurrentOptions(); - auto merged = google::cloud::internal::MergeOptions( - current_options, options_ ? *options_ : google::cloud::Options{}); - - // Default to letting the internal hash function compute and send the - // checksum. - auto action = PartialUpload::kFinalizeWithChecksum; - - if (is_append) { - // For appendable uploads, the internal hash function only sees the chunks - // uploaded in this stream, not the full object. We use `kFinalize` to avoid - // sending this partial hash, which would otherwise fail validation. - if (merged.has()) { - write.mutable_object_checksums()->set_crc32c( - merged.get()); - } - action = PartialUpload::kFinalize; - } else if (current_options - .has() || - current_options.has()) { - // If the user specified a manual expected checksum dynamically at - // Finalize() via current_options, we manually inject it and use `kFinalize` - // so the internal hash function doesn't overwrite it with its own computed - // hash. - if (current_options.has()) { - write.mutable_object_checksums()->set_crc32c( - current_options.get()); - } - if (current_options.has()) { - write.mutable_object_checksums()->set_md5_hash( - current_options.get()); - } - action = PartialUpload::kFinalize; - } - - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), std::move(action)); - return coro->Start().then([coro, size, this](auto f) mutable { - coro.reset(); // breaks the cycle between the completion queue and coro - return OnFinalUpload(size, f.get()); - }); + return state_->Finalize(std::move(payload)); } future AsyncWriterConnectionImpl::Flush(storage::WritePayload payload) { - auto write = MakeRequest(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), PartialUpload::kFlush); - - return coro->Start().then([coro, size, this](auto f) mutable { - coro.reset(); // breaks the cycle between the completion queue and coro - return OnFlush(size, f.get()); - }); + return state_->Flush(std::move(payload)); } future AsyncWriterConnectionImpl::Close(storage::WritePayload payload) { - auto write = MakeRequest(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), PartialUpload::kFlushAndClose); - - return coro->Start().then([coro, size, this](auto f) mutable { - coro.reset(); // breaks the cycle between the completion queue and coro - return OnClose(size, f.get()); - }); + return state_->Close(std::move(payload)); } future> AsyncWriterConnectionImpl::Query() { - std::unique_lock lk(mu_); - if (auto* size = std::get_if(&persisted_state_)) { - return make_ready_future(make_status_or(*size)); - } - if (auto* meta = - std::get_if(&persisted_state_)) { - return make_ready_future( - make_status_or(static_cast(meta->size()))); - } - return make_ready_future(make_status_or(static_cast(0))); + return state_->Query(); } RpcMetadata AsyncWriterConnectionImpl::GetRequestMetadata() { - return impl_->GetRequestMetadata(); -} - -google::storage::v2::BidiWriteObjectRequest -AsyncWriterConnectionImpl::MakeRequest() { - auto request = request_; - if (first_request_) { - first_request_ = false; - if (latest_write_handle_.has_value() && request.has_append_object_spec()) { - *request.mutable_append_object_spec()->mutable_write_handle() = - *latest_write_handle_; - } - } else { - request.clear_upload_id(); - request.clear_write_object_spec(); - request.clear_append_object_spec(); - } - request.set_write_offset(offset_); - return request; -} - -future AsyncWriterConnectionImpl::OnPartialUpload( - std::size_t upload_size, StatusOr success) { - if (!success) { - return Finish().then(HandleFinishAfterError(std::move(success).status())); - } - if (!*success) { - return Finish().then( - HandleFinishAfterError("Expected Finish() error after non-ok Write()")); - } - std::unique_lock lk(mu_); - offset_ += upload_size; - lk.unlock(); - return make_ready_future(Status{}); -} - -future AsyncWriterConnectionImpl::OnFlush(std::size_t upload_size, - StatusOr success) { - if (!success) { - return Finish().then(HandleFinishAfterError(std::move(success).status())); - } - if (!*success) { - return Finish().then( - HandleFinishAfterError("Expected Finish() error after non-ok Write()")); - } - std::unique_lock lk(mu_); - offset_ += upload_size; - auto impl = impl_; - lk.unlock(); - - // The service answers a `state_lookup` with one response carrying the - // persisted size (or the object resource), possibly preceded by responses - // that only refresh the write handle. The persisted size "might lag behind - // the number of bytes written by the client" (`BidiWriteObjectRequest` in - // `google/storage/v2/storage.proto`), e.g., regular buckets only persist - // 256 KiB multiples until the upload is finalized. The service sends no - // further response, so waiting for a size that covers `offset_` would block - // until the stream is cancelled. - struct ConsumeLoop { - AsyncWriterConnectionImpl* self; - std::shared_ptr impl; - - future operator()( - future> f) { - auto response = std::move(f).get(); - if (!response.has_value()) { - return self->Finish().then(HandleFinishAfterError( - "Expected error in Finish() after non-ok Read()")); - } - std::unique_lock lk(self->mu_); - if (response->has_write_handle()) { - self->latest_write_handle_ = response->write_handle(); - } - if (response->has_persisted_size()) { - self->persisted_state_ = response->persisted_size(); - return make_ready_future(Status{}); - } - if (response->has_resource()) { - self->persisted_state_ = response->resource(); - return make_ready_future(Status{}); - } - lk.unlock(); - return impl->Read().then(std::move(*this)); - } - }; - return impl->Read().then(ConsumeLoop{this, impl}); -} - -future AsyncWriterConnectionImpl::OnClose(std::size_t upload_size, - StatusOr success) { - if (!success) { - return Finish().then(HandleFinishAfterError(std::move(success).status())); - } - if (!*success) { - return Finish().then( - HandleFinishAfterError("Expected Finish() error after non-ok Write()")); - } - std::unique_lock lk(mu_); - offset_ += upload_size; - auto impl = impl_; - lk.unlock(); - - struct ConsumeLoop { - std::shared_ptr impl; - - future operator()( - future> f) { - auto response = std::move(f).get(); - if (!response.has_value()) return make_ready_future(); - return impl->Read().then(*this); - } - }; - - return impl->Read().then(ConsumeLoop{impl}).then([this](auto f) { - f.get(); - return Finish(); - }); -} - -future> -AsyncWriterConnectionImpl::OnFinalUpload(std::size_t upload_size, - StatusOr success) { - auto transform = [](future f) { - return StatusOr(f.get()); - }; - if (!success) { - return Finish() - .then(HandleFinishAfterError(std::move(success).status())) - .then(transform); - } - if (!*success) { - return Finish() - .then(HandleFinishAfterError( - "Expected error in Finish() after non-ok Write()")) - .then(transform); - } - std::unique_lock lk(mu_); - offset_ += upload_size; - - auto impl = impl_; - lk.unlock(); - - struct ConsumeLoop { - AsyncWriterConnectionImpl* self; - std::shared_ptr impl; - - future operator()( - future> f) { - auto response = std::move(f).get(); - if (!response.has_value()) return make_ready_future(); - { - std::unique_lock lk(self->mu_); - if (response->has_write_handle()) { - self->latest_write_handle_ = response->write_handle(); - } - if (response->has_persisted_size()) { - self->persisted_state_ = response->persisted_size(); - } - if (response->has_resource()) { - self->persisted_state_ = response->resource(); - } - } - return impl->Read().then(std::move(*this)); - } - }; - - return impl->Read().then(ConsumeLoop{this, impl}).then([this](auto f) { - std::move(f).get(); - return Finish().then( - [this](auto f2) -> StatusOr { - auto status = f2.get(); - if (!status.ok()) return status; - if (!std::holds_alternative( - persisted_state_)) { - return internal::InternalError( - "no object metadata returned after finalizing upload", - GCP_ERROR_INFO()); - } - return std::get(persisted_state_); - }); - }); -} - -future AsyncWriterConnectionImpl::Finish() { - std::unique_lock lk(mu_); - if (std::exchange(finish_called_, true)) { - return make_ready_future( - internal::CancelledError("already finished", GCP_ERROR_INFO())); - } - auto impl = impl_; - lk.unlock(); - - return impl->Finish().then([p = std::move(on_finish_)](auto f) mutable { - p.set_value(); - return f.get(); - }); + return state_->GetRequestMetadata(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/writer_connection_impl.h b/google/cloud/storage/internal/async/writer_connection_impl.h index 2d15e1c4cabaf..d8d639357a8da 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl.h +++ b/google/cloud/storage/internal/async/writer_connection_impl.h @@ -21,10 +21,8 @@ #include "google/cloud/options.h" #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" -#include #include #include -#include namespace google { namespace cloud { @@ -51,14 +49,11 @@ class AsyncWriterConnectionImpl : public storage::AsyncWriterConnection { google::storage::v2::Object metadata, bool first_request = true); ~AsyncWriterConnectionImpl() override; - void Cancel() override { return impl_->Cancel(); } + void Cancel() override; std::string UploadId() const override; std::optional WriteHandle() - const override { - std::unique_lock lk(mu_); - return latest_write_handle_; - } + const override; std::variant PersistedState() const override; @@ -73,6 +68,8 @@ class AsyncWriterConnectionImpl : public storage::AsyncWriterConnection { private: using PersistedStateType = std::variant; + class State; + AsyncWriterConnectionImpl( google::cloud::internal::ImmutableOptions options, google::storage::v2::BidiWriteObjectRequest request, @@ -81,41 +78,7 @@ class AsyncWriterConnectionImpl : public storage::AsyncWriterConnection { PersistedStateType persisted_state, std::int64_t offset, bool first_request = true); - google::storage::v2::BidiWriteObjectRequest MakeRequest(); - - future OnPartialUpload(std::size_t upload_size, - StatusOr success); - future OnFlush(std::size_t upload_size, StatusOr success); - future OnClose(std::size_t upload_size, StatusOr success); - future> OnFinalUpload( - std::size_t upload_size, StatusOr success); - future Finish(); - - google::cloud::internal::ImmutableOptions options_; - std::shared_ptr impl_; - google::storage::v2::BidiWriteObjectRequest request_; - std::shared_ptr hash_function_; - PersistedStateType persisted_state_; - std::int64_t offset_ = 0; - bool first_request_; - - // `Finish()` must be called exactly once. If it has not been called by the - // time the destructor is reached, then the destructor will arrange for a - // call. - bool finish_called_ = false; - - // We need to extend the lifetime of `impl_` until `Finish()` is called and - // completed. We cannot block in the destructor (that results in deadlocks). - // Instead, the destructor creates an object that extends the lifetime of - // `impl_` until `finished_` is satisfied. The destructor arranges things such - // that `on_finish_` is called when `Finish()` is completed. - google::cloud::promise on_finish_; - google::cloud::future finished_; - - // Track the latest write handle seen in responses. - std::optional latest_write_handle_; - - mutable std::mutex mu_; + std::shared_ptr state_; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/writer_connection_impl_test.cc b/google/cloud/storage/internal/async/writer_connection_impl_test.cc index 09a48f90b84c5..eaada5ed60140 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl_test.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl_test.cc @@ -1512,6 +1512,245 @@ TEST(AsyncWriterConnectionTest, ConsecutiveFlushesEachReadOneResponse) { next.first.set_value(true); } +TEST(AsyncWriterConnectionTest, DestroyWithWriteInFlightSucceeds) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future write = tested->Write(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + // Destroy while Write() is still in flight. Finish() must not be called until + // the in-flight Write() completes. + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + EXPECT_THAT(write.get(), IsOk()); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); +} + +TEST(AsyncWriterConnectionTest, DestroyWithWriteInFlightFails) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future write = tested->Write(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(false); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(false); + EXPECT_THAT(write.get(), StatusIs(PermanentError().code())); +} + +TEST(AsyncWriterConnectionTest, DestroyWithFlushWriteInFlight) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).Times(0); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future flush = tested->Flush(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(false); + EXPECT_THAT(flush.get(), StatusIs(PermanentError().code())); +} + +TEST(AsyncWriterConnectionTest, DestroyWithFlushReadInFlight) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).WillOnce([&] { + return sequencer.PushBack("Read").then([](future f) { + if (!f.get()) return std::optional(); + Response response; + response.set_persisted_size(1024); + return std::make_optional(std::move(response)); + }); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future flush = tested->Flush(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + next.first.set_value(true); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Read"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + EXPECT_THAT(flush.get(), IsOk()); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); +} + +TEST(AsyncWriterConnectionTest, DestroyWithFinalizeReadInFlight) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).WillOnce([&] { + return sequencer.PushBack("Read").then( + [](future) { return std::optional(); }); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + EXPECT_CALL(*hash, Finish).WillOnce(Return(storage::internal::HashValues{})); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future> finalize = + tested->Finalize(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + next.first.set_value(true); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Read"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(false); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(false); + EXPECT_THAT(finalize.get(), StatusIs(PermanentError().code())); +} + +TEST(AsyncWriterConnectionTest, DestroyWithCloseReadInFlight) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).WillOnce([&] { + return sequencer.PushBack("Read").then( + [](future) { return std::optional(); }); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future close = tested->Close(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + next.first.set_value(true); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Read"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(false); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(false); + EXPECT_THAT(close.get(), StatusIs(PermanentError().code())); +} + GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal } // namespace cloud diff --git a/google/cloud/storage/internal/async/writer_connection_resumed_test.cc b/google/cloud/storage/internal/async/writer_connection_resumed_test.cc index 02837cde62d1c..4cbde2bae10ea 100644 --- a/google/cloud/storage/internal/async/writer_connection_resumed_test.cc +++ b/google/cloud/storage/internal/async/writer_connection_resumed_test.cc @@ -2739,6 +2739,77 @@ TEST(WriteConnectionResumed, ResumeReplaysUnpersistedFlushedData) { EXPECT_STATUS_OK(f2.get()); } +class WriterConnectionResumedDestroyTest + : public ::testing::TestWithParam {}; + +/// @test Verify that destroying an appendable (resumed) writer while an +/// underlying `AsyncWriterConnectionImpl` write is still in flight does not +/// cause a use-after-free when the in-flight write later completes (either +/// succeeding or failing). +TEST_P(WriterConnectionResumedDestroyTest, PendingWriteOutlivesConnection) { + bool const write_succeeds = GetParam(); + AsyncSequencer sequencer; + + auto mock_stream = std::make_unique(); + EXPECT_CALL(*mock_stream, Cancel).Times(::testing::AtLeast(1)); + EXPECT_CALL(*mock_stream, Write) + .WillOnce([&](google::storage::v2::BidiWriteObjectRequest const&, + grpc::WriteOptions) { + return sequencer.PushBack("StreamWrite"); + }); + EXPECT_CALL(*mock_stream, Finish).WillOnce([&]() { + return sequencer.PushBack("StreamFinish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(An(), An(), + An())) + .WillRepeatedly(Return(Status{})); + + google::storage::v2::BidiWriteObjectRequest initial_request; + initial_request.mutable_write_object_spec()->set_appendable(true); + auto impl = std::make_unique( + google::cloud::internal::MakeImmutableOptions(WatermarkOptions()), + initial_request, std::move(mock_stream), hash, /*persisted_size=*/0); + + MockFactory mock_factory; + EXPECT_CALL(mock_factory, Call).Times(0); + std::unique_ptr connection = + MakeWriterConnectionResumed( + mock_factory.AsStdFunction(), std::move(impl), initial_request, hash, + google::storage::v2::BidiWriteObjectResponse{}, WatermarkOptions()); + + // Buffer is below the high-water mark, so `Write()` returns immediately while + // the underlying `AsyncWriterConnectionImpl::Write()` is still in flight. + future write = connection->Write(TestPayload(1024)); + ASSERT_TRUE(write.is_ready()); + EXPECT_STATUS_OK(write.get()); + + // Pop the pending stream write, then destroy the resumed writer before the + // stream write completes. + std::pair, std::string> pending_write = + sequencer.PopFrontWithName(); + ASSERT_EQ(pending_write.second, "StreamWrite"); + connection.reset(); + + // Completing the pending write after destruction must not use-after-free. + pending_write.first.set_value(write_succeeds); + + std::pair, std::string> pending_finish = + sequencer.PopFrontWithName(); + ASSERT_EQ(pending_finish.second, "StreamFinish"); + pending_finish.first.set_value(write_succeeds); +} + +INSTANTIATE_TEST_SUITE_P(WriteOutcome, WriterConnectionResumedDestroyTest, + ::testing::Bool(), + [](::testing::TestParamInfo const& info) { + return info.param ? "WriteSucceeds" : "WriteFails"; + }); + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal From c953acce62cffeb5fe90d8dcc5fb53fea9613c89 Mon Sep 17 00:00:00 2001 From: Vaibhav Pratap Date: Tue, 1 Dec 2026 06:18:58 +0000 Subject: [PATCH 2/4] fix(storage): address review findings in AsyncWriterConnectionImpl shutdown paths --- .../internal/async/writer_connection_impl.cc | 68 ++++---- .../async/writer_connection_impl_test.cc | 153 ++++++++++++++++++ 2 files changed, 181 insertions(+), 40 deletions(-) diff --git a/google/cloud/storage/internal/async/writer_connection_impl.cc b/google/cloud/storage/internal/async/writer_connection_impl.cc index 1d72b51642ab6..406e2d5a9aab7 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl.cc @@ -77,19 +77,19 @@ class AsyncWriterConnectionImpl::State } void Shutdown() { + // Cancel the streaming RPC before setting `shutdown_` so `Cancel()` always + // happens-before `Finish()` (even if an in-flight callback sees + // `shutdown_` immediately after we release `mu_`). + impl_->Cancel(); + std::unique_lock lk(mu_); shutdown_ = true; - bool const can_finish = (in_flight_ == 0); - lk.unlock(); - - // Cancel the streaming RPC. - impl_->Cancel(); // It is safe to call Finish() only when no `Write()`, `Finalize()`, // `Flush()`, or `Close()` operation is currently in flight. If an // operation is still in flight, its completion handler will call // `Finish()` once `in_flight_` reaches 0. - if (can_finish) { - (void)Finish(); + if (in_flight_ == 0) { + (void)FinishLocked(std::move(lk)); } } @@ -283,13 +283,7 @@ class AsyncWriterConnectionImpl::State std::unique_lock lk(mu_); offset_ += upload_size; if (shutdown_) { - --in_flight_; - if (in_flight_ == 0) { - return FinishLocked(std::move(lk)); - } - lk.unlock(); - return make_ready_future( - internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + return FinishOnShutdownLocked(std::move(lk)); } lk.unlock(); @@ -327,13 +321,7 @@ class AsyncWriterConnectionImpl::State return make_ready_future(Status{}); } if (self->shutdown_) { - --self->in_flight_; - if (self->in_flight_ == 0) { - return self->FinishLocked(std::move(lk)); - } - lk.unlock(); - return make_ready_future( - internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + return self->FinishOnShutdownLocked(std::move(lk)); } lk.unlock(); auto impl = self->impl_; @@ -355,13 +343,7 @@ class AsyncWriterConnectionImpl::State std::unique_lock lk(mu_); offset_ += upload_size; if (shutdown_) { - --in_flight_; - if (in_flight_ == 0) { - return FinishLocked(std::move(lk)); - } - lk.unlock(); - return make_ready_future( - internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + return FinishOnShutdownLocked(std::move(lk)); } lk.unlock(); @@ -404,13 +386,7 @@ class AsyncWriterConnectionImpl::State std::unique_lock lk(mu_); offset_ += upload_size; if (shutdown_) { - --in_flight_; - if (in_flight_ == 0) { - return FinishLocked(std::move(lk)).then(transform); - } - lk.unlock(); - return make_ready_future(StatusOr( - internal::CancelledError("writer destroyed", GCP_ERROR_INFO()))); + return FinishOnShutdownLocked(std::move(lk)).then(transform); } lk.unlock(); @@ -460,6 +436,23 @@ class AsyncWriterConnectionImpl::State }); } + future FinishOnShutdownLocked(std::unique_lock lk) { + --in_flight_; + if (in_flight_ == 0) { + return FinishLocked(std::move(lk)).then([](future f) { + auto status = f.get(); + if (!status.ok()) return status; + // The writer was destroyed before the operation could read its + // response, so never report OK (and avoid constructing + // StatusOr(Status{}) on the Finalize() path). + return internal::CancelledError("writer destroyed", GCP_ERROR_INFO()); + }); + } + lk.unlock(); + return make_ready_future( + internal::CancelledError("writer destroyed", GCP_ERROR_INFO())); + } + void CompleteOpLocked(std::unique_lock lk) { --in_flight_; if (shutdown_ && in_flight_ == 0) { @@ -473,11 +466,6 @@ class AsyncWriterConnectionImpl::State return FinishLocked(std::move(lk)); } - future Finish() { - std::unique_lock lk(mu_); - return FinishLocked(std::move(lk)); - } - future FinishLocked(std::unique_lock lk) { if (std::exchange(finish_called_, true)) { return make_ready_future( diff --git a/google/cloud/storage/internal/async/writer_connection_impl_test.cc b/google/cloud/storage/internal/async/writer_connection_impl_test.cc index eaada5ed60140..7ee36953d59ff 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl_test.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl_test.cc @@ -1751,6 +1751,159 @@ TEST(AsyncWriterConnectionTest, DestroyWithCloseReadInFlight) { EXPECT_THAT(close.get(), StatusIs(PermanentError().code())); } +TEST(AsyncWriterConnectionTest, DestroyWithFlushWriteInFlightFinishOk) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).Times(0); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future flush = tested->Flush(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); + EXPECT_THAT(flush.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST(AsyncWriterConnectionTest, DestroyWithFlushReadWriteHandleOnlyInFlight) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).WillOnce([&] { + return sequencer.PushBack("Read").then([](future f) { + if (!f.get()) return std::optional(); + Response response; + response.mutable_write_handle()->set_handle("refreshed-handle"); + return std::make_optional(std::move(response)); + }); + }); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future flush = tested->Flush(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + next.first.set_value(true); + + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Read"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); + EXPECT_THAT(flush.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST(AsyncWriterConnectionTest, DestroyWithFinalizeWriteInFlightFinishOk) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).Times(0); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + EXPECT_CALL(*hash, Finish).WillOnce(Return(storage::internal::HashValues{})); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future> finalize = + tested->Finalize(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); + EXPECT_THAT(finalize.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST(AsyncWriterConnectionTest, DestroyWithCloseWriteInFlightFinishOk) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Write).WillOnce([&](Request const&, grpc::WriteOptions) { + return sequencer.PushBack("Write"); + }); + EXPECT_CALL(*mock, Read).Times(0); + EXPECT_CALL(*mock, Finish).WillOnce([&] { + return sequencer.PushBack("Finish").then([](future f) { + if (f.get()) return Status{}; + return PermanentError(); + }); + }); + auto hash = std::make_shared(); + EXPECT_CALL(*hash, Update(_, An(), _)).Times(1); + + auto tested = std::make_unique( + TestOptions(), MakeRequest(), std::move(mock), hash, + /*persisted_size=*/0); + + future close = tested->Close(WritePayload(std::string(1024, 'A'))); + std::pair, std::string> next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Write"); + + tested.reset(); + EXPECT_TRUE(sequencer.empty()); + + next.first.set_value(true); + next = sequencer.PopFrontWithName(); + ASSERT_EQ(next.second, "Finish"); + next.first.set_value(true); + EXPECT_THAT(close.get(), StatusIs(StatusCode::kCancelled)); +} + GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal } // namespace cloud From 40e098486fa9821d3efcad05707e2316fddf8919 Mon Sep 17 00:00:00 2001 From: Vaibhav Pratap Date: Tue, 1 Dec 2026 06:24:51 +0000 Subject: [PATCH 3/4] style(storage): spell out explicit types in AsyncWriterConnectionImpl --- .../internal/async/writer_connection_impl.cc | 70 ++++++++++--------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/google/cloud/storage/internal/async/writer_connection_impl.cc b/google/cloud/storage/internal/async/writer_connection_impl.cc index 406e2d5a9aab7..09af38eb45613 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl.cc @@ -109,14 +109,15 @@ class AsyncWriterConnectionImpl::State future Write(storage::WritePayload payload) { std::unique_lock lk(mu_); - auto write = MakeRequestLocked(); + google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; lk.unlock(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), PartialUpload::kNone); + absl::Cord p = WritePayloadImpl::GetImpl(payload); + std::size_t const size = p.size(); + std::shared_ptr coro = + PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), PartialUpload::kNone); return coro->Start().then([coro, size, self = shared_from_this()](auto f) mutable { @@ -128,23 +129,24 @@ class AsyncWriterConnectionImpl::State future> Finalize( storage::WritePayload payload) { std::unique_lock lk(mu_); - auto write = MakeRequestLocked(); + google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; lk.unlock(); write.set_finish_write(true); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto is_append = request_.has_append_object_spec() || - request_.write_object_spec().appendable(); - auto const& current_options = google::cloud::internal::CurrentOptions(); - auto merged = google::cloud::internal::MergeOptions( + absl::Cord p = WritePayloadImpl::GetImpl(payload); + std::size_t const size = p.size(); + bool const is_append = request_.has_append_object_spec() || + request_.write_object_spec().appendable(); + Options const& current_options = google::cloud::internal::CurrentOptions(); + Options merged = google::cloud::internal::MergeOptions( current_options, options_ ? *options_ : google::cloud::Options{}); // Default to letting the internal hash function compute and send the // checksum. - auto action = PartialUpload::kFinalizeWithChecksum; + PartialUpload::LastMessageAction action = + PartialUpload::kFinalizeWithChecksum; if (is_append) { // For appendable uploads, the internal hash function only sees the chunks @@ -175,8 +177,8 @@ class AsyncWriterConnectionImpl::State action = PartialUpload::kFinalize; } - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), std::move(action)); + std::shared_ptr coro = PartialUpload::Call( + impl_, hash_function_, std::move(write), std::move(p), action); return coro->Start().then([coro, size, self = shared_from_this()](auto f) mutable { coro.reset(); // breaks the cycle between the completion queue and coro @@ -186,14 +188,15 @@ class AsyncWriterConnectionImpl::State future Flush(storage::WritePayload payload) { std::unique_lock lk(mu_); - auto write = MakeRequestLocked(); + google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; lk.unlock(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = PartialUpload::Call(impl_, hash_function_, std::move(write), - std::move(p), PartialUpload::kFlush); + absl::Cord p = WritePayloadImpl::GetImpl(payload); + std::size_t const size = p.size(); + std::shared_ptr coro = + PartialUpload::Call(impl_, hash_function_, std::move(write), + std::move(p), PartialUpload::kFlush); return coro->Start().then([coro, size, self = shared_from_this()](auto f) mutable { @@ -204,13 +207,13 @@ class AsyncWriterConnectionImpl::State future Close(storage::WritePayload payload) { std::unique_lock lk(mu_); - auto write = MakeRequestLocked(); + google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; lk.unlock(); - auto p = WritePayloadImpl::GetImpl(payload); - auto size = p.size(); - auto coro = + absl::Cord p = WritePayloadImpl::GetImpl(payload); + std::size_t const size = p.size(); + std::shared_ptr coro = PartialUpload::Call(impl_, hash_function_, std::move(write), std::move(p), PartialUpload::kFlushAndClose); @@ -238,7 +241,7 @@ class AsyncWriterConnectionImpl::State private: google::storage::v2::BidiWriteObjectRequest MakeRequestLocked() { - auto request = request_; + google::storage::v2::BidiWriteObjectRequest request = request_; if (first_request_) { first_request_ = false; if (latest_write_handle_.has_value() && @@ -301,7 +304,8 @@ class AsyncWriterConnectionImpl::State future operator()( future> f) { - auto response = std::move(f).get(); + std::optional response = + std::move(f).get(); if (!response.has_value()) { return self->FinishAndCompleteOp().then(HandleFinishAfterError( "Expected error in Finish() after non-ok Read()")); @@ -324,7 +328,7 @@ class AsyncWriterConnectionImpl::State return self->FinishOnShutdownLocked(std::move(lk)); } lk.unlock(); - auto impl = self->impl_; + std::shared_ptr impl = self->impl_; return impl->Read().then(std::move(*this)); } }; @@ -353,7 +357,8 @@ class AsyncWriterConnectionImpl::State future operator()( future> f) { - auto response = std::move(f).get(); + std::optional response = + std::move(f).get(); if (!response.has_value()) return make_ready_future(); return impl->Read().then(*this); } @@ -396,7 +401,8 @@ class AsyncWriterConnectionImpl::State future operator()( future> f) { - auto response = std::move(f).get(); + std::optional response = + std::move(f).get(); if (!response.has_value()) return make_ready_future(); { std::unique_lock lk(self->mu_); @@ -410,7 +416,7 @@ class AsyncWriterConnectionImpl::State self->persisted_state_ = response->resource(); } } - auto impl = self->impl_; + std::shared_ptr impl = self->impl_; return impl->Read().then(std::move(*this)); } }; @@ -421,7 +427,7 @@ class AsyncWriterConnectionImpl::State std::move(f).get(); return self->FinishAndCompleteOp().then( [self](auto f2) -> StatusOr { - auto status = f2.get(); + Status status = f2.get(); if (!status.ok()) return status; std::unique_lock lk(self->mu_); if (!std::holds_alternative( @@ -440,7 +446,7 @@ class AsyncWriterConnectionImpl::State --in_flight_; if (in_flight_ == 0) { return FinishLocked(std::move(lk)).then([](future f) { - auto status = f.get(); + Status status = f.get(); if (!status.ok()) return status; // The writer was destroyed before the operation could read its // response, so never report OK (and avoid constructing From 43790ea3e7361d7bc1d5f8c1f5445abd3b64640d Mon Sep 17 00:00:00 2001 From: Vaibhav Pratap Date: Tue, 1 Dec 2026 06:56:59 +0000 Subject: [PATCH 4/4] style(storage): fix explicit lambda types and clang-tidy value params --- .../internal/async/writer_connection_impl.cc | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/google/cloud/storage/internal/async/writer_connection_impl.cc b/google/cloud/storage/internal/async/writer_connection_impl.cc index 09af38eb45613..294b758a70ff8 100644 --- a/google/cloud/storage/internal/async/writer_connection_impl.cc +++ b/google/cloud/storage/internal/async/writer_connection_impl.cc @@ -23,6 +23,7 @@ #include "google/cloud/storage/internal/grpc/object_metadata_parser.h" #include "google/cloud/storage/internal/grpc/object_request_parser.h" #include "google/cloud/internal/make_status.h" +#include "absl/strings/cord.h" #include #include #include @@ -107,7 +108,7 @@ class AsyncWriterConnectionImpl::State return persisted_state_; } - future Write(storage::WritePayload payload) { + future Write(storage::WritePayload const& payload) { std::unique_lock lk(mu_); google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; @@ -119,15 +120,15 @@ class AsyncWriterConnectionImpl::State PartialUpload::Call(impl_, hash_function_, std::move(write), std::move(p), PartialUpload::kNone); - return coro->Start().then([coro, size, - self = shared_from_this()](auto f) mutable { + return coro->Start().then([coro, size, self = shared_from_this()]( + future> f) mutable { coro.reset(); // breaks the cycle between the completion queue and coro return self->OnPartialUpload(size, f.get()); }); } future> Finalize( - storage::WritePayload payload) { + storage::WritePayload const& payload) { std::unique_lock lk(mu_); google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; @@ -179,14 +180,14 @@ class AsyncWriterConnectionImpl::State std::shared_ptr coro = PartialUpload::Call( impl_, hash_function_, std::move(write), std::move(p), action); - return coro->Start().then([coro, size, - self = shared_from_this()](auto f) mutable { + return coro->Start().then([coro, size, self = shared_from_this()]( + future> f) mutable { coro.reset(); // breaks the cycle between the completion queue and coro return self->OnFinalUpload(size, f.get()); }); } - future Flush(storage::WritePayload payload) { + future Flush(storage::WritePayload const& payload) { std::unique_lock lk(mu_); google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; @@ -198,14 +199,14 @@ class AsyncWriterConnectionImpl::State PartialUpload::Call(impl_, hash_function_, std::move(write), std::move(p), PartialUpload::kFlush); - return coro->Start().then([coro, size, - self = shared_from_this()](auto f) mutable { + return coro->Start().then([coro, size, self = shared_from_this()]( + future> f) mutable { coro.reset(); // breaks the cycle between the completion queue and coro return self->OnFlush(size, f.get()); }); } - future Close(storage::WritePayload payload) { + future Close(storage::WritePayload const& payload) { std::unique_lock lk(mu_); google::storage::v2::BidiWriteObjectRequest write = MakeRequestLocked(); ++in_flight_; @@ -217,8 +218,8 @@ class AsyncWriterConnectionImpl::State PartialUpload::Call(impl_, hash_function_, std::move(write), std::move(p), PartialUpload::kFlushAndClose); - return coro->Start().then([coro, size, - self = shared_from_this()](auto f) mutable { + return coro->Start().then([coro, size, self = shared_from_this()]( + future> f) mutable { coro.reset(); // breaks the cycle between the completion queue and coro return self->OnClose(size, f.get()); }); @@ -366,7 +367,7 @@ class AsyncWriterConnectionImpl::State return impl_->Read() .then(ConsumeLoop{impl_}) - .then([self = shared_from_this()](auto f) { + .then([self = shared_from_this()](future f) { f.get(); return self->FinishAndCompleteOp(); }); @@ -423,10 +424,11 @@ class AsyncWriterConnectionImpl::State return impl_->Read() .then(ConsumeLoop{shared_from_this()}) - .then([self = shared_from_this()](auto f) { + .then([self = shared_from_this()](future f) { std::move(f).get(); return self->FinishAndCompleteOp().then( - [self](auto f2) -> StatusOr { + [self]( + future f2) -> StatusOr { Status status = f2.get(); if (!status.ok()) return status; std::unique_lock lk(self->mu_); @@ -481,12 +483,13 @@ class AsyncWriterConnectionImpl::State // Extend the lifetime of `*this` (and therefore `impl_`) until // `impl_->Finish()` completes. - return impl_->Finish().then([self = shared_from_this()](auto f) mutable { - // Break any ownership cycle between the completion queue and this - // callback. - self.reset(); - return f.get(); - }); + return impl_->Finish().then( + [self = shared_from_this()](future f) mutable { + // Break any ownership cycle between the completion queue and this + // callback. + self.reset(); + return f.get(); + }); } google::cloud::internal::ImmutableOptions const options_; @@ -562,20 +565,20 @@ AsyncWriterConnectionImpl::PersistedState() const { } future AsyncWriterConnectionImpl::Write(storage::WritePayload payload) { - return state_->Write(std::move(payload)); + return state_->Write(payload); } future> AsyncWriterConnectionImpl::Finalize(storage::WritePayload payload) { - return state_->Finalize(std::move(payload)); + return state_->Finalize(payload); } future AsyncWriterConnectionImpl::Flush(storage::WritePayload payload) { - return state_->Flush(std::move(payload)); + return state_->Flush(payload); } future AsyncWriterConnectionImpl::Close(storage::WritePayload payload) { - return state_->Close(std::move(payload)); + return state_->Close(payload); } future> AsyncWriterConnectionImpl::Query() {