GDTCORStorage.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 "GDTCORLibrary/Private/GDTCORStorage.h"
  17. #import "GDTCORLibrary/Private/GDTCORStorage_Private.h"
  18. #import <GoogleDataTransport/GDTCORAssert.h>
  19. #import <GoogleDataTransport/GDTCORConsoleLogger.h>
  20. #import <GoogleDataTransport/GDTCOREvent.h>
  21. #import <GoogleDataTransport/GDTCORLifecycle.h>
  22. #import <GoogleDataTransport/GDTCORPrioritizer.h>
  23. #import "GDTCORLibrary/Private/GDTCOREvent_Private.h"
  24. #import "GDTCORLibrary/Private/GDTCORRegistrar_Private.h"
  25. #import "GDTCORLibrary/Private/GDTCORUploadCoordinator.h"
  26. /** Creates and/or returns a singleton NSString that is the shared storage path.
  27. *
  28. * @return The SDK event storage path.
  29. */
  30. static NSString *GDTCORStoragePath() {
  31. static NSString *storagePath;
  32. static dispatch_once_t onceToken;
  33. dispatch_once(&onceToken, ^{
  34. NSString *cachePath =
  35. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  36. storagePath = [NSString stringWithFormat:@"%@/google-sdks-events", cachePath];
  37. GDTCORLogDebug("Events will be saved to %@", storagePath);
  38. });
  39. return storagePath;
  40. }
  41. @implementation GDTCORStorage
  42. + (NSString *)archivePath {
  43. static NSString *archivePath;
  44. static dispatch_once_t onceToken;
  45. dispatch_once(&onceToken, ^{
  46. archivePath = [GDTCORStoragePath() stringByAppendingPathComponent:@"GDTCORStorageArchive"];
  47. });
  48. return archivePath;
  49. }
  50. + (instancetype)sharedInstance {
  51. static GDTCORStorage *sharedStorage;
  52. static dispatch_once_t onceToken;
  53. dispatch_once(&onceToken, ^{
  54. sharedStorage = [[GDTCORStorage alloc] init];
  55. });
  56. return sharedStorage;
  57. }
  58. - (instancetype)init {
  59. self = [super init];
  60. if (self) {
  61. _storageQueue = dispatch_queue_create("com.google.GDTCORStorage", DISPATCH_QUEUE_SERIAL);
  62. _targetToEventSet = [[NSMutableDictionary alloc] init];
  63. _storedEvents = [[NSMutableOrderedSet alloc] init];
  64. _uploadCoordinator = [GDTCORUploadCoordinator sharedInstance];
  65. }
  66. return self;
  67. }
  68. - (void)storeEvent:(GDTCOREvent *)event
  69. onComplete:(void (^)(BOOL wasWritten, NSError *error))completion {
  70. GDTCORLogDebug("Saving event: %@", event);
  71. if (event == nil) {
  72. GDTCORLogDebug("%@", @"The event was nil, so it was not saved.");
  73. return;
  74. }
  75. if (!completion) {
  76. completion = ^(BOOL wasWritten, NSError *error) {
  77. };
  78. }
  79. [self createEventDirectoryIfNotExists];
  80. __block GDTCORBackgroundIdentifier bgID = GDTCORBackgroundIdentifierInvalid;
  81. bgID = [[GDTCORApplication sharedApplication]
  82. beginBackgroundTaskWithName:@"GDTStorage"
  83. expirationHandler:^{
  84. // End the background task if it's still valid.
  85. [[GDTCORApplication sharedApplication] endBackgroundTask:bgID];
  86. bgID = GDTCORBackgroundIdentifierInvalid;
  87. }];
  88. dispatch_async(_storageQueue, ^{
  89. // Check that a backend implementation is available for this target.
  90. NSInteger target = event.target;
  91. // Check that a prioritizer is available for this target.
  92. id<GDTCORPrioritizer> prioritizer =
  93. [GDTCORRegistrar sharedInstance].targetToPrioritizer[@(target)];
  94. GDTCORAssert(prioritizer, @"There's no prioritizer registered for the given target. Are you "
  95. @"sure you've added the support library for the backend you need?");
  96. // Write the transport bytes to disk, get a filename.
  97. GDTCORAssert([event.dataObject transportBytes],
  98. @"The event should have been serialized to bytes");
  99. NSError *error = nil;
  100. NSURL *eventFile = [self saveEventBytesToDisk:event eventHash:event.hash error:&error];
  101. GDTCORLogDebug("Event saved to disk: %@", eventFile);
  102. completion(eventFile != nil, error);
  103. // Add event to tracking collections.
  104. [self addEventToTrackingCollections:event];
  105. // Have the prioritizer prioritize the event.
  106. [prioritizer prioritizeEvent:event];
  107. // Check the QoS, if it's high priority, notify the target that it has a high priority event.
  108. if (event.qosTier == GDTCOREventQoSFast) {
  109. [self.uploadCoordinator forceUploadForTarget:target];
  110. }
  111. // Write state to disk if we're in the background.
  112. if ([[GDTCORApplication sharedApplication] isRunningInBackground]) {
  113. GDTCORLogDebug("%@", @"Saving storage state because the app is running in the background");
  114. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  115. NSError *error;
  116. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  117. requiringSecureCoding:YES
  118. error:&error];
  119. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  120. } else {
  121. #if !TARGET_OS_MACCATALYST && !TARGET_OS_WATCH
  122. [NSKeyedArchiver archiveRootObject:self toFile:[GDTCORStorage archivePath]];
  123. #endif
  124. }
  125. }
  126. // Cancel or end the associated background task if it's still valid.
  127. [[GDTCORApplication sharedApplication] endBackgroundTask:bgID];
  128. bgID = GDTCORBackgroundIdentifierInvalid;
  129. GDTCORLogDebug("Event %@ is stored. There are %ld events stored on disk", event,
  130. (unsigned long)self->_storedEvents.count);
  131. });
  132. }
  133. - (void)removeEvents:(NSSet<GDTCOREvent *> *)events {
  134. NSSet<GDTCOREvent *> *eventsToRemove = [events copy];
  135. dispatch_async(_storageQueue, ^{
  136. for (GDTCOREvent *event in eventsToRemove) {
  137. // Remove from disk, first and foremost.
  138. NSError *error;
  139. if (event.fileURL) {
  140. NSURL *fileURL = event.fileURL;
  141. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];
  142. GDTCORAssert(error == nil, @"There was an error removing an event file: %@", error);
  143. GDTCORLogDebug("Removed event from disk: %@", fileURL);
  144. }
  145. // Remove from the tracking collections.
  146. [self.storedEvents removeObject:event];
  147. [self.targetToEventSet[@(event.target)] removeObject:event];
  148. }
  149. });
  150. }
  151. #pragma mark - Private helper methods
  152. /** Creates the storage directory if it does not exist. */
  153. - (void)createEventDirectoryIfNotExists {
  154. NSError *error;
  155. BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:GDTCORStoragePath()
  156. withIntermediateDirectories:YES
  157. attributes:0
  158. error:&error];
  159. if (!result || error) {
  160. GDTCORLogError(GDTCORMCEDirectoryCreationError, @"Error creating the directory: %@", error);
  161. }
  162. }
  163. /** Saves the event's dataObject to a file using NSData mechanisms.
  164. *
  165. * @note This method should only be called from a method within a block on _storageQueue to maintain
  166. * thread safety.
  167. *
  168. * @param event The event.
  169. * @param eventHash The hash value of the event.
  170. * @return The filename
  171. */
  172. - (NSURL *)saveEventBytesToDisk:(GDTCOREvent *)event
  173. eventHash:(NSUInteger)eventHash
  174. error:(NSError **)error {
  175. NSString *storagePath = GDTCORStoragePath();
  176. NSString *eventFileName = [NSString stringWithFormat:@"event-%lu", (unsigned long)eventHash];
  177. NSURL *eventFilePath =
  178. [NSURL fileURLWithPath:[storagePath stringByAppendingPathComponent:eventFileName]];
  179. GDTCORAssert(![[NSFileManager defaultManager] fileExistsAtPath:eventFilePath.path],
  180. @"An event shouldn't already exist at this path: %@", eventFilePath.path);
  181. [event writeToURL:eventFilePath error:error];
  182. return eventFilePath;
  183. }
  184. /** Adds the event to internal tracking collections.
  185. *
  186. * @note This method should only be called from a method within a block on _storageQueue to maintain
  187. * thread safety.
  188. *
  189. * @param event The event to track.
  190. */
  191. - (void)addEventToTrackingCollections:(GDTCOREvent *)event {
  192. [_storedEvents addObject:event];
  193. NSNumber *target = @(event.target);
  194. NSMutableSet<GDTCOREvent *> *events = self.targetToEventSet[target];
  195. events = events ? events : [[NSMutableSet alloc] init];
  196. [events addObject:event];
  197. _targetToEventSet[target] = events;
  198. }
  199. #pragma mark - GDTCORLifecycleProtocol
  200. - (void)appWillForeground:(GDTCORApplication *)app {
  201. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  202. NSError *error;
  203. NSData *data = [NSData dataWithContentsOfFile:[GDTCORStorage archivePath]];
  204. if (data) {
  205. [NSKeyedUnarchiver unarchivedObjectOfClass:[GDTCORStorage class] fromData:data error:&error];
  206. }
  207. } else {
  208. #if !TARGET_OS_MACCATALYST && !TARGET_OS_WATCH
  209. [NSKeyedUnarchiver unarchiveObjectWithFile:[GDTCORStorage archivePath]];
  210. #endif
  211. }
  212. }
  213. - (void)appWillBackground:(GDTCORApplication *)app {
  214. dispatch_async(_storageQueue, ^{
  215. // Immediately request a background task to run until the end of the current queue of work, and
  216. // cancel it once the work is done.
  217. __block GDTCORBackgroundIdentifier bgID =
  218. [app beginBackgroundTaskWithName:@"GDTStorage"
  219. expirationHandler:^{
  220. [app endBackgroundTask:bgID];
  221. bgID = GDTCORBackgroundIdentifierInvalid;
  222. }];
  223. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  224. NSError *error;
  225. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  226. requiringSecureCoding:YES
  227. error:&error];
  228. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  229. } else {
  230. #if !TARGET_OS_MACCATALYST && !TARGET_OS_WATCH
  231. [NSKeyedArchiver archiveRootObject:self toFile:[GDTCORStorage archivePath]];
  232. #endif
  233. }
  234. // End the background task if it's still valid.
  235. [app endBackgroundTask:bgID];
  236. bgID = GDTCORBackgroundIdentifierInvalid;
  237. });
  238. }
  239. - (void)appWillTerminate:(GDTCORApplication *)application {
  240. dispatch_sync(_storageQueue, ^{
  241. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  242. NSError *error;
  243. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  244. requiringSecureCoding:YES
  245. error:&error];
  246. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  247. } else {
  248. #if !TARGET_OS_MACCATALYST && !TARGET_OS_WATCH
  249. [NSKeyedArchiver archiveRootObject:self toFile:[GDTCORStorage archivePath]];
  250. #endif
  251. }
  252. });
  253. }
  254. #pragma mark - NSSecureCoding
  255. /** The NSKeyedCoder key for the storedEvents property. */
  256. static NSString *const kGDTCORStorageStoredEventsKey = @"GDTCORStorageStoredEventsKey";
  257. /** The NSKeyedCoder key for the targetToEventSet property. */
  258. static NSString *const kGDTCORStorageTargetToEventSetKey = @"GDTCORStorageTargetToEventSetKey";
  259. /** The NSKeyedCoder key for the uploadCoordinator property. */
  260. static NSString *const kGDTCORStorageUploadCoordinatorKey = @"GDTCORStorageUploadCoordinatorKey";
  261. + (BOOL)supportsSecureCoding {
  262. return YES;
  263. }
  264. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  265. // Sets a global translation mapping to decode GDTCORStoredEvent objects encoded as instances of
  266. // GDTCOREvent instead.
  267. [NSKeyedUnarchiver setClass:[GDTCOREvent class] forClassName:@"GDTCORStoredEvent"];
  268. // Create the singleton and populate its ivars.
  269. GDTCORStorage *sharedInstance = [self.class sharedInstance];
  270. dispatch_sync(sharedInstance.storageQueue, ^{
  271. NSSet *classes = [NSSet setWithObjects:[NSMutableOrderedSet class], [GDTCOREvent class], nil];
  272. sharedInstance->_storedEvents = [aDecoder decodeObjectOfClasses:classes
  273. forKey:kGDTCORStorageStoredEventsKey];
  274. classes = [NSSet
  275. setWithObjects:[NSMutableDictionary class], [NSMutableSet class], [GDTCOREvent class], nil];
  276. sharedInstance->_targetToEventSet =
  277. [aDecoder decodeObjectOfClasses:classes forKey:kGDTCORStorageTargetToEventSetKey];
  278. sharedInstance->_uploadCoordinator =
  279. [aDecoder decodeObjectOfClass:[GDTCORUploadCoordinator class]
  280. forKey:kGDTCORStorageUploadCoordinatorKey];
  281. });
  282. return sharedInstance;
  283. }
  284. - (void)encodeWithCoder:(NSCoder *)aCoder {
  285. GDTCORStorage *sharedInstance = [self.class sharedInstance];
  286. NSMutableOrderedSet<GDTCOREvent *> *storedEvents = sharedInstance->_storedEvents;
  287. if (storedEvents) {
  288. [aCoder encodeObject:storedEvents forKey:kGDTCORStorageStoredEventsKey];
  289. }
  290. NSMutableDictionary<NSNumber *, NSMutableSet<GDTCOREvent *> *> *targetToEventSet =
  291. sharedInstance->_targetToEventSet;
  292. if (targetToEventSet) {
  293. [aCoder encodeObject:targetToEventSet forKey:kGDTCORStorageTargetToEventSetKey];
  294. }
  295. GDTCORUploadCoordinator *uploadCoordinator = sharedInstance->_uploadCoordinator;
  296. if (uploadCoordinator) {
  297. [aCoder encodeObject:uploadCoordinator forKey:kGDTCORStorageUploadCoordinatorKey];
  298. }
  299. }
  300. @end