From d3f40eacbfb14a4619709feac3ad979c20f5ec4d Mon Sep 17 00:00:00 2001 From: Jay Date: Sat, 14 Nov 2026 08:12:39 -0500 Subject: [PATCH] Add atomic library snapshot file store --- .../musikr/snapshot/LibrarySnapshotStore.kt | 77 ++++++++ .../snapshot/LibrarySnapshotStoreTest.kt | 165 ++++++++++++++++++ 2 files changed, 242 insertions(+) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt create mode 100644 musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt new file mode 100644 index 000000000..e52d8c25f --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 Auxio Project + * LibrarySnapshotStore.kt is part of Auxio. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.musikr.snapshot + +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import kotlin.coroutines.cancellation.CancellationException + +class LibrarySnapshotStore +internal constructor( + private val directory: File, + private val atomicMove: (Path, Path) -> Unit, +) { + constructor( + directory: File + ) : this( + directory, + { source, target -> + Files.move( + source, + target, + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING, + ) + }, + ) + + private val snapshot = File(directory, "library.snapshot") + + fun load(read: (InputStream) -> T): T? { + if (!snapshot.isFile) { + return null + } + return try { + snapshot.inputStream().use(read) + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + null + } + } + + fun replace(write: (OutputStream) -> Unit, verify: (InputStream) -> Unit) { + if (!directory.isDirectory && !directory.mkdirs() && !directory.isDirectory) { + throw IOException("Unable to create library snapshot directory") + } + val tempFile = File.createTempFile("${snapshot.name}.", ".tmp", directory) + try { + tempFile.outputStream().use(write) + tempFile.inputStream().use(verify) + atomicMove(tempFile.toPath(), snapshot.toPath()) + } finally { + tempFile.delete() + } + } +} diff --git a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt new file mode 100644 index 000000000..2f19c7969 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2026 Auxio Project + * LibrarySnapshotStoreTest.kt is part of Auxio. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.musikr.snapshot + +import java.io.ByteArrayOutputStream +import java.io.EOFException +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import kotlin.coroutines.cancellation.CancellationException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test + +class LibrarySnapshotStoreTest { + @Test + fun load_missingSnapshot_returnsNullWithoutCreatingDirectory() { + val root = Files.createTempDirectory("auxio-store-missing").toFile().apply { deleteOnExit() } + val directory = File(root, "snapshots") + val store = LibrarySnapshotStore(directory) + + val result = store.load { error("Absent snapshot must not be decoded") } + + assertNull(result) + assertFalse(directory.exists()) + } + + @Test + fun replace_validSnapshot_verifiesContentsAndCleansTemporaryFiles() { + val directory = Files.createTempDirectory("auxio-store-valid").toFile().apply { deleteOnExit() } + val store = LibrarySnapshotStore(directory) + + store.replace( + write = { writeSnapshot(it, "first") }, + verify = { assertEquals("first", readSnapshot(it)) }, + ) + assertEquals("first", store.load(::readSnapshot)) + + store.replace( + write = { writeSnapshot(it, "second") }, + verify = { assertEquals("second", readSnapshot(it)) }, + ) + + assertEquals("second", store.load(::readSnapshot)) + assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name }) + } + + @Test + fun load_corruptOrTruncatedSnapshot_fallsBackWithoutTouchingOtherFiles() { + val directory = Files.createTempDirectory("auxio-store-invalid").toFile().apply { deleteOnExit() } + val store = LibrarySnapshotStore(directory) + val snapshot = File(directory, "library.snapshot") + val unrelated = File(directory, "unrelated-cache") + unrelated.writeText("preserved") + val valid = ByteArrayOutputStream().also { writeSnapshot(it, "valid") }.toByteArray() + val invalidDocuments = + listOf( + "invalid-magic".toByteArray(), + valid.copyOf(valid.size - 2), + ) + + for (invalid in invalidDocuments) { + snapshot.writeBytes(invalid) + + assertNull(store.load(::readSnapshot)) + assertEquals("preserved", unrelated.readText()) + } + } + + @Test + fun replace_failedWriteVerificationCancellationOrMove_preservesPreviousAndCleansTemps() { + val directory = Files.createTempDirectory("auxio-store-failed").toFile().apply { deleteOnExit() } + val store = LibrarySnapshotStore(directory) + store.replace( + write = { writeSnapshot(it, "stable") }, + verify = { assertEquals("stable", readSnapshot(it)) }, + ) + + assertThrows(IllegalStateException::class.java) { + store.replace( + write = { + writeSnapshot(it, "write-failed") + throw IllegalStateException("Forced write failure") + }, + verify = { error("Failed write must not be verified") }, + ) + } + assertEquals("stable", store.load(::readSnapshot)) + + assertThrows(CancellationException::class.java) { + store.replace( + write = { + writeSnapshot(it, "cancelled") + throw CancellationException("Forced cancellation") + }, + verify = { error("Cancelled write must not be verified") }, + ) + } + assertEquals("stable", store.load(::readSnapshot)) + + val truncated = ByteArrayOutputStream() + LibrarySnapshotCodec.writeHeader(truncated) + LibrarySnapshotCodec.writeInt(truncated, 10) + truncated.write('v'.code) + assertThrows(EOFException::class.java) { + store.replace( + write = { it.write(truncated.toByteArray()) }, + verify = { readSnapshot(it) }, + ) + } + assertEquals("stable", store.load(::readSnapshot)) + + val failedMoveStore = + LibrarySnapshotStore(directory) { source, target -> + throw AtomicMoveNotSupportedException( + source.toString(), + target.toString(), + "Forced move failure", + ) + } + assertThrows(AtomicMoveNotSupportedException::class.java) { + failedMoveStore.replace( + write = { writeSnapshot(it, "move-failed") }, + verify = { assertEquals("move-failed", readSnapshot(it)) }, + ) + } + assertEquals("stable", store.load(::readSnapshot)) + assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name }) + } + + private fun writeSnapshot(output: OutputStream, value: String) { + LibrarySnapshotCodec.writeHeader(output) + LibrarySnapshotCodec.writeString(output, value) + } + + private fun readSnapshot(input: InputStream): String { + LibrarySnapshotCodec.readHeader(input) + val value = LibrarySnapshotCodec.readString(input) + if (input.read() != -1) { + throw IOException("Trailing test data") + } + return value + } +}