Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import org.siloserver.silo.model.section.ResolvedSection
import org.siloserver.silo.network.AuthScopeSnapshot
import org.siloserver.silo.network.DefaultIdentityTransitionBarrier
import org.siloserver.silo.network.IdentityTransitionBarrier
import org.siloserver.silo.repository.ArtworkSizing
import org.siloserver.silo.repository.ArtworkSurface
import org.siloserver.silo.repository.port.CatalogCachePort
import org.siloserver.silo.repository.port.CatalogCacheWriteLease
import kotlinx.serialization.json.Json
Expand All @@ -21,13 +23,15 @@ import kotlinx.serialization.json.Json
* Room-backed [CatalogCachePort] (Track B). Stores each catalog read as a JSON
* blob in the generic `catalog_cache` table, scoped to the active
* `(serverId, profileId)`. Corrupt/forward-incompatible JSON decodes to null
* rather than crashing the browse screen.
* rather than crashing the browse screen. Reads that carry artwork are keyed by
* the widths their screen draws it at.
*/
class RoomCatalogCacheRepository(
db: SiloDatabase,
private val snapshotProvider: suspend () -> AuthScopeSnapshot?,
private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(),
private val now: () -> Long = { System.currentTimeMillis() },
private val artwork: ArtworkSizing = ArtworkSizing.None,
) : CatalogCachePort {

private val dao = db.catalogCacheDao()
Expand All @@ -45,8 +49,9 @@ class RoomCatalogCacheRepository(
override suspend fun cacheLibraries(libraries: List<UserLibrary>) =
cacheLibraries(libraries, currentWriteLease())

override suspend fun cacheLibraries(libraries: List<UserLibrary>, lease: CatalogCacheWriteLease) =
override suspend fun cacheLibraries(libraries: List<UserLibrary>, lease: CatalogCacheWriteLease) {
put(KEY_LIBRARIES, json.encodeToString(libraries), lease)
}

override suspend fun getCachedLibraries(): List<UserLibrary>? =
get(KEY_LIBRARIES)?.let { runCatching { json.decodeFromString<List<UserLibrary>>(it) }.getOrNull() }
Expand All @@ -58,10 +63,11 @@ class RoomCatalogCacheRepository(
libraryId: Int,
response: CatalogResponse,
lease: CatalogCacheWriteLease,
) = put(libraryKey(libraryId), json.encodeToString(response), lease)
) = putArtwork(libraryPrefix(libraryId), ArtworkSurface.BROWSE, json.encodeToString(response), lease)

override suspend fun getCachedDefaultLibraryPage(libraryId: Int): CatalogResponse? =
get(libraryKey(libraryId))?.let { runCatching { json.decodeFromString<CatalogResponse>(it) }.getOrNull() }
getArtwork(libraryPrefix(libraryId), ArtworkSurface.BROWSE)
?.let { runCatching { json.decodeFromString<CatalogResponse>(it) }.getOrNull() }

override suspend fun cacheLibrarySections(libraryId: Int, sections: List<ResolvedSection>) =
cacheLibrarySections(libraryId, sections, currentWriteLease())
Expand All @@ -70,34 +76,44 @@ class RoomCatalogCacheRepository(
libraryId: Int,
sections: List<ResolvedSection>,
lease: CatalogCacheWriteLease,
) = put(librarySectionsKey(libraryId), json.encodeToString(sections), lease)
) {
put(librarySectionsKey(libraryId), json.encodeToString(sections), lease)
}

override suspend fun getCachedLibrarySections(libraryId: Int): List<ResolvedSection>? =
get(librarySectionsKey(libraryId))?.let { runCatching { json.decodeFromString<List<ResolvedSection>>(it) }.getOrNull() }

