package eu.friedcutlet.yokan.database import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** Browser snapshot backend. Calls are serialized by the browser's single thread. */ internal class SnapshotYokanDatabase( private val store: DatabaseSnapshotStore, private val memory: InMemoryYokanDatabase = InMemoryYokanDatabase(store.load() ?: seedDatabaseSnapshot()), private val stopPersistence: suspend () -> Unit = {}, ) : YokanDatabase by memory { private val retirementLock = Mutex() private var closed = false private val _saveFailed = MutableStateFlow(false) val saveFailed = _saveFailed.asStateFlow() /** The `snapshots()` value last written to [store]; publication keeps it by reference until a write. */ private var persisted: YokanDatabaseSnapshot? = null override suspend fun awaitPersistence() { check(persistIfDirty()) { "Browser database persistence failed" } } override suspend fun close() = retirementLock.withLock { if (closed) return@withLock withContext(NonCancellable) { stopPersistence() awaitPersistence() closed = true } } override fun supportsAtomicSnapshotPersistence(): Boolean = true override fun replaceAll( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, ) { check(!closed) { "Browser database is closed" } memory.replaceAll(snapshot, expectedSnapshot) } override suspend fun replaceAllAtomically( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, removedSourceIds: Set, ) { check(!closed) { "Browser database is closed" } memory.batch { if (expectedSnapshot != null && memory.snapshot() != expectedSnapshot) { throw SnapshotReplacementConflictException() } val preview = InMemoryYokanDatabase(memory.snapshot()) preview.replaceAll(snapshot, expectedSnapshot) val target = preview.snapshot() try { store.save(target) } catch (error: Throwable) { if (error is CancellationException) throw error _saveFailed.update { true } throw error } memory.applyRemote { memory.replaceAll(target) } persisted = memory.snapshots().value _saveFailed.update { false } } } override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) { check(!closed) { "Browser database is closed" } memory.batch { if (expectedSnapshot != null && memory.snapshot() != expectedSnapshot) throw SnapshotReplacementConflictException() try { store.save(snapshot) } catch (error: Throwable) { if (error is CancellationException) throw error _saveFailed.update { true } throw error } memory.applyRemote { memory.replaceAll(snapshot) } persisted = memory.snapshots().value _saveFailed.update { false } } } /** Always save current memory, including on retry after a rejected storage write. */ fun persist(): Boolean { if (closed) return false return try { memory.batch { store.save(memory.snapshot()) persisted = memory.snapshots().value } _saveFailed.update { false } true } catch (error: Throwable) { if (error is CancellationException) throw error _saveFailed.update { true } false } } /** Save only when something was published since the last successful write. */ fun persistIfDirty(): Boolean = !closed && (memory.snapshots().value === persisted || persist()) }