| 269 | } |
| 270 | |
| 271 | bool CoalescedLoad::loadOrFuture(folly::SemiFuture<bool>* wait) { |
| 272 | { |
| 273 | std::lock_guard<std::mutex> l(mutex_); |
| 274 | if (state_ == State::kCancelled || state_ == State::kLoaded) { |
| 275 | return true; |
| 276 | } |
| 277 | if (state_ == State::kLoading) { |
| 278 | if (wait == nullptr) { |
| 279 | return false; |
| 280 | } |
| 281 | if (promise_ == nullptr) { |
| 282 | promise_ = std::make_unique<folly::SharedPromise<bool>>(); |
| 283 | } |
| 284 | *wait = promise_->getSemiFuture(); |
| 285 | return false; |
| 286 | } |
| 287 | |
| 288 | BOLT_CHECK_EQ(State::kPlanned, state_); |
| 289 | state_ = State::kLoading; |
| 290 | } |
| 291 | // Outside of 'mutex_'. |
| 292 | try { |
| 293 | const auto pins = loadData(!wait); |
| 294 | for (const auto& pin : pins) { |
| 295 | auto* entry = pin.checkedEntry(); |
| 296 | BOLT_CHECK(entry->key().fileNum.hasValue()); |
| 297 | BOLT_CHECK(entry->isExclusive()); |
| 298 | entry->setExclusiveToShared(entry->getCacheable()); |
| 299 | } |
| 300 | setEndState(State::kLoading, State::kLoaded, State::kCancelled); |
| 301 | } catch (std::exception& e) { |
| 302 | // preload can fail in async thread, then retry in sync load |
| 303 | if (isAsyncPreloadThread()) { |
| 304 | LOG(WARNING) << "thread " << folly::getCurrentThreadName().value() |
| 305 | << " CoalescedLoad " << (uint64_t)this << " state " |
| 306 | << (state_ == State::kLoading ? "kLoading" |
| 307 | : (state_ == State::kCancelled) ? "kCancelled" |
| 308 | : "unExpected") |
| 309 | << " preload failed: " << e.what(); |
| 310 | setEndState(State::kLoading, State::kPlanned, State::kCancelled); |
| 311 | return false; |
| 312 | } |
| 313 | try { |
| 314 | setEndState(State::kCancelled); |
| 315 | } catch (std::exception&) { |
| 316 | // May not throw from inside catch. |
| 317 | } |
| 318 | LOG(ERROR) << "CoalescedLoad " << (uint64_t)this << " failed: " << e.what(); |
| 319 | throw; |
| 320 | } |
| 321 | return true; |
| 322 | } |
| 323 | |
| 324 | void CoalescedLoad::setEndState(State endState) { |
| 325 | std::lock_guard<std::mutex> l(mutex_); |