FIRIAMClearcutLogStorage.m 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 <UIKit/UIKit.h>
  17. #import <FirebaseCore/FIRLogger.h>
  18. #import "FIRCore+InAppMessaging.h"
  19. #import "FIRIAMClearcutLogStorage.h"
  20. #import "FIRIAMTimeFetcher.h"
  21. @implementation FIRIAMClearcutLogRecord
  22. static NSString *const kEventTimestampKey = @"event_ts_seconds";
  23. static NSString *const kEventExtensionJson = @"extension_js";
  24. + (BOOL)supportsSecureCoding {
  25. return YES;
  26. }
  27. - (instancetype)initWithExtensionJsonString:(NSString *)jsonString
  28. eventTimestampInSeconds:(NSInteger)eventTimestampInSeconds {
  29. self = [super init];
  30. if (self != nil) {
  31. _eventTimestampInSeconds = eventTimestampInSeconds;
  32. _eventExtensionJsonString = jsonString;
  33. }
  34. return self;
  35. }
  36. - (id)initWithCoder:(NSCoder *)decoder {
  37. self = [super init];
  38. if (self != nil) {
  39. _eventTimestampInSeconds = [decoder decodeIntegerForKey:kEventTimestampKey];
  40. _eventExtensionJsonString = [decoder decodeObjectOfClass:[NSString class]
  41. forKey:kEventExtensionJson];
  42. }
  43. return self;
  44. }
  45. - (void)encodeWithCoder:(NSCoder *)encoder {
  46. [encoder encodeInteger:self.eventTimestampInSeconds forKey:kEventTimestampKey];
  47. [encoder encodeObject:self.eventExtensionJsonString forKey:kEventExtensionJson];
  48. }
  49. @end
  50. @interface FIRIAMClearcutLogStorage ()
  51. @property(nonatomic) NSInteger recordExpiresInSeconds;
  52. @property(nonatomic) NSMutableArray<FIRIAMClearcutLogRecord *> *records;
  53. @property(nonatomic) id<FIRIAMTimeFetcher> timeFetcher;
  54. @end
  55. // We keep all the records in memory and flush them into files upon receiving
  56. // applicationDidEnterBackground notifications.
  57. @implementation FIRIAMClearcutLogStorage
  58. + (NSString *)determineCacheFilePath {
  59. static NSString *logCachePath;
  60. static dispatch_once_t onceToken;
  61. dispatch_once(&onceToken, ^{
  62. NSString *libraryDirPath =
  63. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  64. logCachePath =
  65. [NSString stringWithFormat:@"%@/firebase-iam-clearcut-retry-records", libraryDirPath];
  66. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230001",
  67. @"Persistent file path for clearcut log records is %@", logCachePath);
  68. });
  69. return logCachePath;
  70. }
  71. - (instancetype)initWithExpireAfterInSeconds:(NSInteger)expireInSeconds
  72. withTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher
  73. cachePath:(nullable NSString *)cachePath {
  74. if (self = [super init]) {
  75. _records = [[NSMutableArray alloc] init];
  76. _timeFetcher = timeFetcher;
  77. _recordExpiresInSeconds = expireInSeconds;
  78. [[NSNotificationCenter defaultCenter] addObserver:self
  79. selector:@selector(appWillBecomeInactive:)
  80. name:UIApplicationWillResignActiveNotification
  81. object:nil];
  82. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  83. if (@available(iOS 13.0, *)) {
  84. [[NSNotificationCenter defaultCenter] addObserver:self
  85. selector:@selector(appWillBecomeInactive:)
  86. name:UISceneWillDeactivateNotification
  87. object:nil];
  88. }
  89. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  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 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  142. if (fetchedClearcutRetryRecords) {
  143. @synchronized(self) {
  144. self.records = (NSMutableArray<FIRIAMClearcutLogRecord *> *)fetchedClearcutRetryRecords;
  145. }
  146. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230002",
  147. @"Loaded %d clearcut log records from file in %lf seconds", (int)self.records.count,
  148. (double)[self.timeFetcher currentTimestampInSeconds] - start);
  149. }
  150. }
  151. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  152. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  153. @synchronized(self) {
  154. BOOL saveResult = [NSKeyedArchiver archiveRootObject:self.records toFile:filePath];
  155. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230003",
  156. @"Saving %d clearcut log records into file is %@", (int)self.records.count,
  157. saveResult ? @"successful" : @"failure");
  158. return saveResult;
  159. }
  160. }
  161. @end