mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-21 22:15:40 +00:00
refactor(player): E.15 — extract server queue sync into module (#578)
The server-side queue persistence (Subsonic `savePlayQueue`) helpers
move into `src/store/queueSync.ts`:
- `syncQueueToServer` — 5-second debounce for rapid edits
- `flushQueueSyncToServer` — immediate flush (heartbeat, pause,
app close)
- `flushPlayQueuePosition` — exported wrapper that reads the live
playerStore queue + playback-progress current-time, skips radio
sessions
- `getLastQueueHeartbeatAt` — accessor the 15-second heartbeat
throttle in `handleAudioProgress` reads
The two timer/heartbeat mutables (`syncTimeout`, `lastQueueHeartbeatAt`)
are no longer reachable from outside the module. `flushPlayQueuePosition`
is re-exported from playerStore so TauriEventBridge + the persistence
characterization test keep their existing imports.
13 focused tests pin the debounce window, the 1000-id queue cap, the
cancel-on-immediate-flush behaviour, the no-op guards (empty queue /
null currentTrack / radio session), and the heartbeat-timestamp
contract.
playerStore 3238 → 3208 LOC.
This commit is contained in:
committed by
GitHub
parent
08d098d5aa
commit
2ad0be6a71
+11
-41
@@ -89,6 +89,16 @@ import {
|
||||
collectLoudnessBackfillWindowTrackIds,
|
||||
isTrackInsideLoudnessBackfillWindow,
|
||||
} from './loudnessBackfillWindow';
|
||||
import {
|
||||
flushPlayQueuePosition,
|
||||
flushQueueSyncToServer,
|
||||
getLastQueueHeartbeatAt,
|
||||
syncQueueToServer,
|
||||
} from './queueSync';
|
||||
|
||||
// Re-export so TauriEventBridge + persistence test keep their existing
|
||||
// `from './playerStore'` imports.
|
||||
export { flushPlayQueuePosition };
|
||||
|
||||
// Re-export the playback-progress public surface so existing call sites
|
||||
// (PlayerBar, FullscreenPlayer, WaveformSeek, LyricsPane, MobilePlayerView,
|
||||
@@ -816,46 +826,6 @@ let gaplessPreloadingId: string | null = null;
|
||||
// Track ID that has already been sent to audio_preload (byte pre-download).
|
||||
let bytePreloadingId: string | null = null;
|
||||
|
||||
// ─── Server queue sync ─────────────────────────────────────────────────────────
|
||||
let syncTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let lastQueueHeartbeatAt = 0;
|
||||
|
||||
function syncQueueToServer(queue: Track[], currentTrack: Track | null, currentTime: number) {
|
||||
if (syncTimeout) clearTimeout(syncTimeout);
|
||||
syncTimeout = setTimeout(() => {
|
||||
syncTimeout = null;
|
||||
const ids = queue.slice(0, 1000).map(t => t.id);
|
||||
const pos = Math.floor(currentTime * 1000);
|
||||
savePlayQueue(ids, currentTrack?.id, pos).catch(err => {
|
||||
console.error('Failed to sync play queue to server', err);
|
||||
});
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Cancel any pending debounced sync and push the current position
|
||||
// immediately. Used by the playback heartbeat, pause(), and the
|
||||
// app-close handler — all paths where a user might switch to another
|
||||
// device and expect to resume from the right spot.
|
||||
function flushQueueSyncToServer(queue: Track[], currentTrack: Track | null, currentTime: number): Promise<void> {
|
||||
if (syncTimeout) {
|
||||
clearTimeout(syncTimeout);
|
||||
syncTimeout = null;
|
||||
}
|
||||
if (!currentTrack || queue.length === 0) return Promise.resolve();
|
||||
lastQueueHeartbeatAt = Date.now();
|
||||
const ids = queue.slice(0, 1000).map(t => t.id);
|
||||
const pos = Math.floor(currentTime * 1000);
|
||||
return savePlayQueue(ids, currentTrack.id, pos).catch(err => {
|
||||
console.error('Failed to flush play queue to server', err);
|
||||
});
|
||||
}
|
||||
|
||||
export function flushPlayQueuePosition(): Promise<void> {
|
||||
const s = usePlayerStore.getState();
|
||||
if (s.currentRadio) return Promise.resolve();
|
||||
return flushQueueSyncToServer(s.queue, s.currentTrack, getPlaybackProgressSnapshot().currentTime);
|
||||
}
|
||||
|
||||
// ─── Audio event handlers (called from initAudioListeners) ───────────────────
|
||||
|
||||
function handleAudioPlaying(_duration: number) {
|
||||
@@ -936,7 +906,7 @@ function handleAudioProgress(current_time: number, duration: number) {
|
||||
// handler flush on top of this for clean shutdowns.
|
||||
if (store.isPlaying && !store.currentRadio) {
|
||||
const now = Date.now();
|
||||
if (now - lastQueueHeartbeatAt >= 15_000) {
|
||||
if (now - getLastQueueHeartbeatAt() >= 15_000) {
|
||||
void flushQueueSyncToServer(store.queue, track, displayTime);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Server-queue-sync helpers: the 5-second debounce, the immediate flush,
|
||||
* the queue-id cap, and the radio-skip guard inside
|
||||
* `flushPlayQueuePosition`. Fake timers drive the debounce; mocks stand
|
||||
* in for `savePlayQueue`, the playerStore, and the playback-progress
|
||||
* snapshot.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Track } from './playerStore';
|
||||
|
||||
const { savePlayQueueMock, playerState, progressSnapshot } = vi.hoisted(() => ({
|
||||
savePlayQueueMock: vi.fn(async (_ids: string[], _currentId: string | undefined, _pos: number) => undefined),
|
||||
playerState: {
|
||||
queue: [] as Track[],
|
||||
currentTrack: null as Track | null,
|
||||
currentRadio: null as { id: string } | null,
|
||||
},
|
||||
progressSnapshot: { currentTime: 0, progress: 0, buffered: 0 },
|
||||
}));
|
||||
|
||||
vi.mock('../api/subsonic', () => ({ savePlayQueue: savePlayQueueMock }));
|
||||
vi.mock('./playerStore', () => ({
|
||||
usePlayerStore: { getState: () => playerState },
|
||||
}));
|
||||
vi.mock('./playbackProgress', () => ({
|
||||
getPlaybackProgressSnapshot: () => progressSnapshot,
|
||||
}));
|
||||
|
||||
import {
|
||||
_resetQueueSyncForTest,
|
||||
flushPlayQueuePosition,
|
||||
flushQueueSyncToServer,
|
||||
getLastQueueHeartbeatAt,
|
||||
syncQueueToServer,
|
||||
} from './queueSync';
|
||||
|
||||
function track(id: string): Track {
|
||||
return { id, title: id, artist: 'A', album: 'X', albumId: 'X', duration: 100 };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-05-12T12:00:00Z'));
|
||||
savePlayQueueMock.mockClear();
|
||||
savePlayQueueMock.mockResolvedValue(undefined);
|
||||
playerState.queue = [];
|
||||
playerState.currentTrack = null;
|
||||
playerState.currentRadio = null;
|
||||
progressSnapshot.currentTime = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
_resetQueueSyncForTest();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('syncQueueToServer (debounced)', () => {
|
||||
const queue = [track('a'), track('b')];
|
||||
|
||||
it('does not fire before 5 s elapse', () => {
|
||||
syncQueueToServer(queue, queue[0], 30);
|
||||
vi.advanceTimersByTime(4999);
|
||||
expect(savePlayQueueMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fires once after 5 s with id list + current id + position in ms', () => {
|
||||
syncQueueToServer(queue, queue[0], 30);
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b'], 'a', 30000);
|
||||
});
|
||||
|
||||
it('cancels the previous timer when called again before fire', () => {
|
||||
syncQueueToServer(queue, queue[0], 10);
|
||||
vi.advanceTimersByTime(3000);
|
||||
syncQueueToServer([...queue, track('c')], queue[0], 20);
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b', 'c'], 'a', 20000);
|
||||
});
|
||||
|
||||
it('caps the queue at 1000 ids', () => {
|
||||
const big = Array.from({ length: 1500 }, (_, i) => track(`t${i}`));
|
||||
syncQueueToServer(big, big[0], 0);
|
||||
vi.advanceTimersByTime(5000);
|
||||
const ids = savePlayQueueMock.mock.calls[0][0] as string[];
|
||||
expect(ids.length).toBe(1000);
|
||||
expect(ids[0]).toBe('t0');
|
||||
expect(ids[999]).toBe('t999');
|
||||
});
|
||||
});
|
||||
|
||||
describe('flushQueueSyncToServer (immediate)', () => {
|
||||
it('fires synchronously with no debounce', async () => {
|
||||
await flushQueueSyncToServer([track('a')], track('a'), 12);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledWith(['a'], 'a', 12000);
|
||||
});
|
||||
|
||||
it('cancels a pending debounced sync first', async () => {
|
||||
syncQueueToServer([track('a')], track('a'), 30);
|
||||
await flushQueueSyncToServer([track('a')], track('a'), 31);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
|
||||
// After the flush returns, advancing past the debounce should not fire again.
|
||||
vi.advanceTimersByTime(10_000);
|
||||
expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('is a no-op when currentTrack is null', async () => {
|
||||
await flushQueueSyncToServer([track('a')], null, 5);
|
||||
expect(savePlayQueueMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is a no-op for an empty queue', async () => {
|
||||
await flushQueueSyncToServer([], track('a'), 5);
|
||||
expect(savePlayQueueMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('records the heartbeat timestamp', async () => {
|
||||
expect(getLastQueueHeartbeatAt()).toBe(0);
|
||||
await flushQueueSyncToServer([track('a')], track('a'), 5);
|
||||
expect(getLastQueueHeartbeatAt()).toBe(Date.now());
|
||||
});
|
||||
});
|
||||
|
||||
describe('flushPlayQueuePosition', () => {
|
||||
it('reads the current playerStore queue + playback-progress time', async () => {
|
||||
playerState.queue = [track('a'), track('b')];
|
||||
playerState.currentTrack = playerState.queue[0];
|
||||
progressSnapshot.currentTime = 42;
|
||||
await flushPlayQueuePosition();
|
||||
expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b'], 'a', 42000);
|
||||
});
|
||||
|
||||
it('is a no-op when a radio session is active', async () => {
|
||||
playerState.queue = [track('a')];
|
||||
playerState.currentTrack = playerState.queue[0];
|
||||
playerState.currentRadio = { id: 'radio-1' };
|
||||
await flushPlayQueuePosition();
|
||||
expect(savePlayQueueMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { savePlayQueue } from '../api/subsonic';
|
||||
import { getPlaybackProgressSnapshot } from './playbackProgress';
|
||||
import { usePlayerStore, type Track } from './playerStore';
|
||||
|
||||
/**
|
||||
* Server-side play-queue persistence. Subsonic's `savePlayQueue` accepts
|
||||
* the current queue, the active track id, and the position in ms — so the
|
||||
* server can hand the same playback state back when the user opens
|
||||
* another client.
|
||||
*
|
||||
* Two flush shapes:
|
||||
* - `syncQueueToServer` debounces for 5 s so rapid edits (drag-reorder,
|
||||
* auto-queue trimming, lucky-mix swaps) collapse into a single roundtrip.
|
||||
* - `flushQueueSyncToServer` cancels the debounce and pushes immediately —
|
||||
* called from the playback heartbeat, `pause()`, and the app-close path
|
||||
* where the user might switch devices mid-track.
|
||||
*
|
||||
* Queues are capped at 1000 ids to match Subsonic's max-length contract.
|
||||
* Radio sessions skip persistence (the seed station is restored separately).
|
||||
*/
|
||||
|
||||
const SYNC_DEBOUNCE_MS = 5000;
|
||||
const QUEUE_ID_LIMIT = 1000;
|
||||
|
||||
let syncTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let lastQueueHeartbeatAt = 0;
|
||||
|
||||
export function syncQueueToServer(queue: Track[], currentTrack: Track | null, currentTime: number): void {
|
||||
if (syncTimeout) clearTimeout(syncTimeout);
|
||||
syncTimeout = setTimeout(() => {
|
||||
syncTimeout = null;
|
||||
const ids = queue.slice(0, QUEUE_ID_LIMIT).map(t => t.id);
|
||||
const pos = Math.floor(currentTime * 1000);
|
||||
savePlayQueue(ids, currentTrack?.id, pos).catch(err => {
|
||||
console.error('Failed to sync play queue to server', err);
|
||||
});
|
||||
}, SYNC_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
export function flushQueueSyncToServer(queue: Track[], currentTrack: Track | null, currentTime: number): Promise<void> {
|
||||
if (syncTimeout) {
|
||||
clearTimeout(syncTimeout);
|
||||
syncTimeout = null;
|
||||
}
|
||||
if (!currentTrack || queue.length === 0) return Promise.resolve();
|
||||
lastQueueHeartbeatAt = Date.now();
|
||||
const ids = queue.slice(0, QUEUE_ID_LIMIT).map(t => t.id);
|
||||
const pos = Math.floor(currentTime * 1000);
|
||||
return savePlayQueue(ids, currentTrack.id, pos).catch(err => {
|
||||
console.error('Failed to flush play queue to server', err);
|
||||
});
|
||||
}
|
||||
|
||||
/** Last heartbeat timestamp (ms epoch). Used by the playback heartbeat to throttle the 15-second auto-flush cadence. */
|
||||
export function getLastQueueHeartbeatAt(): number {
|
||||
return lastQueueHeartbeatAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush the current playerStore queue to the server immediately. Skips
|
||||
* radio sessions (the seed station is restored separately). Reads the
|
||||
* live current-time via the playback-progress snapshot so the position
|
||||
* isn't stale by the debounced store commit.
|
||||
*/
|
||||
export function flushPlayQueuePosition(): Promise<void> {
|
||||
const s = usePlayerStore.getState();
|
||||
if (s.currentRadio) return Promise.resolve();
|
||||
return flushQueueSyncToServer(s.queue, s.currentTrack, getPlaybackProgressSnapshot().currentTime);
|
||||
}
|
||||
|
||||
/** Test-only: drop the debounce + reset the heartbeat. */
|
||||
export function _resetQueueSyncForTest(): void {
|
||||
if (syncTimeout) {
|
||||
clearTimeout(syncTimeout);
|
||||
syncTimeout = null;
|
||||
}
|
||||
lastQueueHeartbeatAt = 0;
|
||||
}
|
||||
Reference in New Issue
Block a user