blob: 44a3d9acb8decf7abbd6d7dc8bb7adf9ed3243be [file] [log] [blame]
Henrik Boström27c29362019-10-21 15:21:55 +02001/*
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
11#ifndef RTC_BASE_OPERATIONS_CHAIN_H_
12#define RTC_BASE_OPERATIONS_CHAIN_H_
13
14#include <functional>
15#include <memory>
16#include <queue>
17#include <set>
18#include <type_traits>
19#include <utility>
20
Henrik Boströme574a312020-08-25 10:20:11 +020021#include "absl/types/optional.h"
Henrik Boström27c29362019-10-21 15:21:55 +020022#include "api/scoped_refptr.h"
23#include "rtc_base/checks.h"
24#include "rtc_base/constructor_magic.h"
25#include "rtc_base/ref_count.h"
26#include "rtc_base/ref_counted_object.h"
27#include "rtc_base/synchronization/sequence_checker.h"
28
29namespace rtc {
30
31namespace rtc_operations_chain_internal {
32
33// Abstract base class for operations on the OperationsChain. Run() must be
34// invoked exactly once during the Operation's lifespan.
35class Operation {
36 public:
37 virtual ~Operation() {}
38
39 virtual void Run() = 0;
40};
41
42// FunctorT is the same as in OperationsChain::ChainOperation(). |callback_| is
43// passed on to the |functor_| and is used to inform the OperationsChain that
44// the operation completed. The functor is responsible for invoking the
45// callback when the operation has completed.
46template <typename FunctorT>
47class OperationWithFunctor final : public Operation {
48 public:
49 OperationWithFunctor(FunctorT&& functor, std::function<void()> callback)
50 : functor_(std::forward<FunctorT>(functor)),
51 callback_(std::move(callback)) {}
52
Tomas Gunnarsson36992362020-10-05 21:41:36 +020053 ~OperationWithFunctor() override {
54#if RTC_DCHECK_IS_ON
55 RTC_DCHECK(has_run_);
56#endif // RTC_DCHECK_IS_ON
57 }
Henrik Boström27c29362019-10-21 15:21:55 +020058
59 void Run() override {
Tomas Gunnarsson36992362020-10-05 21:41:36 +020060#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +020061 RTC_DCHECK(!has_run_);
Henrik Boström27c29362019-10-21 15:21:55 +020062 has_run_ = true;
63#endif // RTC_DCHECK_IS_ON
Henrik Boströmee6f4f62019-11-06 12:36:12 +010064 // The functor being executed may invoke the callback synchronously,
65 // marking the operation as complete. As such, |this| OperationWithFunctor
66 // object may get deleted here, including destroying |functor_|. To
67 // protect the functor from self-destruction while running, it is moved to
68 // a local variable.
69 auto functor = std::move(functor_);
70 functor(std::move(callback_));
71 // |this| may now be deleted; don't touch any member variables.
Henrik Boström27c29362019-10-21 15:21:55 +020072 }
73
74 private:
75 typename std::remove_reference<FunctorT>::type functor_;
76 std::function<void()> callback_;
Tomas Gunnarsson36992362020-10-05 21:41:36 +020077#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +020078 bool has_run_ = false;
79#endif // RTC_DCHECK_IS_ON
80};
81
82} // namespace rtc_operations_chain_internal
83
84// An implementation of an operations chain. An operations chain is used to
85// ensure that asynchronous tasks are executed in-order with at most one task
86// running at a time. The notion of an operation chain is defined in
87// https://w3c.github.io/webrtc-pc/#dfn-operations-chain, though unlike this
88// implementation, the referenced definition is coupled with a peer connection.
89//
90// An operation is an asynchronous task. The operation starts when its functor
91// is invoked, and completes when the callback that is passed to functor is
92// invoked by the operation. The operation must start and complete on the same
93// sequence that the operation was "chained" on. As such, the OperationsChain
94// operates in a "single-threaded" fashion, but the asynchronous operations may
95// use any number of threads to achieve "in parallel" behavior.
96//
97// When an operation is chained onto the OperationsChain, it is enqueued to be
98// executed. Operations are executed in FIFO order, where the next operation
99// does not start until the previous operation has completed. OperationsChain
100// guarantees that:
101// - If the operations chain is empty when an operation is chained, the
102// operation starts immediately, inside ChainOperation().
103// - If the operations chain is not empty when an operation is chained, the
104// operation starts upon the previous operation completing, inside the
105// callback.
106//
107// An operation is contractually obligated to invoke the completion callback
108// exactly once. Cancelling a chained operation is not supported by the
109// OperationsChain; an operation that wants to be cancellable is responsible for
110// aborting its own steps. The callback must still be invoked.
111//
112// The OperationsChain is kept-alive through reference counting if there are
113// operations pending. This, together with the contract, guarantees that all
114// operations that are chained get executed.
115class OperationsChain final : public RefCountedObject<RefCountInterface> {
116 public:
117 static scoped_refptr<OperationsChain> Create();
118 ~OperationsChain();
119
Henrik Boströme574a312020-08-25 10:20:11 +0200120 void SetOnChainEmptyCallback(std::function<void()> on_chain_empty_callback);
121 bool IsEmpty() const;
122
Henrik Boström27c29362019-10-21 15:21:55 +0200123 // Chains an operation. Chained operations are executed in FIFO order. The
124 // operation starts when |functor| is executed by the OperationsChain and is
125 // contractually obligated to invoke the callback passed to it when the
126 // operation is complete. Operations must start and complete on the same
127 // sequence that this method was invoked on.
128 //
129 // If the OperationsChain is empty, the operation starts immediately.
130 // Otherwise it starts upon the previous operation completing.
131 //
132 // Requirements of FunctorT:
133 // - FunctorT is movable.
134 // - FunctorT implements "T operator()(std::function<void()> callback)" or
135 // "T operator()(std::function<void()> callback) const" for some T (if T is
136 // not void, the return value is discarded in the invoking sequence). The
137 // operator starts the operation; when the operation is complete, "callback"
138 // MUST be invoked, and it MUST be so on the sequence that ChainOperation()
139 // was invoked on.
140 //
141 // Lambda expressions are valid functors.
142 template <typename FunctorT>
143 void ChainOperation(FunctorT&& functor) {
144 RTC_DCHECK_RUN_ON(&sequence_checker_);
145 chained_operations_.push(
146 std::make_unique<
147 rtc_operations_chain_internal::OperationWithFunctor<FunctorT>>(
148 std::forward<FunctorT>(functor), CreateOperationsChainCallback()));
149 // If this is the only operation in the chain we execute it immediately.
150 // Otherwise the callback will get invoked when the pending operation
151 // completes which will trigger the next operation to execute.
152 if (chained_operations_.size() == 1) {
153 chained_operations_.front()->Run();
154 }
155 }
156
157 private:
158 friend class CallbackHandle;
159
160 // The callback that is passed to an operation's functor (that is used to
161 // inform the OperationsChain that the operation has completed) is of type
162 // std::function<void()>, which is a copyable type. To allow the callback to
163 // be copyable, it is backed up by this reference counted handle. See
164 // CreateOperationsChainCallback().
165 class CallbackHandle final : public RefCountedObject<RefCountInterface> {
166 public:
167 explicit CallbackHandle(scoped_refptr<OperationsChain> operations_chain);
168 ~CallbackHandle();
169
170 void OnOperationComplete();
171
172 private:
173 scoped_refptr<OperationsChain> operations_chain_;
Tomas Gunnarsson36992362020-10-05 21:41:36 +0200174#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +0200175 bool has_run_ = false;
176#endif // RTC_DCHECK_IS_ON
177
178 RTC_DISALLOW_COPY_AND_ASSIGN(CallbackHandle);
179 };
180
181 OperationsChain();
182
183 std::function<void()> CreateOperationsChainCallback();
184 void OnOperationComplete();
185
Mirko Bonadei0abd5182020-10-06 19:39:59 +0000186 webrtc::SequenceChecker sequence_checker_;
Henrik Boström27c29362019-10-21 15:21:55 +0200187 // FIFO-list of operations that are chained. An operation that is executing
188 // remains on this list until it has completed by invoking the callback passed
189 // to it.
190 std::queue<std::unique_ptr<rtc_operations_chain_internal::Operation>>
191 chained_operations_ RTC_GUARDED_BY(sequence_checker_);
Henrik Boströme574a312020-08-25 10:20:11 +0200192 absl::optional<std::function<void()>> on_chain_empty_callback_
193 RTC_GUARDED_BY(sequence_checker_);
Henrik Boström27c29362019-10-21 15:21:55 +0200194
195 RTC_DISALLOW_COPY_AND_ASSIGN(OperationsChain);
196};
197
198} // namespace rtc
199
200#endif // RTC_BASE_OPERATIONS_CHAIN_H_