GDTCORStorage.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. if (_runningInBackground) {
  74. bgID = [[GDTCORApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  75. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  76. [[GDTCORApplication sharedApplication] endBackgroundTask:bgID];
  77. bgID = GDTCORBackgroundIdentifierInvalid;
  78. }
  79. }];
  80. }
  81. dispatch_async(_storageQueue, ^{
  82. // Check that a backend implementation is available for this target.
  83. NSInteger target = event.target;
  84. // Check that a prioritizer is available for this target.
  85. id<GDTCORPrioritizer> prioritizer =
  86. [GDTCORRegistrar sharedInstance].targetToPrioritizer[@(target)];
  87. GDTCORAssert(prioritizer, @"There's no prioritizer registered for the given target.");
  88. // Write the transport bytes to disk, get a filename.
  89. GDTCORAssert(event.dataObjectTransportBytes, @"The event should have been serialized to bytes");
  90. NSURL *eventFile = [self saveEventBytesToDisk:event.dataObjectTransportBytes
  91. eventHash:event.hash];
  92. GDTCORDataFuture *dataFuture = [[GDTCORDataFuture alloc] initWithFileURL:eventFile];
  93. GDTCORStoredEvent *storedEvent = [event storedEventWithDataFuture:dataFuture];
  94. // Add event to tracking collections.
  95. [self addEventToTrackingCollections:storedEvent];
  96. // Have the prioritizer prioritize the event.
  97. [prioritizer prioritizeEvent:storedEvent];
  98. // Check the QoS, if it's high priority, notify the target that it has a high priority event.
  99. if (event.qosTier == GDTCOREventQoSFast) {
  100. [self.uploadCoordinator forceUploadForTarget:target];
  101. }
  102. // Write state to disk.
  103. if (self->_runningInBackground) {
  104. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  105. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  106. requiringSecureCoding:YES
  107. error:nil];
  108. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  109. } else {
  110. #if !defined(TARGET_OS_MACCATALYST)
  111. [NSKeyedArchiver archiveRootObject:self toFile:[GDTCORStorage archivePath]];
  112. #endif
  113. }
  114. }
  115. // If running in the background, save state to disk and end the associated background task.
  116. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  117. [[GDTCORApplication sharedApplication] endBackgroundTask:bgID];
  118. bgID = GDTCORBackgroundIdentifierInvalid;
  119. }
  120. });
  121. }
  122. - (void)removeEvents:(NSSet<GDTCORStoredEvent *> *)events {
  123. NSSet<GDTCORStoredEvent *> *eventsToRemove = [events copy];
  124. dispatch_async(_storageQueue, ^{
  125. for (GDTCORStoredEvent *event in eventsToRemove) {
  126. // Remove from disk, first and foremost.
  127. NSError *error;
  128. if (event.dataFuture.fileURL) {
  129. NSURL *fileURL = event.dataFuture.fileURL;
  130. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];
  131. GDTCORAssert(error == nil, @"There was an error removing an event file: %@", error);
  132. }
  133. // Remove from the tracking collections.
  134. [self.storedEvents removeObject:event];
  135. [self.targetToEventSet[event.target] removeObject:event];
  136. }
  137. });
  138. }
  139. #pragma mark - Private helper methods
  140. /** Creates the storage directory if it does not exist. */
  141. - (void)createEventDirectoryIfNotExists {
  142. NSError *error;
  143. BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:GDTCORStoragePath()
  144. withIntermediateDirectories:YES
  145. attributes:0
  146. error:&error];
  147. if (!result || error) {
  148. GDTCORLogError(GDTCORMCEDirectoryCreationError, @"Error creating the directory: %@", error);
  149. }
  150. }
  151. /** Saves the event's dataObjectTransportBytes to a file using NSData mechanisms.
  152. *
  153. * @note This method should only be called from a method within a block on _storageQueue to maintain
  154. * thread safety.
  155. *
  156. * @param transportBytes The transport bytes of the event.
  157. * @param eventHash The hash value of the event.
  158. * @return The filename
  159. */
  160. - (NSURL *)saveEventBytesToDisk:(NSData *)transportBytes eventHash:(NSUInteger)eventHash {
  161. NSString *storagePath = GDTCORStoragePath();
  162. NSString *event = [NSString stringWithFormat:@"event-%lu", (unsigned long)eventHash];
  163. NSURL *eventFilePath = [NSURL fileURLWithPath:[storagePath stringByAppendingPathComponent:event]];
  164. GDTCORAssert(![[NSFileManager defaultManager] fileExistsAtPath:eventFilePath.path],
  165. @"An event shouldn't already exist at this path: %@", eventFilePath.path);
  166. BOOL writingSuccess = [transportBytes writeToURL:eventFilePath atomically:YES];
  167. if (!writingSuccess) {
  168. GDTCORLogError(GDTCORMCEFileWriteError, @"An event file could not be written: %@",
  169. eventFilePath);
  170. }
  171. return eventFilePath;
  172. }
  173. /** Adds the event to internal tracking collections.
  174. *
  175. * @note This method should only be called from a method within a block on _storageQueue to maintain
  176. * thread safety.
  177. *
  178. * @param event The event to track.
  179. */
  180. - (void)addEventToTrackingCollections:(GDTCORStoredEvent *)event {
  181. [_storedEvents addObject:event];
  182. NSMutableSet<GDTCORStoredEvent *> *events = self.targetToEventSet[event.target];
  183. events = events ? events : [[NSMutableSet alloc] init];
  184. [events addObject:event];
  185. _targetToEventSet[event.target] = events;
  186. }
  187. #pragma mark - GDTCORLifecycleProtocol
  188. - (void)appWillForeground:(GDTCORApplication *)app {
  189. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  190. NSData *data = [NSData dataWithContentsOfFile:[GDTCORStorage archivePath]];
  191. [NSKeyedUnarchiver unarchivedObjectOfClass:[GDTCORStorage class] fromData:data error:nil];
  192. } else {
  193. #if !defined(TARGET_OS_MACCATALYST)
  194. [NSKeyedUnarchiver unarchiveObjectWithFile:[GDTCORStorage archivePath]];
  195. #endif
  196. }
  197. }
  198. - (void)appWillBackground:(GDTCORApplication *)app {
  199. self->_runningInBackground = YES;
  200. dispatch_async(_storageQueue, ^{
  201. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  202. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  203. requiringSecureCoding:YES
  204. error:nil];
  205. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  206. } else {
  207. #if !defined(TARGET_OS_MACCATALYST)
  208. [NSKeyedArchiver archiveRootObject:self toFile:[GDTCORStorage archivePath]];
  209. #endif
  210. }
  211. });
  212. // Create an immediate background task to run until the end of the current queue of work.
  213. __block GDTCORBackgroundIdentifier bgID = [app beginBackgroundTaskWithExpirationHandler:^{
  214. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  215. [app endBackgroundTask:bgID];
  216. bgID = GDTCORBackgroundIdentifierInvalid;
  217. }
  218. }];
  219. dispatch_async(_storageQueue, ^{
  220. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  221. [app endBackgroundTask:bgID];
  222. bgID = GDTCORBackgroundIdentifierInvalid;
  223. }
  224. });
  225. }
  226. - (void)appWillTerminate:(GDTCORApplication *)application {
  227. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  228. NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self
  229. requiringSecureCoding:YES
  230. error:nil];
  231. [data writeToFile:[GDTCORStorage archivePath] atomically:YES];
  232. } else {
  233. #if !defined(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