Skip to content

Change to discardOldestFileIfNeeded sorting #2189

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

Open
wants to merge 14 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
* Allow the metadata in `leaveBreadcrumb` to be null rather than enforcing non-null, aligning `bugsnag-android` with our other SDKs
[#2180](https://github.com/bugsnag/bugsnag-android/pull/2180)

* Added deterministic sorting for `discardOldestFileIfNeeded` method to avoid potential crashes where mutliple files have the same last modified time
[#2181](https://github.com/bugsnag/bugsnag-android/pull/2189)

## 6.13.0 (2025-04-15)

### Enhancements
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,21 @@ internal abstract class FileStore(
if (isStorageDirValid(storageDir)) {
val listFiles = storageDir.listFiles() ?: return
if (listFiles.size < maxStoreCount) return
val sortedListFiles = listFiles.sortedBy { it.lastModified() }

// Store lastModified to ensure it doesn't change between sorting
val fileMeta = listFiles.map { file ->
FileWithTimestamp(file, file.lastModified())
}

// Sort by cached lastModified timesstamps
val sortedListFiles = fileMeta
.sorted()
.map(FileWithTimestamp::file)

// Number of files to discard takes into account that a new file may need to be written
val numberToDiscard = listFiles.size - maxStoreCount + 1
var discardedCount = 0

for (file in sortedListFiles) {
if (discardedCount == numberToDiscard) {
return
Expand Down Expand Up @@ -188,3 +199,15 @@ internal abstract class FileStore(
}
}
}

/**
* A data holder for associating a {@link File} with its last modified timestamp.
*
* @param file The file to associate with a timestamp.
* @param timestamp The last modified time of the file, cached to ensure consistent ordering.
*/
private data class FileWithTimestamp(val file: File, val timestamp: Long) : Comparable<FileWithTimestamp> {
override fun compareTo(other: FileWithTimestamp): Int {
return timestamp.compareTo(other.timestamp)
}
}
Loading