GDTCORFlatFileStorage.m 13 KB

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