Yokan / rebuild
Course 1 8624561

SnapshotYokanDatabase.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/SnapshotYokanDatabase.kt

implementation111 lines
1package eu.friedcutlet.yokan.database23import kotlinx.coroutines.CancellationException4import kotlinx.coroutines.flow.MutableStateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.flow.update7import kotlinx.coroutines.NonCancellable8import kotlinx.coroutines.sync.Mutex9import kotlinx.coroutines.sync.withLock10import kotlinx.coroutines.withContext1112/** Browser snapshot backend. Calls are serialized by the browser's single thread. */13internal class SnapshotYokanDatabase(14    private val store: DatabaseSnapshotStore,15    private val memory: InMemoryYokanDatabase = InMemoryYokanDatabase(store.load() ?: seedDatabaseSnapshot()),16    private val stopPersistence: suspend () -> Unit = {},17) : YokanDatabase by memory {18    private val retirementLock = Mutex()19    private var closed = false20    private val _saveFailed = MutableStateFlow(false)21    val saveFailed = _saveFailed.asStateFlow()2223    /** The `snapshots()` value last written to [store]; publication keeps it by reference until a write. */24    private var persisted: YokanDatabaseSnapshot? = null2526    override suspend fun awaitPersistence() {27        check(persistIfDirty()) { "Browser database persistence failed" }28    }2930    override suspend fun close() = retirementLock.withLock {31        if (closed) return@withLock32        withContext(NonCancellable) {33            stopPersistence()34            awaitPersistence()35            closed = true36        }37    }3839    override fun supportsAtomicSnapshotPersistence(): Boolean = true4041    override fun replaceAll(42        snapshot: YokanDatabaseSnapshot,43        expectedSnapshot: YokanDatabaseSnapshot?,44    ) {45        check(!closed) { "Browser database is closed" }46        memory.replaceAll(snapshot, expectedSnapshot)47    }4849    override suspend fun replaceAllAtomically(50        snapshot: YokanDatabaseSnapshot,51        expectedSnapshot: YokanDatabaseSnapshot?,52        removedSourceIds: Set<Long>,53    ) {54        check(!closed) { "Browser database is closed" }55        memory.batch {56            if (expectedSnapshot != null && memory.snapshot() != expectedSnapshot) {57                throw SnapshotReplacementConflictException()58            }59            val preview = InMemoryYokanDatabase(memory.snapshot())60            preview.replaceAll(snapshot, expectedSnapshot)61            val target = preview.snapshot()62            try {63                store.save(target)64            } catch (error: Throwable) {65                if (error is CancellationException) throw error66                _saveFailed.update { true }67                throw error68            }69            memory.applyRemote { memory.replaceAll(target) }70            persisted = memory.snapshots().value71            _saveFailed.update { false }72        }73    }7475    override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) {76        check(!closed) { "Browser database is closed" }77        memory.batch {78            if (expectedSnapshot != null && memory.snapshot() != expectedSnapshot) throw SnapshotReplacementConflictException()79            try {80                store.save(snapshot)81            } catch (error: Throwable) {82                if (error is CancellationException) throw error83                _saveFailed.update { true }84                throw error85            }86            memory.applyRemote { memory.replaceAll(snapshot) }87            persisted = memory.snapshots().value88            _saveFailed.update { false }89        }90    }9192    /** Always save current memory, including on retry after a rejected storage write. */93    fun persist(): Boolean {94        if (closed) return false95        return try {96            memory.batch {97                store.save(memory.snapshot())98                persisted = memory.snapshots().value99            }100            _saveFailed.update { false }101            true102        } catch (error: Throwable) {103            if (error is CancellationException) throw error104            _saveFailed.update { true }105            false106        }107    }108109    /** Save only when something was published since the last successful write. */110    fun persistIfDirty(): Boolean = !closed && (memory.snapshots().value === persisted || persist())111}112

Search chapters, reference and source filenames.