• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 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_SRC_CORE_LIB_PROMISE_WAIT_FOR_CALLBACK_H
16 #define GRPC_SRC_CORE_LIB_PROMISE_WAIT_FOR_CALLBACK_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <memory>
21 #include <utility>
22 
23 #include "absl/base/thread_annotations.h"
24 #include "src/core/lib/promise/activity.h"
25 #include "src/core/lib/promise/poll.h"
26 #include "src/core/util/sync.h"
27 
28 namespace grpc_core {
29 
30 // Bridge callback interfaces and promise interfaces.
31 // This class helps bridge older callback interfaces with promises:
32 // MakeWaitPromise() returns a promise that will wait until a callback created
33 // by MakeCallback() has been invoked.
34 class WaitForCallback {
35  public:
36   // Creates a promise that blocks until the callback is invoked.
MakeWaitPromise()37   auto MakeWaitPromise() {
38     return [state = state_]() -> Poll<Empty> {
39       MutexLock lock(&state->mutex);
40       if (state->done) return Empty{};
41       state->waker = GetContext<Activity>()->MakeNonOwningWaker();
42       return Pending{};
43     };
44   }
45 
46   // Creates a callback that unblocks the promise.
MakeCallback()47   auto MakeCallback() {
48     return [state = state_]() {
49       ReleasableMutexLock lock(&state->mutex);
50       state->done = true;
51       auto waker = std::move(state->waker);
52       lock.Release();
53       waker.Wakeup();
54     };
55   }
56 
57  private:
58   struct State {
59     Mutex mutex;
60     bool done ABSL_GUARDED_BY(mutex) = false;
61     Waker waker ABSL_GUARDED_BY(mutex);
62   };
63   const std::shared_ptr<State> state_{std::make_shared<State>()};
64 };
65 
66 }  // namespace grpc_core
67 
68 #endif  // GRPC_SRC_CORE_LIB_PROMISE_WAIT_FOR_CALLBACK_H
69