package eu.friedcutlet.yokan.app.profiles import kotlinx.coroutines.ensureActive import eu.friedcutlet.yokan.domain.ProfileId /** Held until the owner's database and native writes have drained. Lock files live outside its data. */ internal fun interface ProfileStorageLease { suspend fun close() } internal expect suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease internal suspend fun openPlatformProfileSession( id: ProfileId, syncLeases: eu.friedcutlet.yokan.services.sync.SyncAccountLeases, onScheduleChanged: (ProfileSession) -> Unit = {}, ): ProfileSession { kotlinx.coroutines.currentCoroutineContext().ensureActive() val lease = acquireProfileStorageLease(id) var session: ProfileSession? = null return try { kotlinx.coroutines.currentCoroutineContext().ensureActive() ProfileSession(id, storageLease = lease, onScheduleChanged = onScheduleChanged, syncLeases = syncLeases).also { session = it it.localFiles.prepare() } } catch (error: Throwable) { kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { try { session?.close() ?: lease.close() } catch (closing: Throwable) { error.addSuppressed(closing) } } throw error } }