FIRDatabase.m 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. /**
  41. * A static NSMutableDictionary of FirebaseApp names to FirebaseDatabase instance. To ensure thread-
  42. * safety, it should only be accessed in databaseForApp, which is synchronized.
  43. *
  44. * TODO: This serves a duplicate purpose as RepoManager. We should clean up.
  45. * TODO: We should maybe be conscious of leaks and make this a weak map or similar
  46. * but we have a lot of work to do to allow FirebaseDatabase/Repo etc. to be GC'd.
  47. */
  48. + (NSMutableDictionary *)instances {
  49. static dispatch_once_t pred = 0;
  50. static NSMutableDictionary *instances;
  51. dispatch_once(&pred, ^{
  52. instances = [NSMutableDictionary dictionary];
  53. });
  54. return instances;
  55. }
  56. + (FIRDatabase *)database {
  57. if (![FIRApp isDefaultAppConfigured]) {
  58. [NSException raise:@"FIRAppNotConfigured"
  59. format:@"Failed to get default Firebase Database instance. Must call `[FIRApp "
  60. @"configure]` (`FirebaseApp.configure()` in Swift) before using "
  61. @"Firebase Database."];
  62. }
  63. FIRApp *app = [FIRApp defaultApp];
  64. return [FIRDatabase databaseForApp:app];
  65. }
  66. + (FIRDatabase *)databaseForApp:(FIRApp *)app {
  67. if (app == nil) {
  68. [NSException raise:@"InvalidFIRApp" format:@"nil FIRApp instance passed to databaseForApp."];
  69. }
  70. NSMutableDictionary *instances = [self instances];
  71. @synchronized (instances) {
  72. FIRDatabase *database = instances[app.name];
  73. if (!database) {
  74. NSString *databaseUrl = app.options.databaseURL;
  75. if (databaseUrl == nil) {
  76. [NSException raise:@"MissingDatabaseURL" format:@"Failed to get FIRDatabase instance: FIRApp object has no "
  77. "databaseURL in its FirebaseOptions object."];
  78. }
  79. FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl];
  80. if (![parsedUrl.path isEmpty]) {
  81. [NSException raise:@"InvalidDatabaseURL" format:@"Configured Database URL '%@' is invalid. It should "
  82. "point to the root of a Firebase Database but it includes a path: %@",
  83. databaseUrl, [parsedUrl.path toString]];
  84. }
  85. id<FAuthTokenProvider> authTokenProvider = [FAuthTokenProvider authTokenProviderForApp:app];
  86. // If this is the default app, don't set the session persistence key so that we use our
  87. // default ("default") instead of the FIRApp default ("[DEFAULT]") so that we
  88. // preserve the default location used by the legacy Firebase SDK.
  89. NSString *sessionIdentifier = @"default";
  90. if ([FIRApp isDefaultAppConfigured] && app == [FIRApp defaultApp]) {
  91. sessionIdentifier = app.name;
  92. }
  93. FIRDatabaseConfig *config = [[FIRDatabaseConfig alloc] initWithSessionIdentifier:sessionIdentifier
  94. authTokenProvider:authTokenProvider];
  95. database = [[FIRDatabase alloc] initWithApp:app repoInfo:parsedUrl.repoInfo config:config];
  96. instances[app.name] = database;
  97. }
  98. return database;
  99. }
  100. }
  101. + (NSString *) buildVersion {
  102. // TODO: Restore git hash when build moves back to git
  103. return [NSString stringWithFormat:@"%s_%s", FIREBASE_SEMVER, __DATE__];
  104. }
  105. + (FIRDatabase *)createDatabaseForTests:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config {
  106. FIRDatabase *db = [[FIRDatabase alloc] initWithApp:nil repoInfo:repoInfo config:config];
  107. [db ensureRepo];
  108. return db;
  109. }
  110. + (NSString *) sdkVersion {
  111. return [NSString stringWithUTF8String:FIREBASE_SEMVER];
  112. }
  113. + (void) setLoggingEnabled:(BOOL)enabled {
  114. [FUtilities setLoggingEnabled:enabled];
  115. FFLog(@"I-RDB024001", @"BUILD Version: %@", [FIRDatabase buildVersion]);
  116. }
  117. - (id)initWithApp:(FIRApp *)app repoInfo:(FRepoInfo *)info config:(FIRDatabaseConfig *)config {
  118. self = [super init];
  119. if (self != nil) {
  120. self->_repoInfo = info;
  121. self->_config = config;
  122. self->_app = app;
  123. }
  124. return self;
  125. }
  126. - (FIRDatabaseReference *)reference {
  127. [self ensureRepo];
  128. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:[FPath empty]];
  129. }
  130. - (FIRDatabaseReference *)referenceWithPath:(NSString *)path {
  131. [self ensureRepo];
  132. [FValidation validateFrom:@"referenceWithPath" validRootPathString:path];
  133. FPath *childPath = [[FPath alloc] initWith:path];
  134. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:childPath];
  135. }
  136. - (FIRDatabaseReference *)referenceFromURL:(NSString *)databaseUrl {
  137. [self ensureRepo];
  138. if (databaseUrl == nil) {
  139. [NSException raise:@"InvalidDatabaseURL" format:@"Invalid nil url passed to referenceFromURL:"];
  140. }
  141. FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl];
  142. [FValidation validateFrom:@"referenceFromURL:" validURL:parsedUrl];
  143. if (![parsedUrl.repoInfo.host isEqualToString:_repoInfo.host]) {
  144. [NSException raise:@"InvalidDatabaseURL" format:@"Invalid URL (%@) passed to getReference(). URL was expected "
  145. "to match configured Database URL: %@", databaseUrl, [self reference].URL];
  146. }
  147. return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:parsedUrl.path];
  148. }
  149. - (void)purgeOutstandingWrites {
  150. [self ensureRepo];
  151. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  152. [self.repo purgeOutstandingWrites];
  153. });
  154. }
  155. - (void)goOnline {
  156. [self ensureRepo];
  157. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  158. [self.repo resume];
  159. });
  160. }
  161. - (void)goOffline {
  162. [self ensureRepo];
  163. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  164. [self.repo interrupt];
  165. });
  166. }
  167. - (void)setPersistenceEnabled:(BOOL)persistenceEnabled {
  168. [self assertUnfrozen:@"setPersistenceEnabled"];
  169. self->_config.persistenceEnabled = persistenceEnabled;
  170. }
  171. - (BOOL)persistenceEnabled {
  172. return self->_config.persistenceEnabled;
  173. }
  174. - (void)setPersistenceCacheSizeBytes:(NSUInteger)persistenceCacheSizeBytes {
  175. [self assertUnfrozen:@"setPersistenceCacheSizeBytes"];
  176. self->_config.persistenceCacheSizeBytes = persistenceCacheSizeBytes;
  177. }
  178. - (NSUInteger)persistenceCacheSizeBytes {
  179. return self->_config.persistenceCacheSizeBytes;
  180. }
  181. - (void)setCallbackQueue:(dispatch_queue_t)callbackQueue {
  182. [self assertUnfrozen:@"setCallbackQueue"];
  183. self->_config.callbackQueue = callbackQueue;
  184. }
  185. - (dispatch_queue_t)callbackQueue {
  186. return self->_config.callbackQueue;
  187. }
  188. - (void) assertUnfrozen:(NSString*)methodName {
  189. if (self.repo != nil) {
  190. [NSException raise:@"FIRDatabaseAlreadyInUse" format:@"Calls to %@ must be made before any other usage of "
  191. "FIRDatabase instance.", methodName];
  192. }
  193. }
  194. - (void) ensureRepo {
  195. if (self.repo == nil) {
  196. self.repo = [FRepoManager createRepo:self.repoInfo config:self.config database:self];
  197. }
  198. }
  199. @end