fix(web): repeat Play + startup race in playback troubleshooting
Review MUST-FIX + SHOULD-FIX (#145): - Repeat Play with unchanged settings was fully broken: the manifest GET is what starts a session server-side, but an identical URL made setPlayerSrc a state no-op, so HlsPlayer never re-attached and no request was issued — while the poll saw the previous session's stored result and toasted a spurious success over a dead player. HlsPlayer now takes a playToken prop (incremented per Play) that forces teardown/re-attach even for identical src. - First-poll race: PrepareTroubleshootingPlayback runs DB queries BEFORE taking the playback lock, so polls right after Play can still see the stale settled result. Replaced the manually-seeded 'running' assumption with a play-phase machine (idle -> starting -> running -> idle): settled statuses are ignored during 'starting' until the server has reported running at least once, with a 30s timeout that surfaces an error and stops polling. Play + downloads are gated and a Starting/Transcoding indicator shows for the whole busy window. Nits: mediaItem takes precedence over channel when both query params are present (matching Blazor); on-mount poll comment notes the intentional post-restart log recovery. Tests: repeat-play re-issues loadSource, stale settled ignored until running observed, starting timeout, download gating while busy, both-params precedence (web suite 378 -> 384). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,11 @@ export interface HlsPlayerProps {
|
||||
// The HLS manifest (.m3u8) URL to play, or null to render an idle player. Setting a new src
|
||||
// tears down any previous hls.js instance and re-attaches.
|
||||
src: string | null;
|
||||
// Increment to force a full teardown/re-attach even when src is unchanged. Needed when the
|
||||
// manifest GET itself starts a server-side session (e.g. troubleshooting playback.m3u8): a repeat
|
||||
// play with identical settings yields an identical URL, which would otherwise be a state no-op
|
||||
// that never issues a new request.
|
||||
playToken?: number;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
@@ -14,7 +19,7 @@ export interface HlsPlayerProps {
|
||||
// segments exist, so the manifest request must tolerate an unbounded time-to-first-byte), and falls
|
||||
// back to the browser's native HLS support (Safari) otherwise. Reusable across any screen that needs
|
||||
// to preview an ErsatzTV HLS stream.
|
||||
export function HlsPlayer({ src, className, style }: HlsPlayerProps) {
|
||||
export function HlsPlayer({ src, playToken = 0, className, style }: HlsPlayerProps) {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const hlsRef = useRef<Hls | null>(null);
|
||||
|
||||
@@ -76,7 +81,8 @@ export function HlsPlayer({ src, className, style }: HlsPlayerProps) {
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [src]);
|
||||
// playToken forces re-attachment for repeat plays of an identical src (see HlsPlayerProps).
|
||||
}, [src, playToken]);
|
||||
|
||||
// Final unmount safety net (covers the hls.js instance in every path).
|
||||
useEffect(
|
||||
|
||||
@@ -214,22 +214,148 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('opens the archive and media-sample downloads', async () => {
|
||||
it('re-issues the manifest request on a repeat Play with unchanged settings', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
|
||||
// First play through to completion.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000); // observe running
|
||||
statusRef.current = { state: 'completed', exitCode: 0, speed: 1.1, logs: 'done' };
|
||||
await vi.advanceTimersByTimeAsync(2000); // observe completed
|
||||
await vi.waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false)
|
||||
);
|
||||
|
||||
// Repeat Play with untouched settings: identical URL, but the manifest request MUST fire
|
||||
// again (the GET is what starts a session server-side).
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(2);
|
||||
expect(hlsMock.loadSource.mock.calls[1][0]).toBe(hlsMock.loadSource.mock.calls[0][0]);
|
||||
expect(hlsMock.destroy).toHaveBeenCalled(); // previous instance torn down before re-attach
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores a stale settled status while starting and only settles after observing running', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
// The store still holds the PREVIOUS session's result when Play is clicked.
|
||||
const statusRef = {
|
||||
current: { state: 'completed', exitCode: 0, speed: 2, logs: 'old logs' } as Status
|
||||
};
|
||||
installFetch(statusRef);
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
// Mount poll surfaces the previous session's logs (post-restart log recovery) without a toast.
|
||||
await vi.waitFor(() => expect(screen.getByDisplayValue('old logs')).toBeTruthy());
|
||||
expect(screen.queryByText(/exited successfully/i)).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
|
||||
// 'starting': Play disabled immediately, indicator shown, old logs cleared.
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(true);
|
||||
expect(screen.getByText('Starting…')).toBeTruthy();
|
||||
expect(screen.queryByDisplayValue('old logs')).toBeNull();
|
||||
|
||||
// A poll returning the STALE completed result must be ignored — no toast, still gated.
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(screen.queryByText(/exited successfully/i)).toBeNull();
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(true);
|
||||
expect(screen.queryByDisplayValue('old logs')).toBeNull();
|
||||
|
||||
// Server reports running → transcoding phase.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await vi.waitFor(() => expect(screen.getByText('Transcoding…')).toBeTruthy());
|
||||
|
||||
// Real completion → toast + new logs + Play re-enabled.
|
||||
statusRef.current = { state: 'completed', exitCode: 0, speed: 1.2, logs: 'new logs' };
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await vi.waitFor(() => expect(screen.getByText(/exited successfully/i)).toBeTruthy());
|
||||
expect(screen.getByDisplayValue('new logs')).toBeTruthy();
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('gives up with an error when the session never reports running', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
|
||||
// Status stays idle past the 30s starting timeout → error notice, Play re-enabled.
|
||||
await vi.advanceTimersByTimeAsync(32_000);
|
||||
await vi.waitFor(() => expect(screen.getByText(/did not start within 30 seconds/i)).toBeTruthy());
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('opens the archive and media-sample downloads, gated while a session is active', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
|
||||
// Download Media Sample is available while idle.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Media Sample/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/sample/5');
|
||||
|
||||
// Both downloads are gated while a session is starting/running.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((screen.getByRole('button', { name: /Download Media Sample/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
|
||||
// Run to completion → Download Results enabled (hasPlayed && not busy).
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
statusRef.current = { state: 'completed', exitCode: 0, speed: 1, logs: 'done' };
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await vi.waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(false)
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Results/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/archive');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('uses media mode when both mediaItem and channel params are present', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5&channel=7');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await screen.findByText(/Movie Settings/i);
|
||||
|
||||
// Download Media Sample is always available in media mode.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Media Sample/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/sample/5');
|
||||
|
||||
// Download Results is enabled once a session has played.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Results/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/archive');
|
||||
expect(await screen.findByText(/Movie Settings — Test Movie/i)).toBeTruthy();
|
||||
expect(screen.queryByText('Date and Time')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,6 +26,15 @@ import { parseDurationSeconds } from '../media/mediaKinds';
|
||||
// requests the segmenter mode for troubleshooting playback.
|
||||
const STREAMING_MODE_HLS_SEGMENTER = 4;
|
||||
const STATUS_POLL_MS = 2000;
|
||||
// How long after Play we keep waiting for the server to report 'running' before giving up.
|
||||
// PrepareTroubleshootingPlayback runs several DB queries before it takes the playback lock, so the
|
||||
// first polls after Play can still see the PREVIOUS session's settled result — those are ignored
|
||||
// during the 'starting' phase (see applyStatus) until this timeout elapses.
|
||||
const STARTING_TIMEOUT_MS = 30_000;
|
||||
|
||||
// Play lifecycle owned by this screen (the server only knows idle/running/completed/failed):
|
||||
// idle → (Play) → starting → (server reports running) → running → (server settles) → idle.
|
||||
type PlayPhase = 'idle' | 'starting' | 'running';
|
||||
|
||||
type Mode =
|
||||
| { kind: 'media'; mediaItemId: number }
|
||||
@@ -41,11 +50,12 @@ function parseMode(search: string): Mode {
|
||||
const hasMedia = Number.isInteger(mediaItemId) && mediaItemId > 0;
|
||||
const hasChannel = Number.isInteger(channelId) && channelId > 0;
|
||||
|
||||
// Exactly one of mediaItem / channel selects the mode; neither (or both) is the empty state.
|
||||
if (hasMedia && !hasChannel) {
|
||||
// mediaItem takes precedence when both are present (matching Blazor's OnParametersSetAsync,
|
||||
// which checks MediaItemId first); neither param is the empty state.
|
||||
if (hasMedia) {
|
||||
return { kind: 'media', mediaItemId };
|
||||
}
|
||||
if (hasChannel && !hasMedia) {
|
||||
if (hasChannel) {
|
||||
return { kind: 'channel', channelId };
|
||||
}
|
||||
return { kind: 'empty' };
|
||||
@@ -128,14 +138,26 @@ export function PlaybackTroubleshootingScreen() {
|
||||
startValue: ''
|
||||
});
|
||||
const [playerSrc, setPlayerSrc] = useState<null | string>(null);
|
||||
// Incremented on every Play so HlsPlayer re-attaches even when the manifest URL is unchanged —
|
||||
// the manifest GET is what starts a session server-side, so a repeat Play with identical settings
|
||||
// must still issue a new request.
|
||||
const [playToken, setPlayToken] = useState(0);
|
||||
const [playbackStatus, setPlaybackStatus] = useState<null | TroubleshootingPlaybackStatus>(null);
|
||||
const [playPhase, setPlayPhase] = useState<PlayPhase>('idle');
|
||||
const [hasPlayed, setHasPlayed] = useState(false);
|
||||
const [notice, setNotice] = useState<null | { tone: 'ok' | 'warn'; message: string }>(null);
|
||||
const [notice, setNotice] = useState<null | { tone: 'error' | 'ok' | 'warn'; message: string }>(null);
|
||||
|
||||
const activeRef = useRef(true);
|
||||
const loadSeqRef = useRef(0);
|
||||
const pollRef = useRef<null | number>(null);
|
||||
const lastStateRef = useRef<null | string>(null);
|
||||
// Mirror of playPhase readable from the polling interval callback without re-creating it.
|
||||
const phaseRef = useRef<PlayPhase>('idle');
|
||||
const startingSinceRef = useRef(0);
|
||||
|
||||
const setPhase = useCallback((phase: PlayPhase) => {
|
||||
phaseRef.current = phase;
|
||||
setPlayPhase(phase);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// popstate is an external event (not an effect body), so resetting to the loading state here is
|
||||
@@ -162,19 +184,39 @@ export function PlaybackTroubleshootingScreen() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Apply a freshly-fetched status: surface a completion notice exactly once on the running→settled
|
||||
// transition, and stop polling once settled.
|
||||
// Apply a freshly-fetched status through the play-phase machine:
|
||||
// - 'starting': ignore settled/idle states entirely — the server hasn't taken the playback lock
|
||||
// yet, so these are the PREVIOUS session's stale result (applying them would show a spurious
|
||||
// completion over a session that is still spinning up). Promote to 'running' once the server
|
||||
// reports it; give up with an error after STARTING_TIMEOUT_MS.
|
||||
// - 'running': apply; surface the completion notice exactly once on the settled transition.
|
||||
const applyStatus = useCallback(
|
||||
(status: TroubleshootingPlaybackStatus) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (phaseRef.current === 'starting') {
|
||||
if (status.state === 'running') {
|
||||
setPhase('running');
|
||||
setPlaybackStatus(status);
|
||||
} else if (Date.now() - startingSinceRef.current > STARTING_TIMEOUT_MS) {
|
||||
setPhase('idle');
|
||||
stopPolling();
|
||||
setNotice({
|
||||
tone: 'error',
|
||||
message: 'Troubleshooting playback did not start within 30 seconds'
|
||||
});
|
||||
}
|
||||
// Otherwise: stale settled/idle result during startup — keep waiting.
|
||||
return;
|
||||
}
|
||||
|
||||
setPlaybackStatus(status);
|
||||
|
||||
const previous = lastStateRef.current;
|
||||
lastStateRef.current = status.state;
|
||||
|
||||
if ((status.state === 'completed' || status.state === 'failed') && previous === 'running') {
|
||||
if (phaseRef.current === 'running' && (status.state === 'completed' || status.state === 'failed')) {
|
||||
setPhase('idle');
|
||||
stopPolling();
|
||||
if (status.exitCode === 0) {
|
||||
setNotice({ tone: 'ok', message: 'FFmpeg troubleshooting process exited successfully' });
|
||||
} else {
|
||||
@@ -184,12 +226,8 @@ export function PlaybackTroubleshootingScreen() {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (status.state !== 'running') {
|
||||
stopPolling();
|
||||
}
|
||||
},
|
||||
[stopPolling]
|
||||
[setPhase, stopPolling]
|
||||
);
|
||||
|
||||
const pollOnce = useCallback(() => {
|
||||
@@ -217,7 +255,9 @@ export function PlaybackTroubleshootingScreen() {
|
||||
getFFmpegProfiles(),
|
||||
getTroubleshootingStreamSelectors(),
|
||||
getWatermarks(),
|
||||
getGraphicsElements()
|
||||
// refresh=true re-syncs on-disk graphics element definitions first, matching Blazor's
|
||||
// RefreshGraphicsElements-before-GetAllGraphicsElements.
|
||||
getGraphicsElements(true)
|
||||
]);
|
||||
|
||||
base
|
||||
@@ -298,15 +338,18 @@ export function PlaybackTroubleshootingScreen() {
|
||||
}, [load]);
|
||||
|
||||
// On mount, reflect any session already running (started here or elsewhere) so Play stays gated.
|
||||
// Intentional side effect: after an app restart the server reports state=idle with the previous
|
||||
// session's logs.txt tail still attached — we apply that status as-is so those logs are
|
||||
// recoverable from the UI (post-restart log recovery), matching what the status endpoint reports.
|
||||
useEffect(() => {
|
||||
getTroubleshootingPlaybackStatus()
|
||||
.then((status) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
lastStateRef.current = status.state;
|
||||
setPlaybackStatus(status);
|
||||
if (status.state === 'running') {
|
||||
setPhase('running');
|
||||
startPolling();
|
||||
}
|
||||
})
|
||||
@@ -316,9 +359,10 @@ export function PlaybackTroubleshootingScreen() {
|
||||
return () => {
|
||||
stopPolling();
|
||||
};
|
||||
}, [startPolling, stopPolling]);
|
||||
}, [setPhase, startPolling, stopPolling]);
|
||||
|
||||
const isRunning = playbackStatus?.state === 'running';
|
||||
// Busy = a session this screen is aware of is starting or transcoding; gates Play + downloads.
|
||||
const isBusy = playPhase !== 'idle';
|
||||
|
||||
// Build the playback.m3u8 query string, mirroring PlaybackTroubleshooting.razor PreviewChannel.
|
||||
const buildPlaybackUrl = useCallback((): null | string => {
|
||||
@@ -367,9 +411,12 @@ export function PlaybackTroubleshootingScreen() {
|
||||
}
|
||||
setNotice(null);
|
||||
setPlaybackStatus((current) => (current ? { ...current, logs: null, speed: null } : current));
|
||||
lastStateRef.current = 'running';
|
||||
setPhase('starting');
|
||||
startingSinceRef.current = Date.now();
|
||||
setHasPlayed(true);
|
||||
setPlayerSrc(url);
|
||||
// Bump the token so HlsPlayer re-attaches even when the URL is identical to the previous play.
|
||||
setPlayToken((current) => current + 1);
|
||||
startPolling();
|
||||
};
|
||||
|
||||
@@ -446,7 +493,7 @@ export function PlaybackTroubleshootingScreen() {
|
||||
];
|
||||
|
||||
const subtitleDisabled = form.streamSelector !== '';
|
||||
const downloadsDisabled = isRunning;
|
||||
const downloadsDisabled = isBusy;
|
||||
const speed = playbackStatus?.speed ?? null;
|
||||
const logs = playbackStatus?.logs ?? null;
|
||||
|
||||
@@ -575,21 +622,21 @@ export function PlaybackTroubleshootingScreen() {
|
||||
|
||||
<Card padded subtitle="Live segmenter output" title="Preview">
|
||||
<Button
|
||||
disabled={isRunning || (isChannelMode && form.startValue === '')}
|
||||
disabled={isBusy || (isChannelMode && form.startValue === '')}
|
||||
onClick={onPlay}
|
||||
startIcon={<PlayCircle aria-hidden="true" size={15} />}
|
||||
variant="primary"
|
||||
>
|
||||
Play
|
||||
</Button>
|
||||
{isRunning && (
|
||||
{isBusy && (
|
||||
<div className="ctv-collections-loading" role="status" style={{ marginTop: 12 }}>
|
||||
<Spinner size={16} />
|
||||
<span>Transcoding…</span>
|
||||
<span>{playPhase === 'starting' ? 'Starting…' : 'Transcoding…'}</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ marginTop: 16, maxWidth: 720 }}>
|
||||
<HlsPlayer src={playerSrc} style={{ aspectRatio: '16 / 9', width: '100%', background: '#000' }} />
|
||||
<HlsPlayer playToken={playToken} src={playerSrc} style={{ aspectRatio: '16 / 9', width: '100%', background: '#000' }} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user