proxygen
Core.h
Go to the documentation of this file.
1 /*
2  * Copyright 2014-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <atomic>
20 #include <mutex>
21 #include <stdexcept>
22 #include <utility>
23 #include <vector>
24 
25 #include <folly/Executor.h>
26 #include <folly/Function.h>
27 #include <folly/Optional.h>
28 #include <folly/ScopeGuard.h>
29 #include <folly/Try.h>
30 #include <folly/Utility.h>
31 #include <folly/lang/Assume.h>
32 #include <folly/lang/Exception.h>
34 #include <glog/logging.h>
35 
36 #include <folly/io/async/Request.h>
37 
38 namespace folly {
39 namespace futures {
40 namespace detail {
41 
43 enum class State : uint8_t {
44  Start = 1 << 0,
45  OnlyResult = 1 << 1,
46  OnlyCallback = 1 << 2,
47  Proxy = 1 << 3,
48  Done = 1 << 4,
49  Empty = 1 << 5,
50 };
51 constexpr State operator&(State a, State b) {
52  return State(uint8_t(a) & uint8_t(b));
53 }
54 constexpr State operator|(State a, State b) {
55  return State(uint8_t(a) | uint8_t(b));
56 }
57 constexpr State operator^(State a, State b) {
58  return State(uint8_t(a) ^ uint8_t(b));
59 }
60 constexpr State operator~(State a) {
61  return State(~uint8_t(a));
62 }
63 
65 struct SpinLock : private MicroSpinLock {
67 
68  using MicroSpinLock::lock;
70 };
71 static_assert(sizeof(SpinLock) == 1, "missized");
72 
194 template <typename T>
195 class Core final {
196  static_assert(
198  "void futures are not supported. Use Unit instead.");
199 
200  public:
201  using Result = Try<T>;
203 
205  static Core* make() {
206  return new Core();
207  }
208 
211  static Core* make(Try<T>&& t) {
212  return new Core(std::move(t));
213  }
214 
217  template <typename... Args>
218  static Core<T>* make(in_place_t, Args&&... args) {
219  return new Core<T>(in_place, std::forward<Args>(args)...);
220  }
221 
222  // not copyable
223  Core(Core const&) = delete;
224  Core& operator=(Core const&) = delete;
225 
226  // not movable (see comment in the implementation of Future::then)
227  Core(Core&&) noexcept = delete;
228  Core& operator=(Core&&) = delete;
229 
232  constexpr auto allowed = State::OnlyCallback | State::Done;
233  auto const state = state_.load(std::memory_order_acquire);
234  return State() != (state & allowed);
235  }
236 
243  constexpr auto allowed = State::OnlyResult | State::Done;
244  auto core = this;
245  auto state = core->state_.load(std::memory_order_acquire);
246  while (state == State::Proxy) {
247  core = core->proxy_;
248  state = core->state_.load(std::memory_order_acquire);
249  }
250  return State() != (state & allowed);
251  }
252 
259  return hasResult();
260  }
261 
281  DCHECK(hasResult());
282  auto core = this;
283  while (core->state_.load(std::memory_order_relaxed) == State::Proxy) {
284  core = core->proxy_;
285  }
286  return core->result_;
287  }
288  Try<T> const& getTry() const {
289  DCHECK(hasResult());
290  auto core = this;
291  while (core->state_.load(std::memory_order_relaxed) == State::Proxy) {
292  core = core->proxy_;
293  }
294  return core->result_;
295  }
296 
305  template <typename F>
306  void setCallback(F&& func, std::shared_ptr<folly::RequestContext> context) {
307  DCHECK(!hasCallback());
308 
309  // construct callback_ first; if that fails, context_ will not leak
310  ::new (&callback_) Callback(std::forward<F>(func));
311  ::new (&context_) Context(std::move(context));
312 
313  auto state = state_.load(std::memory_order_acquire);
314 
315  if (state == State::Start) {
316  if (state_.compare_exchange_strong(
317  state, State::OnlyCallback, std::memory_order_release)) {
318  return;
319  }
321  }
322 
323  if (state == State::OnlyResult) {
324  state_.store(State::Done, std::memory_order_relaxed);
325  doCallback();
326  return;
327  }
328 
329  if (state == State::Proxy) {
330  return proxyCallback();
331  }
332 
333  terminate_with<std::logic_error>("setCallback unexpected state");
334  }
335 
342  void setProxy(Core* proxy) {
343  DCHECK(!hasResult());
344 
345  proxy_ = proxy;
346 
347  auto state = state_.load(std::memory_order_acquire);
348  switch (state) {
349  case State::Start:
350  if (state_.compare_exchange_strong(
351  state, State::Proxy, std::memory_order_release)) {
352  break;
353  }
356 
357  case State::OnlyCallback:
358  proxyCallback();
359  break;
360 
361  default:
362  terminate_with<std::logic_error>("setCallback unexpected state");
363  }
364 
365  detachOne();
366  }
367 
376  void setResult(Try<T>&& t) {
377  DCHECK(!hasResult());
378 
379  ::new (&result_) Result(std::move(t));
380 
381  auto state = state_.load(std::memory_order_acquire);
382  while (true) {
383  switch (state) {
384  case State::Start:
385  if (state_.compare_exchange_strong(
386  state, State::OnlyResult, std::memory_order_release)) {
387  return;
388  }
391 
392  case State::OnlyCallback:
393  if (state_.compare_exchange_strong(
394  state, State::Done, std::memory_order_release)) {
395  doCallback();
396  return;
397  }
399 
400  default:
401  terminate_with<std::logic_error>("setResult unexpected state");
402  }
403  }
404  }
405 
410  detachOne();
411  }
412 
417  DCHECK(hasResult());
418  detachOne();
419  }
420 
426  int8_t priority = Executor::MID_PRI) {
427  DCHECK(state_ != State::OnlyCallback);
428  executor_ = std::move(x);
429  priority_ = priority;
430  }
431 
433  setExecutor(getKeepAliveToken(x), priority);
434  }
435 
437  return executor_.get();
438  }
439 
440  int8_t getPriority() const {
441  return priority_;
442  }
443 
453  void raise(exception_wrapper e) {
454  std::lock_guard<SpinLock> lock(interruptLock_);
455  if (!interrupt_ && !hasResult()) {
456  interrupt_ = std::make_unique<exception_wrapper>(std::move(e));
457  if (interruptHandler_) {
458  interruptHandler_(*interrupt_);
459  }
460  }
461  }
462 
463  std::function<void(exception_wrapper const&)> getInterruptHandler() {
464  if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
465  return nullptr;
466  }
467  std::lock_guard<SpinLock> lock(interruptLock_);
468  return interruptHandler_;
469  }
470 
482  template <typename F>
483  void setInterruptHandler(F&& fn) {
484  std::lock_guard<SpinLock> lock(interruptLock_);
485  if (!hasResult()) {
486  if (interrupt_) {
487  fn(as_const(*interrupt_));
488  } else {
489  setInterruptHandlerNoLock(std::forward<F>(fn));
490  }
491  }
492  }
493 
495  std::function<void(exception_wrapper const&)> fn) {
496  interruptHandlerSet_.store(true, std::memory_order_relaxed);
497  interruptHandler_ = std::move(fn);
498  }
499 
500  private:
501  Core() : state_(State::Start), attached_(2) {}
502 
503  explicit Core(Try<T>&& t)
504  : result_(std::move(t)), state_(State::OnlyResult), attached_(1) {}
505 
506  template <typename... Args>
507  explicit Core(in_place_t, Args&&... args) noexcept(
508  std::is_nothrow_constructible<T, Args&&...>::value)
509  : result_(in_place, std::forward<Args>(args)...),
510  state_(State::OnlyResult),
511  attached_(1) {}
512 
513  ~Core() {
514  DCHECK(attached_ == 0);
515  auto state = state_.load(std::memory_order_relaxed);
516  switch (state) {
517  case State::OnlyResult:
519 
520  case State::Done:
521  result_.~Result();
522  break;
523 
524  case State::Proxy:
525  proxy_->detachFuture();
526  break;
527 
528  case State::Empty:
529  break;
530 
531  default:
532  terminate_with<std::logic_error>("~Core unexpected state");
533  }
534  }
535 
536  // Helper class that stores a pointer to the `Core` object and calls
537  // `derefCallback` and `detachOne` in the destructor.
539  public:
540  explicit CoreAndCallbackReference(Core* core) noexcept : core_(core) {}
541 
543  detach();
544  }
545 
548  delete;
549  CoreAndCallbackReference& operator=(CoreAndCallbackReference&&) = delete;
550 
552  : core_(exchange(o.core_, nullptr)) {}
553 
555  return core_;
556  }
557 
558  private:
559  void detach() noexcept {
560  if (core_) {
561  core_->derefCallback();
562  core_->detachOne();
563  }
564  }
565 
566  Core* core_{nullptr};
567  };
568 
569  // May be called at most once.
570  void doCallback() {
571  DCHECK(state_ == State::Done);
572  auto x = exchange(executor_, Executor::KeepAlive<>());
573  int8_t priority = priority_;
574 
575  if (x) {
577  // We need to reset `callback_` after it was executed (which can happen
578  // through the executor or, if `Executor::add` throws, below). The
579  // executor might discard the function without executing it (now or
580  // later), in which case `callback_` also needs to be reset.
581  // The `Core` has to be kept alive throughout that time, too. Hence we
582  // increment `attached_` and `callbackReferences_` by two, and construct
583  // exactly two `CoreAndCallbackReference` objects, which call
584  // `derefCallback` and `detachOne` in their destructor. One will guard
585  // this scope, the other one will guard the lambda passed to the executor.
586  attached_.fetch_add(2, std::memory_order_relaxed);
587  callbackReferences_.fetch_add(2, std::memory_order_relaxed);
588  CoreAndCallbackReference guard_local_scope(this);
589  CoreAndCallbackReference guard_lambda(this);
590  try {
591  auto xPtr = x.get();
592  if (LIKELY(x->getNumPriorities() == 1)) {
593  xPtr->add([core_ref = std::move(guard_lambda),
594  keepAlive = std::move(x)]() mutable {
595  auto cr = std::move(core_ref);
596  Core* const core = cr.getCore();
598  core->callback_(std::move(core->result_));
599  });
600  } else {
601  xPtr->addWithPriority(
602  [core_ref = std::move(guard_lambda),
603  keepAlive = std::move(x)]() mutable {
604  auto cr = std::move(core_ref);
605  Core* const core = cr.getCore();
607  core->callback_(std::move(core->result_));
608  },
609  priority);
610  }
611  } catch (const std::exception& e) {
612  ew = exception_wrapper(std::current_exception(), e);
613  } catch (...) {
614  ew = exception_wrapper(std::current_exception());
615  }
616  if (ew) {
617  RequestContextScopeGuard rctx(context_);
618  result_ = Try<T>(std::move(ew));
619  callback_(std::move(result_));
620  }
621  } else {
622  attached_.fetch_add(1, std::memory_order_relaxed);
623  SCOPE_EXIT {
624  context_.~Context();
625  callback_.~Callback();
626  detachOne();
627  };
628  RequestContextScopeGuard rctx(context_);
629  callback_(std::move(result_));
630  }
631  }
632 
633  void proxyCallback() {
634  state_.store(State::Empty, std::memory_order_relaxed);
635  proxy_->setExecutor(std::move(executor_), priority_);
636  proxy_->setCallback(std::move(callback_), std::move(context_));
637  proxy_->detachFuture();
638  context_.~Context();
639  callback_.~Callback();
640  }
641 
643  auto a = attached_.fetch_sub(1, std::memory_order_acq_rel);
644  assert(a >= 1);
645  if (a == 1) {
646  delete this;
647  }
648  }
649 
651  auto c = callbackReferences_.fetch_sub(1, std::memory_order_acq_rel);
652  assert(c >= 1);
653  if (c == 1) {
654  context_.~Context();
655  callback_.~Callback();
656  }
657  }
658 
659  using Context = std::shared_ptr<RequestContext>;
660 
661  union {
663  };
664  // place result_ next to increase the likelihood that the value will be
665  // contained entirely in one cache line
666  union {
669  };
670  std::atomic<State> state_;
671  std::atomic<unsigned char> attached_;
672  std::atomic<unsigned char> callbackReferences_{0};
673  std::atomic<bool> interruptHandlerSet_{false};
675  int8_t priority_{-1};
677  union {
679  };
680  std::unique_ptr<exception_wrapper> interrupt_{};
681  std::function<void(exception_wrapper const&)> interruptHandler_{nullptr};
682 };
683 
684 } // namespace detail
685 } // namespace futures
686 } // namespace folly
Definition: InvokeTest.cpp:58
SpinLock is and must stay a 1-byte object because of how Core is laid out.
Definition: Core.h:65
std::atomic< State > state_
Definition: Core.h:670
std::atomic< unsigned char > attached_
Definition: Core.h:671
static const int8_t MID_PRI
Definition: Executor.h:49
constexpr State operator~(State a)
Definition: Core.h:60
char b
void detachOne() noexcept
Definition: Core.h:642
int8_t getPriority() const
Definition: Core.h:440
context
Definition: CMakeCache.txt:563
void setProxy(Core *proxy)
Definition: Core.h:342
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define LIKELY(x)
Definition: Likely.h:47
void derefCallback() noexcept
Definition: Core.h:650
STL namespace.
Try< T > const & getTry() const
Definition: Core.h:288
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
folly::std T
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
static Core< T > * make(in_place_t, Args &&...args)
Definition: Core.h:218
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
static Core * make(Try< T > &&t)
Definition: Core.h:211
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
requires E e noexcept(noexcept(s.error(std::move(e))))
in_place_tag(&)(in_place_tag) in_place_t
Definition: Utility.h:229
constexpr State operator&(State a, State b)
Definition: Core.h:51
std::function< void(exception_wrapper const &)> getInterruptHandler()
Definition: Core.h:463
void detachFuture() noexcept
Definition: Core.h:409
constexpr T const & as_const(T &t) noexcept
Definition: Utility.h:96
bool ready() const noexcept
Definition: Core.h:258
void unlock() noexcept
Definition: MicroSpinLock.h:90
constexpr State operator^(State a, State b)
Definition: Core.h:57
State
See Core for details.
Definition: Core.h:43
void detachPromise() noexcept
Definition: Core.h:416
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
void lock() noexcept
Definition: MicroSpinLock.h:80
char a
void setInterruptHandler(F &&fn)
Definition: Core.h:483
Executor::KeepAlive executor_
Definition: Core.h:676
bool hasCallback() const noexcept
May call from any thread.
Definition: Core.h:231
void setExecutor(Executor::KeepAlive<> x, int8_t priority=Executor::MID_PRI)
Definition: Core.h:424
static const char *const value
Definition: Conv.cpp:50
Definition: Try.h:51
Try< T > & getTry()
Definition: Core.h:280
Core(in_place_t, Args &&...args) noexcept(std::is_nothrow_constructible< T, Args &&... >::value)
Definition: Core.h:507
Executor * getExecutor() const
Definition: Core.h:436
Core(Try< T > &&t)
Definition: Core.h:503
T exchange(T &obj, U &&new_value)
Definition: Utility.h:120
void setExecutor(Executor *x, int8_t priority=Executor::MID_PRI)
Definition: Core.h:432
const
Definition: upload.py:398
void setInterruptHandlerNoLock(std::function< void(exception_wrapper const &)> fn)
Definition: Core.h:494
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
void setCallback(F &&func, std::shared_ptr< folly::RequestContext > context)
Definition: Core.h:306
CoreAndCallbackReference(CoreAndCallbackReference &&o) noexcept
Definition: Core.h:551
void setResult(Try< T > &&t)
Definition: Core.h:376
folly::Function< void()> callback_
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
std::shared_ptr< RequestContext > Context
Definition: Core.h:659
FOLLY_ALWAYS_INLINE void assume(bool cond)
Definition: Assume.h:41
char c
bool hasResult() const noexcept
Definition: Core.h:242
#define FOLLY_FALLTHROUGH
Definition: CppAttributes.h:63
constexpr State operator|(State a, State b)
Definition: Core.h:54
state
Definition: http_parser.c:272
static Core * make()
State will be Start.
Definition: Core.h:205