GDTCORStorage.m 12 KB

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