Debian Codegraph @

src/core/lib/promise/activity.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_ACTIVITY_H
16 #define GRPC_CORE_LIB_PROMISE_ACTIVITY_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <stdint.h>
21
22 #include <algorithm>
23 #include <atomic>
24 #include <memory>
25 #include <string>
26 #include <utility>
27
28 #include "absl/base/thread_annotations.h"
29 #include "absl/status/status.h"
30 #include "absl/types/optional.h"
31 #include "absl/types/variant.h"
32 #include "absl/utility/utility.h"
33
34 #include <grpc/support/log.h>
35
36 #include "src/core/lib/gprpp/construct_destruct.h"
37 #include "src/core/lib/gprpp/no_destruct.h"
38 #include "src/core/lib/gprpp/orphanable.h"
39 #include "src/core/lib/gprpp/sync.h"
40 #include "src/core/lib/promise/context.h"
41 #include "src/core/lib/promise/detail/promise_factory.h"
42 #include "src/core/lib/promise/detail/status.h"
43 #include "src/core/lib/promise/poll.h"
44
45 namespace grpc_core {
46
47 class Activity;
48
49 // A Wakeable object is used by queues to wake activities.
50 class Wakeable {
51 public:
52 // Wake up the underlying activity.
53 // After calling, this Wakeable cannot be used again.
54 virtual void Wakeup() = 0;
55 // Drop this wakeable without waking up the underlying activity.
56 virtual void Drop() = 0;
57
58 // Return the underlying activity debug tag, or "<unknown>" if not available.
59 virtual std::string ActivityDebugTag() const = 0;
60
61 protected:
62 inline ~Wakeable() {}
63 };
64
65 namespace promise_detail {
66 struct Unwakeable final : public Wakeable {
67 void Wakeup() override {}
68 void Drop() override {}
69 std::string ActivityDebugTag() const override;
70 };
71 static Unwakeable* unwakeable() {
72 return NoDestructSingleton<Unwakeable>::Get();
73 }
74 } // namespace promise_detail
75
76 class AtomicWaker;
77
78 // An owning reference to a Wakeable.
79 // This type is non-copyable but movable.
80 class Waker {
81 public:
82 explicit Waker(Wakeable* wakeable) : wakeable_(wakeable) {}
83 Waker() : Waker(promise_detail::unwakeable()) {}
84 ~Waker() { wakeable_->Drop(); }
85 Waker(const Waker&) = delete;
86 Waker& operator=(const Waker&) = delete;
87 Waker(Waker&& other) noexcept : wakeable_(other.Take()) {}
88 Waker& operator=(Waker&& other) noexcept {
89 std::swap(wakeable_, other.wakeable_);
90 return *this;
91 }
92
93 // Wake the underlying activity.
94 void Wakeup() { Take()->Wakeup(); }
95
96 template <typename H>
97 friend H AbslHashValue(H h, const Waker& w) {
98 return H::combine(std::move(h), w.wakeable_);
99 }
100
101 bool operator==(const Waker& other) const noexcept {
102 return wakeable_ == other.wakeable_;
103 }
104
105 std::string ActivityDebugTag() {
106 return wakeable_ == nullptr ? "<unknown>" : wakeable_->ActivityDebugTag();
107 }
108
109 private:
110 friend class AtomicWaker;
111
112 Wakeable* Take() {
113 return std::exchange(wakeable_, promise_detail::unwakeable());
114 }
115
116 Wakeable* wakeable_;
117 };
118
119 // An atomic variant of Waker - this type is non-copyable and non-movable.
120 class AtomicWaker {
121 public:
122 explicit AtomicWaker(Wakeable* wakeable) : wakeable_(wakeable) {}
123 AtomicWaker() : AtomicWaker(promise_detail::unwakeable()) {}
124 explicit AtomicWaker(Waker waker) : AtomicWaker(waker.Take()) {}
125 ~AtomicWaker() { wakeable_.load(std::memory_order_acquire)->Drop(); }
126 AtomicWaker(const AtomicWaker&) = delete;
127 AtomicWaker& operator=(const AtomicWaker&) = delete;
128 AtomicWaker(AtomicWaker&& other) noexcept = delete;
129 AtomicWaker& operator=(AtomicWaker&& other) noexcept = delete;
130
131 // Wake the underlying activity.
132 void Wakeup() { Take()->Wakeup(); }
133
134 // Return true if there is a not-unwakeable wakeable present.
135 bool Armed() const noexcept {
136 return wakeable_.load(std::memory_order_relaxed) !=
137 promise_detail::unwakeable();
138 }
139
140 // Set to some new waker
141 void Set(Waker waker) {
142 wakeable_.exchange(waker.Take(), std::memory_order_acq_rel)->Wakeup();
143 }
144
145 private:
146 Wakeable* Take() {
147 return wakeable_.exchange(promise_detail::unwakeable(),
148 std::memory_order_acq_rel);
149 }
150
151 std::atomic<Wakeable*> wakeable_;
152 };
153
154 // An Activity tracks execution of a single promise.
155 // It executes the promise under a mutex.
156 // When the promise stalls, it registers the containing activity to be woken up
157 // later.
158 // The activity takes a callback, which will be called exactly once with the
159 // result of execution.
160 // Activity execution may be cancelled by simply deleting the activity. In such
161 // a case, if execution had not already finished, the done callback would be
162 // called with absl::CancelledError().
163 class Activity : public Orphanable {
164 public:
165 // Force wakeup from the outside.
166 // This should be rarely needed, and usages should be accompanied with a note
167 // on why it's not possible to wakeup with a Waker object.
168 // Nevertheless, it's sometimes useful for integrations with Activity to force
169 // an Activity to repoll.
170 void ForceWakeup() { MakeOwningWaker().Wakeup(); }
171
172 // Force the current activity to immediately repoll if it doesn't complete.
173 virtual void ForceImmediateRepoll() = 0;
174
175 // Return the current activity.
176 // Additionally:
177 // - assert that there is a current activity (and catch bugs if there's not)
178 // - indicate to thread safety analysis that the current activity is indeed
179 // locked
180 // - back up that assertation with a runtime check in debug builds (it's
181 // prohibitively expensive in non-debug builds)
182 static Activity* current() { return g_current_activity_; }
183
184 // Produce an activity-owning Waker. The produced waker will keep the activity
185 // alive until it's awoken or dropped.
186 virtual Waker MakeOwningWaker() = 0;
187
188 // Produce a non-owning Waker. The waker will own a small heap allocated weak
189 // pointer to this activity. This is more suitable for wakeups that may not be
190 // delivered until long after the activity should be destroyed.
191 virtual Waker MakeNonOwningWaker() = 0;
192
193 // Some descriptive text to add to log messages to identify this activity.
194 virtual std::string DebugTag() const;
195
196 protected:
197 // Check if this activity is the current activity executing on the current
198 // thread.
199 bool is_current() const { return this == g_current_activity_; }
200 // Check if there is an activity executing on the current thread.
201 static bool have_current() { return g_current_activity_ != nullptr; }
202 // Set the current activity at construction, clean it up at destruction.
203 class ScopedActivity {
204 public:
205 explicit ScopedActivity(Activity* activity)
206 : prior_activity_(g_current_activity_) {
207 g_current_activity_ = activity;
208 }
209 ~ScopedActivity() { g_current_activity_ = prior_activity_; }
210 ScopedActivity(const ScopedActivity&) = delete;
211 ScopedActivity& operator=(const ScopedActivity&) = delete;
212
213 private:
214 Activity* const prior_activity_;
215 };
216
217 private:
218 // Set during RunLoop to the Activity that's executing.
219 // Being set implies that mu_ is held.
220 static thread_local Activity* g_current_activity_;
221 };
222
223 // Owned pointer to one Activity.
224 using ActivityPtr = OrphanablePtr<Activity>;
225
226 namespace promise_detail {
227
228 template <typename Context>
229 class ContextHolder {
230 public:
231 using ContextType = Context;
232
233 explicit ContextHolder(Context value) : value_(std::move(value)) {}
234 Context* GetContext() { return &value_; }
235
236 private:
237 Context value_;
238 };
239
240 template <typename Context>
241 class ContextHolder<Context*> {
242 public:
243 using ContextType = Context;
244
245 explicit ContextHolder(Context* value) : value_(value) {}
246 Context* GetContext() { return value_; }
247
248 private:
249 Context* value_;
250 };
251
252 template <typename Context, typename Deleter>
253 class ContextHolder<std::unique_ptr<Context, Deleter>> {
254 public:
255 using ContextType = Context;
256
257 explicit ContextHolder(std::unique_ptr<Context, Deleter> value)
258 : value_(std::move(value)) {}
259 Context* GetContext() { return value_.get(); }
260
261 private:
262 std::unique_ptr<Context, Deleter> value_;
263 };
264
265 template <typename HeldContext>
266 using ContextTypeFromHeld = typename ContextHolder<HeldContext>::ContextType;
267
268 template <typename... Contexts>
269 class ActivityContexts : public ContextHolder<Contexts>... {
270 public:
271 explicit ActivityContexts(Contexts&&... contexts)
272 : ContextHolder<Contexts>(std::forward<Contexts>(contexts))... {}
273
274 class ScopedContext : public Context<ContextTypeFromHeld<Contexts>>... {
275 public:
276 explicit ScopedContext(ActivityContexts* contexts)
277 : Context<ContextTypeFromHeld<Contexts>>(
278 static_cast<ContextHolder<Contexts>*>(contexts)
279 ->GetContext())... {
280 // Silence `unused-but-set-parameter` in case of Contexts = {}
281 (void)contexts;
282 }
283 };
284 };
285
286 // A free standing activity: an activity that owns its own synchronization and
287 // memory.
288 // The alternative is an activity that's somehow tied into another system, for
289 // instance the type seen in promise_based_filter.h as we're transitioning from
290 // the old filter stack to the new system.
291 // FreestandingActivity is-a Wakeable, but needs to increment a refcount before
292 // returning that Wakeable interface. Additionally, we want to keep
293 // FreestandingActivity as small as is possible, since it will be used
294 // everywhere. So we use inheritance to provide the Wakeable interface: this
295 // makes it zero sized, and we make the inheritance private to prevent
296 // accidental casting.
297 class FreestandingActivity : public Activity, private Wakeable {
298 public:
299 Waker MakeOwningWaker() final {
300 Ref();
301 return Waker(this);
302 }
303 Waker MakeNonOwningWaker() final;
304
305 void Orphan() final {
306 Cancel();
307 Unref();
308 }
309
310 void ForceImmediateRepoll() final {
311 mu_.AssertHeld();
312 SetActionDuringRun(ActionDuringRun::kWakeup);
313 }
314
315 protected:
316 // Action received during a run, in priority order.
317 // If more than one action is received during a run, we use max() to resolve
318 // which one to report (so Cancel overrides Wakeup).
319 enum class ActionDuringRun : uint8_t {
320 kNone, // No action occured during run.
321 kWakeup, // A wakeup occured during run.
322 kCancel, // Cancel was called during run.
323 };
324
325 inline ~FreestandingActivity() override {
326 if (handle_) {
327 DropHandle();
328 }
329 }
330
331 // Check if we got an internal wakeup since the last time this function was
332 // called.
333 ActionDuringRun GotActionDuringRun() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
334 return std::exchange(action_during_run_, ActionDuringRun::kNone);
335 }
336
337 // Implementors of Wakeable::Wakeup should call this after the wakeup has
338 // completed.
339 void WakeupComplete() { Unref(); }
340
341 // Set the action that occured during this run.
342 // We use max to combine actions so that cancellation overrides wakeups.
343 void SetActionDuringRun(ActionDuringRun action)
344 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
345 action_during_run_ = std::max(action_during_run_, action);
346 }
347
348 Mutex* mu() ABSL_LOCK_RETURNED(mu_) { return &mu_; }
349
350 std::string ActivityDebugTag() const override { return DebugTag(); }
351
352 private:
353 class Handle;
354
355 // Cancel execution of the underlying promise.
356 virtual void Cancel() = 0;
357
358 void Ref() { refs_.fetch_add(1, std::memory_order_relaxed); }
359 void Unref() {
360 if (1 == refs_.fetch_sub(1, std::memory_order_acq_rel)) {
361 delete this;
362 }
363 }
364
365 // Return a Handle instance with a ref so that it can be stored waiting for
366 // some wakeup.
367 Handle* RefHandle() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
368 // If our refcount is non-zero, ref and return true.
369 // Otherwise, return false.
370 bool RefIfNonzero();
371 // Drop the (proved existing) wait handle.
372 void DropHandle() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
373
374 // All promise execution occurs under this mutex.
375 Mutex mu_;
376
377 // Current refcount.
378 std::atomic<uint32_t> refs_{1};
379 // If wakeup is called during Promise polling, we set this to Wakeup and
380 // repoll. If cancel is called during Promise polling, we set this to Cancel
381 // and cancel at the end of polling.
382 ActionDuringRun action_during_run_ ABSL_GUARDED_BY(mu_) =
383 ActionDuringRun::kNone;
384 // Handle for long waits. Allows a very small weak pointer type object to
385 // queue for wakeups while Activity may be deleted earlier.
386 Handle* handle_ ABSL_GUARDED_BY(mu_) = nullptr;
387 };
388
389 // Implementation details for an Activity of an arbitrary type of promise.
390 // There should exist a static function:
391 // struct WakeupScheduler {
392 // template <typename ActivityType>
393 // void ScheduleWakeup(ActivityType* activity);
394 // };
395 // This function should arrange that activity->RunScheduledWakeup() be invoked
396 // at the earliest opportunity.
397 // It can assume that activity will remain live until RunScheduledWakeup() is
398 // invoked, and that a given activity will not be concurrently scheduled again
399 // until its RunScheduledWakeup() has been invoked.
400 // We use private inheritance here as a way of getting private members for
401 // each of the contexts.
402 // TODO(ctiller): We can probably reconsider the private inheritance here
403 // when we move away from C++11 and have more powerful template features.
404 template <class F, class WakeupScheduler, class OnDone, typename... Contexts>
405 class PromiseActivity final : public FreestandingActivity,
406 private ActivityContexts<Contexts...> {
407 public:
408 using Factory = OncePromiseFactory<void, F>;
409 using ResultType = typename Factory::Promise::Result;
410
411 PromiseActivity(F promise_factory, WakeupScheduler wakeup_scheduler,
412 OnDone on_done, Contexts&&... contexts)
413 : FreestandingActivity(),
414 ActivityContexts<Contexts...>(std::forward<Contexts>(contexts)...),
415 wakeup_scheduler_(std::move(wakeup_scheduler)),
416 on_done_(std::move(on_done)) {
417 // Lock, construct an initial promise from the factory, and step it.
418 // This may hit a waiter, which could expose our this pointer to other
419 // threads, meaning we do need to hold this mutex even though we're still
420 // constructing.
421 mu()->Lock();
422 auto status = Start(Factory(std::move(promise_factory)));
423 mu()->Unlock();
424 // We may complete immediately.
425 if (status.has_value()) {
426 on_done_(std::move(*status));
427 }
428 }
429
430 ~PromiseActivity() override {
431 // We shouldn't destruct without calling Cancel() first, and that must get
432 // us to be done_, so we assume that and have no logic to destruct the
433 // promise here.
434 GPR_ASSERT(done_);
435 }
436
437 void RunScheduledWakeup() {
438 GPR_ASSERT(wakeup_scheduled_.exchange(false, std::memory_order_acq_rel));
439 Step();
440 WakeupComplete();
441 }
442
443 private:
444 using typename ActivityContexts<Contexts...>::ScopedContext;
445
446 void Cancel() final {
447 if (Activity::is_current()) {
448 mu()->AssertHeld();
449 SetActionDuringRun(ActionDuringRun::kCancel);
450 return;
451 }
452 bool was_done;
453 {
454 MutexLock lock(mu());
455 // Check if we were done, and flag done.
456 was_done = done_;
457 if (!done_) {
458 ScopedActivity scoped_activity(this);
459 ScopedContext contexts(this);
460 MarkDone();
461 }
462 }
463 // If we were not done, then call the on_done callback.
464 if (!was_done) {
465 on_done_(absl::CancelledError());
466 }
467 }
468
469 // Wakeup this activity. Arrange to poll the activity again at a convenient
470 // time: this could be inline if it's deemed safe, or it could be by passing
471 // the activity to an external threadpool to run. If the activity is already
472 // running on this thread, a note is taken of such and the activity is
473 // repolled if it doesn't complete.
474 void Wakeup() final {
475 // If there is an active activity, but hey it's us, flag that and we'll loop
476 // in RunLoop (that's calling from above here!).
477 if (Activity::is_current()) {
478 mu()->AssertHeld();
479 SetActionDuringRun(ActionDuringRun::kWakeup);
480 WakeupComplete();
481 return;
482 }
483 if (!wakeup_scheduled_.exchange(true, std::memory_order_acq_rel)) {
484 // Can't safely run, so ask to run later.
485 wakeup_scheduler_.ScheduleWakeup(this);
486 } else {
487 // Already a wakeup scheduled for later, drop ref.
488 WakeupComplete();
489 }
490 }
491
492 // Drop a wakeup
493 void Drop() final { this->WakeupComplete(); }
494
495 // Notification that we're no longer executing - it's ok to destruct the
496 // promise.
497 void MarkDone() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()) {
498 GPR_ASSERT(!absl::exchange(done_, true));
499 ScopedContext contexts(this);
500 Destruct(&promise_holder_.promise);
501 }
502
503 // In response to Wakeup, run the Promise state machine again until it
504 // settles. Then check for completion, and if we have completed, call on_done.
505 void Step() ABSL_LOCKS_EXCLUDED(mu()) {
506 // Poll the promise until things settle out under a lock.
507 mu()->Lock();
508 if (done_) {
509 // We might get some spurious wakeups after finishing.
510 mu()->Unlock();
511 return;
512 }
513 auto status = RunStep();
514 mu()->Unlock();
515 if (status.has_value()) {
516 on_done_(std::move(*status));
517 }
518 }
519
520 // The main body of a step: set the current activity, and any contexts, and
521 // then run the main polling loop. Contained in a function by itself in
522 // order to keep the scoping rules a little easier in Step().
523 absl::optional<ResultType> RunStep() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()) {
524 ScopedActivity scoped_activity(this);
525 ScopedContext contexts(this);
526 return StepLoop();
527 }
528
529 // Similarly to RunStep, but additionally construct the promise from a
530 // promise factory before entering the main loop. Called once from the
531 // constructor.
532 absl::optional<ResultType> Start(Factory promise_factory)
533 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()) {
534 ScopedActivity scoped_activity(this);
535 ScopedContext contexts(this);
536 Construct(&promise_holder_.promise, promise_factory.Make());
537 return StepLoop();
538 }
539
540 // Until there are no wakeups from within and the promise is incomplete:
541 // poll the promise.
542 absl::optional<ResultType> StepLoop() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()) {
543 GPR_ASSERT(is_current());
544 while (true) {
545 // Run the promise.
546 GPR_ASSERT(!done_);
547 auto r = promise_holder_.promise();
548 if (auto* status = absl::get_if<kPollReadyIdx>(&r)) {
549 // If complete, destroy the promise, flag done, and exit this loop.
550 MarkDone();
551 return IntoStatus(status);
552 }
553 // Continue looping til no wakeups occur.
554 switch (GotActionDuringRun()) {
555 case ActionDuringRun::kNone:
556 return {};
557 case ActionDuringRun::kWakeup:
558 break;
559 case ActionDuringRun::kCancel:
560 MarkDone();
561 return absl::CancelledError();
562 }
563 }
564 }
565
566 using Promise = typename Factory::Promise;
567 // Scheduler for wakeups
568 GPR_NO_UNIQUE_ADDRESS WakeupScheduler wakeup_scheduler_;
569 // Callback on completion of the promise.
570 GPR_NO_UNIQUE_ADDRESS OnDone on_done_;
571 // Has execution completed?
572 GPR_NO_UNIQUE_ADDRESS bool done_ ABSL_GUARDED_BY(mu()) = false;
573 // Is there a wakeup scheduled?
574 GPR_NO_UNIQUE_ADDRESS std::atomic<bool> wakeup_scheduled_{false};
575 // We wrap the promise in a union to allow control over the construction
576 // simultaneously with annotating mutex requirements and noting that the
577 // promise contained may not use any memory.
578 union PromiseHolder {
579 PromiseHolder() {}
580 ~PromiseHolder() {}
581 GPR_NO_UNIQUE_ADDRESS Promise promise;
582 };
583 GPR_NO_UNIQUE_ADDRESS PromiseHolder promise_holder_ ABSL_GUARDED_BY(mu());
584 };
585
586 } // namespace promise_detail
587
588 // Given a functor that returns a promise (a promise factory), a callback for
589 // completion, and a callback scheduler, construct an activity.
590 template <typename Factory, typename WakeupScheduler, typename OnDone,
591 typename... Contexts>
592 ActivityPtr MakeActivity(Factory promise_factory,
593 WakeupScheduler wakeup_scheduler, OnDone on_done,
594 Contexts&&... contexts) {
595 return ActivityPtr(
596 new promise_detail::PromiseActivity<Factory, WakeupScheduler, OnDone,
597 Contexts...>(
598 std::move(promise_factory), std::move(wakeup_scheduler),
599 std::move(on_done), std::forward<Contexts>(contexts)...));
600 }
601
602 } // namespace grpc_core
603
604 #endif // GRPC_CORE_LIB_PROMISE_ACTIVITY_H