diff --git a/app/src/main/java/com/example/research/common/util/FileStorageManager.kt b/app/src/main/java/com/example/research/common/util/FileStorageManager.kt index 826ce4b..114b29b 100644 --- a/app/src/main/java/com/example/research/common/util/FileStorageManager.kt +++ b/app/src/main/java/com/example/research/common/util/FileStorageManager.kt @@ -19,6 +19,8 @@ class FileStorageManager { private const val DELETE_WAIT_INTERVAL = 50L private const val MAX_DELETE_WAIT_COUNT = 10 private const val DEFAULT_MAX_RETRIES = 5 + private const val CREATE_RETRY_DELAY = 100L + private const val MAX_CREATE_RETRIES = 3 private const val TAG = "FileStorageManager" } @@ -87,6 +89,7 @@ class FileStorageManager { Log.e(TAG, "Could not delete existing file: $fileName") return@withContext null } + waitForDeletion(targetFile) } else { return@withContext Uri.fromFile(targetFile) } @@ -95,7 +98,18 @@ class FileStorageManager { if (tempBinFile.exists()) { tempBinFile.delete() } - if (targetFile.createNewFile()) { + var created = targetFile.createNewFile() + var createAttempt = 0 + while (!created && createAttempt < MAX_CREATE_RETRIES) { + delay(CREATE_RETRY_DELAY.milliseconds) + if (targetFile.exists()) { + targetFile.delete() + waitForDeletion(targetFile) + } + created = targetFile.createNewFile() + createAttempt++ + } + if (created) { Uri.fromFile(targetFile) } else { Log.e(TAG, "Failed to create file: $fileName") @@ -141,6 +155,15 @@ class FileStorageManager { } } + // FUSE-backed storage keeps a just-deleted file visible to stat/open for a short window + private suspend fun waitForDeletion(file: File) { + var waitCount = 0 + while (file.exists() && waitCount < MAX_DELETE_WAIT_COUNT) { + delay(DELETE_WAIT_INTERVAL.milliseconds) + waitCount++ + } + } + private suspend fun waitForFileDeletion(file: DocumentFile) { var waitCount = 0 while (file.exists() && waitCount < MAX_DELETE_WAIT_COUNT) {