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
11 changes: 11 additions & 0 deletions google/cloud/storage/async/object_descriptor.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
*
* Applications use an `ObjectDescriptor` to perform multiple reads on the same
* Google Cloud Storage object.
*
* Destroying an `ObjectDescriptor` cancels any unfinished reads started from
* it. Each affected `AsyncReader` returns any data received before
* cancellation, followed by `StatusCode::kCancelled`. To receive all data, keep
* the `ObjectDescriptor` alive until every `AsyncReader` started from it
* returns its final status.
*
* Cancelled reads complete on the client's completion queue, like any other
* read. If that queue has already been shut down (for example, via
* `CompletionQueue::Shutdown()`), they complete on the thread that destroys
* the descriptor.
*/
class ObjectDescriptor {
public:
Expand Down
58 changes: 30 additions & 28 deletions google/cloud/storage/internal/async/connection_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -344,34 +344,36 @@ AsyncConnectionImpl::Open(OpenParams p) {

auto pending = factory(std::move(initial_request));
using ReturnType = std::shared_ptr<storage::ObjectDescriptorConnection>;
return pending.then([rp = std::move(resume_policy), fa = std::move(factory),
qfa = std::move(clean_resume_factory),
rs = std::move(p.read_spec),
options = std::move(p.options), refresh = refresh_](
auto f) mutable -> StatusOr<ReturnType> {
auto result = f.get();
if (!result) return std::move(result).status();

// The descriptor remains open if at least one gRPC channel is in a
// functional state. We consider READY, IDLE, and CONNECTING to be
// functional. TRANSIENT_FAILURE and SHUTDOWN are not included because
// they indicate a definitive loss of connectivity or terminal closure.
auto transport_ok = [refresh] {
if (!refresh) return true;
auto const& channels = refresh->channels();
return std::any_of(
channels.begin(), channels.end(), [](auto const& channel) {
auto state = channel->GetState(false);
return state == GRPC_CHANNEL_READY || state == GRPC_CHANNEL_IDLE ||
state == GRPC_CHANNEL_CONNECTING;
});
};
auto impl = std::make_shared<ObjectDescriptorImpl>(
std::move(rp), std::move(fa), std::move(qfa), std::move(rs),
std::move(result->stream), std::move(options), std::move(transport_ok));
impl->Start(std::move(result->first_response));
return ReturnType(impl);
});
return pending.then(
[cq = cq_, rp = std::move(resume_policy), fa = std::move(factory),
qfa = std::move(clean_resume_factory), rs = std::move(p.read_spec),
options = std::move(p.options),
refresh = refresh_](auto f) mutable -> StatusOr<ReturnType> {
auto result = f.get();
if (!result) return std::move(result).status();

// The descriptor remains open if at least one gRPC channel is in a
// functional state. We consider READY, IDLE, and CONNECTING to be
// functional. TRANSIENT_FAILURE and SHUTDOWN are not included because
// they indicate a definitive loss of connectivity or terminal closure.
auto transport_ok = [refresh] {
if (!refresh) return true;
auto const& channels = refresh->channels();
return std::any_of(channels.begin(), channels.end(),
[](auto const& channel) {
auto state = channel->GetState(false);
return state == GRPC_CHANNEL_READY ||
state == GRPC_CHANNEL_IDLE ||
state == GRPC_CHANNEL_CONNECTING;
});
};
auto impl = std::make_shared<ObjectDescriptorImpl>(
std::move(cq), std::move(rp), std::move(fa), std::move(qfa),
std::move(rs), std::move(result->stream), std::move(options),
std::move(transport_ok));
impl->Start(std::move(result->first_response));
return ReturnType(impl);
});
}

future<StatusOr<std::unique_ptr<storage::AsyncReaderConnection>>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@
#include "absl/strings/match.h"
#include <google/protobuf/text_format.h>
#include <gmock/gmock.h>
#include <chrono>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
Expand Down Expand Up @@ -73,6 +75,7 @@ using ::testing::NotNull;
using ::testing::Optional;
using ::testing::Pair;
using ::testing::SizeIs;
using ::testing::VariantWith;

using BidiReadStream = google::cloud::AsyncStreamingReadWriteRpc<
google::storage::v2::BidiReadObjectRequest,
Expand Down Expand Up @@ -908,6 +911,89 @@ TEST(AsyncConnectionImplTest, OpenWithReadRanges) {
next.first.set_value(true);
}

/// @test Verify that `AsyncConnectionImpl::Open()` passes its completion queue
/// to the `ObjectDescriptorImpl` it creates, so destroying the descriptor
/// schedules cancellation of active range reads on that queue.
TEST(AsyncConnectionImplTest, OpenPassesCompletionQueueToDescriptor) {
AsyncSequencer<bool> sequencer;
auto mock = std::make_shared<storage::testing::MockStorageStub>();
EXPECT_CALL(*mock, AsyncBidiReadObject)
.WillOnce([&sequencer](CompletionQueue const&,
std::shared_ptr<grpc::ClientContext> const&,
google::cloud::internal::ImmutableOptions const&) {
auto stream = std::make_unique<NiceMock<MockStream>>();
ON_CALL(*stream, Start).WillByDefault(InvokeWithoutArgs([] {
return make_ready_future(true);
}));
ON_CALL(*stream, Write).WillByDefault([](auto const&, auto) {
return make_ready_future(true);
});
ON_CALL(*stream, Read)
.WillByDefault(InvokeWithoutArgs([&sequencer,
read_count = 0]() mutable {
using Response = google::storage::v2::BidiReadObjectResponse;
// The first read satisfies Open(); the second stays parked
// until the descriptor is destroyed.
if (read_count++ == 0) {
return make_ready_future(std::optional<Response>(Response{}));
}
return sequencer.PushBack("Read").then(
[](auto) { return std::optional<Response>(); });
}));
ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] {
return make_ready_future(Status{});
}));
return std::unique_ptr<BidiReadStream>(std::move(stream));
});

