operations_chain.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /*
  2. * Copyright 2019 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_OPERATIONS_CHAIN_H_
  11. #define RTC_BASE_OPERATIONS_CHAIN_H_
  12. #include <functional>
  13. #include <memory>
  14. #include <queue>
  15. #include <set>
  16. #include <type_traits>
  17. #include <utility>
  18. #include "api/scoped_refptr.h"
  19. #include "rtc_base/checks.h"
  20. #include "rtc_base/constructor_magic.h"
  21. #include "rtc_base/ref_count.h"
  22. #include "rtc_base/ref_counted_object.h"
  23. #include "rtc_base/synchronization/sequence_checker.h"
  24. namespace rtc {
  25. namespace rtc_operations_chain_internal {
  26. // Abstract base class for operations on the OperationsChain. Run() must be
  27. // invoked exactly once during the Operation's lifespan.
  28. class Operation {
  29. public:
  30. virtual ~Operation() {}
  31. virtual void Run() = 0;
  32. };
  33. // FunctorT is the same as in OperationsChain::ChainOperation(). |callback_| is
  34. // passed on to the |functor_| and is used to inform the OperationsChain that
  35. // the operation completed. The functor is responsible for invoking the
  36. // callback when the operation has completed.
  37. template <typename FunctorT>
  38. class OperationWithFunctor final : public Operation {
  39. public:
  40. OperationWithFunctor(FunctorT&& functor, std::function<void()> callback)
  41. : functor_(std::forward<FunctorT>(functor)),
  42. callback_(std::move(callback)) {}
  43. ~OperationWithFunctor() override { RTC_DCHECK(has_run_); }
  44. void Run() override {
  45. RTC_DCHECK(!has_run_);
  46. #ifdef RTC_DCHECK_IS_ON
  47. has_run_ = true;
  48. #endif // RTC_DCHECK_IS_ON
  49. // The functor being executed may invoke the callback synchronously,
  50. // marking the operation as complete. As such, |this| OperationWithFunctor
  51. // object may get deleted here, including destroying |functor_|. To
  52. // protect the functor from self-destruction while running, it is moved to
  53. // a local variable.
  54. auto functor = std::move(functor_);
  55. functor(std::move(callback_));
  56. // |this| may now be deleted; don't touch any member variables.
  57. }
  58. private:
  59. typename std::remove_reference<FunctorT>::type functor_;
  60. std::function<void()> callback_;
  61. #ifdef RTC_DCHECK_IS_ON
  62. bool has_run_ = false;
  63. #endif // RTC_DCHECK_IS_ON
  64. };
  65. } // namespace rtc_operations_chain_internal
  66. // An implementation of an operations chain. An operations chain is used to
  67. // ensure that asynchronous tasks are executed in-order with at most one task
  68. // running at a time. The notion of an operation chain is defined in
  69. // https://w3c.github.io/webrtc-pc/#dfn-operations-chain, though unlike this
  70. // implementation, the referenced definition is coupled with a peer connection.
  71. //
  72. // An operation is an asynchronous task. The operation starts when its functor
  73. // is invoked, and completes when the callback that is passed to functor is
  74. // invoked by the operation. The operation must start and complete on the same
  75. // sequence that the operation was "chained" on. As such, the OperationsChain
  76. // operates in a "single-threaded" fashion, but the asynchronous operations may
  77. // use any number of threads to achieve "in parallel" behavior.
  78. //
  79. // When an operation is chained onto the OperationsChain, it is enqueued to be
  80. // executed. Operations are executed in FIFO order, where the next operation
  81. // does not start until the previous operation has completed. OperationsChain
  82. // guarantees that:
  83. // - If the operations chain is empty when an operation is chained, the
  84. // operation starts immediately, inside ChainOperation().
  85. // - If the operations chain is not empty when an operation is chained, the
  86. // operation starts upon the previous operation completing, inside the
  87. // callback.
  88. //
  89. // An operation is contractually obligated to invoke the completion callback
  90. // exactly once. Cancelling a chained operation is not supported by the
  91. // OperationsChain; an operation that wants to be cancellable is responsible for
  92. // aborting its own steps. The callback must still be invoked.
  93. //
  94. // The OperationsChain is kept-alive through reference counting if there are
  95. // operations pending. This, together with the contract, guarantees that all
  96. // operations that are chained get executed.
  97. class OperationsChain final : public RefCountedObject<RefCountInterface> {
  98. public:
  99. static scoped_refptr<OperationsChain> Create();
  100. ~OperationsChain();
  101. // Chains an operation. Chained operations are executed in FIFO order. The
  102. // operation starts when |functor| is executed by the OperationsChain and is
  103. // contractually obligated to invoke the callback passed to it when the
  104. // operation is complete. Operations must start and complete on the same
  105. // sequence that this method was invoked on.
  106. //
  107. // If the OperationsChain is empty, the operation starts immediately.
  108. // Otherwise it starts upon the previous operation completing.
  109. //
  110. // Requirements of FunctorT:
  111. // - FunctorT is movable.
  112. // - FunctorT implements "T operator()(std::function<void()> callback)" or
  113. // "T operator()(std::function<void()> callback) const" for some T (if T is
  114. // not void, the return value is discarded in the invoking sequence). The
  115. // operator starts the operation; when the operation is complete, "callback"
  116. // MUST be invoked, and it MUST be so on the sequence that ChainOperation()
  117. // was invoked on.
  118. //
  119. // Lambda expressions are valid functors.
  120. template <typename FunctorT>
  121. void ChainOperation(FunctorT&& functor) {
  122. RTC_DCHECK_RUN_ON(&sequence_checker_);
  123. chained_operations_.push(
  124. std::make_unique<
  125. rtc_operations_chain_internal::OperationWithFunctor<FunctorT>>(
  126. std::forward<FunctorT>(functor), CreateOperationsChainCallback()));
  127. // If this is the only operation in the chain we execute it immediately.
  128. // Otherwise the callback will get invoked when the pending operation
  129. // completes which will trigger the next operation to execute.
  130. if (chained_operations_.size() == 1) {
  131. chained_operations_.front()->Run();
  132. }
  133. }
  134. private:
  135. friend class CallbackHandle;
  136. // The callback that is passed to an operation's functor (that is used to
  137. // inform the OperationsChain that the operation has completed) is of type
  138. // std::function<void()>, which is a copyable type. To allow the callback to
  139. // be copyable, it is backed up by this reference counted handle. See
  140. // CreateOperationsChainCallback().
  141. class CallbackHandle final : public RefCountedObject<RefCountInterface> {
  142. public:
  143. explicit CallbackHandle(scoped_refptr<OperationsChain> operations_chain);
  144. ~CallbackHandle();
  145. void OnOperationComplete();
  146. private:
  147. scoped_refptr<OperationsChain> operations_chain_;
  148. #ifdef RTC_DCHECK_IS_ON
  149. bool has_run_ = false;
  150. #endif // RTC_DCHECK_IS_ON
  151. RTC_DISALLOW_COPY_AND_ASSIGN(CallbackHandle);
  152. };
  153. OperationsChain();
  154. std::function<void()> CreateOperationsChainCallback();
  155. void OnOperationComplete();
  156. webrtc::SequenceChecker sequence_checker_;
  157. // FIFO-list of operations that are chained. An operation that is executing
  158. // remains on this list until it has completed by invoking the callback passed
  159. // to it.
  160. std::queue<std::unique_ptr<rtc_operations_chain_internal::Operation>>
  161. chained_operations_ RTC_GUARDED_BY(sequence_checker_);
  162. RTC_DISALLOW_COPY_AND_ASSIGN(OperationsChain);
  163. };
  164. } // namespace rtc
  165. #endif // RTC_BASE_OPERATIONS_CHAIN_H_