GDTCORStorage.m 12 KB

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