Yokan / rebuild
Course 1 8624561

PersistentDatabase.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/database/PersistentDatabase.wasm.kt

implementation114 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)23package eu.friedcutlet.yokan.database45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.domain.ProfileStorageNamespace7import kotlinx.browser.document8import kotlinx.browser.localStorage9import kotlinx.browser.window10import kotlinx.coroutines.CoroutineScope11import kotlinx.coroutines.Dispatchers12import kotlinx.coroutines.SupervisorJob13import kotlinx.coroutines.cancelAndJoin14import kotlinx.coroutines.channels.Channel15import kotlinx.coroutines.coroutineScope16import kotlinx.coroutines.flow.Flow17import kotlinx.coroutines.launch18import kotlinx.coroutines.withTimeoutOrNull19import kotlinx.serialization.json.Json20import org.w3c.dom.events.Event2122actual fun createDefaultDatabaseSnapshotStore(): DatabaseSnapshotStore = WasmLocalStorageSnapshotStore(SnapshotStorageKey)2324private const val SnapshotStorageKey = "yokan-database-v1"2526/** Compact: indentation would count against the ~5 MB localStorage quota for nothing. */27private val BrowserDatabaseJson = Json(DatabaseJson) { prettyPrint = false }2829/**30 * The page cache is dropped: page URLs expire, the web target has no offline reader, and it31 * was the largest unbounded part of the stored snapshot.32 */33internal fun encodeBrowserSnapshot(snapshot: YokanDatabaseSnapshot): String =34    BrowserDatabaseJson.encodeToString(35        PersistedDatabaseSnapshot(snapshot = snapshot.copy(pageCache = emptyList())),36    )3738/**39 * Whole-snapshot JSON persistence in `window.localStorage`. Room and the40 * bundled SQLite driver have no wasm artifacts, so the browser keeps the41 * legacy snapshot backend.42 */43// ponytail: one localStorage key keeps every save atomic (restore and F9 retry rely on it);44// per-section keys need a generation/manifest scheme, add it if saves still hit the quota.45private class WasmLocalStorageSnapshotStore(46    private val key: String,47    private val requireValidSnapshot: Boolean = false,48) : DatabaseSnapshotStore {49    override fun load(): YokanDatabaseSnapshot? {50        val raw = localStorage.getItem(key) ?: return null51        val snapshot = decodeDatabaseSnapshot(raw)52        check(!requireValidSnapshot || snapshot != null) { "Profile database cannot be read safely" }53        return snapshot54    }5556    override fun save(snapshot: YokanDatabaseSnapshot) {57        localStorage.setItem(key, encodeBrowserSnapshot(snapshot))58    }59}6061/**62 * Calls [write] once [quietMillis] pass without a change, or [maxWaitMillis] after the first63 * unsaved change while changes keep arriving, so a steady stream can't postpone saving forever.64 */65internal suspend fun coalesceWrites(66    changes: Flow<*>,67    quietMillis: Long,68    maxWaitMillis: Long,69    write: () -> Unit,70) = coroutineScope {71    val pending = Channel<Unit>(Channel.CONFLATED)72    launch { changes.collect { pending.send(Unit) } }73    while (true) {74        pending.receive()75        withTimeoutOrNull(maxWaitMillis) {76            do {77                val changed = withTimeoutOrNull(quietMillis) { pending.receive() }78            } while (changed != null)79        }80        write()81    }82}8384private fun pageHidden(): Boolean = js("document.visibilityState === 'hidden'")8586private fun createBrowserDatabase(profileId: ProfileId): SnapshotYokanDatabase {87    val job = SupervisorJob()88    lateinit var database: SnapshotYokanDatabase89    val hidden: (Event) -> Unit = { if (pageHidden()) database.persistIfDirty() }90    val pageHide: (Event) -> Unit = { database.persistIfDirty() }91    database = SnapshotYokanDatabase(92        WasmLocalStorageSnapshotStore(ProfileStorageNamespace(profileId).browserSnapshotKey, requireValidSnapshot = profileId != ProfileId.Default),93        stopPersistence = {94            job.cancelAndJoin()95            document.removeEventListener("visibilitychange", hidden)96            window.removeEventListener("pagehide", pageHide)97        },98    )99    CoroutineScope(Dispatchers.Default + job).launch {100        // persistIfDirty saves current memory, so a pending old emission cannot undo a restore.101        coalesceWrites(database.snapshots(), quietMillis = 1_000L, maxWaitMillis = 10_000L) {102            database.persistIfDirty()103        }104    }105    // The page may be discarded after either event without another chance to run.106    document.addEventListener("visibilitychange", hidden)107    window.addEventListener("pagehide", pageHide)108    return database109}110111actual fun createDefaultDatabase(): YokanDatabase = createBrowserDatabase(ProfileId.Default)112113/** Each backend owns and removes its persistence job/listeners when the session closes it. */114actual fun createProfileDatabase(profileId: ProfileId): YokanDatabase = createBrowserDatabase(profileId)115

Search chapters, reference and source filenames.