override suspend fun cacheLibrarySectionsV2(libraryId: Int, sections: List<ResolvedSection>, owner: AuthScopeSnapshot) {
override suspend fun cacheLibrarySectionsV2(libraryId: Int, sections: List<ResolvedSection>, owner: AuthScopeSnapshot,
artworkFingerprint: String?) {
val profile = owner.profileId ?: return
if (owner != snapshotProvider()) return
val key = librarySectionsV2Key(libraryId, owner)
val key = librarySectionsV2Key(libraryId, owner, artworkFingerprint)
val body = json.encodeToString(sections)
if (body.encodeToByteArray().size > MAX_CACHE_BYTES) {
dao.delete(owner.serverId, profile, key)
return
}
// Address only the captured owner's key, even if identity changes during Room's suspension.
dao.upsert(CatalogCacheEntity(owner.serverId, profile, key, body, now()))
val legacy = librarySectionsV2LegacyKey(libraryId, owner)
if (key != legacy) runCatching { dao.delete(owner.serverId, profile, legacy) }
}

override suspend fun getCachedLibrarySectionsV2(libraryId: Int, owner: AuthScopeSnapshot): List<ResolvedSection>? {
val profile = owner.profileId ?: return null
if (owner != snapshotProvider()) return null
val key = librarySectionsV2Key(libraryId, owner)
val row = runCatching { dao.get(owner.serverId, profile, key) }.getOrNull()
val legacy = librarySectionsV2LegacyKey(libraryId, owner)
val row = runCatching {
dao.get(owner.serverId, profile, key) ?: if (key != legacy) dao.get(owner.serverId, profile, legacy) else null
}.getOrNull()
if (owner != snapshotProvider()) return null
return row?.json?.let { runCatching { json.decodeFromString<List<ResolvedSection>>(it) }.getOrNull() }
}

private fun librarySectionsV2Key(libraryId: Int, owner: AuthScopeSnapshot): String =
private suspend fun librarySectionsV2Key(libraryId: Int, owner: AuthScopeSnapshot, artworkFingerprint: String? = null): String =
owner.identityCacheKey(artworkKey("library-sections-v2:$libraryId", ArtworkSurface.HOME, artworkFingerprint))
private fun librarySectionsV2LegacyKey(libraryId: Int, owner: AuthScopeSnapshot): String =
owner.identityCacheKey("library-sections-v2:$libraryId")

override suspend fun cacheItemDetail(contentId: String, detail: ItemDetail) =
Expand All @@ -107,10 +123,11 @@ class RoomCatalogCacheRepository(
contentId: String,
detail: ItemDetail,
lease: CatalogCacheWriteLease,
) = put(itemDetailKey(contentId), json.encodeToString(detail), lease)
) = putArtwork(itemDetailPrefix(contentId), ArtworkSurface.DETAIL, json.encodeToString(detail), lease)

override suspend fun getCachedItemDetail(contentId: String): ItemDetail? =
get(itemDetailKey(contentId))?.let { runCatching { json.decodeFromString<ItemDetail>(it) }.getOrNull() }
getArtwork(itemDetailPrefix(contentId), ArtworkSurface.DETAIL)
?.let { runCatching { json.decodeFromString<ItemDetail>(it) }.getOrNull() }

override suspend fun cacheSeasons(seriesId: String, response: SeasonsResponse) =
cacheSeasons(seriesId, response, currentWriteLease())
Expand All @@ -119,7 +136,9 @@ class RoomCatalogCacheRepository(
seriesId: String,
response: SeasonsResponse,
lease: CatalogCacheWriteLease,
) = put(seasonsKey(seriesId), json.encodeToString(response), lease)
) {
put(seasonsKey(seriesId), json.encodeToString(response), lease)
}

override suspend fun getCachedSeasons(seriesId: String): SeasonsResponse? =
get(seasonsKey(seriesId))?.let { runCatching { json.decodeFromString<SeasonsResponse>(it) }.getOrNull() }
Expand All @@ -132,26 +151,29 @@ class RoomCatalogCacheRepository(
seasonNumber: Int,
response: EpisodesResponse,
lease: CatalogCacheWriteLease,
) = put(episodesKey(seriesId, seasonNumber), json.encodeToString(response), lease)
surface: ArtworkSurface,
) = putArtwork(episodesPrefix(seriesId, seasonNumber), surface, json.encodeToString(response), lease)

