Debian Codegraph @

src/core/lib/promise/observable.h

raw
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_PROMISE_OBSERVABLE_H
16 #define GRPC_CORE_LIB_PROMISE_OBSERVABLE_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <stdint.h>
21
22 #include <limits>
23 #include <memory>
24 #include <type_traits>
25 #include <utility>
26
27 #include "absl/base/thread_annotations.h"
28 #include "absl/types/optional.h"
29 #include "absl/types/variant.h"
30
31 #include "src/core/lib/gprpp/sync.h"
32 #include "src/core/lib/promise/activity.h"
33 #include "src/core/lib/promise/detail/promise_like.h"
34 #include "src/core/lib/promise/poll.h"
35 #include "src/core/lib/promise/wait_set.h"
36
37 namespace grpc_core {
38
39 namespace promise_detail {
40
41 using ObservableVersion = uint64_t;
42 static constexpr ObservableVersion kTombstoneVersion =
43 std::numeric_limits<ObservableVersion>::max();
44
45 } // namespace promise_detail
46
47 class WatchCommitter {
48 public:
49 void Commit() { version_seen_ = promise_detail::kTombstoneVersion; }
50
51 protected:
52 promise_detail::ObservableVersion version_seen_ = 0;
53 };
54
55 namespace promise_detail {
56
57 // Shared state between Observable and Observer.
58 template <typename T>
59 class ObservableState {
60 public:
61 explicit ObservableState(absl::optional<T> value)
62 : value_(std::move(value)) {}
63
64 // Publish that we're closed.
65 void Close() {
66 mu_.Lock();
67 version_ = kTombstoneVersion;
68 value_.reset();
69 auto wakeup = waiters_.TakeWakeupSet();
70 mu_.Unlock();
71 wakeup.Wakeup();
72 }
73
74 // Synchronously publish a new value, and wake any waiters.
75 void Push(T value) {
76 mu_.Lock();
77 version_++;
78 value_ = std::move(value);
79 auto wakeup = waiters_.TakeWakeupSet();
80 mu_.Unlock();
81 wakeup.Wakeup();
82 }
83
84 Poll<absl::optional<T>> PollGet(ObservableVersion* version_seen) {
85 MutexLock lock(&mu_);
86 if (!Started()) return Pending();
87 *version_seen = version_;
88 return value_;
89 }
90
91 Poll<absl::optional<T>> PollNext(ObservableVersion* version_seen) {
92 MutexLock lock(&mu_);
93 if (!NextValueReady(version_seen)) return Pending();
94 return value_;
95 }
96
97 Poll<absl::optional<T>> PollWatch(ObservableVersion* version_seen) {
98 if (*version_seen == kTombstoneVersion) return Pending();
99
100 MutexLock lock(&mu_);
101 if (!NextValueReady(version_seen)) return Pending();
102 // Watch needs to be woken up if the value changes even if it's ready now.
103 waiters_.AddPending(Activity::current()->MakeNonOwningWaker());
104 return value_;
105 }
106
107 private:
108 // Returns true if an initial value is set.
109 // If one is not set, add ourselves as pending to waiters_, and return false.
110 bool Started() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
111 if (!value_.has_value()) {
112 if (version_ != kTombstoneVersion) {
113 // We allow initial no-value, which does not indicate closure.
114 waiters_.AddPending(Activity::current()->MakeNonOwningWaker());
115 return false;
116 }
117 }
118 return true;
119 }
120
121 // If no value is ready, add ourselves as pending to waiters_ and return
122 // false.
123 // If the next value is ready, update the last version seen and return true.
124 bool NextValueReady(ObservableVersion* version_seen)
125 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
126 if (!Started()) return false;
127 if (version_ == *version_seen) {
128 waiters_.AddPending(Activity::current()->MakeNonOwningWaker());
129 return false;
130 }
131 *version_seen = version_;
132 return true;
133 }
134
135 Mutex mu_;
136 WaitSet waiters_ ABSL_GUARDED_BY(mu_);
137 ObservableVersion version_ ABSL_GUARDED_BY(mu_) = 1;
138 absl::optional<T> value_ ABSL_GUARDED_BY(mu_);
139 };
140
141 // Promise implementation for Observer::Get.
142 template <typename T>
143 class ObservableGet {
144 public:
145 ObservableGet(ObservableVersion* version_seen, ObservableState<T>* state)
146 : version_seen_(version_seen), state_(state) {}
147
148 Poll<absl::optional<T>> operator()() {
149 return state_->PollGet(version_seen_);
150 }
151
152 private:
153 ObservableVersion* version_seen_;
154 ObservableState<T>* state_;
155 };
156
157 // Promise implementation for Observer::Next.
158 template <typename T>
159 class ObservableNext {
160 public:
161 ObservableNext(ObservableVersion* version_seen, ObservableState<T>* state)
162 : version_seen_(version_seen), state_(state) {}
163
164 Poll<absl::optional<T>> operator()() {
165 return state_->PollNext(version_seen_);
166 }
167
168 private:
169 ObservableVersion* version_seen_;
170 ObservableState<T>* state_;
171 };
172
173 template <typename T, typename F>
174 class ObservableWatch final : private WatchCommitter {
175 private:
176 using Promise = PromiseLike<decltype(std::declval<F>()(
177 std::declval<T>(), std::declval<WatchCommitter*>()))>;
178 using Result = typename Promise::Result;
179
180 public:
181 explicit ObservableWatch(F factory, std::shared_ptr<ObservableState<T>> state)
182 : state_(std::move(state)), factory_(std::move(factory)) {}
183 ObservableWatch(const ObservableWatch&) = delete;
184 ObservableWatch& operator=(const ObservableWatch&) = delete;
185 ObservableWatch(ObservableWatch&& other) noexcept
186 : state_(std::move(other.state_)),
187 promise_(std::move(other.promise_)),
188 factory_(std::move(other.factory_)) {}
189 ObservableWatch& operator=(ObservableWatch&&) noexcept = default;
190
191 Poll<Result> operator()() {
192 auto r = state_->PollWatch(&version_seen_);
193 if (auto* p = absl::get_if<kPollReadyIdx>(&r)) {
194 if (p->has_value()) {
195 promise_ = Promise(factory_(std::move(**p), this));
196 } else {
197 promise_ = {};
198 }
199 }
200 if (promise_.has_value()) {
201 return (*promise_)();
202 } else {
203 return Pending();
204 }
205 }
206
207 private:
208 std::shared_ptr<ObservableState<T>> state_;
209 absl::optional<Promise> promise_;
210 F factory_;
211 };
212
213 } // namespace promise_detail
214
215 template <typename T>
216 class Observable;
217
218 // Observer watches an Observable for updates.
219 // It can see either the latest value or wait for a new value, but is not
220 // guaranteed to see every value pushed to the Observable.
221 template <typename T>
222 class Observer {
223 public:
224 Observer(const Observer&) = delete;
225 Observer& operator=(const Observer&) = delete;
226 Observer(Observer&& other) noexcept
227 : version_seen_(other.version_seen_), state_(std::move(other.state_)) {}
228 Observer& operator=(Observer&& other) noexcept {
229 version_seen_ = other.version_seen_;
230 state_ = std::move(other.state_);
231 return *this;
232 }
233
234 // Return a promise that will produce an optional<T>.
235 // If the Observable is still present, this will be a value T, but if the
236 // Observable has been closed, this will be nullopt. Borrows data from the
237 // Observer, so this value must stay valid until the promise is resolved. Only
238 // one Next, Get call is allowed to be outstanding at a time.
239 promise_detail::ObservableGet<T> Get() {
240 return promise_detail::ObservableGet<T>{&version_seen_, &*state_};
241 }
242
243 // Return a promise that will produce the next unseen value as an optional<T>.
244 // If the Observable is still present, this will be a value T, but if the
245 // Observable has been closed, this will be nullopt. Borrows data from the
246 // Observer, so this value must stay valid until the promise is resolved. Only
247 // one Next, Get call is allowed to be outstanding at a time.
248 promise_detail::ObservableNext<T> Next() {
249 return promise_detail::ObservableNext<T>{&version_seen_, &*state_};
250 }
251
252 private:
253 using State = promise_detail::ObservableState<T>;
254 friend class Observable<T>;
255 explicit Observer(std::shared_ptr<State> state) : state_(state) {}
256 promise_detail::ObservableVersion version_seen_ = 0;
257 std::shared_ptr<State> state_;
258 };
259
260 // Observable models a single writer multiple reader broadcast channel.
261 // Readers can observe the latest value, or await a new latest value, but they
262 // are not guaranteed to observe every value.
263 template <typename T>
264 class Observable {
265 public:
266 Observable() : state_(std::make_shared<State>(absl::nullopt)) {}
267 explicit Observable(T value)
268 : state_(std::make_shared<State>(std::move(value))) {}
269 ~Observable() { state_->Close(); }
270 Observable(const Observable&) = delete;
271 Observable& operator=(const Observable&) = delete;
272
273 // Push a new value into the observable.
274 void Push(T value) { state_->Push(std::move(value)); }
275
276 // Create a new Observer - which can pull the current state from this
277 // Observable.
278 Observer<T> MakeObserver() { return Observer<T>(state_); }
279
280 // Create a new Watch - a promise that pushes state into the passed in promise
281 // factory. The promise factory takes two parameters - the current value and a
282 // commit token. If the commit token is used (the Commit function on it is
283 // called), then no further Watch updates are provided.
284 template <typename F>
285 promise_detail::ObservableWatch<T, F> Watch(F f) {
286 return promise_detail::ObservableWatch<T, F>(std::move(f), state_);
287 }
288
289 private:
290 using State = promise_detail::ObservableState<T>;
291 std::shared_ptr<State> state_;
292 };
293
294 } // namespace grpc_core
295
296 #endif // GRPC_CORE_LIB_PROMISE_OBSERVABLE_H