319 lines
8.3 KiB
TypeScript
319 lines
8.3 KiB
TypeScript
import type { Id } from "../convex/_generated/dataModel"
|
|
import { MAX_QUEUE_LENGTH } from "../convex/limits"
|
|
import {
|
|
EMPTY_PLAYBACK_QUEUE,
|
|
type PlaybackQueueState,
|
|
type RepeatMode,
|
|
} from "./playback-queue"
|
|
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
|
|
|
const SYNC_DELAY_MS = 300
|
|
/**
|
|
* Backoff for failed syncs. Convex queues mutations while offline, so a
|
|
* rejection means the server refused the state; after the last retry the
|
|
* change is dropped until the next local edit instead of retrying forever.
|
|
*/
|
|
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
|
|
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 = {
|
|
/** Saves the state and resolves with the new server revision. */
|
|
sync: (state: PlaybackQueueState) => Promise<number>
|
|
/** One-shot read of the server's saved progress for its current song. */
|
|
loadProgress: () => 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 adopting = false
|
|
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 = capQueue(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) {
|
|
void 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 = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state })
|
|
}
|
|
|
|
this.snapshot = toSnapshot(this.state, true)
|
|
this.emit()
|
|
void this.adoptServerState()
|
|
if (this.dirty) {
|
|
this.scheduleSync(0)
|
|
}
|
|
}
|
|
|
|
private canAdopt(serverState: ServerPlaybackState | null) {
|
|
return (
|
|
serverState !== null &&
|
|
!this.dirty &&
|
|
!this.inFlight &&
|
|
(this.revision === null || serverState.revision > this.revision)
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Adopts the latest server queue. Progress is not part of the queue query
|
|
* (it changes every few seconds), so it is fetched once here.
|
|
*/
|
|
private async adoptServerState() {
|
|
const serverState = this.latestServerState
|
|
if (this.adopting || !serverState || !this.canAdopt(serverState)) {
|
|
return
|
|
}
|
|
|
|
this.adopting = true
|
|
let progressSeconds = 0
|
|
try {
|
|
progressSeconds = (await this.transport?.loadProgress()) ?? 0
|
|
} catch {
|
|
// Starting from 0 beats not adopting the queue at all.
|
|
} finally {
|
|
this.adopting = false
|
|
}
|
|
|
|
// Newer server state or local edits may have arrived while loading.
|
|
if (this.latestServerState !== serverState) {
|
|
void this.adoptServerState()
|
|
return
|
|
}
|
|
if (!this.canAdopt(serverState)) {
|
|
return
|
|
}
|
|
|
|
this.revision = serverState.revision
|
|
this.setState({
|
|
queue: serverState.queueSongIds,
|
|
history: serverState.queueHistorySongIds,
|
|
shuffleEnabled: serverState.shuffleEnabled,
|
|
repeatEnabled: serverState.repeatEnabled,
|
|
progressSeconds,
|
|
})
|
|
}
|
|
|
|
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.sync(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 && this.retryAttempt < RETRY_DELAYS_MS.length) {
|
|
this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt])
|
|
this.retryAttempt += 1
|
|
} else if (failed) {
|
|
this.retryAttempt = 0
|
|
this.dirty = false
|
|
this.persist()
|
|
} else if (this.dirty) {
|
|
this.scheduleSync(SYNC_DELAY_MS)
|
|
} else {
|
|
void 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()
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Mirrors the server's queue cap so local and synced state agree. */
|
|
function capQueue(state: PlaybackQueueState): PlaybackQueueState {
|
|
if (state.queue.length <= MAX_QUEUE_LENGTH) {
|
|
return state
|
|
}
|
|
return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) }
|
|
}
|
|
|
|
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()
|
|
}
|