2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
19 #include <folly/io/async/HHWheelTimer.h>
20 #include <folly/io/async/EventBase.h>
21 #include <folly/io/async/test/UndelayedDestruction.h>
22 #include <folly/io/async/test/Util.h>
24 #include <gtest/gtest.h>
27 using namespace folly;
28 using std::chrono::milliseconds;
30 typedef UndelayedDestruction<HHWheelTimer> StackWheelTimer;
32 class TestTimeout : public HHWheelTimer::Callback {
35 TestTimeout(HHWheelTimer* t, milliseconds timeout) {
36 t->scheduleTimeout(this, timeout);
38 virtual void timeoutExpired() noexcept {
39 timestamps.push_back(TimePoint());
45 std::deque<TimePoint> timestamps;
46 std::function<void()> fn;
50 class TestTimeoutDelayed : public TestTimeout {
52 std::chrono::milliseconds getCurTime() override {
53 return std::chrono::duration_cast<std::chrono::milliseconds>(
54 std::chrono::steady_clock::now().time_since_epoch()) -
60 * Test firing some simple timeouts that are fired once and never rescheduled
62 TEST(HHWheelTimerTest, FireOnce) {
64 StackWheelTimer t(&eventBase, milliseconds(1));
66 const HHWheelTimer::Callback* nullCallback = nullptr;
72 ASSERT_EQ(t.count(), 0);
74 t.scheduleTimeout(&t1, milliseconds(5));
75 t.scheduleTimeout(&t2, milliseconds(5));
76 // Verify scheduling it twice cancels, then schedules.
77 // Should only get one callback.
78 t.scheduleTimeout(&t2, milliseconds(5));
79 t.scheduleTimeout(&t3, milliseconds(10));
81 ASSERT_EQ(t.count(), 3);
87 ASSERT_EQ(t1.timestamps.size(), 1);
88 ASSERT_EQ(t2.timestamps.size(), 1);
89 ASSERT_EQ(t3.timestamps.size(), 1);
91 ASSERT_EQ(t.count(), 0);
93 T_CHECK_TIMEOUT(start, t1.timestamps[0], milliseconds(5));
94 T_CHECK_TIMEOUT(start, t2.timestamps[0], milliseconds(5));
95 T_CHECK_TIMEOUT(start, t3.timestamps[0], milliseconds(10));
96 T_CHECK_TIMEOUT(start, end, milliseconds(10));
100 * Test cancelling a timeout when it is scheduled to be fired right away.
103 TEST(HHWheelTimerTest, CancelTimeout) {
105 StackWheelTimer t(&eventBase, milliseconds(1));
107 // Create several timeouts that will all fire in 5ms.
108 TestTimeout t5_1(&t, milliseconds(5));
109 TestTimeout t5_2(&t, milliseconds(5));
110 TestTimeout t5_3(&t, milliseconds(5));
111 TestTimeout t5_4(&t, milliseconds(5));
112 TestTimeout t5_5(&t, milliseconds(5));
114 // Also create a few timeouts to fire in 10ms
115 TestTimeout t10_1(&t, milliseconds(10));
116 TestTimeout t10_2(&t, milliseconds(10));
117 TestTimeout t10_3(&t, milliseconds(10));
119 TestTimeout t20_1(&t, milliseconds(20));
120 TestTimeout t20_2(&t, milliseconds(20));
122 // Have t5_1 cancel t5_2 and t5_4.
124 // Cancelling t5_2 will test cancelling a timeout that is at the head of the
125 // list and ready to be fired.
127 // Cancelling t5_4 will test cancelling a timeout in the middle of the list
129 t5_2.cancelTimeout();
130 t5_4.cancelTimeout();
133 // Have t5_3 cancel t5_5.
134 // This will test cancelling the last remaining timeout.
136 // Then have t5_3 reschedule itself.
138 t5_5.cancelTimeout();
139 // Reset our function so we won't continually reschedule ourself
140 std::function<void()> fnDtorGuard;
141 t5_3.fn.swap(fnDtorGuard);
142 t.scheduleTimeout(&t5_3, milliseconds(5));
144 // Also test cancelling timeouts in another timeset that isn't ready to
147 // Cancel the middle timeout in ts10.
148 t10_2.cancelTimeout();
149 // Cancel both the timeouts in ts20.
150 t20_1.cancelTimeout();
151 t20_2.cancelTimeout();
158 ASSERT_EQ(t5_1.timestamps.size(), 1);
159 T_CHECK_TIMEOUT(start, t5_1.timestamps[0], milliseconds(5));
161 ASSERT_EQ(t5_3.timestamps.size(), 2);
162 T_CHECK_TIMEOUT(start, t5_3.timestamps[0], milliseconds(5));
163 T_CHECK_TIMEOUT(t5_3.timestamps[0], t5_3.timestamps[1], milliseconds(5));
165 ASSERT_EQ(t10_1.timestamps.size(), 1);
166 T_CHECK_TIMEOUT(start, t10_1.timestamps[0], milliseconds(10));
167 ASSERT_EQ(t10_3.timestamps.size(), 1);
168 T_CHECK_TIMEOUT(start, t10_3.timestamps[0], milliseconds(10));
170 // Cancelled timeouts
171 ASSERT_EQ(t5_2.timestamps.size(), 0);
172 ASSERT_EQ(t5_4.timestamps.size(), 0);
173 ASSERT_EQ(t5_5.timestamps.size(), 0);
174 ASSERT_EQ(t10_2.timestamps.size(), 0);
175 ASSERT_EQ(t20_1.timestamps.size(), 0);
176 ASSERT_EQ(t20_2.timestamps.size(), 0);
178 T_CHECK_TIMEOUT(start, end, milliseconds(10));
182 * Test destroying a HHWheelTimer with timeouts outstanding
185 TEST(HHWheelTimerTest, DestroyTimeoutSet) {
188 HHWheelTimer::UniquePtr t(
189 new HHWheelTimer(&eventBase, milliseconds(1)));
191 TestTimeout t5_1(t.get(), milliseconds(5));
192 TestTimeout t5_2(t.get(), milliseconds(5));
193 TestTimeout t5_3(t.get(), milliseconds(5));
195 TestTimeout t10_1(t.get(), milliseconds(10));
196 TestTimeout t10_2(t.get(), milliseconds(10));
198 // Have t5_2 destroy t
199 // Note that this will call destroy() inside t's timeoutExpired()
202 t5_3.cancelTimeout();
203 t5_1.cancelTimeout();
204 t10_1.cancelTimeout();
205 t10_2.cancelTimeout();
212 ASSERT_EQ(t5_1.timestamps.size(), 1);
213 T_CHECK_TIMEOUT(start, t5_1.timestamps[0], milliseconds(5));
214 ASSERT_EQ(t5_2.timestamps.size(), 1);
215 T_CHECK_TIMEOUT(start, t5_2.timestamps[0], milliseconds(5));
217 ASSERT_EQ(t5_3.timestamps.size(), 0);
218 ASSERT_EQ(t10_1.timestamps.size(), 0);
219 ASSERT_EQ(t10_2.timestamps.size(), 0);
221 T_CHECK_TIMEOUT(start, end, milliseconds(5));
225 * Test the tick interval parameter
227 TEST(HHWheelTimerTest, AtMostEveryN) {
230 // Create a timeout set with a 10ms interval, to fire no more than once
232 milliseconds interval(25);
233 milliseconds atMostEveryN(6);
234 StackWheelTimer t(&eventBase, atMostEveryN);
235 t.setCatchupEveryN(70);
237 // Create 60 timeouts to be added to ts10 at 1ms intervals.
238 uint32_t numTimeouts = 60;
239 std::vector<TestTimeout> timeouts(numTimeouts);
241 // Create a scheduler timeout to add the timeouts 1ms apart.
243 StackWheelTimer ts1(&eventBase, milliseconds(1));
244 TestTimeout scheduler(&ts1, milliseconds(1));
246 if (index >= numTimeouts) {
249 // Call timeoutExpired() on the timeout so it will record a timestamp.
250 // This is done only so we can record when we scheduled the timeout.
251 // This way if ts1 starts to fall behind a little over time we will still
252 // be comparing the ts10 timeouts to when they were first scheduled (rather
253 // than when we intended to schedule them). The scheduler may fall behind
254 // eventually since we don't really schedule it once every millisecond.
255 // Each time it finishes we schedule it for 1 millisecond in the future.
256 // The amount of time it takes to run, and any delays it encounters
257 // getting scheduled may eventually add up over time.
258 timeouts[index].timeoutExpired();
260 // Schedule the new timeout
261 t.scheduleTimeout(&timeouts[index], interval);
262 // Reschedule ourself
263 ts1.scheduleTimeout(&scheduler, milliseconds(1));
267 // Go ahead and schedule the first timeout now.
274 // We scheduled timeouts 1ms apart, when the HHWheelTimer is only allowed
275 // to wake up at most once every 3ms. It will therefore wake up every 3ms
276 // and fire groups of approximately 3 timeouts at a time.
278 // This is "approximately 3" since it may get slightly behind and fire 4 in
279 // one interval, etc. T_CHECK_TIMEOUT normally allows a few milliseconds of
280 // tolerance. We have to add the same into our checking algorithm here.
281 for (uint32_t idx = 0; idx < numTimeouts; ++idx) {
282 ASSERT_EQ(timeouts[idx].timestamps.size(), 2);
284 TimePoint scheduledTime(timeouts[idx].timestamps[0]);
285 TimePoint firedTime(timeouts[idx].timestamps[1]);
287 // Assert that the timeout fired at roughly the right time.
288 // T_CHECK_TIMEOUT() normally has a tolerance of 5ms. Allow an additional
290 milliseconds tolerance = milliseconds(5) + interval;
291 T_CHECK_TIMEOUT(scheduledTime, firedTime, atMostEveryN, tolerance);
293 // Assert that the difference between the previous timeout and now was
294 // either very small (fired in the same event loop), or larger than
300 TimePoint prev(timeouts[idx - 1].timestamps[1]);
302 auto delta = (firedTime.getTimeStart() - prev.getTimeEnd()) -
303 (firedTime.getTimeWaiting() - prev.getTimeWaiting());
304 if (delta > milliseconds(1)) {
305 T_CHECK_TIMEOUT(prev, firedTime, atMostEveryN);
311 * Test an event loop that is blocking
314 TEST(HHWheelTimerTest, SlowLoop) {
316 StackWheelTimer t(&eventBase, milliseconds(1));
321 ASSERT_EQ(t.count(), 0);
323 eventBase.runInLoop([](){usleep(10000);});
324 t.scheduleTimeout(&t1, milliseconds(5));
326 ASSERT_EQ(t.count(), 1);
332 ASSERT_EQ(t1.timestamps.size(), 1);
333 ASSERT_EQ(t.count(), 0);
335 // Check that the timeout was delayed by sleep
336 T_CHECK_TIMEOUT(start, t1.timestamps[0], milliseconds(15), milliseconds(1));
337 T_CHECK_TIMEOUT(start, end, milliseconds(15), milliseconds(1));
339 // Try it again, this time with catchup timing every loop
340 t.setCatchupEveryN(1);
342 eventBase.runInLoop([](){usleep(10000);});
343 t.scheduleTimeout(&t2, milliseconds(5));
345 ASSERT_EQ(t.count(), 1);
351 ASSERT_EQ(t2.timestamps.size(), 1);
352 ASSERT_EQ(t.count(), 0);
354 // Check that the timeout was NOT delayed by sleep
355 T_CHECK_TIMEOUT(start2, t2.timestamps[0], milliseconds(10), milliseconds(1));
356 T_CHECK_TIMEOUT(start2, end2, milliseconds(10), milliseconds(1));