auto mock_cq = std::make_shared<MockCompletionQueueImpl>();
promise<StatusOr<std::chrono::system_clock::time_point>> timer_promise;
bool timer_started = false;
EXPECT_CALL(*mock_cq, MakeRelativeTimer(std::chrono::nanoseconds(0)))
.WillOnce([&timer_started, &timer_promise] {
timer_started = true;
return timer_promise.get_future();
});

auto connection = std::make_shared<AsyncConnectionImpl>(
CompletionQueue(mock_cq), std::shared_ptr<GrpcChannelRefresh>(), mock,
TestOptions(
Options{}.set<storage::EnableMultiStreamOptimizationOption>(false)));

google::storage::v2::BidiReadObjectSpec request;
request.set_bucket("test-only-invalid");
request.set_object("test-object");
StatusOr<std::shared_ptr<storage::ObjectDescriptorConnection>> opened =
connection->Open({std::move(request), connection->options()}).get();
ASSERT_THAT(opened, IsOkAndHolds(NotNull()));
std::shared_ptr<storage::ObjectDescriptorConnection> descriptor =
*std::move(opened);

std::unique_ptr<storage::AsyncReaderConnection> reader =
descriptor->Read({/*start=*/0, /*length=*/1024});
future<storage::AsyncReaderConnection::ReadResponse> pending_read =
reader->Read();
ASSERT_FALSE(pending_read.is_ready());
ASSERT_FALSE(timer_started);

descriptor.reset();
EXPECT_TRUE(timer_started);
// Cancellation waits for the connection's completion queue timer rather than
// running inline on the destroying thread.
EXPECT_FALSE(pending_read.is_ready());

timer_promise.set_value(std::chrono::system_clock::now());
ASSERT_TRUE(pending_read.is_ready());
EXPECT_THAT(pending_read.get(),
VariantWith<Status>(StatusIs(StatusCode::kCancelled)));

// Release the parked read so the stream winds down before mocks are
// destroyed.
std::pair<promise<bool>, std::string> next = sequencer.PopFrontWithName();
EXPECT_EQ(next.second, "Read");
next.first.set_value(false);
}

} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage_internal
Expand Down
19 changes: 19 additions & 0 deletions google/cloud/storage/internal/async/multi_stream_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
#include <list>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>

