- Cache queries and songs across mobile and web - Show cached content and skeletons during loading - Move shared playback and cache utilities into Convex client
271 lines
6.7 KiB
TypeScript
271 lines
6.7 KiB
TypeScript
import type { Id } from "../convex/_generated/dataModel"
|
|
import {
|
|
EMPTY_PLAYBACK_QUEUE,
|
|
type PlaybackQueueState,
|
|
type RepeatMode,
|
|
} from "./playback-queue"
|
|
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
|
|
|
const SYNC_DELAY_MS = 300
|
|
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
|
|
|
export type ServerPlaybackState = {
|
|
queueSongIds: Id<"songs">[]
|
|
queueHistorySongIds: Id<"songs">[]
|
|
shuffleEnabled: boolean
|
|
repeatEnabled: RepeatMode
|
|
currentSongProgress: number
|
|
revision: number
|
|
}
|
|
|
|
/** Everything except progress, which changes too often to re-render on. */
|
|
export type PlaybackSnapshot = Omit<PlaybackQueueState, "progressSeconds"> & {
|
|
hydrated: boolean
|
|
}
|
|
|
|
type PersistedPlayback = PlaybackQueueState & {
|
|
/** Server revision the local state was last reconciled with. */
|
|
revision: number | null
|
|
/** Local changes that the server has not acknowledged yet. */
|
|
dirty: boolean
|
|
}
|
|
|
|
export type PlaybackSyncTransport = (
|
|
state: PlaybackQueueState
|
|
) => Promise<number>
|
|
|
|
/**
|
|
* Client-owned playback queue. Changes apply locally (and persist on this
|
|
* device) immediately, then sync to Convex in the background. Remote changes
|
|
* are adopted only when there are no unsynced local changes.
|
|
*/
|
|
export class PlaybackStore {
|
|
private state: PlaybackQueueState = EMPTY_PLAYBACK_QUEUE
|
|
private snapshot: PlaybackSnapshot = toSnapshot(EMPTY_PLAYBACK_QUEUE, false)
|
|
private revision: number | null = null
|
|
private dirty = false
|
|
private changeCount = 0
|
|
private inFlight = false
|
|
private retryAttempt = 0
|
|
private syncTimer: ReturnType<typeof setTimeout> | null = null
|
|
private latestServerState: ServerPlaybackState | null = null
|
|
private transport: PlaybackSyncTransport | null = null
|
|
private readonly listeners = new Set<() => void>()
|
|
|
|
constructor(private readonly storageKey: string | null) {
|
|
if (typeof window !== "undefined") {
|
|
void this.hydrate()
|
|
}
|
|
}
|
|
|
|
subscribe = (listener: () => void) => {
|
|
this.listeners.add(listener)
|
|
return () => {
|
|
this.listeners.delete(listener)
|
|
}
|
|
}
|
|
|
|
getSnapshot = () => this.snapshot
|
|
|
|
getState() {
|
|
return this.state
|
|
}
|
|
|
|
setTransport(transport: PlaybackSyncTransport | null) {
|
|
this.transport = transport
|
|
if (transport && this.dirty) {
|
|
this.scheduleSync(0)
|
|
}
|
|
}
|
|
|
|
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
|
|
const next = recipe(this.state)
|
|
if (next === this.state) {
|
|
return
|
|
}
|
|
|
|
this.changeCount += 1
|
|
this.dirty = true
|
|
this.setState(next)
|
|
this.scheduleSync(SYNC_DELAY_MS)
|
|
}
|
|
|
|
/** Records progress locally; the server copy is synced separately. */
|
|
setProgress(songId: Id<"songs">, progressSeconds: number) {
|
|
if (this.state.queue[0] !== songId) {
|
|
return
|
|
}
|
|
this.state = { ...this.state, progressSeconds }
|
|
this.persist()
|
|
}
|
|
|
|
receiveServerState(serverState: ServerPlaybackState) {
|
|
this.latestServerState = serverState
|
|
if (this.snapshot.hydrated) {
|
|
this.adoptServerState()
|
|
}
|
|
}
|
|
|
|
private async hydrate() {
|
|
await loadPersistentCache()
|
|
const persisted = this.storageKey
|
|
? readCache<PersistedPlayback>(this.storageKey)
|
|
: undefined
|
|
|
|
if (persisted && this.changeCount === 0) {
|
|
const { revision, dirty, ...state } = persisted
|
|
this.revision = revision
|
|
this.dirty = dirty
|
|
this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
|
|
}
|
|
|
|
this.snapshot = toSnapshot(this.state, true)
|
|
this.emit()
|
|
this.adoptServerState()
|
|
if (this.dirty) {
|
|
this.scheduleSync(0)
|
|
}
|
|
}
|
|
|
|
private adoptServerState() {
|
|
const serverState = this.latestServerState
|
|
if (!serverState || this.dirty || this.inFlight) {
|
|
return
|
|
}
|
|
if (this.revision !== null && serverState.revision <= this.revision) {
|
|
return
|
|
}
|
|
|
|
this.revision = serverState.revision
|
|
this.setState({
|
|
queue: serverState.queueSongIds,
|
|
history: serverState.queueHistorySongIds,
|
|
shuffleEnabled: serverState.shuffleEnabled,
|
|
repeatEnabled: serverState.repeatEnabled,
|
|
progressSeconds: serverState.currentSongProgress,
|
|
})
|
|
}
|
|
|
|
private scheduleSync(delayMs: number) {
|
|
if (this.syncTimer !== null) {
|
|
clearTimeout(this.syncTimer)
|
|
}
|
|
this.syncTimer = setTimeout(() => {
|
|
this.syncTimer = null
|
|
void this.flush()
|
|
}, delayMs)
|
|
}
|
|
|
|
private async flush() {
|
|
const transport = this.transport
|
|
if (!transport || this.inFlight || !this.dirty) {
|
|
return
|
|
}
|
|
|
|
this.inFlight = true
|
|
const changeCountAtStart = this.changeCount
|
|
let failed = false
|
|
|
|
try {
|
|
const revision = await transport(this.state)
|
|
this.revision = Math.max(revision, this.revision ?? 0)
|
|
this.retryAttempt = 0
|
|
if (this.changeCount === changeCountAtStart) {
|
|
this.dirty = false
|
|
}
|
|
} catch {
|
|
failed = true
|
|
} finally {
|
|
this.inFlight = false
|
|
}
|
|
|
|
this.persist()
|
|
|
|
if (failed) {
|
|
const delay =
|
|
RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
|
|
this.retryAttempt += 1
|
|
this.scheduleSync(delay)
|
|
} else if (this.dirty) {
|
|
this.scheduleSync(SYNC_DELAY_MS)
|
|
} else {
|
|
this.adoptServerState()
|
|
}
|
|
}
|
|
|
|
private setState(state: PlaybackQueueState) {
|
|
const previous = this.state
|
|
this.state = state
|
|
this.persist()
|
|
|
|
if (
|
|
previous.queue !== state.queue ||
|
|
previous.history !== state.history ||
|
|
previous.shuffleEnabled !== state.shuffleEnabled ||
|
|
previous.repeatEnabled !== state.repeatEnabled
|
|
) {
|
|
this.snapshot = toSnapshot(state, this.snapshot.hydrated)
|
|
this.emit()
|
|
}
|
|
}
|
|
|
|
private persist() {
|
|
if (!this.storageKey) {
|
|
return
|
|
}
|
|
writeCache(this.storageKey, {
|
|
...this.state,
|
|
revision: this.revision,
|
|
dirty: this.dirty,
|
|
} satisfies PersistedPlayback)
|
|
}
|
|
|
|
private emit() {
|
|
for (const listener of this.listeners) {
|
|
listener()
|
|
}
|
|
}
|
|
}
|
|
|
|
function toSnapshot(
|
|
state: PlaybackQueueState,
|
|
hydrated: boolean
|
|
): PlaybackSnapshot {
|
|
return {
|
|
queue: state.queue,
|
|
history: state.history,
|
|
shuffleEnabled: state.shuffleEnabled,
|
|
repeatEnabled: state.repeatEnabled,
|
|
hydrated,
|
|
}
|
|
}
|
|
|
|
const SERVER_SNAPSHOT = toSnapshot(EMPTY_PLAYBACK_QUEUE, false)
|
|
|
|
export function getServerPlaybackSnapshot() {
|
|
return SERVER_SNAPSHOT
|
|
}
|
|
|
|
const stores = new Map<string, PlaybackStore>()
|
|
|
|
export function getPlaybackStore(scope: string | null) {
|
|
if (typeof window === "undefined") {
|
|
return new PlaybackStore(null)
|
|
}
|
|
|
|
const key = scope ?? ""
|
|
let store = stores.get(key)
|
|
if (!store) {
|
|
store = new PlaybackStore(scope ? `playback:${scope}` : null)
|
|
stores.set(key, store)
|
|
}
|
|
return store
|
|
}
|
|
|
|
export function resetPlaybackStores() {
|
|
for (const store of stores.values()) {
|
|
store.setTransport(null)
|
|
}
|
|
stores.clear()
|
|
}
|