Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3580,11 +3580,10 @@ TEST(ObjectDescriptorImpl, IgnoresCallbacksFromStaleStreams) {
return f.get();
});
});
EXPECT_CALL(*stream1, Finish).WillOnce([&sequencer]() {
return sequencer.PushBack("Finish[1]").then([](auto f) {
if (f.get()) return TransientError();
return PermanentError();
});
int stream1_finish_calls = 0;
EXPECT_CALL(*stream1, Finish).WillOnce([&stream1_finish_calls]() {
++stream1_finish_calls;
return make_ready_future(TransientError());
});

auto stream2 = std::make_unique<MockStream>();
Expand All @@ -3601,7 +3600,9 @@ TEST(ObjectDescriptorImpl, IgnoresCallbacksFromStaleStreams) {
return f.get();
});
});
EXPECT_CALL(*stream2, Finish).WillRepeatedly([]() {
int stream2_finish_calls = 0;
EXPECT_CALL(*stream2, Finish).WillRepeatedly([&stream2_finish_calls]() {
++stream2_finish_calls;
return make_ready_future(Status{});
});

Expand Down Expand Up @@ -3635,21 +3636,23 @@ TEST(ObjectDescriptorImpl, IgnoresCallbacksFromStaleStreams) {
auto write1 = sequencer.PopFrontWithName();
EXPECT_EQ(write1.second, "Write[1]");

// Stream 1 fails on read and resumes stream 2
// Stream 1 fails on read while Write[1] is still in flight. OpenStream defers
// Finish[1] until Write[1] drains.
read1.first.set_value(false);
EXPECT_EQ(stream1_finish_calls, 0);
EXPECT_TRUE(sequencer.empty());

auto next = sequencer.PopFrontWithName();
EXPECT_EQ(next.second, "Finish[1]");
next.first.set_value(true);
// When Write[1] completes, OpenStream::EndOp() runs Finish[1] synchronously,
// resuming stream 2 before ObjectDescriptorImpl::OnWrite() runs with the
// stale stream 1 callback. It must NOT call Finish[2] on stream 2.
write1.first.set_value(false);
EXPECT_EQ(stream1_finish_calls, 1);
EXPECT_EQ(stream2_finish_calls, 0);

// Stream 2 is now active
auto read2 = sequencer.PopFrontWithName();
EXPECT_EQ(read2.second, "Read[2]");

// A stale Write[1] callback from stream 1 arrives late with false (error).
// It should NOT call Finish[2] on stream 2!
write1.first.set_value(false);

EXPECT_TRUE(sequencer.empty());

tested.reset();
Expand Down
21 changes: 20 additions & 1 deletion google/cloud/storage/internal/async/open_object.cc
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ OpenObject::OpenObject(storage_internal::StorageStub& stub, CompletionQueue& cq,
initial_request_(std::move(request)) {}

future<StatusOr<OpenStreamResult>> OpenObject::Call() {
auto future = promise_.get_future();
promise_ = promise<StatusOr<OpenStreamResult>>([w = WeakFromThis()] {
if (std::shared_ptr<OpenObject> self = w.lock()) self->OnCancel();
});
future<StatusOr<OpenStreamResult>> future = promise_.get_future();
rpc_->Start().then([w = WeakFromThis()](auto f) {
if (auto self = w.lock()) self->OnStart(f.get());
});
Expand Down Expand Up @@ -92,16 +95,32 @@ void OpenObject::OnWrite(bool ok) {
void OpenObject::OnRead(
std::optional<google::storage::v2::BidiReadObjectResponse> 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());
});
}

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.
Expand Down
7 changes: 6 additions & 1 deletion google/cloud/storage/internal/async/open_object.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "google/cloud/version.h"
#include "google/storage/v2/storage.pb.h"
#include <grpcpp/grpcpp.h>
#include <atomic>
#include <memory>
#include <string>

Expand Down Expand Up @@ -89,6 +90,8 @@ class OpenObject : public std::enable_shared_from_this<OpenObject> {
future<StatusOr<OpenStreamResult>> Call();

private:
enum class State { kOpening, kCommitted, kCancelled };

std::weak_ptr<OpenObject> WeakFromThis();

static std::unique_ptr<OpenStream::StreamingRpc> CreateRpc(
Expand All @@ -101,12 +104,14 @@ class OpenObject : public std::enable_shared_from_this<OpenObject> {
void OnWrite(bool ok);
void OnRead(
std::optional<google::storage::v2::BidiReadObjectResponse> response);
void OnCancel();
void DoFinish();
void OnFinish(Status status);

std::shared_ptr<OpenStream> rpc_;
promise<StatusOr<OpenStreamResult>> promise_;
promise<StatusOr<OpenStreamResult>> promise_{null_promise_t{}};
google::storage::v2::BidiReadObjectRequest initial_request_;
std::atomic<State> state_{State::kOpening};
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
Expand Down
181 changes: 181 additions & 0 deletions google/cloud/storage/internal/async/open_object_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@
#include "google/cloud/testing_util/validate_metadata.h"
#include <google/protobuf/text_format.h>
#include <gmock/gmock.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>

namespace google {
namespace cloud {
Expand Down Expand Up @@ -472,6 +476,183 @@ TEST(OpenImpl, TimeoutCancellation) {
EXPECT_THAT(response, StatusIs(StatusCode::kCancelled));
}

enum class CancelPhase { kStart, kWrite, kRead, kFinish };

class OpenObjectCancelPhaseTest : public ::testing::TestWithParam<CancelPhase> {
};

TEST_P(OpenObjectCancelPhaseTest, CancelsCleanlyAtHandshakePhase) {
CancelPhase const phase = GetParam();
AsyncSequencer<bool> sequencer;
MockStorageStub mock;
EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&sequencer, phase] {
auto stream = std::make_unique<MockStream>();
EXPECT_CALL(*stream, Start).WillOnce([&sequencer] {
return sequencer.PushBack("Start").then(
[](future<bool> f) { return f.get(); });
});
if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) {
EXPECT_CALL(*stream, Write).WillOnce([&sequencer] {
return sequencer.PushBack("Write").then(
[](future<bool> f) { return f.get(); });
});
}
if (phase == CancelPhase::kRead) {
EXPECT_CALL(*stream, Read).WillOnce([&sequencer] {
return sequencer.PushBack("Read").then([](future<bool>) {
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<bool>) {
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<bool>) { return Status{}; });
});
EXPECT_CALL(*stream, Cancel).Times(1);
}
return std::unique_ptr<OpenStream::StreamingRpc>(std::move(stream));
});

CompletionQueue cq;
auto coro = std::make_shared<OpenObject>(
mock, cq, std::make_shared<grpc::ClientContext>(),
internal::MakeImmutableOptions({}),
google::storage::v2::BidiReadObjectRequest{});
future<StatusOr<OpenStreamResult>> pending = coro->Call();

auto const pop = [&sequencer](char const* expected) {
auto [p, name] = sequencer.PopFrontWithName();
EXPECT_EQ(name, expected);
return std::move(p);
};

promise<bool> start = pop("Start");
if (phase == CancelPhase::kStart) pending.cancel();
start.set_value(phase != CancelPhase::kFinish);

if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) {
promise<bool> write = pop("Write");
if (phase == CancelPhase::kWrite) pending.cancel();
write.set_value(true);
}
if (phase == CancelPhase::kRead) {
promise<bool> read = pop("Read");
pending.cancel();
read.set_value(true);
}

promise<bool> 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<int> cancel_calls{0};
std::atomic<int> finish_calls{0};
auto read_promise = std::make_shared<
promise<std::optional<google::storage::v2::BidiReadObjectResponse>>>();
future<OpenStream::ReadType> read_future = read_promise->get_future();

MockStorageStub mock;
EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&] {
auto stream = std::make_unique<::testing::NiceMock<MockStream>>();
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([&cancel_calls, &finish_calls] {
EXPECT_EQ(cancel_calls.load(), 1);
++finish_calls;
return make_ready_future(Status{});
});
return std::unique_ptr<OpenStream::StreamingRpc>(std::move(stream));
});

CompletionQueue cq;
auto coro = std::make_shared<OpenObject>(
mock, cq, std::make_shared<grpc::ClientContext>(),
internal::MakeImmutableOptions({}),
google::storage::v2::BidiReadObjectRequest{});
future<StatusOr<OpenStreamResult>> pending = coro->Call();

auto const wait_at_gate = [&] {
std::unique_lock<std::mutex> 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<std::mutex> lock(gate_mu);
gate_cv.wait(lock, [&] { return ready == 2; });
release = true;
}
gate_cv.notify_all();
reader.join();
canceller.join();

StatusOr<OpenStreamResult> result = pending.get();
if (result.ok()) {
EXPECT_EQ(cancel_calls.load(), 0);
EXPECT_EQ(finish_calls.load(), 0);
EXPECT_TRUE(result->stream->Read().get().has_value());
} else {
EXPECT_THAT(result, StatusIs(StatusCode::kCancelled));
EXPECT_EQ(cancel_calls.load(), 1);
EXPECT_EQ(finish_calls.load(), 1);
}
}
}

} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage_internal
Expand Down
Loading
Loading