namespace google {
namespace cloud {
Expand Down Expand Up @@ -139,6 +141,23 @@ class MultiStreamManager {
}
}

// Detaches and returns all active ranges across all streams without
// notifying them.
//
// Unlike `RemoveStreamAndNotifyRanges()`, this leaves the streams in place
// and defers range notifications so the caller can invoke them after
// releasing its mutex.
std::vector<std::shared_ptr<RangeT>> TakeActiveRanges() {
std::vector<std::shared_ptr<RangeT>> ranges;
for (Stream& stream : streams_) {
for (auto& [id, range] : stream.active_ranges) {
ranges.push_back(std::move(range));
}
stream.active_ranges.clear();
}
return ranges;
}

void MoveActiveRanges(StreamIterator from, StreamIterator to) {
to->active_ranges = std::move(from->active_ranges);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <gmock/gmock.h>
#include <memory>
#include <unordered_map>
#include <vector>

namespace google {
namespace cloud {
Expand Down Expand Up @@ -173,6 +174,64 @@ TEST(MultiStreamManagerTest, CancelAllInvokesCancel) {
EXPECT_EQ(s2->cancelled, 1);
}

/// @test Verify `TakeActiveRanges()` returns the active ranges from all
/// streams.
TEST(MultiStreamManagerTest, TakeActiveRangesReturnsRangesOfAllStreams) {
Manager mgr = MultiStreamManagerTest::MakeManager();
auto r1 = std::make_shared<FakeRange>();
auto r2 = std::make_shared<FakeRange>();
auto r3 = std::make_shared<FakeRange>();
mgr.GetFirstStream()->active_ranges.emplace(11, r1);
auto second = mgr.AddStream(std::make_shared<FakeStream>());
second->active_ranges.emplace(22, r2);
second->active_ranges.emplace(33, r3);

std::vector<std::shared_ptr<FakeRange>> const ranges = mgr.TakeActiveRanges();

EXPECT_THAT(ranges, ::testing::UnorderedElementsAre(r1, r2, r3));
}

/// @test Verify `TakeActiveRanges()` detaches active ranges without notifying
/// them and leaves all streams in place.
TEST(MultiStreamManagerTest,
TakeActiveRangesDetachesWithoutNotifyingAndKeepsStreams) {
Manager mgr = MultiStreamManagerTest::MakeManager();
auto r1 = std::make_shared<FakeRange>();
auto r2 = std::make_shared<FakeRange>();
auto first = mgr.GetFirstStream();
first->active_ranges.emplace(11, r1);
auto second = mgr.AddStream(std::make_shared<FakeStream>());
second->active_ranges.emplace(22, r2);

(void)mgr.TakeActiveRanges();

EXPECT_EQ(mgr.Size(), 2U);
EXPECT_THAT(first->active_ranges, ::testing::IsEmpty());
EXPECT_THAT(second->active_ranges, ::testing::IsEmpty());
EXPECT_EQ(r1->finished, 0);
EXPECT_EQ(r2->finished, 0);
EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty());
}

/// @test Verify `TakeActiveRanges()` returns an empty vector when no stream
/// has active ranges.
TEST(MultiStreamManagerTest, TakeActiveRangesReturnsEmptyWithoutRanges) {
Manager mgr = MultiStreamManagerTest::MakeManager();
mgr.AddStream(std::make_shared<FakeStream>());

EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty());
}

/// @test Verify `TakeActiveRanges()` returns an empty vector when no streams
/// remain.
TEST(MultiStreamManagerTest, TakeActiveRangesReturnsEmptyWhenNoStreamsRemain) {
Manager mgr = MultiStreamManagerTest::MakeManager();
mgr.RemoveStreamAndNotifyRanges(mgr.GetFirstStream(), Status{});
ASSERT_TRUE(mgr.Empty());

EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty());
}

TEST(MultiStreamManagerTest, ReuseIdleStreamToFrontMovesElement) {
auto mgr = MultiStreamManagerTest::MakeManager();
// Capture the factory-created stream pointer (initial element)
Expand Down
43 changes: 35 additions & 8 deletions google/cloud/storage/internal/async/object_descriptor_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,16 @@
#include "google/cloud/storage/internal/retry_logging.h"
#include "google/cloud/storage/options.h"
#include "google/cloud/grpc_error_delegate.h"
#include "google/cloud/internal/make_status.h"
#include "google/cloud/internal/opentelemetry.h"
#include "google/rpc/status.pb.h"
#include <algorithm>
#include <chrono>
#include <limits>
#include <memory>
#include <string_view>
#include <utility>
#include <vector>

namespace google {
namespace cloud {
Expand Down Expand Up @@ -69,26 +72,27 @@ std::string_view CacheStatusToString(InitialReadRangesCacheStatus status) {
} // namespace

ObjectDescriptorImpl::ObjectDescriptorImpl(
std::unique_ptr<storage::ResumePolicy> resume_policy,
CompletionQueue cq, std::unique_ptr<storage::ResumePolicy> resume_policy,
OpenStreamFactory make_stream,
google::storage::v2::BidiReadObjectSpec read_object_spec,
std::shared_ptr<OpenStream> stream, Options options,
std::function<bool()> transport_ok)
// An empty clean-resume factory means "use `make_stream` for those
// re-opens too", i.e. every re-open behaves the same way, including
// whether it reports its retries.
: ObjectDescriptorImpl(std::move(resume_policy), std::move(make_stream),
OpenStreamFactory{}, std::move(read_object_spec),
std::move(stream), std::move(options),
std::move(transport_ok)) {}
: ObjectDescriptorImpl(std::move(cq), std::move(resume_policy),
std::move(make_stream), OpenStreamFactory{},
std::move(read_object_spec), std::move(stream),
std::move(options), std::move(transport_ok)) {}

ObjectDescriptorImpl::ObjectDescriptorImpl(
std::unique_ptr<storage::ResumePolicy> resume_policy,
CompletionQueue cq, std::unique_ptr<storage::ResumePolicy> resume_policy,
OpenStreamFactory make_stream, OpenStreamFactory make_clean_resume_stream,
google::storage::v2::BidiReadObjectSpec read_object_spec,
std::shared_ptr<OpenStream> stream, Options options,
std::function<bool()> transport_ok)
: resume_policy_prototype_(std::move(resume_policy)),
: cq_(std::move(cq)),
resume_policy_prototype_(std::move(resume_policy)),
make_stream_(std::move(make_stream)),
make_clean_resume_stream_(std::move(make_clean_resume_stream)),
read_object_spec_(std::move(read_object_spec)),
Expand Down Expand Up @@ -169,8 +173,31 @@ void ObjectDescriptorImpl::Cancel() {
std::unique_lock<std::mutex> lk(mu_);
if (cancelled_) return;
cancelled_ = true;
if (stream_manager_) stream_manager_->CancelAll();
std::vector<std::shared_ptr<ReadRange>> active_ranges;
if (stream_manager_) {
stream_manager_->CancelAll();
active_ranges = stream_manager_->TakeActiveRanges();
}
if (pending_stream_.valid()) pending_stream_.cancel();
lk.unlock();
if (active_ranges.empty()) return;
// Stream callbacks become no-ops once `cancelled_` is set or this object is
// destroyed, so `Cancel()` must complete all detached ranges or readers will
// wait forever.
//
// Schedule via a zero-delay timer (ignoring its status) rather than
// `RunAsync()`: unlike `RunAsync()`, a timer still runs its continuation
// inline when the completion queue is already shut down.
Status status = internal::CancelledError(
"the ObjectDescriptor was destroyed before the read completed",
GCP_ERROR_INFO());
cq_.MakeRelativeTimer(std::chrono::nanoseconds(0))
.then([ranges = std::move(active_ranges),
status = std::move(status)](auto) {
for (std::shared_ptr<ReadRange> const& range : ranges) {
range->OnFinish(status);
}
});
}

std::optional<google::storage::v2::Object> ObjectDescriptorImpl::metadata()
Expand Down
Loading
Loading