blob: 0e8c0681bae1e3c164a8dc4dc63a7e02010ac262 [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"
Niels Möller95129102022-01-13 11:00:05 +010022#include "api/ref_counted_base.h"
Henrik Boström27c29362019-10-21 15:21:55 +020023#include "api/scoped_refptr.h"
Artem Titovd15a5752021-02-10 14:31:24 +010024#include "api/sequence_checker.h"
Henrik Boström27c29362019-10-21 15:21:55 +020025#include "rtc_base/checks.h"
Henrik Boström27c29362019-10-21 15:21:55 +020026#include "rtc_base/ref_count.h"
27#include "rtc_base/ref_counted_object.h"
Mirko Bonadei20e4c802020-11-23 11:07:42 +010028#include "rtc_base/system/no_unique_address.h"
Henrik Boström27c29362019-10-21 15:21:55 +020029
30namespace rtc {
31
32namespace rtc_operations_chain_internal {
33
34// Abstract base class for operations on the OperationsChain. Run() must be
35// invoked exactly once during the Operation's lifespan.
36class Operation {
37 public:
38 virtual ~Operation() {}
39
40 virtual void Run() = 0;
41};
42
Artem Titov96e3b992021-07-26 16:03:14 +020043// FunctorT is the same as in OperationsChain::ChainOperation(). `callback_` is
44// passed on to the `functor_` and is used to inform the OperationsChain that
Henrik Boström27c29362019-10-21 15:21:55 +020045// the operation completed. The functor is responsible for invoking the
46// callback when the operation has completed.
47template <typename FunctorT>
48class OperationWithFunctor final : public Operation {
49 public:
50 OperationWithFunctor(FunctorT&& functor, std::function<void()> callback)
51 : functor_(std::forward<FunctorT>(functor)),
52 callback_(std::move(callback)) {}
53
Tomas Gunnarsson36992362020-10-05 21:41:36 +020054 ~OperationWithFunctor() override {
55#if RTC_DCHECK_IS_ON
56 RTC_DCHECK(has_run_);
57#endif // RTC_DCHECK_IS_ON
58 }
Henrik Boström27c29362019-10-21 15:21:55 +020059
60 void Run() override {
Tomas Gunnarsson36992362020-10-05 21:41:36 +020061#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +020062 RTC_DCHECK(!has_run_);
Henrik Boström27c29362019-10-21 15:21:55 +020063 has_run_ = true;
64#endif // RTC_DCHECK_IS_ON
Henrik Boströmee6f4f62019-11-06 12:36:12 +010065 // The functor being executed may invoke the callback synchronously,
Artem Titov96e3b992021-07-26 16:03:14 +020066 // marking the operation as complete. As such, `this` OperationWithFunctor
67 // object may get deleted here, including destroying `functor_`. To
Henrik Boströmee6f4f62019-11-06 12:36:12 +010068 // protect the functor from self-destruction while running, it is moved to
69 // a local variable.
70 auto functor = std::move(functor_);
71 functor(std::move(callback_));
Artem Titov96e3b992021-07-26 16:03:14 +020072 // `this` may now be deleted; don't touch any member variables.
Henrik Boström27c29362019-10-21 15:21:55 +020073 }
74
75 private:
76 typename std::remove_reference<FunctorT>::type functor_;
77 std::function<void()> callback_;
Tomas Gunnarsson36992362020-10-05 21:41:36 +020078#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +020079 bool has_run_ = false;
80#endif // RTC_DCHECK_IS_ON
81};
82
83} // namespace rtc_operations_chain_internal
84
85// An implementation of an operations chain. An operations chain is used to
86// ensure that asynchronous tasks are executed in-order with at most one task
87// running at a time. The notion of an operation chain is defined in
88// https://w3c.github.io/webrtc-pc/#dfn-operations-chain, though unlike this
89// implementation, the referenced definition is coupled with a peer connection.
90//
91// An operation is an asynchronous task. The operation starts when its functor
92// is invoked, and completes when the callback that is passed to functor is
93// invoked by the operation. The operation must start and complete on the same
94// sequence that the operation was "chained" on. As such, the OperationsChain
95// operates in a "single-threaded" fashion, but the asynchronous operations may
96// use any number of threads to achieve "in parallel" behavior.
97//
98// When an operation is chained onto the OperationsChain, it is enqueued to be
99// executed. Operations are executed in FIFO order, where the next operation
100// does not start until the previous operation has completed. OperationsChain
101// guarantees that:
102// - If the operations chain is empty when an operation is chained, the
103// operation starts immediately, inside ChainOperation().
104// - If the operations chain is not empty when an operation is chained, the
105// operation starts upon the previous operation completing, inside the
106// callback.
107//
108// An operation is contractually obligated to invoke the completion callback
109// exactly once. Cancelling a chained operation is not supported by the
110// OperationsChain; an operation that wants to be cancellable is responsible for
111// aborting its own steps. The callback must still be invoked.
112//
113// The OperationsChain is kept-alive through reference counting if there are
114// operations pending. This, together with the contract, guarantees that all
115// operations that are chained get executed.
Niels Möller95129102022-01-13 11:00:05 +0100116class OperationsChain final : public RefCountedNonVirtual<OperationsChain> {
Henrik Boström27c29362019-10-21 15:21:55 +0200117 public:
118 static scoped_refptr<OperationsChain> Create();
119 ~OperationsChain();
120
Byoungchan Lee14af7622022-01-12 05:24:58 +0900121 OperationsChain(const OperationsChain&) = delete;
122 OperationsChain& operator=(const OperationsChain&) = delete;
123
Henrik Boströme574a312020-08-25 10:20:11 +0200124 void SetOnChainEmptyCallback(std::function<void()> on_chain_empty_callback);
125 bool IsEmpty() const;
126
Henrik Boström27c29362019-10-21 15:21:55 +0200127 // Chains an operation. Chained operations are executed in FIFO order. The
Artem Titov96e3b992021-07-26 16:03:14 +0200128 // operation starts when `functor` is executed by the OperationsChain and is
Henrik Boström27c29362019-10-21 15:21:55 +0200129 // contractually obligated to invoke the callback passed to it when the
130 // operation is complete. Operations must start and complete on the same
131 // sequence that this method was invoked on.
132 //
133 // If the OperationsChain is empty, the operation starts immediately.
134 // Otherwise it starts upon the previous operation completing.
135 //
136 // Requirements of FunctorT:
137 // - FunctorT is movable.
138 // - FunctorT implements "T operator()(std::function<void()> callback)" or
139 // "T operator()(std::function<void()> callback) const" for some T (if T is
140 // not void, the return value is discarded in the invoking sequence). The
141 // operator starts the operation; when the operation is complete, "callback"
142 // MUST be invoked, and it MUST be so on the sequence that ChainOperation()
143 // was invoked on.
144 //
145 // Lambda expressions are valid functors.
146 template <typename FunctorT>
147 void ChainOperation(FunctorT&& functor) {
148 RTC_DCHECK_RUN_ON(&sequence_checker_);
149 chained_operations_.push(
150 std::make_unique<
151 rtc_operations_chain_internal::OperationWithFunctor<FunctorT>>(
152 std::forward<FunctorT>(functor), CreateOperationsChainCallback()));
153 // If this is the only operation in the chain we execute it immediately.
154 // Otherwise the callback will get invoked when the pending operation
155 // completes which will trigger the next operation to execute.
156 if (chained_operations_.size() == 1) {
157 chained_operations_.front()->Run();
158 }
159 }
160
161 private:
162 friend class CallbackHandle;
163
164 // The callback that is passed to an operation's functor (that is used to
165 // inform the OperationsChain that the operation has completed) is of type
166 // std::function<void()>, which is a copyable type. To allow the callback to
167 // be copyable, it is backed up by this reference counted handle. See
168 // CreateOperationsChainCallback().
Niels Möller95129102022-01-13 11:00:05 +0100169 class CallbackHandle final : public RefCountedNonVirtual<CallbackHandle> {
Henrik Boström27c29362019-10-21 15:21:55 +0200170 public:
171 explicit CallbackHandle(scoped_refptr<OperationsChain> operations_chain);
172 ~CallbackHandle();
173
Byoungchan Lee14af7622022-01-12 05:24:58 +0900174 CallbackHandle(const CallbackHandle&) = delete;
175 CallbackHandle& operator=(const CallbackHandle&) = delete;
176
Henrik Boström27c29362019-10-21 15:21:55 +0200177 void OnOperationComplete();
178
179 private:
180 scoped_refptr<OperationsChain> operations_chain_;
Tomas Gunnarsson36992362020-10-05 21:41:36 +0200181#if RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +0200182 bool has_run_ = false;
183#endif // RTC_DCHECK_IS_ON
Henrik Boström27c29362019-10-21 15:21:55 +0200184 };
185
186 OperationsChain();
187
188 std::function<void()> CreateOperationsChainCallback();
189 void OnOperationComplete();
190
Mirko Bonadei20e4c802020-11-23 11:07:42 +0100191 RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker sequence_checker_;
Henrik Boström27c29362019-10-21 15:21:55 +0200192 // FIFO-list of operations that are chained. An operation that is executing
193 // remains on this list until it has completed by invoking the callback passed
194 // to it.
195 std::queue<std::unique_ptr<rtc_operations_chain_internal::Operation>>
196 chained_operations_ RTC_GUARDED_BY(sequence_checker_);
Henrik Boströme574a312020-08-25 10:20:11 +0200197 absl::optional<std::function<void()>> on_chain_empty_callback_
198 RTC_GUARDED_BY(sequence_checker_);
Henrik Boström27c29362019-10-21 15:21:55 +0200199};
200
201} // namespace rtc
202
203#endif // RTC_BASE_OPERATIONS_CHAIN_H_