Skip to content

Commit 136ec5d

Browse files
authored
Merge pull request #13 from TypeType-Video/fix/sabr-token-renewal
fix: wait for a token session renewal before giving up a resume
2 parents fce661a + 149b807 commit 136ec5d

3 files changed

Lines changed: 51 additions & 3 deletions

File tree

‎core/data/src/main/java/video/typetype/tv/data/dto/SabrDto.kt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,5 @@ data class SabrWindowDto(
7878
val terminalError: String? = null,
7979
val recoveryAction: String? = null,
8080
val retryVideoItags: List<Int> = emptyList(),
81+
val blockedBy: String? = null,
8182
)

‎core/playback/src/main/java/video/typetype/tv/playback/SabrWindowLoader.kt‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,12 @@ class SabrWindowLoader(
2727
private val scope: CoroutineScope,
2828
private val maxPolls: Int = MAX_POLLS,
2929
private val windowDeadlineMillis: Long = WINDOW_DEADLINE_MILLIS,
30+
private val tokenRenewalWaitMillis: Long = TOKEN_RENEWAL_WAIT_MILLIS,
3031
) : PlaybackWindowLoader {
3132

33+
@Volatile
34+
private var renewingToken = false
35+
3236
suspend fun firstWindow(positionMs: Long): PlaybackWindow = awaitWindow { WindowPosition(positionMs, emptyList()) }
3337

3438
override fun load(
@@ -75,14 +79,27 @@ class SabrWindowLoader(
7579
// A stuck session is replaced in place once, as the Android app does, so the player keeps its buffer instead of
7680
// being rebuilt; only a second stall is reported.
7781
private suspend fun awaitWindow(position: () -> WindowPosition): PlaybackWindow {
78-
withTimeoutOrNull(windowDeadlineMillis) { pollWindow(position) }?.let { return it }
82+
pollWithinDeadline(position)?.let { return it }
7983
if (session.canRecover()) {
8084
createFreshSession(position().positionMs)
81-
withTimeoutOrNull(windowDeadlineMillis) { pollWindow(position) }?.let { return it }
85+
pollWithinDeadline(position)?.let { return it }
8286
}
8387
throw ApiException(ApiFailure(FailureCategory.Network, null, "sabr_timeout", "The video did not become ready", null))
8488
}
8589

90+
// When YouTube asks a resumed session to attest, the server replaces its token session before telling the
91+
// player to start a fresh one; a fresh session opened sooner would get the refused token again. That wait,
92+
// reported as a blocker, does not count against the deadline, up to a bound of its own.
93+
private suspend fun pollWithinDeadline(position: () -> WindowPosition): PlaybackWindow? {
94+
val started = System.nanoTime()
95+
while (true) {
96+
renewingToken = false
97+
withTimeoutOrNull(windowDeadlineMillis) { pollWindow(position) }?.let { return it }
98+
val waitedMs = (System.nanoTime() - started) / NANOS_PER_MILLI
99+
if (!renewingToken || waitedMs >= tokenRenewalWaitMillis) return null
100+
}
101+
}
102+
86103
// The server starts fetching on prefetch; asking again while it is already filling makes it reposition and
87104
// restart, so prefetch is sent once per wait and repeated only when the server reports it went idle.
88105
private suspend fun pollWindow(position: () -> WindowPosition): PlaybackWindow? {
@@ -102,6 +119,7 @@ class SabrWindowLoader(
102119
}
103120
val window = api.segments(session.sessionId, body)
104121
if (window.ready) return mapper.map(window, session)
122+
renewingToken = window.blockedBy == TOKEN_SESSION_RENEWAL
105123
if (recover(window, positionMs)) {
106124
reported = false
107125
requested = false
@@ -120,7 +138,8 @@ class SabrWindowLoader(
120138
}
121139

122140
private suspend fun recover(window: SabrWindowDto, positionMs: Long): Boolean {
123-
if (window.terminalError != null && window.recoveryAction == null) {
141+
val spent = window.recoveryAction == RETRY_FRESH_SESSION && !session.canRecover()
142+
if (window.terminalError != null && (window.recoveryAction == null || spent)) {
124143
throw ApiException(ApiFailure(FailureCategory.Server, null, window.terminalError, "Playback failed on the server", null))
125144
}
126145
if (window.recoveryAction == RETRY_FRESH_SESSION && session.canRecover()) {
@@ -169,6 +188,9 @@ class SabrWindowLoader(
169188
const val MIN_RETRY_MS = 150L
170189
const val MAX_RETRY_MS = 2_000L
171190
const val RETRY_FRESH_SESSION = "retry_fresh_session"
191+
const val TOKEN_SESSION_RENEWAL = "token_session_renewal"
192+
const val TOKEN_RENEWAL_WAIT_MILLIS = 60_000L
193+
const val NANOS_PER_MILLI = 1_000_000L
172194
const val IDLE = "idle"
173195
}
174196
}

‎core/playback/src/test/java/video/typetype/tv/playback/SabrWindowLoaderTest.kt‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,31 @@ class SabrWindowLoaderTest {
148148
assertEquals("fresh", session.sessionId)
149149
}
150150

151+
@Test
152+
fun aFreshSessionTheClientCanNoLongerOpenIsReportedAtOnce() {
153+
val attestation = """{"ready":false,"terminalError":"SABR attestation required","recoveryAction":"retry_fresh_session"}"""
154+
responses += { _ -> MockResponse().setResponseCode(202).setBody(attestation) }
155+
val session = newSession().apply { repeat(2) { adopt(SabrSessionDto(sessionId = "s$it", generation = 1), replacement = true) } }
156+
try {
157+
runBlocking { loader(session, polls = 40).firstWindow(69_343) }
158+
fail("expected a failure")
159+
} catch (error: ApiException) {
160+
assertEquals("SABR attestation required", error.failure.code)
161+
}
162+
assertEquals(1, segmentsPaths.size)
163+
}
164+
165+
@Test
166+
fun aTokenSessionRenewalIsAwaitedPastTheDeadline() = runBlocking {
167+
val renewing = """{"ready":false,"status":"terminal","retryAfterMs":150,"blockedBy":"token_session_renewal"}"""
168+
repeat(6) { responses += { _ -> MockResponse().setResponseCode(202).setBody(renewing) } }
169+
responses += { _ -> MockResponse().setResponseCode(200).setBody(ready("s1", 1)) }
170+
val session = newSession()
171+
val window = loader(session, polls = 40, deadlineMillis = 400).firstWindow(69_343)
172+
assertEquals("s1", session.sessionId)
173+
assertEquals(1L, window.generation)
174+
}
175+
151176
@Test
152177
fun aWindowThatNeverBecomesReadyTimesOut() {
153178
repeat(10) { responses += { _ -> MockResponse().setResponseCode(202).setBody("""{"ready":false,"retryAfterMs":150}""") } }

0 commit comments

Comments
 (0)