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()) -
59 struct HHWheelTimerTest : public ::testing::Test {
64 * Test firing some simple timeouts that are fired once and never rescheduled
66 TEST_F(HHWheelTimerTest, FireOnce) {
67 StackWheelTimer t(&eventBase, milliseconds(1));
69 const HHWheelTimer::Callback* nullCallback = nullptr;
75 ASSERT_EQ(t.count(), 0);
77 t.scheduleTimeout(&t1, milliseconds(5));
78 t.scheduleTimeout(&t2, milliseconds(5));
79 // Verify scheduling it twice cancels, then schedules.
80 // Should only get one callback.
81 t.scheduleTimeout(&t2, milliseconds(5));
82 t.scheduleTimeout(&t3, milliseconds(10));
84 ASSERT_EQ(t.count(), 3);
90 ASSERT_EQ(t1.timestamps.size(), 1);
91 ASSERT_EQ(t2.timestamps.size(), 1);
92 ASSERT_EQ(t3.timestamps.size(), 1);
94 ASSERT_EQ(t.count(), 0);
96 T_CHECK_TIMEOUT(start, t1.timestamps[0], milliseconds(5));
97 T_CHECK_TIMEOUT(start, t2.timestamps[0], milliseconds(5));
98 T_CHECK_TIMEOUT(start, t3.timestamps[0], milliseconds(10));
99 T_CHECK_TIMEOUT(start, end, milliseconds(10));
103 * Test scheduling a timeout from another timeout callback.
105 TEST_F(HHWheelTimerTest, TestSchedulingWithinCallback) {
106 StackWheelTimer t(&eventBase, milliseconds(10));
107 const HHWheelTimer::Callback* nullCallback = nullptr;
110 // Delayed to simulate the steady_clock counter lagging
111 TestTimeoutDelayed t2;
113 t.scheduleTimeout(&t1, milliseconds(500));
114 t1.fn = [&] { t.scheduleTimeout(&t2, milliseconds(1)); };
115 // If t is in an inconsistent state, detachEventBase should fail.
116 t2.fn = [&] { t.detachEventBase(); };
118 ASSERT_EQ(t.count(), 1);
122 ASSERT_EQ(t.count(), 0);
123 ASSERT_EQ(t1.timestamps.size(), 1);
124 ASSERT_EQ(t2.timestamps.size(), 1);
128 * Test cancelling a timeout when it is scheduled to be fired right away.
131 TEST_F(HHWheelTimerTest, CancelTimeout) {
132 StackWheelTimer t(&eventBase, milliseconds(1));
134 // Create several timeouts that will all fire in 5ms.
135 TestTimeout t5_1(&t, milliseconds(5));
136 TestTimeout t5_2(&t, milliseconds(5));
137 TestTimeout t5_3(&t, milliseconds(5));
138 TestTimeout t5_4(&t, milliseconds(5));
139 TestTimeout t5_5(&t, milliseconds(5));
141 // Also create a few timeouts to fire in 10ms
142 TestTimeout t10_1(&t, milliseconds(10));
143 TestTimeout t10_2(&t, milliseconds(10));
144 TestTimeout t10_3(&t, milliseconds(10));
146 TestTimeout t20_1(&t, milliseconds(20));
147 TestTimeout t20_2(&t, milliseconds(20));
149 // Have t5_1 cancel t5_2 and t5_4.
151 // Cancelling t5_2 will test cancelling a timeout that is at the head of the
152 // list and ready to be fired.
154 // Cancelling t5_4 will test cancelling a timeout in the middle of the list
156 t5_2.cancelTimeout();
157 t5_4.cancelTimeout();
160 // Have t5_3 cancel t5_5.
161 // This will test cancelling the last remaining timeout.
163 // Then have t5_3 reschedule itself.
165 t5_5.cancelTimeout();
166 // Reset our function so we won't continually reschedule ourself
167 std::function<void()> fnDtorGuard;
168 t5_3.fn.swap(fnDtorGuard);
169 t.scheduleTimeout(&t5_3, milliseconds(5));
171 // Also test cancelling timeouts in another timeset that isn't ready to
174 // Cancel the middle timeout in ts10.
175 t10_2.cancelTimeout();
176 // Cancel both the timeouts in ts20.
177 t20_1.cancelTimeout();
178 t20_2.cancelTimeout();
185 ASSERT_EQ(t5_1.timestamps.size(), 1);
186 T_CHECK_TIMEOUT(start, t5_1.timestamps[0], milliseconds(5));
188 ASSERT_EQ(t5_3.timestamps.size(), 2);
189 T_CHECK_TIMEOUT(start, t5_3.timestamps[0], milliseconds(5));
190 T_CHECK_TIMEOUT(t5_3.timestamps[0], t5_3.timestamps[1], milliseconds(5));
192 ASSERT_EQ(t10_1.timestamps.size(), 1);
193 T_CHECK_TIMEOUT(start, t10_1.timestamps[0], milliseconds(10));
194 ASSERT_EQ(t10_3.timestamps.size(), 1);
195 T_CHECK_TIMEOUT(start, t10_3.timestamps[0], milliseconds(10));
197 // Cancelled timeouts
198 ASSERT_EQ(t5_2.timestamps.size(), 0);
199 ASSERT_EQ(t5_4.timestamps.size(), 0);
200 ASSERT_EQ(t5_5.timestamps.size(), 0);
201 ASSERT_EQ(t10_2.timestamps.size(), 0);
202 ASSERT_EQ(t20_1.timestamps.size(), 0);
203 ASSERT_EQ(t20_2.timestamps.size(), 0);
205 T_CHECK_TIMEOUT(start, end, milliseconds(10));
209 * Test destroying a HHWheelTimer with timeouts outstanding
212 TEST_F(HHWheelTimerTest, DestroyTimeoutSet) {
214 HHWheelTimer::UniquePtr t(
215 new HHWheelTimer(&eventBase, milliseconds(1)));
217 TestTimeout t5_1(t.get(), milliseconds(5));
218 TestTimeout t5_2(t.get(), milliseconds(5));
219 TestTimeout t5_3(t.get(), milliseconds(5));
221 TestTimeout t10_1(t.get(), milliseconds(10));
222 TestTimeout t10_2(t.get(), milliseconds(10));
224 // Have t5_2 destroy t
225 // Note that this will call destroy() inside t's timeoutExpired()
228 t5_3.cancelTimeout();
229 t5_1.cancelTimeout();
230 t10_1.cancelTimeout();
231 t10_2.cancelTimeout();
238 ASSERT_EQ(t5_1.timestamps.size(), 1);
239 T_CHECK_TIMEOUT(start, t5_1.timestamps[0], milliseconds(5));
240 ASSERT_EQ(t5_2.timestamps.size(), 1);
241 T_CHECK_TIMEOUT(start, t5_2.timestamps[0], milliseconds(5));
243 ASSERT_EQ(t5_3.timestamps.size(), 0);
244 ASSERT_EQ(t10_1.timestamps.size(), 0);
245 ASSERT_EQ(t10_2.timestamps.size(), 0);
247 T_CHECK_TIMEOUT(start, end, milliseconds(5));
251 * Test the tick interval parameter
253 TEST_F(HHWheelTimerTest, AtMostEveryN) {
255 // Create a timeout set with a 10ms interval, to fire no more than once
257 milliseconds interval(25);
258 milliseconds atMostEveryN(6);
259 StackWheelTimer t(&eventBase, atMostEveryN);
260 t.setCatchupEveryN(70);
262 // Create 60 timeouts to be added to ts10 at 1ms intervals.
263 uint32_t numTimeouts = 60;
264 std::vector<TestTimeout> timeouts(numTimeouts);
266 // Create a scheduler timeout to add the timeouts 1ms apart.
268 StackWheelTimer ts1(&eventBase, milliseconds(1));
269 TestTimeout scheduler(&ts1, milliseconds(1));
271 if (index >= numTimeouts) {
274 // Call timeoutExpired() on the timeout so it will record a timestamp.
275 // This is done only so we can record when we scheduled the timeout.
276 // This way if ts1 starts to fall behind a little over time we will still
277 // be comparing the ts10 timeouts to when they were first scheduled (rather
278 // than when we intended to schedule them). The scheduler may fall behind
279 // eventually since we don't really schedule it once every millisecond.
280 // Each time it finishes we schedule it for 1 millisecond in the future.
281 // The amount of time it takes to run, and any delays it encounters
282 // getting scheduled may eventually add up over time.
283 timeouts[index].timeoutExpired();
285 // Schedule the new timeout
286 t.scheduleTimeout(&timeouts[index], interval);
287 // Reschedule ourself
288 ts1.scheduleTimeout(&scheduler, milliseconds(1));
292 // Go ahead and schedule the first timeout now.
299 // We scheduled timeouts 1ms apart, when the HHWheelTimer is only allowed
300 // to wake up at most once every 3ms. It will therefore wake up every 3ms
301 // and fire groups of approximately 3 timeouts at a time.
303 // This is "approximately 3" since it may get slightly behind and fire 4 in
304 // one interval, etc. T_CHECK_TIMEOUT normally allows a few milliseconds of
305 // tolerance. We have to add the same into our checking algorithm here.
306 for (uint32_t idx = 0; idx < numTimeouts; ++idx) {
307 ASSERT_EQ(timeouts[idx].timestamps.size(), 2);
309 TimePoint scheduledTime(timeouts[idx].timestamps[0]);
310 TimePoint firedTime(timeouts[idx].timestamps[1]);
312 // Assert that the timeout fired at roughly the right time.
313 // T_CHECK_TIMEOUT() normally has a tolerance of 5ms. Allow an additional
315 milliseconds tolerance = milliseconds(5) + interval;
316 T_CHECK_TIMEOUT(scheduledTime, firedTime, atMostEveryN, tolerance);
318 // Assert that the difference between the previous timeout and now was
319 // either very small (fired in the same event loop), or larger than
325 TimePoint prev(timeouts[idx - 1].timestamps[1]);
327 auto delta = (firedTime.getTimeStart() - prev.getTimeEnd()) -
328 (firedTime.getTimeWaiting() - prev.getTimeWaiting());
329 if (delta > milliseconds(1)) {
330 T_CHECK_TIMEOUT(prev, firedTime, atMostEveryN);
336 * Test an event loop that is blocking
339 TEST_F(HHWheelTimerTest, SlowLoop) {
340 StackWheelTimer t(&eventBase, milliseconds(1));
345 ASSERT_EQ(t.count(), 0);
347 eventBase.runInLoop([](){usleep(10000);});
348 t.scheduleTimeout(&t1, milliseconds(5));
350 ASSERT_EQ(t.count(), 1);
356 ASSERT_EQ(t1.timestamps.size(), 1);
357 ASSERT_EQ(t.count(), 0);
359 // Check that the timeout was delayed by sleep
360 T_CHECK_TIMEOUT(start, t1.timestamps[0], milliseconds(15), milliseconds(1));
361 T_CHECK_TIMEOUT(start, end, milliseconds(15), milliseconds(1));
363 // Try it again, this time with catchup timing every loop
364 t.setCatchupEveryN(1);
366 eventBase.runInLoop([](){usleep(10000);});
367 t.scheduleTimeout(&t2, milliseconds(5));
369 ASSERT_EQ(t.count(), 1);
375 ASSERT_EQ(t2.timestamps.size(), 1);
376 ASSERT_EQ(t.count(), 0);
378 // Check that the timeout was NOT delayed by sleep
379 T_CHECK_TIMEOUT(start2, t2.timestamps[0], milliseconds(10), milliseconds(1));
380 T_CHECK_TIMEOUT(start2, end2, milliseconds(10), milliseconds(1));
383 TEST_F(HHWheelTimerTest, lambda) {
384 StackWheelTimer t(&eventBase, milliseconds(1));
386 t.scheduleTimeoutFn([&]{ count++; }, milliseconds(1));
391 // shouldn't crash because we swallow and log the error (you'll have to look
392 // at the console to confirm logging)
393 TEST_F(HHWheelTimerTest, lambdaThrows) {
394 StackWheelTimer t(&eventBase, milliseconds(1));
395 t.scheduleTimeoutFn([&]{ throw std::runtime_error("foo"); },