ProfileStorageLease.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.kt
1package eu.friedcutlet.yokan.app.profiles23import kotlinx.coroutines.ensureActive4import eu.friedcutlet.yokan.domain.ProfileId56/** Held until the owner's database and native writes have drained. Lock files live outside its data. */7internal fun interface ProfileStorageLease { suspend fun close() }8internal expect suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease910internal suspend fun openPlatformProfileSession(11 id: ProfileId,12 syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases,13 onScheduleChanged: (ProfileSession) -> Unit = {},14): ProfileSession {15 kotlinx.coroutines.currentCoroutineContext().ensureActive()16 val lease = acquireProfileStorageLease(id)17 var session: ProfileSession? = null18 return try {19 kotlinx.coroutines.currentCoroutineContext().ensureActive()20 ProfileSession(id, storageLease = lease, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases).also {21 session = it22 it.localFiles.prepare()23 }24 }25 catch (error: Throwable) {26 kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {27 try { session?.close() ?: lease.close() }28 catch (closing: Throwable) { error.addSuppressed(closing) }29 }30 throw error31 }32}33