ProfileStorageLease.jvm.kt
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.jvm.kt
1package eu.friedcutlet.yokan.app.profiles23import java.io.File4import java.io.RandomAccessFile5import java.nio.channels.OverlappingFileLockException6import kotlinx.coroutines.Dispatchers7import kotlinx.coroutines.withContext8import eu.friedcutlet.yokan.domain.ProfileId910internal fun acquireFileProfileLease(root: File, id: ProfileId): ProfileStorageLease {11 require(id != ProfileId.Default)12 val locks = File(root, "profiles/locks")13 check(locks.isDirectory || locks.mkdirs()) { "Profile lock directory unavailable" }14 val file = RandomAccessFile(File(locks, "${id.value}.lock"), "rw")15 val lock = try { file.channel.tryLock() }16 catch (_: OverlappingFileLockException) { null }17 catch (error: Throwable) { file.close(); throw error }18 if (lock == null) { file.close(); error("Profile is open in another window or process") }19 // Never unlink the lock file: another process may already have opened the same inode.20 return ProfileStorageLease {21 withContext(Dispatchers.IO) { try { if (lock.isValid) lock.release() } finally { file.close() } }22 }23}24