override suspend fun getCachedEpisodes(seriesId: String, seasonNumber: Int): EpisodesResponse? =
get(episodesKey(seriesId, seasonNumber))?.let { runCatching { json.decodeFromString<EpisodesResponse>(it) }.getOrNull() }
override suspend fun getCachedEpisodes(seriesId: String, seasonNumber: Int, surface: ArtworkSurface): EpisodesResponse? =
getArtwork(episodesPrefix(seriesId, seasonNumber), surface)
?.let { runCatching { json.decodeFromString<EpisodesResponse>(it) }.getOrNull() }

/** The owner the row was written for, or null when it wasn't written. */
private suspend fun put(
cacheKey: String,
jsonStr: String,
lease: CatalogCacheWriteLease,
) {
if (lease.identityGeneration != identityTransitions.generation.value) return
val snapshot = snapshotProvider() ?: return
val profileId = snapshot.profileId ?: return
if (lease.identityGeneration != identityTransitions.generation.value) return
): CatalogCacheScope? {
if (lease.identityGeneration != identityTransitions.generation.value) return null
val snapshot = snapshotProvider() ?: return null
val profileId = snapshot.profileId ?: return null
if (lease.identityGeneration != identityTransitions.generation.value) return null
// A Room row must fit SQLite's ~2MB CursorWindow or the *read* throws
// SQLiteBlobTooBigException. Big library pages can exceed it, so don't
// store an unreadable row — drop any prior row for this key and skip.
if (jsonStr.encodeToByteArray().size > MAX_CACHE_BYTES) {
runCatching { dao.delete(snapshot.serverId, profileId, cacheKey) }
return
return null
}
dao.upsert(
CatalogCacheEntity(
Expand All @@ -162,6 +184,7 @@ class RoomCatalogCacheRepository(
cachedAtMs = now(),
),
)
return CatalogCacheScope(snapshot.serverId, profileId)
}

private fun currentWriteLease() =
Expand All @@ -179,14 +202,33 @@ class RoomCatalogCacheRepository(
}?.json
}

// A write uses the fingerprint its read captured; a read uses the current one.
private suspend fun artworkKey(prefix: String, surface: ArtworkSurface, captured: String?) =
if (captured != null) ArtworkSizing.cacheKey(prefix, captured) else artwork.cacheKey(prefix, surface)

// Rows cached before artwork widths were keyed by the bare prefix. A read
// falls back to one until this item is cached again, which retires it.
private suspend fun getArtwork(prefix: String, surface: ArtworkSurface): String? {
val key = artwork.cacheKey(prefix, surface)
return get(key) ?: if (key != prefix) get(prefix) else null
}

private suspend fun putArtwork(prefix: String, surface: ArtworkSurface, jsonStr: String, lease: CatalogCacheWriteLease) {
val key = artworkKey(prefix, surface, lease.artworkFingerprint)
// Retire the legacy row of the owner the write went to, even if identity changed since.
val owner = put(key, jsonStr, lease) ?: return
if (key != prefix) runCatching { dao.delete(owner.serverId, owner.profileId, prefix) }
}

private fun libraryPrefix(libraryId: Int) = "library:$libraryId"
private fun itemDetailPrefix(contentId: String) = "item-detail:$contentId"
private fun episodesPrefix(seriesId: String, seasonNumber: Int) = "episodes:$seriesId:$seasonNumber"

