Improve messaging when registrationComplete hasn't been called
[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 // The singleton will be created on demand.  If the constructor for
38 // MyExpensiveService actually makes use of *another* Singleton, then
39 // the right thing will happen -- that other singleton will complete
40 // construction before get() returns.  However, in the event of a
41 // circular dependency, a runtime error will occur.
42 //
43 // By default, the singleton instance is constructed via new and
44 // deleted via delete, but this is configurable:
45 //
46 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
47 //                                                                destroy); }
48 //
49 // Where create and destroy are functions, Singleton<T>::CreateFunc
50 // Singleton<T>::TeardownFunc.
51 //
52 // What if you need to destroy all of your singletons?  Say, some of
53 // your singletons manage threads, but you need to fork?  Or your unit
54 // test wants to clean up all global state?  Then you can call
55 // SingletonVault::singleton()->destroyInstances(), which invokes the
56 // TeardownFunc for each singleton, in the reverse order they were
57 // created.  It is your responsibility to ensure your singletons can
58 // handle cases where the singletons they depend on go away, however.
59
60 #pragma once
61 #include <folly/Exception.h>
62
63 #include <vector>
64 #include <mutex>
65 #include <string>
66 #include <unordered_map>
67 #include <functional>
68 #include <typeinfo>
69 #include <typeindex>
70
71 #include <glog/logging.h>
72
73 namespace folly {
74
75 // For actual usage, please see the Singleton<T> class at the bottom
76 // of this file; that is what you will actually interact with.
77
78 // SingletonVault is the class that manages singleton instances.  It
79 // is unaware of the underlying types of singletons, and simply
80 // manages lifecycles and invokes CreateFunc and TeardownFunc when
81 // appropriate.  In general, you won't need to interact with the
82 // SingletonVault itself.
83 //
84 // A vault goes through a few stages of life:
85 //
86 //   1. Registration phase; singletons can be registered, but no
87 //      singleton can be created.
88 //   2. registrationComplete() has been called; singletons can no
89 //      longer be registered, but they can be created.
90 //   3. A vault can return to stage 1 when destroyInstances is called.
91 //
92 // In general, you don't need to worry about any of the above; just
93 // ensure registrationComplete() is called near the top of your main()
94 // function, otherwise no singletons can be instantiated.
95 class SingletonVault {
96  public:
97   SingletonVault() {};
98   ~SingletonVault();
99
100   typedef std::function<void(void*)> TeardownFunc;
101   typedef std::function<void*(void)> CreateFunc;
102
103   // Register a singleton of a given type with the create and teardown
104   // functions.
105   void registerSingleton(const std::type_info& type,
106                          CreateFunc create,
107                          TeardownFunc teardown) {
108     std::lock_guard<std::mutex> guard(mutex_);
109
110     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
111     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
112     auto& entry = singletons_[type];
113     if (!entry) {
114       entry.reset(new SingletonEntry);
115     }
116
117     std::lock_guard<std::mutex> entry_guard(entry->mutex_);
118     CHECK(entry->instance == nullptr);
119     CHECK(create);
120     CHECK(teardown);
121     entry->create = create;
122     entry->teardown = teardown;
123     entry->state = SingletonEntryState::Dead;
124   }
125
126   // Mark registration is complete; no more singletons can be
127   // registered at this point.
128   void registrationComplete() {
129     std::lock_guard<std::mutex> guard(mutex_);
130     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
131     state_ = SingletonVaultState::Running;
132   }
133
134   // Destroy all singletons; when complete, the vault can create
135   // singletons once again, or remain dormant.
136   void destroyInstances();
137
138   // Retrieve a singleton from the vault, creating it if necessary.
139   std::shared_ptr<void> get_shared(const std::type_info& type) {
140     std::unique_lock<std::mutex> lock(mutex_);
141     if (state_ != SingletonVaultState::Running) {
142       throw std::logic_error(
143           "Attempt to load a singleton before "
144           "SingletonVault::registrationComplete was called (hint: you probably "
145           "didn't call initFacebook)");
146     }
147
148     auto it = singletons_.find(type);
149     if (it == singletons_.end()) {
150       throw std::out_of_range(std::string("non-existent singleton: ") +
151                               type.name());
152     }
153
154     auto& entry = it->second;
155     std::unique_lock<std::mutex> entry_lock(entry->mutex_);
156
157     if (entry->state == SingletonEntryState::BeingBorn) {
158       throw std::out_of_range(std::string("circular singleton dependency: ") +
159                               type.name());
160     }
161
162     if (entry->instance == nullptr) {
163       CHECK(entry->state == SingletonEntryState::Dead);
164       entry->state = SingletonEntryState::BeingBorn;
165
166       entry_lock.unlock();
167       lock.unlock();
168       // Can't use make_shared -- no support for a custom deleter, sadly.
169       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
170       lock.lock();
171       entry_lock.lock();
172
173       CHECK(entry->state == SingletonEntryState::BeingBorn);
174       entry->instance = instance;
175       entry->state = SingletonEntryState::Living;
176
177       creation_order_.push_back(type);
178     }
179     CHECK(entry->state == SingletonEntryState::Living);
180
181     return entry->instance;
182   }
183
184   // For testing; how many registered and living singletons we have.
185   size_t registeredSingletonCount() const {
186     std::lock_guard<std::mutex> guard(mutex_);
187     return singletons_.size();
188   }
189
190   size_t livingSingletonCount() const {
191     std::lock_guard<std::mutex> guard(mutex_);
192     size_t ret = 0;
193     for (const auto& p : singletons_) {
194       if (p.second->instance) {
195         ++ret;
196       }
197     }
198
199     return ret;
200   }
201
202   // A well-known vault; you can actually have others, but this is the
203   // default.
204   static SingletonVault* singleton();
205
206  private:
207   // The two stages of life for a vault, as mentioned in the class comment.
208   enum class SingletonVaultState {
209     Registering,
210     Running,
211   };
212
213   // Each singleton in the vault can be in three states: dead
214   // (registered but never created), being born (running the
215   // CreateFunc), and living (CreateFunc returned an instance).
216   enum class SingletonEntryState {
217     Dead,
218     BeingBorn,
219     Living,
220   };
221
222   // An actual instance of a singleton, tracking the instance itself,
223   // its state as described above, and the create and teardown
224   // functions.
225   struct SingletonEntry {
226     std::mutex mutex_;
227     std::shared_ptr<void> instance;
228     CreateFunc create = nullptr;
229     TeardownFunc teardown = nullptr;
230     SingletonEntryState state = SingletonEntryState::Dead;
231
232     SingletonEntry() = default;
233     SingletonEntry(const SingletonEntry&) = delete;
234     SingletonEntry& operator=(const SingletonEntry&) = delete;
235     SingletonEntry& operator=(SingletonEntry&&) = delete;
236     SingletonEntry(SingletonEntry&&) = delete;
237   };
238
239   mutable std::mutex mutex_;
240   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
241   std::unordered_map<std::type_index, SingletonEntryPtr> singletons_;
242   std::vector<std::type_index> creation_order_;
243   SingletonVaultState state_ = SingletonVaultState::Registering;
244 };
245
246 // This is the wrapper class that most users actually interact with.
247 // It allows for simple access to registering and instantiating
248 // singletons.  Create instances of this class in the global scope of
249 // type Singleton<T> to register your singleton for later access via
250 // Singleton<T>::get().
251 template <typename T>
252 class Singleton {
253  public:
254   typedef std::function<T*(void)> CreateFunc;
255   typedef std::function<void(T*)> TeardownFunc;
256
257   // Generally your program life cycle should be fine with calling
258   // get() repeatedly rather than saving the reference, and then not
259   // call get() during process shutdown.
260   static T* get(SingletonVault* vault = nullptr /* for testing */) {
261     return get_shared(vault).get();
262   }
263
264   // If, however, you do need to hold a reference to the specific
265   // singleton, you can try to do so with a weak_ptr.  Avoid this when
266   // possible but the inability to lock the weak pointer can be a
267   // signal that the vault has been destroyed.
268   static std::weak_ptr<T> get_weak(SingletonVault* vault =
269                                        nullptr /* for testing */) {
270     return std::weak_ptr<T>(get_shared(vault));
271   }
272
273   Singleton(Singleton::CreateFunc c = nullptr,
274             Singleton::TeardownFunc t = nullptr,
275             SingletonVault* vault = nullptr /* for testing */) {
276     if (c == nullptr) {
277       c = []() { return new T; };
278     }
279     SingletonVault::TeardownFunc teardown;
280     if (t == nullptr) {
281       teardown = [](void* v) { delete static_cast<T*>(v); };
282     } else {
283       teardown = [t](void* v) { t(static_cast<T*>(v)); };
284     }
285
286     if (vault == nullptr) {
287       vault = SingletonVault::singleton();
288     }
289
290     vault->registerSingleton(typeid(T), c, teardown);
291   }
292
293  private:
294   // Don't use this function, it's private for a reason!  Using it
295   // would defeat the *entire purpose* of the vault in that we lose
296   // the ability to guarantee that, after a destroyInstances is
297   // called, all instances are, in fact, destroyed.  You should use
298   // weak_ptr if you need to hold a reference to the singleton and
299   // guarantee briefly that it exists.
300   //
301   // Yes, you can just get the weak pointer and lock it, but hopefully
302   // if you have taken the time to read this far, you see why that
303   // would be bad.
304   static std::shared_ptr<T> get_shared(SingletonVault* vault =
305                                            nullptr /* for testing */) {
306     return std::static_pointer_cast<T>(
307         (vault ?: SingletonVault::singleton())->get_shared(typeid(T)));
308   }
309 };
310 }