Yokan / rebuild
Course 1 8624561

PersistentDatabase.kt

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

implementation68 lines
1package eu.friedcutlet.yokan.database23import kotlinx.serialization.Serializable4import kotlinx.serialization.json.Json56/**7 * Snapshot storage used by the browser backend and as the one-shot legacy8 * loader for Room migration. Non-web runtime persistence is owned by Room;9 * the browser uses `save()` for its deferred snapshot persistence.10 */11interface DatabaseSnapshotStore {12    fun load(): YokanDatabaseSnapshot?13    fun save(snapshot: YokanDatabaseSnapshot)14}1516expect fun createDefaultDatabaseSnapshotStore(): DatabaseSnapshotStore1718/**19 * Pick the persistence backend. Android/desktop/iOS use Room (per-row20 * INSERTs, fast); the browser keeps the whole-snapshot JSON store because21 * neither Room nor bundled SQLite ship wasm artifacts.22 */23expect fun createDefaultDatabase(): YokanDatabase2425/** Low-level storage factory; only a registry/session coordinator may publish an additional profile. */26expect fun createProfileDatabase(profileId: eu.friedcutlet.yokan.domain.ProfileId): YokanDatabase2728@Serializable29data class PersistedDatabaseSnapshot(30    val schemaVersion: Int = CurrentDatabaseSchemaVersion,31    val snapshot: YokanDatabaseSnapshot,32)3334const val CurrentDatabaseSchemaVersion = 13536val DatabaseJson = Json {37    encodeDefaults = true38    ignoreUnknownKeys = true39    prettyPrint = true40}4142fun encodeDatabaseSnapshot(snapshot: YokanDatabaseSnapshot): String =43    DatabaseJson.encodeToString(PersistedDatabaseSnapshot(snapshot = snapshot))4445fun decodeDatabaseSnapshot(raw: String): YokanDatabaseSnapshot? = runCatching {46    normalizeLegacySnapshot(raw, DatabaseJson.decodeFromString<PersistedDatabaseSnapshot>(raw).snapshot)47}.recoverCatching {48    normalizeLegacySnapshot(raw, DatabaseJson.decodeFromString<YokanDatabaseSnapshot>(raw))49}.getOrNull()5051private fun normalizeLegacySnapshot(raw: String, snapshot: YokanDatabaseSnapshot): YokanDatabaseSnapshot {52    if (raw.contains("\"hubRecoveryPending\"") && raw.contains("\"hubBootstrapComplete\"")) {53        return snapshot54    }55    return snapshot.copy(56        syncPreferences = snapshot.syncPreferences.map { preference ->57            if (preference.hubEpoch > 0 ||58                preference.hubHead > 0 ||59                preference.hubRecoveryPending ||60                (!preference.server.isNullOrBlank() && !preference.authToken.isNullOrBlank())61            ) {62                preference.copy(hubBootstrapComplete = true)63            } else {64                preference65            }66        },67    )68}69

Search chapters, reference and source filenames.