| 1 | /* |
| 2 | * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | #ifndef NET_DCSCTP_TIMER_TIMER_H_ |
| 11 | #define NET_DCSCTP_TIMER_TIMER_H_ |
| 12 | |
| 13 | #include <stdint.h> |
| 14 | |
| 15 | #include <algorithm> |
| 16 | #include <functional> |
| 17 | #include <map> |
| 18 | #include <memory> |
| 19 | #include <string> |
| 20 | #include <utility> |
| 21 | |
| 22 | #include "absl/strings/string_view.h" |
| 23 | #include "absl/types/optional.h" |
| 24 | #include "api/task_queue/task_queue_base.h" |
| 25 | #include "api/units/time_delta.h" |
| 26 | #include "net/dcsctp/public/timeout.h" |
| 27 | #include "rtc_base/strong_alias.h" |
| 28 | |
| 29 | namespace dcsctp { |
| 30 | |
| 31 | using TimerID = webrtc::StrongAlias<class TimerIDTag, uint32_t>; |
| 32 | using TimerGeneration = webrtc::StrongAlias<class TimerGenerationTag, uint32_t>; |
| 33 | |
| 34 | enum class TimerBackoffAlgorithm { |
| 35 | // The base duration will be used for any restart. |
| 36 | kFixed, |
| 37 | // An exponential backoff is used for restarts, with a 2x multiplier, meaning |
| 38 | // that every restart will use a duration that is twice as long as the |
| 39 | // previous. |
| 40 | kExponential, |
| 41 | }; |
| 42 | |
| 43 | struct TimerOptions { |
| 44 | explicit TimerOptions(webrtc::TimeDelta duration) |
| 45 | : TimerOptions(duration, TimerBackoffAlgorithm::kExponential) {} |
| 46 | TimerOptions(webrtc::TimeDelta duration, |
| 47 | TimerBackoffAlgorithm backoff_algorithm) |
| 48 | : TimerOptions(duration, backoff_algorithm, absl::nullopt) {} |
| 49 | TimerOptions(webrtc::TimeDelta duration, |
| 50 | TimerBackoffAlgorithm backoff_algorithm, |
| 51 | absl::optional<int> max_restarts) |
| 52 | : TimerOptions(duration, |
| 53 | backoff_algorithm, |
| 54 | max_restarts, |
| 55 | webrtc::TimeDelta::PlusInfinity()) {} |
| 56 | TimerOptions(webrtc::TimeDelta duration, |
| 57 | TimerBackoffAlgorithm backoff_algorithm, |
| 58 | absl::optional<int> max_restarts, |
| 59 | webrtc::TimeDelta max_backoff_duration) |
| 60 | : TimerOptions(duration, |
| 61 | backoff_algorithm, |
| 62 | max_restarts, |
| 63 | max_backoff_duration, |
| 64 | webrtc::TaskQueueBase::DelayPrecision::kLow) {} |
| 65 | TimerOptions(webrtc::TimeDelta duration, |
| 66 | TimerBackoffAlgorithm backoff_algorithm, |
| 67 | absl::optional<int> max_restarts, |
| 68 | webrtc::TimeDelta max_backoff_duration, |
| 69 | webrtc::TaskQueueBase::DelayPrecision precision) |
| 70 | : duration(duration), |
| 71 | backoff_algorithm(backoff_algorithm), |
| 72 | max_restarts(max_restarts), |
| 73 | max_backoff_duration(max_backoff_duration), |
| 74 | precision(precision) {} |
| 75 | |
| 76 | // The initial timer duration. Can be overridden with `set_duration`. |
| 77 | const webrtc::TimeDelta duration; |
| 78 | // If the duration should be increased (using exponential backoff) when it is |
| 79 | // restarted. If not set, the same duration will be used. |
| 80 | const TimerBackoffAlgorithm backoff_algorithm; |
| 81 | // The maximum number of times that the timer will be automatically restarted, |
| 82 | // or absl::nullopt if there is no limit. |
| 83 | const absl::optional<int> max_restarts; |
| 84 | // The maximum timeout value for exponential backoff. |
| 85 | const webrtc::TimeDelta max_backoff_duration; |
| 86 | // The precision of the webrtc::TaskQueueBase used for scheduling. |
| 87 | const webrtc::TaskQueueBase::DelayPrecision precision; |
| 88 | }; |
| 89 | |
| 90 | // A high-level timer (in contrast to the low-level `Timeout` class). |
| 91 | // |
| 92 | // Timers are started and can be stopped or restarted. When a timer expires, |
| 93 | // the provided `on_expired` callback will be triggered. A timer is |
| 94 | // automatically restarted, as long as the number of restarts is below the |
| 95 | // configurable `max_restarts` parameter. The `is_running` property can be |
| 96 | // queried to know if it's still running after having expired. |
| 97 | // |
| 98 | // When a timer is restarted, it will use a configurable `backoff_algorithm` to |
| 99 | // possibly adjust the duration of the next expiry. It is also possible to |
| 100 | // return a new base duration (which is the duration before it's adjusted by the |
| 101 | // backoff algorithm). |
| 102 | class Timer { |
| 103 | public: |
| 104 | // The maximum timer duration - one day. |
| 105 | static constexpr webrtc::TimeDelta kMaxTimerDuration = |
| 106 | webrtc::TimeDelta::Seconds(24 * 3600); |
| 107 | |
| 108 | // When expired, the timer handler can optionally return a new non-zero |
| 109 | // duration which will be set as `duration` and used as base duration when the |
| 110 | // timer is restarted and as input to the backoff algorithm. If zero is |
| 111 | // returned, the current duration is used. |
| 112 | using OnExpired = std::function<webrtc::TimeDelta()>; |
| 113 | |
| 114 | // TimerManager will have pointers to these instances, so they must not move. |
| 115 | Timer(const Timer&) = delete; |
| 116 | Timer& operator=(const Timer&) = delete; |
| 117 | |
| 118 | ~Timer(); |
| 119 | |
| 120 | // Starts the timer if it's stopped or restarts the timer if it's already |
| 121 | // running. The `expiration_count` will be reset. |
| 122 | void Start(); |
| 123 | |
| 124 | // Stops the timer. This can also be called when the timer is already stopped. |
| 125 | // The `expiration_count` will be reset. |
| 126 | void Stop(); |
| 127 | |
| 128 | // Sets the base duration. The actual timer duration may be larger depending |
| 129 | // on the backoff algorithm. |
| 130 | void set_duration(webrtc::TimeDelta duration) { |
| 131 | duration_ = std::min(duration, kMaxTimerDuration); |
| 132 | } |
| 133 | |
| 134 | // Retrieves the base duration. The actual timer duration may be larger |
| 135 | // depending on the backoff algorithm. |
| 136 | webrtc::TimeDelta duration() const { return duration_; } |
| 137 | |
| 138 | // Returns the number of times the timer has expired. |
| 139 | int expiration_count() const { return expiration_count_; } |
| 140 | |
| 141 | // Returns the timer's options. |
| 142 | const TimerOptions& options() const { return options_; } |
| 143 | |
| 144 | // Returns the name of the timer. |
| 145 | absl::string_view name() const { return name_; } |
| 146 | |
| 147 | // Indicates if this timer is currently running. |
| 148 | bool is_running() const { return is_running_; } |
| 149 | |
| 150 | private: |
| 151 | friend class TimerManager; |
| 152 | using UnregisterHandler = std::function<void()>; |
| 153 | Timer(TimerID id, |
| 154 | absl::string_view name, |
| 155 | OnExpired on_expired, |
| 156 | UnregisterHandler unregister, |
| 157 | std::unique_ptr<Timeout> timeout, |
| 158 | const TimerOptions& options); |
| 159 | |
| 160 | // Called by TimerManager. Will trigger the callback and increment |
| 161 | // `expiration_count`. The timer will automatically be restarted at the |
| 162 | // duration as decided by the backoff algorithm, unless the |
| 163 | // `TimerOptions::max_restarts` has been reached and then it will be stopped |
| 164 | // and `is_running()` will return false. |
| 165 | void Trigger(TimerGeneration generation); |
| 166 | |
| 167 | const TimerID id_; |
| 168 | const std::string name_; |
| 169 | const TimerOptions options_; |
| 170 | const OnExpired on_expired_; |
| 171 | const UnregisterHandler unregister_handler_; |
| 172 | const std::unique_ptr<Timeout> timeout_; |
| 173 | |
| 174 | webrtc::TimeDelta duration_; |
| 175 | |
| 176 | // Increased on each start, and is matched on Trigger, to avoid races. And by |
| 177 | // race, meaning that a timeout - which may be evaluated/expired on a |
| 178 | // different thread while this thread has stopped that timer already. Note |
| 179 | // that the entire socket is not thread-safe, so `TimerManager::HandleTimeout` |
| 180 | // is never executed concurrently with any timer starting/stopping. |
| 181 | // |
| 182 | // This will wrap around after 4 billion timer restarts, and if it wraps |
| 183 | // around, it would just trigger _this_ timer in advance (but it's hard to |
| 184 | // restart it 4 billion times within its duration). |
| 185 | TimerGeneration generation_ = TimerGeneration(0); |
| 186 | bool is_running_ = false; |
| 187 | // Incremented each time time has expired and reset when stopped or restarted. |
| 188 | int expiration_count_ = 0; |
| 189 | }; |
| 190 | |
| 191 | // Creates and manages timers. |
| 192 | class TimerManager { |
| 193 | public: |
| 194 | explicit TimerManager( |
| 195 | std::function<std::unique_ptr<Timeout>( |
| 196 | webrtc::TaskQueueBase::DelayPrecision)> create_timeout) |
| 197 | : create_timeout_(std::move(create_timeout)) {} |
| 198 | |
| 199 | // Creates a timer with name `name` that will expire (when started) after |
| 200 | // `options.duration` and call `on_expired`. There are more `options` that |
| 201 | // affects the behavior. Note that timers are created initially stopped. |
| 202 | std::unique_ptr<Timer> CreateTimer(absl::string_view name, |
| 203 | Timer::OnExpired on_expired, |
| 204 | const TimerOptions& options); |
| 205 | |
| 206 | void HandleTimeout(TimeoutID timeout_id); |
| 207 | |
| 208 | private: |
| 209 | const std::function<std::unique_ptr<Timeout>( |
| 210 | webrtc::TaskQueueBase::DelayPrecision)> |
| 211 | create_timeout_; |
| 212 | std::map<TimerID, Timer*> timers_; |
| 213 | TimerID next_id_ = TimerID(0); |
| 214 | }; |
| 215 | |
| 216 | } // namespace dcsctp |
| 217 | |
| 218 | #endif // NET_DCSCTP_TIMER_TIMER_H_ |
| 219 | |