package eu.friedcutlet.yokan.app.profiles import java.io.File import java.io.RandomAccessFile import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** One lock file remains stable while registry.json is atomically replaced. */ internal class FileProfileRegistryPersistence(private val file: File) : ProfileRegistryPersistence { private val monitor = locks.computeIfAbsent(file.canonicalPath) { Any() } override suspend fun read(): String? = withContext(Dispatchers.IO) { locked { readLocked() } } override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.IO) { require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes) locked { if (readLocked() != expected) return@locked false val staged = File.createTempFile("registry-", ".tmp", file.parentFile) try { staged.outputStream().use { output -> output.write(replacement.encodeToByteArray()); output.fd.sync() } // Never fall back to deleting the live file or a non-atomic overwrite. Files.move(staged.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) true } finally { staged.delete() } } } private fun readLocked(): String? { if (!file.exists()) return null check(file.isFile && file.length() <= MaxProfileRegistryBytes) { "Profile registry cannot be read safely" } return file.readBytes().decodeToString(throwOnInvalidSequence = true) } private fun locked(block: () -> T): T = synchronized(monitor) { val parent = requireNotNull(file.parentFile) check(parent.isDirectory || parent.mkdirs()) { "Profile registry directory unavailable" } RandomAccessFile(File(parent, "registry.lock"), "rw").use { lockFile -> lockFile.channel.lock().use { block() } } } private companion object { val locks = ConcurrentHashMap() } }