Yokan / rebuild
Course 1 8624561

FileProfileRegistryPersistence.kt

composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/FileProfileRegistryPersistence.kt

implementation41 lines
1package eu.friedcutlet.yokan.app.profiles23import java.io.File4import java.io.RandomAccessFile5import java.nio.file.Files6import java.nio.file.StandardCopyOption7import java.util.concurrent.ConcurrentHashMap8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.withContext1011/** One lock file remains stable while registry.json is atomically replaced. */12internal class FileProfileRegistryPersistence(private val file: File) : ProfileRegistryPersistence {13    private val monitor = locks.computeIfAbsent(file.canonicalPath) { Any() }14    override suspend fun read(): String? = withContext(Dispatchers.IO) { locked { readLocked() } }15    override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.IO) {16        require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)17        locked {18            if (readLocked() != expected) return@locked false19            val staged = File.createTempFile("registry-", ".tmp", file.parentFile)20            try {21                staged.outputStream().use { output -> output.write(replacement.encodeToByteArray()); output.fd.sync() }22                // Never fall back to deleting the live file or a non-atomic overwrite.23                Files.move(staged.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)24                true25            } finally { staged.delete() }26        }27    }28    private fun readLocked(): String? {29        if (!file.exists()) return null30        check(file.isFile && file.length() <= MaxProfileRegistryBytes) { "Profile registry cannot be read safely" }31        return file.readBytes().decodeToString(throwOnInvalidSequence = true)32    }33    private fun <T> locked(block: () -> T): T = synchronized(monitor) {34        val parent = requireNotNull(file.parentFile)35        check(parent.isDirectory || parent.mkdirs()) { "Profile registry directory unavailable" }36        RandomAccessFile(File(parent, "registry.lock"), "rw").use { lockFile ->37            lockFile.channel.lock().use { block() }38        }39    }40    private companion object { val locks = ConcurrentHashMap<String, Any>() }41}42

Search chapters, reference and source filenames.