Fix a sync issue after reconnecting

This commit is contained in:
Brahim Hadriche committed 2026-10-13 21:37:48 -04:00
1 parent 029582817f
commit 8c22152d8e
4 files changed
+108 -34

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- SponsorBlock skip looping back to the start of a segment on some devices, and overlapping segments
- Live streams buffering on slow networks
- Playback errors with a preferred quality set, on some devices
- Lounge (cast from phone) fix a sync issue after reconnecting
### Changed
@@ -34,11 +34,15 @@ class LoungeApi
public sessionId
public gSessionId
public devices
' Set by a send's failure, until the next bind.
public sessionGone = false
public tokenExpired = false
private ofs
private lastProcessedCommandIndex = -1
private backchannel
private pendingOutgoingMessages
private lastLoungeDisconnect
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object)
m.loungeServiceNode = loungeServiceNode
@@ -216,8 +220,11 @@ class LoungeApi
body.FromAsciiString(response.Text())
' A new session restarts command indices from 0; clear the high-water mark so its commands
' aren't skipped as duplicates.
' aren't skipped as duplicates. Its outbound offset restarts from 0 too.
m.lastProcessedCommandIndex = -1
m.ofs = 0
m.sessionGone = false
m.tokenExpired = false
messagesToSend = []
result = LoungeFraming.Extract(body, 0)
for each frame in result.frames
@@ -287,6 +294,31 @@ class LoungeApi
return m.GetToken()
end function
function Bind() as boolean
if not m.GetSessionData()
return false
end if
m.SaveCurrentLoungeData()
return true
end function
function Rebind(withNewToken as boolean) as boolean
for each pending in m.pendingOutgoingMessages
pending.Cancel()
end for
m.pendingOutgoingMessages = []
if withNewToken
LogWarnNoTelemetry("Lounge token expired, refreshing")
if StringUtils.IsNullOrEmpty(m.RefreshToken())
return false
end if
end if
LogWarnNoTelemetry("Rebinding lounge session")
return m.Bind()
end function
function ProcessFrame(frame as string, messagesToSend as object) as void
commands = StringUtils.ParseJsonSafe(frame)
if not IsArray(commands)
@@ -545,11 +577,14 @@ class LoungeApi
messagesToSend.Push(message)
end function
function SendMessages(messages as object, loungeData = invalid as object) as void
function SendMessages(messages as object) as void
if messages.Count() = 0
return
end if
m.pendingOutgoingMessages.Push(m.SendMessagesTo(m, messages))
end function
private function SendMessagesTo(loungeData as object, messages as object) as HttpClient.PendingResponse
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
@@ -562,10 +597,6 @@ class LoungeApi
"RID": "1337"
}
if loungeData = invalid
loungeData = m
end if
queryParams["name"] = loungeData.screenName
queryParams["id"] = loungeData.deviceId
queryParams["loungeIdToken"] = loungeData.loungeToken
@@ -602,7 +633,11 @@ class LoungeApi
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
request.FormBody(postData)
m.pendingOutgoingMessages.Push(request.Send())
return request.Send()
end function
function HasPendingOutgoingMessages() as boolean
return m.pendingOutgoingMessages.Count() > 0
end function
function ProcessPendingOutgoingMessages() as object
@@ -626,6 +661,11 @@ class LoungeApi
unknownSid = response.StatusCode() = 400 and response.ErrorMessage().InStr("Unknown SID") <> -1
expiredToken = response.StatusCode() = 401 and response.ErrorMessage().InStr("Expired lounge id token") <> -1
isKnownError = isGone or unknownSid or expiredToken
if isGone or unknownSid
m.sessionGone = true
else if expiredToken
m.tokenExpired = true
end if
if isKnownError
' NoTelemetry: the body carries a volatile token; logging it would fragment these.
@@ -709,7 +749,8 @@ class LoungeApi
' we didn't keep track of the ofs, so we'll just set it to a large number.
' This is the last message we'll be sending to this lounge.
loungeData.ofs = 99999999
m.SendMessages(messages, loungeData)
' Held: dropping it releases its transfer, which aborts the send.
m.lastLoungeDisconnect = m.SendMessagesTo(loungeData, messages)
end function
end class
@@ -1,6 +1,9 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
const IDLE_WAIT_MS = 60000
const SENDS_IN_FLIGHT_WAIT_MS = 500
function Init()
m.top.functionName = "LoungeServiceLoop"
@@ -63,12 +66,11 @@ function LoungeServiceLoop() as void
m.top.observeField("outgoingMessages", messagePort)
if not api.GetSessionData()
Shutdown("Failed to get session data")
if not api.Bind()
Shutdown("Failed to bind")
return
end if
api.SaveCurrentLoungeData()
api.FetchCommandsRpc(messagePort)
m.top.shouldQuit = false
@@ -83,7 +85,12 @@ function LoungeServiceLoop() as void
exit while
end if
message = wait(60000, messagePort)
' Sends answer on ports of their own, read only when the loop wakes.
waitMs = IDLE_WAIT_MS
if api.HasPendingOutgoingMessages()
waitMs = SENDS_IN_FLIGHT_WAIT_MS
end if
message = wait(waitMs, messagePort)
portMessages.Clear()
portMessages.Push(message)
@@ -117,20 +124,13 @@ function LoungeServiceLoop() as void
isOpen = api.Poll(socketMessages, outgoingLoungeMessages)
api.SendMessages(outgoingLoungeMessages)
outgoingLoungeMessagesResults = api.ProcessPendingOutgoingMessages()
api.ProcessPendingOutgoingMessages()
' A send's failure is acted on once the backchannel closes, which a dead session's does too.
if not isOpen
closeInfo = api.GetCloseInfo()
needsRebind = closeInfo.statusCode = 410 or closeInfo.statusCode = 400
needsTokenRefresh = closeInfo.statusCode = 401
for each result in outgoingLoungeMessagesResults
if result.status = 410 or (result.status = 400 and result.error.InStr("Unknown SID") <> -1)
needsRebind = true
else if result.status = 401 and result.error.InStr("Expired lounge id token") <> -1
needsTokenRefresh = true
end if
end for
needsRebind = closeInfo.statusCode = 410 or closeInfo.statusCode = 400 or api.sessionGone
needsTokenRefresh = closeInfo.statusCode = 401 or api.tokenExpired
LogDebug("Backchannel closed:", closeInfo.reason)
if IsActionableCloseFailure(closeInfo.reason, needsRebind, needsTokenRefresh)
@@ -148,19 +148,12 @@ function LoungeServiceLoop() as void
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if needsTokenRefresh
LogWarnNoTelemetry("Lounge token expired, refreshing")
api.RefreshToken()
needsRebind = true
end if
if needsRebind
LogWarnNoTelemetry("Rejoining lounge session")
if not api.GetSessionData()
Shutdown("Failed to rejoin session data")
if needsRebind or needsTokenRefresh
if not api.Rebind(needsTokenRefresh)
Shutdown("Failed to rebind")
return
end if
api.SaveCurrentLoungeData()
m.top.loungeToken = api.loungeToken
end if
api.FetchCommandsRpc(messagePort)
@@ -1,5 +1,6 @@
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Tests
@@ -10,10 +11,17 @@ namespace Tests
protected override function setup()
m.logLevel = Tests.MuteLogger()
' Rebind saves the test lounge as the last one, which the next app launch disconnects from.
m.lastLoungeData = RegistryUtils.Read(RegistryUtils.LAST_LOUNGE_DATA)
end function
protected override function tearDown()
m.global.logger.logLevel = m.logLevel
if m.lastLoungeData = invalid
RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA)
else
RegistryUtils.Write(RegistryUtils.LAST_LOUNGE_DATA, m.lastLoungeData)
end if
end function
@describe("Lounge token-refresh recovery (live)")
@@ -62,6 +70,37 @@ namespace Tests
end for
end function
@slow(30000)
@it("Rebind cancels the replaced session's sends, and the new session's sends complete")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
m.assertTrue(api.HasPendingOutgoingMessages(), "the bind sent no messages")
replacedSends = []
replacedSends.Append(api.pendingOutgoingMessages)
m.assertTrue(api.Rebind(true), "rebind failed")
m.assertNotEmpty(replacedSends)
for each pending in replacedSends
m.assertTrue(pending.Poll().IsCancelled(), "a send of the replaced session was not cancelled")
end for
results = []
timer = CreateObject("roTimespan")
while api.HasPendingOutgoingMessages() and timer.TotalMilliseconds() < 10000
results.Append(api.ProcessPendingOutgoingMessages())
sleep(50)
end while
m.assertFalse(api.HasPendingOutgoingMessages(), "the new session's sends did not complete")
m.assertNotEmpty(results, "the rebind sent no messages")
for each result in results
m.assertEqual(result.status, 200, result.error)
end for
end function
private function CreateLiveApi() as object
loungeServiceNode = CreateObject("roSGNode", "Node")
loungeServiceNode.addFields({