No Description

FIRComponentContainer.m 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. * Copyright 2018 Google
  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. #import "Private/FIRComponentContainer.h"
  17. #import "Private/FIRAppInternal.h"
  18. #import "Private/FIRComponent.h"
  19. #import "Private/FIRLibrary.h"
  20. #import "Private/FIRLogger.h"
  21. NS_ASSUME_NONNULL_BEGIN
  22. @interface FIRComponentContainer ()
  23. /// The dictionary of components that are registered for a particular app. The key is an `NSString`
  24. /// of the protocol.
  25. @property(nonatomic, strong) NSMutableDictionary<NSString *, FIRComponentCreationBlock> *components;
  26. /// Cached instances of components that requested to be cached.
  27. @property(nonatomic, strong) NSMutableDictionary<NSString *, id> *cachedInstances;
  28. /// Protocols of components that have requested to be eagerly instantiated.
  29. @property(nonatomic, strong, nullable) NSMutableArray<Protocol *> *eagerProtocolsToInstantiate;
  30. @end
  31. @implementation FIRComponentContainer
  32. // Collection of all classes that register to provide components.
  33. static NSMutableSet<Class> *sFIRComponentRegistrants;
  34. #pragma mark - Public Registration
  35. + (void)registerAsComponentRegistrant:(Class<FIRLibrary>)klass {
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. sFIRComponentRegistrants = [[NSMutableSet<Class> alloc] init];
  39. });
  40. [self registerAsComponentRegistrant:klass inSet:sFIRComponentRegistrants];
  41. }
  42. + (void)registerAsComponentRegistrant:(Class<FIRLibrary>)klass
  43. inSet:(NSMutableSet<Class> *)allRegistrants {
  44. [allRegistrants addObject:klass];
  45. }
  46. #pragma mark - Internal Initialization
  47. - (instancetype)initWithApp:(FIRApp *)app {
  48. return [self initWithApp:app registrants:sFIRComponentRegistrants];
  49. }
  50. - (instancetype)initWithApp:(FIRApp *)app registrants:(NSMutableSet<Class> *)allRegistrants {
  51. self = [super init];
  52. if (self) {
  53. _app = app;
  54. _cachedInstances = [NSMutableDictionary<NSString *, id> dictionary];
  55. _components = [NSMutableDictionary<NSString *, FIRComponentCreationBlock> dictionary];
  56. [self populateComponentsFromRegisteredClasses:allRegistrants forApp:app];
  57. }
  58. return self;
  59. }
  60. - (void)populateComponentsFromRegisteredClasses:(NSSet<Class> *)classes forApp:(FIRApp *)app {
  61. // Keep track of any components that need to eagerly instantiate after all components are added.
  62. self.eagerProtocolsToInstantiate = [[NSMutableArray alloc] init];
  63. // Loop through the verified component registrants and populate the components array.
  64. for (Class<FIRLibrary> klass in classes) {
  65. // Loop through all the components being registered and store them as appropriate.
  66. // Classes which do not provide functionality should use a dummy FIRComponentRegistrant
  67. // protocol.
  68. for (FIRComponent *component in [klass componentsToRegister]) {
  69. // Check if the component has been registered before, and error out if so.
  70. NSString *protocolName = NSStringFromProtocol(component.protocol);
  71. if (self.components[protocolName]) {
  72. FIRLogError(kFIRLoggerCore, @"I-COR000029",
  73. @"Attempted to register protocol %@, but it already has an implementation.",
  74. protocolName);
  75. continue;
  76. }
  77. // Store the creation block for later usage.
  78. self.components[protocolName] = component.creationBlock;
  79. // Queue any protocols that should be eagerly instantiated. Don't instantiate them yet
  80. // because they could depend on other components that haven't been added to the components
  81. // array yet.
  82. BOOL shouldInstantiateEager =
  83. (component.instantiationTiming == FIRInstantiationTimingAlwaysEager);
  84. BOOL shouldInstantiateDefaultEager =
  85. (component.instantiationTiming == FIRInstantiationTimingEagerInDefaultApp &&
  86. [app isDefaultApp]);
  87. if (shouldInstantiateEager || shouldInstantiateDefaultEager) {
  88. [self.eagerProtocolsToInstantiate addObject:component.protocol];
  89. }
  90. }
  91. }
  92. }
  93. #pragma mark - Instance Creation
  94. - (void)instantiateEagerComponents {
  95. // After all components are registered, instantiate the ones that are requesting eager
  96. // instantiation.
  97. @synchronized(self) {
  98. for (Protocol *protocol in self.eagerProtocolsToInstantiate) {
  99. // Get an instance for the protocol, which will instantiate it since it couldn't have been
  100. // cached yet. Ignore the instance coming back since we don't need it.
  101. __unused id unusedInstance = [self instanceForProtocol:protocol];
  102. }
  103. // All eager instantiation is complete, clear the stored property now.
  104. self.eagerProtocolsToInstantiate = nil;
  105. }
  106. }
  107. /// Instantiate an instance of a class that conforms to the specified protocol.
  108. /// This will:
  109. /// - Call the block to create an instance if possible,
  110. /// - Validate that the instance returned conforms to the protocol it claims to,
  111. /// - Cache the instance if the block requests it
  112. ///
  113. /// Note that this method assumes the caller already has @sychronized on self.
  114. - (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol
  115. withBlock:(FIRComponentCreationBlock)creationBlock {
  116. if (!creationBlock) {
  117. return nil;
  118. }
  119. // Create an instance using the creation block.
  120. BOOL shouldCache = NO;
  121. id instance = creationBlock(self, &shouldCache);
  122. if (!instance) {
  123. return nil;
  124. }
  125. // An instance was created, validate that it conforms to the protocol it claims to.
  126. NSString *protocolName = NSStringFromProtocol(protocol);
  127. if (![instance conformsToProtocol:protocol]) {
  128. FIRLogError(kFIRLoggerCore, @"I-COR000030",
  129. @"An instance conforming to %@ was requested, but the instance provided does not "
  130. @"conform to the protocol",
  131. protocolName);
  132. }
  133. // The instance is ready to be returned, but check if it should be cached first before returning.
  134. if (shouldCache) {
  135. self.cachedInstances[protocolName] = instance;
  136. }
  137. return instance;
  138. }
  139. #pragma mark - Internal Retrieval
  140. - (nullable id)instanceForProtocol:(Protocol *)protocol {
  141. // Check if there is a cached instance, and return it if so.
  142. NSString *protocolName = NSStringFromProtocol(protocol);
  143. id cachedInstance;
  144. @synchronized(self) {
  145. cachedInstance = self.cachedInstances[protocolName];
  146. if (!cachedInstance) {
  147. // Use the creation block to instantiate an instance and return it.
  148. FIRComponentCreationBlock creationBlock = self.components[protocolName];
  149. cachedInstance = [self instantiateInstanceForProtocol:protocol withBlock:creationBlock];
  150. }
  151. }
  152. return cachedInstance;
  153. }
  154. #pragma mark - Lifecycle
  155. - (void)removeAllCachedInstances {
  156. @synchronized(self) {
  157. // Loop through the cache and notify each instance that is a maintainer to clean up after
  158. // itself.
  159. for (id instance in self.cachedInstances.allValues) {
  160. if ([instance conformsToProtocol:@protocol(FIRComponentLifecycleMaintainer)] &&
  161. [instance respondsToSelector:@selector(appWillBeDeleted:)]) {
  162. [instance appWillBeDeleted:self.app];
  163. }
  164. }
  165. // Empty the cache.
  166. [self.cachedInstances removeAllObjects];
  167. }
  168. }
  169. @end
  170. NS_ASSUME_NONNULL_END