Repository navigation
fix(audiobook): start a fresh session when the server expired the old one #708
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
fa19933
83f4e30
cc600cd
863ad25
37d6d4b
dc1101a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -91,7 +91,18 @@ data class AudiobookPlayerUiState( | |
| val sessionId: String? = null, | ||
| val selectedFileId: Int? = null, | ||
| val error: String? = null, | ||
| ) | ||
| /** The server ended the session (an administrator stopped it), so the | ||
| * player must not start a fresh one on its own. */ | ||
| val sessionEndedByServer: Boolean = false, | ||
| ) { | ||
| /** Playback stopped on an error with no stream left: Play starts it again. */ | ||
| val canRetryPlayback: Boolean | ||
| get() = error != null && | ||
| !sessionEndedByServer && | ||
| streamUrl == null && | ||
| sessionId == null && | ||
| !isLoading | ||
| } | ||
|
|
||
| /** | ||
| * Drives the [AudiobookPlayerScreen]. Wraps Media3 for actual decoding | ||
|
|
@@ -261,68 +272,94 @@ class AudiobookPlayerViewModel( | |
| ) { | ||
| return@collect | ||
| } | ||
| val profileId = profileRepository.getActiveProfileId() ?: return@collect | ||
| val generation = ++loadGeneration | ||
| val trackIndex = activeTrackIndex | ||
| when ( | ||
| val playback = startPartSession( | ||
| fileId = renewal.startParams.fileId, | ||
| profileId = profileId, | ||
| startPosition = renewal.positionSeconds, | ||
| capabilities = renewal.startParams.capabilities, | ||
| clientPlaybackContext = renewal.startParams.clientPlaybackContext, | ||
| ) | ||
| ) { | ||
| is ApiResult.Success -> { | ||
| val start = playback.data | ||
| if (generation != loadGeneration || isClosing) { | ||
| if (start is VideoSessionStartV3.Ready) { | ||
| runCatching { | ||
| playbackSessionManager.stopSession(start.session.sessionId) | ||
| } | ||
| } | ||
| } else if (start is VideoSessionStartV3.Ready) { | ||
| applyStartedSession( | ||
| ready = start, | ||
| localSeek = renewal.positionSeconds, | ||
| globalPosition = state.positionSeconds, | ||
| trackIndex = trackIndex, | ||
| fileId = renewal.startParams.fileId, | ||
| isCurrent = { | ||
| generation == loadGeneration && | ||
| !isClosing && | ||
| _uiState.value.sessionId == renewal.staleSessionId | ||
| }, | ||
| ) | ||
| } else { | ||
| applyFailedSessionStart( | ||
| start.failureMessage(), | ||
| expectedSessionId = renewal.staleSessionId, | ||
| ) | ||
| renewExpiredSession( | ||
| staleSessionId = renewal.staleSessionId, | ||
| fileId = renewal.startParams.fileId, | ||
| localPosition = renewal.positionSeconds, | ||
| globalPosition = state.positionSeconds, | ||
| capabilities = renewal.startParams.capabilities, | ||
| clientPlaybackContext = renewal.startParams.clientPlaybackContext, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Replace [staleSessionId], which the server no longer knows, with a fresh | ||
| * session for [fileId] at the file-local [localPosition]. The stale session | ||
| * stays published until the new one is adopted, so a close or a newer seek | ||
| * in the meantime wins and the late session is released. | ||
| */ | ||
| private suspend fun renewExpiredSession( | ||
| staleSessionId: String, | ||
| fileId: Int, | ||
| localPosition: Double, | ||
| globalPosition: Double, | ||
| capabilities: ClientCodecCapabilities? = null, | ||
| clientPlaybackContext: ClientPlaybackContext? = null, | ||
| ) { | ||
| // A seek, track load or close can land while the profile lookup | ||
| // suspends. Claiming the generation after it would make this renewal | ||
| // current again and replace that newer request with the old position. | ||
| val observedGeneration = loadGeneration | ||
| val profileId = profileRepository.getActiveProfileId() ?: return | ||
| if ( | ||
| observedGeneration != loadGeneration || | ||
| isClosing || | ||
| _uiState.value.sessionId != staleSessionId | ||
| ) { | ||
| return | ||
| } | ||
| val generation = ++loadGeneration | ||
| val trackIndex = activeTrackIndex | ||
| fun isCurrent() = generation == loadGeneration && | ||
| !isClosing && | ||
| _uiState.value.sessionId == staleSessionId | ||
| when ( | ||
| val playback = startPartSession( | ||
| fileId = fileId, | ||
| profileId = profileId, | ||
| startPosition = localPosition, | ||
| capabilities = capabilities, | ||
| clientPlaybackContext = clientPlaybackContext, | ||
| ) | ||
| ) { | ||
| is ApiResult.Success -> { | ||
| val start = playback.data | ||
| if (generation != loadGeneration || isClosing) { | ||
| if (start is VideoSessionStartV3.Ready) { | ||
| runCatching { | ||
| playbackSessionManager.stopSession(start.session.sessionId) | ||
| } | ||
| } | ||
| is ApiResult.Error -> if ( | ||
| generation == loadGeneration && | ||
| !isClosing && | ||
| _uiState.value.sessionId == renewal.staleSessionId | ||
| ) { | ||
| applyFailedSessionStart( | ||
| playback.message, | ||
| expectedSessionId = renewal.staleSessionId, | ||
| ) | ||
| } | ||
| is ApiResult.NetworkError -> if ( | ||
| generation == loadGeneration && | ||
| !isClosing && | ||
| _uiState.value.sessionId == renewal.staleSessionId | ||
| ) { | ||
| applyFailedSessionStart( | ||
| playback.exception.message ?: "Network error", | ||
| expectedSessionId = renewal.staleSessionId, | ||
| ) | ||
| } | ||
| } else if (start is VideoSessionStartV3.Ready) { | ||
| applyStartedSession( | ||
| ready = start, | ||
| localSeek = localPosition, | ||
| globalPosition = globalPosition, | ||
| trackIndex = trackIndex, | ||
| fileId = fileId, | ||
| isCurrent = ::isCurrent, | ||
| ) | ||
| } else { | ||
| applyFailedSessionStart( | ||
| start.failureMessage(), | ||
| expectedSessionId = staleSessionId, | ||
| ) | ||
| } | ||
| } | ||
| is ApiResult.Error -> if (isCurrent()) { | ||
| applyFailedSessionStart( | ||
| playback.message.ifBlank { "Audiobook playback failed" }, | ||
| expectedSessionId = staleSessionId, | ||
| ) | ||
| } | ||
| is ApiResult.NetworkError -> if (isCurrent()) { | ||
| applyFailedSessionStart( | ||
| playback.exception.message ?: "Network error", | ||
| expectedSessionId = staleSessionId, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -670,6 +707,9 @@ class AudiobookPlayerViewModel( | |
| startGlobal: Double, | ||
| generation: Int, | ||
| ) { | ||
| // Publish the start position now, as [loadTrack] does, so a failed | ||
| // start leaves Retry resuming here rather than at 0:00. | ||
| _uiState.update { it.copy(positionSeconds = startGlobal) } | ||
| when (val playback = startPartSession(fileId, profileId, startGlobal)) { | ||
| is ApiResult.Success -> { | ||
| val start = playback.data | ||
|
|
@@ -859,6 +899,7 @@ class AudiobookPlayerViewModel( | |
| selectedFileId = fileId, | ||
| positionSeconds = globalPosition, | ||
| error = null, | ||
| sessionEndedByServer = false, | ||
| ) | ||
| } | ||
| published = true | ||
|
|
@@ -897,6 +938,7 @@ class AudiobookPlayerViewModel( | |
| private fun applyFailedSessionStart( | ||
| failureMessage: String, | ||
| expectedSessionId: String? = _uiState.value.sessionId, | ||
| sessionEndedByServer: Boolean = false, | ||
| ) { | ||
| val state = _uiState.value | ||
| if (expectedSessionId != null && state.sessionId != expectedSessionId) return | ||
|
|
@@ -921,6 +963,7 @@ class AudiobookPlayerViewModel( | |
| isPlaying = false, | ||
| isPaused = true, | ||
| error = failureMessage, | ||
| sessionEndedByServer = sessionEndedByServer, | ||
| ) | ||
| } | ||
| } | ||
|
|
@@ -1035,6 +1078,10 @@ class AudiobookPlayerViewModel( | |
| * whole-book and this is the pre-timeline behaviour. | ||
| */ | ||
| fun onPositionChanged(seconds: Double, streamUri: String?) { | ||
| // No stream published (before the first start, or after a failure | ||
| // cleared it): the engine is empty or still holds the outgoing item, so | ||
| // its time would overwrite the position Retry resumes from. | ||
| if (_uiState.value.streamUrl == null) return | ||
| val tl = timeline | ||
| val active = activeTrackIndex?.let { idx -> tl?.tracks?.firstOrNull { it.index == idx } } | ||
|
|
||
|
|
@@ -1166,10 +1213,20 @@ class AudiobookPlayerViewModel( | |
| !isClosing && | ||
| _uiState.value.sessionId == sessionId | ||
| ) { | ||
| applyFailedSessionStart( | ||
| result.message.ifBlank { "Audiobook playback failed" }, | ||
| expectedSessionId = sessionId, | ||
| ) | ||
| when (val recovery = audiobookReplanRecovery(result)) { | ||
| AudiobookReplanRecovery.StartFreshSession -> renewExpiredSession( | ||
| staleSessionId = sessionId, | ||
| fileId = fileId, | ||
| localPosition = sourcePosition, | ||
| globalPosition = globalPosition, | ||
| ) | ||
| AudiobookReplanRecovery.Ended, | ||
| AudiobookReplanRecovery.Fail -> applyFailedSessionStart( | ||
|
Quick104 marked this conversation as resolved.
Resolved
|
||
| result.message.ifBlank { "Audiobook playback failed" }, | ||
| expectedSessionId = sessionId, | ||
| sessionEndedByServer = recovery == AudiobookReplanRecovery.Ended, | ||
| ) | ||
| } | ||
| } | ||
| is ApiResult.NetworkError -> if ( | ||
| generation == loadGeneration && | ||
|
|
@@ -1186,9 +1243,49 @@ class AudiobookPlayerViewModel( | |
| } | ||
|
|
||
| fun togglePlay() { | ||
| if (_uiState.value.canRetryPlayback) { | ||
| retryPlayback() | ||
| return | ||
| } | ||
| _uiState.update { it.copy(isPaused = !it.isPaused) } | ||
| } | ||
|
|
||
| /** | ||
| * Start playback again after it stopped on an error, at the position the | ||
| * player last held. Used once the server is reachable again after an | ||
| * outage that outlived the session, or after any other failed start. | ||
| */ | ||
| fun retryPlayback() { | ||
| val state = _uiState.value | ||
| if (isClosing || !state.canRetryPlayback || contentId.isBlank()) return | ||
| val fileId = state.selectedFileId | ||
| if (fileId == null) { | ||
| // The item never loaded: load it from the start. | ||
| _uiState.update { it.copy(isLoading = true, error = null) } | ||
| loadDetail() | ||
| return | ||
| } | ||
| _uiState.update { it.copy(error = null, isPaused = false) } | ||
| if (timeline != null) { | ||
| loadTrack(atGlobalTime = state.positionSeconds, autoplay = true) | ||
| return | ||
| } | ||
| val generation = ++startGeneration | ||
| viewModelScope.launch { | ||
| val profileId = profileRepository.getActiveProfileId() | ||
| if (profileId == null) { | ||
| _uiState.update { it.copy(error = "No active profile") } | ||
| return@launch | ||
| } | ||
| startSingleFileSession( | ||
| fileId = fileId, | ||
| profileId = profileId, | ||
| startGlobal = state.positionSeconds, | ||
| generation = generation, | ||
|
Comment on lines
+1280
to
+1284
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Resume offset loss occurs when the initial single-file session start fails: loadDetail resolves startGlobal, but neither loadDetail nor the failed start publishes it to uiState.positionSeconds before Retry reads state.positionSeconds, causing a book opened at a saved or explicitly requested nonzero position to restart at 0:00. Retain the attempted start position on failure and use it for the next startSingleFileSession call. Prompt for LLMTalk to Kody by mentioning @kody Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 37d6d4b: the single-file start publishes its start position before the request, and position polls are ignored while no stream is published, so Retry resumes at the saved position instead of 0:00. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for fixing this in |
||
| ) | ||
| } | ||
| } | ||
|
|
||
| /** Audiobook-style ±30s seek. The Compose layer reads the requested | ||
| * position from [pendingSeekToSeconds] and clears the marker once it | ||
| * applies the seek to the underlying Media3 controller. */ | ||
|
|
@@ -1220,6 +1317,9 @@ class AudiobookPlayerViewModel( | |
| fileId = _uiState.value.selectedFileId ?: return, | ||
| ) | ||
| } else { | ||
| // Polls are ignored while no stream is published, so record a | ||
| // seek made in the error state here for Retry to resume from. | ||
| _uiState.update { it.copy(positionSeconds = target) } | ||
| _pendingSeek.value = target | ||
| } | ||
| return | ||
|
|
@@ -1302,7 +1402,17 @@ class AudiobookPlayerViewModel( | |
| !isClosing && | ||
| _uiState.value.sessionId == sessionId | ||
| ) { | ||
| _uiState.update { it.copy(error = result.message.ifBlank { "Seek failed" }) } | ||
| when (audiobookReplanRecovery(result)) { | ||
| AudiobookReplanRecovery.StartFreshSession -> renewExpiredSession( | ||
| staleSessionId = sessionId, | ||
| fileId = fileId, | ||
| localPosition = decision.targetSourcePositionSeconds, | ||
| globalPosition = globalSeconds, | ||
| ) | ||
| AudiobookReplanRecovery.Ended, | ||
| AudiobookReplanRecovery.Fail -> | ||
| _uiState.update { it.copy(error = result.message.ifBlank { "Seek failed" }) } | ||
|
Comment on lines
+1412
to
+1414
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Incomplete session cleanup in the seek-reanchor Ended branch only sets error after a 410 playback_session_ended response, leaving sessionEndedByServer false and retaining the stream, session, and unpaused state so buffered audio can continue after the administrator's stop. Handle Ended separately with applyFailedSessionStart(message, expectedSessionId = sessionId, sessionEndedByServer = true), as onPlayerError does. AudiobookReplanRecovery.Ended -> applyFailedSessionStart(
result.message.ifBlank { "Seek failed" },
expectedSessionId = sessionId,
sessionEndedByServer = true,
)
AudiobookReplanRecovery.Fail ->
_uiState.update { it.copy(error = result.message.ifBlank { "Seek failed" }) }Prompt for LLMTalk to Kody by mentioning @kody Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction. |
||
| } | ||
| } | ||
| is ApiResult.NetworkError -> if ( | ||
| generation == loadGeneration && | ||
|
|
@@ -1777,3 +1887,20 @@ private fun androidx.media3.common.PlaybackException.audiobookFailureClassificat | |
| androidx.media3.common.PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND -> "source_unavailable" | ||
| else -> "player_error" | ||
| } | ||
|
|
||
| /** What the audiobook player does after a replan or reanchor request failed. */ | ||
| internal enum class AudiobookReplanRecovery { StartFreshSession, Ended, Fail } | ||
|
|
||
| /** | ||
| * A replan or reanchor names the session it replaces. Once the server has | ||
| * expired that session (the player was cut off past the server's grace), it | ||
| * answers 404 "Playback session not found" and no replan can succeed; the | ||
| * only way back is a fresh session at the same position. A session an | ||
| * administrator ended answers 410 `playback_session_ended` instead, and the | ||
| * player must not start a fresh one, not even from Retry. | ||
| */ | ||
| internal fun audiobookReplanRecovery(result: ApiResult<*>): AudiobookReplanRecovery = when { | ||
| result.isPlaybackSessionMissingError() -> AudiobookReplanRecovery.StartFreshSession | ||
| result.isPlaybackSessionEnded() -> AudiobookReplanRecovery.Ended | ||
| else -> AudiobookReplanRecovery.Fail | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package org.siloserver.silo.common.player | ||
|
|
||
| import java.io.IOException | ||
| import org.siloserver.silo.network.ApiResult | ||
| import kotlin.test.Test | ||
| import kotlin.test.assertEquals | ||
|
|
||
| class AudiobookReplanRecoveryTest { | ||
| @Test | ||
| fun onlyAnExpiredSessionStartsAFreshOne() { | ||
| val cases = listOf( | ||
| // What the v2 replan answers once the server reaped the session: | ||
| // the not_found problem with the session detail. | ||
| ApiResult.Error(404, "not_found", "Playback session not found") | ||
| to AudiobookReplanRecovery.StartFreshSession, | ||
| // The v1 code for the same condition. | ||
| ApiResult.Error(404, "playback_session_not_found", "Playback session not found") | ||
| to AudiobookReplanRecovery.StartFreshSession, | ||
| // An administrator ended the session: renewing, or offering Retry, | ||
| // would undo that. | ||
| ApiResult.Error(410, "playback_session_ended", "An administrator ended this playback session") | ||
| to AudiobookReplanRecovery.Ended, | ||
| // Other 404s say nothing about the session. | ||
| ApiResult.Error(404, "not_found", "Source media file is missing") | ||
| to AudiobookReplanRecovery.Fail, | ||
| ApiResult.Error(503, "dependency_unavailable", "Playback is temporarily unavailable.") | ||
| to AudiobookReplanRecovery.Fail, | ||
| ApiResult.NetworkError(IOException("connection refused")) | ||
| to AudiobookReplanRecovery.Fail, | ||
| ) | ||
| for ((result, expected) in cases) { | ||
| assertEquals(expected, audiobookReplanRecovery(result), "for $result") | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Race condition identified in session renewal: a newer seek or track load can advance loadGeneration while profileRepository.getActiveProfileId() suspends, and the subsequent increment makes the obsolete renewal current again, allowing its old position to replace newer playback intent. Capture loadGeneration before the lookup and afterward reject renewal if the generation changed, isClosing is true, or _uiState.value.sessionId no longer matches staleSessionId.
Also found in:
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt:1247-1247Kody rule violation: Revalidate asynchronous ownership before publication, launch, and cleanup
Prompt for LLM
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 37d6d4b: the renewal records the load generation before the profile lookup and stops if it changed, the player is closing, or the session ID changed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks—the guard described in
37d6d4b42addresses this race by rejecting an obsolete renewal after the profile lookup, before it can advanceloadGenerationand override newer playback intent.I haven’t independently verified the commit, but the described fix matches the suggestion.