Revise API to load cert/key in SSLContext.
[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 #ifdef FOLLY_HAVE_EVENTFD
270     if (fdType == FdType::EVENTFD) {
271       eventfd_ = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
272       if (eventfd_ == -1) {
273         if (errno == ENOSYS || errno == EINVAL) {
274           // eventfd not availalble
275           LOG(ERROR) << "failed to create eventfd for NotificationQueue: "
276                      << errno << ", falling back to pipe mode (is your kernel "
277                      << "> 2.6.30?)";
278           fdType = FdType::PIPE;
279         } else {
280           // some other error
281           folly::throwSystemError("Failed to create eventfd for "
282                                   "NotificationQueue", errno);
283         }
284       }
285     }
286 #endif
287     if (fdType == FdType::PIPE) {
288       if (pipe(pipeFds_)) {
289         folly::throwSystemError("Failed to create pipe for NotificationQueue",
290                                 errno);
291       }
292       try {
293         // put both ends of the pipe into non-blocking mode
294         if (fcntl(pipeFds_[0], F_SETFL, O_RDONLY | O_NONBLOCK) != 0) {
295           folly::throwSystemError("failed to put NotificationQueue pipe read "
296                                   "endpoint into non-blocking mode", errno);
297         }
298         if (fcntl(pipeFds_[1], F_SETFL, O_WRONLY | O_NONBLOCK) != 0) {
299           folly::throwSystemError("failed to put NotificationQueue pipe write "
300                                   "endpoint into non-blocking mode", errno);
301         }
302       } catch (...) {
303         ::close(pipeFds_[0]);
304         ::close(pipeFds_[1]);
305         throw;
306       }
307     }
308   }
309
310   ~NotificationQueue() {
311     if (eventfd_ >= 0) {
312       ::close(eventfd_);
313       eventfd_ = -1;
314     }
315     if (pipeFds_[0] >= 0) {
316       ::close(pipeFds_[0]);
317       pipeFds_[0] = -1;
318     }
319     if (pipeFds_[1] >= 0) {
320       ::close(pipeFds_[1]);
321       pipeFds_[1] = -1;
322     }
323   }
324
325   /**
326    * Set the advisory maximum queue size.
327    *
328    * This maximum queue size affects calls to tryPutMessage().  Message
329    * producers can still use the putMessage() call to unconditionally put a
330    * message on the queue, ignoring the configured maximum queue size.  This
331    * can cause the queue size to exceed the configured maximum.
332    */
333   void setMaxQueueSize(uint32_t max) {
334     advisoryMaxQueueSize_ = max;
335   }
336
337   /**
338    * Attempt to put a message on the queue if the queue is not already full.
339    *
340    * If the queue is full, a std::overflow_error will be thrown.  The
341    * setMaxQueueSize() function controls the maximum queue size.
342    *
343    * If the queue is currently draining, an std::runtime_error will be thrown.
344    *
345    * This method may contend briefly on a spinlock if many threads are
346    * concurrently accessing the queue, but for all intents and purposes it will
347    * immediately place the message on the queue and return.
348    *
349    * tryPutMessage() may throw std::bad_alloc if memory allocation fails, and
350    * may throw any other exception thrown by the MessageT move/copy
351    * constructor.
352    */
353   template <typename MessageTT>
354   void tryPutMessage(MessageTT&& message) {
355     putMessageImpl(std::forward<MessageTT>(message), advisoryMaxQueueSize_);
356   }
357
358   /**
359    * No-throw versions of the above.  Instead returns true on success, false on
360    * failure.
361    *
362    * Only std::overflow_error (the common exception case) and std::runtime_error
363    * (which indicates that the queue is being drained) are prevented from being
364    * thrown. User code must still catch std::bad_alloc errors.
365    */
366   template <typename MessageTT>
367   bool tryPutMessageNoThrow(MessageTT&& message) {
368     return putMessageImpl(
369         std::forward<MessageTT>(message), advisoryMaxQueueSize_, false);
370   }
371
372   /**
373    * Unconditionally put a message on the queue.
374    *
375    * This method is like tryPutMessage(), but ignores the maximum queue size
376    * and always puts the message on the queue, even if the maximum queue size
377    * would be exceeded.
378    *
379    * putMessage() may throw
380    *   - std::bad_alloc if memory allocation fails, and may
381    *   - std::runtime_error if the queue is currently draining
382    *   - any other exception thrown by the MessageT move/copy constructor.
383    */
384   template <typename MessageTT>
385   void putMessage(MessageTT&& message) {
386     putMessageImpl(std::forward<MessageTT>(message), 0);
387   }
388
389   /**
390    * Put several messages on the queue.
391    */
392   template <typename InputIteratorT>
393   void putMessages(InputIteratorT first, InputIteratorT last) {
394     typedef typename std::iterator_traits<InputIteratorT>::iterator_category
395       IterCategory;
396     putMessagesImpl(first, last, IterCategory());
397   }
398
399   /**
400    * Try to immediately pull a message off of the queue, without blocking.
401    *
402    * If a message is immediately available, the result parameter will be
403    * updated to contain the message contents and true will be returned.
404    *
405    * If no message is available, false will be returned and result will be left
406    * unmodified.
407    */
408   bool tryConsume(MessageT& result) {
409     SCOPE_EXIT { syncSignalAndQueue(); };
410
411     checkPid();
412
413     folly::SpinLockGuard g(spinlock_);
414
415     if (UNLIKELY(queue_.empty())) {
416       return false;
417     }
418
419     auto& data = queue_.front();
420     result = std::move(data.first);
421     RequestContext::setContext(std::move(data.second));
422
423     queue_.pop_front();
424
425     return true;
426   }
427
428   size_t size() const {
429     folly::SpinLockGuard g(spinlock_);
430     return queue_.size();
431   }
432
433   /**
434    * Check that the NotificationQueue is being used from the correct process.
435    *
436    * If you create a NotificationQueue in one process, then fork, and try to
437    * send messages to the queue from the child process, you're going to have a
438    * bad time.  Unfortunately users have (accidentally) run into this.
439    *
440    * Because we use an eventfd/pipe, the child process can actually signal the
441    * parent process that an event is ready.  However, it can't put anything on
442    * the parent's queue, so the parent wakes up and finds an empty queue.  This
443    * check ensures that we catch the problem in the misbehaving child process
444    * code, and crash before signalling the parent process.
445    */
446   void checkPid() const { CHECK_EQ(pid_, pid_t(getpid())); }
447
448  private:
449   // Forbidden copy constructor and assignment operator
450   NotificationQueue(NotificationQueue const &) = delete;
451   NotificationQueue& operator=(NotificationQueue const &) = delete;
452
453   inline bool checkQueueSize(size_t maxSize, bool throws=true) const {
454     DCHECK(0 == spinlock_.try_lock());
455     if (maxSize > 0 && queue_.size() >= maxSize) {
456       if (throws) {
457         throw std::overflow_error("unable to add message to NotificationQueue: "
458                                   "queue is full");
459       }
460       return false;
461     }
462     return true;
463   }
464
465   inline bool checkDraining(bool throws=true) {
466     if (UNLIKELY(draining_ && throws)) {
467       throw std::runtime_error("queue is draining, cannot add message");
468     }
469     return draining_;
470   }
471
472 #ifdef __ANDROID__
473   // TODO 10860938 Remove after figuring out crash
474   mutable std::atomic<int> eventBytes_{0};
475   mutable std::atomic<int> maxEventBytes_{0};
476 #endif
477
478   void ensureSignalLocked() const {
479     // semantics: empty fd == empty queue <=> !signal_
480     if (signal_) {
481       return;
482     }
483
484     ssize_t bytes_written = 0;
485     size_t bytes_expected = 0;
486
487     do {
488       if (eventfd_ >= 0) {
489         // eventfd(2) dictates that we must write a 64-bit integer
490         uint64_t signal = 1;
491         bytes_expected = sizeof(signal);
492         bytes_written = ::write(eventfd_, &signal, bytes_expected);
493       } else {
494         uint8_t signal = 1;
495         bytes_expected = sizeof(signal);
496         bytes_written = ::write(pipeFds_[1], &signal, bytes_expected);
497       }
498     } while (bytes_written == -1 && errno == EINTR);
499
500 #ifdef __ANDROID__
501     if (bytes_written > 0) {
502       eventBytes_ += bytes_written;
503       maxEventBytes_ = std::max((int)maxEventBytes_, (int)eventBytes_);
504     }
505 #endif
506
507     if (bytes_written == ssize_t(bytes_expected)) {
508       signal_ = true;
509     } else {
510 #ifdef __ANDROID__
511       LOG(ERROR) << "NotificationQueue Write Error=" << errno
512                  << " bytesInPipe=" << eventBytes_
513                  << " maxInPipe=" << maxEventBytes_ << " queue=" << size();
514 #endif
515       folly::throwSystemError("failed to signal NotificationQueue after "
516                               "write", errno);
517     }
518   }
519
520   void drainSignalsLocked() {
521     ssize_t bytes_read = 0;
522     if (eventfd_ > 0) {
523       uint64_t message;
524       bytes_read = readNoInt(eventfd_, &message, sizeof(message));
525       CHECK(bytes_read != -1 || errno == EAGAIN);
526     } else {
527       // There should only be one byte in the pipe. To avoid potential leaks we still drain.
528       uint8_t message[32];
529       ssize_t result;
530       while ((result = readNoInt(pipeFds_[0], &message, sizeof(message))) != -1) {
531         bytes_read += result;
532       }
533       CHECK(result == -1 && errno == EAGAIN);
534       LOG_IF(ERROR, bytes_read > 1)
535         << "[NotificationQueue] Unexpected state while draining pipe: bytes_read="
536         << bytes_read << " bytes, expected <= 1";
537     }
538     LOG_IF(ERROR, (signal_ && bytes_read == 0) || (!signal_ && bytes_read > 0))
539       << "[NotificationQueue] Unexpected state while draining signals: signal_="
540       << signal_ << " bytes_read=" << bytes_read;
541
542     signal_ = false;
543
544 #ifdef __ANDROID__
545     if (bytes_read > 0) {
546       eventBytes_ -= bytes_read;
547     }
548 #endif
549   }
550
551   void ensureSignal() const {
552     folly::SpinLockGuard g(spinlock_);
553     ensureSignalLocked();
554   }
555
556   void syncSignalAndQueue() {
557     folly::SpinLockGuard g(spinlock_);
558
559     if (queue_.empty()) {
560       drainSignalsLocked();
561     } else {
562       ensureSignalLocked();
563     }
564   }
565
566   template <typename MessageTT>
567   bool putMessageImpl(MessageTT&& message, size_t maxSize, bool throws = true) {
568     checkPid();
569     bool signal = false;
570     {
571       folly::SpinLockGuard g(spinlock_);
572       if (checkDraining(throws) || !checkQueueSize(maxSize, throws)) {
573         return false;
574       }
575       // We only need to signal an event if not all consumers are
576       // awake.
577       if (numActiveConsumers_ < numConsumers_) {
578         signal = true;
579       }
580       queue_.emplace_back(
581           std::forward<MessageTT>(message), RequestContext::saveContext());
582       if (signal) {
583         ensureSignalLocked();
584       }
585     }
586     return true;
587   }
588
589   template <typename InputIteratorT>
590   void putMessagesImpl(InputIteratorT first, InputIteratorT last,
591                        std::input_iterator_tag) {
592     checkPid();
593     bool signal = false;
594     size_t numAdded = 0;
595     {
596       folly::SpinLockGuard g(spinlock_);
597       checkDraining();
598       while (first != last) {
599         queue_.emplace_back(*first, RequestContext::saveContext());
600         ++first;
601         ++numAdded;
602       }
603       if (numActiveConsumers_ < numConsumers_) {
604         signal = true;
605       }
606       if (signal) {
607         ensureSignalLocked();
608       }
609     }
610   }
611
612   mutable folly::SpinLock spinlock_;
613   mutable bool signal_{false};
614   int eventfd_;
615   int pipeFds_[2]; // to fallback to on older/non-linux systems
616   uint32_t advisoryMaxQueueSize_;
617   pid_t pid_;
618   std::deque<std::pair<MessageT, std::shared_ptr<RequestContext>>> queue_;
619   int numConsumers_{0};
620   std::atomic<int> numActiveConsumers_{0};
621   bool draining_{false};
622 };
623
624 template <typename MessageT>
625 void NotificationQueue<MessageT>::Consumer::destroy() {
626   // If we are in the middle of a call to handlerReady(), destroyedFlagPtr_
627   // will be non-nullptr.  Mark the value that it points to, so that
628   // handlerReady() will know the callback is destroyed, and that it cannot
629   // access any member variables anymore.
630   if (destroyedFlagPtr_) {
631     *destroyedFlagPtr_ = true;
632   }
633   stopConsuming();
634   DelayedDestruction::destroy();
635 }
636
637 template <typename MessageT>
638 void NotificationQueue<MessageT>::Consumer::handlerReady(uint16_t /*events*/)
639     noexcept {
640   consumeMessages(false);
641 }
642
643 template <typename MessageT>
644 void NotificationQueue<MessageT>::Consumer::consumeMessages(
645     bool isDrain, size_t* numConsumed) noexcept {
646   DestructorGuard dg(this);
647   uint32_t numProcessed = 0;
648   setActive(true);
649   SCOPE_EXIT {
650     if (queue_) {
651       queue_->syncSignalAndQueue();
652     }
653   };
654   SCOPE_EXIT { setActive(false, /* shouldLock = */ true); };
655   SCOPE_EXIT {
656     if (numConsumed != nullptr) {
657       *numConsumed = numProcessed;
658     }
659   };
660   while (true) {
661     // Now pop the message off of the queue.
662     //
663     // We have to manually acquire and release the spinlock here, rather than
664     // using SpinLockHolder since the MessageT has to be constructed while
665     // holding the spinlock and available after we release it.  SpinLockHolder
666     // unfortunately doesn't provide a release() method.  (We can't construct
667     // MessageT first since we have no guarantee that MessageT has a default
668     // constructor.
669     queue_->spinlock_.lock();
670     bool locked = true;
671
672     try {
673       if (UNLIKELY(queue_->queue_.empty())) {
674         // If there is no message, we've reached the end of the queue, return.
675         setActive(false);
676         queue_->spinlock_.unlock();
677         return;
678       }
679
680       // Pull a message off the queue.
681       auto& data = queue_->queue_.front();
682
683       MessageT msg(std::move(data.first));
684       RequestContextScopeGuard rctx(std::move(data.second));
685       queue_->queue_.pop_front();
686
687       // Check to see if the queue is empty now.
688       // We use this as an optimization to see if we should bother trying to
689       // loop again and read another message after invoking this callback.
690       bool wasEmpty = queue_->queue_.empty();
691       if (wasEmpty) {
692         setActive(false);
693       }
694
695       // Now unlock the spinlock before we invoke the callback.
696       queue_->spinlock_.unlock();
697       locked = false;
698
699       // Call the callback
700       bool callbackDestroyed = false;
701       CHECK(destroyedFlagPtr_ == nullptr);
702       destroyedFlagPtr_ = &callbackDestroyed;
703       messageAvailable(std::move(msg));
704       destroyedFlagPtr_ = nullptr;
705
706       // If the callback was destroyed before it returned, we are done
707       if (callbackDestroyed) {
708         return;
709       }
710
711       // If the callback is no longer installed, we are done.
712       if (queue_ == nullptr) {
713         return;
714       }
715
716       // If we have hit maxReadAtOnce_, we are done.
717       ++numProcessed;
718       if (!isDrain && maxReadAtOnce_ > 0 &&
719           numProcessed >= maxReadAtOnce_) {
720         return;
721       }
722
723       // If the queue was empty before we invoked the callback, it's probable
724       // that it is still empty now.  Just go ahead and return, rather than
725       // looping again and trying to re-read from the eventfd.  (If a new
726       // message had in fact arrived while we were invoking the callback, we
727       // will simply be woken up the next time around the event loop and will
728       // process the message then.)
729       if (wasEmpty) {
730         return;
731       }
732     } catch (const std::exception&) {
733       // This catch block is really just to handle the case where the MessageT
734       // constructor throws.  The messageAvailable() callback itself is
735       // declared as noexcept and should never throw.
736       //
737       // If the MessageT constructor does throw we try to handle it as best as
738       // we can, but we can't work miracles.  We will just ignore the error for
739       // now and return.  The next time around the event loop we will end up
740       // trying to read the message again.  If MessageT continues to throw we
741       // will never make forward progress and will keep trying each time around
742       // the event loop.
743       if (locked) {
744         // Unlock the spinlock.
745         queue_->spinlock_.unlock();
746       }
747
748       return;
749     }
750   }
751 }
752
753 template <typename MessageT>
754 void NotificationQueue<MessageT>::Consumer::init(
755     EventBase* eventBase,
756     NotificationQueue* queue) {
757   eventBase->dcheckIsInEventBaseThread();
758   assert(queue_ == nullptr);
759   assert(!isHandlerRegistered());
760   queue->checkPid();
761
762   base_ = eventBase;
763
764   queue_ = queue;
765
766   {
767     folly::SpinLockGuard g(queue_->spinlock_);
768     queue_->numConsumers_++;
769   }
770   queue_->ensureSignal();
771
772   if (queue_->eventfd_ >= 0) {
773     initHandler(eventBase, queue_->eventfd_);
774   } else {
775     initHandler(eventBase, queue_->pipeFds_[0]);
776   }
777 }
778
779 template <typename MessageT>
780 void NotificationQueue<MessageT>::Consumer::stopConsuming() {
781   if (queue_ == nullptr) {
782     assert(!isHandlerRegistered());
783     return;
784   }
785
786   {
787     folly::SpinLockGuard g(queue_->spinlock_);
788     queue_->numConsumers_--;
789     setActive(false);
790   }
791
792   assert(isHandlerRegistered());
793   unregisterHandler();
794   detachEventBase();
795   queue_ = nullptr;
796 }
797
798 template <typename MessageT>
799 bool NotificationQueue<MessageT>::Consumer::consumeUntilDrained(
800     size_t* numConsumed) noexcept {
801   DestructorGuard dg(this);
802   {
803     folly::SpinLockGuard g(queue_->spinlock_);
804     if (queue_->draining_) {
805       return false;
806     }
807     queue_->draining_ = true;
808   }
809   consumeMessages(true, numConsumed);
810   {
811     folly::SpinLockGuard g(queue_->spinlock_);
812     queue_->draining_ = false;
813   }
814   return true;
815 }
816
817 /**
818  * Creates a NotificationQueue::Consumer wrapping a function object
819  * Modeled after AsyncTimeout::make
820  *
821  */
822
823 namespace detail {
824
825 template <typename MessageT, typename TCallback>
826 struct notification_queue_consumer_wrapper
827     : public NotificationQueue<MessageT>::Consumer {
828
829   template <typename UCallback>
830   explicit notification_queue_consumer_wrapper(UCallback&& callback)
831       : callback_(std::forward<UCallback>(callback)) {}
832
833   // we are being stricter here and requiring noexcept for callback
834   void messageAvailable(MessageT&& message) noexcept override {
835     static_assert(
836       noexcept(std::declval<TCallback>()(std::forward<MessageT>(message))),
837       "callback must be declared noexcept, e.g.: `[]() noexcept {}`"
838     );
839
840     callback_(std::forward<MessageT>(message));
841   }
842
843  private:
844   TCallback callback_;
845 };
846
847 } // namespace detail
848
849 template <typename MessageT>
850 template <typename TCallback>
851 std::unique_ptr<typename NotificationQueue<MessageT>::Consumer,
852                 DelayedDestruction::Destructor>
853 NotificationQueue<MessageT>::Consumer::make(TCallback&& callback) {
854   return std::unique_ptr<NotificationQueue<MessageT>::Consumer,
855                          DelayedDestruction::Destructor>(
856       new detail::notification_queue_consumer_wrapper<
857           MessageT,
858           typename std::decay<TCallback>::type>(
859           std::forward<TCallback>(callback)));
860 }
861
862 } // namespace folly