private companion object {
// Stay well under SQLite's ~2MB CursorWindow.
const val MAX_CACHE_BYTES = 1_500_000
const val KEY_LIBRARIES = "libraries"
fun libraryKey(libraryId: Int) = "library:$libraryId"
fun librarySectionsKey(libraryId: Int) = "library-sections:$libraryId"
fun itemDetailKey(contentId: String) = "item-detail:$contentId"
fun seasonsKey(seriesId: String) = "seasons:$seriesId"
fun episodesKey(seriesId: String, seasonNumber: Int) = "episodes:$seriesId:$seasonNumber"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import org.siloserver.silo.model.section.ResolvedSection
import org.siloserver.silo.network.AuthScopeSnapshot
import org.siloserver.silo.network.DefaultIdentityTransitionBarrier
import org.siloserver.silo.network.IdentityTransitionBarrier
import org.siloserver.silo.repository.ArtworkSizing
import org.siloserver.silo.repository.ArtworkSurface
import org.siloserver.silo.repository.port.HomeCachePort
import org.siloserver.silo.repository.port.HomeCacheSnapshot
import org.siloserver.silo.repository.port.HomeCacheWriteLease
Expand All @@ -26,13 +28,17 @@ import kotlinx.serialization.json.Json
* The blob is encoded and decoded on [jsonDispatcher]: callers read the cache
* from the main thread, and with 100-item Home rows the blob is about 1 MB,
* which takes hundreds of milliseconds to decode on a low-end TV.
*
* The v2 key carries the artwork widths Home is drawn at, so a layout change
* never serves artwork sized for another.
*/
class RoomHomeCacheRepository(
private val db: SiloDatabase,
private val snapshotProvider: suspend () -> AuthScopeSnapshot?,
private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(),
private val now: () -> Long = { System.currentTimeMillis() },
private val jsonDispatcher: CoroutineDispatcher = Dispatchers.Default,
private val artwork: ArtworkSizing = ArtworkSizing.None,
) : HomeCachePort {

private val dao = db.homeCacheDao()
Expand All @@ -52,25 +58,31 @@ class RoomHomeCacheRepository(
}
}

override suspend fun cacheHomeV2(sections: List<ResolvedSection>, owner: AuthScopeSnapshot, stillCurrent: () -> Boolean) {
override suspend fun artworkFingerprint(): String = artwork.cacheFingerprint(ArtworkSurface.HOME)

override suspend fun cacheHomeV2(sections: List<ResolvedSection>, owner: AuthScopeSnapshot, artworkFingerprint: String?,
stillCurrent: () -> Boolean) {
val profile = owner.profileId ?: return
// Encoding suspends, so it runs before the ownership check, not between it and the write.
val body = encode(sections)
if (owner != snapshotProvider()) return
val key = scopedKey(owner)
val key = scopedKey(owner, artworkFingerprint)
val legacy = legacyKey(owner)
db.withTransaction {
if (!stillCurrent()) return@withTransaction
if (body.encodeToByteArray().size > MAX_CACHE_BYTES) scopedDao.delete(owner.serverId, profile, key)
else scopedDao.upsert(org.siloserver.silo.common.data.db.entity.CatalogCacheEntity(owner.serverId, profile, key, body, now()))
if (key != legacy) scopedDao.delete(owner.serverId, profile, legacy)
}
}

override suspend fun cacheHomeV2IfAbsent(sections: List<ResolvedSection>, owner: AuthScopeSnapshot, stillCurrent: () -> Boolean) {
override suspend fun cacheHomeV2IfAbsent(sections: List<ResolvedSection>, owner: AuthScopeSnapshot, artworkFingerprint: String?,
stillCurrent: () -> Boolean) {
val profile = owner.profileId ?: return
val body = encode(sections)
if (body.encodeToByteArray().size > MAX_CACHE_BYTES) return
if (owner != snapshotProvider()) return
val key = scopedKey(owner)
val key = scopedKey(owner, artworkFingerprint)
db.withTransaction {
if (!stillCurrent() || scopedDao.get(owner.serverId, profile, key) != null) return@withTransaction
scopedDao.upsert(org.siloserver.silo.common.data.db.entity.CatalogCacheEntity(owner.serverId, profile, key, body, now()))
Expand All @@ -80,13 +92,23 @@ class RoomHomeCacheRepository(
override suspend fun getCachedHomeV2(owner: AuthScopeSnapshot): HomeCacheSnapshot? {
val profile = owner.profileId ?: return null
if (owner != snapshotProvider()) return null
val row = runCatching { scopedDao.get(owner.serverId, profile, scopedKey(owner)) }.getOrNull() ?: return null
val key = scopedKey(owner)
val legacy = legacyKey(owner)
val row = runCatching {
scopedDao.get(owner.serverId, profile, key) ?: if (key != legacy) scopedDao.get(owner.serverId, profile, legacy) else null
}.getOrNull() ?: return null
val sections = decode(row.json)
if (owner != snapshotProvider()) return null
return sections?.let { HomeCacheSnapshot(it, row.cachedAtMs) }
}

private fun scopedKey(owner: AuthScopeSnapshot): String = owner.identityCacheKey("home-sections-v2")
// A write uses the fingerprint its read captured; a read uses the current one.
private suspend fun scopedKey(owner: AuthScopeSnapshot, captured: String? = null): String =
owner.identityCacheKey(ArtworkSizing.cacheKey("home-sections-v2", captured ?: artworkFingerprint()))

// Home cached before artwork widths was keyed without them. A read falls
// back to it until Home is cached again, which retires it.
private fun legacyKey(owner: AuthScopeSnapshot): String = owner.identityCacheKey("home-sections-v2")

override suspend fun cacheHome(sections: List<ResolvedSection>) {
cacheHome(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ interface CardPresentationStore {
/** Idempotent first-load. Safe to call from every provider mount. */
suspend fun hydrateIfNeeded()

/**
* Applies this identity's last-known value from the local cache, without
* the network, if nothing has loaded yet. Idempotent and cheap after the
* first call, so work that runs before the UI (such as sizing the first
* Home read) can see the user's choice.
*/
suspend fun seedFromCache() {}

/** Re-probe capabilities + re-resolve the effective value. */
suspend fun refresh()

Expand Down Expand Up @@ -112,6 +120,10 @@ class DefaultCardPresentationStore(
@Volatile
private var hasHydrated: Boolean = false

// Whether this session's cached value has been applied (or there was none).
@Volatile
private var hasSeeded: Boolean = false

// The last state confirmed by a canonical read or write; the rollback
// target for a failed optimistic edit.
private var confirmedState: CardPresentationUiState = _state.value
Expand Down Expand Up @@ -146,19 +158,24 @@ class DefaultCardPresentationStore(
// Seed from the last-known cache for this exact identity so cold start
// renders at the right size without a resize jump once the network
// answer lands.
currentIdentity()?.let { identity ->
readCachedState(identity)?.let { cached ->
synchronized(stateLock) {
// Only paint the cache over untouched (pre-hydration,
// pre-edit) state.
if (!hasHydrated && _state.value == confirmedState) {
confirmedState = cached
_state.value = cached
}
seedFromCache()
refresh()
}

override suspend fun seedFromCache() {
if (hasSeeded || hasHydrated) return
val identity = currentIdentity() ?: return
readCachedState(identity)?.let { cached ->
synchronized(stateLock) {
// Only paint the cache over untouched (pre-hydration,
// pre-edit) state.
if (!hasHydrated && _state.value == confirmedState) {
confirmedState = cached
_state.value = cached
}
}
}
refresh()
hasSeeded = true
}

/**
Expand Down Expand Up @@ -441,6 +458,7 @@ class DefaultCardPresentationStore(
_state.value = CardPresentationUiState()
confirmedState = _state.value
hasHydrated = false
hasSeeded = false
// Let the next session's hydrateIfNeeded run instead of observing
// the previous session's loading flag and returning early.
_isLoading.value = false
Expand Down
Loading
Loading