FIRDatabase.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. * Copyright 2017 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 <Foundation/Foundation.h>
  17. #import "FIRAppInternal.h"
  18. #import "FIRLogger.h"
  19. #import "FIRDatabase.h"
  20. #import "FIRDatabase_Private.h"
  21. #import "FIRDatabaseQuery_Private.h"
  22. #import "FRepoManager.h"
  23. #import "FValidation.h"
  24. #import "FIRDatabaseConfig_Private.h"
  25. #import "FRepoInfo.h"
  26. #import "FIRDatabaseConfig.h"
  27. #import "FIRDatabaseReference_Private.h"
  28. #import "FIROptions.h"
  29. @interface FIRDatabase ()
  30. @property (nonatomic, strong) FRepoInfo *repoInfo;
  31. @property (nonatomic, strong) FIRDatabaseConfig *config;
  32. @property (nonatomic, strong) FRepo *repo;
  33. @end
  34. @implementation FIRDatabase
  35. // The STR and STR_EXPAND macro allow a numeric version passed to he compiler driver
  36. // with a -D to be treated as a string instead of an invalid floating point value.
  37. #define STR(x) STR_EXPAND(x)
  38. #define STR_EXPAND(x) #x
  39. static const char *FIREBASE_SEMVER = (const char *)STR(FIRDatabase_VERSION);
  40. + (void)load {
  41. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  42. [center addObserverForName:kFIRAppDeleteNotification
  43. object:nil
  44. queue:nil
  45. usingBlock:^(NSNotification * _Nonnull note) {
  46. NSString *appName = note.userInfo[kFIRAppNameKey];
  47. if (appName == nil) { return; }
  48. NSMutableDictionary *instances = [self instances];
  49. @synchronized (instances) {
  50. FIRDatabase *deletedApp = instances[appName];
  51. // Clean up the deleted instance in an effort to remove any resources still in use.
  52. // Note: Any leftover instances of this exact database will be invalid.
  53. [FRepoManager disposeRepos:deletedApp.config];
  54. [instances removeObjectForKey:appName];
  55. }
  56. }];
  57. }
  58. /**
  59. * A static NSMutableDictionary of FirebaseApp names to FirebaseDatabase instance. To ensure thread-
  60. * safety, it should only be accessed in databaseForApp, which is synchronized.
  61. *
  62. * TODO: This serves a duplicate purpose as RepoManager. We should clean up.
  63. * TODO: We should maybe be conscious of leaks and make this a weak map or similar
  64. * but we have a lot of work to do to allow FirebaseDatabase/Repo etc. to be GC'd.
  65. */
  66. + (NSMutableDictionary *)instances {
  67. static dispatch_once_t pred = 0;
  68. static NSMutableDictionary *instances;
  69. dispatch_once(&pred, ^{
  70. instances = [NSMutableDictionary dictionary];
  71. });
  72. return instances;
  73. }
  74. + (FIRDatabase *)database {
  75. if (![FIRApp isDefaultAppConfigured]) {
  76. [NSException raise:@"FIRAppNotConfigured"
  77. format:@"Failed to get default Firebase Database instance. Must call `[FIRApp "
  78. @"configure]` (`FirebaseApp.configure()` in Swift) before using "
  79. @"Firebase Database."];
  80. }
  81. FIRApp *app = [FIRApp defaultApp];
  82. return [FIRDatabase databaseForApp:app];
  83. }
  84. + (FIRDatabase *)databaseForApp:(FIRApp *)app {
  85. if (app == nil) {
  86. [NSException raise:@"InvalidFIRApp" format:@"nil FIRApp instance passed to databaseForApp."];
  87. }
  88. NSMutableDictionary *instances = [self instances];
  89. @synchronized (instances) {
  90. FIRDatabase *database = instances[app.name];
  91. if (!database) {
  92. NSString *databaseUrl = app.options.databaseURL;
  93. if (databaseUrl == nil) {
  94. [NSException raise:@"MissingDatabaseURL" format:@"Failed to get FIRDatabase instance: FIRApp object has no "
  95. "databaseURL in its FirebaseOptions object."];
  96. }
  97. FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl];
  98. if (![parsedUrl.path isEmpty]) {
  99. [NSException raise:@"InvalidDatabaseURL" format:@"Configured Database URL '%@' is invalid. It should "
  100. "point to the root of a Firebase Database but it includes a path: %@",
  101. databaseUrl, [parsedUrl.path toString]];
  102. }
  103. id<FAuthTokenProvider> authTokenProvider = [FAuthTokenProvider authTokenProviderForApp:app];
  104. // If this is the default app, don't set the session persistence key so that we use our
  105. // default ("default") instead of the FIRApp default ("[DEFAULT]") so that we
  106. // preserve the default location used by the legacy Firebase SDK.
  107. NSString *sessionIdentifier = @"default";
  108. if (![FIRApp isDefaultAppConfigured] || app != [FIRApp defaultApp]) {
  109. sessionIdentifier = app.name;
  110. }
  111. FIRDatabaseConfig *config = [[FIRDatabaseConfig alloc] initWithSessionIdentifier:sessionIdentifier
  112. authTokenProvider:authTokenProvider];
  113. database = [[FIRDatabase alloc] initWithApp:app repoInfo:parsedUrl.repoInfo config:config];
  114. instances[app.name] = database;
  115. }
  116. return database;
  117. }
  118. }
  119. + (NSString *) buildVersion {
  120. // TODO: Restore git hash when build moves back to git
  121. return [NSString stringWithFormat:@"%s_%s", FIREBASE_SEMVER, __DATE__];
  122. }
  123. + (FIRDatabase *)createDatabaseForTests:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config {
  124. FIRDatabase *db = [[FIRDatabase alloc] initWithApp:nil repoInfo:repoInfo config:config];
  125. [db ensureRepo];
  126. return db;
  127. }
  128. + (NSString *) sdkVersion {
  129. return [NSString stringWithUTF8String:FIREBASE_SEMVER];
  130. }
  131. + (void) setLoggingEnabled:(BOOL)enabled {
  132. [FUtilities setLoggingEnabled:enabled];
  133. FFLog(@"I-RDB024001", @"BUILD Version: %@", [FIRDatabase buildVersion]);
  134. }
  135. - (id)initWithApp:(FIRApp *)app repoInfo:(FRepoInfo *)info config:(FIRDatabaseConfig *)config {
  136. self = [super init];
  137. if (self != nil) {
  138. self->_repoInfo = info;
  139. self->_config = config;
  140. self->_app = app;
  141. }
  142. return self;
  143. }
  144. - (FIRDatabaseReference *)reference {
  145. [self ensureRepo];
  146. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:[FPath empty]];
  147. }
  148. - (FIRDatabaseReference *)referenceWithPath:(NSString *)path {
  149. [self ensureRepo];
  150. [FValidation validateFrom:@"referenceWithPath" validRootPathString:path];
  151. FPath *childPath = [[FPath alloc] initWith:path];
  152. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:childPath];
  153. }
  154. - (FIRDatabaseReference *)referenceFromURL:(NSString *)databaseUrl {
  155. [self ensureRepo];
  156. if (databaseUrl == nil) {
  157. [NSException raise:@"InvalidDatabaseURL" format:@"Invalid nil url passed to referenceFromURL:"];
  158. }
  159. FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl];
  160. [FValidation validateFrom:@"referenceFromURL:" validURL:parsedUrl];
  161. if (![parsedUrl.repoInfo.host isEqualToString:_repoInfo.host]) {
  162. [NSException raise:@"InvalidDatabaseURL" format:@"Invalid URL (%@) passed to getReference(). URL was expected "
  163. "to match configured Database URL: %@", databaseUrl, [self reference].URL];
  164. }
  165. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:parsedUrl.path];
  166. }
  167. - (void)purgeOutstandingWrites {
  168. [self ensureRepo];
  169. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  170. [self.repo purgeOutstandingWrites];
  171. });
  172. }
  173. - (void)goOnline {
  174. [self ensureRepo];
  175. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  176. [self.repo resume];
  177. });
  178. }
  179. - (void)goOffline {
  180. [self ensureRepo];
  181. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  182. [self.repo interrupt];
  183. });
  184. }
  185. - (void)setPersistenceEnabled:(BOOL)persistenceEnabled {
  186. [self assertUnfrozen:@"setPersistenceEnabled"];
  187. self->_config.persistenceEnabled = persistenceEnabled;
  188. }
  189. - (BOOL)persistenceEnabled {
  190. return self->_config.persistenceEnabled;
  191. }
  192. - (void)setPersistenceCacheSizeBytes:(NSUInteger)persistenceCacheSizeBytes {
  193. [self assertUnfrozen:@"setPersistenceCacheSizeBytes"];
  194. self->_config.persistenceCacheSizeBytes = persistenceCacheSizeBytes;
  195. }
  196. - (NSUInteger)persistenceCacheSizeBytes {
  197. return self->_config.persistenceCacheSizeBytes;
  198. }
  199. - (void)setCallbackQueue:(dispatch_queue_t)callbackQueue {
  200. [self assertUnfrozen:@"setCallbackQueue"];
  201. self->_config.callbackQueue = callbackQueue;
  202. }
  203. - (dispatch_queue_t)callbackQueue {
  204. return self->_config.callbackQueue;
  205. }
  206. - (void) assertUnfrozen:(NSString*)methodName {
  207. if (self.repo != nil) {
  208. [NSException raise:@"FIRDatabaseAlreadyInUse" format:@"Calls to %@ must be made before any other usage of "
  209. "FIRDatabase instance.", methodName];
  210. }
  211. }
  212. - (void) ensureRepo {
  213. if (self.repo == nil) {
  214. self.repo = [FRepoManager createRepo:self.repoInfo config:self.config database:self];
  215. }
  216. }
  217. @end