e1b1cb36fe29b3ea4dd4149d28fd1d517b13d0bf
[folly.git] / folly / io / async / NotificationQueue.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <sys/types.h>
20
21 #include <algorithm>
22 #include <deque>
23 #include <iterator>
24 #include <memory>
25 #include <stdexcept>
26 #include <utility>
27
28 #include <folly/Exception.h>
29 #include <folly/FileUtil.h>
30 #include <folly/Likely.h>
31 #include <folly/ScopeGuard.h>
32 #include <folly/SpinLock.h>
33 #include <folly/io/async/DelayedDestruction.h>
34 #include <folly/io/async/EventBase.h>
35 #include <folly/io/async/EventHandler.h>
36 #include <folly/io/async/Request.h>
37 #include <folly/portability/Fcntl.h>
38 #include <folly/portability/Sockets.h>
39 #include <folly/portability/Unistd.h>
40
41 #include <glog/logging.h>
42
43 #if __linux__ && !__ANDROID__
44 #define FOLLY_HAVE_EVENTFD
45 #include <folly/io/async/EventFDWrapper.h>
46 #endif
47
48 namespace folly {
49
50 /**
51  * A producer-consumer queue for passing messages between EventBase threads.
52  *
53  * Messages can be added to the queue from any thread.  Multiple consumers may
54  * listen to the queue from multiple EventBase threads.
55  *
56  * A NotificationQueue may not be destroyed while there are still consumers
57  * registered to receive events from the queue.  It is the user's
58  * responsibility to ensure that all consumers are unregistered before the
59  * queue is destroyed.
60  *
61  * MessageT should be MoveConstructible (i.e., must support either a move
62  * constructor or a copy constructor, or both).  Ideally it's move constructor
63  * (or copy constructor if no move constructor is provided) should never throw
64  * exceptions.  If the constructor may throw, the consumers could end up
65  * spinning trying to move a message off the queue and failing, and then
66  * retrying.
67  */
68 template <typename MessageT>
69 class NotificationQueue {
70  public:
71   /**
72    * A callback interface for consuming messages from the queue as they arrive.
73    */
74   class Consumer : public DelayedDestruction, private EventHandler {
75    public:
76     enum : uint16_t { kDefaultMaxReadAtOnce = 10 };
77
78     Consumer()
79       : queue_(nullptr),
80         destroyedFlagPtr_(nullptr),
81         maxReadAtOnce_(kDefaultMaxReadAtOnce) {}
82
83     // create a consumer in-place, without the need to build new class
84     template <typename TCallback>
85     static std::unique_ptr<Consumer, DelayedDestruction::Destructor> make(
86         TCallback&& callback);
87
88     /**
89      * messageAvailable() will be invoked whenever a new
90      * message is available from the pipe.
91      */
92     virtual void messageAvailable(MessageT&& message) noexcept = 0;
93
94     /**
95      * Begin consuming messages from the specified queue.
96      *
97      * messageAvailable() will be called whenever a message is available.  This
98      * consumer will continue to consume messages until stopConsuming() is
99      * called.
100      *
101      * A Consumer may only consume messages from a single NotificationQueue at
102      * a time.  startConsuming() should not be called if this consumer is
103      * already consuming.
104      */
105     void startConsuming(EventBase* eventBase, NotificationQueue* queue) {
106       init(eventBase, queue);
107       registerHandler(READ | PERSIST);
108     }
109
110     /**
111      * Same as above but registers this event handler as internal so that it
112      * doesn't count towards the pending reader count for the IOLoop.
113      */
114     void startConsumingInternal(
115         EventBase* eventBase, NotificationQueue* queue) {
116       init(eventBase, queue);
117       registerInternalHandler(READ | PERSIST);
118     }
119
120     /**
121      * Stop consuming messages.
122      *
123      * startConsuming() may be called again to resume consumption of messages
124      * at a later point in time.
125      */
126     void stopConsuming();
127
128     /**
129      * Consume messages off the queue until it is empty. No messages may be
130      * added to the queue while it is draining, so that the process is bounded.
131      * To that end, putMessage/tryPutMessage will throw an std::runtime_error,
132      * and tryPutMessageNoThrow will return false.
133      *
134      * @returns true if the queue was drained, false otherwise. In practice,
135      * this will only fail if someone else is already draining the queue.
136      */
137     bool consumeUntilDrained(size_t* numConsumed = nullptr) noexcept;
138
139     /**
140      * Get the NotificationQueue that this consumer is currently consuming
141      * messages from.  Returns nullptr if the consumer is not currently
142      * consuming events from any queue.
143      */
144     NotificationQueue* getCurrentQueue() const {
145       return queue_;
146     }
147
148     /**
149      * Set a limit on how many messages this consumer will read each iteration
150      * around the event loop.
151      *
152      * This helps rate-limit how much work the Consumer will do each event loop
153      * iteration, to prevent it from starving other event handlers.
154      *
155      * A limit of 0 means no limit will be enforced.  If unset, the limit
156      * defaults to kDefaultMaxReadAtOnce (defined to 10 above).
157      */
158     void setMaxReadAtOnce(uint32_t maxAtOnce) {
159       maxReadAtOnce_ = maxAtOnce;
160     }
161     uint32_t getMaxReadAtOnce() const {
162       return maxReadAtOnce_;
163     }
164
165     EventBase* getEventBase() {
166       return base_;
167     }
168
169     void handlerReady(uint16_t events) noexcept override;
170
171    protected:
172
173     void destroy() override;
174
175     ~Consumer() override {}
176
177    private:
178     /**
179      * Consume messages off the the queue until
180      *   - the queue is empty (1), or
181      *   - until the consumer is destroyed, or
182      *   - until the consumer is uninstalled, or
183      *   - an exception is thrown in the course of dequeueing, or
184      *   - unless isDrain is true, until the maxReadAtOnce_ limit is hit
185      *
186      * (1) Well, maybe. See logic/comments around "wasEmpty" in implementation.
187      */
188     void consumeMessages(bool isDrain, size_t* numConsumed = nullptr) noexcept;
189
190     void setActive(bool active, bool shouldLock = false) {
191       if (!queue_) {
192         active_ = active;
193         return;
194       }
195       if (shouldLock) {
196         queue_->spinlock_.lock();
197       }
198       if (!active_ && active) {
199         ++queue_->numActiveConsumers_;
200       } else if (active_ && !active) {
201         --queue_->numActiveConsumers_;
202       }
203       active_ = active;
204       if (shouldLock) {
205         queue_->spinlock_.unlock();
206       }
207     }
208     void init(EventBase* eventBase, NotificationQueue* queue);
209
210     NotificationQueue* queue_;
211     bool* destroyedFlagPtr_;
212     uint32_t maxReadAtOnce_;
213     EventBase* base_;
214     bool active_{false};
215   };
216
217   class SimpleConsumer {
218    public:
219     explicit SimpleConsumer(NotificationQueue& queue) : queue_(queue) {
220       ++queue_.numConsumers_;
221     }
222
223     ~SimpleConsumer() {
224       --queue_.numConsumers_;
225     }
226
227     int getFd() const {
228       return queue_.eventfd_ >= 0 ? queue_.eventfd_ : queue_.pipeFds_[0];
229     }
230
231    private:
232     NotificationQueue& queue_;
233   };
234
235   enum class FdType {
236     PIPE,
237 #ifdef FOLLY_HAVE_EVENTFD
238     EVENTFD,
239 #endif
240   };
241
242   /**
243    * Create a new NotificationQueue.
244    *
245    * If the maxSize parameter is specified, this sets the maximum queue size
246    * that will be enforced by tryPutMessage().  (This size is advisory, and may
247    * be exceeded if producers explicitly use putMessage() instead of
248    * tryPutMessage().)
249    *
250    * The fdType parameter determines the type of file descriptor used
251    * internally to signal message availability.  The default (eventfd) is
252    * preferable for performance and because it won't fail when the queue gets
253    * too long.  It is not available on on older and non-linux kernels, however.
254    * In this case the code will fall back to using a pipe, the parameter is
255    * mostly for testing purposes.
256    */
257   explicit NotificationQueue(uint32_t maxSize = 0,
258 #ifdef FOLLY_HAVE_EVENTFD
259                              FdType fdType = FdType::EVENTFD)
260 #else
261                              FdType fdType = FdType::PIPE)
262 #endif
263       : eventfd_(-1),
264         pipeFds_{-1, -1},
265         advisoryMaxQueueSize_(maxSize),
266         pid_(pid_t(getpid())),
267         queue_() {
268
269     RequestContext::saveContext();
270
271 #ifdef FOLLY_HAVE_EVENTFD
272     if (fdType == FdType::EVENTFD) {
273       eventfd_ = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
274       if (eventfd_ == -1) {
275         if (errno == ENOSYS || errno == EINVAL) {
276           // eventfd not availalble
277           LOG(ERROR) << "failed to create eventfd for NotificationQueue: "
278                      << errno << ", falling back to pipe mode (is your kernel "
279                      << "> 2.6.30?)";
280           fdType = FdType::PIPE;
281         } else {
282           // some other error
283           folly::throwSystemError("Failed to create eventfd for "
284                                   "NotificationQueue", errno);
285         }
286       }
287     }
288 #endif
289     if (fdType == FdType::PIPE) {
290       if (pipe(pipeFds_)) {
291         folly::throwSystemError("Failed to create pipe for NotificationQueue",
292                                 errno);
293       }
294       try {
295         // put both ends of the pipe into non-blocking mode
296         if (fcntl(pipeFds_[0], F_SETFL, O_RDONLY | O_NONBLOCK) != 0) {
297           folly::throwSystemError("failed to put NotificationQueue pipe read "
298                                   "endpoint into non-blocking mode", errno);
299         }
300         if (fcntl(pipeFds_[1], F_SETFL, O_WRONLY | O_NONBLOCK) != 0) {
301           folly::throwSystemError("failed to put NotificationQueue pipe write "
302                                   "endpoint into non-blocking mode", errno);
303         }
304       } catch (...) {
305         ::close(pipeFds_[0]);
306         ::close(pipeFds_[1]);
307         throw;
308       }
309     }
310   }
311
312   ~NotificationQueue() {
313     if (eventfd_ >= 0) {
314       ::close(eventfd_);
315       eventfd_ = -1;
316     }
317     if (pipeFds_[0] >= 0) {
318       ::close(pipeFds_[0]);
319       pipeFds_[0] = -1;
320     }
321     if (pipeFds_[1] >= 0) {
322       ::close(pipeFds_[1]);
323       pipeFds_[1] = -1;
324     }
325   }
326
327   /**
328    * Set the advisory maximum queue size.
329    *
330    * This maximum queue size affects calls to tryPutMessage().  Message
331    * producers can still use the putMessage() call to unconditionally put a
332    * message on the queue, ignoring the configured maximum queue size.  This
333    * can cause the queue size to exceed the configured maximum.
334    */
335   void setMaxQueueSize(uint32_t max) {
336     advisoryMaxQueueSize_ = max;
337   }
338
339   /**
340    * Attempt to put a message on the queue if the queue is not already full.
341    *
342    * If the queue is full, a std::overflow_error will be thrown.  The
343    * setMaxQueueSize() function controls the maximum queue size.
344    *
345    * If the queue is currently draining, an std::runtime_error will be thrown.
346    *
347    * This method may contend briefly on a spinlock if many threads are
348    * concurrently accessing the queue, but for all intents and purposes it will
349    * immediately place the message on the queue and return.
350    *
351    * tryPutMessage() may throw std::bad_alloc if memory allocation fails, and
352    * may throw any other exception thrown by the MessageT move/copy
353    * constructor.
354    */
355   template <typename MessageTT>
356   void tryPutMessage(MessageTT&& message) {
357     putMessageImpl(std::forward<MessageTT>(message), advisoryMaxQueueSize_);
358   }
359
360   /**
361    * No-throw versions of the above.  Instead returns true on success, false on
362    * failure.
363    *
364    * Only std::overflow_error (the common exception case) and std::runtime_error
365    * (which indicates that the queue is being drained) are prevented from being
366    * thrown. User code must still catch std::bad_alloc errors.
367    */
368   template <typename MessageTT>
369   bool tryPutMessageNoThrow(MessageTT&& message) {
370     return putMessageImpl(
371         std::forward<MessageTT>(message), advisoryMaxQueueSize_, false);
372   }
373
374   /**
375    * Unconditionally put a message on the queue.
376    *
377    * This method is like tryPutMessage(), but ignores the maximum queue size
378    * and always puts the message on the queue, even if the maximum queue size
379    * would be exceeded.
380    *
381    * putMessage() may throw
382    *   - std::bad_alloc if memory allocation fails, and may
383    *   - std::runtime_error if the queue is currently draining
384    *   - any other exception thrown by the MessageT move/copy constructor.
385    */
386   template <typename MessageTT>
387   void putMessage(MessageTT&& message) {
388     putMessageImpl(std::forward<MessageTT>(message), 0);
389   }
390
391   /**
392    * Put several messages on the queue.
393    */
394   template <typename InputIteratorT>
395   void putMessages(InputIteratorT first, InputIteratorT last) {
396     typedef typename std::iterator_traits<InputIteratorT>::iterator_category
397       IterCategory;
398     putMessagesImpl(first, last, IterCategory());
399   }
400
401   /**
402    * Try to immediately pull a message off of the queue, without blocking.
403    *
404    * If a message is immediately available, the result parameter will be
405    * updated to contain the message contents and true will be returned.
406    *
407    * If no message is available, false will be returned and result will be left
408    * unmodified.
409    */
410   bool tryConsume(MessageT& result) {
411     SCOPE_EXIT { syncSignalAndQueue(); };
412
413     checkPid();
414
415     folly::SpinLockGuard g(spinlock_);
416
417     if (UNLIKELY(queue_.empty())) {
418       return false;
419     }
420
421     auto& data = queue_.front();
422     result = std::move(data.first);
423     RequestContext::setContext(std::move(data.second));
424
425     queue_.pop_front();
426
427     return true;
428   }
429
430   size_t size() const {
431     folly::SpinLockGuard g(spinlock_);
432     return queue_.size();
433   }
434
435   /**
436    * Check that the NotificationQueue is being used from the correct process.
437    *
438    * If you create a NotificationQueue in one process, then fork, and try to
439    * send messages to the queue from the child process, you're going to have a
440    * bad time.  Unfortunately users have (accidentally) run into this.
441    *
442    * Because we use an eventfd/pipe, the child process can actually signal the
443    * parent process that an event is ready.  However, it can't put anything on
444    * the parent's queue, so the parent wakes up and finds an empty queue.  This
445    * check ensures that we catch the problem in the misbehaving child process
446    * code, and crash before signalling the parent process.
447    */
448   void checkPid() const { CHECK_EQ(pid_, pid_t(getpid())); }
449
450  private:
451   // Forbidden copy constructor and assignment operator
452   NotificationQueue(NotificationQueue const &) = delete;
453   NotificationQueue& operator=(NotificationQueue const &) = delete;
454
455   inline bool checkQueueSize(size_t maxSize, bool throws=true) const {
456     DCHECK(0 == spinlock_.try_lock());
457     if (maxSize > 0 && queue_.size() >= maxSize) {
458       if (throws) {
459         throw std::overflow_error("unable to add message to NotificationQueue: "
460                                   "queue is full");
461       }
462       return false;
463     }
464     return true;
465   }
466
467   inline bool checkDraining(bool throws=true) {
468     if (UNLIKELY(draining_ && throws)) {
469       throw std::runtime_error("queue is draining, cannot add message");
470     }
471     return draining_;
472   }
473
474 #ifdef __ANDROID__
475   // TODO 10860938 Remove after figuring out crash
476   mutable std::atomic<int> eventBytes_{0};
477   mutable std::atomic<int> maxEventBytes_{0};
478 #endif
479
480   void ensureSignalLocked() const {
481     // semantics: empty fd == empty queue <=> !signal_
482     if (signal_) {
483       return;
484     }
485
486     ssize_t bytes_written = 0;
487     size_t bytes_expected = 0;
488
489     do {
490       if (eventfd_ >= 0) {
491         // eventfd(2) dictates that we must write a 64-bit integer
492         uint64_t signal = 1;
493         bytes_expected = sizeof(signal);
494         bytes_written = ::write(eventfd_, &signal, bytes_expected);
495       } else {
496         uint8_t signal = 1;
497         bytes_expected = sizeof(signal);
498         bytes_written = ::write(pipeFds_[1], &signal, bytes_expected);
499       }
500     } while (bytes_written == -1 && errno == EINTR);
501
502 #ifdef __ANDROID__
503     if (bytes_written > 0) {
504       eventBytes_ += bytes_written;
505       maxEventBytes_ = std::max((int)maxEventBytes_, (int)eventBytes_);
506     }
507 #endif
508
509     if (bytes_written == ssize_t(bytes_expected)) {
510       signal_ = true;
511     } else {
512 #ifdef __ANDROID__
513       LOG(ERROR) << "NotificationQueue Write Error=" << errno
514                  << " bytesInPipe=" << eventBytes_
515                  << " maxInPipe=" << maxEventBytes_ << " queue=" << size();
516 #endif
517       folly::throwSystemError("failed to signal NotificationQueue after "
518                               "write", errno);
519     }
520   }
521
522   void drainSignalsLocked() {
523     ssize_t bytes_read = 0;
524     if (eventfd_ > 0) {
525       uint64_t message;
526       bytes_read = readNoInt(eventfd_, &message, sizeof(message));
527       CHECK(bytes_read != -1 || errno == EAGAIN);
528     } else {
529       // There should only be one byte in the pipe. To avoid potential leaks we still drain.
530       uint8_t message[32];
531       ssize_t result;
532       while ((result = readNoInt(pipeFds_[0], &message, sizeof(message))) != -1) {
533         bytes_read += result;
534       }
535       CHECK(result == -1 && errno == EAGAIN);
536       LOG_IF(ERROR, bytes_read > 1)
537         << "[NotificationQueue] Unexpected state while draining pipe: bytes_read="
538         << bytes_read << " bytes, expected <= 1";
539     }
540     LOG_IF(ERROR, (signal_ && bytes_read == 0) || (!signal_ && bytes_read > 0))
541       << "[NotificationQueue] Unexpected state while draining signals: signal_="
542       << signal_ << " bytes_read=" << bytes_read;
543
544     signal_ = false;
545
546 #ifdef __ANDROID__
547     if (bytes_read > 0) {
548       eventBytes_ -= bytes_read;
549     }
550 #endif
551   }
552
553   void ensureSignal() const {
554     folly::SpinLockGuard g(spinlock_);
555     ensureSignalLocked();
556   }
557
558   void syncSignalAndQueue() {
559     folly::SpinLockGuard g(spinlock_);
560
561     if (queue_.empty()) {
562       drainSignalsLocked();
563     } else {
564       ensureSignalLocked();
565     }
566   }
567
568   template <typename MessageTT>
569   bool putMessageImpl(MessageTT&& message, size_t maxSize, bool throws = true) {
570     checkPid();
571     bool signal = false;
572     {
573       folly::SpinLockGuard g(spinlock_);
574       if (checkDraining(throws) || !checkQueueSize(maxSize, throws)) {
575         return false;
576       }
577       // We only need to signal an event if not all consumers are
578       // awake.
579       if (numActiveConsumers_ < numConsumers_) {
580         signal = true;
581       }
582       queue_.emplace_back(
583           std::forward<MessageTT>(message), RequestContext::saveContext());
584       if (signal) {
585         ensureSignalLocked();
586       }
587     }
588     return true;
589   }
590
591   template <typename InputIteratorT>
592   void putMessagesImpl(InputIteratorT first, InputIteratorT last,
593                        std::input_iterator_tag) {
594     checkPid();
595     bool signal = false;
596     size_t numAdded = 0;
597     {
598       folly::SpinLockGuard g(spinlock_);
599       checkDraining();
600       while (first != last) {
601         queue_.emplace_back(*first, RequestContext::saveContext());
602         ++first;
603         ++numAdded;
604       }
605       if (numActiveConsumers_ < numConsumers_) {
606         signal = true;
607       }
608       if (signal) {
609         ensureSignalLocked();
610       }
611     }
612   }
613
614   mutable folly::SpinLock spinlock_;
615   mutable bool signal_{false};
616   int eventfd_;
617   int pipeFds_[2]; // to fallback to on older/non-linux systems
618   uint32_t advisoryMaxQueueSize_;
619   pid_t pid_;
620   std::deque<std::pair<MessageT, std::shared_ptr<RequestContext>>> queue_;
621   int numConsumers_{0};
622   std::atomic<int> numActiveConsumers_{0};
623   bool draining_{false};
624 };
625
626 template <typename MessageT>
627 void NotificationQueue<MessageT>::Consumer::destroy() {
628   // If we are in the middle of a call to handlerReady(), destroyedFlagPtr_
629   // will be non-nullptr.  Mark the value that it points to, so that
630   // handlerReady() will know the callback is destroyed, and that it cannot
631   // access any member variables anymore.
632   if (destroyedFlagPtr_) {
633     *destroyedFlagPtr_ = true;
634   }
635   stopConsuming();
636   DelayedDestruction::destroy();
637 }
638
639 template <typename MessageT>
640 void NotificationQueue<MessageT>::Consumer::handlerReady(uint16_t /*events*/)
641     noexcept {
642   consumeMessages(false);
643 }
644
645 template <typename MessageT>
646 void NotificationQueue<MessageT>::Consumer::consumeMessages(
647     bool isDrain, size_t* numConsumed) noexcept {
648   DestructorGuard dg(this);
649   uint32_t numProcessed = 0;
650   setActive(true);
651   SCOPE_EXIT {
652     if (queue_) {
653       queue_->syncSignalAndQueue();
654     }
655   };
656   SCOPE_EXIT { setActive(false, /* shouldLock = */ true); };
657   SCOPE_EXIT {
658     if (numConsumed != nullptr) {
659       *numConsumed = numProcessed;
660     }
661   };
662   while (true) {
663     // Now pop the message off of the queue.
664     //
665     // We have to manually acquire and release the spinlock here, rather than
666     // using SpinLockHolder since the MessageT has to be constructed while
667     // holding the spinlock and available after we release it.  SpinLockHolder
668     // unfortunately doesn't provide a release() method.  (We can't construct
669     // MessageT first since we have no guarantee that MessageT has a default
670     // constructor.
671     queue_->spinlock_.lock();
672     bool locked = true;
673
674     try {
675       if (UNLIKELY(queue_->queue_.empty())) {
676         // If there is no message, we've reached the end of the queue, return.
677         setActive(false);
678         queue_->spinlock_.unlock();
679         return;
680       }
681
682       // Pull a message off the queue.
683       auto& data = queue_->queue_.front();
684
685       MessageT msg(std::move(data.first));
686       RequestContextScopeGuard rctx(std::move(data.second));
687       queue_->queue_.pop_front();
688
689       // Check to see if the queue is empty now.
690       // We use this as an optimization to see if we should bother trying to
691       // loop again and read another message after invoking this callback.
692       bool wasEmpty = queue_->queue_.empty();
693       if (wasEmpty) {
694         setActive(false);
695       }
696
697       // Now unlock the spinlock before we invoke the callback.
698       queue_->spinlock_.unlock();
699       locked = false;
700
701       // Call the callback
702       bool callbackDestroyed = false;
703       CHECK(destroyedFlagPtr_ == nullptr);
704       destroyedFlagPtr_ = &callbackDestroyed;
705       messageAvailable(std::move(msg));
706       destroyedFlagPtr_ = nullptr;
707
708       // If the callback was destroyed before it returned, we are done
709       if (callbackDestroyed) {
710         return;
711       }
712
713       // If the callback is no longer installed, we are done.
714       if (queue_ == nullptr) {
715         return;
716       }
717
718       // If we have hit maxReadAtOnce_, we are done.
719       ++numProcessed;
720       if (!isDrain && maxReadAtOnce_ > 0 &&
721           numProcessed >= maxReadAtOnce_) {
722         return;
723       }
724
725       // If the queue was empty before we invoked the callback, it's probable
726       // that it is still empty now.  Just go ahead and return, rather than
727       // looping again and trying to re-read from the eventfd.  (If a new
728       // message had in fact arrived while we were invoking the callback, we
729       // will simply be woken up the next time around the event loop and will
730       // process the message then.)
731       if (wasEmpty) {
732         return;
733       }
734     } catch (const std::exception&) {
735       // This catch block is really just to handle the case where the MessageT
736       // constructor throws.  The messageAvailable() callback itself is
737       // declared as noexcept and should never throw.
738       //
739       // If the MessageT constructor does throw we try to handle it as best as
740       // we can, but we can't work miracles.  We will just ignore the error for
741       // now and return.  The next time around the event loop we will end up
742       // trying to read the message again.  If MessageT continues to throw we
743       // will never make forward progress and will keep trying each time around
744       // the event loop.
745       if (locked) {
746         // Unlock the spinlock.
747         queue_->spinlock_.unlock();
748       }
749
750       return;
751     }
752   }
753 }
754
755 template <typename MessageT>
756 void NotificationQueue<MessageT>::Consumer::init(
757     EventBase* eventBase,
758     NotificationQueue* queue) {
759   eventBase->dcheckIsInEventBaseThread();
760   assert(queue_ == nullptr);
761   assert(!isHandlerRegistered());
762   queue->checkPid();
763
764   base_ = eventBase;
765
766   queue_ = queue;
767
768   {
769     folly::SpinLockGuard g(queue_->spinlock_);
770     queue_->numConsumers_++;
771   }
772   queue_->ensureSignal();
773
774   if (queue_->eventfd_ >= 0) {
775     initHandler(eventBase, queue_->eventfd_);
776   } else {
777     initHandler(eventBase, queue_->pipeFds_[0]);
778   }
779 }
780
781 template <typename MessageT>
782 void NotificationQueue<MessageT>::Consumer::stopConsuming() {
783   if (queue_ == nullptr) {
784     assert(!isHandlerRegistered());
785     return;
786   }
787
788   {
789     folly::SpinLockGuard g(queue_->spinlock_);
790     queue_->numConsumers_--;
791     setActive(false);
792   }
793
794   assert(isHandlerRegistered());
795   unregisterHandler();
796   detachEventBase();
797   queue_ = nullptr;
798 }
799
800 template <typename MessageT>
801 bool NotificationQueue<MessageT>::Consumer::consumeUntilDrained(
802     size_t* numConsumed) noexcept {
803   DestructorGuard dg(this);
804   {
805     folly::SpinLockGuard g(queue_->spinlock_);
806     if (queue_->draining_) {
807       return false;
808     }
809     queue_->draining_ = true;
810   }
811   consumeMessages(true, numConsumed);
812   {
813     folly::SpinLockGuard g(queue_->spinlock_);
814     queue_->draining_ = false;
815   }
816   return true;
817 }
818
819 /**
820  * Creates a NotificationQueue::Consumer wrapping a function object
821  * Modeled after AsyncTimeout::make
822  *
823  */
824
825 namespace detail {
826
827 template <typename MessageT, typename TCallback>
828 struct notification_queue_consumer_wrapper
829     : public NotificationQueue<MessageT>::Consumer {
830
831   template <typename UCallback>
832   explicit notification_queue_consumer_wrapper(UCallback&& callback)
833       : callback_(std::forward<UCallback>(callback)) {}
834
835   // we are being stricter here and requiring noexcept for callback
836   void messageAvailable(MessageT&& message) noexcept override {
837     static_assert(
838       noexcept(std::declval<TCallback>()(std::forward<MessageT>(message))),
839       "callback must be declared noexcept, e.g.: `[]() noexcept {}`"
840     );
841
842     callback_(std::forward<MessageT>(message));
843   }
844
845  private:
846   TCallback callback_;
847 };
848
849 } // namespace detail
850
851 template <typename MessageT>
852 template <typename TCallback>
853 std::unique_ptr<typename NotificationQueue<MessageT>::Consumer,
854                 DelayedDestruction::Destructor>
855 NotificationQueue<MessageT>::Consumer::make(TCallback&& callback) {
856   return std::unique_ptr<NotificationQueue<MessageT>::Consumer,
857                          DelayedDestruction::Destructor>(
858       new detail::notification_queue_consumer_wrapper<
859           MessageT,
860           typename std::decay<TCallback>::type>(
861           std::forward<TCallback>(callback)));
862 }
863
864 } // namespace folly