Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Delete old session replay files #4446

Merged
merged 9 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ via the option `swizzleClassNameExclude`.
- Finish TTID correctly when viewWillAppear is skipped (#4417)
- Swizzling RootUIViewController if ignored by `swizzleClassNameExclude` (#4407)
- Data race in SentrySwizzleInfo.originalCalled (#4434)

- Delete old session replay files (#4446)

### Improvements

Expand Down
61 changes: 53 additions & 8 deletions Sources/Sentry/SentrySessionReplayIntegration.m
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@
_notificationCenter = SentryDependencyContainer.sharedInstance.notificationCenterWrapper;

[self moveCurrentReplay];
[self cleanUp];

[SentrySDK.currentHub registerSessionListener:self];
[SentryGlobalEventProcessor.shared
addEventProcessor:^SentryEvent *_Nullable(SentryEvent *_Nonnull event) {
Expand All @@ -103,6 +105,19 @@
[SentryDependencyContainer.sharedInstance.reachability addObserver:self];
}

- (nullable NSDictionary<NSString *, id> *)lastReplayInfo
{
NSURL *dir = [self replayDirectory];
NSURL *lastReplayUrl = [dir URLByAppendingPathComponent:SENTRY_LAST_REPLAY];
NSData *lastReplay = [NSData dataWithContentsOfURL:lastReplayUrl];

if (lastReplay == nil) {
return nil;
}

return [SentrySerialization deserializeDictionaryFromJsonData:lastReplay];
}

/**
* Send the cached frames from a previous session that eventually crashed.
* This function is called when processing an event created by SentryCrashIntegration,
Expand All @@ -112,15 +127,8 @@
- (void)resumePreviousSessionReplay:(SentryEvent *)event
{
NSURL *dir = [self replayDirectory];
NSURL *lastReplayUrl = [dir URLByAppendingPathComponent:SENTRY_LAST_REPLAY];
NSData *lastReplay = [NSData dataWithContentsOfURL:lastReplayUrl];
NSDictionary<NSString *, id> *jsonObject = [self lastReplayInfo];

if (lastReplay == nil) {
return;
}

NSDictionary<NSString *, id> *jsonObject =
[SentrySerialization deserializeDictionaryFromJsonData:lastReplay];
if (jsonObject == nil) {
return;
}
Expand Down Expand Up @@ -359,6 +367,43 @@
}
}

- (void)cleanUp
{
NSURL *replayDir = [self replayDirectory];
NSDictionary<NSString *, id> *lastReplayInfo = [self lastReplayInfo];
NSString *lastReplayFolder = lastReplayInfo[@"path"];

// Mapping replay folder here and not in dispatched queue to prevent a race condition between
// listing files and creating a new replay session.
brustolin marked this conversation as resolved.
Show resolved Hide resolved
NSArray *replayFiles =
[SentryDependencyContainer.sharedInstance.fileManager allFilesInFolder:replayDir.path];
if (replayFiles.count == 0) {
return;

Check warning on line 381 in Sources/Sentry/SentrySessionReplayIntegration.m

View check run for this annotation

Codecov / codecov/patch

Sources/Sentry/SentrySessionReplayIntegration.m#L381

Added line #L381 was not covered by tests
brustolin marked this conversation as resolved.
Show resolved Hide resolved
}

[SentryDependencyContainer.sharedInstance.dispatchQueueWrapper dispatchAsyncWithBlock:^{
NSFileManager *fileManager = [NSFileManager defaultManager];
for (NSString *file in replayFiles) {
NSString *filePath = [replayDir.path stringByAppendingPathComponent:file];

// Skip the last replay folder.
if ([file isEqualToString:lastReplayFolder]) {
continue;
}
brustolin marked this conversation as resolved.
Show resolved Hide resolved

// Check if the file exists and is a directory before deleting it.
BOOL isDirectory = NO;
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
NSError *error = nil;
if (![fileManager removeItemAtPath:filePath error:&error]) {
SENTRY_LOG_ERROR(@"Error deleting file at path: %@, error: %@", filePath,
error.localizedDescription);

Check warning on line 400 in Sources/Sentry/SentrySessionReplayIntegration.m

View check run for this annotation

Codecov / codecov/patch

Sources/Sentry/SentrySessionReplayIntegration.m#L400

Added line #L400 was not covered by tests
}
philipphofmann marked this conversation as resolved.
Show resolved Hide resolved
}
}
}];
}

- (void)pause
{
[self.sessionReplay pause];
Expand Down
1 change: 1 addition & 0 deletions Sources/Sentry/include/SentryFileManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ SENTRY_NO_INIT
- (NSNumber *_Nullable)readTimezoneOffset;
- (void)storeTimezoneOffset:(NSInteger)offset;
- (void)deleteTimezoneOffset;
- (NSArray<NSString *> *)allFilesInFolder:(NSString *)path;

BOOL createDirectoryIfNotExists(NSString *path, NSError **error);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,12 +358,26 @@ class SentrySessionReplayIntegrationTests: XCTestCase {
XCTAssertTrue(sessionReplay.isFullSession)
}

func createLastSessionReplay(writeSessionInfo: Bool = true, errorSampleRate: Double = 1) throws {
let options = Options()
options.dsn = "https://[email protected]/test"
options.cacheDirectoryPath = FileManager.default.temporaryDirectory.path
func testCleanUp() throws {
// Create 3 old Sessions
try createLastSessionReplay()
try createLastSessionReplay()
try createLastSessionReplay()
SentryDependencyContainer.sharedInstance().dispatchQueueWrapper = TestSentryDispatchQueueWrapper()

let replayFolder = options.cacheDirectoryPath + "/io.sentry/\(options.parsedDsn?.getHash() ?? "")/replay"
// Start the integration with a configuration that will enable it
startSDK(sessionSampleRate: 0, errorSampleRate: 1)

// Check whether there is only one old session directory and the current session directory
let content = try FileManager.default.contentsOfDirectory(atPath: replayFolder()).filter { name in
!name.hasPrefix("replay") && !name.hasPrefix(".") //remove replay info files and system directories
}

XCTAssertEqual(content.count, 2)
}

func createLastSessionReplay(writeSessionInfo: Bool = true, errorSampleRate: Double = 1) throws {
let replayFolder = replayFolder()
let jsonPath = replayFolder + "/replay.current"
var sessionFolder = UUID().uuidString
let info: [String: Any] = ["replayId": SentryId().sentryIdString,
Expand All @@ -389,6 +403,13 @@ class SentrySessionReplayIntegrationTests: XCTestCase {
sentrySessionReplaySync_writeInfo()
}
}

func replayFolder() -> String {
let options = Options()
options.dsn = "https://[email protected]/test"
options.cacheDirectoryPath = FileManager.default.temporaryDirectory.path
return options.cacheDirectoryPath + "/io.sentry/\(options.parsedDsn?.getHash() ?? "")/replay"
}
}

#endif
Loading