Wait for all threads to finish executing before leaving in an EventBase test
[folly.git] / folly / io / async / test / EventBaseTest.cpp
1 /*
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
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
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
17  * under the License.
18  */
19
20 #include <folly/Memory.h>
21 #include <folly/ScopeGuard.h>
22
23 #include <folly/io/async/AsyncTimeout.h>
24 #include <folly/io/async/EventBase.h>
25 #include <folly/io/async/EventHandler.h>
26 #include <folly/io/async/test/SocketPair.h>
27 #include <folly/io/async/test/Util.h>
28 #include <folly/portability/Unistd.h>
29
30 #include <folly/futures/Promise.h>
31
32 #include <atomic>
33 #include <iostream>
34 #include <memory>
35 #include <thread>
36
37 using std::atomic;
38 using std::deque;
39 using std::pair;
40 using std::vector;
41 using std::unique_ptr;
42 using std::thread;
43 using std::make_pair;
44 using std::cerr;
45 using std::endl;
46 using std::chrono::milliseconds;
47 using std::chrono::microseconds;
48 using std::chrono::duration_cast;
49
50 using namespace folly;
51
52 ///////////////////////////////////////////////////////////////////////////
53 // Tests for read and write events
54 ///////////////////////////////////////////////////////////////////////////
55
56 enum { BUF_SIZE = 4096 };
57
58 ssize_t writeToFD(int fd, size_t length) {
59   // write an arbitrary amount of data to the fd
60   auto bufv = vector<char>(length);
61   auto buf = bufv.data();
62   memset(buf, 'a', length);
63   ssize_t rc = write(fd, buf, length);
64   CHECK_EQ(rc, length);
65   return rc;
66 }
67
68 size_t writeUntilFull(int fd) {
69   // Write to the fd until EAGAIN is returned
70   size_t bytesWritten = 0;
71   char buf[BUF_SIZE];
72   memset(buf, 'a', sizeof(buf));
73   while (true) {
74     ssize_t rc = write(fd, buf, sizeof(buf));
75     if (rc < 0) {
76       CHECK_EQ(errno, EAGAIN);
77       break;
78     } else {
79       bytesWritten += rc;
80     }
81   }
82   return bytesWritten;
83 }
84
85 ssize_t readFromFD(int fd, size_t length) {
86   // write an arbitrary amount of data to the fd
87   auto buf = vector<char>(length);
88   return read(fd, buf.data(), length);
89 }
90
91 size_t readUntilEmpty(int fd) {
92   // Read from the fd until EAGAIN is returned
93   char buf[BUF_SIZE];
94   size_t bytesRead = 0;
95   while (true) {
96     int rc = read(fd, buf, sizeof(buf));
97     if (rc == 0) {
98       CHECK(false) << "unexpected EOF";
99     } else if (rc < 0) {
100       CHECK_EQ(errno, EAGAIN);
101       break;
102     } else {
103       bytesRead += rc;
104     }
105   }
106   return bytesRead;
107 }
108
109 void checkReadUntilEmpty(int fd, size_t expectedLength) {
110   ASSERT_EQ(readUntilEmpty(fd), expectedLength);
111 }
112
113 struct ScheduledEvent {
114   int milliseconds;
115   uint16_t events;
116   size_t length;
117   ssize_t result;
118
119   void perform(int fd) {
120     if (events & EventHandler::READ) {
121       if (length == 0) {
122         result = readUntilEmpty(fd);
123       } else {
124         result = readFromFD(fd, length);
125       }
126     }
127     if (events & EventHandler::WRITE) {
128       if (length == 0) {
129         result = writeUntilFull(fd);
130       } else {
131         result = writeToFD(fd, length);
132       }
133     }
134   }
135 };
136
137 void scheduleEvents(EventBase* eventBase, int fd, ScheduledEvent* events) {
138   for (ScheduledEvent* ev = events; ev->milliseconds > 0; ++ev) {
139     eventBase->tryRunAfterDelay(std::bind(&ScheduledEvent::perform, ev, fd),
140                              ev->milliseconds);
141   }
142 }
143
144 class TestHandler : public EventHandler {
145  public:
146   TestHandler(EventBase* eventBase, int fd)
147     : EventHandler(eventBase, fd), fd_(fd) {}
148
149   void handlerReady(uint16_t events) noexcept override {
150     ssize_t bytesRead = 0;
151     ssize_t bytesWritten = 0;
152     if (events & READ) {
153       // Read all available data, so EventBase will stop calling us
154       // until new data becomes available
155       bytesRead = readUntilEmpty(fd_);
156     }
157     if (events & WRITE) {
158       // Write until the pipe buffer is full, so EventBase will stop calling
159       // us until the other end has read some data
160       bytesWritten = writeUntilFull(fd_);
161     }
162
163     log.emplace_back(events, bytesRead, bytesWritten);
164   }
165
166   struct EventRecord {
167     EventRecord(uint16_t events, size_t bytesRead, size_t bytesWritten)
168       : events(events)
169       , timestamp()
170       , bytesRead(bytesRead)
171       , bytesWritten(bytesWritten) {}
172
173     uint16_t events;
174     TimePoint timestamp;
175     ssize_t bytesRead;
176     ssize_t bytesWritten;
177   };
178
179   deque<EventRecord> log;
180
181  private:
182   int fd_;
183 };
184
185 /**
186  * Test a READ event
187  */
188 TEST(EventBaseTest, ReadEvent) {
189   EventBase eb;
190   SocketPair sp;
191
192   // Register for read events
193   TestHandler handler(&eb, sp[0]);
194   handler.registerHandler(EventHandler::READ);
195
196   // Register timeouts to perform two write events
197   ScheduledEvent events[] = {
198     { 10, EventHandler::WRITE, 2345, 0 },
199     { 160, EventHandler::WRITE, 99, 0 },
200     { 0, 0, 0, 0 },
201   };
202   scheduleEvents(&eb, sp[1], events);
203
204   // Loop
205   TimePoint start;
206   eb.loop();
207   TimePoint end;
208
209   // Since we didn't use the EventHandler::PERSIST flag, the handler should
210   // have received the first read, then unregistered itself.  Check that only
211   // the first chunk of data was received.
212   ASSERT_EQ(handler.log.size(), 1);
213   ASSERT_EQ(handler.log[0].events, EventHandler::READ);
214   T_CHECK_TIMEOUT(start, handler.log[0].timestamp,
215                   milliseconds(events[0].milliseconds), milliseconds(90));
216   ASSERT_EQ(handler.log[0].bytesRead, events[0].length);
217   ASSERT_EQ(handler.log[0].bytesWritten, 0);
218   T_CHECK_TIMEOUT(start, end,
219                   milliseconds(events[1].milliseconds), milliseconds(30));
220
221   // Make sure the second chunk of data is still waiting to be read.
222   size_t bytesRemaining = readUntilEmpty(sp[0]);
223   ASSERT_EQ(bytesRemaining, events[1].length);
224 }
225
226 /**
227  * Test (READ | PERSIST)
228  */
229 TEST(EventBaseTest, ReadPersist) {
230   EventBase eb;
231   SocketPair sp;
232
233   // Register for read events
234   TestHandler handler(&eb, sp[0]);
235   handler.registerHandler(EventHandler::READ | EventHandler::PERSIST);
236
237   // Register several timeouts to perform writes
238   ScheduledEvent events[] = {
239     { 10,  EventHandler::WRITE, 1024, 0 },
240     { 20,  EventHandler::WRITE, 2211, 0 },
241     { 30,  EventHandler::WRITE, 4096, 0 },
242     { 100, EventHandler::WRITE, 100,  0 },
243     { 0, 0, 0, 0 },
244   };
245   scheduleEvents(&eb, sp[1], events);
246
247   // Schedule a timeout to unregister the handler after the third write
248   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 85);
249
250   // Loop
251   TimePoint start;
252   eb.loop();
253   TimePoint end;
254
255   // The handler should have received the first 3 events,
256   // then been unregistered after that.
257   ASSERT_EQ(handler.log.size(), 3);
258   for (int n = 0; n < 3; ++n) {
259     ASSERT_EQ(handler.log[n].events, EventHandler::READ);
260     T_CHECK_TIMEOUT(start, handler.log[n].timestamp,
261                     milliseconds(events[n].milliseconds));
262     ASSERT_EQ(handler.log[n].bytesRead, events[n].length);
263     ASSERT_EQ(handler.log[n].bytesWritten, 0);
264   }
265   T_CHECK_TIMEOUT(start, end, milliseconds(events[3].milliseconds));
266
267   // Make sure the data from the last write is still waiting to be read
268   size_t bytesRemaining = readUntilEmpty(sp[0]);
269   ASSERT_EQ(bytesRemaining, events[3].length);
270 }
271
272 /**
273  * Test registering for READ when the socket is immediately readable
274  */
275 TEST(EventBaseTest, ReadImmediate) {
276   EventBase eb;
277   SocketPair sp;
278
279   // Write some data to the socket so the other end will
280   // be immediately readable
281   size_t dataLength = 1234;
282   writeToFD(sp[1], dataLength);
283
284   // Register for read events
285   TestHandler handler(&eb, sp[0]);
286   handler.registerHandler(EventHandler::READ | EventHandler::PERSIST);
287
288   // Register a timeout to perform another write
289   ScheduledEvent events[] = {
290     { 10, EventHandler::WRITE, 2345, 0 },
291     { 0, 0, 0, 0 },
292   };
293   scheduleEvents(&eb, sp[1], events);
294
295   // Schedule a timeout to unregister the handler
296   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 20);
297
298   // Loop
299   TimePoint start;
300   eb.loop();
301   TimePoint end;
302
303   ASSERT_EQ(handler.log.size(), 2);
304
305   // There should have been 1 event for immediate readability
306   ASSERT_EQ(handler.log[0].events, EventHandler::READ);
307   T_CHECK_TIMEOUT(start, handler.log[0].timestamp, milliseconds(0));
308   ASSERT_EQ(handler.log[0].bytesRead, dataLength);
309   ASSERT_EQ(handler.log[0].bytesWritten, 0);
310
311   // There should be another event after the timeout wrote more data
312   ASSERT_EQ(handler.log[1].events, EventHandler::READ);
313   T_CHECK_TIMEOUT(start, handler.log[1].timestamp,
314                   milliseconds(events[0].milliseconds));
315   ASSERT_EQ(handler.log[1].bytesRead, events[0].length);
316   ASSERT_EQ(handler.log[1].bytesWritten, 0);
317
318   T_CHECK_TIMEOUT(start, end, milliseconds(20));
319 }
320
321 /**
322  * Test a WRITE event
323  */
324 TEST(EventBaseTest, WriteEvent) {
325   EventBase eb;
326   SocketPair sp;
327
328   // Fill up the write buffer before starting
329   size_t initialBytesWritten = writeUntilFull(sp[0]);
330
331   // Register for write events
332   TestHandler handler(&eb, sp[0]);
333   handler.registerHandler(EventHandler::WRITE);
334
335   // Register timeouts to perform two reads
336   ScheduledEvent events[] = {
337     { 10, EventHandler::READ, 0, 0 },
338     { 60, EventHandler::READ, 0, 0 },
339     { 0, 0, 0, 0 },
340   };
341   scheduleEvents(&eb, sp[1], events);
342
343   // Loop
344   TimePoint start;
345   eb.loop();
346   TimePoint end;
347
348   // Since we didn't use the EventHandler::PERSIST flag, the handler should
349   // have only been able to write once, then unregistered itself.
350   ASSERT_EQ(handler.log.size(), 1);
351   ASSERT_EQ(handler.log[0].events, EventHandler::WRITE);
352   T_CHECK_TIMEOUT(start, handler.log[0].timestamp,
353                   milliseconds(events[0].milliseconds));
354   ASSERT_EQ(handler.log[0].bytesRead, 0);
355   ASSERT_GT(handler.log[0].bytesWritten, 0);
356   T_CHECK_TIMEOUT(start, end, milliseconds(events[1].milliseconds));
357
358   ASSERT_EQ(events[0].result, initialBytesWritten);
359   ASSERT_EQ(events[1].result, handler.log[0].bytesWritten);
360 }
361
362 /**
363  * Test (WRITE | PERSIST)
364  */
365 TEST(EventBaseTest, WritePersist) {
366   EventBase eb;
367   SocketPair sp;
368
369   // Fill up the write buffer before starting
370   size_t initialBytesWritten = writeUntilFull(sp[0]);
371
372   // Register for write events
373   TestHandler handler(&eb, sp[0]);
374   handler.registerHandler(EventHandler::WRITE | EventHandler::PERSIST);
375
376   // Register several timeouts to read from the socket at several intervals
377   ScheduledEvent events[] = {
378     { 10,  EventHandler::READ, 0, 0 },
379     { 40,  EventHandler::READ, 0, 0 },
380     { 70,  EventHandler::READ, 0, 0 },
381     { 100, EventHandler::READ, 0, 0 },
382     { 0, 0, 0, 0 },
383   };
384   scheduleEvents(&eb, sp[1], events);
385
386   // Schedule a timeout to unregister the handler after the third read
387   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 85);
388
389   // Loop
390   TimePoint start;
391   eb.loop();
392   TimePoint end;
393
394   // The handler should have received the first 3 events,
395   // then been unregistered after that.
396   ASSERT_EQ(handler.log.size(), 3);
397   ASSERT_EQ(events[0].result, initialBytesWritten);
398   for (int n = 0; n < 3; ++n) {
399     ASSERT_EQ(handler.log[n].events, EventHandler::WRITE);
400     T_CHECK_TIMEOUT(start, handler.log[n].timestamp,
401                     milliseconds(events[n].milliseconds));
402     ASSERT_EQ(handler.log[n].bytesRead, 0);
403     ASSERT_GT(handler.log[n].bytesWritten, 0);
404     ASSERT_EQ(handler.log[n].bytesWritten, events[n + 1].result);
405   }
406   T_CHECK_TIMEOUT(start, end, milliseconds(events[3].milliseconds));
407 }
408
409 /**
410  * Test registering for WRITE when the socket is immediately writable
411  */
412 TEST(EventBaseTest, WriteImmediate) {
413   EventBase eb;
414   SocketPair sp;
415
416   // Register for write events
417   TestHandler handler(&eb, sp[0]);
418   handler.registerHandler(EventHandler::WRITE | EventHandler::PERSIST);
419
420   // Register a timeout to perform a read
421   ScheduledEvent events[] = {
422     { 10, EventHandler::READ, 0, 0 },
423     { 0, 0, 0, 0 },
424   };
425   scheduleEvents(&eb, sp[1], events);
426
427   // Schedule a timeout to unregister the handler
428   int64_t unregisterTimeout = 40;
429   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler),
430                    unregisterTimeout);
431
432   // Loop
433   TimePoint start;
434   eb.loop();
435   TimePoint end;
436
437   ASSERT_EQ(handler.log.size(), 2);
438
439   // Since the socket buffer was initially empty,
440   // there should have been 1 event for immediate writability
441   ASSERT_EQ(handler.log[0].events, EventHandler::WRITE);
442   T_CHECK_TIMEOUT(start, handler.log[0].timestamp, milliseconds(0));
443   ASSERT_EQ(handler.log[0].bytesRead, 0);
444   ASSERT_GT(handler.log[0].bytesWritten, 0);
445
446   // There should be another event after the timeout wrote more data
447   ASSERT_EQ(handler.log[1].events, EventHandler::WRITE);
448   T_CHECK_TIMEOUT(start, handler.log[1].timestamp,
449                   milliseconds(events[0].milliseconds));
450   ASSERT_EQ(handler.log[1].bytesRead, 0);
451   ASSERT_GT(handler.log[1].bytesWritten, 0);
452
453   T_CHECK_TIMEOUT(start, end, milliseconds(unregisterTimeout));
454 }
455
456 /**
457  * Test (READ | WRITE) when the socket becomes readable first
458  */
459 TEST(EventBaseTest, ReadWrite) {
460   EventBase eb;
461   SocketPair sp;
462
463   // Fill up the write buffer before starting
464   size_t sock0WriteLength = writeUntilFull(sp[0]);
465
466   // Register for read and write events
467   TestHandler handler(&eb, sp[0]);
468   handler.registerHandler(EventHandler::READ_WRITE);
469
470   // Register timeouts to perform a write then a read.
471   ScheduledEvent events[] = {
472     { 10, EventHandler::WRITE, 2345, 0 },
473     { 40, EventHandler::READ, 0, 0 },
474     { 0, 0, 0, 0 },
475   };
476   scheduleEvents(&eb, sp[1], events);
477
478   // Loop
479   TimePoint start;
480   eb.loop();
481   TimePoint end;
482
483   // Since we didn't use the EventHandler::PERSIST flag, the handler should
484   // have only noticed readability, then unregistered itself.  Check that only
485   // one event was logged.
486   ASSERT_EQ(handler.log.size(), 1);
487   ASSERT_EQ(handler.log[0].events, EventHandler::READ);
488   T_CHECK_TIMEOUT(start, handler.log[0].timestamp,
489                   milliseconds(events[0].milliseconds));
490   ASSERT_EQ(handler.log[0].bytesRead, events[0].length);
491   ASSERT_EQ(handler.log[0].bytesWritten, 0);
492   ASSERT_EQ(events[1].result, sock0WriteLength);
493   T_CHECK_TIMEOUT(start, end, milliseconds(events[1].milliseconds));
494 }
495
496 /**
497  * Test (READ | WRITE) when the socket becomes writable first
498  */
499 TEST(EventBaseTest, WriteRead) {
500   EventBase eb;
501   SocketPair sp;
502
503   // Fill up the write buffer before starting
504   size_t sock0WriteLength = writeUntilFull(sp[0]);
505
506   // Register for read and write events
507   TestHandler handler(&eb, sp[0]);
508   handler.registerHandler(EventHandler::READ_WRITE);
509
510   // Register timeouts to perform a read then a write.
511   size_t sock1WriteLength = 2345;
512   ScheduledEvent events[] = {
513     { 10, EventHandler::READ, 0, 0 },
514     { 40, EventHandler::WRITE, sock1WriteLength, 0 },
515     { 0, 0, 0, 0 },
516   };
517   scheduleEvents(&eb, sp[1], events);
518
519   // Loop
520   TimePoint start;
521   eb.loop();
522   TimePoint end;
523
524   // Since we didn't use the EventHandler::PERSIST flag, the handler should
525   // have only noticed writability, then unregistered itself.  Check that only
526   // one event was logged.
527   ASSERT_EQ(handler.log.size(), 1);
528   ASSERT_EQ(handler.log[0].events, EventHandler::WRITE);
529   T_CHECK_TIMEOUT(start, handler.log[0].timestamp,
530                   milliseconds(events[0].milliseconds));
531   ASSERT_EQ(handler.log[0].bytesRead, 0);
532   ASSERT_GT(handler.log[0].bytesWritten, 0);
533   ASSERT_EQ(events[0].result, sock0WriteLength);
534   ASSERT_EQ(events[1].result, sock1WriteLength);
535   T_CHECK_TIMEOUT(start, end, milliseconds(events[1].milliseconds));
536
537   // Make sure the written data is still waiting to be read.
538   size_t bytesRemaining = readUntilEmpty(sp[0]);
539   ASSERT_EQ(bytesRemaining, events[1].length);
540 }
541
542 /**
543  * Test (READ | WRITE) when the socket becomes readable and writable
544  * at the same time.
545  */
546 TEST(EventBaseTest, ReadWriteSimultaneous) {
547   EventBase eb;
548   SocketPair sp;
549
550   // Fill up the write buffer before starting
551   size_t sock0WriteLength = writeUntilFull(sp[0]);
552
553   // Register for read and write events
554   TestHandler handler(&eb, sp[0]);
555   handler.registerHandler(EventHandler::READ_WRITE);
556
557   // Register a timeout to perform a read and write together
558   ScheduledEvent events[] = {
559     { 10, EventHandler::READ | EventHandler::WRITE, 0, 0 },
560     { 0, 0, 0, 0 },
561   };
562   scheduleEvents(&eb, sp[1], events);
563
564   // Loop
565   TimePoint start;
566   eb.loop();
567   TimePoint end;
568
569   // It's not strictly required that the EventBase register us about both
570   // events in the same call.  So, it's possible that if the EventBase
571   // implementation changes this test could start failing, and it wouldn't be
572   // considered breaking the API.  However for now it's nice to exercise this
573   // code path.
574   ASSERT_EQ(handler.log.size(), 1);
575   ASSERT_EQ(handler.log[0].events,
576                     EventHandler::READ | EventHandler::WRITE);
577   T_CHECK_TIMEOUT(start, handler.log[0].timestamp,
578                   milliseconds(events[0].milliseconds));
579   ASSERT_EQ(handler.log[0].bytesRead, sock0WriteLength);
580   ASSERT_GT(handler.log[0].bytesWritten, 0);
581   T_CHECK_TIMEOUT(start, end, milliseconds(events[0].milliseconds));
582 }
583
584 /**
585  * Test (READ | WRITE | PERSIST)
586  */
587 TEST(EventBaseTest, ReadWritePersist) {
588   EventBase eb;
589   SocketPair sp;
590
591   // Register for read and write events
592   TestHandler handler(&eb, sp[0]);
593   handler.registerHandler(EventHandler::READ | EventHandler::WRITE |
594                           EventHandler::PERSIST);
595
596   // Register timeouts to perform several reads and writes
597   ScheduledEvent events[] = {
598     { 10, EventHandler::WRITE, 2345, 0 },
599     { 20, EventHandler::READ, 0, 0 },
600     { 35, EventHandler::WRITE, 200, 0 },
601     { 45, EventHandler::WRITE, 15, 0 },
602     { 55, EventHandler::READ, 0, 0 },
603     { 120, EventHandler::WRITE, 2345, 0 },
604     { 0, 0, 0, 0 },
605   };
606   scheduleEvents(&eb, sp[1], events);
607
608   // Schedule a timeout to unregister the handler
609   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 80);
610
611   // Loop
612   TimePoint start;
613   eb.loop();
614   TimePoint end;
615
616   ASSERT_EQ(handler.log.size(), 6);
617
618   // Since we didn't fill up the write buffer immediately, there should
619   // be an immediate event for writability.
620   ASSERT_EQ(handler.log[0].events, EventHandler::WRITE);
621   T_CHECK_TIMEOUT(start, handler.log[0].timestamp, milliseconds(0));
622   ASSERT_EQ(handler.log[0].bytesRead, 0);
623   ASSERT_GT(handler.log[0].bytesWritten, 0);
624
625   // Events 1 through 5 should correspond to the scheduled events
626   for (int n = 1; n < 6; ++n) {
627     ScheduledEvent* event = &events[n - 1];
628     T_CHECK_TIMEOUT(start, handler.log[n].timestamp,
629                     milliseconds(event->milliseconds));
630     if (event->events == EventHandler::READ) {
631       ASSERT_EQ(handler.log[n].events, EventHandler::WRITE);
632       ASSERT_EQ(handler.log[n].bytesRead, 0);
633       ASSERT_GT(handler.log[n].bytesWritten, 0);
634     } else {
635       ASSERT_EQ(handler.log[n].events, EventHandler::READ);
636       ASSERT_EQ(handler.log[n].bytesRead, event->length);
637       ASSERT_EQ(handler.log[n].bytesWritten, 0);
638     }
639   }
640
641   // The timeout should have unregistered the handler before the last write.
642   // Make sure that data is still waiting to be read
643   size_t bytesRemaining = readUntilEmpty(sp[0]);
644   ASSERT_EQ(bytesRemaining, events[5].length);
645 }
646
647
648 class PartialReadHandler : public TestHandler {
649  public:
650   PartialReadHandler(EventBase* eventBase, int fd, size_t readLength)
651     : TestHandler(eventBase, fd), fd_(fd), readLength_(readLength) {}
652
653   void handlerReady(uint16_t events) noexcept override {
654     assert(events == EventHandler::READ);
655     ssize_t bytesRead = readFromFD(fd_, readLength_);
656     log.emplace_back(events, bytesRead, 0);
657   }
658
659  private:
660   int fd_;
661   size_t readLength_;
662 };
663
664 /**
665  * Test reading only part of the available data when a read event is fired.
666  * When PERSIST is used, make sure the handler gets notified again the next
667  * time around the loop.
668  */
669 TEST(EventBaseTest, ReadPartial) {
670   EventBase eb;
671   SocketPair sp;
672
673   // Register for read events
674   size_t readLength = 100;
675   PartialReadHandler handler(&eb, sp[0], readLength);
676   handler.registerHandler(EventHandler::READ | EventHandler::PERSIST);
677
678   // Register a timeout to perform a single write,
679   // with more data than PartialReadHandler will read at once
680   ScheduledEvent events[] = {
681     { 10, EventHandler::WRITE, (3*readLength) + (readLength / 2), 0 },
682     { 0, 0, 0, 0 },
683   };
684   scheduleEvents(&eb, sp[1], events);
685
686   // Schedule a timeout to unregister the handler
687   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 30);
688
689   // Loop
690   TimePoint start;
691   eb.loop();
692   TimePoint end;
693
694   ASSERT_EQ(handler.log.size(), 4);
695
696   // The first 3 invocations should read readLength bytes each
697   for (int n = 0; n < 3; ++n) {
698     ASSERT_EQ(handler.log[n].events, EventHandler::READ);
699     T_CHECK_TIMEOUT(start, handler.log[n].timestamp,
700                     milliseconds(events[0].milliseconds));
701     ASSERT_EQ(handler.log[n].bytesRead, readLength);
702     ASSERT_EQ(handler.log[n].bytesWritten, 0);
703   }
704   // The last read only has readLength/2 bytes
705   ASSERT_EQ(handler.log[3].events, EventHandler::READ);
706   T_CHECK_TIMEOUT(start, handler.log[3].timestamp,
707                   milliseconds(events[0].milliseconds));
708   ASSERT_EQ(handler.log[3].bytesRead, readLength / 2);
709   ASSERT_EQ(handler.log[3].bytesWritten, 0);
710 }
711
712
713 class PartialWriteHandler : public TestHandler {
714  public:
715   PartialWriteHandler(EventBase* eventBase, int fd, size_t writeLength)
716     : TestHandler(eventBase, fd), fd_(fd), writeLength_(writeLength) {}
717
718   void handlerReady(uint16_t events) noexcept override {
719     assert(events == EventHandler::WRITE);
720     ssize_t bytesWritten = writeToFD(fd_, writeLength_);
721     log.emplace_back(events, 0, bytesWritten);
722   }
723
724  private:
725   int fd_;
726   size_t writeLength_;
727 };
728
729 /**
730  * Test writing without completely filling up the write buffer when the fd
731  * becomes writable.  When PERSIST is used, make sure the handler gets
732  * notified again the next time around the loop.
733  */
734 TEST(EventBaseTest, WritePartial) {
735   EventBase eb;
736   SocketPair sp;
737
738   // Fill up the write buffer before starting
739   size_t initialBytesWritten = writeUntilFull(sp[0]);
740
741   // Register for write events
742   size_t writeLength = 100;
743   PartialWriteHandler handler(&eb, sp[0], writeLength);
744   handler.registerHandler(EventHandler::WRITE | EventHandler::PERSIST);
745
746   // Register a timeout to read, so that more data can be written
747   ScheduledEvent events[] = {
748     { 10, EventHandler::READ, 0, 0 },
749     { 0, 0, 0, 0 },
750   };
751   scheduleEvents(&eb, sp[1], events);
752
753   // Schedule a timeout to unregister the handler
754   eb.tryRunAfterDelay(std::bind(&TestHandler::unregisterHandler, &handler), 30);
755
756   // Loop
757   TimePoint start;
758   eb.loop();
759   TimePoint end;
760
761   // Depending on how big the socket buffer is, there will be multiple writes
762   // Only check the first 5
763   int numChecked = 5;
764   ASSERT_GE(handler.log.size(), numChecked);
765   ASSERT_EQ(events[0].result, initialBytesWritten);
766
767   // The first 3 invocations should read writeLength bytes each
768   for (int n = 0; n < numChecked; ++n) {
769     ASSERT_EQ(handler.log[n].events, EventHandler::WRITE);
770     T_CHECK_TIMEOUT(start, handler.log[n].timestamp,
771                     milliseconds(events[0].milliseconds));
772     ASSERT_EQ(handler.log[n].bytesRead, 0);
773     ASSERT_EQ(handler.log[n].bytesWritten, writeLength);
774   }
775 }
776
777
778 /**
779  * Test destroying a registered EventHandler
780  */
781 TEST(EventBaseTest, DestroyHandler) {
782   class DestroyHandler : public AsyncTimeout {
783    public:
784     DestroyHandler(EventBase* eb, EventHandler* h)
785       : AsyncTimeout(eb)
786       , handler_(h) {}
787
788     void timeoutExpired() noexcept override { delete handler_; }
789
790    private:
791     EventHandler* handler_;
792   };
793
794   EventBase eb;
795   SocketPair sp;
796
797   // Fill up the write buffer before starting
798   size_t initialBytesWritten = writeUntilFull(sp[0]);
799
800   // Register for write events
801   TestHandler* handler = new TestHandler(&eb, sp[0]);
802   handler->registerHandler(EventHandler::WRITE | EventHandler::PERSIST);
803
804   // After 10ms, read some data, so that the handler
805   // will be notified that it can write.
806   eb.tryRunAfterDelay(std::bind(checkReadUntilEmpty, sp[1], initialBytesWritten),
807                    10);
808
809   // Start a timer to destroy the handler after 25ms
810   // This mainly just makes sure the code doesn't break or assert
811   DestroyHandler dh(&eb, handler);
812   dh.scheduleTimeout(25);
813
814   TimePoint start;
815   eb.loop();
816   TimePoint end;
817
818   // Make sure the EventHandler was uninstalled properly when it was
819   // destroyed, and the EventBase loop exited
820   T_CHECK_TIMEOUT(start, end, milliseconds(25));
821
822   // Make sure that the handler wrote data to the socket
823   // before it was destroyed
824   size_t bytesRemaining = readUntilEmpty(sp[1]);
825   ASSERT_GT(bytesRemaining, 0);
826 }
827
828
829 ///////////////////////////////////////////////////////////////////////////
830 // Tests for timeout events
831 ///////////////////////////////////////////////////////////////////////////
832
833 TEST(EventBaseTest, RunAfterDelay) {
834   EventBase eb;
835
836   TimePoint timestamp1(false);
837   TimePoint timestamp2(false);
838   TimePoint timestamp3(false);
839   eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp1), 10);
840   eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp2), 20);
841   eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp3), 40);
842
843   TimePoint start;
844   eb.loop();
845   TimePoint end;
846
847   T_CHECK_TIMEOUT(start, timestamp1, milliseconds(10));
848   T_CHECK_TIMEOUT(start, timestamp2, milliseconds(20));
849   T_CHECK_TIMEOUT(start, timestamp3, milliseconds(40));
850   T_CHECK_TIMEOUT(start, end, milliseconds(40));
851 }
852
853 /**
854  * Test the behavior of tryRunAfterDelay() when some timeouts are
855  * still scheduled when the EventBase is destroyed.
856  */
857 TEST(EventBaseTest, RunAfterDelayDestruction) {
858   TimePoint timestamp1(false);
859   TimePoint timestamp2(false);
860   TimePoint timestamp3(false);
861   TimePoint timestamp4(false);
862   TimePoint start(false);
863   TimePoint end(false);
864
865   {
866     EventBase eb;
867
868     // Run two normal timeouts
869     eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp1), 10);
870     eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp2), 20);
871
872     // Schedule a timeout to stop the event loop after 40ms
873     eb.tryRunAfterDelay(std::bind(&EventBase::terminateLoopSoon, &eb), 40);
874
875     // Schedule 2 timeouts that would fire after the event loop stops
876     eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp3), 80);
877     eb.tryRunAfterDelay(std::bind(&TimePoint::reset, &timestamp4), 160);
878
879     start.reset();
880     eb.loop();
881     end.reset();
882   }
883
884   T_CHECK_TIMEOUT(start, timestamp1, milliseconds(10));
885   T_CHECK_TIMEOUT(start, timestamp2, milliseconds(20));
886   T_CHECK_TIMEOUT(start, end, milliseconds(40));
887
888   ASSERT_TRUE(timestamp3.isUnset());
889   ASSERT_TRUE(timestamp4.isUnset());
890
891   // Ideally this test should be run under valgrind to ensure that no
892   // memory is leaked.
893 }
894
895 class TestTimeout : public AsyncTimeout {
896  public:
897   explicit TestTimeout(EventBase* eventBase)
898     : AsyncTimeout(eventBase)
899     , timestamp(false) {}
900
901   void timeoutExpired() noexcept override { timestamp.reset(); }
902
903   TimePoint timestamp;
904 };
905
906 TEST(EventBaseTest, BasicTimeouts) {
907   EventBase eb;
908
909   TestTimeout t1(&eb);
910   TestTimeout t2(&eb);
911   TestTimeout t3(&eb);
912   t1.scheduleTimeout(10);
913   t2.scheduleTimeout(20);
914   t3.scheduleTimeout(40);
915
916   TimePoint start;
917   eb.loop();
918   TimePoint end;
919
920   T_CHECK_TIMEOUT(start, t1.timestamp, milliseconds(10));
921   T_CHECK_TIMEOUT(start, t2.timestamp, milliseconds(20));
922   T_CHECK_TIMEOUT(start, t3.timestamp, milliseconds(40));
923   T_CHECK_TIMEOUT(start, end, milliseconds(40));
924 }
925
926 class ReschedulingTimeout : public AsyncTimeout {
927  public:
928   ReschedulingTimeout(EventBase* evb, const vector<uint32_t>& timeouts)
929     : AsyncTimeout(evb)
930     , timeouts_(timeouts)
931     , iterator_(timeouts_.begin()) {}
932
933   void start() {
934     reschedule();
935   }
936
937   void timeoutExpired() noexcept override {
938     timestamps.emplace_back();
939     reschedule();
940   }
941
942   void reschedule() {
943     if (iterator_ != timeouts_.end()) {
944       uint32_t timeout = *iterator_;
945       ++iterator_;
946       scheduleTimeout(timeout);
947     }
948   }
949
950   vector<TimePoint> timestamps;
951
952  private:
953   vector<uint32_t> timeouts_;
954   vector<uint32_t>::const_iterator iterator_;
955 };
956
957 /**
958  * Test rescheduling the same timeout multiple times
959  */
960 TEST(EventBaseTest, ReuseTimeout) {
961   EventBase eb;
962
963   vector<uint32_t> timeouts;
964   timeouts.push_back(10);
965   timeouts.push_back(30);
966   timeouts.push_back(15);
967
968   ReschedulingTimeout t(&eb, timeouts);
969   t.start();
970
971   TimePoint start;
972   eb.loop();
973   TimePoint end;
974
975   // Use a higher tolerance than usual.  We're waiting on 3 timeouts
976   // consecutively.  In general, each timeout may go over by a few
977   // milliseconds, and we're tripling this error by witing on 3 timeouts.
978   milliseconds tolerance{6};
979
980   ASSERT_EQ(timeouts.size(), t.timestamps.size());
981   uint32_t total = 0;
982   for (size_t n = 0; n < timeouts.size(); ++n) {
983     total += timeouts[n];
984     T_CHECK_TIMEOUT(start, t.timestamps[n], milliseconds(total), tolerance);
985   }
986   T_CHECK_TIMEOUT(start, end, milliseconds(total), tolerance);
987 }
988
989 /**
990  * Test rescheduling a timeout before it has fired
991  */
992 TEST(EventBaseTest, RescheduleTimeout) {
993   EventBase eb;
994
995   TestTimeout t1(&eb);
996   TestTimeout t2(&eb);
997   TestTimeout t3(&eb);
998
999   t1.scheduleTimeout(15);
1000   t2.scheduleTimeout(30);
1001   t3.scheduleTimeout(30);
1002
1003   auto f = static_cast<bool(AsyncTimeout::*)(uint32_t)>(
1004       &AsyncTimeout::scheduleTimeout);
1005
1006   // after 10ms, reschedule t2 to run sooner than originally scheduled
1007   eb.tryRunAfterDelay(std::bind(f, &t2, 10), 10);
1008   // after 10ms, reschedule t3 to run later than originally scheduled
1009   eb.tryRunAfterDelay(std::bind(f, &t3, 40), 10);
1010
1011   TimePoint start;
1012   eb.loop();
1013   TimePoint end;
1014
1015   T_CHECK_TIMEOUT(start, t1.timestamp, milliseconds(15));
1016   T_CHECK_TIMEOUT(start, t2.timestamp, milliseconds(20));
1017   T_CHECK_TIMEOUT(start, t3.timestamp, milliseconds(50));
1018   T_CHECK_TIMEOUT(start, end, milliseconds(50));
1019 }
1020
1021 /**
1022  * Test cancelling a timeout
1023  */
1024 TEST(EventBaseTest, CancelTimeout) {
1025   EventBase eb;
1026
1027   vector<uint32_t> timeouts;
1028   timeouts.push_back(10);
1029   timeouts.push_back(30);
1030   timeouts.push_back(25);
1031
1032   ReschedulingTimeout t(&eb, timeouts);
1033   t.start();
1034   eb.tryRunAfterDelay(std::bind(&AsyncTimeout::cancelTimeout, &t), 50);
1035
1036   TimePoint start;
1037   eb.loop();
1038   TimePoint end;
1039
1040   ASSERT_EQ(t.timestamps.size(), 2);
1041   T_CHECK_TIMEOUT(start, t.timestamps[0], milliseconds(10));
1042   T_CHECK_TIMEOUT(start, t.timestamps[1], milliseconds(40));
1043   T_CHECK_TIMEOUT(start, end, milliseconds(50));
1044 }
1045
1046 /**
1047  * Test destroying a scheduled timeout object
1048  */
1049 TEST(EventBaseTest, DestroyTimeout) {
1050   class DestroyTimeout : public AsyncTimeout {
1051    public:
1052     DestroyTimeout(EventBase* eb, AsyncTimeout* t)
1053       : AsyncTimeout(eb)
1054       , timeout_(t) {}
1055
1056     void timeoutExpired() noexcept override { delete timeout_; }
1057
1058    private:
1059     AsyncTimeout* timeout_;
1060   };
1061
1062   EventBase eb;
1063
1064   TestTimeout* t1 = new TestTimeout(&eb);
1065   t1->scheduleTimeout(30);
1066
1067   DestroyTimeout dt(&eb, t1);
1068   dt.scheduleTimeout(10);
1069
1070   TimePoint start;
1071   eb.loop();
1072   TimePoint end;
1073
1074   T_CHECK_TIMEOUT(start, end, milliseconds(10));
1075 }
1076
1077
1078 ///////////////////////////////////////////////////////////////////////////
1079 // Test for runInThreadTestFunc()
1080 ///////////////////////////////////////////////////////////////////////////
1081
1082 struct RunInThreadData {
1083   RunInThreadData(int numThreads, int opsPerThread)
1084     : opsPerThread(opsPerThread)
1085     , opsToGo(numThreads*opsPerThread) {}
1086
1087   EventBase evb;
1088   deque< pair<int, int> > values;
1089
1090   int opsPerThread;
1091   int opsToGo;
1092 };
1093
1094 struct RunInThreadArg {
1095   RunInThreadArg(RunInThreadData* data,
1096                  int threadId,
1097                  int value)
1098     : data(data)
1099     , thread(threadId)
1100     , value(value) {}
1101
1102   RunInThreadData* data;
1103   int thread;
1104   int value;
1105 };
1106
1107 void runInThreadTestFunc(RunInThreadArg* arg) {
1108   arg->data->values.emplace_back(arg->thread, arg->value);
1109   RunInThreadData* data = arg->data;
1110   delete arg;
1111
1112   if(--data->opsToGo == 0) {
1113     // Break out of the event base loop if we are the last thread running
1114     data->evb.terminateLoopSoon();
1115   }
1116 }
1117
1118 TEST(EventBaseTest, RunInThread) {
1119   constexpr uint32_t numThreads = 50;
1120   constexpr uint32_t opsPerThread = 100;
1121   RunInThreadData data(numThreads, opsPerThread);
1122
1123   deque<std::thread> threads;
1124   SCOPE_EXIT {
1125     // Wait on all of the threads.
1126     for (auto& thread : threads) {
1127       thread.join();
1128     }
1129   };
1130
1131   for (uint32_t i = 0; i < numThreads; ++i) {
1132     threads.emplace_back([i, &data] {
1133         for (int n = 0; n < data.opsPerThread; ++n) {
1134           RunInThreadArg* arg = new RunInThreadArg(&data, i, n);
1135           data.evb.runInEventBaseThread(runInThreadTestFunc, arg);
1136           usleep(10);
1137         }
1138       });
1139   }
1140
1141   // Add a timeout event to run after 3 seconds.
1142   // Otherwise loop() will return immediately since there are no events to run.
1143   // Once the last thread exits, it will stop the loop().  However, this
1144   // timeout also stops the loop in case there is a bug performing the normal
1145   // stop.
1146   data.evb.tryRunAfterDelay(std::bind(&EventBase::terminateLoopSoon, &data.evb),
1147                          3000);
1148
1149   TimePoint start;
1150   data.evb.loop();
1151   TimePoint end;
1152
1153   // Verify that the loop exited because all threads finished and requested it
1154   // to stop.  This should happen much sooner than the 3 second timeout.
1155   // Assert that it happens in under a second.  (This is still tons of extra
1156   // padding.)
1157
1158   auto timeTaken = std::chrono::duration_cast<milliseconds>(
1159     end.getTime() - start.getTime());
1160   ASSERT_LT(timeTaken.count(), 1000);
1161   VLOG(11) << "Time taken: " << timeTaken.count();
1162
1163   // Verify that we have all of the events from every thread
1164   int expectedValues[numThreads];
1165   for (uint32_t n = 0; n < numThreads; ++n) {
1166     expectedValues[n] = 0;
1167   }
1168   for (deque< pair<int, int> >::const_iterator it = data.values.begin();
1169        it != data.values.end();
1170        ++it) {
1171     int threadID = it->first;
1172     int value = it->second;
1173     ASSERT_EQ(expectedValues[threadID], value);
1174     ++expectedValues[threadID];
1175   }
1176   for (uint32_t n = 0; n < numThreads; ++n) {
1177     ASSERT_EQ(expectedValues[n], opsPerThread);
1178   }
1179
1180   // Wait on all of the threads.
1181   for (auto& thread: threads) {
1182     thread.join();
1183   }
1184 }
1185
1186 //  This test simulates some calls, and verifies that the waiting happens by
1187 //  triggering what otherwise would be race conditions, and trying to detect
1188 //  whether any of the race conditions happened.
1189 TEST(EventBaseTest, RunInEventBaseThreadAndWait) {
1190   const size_t c = 256;
1191   vector<unique_ptr<atomic<size_t>>> atoms(c);
1192   for (size_t i = 0; i < c; ++i) {
1193     auto& atom = atoms.at(i);
1194     atom = make_unique<atomic<size_t>>(0);
1195   }
1196   vector<thread> threads;
1197   for (size_t i = 0; i < c; ++i) {
1198     threads.emplace_back([&atoms, i] {
1199       EventBase eb;
1200       auto& atom = *atoms.at(i);
1201       auto ebth = thread([&] { eb.loopForever(); });
1202       eb.waitUntilRunning();
1203       eb.runInEventBaseThreadAndWait([&] {
1204         size_t x = 0;
1205         atom.compare_exchange_weak(
1206             x, 1, std::memory_order_release, std::memory_order_relaxed);
1207       });
1208       size_t x = 0;
1209       atom.compare_exchange_weak(
1210           x, 2, std::memory_order_release, std::memory_order_relaxed);
1211       eb.terminateLoopSoon();
1212       ebth.join();
1213     });
1214   }
1215   for (size_t i = 0; i < c; ++i) {
1216     auto& th = threads.at(i);
1217     th.join();
1218   }
1219   size_t sum = 0;
1220   for (auto& atom : atoms) sum += *atom;
1221   EXPECT_EQ(c, sum);
1222 }
1223
1224 TEST(EventBaseTest, RunImmediatelyOrRunInEventBaseThreadAndWaitCross) {
1225   EventBase eb;
1226   thread th(&EventBase::loopForever, &eb);
1227   SCOPE_EXIT {
1228     eb.terminateLoopSoon();
1229     th.join();
1230   };
1231   auto mutated = false;
1232   eb.runImmediatelyOrRunInEventBaseThreadAndWait([&] {
1233       mutated = true;
1234   });
1235   EXPECT_TRUE(mutated);
1236 }
1237
1238 TEST(EventBaseTest, RunImmediatelyOrRunInEventBaseThreadAndWaitWithin) {
1239   EventBase eb;
1240   thread th(&EventBase::loopForever, &eb);
1241   SCOPE_EXIT {
1242     eb.terminateLoopSoon();
1243     th.join();
1244   };
1245   eb.runInEventBaseThreadAndWait([&] {
1246       auto mutated = false;
1247       eb.runImmediatelyOrRunInEventBaseThreadAndWait([&] {
1248           mutated = true;
1249       });
1250       EXPECT_TRUE(mutated);
1251   });
1252 }
1253
1254 TEST(EventBaseTest, RunImmediatelyOrRunInEventBaseThreadNotLooping) {
1255   EventBase eb;
1256   auto mutated = false;
1257   eb.runImmediatelyOrRunInEventBaseThreadAndWait([&] {
1258       mutated = true;
1259     });
1260   EXPECT_TRUE(mutated);
1261 }
1262
1263 ///////////////////////////////////////////////////////////////////////////
1264 // Tests for runInLoop()
1265 ///////////////////////////////////////////////////////////////////////////
1266
1267 class CountedLoopCallback : public EventBase::LoopCallback {
1268  public:
1269   CountedLoopCallback(EventBase* eventBase,
1270                       unsigned int count,
1271                       std::function<void()> action =
1272                         std::function<void()>())
1273     : eventBase_(eventBase)
1274     , count_(count)
1275     , action_(action) {}
1276
1277   void runLoopCallback() noexcept override {
1278     --count_;
1279     if (count_ > 0) {
1280       eventBase_->runInLoop(this);
1281     } else if (action_) {
1282       action_();
1283     }
1284   }
1285
1286   unsigned int getCount() const {
1287     return count_;
1288   }
1289
1290  private:
1291   EventBase* eventBase_;
1292   unsigned int count_;
1293   std::function<void()> action_;
1294 };
1295
1296 // Test that EventBase::loop() doesn't exit while there are
1297 // still LoopCallbacks remaining to be invoked.
1298 TEST(EventBaseTest, RepeatedRunInLoop) {
1299   EventBase eventBase;
1300
1301   CountedLoopCallback c(&eventBase, 10);
1302   eventBase.runInLoop(&c);
1303   // The callback shouldn't have run immediately
1304   ASSERT_EQ(c.getCount(), 10);
1305   eventBase.loop();
1306
1307   // loop() should loop until the CountedLoopCallback stops
1308   // re-installing itself.
1309   ASSERT_EQ(c.getCount(), 0);
1310 }
1311
1312 // Test that EventBase::loop() works as expected without time measurements.
1313 TEST(EventBaseTest, RunInLoopNoTimeMeasurement) {
1314   EventBase eventBase(false);
1315
1316   CountedLoopCallback c(&eventBase, 10);
1317   eventBase.runInLoop(&c);
1318   // The callback shouldn't have run immediately
1319   ASSERT_EQ(c.getCount(), 10);
1320   eventBase.loop();
1321
1322   // loop() should loop until the CountedLoopCallback stops
1323   // re-installing itself.
1324   ASSERT_EQ(c.getCount(), 0);
1325 }
1326
1327 // Test runInLoop() calls with terminateLoopSoon()
1328 TEST(EventBaseTest, RunInLoopStopLoop) {
1329   EventBase eventBase;
1330
1331   CountedLoopCallback c1(&eventBase, 20);
1332   CountedLoopCallback c2(&eventBase, 10,
1333                          std::bind(&EventBase::terminateLoopSoon, &eventBase));
1334
1335   eventBase.runInLoop(&c1);
1336   eventBase.runInLoop(&c2);
1337   ASSERT_EQ(c1.getCount(), 20);
1338   ASSERT_EQ(c2.getCount(), 10);
1339
1340   eventBase.loopForever();
1341
1342   // c2 should have stopped the loop after 10 iterations
1343   ASSERT_EQ(c2.getCount(), 0);
1344
1345   // We allow the EventBase to run the loop callbacks in whatever order it
1346   // chooses.  We'll accept c1's count being either 10 (if the loop terminated
1347   // after c1 ran on the 10th iteration) or 11 (if c2 terminated the loop
1348   // before c1 ran).
1349   //
1350   // (With the current code, c1 will always run 10 times, but we don't consider
1351   // this a hard API requirement.)
1352   ASSERT_GE(c1.getCount(), 10);
1353   ASSERT_LE(c1.getCount(), 11);
1354 }
1355
1356 TEST(EventBaseTest, TryRunningAfterTerminate) {
1357   EventBase eventBase;
1358   CountedLoopCallback c1(&eventBase, 1,
1359                          std::bind(&EventBase::terminateLoopSoon, &eventBase));
1360   eventBase.runInLoop(&c1);
1361   eventBase.loopForever();
1362   bool ran = false;
1363   eventBase.runInEventBaseThread([&]() {
1364     ran = true;
1365   });
1366
1367   ASSERT_FALSE(ran);
1368 }
1369
1370 // Test cancelling runInLoop() callbacks
1371 TEST(EventBaseTest, CancelRunInLoop) {
1372   EventBase eventBase;
1373
1374   CountedLoopCallback c1(&eventBase, 20);
1375   CountedLoopCallback c2(&eventBase, 20);
1376   CountedLoopCallback c3(&eventBase, 20);
1377
1378   std::function<void()> cancelC1Action =
1379     std::bind(&EventBase::LoopCallback::cancelLoopCallback, &c1);
1380   std::function<void()> cancelC2Action =
1381     std::bind(&EventBase::LoopCallback::cancelLoopCallback, &c2);
1382
1383   CountedLoopCallback cancelC1(&eventBase, 10, cancelC1Action);
1384   CountedLoopCallback cancelC2(&eventBase, 10, cancelC2Action);
1385
1386   // Install cancelC1 after c1
1387   eventBase.runInLoop(&c1);
1388   eventBase.runInLoop(&cancelC1);
1389
1390   // Install cancelC2 before c2
1391   eventBase.runInLoop(&cancelC2);
1392   eventBase.runInLoop(&c2);
1393
1394   // Install c3
1395   eventBase.runInLoop(&c3);
1396
1397   ASSERT_EQ(c1.getCount(), 20);
1398   ASSERT_EQ(c2.getCount(), 20);
1399   ASSERT_EQ(c3.getCount(), 20);
1400   ASSERT_EQ(cancelC1.getCount(), 10);
1401   ASSERT_EQ(cancelC2.getCount(), 10);
1402
1403   // Run the loop
1404   eventBase.loop();
1405
1406   // cancelC1 and cancelC3 should have both fired after 10 iterations and
1407   // stopped re-installing themselves
1408   ASSERT_EQ(cancelC1.getCount(), 0);
1409   ASSERT_EQ(cancelC2.getCount(), 0);
1410   // c3 should have continued on for the full 20 iterations
1411   ASSERT_EQ(c3.getCount(), 0);
1412
1413   // c1 and c2 should have both been cancelled on the 10th iteration.
1414   //
1415   // Callbacks are always run in the order they are installed,
1416   // so c1 should have fired 10 times, and been canceled after it ran on the
1417   // 10th iteration.  c2 should have only fired 9 times, because cancelC2 will
1418   // have run before it on the 10th iteration, and cancelled it before it
1419   // fired.
1420   ASSERT_EQ(c1.getCount(), 10);
1421   ASSERT_EQ(c2.getCount(), 11);
1422 }
1423
1424 class TerminateTestCallback : public EventBase::LoopCallback,
1425                               public EventHandler {
1426  public:
1427   TerminateTestCallback(EventBase* eventBase, int fd)
1428     : EventHandler(eventBase, fd),
1429       eventBase_(eventBase),
1430       loopInvocations_(0),
1431       maxLoopInvocations_(0),
1432       eventInvocations_(0),
1433       maxEventInvocations_(0) {}
1434
1435   void reset(uint32_t maxLoopInvocations, uint32_t maxEventInvocations) {
1436     loopInvocations_ = 0;
1437     maxLoopInvocations_ = maxLoopInvocations;
1438     eventInvocations_ = 0;
1439     maxEventInvocations_ = maxEventInvocations;
1440
1441     cancelLoopCallback();
1442     unregisterHandler();
1443   }
1444
1445   void handlerReady(uint16_t /* events */) noexcept override {
1446     // We didn't register with PERSIST, so we will have been automatically
1447     // unregistered already.
1448     ASSERT_FALSE(isHandlerRegistered());
1449
1450     ++eventInvocations_;
1451     if (eventInvocations_ >= maxEventInvocations_) {
1452       return;
1453     }
1454
1455     eventBase_->runInLoop(this);
1456   }
1457   void runLoopCallback() noexcept override {
1458     ++loopInvocations_;
1459     if (loopInvocations_ >= maxLoopInvocations_) {
1460       return;
1461     }
1462
1463     registerHandler(READ);
1464   }
1465
1466   uint32_t getLoopInvocations() const {
1467     return loopInvocations_;
1468   }
1469   uint32_t getEventInvocations() const {
1470     return eventInvocations_;
1471   }
1472
1473  private:
1474   EventBase* eventBase_;
1475   uint32_t loopInvocations_;
1476   uint32_t maxLoopInvocations_;
1477   uint32_t eventInvocations_;
1478   uint32_t maxEventInvocations_;
1479 };
1480
1481 /**
1482  * Test that EventBase::loop() correctly detects when there are no more events
1483  * left to run.
1484  *
1485  * This uses a single callback, which alternates registering itself as a loop
1486  * callback versus a EventHandler callback.  This exercises a regression where
1487  * EventBase::loop() incorrectly exited if there were no more fd handlers
1488  * registered, but a loop callback installed a new fd handler.
1489  */
1490 TEST(EventBaseTest, LoopTermination) {
1491   EventBase eventBase;
1492
1493   // Open a pipe and close the write end,
1494   // so the read endpoint will be readable
1495   int pipeFds[2];
1496   int rc = pipe(pipeFds);
1497   ASSERT_EQ(rc, 0);
1498   close(pipeFds[1]);
1499   TerminateTestCallback callback(&eventBase, pipeFds[0]);
1500
1501   // Test once where the callback will exit after a loop callback
1502   callback.reset(10, 100);
1503   eventBase.runInLoop(&callback);
1504   eventBase.loop();
1505   ASSERT_EQ(callback.getLoopInvocations(), 10);
1506   ASSERT_EQ(callback.getEventInvocations(), 9);
1507
1508   // Test once where the callback will exit after an fd event callback
1509   callback.reset(100, 7);
1510   eventBase.runInLoop(&callback);
1511   eventBase.loop();
1512   ASSERT_EQ(callback.getLoopInvocations(), 7);
1513   ASSERT_EQ(callback.getEventInvocations(), 7);
1514
1515   close(pipeFds[0]);
1516 }
1517
1518 ///////////////////////////////////////////////////////////////////////////
1519 // Tests for latency calculations
1520 ///////////////////////////////////////////////////////////////////////////
1521
1522 class IdleTimeTimeoutSeries : public AsyncTimeout {
1523
1524  public:
1525
1526   explicit IdleTimeTimeoutSeries(EventBase *base,
1527                                  std::deque<std::uint64_t>& timeout) :
1528     AsyncTimeout(base),
1529     timeouts_(0),
1530     timeout_(timeout) {
1531       scheduleTimeout(1);
1532     }
1533
1534     ~IdleTimeTimeoutSeries() override {}
1535
1536     void timeoutExpired() noexcept override {
1537     ++timeouts_;
1538
1539     if(timeout_.empty()){
1540       cancelTimeout();
1541     } else {
1542       uint64_t sleepTime = timeout_.front();
1543       timeout_.pop_front();
1544       if (sleepTime) {
1545         usleep(sleepTime);
1546       }
1547       scheduleTimeout(1);
1548     }
1549   }
1550
1551   int getTimeouts() const {
1552     return timeouts_;
1553   }
1554
1555  private:
1556   int timeouts_;
1557   std::deque<uint64_t>& timeout_;
1558 };
1559
1560 /**
1561  * Verify that idle time is correctly accounted for when decaying our loop
1562  * time.
1563  *
1564  * This works by creating a high loop time (via usleep), expecting a latency
1565  * callback with known value, and then scheduling a timeout for later. This
1566  * later timeout is far enough in the future that the idle time should have
1567  * caused the loop time to decay.
1568  */
1569 TEST(EventBaseTest, IdleTime) {
1570   EventBase eventBase;
1571   eventBase.setLoadAvgMsec(1000);
1572   eventBase.resetLoadAvg(5900.0);
1573   std::deque<uint64_t> timeouts0(4, 8080);
1574   timeouts0.push_front(8000);
1575   timeouts0.push_back(14000);
1576   IdleTimeTimeoutSeries tos0(&eventBase, timeouts0);
1577   std::deque<uint64_t> timeouts(20, 20);
1578   std::unique_ptr<IdleTimeTimeoutSeries> tos;
1579   int64_t testStart = duration_cast<microseconds>(
1580     std::chrono::steady_clock::now().time_since_epoch()).count();
1581   bool hostOverloaded = false;
1582
1583   int latencyCallbacks = 0;
1584   eventBase.setMaxLatency(6000, [&]() {
1585     ++latencyCallbacks;
1586
1587     switch (latencyCallbacks) {
1588     case 1:
1589       if (tos0.getTimeouts() < 6) {
1590         // This could only happen if the host this test is running
1591         // on is heavily loaded.
1592         int64_t maxLatencyReached = duration_cast<microseconds>(
1593             std::chrono::steady_clock::now().time_since_epoch()).count();
1594         ASSERT_LE(43800, maxLatencyReached - testStart);
1595         hostOverloaded = true;
1596         break;
1597       }
1598       ASSERT_EQ(6, tos0.getTimeouts());
1599       ASSERT_GE(6100, eventBase.getAvgLoopTime() - 1200);
1600       ASSERT_LE(6100, eventBase.getAvgLoopTime() + 1200);
1601       tos.reset(new IdleTimeTimeoutSeries(&eventBase, timeouts));
1602       break;
1603
1604     default:
1605       FAIL() << "Unexpected latency callback";
1606       break;
1607     }
1608   });
1609
1610   // Kick things off with an "immedite" timeout
1611   tos0.scheduleTimeout(1);
1612
1613   eventBase.loop();
1614
1615   if (hostOverloaded) {
1616     return;
1617   }
1618
1619   ASSERT_EQ(1, latencyCallbacks);
1620   ASSERT_EQ(7, tos0.getTimeouts());
1621   ASSERT_GE(5900, eventBase.getAvgLoopTime() - 1200);
1622   ASSERT_LE(5900, eventBase.getAvgLoopTime() + 1200);
1623   ASSERT_TRUE(!!tos);
1624   ASSERT_EQ(21, tos->getTimeouts());
1625 }
1626
1627 /**
1628  * Test that thisLoop functionality works with terminateLoopSoon
1629  */
1630 TEST(EventBaseTest, ThisLoop) {
1631   EventBase eb;
1632   bool runInLoop = false;
1633   bool runThisLoop = false;
1634
1635   eb.runInLoop([&](){
1636       eb.terminateLoopSoon();
1637       eb.runInLoop([&]() {
1638           runInLoop = true;
1639         });
1640       eb.runInLoop([&]() {
1641           runThisLoop = true;
1642         }, true);
1643     }, true);
1644   eb.loopForever();
1645
1646   // Should not work
1647   ASSERT_FALSE(runInLoop);
1648   // Should work with thisLoop
1649   ASSERT_TRUE(runThisLoop);
1650 }
1651
1652 TEST(EventBaseTest, EventBaseThreadLoop) {
1653   EventBase base;
1654   bool ran = false;
1655
1656   base.runInEventBaseThread([&](){
1657     ran = true;
1658   });
1659   base.loop();
1660
1661   ASSERT_EQ(true, ran);
1662 }
1663
1664 TEST(EventBaseTest, EventBaseThreadName) {
1665   EventBase base;
1666   base.setName("foo");
1667   base.loop();
1668
1669 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
1670   char name[16];
1671   pthread_getname_np(pthread_self(), name, 16);
1672   ASSERT_EQ(0, strcmp("foo", name));
1673 #endif
1674 }
1675
1676 TEST(EventBaseTest, RunBeforeLoop) {
1677   EventBase base;
1678   CountedLoopCallback cb(&base, 1, [&](){
1679     base.terminateLoopSoon();
1680   });
1681   base.runBeforeLoop(&cb);
1682   base.loopForever();
1683   ASSERT_EQ(cb.getCount(), 0);
1684 }
1685
1686 TEST(EventBaseTest, RunBeforeLoopWait) {
1687   EventBase base;
1688   CountedLoopCallback cb(&base, 1);
1689   base.tryRunAfterDelay([&](){
1690       base.terminateLoopSoon();
1691     }, 500);
1692   base.runBeforeLoop(&cb);
1693   base.loopForever();
1694
1695   // Check that we only ran once, and did not loop multiple times.
1696   ASSERT_EQ(cb.getCount(), 0);
1697 }
1698
1699 class PipeHandler : public EventHandler {
1700 public:
1701   PipeHandler(EventBase* eventBase, int fd)
1702     : EventHandler(eventBase, fd) {}
1703
1704   void handlerReady(uint16_t /* events */) noexcept override { abort(); }
1705 };
1706
1707 TEST(EventBaseTest, StopBeforeLoop) {
1708   EventBase evb;
1709
1710   // Give the evb something to do.
1711   int p[2];
1712   ASSERT_EQ(0, pipe(p));
1713   PipeHandler handler(&evb, p[0]);
1714   handler.registerHandler(EventHandler::READ);
1715
1716   // It's definitely not running yet
1717   evb.terminateLoopSoon();
1718
1719   // let it run, it should exit quickly.
1720   std::thread t([&] { evb.loop(); });
1721   t.join();
1722
1723   handler.unregisterHandler();
1724   close(p[0]);
1725   close(p[1]);
1726
1727   SUCCEED();
1728 }
1729
1730 TEST(EventBaseTest, RunCallbacksOnDestruction) {
1731   bool ran = false;
1732
1733   {
1734     EventBase base;
1735     base.runInEventBaseThread([&](){
1736       ran = true;
1737     });
1738   }
1739
1740   ASSERT_TRUE(ran);
1741 }
1742
1743 TEST(EventBaseTest, LoopKeepAlive) {
1744   EventBase evb;
1745
1746   bool done = false;
1747   std::thread t([&, loopKeepAlive = evb.loopKeepAlive() ]() mutable {
1748     /* sleep override */ std::this_thread::sleep_for(
1749         std::chrono::milliseconds(100));
1750     evb.runInEventBaseThread(
1751         [&done, loopKeepAlive = std::move(loopKeepAlive) ] { done = true; });
1752   });
1753
1754   evb.loop();
1755
1756   ASSERT_TRUE(done);
1757
1758   t.join();
1759 }
1760
1761 TEST(EventBaseTest, LoopKeepAliveInLoop) {
1762   EventBase evb;
1763
1764   bool done = false;
1765   std::thread t;
1766
1767   evb.runInEventBaseThread([&] {
1768     t = std::thread([&, loopKeepAlive = evb.loopKeepAlive() ]() mutable {
1769       /* sleep override */ std::this_thread::sleep_for(
1770           std::chrono::milliseconds(100));
1771       evb.runInEventBaseThread(
1772           [&done, loopKeepAlive = std::move(loopKeepAlive) ] { done = true; });
1773     });
1774   });
1775
1776   evb.loop();
1777
1778   ASSERT_TRUE(done);
1779
1780   t.join();
1781 }
1782
1783 TEST(EventBaseTest, LoopKeepAliveWithLoopForever) {
1784   std::unique_ptr<EventBase> evb = folly::make_unique<EventBase>();
1785
1786   bool done = false;
1787
1788   std::thread evThread([&] {
1789     evb->loopForever();
1790     evb.reset();
1791     done = true;
1792   });
1793
1794   {
1795     auto* ev = evb.get();
1796     EventBase::LoopKeepAlive keepAlive;
1797     ev->runInEventBaseThreadAndWait(
1798         [&ev, &keepAlive] { keepAlive = ev->loopKeepAlive(); });
1799     ASSERT_FALSE(done) << "Loop finished before we asked it to";
1800     ev->terminateLoopSoon();
1801     /* sleep override */
1802     std::this_thread::sleep_for(std::chrono::milliseconds(30));
1803     ASSERT_FALSE(done) << "Loop terminated early";
1804     ev->runInEventBaseThread([&ev, keepAlive = std::move(keepAlive) ]{});
1805   }
1806
1807   evThread.join();
1808   ASSERT_TRUE(done);
1809 }
1810
1811 TEST(EventBaseTest, LoopKeepAliveShutdown) {
1812   auto evb = folly::make_unique<EventBase>();
1813
1814   bool done = false;
1815
1816   std::thread t([
1817     &done,
1818     loopKeepAlive = evb->loopKeepAlive(),
1819     evbPtr = evb.get()
1820   ]() mutable {
1821     /* sleep override */ std::this_thread::sleep_for(
1822         std::chrono::milliseconds(100));
1823     evbPtr->runInEventBaseThread(
1824         [&done, loopKeepAlive = std::move(loopKeepAlive) ] { done = true; });
1825   });
1826
1827   evb.reset();
1828
1829   ASSERT_TRUE(done);
1830
1831   t.join();
1832 }
1833
1834 TEST(EventBaseTest, DrivableExecutorTest) {
1835   folly::Promise<bool> p;
1836   auto f = p.getFuture();
1837   EventBase base;
1838   bool finished = false;
1839
1840   std::thread t([&] {
1841     /* sleep override */
1842     std::this_thread::sleep_for(std::chrono::microseconds(10));
1843     finished = true;
1844     base.runInEventBaseThread([&]() { p.setValue(true); });
1845   });
1846
1847   // Ensure drive does not busy wait
1848   base.drive(); // TODO: fix notification queue init() extra wakeup
1849   base.drive();
1850   EXPECT_TRUE(finished);
1851
1852   folly::Promise<bool> p2;
1853   auto f2 = p2.getFuture();
1854   // Ensure waitVia gets woken up properly, even from
1855   // a separate thread.
1856   base.runAfterDelay([&]() { p2.setValue(true); }, 10);
1857   f2.waitVia(&base);
1858   EXPECT_TRUE(f2.isReady());
1859
1860   t.join();
1861 }
1862
1863 TEST(EventBaseTest, RequestContextTest) {
1864   EventBase evb;
1865   auto defaultCtx = RequestContext::get();
1866
1867   {
1868     RequestContextScopeGuard rctx;
1869     auto context = RequestContext::get();
1870     EXPECT_NE(defaultCtx, context);
1871     evb.runInLoop([context] { EXPECT_EQ(context, RequestContext::get()); });
1872   }
1873
1874   EXPECT_EQ(defaultCtx, RequestContext::get());
1875   evb.loop();
1876   EXPECT_EQ(defaultCtx, RequestContext::get());
1877 }