GDTCORFlatFileStorage.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/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. completion(NO, error);
  103. return;
  104. } else {
  105. GDTCORLogDebug(@"Event saved to disk: %@", eventFile);
  106. completion(YES, error);
  107. }
  108. // Add event to tracking collections.
  109. [self addEventToTrackingCollections:event];
  110. // Have the prioritizer prioritize the event and save state if there was an onComplete block.
  111. [prioritizer prioritizeEvent:event];
  112. if (hadOriginalCompletion && [prioritizer respondsToSelector:@selector(saveState)]) {
  113. [prioritizer saveState];
  114. GDTCORLogDebug(@"Prioritizer %@ has saved state due to an event's onComplete block.",
  115. prioritizer);
  116. }
  117. // Check the QoS, if it's high priority, notify the target that it has a high priority event.
  118. if (event.qosTier == GDTCOREventQoSFast) {
  119. [self.uploadCoordinator forceUploadForTarget:target];
  120. }
  121. // Write state to disk if there was an onComplete block or if we're in the background.
  122. if (hadOriginalCompletion || [[GDTCORApplication sharedApplication] isRunningInBackground]) {
  123. if (hadOriginalCompletion) {
  124. GDTCORLogDebug(@"%@",
  125. @"Saving flat file storage state because a completion block was passed.");
  126. } else {
  127. GDTCORLogDebug(
  128. @"%@", @"Saving flat file storage state because the app is running in the background");
  129. }
  130. NSError *error;
  131. GDTCOREncodeArchive(self, [GDTCORFlatFileStorage archivePath], &error);
  132. if (error) {
  133. GDTCORLogDebug(@"Serializing GDTCORFlatFileStorage to an archive failed: %@", error);
  134. }
  135. }
  136. // Cancel or end the associated background task if it's still valid.
  137. [[GDTCORApplication sharedApplication] endBackgroundTask:bgID];
  138. bgID = GDTCORBackgroundIdentifierInvalid;
  139. GDTCORLogDebug(@"Event %@ is stored. There are %ld events stored on disk", event,
  140. (unsigned long)self->_storedEvents.count);
  141. });
  142. }
  143. - (void)removeEvents:(NSSet<NSNumber *> *)eventIDs {
  144. NSSet<NSNumber *> *eventsToRemove = [eventIDs copy];
  145. dispatch_async(_storageQueue, ^{
  146. for (NSNumber *eventID in eventsToRemove) {
  147. // Remove from disk, first and foremost.
  148. GDTCOREvent *event = self->_storedEvents[eventID];
  149. if (event) {
  150. NSError *error;
  151. if (event.fileURL) {
  152. NSURL *fileURL = event.fileURL;
  153. BOOL result = [[NSFileManager defaultManager] removeItemAtPath:fileURL.path error:&error];
  154. if (!result || error) {
  155. GDTCORLogWarning(GDTCORMCWFileReadError,
  156. @"There was an error removing an event file: %@", error);
  157. } else {
  158. GDTCORLogDebug(@"Removed event from disk: %@", fileURL);
  159. }
  160. }
  161. // Remove from the tracking collections.
  162. [self.storedEvents removeObjectForKey:event.eventID];
  163. [self.targetToEventSet[@(event.target)] removeObject:event];
  164. }
  165. }
  166. });
  167. }
  168. #pragma mark - Private helper methods
  169. /** Saves the event's dataObject to a file using NSData mechanisms.
  170. *
  171. * @note This method should only be called from a method within a block on _storageQueue to maintain
  172. * thread safety.
  173. *
  174. * @param event The event.
  175. * @param eventHash The hash value of the event.
  176. * @return The filename
  177. */
  178. - (NSURL *)saveEventBytesToDisk:(GDTCOREvent *)event
  179. eventHash:(NSUInteger)eventHash
  180. error:(NSError **)error {
  181. NSString *eventFileName = [NSString stringWithFormat:@"event-%lu", (unsigned long)eventHash];
  182. NSError *writingError;
  183. [event writeToGDTPath:eventFileName error:&writingError];
  184. if (writingError) {
  185. GDTCORLogDebug(@"There was an error saving an event to disk: %@", writingError);
  186. }
  187. return event.fileURL;
  188. }
  189. /** Adds the event to internal tracking collections.
  190. *
  191. * @note This method should only be called from a method within a block on _storageQueue to maintain
  192. * thread safety.
  193. *
  194. * @param event The event to track.
  195. */
  196. - (void)addEventToTrackingCollections:(GDTCOREvent *)event {
  197. _storedEvents[event.eventID] = event;
  198. NSNumber *target = @(event.target);
  199. NSMutableSet<GDTCOREvent *> *events = self.targetToEventSet[target];
  200. events = events ? events : [[NSMutableSet alloc] init];
  201. [events addObject:event];
  202. _targetToEventSet[target] = events;
  203. }
  204. #pragma mark - GDTCORLifecycleProtocol
  205. - (void)appWillForeground:(GDTCORApplication *)app {
  206. dispatch_async(_storageQueue, ^{
  207. NSError *error;
  208. GDTCORDecodeArchive([GDTCORFlatFileStorage class], [GDTCORFlatFileStorage archivePath], nil,
  209. &error);
  210. if (error) {
  211. GDTCORLogDebug(@"Deserializing GDTCORFlatFileStorage from an archive failed: %@", error);
  212. }
  213. });
  214. }
  215. - (void)appWillBackground:(GDTCORApplication *)app {
  216. dispatch_async(_storageQueue, ^{
  217. // Immediately request a background task to run until the end of the current queue of work, and
  218. // cancel it once the work is done.
  219. __block GDTCORBackgroundIdentifier bgID =
  220. [app beginBackgroundTaskWithName:@"GDTStorage"
  221. expirationHandler:^{
  222. [app endBackgroundTask:bgID];
  223. bgID = GDTCORBackgroundIdentifierInvalid;
  224. }];
  225. NSError *error;
  226. GDTCOREncodeArchive(self, [GDTCORFlatFileStorage archivePath], &error);
  227. if (error) {
  228. GDTCORLogDebug(@"Serializing GDTCORFlatFileStorage to an archive failed: %@", error);
  229. } else {
  230. GDTCORLogDebug(@"Serialized GDTCORFlatFileStorage to %@",
  231. [GDTCORFlatFileStorage archivePath]);
  232. }
  233. // End the background task if it's still valid.
  234. [app endBackgroundTask:bgID];
  235. bgID = GDTCORBackgroundIdentifierInvalid;
  236. });
  237. }
  238. - (void)appWillTerminate:(GDTCORApplication *)application {
  239. dispatch_sync(_storageQueue, ^{
  240. NSError *error;
  241. GDTCOREncodeArchive(self, [GDTCORFlatFileStorage archivePath], &error);
  242. if (error) {
  243. GDTCORLogDebug(@"Serializing GDTCORFlatFileStorage to an archive failed: %@", error);
  244. } else {
  245. GDTCORLogDebug(@"Serialized GDTCORFlatFileStorage to %@",
  246. [GDTCORFlatFileStorage archivePath]);
  247. }
  248. });
  249. }
  250. #pragma mark - NSSecureCoding
  251. /** The NSKeyedCoder key for the storedEvents property. */
  252. static NSString *const kGDTCORFlatFileStorageStoredEventsKey = @"GDTCORStorageStoredEventsKey";
  253. /** The NSKeyedCoder key for the targetToEventSet property. */
  254. static NSString *const kGDTCORFlatFileStorageTargetToEventSetKey =
  255. @"GDTCORStorageTargetToEventSetKey";
  256. /** The NSKeyedCoder key for the uploadCoordinator property. */
  257. static NSString *const kGDTCORFlatFileStorageUploadCoordinatorKey =
  258. @"GDTCORStorageUploadCoordinatorKey";
  259. + (BOOL)supportsSecureCoding {
  260. return YES;
  261. }
  262. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  263. // Create the singleton and populate its ivars.
  264. GDTCORFlatFileStorage *sharedInstance = [self.class sharedInstance];
  265. NSSet *classes = [NSSet setWithObjects:[NSMutableOrderedSet class], [NSMutableDictionary class],
  266. [GDTCOREvent class], nil];
  267. id storedEvents = [aDecoder decodeObjectOfClasses:classes
  268. forKey:kGDTCORFlatFileStorageStoredEventsKey];
  269. NSMutableDictionary<NSNumber *, GDTCOREvent *> *events = [[NSMutableDictionary alloc] init];
  270. if ([storedEvents isKindOfClass:[NSMutableOrderedSet class]]) {
  271. [(NSMutableOrderedSet *)storedEvents
  272. enumerateObjectsUsingBlock:^(GDTCOREvent *_Nonnull obj, NSUInteger idx,
  273. BOOL *_Nonnull stop) {
  274. events[obj.eventID] = obj;
  275. }];
  276. } else if ([storedEvents isKindOfClass:[NSMutableDictionary class]]) {
  277. events = (NSMutableDictionary *)storedEvents;
  278. }
  279. sharedInstance->_storedEvents = events;
  280. classes = [NSSet
  281. setWithObjects:[NSMutableDictionary class], [NSMutableSet class], [GDTCOREvent class], nil];
  282. sharedInstance->_targetToEventSet =
  283. [aDecoder decodeObjectOfClasses:classes forKey:kGDTCORFlatFileStorageTargetToEventSetKey];
  284. sharedInstance->_uploadCoordinator =
  285. [aDecoder decodeObjectOfClass:[GDTCORUploadCoordinator class]
  286. forKey:kGDTCORFlatFileStorageUploadCoordinatorKey];
  287. return sharedInstance;
  288. }
  289. - (void)encodeWithCoder:(NSCoder *)aCoder {
  290. GDTCORFlatFileStorage *sharedInstance = [self.class sharedInstance];
  291. NSMutableDictionary<NSNumber *, GDTCOREvent *> *storedEvents = sharedInstance->_storedEvents;
  292. if (storedEvents) {
  293. [aCoder encodeObject:storedEvents forKey:kGDTCORFlatFileStorageStoredEventsKey];
  294. }
  295. NSMutableDictionary<NSNumber *, NSMutableSet<GDTCOREvent *> *> *targetToEventSet =
  296. sharedInstance->_targetToEventSet;
  297. if (targetToEventSet) {
  298. [aCoder encodeObject:targetToEventSet forKey:kGDTCORFlatFileStorageTargetToEventSetKey];
  299. }
  300. GDTCORUploadCoordinator *uploadCoordinator = sharedInstance->_uploadCoordinator;
  301. if (uploadCoordinator) {
  302. [aCoder encodeObject:uploadCoordinator forKey:kGDTCORFlatFileStorageUploadCoordinatorKey];
  303. }
  304. }
  305. @end