FIRComponentContainer.m 9.3 KB

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