Make using folly::Singleton easier: names and direct referencing
[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 // You also can directly access it by the variable defining the
38 // singleton rather than via get(), and even treat that variable like
39 // a smart pointer (dereferencing it or using the -> operator).
40 //
41 // Please note, however, that all non-weak_ptr interfaces are
42 // inherently subject to races with destruction.  Use responsibly.
43 //
44 // The singleton will be created on demand.  If the constructor for
45 // MyExpensiveService actually makes use of *another* Singleton, then
46 // the right thing will happen -- that other singleton will complete
47 // construction before get() returns.  However, in the event of a
48 // circular dependency, a runtime error will occur.
49 //
50 // You can have multiple singletons of the same underlying type, but
51 // each must be given a unique name:
52 //
53 // namespace {
54 // folly::Singleton<MyExpensiveService> s1("name1");
55 // folly::Singleton<MyExpensiveService> s2("name2");
56 // }
57 // ...
58 // MyExpensiveService* svc1 = Singleton<MyExpensiveService>::get("name1");
59 // MyExpensiveService* svc2 = Singleton<MyExpensiveService>::get("name2");
60 //
61 // By default, the singleton instance is constructed via new and
62 // deleted via delete, but this is configurable:
63 //
64 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
65 //                                                                destroy); }
66 //
67 // Where create and destroy are functions, Singleton<T>::CreateFunc
68 // Singleton<T>::TeardownFunc.
69 //
70 // What if you need to destroy all of your singletons?  Say, some of
71 // your singletons manage threads, but you need to fork?  Or your unit
72 // test wants to clean up all global state?  Then you can call
73 // SingletonVault::singleton()->destroyInstances(), which invokes the
74 // TeardownFunc for each singleton, in the reverse order they were
75 // created.  It is your responsibility to ensure your singletons can
76 // handle cases where the singletons they depend on go away, however.
77
78 #pragma once
79 #include <folly/Exception.h>
80 #include <folly/Hash.h>
81
82 #include <vector>
83 #include <mutex>
84 #include <string>
85 #include <unordered_map>
86 #include <functional>
87 #include <typeinfo>
88 #include <typeindex>
89
90 #include <glog/logging.h>
91
92 namespace folly {
93
94 // For actual usage, please see the Singleton<T> class at the bottom
95 // of this file; that is what you will actually interact with.
96
97 // SingletonVault is the class that manages singleton instances.  It
98 // is unaware of the underlying types of singletons, and simply
99 // manages lifecycles and invokes CreateFunc and TeardownFunc when
100 // appropriate.  In general, you won't need to interact with the
101 // SingletonVault itself.
102 //
103 // A vault goes through a few stages of life:
104 //
105 //   1. Registration phase; singletons can be registered, but no
106 //      singleton can be created.
107 //   2. registrationComplete() has been called; singletons can no
108 //      longer be registered, but they can be created.
109 //   3. A vault can return to stage 1 when destroyInstances is called.
110 //
111 // In general, you don't need to worry about any of the above; just
112 // ensure registrationComplete() is called near the top of your main()
113 // function, otherwise no singletons can be instantiated.
114
115 namespace detail {
116
117 const char* const kDefaultTypeDescriptorName = "(default)";
118 // A TypeDescriptor is the unique handle for a given singleton.  It is
119 // a combinaiton of the type and of the optional name, and is used as
120 // a key in unordered_maps.
121 class TypeDescriptor {
122  public:
123   TypeDescriptor(const std::type_info& ti, std::string name)
124       : ti_(ti), name_(name) {
125     if (name_ == kDefaultTypeDescriptorName) {
126       LOG(DFATAL) << "Caller used the default name as their literal name; "
127                   << "name your singleton something other than "
128                   << kDefaultTypeDescriptorName;
129     }
130   }
131
132   std::string name() const {
133     std::string ret = ti_.name();
134     ret += "/";
135     if (name_.empty()) {
136       ret += kDefaultTypeDescriptorName;
137     } else {
138       ret += name_;
139     }
140     return ret;
141   }
142
143   friend class TypeDescriptorHasher;
144
145   bool operator==(const TypeDescriptor& other) const {
146     return ti_ == other.ti_ && name_ == other.name_;
147   }
148
149  private:
150   const std::type_index ti_;
151   const std::string name_;
152 };
153
154 class TypeDescriptorHasher {
155  public:
156   size_t operator()(const TypeDescriptor& ti) const {
157     return folly::hash::hash_combine(ti.ti_, ti.name_);
158   }
159 };
160 }
161
162 class SingletonVault {
163  public:
164   SingletonVault() {};
165   ~SingletonVault();
166
167   typedef std::function<void(void*)> TeardownFunc;
168   typedef std::function<void*(void)> CreateFunc;
169
170   // Register a singleton of a given type with the create and teardown
171   // functions.
172   void registerSingleton(detail::TypeDescriptor type,
173                          CreateFunc create,
174                          TeardownFunc teardown) {
175     std::lock_guard<std::mutex> guard(mutex_);
176
177     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
178     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
179     auto& entry = singletons_[type];
180     if (!entry) {
181       entry.reset(new SingletonEntry);
182     }
183
184     std::lock_guard<std::mutex> entry_guard(entry->mutex_);
185     CHECK(entry->instance == nullptr);
186     CHECK(create);
187     CHECK(teardown);
188     entry->create = create;
189     entry->teardown = teardown;
190     entry->state = SingletonEntryState::Dead;
191   }
192
193   // Mark registration is complete; no more singletons can be
194   // registered at this point.
195   void registrationComplete() {
196     std::lock_guard<std::mutex> guard(mutex_);
197     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
198     state_ = SingletonVaultState::Running;
199   }
200
201   // Destroy all singletons; when complete, the vault can create
202   // singletons once again, or remain dormant.
203   void destroyInstances();
204
205   // Retrieve a singleton from the vault, creating it if necessary.
206   std::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
207     std::unique_lock<std::mutex> lock(mutex_);
208     auto entry = get_entry(type, &lock);
209     return entry->instance;
210   }
211
212   // This function is inherently racy since we don't hold the
213   // shared_ptr that contains the Singleton.  It is the caller's
214   // responsibility to be sane with this, but it is preferable to use
215   // the weak_ptr interface for true safety.
216   void* get_ptr(detail::TypeDescriptor type) {
217     std::unique_lock<std::mutex> lock(mutex_);
218     auto entry = get_entry(type, &lock);
219     return entry->instance_ptr;
220   }
221
222   // For testing; how many registered and living singletons we have.
223   size_t registeredSingletonCount() const {
224     std::lock_guard<std::mutex> guard(mutex_);
225     return singletons_.size();
226   }
227
228   size_t livingSingletonCount() const {
229     std::lock_guard<std::mutex> guard(mutex_);
230     size_t ret = 0;
231     for (const auto& p : singletons_) {
232       if (p.second->instance) {
233         ++ret;
234       }
235     }
236
237     return ret;
238   }
239
240   // A well-known vault; you can actually have others, but this is the
241   // default.
242   static SingletonVault* singleton();
243
244  private:
245   // The two stages of life for a vault, as mentioned in the class comment.
246   enum class SingletonVaultState {
247     Registering,
248     Running,
249   };
250
251   // Each singleton in the vault can be in three states: dead
252   // (registered but never created), being born (running the
253   // CreateFunc), and living (CreateFunc returned an instance).
254   enum class SingletonEntryState {
255     Dead,
256     BeingBorn,
257     Living,
258   };
259
260   // An actual instance of a singleton, tracking the instance itself,
261   // its state as described above, and the create and teardown
262   // functions.
263   struct SingletonEntry {
264     std::mutex mutex_;
265     std::shared_ptr<void> instance;
266     void* instance_ptr = nullptr;
267     CreateFunc create = nullptr;
268     TeardownFunc teardown = nullptr;
269     SingletonEntryState state = SingletonEntryState::Dead;
270
271     SingletonEntry() = default;
272     SingletonEntry(const SingletonEntry&) = delete;
273     SingletonEntry& operator=(const SingletonEntry&) = delete;
274     SingletonEntry& operator=(SingletonEntry&&) = delete;
275     SingletonEntry(SingletonEntry&&) = delete;
276   };
277
278   // Get a pointer to the living SingletonEntry for the specified
279   // type.  The singleton is created as part of this function, if
280   // necessary.
281   SingletonEntry* get_entry(detail::TypeDescriptor type,
282                             std::unique_lock<std::mutex>* lock) {
283     // mutex_ must be held when calling this function
284     if (state_ != SingletonVaultState::Running) {
285       throw std::logic_error(
286           "Attempt to load a singleton before "
287           "SingletonVault::registrationComplete was called (hint: you probably "
288           "didn't call initFacebook)");
289     }
290
291     auto it = singletons_.find(type);
292     if (it == singletons_.end()) {
293       throw std::out_of_range(std::string("non-existent singleton: ") +
294                               type.name());
295     }
296
297     auto& entry = it->second;
298     std::unique_lock<std::mutex> entry_lock(entry->mutex_);
299
300     if (entry->state == SingletonEntryState::BeingBorn) {
301       throw std::out_of_range(std::string("circular singleton dependency: ") +
302                               type.name());
303     }
304
305     if (entry->instance == nullptr) {
306       CHECK(entry->state == SingletonEntryState::Dead);
307       entry->state = SingletonEntryState::BeingBorn;
308
309       entry_lock.unlock();
310       lock->unlock();
311       // Can't use make_shared -- no support for a custom deleter, sadly.
312       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
313       lock->lock();
314       entry_lock.lock();
315
316       CHECK(entry->state == SingletonEntryState::BeingBorn);
317       entry->instance = instance;
318       entry->instance_ptr = instance.get();
319       entry->state = SingletonEntryState::Living;
320
321       creation_order_.push_back(type);
322     }
323     CHECK(entry->state == SingletonEntryState::Living);
324     return entry.get();
325   }
326
327   mutable std::mutex mutex_;
328   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
329   std::unordered_map<detail::TypeDescriptor,
330                      SingletonEntryPtr,
331                      detail::TypeDescriptorHasher> singletons_;
332   std::vector<detail::TypeDescriptor> creation_order_;
333   SingletonVaultState state_ = SingletonVaultState::Registering;
334 };
335
336 // This is the wrapper class that most users actually interact with.
337 // It allows for simple access to registering and instantiating
338 // singletons.  Create instances of this class in the global scope of
339 // type Singleton<T> to register your singleton for later access via
340 // Singleton<T>::get().
341 template <typename T>
342 class Singleton {
343  public:
344   typedef std::function<T*(void)> CreateFunc;
345   typedef std::function<void(T*)> TeardownFunc;
346
347   // Generally your program life cycle should be fine with calling
348   // get() repeatedly rather than saving the reference, and then not
349   // call get() during process shutdown.
350   static T* get(SingletonVault* vault = nullptr /* for testing */) {
351     return get_ptr({typeid(T), ""}, vault);
352   }
353
354   static T* get(const char* name,
355                 SingletonVault* vault = nullptr /* for testing */) {
356     return get_ptr({typeid(T), name}, vault);
357   }
358
359   // If, however, you do need to hold a reference to the specific
360   // singleton, you can try to do so with a weak_ptr.  Avoid this when
361   // possible but the inability to lock the weak pointer can be a
362   // signal that the vault has been destroyed.
363   static std::weak_ptr<T> get_weak(
364       SingletonVault* vault = nullptr /* for testing */) {
365     return get_weak("", vault);
366   }
367
368   static std::weak_ptr<T> get_weak(
369       const char* name, SingletonVault* vault = nullptr /* for testing */) {
370     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
371   }
372
373   std::weak_ptr<T> get_weak(const char* name) {
374     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault_));
375   }
376
377   // Allow the Singleton<t> instance to also retrieve the underlying
378   // singleton, if desired.
379   T* ptr() { return get_ptr(type_descriptor_, vault_); }
380   T& operator*() { return *ptr(); }
381   T* operator->() { return ptr(); }
382
383   explicit Singleton(Singleton::CreateFunc c = nullptr,
384                      Singleton::TeardownFunc t = nullptr,
385                      SingletonVault* vault = nullptr /* for testing */)
386       : Singleton({typeid(T), ""}, c, t, vault) {}
387
388   explicit Singleton(const char* name,
389                      Singleton::CreateFunc c = nullptr,
390                      Singleton::TeardownFunc t = nullptr,
391                      SingletonVault* vault = nullptr /* for testing */)
392       : Singleton({typeid(T), name}, c, t, vault) {}
393
394  private:
395   explicit Singleton(detail::TypeDescriptor type,
396                      Singleton::CreateFunc c = nullptr,
397                      Singleton::TeardownFunc t = nullptr,
398                      SingletonVault* vault = nullptr /* for testing */)
399       : type_descriptor_(type) {
400     if (c == nullptr) {
401       c = []() { return new T; };
402     }
403     SingletonVault::TeardownFunc teardown;
404     if (t == nullptr) {
405       teardown = [](void* v) { delete static_cast<T*>(v); };
406     } else {
407       teardown = [t](void* v) { t(static_cast<T*>(v)); };
408     }
409
410     if (vault == nullptr) {
411       vault = SingletonVault::singleton();
412     }
413     vault_ = vault;
414     vault->registerSingleton(type, c, teardown);
415   }
416
417   static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
418                     SingletonVault* vault = nullptr /* for testing */) {
419     return static_cast<T*>(
420         (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
421   }
422
423   // Don't use this function, it's private for a reason!  Using it
424   // would defeat the *entire purpose* of the vault in that we lose
425   // the ability to guarantee that, after a destroyInstances is
426   // called, all instances are, in fact, destroyed.  You should use
427   // weak_ptr if you need to hold a reference to the singleton and
428   // guarantee briefly that it exists.
429   //
430   // Yes, you can just get the weak pointer and lock it, but hopefully
431   // if you have taken the time to read this far, you see why that
432   // would be bad.
433   static std::shared_ptr<T> get_shared(
434       detail::TypeDescriptor type_descriptor = {typeid(T), ""},
435       SingletonVault* vault = nullptr /* for testing */) {
436     return std::static_pointer_cast<T>(
437         (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
438   }
439
440   detail::TypeDescriptor type_descriptor_;
441   SingletonVault* vault_;
442 };
443 }