Using type-tags for test SingletonVaults
[folly.git] / folly / experimental / Singleton.h
1 /*
2  * Copyright 2014 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 // SingletonVault - a library to manage the creation and destruction
18 // of interdependent singletons.
19 //
20 // Basic usage of this class is very simple; suppose you have a class
21 // called MyExpensiveService, and you only want to construct one (ie,
22 // it's a singleton), but you only want to construct it if it is used.
23 //
24 // In your .h file:
25 // class MyExpensiveService { ... };
26 //
27 // In your .cpp file:
28 // namespace { folly::Singleton<MyExpensiveService> the_singleton; }
29 //
30 // Code can access it via:
31 //
32 // MyExpensiveService* instance = Singleton<MyExpensiveService>::get();
33 // or
34 // std::weak_ptr<MyExpensiveService> instance =
35 //     Singleton<MyExpensiveService>::get_weak();
36 //
37 // Within same compilation unit you should directly access it by the variable
38 // defining the singleton via get_fast()/get_weak_fast(), and even treat that
39 // variable like a smart pointer (dereferencing it or using the -> operator):
40 //
41 // MyExpensiveService* instance = the_singleton.get_fast();
42 // or
43 // std::weak_ptr<MyExpensiveService> instance = the_singleton.get_weak_fast();
44 // or even
45 // the_singleton->doSomething();
46 //
47 // *_fast() accessors are faster than static accessors, and have performance
48 // similar to Meyers singletons/static objects.
49 //
50 // Please note, however, that all non-weak_ptr interfaces are
51 // inherently subject to races with destruction.  Use responsibly.
52 //
53 // The singleton will be created on demand.  If the constructor for
54 // MyExpensiveService actually makes use of *another* Singleton, then
55 // the right thing will happen -- that other singleton will complete
56 // construction before get() returns.  However, in the event of a
57 // circular dependency, a runtime error will occur.
58 //
59 // You can have multiple singletons of the same underlying type, but
60 // each must be given a unique tag. If no tag is specified - default tag is used
61 //
62 // namespace {
63 // struct Tag1 {};
64 // struct Tag2 {};
65 // folly::Singleton<MyExpensiveService> s_default();
66 // folly::Singleton<MyExpensiveService, Tag1> s1();
67 // folly::Singleton<MyExpensiveService, Tag2> s2();
68 // }
69 // ...
70 // MyExpensiveService* svc_default = s_default.get_fast();
71 // MyExpensiveService* svc1 = s1.get_fast();
72 // MyExpensiveService* svc2 = s2.get_fast();
73 //
74 // By default, the singleton instance is constructed via new and
75 // deleted via delete, but this is configurable:
76 //
77 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
78 //                                                                destroy); }
79 //
80 // Where create and destroy are functions, Singleton<T>::CreateFunc
81 // Singleton<T>::TeardownFunc.
82 //
83 // What if you need to destroy all of your singletons?  Say, some of
84 // your singletons manage threads, but you need to fork?  Or your unit
85 // test wants to clean up all global state?  Then you can call
86 // SingletonVault::singleton()->destroyInstances(), which invokes the
87 // TeardownFunc for each singleton, in the reverse order they were
88 // created.  It is your responsibility to ensure your singletons can
89 // handle cases where the singletons they depend on go away, however.
90 // Singletons won't be recreated after destroyInstances call. If you
91 // want to re-enable singleton creation (say after fork was called) you
92 // should call reenableInstances.
93
94 #pragma once
95 #include <folly/Baton.h>
96 #include <folly/Exception.h>
97 #include <folly/Hash.h>
98 #include <folly/Memory.h>
99 #include <folly/RWSpinLock.h>
100 #include <folly/Demangle.h>
101 #include <folly/io/async/Request.h>
102
103 #include <algorithm>
104 #include <vector>
105 #include <mutex>
106 #include <thread>
107 #include <condition_variable>
108 #include <string>
109 #include <unordered_map>
110 #include <functional>
111 #include <typeinfo>
112 #include <typeindex>
113
114 #include <glog/logging.h>
115
116 namespace folly {
117
118 // For actual usage, please see the Singleton<T> class at the bottom
119 // of this file; that is what you will actually interact with.
120
121 // SingletonVault is the class that manages singleton instances.  It
122 // is unaware of the underlying types of singletons, and simply
123 // manages lifecycles and invokes CreateFunc and TeardownFunc when
124 // appropriate.  In general, you won't need to interact with the
125 // SingletonVault itself.
126 //
127 // A vault goes through a few stages of life:
128 //
129 //   1. Registration phase; singletons can be registered, but no
130 //      singleton can be created.
131 //   2. registrationComplete() has been called; singletons can no
132 //      longer be registered, but they can be created.
133 //   3. A vault can return to stage 1 when destroyInstances is called.
134 //
135 // In general, you don't need to worry about any of the above; just
136 // ensure registrationComplete() is called near the top of your main()
137 // function, otherwise no singletons can be instantiated.
138
139 namespace detail {
140
141 struct DefaultTag {};
142
143 // A TypeDescriptor is the unique handle for a given singleton.  It is
144 // a combinaiton of the type and of the optional name, and is used as
145 // a key in unordered_maps.
146 class TypeDescriptor {
147  public:
148   TypeDescriptor(const std::type_info& ti,
149                  const std::type_info& tag_ti)
150       : ti_(ti), tag_ti_(tag_ti) {
151   }
152
153   TypeDescriptor(const TypeDescriptor& other)
154       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
155   }
156
157   TypeDescriptor& operator=(const TypeDescriptor& other) {
158     if (this != &other) {
159       ti_ = other.ti_;
160       tag_ti_ = other.tag_ti_;
161     }
162
163     return *this;
164   }
165
166   std::string prettyName() const {
167     auto ret = demangle(ti_.name());
168     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
169       ret += "/";
170       ret += demangle(tag_ti_.name());
171     }
172     return ret.toStdString();
173   }
174
175   friend class TypeDescriptorHasher;
176
177   bool operator==(const TypeDescriptor& other) const {
178     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
179   }
180
181  private:
182   std::type_index ti_;
183   std::type_index tag_ti_;
184 };
185
186 class TypeDescriptorHasher {
187  public:
188   size_t operator()(const TypeDescriptor& ti) const {
189     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
190   }
191 };
192
193 enum class SingletonEntryState {
194   Dead,
195   Living,
196 };
197
198 // An actual instance of a singleton, tracking the instance itself,
199 // its state as described above, and the create and teardown
200 // functions.
201 struct SingletonEntry {
202   typedef std::function<void(void*)> TeardownFunc;
203   typedef std::function<void*(void)> CreateFunc;
204
205   SingletonEntry(CreateFunc c, TeardownFunc t) :
206       create(std::move(c)), teardown(std::move(t)) {}
207
208   // mutex protects the entire entry during construction/destruction
209   std::mutex mutex;
210
211   // State of the singleton entry. If state is Living, instance_ptr and
212   // instance_weak can be safely accessed w/o synchronization.
213   std::atomic<SingletonEntryState> state{SingletonEntryState::Dead};
214
215   // the thread creating the singleton (only valid while creating an object)
216   std::thread::id creating_thread;
217
218   // The singleton itself and related functions.
219
220   // holds a shared_ptr to singleton instance, set when state is changed from
221   // Dead to Living. Reset when state is changed from Living to Dead.
222   std::shared_ptr<void> instance;
223   // weak_ptr to the singleton instance, set when state is changed from Dead
224   // to Living. We never write to this object after initialization, so it is
225   // safe to read it from different threads w/o synchronization if we know
226   // that state is set to Living
227   std::weak_ptr<void> instance_weak;
228   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
229   std::shared_ptr<folly::Baton<>> destroy_baton;
230   void* instance_ptr = nullptr;
231   CreateFunc create = nullptr;
232   TeardownFunc teardown = nullptr;
233
234   SingletonEntry(const SingletonEntry&) = delete;
235   SingletonEntry& operator=(const SingletonEntry&) = delete;
236   SingletonEntry& operator=(SingletonEntry&&) = delete;
237   SingletonEntry(SingletonEntry&&) = delete;
238 };
239
240 }
241
242 class SingletonVault {
243  public:
244   enum class Type { Strict, Relaxed };
245
246   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
247
248   // Destructor is only called by unit tests to check destroyInstances.
249   ~SingletonVault();
250
251   typedef std::function<void(void*)> TeardownFunc;
252   typedef std::function<void*(void)> CreateFunc;
253
254   // Ensure that Singleton has not been registered previously and that
255   // registration is not complete. If validations succeeds,
256   // register a singleton of a given type with the create and teardown
257   // functions.
258   detail::SingletonEntry& registerSingleton(detail::TypeDescriptor type,
259                                             CreateFunc create,
260                                             TeardownFunc teardown) {
261     RWSpinLock::ReadHolder rh(&stateMutex_);
262
263     stateCheck(SingletonVaultState::Running);
264
265     if (UNLIKELY(registrationComplete_)) {
266       throw std::logic_error(
267         "Registering singleton after registrationComplete().");
268     }
269
270     RWSpinLock::ReadHolder rhMutex(&mutex_);
271     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
272
273     return registerSingletonImpl(type, create, teardown);
274   }
275
276   // Register a singleton of a given type with the create and teardown
277   // functions. Must hold reader locks on stateMutex_ and mutex_
278   // when invoking this function.
279   detail::SingletonEntry& registerSingletonImpl(detail::TypeDescriptor type,
280                              CreateFunc create,
281                              TeardownFunc teardown) {
282     RWSpinLock::UpgradedHolder wh(&mutex_);
283
284     singletons_[type] =
285       folly::make_unique<detail::SingletonEntry>(std::move(create),
286                                                  std::move(teardown));
287     return *singletons_[type];
288   }
289
290   /* Register a mock singleton used for testing of singletons which
291    * depend on other private singletons which cannot be otherwise injected.
292    */
293   void registerMockSingleton(detail::TypeDescriptor type,
294                              CreateFunc create,
295                              TeardownFunc teardown) {
296     RWSpinLock::ReadHolder rh(&stateMutex_);
297     RWSpinLock::ReadHolder rhMutex(&mutex_);
298
299     auto entry_it = singletons_.find(type);
300     // Mock singleton registration, we allow existing entry to be overridden.
301     if (entry_it == singletons_.end()) {
302       throw std::logic_error(
303         "Registering mock before the singleton was registered");
304     }
305
306     {
307       auto& entry = *(entry_it->second);
308       // Destroy existing singleton.
309       std::lock_guard<std::mutex> entry_lg(entry.mutex);
310
311       destroyInstance(entry_it);
312       entry.create = create;
313       entry.teardown = teardown;
314     }
315
316     // Upgrade to write lock.
317     RWSpinLock::UpgradedHolder whMutex(&mutex_);
318
319     // Remove singleton from creation order and singletons_.
320     // This happens only in test code and not frequently.
321     // Performance is not a concern here.
322     auto creation_order_it = std::find(
323       creation_order_.begin(),
324       creation_order_.end(),
325       type);
326     if (creation_order_it != creation_order_.end()) {
327       creation_order_.erase(creation_order_it);
328     }
329   }
330
331   // Mark registration is complete; no more singletons can be
332   // registered at this point.
333   void registrationComplete() {
334     RequestContext::getStaticContext();
335     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
336
337     RWSpinLock::WriteHolder wh(&stateMutex_);
338
339     stateCheck(SingletonVaultState::Running);
340
341     if (type_ == Type::Strict) {
342       for (const auto& id_singleton_entry: singletons_) {
343         const auto& singleton_entry = *id_singleton_entry.second;
344         if (singleton_entry.state != detail::SingletonEntryState::Dead) {
345           throw std::runtime_error(
346             "Singleton created before registration was complete.");
347         }
348       }
349     }
350
351     registrationComplete_ = true;
352   }
353
354   // Destroy all singletons; when complete, the vault can't create
355   // singletons once again until reenableInstances() is called.
356   void destroyInstances();
357
358   // Enable re-creating singletons after destroyInstances() was called.
359   void reenableInstances();
360
361   // Retrieve a singleton from the vault, creating it if necessary.
362   std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
363     auto entry = get_entry_create(type);
364     return entry->instance_weak;
365   }
366
367   // This function is inherently racy since we don't hold the
368   // shared_ptr that contains the Singleton.  It is the caller's
369   // responsibility to be sane with this, but it is preferable to use
370   // the weak_ptr interface for true safety.
371   void* get_ptr(detail::TypeDescriptor type) {
372     auto entry = get_entry_create(type);
373     if (UNLIKELY(entry->instance_weak.expired())) {
374       throw std::runtime_error(
375         "Raw pointer to a singleton requested after its destruction.");
376     }
377     return entry->instance_ptr;
378   }
379
380   // For testing; how many registered and living singletons we have.
381   size_t registeredSingletonCount() const {
382     RWSpinLock::ReadHolder rh(&mutex_);
383
384     return singletons_.size();
385   }
386
387   size_t livingSingletonCount() const {
388     RWSpinLock::ReadHolder rh(&mutex_);
389
390     size_t ret = 0;
391     for (const auto& p : singletons_) {
392       if (p.second->state == detail::SingletonEntryState::Living) {
393         ++ret;
394       }
395     }
396
397     return ret;
398   }
399
400   // A well-known vault; you can actually have others, but this is the
401   // default.
402   static SingletonVault* singleton() {
403     return singleton<>();
404   }
405
406   // Gets singleton vault for any Tag. Non-default tag should be used in unit
407   // tests only.
408   template <typename VaultTag = detail::DefaultTag>
409   static SingletonVault* singleton() {
410     static SingletonVault* vault = new SingletonVault();
411     return vault;
412   }
413
414  private:
415   // The two stages of life for a vault, as mentioned in the class comment.
416   enum class SingletonVaultState {
417     Running,
418     Quiescing,
419   };
420
421   // Each singleton in the vault can be in two states: dead
422   // (registered but never created), living (CreateFunc returned an instance).
423
424   void stateCheck(SingletonVaultState expected,
425                   const char* msg="Unexpected singleton state change") {
426     if (expected != state_) {
427         throw std::logic_error(msg);
428     }
429   }
430
431   // This method only matters if registrationComplete() is never called.
432   // Otherwise destroyInstances is scheduled to be executed atexit.
433   //
434   // Initializes static object, which calls destroyInstances on destruction.
435   // Used to have better deletion ordering with singleton not managed by
436   // folly::Singleton. The desruction will happen in the following order:
437   // 1. Singletons, not managed by folly::Singleton, which were created after
438   //    any of the singletons managed by folly::Singleton was requested.
439   // 2. All singletons managed by folly::Singleton
440   // 3. Singletons, not managed by folly::Singleton, which were created before
441   //    any of the singletons managed by folly::Singleton was requested.
442   static void scheduleDestroyInstances();
443
444   detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
445     RWSpinLock::ReadHolder rh(&mutex_);
446
447     auto it = singletons_.find(type);
448     if (it == singletons_.end()) {
449       throw std::out_of_range(std::string("non-existent singleton: ") +
450                               type.prettyName());
451     }
452
453     return it->second.get();
454   }
455
456   // Get a pointer to the living SingletonEntry for the specified
457   // type.  The singleton is created as part of this function, if
458   // necessary.
459   detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
460     auto entry = get_entry(type);
461
462     if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
463       return entry;
464     }
465
466     // There's no synchronization here, so we may not see the current value
467     // for creating_thread if it was set by other thread, but we only care about
468     // it if it was set by current thread anyways.
469     if (entry->creating_thread == std::this_thread::get_id()) {
470       throw std::out_of_range(std::string("circular singleton dependency: ") +
471                               type.prettyName());
472     }
473
474     std::lock_guard<std::mutex> entry_lock(entry->mutex);
475
476     if (entry->state == detail::SingletonEntryState::Living) {
477       return entry;
478     }
479
480     entry->creating_thread = std::this_thread::get_id();
481
482     RWSpinLock::ReadHolder rh(&stateMutex_);
483     if (state_ == SingletonVaultState::Quiescing) {
484       entry->creating_thread = std::thread::id();
485       return entry;
486     }
487
488     auto destroy_baton = std::make_shared<folly::Baton<>>();
489     auto teardown = entry->teardown;
490
491     // Can't use make_shared -- no support for a custom deleter, sadly.
492     auto instance = std::shared_ptr<void>(
493       entry->create(),
494       [destroy_baton, teardown](void* instance_ptr) mutable {
495         teardown(instance_ptr);
496         destroy_baton->post();
497       });
498
499     // We should schedule destroyInstances() only after the singleton was
500     // created. This will ensure it will be destroyed before singletons,
501     // not managed by folly::Singleton, which were initialized in its
502     // constructor
503     scheduleDestroyInstances();
504
505     entry->instance = instance;
506     entry->instance_weak = instance;
507     entry->instance_ptr = instance.get();
508     entry->creating_thread = std::thread::id();
509     entry->destroy_baton = std::move(destroy_baton);
510
511     // This has to be the last step, because once state is Living other threads
512     // may access instance and instance_weak w/o synchronization.
513     entry->state.store(detail::SingletonEntryState::Living);
514
515     {
516       RWSpinLock::WriteHolder wh(&mutex_);
517       creation_order_.push_back(type);
518     }
519     return entry;
520   }
521
522   typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
523   typedef std::unordered_map<detail::TypeDescriptor,
524                              SingletonEntryPtr,
525                              detail::TypeDescriptorHasher> SingletonMap;
526
527   /* Destroy and clean-up one singleton. Must be invoked while holding
528    * a read lock on mutex_.
529    * @param typeDescriptor - the type key for the removed singleton.
530    */
531   void destroyInstance(SingletonMap::iterator entry_it);
532
533   mutable folly::RWSpinLock mutex_;
534   SingletonMap singletons_;
535   std::vector<detail::TypeDescriptor> creation_order_;
536   SingletonVaultState state_{SingletonVaultState::Running};
537   bool registrationComplete_{false};
538   folly::RWSpinLock stateMutex_;
539   Type type_{Type::Relaxed};
540 };
541
542 // This is the wrapper class that most users actually interact with.
543 // It allows for simple access to registering and instantiating
544 // singletons.  Create instances of this class in the global scope of
545 // type Singleton<T> to register your singleton for later access via
546 // Singleton<T>::get().
547 template <typename T,
548           typename Tag = detail::DefaultTag,
549           typename VaultTag = detail::DefaultTag /* for testing */>
550 class Singleton {
551  public:
552   typedef std::function<T*(void)> CreateFunc;
553   typedef std::function<void(T*)> TeardownFunc;
554
555   // Generally your program life cycle should be fine with calling
556   // get() repeatedly rather than saving the reference, and then not
557   // call get() during process shutdown.
558   static T* get() {
559     return static_cast<T*>(
560       SingletonVault::singleton<VaultTag>()->get_ptr(typeDescriptor()));
561   }
562
563   // Same as get, but should be preffered to it in the same compilation
564   // unit, where Singleton is registered.
565   T* get_fast() {
566     if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
567       return reinterpret_cast<T*>(entry_->instance_ptr);
568     } else {
569       return get();
570     }
571   }
572
573   // If, however, you do need to hold a reference to the specific
574   // singleton, you can try to do so with a weak_ptr.  Avoid this when
575   // possible but the inability to lock the weak pointer can be a
576   // signal that the vault has been destroyed.
577   static std::weak_ptr<T> get_weak() {
578     auto weak_void_ptr =
579       (SingletonVault::singleton<VaultTag>())->get_weak(typeDescriptor());
580
581     // This is ugly and inefficient, but there's no other way to do it, because
582     // there's no static_pointer_cast for weak_ptr.
583     auto shared_void_ptr = weak_void_ptr.lock();
584     if (!shared_void_ptr) {
585       return std::weak_ptr<T>();
586     }
587     return std::static_pointer_cast<T>(shared_void_ptr);
588   }
589
590   // Same as get_weak, but should be preffered to it in the same compilation
591   // unit, where Singleton is registered.
592   std::weak_ptr<T> get_weak_fast() {
593     if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
594       // This is ugly and inefficient, but there's no other way to do it,
595       // because there's no static_pointer_cast for weak_ptr.
596       auto shared_void_ptr = entry_->instance_weak.lock();
597       if (!shared_void_ptr) {
598         return std::weak_ptr<T>();
599       }
600       return std::static_pointer_cast<T>(shared_void_ptr);
601     } else {
602       return get_weak();
603     }
604   }
605
606   // Allow the Singleton<t> instance to also retrieve the underlying
607   // singleton, if desired.
608   T* ptr() { return get_fast(); }
609   T& operator*() { return *ptr(); }
610   T* operator->() { return ptr(); }
611
612   explicit Singleton(std::nullptr_t _ = nullptr,
613                      Singleton::TeardownFunc t = nullptr) :
614       Singleton ([]() { return new T; }, std::move(t)) {
615   }
616
617   explicit Singleton(Singleton::CreateFunc c,
618                      Singleton::TeardownFunc t = nullptr) {
619     if (c == nullptr) {
620       throw std::logic_error(
621         "nullptr_t should be passed if you want T to be default constructed");
622     }
623
624     auto vault = SingletonVault::singleton<VaultTag>();
625
626     entry_ =
627       &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
628   }
629
630   /**
631   * Construct and inject a mock singleton which should be used only from tests.
632   * Unlike regular singletons which are initialized once per process lifetime,
633   * mock singletons live for the duration of a test. This means that one process
634   * running multiple tests can initialize and register the same singleton
635   * multiple times. This functionality should be used only from tests
636   * since it relaxes validation and performance in order to be able to perform
637   * the injection. The returned mock singleton is functionality identical to
638   * regular singletons.
639   */
640   static void make_mock(std::nullptr_t c = nullptr,
641                         typename Singleton<T>::TeardownFunc t = nullptr) {
642     make_mock([]() { return new T; }, t);
643   }
644
645   static void make_mock(CreateFunc c,
646                         typename Singleton<T>::TeardownFunc t = nullptr) {
647     if (c == nullptr) {
648       throw std::logic_error(
649         "nullptr_t should be passed if you want T to be default constructed");
650     }
651
652     auto vault = SingletonVault::singleton<VaultTag>();
653
654     vault->registerMockSingleton(
655       typeDescriptor(),
656       c,
657       getTeardownFunc(t));
658   }
659
660  private:
661   static detail::TypeDescriptor typeDescriptor() {
662     return {typeid(T), typeid(Tag)};
663   }
664
665   // Construct SingletonVault::TeardownFunc.
666   static SingletonVault::TeardownFunc getTeardownFunc(
667       TeardownFunc t) {
668     SingletonVault::TeardownFunc teardown;
669     if (t == nullptr) {
670       teardown = [](void* v) { delete static_cast<T*>(v); };
671     } else {
672       teardown = [t](void* v) { t(static_cast<T*>(v)); };
673     }
674
675     return teardown;
676   }
677
678   // This is pointing to SingletonEntry paired with this singleton object. This
679   // is never reset, so each SingletonEntry should never be destroyed.
680   // We rely on the fact that Singleton destructor won't reset this pointer, so
681   // it can be "safely" used even after static Singleton object is destroyed.
682   detail::SingletonEntry* entry_;
683 };
684
685 }