|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include "google/cloud/storage/internal/async/hedged_open_stream.h" |
| 16 | +#include "google/cloud/internal/call_context.h" |
| 17 | +#include "google/cloud/internal/make_status.h" |
| 18 | +#include <algorithm> |
| 19 | +#include <chrono> |
| 20 | +#include <cstddef> |
| 21 | +#include <cstdint> |
| 22 | +#include <memory> |
| 23 | +#include <mutex> |
| 24 | +#include <optional> |
| 25 | +#include <utility> |
| 26 | +#include <vector> |
| 27 | + |
| 28 | +namespace google { |
| 29 | +namespace cloud { |
| 30 | +namespace storage_internal { |
| 31 | +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN |
| 32 | +namespace { |
| 33 | + |
| 34 | +std::chrono::milliseconds constexpr kHedgeRetryMinDelay{10}; |
| 35 | + |
| 36 | +class HedgedOpenOperation |
| 37 | + : public std::enable_shared_from_this<HedgedOpenOperation> { |
| 38 | + public: |
| 39 | + HedgedOpenOperation( |
| 40 | + CompletionQueue cq, OpenStreamFactory factory, |
| 41 | + google::storage::v2::BidiReadObjectRequest initial_request, |
| 42 | + std::shared_ptr<storage::AsyncRetryPolicy> retry_policy, |
| 43 | + HedgedOpenParams params, |
| 44 | + std::shared_ptr<storage::internal::HedgeLimiter> limiter, |
| 45 | + std::shared_ptr<storage::internal::HedgedReadMetrics> metrics, |
| 46 | + google::cloud::internal::ImmutableOptions options) |
| 47 | + : cq_(std::move(cq)), |
| 48 | + factory_(std::move(factory)), |
| 49 | + initial_request_(std::move(initial_request)), |
| 50 | + retry_policy_(std::move(retry_policy)), |
| 51 | + hedge_delay_( |
| 52 | + (std::max)(std::chrono::milliseconds::zero(), params.delay)), |
| 53 | + max_hedges_((std::max)(0, params.max_hedges)), |
| 54 | + limiter_(std::move(limiter)), |
| 55 | + metrics_(std::move(metrics)), |
| 56 | + call_context_(std::move(options)) {} |
| 57 | + |
| 58 | + future<StatusOr<OpenStreamResult>> Start() { |
| 59 | + std::weak_ptr<HedgedOpenOperation> weak = shared_from_this(); |
| 60 | + result_promise_ = promise<StatusOr<OpenStreamResult>>([weak] { |
| 61 | + if (std::shared_ptr<HedgedOpenOperation> self = weak.lock()) { |
| 62 | + google::cloud::internal::ScopedCallContext scope(self->call_context_); |
| 63 | + self->OnCallerCancel(); |
| 64 | + } |
| 65 | + }); |
| 66 | + future<StatusOr<OpenStreamResult>> result_future = |
| 67 | + result_promise_.get_future(); |
| 68 | + |
| 69 | + active_attempts_ = 1; |
| 70 | + attempts_.emplace_back(future<void>{}); |
| 71 | + bool const arm_timer = CanHedge(); |
| 72 | + |
| 73 | + AttachAttempt(0, StartAttempt(0)); |
| 74 | + if (arm_timer) ArmTimer(hedge_delay_); |
| 75 | + return result_future; |
| 76 | + } |
| 77 | + |
| 78 | + private: |
| 79 | + struct HedgeSlot { |
| 80 | + std::shared_ptr<storage::internal::HedgeLimiter> limiter; |
| 81 | + |
| 82 | + HedgeSlot() = default; |
| 83 | + explicit HedgeSlot(std::shared_ptr<storage::internal::HedgeLimiter> l) |
| 84 | + : limiter(std::move(l)) {} |
| 85 | + ~HedgeSlot() { Release(); } |
| 86 | + HedgeSlot(HedgeSlot&&) noexcept = default; |
| 87 | + HedgeSlot& operator=(HedgeSlot&&) = delete; |
| 88 | + HedgeSlot(HedgeSlot const&) = delete; |
| 89 | + HedgeSlot& operator=(HedgeSlot const&) = delete; |
| 90 | + |
| 91 | + void Release() { |
| 92 | + if (limiter) std::exchange(limiter, nullptr)->ReleaseHedgeSlot(); |
| 93 | + } |
| 94 | + }; |
| 95 | + |
| 96 | + struct Outstanding { |
| 97 | + future<void> timer; |
| 98 | + std::vector<std::optional<future<void>>> attempts; |
| 99 | + |
| 100 | + void Cancel() { |
| 101 | + CancelIfValid(timer); |
| 102 | + for (std::optional<future<void>>& pending : attempts) { |
| 103 | + if (pending) CancelIfValid(*pending); |
| 104 | + } |
| 105 | + } |
| 106 | + }; |
| 107 | + |
| 108 | + static void CancelIfValid(future<void>& f) { |
| 109 | + if (f.valid()) f.cancel(); |
| 110 | + } |
| 111 | + |
| 112 | + static Status CancelledOpenError() { |
| 113 | + return google::cloud::internal::CancelledError("Open operation cancelled", |
| 114 | + GCP_ERROR_INFO()); |
| 115 | + } |
| 116 | + |
| 117 | + bool CanHedge() const { |
| 118 | + return hedges_dispatched_ < max_hedges_ && |
| 119 | + (!limiter_ || !limiter_->IsTotalBudgetSpent()); |
| 120 | + } |
| 121 | + |
| 122 | + future<void> FinishAttemptLocked(std::size_t idx) { |
| 123 | + --active_attempts_; |
| 124 | + if (idx < attempts_.size() && attempts_[idx].has_value()) { |
| 125 | + return *std::exchange(attempts_[idx], std::nullopt); |
| 126 | + } |
| 127 | + return future<void>{}; |
| 128 | + } |
| 129 | + |
| 130 | + Outstanding DrainOutstandingLocked() { |
| 131 | + ++timer_generation_; |
| 132 | + return Outstanding{std::move(timer_future_), std::exchange(attempts_, {})}; |
| 133 | + } |
| 134 | + |
| 135 | + void Resolve(Outstanding& outstanding, StatusOr<OpenStreamResult> result) { |
| 136 | + outstanding.Cancel(); |
| 137 | + result_promise_.set_value(std::move(result)); |
| 138 | + } |
| 139 | + |
| 140 | + future<void> StartAttempt(std::size_t idx) { |
| 141 | + HedgeSlot slot = idx == 0 ? HedgeSlot{} : HedgeSlot{limiter_}; |
| 142 | + google::cloud::internal::ScopedCallContext scope(call_context_); |
| 143 | + std::shared_ptr<HedgedOpenOperation> self = shared_from_this(); |
| 144 | + return factory_(initial_request_) |
| 145 | + .then([self = std::move(self), slot = std::move(slot), |
| 146 | + idx](future<StatusOr<OpenStreamResult>> f) mutable { |
| 147 | + slot.Release(); |
| 148 | + self->OnAttemptDone(idx, f.get()); |
| 149 | + }); |
| 150 | + } |
| 151 | + |
| 152 | + void AttachAttempt(std::size_t idx, future<void> attempt) { |
| 153 | + if (!attempt.valid() || attempt.is_ready()) return; |
| 154 | + bool cancel_now = false; |
| 155 | + { |
| 156 | + std::lock_guard<std::mutex> lock(mu_); |
| 157 | + if (resolved_ || caller_cancelled_) { |
| 158 | + cancel_now = true; |
| 159 | + } else if (idx < attempts_.size() && attempts_[idx].has_value()) { |
| 160 | + attempts_[idx] = std::move(attempt); |
| 161 | + } |
| 162 | + } |
| 163 | + if (cancel_now) CancelIfValid(attempt); |
| 164 | + } |
| 165 | + |
| 166 | + void ArmTimer(std::chrono::milliseconds delay) { |
| 167 | + std::uint64_t gen = 0; |
| 168 | + { |
| 169 | + std::lock_guard<std::mutex> lock(mu_); |
| 170 | + if (resolved_ || caller_cancelled_) return; |
| 171 | + gen = ++timer_generation_; |
| 172 | + } |
| 173 | + std::weak_ptr<HedgedOpenOperation> weak = shared_from_this(); |
| 174 | + future<void> timer = cq_.MakeRelativeTimer(delay).then( |
| 175 | + [weak, gen](future<StatusOr<std::chrono::system_clock::time_point>> f) { |
| 176 | + if (std::shared_ptr<HedgedOpenOperation> self = weak.lock()) { |
| 177 | + self->OnTimer(gen, f.get().ok()); |
| 178 | + } |
| 179 | + }); |
| 180 | + if (!timer.valid() || timer.is_ready()) return; |
| 181 | + bool cancel_now = false; |
| 182 | + { |
| 183 | + std::lock_guard<std::mutex> lock(mu_); |
| 184 | + if (resolved_ || caller_cancelled_) { |
| 185 | + cancel_now = true; |
| 186 | + } else if (gen == timer_generation_) { |
| 187 | + timer_future_ = std::move(timer); |
| 188 | + } |
| 189 | + } |
| 190 | + if (cancel_now) CancelIfValid(timer); |
| 191 | + } |
| 192 | + |
| 193 | + void OnTimer(std::uint64_t gen, bool expired) { |
| 194 | + if (!expired) return; |
| 195 | + google::cloud::internal::ScopedCallContext scope(call_context_); |
| 196 | + |
| 197 | + bool dispatch_hedge = false; |
| 198 | + std::size_t idx = 0; |
| 199 | + bool arm_next_timer = false; |
| 200 | + std::chrono::milliseconds next_delay = hedge_delay_; |
| 201 | + { |
| 202 | + std::lock_guard<std::mutex> lock(mu_); |
| 203 | + if (resolved_ || caller_cancelled_ || gen != timer_generation_ || |
| 204 | + hedges_dispatched_ >= max_hedges_) { |
| 205 | + return; |
| 206 | + } |
| 207 | + ++timer_generation_; |
| 208 | + timer_future_ = future<void>{}; |
| 209 | + bool const acquired = !limiter_ || limiter_->TryAcquireHedgeToken(); |
| 210 | + if (acquired) { |
| 211 | + dispatch_hedge = true; |
| 212 | + ++active_attempts_; |
| 213 | + ++hedges_dispatched_; |
| 214 | + idx = attempts_.size(); |
| 215 | + attempts_.emplace_back(future<void>{}); |
| 216 | + } |
| 217 | + if (CanHedge()) { |
| 218 | + arm_next_timer = true; |
| 219 | + next_delay = acquired ? hedge_delay_ |
| 220 | + : (std::max)(hedge_delay_, kHedgeRetryMinDelay); |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + // If a sibling won after unlocking `mu_`, `AttachAttempt` cancels it. |
| 225 | + if (dispatch_hedge) { |
| 226 | + if (metrics_) metrics_->OnHedgeDispatched(); |
| 227 | + AttachAttempt(idx, StartAttempt(idx)); |
| 228 | + } |
| 229 | + if (arm_next_timer) ArmTimer(next_delay); |
| 230 | + } |
| 231 | + |
| 232 | + void OnAttemptDone(std::size_t idx, StatusOr<OpenStreamResult> result) { |
| 233 | + google::cloud::internal::ScopedCallContext scope(call_context_); |
| 234 | + if (!result) return OnAttemptError(idx, std::move(result).status()); |
| 235 | + future<void> self_attempt; |
| 236 | + Outstanding outstanding; |
| 237 | + bool won = false; |
| 238 | + { |
| 239 | + std::lock_guard<std::mutex> lock(mu_); |
| 240 | + if (!resolved_ && !caller_cancelled_) { |
| 241 | + won = true; |
| 242 | + self_attempt = FinishAttemptLocked(idx); |
| 243 | + resolved_ = true; |
| 244 | + outstanding = DrainOutstandingLocked(); |
| 245 | + } |
| 246 | + } |
| 247 | + if (!won) { |
| 248 | + if (result->stream) result->stream->Cancel(); |
| 249 | + OnAttemptError(idx, CancelledOpenError()); |
| 250 | + return; |
| 251 | + } |
| 252 | + if (idx > 0 && metrics_) metrics_->OnHedgeWon(); |
| 253 | + Resolve(outstanding, *std::move(result)); |
| 254 | + } |
| 255 | + |
| 256 | + Status SelectFinalErrorLocked() const { |
| 257 | + // `RetryLoopCancelled` preserves the last transient status code when |
| 258 | + // cancelled during backoff, so map caller-cancelled races to `kCancelled`. |
| 259 | + if (caller_cancelled_) { |
| 260 | + return primary_error_.code() == StatusCode::kCancelled |
| 261 | + ? primary_error_ |
| 262 | + : CancelledOpenError(); |
| 263 | + } |
| 264 | + if (!permanent_error_.ok()) return permanent_error_; |
| 265 | + return primary_error_; |
| 266 | + } |
| 267 | + |
| 268 | + void OnAttemptError(std::size_t idx, Status status) { |
| 269 | + // Unlike mid-stream sync `HedgedObjectReadSource`, every `Open()` attempt |
| 270 | + // sends the identical initial request, so an authoritative permanent |
| 271 | + // rejection (`kNotFound`, `kPermissionDenied`, ...) from *any* attempt |
| 272 | + // aborts stalled siblings immediately. `kCancelled` is excluded because |
| 273 | + // per-stream stall timeouts surface as `kCancelled` on that attempt alone. |
| 274 | + bool const permanent_error = status.code() != StatusCode::kCancelled && |
| 275 | + retry_policy_ && |
| 276 | + retry_policy_->IsPermanentFailure(status); |
| 277 | + future<void> self_attempt; |
| 278 | + Outstanding outstanding; |
| 279 | + Status final_error; |
| 280 | + bool resolve_now = false; |
| 281 | + { |
| 282 | + std::lock_guard<std::mutex> lock(mu_); |
| 283 | + self_attempt = FinishAttemptLocked(idx); |
| 284 | + if (resolved_) return; |
| 285 | + if (permanent_error && permanent_error_.ok()) permanent_error_ = status; |
| 286 | + if (idx == 0) primary_error_ = std::move(status); |
| 287 | + // Each attempt runs its own `AsyncRetryLoop`, so `active_attempts_ == 0` |
| 288 | + // means every launched attempt already exhausted its retry policy; do |
| 289 | + // not wait for un-fired hedge timers to double the retry budget. |
| 290 | + if (active_attempts_ == 0 || |
| 291 | + (!caller_cancelled_ && !permanent_error_.ok())) { |
| 292 | + resolve_now = true; |
| 293 | + resolved_ = true; |
| 294 | + final_error = SelectFinalErrorLocked(); |
| 295 | + outstanding = DrainOutstandingLocked(); |
| 296 | + } |
| 297 | + } |
| 298 | + if (resolve_now) Resolve(outstanding, std::move(final_error)); |
| 299 | + } |
| 300 | + |
| 301 | + void OnCallerCancel() { |
| 302 | + Outstanding outstanding; |
| 303 | + { |
| 304 | + std::lock_guard<std::mutex> lock(mu_); |
| 305 | + if (resolved_ || caller_cancelled_) return; |
| 306 | + caller_cancelled_ = true; |
| 307 | + outstanding = DrainOutstandingLocked(); |
| 308 | + } |
| 309 | + outstanding.Cancel(); |
| 310 | + } |
| 311 | + |
| 312 | + CompletionQueue cq_; |
| 313 | + OpenStreamFactory factory_; |
| 314 | + google::storage::v2::BidiReadObjectRequest initial_request_; |
| 315 | + std::shared_ptr<storage::AsyncRetryPolicy> retry_policy_; |
| 316 | + std::chrono::milliseconds const hedge_delay_; |
| 317 | + int const max_hedges_; |
| 318 | + std::shared_ptr<storage::internal::HedgeLimiter> limiter_; |
| 319 | + std::shared_ptr<storage::internal::HedgedReadMetrics> metrics_; |
| 320 | + google::cloud::internal::CallContext call_context_; |
| 321 | + promise<StatusOr<OpenStreamResult>> result_promise_{null_promise_t{}}; |
| 322 | + |
| 323 | + std::mutex mu_; |
| 324 | + bool resolved_ = false; |
| 325 | + bool caller_cancelled_ = false; |
| 326 | + int active_attempts_ = 0; |
| 327 | + int hedges_dispatched_ = 0; |
| 328 | + std::uint64_t timer_generation_ = 0; |
| 329 | + Status permanent_error_; |
| 330 | + Status primary_error_; |
| 331 | + future<void> timer_future_; |
| 332 | + std::vector<std::optional<future<void>>> attempts_; |
| 333 | +}; |
| 334 | + |
| 335 | +} // namespace |
| 336 | + |
| 337 | +future<StatusOr<OpenStreamResult>> HedgedOpenStream( |
| 338 | + CompletionQueue cq, OpenStreamFactory factory, |
| 339 | + google::storage::v2::BidiReadObjectRequest initial_request, |
| 340 | + std::shared_ptr<storage::AsyncRetryPolicy> retry_policy, |
| 341 | + HedgedOpenParams params, |
| 342 | + std::shared_ptr<storage::internal::HedgeLimiter> limiter, |
| 343 | + std::shared_ptr<storage::internal::HedgedReadMetrics> metrics, |
| 344 | + google::cloud::internal::ImmutableOptions options) { |
| 345 | + return std::make_shared<HedgedOpenOperation>( |
| 346 | + std::move(cq), std::move(factory), std::move(initial_request), |
| 347 | + std::move(retry_policy), params, std::move(limiter), |
| 348 | + std::move(metrics), std::move(options)) |
| 349 | + ->Start(); |
| 350 | +} |
| 351 | + |
| 352 | +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END |
| 353 | +} // namespace storage_internal |
| 354 | +} // namespace cloud |
| 355 | +} // namespace google |
0 commit comments