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_SRC_CORE_LIB_PROMISE_EVENT_ENGINE_WAKEUP_SCHEDULER_H
16 #define GRPC_SRC_CORE_LIB_PROMISE_EVENT_ENGINE_WAKEUP_SCHEDULER_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <memory>
21 #include <utility>
22 
23 #include <grpc/event_engine/event_engine.h>
24 
25 #include "src/core/lib/iomgr/exec_ctx.h"
26 
27 namespace grpc_core {
28 
29 // A callback scheduler for activities that works by scheduling callbacks on the
30 // exec ctx.
31 class EventEngineWakeupScheduler {
32  public:
EventEngineWakeupScheduler(std::shared_ptr<grpc_event_engine::experimental::EventEngine> event_engine)33   explicit EventEngineWakeupScheduler(
34       std::shared_ptr<grpc_event_engine::experimental::EventEngine>
35           event_engine)
36       : event_engine_(std::move(event_engine)) {}
37 
38   template <typename ActivityType>
39   class BoundScheduler
40       : public grpc_event_engine::experimental::EventEngine::Closure {
41    protected:
BoundScheduler(EventEngineWakeupScheduler scheduler)42     explicit BoundScheduler(EventEngineWakeupScheduler scheduler)
43         : event_engine_(std::move(scheduler.event_engine_)) {}
44     BoundScheduler(const BoundScheduler&) = delete;
45     BoundScheduler& operator=(const BoundScheduler&) = delete;
ScheduleWakeup()46     void ScheduleWakeup() { event_engine_->Run(this); }
Run()47     void Run() final {
48       ApplicationCallbackExecCtx app_exec_ctx;
49       ExecCtx exec_ctx;
50       static_cast<ActivityType*>(this)->RunScheduledWakeup();
51     }
52 
53    private:
54     std::shared_ptr<grpc_event_engine::experimental::EventEngine> event_engine_;
55   };
56 
57  private:
58   std::shared_ptr<grpc_event_engine::experimental::EventEngine> event_engine_;
59 };
60 
61 }  // namespace grpc_core
62 
63 #endif  // GRPC_SRC_CORE_LIB_PROMISE_EVENT_ENGINE_WAKEUP_SCHEDULER_H
64