1 | /* |
2 | * Copyright (c) Facebook, Inc. and its affiliates. |
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 | // Recommended usage of this class: 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 | // // Caution - may return a null ptr during startup and shutdown. |
27 | // static std::shared_ptr<MyExpensiveService> getInstance(); |
28 | // .... |
29 | // }; |
30 | // |
31 | // In your .cpp file: |
32 | // namespace { struct PrivateTag {}; } |
33 | // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton; |
34 | // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() { |
35 | // return the_singleton.try_get(); |
36 | // } |
37 | // |
38 | // Code in other modules can access it via: |
39 | // |
40 | // auto instance = MyExpensiveService::getInstance(); |
41 | // |
42 | // Advanced usage and notes: |
43 | // |
44 | // You can also access a singleton instance with |
45 | // `Singleton<ObjectType, TagType>::try_get()`. We recommend |
46 | // that you prefer the form `the_singleton.try_get()` because it ensures that |
47 | // `the_singleton` is used and cannot be garbage-collected during linking: this |
48 | // is necessary because the constructor of `the_singleton` is what registers it |
49 | // to the SingletonVault. |
50 | // |
51 | // The singleton will be created on demand. If the constructor for |
52 | // MyExpensiveService actually makes use of *another* Singleton, then |
53 | // the right thing will happen -- that other singleton will complete |
54 | // construction before get() returns. However, in the event of a |
55 | // circular dependency, a runtime error will occur. |
56 | // |
57 | // You can have multiple singletons of the same underlying type, but |
58 | // each must be given a unique tag. If no tag is specified a default tag is |
59 | // used. We recommend that you use a tag from an anonymous namespace private to |
60 | // your implementation file, as this ensures that the singleton is only |
61 | // available via your interface and not also through Singleton<T>::try_get() |
62 | // |
63 | // namespace { |
64 | // struct Tag1 {}; |
65 | // struct Tag2 {}; |
66 | // folly::Singleton<MyExpensiveService> s_default; |
67 | // folly::Singleton<MyExpensiveService, Tag1> s1; |
68 | // folly::Singleton<MyExpensiveService, Tag2> s2; |
69 | // } |
70 | // ... |
71 | // MyExpensiveService* svc_default = s_default.get(); |
72 | // MyExpensiveService* svc1 = s1.get(); |
73 | // MyExpensiveService* svc2 = s2.get(); |
74 | // |
75 | // By default, the singleton instance is constructed via new and |
76 | // deleted via delete, but this is configurable: |
77 | // |
78 | // namespace { folly::Singleton<MyExpensiveService> the_singleton(create, |
79 | // destroy); } |
80 | // |
81 | // Where create and destroy are functions, Singleton<T>::CreateFunc |
82 | // Singleton<T>::TeardownFunc. |
83 | // |
84 | // For example, if you need to pass arguments to your class's constructor: |
85 | // class X { |
86 | // public: |
87 | // X(int a1, std::string a2); |
88 | // // ... |
89 | // } |
90 | // Make your singleton like this: |
91 | // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); }); |
92 | // |
93 | // The above examples detail a situation where an expensive singleton is loaded |
94 | // on-demand (thus only if needed). However if there is an expensive singleton |
95 | // that will likely be needed, and initialization takes a potentially long time, |
96 | // e.g. while initializing, parsing some files, talking to remote services, |
97 | // making uses of other singletons, and so on, the initialization of those can |
98 | // be scheduled up front, or "eagerly". |
99 | // |
100 | // In that case the singleton can be declared this way: |
101 | // |
102 | // namespace { |
103 | // auto the_singleton = |
104 | // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */) |
105 | // .shouldEagerInit(); |
106 | // } |
107 | // |
108 | // This way the singleton's instance is built at program initialization, |
109 | // if the program opted-in to that feature by calling "doEagerInit" or |
110 | // "doEagerInitVia" during its startup. |
111 | // |
112 | // What if you need to destroy all of your singletons? Say, some of |
113 | // your singletons manage threads, but you need to fork? Or your unit |
114 | // test wants to clean up all global state? Then you can call |
115 | // SingletonVault::singleton()->destroyInstances(), which invokes the |
116 | // TeardownFunc for each singleton, in the reverse order they were |
117 | // created. It is your responsibility to ensure your singletons can |
118 | // handle cases where the singletons they depend on go away, however. |
119 | // Singletons won't be recreated after destroyInstances call. If you |
120 | // want to re-enable singleton creation (say after fork was called) you |
121 | // should call reenableInstances. |
122 | |
123 | #pragma once |
124 | |
125 | #include <folly/Exception.h> |
126 | #include <folly/Executor.h> |
127 | #include <folly/Memory.h> |
128 | #include <folly/Synchronized.h> |
129 | #include <folly/detail/Singleton.h> |
130 | #include <folly/detail/StaticSingletonManager.h> |
131 | #include <folly/experimental/ReadMostlySharedPtr.h> |
132 | #include <folly/hash/Hash.h> |
133 | #include <folly/lang/Exception.h> |
134 | #include <folly/memory/SanitizeLeak.h> |
135 | #include <folly/synchronization/Baton.h> |
136 | #include <folly/synchronization/RWSpinLock.h> |
137 | |
138 | #include <algorithm> |
139 | #include <atomic> |
140 | #include <condition_variable> |
141 | #include <functional> |
142 | #include <list> |
143 | #include <memory> |
144 | #include <mutex> |
145 | #include <string> |
146 | #include <thread> |
147 | #include <typeindex> |
148 | #include <typeinfo> |
149 | #include <unordered_map> |
150 | #include <unordered_set> |
151 | #include <vector> |
152 | |
153 | #include <glog/logging.h> |
154 | |
155 | // use this guard to handleSingleton breaking change in 3rd party code |
156 | #ifndef FOLLY_SINGLETON_TRY_GET |
157 | #define FOLLY_SINGLETON_TRY_GET |
158 | #endif |
159 | |
160 | namespace folly { |
161 | |
162 | // For actual usage, please see the Singleton<T> class at the bottom |
163 | // of this file; that is what you will actually interact with. |
164 | |
165 | // SingletonVault is the class that manages singleton instances. It |
166 | // is unaware of the underlying types of singletons, and simply |
167 | // manages lifecycles and invokes CreateFunc and TeardownFunc when |
168 | // appropriate. In general, you won't need to interact with the |
169 | // SingletonVault itself. |
170 | // |
171 | // A vault goes through a few stages of life: |
172 | // |
173 | // 1. Registration phase; singletons can be registered: |
174 | // a) Strict: no singleton can be created in this stage. |
175 | // b) Relaxed: singleton can be created (the default vault is Relaxed). |
176 | // 2. registrationComplete() has been called; singletons can no |
177 | // longer be registered, but they can be created. |
178 | // 3. A vault can return to stage 1 when destroyInstances is called. |
179 | // |
180 | // In general, you don't need to worry about any of the above; just |
181 | // ensure registrationComplete() is called near the top of your main() |
182 | // function, otherwise no singletons can be instantiated. |
183 | |
184 | class SingletonVault; |
185 | |
186 | namespace detail { |
187 | |
188 | // A TypeDescriptor is the unique handle for a given singleton. It is |
189 | // a combinaiton of the type and of the optional name, and is used as |
190 | // a key in unordered_maps. |
191 | class TypeDescriptor { |
192 | public: |
193 | TypeDescriptor(const std::type_info& ti, const std::type_info& tag_ti) |
194 | : ti_(ti), tag_ti_(tag_ti) {} |
195 | |
196 | TypeDescriptor(const TypeDescriptor& other) |
197 | : ti_(other.ti_), tag_ti_(other.tag_ti_) {} |
198 | |
199 | TypeDescriptor& operator=(const TypeDescriptor& other) { |
200 | if (this != &other) { |
201 | ti_ = other.ti_; |
202 | tag_ti_ = other.tag_ti_; |
203 | } |
204 | |
205 | return *this; |
206 | } |
207 | |
208 | std::string name() const; |
209 | |
210 | friend class TypeDescriptorHasher; |
211 | |
212 | bool operator==(const TypeDescriptor& other) const { |
213 | return ti_ == other.ti_ && tag_ti_ == other.tag_ti_; |
214 | } |
215 | |
216 | private: |
217 | std::type_index ti_; |
218 | std::type_index tag_ti_; |
219 | }; |
220 | |
221 | class TypeDescriptorHasher { |
222 | public: |
223 | size_t operator()(const TypeDescriptor& ti) const { |
224 | return folly::hash::hash_combine(ti.ti_, ti.tag_ti_); |
225 | } |
226 | }; |
227 | |
228 | [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort( |
229 | const TypeDescriptor& type); |
230 | |
231 | [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort( |
232 | const TypeDescriptor& type); |
233 | |
234 | [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort( |
235 | const TypeDescriptor& type); |
236 | |
237 | void singletonWarnDestroyInstanceLeak( |
238 | const TypeDescriptor& type, |
239 | const void* ptr); |
240 | |
241 | [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort( |
242 | const TypeDescriptor& type); |
243 | |
244 | [[noreturn]] void singletonWarnCreateUnregisteredAndAbort( |
245 | const TypeDescriptor& type); |
246 | |
247 | [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort( |
248 | const TypeDescriptor& type); |
249 | |
250 | void singletonPrintDestructionStackTrace(const TypeDescriptor& type); |
251 | |
252 | [[noreturn]] void singletonThrowNullCreator(const std::type_info& type); |
253 | |
254 | [[noreturn]] void singletonThrowGetInvokedAfterDestruction( |
255 | const TypeDescriptor& type); |
256 | |
257 | struct SingletonVaultState { |
258 | // The two stages of life for a vault, as mentioned in the class comment. |
259 | enum class Type { |
260 | Running, |
261 | Quiescing, |
262 | }; |
263 | |
264 | Type state{Type::Running}; |
265 | bool registrationComplete{false}; |
266 | |
267 | // Each singleton in the vault can be in two states: dead |
268 | // (registered but never created), living (CreateFunc returned an instance). |
269 | |
270 | void check( |
271 | Type expected, |
272 | const char* msg = "Unexpected singleton state change" ) const { |
273 | if (expected != state) { |
274 | throw_exception<std::logic_error>(msg); |
275 | } |
276 | } |
277 | }; |
278 | |
279 | // This interface is used by SingletonVault to interact with SingletonHolders. |
280 | // Having a non-template interface allows SingletonVault to keep a list of all |
281 | // SingletonHolders. |
282 | class SingletonHolderBase { |
283 | public: |
284 | explicit SingletonHolderBase(TypeDescriptor typeDesc) noexcept |
285 | : type_(typeDesc) {} |
286 | virtual ~SingletonHolderBase() = default; |
287 | |
288 | TypeDescriptor type() const { |
289 | return type_; |
290 | } |
291 | virtual bool hasLiveInstance() = 0; |
292 | virtual void createInstance() = 0; |
293 | virtual bool creationStarted() = 0; |
294 | virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0; |
295 | virtual void destroyInstance() = 0; |
296 | |
297 | private: |
298 | TypeDescriptor type_; |
299 | }; |
300 | |
301 | // An actual instance of a singleton, tracking the instance itself, |
302 | // its state as described above, and the create and teardown |
303 | // functions. |
304 | template <typename T> |
305 | struct SingletonHolder : public SingletonHolderBase { |
306 | public: |
307 | typedef std::function<void(T*)> TeardownFunc; |
308 | typedef std::function<T*(void)> CreateFunc; |
309 | |
310 | template <typename Tag, typename VaultTag> |
311 | inline static SingletonHolder<T>& singleton(); |
312 | |
313 | inline T* get(); |
314 | inline std::weak_ptr<T> get_weak(); |
315 | inline std::shared_ptr<T> try_get(); |
316 | inline folly::ReadMostlySharedPtr<T> try_get_fast(); |
317 | template <typename Func> |
318 | inline invoke_result_t<Func, T*> apply(Func f); |
319 | inline void vivify(); |
320 | |
321 | void registerSingleton(CreateFunc c, TeardownFunc t); |
322 | void registerSingletonMock(CreateFunc c, TeardownFunc t); |
323 | bool hasLiveInstance() override; |
324 | void createInstance() override; |
325 | bool creationStarted() override; |
326 | void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override; |
327 | void destroyInstance() override; |
328 | |
329 | private: |
330 | template <typename Tag, typename VaultTag> |
331 | struct Impl; |
332 | |
333 | SingletonHolder(TypeDescriptor type, SingletonVault& vault) noexcept; |
334 | |
335 | enum class SingletonHolderState { |
336 | NotRegistered, |
337 | Dead, |
338 | Living, |
339 | }; |
340 | |
341 | SingletonVault& vault_; |
342 | |
343 | // mutex protects the entire entry during construction/destruction |
344 | std::mutex mutex_; |
345 | |
346 | // State of the singleton entry. If state is Living, instance_ptr and |
347 | // instance_weak can be safely accessed w/o synchronization. |
348 | std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered}; |
349 | |
350 | // the thread creating the singleton (only valid while creating an object) |
351 | std::atomic<std::thread::id> creating_thread_{}; |
352 | |
353 | // The singleton itself and related functions. |
354 | |
355 | // holds a ReadMostlyMainPtr to singleton instance, set when state is changed |
356 | // from Dead to Living. Reset when state is changed from Living to Dead. |
357 | folly::ReadMostlyMainPtr<T> instance_; |
358 | // used to release all ReadMostlyMainPtrs at once |
359 | folly::ReadMostlySharedPtr<T> instance_copy_; |
360 | // weak_ptr to the singleton instance, set when state is changed from Dead |
361 | // to Living. We never write to this object after initialization, so it is |
362 | // safe to read it from different threads w/o synchronization if we know |
363 | // that state is set to Living |
364 | std::weak_ptr<T> instance_weak_; |
365 | // Fast equivalent of instance_weak_ |
366 | folly::ReadMostlyWeakPtr<T> instance_weak_fast_; |
367 | // Time we wait on destroy_baton after releasing Singleton shared_ptr. |
368 | std::shared_ptr<folly::Baton<>> destroy_baton_; |
369 | T* instance_ptr_ = nullptr; |
370 | CreateFunc create_ = nullptr; |
371 | TeardownFunc teardown_ = nullptr; |
372 | |
373 | std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_; |
374 | |
375 | SingletonHolder(const SingletonHolder&) = delete; |
376 | SingletonHolder& operator=(const SingletonHolder&) = delete; |
377 | SingletonHolder& operator=(SingletonHolder&&) = delete; |
378 | SingletonHolder(SingletonHolder&&) = delete; |
379 | }; |
380 | |
381 | } // namespace detail |
382 | |
383 | class SingletonVault { |
384 | public: |
385 | enum class Type { |
386 | Strict, // Singletons can't be created before registrationComplete() |
387 | Relaxed, // Singletons can be created before registrationComplete() |
388 | }; |
389 | |
390 | /** |
391 | * Clears all singletons in the given vault at ctor and dtor times. |
392 | * Useful for unit-tests that need to clear the world. |
393 | * |
394 | * This need can arise when a unit-test needs to swap out an object used by a |
395 | * singleton for a test-double, but the singleton needing its dependency to be |
396 | * swapped has a type or a tag local to some other translation unit and |
397 | * unavailable in the current translation unit. |
398 | * |
399 | * Other, better approaches to this need are "plz 2 refactor" .... |
400 | */ |
401 | struct ScopedExpunger { |
402 | SingletonVault* vault; |
403 | explicit ScopedExpunger(SingletonVault* v) : vault(v) { |
404 | expunge(); |
405 | } |
406 | ~ScopedExpunger() { |
407 | expunge(); |
408 | } |
409 | void expunge() { |
410 | vault->destroyInstances(); |
411 | vault->reenableInstances(); |
412 | } |
413 | }; |
414 | |
415 | static Type defaultVaultType(); |
416 | |
417 | explicit SingletonVault(Type type = defaultVaultType()) noexcept |
418 | : type_(type) {} |
419 | |
420 | // Destructor is only called by unit tests to check destroyInstances. |
421 | ~SingletonVault(); |
422 | |
423 | typedef std::function<void(void*)> TeardownFunc; |
424 | typedef std::function<void*(void)> CreateFunc; |
425 | |
426 | // Ensure that Singleton has not been registered previously and that |
427 | // registration is not complete. If validations succeeds, |
428 | // register a singleton of a given type with the create and teardown |
429 | // functions. |
430 | void registerSingleton(detail::SingletonHolderBase* entry); |
431 | |
432 | /** |
433 | * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance |
434 | * is built when `doEagerInit[Via]` is called; see those methods |
435 | * for more info. |
436 | */ |
437 | void addEagerInitSingleton(detail::SingletonHolderBase* entry); |
438 | |
439 | // Mark registration is complete; no more singletons can be |
440 | // registered at this point. |
441 | void registrationComplete(); |
442 | |
443 | /** |
444 | * Initialize all singletons which were marked as eager-initialized |
445 | * (using `shouldEagerInit()`). No return value. Propagates exceptions |
446 | * from constructors / create functions, as is the usual case when calling |
447 | * for example `Singleton<Foo>::get_weak()`. |
448 | */ |
449 | void doEagerInit(); |
450 | |
451 | /** |
452 | * Schedule eager singletons' initializations through the given executor. |
453 | * If baton ptr is not null, its `post` method is called after all |
454 | * early initialization has completed. |
455 | * |
456 | * If exceptions are thrown during initialization, this method will still |
457 | * `post` the baton to indicate completion. The exception will not propagate |
458 | * and future attempts to `try_get` or `get_weak` the failed singleton will |
459 | * retry initialization. |
460 | * |
461 | * Sample usage: |
462 | * |
463 | * folly::IOThreadPoolExecutor executor(max_concurrency_level); |
464 | * folly::Baton<> done; |
465 | * doEagerInitVia(executor, &done); |
466 | * done.wait(); // or 'try_wait_for', etc. |
467 | * |
468 | */ |
469 | void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr); |
470 | |
471 | // Destroy all singletons; when complete, the vault can't create |
472 | // singletons once again until reenableInstances() is called. |
473 | void destroyInstances(); |
474 | |
475 | // Enable re-creating singletons after destroyInstances() was called. |
476 | void reenableInstances(); |
477 | |
478 | // For testing; how many registered and living singletons we have. |
479 | size_t registeredSingletonCount() const { |
480 | return singletons_.rlock()->size(); |
481 | } |
482 | |
483 | /** |
484 | * Flips to true if eager initialization was used, and has completed. |
485 | * Never set to true if "doEagerInit()" or "doEagerInitVia" never called. |
486 | */ |
487 | bool eagerInitComplete() const; |
488 | |
489 | size_t livingSingletonCount() const { |
490 | auto singletons = singletons_.rlock(); |
491 | |
492 | size_t ret = 0; |
493 | for (const auto& p : *singletons) { |
494 | if (p.second->hasLiveInstance()) { |
495 | ++ret; |
496 | } |
497 | } |
498 | |
499 | return ret; |
500 | } |
501 | |
502 | // A well-known vault; you can actually have others, but this is the |
503 | // default. |
504 | static SingletonVault* singleton() { |
505 | return singleton<>(); |
506 | } |
507 | |
508 | // Gets singleton vault for any Tag. Non-default tag should be used in unit |
509 | // tests only. |
510 | template <typename VaultTag = detail::DefaultTag> |
511 | static SingletonVault* singleton() { |
512 | return &detail::createGlobal<SingletonVault, VaultTag>(); |
513 | } |
514 | |
515 | void setType(Type type) { |
516 | type_ = type; |
517 | } |
518 | |
519 | private: |
520 | template <typename T> |
521 | friend struct detail::SingletonHolder; |
522 | |
523 | // This method only matters if registrationComplete() is never called. |
524 | // Otherwise destroyInstances is scheduled to be executed atexit. |
525 | // |
526 | // Initializes static object, which calls destroyInstances on destruction. |
527 | // Used to have better deletion ordering with singleton not managed by |
528 | // folly::Singleton. The desruction will happen in the following order: |
529 | // 1. Singletons, not managed by folly::Singleton, which were created after |
530 | // any of the singletons managed by folly::Singleton was requested. |
531 | // 2. All singletons managed by folly::Singleton |
532 | // 3. Singletons, not managed by folly::Singleton, which were created before |
533 | // any of the singletons managed by folly::Singleton was requested. |
534 | static void scheduleDestroyInstances(); |
535 | |
536 | typedef std::unordered_map< |
537 | detail::TypeDescriptor, |
538 | detail::SingletonHolderBase*, |
539 | detail::TypeDescriptorHasher> |
540 | SingletonMap; |
541 | |
542 | // Use SharedMutexSuppressTSAN to suppress noisy lock inversions when building |
543 | // with TSAN. If TSAN is not enabled, SharedMutexSuppressTSAN is equivalent |
544 | // to a normal SharedMutex. |
545 | Synchronized<SingletonMap, SharedMutexSuppressTSAN> singletons_; |
546 | Synchronized< |
547 | std::unordered_set<detail::SingletonHolderBase*>, |
548 | SharedMutexSuppressTSAN> |
549 | eagerInitSingletons_; |
550 | Synchronized<std::vector<detail::TypeDescriptor>, SharedMutexSuppressTSAN> |
551 | creationOrder_; |
552 | |
553 | // Using SharedMutexReadPriority is important here, because we want to make |
554 | // sure we don't block nested singleton creation happening concurrently with |
555 | // destroyInstances(). |
556 | Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_; |
557 | |
558 | Type type_; |
559 | }; |
560 | |
561 | // This is the wrapper class that most users actually interact with. |
562 | // It allows for simple access to registering and instantiating |
563 | // singletons. Create instances of this class in the global scope of |
564 | // type Singleton<T> to register your singleton for later access via |
565 | // Singleton<T>::try_get(). |
566 | template < |
567 | typename T, |
568 | typename Tag = detail::DefaultTag, |
569 | typename VaultTag = detail::DefaultTag /* for testing */> |
570 | class Singleton { |
571 | public: |
572 | typedef std::function<T*(void)> CreateFunc; |
573 | typedef std::function<void(T*)> TeardownFunc; |
574 | |
575 | // Generally your program life cycle should be fine with calling |
576 | // get() repeatedly rather than saving the reference, and then not |
577 | // call get() during process shutdown. |
578 | [[deprecated("Replaced by try_get" )]] static T* get() { |
579 | return getEntry().get(); |
580 | } |
581 | |
582 | // If, however, you do need to hold a reference to the specific |
583 | // singleton, you can try to do so with a weak_ptr. Avoid this when |
584 | // possible but the inability to lock the weak pointer can be a |
585 | // signal that the vault has been destroyed. |
586 | [[deprecated("Replaced by try_get" )]] static std::weak_ptr<T> get_weak() { |
587 | return getEntry().get_weak(); |
588 | } |
589 | |
590 | // Preferred alternative to get_weak, it returns shared_ptr that can be |
591 | // stored; a singleton won't be destroyed unless shared_ptr is destroyed. |
592 | // Avoid holding these shared_ptrs beyond the scope of a function; |
593 | // don't put them in member variables, always use try_get() instead |
594 | // |
595 | // try_get() can return nullptr if the singleton was destroyed, caller is |
596 | // responsible for handling nullptr return |
597 | static std::shared_ptr<T> try_get() { |
598 | return getEntry().try_get(); |
599 | } |
600 | |
601 | static folly::ReadMostlySharedPtr<T> try_get_fast() { |
602 | return getEntry().try_get_fast(); |
603 | } |
604 | |
605 | /** |
606 | * Applies a callback to the possibly-nullptr singleton instance, returning |
607 | * the callback's result. That is, the following two are functionally |
608 | * equivalent: |
609 | * singleton.apply(std::ref(f)); |
610 | * f(singleton.try_get().get()); |
611 | * |
612 | * For example, the following returns the singleton |
613 | * instance directly without any extra operations on the instance: |
614 | * auto ret = Singleton<T>::apply([](auto* v) { return v; }); |
615 | */ |
616 | template <typename Func> |
617 | static invoke_result_t<Func, T*> apply(Func f) { |
618 | return getEntry().apply(std::ref(f)); |
619 | } |
620 | |
621 | // Quickly ensure the instance exists. |
622 | static void vivify() { |
623 | getEntry().vivify(); |
624 | } |
625 | |
626 | explicit Singleton( |
627 | std::nullptr_t /* _ */ = nullptr, |
628 | typename Singleton::TeardownFunc t = nullptr) |
629 | : Singleton([]() { return new T; }, std::move(t)) {} |
630 | |
631 | explicit Singleton( |
632 | typename Singleton::CreateFunc c, |
633 | typename Singleton::TeardownFunc t = nullptr) { |
634 | if (c == nullptr) { |
635 | detail::singletonThrowNullCreator(typeid(T)); |
636 | } |
637 | |
638 | auto vault = SingletonVault::singleton<VaultTag>(); |
639 | getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t))); |
640 | vault->registerSingleton(&getEntry()); |
641 | } |
642 | |
643 | /** |
644 | * Should be instantiated as soon as "doEagerInit[Via]" is called. |
645 | * Singletons are usually lazy-loaded (built on-demand) but for those which |
646 | * are known to be needed, to avoid the potential lag for objects that take |
647 | * long to construct during runtime, there is an option to make sure these |
648 | * are built up-front. |
649 | * |
650 | * Use like: |
651 | * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit(); |
652 | * |
653 | * Or alternately, define the singleton as usual, and say |
654 | * gFooInstance.shouldEagerInit(); |
655 | * |
656 | * at some point prior to calling registrationComplete(). |
657 | * Then doEagerInit() or doEagerInitVia(Executor*) can be called. |
658 | */ |
659 | Singleton& shouldEagerInit() { |
660 | auto vault = SingletonVault::singleton<VaultTag>(); |
661 | vault->addEagerInitSingleton(&getEntry()); |
662 | return *this; |
663 | } |
664 | |
665 | /** |
666 | * Construct and inject a mock singleton which should be used only from tests. |
667 | * Unlike regular singletons which are initialized once per process lifetime, |
668 | * mock singletons live for the duration of a test. This means that one |
669 | * process running multiple tests can initialize and register the same |
670 | * singleton multiple times. This functionality should be used only from tests |
671 | * since it relaxes validation and performance in order to be able to perform |
672 | * the injection. The returned mock singleton is functionality identical to |
673 | * regular singletons. |
674 | */ |
675 | static void make_mock( |
676 | std::nullptr_t /* c */ = nullptr, |
677 | typename Singleton<T>::TeardownFunc t = nullptr) { |
678 | make_mock([]() { return new T; }, t); |
679 | } |
680 | |
681 | static void make_mock( |
682 | CreateFunc c, |
683 | typename Singleton<T>::TeardownFunc t = nullptr) { |
684 | if (c == nullptr) { |
685 | detail::singletonThrowNullCreator(typeid(T)); |
686 | } |
687 | |
688 | auto& entry = getEntry(); |
689 | |
690 | entry.registerSingletonMock(c, getTeardownFunc(t)); |
691 | } |
692 | |
693 | private: |
694 | inline static detail::SingletonHolder<T>& getEntry() { |
695 | return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>(); |
696 | } |
697 | |
698 | // Construct TeardownFunc. |
699 | static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc( |
700 | TeardownFunc t) { |
701 | if (t == nullptr) { |
702 | return [](T* v) { delete v; }; |
703 | } else { |
704 | return t; |
705 | } |
706 | } |
707 | }; |
708 | |
709 | template <typename T, typename Tag = detail::DefaultTag> |
710 | class LeakySingleton { |
711 | public: |
712 | using CreateFunc = std::function<T*()>; |
713 | |
714 | LeakySingleton() : LeakySingleton([] { return new T(); }) {} |
715 | |
716 | explicit LeakySingleton(CreateFunc createFunc) { |
717 | auto& entry = entryInstance(); |
718 | if (entry.state != State::NotRegistered) { |
719 | detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_); |
720 | } |
721 | entry.createFunc = createFunc; |
722 | entry.state = State::Dead; |
723 | } |
724 | |
725 | static T& get() { |
726 | return instance(); |
727 | } |
728 | |
729 | static void make_mock(std::nullptr_t /* c */ = nullptr) { |
730 | make_mock([]() { return new T; }); |
731 | } |
732 | |
733 | static void make_mock(CreateFunc createFunc) { |
734 | if (createFunc == nullptr) { |
735 | detail::singletonThrowNullCreator(typeid(T)); |
736 | } |
737 | |
738 | auto& entry = entryInstance(); |
739 | if (entry.ptr) { |
740 | annotate_object_leaked(std::exchange(entry.ptr, nullptr)); |
741 | } |
742 | entry.createFunc = createFunc; |
743 | entry.state = State::Dead; |
744 | } |
745 | |
746 | private: |
747 | enum class State { NotRegistered, Dead, Living }; |
748 | |
749 | struct Entry { |
750 | Entry() noexcept {} |
751 | Entry(const Entry&) = delete; |
752 | Entry& operator=(const Entry&) = delete; |
753 | |
754 | std::atomic<State> state{State::NotRegistered}; |
755 | T* ptr{nullptr}; |
756 | CreateFunc createFunc; |
757 | std::mutex mutex; |
758 | detail::TypeDescriptor type_{typeid(T), typeid(Tag)}; |
759 | }; |
760 | |
761 | static Entry& entryInstance() { |
762 | return detail::createGlobal<Entry, Tag>(); |
763 | } |
764 | |
765 | static T& instance() { |
766 | auto& entry = entryInstance(); |
767 | if (UNLIKELY(entry.state != State::Living)) { |
768 | createInstance(); |
769 | } |
770 | |
771 | return *entry.ptr; |
772 | } |
773 | |
774 | static void createInstance() { |
775 | auto& entry = entryInstance(); |
776 | |
777 | std::lock_guard<std::mutex> lg(entry.mutex); |
778 | if (entry.state == State::Living) { |
779 | return; |
780 | } |
781 | |
782 | if (entry.state == State::NotRegistered) { |
783 | detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_); |
784 | } |
785 | |
786 | entry.ptr = entry.createFunc(); |
787 | entry.state = State::Living; |
788 | } |
789 | }; |
790 | } // namespace folly |
791 | |
792 | #include <folly/Singleton-inl.h> |
793 | |