diff --git a/google/cloud/storage/internal/async/open_object.cc b/google/cloud/storage/internal/async/open_object.cc index 148bdfb1cd593..659750d9faad3 100644 --- a/google/cloud/storage/internal/async/open_object.cc +++ b/google/cloud/storage/internal/async/open_object.cc @@ -44,7 +44,10 @@ OpenObject::OpenObject(storage_internal::StorageStub& stub, CompletionQueue& cq, initial_request_(std::move(request)) {} future> OpenObject::Call() { - auto future = promise_.get_future(); + promise_ = promise>([w = WeakFromThis()] { + if (std::shared_ptr self = w.lock()) self->OnCancel(); + }); + future> future = promise_.get_future(); rpc_->Start().then([w = WeakFromThis()](auto f) { if (auto self = w.lock()) self->OnStart(f.get()); }); @@ -92,9 +95,20 @@ void OpenObject::OnWrite(bool ok) { void OpenObject::OnRead( std::optional response) { if (!response) return DoFinish(); + State expected = State::kOpening; + if (!state_.compare_exchange_strong(expected, State::kCommitted)) { + rpc_->Cancel(); + return DoFinish(); + } promise_.set_value(OpenStreamResult{std::move(rpc_), std::move(*response)}); } +void OpenObject::OnCancel() { + State expected = State::kOpening; + if (!state_.compare_exchange_strong(expected, State::kCancelled)) return; + rpc_->Cancel(); +} + void OpenObject::DoFinish() { rpc_->Finish().then([w = WeakFromThis()](auto f) { if (auto self = w.lock()) self->OnFinish(f.get()); @@ -102,6 +116,11 @@ void OpenObject::DoFinish() { } void OpenObject::OnFinish(Status status) { + if (state_.load() == State::kCancelled) { + promise_.set_value(google::cloud::internal::CancelledError( + "Stream cancelled while opening", GCP_ERROR_INFO())); + return; + } if (!status.ok()) return promise_.set_value(std::move(status)); // This should not happen, it indicates an EOF on the stream, but we // did not ask to close it. diff --git a/google/cloud/storage/internal/async/open_object.h b/google/cloud/storage/internal/async/open_object.h index 65f01dba4024c..c600e3e3540d8 100644 --- a/google/cloud/storage/internal/async/open_object.h +++ b/google/cloud/storage/internal/async/open_object.h @@ -25,6 +25,7 @@ #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" #include +#include #include #include @@ -89,6 +90,8 @@ class OpenObject : public std::enable_shared_from_this { future> Call(); private: + enum class State { kOpening, kCommitted, kCancelled }; + std::weak_ptr WeakFromThis(); static std::unique_ptr CreateRpc( @@ -101,12 +104,14 @@ class OpenObject : public std::enable_shared_from_this { void OnWrite(bool ok); void OnRead( std::optional response); + void OnCancel(); void DoFinish(); void OnFinish(Status status); std::shared_ptr rpc_; - promise> promise_; + promise> promise_{null_promise_t{}}; google::storage::v2::BidiReadObjectRequest initial_request_; + std::atomic state_{State::kOpening}; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/open_object_test.cc b/google/cloud/storage/internal/async/open_object_test.cc index c1fa3a4dcde02..0ccf2e714276b 100644 --- a/google/cloud/storage/internal/async/open_object_test.cc +++ b/google/cloud/storage/internal/async/open_object_test.cc @@ -24,8 +24,12 @@ #include "google/cloud/testing_util/validate_metadata.h" #include #include +#include #include +#include #include +#include +#include namespace google { namespace cloud { @@ -472,6 +476,178 @@ TEST(OpenImpl, TimeoutCancellation) { EXPECT_THAT(response, StatusIs(StatusCode::kCancelled)); } +enum class CancelPhase { kStart, kWrite, kRead, kFinish }; + +class OpenObjectCancelPhaseTest : public ::testing::TestWithParam { +}; + +TEST_P(OpenObjectCancelPhaseTest, CancelsCleanlyAtHandshakePhase) { + CancelPhase const phase = GetParam(); + AsyncSequencer sequencer; + MockStorageStub mock; + EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&sequencer, phase] { + auto stream = std::make_unique(); + EXPECT_CALL(*stream, Start).WillOnce([&sequencer] { + return sequencer.PushBack("Start").then( + [](future f) { return f.get(); }); + }); + if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) { + EXPECT_CALL(*stream, Write).WillOnce([&sequencer] { + return sequencer.PushBack("Write").then( + [](future f) { return f.get(); }); + }); + } + if (phase == CancelPhase::kRead) { + EXPECT_CALL(*stream, Read).WillOnce([&sequencer] { + return sequencer.PushBack("Read").then([](future) { + return std::make_optional( + google::storage::v2::BidiReadObjectResponse{}); + }); + }); + } + if (phase != CancelPhase::kFinish) { + ::testing::InSequence seq; + EXPECT_CALL(*stream, Cancel).Times(1); + EXPECT_CALL(*stream, Finish).WillOnce([&sequencer, phase] { + return sequencer.PushBack("Finish").then([phase](future) { + return phase == CancelPhase::kRead + ? internal::UnavailableError("reset", GCP_ERROR_INFO()) + : Status{}; + }); + }); + } else { + ::testing::InSequence seq; + EXPECT_CALL(*stream, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then( + [](future) { return Status{}; }); + }); + EXPECT_CALL(*stream, Cancel).Times(1); + } + return std::unique_ptr(std::move(stream)); + }); + + CompletionQueue cq; + auto coro = std::make_shared( + mock, cq, std::make_shared(), + internal::MakeImmutableOptions({}), + google::storage::v2::BidiReadObjectRequest{}); + future> pending = coro->Call(); + + auto const pop = [&sequencer](char const* expected) { + auto [p, name] = sequencer.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + }; + + promise start = pop("Start"); + if (phase == CancelPhase::kStart) pending.cancel(); + start.set_value(phase != CancelPhase::kFinish); + + if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) { + promise write = pop("Write"); + if (phase == CancelPhase::kWrite) pending.cancel(); + write.set_value(true); + } + if (phase == CancelPhase::kRead) { + promise read = pop("Read"); + pending.cancel(); + read.set_value(true); + } + + promise finish = pop("Finish"); + if (phase == CancelPhase::kFinish) pending.cancel(); + EXPECT_FALSE(pending.is_ready()); + finish.set_value(true); + + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); +} + +INSTANTIATE_TEST_SUITE_P(CancelPhases, OpenObjectCancelPhaseTest, + ::testing::Values(CancelPhase::kStart, + CancelPhase::kWrite, + CancelPhase::kRead, + CancelPhase::kFinish)); + +TEST(OpenImpl, ConcurrentCancelAndReadCompletion) { + for (int iter = 0; iter != 25; ++iter) { + std::mutex gate_mu; + std::condition_variable gate_cv; + int ready = 0; + bool release = false; + std::atomic cancel_calls{0}; + auto read_promise = std::make_shared< + promise>>(); + future read_future = read_promise->get_future(); + + MockStorageStub mock; + EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&] { + auto stream = std::make_unique<::testing::NiceMock>(); + ON_CALL(*stream, Start).WillByDefault([] { + return make_ready_future(true); + }); + ON_CALL(*stream, Write) + .WillByDefault( + [](google::storage::v2::BidiReadObjectRequest const&, + grpc::WriteOptions) { return make_ready_future(true); }); + EXPECT_CALL(*stream, Read) + .WillOnce( + [f = std::move(read_future)]() mutable { return std::move(f); }) + .WillRepeatedly([] { + return make_ready_future(std::make_optional( + google::storage::v2::BidiReadObjectResponse{})); + }); + ON_CALL(*stream, Cancel).WillByDefault([&cancel_calls] { + ++cancel_calls; + }); + ON_CALL(*stream, Finish).WillByDefault([] { + return make_ready_future(Status{}); + }); + return std::unique_ptr(std::move(stream)); + }); + + CompletionQueue cq; + auto coro = std::make_shared( + mock, cq, std::make_shared(), + internal::MakeImmutableOptions({}), + google::storage::v2::BidiReadObjectRequest{}); + future> pending = coro->Call(); + + auto const wait_at_gate = [&] { + std::unique_lock lock(gate_mu); + ++ready; + gate_cv.notify_all(); + gate_cv.wait(lock, [&] { return release; }); + }; + std::thread reader([&] { + wait_at_gate(); + read_promise->set_value( + std::make_optional(google::storage::v2::BidiReadObjectResponse{})); + }); + std::thread canceller([&] { + wait_at_gate(); + pending.cancel(); + }); + + { + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return ready == 2; }); + release = true; + } + gate_cv.notify_all(); + reader.join(); + canceller.join(); + + StatusOr result = pending.get(); + if (result.ok()) { + EXPECT_EQ(cancel_calls.load(), 0); + EXPECT_TRUE(result->stream->Read().get().has_value()); + } else { + EXPECT_THAT(result, StatusIs(StatusCode::kCancelled)); + EXPECT_EQ(cancel_calls.load(), 1); + } + } +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/open_stream.cc b/google/cloud/storage/internal/async/open_stream.cc index ca41fba9c6557..c5ff2660a0991 100644 --- a/google/cloud/storage/internal/async/open_stream.cc +++ b/google/cloud/storage/internal/async/open_stream.cc @@ -24,62 +24,100 @@ OpenStream::OpenStream(std::unique_ptr rpc) : rpc_(std::move(rpc)) {} void OpenStream::Cancel() { - cancel_.store(true); + { + std::lock_guard lk(mu_); + if (cancel_) return; + cancel_ = true; + ++pending_ops_; + if (!finish_issued_) { + finish_issued_ = true; + finish_deferred_ = true; + finish_promise_ = promise{}; + finish_ = finish_promise_.get_future(); + } + } rpc_->Cancel(); - MaybeFinish(); + EndOp(); } future OpenStream::Start() { - if (cancel_) return make_ready_future(false); - return rpc_->Start(); + if (!BeginOp()) return make_ready_future(false); + return rpc_->Start().then([s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + bool const ok = f.get(); + return !cancelled && ok; + }); } future OpenStream::Write( google::storage::v2::BidiReadObjectRequest const& request) { - if (cancel_) return make_ready_future(false); - pending_write_.store(true); + if (!BeginOp()) return make_ready_future(false); return rpc_->Write(request, grpc::WriteOptions{}) - .then([s = shared_from_this()](auto f) mutable { - auto self = std::move(s); - self->OnWrite(); - return f.get(); + .then([s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + bool const ok = f.get(); + return !cancelled && ok; }); } future OpenStream::Read() { - if (cancel_) return make_ready_future(ReadType(std::nullopt)); - pending_read_.store(true); - return rpc_->Read().then([s = shared_from_this()](auto f) mutable { - auto self = std::move(s); - self->OnRead(); - return f.get(); - }); + if (!BeginOp()) return make_ready_future(ReadType(std::nullopt)); + return rpc_->Read().then( + [s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + ReadType result = f.get(); + if (cancelled) return ReadType(std::nullopt); + return result; + }); } future OpenStream::Finish() { - if (finish_issued_.exchange(true)) return {}; - return rpc_->Finish().then([s = shared_from_this()](auto f) mutable { - auto result = f.get(); - s.reset(); - return result; - }); -} - -void OpenStream::OnWrite() { - pending_write_.store(false); - return MaybeFinish(); + { + std::lock_guard lk(mu_); + if (finish_issued_) return std::move(finish_); + finish_issued_ = true; + } + return rpc_->Finish().then( + [s = shared_from_this()](future f) mutable { + s.reset(); + return f.get(); + }); } -void OpenStream::OnRead() { - pending_read_.store(false); - return MaybeFinish(); +bool OpenStream::BeginOp() { + std::lock_guard lk(mu_); + if (cancel_ || finish_issued_) return false; + ++pending_ops_; + return true; } -void OpenStream::MaybeFinish() { - if (!cancel_) return; - // Once `cancel_` is true these can only become false. - if (pending_read_ || pending_write_) return; - Finish(); +bool OpenStream::EndOp() { + promise deferred_finish{null_promise_t{}}; + bool issue_finish = false; + bool cancelled = false; + { + std::lock_guard lk(mu_); + --pending_ops_; + cancelled = cancel_; + if (finish_deferred_ && pending_ops_ == 0) { + finish_deferred_ = false; + deferred_finish = std::move(finish_promise_); + issue_finish = true; + } + } + if (issue_finish) { + rpc_->Finish().then( + [s = shared_from_this(), + p = std::move(deferred_finish)](future f) mutable { + promise out = std::move(p); + s.reset(); + out.set_value(f.get()); + }); + } + return cancelled; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/open_stream.h b/google/cloud/storage/internal/async/open_stream.h index b339d6949bd02..7574994514d38 100644 --- a/google/cloud/storage/internal/async/open_stream.h +++ b/google/cloud/storage/internal/async/open_stream.h @@ -21,9 +21,9 @@ #include "google/cloud/status_or.h" #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" -#include #include #include +#include #include namespace google { @@ -36,12 +36,13 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN * * gRPC imposes a number of restrictions on how to close bidi streaming RPCs. * This class automates most of these restrictions. In particular, it waits - * (using background threads) until all pending `Read()` and `Write()` calls - * complete before trying to `Finish()` and then delete the stream. + * (using background threads) until all pending `Start()`, `Read()`, and + * `Write()` calls complete before trying to `Finish()` and then delete the + * stream. * * gRPC will assert if one deletes a streaming read-write RPC before waiting for * the result of `Finish()` calls. It will also assert if one calls `Finish()` - * while there are pending `Read()` or `Write()` calls. + * while there are pending `Start()`, `Read()`, or `Write()` calls. * * This class tracks what operations, if any, are pending. On cancel, it waits * until all pending operations complete, then calls `Finish()` and then deletes @@ -62,21 +63,29 @@ class OpenStream : public std::enable_shared_from_this { explicit OpenStream(std::unique_ptr rpc); + /// Cancels the stream and calls `Finish()` once pending operations drain. void Cancel(); future Start(); future Write(google::storage::v2::BidiReadObjectRequest const& request); future Read(); + /// Returns the stream's `Finish()` future; subsequent calls return `{}`. future Finish(); private: - void OnWrite(); - void OnRead(); - void MaybeFinish(); + bool BeginOp(); + /// Decrements `pending_ops_`, starts any cancel-deferred `Finish()` at 0, + /// and returns whether `Cancel()` has been called. + bool EndOp(); - std::atomic cancel_{false}; - std::atomic pending_read_{false}; - std::atomic pending_write_{false}; - std::atomic finish_issued_{false}; + std::mutex mu_; + /// Active `Start()`, `Write()`, `Read()`, and `Cancel()` calls blocking + /// cancel-deferred `rpc_->Finish()`. + int pending_ops_ = 0; + bool cancel_ = false; + bool finish_issued_ = false; + bool finish_deferred_ = false; + promise finish_promise_{null_promise_t{}}; + future finish_; std::unique_ptr rpc_; }; diff --git a/google/cloud/storage/internal/async/open_stream_test.cc b/google/cloud/storage/internal/async/open_stream_test.cc index 7a8183e36ebe9..0de36586e7f30 100644 --- a/google/cloud/storage/internal/async/open_stream_test.cc +++ b/google/cloud/storage/internal/async/open_stream_test.cc @@ -40,12 +40,15 @@ TEST(OpenStream, CancelBlocksAllRequest) { EXPECT_CALL(*mock, Start).Times(0); EXPECT_CALL(*mock, Write).Times(0); EXPECT_CALL(*mock, Read).Times(0); - EXPECT_CALL(*mock, Cancel).Times(1); - EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { - return sequencer.PushBack("Finish").then([](auto) { - return internal::CancelledError("test-only", GCP_ERROR_INFO()); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then([](auto) { + return internal::CancelledError("test-only", GCP_ERROR_INFO()); + }); }); - }); + } auto actual = std::make_shared(std::move(mock)); actual->Cancel(); @@ -73,7 +76,8 @@ TEST(OpenStream, DuplicateFinish) { auto actual = std::make_shared(std::move(mock)); - auto f1 = actual->Finish(); + future f1 = actual->Finish(); + EXPECT_FALSE(actual->Finish().valid()); auto next = sequencer.PopFrontWithName(); EXPECT_EQ(next.second, "Finish"); next.first.set_value(true); @@ -119,6 +123,75 @@ TEST(OpenStream, CleanShutdown) { next.first.set_value(true); } +TEST(OpenStream, CancelDuringStartDefersFinishAndHandsOffFutureOnce) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Start).WillOnce([&sequencer] { + return sequencer.PushBack("Start").then( + [](future f) { return f.get(); }); + }); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then([](future) { + return internal::CancelledError("test-only", GCP_ERROR_INFO()); + }); + }); + } + + auto actual = std::make_shared(std::move(mock)); + future start = actual->Start(); + auto [pending_start, start_name] = sequencer.PopFrontWithName(); + EXPECT_EQ(start_name, "Start"); + + actual->Cancel(); + actual->Cancel(); + future claimed = actual->Finish(); + ASSERT_TRUE(claimed.valid()); + EXPECT_FALSE(claimed.is_ready()); + EXPECT_FALSE(actual->Finish().valid()); + actual.reset(); + + // `Finish` must not be invoked on `mock` until `Start` completes. + EXPECT_TRUE(sequencer.empty()); + pending_start.set_value(true); + EXPECT_FALSE(start.get()); + + auto [pending_finish, finish_name] = sequencer.PopFrontWithName(); + EXPECT_EQ(finish_name, "Finish"); + pending_finish.set_value(true); + EXPECT_THAT(claimed.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST(OpenStream, CancelDuringReadDropsResponseAndReleasesRetainedPromise) { + auto retained_read = std::make_shared>(); + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Read).WillOnce([retained_read] { + return retained_read->get_future(); + }); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([] { + return make_ready_future(Status{}); + }); + } + + auto actual = std::make_shared(std::move(mock)); + std::weak_ptr weak = actual; + future read = actual->Read(); + + actual->Cancel(); + actual.reset(); + EXPECT_FALSE(weak.expired()); + + retained_read->set_value( + ReadType(google::storage::v2::BidiReadObjectResponse{})); + EXPECT_FALSE(read.get().has_value()); + EXPECT_TRUE(weak.expired()); +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal