Add validated library snapshot documents
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* LibrarySnapshotDocument.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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.snapshot
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.util.zip.CRC32
|
||||
import java.util.zip.CheckedInputStream
|
||||
import java.util.zip.CheckedOutputStream
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.playlist.db.StoredPlaylists
|
||||
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
|
||||
import org.oxycblt.musikr.tag.interpret.PreSong
|
||||
|
||||
internal object LibrarySnapshotDocument {
|
||||
private const val MAX_SONGS = 100_000
|
||||
|
||||
fun write(output: OutputStream, songs: List<PreSong>) {
|
||||
LibrarySnapshotCodec.writeHeader(output)
|
||||
val checkedOutput = CheckedOutputStream(output, CRC32())
|
||||
LibrarySnapshotCodec.writeCount(checkedOutput, songs.size, MAX_SONGS)
|
||||
for (song in songs) {
|
||||
LibrarySnapshotCodec.writePreSong(checkedOutput, song)
|
||||
}
|
||||
LibrarySnapshotCodec.writeLong(output, checkedOutput.checksum.value)
|
||||
}
|
||||
|
||||
suspend fun read(
|
||||
input: InputStream,
|
||||
storedCoverDirectory: File,
|
||||
context: Context,
|
||||
storedPlaylists: StoredPlaylists,
|
||||
playlistInterpreter: PlaylistInterpreter,
|
||||
): MutableLibrary {
|
||||
LibrarySnapshotCodec.readHeader(input)
|
||||
val checkedInput = CheckedInputStream(input, CRC32())
|
||||
val songCount = LibrarySnapshotCodec.readCount(checkedInput, MAX_SONGS)
|
||||
val songs = ArrayList<PreSong>(songCount)
|
||||
repeat(songCount) {
|
||||
songs.add(
|
||||
LibrarySnapshotCodec.readPreSong(checkedInput, storedCoverDirectory, context)
|
||||
)
|
||||
}
|
||||
val expectedChecksum = LibrarySnapshotCodec.readLong(input)
|
||||
if (checkedInput.checksum.value != expectedChecksum) {
|
||||
throw IOException("Snapshot checksum mismatch")
|
||||
}
|
||||
if (input.read() != -1) {
|
||||
throw IOException("Trailing snapshot data")
|
||||
}
|
||||
return LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* LibrarySnapshotDocumentTest.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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.snapshot
|
||||
|
||||
import android.net.Uri
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.EOFException
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.file.Files
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Format
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.path.InternalVolumeValue
|
||||
import org.oxycblt.musikr.playlist.PlaylistFile
|
||||
import org.oxycblt.musikr.playlist.PlaylistHandle
|
||||
import org.oxycblt.musikr.playlist.SongPointer
|
||||
import org.oxycblt.musikr.playlist.db.StoredPlaylists
|
||||
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
|
||||
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
|
||||
import org.oxycblt.musikr.tag.ReleaseType
|
||||
import org.oxycblt.musikr.tag.ReplayGainAdjustment
|
||||
import org.oxycblt.musikr.tag.interpret.Naming
|
||||
import org.oxycblt.musikr.tag.interpret.PreAlbum
|
||||
import org.oxycblt.musikr.tag.interpret.PreArtist
|
||||
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
|
||||
import org.oxycblt.musikr.tag.interpret.PreGenre
|
||||
import org.oxycblt.musikr.tag.interpret.PreSong
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [30])
|
||||
class LibrarySnapshotDocumentTest {
|
||||
@Test
|
||||
fun document_roundTrip_preservesCompleteGraphAndLivePlaylist() {
|
||||
val storedCoverDirectory =
|
||||
Files.createTempDirectory("auxio-document-cover").toFile().apply { deleteOnExit() }
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val cover =
|
||||
requireNotNull(
|
||||
LibrarySnapshotCovers.restore("mcs:shared.webp", storedCoverDirectory, context)
|
||||
)
|
||||
val first =
|
||||
preSong(61, "First", albumName = "Shared album", artistName = "Shared artist", genreName = "Shared genre", cover = cover)
|
||||
val second =
|
||||
preSong(
|
||||
62,
|
||||
"Second",
|
||||
v400Uid = songUid(162),
|
||||
albumName = "Shared album",
|
||||
artistName = "Shared artist",
|
||||
genreName = "Shared genre",
|
||||
cover = cover,
|
||||
)
|
||||
val third = preSong(63, "Third", albumName = "Other album", artistName = "Other artist", genreName = "Other genre")
|
||||
val missing = songUid(999)
|
||||
val handle = TestPlaylistHandle(playlistUid(71))
|
||||
val file =
|
||||
PlaylistFile(
|
||||
"Bangers",
|
||||
listOf(
|
||||
SongPointer.UID(third.v363Uid),
|
||||
SongPointer.UID(first.v400Uid),
|
||||
SongPointer.UID(missing),
|
||||
SongPointer.UID(second.v363Uid),
|
||||
SongPointer.UID(first.v363Uid),
|
||||
),
|
||||
handle,
|
||||
)
|
||||
val storedPlaylists = mockk<StoredPlaylists>()
|
||||
coEvery { storedPlaylists.read() } returns listOf(file)
|
||||
val playlistInterpreter = playlistInterpreter()
|
||||
val original =
|
||||
runBlocking {
|
||||
LibrarySnapshotGraph.restore(
|
||||
listOf(first, second, third),
|
||||
storedPlaylists,
|
||||
playlistInterpreter,
|
||||
)
|
||||
}
|
||||
val output = ByteArrayOutputStream()
|
||||
|
||||
LibrarySnapshotDocument.write(output, listOf(first, second, third))
|
||||
val restored =
|
||||
runBlocking {
|
||||
LibrarySnapshotDocument.read(
|
||||
ByteArrayInputStream(output.toByteArray()),
|
||||
storedCoverDirectory,
|
||||
context,
|
||||
storedPlaylists,
|
||||
playlistInterpreter,
|
||||
)
|
||||
}
|
||||
val restoredSongs = restored.songs.associateBy { it.uid }
|
||||
|
||||
assertEquals(original.songs, restored.songs)
|
||||
assertEquals(original.albums, restored.albums)
|
||||
assertEquals(original.artists, restored.artists)
|
||||
assertEquals(original.genres, restored.genres)
|
||||
assertEquals(original.playlists, restored.playlists)
|
||||
assertEquals(2, restored.albums.size)
|
||||
assertEquals(2, restored.artists.size)
|
||||
assertEquals(2, restored.genres.size)
|
||||
assertSame(restoredSongs[first.v363Uid], restored.playlists.single().songs[1])
|
||||
assertSame(
|
||||
restoredSongs[third.v363Uid],
|
||||
restored.playlists.single().songs.first(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun document_invalidSongCounts_rejectBeforePayloadAllocation() {
|
||||
val storedCoverDirectory =
|
||||
Files.createTempDirectory("auxio-invalid-count").toFile().apply { deleteOnExit() }
|
||||
for (count in listOf(-1, 100_001)) {
|
||||
val output = ByteArrayOutputStream()
|
||||
LibrarySnapshotCodec.writeHeader(output)
|
||||
LibrarySnapshotCodec.writeInt(output, count)
|
||||
|
||||
val error =
|
||||
assertThrows(IOException::class.java) {
|
||||
readDocument(
|
||||
ByteArrayInputStream(output.toByteArray()),
|
||||
storedCoverDirectory,
|
||||
mockk<StoredPlaylists>(),
|
||||
mockk<PlaylistInterpreter>(),
|
||||
)
|
||||
}
|
||||
|
||||
assertEquals("Invalid snapshot collection count: $count", error.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun document_corruptionTrailingDataAndTruncation_failBeforeGraphConstruction() {
|
||||
val storedCoverDirectory =
|
||||
Files.createTempDirectory("auxio-integrity").toFile().apply { deleteOnExit() }
|
||||
val song = preSong(81, "Integrity")
|
||||
val storedPlaylists = mockk<StoredPlaylists>()
|
||||
coEvery { storedPlaylists.read() } returns emptyList()
|
||||
val output = ByteArrayOutputStream()
|
||||
LibrarySnapshotDocument.write(output, listOf(song))
|
||||
val bytes = output.toByteArray()
|
||||
val restored =
|
||||
readDocument(
|
||||
ByteArrayInputStream(bytes),
|
||||
storedCoverDirectory,
|
||||
storedPlaylists,
|
||||
playlistInterpreter(),
|
||||
)
|
||||
assertEquals(1, restored.songs.size)
|
||||
|
||||
val corrupted = bytes.copyOf()
|
||||
val corruptedIndex = corrupted.lastIndex - 8
|
||||
corrupted[corruptedIndex] = (corrupted[corruptedIndex].toInt() xor 1).toByte()
|
||||
val checksumError =
|
||||
assertThrows(IOException::class.java) {
|
||||
readDocument(
|
||||
ByteArrayInputStream(corrupted),
|
||||
storedCoverDirectory,
|
||||
storedPlaylists,
|
||||
playlistInterpreter(),
|
||||
)
|
||||
}
|
||||
assertEquals("Snapshot checksum mismatch", checksumError.message)
|
||||
|
||||
val trailingError =
|
||||
assertThrows(IOException::class.java) {
|
||||
readDocument(
|
||||
ByteArrayInputStream(bytes + byteArrayOf(0)),
|
||||
storedCoverDirectory,
|
||||
storedPlaylists,
|
||||
playlistInterpreter(),
|
||||
)
|
||||
}
|
||||
assertEquals("Trailing snapshot data", trailingError.message)
|
||||
assertThrows(EOFException::class.java) {
|
||||
readDocument(
|
||||
ByteArrayInputStream(bytes.copyOf(bytes.size - 9)),
|
||||
storedCoverDirectory,
|
||||
storedPlaylists,
|
||||
playlistInterpreter(),
|
||||
)
|
||||
}
|
||||
assertThrows(EOFException::class.java) {
|
||||
readDocument(
|
||||
ByteArrayInputStream(bytes.copyOf(bytes.size - 1)),
|
||||
storedCoverDirectory,
|
||||
storedPlaylists,
|
||||
playlistInterpreter(),
|
||||
)
|
||||
}
|
||||
coVerify(exactly = 1) { storedPlaylists.read() }
|
||||
}
|
||||
|
||||
private fun readDocument(
|
||||
input: InputStream,
|
||||
storedCoverDirectory: java.io.File,
|
||||
storedPlaylists: StoredPlaylists,
|
||||
playlistInterpreter: PlaylistInterpreter,
|
||||
) = runBlocking {
|
||||
LibrarySnapshotDocument.read(
|
||||
input,
|
||||
storedCoverDirectory,
|
||||
RuntimeEnvironment.getApplication(),
|
||||
storedPlaylists,
|
||||
playlistInterpreter,
|
||||
)
|
||||
}
|
||||
|
||||
private fun playlistInterpreter(): PlaylistInterpreter {
|
||||
val interpreter = mockk<PlaylistInterpreter>()
|
||||
every { interpreter.interpret(any<PlaylistFile>()) } answers {
|
||||
val file = firstArg<PlaylistFile>()
|
||||
PrePlaylist(
|
||||
Naming.simple().name(file.name, null),
|
||||
file.name,
|
||||
file.handle,
|
||||
file.songPointers,
|
||||
)
|
||||
}
|
||||
return interpreter
|
||||
}
|
||||
|
||||
private fun preSong(
|
||||
suffix: Int,
|
||||
name: String,
|
||||
v400Uid: Music.UID = songUid(suffix),
|
||||
v401Uid: Music.UID = songUid(suffix),
|
||||
albumName: String = "Album",
|
||||
artistName: String = "Artist",
|
||||
genreName: String = "Genre",
|
||||
cover: org.oxycblt.musikr.covers.Cover? = null,
|
||||
): PreSong {
|
||||
val artist = PreArtist(null, Naming.simple().name(artistName, null), artistName)
|
||||
return PreSong(
|
||||
v363Uid = songUid(suffix),
|
||||
v400Uid = v400Uid,
|
||||
v401Uid = v401Uid,
|
||||
musicBrainzId = null,
|
||||
name = Naming.simple().name(name, null),
|
||||
rawName = name,
|
||||
track = null,
|
||||
disc = null,
|
||||
date = null,
|
||||
uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
|
||||
path =
|
||||
Path(
|
||||
InternalVolumeValue(
|
||||
null,
|
||||
Components.parseUnix("/storage/emulated/0"),
|
||||
"Internal shared storage",
|
||||
),
|
||||
Components.parseUnix("Download/$name.mp3"),
|
||||
),
|
||||
format = Format.MPEG3,
|
||||
size = 1_024L,
|
||||
durationMs = 60_000L,
|
||||
bitrateKbps = 128,
|
||||
sampleRateHz = 44_100,
|
||||
replayGainAdjustment = ReplayGainAdjustment(null, null),
|
||||
modifiedMs = 100L,
|
||||
addedMs = 200L,
|
||||
cover = cover,
|
||||
preAlbum =
|
||||
PreAlbum(
|
||||
null,
|
||||
Naming.simple().name(albumName, null),
|
||||
albumName,
|
||||
ReleaseType.Album(null),
|
||||
PreArtistsFrom.Album(listOf(artist)),
|
||||
),
|
||||
preArtists = listOf(artist),
|
||||
preGenres = listOf(PreGenre(Naming.simple().name(genreName, null), genreName)),
|
||||
)
|
||||
}
|
||||
|
||||
private fun songUid(suffix: Int, format: Char = 'a') =
|
||||
requireNotNull(
|
||||
Music.UID.fromString("u${format}s00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
|
||||
)
|
||||
|
||||
private fun playlistUid(suffix: Int) =
|
||||
requireNotNull(
|
||||
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
|
||||
)
|
||||
|
||||
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
|
||||
override suspend fun rename(name: String) {}
|
||||
|
||||
override suspend fun add(songs: List<Song>) {}
|
||||
|
||||
override suspend fun rewrite(songs: List<Song>) {}
|
||||
|
||||
override suspend fun delete() {}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user