FIRIAMClearcutLogStorage.m 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. @try {
  83. [self loadFromCachePath:cachePath];
  84. } @catch (NSException *exception) {
  85. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM230004",
  86. @"Non-fatal exception in loading persisted clearcut log records: %@.",
  87. exception);
  88. }
  89. }
  90. return self;
  91. }
  92. - (instancetype)initWithExpireAfterInSeconds:(NSInteger)expireInSeconds
  93. withTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher {
  94. return [self initWithExpireAfterInSeconds:expireInSeconds
  95. withTimeFetcher:timeFetcher
  96. cachePath:nil];
  97. }
  98. - (void)appWillBecomeInactive {
  99. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
  100. [self saveIntoCacheWithPath:nil];
  101. });
  102. }
  103. - (void)dealloc {
  104. [[NSNotificationCenter defaultCenter] removeObserver:self];
  105. }
  106. - (void)pushRecords:(NSArray<FIRIAMClearcutLogRecord *> *)newRecords {
  107. @synchronized(self) {
  108. [self.records addObjectsFromArray:newRecords];
  109. }
  110. }
  111. - (NSArray<FIRIAMClearcutLogRecord *> *)popStillValidRecordsForUpTo:(NSInteger)upTo {
  112. NSMutableArray<FIRIAMClearcutLogRecord *> *resultArray = [[NSMutableArray alloc] init];
  113. NSInteger nowInSeconds = (NSInteger)[self.timeFetcher currentTimestampInSeconds];
  114. NSInteger next = 0;
  115. @synchronized(self) {
  116. while (resultArray.count < upTo && next < self.records.count) {
  117. FIRIAMClearcutLogRecord *nextRecord = self.records[next++];
  118. if (nextRecord.eventTimestampInSeconds > nowInSeconds - self.recordExpiresInSeconds) {
  119. // record not expired yet
  120. [resultArray addObject:nextRecord];
  121. }
  122. }
  123. [self.records removeObjectsInRange:NSMakeRange(0, next)];
  124. }
  125. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230005",
  126. @"Returning %d clearcut retry records from popStillValidRecords",
  127. (int)resultArray.count);
  128. return resultArray;
  129. }
  130. - (void)loadFromCachePath:(NSString *)cacheFilePath {
  131. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  132. NSTimeInterval start = [self.timeFetcher currentTimestampInSeconds];
  133. id fetchedClearcutRetryRecords = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  134. if (fetchedClearcutRetryRecords) {
  135. @synchronized(self) {
  136. self.records = (NSMutableArray<FIRIAMClearcutLogRecord *> *)fetchedClearcutRetryRecords;
  137. }
  138. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230002",
  139. @"Loaded %d clearcut log records from file in %lf seconds", (int)self.records.count,
  140. (double)[self.timeFetcher currentTimestampInSeconds] - start);
  141. }
  142. }
  143. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  144. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  145. @synchronized(self) {
  146. BOOL saveResult = [NSKeyedArchiver archiveRootObject:self.records toFile:filePath];
  147. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM230003",
  148. @"Saving %d clearcut log records into file is %@", (int)self.records.count,
  149. saveResult ? @"successful" : @"failure");
  150. return saveResult;
  151. }
  152. }
  153. @end