FIRIAMClearcutLogStorage.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 || 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 (@available(iOS 13.0, tvOS 13.0, *)) {
  85. [[NSNotificationCenter defaultCenter] addObserver:self
  86. selector:@selector(appWillBecomeInactive:)
  87. name:UISceneWillDeactivateNotification
  88. object:nil];
  89. }
  90. @try {
  91. [self loadFromCachePath:cachePath];
  92. } @catch (NSException *exception) {
  93. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM230004",
  94. @"Non-fatal exception in loading persisted clearcut log records: %@.",
  95. exception);
  96. }
  97. }
  98. return self;
  99. }
  100. - (instancetype)initWithExpireAfterInSeconds:(NSInteger)expireInSeconds
  101. withTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher {
  102. return [self initWithExpireAfterInSeconds:expireInSeconds
  103. withTimeFetcher:timeFetcher
  104. cachePath:nil];
  105. }
  106. - (void)appWillBecomeInactive:(NSNotification *)notification {
  107. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
  108. [self saveIntoCacheWithPath:nil];
  109. });
  110. }
  111. - (void)dealloc {
  112. [[NSNotificationCenter defaultCenter] removeObserver:self];
  113. }
  114. - (void)pushRecords:(NSArray<FIRIAMClearcutLogRecord *> *)newRecords {
  115. @synchronized(self) {
  116. [self.records addObjectsFromArray:newRecords];
  117. }
  118. }
  119. - (NSArray<FIRIAMClearcutLogRecord *> *)popStillValidRecordsForUpTo:(NSInteger)upTo {
  120. NSMutableArray<FIRIAMClearcutLogRecord *> *resultArray = [[NSMutableArray alloc] init];
  121. NSInteger nowInSeconds = (NSInteger)[self.timeFetcher currentTimestampInSeconds];
  122. NSInteger next = 0;
  123. @synchronized(self) {
  124. while (resultArray.count < upTo && next < self.records.count) {
  125. FIRIAMClearcutLogRecord *nextRecord = self.records[next++];
  126. if (nextRecord.eventTimestampInSeconds > nowInSeconds - self.recordExpiresInSeconds) {
  127. // record not expired yet
  128. [resultArray addObject:nextRecord];
  129. }
  130. }
  131. [self.records removeObjectsInRange:NSMakeRange(0, next)];
  132. }
  133. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230005",
  134. @"Returning %d clearcut retry records from popStillValidRecords",
  135. (int)resultArray.count);
  136. return resultArray;
  137. }
  138. - (void)loadFromCachePath:(NSString *)cacheFilePath {
  139. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  140. NSTimeInterval start = [self.timeFetcher currentTimestampInSeconds];
  141. id fetchedClearcutRetryRecords;
  142. NSData *data = [NSData dataWithContentsOfFile:filePath];
  143. if (data) {
  144. fetchedClearcutRetryRecords = [NSKeyedUnarchiver
  145. unarchivedObjectOfClasses:[NSSet setWithObjects:[FIRIAMClearcutLogRecord class],
  146. [NSMutableArray class], nil]
  147. fromData:data
  148. error:nil];
  149. }
  150. if (fetchedClearcutRetryRecords) {
  151. @synchronized(self) {
  152. self.records = (NSMutableArray<FIRIAMClearcutLogRecord *> *)fetchedClearcutRetryRecords;
  153. }
  154. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230002",
  155. @"Loaded %d clearcut log records from file in %lf seconds", (int)self.records.count,
  156. (double)[self.timeFetcher currentTimestampInSeconds] - start);
  157. }
  158. }
  159. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  160. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  161. @synchronized(self) {
  162. #pragma clang diagnostic push
  163. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  164. BOOL saveResult = [NSKeyedArchiver archiveRootObject:self.records toFile:filePath];
  165. #pragma clang diagnostic pop
  166. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230003",
  167. @"Saving %d clearcut log records into file is %@", (int)self.records.count,
  168. saveResult ? @"successful" : @"failure");
  169. return saveResult;
  170. }
  171. }
  172. @end
  173. #endif // TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION