• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 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_SLEEP_H
16 #define GRPC_SRC_CORE_LIB_PROMISE_SLEEP_H
17 
18 #include <grpc/event_engine/event_engine.h>
19 #include <grpc/support/port_platform.h>
20 
21 #include <atomic>
22 #include <utility>
23 
24 #include "absl/status/status.h"
25 #include "src/core/lib/promise/activity.h"
26 #include "src/core/lib/promise/poll.h"
27 #include "src/core/util/time.h"
28 
29 namespace grpc_core {
30 
31 // Promise that sleeps until a deadline and then finishes.
32 class Sleep final {
33  public:
34   explicit Sleep(Timestamp deadline);
Sleep(Duration timeout)35   explicit Sleep(Duration timeout) : Sleep(Timestamp::Now() + timeout) {}
36   ~Sleep();
37 
38   Sleep(const Sleep&) = delete;
39   Sleep& operator=(const Sleep&) = delete;
Sleep(Sleep && other)40   Sleep(Sleep&& other) noexcept
41       : deadline_(other.deadline_),
42         closure_(std::exchange(other.closure_, nullptr)) {}
43   Sleep& operator=(Sleep&& other) noexcept {
44     deadline_ = other.deadline_;
45     std::swap(closure_, other.closure_);
46     return *this;
47   };
48 
49   Poll<absl::Status> operator()();
50 
51  private:
52   class ActiveClosure final
53       : public grpc_event_engine::experimental::EventEngine::Closure {
54    public:
55     explicit ActiveClosure(Timestamp deadline);
56 
57     void Run() override;
58     // After calling Cancel, it's no longer safe to access this object.
59     void Cancel();
60 
61     bool HasRun() const;
62 
63    private:
64     bool Unref();
65 
66     Waker waker_;
67     // One ref dropped by Run(), the other by Cancel().
68     std::atomic<int> refs_{2};
69     grpc_event_engine::experimental::EventEngine::TaskHandle timer_handle_;
70   };
71 
72   Timestamp deadline_;
73   ActiveClosure* closure_{nullptr};
74 };
75 
76 }  // namespace grpc_core
77 
78 #endif  // GRPC_SRC_CORE_LIB_PROMISE_SLEEP_H
79