FIRIAMClearcutLogStorage.m 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 <TargetConditionals.h>
  17. #if TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) && TARGET_OS_VISION)
  18. #import <UIKit/UIKit.h>
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseInAppMessaging/Sources/Analytics/FIRIAMClearcutLogStorage.h"
  21. #import "FirebaseInAppMessaging/Sources/FIRCore+InAppMessaging.h"
  22. #import "FirebaseInAppMessaging/Sources/Private/Util/FIRIAMTimeFetcher.h"
  23. @implementation FIRIAMClearcutLogRecord
  24. static NSString *const kEventTimestampKey = @"event_ts_seconds";
  25. static NSString *const kEventExtensionJson = @"extension_js";
  26. + (BOOL)supportsSecureCoding {
  27. return YES;
  28. }
  29. - (instancetype)initWithExtensionJsonString:(NSString *)jsonString
  30. eventTimestampInSeconds:(NSInteger)eventTimestampInSeconds {
  31. self = [super init];
  32. if (self != nil) {
  33. _eventTimestampInSeconds = eventTimestampInSeconds;
  34. _eventExtensionJsonString = jsonString;
  35. }
  36. return self;
  37. }
  38. - (id)initWithCoder:(NSCoder *)decoder {
  39. self = [super init];
  40. if (self != nil) {
  41. _eventTimestampInSeconds = [decoder decodeIntegerForKey:kEventTimestampKey];
  42. _eventExtensionJsonString = [decoder decodeObjectOfClass:[NSString class]
  43. forKey:kEventExtensionJson];
  44. }
  45. return self;
  46. }
  47. - (void)encodeWithCoder:(NSCoder *)encoder {
  48. [encoder encodeInteger:self.eventTimestampInSeconds forKey:kEventTimestampKey];
  49. [encoder encodeObject:self.eventExtensionJsonString forKey:kEventExtensionJson];
  50. }
  51. @end
  52. @interface FIRIAMClearcutLogStorage ()
  53. @property(nonatomic) NSInteger recordExpiresInSeconds;
  54. @property(nonatomic) NSMutableArray<FIRIAMClearcutLogRecord *> *records;
  55. @property(nonatomic) id<FIRIAMTimeFetcher> timeFetcher;
  56. @end
  57. // We keep all the records in memory and flush them into files upon receiving
  58. // applicationDidEnterBackground notifications.
  59. @implementation FIRIAMClearcutLogStorage
  60. + (NSString *)determineCacheFilePath {
  61. static NSString *logCachePath;
  62. static dispatch_once_t onceToken;
  63. dispatch_once(&onceToken, ^{
  64. NSString *libraryDirPath =
  65. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  66. logCachePath =
  67. [NSString stringWithFormat:@"%@/firebase-iam-clearcut-retry-records", libraryDirPath];
  68. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230001",
  69. @"Persistent file path for clearcut log records is %@", logCachePath);
  70. });
  71. return logCachePath;
  72. }
  73. - (instancetype)initWithExpireAfterInSeconds:(NSInteger)expireInSeconds
  74. withTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher
  75. cachePath:(nullable NSString *)cachePath {
  76. if (self = [super init]) {
  77. _records = [[NSMutableArray alloc] init];
  78. _timeFetcher = timeFetcher;
  79. _recordExpiresInSeconds = expireInSeconds;
  80. [[NSNotificationCenter defaultCenter] addObserver:self
  81. selector:@selector(appWillBecomeInactive:)
  82. name:UIApplicationWillResignActiveNotification
  83. object:nil];
  84. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  85. if (@available(iOS 13.0, tvOS 13.0, *)) {
  86. [[NSNotificationCenter defaultCenter] addObserver:self
  87. selector:@selector(appWillBecomeInactive:)
  88. name:UISceneWillDeactivateNotification
  89. object:nil];
  90. }
  91. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  92. @try {
  93. [self loadFromCachePath:cachePath];
  94. } @catch (NSException *exception) {
  95. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM230004",
  96. @"Non-fatal exception in loading persisted clearcut log records: %@.",
  97. exception);
  98. }
  99. }
  100. return self;
  101. }
  102. - (instancetype)initWithExpireAfterInSeconds:(NSInteger)expireInSeconds
  103. withTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher {
  104. return [self initWithExpireAfterInSeconds:expireInSeconds
  105. withTimeFetcher:timeFetcher
  106. cachePath:nil];
  107. }
  108. - (void)appWillBecomeInactive:(NSNotification *)notification {
  109. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
  110. [self saveIntoCacheWithPath:nil];
  111. });
  112. }
  113. - (void)dealloc {
  114. [[NSNotificationCenter defaultCenter] removeObserver:self];
  115. }
  116. - (void)pushRecords:(NSArray<FIRIAMClearcutLogRecord *> *)newRecords {
  117. @synchronized(self) {
  118. [self.records addObjectsFromArray:newRecords];
  119. }
  120. }
  121. - (NSArray<FIRIAMClearcutLogRecord *> *)popStillValidRecordsForUpTo:(NSInteger)upTo {
  122. NSMutableArray<FIRIAMClearcutLogRecord *> *resultArray = [[NSMutableArray alloc] init];
  123. NSInteger nowInSeconds = (NSInteger)[self.timeFetcher currentTimestampInSeconds];
  124. NSInteger next = 0;
  125. @synchronized(self) {
  126. while (resultArray.count < upTo && next < self.records.count) {
  127. FIRIAMClearcutLogRecord *nextRecord = self.records[next++];
  128. if (nextRecord.eventTimestampInSeconds > nowInSeconds - self.recordExpiresInSeconds) {
  129. // record not expired yet
  130. [resultArray addObject:nextRecord];
  131. }
  132. }
  133. [self.records removeObjectsInRange:NSMakeRange(0, next)];
  134. }
  135. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230005",
  136. @"Returning %d clearcut retry records from popStillValidRecords",
  137. (int)resultArray.count);
  138. return resultArray;
  139. }
  140. - (void)loadFromCachePath:(NSString *)cacheFilePath {
  141. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  142. NSTimeInterval start = [self.timeFetcher currentTimestampInSeconds];
  143. id fetchedClearcutRetryRecords;
  144. NSData *data = [NSData dataWithContentsOfFile:filePath];
  145. if (data) {
  146. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  147. fetchedClearcutRetryRecords = [NSKeyedUnarchiver
  148. unarchivedObjectOfClasses:[NSSet setWithObjects:[FIRIAMClearcutLogRecord class],
  149. [NSMutableArray class], nil]
  150. fromData:data
  151. error:nil];
  152. } else {
  153. // Fallback on earlier versions
  154. #pragma clang diagnostic push
  155. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  156. fetchedClearcutRetryRecords = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  157. #pragma clang diagnostic pop
  158. }
  159. }
  160. if (fetchedClearcutRetryRecords) {
  161. @synchronized(self) {
  162. self.records = (NSMutableArray<FIRIAMClearcutLogRecord *> *)fetchedClearcutRetryRecords;
  163. }
  164. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230002",
  165. @"Loaded %d clearcut log records from file in %lf seconds", (int)self.records.count,
  166. (double)[self.timeFetcher currentTimestampInSeconds] - start);
  167. }
  168. }
  169. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  170. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  171. @synchronized(self) {
  172. #pragma clang diagnostic push
  173. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  174. BOOL saveResult = [NSKeyedArchiver archiveRootObject:self.records toFile:filePath];
  175. #pragma clang diagnostic pop
  176. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230003",
  177. @"Saving %d clearcut log records into file is %@", (int)self.records.count,
  178. saveResult ? @"successful" : @"failure");
  179. return saveResult;
  180. }
  181. }
  182. @end
  183. #endif // TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) && TARGET_OS_VISION)