diff --git a/Crashlytics/CHANGELOG.md b/Crashlytics/CHANGELOG.md index 1cba8a640e4..9797da4dfd0 100644 --- a/Crashlytics/CHANGELOG.md +++ b/Crashlytics/CHANGELOG.md @@ -1,4 +1,8 @@ # Unreleased +- [fixed] Fixed a thread-safety issue where stored on-demand exception paths + could be accessed concurrently from multiple queues when data collection is + disabled, and ensured queued on-demand exceptions re-check consent after + rate-limiting delays and are cleaned up by `deleteUnsentReports()`. (#16805) - [fixed] Fixed two Swift concurrency warnings in Firebase Sessions when building for watchOS with Xcode 27. (#17119) diff --git a/Crashlytics/Crashlytics/Controllers/FIRCLSExistingReportManager.m b/Crashlytics/Crashlytics/Controllers/FIRCLSExistingReportManager.m index e46526a077a..415f2e11bf0 100644 --- a/Crashlytics/Crashlytics/Controllers/FIRCLSExistingReportManager.m +++ b/Crashlytics/Crashlytics/Controllers/FIRCLSExistingReportManager.m @@ -176,12 +176,12 @@ - (void)sendUnsentReportsWithToken:(FIRCLSDataCollectionToken *)dataCollectionTo asUrgent:urgent]; } - for (NSString *path in self.onDemandModel.storedActiveReportPaths) { + NSArray *storedOnDemandPaths = [self.onDemandModel takeStoredActiveReportPaths]; + for (NSString *path in storedOnDemandPaths) { [self processExistingActiveReportPath:path dataCollectionToken:dataCollectionToken asUrgent:urgent]; } - [self.onDemandModel.storedActiveReportPaths removeAllObjects]; // deal with stuff in processing more carefully - do not process again [self.operationQueue addOperationWithBlock:^{ @@ -241,8 +241,11 @@ - (void)processExistingActiveReportPath:(NSString *)path } - (void)deleteUnsentReports { + NSArray *storedOnDemandPaths = + [self.onDemandModel takeStoredActiveReportPaths] ?: @[]; NSArray *reportPaths = @[]; reportPaths = [reportPaths arrayByAddingObjectsFromArray:self.existingUnemptyActiveReportPaths]; + reportPaths = [reportPaths arrayByAddingObjectsFromArray:storedOnDemandPaths]; reportPaths = [reportPaths arrayByAddingObjectsFromArray:self.processingReportPaths]; reportPaths = [reportPaths arrayByAddingObjectsFromArray:self.preparedReportPaths]; diff --git a/Crashlytics/Crashlytics/FIRCrashlytics.m b/Crashlytics/Crashlytics/FIRCrashlytics.m index c406dab4603..ca93d796ac4 100644 --- a/Crashlytics/Crashlytics/FIRCrashlytics.m +++ b/Crashlytics/Crashlytics/FIRCrashlytics.m @@ -497,8 +497,7 @@ - (void)recordOnDemandExceptionModel:(FIRExceptionModel *)exceptionModel { callback:^{ [self.managerData.onDemandModel recordOnDemandExceptionIfQuota:copiedModel - withDataCollectionEnabled:[self.dataArbiter - isCrashlyticsCollectionEnabled] + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; }]; } diff --git a/Crashlytics/Crashlytics/Models/FIRCLSOnDemandModel.m b/Crashlytics/Crashlytics/Models/FIRCLSOnDemandModel.m index 649940f0bd9..ba4918a3a4d 100644 --- a/Crashlytics/Crashlytics/Models/FIRCLSOnDemandModel.m +++ b/Crashlytics/Crashlytics/Models/FIRCLSOnDemandModel.m @@ -40,7 +40,7 @@ @interface FIRCLSOnDemandModel () @property(nonatomic) double currentStep; @property(nonatomic, strong) FIRCLSFileManager *fileManager; -@property(nonatomic, strong) NSMutableArray *storedActiveReportPaths; +@property(nonatomic, strong, readonly) NSMutableArray *storedActiveReportPaths; @end @@ -78,7 +78,7 @@ - (instancetype)initWithFIRCLSSettings:(FIRCLSSettings *)settings _lastUpdated = [NSDate timeIntervalSinceReferenceDate]; _currentStep = -1; - self.storedActiveReportPaths = [NSMutableArray array]; + _storedActiveReportPaths = [NSMutableArray array]; return self; } @@ -88,7 +88,7 @@ - (instancetype)initWithFIRCLSSettings:(FIRCLSSettings *)settings * rate limiting and exponential backoff. */ - (BOOL)recordOnDemandExceptionIfQuota:(FIRExceptionModel *)exceptionModel - withDataCollectionEnabled:(BOOL)dataCollectionEnabled + withDataArbiter:(FIRCLSDataCollectionArbiter *)dataArbiter usingExistingReportManager:(FIRCLSExistingReportManager *)existingReportManager { // Record the exception model into a new report if there is unused on-demand quota. Otherwise, // log the occurrence but drop the event. @@ -118,16 +118,15 @@ - (BOOL)recordOnDemandExceptionIfQuota:(FIRExceptionModel *)exceptionModel [self.operationQueue addOperationWithBlock:^{ double uploadDelay = [self calculateUploadDelay]; - if (dataCollectionEnabled) { + if ([dataArbiter isCrashlyticsCollectionEnabled]) { [existingReportManager handleOnDemandReportUpload:activeReportPath dataCollectionToken:dataCollectionToken asUrgent:YES]; FIRCLSDebugLog(@"Submitted an on-demand exception, starting delay %.20f", uploadDelay); } else { - [self.storedActiveReportPaths insertObject:activeReportPath atIndex:0]; - if ([self.storedActiveReportPaths count] > FIRCLSMaxUnsentReports) { - [self.fileManager removeItemAtPath:[self.storedActiveReportPaths lastObject]]; - [self.storedActiveReportPaths removeLastObject]; + NSString *evictedPath = [self storeActiveReportPath:activeReportPath]; + if (evictedPath) { + [self.fileManager removeItemAtPath:evictedPath]; [self decrementRecordedExceptionCount]; [self incrementDroppedExceptionCount]; } @@ -140,6 +139,32 @@ - (BOOL)recordOnDemandExceptionIfQuota:(FIRExceptionModel *)exceptionModel } } +- (NSArray *)takeStoredActiveReportPaths { + @synchronized(_storedActiveReportPaths) { + NSArray *paths = [_storedActiveReportPaths copy]; + [_storedActiveReportPaths removeAllObjects]; + return paths; + } +} + +- (NSArray *)storedActiveReportPathsSnapshot { + @synchronized(_storedActiveReportPaths) { + return [_storedActiveReportPaths copy]; + } +} + +- (NSString *)storeActiveReportPath:(NSString *)activeReportPath { + @synchronized(_storedActiveReportPaths) { + [_storedActiveReportPaths insertObject:activeReportPath atIndex:0]; + if ([_storedActiveReportPaths count] > FIRCLSMaxUnsentReports) { + NSString *evictedPath = [_storedActiveReportPaths lastObject]; + [_storedActiveReportPaths removeLastObject]; + return evictedPath; + } + return nil; + } +} + - (double)calculateUploadDelay { double calculatedStepDuration = [self calculateStepDuration]; double power = pow(self.settings.onDemandBackoffBase, calculatedStepDuration); diff --git a/Crashlytics/Crashlytics/Private/FIRCLSOnDemandModel_Private.h b/Crashlytics/Crashlytics/Private/FIRCLSOnDemandModel_Private.h index 3b589446eb8..b291bbbc1f8 100644 --- a/Crashlytics/Crashlytics/Private/FIRCLSOnDemandModel_Private.h +++ b/Crashlytics/Crashlytics/Private/FIRCLSOnDemandModel_Private.h @@ -22,22 +22,25 @@ #import "Crashlytics/Crashlytics/Private/FIRCLSExistingReportManager_Private.h" #import "Crashlytics/Crashlytics/Private/FIRExceptionModel_Private.h" +@class FIRCLSDataCollectionArbiter; + @interface FIRCLSOnDemandModel (Private) - (instancetype)initWithFIRCLSSettings:(FIRCLSSettings *)settings fileManager:(FIRCLSFileManager *)fileManager; - (BOOL)recordOnDemandExceptionIfQuota:(FIRExceptionModel *)exceptionModel - withDataCollectionEnabled:(BOOL)dataCollectionEnabled + withDataArbiter:(FIRCLSDataCollectionArbiter *)dataArbiter usingExistingReportManager:(FIRCLSExistingReportManager *)existingReportManager; - (int)getQueuedOperationsCount; - (void)setQueuedOperationsCount:(int)count; -// When data collection is off, stores active paths that have been recorded but not dispatched for -// upload. Kept sorted (newest at front) so that we can limit on-device reports to the newest -// `FIRCLSMaxUnsentReports` reports. -@property(nonatomic, strong) NSMutableArray *storedActiveReportPaths; +// Returns a copy of the stored active report paths and removes the original. +- (NSArray *)takeStoredActiveReportPaths; + +// Returns a copy of the currently stored active report paths without removing them. +- (NSArray *)storedActiveReportPathsSnapshot; @property(nonatomic, readonly) int recordedOnDemandExceptionCount; @property(nonatomic, readonly) int droppedOnDemandExceptionCount; diff --git a/Crashlytics/UnitTests/FIRCLSOnDemandModelTests.m b/Crashlytics/UnitTests/FIRCLSOnDemandModelTests.m index 94c41d4c4ce..fb15e7406d1 100644 --- a/Crashlytics/UnitTests/FIRCLSOnDemandModelTests.m +++ b/Crashlytics/UnitTests/FIRCLSOnDemandModelTests.m @@ -15,10 +15,8 @@ #import #include "Crashlytics/Crashlytics/Components/FIRCLSContext.h" -#import "Crashlytics/Crashlytics/Controllers/FIRCLSContextManager.h" #import "Crashlytics/Crashlytics/Controllers/FIRCLSManagerData.h" #import "Crashlytics/Crashlytics/Models/FIRCLSExecutionIdentifierModel.h" -#import "Crashlytics/Crashlytics/Models/FIRCLSInternalReport.h" #import "Crashlytics/Crashlytics/Private/FIRCLSOnDemandModel_Private.h" #import "Crashlytics/UnitTests/Mocks/FIRAppFake.h" #import "Crashlytics/UnitTests/Mocks/FIRCLSMockExistingReportManager.h" @@ -31,6 +29,7 @@ #import "Crashlytics/Crashlytics/DataCollection/FIRCLSDataCollectionArbiter.h" #import "Crashlytics/Crashlytics/DataCollection/FIRCLSDataCollectionToken.h" +#import "Crashlytics/Crashlytics/FIRCLSUserDefaults/FIRCLSUserDefaults.h" #import "Crashlytics/Crashlytics/Settings/Models/FIRCLSApplicationIdentifierModel.h" #define TEST_GOOGLE_APP_ID (@"1:632950151350:ios:d5b0d08d4f00f4b1") @@ -53,6 +52,9 @@ - (void)setUp { [super setUp]; FIRSetLoggerLevel(FIRLoggerLevelMax); + [[FIRCLSUserDefaults standardUserDefaults] removeAllObjects]; + [[FIRCLSUserDefaults standardUserDefaults] synchronize]; + FIRCLSContextBaseInit(); id fakeApp = [[FIRAppFake alloc] init]; @@ -89,24 +91,17 @@ - (void)setUp { [self.fileManager createReportDirectories]; [self.fileManager setupNewPathForExecutionIdentifier:self.managerData.executionIDModel.executionID]; - - NSString *name = @"exception_model_report"; - NSString *reportPath = [self.fileManager.rootPath stringByAppendingPathComponent:name]; - [self.fileManager createDirectoryAtPath:reportPath]; - - FIRCLSInternalReport *report = - [[FIRCLSInternalReport alloc] initWithPath:reportPath - executionIdentifier:@"TEST_EXECUTION_IDENTIFIER"]; - - FIRCLSContextManager *contextManager = [[FIRCLSContextManager alloc] init]; - FBLPromiseAwait([contextManager setupContextWithReport:report - settings:self.mockSettings - fileManager:self.fileManager], - nil); } - (void)tearDown { + [self.managerData.onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + dispatch_sync(self.managerData.dispatchQueue, ^{ + }); + [self.existingReportManager.operationQueue waitUntilAllOperationsAreFinished]; + [[FIRCLSUserDefaults standardUserDefaults] removeAllObjects]; + [[FIRCLSUserDefaults standardUserDefaults] synchronize]; self.onDemandModel = nil; + FIRCLSContextBaseDeinit(); [[NSFileManager defaultManager] removeItemAtPath:self.fileManager.rootPath error:nil]; [super tearDown]; } @@ -116,6 +111,7 @@ - (void)setSleepBlock:(void (^)(int))sleepBlock { } - (void)testIncrementsQueueWhenEventRecorded { + [self.dataArbiter setCrashlyticsCollectionEnabled:YES]; FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; XCTestExpectation *testComplete = [[XCTestExpectation alloc] initWithDescription:@"complete test"]; @@ -128,9 +124,9 @@ - (void)testIncrementsQueueWhenEventRecorded { }]; BOOL success = [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:YES + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; - // Should record but not submit a report. + // Should record and submit a report. XCTAssertTrue(success); XCTAssertEqual([self.onDemandModel recordedOnDemandExceptionCount], 1); XCTAssertEqual(self.onDemandModel.getQueuedOperationsCount, 1); @@ -140,6 +136,7 @@ - (void)testIncrementsQueueWhenEventRecorded { } - (void)testCompliesWithDataCollectionOff { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; XCTestExpectation *sleepComplete = [[XCTestExpectation alloc] initWithDescription:@"complete test"]; @@ -152,7 +149,7 @@ - (void)testCompliesWithDataCollectionOff { }]; BOOL success = [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:NO + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; // Should record but not submit a report. @@ -168,16 +165,17 @@ - (void)testCompliesWithDataCollectionOff { XCTAssertEqual(self.onDemandModel.getQueuedOperationsCount, 0); XCTAssertEqual([self contentsOfActivePath].count, 1); - XCTAssertEqual([self.onDemandModel.storedActiveReportPaths count], 1); + XCTAssertEqual([[self.onDemandModel storedActiveReportPathsSnapshot] count], 1); } - (void)testQuotaWithDataCollectionOff { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; for (int i = 0; i < 10; i++) { BOOL success = [self.managerData.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:NO + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; XCTAssertTrue(success); @@ -192,7 +190,7 @@ - (void)testQuotaWithDataCollectionOff { XCTAssertEqual([self.managerData.onDemandModel recordedOnDemandExceptionCount], FIRCLSMaxUnsentReports); XCTAssertEqual([self contentsOfActivePath].count, FIRCLSMaxUnsentReports); - XCTAssertEqual([self.managerData.onDemandModel.storedActiveReportPaths count], + XCTAssertEqual([[self.managerData.onDemandModel storedActiveReportPathsSnapshot] count], FIRCLSMaxUnsentReports); // Once we call sendUnsentReports, stored reports should be sent immediately. @@ -202,14 +200,15 @@ - (void)testQuotaWithDataCollectionOff { FIRCLSMaxUnsentReports); [self.existingReportManager.operationQueue waitUntilAllOperationsAreFinished]; XCTAssertEqual([self contentsOfActivePath].count, 0); - XCTAssertEqual([self.managerData.onDemandModel.storedActiveReportPaths count], 0); + XCTAssertEqual([[self.managerData.onDemandModel storedActiveReportPathsSnapshot] count], 0); } - (void)testDropsEventIfNoQuota { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; [self.onDemandModel setQueueToFull]; FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; BOOL success = [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:NO + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; // Should return false when attempting to record an event and increment the count of dropped @@ -220,11 +219,12 @@ - (void)testDropsEventIfNoQuota { } - (void)testDroppedEventCountResets { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; [self.onDemandModel setQueueToFull]; FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; BOOL success = [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:NO + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; // Should return false when attempting to record an event and increment the count of dropped @@ -236,7 +236,7 @@ - (void)testDroppedEventCountResets { // Reset the queue to empty [self.onDemandModel setQueuedOperationsCount:0]; success = [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel - withDataCollectionEnabled:NO + withDataArbiter:self.dataArbiter usingExistingReportManager:self.existingReportManager]; // Now have room in the queue to record the event @@ -245,6 +245,142 @@ - (void)testDroppedEventCountResets { XCTAssertEqual([self.onDemandModel droppedOnDemandExceptionCount], 0); } +- (void)testTakeStoredActiveReportPathsAtomicallyClaimsAndClearsPaths { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; + FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; + + for (int i = 0; i < 3; i++) { + XCTAssertTrue([self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + } + [self.onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + + NSArray *snapshotBeforeTake = [self.onDemandModel storedActiveReportPathsSnapshot]; + XCTAssertEqual(snapshotBeforeTake.count, 3); + + NSArray *claimedPaths = [self.onDemandModel takeStoredActiveReportPaths]; + XCTAssertEqualObjects(claimedPaths, snapshotBeforeTake); + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 0); + XCTAssertEqual([self.onDemandModel takeStoredActiveReportPaths].count, 0); +} + +- (void)testDeleteUnsentReportsDeletesStoredOnDemandReports { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; + FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; + + for (int i = 0; i < 3; i++) { + XCTAssertTrue([self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + } + [self.onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 3); + XCTAssertEqual([self contentsOfActivePath].count, 3); + + [self.existingReportManager deleteUnsentReports]; + [self.existingReportManager.operationQueue waitUntilAllOperationsAreFinished]; + + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 0); + XCTAssertEqual([self contentsOfActivePath].count, 0); +} + +- (void)testQueuedOperationsUploadImmediatelyWhenConsentEnabledDuringSleep { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; + FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; + + XCTestExpectation *firstOpEnteredSleep = + [[XCTestExpectation alloc] initWithDescription:@"first on-demand op entered sleep"]; + dispatch_semaphore_t releaseFirstSleep = dispatch_semaphore_create(0); + __block BOOL didPauseFirstSleep = NO; + + [self setSleepBlock:^(int delay) { + if (!didPauseFirstSleep) { + didPauseFirstSleep = YES; + [firstOpEnteredSleep fulfill]; + dispatch_semaphore_wait(releaseFirstSleep, + dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)); + } + }]; + + // 1. Record Operation #1 while collection is disabled; wait until it stores its path and enters + // sleep. + XCTAssertTrue([self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + [self waitForExpectations:@[ firstOpEnteredSleep ] timeout:2.0]; + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 1); + + // 2. Enqueue Operations #2 and #3 while Operation #1 is asleep and collection is still disabled. + XCTAssertTrue([self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + XCTAssertTrue([self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + XCTAssertEqual(self.onDemandModel.getQueuedOperationsCount, 3); + + // 3. Enable consent mid-sleep and drain the already-stored Operation #1 report. + [self.dataArbiter setCrashlyticsCollectionEnabled:YES]; + [self.existingReportManager sendUnsentReportsWithToken:[FIRCLSDataCollectionToken validToken] + asUrgent:YES]; + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 0); + + // 4. Wake Operation #1 so Operations #2 and #3 run; they must see live consent == YES and upload + // immediately instead of stranding in storedActiveReportPaths. + dispatch_semaphore_signal(releaseFirstSleep); + [self.onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + dispatch_sync(self.managerData.dispatchQueue, ^{ + }); + [self.existingReportManager.operationQueue waitUntilAllOperationsAreFinished]; + + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 0); + XCTAssertEqual([self contentsOfActivePath].count, 0); +} + +- (void)testConcurrentRecordAndSendUnsentReportsDoesNotCrashOrCorruptPaths { + [self.dataArbiter setCrashlyticsCollectionEnabled:NO]; + FIRExceptionModel *exceptionModel = [self getTestExceptionModel]; + + dispatch_group_t group = dispatch_group_create(); + dispatch_queue_t producerQueue = dispatch_queue_create( + "com.google.firebase.crashlytics.test.producers", DISPATCH_QUEUE_CONCURRENT); + + // Hammer on-demand recording from multiple threads (exceeding FIRCLSMaxUnsentReports repeatedly) + // while concurrently draining via sendUnsentReportsWithToken: on the startup queue (#16805). + for (int t = 0; t < 4; t++) { + dispatch_group_async(group, producerQueue, ^{ + for (int i = 0; i < 60; i++) { + [self.onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]; + } + }); + } + + for (int i = 0; i < 60; i++) { + dispatch_group_async(group, self.managerData.dispatchQueue, ^{ + [self.existingReportManager sendUnsentReportsWithToken:[FIRCLSDataCollectionToken validToken] + asUrgent:NO]; + }); + } + + XCTAssertEqual(dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)), + 0); + [self.onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + + // Perform a final drain and verify stored paths and active files are completely clean. + dispatch_sync(self.managerData.dispatchQueue, ^{ + [self.existingReportManager sendUnsentReportsWithToken:[FIRCLSDataCollectionToken validToken] + asUrgent:NO]; + }); + [self.existingReportManager.operationQueue waitUntilAllOperationsAreFinished]; + + XCTAssertEqual([self.onDemandModel storedActiveReportPathsSnapshot].count, 0); + XCTAssertEqual([self contentsOfActivePath].count, 0); +} + #pragma mark - Helpers - (NSArray *)contentsOfActivePath { return [self.fileManager activePathContents]; diff --git a/Crashlytics/UnitTests/FIRCLSReportManagerTests.m b/Crashlytics/UnitTests/FIRCLSReportManagerTests.m index fcdfe7e91ed..0107699b13f 100644 --- a/Crashlytics/UnitTests/FIRCLSReportManagerTests.m +++ b/Crashlytics/UnitTests/FIRCLSReportManagerTests.m @@ -38,6 +38,7 @@ #import "Crashlytics/Crashlytics/Settings/Models/FIRCLSApplicationIdentifierModel.h" #import "Crashlytics/UnitTests/Mocks/FABMockApplicationIdentifierModel.h" #import "Crashlytics/UnitTests/Mocks/FIRAppFake.h" +#import "Crashlytics/UnitTests/Mocks/FIRCLSMockOnDemandModel.h" #import "Crashlytics/UnitTests/Mocks/FIRCLSMockReportManager.h" #import "Crashlytics/UnitTests/Mocks/FIRCLSMockReportUploader.h" #import "Crashlytics/UnitTests/Mocks/FIRCLSMockSettings.h" @@ -433,6 +434,65 @@ - (void)testExistingReportOnStartWithDataCollectionDisabledAndDelete { XCTAssertEqual([self.prepareAndSubmitReportArray count], 0); } +- (void)testDeleteUnsentReportsDeletesStoredOnDemandReportsFromReportManager { + FIRCLSMockOnDemandModel *onDemandModel = + [[FIRCLSMockOnDemandModel alloc] initWithFIRCLSSettings:self.mockSettings + fileManager:self.fileManager + sleepBlock:^(int delay){ + }]; + FIRMockInstallations *iid = [[FIRMockInstallations alloc] initWithFID:@"test_token"]; + FIRMockGDTCORTransport *mockGoogleTransport = + [[FIRMockGDTCORTransport alloc] initWithMappingID:@"id" transformers:nil target:0]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonnull" + FIRCLSManagerData *managerData = + [[FIRCLSManagerData alloc] initWithGoogleAppID:TEST_GOOGLE_APP_ID + googleTransport:mockGoogleTransport + installations:iid + analytics:nil + fileManager:self.fileManager + dataArbiter:self.dataArbiter + settings:self.mockSettings + onDemandModel:onDemandModel]; +#pragma clang diagnostic pop + self.mockReportUploader = [[FIRCLSMockReportUploader alloc] initWithManagerData:managerData]; + self.existingReportManager = + [[FIRCLSMockExistingReportManager alloc] initWithManagerData:managerData + reportUploader:self.mockReportUploader]; + FIRCLSAnalyticsManager *analyticsManager = [[FIRCLSAnalyticsManager alloc] initWithAnalytics:nil]; + self.reportManager = + [[FIRCLSMockReportManager alloc] initWithManagerData:managerData + existingReportManager:self.existingReportManager + analyticsManager:analyticsManager]; + + FIRCLSInternalReport *report = [self createActiveReport]; + XCTAssertTrue([self createFileWithContents:@"signal" + atPath:[report pathForContentFile:FIRCLSReportSignalFile]]); + XCTAssertEqual([[self contentsOfActivePath] count], 1); + + [self startReportManagerWithDataCollectionEnabled:NO]; + XCTAssertEqual([[self contentsOfActivePath] count], 2, + @"should contain the current and old reports"); + + FIRExceptionModel *exceptionModel = + [FIRExceptionModel exceptionModelWithName:@"PreConsentException" reason:@"OptOutTest"]; + XCTAssertTrue([onDemandModel recordOnDemandExceptionIfQuota:exceptionModel + withDataArbiter:self.dataArbiter + usingExistingReportManager:self.existingReportManager]); + [onDemandModel.operationQueue waitUntilAllOperationsAreFinished]; + + XCTAssertEqual([onDemandModel storedActiveReportPathsSnapshot].count, 1); + XCTAssertEqual([[self contentsOfActivePath] count], 3, + @"should contain old, current, and stored on-demand reports"); + + [self processReports:NO]; + + XCTAssertEqual([onDemandModel storedActiveReportPathsSnapshot].count, 0); + XCTAssertEqual([[self contentsOfActivePath] count], 1, + @"should contain only the current report after deleteUnsentReports"); + XCTAssertEqual([self.prepareAndSubmitReportArray count], 0); +} + - (void)testExistingUrgentReportOnStart { // create a report and put it in place FIRCLSInternalReport *report = [self createActiveReport]; diff --git a/Crashlytics/UnitTests/FIRCrashlyticsTests.m b/Crashlytics/UnitTests/FIRCrashlyticsTests.m index 53858c1ecff..e1cd8cb0704 100644 --- a/Crashlytics/UnitTests/FIRCrashlyticsTests.m +++ b/Crashlytics/UnitTests/FIRCrashlyticsTests.m @@ -96,6 +96,7 @@ @interface FIRCLSThreadTrackingOnDemandModel : FIRCLSMockOnDemandModel @property(nonatomic, assign) BOOL lastCallWasOnMainThread; @property(nonatomic, strong, nullable) NSThread *lastCallThread; @property(nonatomic, strong, nullable) FIRExceptionModel *lastRecordedExceptionModel; +@property(nonatomic, strong, nullable) FIRCLSDataCollectionArbiter *lastDataArbiter; @property(nonatomic, assign) NSUInteger callCount; @property(nonatomic, strong, nullable) NSException *exceptionToThrow; @@ -104,11 +105,12 @@ @interface FIRCLSThreadTrackingOnDemandModel : FIRCLSMockOnDemandModel @implementation FIRCLSThreadTrackingOnDemandModel - (BOOL)recordOnDemandExceptionIfQuota:(FIRExceptionModel *)exceptionModel - withDataCollectionEnabled:(BOOL)dataCollectionEnabled + withDataArbiter:(FIRCLSDataCollectionArbiter *)dataArbiter usingExistingReportManager:(FIRCLSExistingReportManager *)existingReportManager { self.lastCallWasOnMainThread = [NSThread isMainThread]; self.lastCallThread = [NSThread currentThread]; self.lastRecordedExceptionModel = exceptionModel; + self.lastDataArbiter = dataArbiter; self.callCount += 1; if (self.exceptionToThrow) { NSException *exception = self.exceptionToThrow; @@ -190,18 +192,13 @@ - (void)setUp { @(dispatch_queue_get_label(self.crashlytics.preInitAPIDispatchQueue)), [FIRCLSApplicationGetSDKBundleID() stringByAppendingString:@".pre-init-api"]); - __block BOOL initSettled = NO; + XCTestExpectation *initSettled = [self expectationWithDescription:@"contextInitPromise settled"]; [self.crashlytics.contextInitPromise onQueue:self.crashlytics.preInitAPIDispatchQueue then:^id _Nullable(id _Nullable value) { - initSettled = YES; + [initSettled fulfill]; return nil; }]; - NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:5.0]; - while (!initSettled && [deadline timeIntervalSinceNow] > 0) { - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode - beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.005]]; - } - XCTAssertTrue(initSettled); + [self waitForExpectations:@[ initSettled ] timeout:5.0]; self.onDemandModel = [[FIRCLSThreadTrackingOnDemandModel alloc] initWithFIRCLSSettings:self.mockSettings @@ -453,6 +450,7 @@ - (void)testPreInitErrorsAndExceptionsFlushOffMainThread { XCTAssertEqual([self customExceptionAContents].count, 1); XCTAssertEqual(self.onDemandModel.callCount, 1); XCTAssertFalse(self.onDemandModel.lastCallWasOnMainThread); + XCTAssertNotNil(self.onDemandModel.lastDataArbiter); } - (void)testRejectedInitPromiseDiscardsPreInitAndSubsequentCallsOffMainThread { diff --git a/Crashlytics/UnitTests/Mocks/FIRCLSMockFileManager.m b/Crashlytics/UnitTests/Mocks/FIRCLSMockFileManager.m index b89d05bbff8..261226e0b9a 100644 --- a/Crashlytics/UnitTests/Mocks/FIRCLSMockFileManager.m +++ b/Crashlytics/UnitTests/Mocks/FIRCLSMockFileManager.m @@ -17,11 +17,14 @@ @interface FIRCLSMockFileManager () @property(nonatomic) NSMutableDictionary *fileSystemDict; +@property(nonatomic) BOOL didFulfillRemoveExpectation; @end @implementation FIRCLSMockFileManager +@synthesize removeExpectation = _removeExpectation; + - (instancetype)init { self = [super init]; if (!self) { @@ -33,49 +36,81 @@ - (instancetype)init { return self; } -- (BOOL)removeItemAtPath:(NSString *)path { - [self.fileSystemDict removeObjectForKey:path]; +- (void)setRemoveExpectation:(XCTestExpectation *)removeExpectation { + @synchronized(self) { + _removeExpectation = removeExpectation; + _didFulfillRemoveExpectation = NO; + } +} - self.removeCount += 1; +- (XCTestExpectation *)removeExpectation { + @synchronized(self) { + return _removeExpectation; + } +} - // If we set up the expectation, and we went over the expected count or removes, fulfill the - // expectation - if (self.removeExpectation && self.removeCount >= self.expectedRemoveCount) { - [self.removeExpectation fulfill]; +- (BOOL)removeItemAtPath:(NSString *)path { + XCTestExpectation *expectationToFulfill = nil; + @synchronized(self) { + [self.fileSystemDict removeObjectForKey:path]; + + self.removeCount += 1; + + // Fulfill the expectation at most once when we reach the expected remove count, without + // clearing `_removeExpectation` since tests such as `FIRCLSSettingsTests` read + // `self.fileManager.removeExpectation` when calling `waitForExpectations:`. + if (_removeExpectation && !_didFulfillRemoveExpectation && + self.removeCount >= self.expectedRemoveCount) { + expectationToFulfill = _removeExpectation; + _didFulfillRemoveExpectation = YES; + } } + [expectationToFulfill fulfill]; return YES; } - (BOOL)fileExistsAtPath:(NSString *)path { - return self.fileSystemDict[path] != nil; + @synchronized(self) { + return self.fileSystemDict[path] != nil; + } } - (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr { - self.fileSystemDict[path] = data; + @synchronized(self) { + self.fileSystemDict[path] = data; + } return YES; } - (NSArray *)activePathContents { - NSMutableArray *pathsWithActive = [[NSMutableArray alloc] init]; - for (NSString *path in [_fileSystemDict allKeys]) { - if ([path containsString:@"v5/reports/active"]) { - [pathsWithActive addObject:path]; + @synchronized(self) { + NSMutableArray *pathsWithActive = [[NSMutableArray alloc] init]; + for (NSString *path in [_fileSystemDict allKeys]) { + if ([path containsString:@"v5/reports/active"]) { + [pathsWithActive addObject:path]; + } } - } - return pathsWithActive; + return pathsWithActive; + } } - (NSData *)dataWithContentsOfFile:(NSString *)path { - return self.fileSystemDict[path]; + @synchronized(self) { + return self.fileSystemDict[path]; + } } - (void)enumerateFilesInDirectory:(NSString *)directory usingBlock:(void (^)(NSString *filePath, NSString *extension))block { - NSArray *filteredPaths = [self.fileSystemDict.allKeys + NSArray *allKeysSnapshot = nil; + @synchronized(self) { + allKeysSnapshot = [self.fileSystemDict.allKeys copy]; + } + NSArray *filteredPaths = [allKeysSnapshot filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *path, NSDictionary *bindings) { return [path hasPrefix:directory]; diff --git a/Crashlytics/UnitTests/Mocks/FIRCLSMockOnDemandModel.m b/Crashlytics/UnitTests/Mocks/FIRCLSMockOnDemandModel.m index 80ffd09462b..483d867ad55 100644 --- a/Crashlytics/UnitTests/Mocks/FIRCLSMockOnDemandModel.m +++ b/Crashlytics/UnitTests/Mocks/FIRCLSMockOnDemandModel.m @@ -53,11 +53,11 @@ - (void)implementOnDemandUploadDelay:(int)delay { } - (NSString *)recordOnDemandExceptionWithModel:(FIRExceptionModel *)exceptionModel { - int randomSuffix = arc4random_uniform(10000); + NSString *uniqueSuffix = [[NSUUID UUID] UUIDString]; NSString *activePath = [_fileManager activePath]; NSString *exceptionName = - [activePath stringByAppendingPathComponent:[NSString stringWithFormat:@"test_exception_%d", - randomSuffix]]; + [activePath stringByAppendingPathComponent:[NSString stringWithFormat:@"test_exception_%@", + uniqueSuffix]]; NSData *data = [exceptionName dataUsingEncoding:NSUTF8StringEncoding]; [self.fileManager createFileAtPath:exceptionName contents:data attributes:nil]; return exceptionName;