Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,33 @@ internal class FileBasedCache(
init {
scope.launch {
withContext(context = dispatcher) {
latestMutable = getAssignments()
runCatching { latestMutable = getAssignments() }
.onFailure { throwable -> logger.e("Failed to load cached assignments", throwable) }
}
}
}

suspend fun getAssignments(): Assignments? {
return withContext(dispatcher) {
assignmentsFile.takeIf { it.exists() }?.readText()?.let { json: String ->
val fromJson = cacheDtoJsonAdapter.fromJson(json) ?: return@let null

fromJson.assignmentsDto.toAssignments(
fetchedAt = fromJson.fetchedAt,
anonymousId = fromJson.anonymousId,
)
assignmentsFile.takeIf { it.exists() }?.let { file ->
val json = file.readText()
if (json.isBlank()) {
logger.e("Cached assignments file is empty, deleting: ${file.path}")
file.delete()
return@withContext null
}
runCatching { cacheDtoJsonAdapter.fromJson(json) }
.onFailure { throwable ->
logger.e("Cached assignments file is corrupted, deleting: ${file.path}", throwable)
file.delete()
}
.getOrNull()
?.let { fromJson ->
fromJson.assignmentsDto.toAssignments(
fetchedAt = fromJson.fetchedAt,
anonymousId = fromJson.anonymousId,
)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
Expand Down Expand Up @@ -66,6 +67,30 @@ internal class FileBasedCacheTest {
sut.clear()
}

@Test
fun `getting assignments from empty file returns null and deletes the file`() = runTest {
val cacheDir = tempDir.newFolder()
val assignmentsFile = File(cacheDir, "assignments.json").apply { createNewFile() }
val sut = fileBasedCache(this, cacheDir = cacheDir)

val result = sut.getAssignments()

assertNull(result)
assertFalse(assignmentsFile.exists())
}

@Test
fun `getting assignments from corrupted file returns null and deletes the file`() = runTest {
val cacheDir = tempDir.newFolder()
val assignmentsFile = File(cacheDir, "assignments.json").apply { writeText("{corrupted") }
val sut = fileBasedCache(this, cacheDir = cacheDir)

val result = sut.getAssignments()

assertNull(result)
assertFalse(assignmentsFile.exists())
}

@Test
fun `saving cache when cache dir doesnt exist is successful`() = runTest {
val cacheDir = File(tempDir.newFolder(), "cache").apply { assert(!this.exists()) }
Expand Down
Loading