@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class) package eu.friedcutlet.yokan.database import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.domain.ProfileStorageNamespace import kotlinx.browser.document import kotlinx.browser.localStorage import kotlinx.browser.window import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import org.w3c.dom.events.Event actual fun createDefaultDatabaseSnapshotStore(): DatabaseSnapshotStore = WasmLocalStorageSnapshotStore(SnapshotStorageKey) private const val SnapshotStorageKey = "yokan-database-v1" /** Compact: indentation would count against the ~5 MB localStorage quota for nothing. */ private val BrowserDatabaseJson = Json(DatabaseJson) { prettyPrint = false } /** * The page cache is dropped: page URLs expire, the web target has no offline reader, and it * was the largest unbounded part of the stored snapshot. */ internal fun encodeBrowserSnapshot(snapshot: YokanDatabaseSnapshot): String = BrowserDatabaseJson.encodeToString( PersistedDatabaseSnapshot(snapshot = snapshot.copy(pageCache = emptyList())), ) /** * Whole-snapshot JSON persistence in `window.localStorage`. Room and the * bundled SQLite driver have no wasm artifacts, so the browser keeps the * legacy snapshot backend. */ // ponytail: one localStorage key keeps every save atomic (restore and F9 retry rely on it); // per-section keys need a generation/manifest scheme, add it if saves still hit the quota. private class WasmLocalStorageSnapshotStore( private val key: String, private val requireValidSnapshot: Boolean = false, ) : DatabaseSnapshotStore { override fun load(): YokanDatabaseSnapshot? { val raw = localStorage.getItem(key) ?: return null val snapshot = decodeDatabaseSnapshot(raw) check(!requireValidSnapshot || snapshot != null) { "Profile database cannot be read safely" } return snapshot } override fun save(snapshot: YokanDatabaseSnapshot) { localStorage.setItem(key, encodeBrowserSnapshot(snapshot)) } } /** * Calls [write] once [quietMillis] pass without a change, or [maxWaitMillis] after the first * unsaved change while changes keep arriving, so a steady stream can't postpone saving forever. */ internal suspend fun coalesceWrites( changes: Flow<*>, quietMillis: Long, maxWaitMillis: Long, write: () -> Unit, ) = coroutineScope { val pending = Channel(Channel.CONFLATED) launch { changes.collect { pending.send(Unit) } } while (true) { pending.receive() withTimeoutOrNull(maxWaitMillis) { do { val changed = withTimeoutOrNull(quietMillis) { pending.receive() } } while (changed != null) } write() } } private fun pageHidden(): Boolean = js("document.visibilityState === 'hidden'") private fun createBrowserDatabase(profileId: ProfileId): SnapshotYokanDatabase { val job = SupervisorJob() lateinit var database: SnapshotYokanDatabase val hidden: (Event) -> Unit = { if (pageHidden()) database.persistIfDirty() } val pageHide: (Event) -> Unit = { database.persistIfDirty() } database = SnapshotYokanDatabase( WasmLocalStorageSnapshotStore(ProfileStorageNamespace(profileId).browserSnapshotKey, requireValidSnapshot = profileId != ProfileId.Default), stopPersistence = { job.cancelAndJoin() document.removeEventListener("visibilitychange", hidden) window.removeEventListener("pagehide", pageHide) }, ) CoroutineScope(Dispatchers.Default + job).launch { // persistIfDirty saves current memory, so a pending old emission cannot undo a restore. coalesceWrites(database.snapshots(), quietMillis = 1_000L, maxWaitMillis = 10_000L) { database.persistIfDirty() } } // The page may be discarded after either event without another chance to run. document.addEventListener("visibilitychange", hidden) window.addEventListener("pagehide", pageHide) return database } actual fun createDefaultDatabase(): YokanDatabase = createBrowserDatabase(ProfileId.Default) /** Each backend owns and removes its persistence job/listeners when the session closes it. */ actual fun createProfileDatabase(profileId: ProfileId): YokanDatabase = createBrowserDatabase(profileId)