Lounge: use buffered mode, restore https connection

This commit is contained in:
Brahim Hadriche committed 2026-10-15 15:55:39 -04:00
1 parent b7fb8614b7
commit 99fdd31c36
22 files changed
+956 -1269

No files matched your search

@@ -1,271 +0,0 @@
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/source/utils/ByteArrayUtils.bs"
enum HttpDecoderState
Head
ChunkSize
ChunkData
Done
Redirect
Error
end enum
enum HttpDecoderError
None = ""
MalformedStatus = "malformed_status"
UnsupportedEncoding = "unsupported_encoding"
ChunkOverflow = "chunk_overflow"
ShortRead = "short_read"
end enum
const HTTP_DECODER_COMPACT_THRESHOLD = 32768
const HTTP_DECODER_READ_LENGTH = 65536
class HttpChunkedDecoder
public statusCode = 0
public statusText = ""
public errorReason = HttpDecoderError.None
public headers
private buffer
private cursor = 0
private state = HttpDecoderState.Head
private chunkRemaining = 0
private headCheckedSize = 0
function new()
m.buffer = CreateObject("roByteArray")
m.headers = {}
end function
function Pump(socket as object, output as object) as integer
received = m.ReceiveFrom(socket)
if received > 0
m.Process(output)
end if
return received
end function
function IsDone() as boolean
return m.state = HttpDecoderState.Done
end function
function IsError() as boolean
return m.state = HttpDecoderState.Error
end function
function IsRedirect() as boolean
return m.state = HttpDecoderState.Redirect
end function
function Location() as dynamic
return m.headers["location"]
end function
private function ReceiveFrom(socket as object) as integer
available = socket.GetCountRcvBuf()
if available <= 0
return 0
end if
lengthToRead = available
if lengthToRead > HTTP_DECODER_READ_LENGTH
lengthToRead = HTTP_DECODER_READ_LENGTH
end if
writeIndex = m.buffer.Count()
m.buffer[writeIndex + lengthToRead - 1] = 0
received = socket.Receive(m.buffer, writeIndex, lengthToRead)
if received > 0 and received < lengthToRead
' GetCountRcvBuf reported more than Receive delivered, leaving uninitialised slack.
m.errorReason = HttpDecoderError.ShortRead
m.state = HttpDecoderState.Error
end if
return received
end function
private function Process(output as object) as void
running = true
while running
if m.state = HttpDecoderState.Head
running = m.ParseHead()
else if m.state = HttpDecoderState.ChunkSize
running = m.ParseChunkSize()
else if m.state = HttpDecoderState.ChunkData
running = m.ParseChunkData(output)
else
running = false
end if
end while
m.Compact()
end function
' Status line and headers are ASCII, so they parse as a string; the chunk body that follows is
' not, so it stays in bytes.
private function ParseHead() as boolean
bufferSize = m.buffer.Count()
if bufferSize = m.headCheckedSize
return false
end if
head = m.buffer.ToAsciiString()
delimiter = head.InStr(`\r\n\r\n`)
if delimiter = -1
m.headCheckedSize = bufferSize
return false
end if
contentStart = delimiter + 4
if m.buffer[contentStart - 4] <> 13 or m.buffer[contentStart - 3] <> 10 or m.buffer[contentStart - 2] <> 13 or m.buffer[contentStart - 1] <> 10
m.statusText = "Invalid header delimiter - is there unicode text in headers?"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
lines = head.Left(delimiter).Split(`\r\n`)
if not m.ParseStatusLine(lines[0])
return false
end if
for i = 1 to lines.Count() - 1
m.ParseHeaderLine(lines[i])
end for
m.cursor = contentStart
return m.FinishHead()
end function
private function ParseStatusLine(line as string) as boolean
if not line.StartsWith("HTTP/1.1 ") and not line.StartsWith("HTTP/1.0 ")
m.statusText = "Malformed status line"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
rest = line.Mid(9).Trim()
spaceIndex = rest.InStr(" ")
if spaceIndex = -1
m.statusCode = Int(Val(rest, 10))
m.statusText = ""
else
m.statusCode = Int(Val(rest.Left(spaceIndex), 10))
m.statusText = rest.Mid(spaceIndex + 1)
end if
return true
end function
private function ParseHeaderLine(line as string) as void
colon = line.InStr(":")
if colon > 0
key = LCase(line.Left(colon).Trim())
m.headers[key] = line.Mid(colon + 1).Trim()
end if
end function
private function FinishHead() as boolean
if m.IsRedirectStatus(m.statusCode)
m.state = HttpDecoderState.Redirect
return false
end if
if m.statusCode <> 200
m.state = HttpDecoderState.Error
return false
end if
transferEncoding = m.headers["transfer-encoding"]
if transferEncoding = invalid or LCase(transferEncoding).InStr("chunked") = -1
m.statusText = "Unsupported transfer-encoding"
m.errorReason = HttpDecoderError.UnsupportedEncoding
m.state = HttpDecoderState.Error
return false
end if
m.state = HttpDecoderState.ChunkSize
return true
end function
private function IsRedirectStatus(code as integer) as boolean
return code = 301 or code = 302 or code = 303 or code = 307 or code = 308
end function
private function ParseChunkSize() as boolean
' Skip the CRLF trailing the previous chunk's data (and any stray newlines).
while m.cursor < m.buffer.Count() and (m.buffer[m.cursor] = 13 or m.buffer[m.cursor] = 10)
m.cursor += 1
end while
crlf = LoungeBytes.IndexOfCrlf(m.buffer, m.cursor)
if crlf = -1
return false
end if
sizeLine = LoungeBytes.RangeToString(m.buffer, m.cursor, crlf)
m.cursor = crlf + 2
' A chunk-size line may carry ';ext' extensions; the size is the leading hex token.
semicolon = sizeLine.InStr(";")
if semicolon > 0
sizeLine = sizeLine.Left(semicolon)
end if
m.chunkRemaining = Int(Val(sizeLine.Trim(), 16))
if m.chunkRemaining < 0
' A size that doesn't fit a 32-bit int is a corrupt size line or a parse desync.
m.errorReason = HttpDecoderError.ChunkOverflow
m.state = HttpDecoderState.Error
return false
end if
if m.chunkRemaining = 0
m.state = HttpDecoderState.Done
return false
end if
m.state = HttpDecoderState.ChunkData
return true
end function
private function ParseChunkData(output as object) as boolean
available = m.buffer.Count() - m.cursor
if available <= 0
return false
end if
take = available
if take > m.chunkRemaining
take = m.chunkRemaining
end if
chunk = ByteArrayUtils.Slice(m.buffer, m.cursor, m.cursor + take)
output.Append(chunk)
m.cursor += take
m.chunkRemaining -= take
if m.chunkRemaining = 0
m.state = HttpDecoderState.ChunkSize
return true
end if
return false
end function
' A fully consumed buffer Clears for free; a partial one waits until the dead prefix is worth a slice.
private function Compact() as void
if m.cursor = 0
return
end if
if m.cursor >= m.buffer.Count()
m.buffer.Clear()
else if m.cursor >= HTTP_DECODER_COMPACT_THRESHOLD
m.buffer = LoungeBytes.Tail(m.buffer, m.cursor)
else
return
end if
m.cursor = 0
m.headCheckedSize = 0
end function
end class
@@ -1,8 +1,6 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs" import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeConstants.bs" import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/components/Services/LoungeService/LoungeMessages.bs" import "pkg:/components/Services/LoungeService/LoungeMessages.bs"
import "pkg:/components/Services/LoungeService/LoungeVideoQueue.bs" import "pkg:/components/Services/LoungeService/LoungeVideoQueue.bs"
import "pkg:/components/Services/LoungeService/Notifications/DeviceConnectedNotificationUtils.bs" import "pkg:/components/Services/LoungeService/Notifications/DeviceConnectedNotificationUtils.bs"
@@ -10,7 +8,7 @@ import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs" import "pkg:/source/utils/Types.bs"
const COMMAND_HANDLER_PREFIX = "_Handle_" const COMMAND_HANDLER_PREFIX = "_Handle_"
@@ -37,14 +35,14 @@ class LoungeApi
' Set by a send's failure, until the next bind. ' Set by a send's failure, until the next bind.
public sessionGone = false public sessionGone = false
public tokenExpired = false public tokenExpired = false
public backchannel as LoungeBackchannel
private ofs private ofs
private lastProcessedCommandIndex = -1 private messagePort
private backchannel
private pendingOutgoingMessages private pendingOutgoingMessages
private lastLoungeDisconnect private lastLoungeDisconnect
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object) function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object, messagePort as object)
m.loungeServiceNode = loungeServiceNode m.loungeServiceNode = loungeServiceNode
m.videoQueueNode = videoQueueNode m.videoQueueNode = videoQueueNode
m.notificationsNode = notificationsNode m.notificationsNode = notificationsNode
@@ -55,7 +53,8 @@ class LoungeApi
m.deviceName = deviceName m.deviceName = deviceName
m.screenName = deviceName m.screenName = deviceName
m.ofs = 0 m.ofs = 0
m.backchannel = invalid m.messagePort = messagePort
m.backchannel = new LoungeBackchannel()
m.pendingOutgoingMessages = [] m.pendingOutgoingMessages = []
m.devices = {} m.devices = {}
@@ -119,23 +118,13 @@ class LoungeApi
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n${response.ErrorMessage()}` LogError(`Failed to get lounge screen ID\n${response.ErrorMessage()}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
return invalid return invalid
end if end if
id = response.Text() id = response.Text()
if not IsString(id) if StringUtils.IsNullOrEmpty(id)
error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n` = Tr(Locale.Dialogs.LoungeNotAValidScreenId).Replace("%1", `${id}`) LogError("Failed to get lounge screen ID: empty response")
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
return invalid return invalid
end if end if
@@ -155,24 +144,14 @@ class LoungeApi
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n${response.ErrorMessage()}` LogError(`Failed to get lounge token\n${response.ErrorMessage()}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
return invalid return invalid
end if end if
json = response.Json() json = response.Json()
screens = json.screens screens = ValidAssociativeArray(json).screens
if not IsArray(screens) or screens.Count() <> 1 if not IsArray(screens) or screens.Count() <> 1
error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n` + Tr(Locale.Dialogs.LoungeInvalidResponse).Replace("%1", `${json}`) LogError(`Failed to get lounge token: invalid response\nBody: ${response.Text()}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
return invalid return invalid
end if end if
@@ -181,8 +160,8 @@ class LoungeApi
return m.loungeToken return m.loungeToken
end function end function
function GetSessionData() as boolean private function BindQueryParams(loungeData as object) as object
queryParams = { return {
"device": "LOUNGE_SCREEN" "device": "LOUNGE_SCREEN"
"theme": "cl" "theme": "cl"
"capabilities": "vsp" "capabilities": "vsp"
@@ -191,13 +170,16 @@ class LoungeApi
"v": "2" "v": "2"
"t": "1" "t": "1"
"app": "lb-v4" "app": "lb-v4"
"RID": "1337" "name": loungeData.screenName
"id": loungeData.deviceId
"loungeIdToken": loungeData.loungeToken
"zx": m.Zx()
} }
end function
queryParams["name"] = m.screenName function GetSessionData() as boolean
queryParams["id"] = m.deviceId queryParams = m.BindQueryParams(m)
queryParams["loungeIdToken"] = m.loungeToken queryParams["RID"] = "1337"
queryParams["zx"] = m.Zx()
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind") request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams) request.QueryParams(queryParams)
@@ -207,28 +189,16 @@ class LoungeApi
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetSessionData) + `\n${response.ErrorMessage()}` LogError(`Failed to get lounge session data\n${response.ErrorMessage()}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
return false return false
end if end if
body = CreateObject("roByteArray")
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. Its outbound offset restarts from 0 too.
m.lastProcessedCommandIndex = -1
m.ofs = 0 m.ofs = 0
m.sessionGone = false m.sessionGone = false
m.tokenExpired = false m.tokenExpired = false
messagesToSend = [] messagesToSend = []
result = LoungeFraming.Extract(body, 0) for each command in m.backchannel.StartSession(response.Text())
for each frame in result.frames m.ProcessCommand(command, messagesToSend)
m.ProcessFrame(frame, messagesToSend)
end for end for
if StringUtils.IsNullOrEmpty(m.sessionId) or StringUtils.IsNullOrEmpty(m.gSessionId) if StringUtils.IsNullOrEmpty(m.sessionId) or StringUtils.IsNullOrEmpty(m.gSessionId)
LogTelemetryEvent({ LogTelemetryEvent({
@@ -241,52 +211,35 @@ class LoungeApi
return true return true
end function end function
function FetchCommandsRpc(messagePort as object) as void function StartPoll() as void
' Plain HTTP: LoungeBackchannel streams this response over a raw socket, which has no TLS queryParams = m.BindQueryParams(m)
baseUrl = "http://www.youtube.com/api/lounge/bc/bind" queryParams["RID"] = "rpc"
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": "vsp"
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"app": "lb-v4"
"RID": "rpc"
"CI": "0"
}
queryParams["name"] = m.screenName
queryParams["id"] = m.deviceId
queryParams["loungeIdToken"] = m.loungeToken
queryParams["SID"] = m.sessionId queryParams["SID"] = m.sessionId
queryParams["gsessionid"] = m.gSessionId queryParams["gsessionid"] = m.gSessionId
queryParams["zx"] = m.Zx() queryParams["CI"] = "1"
queryParams["TYPE"] = "xmlhttp"
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams) request = HttpClient.Get("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
if m.backchannel = invalid m.backchannel.Open(request, m.messagePort)
m.backchannel = new LoungeBackchannel()
end if
m.backchannel.Open(url, messagePort)
end function end function
function Poll(socketMessages as object, messagesToSend as object) as boolean function HandleMessage(message as dynamic, messagesToSend as object) as void
frames = m.backchannel.Poll(socketMessages) for each command in m.backchannel.Handle(message)
for each frame in frames m.ProcessCommand(command, messagesToSend)
m.ProcessFrame(frame, messagesToSend)
end for end for
m.HandleSends(message)
return m.backchannel.IsOpen()
end function end function
function GetCloseInfo() as object function MaxWaitMs() as integer
if m.backchannel = invalid waitMs = m.backchannel.MaxWaitMs()
return { statusCode: 0, reason: "", target: "" } for each pending in m.pendingOutgoingMessages
end if pendingWaitMs = pending.MaxWaitMs()
return { statusCode: m.backchannel.statusCode, reason: m.backchannel.closeReason, target: m.backchannel.redirectTarget } if waitMs = 0 or pendingWaitMs < waitMs
waitMs = pendingWaitMs
end if
end for
return waitMs
end function end function
function RefreshToken() as dynamic function RefreshToken() as dynamic
@@ -303,10 +256,7 @@ class LoungeApi
end function end function
function Rebind(withNewToken as boolean) as boolean function Rebind(withNewToken as boolean) as boolean
for each pending in m.pendingOutgoingMessages m.CancelSends()
pending.Cancel()
end for
m.pendingOutgoingMessages = []
if withNewToken if withNewToken
LogWarnNoTelemetry("Lounge token expired, refreshing") LogWarnNoTelemetry("Lounge token expired, refreshing")
@@ -319,58 +269,38 @@ class LoungeApi
return m.Bind() return m.Bind()
end function end function
function ProcessFrame(frame as string, messagesToSend as object) as void function EndSession() as void
commands = StringUtils.ParseJsonSafe(frame) m.backchannel.Close()
if not IsArray(commands) m.CancelSends()
LogTelemetryEvent({ m.loungeToken = invalid
level: "error"
message: "Lounge frame did not parse to a command array: " + frame.Left(256)
fingerprint: "lounge-unparseable-frame"
})
return
end if
m.ProcessCommands(commands, messagesToSend)
end function end function
function ProcessCommands(commands as object, messagesToSend as object) as void private function CancelSends() as void
for each command in commands for each pending in m.pendingOutgoingMessages
if not IsArray(command) or command.Count() <> 2 pending.Cancel()
continue for
end if
commandIndex = command[0]
commandData = command[1]
commandType = commandData[0]
if commandIndex <= m.lastProcessedCommandIndex and commandType <> COMMAND_TYPE_G_SESSION_ID and commandType <> COMMAND_TYPE_SESSION_ID
LogDebug("Skipping command already processed:", command)
continue for
end if
m.lastProcessedCommandIndex = commandIndex
commandArgs = invalid
if commandData.Count() > 1
commandArgs = commandData[1]
end if
handler = COMMAND_HANDLER_PREFIX + commandType
if m.DoesExist(handler)
LogInfo(commandIndex, commandType)
m[handler](commandIndex, commandType, commandArgs, messagesToSend)
else
fingerprint = "Unknown command type:" + ToString(commandType)
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw message
#end if
end if
end for end for
m.pendingOutgoingMessages = []
end function
function ProcessCommand(command as LoungeCommand, messagesToSend as object) as void
handler = COMMAND_HANDLER_PREFIX + command.type
if m.DoesExist(handler)
LogInfo(command.index, command.type)
m[handler](command.index, command.type, command.args, messagesToSend)
return
end if
fingerprint = "Unknown command type:" + command.type
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw message
#end if
end function end function
function HandleIgnoreCommand(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object) function HandleIgnoreCommand(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object)
@@ -387,20 +317,11 @@ class LoungeApi
LogInfo("gSessionId:", m.gSessionId) LogInfo("gSessionId:", m.gSessionId)
end function end function
function HandleGetPlayingNow(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void function HandleGetPlayingNow(_commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player player = m.videoQueueNode.player
messagesToSend.Push(LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext))
message = LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext) messagesToSend.Push(LoungeMessages.NowPlaying(player))
message["commandId"] = commandId messagesToSend.Push(LoungeMessages.OnStateChange(player))
messagesToSend.Push(message)
message = LoungeMessages.NowPlaying(player)
message["commandId"] = commandId
messagesToSend.Push(message)
message = LoungeMessages.OnStateChange(player)
message["commandId"] = commandId
messagesToSend.Push(message)
end function end function
function HandleLoungeStatus(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object) as void function HandleLoungeStatus(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object) as void
@@ -556,7 +477,7 @@ class LoungeApi
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true)) messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true))
end function end function
function HandleGetPlaybackSpeed(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void function HandleGetPlaybackSpeed(_commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player player = m.videoQueueNode.player
if player = invalid if player = invalid
return return
@@ -572,39 +493,23 @@ class LoungeApi
speed = 1.0 speed = 1.0
end if end if
message = LoungeMessages.OnPlaybackSpeedChanged(speed) messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed))
message["commandId"] = commandId
messagesToSend.Push(message)
end function end function
function SendMessages(messages as object) as void function SendMessages(messages as object) as void
if messages.Count() = 0 if messages.Count() = 0
return return
end if end if
m.pendingOutgoingMessages.Push(m.SendMessagesTo(m, messages)) m.pendingOutgoingMessages.Push(m.SendRequest(m, messages, m.backchannel.ackedCommandIndex).SendOn(m.messagePort))
end function end function
private function SendMessagesTo(loungeData as object, messages as object) as HttpClient.PendingResponse private function SendRequest(loungeData as object, messages as object, ackedCommandIndex as integer) as HttpClient.Request
queryParams = { queryParams = m.BindQueryParams(loungeData)
"device": "LOUNGE_SCREEN" queryParams["RID"] = "1337"
"theme": "cl"
"capabilities": "vsp"
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"app": "lb-v4"
"RID": "1337"
}
queryParams["name"] = loungeData.screenName
queryParams["id"] = loungeData.deviceId
queryParams["loungeIdToken"] = loungeData.loungeToken
queryParams["SID"] = loungeData.sessionId queryParams["SID"] = loungeData.sessionId
queryParams["gsessionid"] = loungeData.gSessionId queryParams["gsessionid"] = loungeData.gSessionId
queryParams["zx"] = m.Zx() if ackedCommandIndex >= 0
if messages[0].commandId <> invalid queryParams["AID"] = ackedCommandIndex
queryParams["AID"] = messages[0].commandId
end if end if
postData = [ postData = [
@@ -633,64 +538,51 @@ class LoungeApi
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind") request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams) request.QueryParams(queryParams)
request.FormBody(postData) request.FormBody(postData)
return request.Send() return request
end function end function
function HasPendingOutgoingMessages() as boolean private function HandleSends(message as dynamic) as void
return m.pendingOutgoingMessages.Count() > 0 for i = m.pendingOutgoingMessages.Count() - 1 to 0 step -1
end function response = m.pendingOutgoingMessages[i].Handle(message)
if response <> invalid
function ProcessPendingOutgoingMessages() as object m.pendingOutgoingMessages.Delete(i)
results = []
stillPending = []
for each pending in m.pendingOutgoingMessages
response = pending.Poll()
if response = invalid
stillPending.Push(pending)
else
status = response.StatusCode()
error = response.ErrorMessage()
results.Push({
"status": status
"error": error
})
if not response.IsSuccess() if not response.IsSuccess()
isGone = response.StatusCode() = 410 m.OnSendFailed(response)
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.
LogErrorNoTelemetry(response.ErrorMessage())
if expiredToken
LogTelemetryEvent({
level: "warning"
message: "Lounge id token expired"
fingerprint: "lounge-expired-token"
})
end if
else
LogErrorNoTelemetry(error)
LogTelemetryEvent({
level: "error"
message: error
fingerprint: ["lounge-send-failure", status]
})
end if
end if end if
end if end if
end for end for
m.pendingOutgoingMessages = stillPending end function
return results private function OnSendFailed(response as HttpClient.Response) as void
status = response.StatusCode()
error = response.ErrorMessage()
isGone = status = 410
unknownSid = status = 400 and error.InStr("Unknown SID") <> -1
expiredToken = status = 401 and error.InStr("Expired lounge id token") <> -1
if isGone or unknownSid
m.sessionGone = true
else if expiredToken
m.tokenExpired = true
end if
if isGone or unknownSid or expiredToken
' NoTelemetry: the body carries a volatile token; logging it would fragment these.
LogErrorNoTelemetry(error)
if expiredToken
LogTelemetryEvent({
level: "warning"
message: "Lounge id token expired"
fingerprint: "lounge-expired-token"
})
end if
else
LogErrorNoTelemetry(error)
LogTelemetryEvent({
level: "error"
message: error
fingerprint: ["lounge-send-failure", status]
})
end if
end function end function
function SaveCurrentLoungeData() as void function SaveCurrentLoungeData() as void
@@ -750,7 +642,7 @@ class LoungeApi
' This is the last message we'll be sending to this lounge. ' This is the last message we'll be sending to this lounge.
loungeData.ofs = 99999999 loungeData.ofs = 99999999
' Held: dropping it releases its transfer, which aborts the send. ' Held: dropping it releases its transfer, which aborts the send.
m.lastLoungeDisconnect = m.SendMessagesTo(loungeData, messages) m.lastLoungeDisconnect = m.SendRequest(loungeData, messages, -1).Send()
end function end function
end class end class
@@ -1,242 +1,166 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs" import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/UrlUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' Server sends periodic noop keepalives, so no data for this long means a dead connection. ' The server answers a poll with a noop after at most ~30 s idle, and drops a session that goes 55-60 s without a poll.
const LOUNGE_BACKCHANNEL_TIMEOUT_MS = 60000 ' Giving up on a dead connection by 40 s lets the next poll, after the first backoff, land before the session is gone.
const LOUNGE_BACKCHANNEL_BODY_COMPACT = 32768 const LOUNGE_POLL_TIMEOUT_MS = 40000
const LOUNGE_BACKCHANNEL_MAX_REDIRECTS = 10
' Raw socket on plain HTTP: roUrlTransfer can't read a streaming body incrementally, and
' roStreamSocket has no TLS.
class LoungeBackchannel class LoungeBackchannel
public statusCode = 0 public statusCode = 0
public closeReason = "" public closeReason as LoungeCloseReason
public redirectTarget = "" public ackedCommandIndex = -1
public stalledPolls = 0
public pollTimeoutMs = LOUNGE_POLL_TIMEOUT_MS
private socket private pending = invalid
private decoder private polledCommandIndex = -1
private body
private bodyCursor = 0
private timer
private url = ""
private messagePort
private redirectCount = 0
function new() ' A new session restarts command indices from 0.
m.timer = CreateObject("roTimespan") function StartSession(bindResponseText as string) as LoungeCommand[]
m.ackedCommandIndex = -1
m.stalledPolls = 0
return m.Receive(m.ExtractFrames(bindResponseText))
end function end function
function Open(url as string, messagePort as object) as boolean function Open(request as HttpClient.Request, messagePort as object) as void
m.messagePort = messagePort
m.redirectCount = 0
m.redirectTarget = ""
return m.Connect(url)
end function
private function Connect(url as string) as boolean
' A redirect or reconnect reuses Connect; close the previous socket so it doesn't leak.
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
m.url = url
m.statusCode = 0 m.statusCode = 0
m.closeReason = "" m.closeReason = invalid
m.polledCommandIndex = m.ackedCommandIndex
urlObject = UrlUtils.ParseUrl(url) m.pending = request.QueryParam("AID", m.ackedCommandIndex).NoCache().RetryCount(0).AttemptTimeoutMs(m.pollTimeoutMs).SendOn(messagePort)
if urlObject.protocol <> "http"
m.closeReason = "invalid_protocol"
LogError("Lounge backchannel needs http, got:", urlObject.protocol)
return false
end if
portValue = urlObject.port
if portValue = invalid or portValue = ""
portValue = "80"
end if
address = CreateObject("roSocketAddress")
address.SetAddress(urlObject.host + ":" + portValue)
socket = CreateObject("roStreamSocket")
socket.SetSendToAddress(address)
if not socket.Connect()
m.closeReason = "connect_failed"
LogWarnNoTelemetry("Lounge backchannel connect failed:", urlObject.host)
return false
end if
CRLF = Chr(13) + Chr(10)
request = "GET " + urlObject.path + " HTTP/1.1" + CRLF
request += "Host: " + urlObject.host + CRLF
request += "Connection: keep-alive" + CRLF
request += CRLF
socket.SendStr(request)
socket.NotifyReadable(true)
socket.SetMessagePort(m.messagePort)
m.socket = socket
m.decoder = new HttpChunkedDecoder()
m.body = CreateObject("roByteArray")
m.bodyCursor = 0
m.timer.Mark()
LogInfo("Lounge backchannel open, socket", socket.GetID())
return true
end function
function IsOpen() as boolean
return m.socket <> invalid and m.closeReason = ""
end function
function Poll(socketEvents as object) as object
frames = []
if m.socket = invalid
return frames
end if
if not m.socket.IsConnected()
m.CloseWith("disconnected")
return frames
end if
if m.timer.TotalMilliseconds() > LOUNGE_BACKCHANNEL_TIMEOUT_MS
m.CloseWith("timeout")
return frames
end if
if not m.HasReadableEvent(socketEvents)
return frames
end if
received = m.decoder.Pump(m.socket, m.body)
if received = 0
m.CloseWith("eof")
return frames
else if received < 0
if not m.socket.eOK()
m.CloseWith("receive_error")
end if
return frames
end if
m.timer.Mark()
if m.decoder.IsRedirect()
return m.FollowRedirect()
end if
result = LoungeFraming.Extract(m.body, m.bodyCursor)
m.bodyCursor = result.nextPos
for each frame in result.frames
frames.Push(frame)
end for
m.CompactBody()
if m.decoder.IsError()
m.statusCode = m.decoder.statusCode
if m.decoder.errorReason <> HttpDecoderError.None
m.CloseWith(m.decoder.errorReason)
else
m.CloseWith("http_" + StrI(m.statusCode).Trim())
end if
else if m.decoder.IsDone()
m.CloseWith("complete")
end if
return frames
end function end function
function Close() as void function Close() as void
m.CloseWith("closed") if m.pending <> invalid
end function m.pending.Cancel()
m.pending = invalid
private function HasReadableEvent(socketEvents as object) as boolean
id = m.socket.GetID()
for each event in socketEvents
if event.GetSocketID() = id
return true
end if
end for
return false
end function
private function CloseWith(reason as string) as void
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
if m.closeReason = ""
m.closeReason = reason
end if end if
end function end function
private function CompactBody() as void function IsPolling() as boolean
if m.bodyCursor = 0 return m.pending <> invalid
return end function
function MaxWaitMs() as integer
if m.pending = invalid
return 0
end if end if
if m.bodyCursor >= m.body.Count() return m.pending.MaxWaitMs()
m.body.Clear() end function
else if m.bodyCursor >= LOUNGE_BACKCHANNEL_BODY_COMPACT
m.body = LoungeBytes.Tail(m.body, m.bodyCursor) function Handle(message as dynamic) as LoungeCommand[]
if m.pending = invalid
return []
end if
response = m.pending.Handle(message)
if response = invalid
return []
end if
m.pending = invalid
m.statusCode = response.StatusCode()
if response.IsTimedOut()
m.closeReason = LoungeCloseReason.Timeout
return []
end if
if m.statusCode = 0
m.closeReason = LoungeCloseReason.NotSent
return []
end if
if m.statusCode < 0
m.closeReason = LoungeCloseReason.Curl
return []
end if
if m.statusCode < 200 or m.statusCode >= 300
m.closeReason = LoungeCloseReason.Http
return []
end if
frames = m.ExtractFrames(response.Text())
if frames.Count() = 0
m.closeReason = LoungeCloseReason.Empty
return []
end if
commands = m.Receive(frames)
' Nothing acknowledged: the next poll is answered with the same frames.
if m.ackedCommandIndex = m.polledCommandIndex
m.closeReason = LoungeCloseReason.Stalled
m.stalledPolls += 1
else else
return m.closeReason = LoungeCloseReason.Complete
m.stalledPolls = 0
end if end if
m.bodyCursor = 0 return commands
end function end function
private function FollowRedirect() as object function CloseLabel() as string
frames = [] if m.closeReason = LoungeCloseReason.Curl or m.closeReason = LoungeCloseReason.Http
return `${m.closeReason}_${Abs(m.statusCode)}`
location = m.decoder.Location()
if not IsString(location) or location = ""
m.CloseWith("redirect_no_location")
return frames
end if end if
return m.closeReason
end function
nextUrl = LoungeRedirect.Resolve(m.url, location) private function ExtractFrames(text as string) as object
m.redirectTarget = nextUrl body = CreateObject("roByteArray")
body.FromAsciiString(text)
m.redirectCount += 1 result = LoungeFraming.Extract(body, 0)
if m.redirectCount > LOUNGE_BACKCHANNEL_MAX_REDIRECTS if result.nextPos < body.Count()
m.CloseWith("redirect_limit") LogTelemetryEvent({
return frames level: "warning"
message: `Lounge answer ended mid-frame, ${body.Count() - result.nextPos} bytes left: ${text}`
fingerprint: "lounge-partial-frame"
})
end if end if
return result.frames
end function
LogInfo("Lounge backchannel following redirect to", m.redirectTarget) private function Receive(frames as object) as LoungeCommand[]
m.Connect(nextUrl) commands = []
return frames for each frame in frames
entries = StringUtils.ParseJsonSafe(frame)
if not IsArray(entries)
LogTelemetryEvent({
level: "error"
message: "Lounge frame did not parse to a command array: " + frame.Left(256)
fingerprint: "lounge-unparseable-frame"
})
continue for
end if
for each entry in entries
if not IsArray(entry) or entry.Count() = 0 or not IsInt(entry[0])
m.LogMalformedCommand(entry)
continue for
end if
index = entry[0]
if index <= m.ackedCommandIndex
LogDebug("Skipping command already received:", entry)
continue for
end if
' Acknowledged before validation: the server answers an unacknowledged command again, at once.
m.ackedCommandIndex = index
data = entry[1]
if not IsArray(data) or data.Count() = 0 or not IsString(data[0])
m.LogMalformedCommand(entry)
continue for
end if
commands.Push({ index: index, type: data[0], args: data[1] })
end for
end for
return commands
end function
private function LogMalformedCommand(entry as dynamic) as void
LogTelemetryEvent({
level: "error"
message: "Malformed lounge command: " + FormatJson(entry).Left(256)
fingerprint: "lounge-malformed-command"
})
end function end function
end class end class
namespace LoungeRedirect
' Force the target to plain HTTP - a raw socket has no TLS, so an https redirect is followed over http.
function Resolve(currentUrl as string, location as string) as string
if location.StartsWith("http://") or location.StartsWith("https://")
parts = UrlUtils.ParseUrl(location)
else
parts = UrlUtils.ParseUrl(currentUrl)
if not location.StartsWith("/")
location = "/" + location
end if
parts.path = location
end if
parts.protocol = "http"
if parts.port = "80" or parts.port = "443"
parts.port = invalid
end if
return UrlUtils.BuildUrlFromParts(parts)
end function
end namespace
@@ -6,16 +6,6 @@ namespace LoungeBytes
return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString() return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString()
end function end function
function IndexOfCrlf(bytes as object, fromIndex as integer) as integer
last = bytes.Count() - 2
for i = fromIndex to last
if bytes[i] = 13 and bytes[i + 1] = 10
return i
end if
end for
return -1
end function
function IndexOfByte(bytes as object, fromIndex as integer, value as integer) as integer function IndexOfByte(bytes as object, fromIndex as integer, value as integer) as integer
last = bytes.Count() - 1 last = bytes.Count() - 1
for i = fromIndex to last for i = fromIndex to last
@@ -26,8 +16,4 @@ namespace LoungeBytes
return -1 return -1
end function end function
function Tail(bytes as object, fromIndex as integer) as object
return ByteArrayUtils.Slice(bytes, fromIndex)
end function
end namespace end namespace
@@ -1,8 +1,7 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs" import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/LoungeService/LoungeApi.bs" import "pkg:/components/Services/LoungeService/LoungeApi.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
const IDLE_WAIT_MS = 60000 import "pkg:/components/Services/LoungeService/LoungeSession.bs"
const SENDS_IN_FLIGHT_WAIT_MS = 500
function Init() function Init()
m.top.functionName = "LoungeServiceLoop" m.top.functionName = "LoungeServiceLoop"
@@ -21,6 +20,7 @@ function StartService(_unused as dynamic) as boolean
return true return true
end if end if
m.top.isRunning = true
m.top.control = "run" m.top.control = "run"
return true return true
end function end function
@@ -34,65 +34,83 @@ function StopService(_unused as dynamic) as void
end function end function
function LoungeServiceLoop() as void function LoungeServiceLoop() as void
api = new LoungeApi(m.top, m.top.videoQueue, m.top.notifications, m.top.invidious) messagePort = CreateObject("roMessagePort")
m.top.observeField("shouldQuit", messagePort)
api = new LoungeApi(m.top, m.top.videoQueue, m.top.notifications, m.top.invidious, messagePort)
' Mobile app can remain connected to devices even after restarts. ' Mobile app can remain connected to devices even after restarts.
' Since we create a new lounge every time, we signal to the last lounge ' Since we create a new lounge every time, we signal to the last lounge
' that we're no longer there, and we're not coming back. ' that we're no longer there, and we're not coming back.
api.DisconnectFromLastLounge() api.DisconnectFromLastLounge()
messagePort = CreateObject("roMessagePort")
' We do not join a lounge until something asks us to like ' We do not join a lounge until something asks us to like
' - A remote connects through DIAL ' - A remote connects through DIAL
' - Generating a TV link code ' - Generating a TV link code
' Both join only while loungeToken is empty: a session that ends clears it.
while WaitForJoin(messagePort)
quitRequested = RunSession(api, messagePort)
api.EndSession()
m.top.unobserveField("outgoingMessages")
m.top.loungeToken = ""
if quitRequested
exit while
end if
end while
LogInfo("Lounge service stopped")
m.top.unobserveField("shouldQuit")
m.top.isRunning = false
end function
function WaitForJoin(messagePort as object) as boolean
m.top.observeField("join", messagePort) m.top.observeField("join", messagePort)
wait(0, messagePort) joinRequested = false
while true
message = wait(0, messagePort)
if IsQuitRequested([message])
exit while
end if
if type(message) = "roSGNodeEvent" and message.GetField() = "join"
joinRequested = true
exit while
end if
end while
m.top.unobserveField("join") m.top.unobserveField("join")
return joinRequested
end function
function RunSession(api as LoungeApi, messagePort as object) as boolean
screenId = api.GetScreenId() screenId = api.GetScreenId()
if StringUtils.IsNullOrEmpty(screenId) if StringUtils.IsNullOrEmpty(screenId)
Shutdown("No screen ID found") LogInfo("Lounge session ended: no screen ID")
return return false
end if end if
m.top.screenId = screenId m.top.screenId = screenId
loungeToken = api.GetToken() loungeToken = api.GetToken()
if StringUtils.IsNullOrEmpty(loungeToken) if StringUtils.IsNullOrEmpty(loungeToken)
Shutdown("No lounge token found") LogInfo("Lounge session ended: no lounge token")
return return false
end if end if
m.top.loungeToken = loungeToken m.top.loungeToken = loungeToken
m.top.observeField("outgoingMessages", messagePort) m.top.observeField("outgoingMessages", messagePort)
if not api.Bind() if not api.Bind()
Shutdown("Failed to bind") LogInfo("Lounge session ended: bind failed")
return return false
end if end if
api.FetchCommandsRpc(messagePort) api.StartPoll()
m.top.shouldQuit = false backchannel = api.backchannel
isOpen = false
reconnectAttempts = 0 reconnectAttempts = 0
sinceDelivered = CreateObject("roTimespan")
outgoingLoungeMessages = [] outgoingLoungeMessages = []
portMessages = [] portMessages = []
socketMessages = []
while true while true
if m.top.shouldQuit = true
exit while
end if
' 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.Clear()
portMessages.Push(message) portMessages.Push(wait(api.MaxWaitMs(), messagePort))
' There's a chance messages were piling up while we were sending messages to the lounge ' There's a chance messages were piling up while we were sending messages to the lounge
' This could happen if we were sending things to the lounge and the player state ' This could happen if we were sending things to the lounge and the player state
@@ -100,75 +118,81 @@ function LoungeServiceLoop() as void
while messagePort.PeekMessage() <> invalid while messagePort.PeekMessage() <> invalid
portMessages.Push(messagePort.GetMessage()) portMessages.Push(messagePort.GetMessage())
end while end while
if IsQuitRequested(portMessages)
return true
end if
' At this point: ' At this point:
' - We check if we need to send messages to the lounge based on player state ' - We check if we need to send messages to the lounge based on player state
' - We check the lounge for new commands, which might need responding to ' - We check the lounge for new commands, which might need responding to
' - Finally, we send the outgoing messages to the lounge in one go ' - Finally, we send the outgoing messages to the lounge in one go
outgoingLoungeMessages.Clear() outgoingLoungeMessages.Clear()
socketMessages.Clear()
for each portMessage in portMessages for each portMessage in portMessages
messageType = type(portMessage) if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "outgoingMessages"
if messageType = "roSocketEvent" outgoingLoungeMessages.Append(portMessage.GetData())
socketMessages.Push(portMessage)
else if messageType = "roSGNodeEvent"
field = portMessage.GetField()
if field = "outgoingMessages"
messages = portMessage.GetData()
outgoingLoungeMessages.Append(messages)
end if
end if end if
api.HandleMessage(portMessage, outgoingLoungeMessages)
end for end for
isOpen = api.Poll(socketMessages, outgoingLoungeMessages)
api.SendMessages(outgoingLoungeMessages) api.SendMessages(outgoingLoungeMessages)
api.ProcessPendingOutgoingMessages()
' A send's failure is acted on once the backchannel closes, which a dead session's does too. if backchannel.IsPolling()
if not isOpen continue while
closeInfo = api.GetCloseInfo()
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)
message = "Lounge backchannel failure: " + closeInfo.reason
if not StringUtils.IsNullOrEmpty(closeInfo.target)
message += " -> " + closeInfo.target
end if
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: "lounge-backchannel-" + closeInfo.reason
})
end if
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if needsRebind or needsTokenRefresh
if not api.Rebind(needsTokenRefresh)
Shutdown("Failed to rebind")
return
end if
m.top.loungeToken = api.loungeToken
end if
api.FetchCommandsRpc(messagePort)
else
reconnectAttempts = 0
end if end if
if backchannel.closeReason = LoungeCloseReason.Complete
sinceDelivered.Mark()
end if
' A send's failure is acted on once the poll ends, which a dead session's does too.
nextStep = LoungeSession.StepAfterPoll(backchannel.closeReason, backchannel.statusCode, backchannel.stalledPolls, api.sessionGone, api.tokenExpired, sinceDelivered.TotalMilliseconds())
if nextStep = LoungeSessionStep.Poll
reconnectAttempts = 0
api.StartPoll()
continue while
end if
closeLabel = backchannel.CloseLabel()
LogDebug("Backchannel closed:", closeLabel, "next:", nextStep)
if nextStep = LoungeSessionStep.Drop
LogTelemetryEvent({
level: "error"
message: `Lounge session dropped: no poll delivered for ${sinceDelivered.TotalSeconds()} s, last close: ${closeLabel}`
fingerprint: ["lounge-session-dropped", closeLabel]
})
return false
end if
if nextStep = LoungeSessionStep.Retry and backchannel.closeReason <> LoungeCloseReason.Timeout
LogTelemetryEvent({
level: "warning"
message: "Lounge backchannel failure: " + closeLabel
fingerprint: "lounge-backchannel-" + closeLabel
})
end if
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if nextStep <> LoungeSessionStep.Retry
if not api.Rebind(nextStep = LoungeSessionStep.RebindWithNewToken)
LogInfo("Lounge session ended: rebind failed")
return false
end if
m.top.loungeToken = api.loungeToken
end if
api.StartPoll()
end while end while
Shutdown("Service stopped") return false
end function end function
function Shutdown(reason as string) function IsQuitRequested(portMessages as object) as boolean
LogInfo("Shutting down:", reason) for each portMessage in portMessages
m.top.unobserveField("outgoingMessages") if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "shouldQuit" and portMessage.GetData() = true
m.top.isRunning = false return true
end if
end for
return false
end function end function
' Full jitter (random in [0, window)) avoids a fleet-wide thundering-herd reconnect. ' Full jitter (random in [0, window)) avoids a fleet-wide thundering-herd reconnect.
@@ -183,13 +207,3 @@ function ComputeReconnectBackoffMs(attempts as integer) as integer
end if end if
return 500 + Int(Rnd(0) * windowMs) return 500 + Int(Rnd(0) * windowMs)
end function end function
function IsActionableCloseFailure(reason as string, needsRebind as boolean, needsTokenRefresh as boolean) as boolean
if needsRebind or needsTokenRefresh
return false
end if
if reason = "complete" or reason = "eof" or reason = "closed" or reason = "timeout" or reason = "disconnected" or reason = ""
return false
end if
return true
end function
@@ -0,0 +1,23 @@
enum LoungeCloseReason
Complete = "complete"
Empty = "empty"
Stalled = "stalled"
Timeout = "timeout"
NotSent = "not_sent"
Curl = "curl"
Http = "http"
end enum
enum LoungeSessionStep
Poll = "poll"
Retry = "retry"
Rebind = "rebind"
RebindWithNewToken = "rebind_with_new_token"
Drop = "drop"
end enum
interface LoungeCommand
index as integer
type as string
args as dynamic
end interface
@@ -0,0 +1,26 @@
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
namespace LoungeSession
const GIVE_UP_MS = 300000
function StepAfterPoll(closeReason as LoungeCloseReason, statusCode as integer, stalledPolls as integer, sessionGone as boolean, tokenExpired as boolean, msSinceDelivered as integer) as LoungeSessionStep
' A new session doesn't answer the frames a stalled one keeps answering.
needsRebind = statusCode = 400 or statusCode = 410 or sessionGone or stalledPolls > 1
needsNewToken = statusCode = 401 or tokenExpired
if closeReason = LoungeCloseReason.Complete and not needsRebind and not needsNewToken
return LoungeSessionStep.Poll
end if
if msSinceDelivered >= LoungeSession.GIVE_UP_MS
return LoungeSessionStep.Drop
end if
if needsNewToken
return LoungeSessionStep.RebindWithNewToken
end if
if needsRebind
return LoungeSessionStep.Rebind
end if
return LoungeSessionStep.Retry
end function
end namespace
@@ -68,14 +68,6 @@
<source>Premieres in 1 minute</source> <source>Premieres in 1 minute</source>
<translation>Premiere in 1 Minute</translation> <translation>Premiere in 1 Minute</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Fehler beim Setup des Lounge-Services</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Lounge Token konnte nicht geladen werden. Bitte starten Sie Playlet erneut, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message> <message>
<source>name</source> <source>name</source>
<translation>Name</translation> <translation>Name</translation>
@@ -424,22 +416,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Feed konnte nicht geladen werden</translation> <translation>Feed konnte nicht geladen werden</translation>
</message> </message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Ungültige Bildschirm-ID: %1</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Ungültige Antwort: %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Session-Daten konnten nicht geladen werden. Bitte starten Sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message> <message>
<source>Invidious custom instance</source> <source>Invidious custom instance</source>
<translation>Benutzerdefinierte Invidious-Instanz</translation> <translation>Benutzerdefinierte Invidious-Instanz</translation>
@@ -248,30 +248,6 @@
<source>Backend changed to Playlet, because no Invidious instance is set.</source> <source>Backend changed to Playlet, because no Invidious instance is set.</source>
<translation>Backend changed to Playlet, because no Invidious instance is set.</translation> <translation>Backend changed to Playlet, because no Invidious instance is set.</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Lounge service setup error</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Failed to get screen ID. Please restart Playlet to use the cast function.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Not a valid screen id: %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Failed to get lounge token. Please restart Playlet to use the cast function.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Invalid response: %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Failed to get session data. Please restart Playlet to use the cast function.</translation>
</message>
<message> <message>
<source>Select a service to login</source> <source>Select a service to login</source>
<translation>Select a service to login</translation> <translation>Select a service to login</translation>
@@ -208,30 +208,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Fallo al cargar el feed</translation> <translation>Fallo al cargar el feed</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Id de pantalla no válida: %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>No se ha podido obtener el token dela sala. Por favor, reinicia Playlet para utilizar la función de la transmisión.</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>No se han podido obtener los datos de la sesión. Por favor, reinicia Playlet para utilizar la función de transmisión.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Respuesta no válida: %1</translation>
</message>
<message> <message>
<source>Invidious custom instance</source> <source>Invidious custom instance</source>
<translation>Instancia personalizada de Invidious</translation> <translation>Instancia personalizada de Invidious</translation>
@@ -840,18 +840,6 @@
<source>Failed to load Invidious public instances</source> <source>Failed to load Invidious public instances</source>
<translation>No se pudieron cargar las instancias públicas de Invidious</translation> <translation>No se pudieron cargar las instancias públicas de Invidious</translation>
</message> </message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>La ID de pantalla no es válida: %1</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Respuesta inválida: %1</translation>
</message>
<message> <message>
<source>Invidious public instances</source> <source>Invidious public instances</source>
<translation>Instancias públicas de Invidious</translation> <translation>Instancias públicas de Invidious</translation>
@@ -944,14 +932,6 @@
<source>Latest (default)</source> <source>Latest (default)</source>
<translation>Más reciente (por defecto)</translation> <translation>Más reciente (por defecto)</translation>
</message> </message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>No se ha podido obtener el token de Lounge. Por favor reinicia Playlet para usar la función de transmión.</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>No se han podido obtener los datos de sesión. Por favor reinicia Playlet para usar la función de transmisión.</translation>
</message>
<message> <message>
<source>Invidious custom instance</source> <source>Invidious custom instance</source>
<translation>Instancia personalizada de Invidious</translation> <translation>Instancia personalizada de Invidious</translation>
@@ -1020,10 +1000,6 @@
<source>Invalid caption data from %1 (response is not a valid vtt file)</source> <source>Invalid caption data from %1 (response is not a valid vtt file)</source>
<translation>Datos de subtítulos inválidos de %1 (la respuesta no es un archivo vtt válido)</translation> <translation>Datos de subtítulos inválidos de %1 (la respuesta no es un archivo vtt válido)</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation>
</message>
<message> <message>
<source>signup</source> <source>signup</source>
<translation>registro</translation> <translation>registro</translation>
@@ -208,30 +208,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Échec du chargement du flux</translation> <translation>Échec du chargement du flux</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Erreur de configuration du service Lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Impossible d&apos;obtenir l&apos;identifiant de l&apos;écran. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Identifiant d&apos;écran non valide : %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Échec de l&apos;obtention du jeton Lounge. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Réponse non valide : %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Échec de l&apos;obtention des données de session. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message> <message>
<source>Invidious custom instance</source> <source>Invidious custom instance</source>
<translation>Instance personnalisée d&apos;Invidious</translation> <translation>Instance personnalisée d&apos;Invidious</translation>
@@ -128,10 +128,6 @@
<source>Failed to load channel %1</source> <source>Failed to load channel %1</source>
<translation>Falha ao carregar o canal %1</translation> <translation>Falha ao carregar o canal %1</translation>
</message> </message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Não conseguiu obter token lounge. Por favor, reinicie Playlet para usar a função de transmitir.</translation>
</message>
<message> <message>
<source>Subscriptions</source> <source>Subscriptions</source>
<translation>Inscrições</translation> <translation>Inscrições</translation>
@@ -216,18 +212,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Erro ao carregar o feed</translation> <translation>Erro ao carregar o feed</translation>
</message> </message>
<message>
<source>Lounge service setup error</source>
<translation>Erro ao configurar o serviço de lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Falha ao obter o ID da tela. Por favor, reinicie Playlet para usar a função de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Não é um id de tela válido: %1</translation>
</message>
<message> <message>
<source>Invidious instance to use. Example: https://example.com. Find more instances at %INVIDIOUS_PUBLIC_INSTANCES%</source> <source>Invidious instance to use. Example: https://example.com. Find more instances at %INVIDIOUS_PUBLIC_INSTANCES%</source>
<translation>Instância Invidious para usar. Exemplo: https://example.com. Encontre mais casos em %INVIDIOUS_PUBLIC_INSTANCES%</translation> <translation>Instância Invidious para usar. Exemplo: https://example.com. Encontre mais casos em %INVIDIOUS_PUBLIC_INSTANCES%</translation>
@@ -504,10 +488,6 @@
<source>This will restart Playlet.</source> <source>This will restart Playlet.</source>
<translation>Isso vai reiniciar o Playlet.</translation> <translation>Isso vai reiniciar o Playlet.</translation>
</message> </message>
<message>
<source>Invalid response: %1</source>
<translation>Resposta inválida: %1</translation>
</message>
<message> <message>
<source>Test</source> <source>Test</source>
<translation>Teste</translation> <translation>Teste</translation>
@@ -712,10 +692,6 @@
<source>Queue Playlist</source> <source>Queue Playlist</source>
<translation>Lista dereprodução em fila</translation> <translation>Lista dereprodução em fila</translation>
</message> </message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Não conseguimos obter dados da sessão. Por favor, reinicie Playlet para usar a função transmitir.</translation>
</message>
<message> <message>
<source>Invalid JSON from %1 (couldn&apos;t read %2)</source> <source>Invalid JSON from %1 (couldn&apos;t read %2)</source>
<translation>JSON inválido de %1 (Não conseguiu ler %2)</translation> <translation>JSON inválido de %1 (Não conseguiu ler %2)</translation>
@@ -1,176 +0,0 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
namespace Tests
@suite
class HttpChunkedDecoderTests extends Rooibos.BaseTestSuite
@describe("HttpChunkedDecoder.Pump")
@it("decodes a single-chunk 200 response and reaches Done")
function singleChunk()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
m.assertEqual(r.decoder.statusCode, 200)
m.assertTrue(r.decoder.IsDone())
m.assertFalse(r.decoder.IsError())
end function
@it("concatenates multiple chunks into one body")
function multipleChunks()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
' A chunk boundary need not align with a socket read: the same response delivered one byte
' per read must reassemble identically.
@it("reassembles a response delivered one byte per socket read")
function bytewise()
r = m.Drive(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`, 1)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
@it("parses a hex chunk size greater than 9")
function hexChunkSize()
payload = "0123456789abcdef" ' 16 bytes -> chunk size "10" in hex
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10\r\n` + payload + `\r\n0\r\n\r\n`)
m.assertEqual(r.body, payload)
end function
@it("ignores chunk-size extensions after a semicolon")
function chunkExtensions()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;foo=bar\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
end function
@it("extracts a chunk byte-exactly when the body holds multi-byte UTF-8")
function utf8Chunk()
' "café" is 4 characters but 5 UTF-8 bytes; the chunk size counts bytes.
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\ncafé\r\n0\r\n\r\n`)
m.assertEqual(r.body, "café")
m.assertTrue(r.decoder.IsDone())
end function
@it("flags a non-200 status as an error carrying the code")
@params("410 Gone", 410)
@params("400 Bad Request", 400)
@params("401 Unauthorized", 401)
function non200(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.errorReason, "", "an HTTP status error is fingerprinted by code, not a slug")
end function
@it("surfaces a 3xx as a redirect carrying the Location, not an error")
@params("301 Moved Permanently", 301)
@params("302 Found", 302)
@params("303 See Other", 303)
@params("307 Temporary Redirect", 307)
@params("308 Permanent Redirect", 308)
function redirect(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\nLocation: https://rr4.youtube.com/api/lounge/bc/bind?SID=x\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.Location(), "https://rr4.youtube.com/api/lounge/bc/bind?SID=x")
end function
@it("treats an HTTP/1.0 307 as a redirect")
function redirectHttp10()
r = m.DecodeWhole(`HTTP/1.0 307 Temporary Redirect\r\nLocation: http://portal.example/login\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertEqual(r.decoder.Location(), "http://portal.example/login")
end function
@it("flags a 200 response that is not chunked as an error rather than crashing")
function nonChunked()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "unsupported_encoding")
end function
@it("flags a malformed status line with a stable error reason")
function malformedStatus()
r = m.DecodeWhole(`HELLO not http\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "malformed_status")
end function
@it("waits for more bytes when the status line is incomplete")
function partialStatus()
r = m.Drive("HTTP/1.1 20", 0)
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.body, "")
end function
@it("errors on a chunk size that overflows a 32-bit int")
function chunkOverflow()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFFF\r\nx`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "chunk_overflow")
end function
function DecodeWhole(response as string) as object
return m.Drive(response, 0)
end function
function Drive(response as string, readSize as integer) as object
decoder = new HttpChunkedDecoder()
socket = new LoungeMockSocket(m.Bytes(response), readSize)
out = CreateObject("roByteArray")
while socket.GetCountRcvBuf() > 0 and not decoder.IsDone() and not decoder.IsError() and not decoder.IsRedirect()
decoder.Pump(socket, out)
end while
return { decoder: decoder, body: out.ToAsciiString() }
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
end class
' Feeds `bytes` to the decoder, at most `readSize` per Receive (0 = all at once), so a test
' can drive fragmented reads.
class LoungeMockSocket
private data
private readPos = 0
private readSize = 0
function new(bytes as object, readSize as integer)
m.data = bytes
m.readSize = readSize
end function
function GetCountRcvBuf() as integer
remaining = m.data.Count() - m.readPos
if remaining <= 0
return 0
end if
if m.readSize > 0 and m.readSize < remaining
return m.readSize
end if
return remaining
end function
function Receive(ba as object, index as integer, length as integer) as integer
count = 0
while count < length and m.readPos < m.data.Count()
ba[index + count] = m.data[m.readPos]
count += 1
m.readPos += 1
end while
return count
end function
end class
end namespace
@@ -0,0 +1,209 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class LoungeBackchannelTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function PollOnce(backchannel as LoungeBackchannel, path as string, route as dynamic) as object
if route <> invalid
routes = {}
routes[path] = route
m.server.routes = routes
end if
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl(path)), port)
commands = []
timer = CreateObject("roTimespan")
while backchannel.IsPolling() and timer.TotalMilliseconds() < 5000
commands.Append(backchannel.Handle(wait(backchannel.MaxWaitMs(), port)))
end while
return commands
end function
function Frame(json as string) as string
body = CreateObject("roByteArray")
body.FromAsciiString(json)
return `${body.Count()}\n${json}`
end function
@describe("LoungeBackchannel")
@it("returns the commands of a 2xx answer, complete, and acknowledges the last one in the next poll")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]\n`) + m.Frame(`[[8,["seekTo",{"newTime":"12"}]]]\n`) + `\n`
commands = m.PollOnce(backchannel, "/lounge/frames", { status: 200, body: body })
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].index, 7)
m.assertEqual(commands[0].type, "noop")
m.assertInvalid(commands[0].args)
m.assertEqual(commands[1].index, 8)
m.assertEqual(commands[1].type, "seekTo")
m.assertEqual(commands[1].args, { newTime: "12" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.statusCode, 200)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(m.global.telemetry.LogEvent)
m.PollOnce(backchannel, "/lounge/next", { status: 200, body: m.Frame(`[[9,["noop"]]]`) })
m.assertEqual(Tests.HttpTestServerHits(m.server, "/lounge/next?AID=8"), 1)
end function
@it("ends a 2xx answer without frames as empty")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/empty", { status: 200, body: "" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Empty)
end function
@it("returns the commands of the whole frames of an answer that ends mid-frame, and reports what is left")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/partial", { status: 200, body: m.Frame(`[[7,["noop"]]]`) + `40\n[[8,` })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 7)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
event = m.global.telemetry.LogEvent
m.assertEqual(event.fingerprint, "lounge-partial-frame")
m.assertTrue(event.message.InStr("7 bytes left") <> -1, event.message)
end function
@it("skips the commands it already received")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/first", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
commands = m.PollOnce(backchannel, "/lounge/resent", { status: 200, body: m.Frame(`[[7,["noop"]],[8,["play"]]]`) })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
end function
@it("acknowledges a malformed command it can read the index of, and reports it")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/malformed", { status: 200, body: m.Frame(`[[7],[8,{"not":"an array"}]]`) })
m.assertEmpty(commands)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-malformed-command")
end function
@it("ends a 2xx answer that acknowledges nothing as stalled")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]`)
m.PollOnce(backchannel, "/lounge/stalled", { status: 200, body: body })
m.assertEmpty(m.PollOnce(backchannel, "/lounge/stalled", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 1)
m.assertEqual(backchannel.ackedCommandIndex, 7)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unparseable", { status: 200, body: m.Frame(`[[8,["noop"]`) }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 2)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-unparseable-frame")
m.PollOnce(backchannel, "/lounge/unstalled", { status: 200, body: m.Frame(`[[8,["noop"]]]`) })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("restarts the acknowledged index for the session a bind starts")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/old-session", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
m.PollOnce(backchannel, "/lounge/old-session", invalid)
commands = backchannel.StartSession(m.Frame(`[[0,["c","SID"]],[1,["S","GSID"]]]`))
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].type, "c")
m.assertEqual(commands[0].args, "SID")
m.assertEqual(backchannel.ackedCommandIndex, 1)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("ends a non-2xx answer with its status")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unknownsid", { status: 400, body: "Unknown SID" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
m.assertEqual(backchannel.CloseLabel(), "http_400")
m.assertEqual(backchannel.statusCode, 400)
end function
@it("ends a poll the server drops with its curl code")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/dropped", { drop: true }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Curl)
m.assertEqual(backchannel.CloseLabel(), "curl_52")
m.assertEqual(backchannel.statusCode, HttpClient.CurlErrors.CURLE_GOT_NOTHING)
end function
@it("ends a poll the server holds past the poll timeout as timeout")
function _()
backchannel = new LoungeBackchannel()
backchannel.pollTimeoutMs = 300
m.assertEmpty(m.PollOnce(backchannel, "/delay/3000", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Timeout)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("ends a poll that can't be sent as not_sent")
function _()
backchannel = new LoungeBackchannel()
' A transfer already in progress refuses another.
busyTransfer = CreateObject("roUrlTransfer")
busyTransfer.SetUrl(Tests.HttpTestServerUrl("/delay/2000"))
busyTransfer.SetMessagePort(CreateObject("roMessagePort"))
busyTransfer.AsyncGetToString()
m.stubCall(HttpClient.CreateUrlTransfer, busyTransfer)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/not-sent", invalid))
busyTransfer.AsyncCancel()
m.assertEqual(backchannel.closeReason, LoungeCloseReason.NotSent)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("cancels the poll in flight when closed")
function _()
backchannel = new LoungeBackchannel()
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), port)
backchannel.Close()
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(backchannel.Handle(wait(500, port)))
m.assertInvalid(backchannel.closeReason)
end function
@it("resets the status and reason of the previous poll when it opens the next")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/gone", { status: 410, body: "" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), CreateObject("roMessagePort"))
m.assertTrue(backchannel.IsPolling())
m.assertInvalid(backchannel.closeReason)
m.assertEqual(backchannel.statusCode, 0)
end function
end class
end namespace
@@ -15,18 +15,6 @@ namespace Tests
m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe) m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe)
end function end function
@it("finds the first CRLF at or after a position")
function indexOfCrlf()
bytes = m.Bytes(`ab\r\ncd\r\n`)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 0), 2)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 3), 6)
end function
@it("returns -1 when no CRLF is present")
function indexOfCrlfMissing()
m.assertEqual(LoungeBytes.IndexOfCrlf(m.Bytes("abc"), 0), -1)
end function
@it("finds the first byte value at or after a position, or -1") @it("finds the first byte value at or after a position, or -1")
function indexOfByte() function indexOfByte()
bytes = m.Bytes("a,b,c") bytes = m.Bytes("a,b,c")
@@ -35,12 +23,6 @@ namespace Tests
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1) m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1)
end function end function
@it("returns a tail copy from a position to the end")
function tail()
tail = LoungeBytes.Tail(m.Bytes("hello"), 2)
m.assertEqual(tail.ToAsciiString(), "llo")
end function
function Bytes(text as string) as object function Bytes(text as string) as object
bytes = CreateObject("roByteArray") bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text) bytes.FromAsciiString(text)
@@ -1,44 +0,0 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
namespace Tests
@suite
class LoungeRedirectTests extends Rooibos.BaseTestSuite
@describe("LoungeRedirect.Resolve")
@it("downgrades an https target to http, keeping host, path and query")
function downgradesHttps()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "https://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
m.assertEqual(resolved, "http://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
end function
@it("keeps an http target as-is")
function keepsHttp()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/x", "http://other.host/y?z=1")
m.assertEqual(resolved, "http://other.host/y?z=1")
end function
@it("drops a default 80 or 443 port")
@params("https://host:443/p", "http://host/p")
@params("http://host:80/p", "http://host/p")
@params("http://host:8080/p", "http://host:8080/p")
function dropsDefaultPort(location as string, expected as string)
m.assertEqual(LoungeRedirect.Resolve("http://www.youtube.com/x", location), expected)
end function
@it("resolves a root-relative Location against the current host")
function relativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "/api/lounge/bc/bind?SID=a&AID=5")
m.assertEqual(resolved, "http://www.youtube.com/api/lounge/bc/bind?SID=a&AID=5")
end function
@it("prefixes a slash onto a bare relative Location")
function bareRelativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind", "elsewhere?x=1")
m.assertEqual(resolved, "http://www.youtube.com/elsewhere?x=1")
end function
end class
end namespace
@@ -51,23 +51,39 @@ namespace Tests
end function end function
@slow(30000) @slow(30000)
@it("sends the messages a bind calls for, and reports each one's status once it completes") @it("sends the messages a bind calls for, each completing on the service loop's port")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
sends = []
sends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(sends, "the bind sent no messages")
m.RunLoop(api, 10000, function(api as object) as boolean
return api.pendingOutgoingMessages.Count() = 0
end function)
m.AssertSendsSucceeded(sends)
end function
@slow(60000)
@it("polls the backchannel over HTTPS: the server holds the poll, then answers with a frame")
function _() function _()
api = m.CreateLiveApi() api = m.CreateLiveApi()
api.GetScreenId() api.GetScreenId()
api.GetToken() api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed") m.assertTrue(api.GetSessionData(), "bind failed")
results = [] api.StartPoll()
m.assertTrue(api.backchannel.IsPolling())
timer = CreateObject("roTimespan") timer = CreateObject("roTimespan")
while results.Count() = 0 and timer.TotalMilliseconds() < 10000 m.RunLoop(api, 50000, function(api as object) as boolean
results.Append(api.ProcessPendingOutgoingMessages()) return not api.backchannel.IsPolling()
sleep(50) end function)
end while m.assertEqual(api.backchannel.closeReason, LoungeCloseReason.Complete, `status ${api.backchannel.statusCode}`)
m.assertNotEmpty(results, "no outgoing message completed") m.assertEqual(api.backchannel.statusCode, 200)
for each result in results m.assertTrue(timer.TotalMilliseconds() > 5000, `answered after ${timer.TotalMilliseconds()} ms: AID didn't acknowledge the bind's commands`)
m.assertEqual(result.status, 200, result.error)
end for
end function end function
@slow(30000) @slow(30000)
@@ -77,27 +93,37 @@ namespace Tests
api.GetScreenId() api.GetScreenId()
api.GetToken() api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed") m.assertTrue(api.GetSessionData(), "bind failed")
m.assertTrue(api.HasPendingOutgoingMessages(), "the bind sent no messages")
replacedSends = [] replacedSends = []
replacedSends.Append(api.pendingOutgoingMessages) replacedSends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(replacedSends, "the bind sent no messages")
m.assertTrue(api.Rebind(true), "rebind failed") m.assertTrue(api.Rebind(true), "rebind failed")
m.assertNotEmpty(replacedSends)
for each pending in replacedSends for each pending in replacedSends
m.assertTrue(pending.Poll().IsCancelled(), "a send of the replaced session was not cancelled") m.assertTrue(pending.Handle(invalid).IsCancelled(), "a send of the replaced session was not cancelled")
end for end for
results = [] sends = []
sends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(sends, "the rebind sent no messages")
m.RunLoop(api, 10000, function(api as object) as boolean
return api.pendingOutgoingMessages.Count() = 0
end function)
m.AssertSendsSucceeded(sends)
end function
private function RunLoop(api as object, limitMs as integer, done as function) as void
timer = CreateObject("roTimespan") timer = CreateObject("roTimespan")
while api.HasPendingOutgoingMessages() and timer.TotalMilliseconds() < 10000 while not done(api) and timer.TotalMilliseconds() < limitMs
results.Append(api.ProcessPendingOutgoingMessages()) api.HandleMessage(wait(api.MaxWaitMs(), m.messagePort), [])
sleep(50)
end while end while
m.assertFalse(api.HasPendingOutgoingMessages(), "the new session's sends did not complete") end function
m.assertNotEmpty(results, "the rebind sent no messages")
for each result in results private function AssertSendsSucceeded(sends as object) as void
m.assertEqual(result.status, 200, result.error) for each pending in sends
response = pending.Handle(invalid)
m.assertNotInvalid(response, "a send did not complete")
m.assertEqual(response.StatusCode(), 200, response.ErrorMessage())
end for end for
end function end function
@@ -111,7 +137,8 @@ namespace Tests
queueStub = CreateObject("roSGNode", "Node") queueStub = CreateObject("roSGNode", "Node")
queueStub.addFields({ hasPrevious: false, hasNext: false }) queueStub.addFields({ hasPrevious: false, hasNext: false })
notifyStub = CreateObject("roSGNode", "Node") notifyStub = CreateObject("roSGNode", "Node")
return new LoungeApi(loungeServiceNode, queueStub, notifyStub, invalid) m.messagePort = CreateObject("roMessagePort")
return new LoungeApi(loungeServiceNode, queueStub, notifyStub, invalid, m.messagePort)
end function end function
end class end class
@@ -0,0 +1,63 @@
import "pkg:/components/Services/LoungeService/LoungeSession.bs"
namespace Tests
@suite
class LoungeSessionTests extends Rooibos.BaseTestSuite
@describe("LoungeSession.StepAfterPoll")
@it("polls again after a complete poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, 0), LoungeSessionStep.Poll)
end function
@it("retries a failed poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Timeout, 0, 0, false, false, 40000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Http, 503, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Empty, 200, 0, false, false, 1000), LoungeSessionStep.Retry)
end function
@it("retries the first stall, and rebinds on the second in a row")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 1, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 2, false, false, 2000), LoungeSessionStep.Rebind)
end function
@it("rebinds a session the server no longer has")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Http, 410, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, true, false, 0), LoungeSessionStep.Rebind)
end function
@it("rebinds with a new token when the token expired")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, 1000), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, true, 0), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, true, 1000), LoungeSessionStep.RebindWithNewToken)
end function
@it("drops a session that delivered no poll for the give-up time, whatever the failure")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 3, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS - 1), LoungeSessionStep.Retry)
end function
@it("never drops a session whose poll just delivered")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Poll)
end function
function step(closeReason as LoungeCloseReason, statusCode as integer, stalledPolls as integer, sessionGone as boolean, tokenExpired as boolean, msSinceDelivered as integer) as LoungeSessionStep
return LoungeSession.StepAfterPoll(closeReason, statusCode, stalledPolls, sessionGone, tokenExpired, msSinceDelivered)
end function
end class
end namespace
+72 -36
View File
@@ -23,18 +23,21 @@ import "pkg:/source/utils/UrlUtils.bs"
' response = pending.Wait(2000) ' the response, or invalid after 2s; the fetch goes on ' response = pending.Wait(2000) ' the response, or invalid after 2s; the fetch goes on
' response = pending.Poll() ' the response, or invalid; never blocks ' response = pending.Poll() ' the response, or invalid; never blocks
' '
' pending = HttpClient.Post(url).Send() ' in a task loop, which blocks only on its own port ' pending = HttpClient.Post(url).SendOn(port) ' in a task loop: a Fetch on the loop's own port
' while true ' while true
' message = wait(500, port) ' message = wait(pending.MaxWaitMs(), port) ' wakes for the answer, the attempt's deadline or a retry
' response = pending.Poll() ' at each wake: the response once it is in, up to 500ms late ' response = pending.Handle(message) ' the response once it is in; the loop's messages are ignored
' ... ' the loop's own messages ' ... ' the loop's own messages
' if response <> invalid then exit while
' '
' Retries run inside the fetch, on the thread that started it, while Await, Wait or Poll runs. ' Retries run inside the fetch, on the thread that started it, while Await, Wait, Poll or Handle runs.
namespace HttpClient namespace HttpClient
const COMPRESSION_ENABLED = true const COMPRESSION_ENABLED = true
const DEFAULT_ATTEMPT_TIMEOUT_MS = 30000 const DEFAULT_ATTEMPT_TIMEOUT_MS = 30000
const DEFAULT_RETRY_DELAY_MS = 1000 const DEFAULT_RETRY_DELAY_MS = 1000
' The id of every cancellation observer, which tells its events from the other node events on a shared port.
const CANCELLATION_OBSERVER_ID = "HttpClient.CancellationObserver"
' https://developer.roku.com/en-ca/docs/references/brightscript/events/rourlevent.md#getresponsecode-as-integer ' https://developer.roku.com/en-ca/docs/references/brightscript/events/rourlevent.md#getresponsecode-as-integer
' Seem to mirror the curl error codes https://curl.se/libcurl/c/libcurl-errors.html ' Seem to mirror the curl error codes https://curl.se/libcurl/c/libcurl-errors.html
@@ -385,11 +388,21 @@ namespace HttpClient
' Starts a fetch on a port of its own, which Await, Wait or Poll runs: a request never waited on or polled may ' Starts a fetch on a port of its own, which Await, Wait or Poll runs: a request never waited on or polled may
' be dropped when its task ends, and its retries never run. ' be dropped when its task ends, and its retries never run.
function Send() as PendingResponse function Send() as PendingResponse
messagePort = CreateObject("roMessagePort") return m.StartFetch(CreateObject("roMessagePort"), true)
end function
' Starts a fetch on a task loop's port: the loop caps each wait with MaxWaitMs and hands Handle every message
' it takes, so it wakes as soon as the answer is in, and the fetch's deadline and retries run on time.
function SendOn(messagePort as object) as PendingResponse
return m.StartFetch(messagePort, false)
end function
private function StartFetch(messagePort as object, ownsPort as boolean) as PendingResponse
' Observed before the fetch starts, so a cancellation set between its check and the observation isn't missed. ' Observed before the fetch starts, so a cancellation set between its check and the observation isn't missed.
cancellationObserver = invalid cancellationObserver = invalid
if m._cancellation <> invalid if m._cancellation <> invalid
cancellationObserver = CreateObject("roSGNode", "NodeObserver") cancellationObserver = CreateObject("roSGNode", "NodeObserver")
cancellationObserver.id = CANCELLATION_OBSERVER_ID
' Observed before the target is set: the NodeObserver's callback on the render-thread cancellation moves the ' Observed before the target is set: the NodeObserver's callback on the render-thread cancellation moves the
' NodeObserver to the render thread, after which each access to it is a rendezvous. ' NodeObserver to the render thread, after which each access to it is a rendezvous.
cancellationObserver.ObserveField("changed", messagePort) cancellationObserver.ObserveField("changed", messagePort)
@@ -397,13 +410,13 @@ namespace HttpClient
end if end if
startedFetch = new Fetch(m, messagePort) startedFetch = new Fetch(m, messagePort)
startedFetch.Start() startedFetch.Start()
return new PendingResponse(startedFetch, messagePort, m._cancellation, cancellationObserver) return new PendingResponse(startedFetch, messagePort, ownsPort, m._cancellation, cancellationObserver)
end function end function
end class end class
' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send returns. ' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send or SendOn
' It reads the request as it goes, so the request isn't changed after it is sent. Its port is its own: it gets ' returns. It reads the request as it goes, so the request isn't changed after it is sent. Of the messages it is
' only the attempts' answers and the cancellation's events. ' handed, it takes only its current attempt's answer.
class Fetch class Fetch
function new(request as Request, messagePort as object) function new(request as Request, messagePort as object)
m._request = request m._request = request
@@ -446,10 +459,14 @@ namespace HttpClient
m.StartAttempt() m.StartAttempt()
end function end function
' How long a wait on the port may last before the next HandleMessage, while the response isn't in: until the ' How long a wait on the port may last before the next HandleMessage: until the attempt's deadline while it is
' attempt's deadline while it is sent, until the retry is due between attempts. At least 1, as wait(0) has no ' sent, until the retry is due between attempts, 1 once complete, as a cache hit, a request not sent and a
' cancellation before the first attempt complete with no message on the port. At least 1, as wait(0) has no
' time limit. ' time limit.
function MaxWaitMs() as integer function MaxWaitMs() as integer
if m._response <> invalid
return 1
end if
if m._urlTransfer <> invalid if m._urlTransfer <> invalid
waitMs = m._attemptDeadlineMs - m._clock.TotalMilliseconds() waitMs = m._attemptDeadlineMs - m._clock.TotalMilliseconds()
else else
@@ -689,12 +706,14 @@ namespace HttpClient
end function end function
end class end class
' A fetch on a port of its own, which Await, Wait and Poll wait on. They return the same response once it is in. ' A fetch on a port of its own (Send), which Await, Wait and Poll wait on, or on a task loop's port (SendOn), whose
' Whoever sends the request takes its response or calls Cancel(): either ends the observation of its cancellation. ' messages the loop hands to Handle. Each returns the same response once it is in. Whoever sends the request takes
' its response or calls Cancel(): either ends the observation of its cancellation.
class PendingResponse class PendingResponse
function new(startedFetch as Fetch, messagePort as object, cancellation as dynamic, cancellationObserver as dynamic) function new(startedFetch as Fetch, messagePort as object, ownsPort as boolean, cancellation as dynamic, cancellationObserver as dynamic)
m._fetch = startedFetch m._fetch = startedFetch
m._messagePort = messagePort m._messagePort = messagePort
m._ownsPort = ownsPort
m._cancellation = cancellation m._cancellation = cancellation
m._cancellationObserver = cancellationObserver m._cancellationObserver = cancellationObserver
m._clock = CreateObject("roTimespan") m._clock = CreateObject("roTimespan")
@@ -716,6 +735,27 @@ namespace HttpClient
return m.WaitForResponse(0) return m.WaitForResponse(0)
end function end function
' message: what the loop took from the port, invalid when its wait timed out. Returns the response once it is
' in, invalid until then.
function Handle(message as dynamic) as dynamic
if m._response <> invalid
return m._response
end if
if type(message) = "roSGNodeEvent" and message.GetNode() = CANCELLATION_OBSERVER_ID and CancellationUtils.IsCancelled(m._cancellation)
m._fetch.Cancel()
end if
m._response = m._fetch.HandleMessage(message)
if m._response <> invalid
m.StopObservingCancellation()
end if
return m._response
end function
' How long the loop may wait on the port before the next Handle; 1 once the response is in.
function MaxWaitMs() as integer
return m._fetch.MaxWaitMs()
end function
function Cancel() as void function Cancel() as void
m._fetch.Cancel() m._fetch.Cancel()
m.StopObservingCancellation() m.StopObservingCancellation()
@@ -723,34 +763,30 @@ namespace HttpClient
' timeoutMs: -1 for as long as it takes, 0 to take only what is already on the port. ' timeoutMs: -1 for as long as it takes, 0 to take only what is already on the port.
private function WaitForResponse(timeoutMs as integer) as dynamic private function WaitForResponse(timeoutMs as integer) as dynamic
#if DEBUG
Assert.IsTrue(m._ownsPort, "Await, Wait or Poll on a SendOn fetch: they would take the loop's messages; hand them to Handle")
#end if
m._clock.Mark() m._clock.Mark()
' Messages already on the port go first: an answer there is taken even past the deadline. ' Messages already on the port go first: an answer there is taken even past the deadline.
message = m._messagePort.GetMessage() response = m.Handle(m._messagePort.GetMessage())
while m._response = invalid while response = invalid
' The port's only node events are the cancellation observer's. message = m._messagePort.GetMessage()
if type(message) = "roSGNodeEvent" and CancellationUtils.IsCancelled(m._cancellation) if message = invalid
m._fetch.Cancel() waitMs = m.MaxWaitMs()
end if if timeoutMs >= 0
m._response = m._fetch.HandleMessage(message) remainingMs = timeoutMs - m._clock.TotalMilliseconds()
if m._response = invalid if remainingMs <= 0
message = m._messagePort.GetMessage() return invalid
if message = invalid end if
waitMs = m._fetch.MaxWaitMs() if remainingMs < waitMs
if timeoutMs >= 0 waitMs = remainingMs
remainingMs = timeoutMs - m._clock.TotalMilliseconds()
if remainingMs <= 0
return invalid
end if
if remainingMs < waitMs
waitMs = remainingMs
end if
end if end if
message = wait(waitMs, m._messagePort)
end if end if
message = wait(waitMs, m._messagePort)
end if end if
response = m.Handle(message)
end while end while
m.StopObservingCancellation() return response
return m._response
end function end function
private function StopObservingCancellation() as void private function StopObservingCancellation() as void
@@ -122,6 +122,26 @@ namespace Tests
return invalid return invalid
end function end function
' Waits on the loop's own port, shared with the fetch, the way a task loop does: each wait capped by MaxWaitMs,
' every message handed to Handle, until it returns the response or limitMs passed.
function RunSharedLoop(loop as object, pending as object, limitMs as integer) as dynamic
timer = CreateObject("roTimespan")
while timer.TotalMilliseconds() < limitMs
message = wait(pending.MaxWaitMs(), loop.port)
if type(message) = "roSGNodeEvent" and message.GetField() = "ping"
loop.pings += 1
end if
response = pending.Handle(message)
if response <> invalid
return response
end if
if loop.pingEveryMessage
loop.node.ping = loop.pings + 1
end if
end while
return invalid
end function
function CacheFilePath(request as HttpClient.Request) as string function CacheFilePath(request as HttpClient.Request) as string
return HttpCache.GetFilePath(request.GetFullUrl(), request.GetHeaders(), request._saveBodyToFilePath) return HttpCache.GetFilePath(request.GetFullUrl(), request.GetHeaders(), request._saveBodyToFilePath)
end function end function
@@ -762,6 +782,8 @@ namespace Tests
cancellation.node.cancel = true cancellation.node.cancel = true
pending.Await() pending.Await()
HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await() HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await()
loop = m.CreateLoop()
m.RunSharedLoop(loop, HttpClient.Get(m.ServerUrl("/status/200")).NoCache().Cancellation(m.CreateCancellation()).SendOn(loop.port), 3000)
m.assertEqual(RunGarbageCollector().orphaned, 0) m.assertEqual(RunGarbageCollector().orphaned, 0)
end function end function
@@ -864,6 +886,114 @@ namespace Tests
m.assertTrue(loop.pings > 1) m.assertTrue(loop.pings > 1)
end function end function
@describe("HttpClient.PendingResponse on a task loop's port (SendOn)")
@it("wakes the loop as soon as the response is in, its own messages left to it")
function _()
loop = m.CreateLoop()
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/delay/200")).SendOn(loop.port)
loop.node.ping = 1
response = m.RunSharedLoop(loop, pending, 3000)
m.assertEqual(response.StatusCode(), 200)
m.AssertTook(timer, 200, 300)
m.assertEqual(loop.pings, 1)
end function
@it("times out at the deadline, its port idle or busy with the loop's messages")
function _()
for each busy in [false, true]
loop = m.CreateLoop()
loop.pingEveryMessage = busy
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(300).SendOn(loop.port)
loop.node.ping = 1
response = m.RunSharedLoop(loop, pending, 3000)
m.AssertTook(timer, 300, 400)
m.assertTrue(response.IsTimedOut())
end for
end function
@it("sends a retry when it is due")
function _()
loop = m.CreateLoop()
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/seq/sharedretry/503,200")).RetryCount(1).RetryDelayMs(300).SendOn(loop.port)
response = m.RunSharedLoop(loop, pending, 3000)
m.assertEqual(response.StatusCode(), 200)
m.AssertTook(timer, 300, 750)
m.assertEqual(m.Hits("/seq/sharedretry/503,200"), 2)
end function
@it("takes only its own answer when fetches share the port")
function _()
port = CreateObject("roMessagePort")
timer = CreateObject("roTimespan")
slow = HttpClient.Get(m.ServerUrl("/seq/sharedslow/202@500")).SendOn(port)
fast = HttpClient.Get(m.ServerUrl("/seq/sharedfast/201@100")).SendOn(port)
fastResponse = invalid
fastMs = -1
slowResponse = invalid
while slowResponse = invalid and timer.TotalMilliseconds() < 3000
waitMs = slow.MaxWaitMs()
if fastResponse = invalid and fast.MaxWaitMs() < waitMs
waitMs = fast.MaxWaitMs()
end if
message = wait(waitMs, port)
if fastResponse = invalid
fastResponse = fast.Handle(message)
if fastResponse <> invalid
fastMs = timer.TotalMilliseconds()
end if
end if
slowResponse = slow.Handle(message)
end while
m.assertEqual(fastResponse.StatusCode(), 201)
m.assertTrue(fastMs >= 100 and fastMs < 250, `fast took ${fastMs} ms`)
m.assertEqual(slowResponse.StatusCode(), 202)
m.AssertTook(timer, 500, 700)
end function
@it("is cancelled at its cancellation's event, not at the loop's own node events")
function _()
cancellation = m.CreateCancellation()
loop = m.CreateLoop()
pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).SendOn(loop.port)
loop.node.ping = 1
m.assertInvalid(pending.Handle(wait(1000, loop.port)))
cancellation.node.cancel = true
m.assertTrue(pending.Handle(wait(1000, loop.port)).IsCancelled())
end function
@it("ignores another fetch's cancellation event when it has no cancellation of its own")
function _()
loop = m.CreateLoop()
cancellation = m.CreateCancellation()
cancelled = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).SendOn(loop.port)
uncancellable = HttpClient.Get(m.ServerUrl("/delay/200")).SendOn(loop.port)
cancellation.node.cancel = true
message = wait(1000, loop.port)
m.assertEqual(message.GetNode(), "HttpClient.CancellationObserver")
m.assertInvalid(uncancellable.Handle(message))
m.assertTrue(cancelled.Handle(message).IsCancelled())
m.assertEqual(m.RunSharedLoop(loop, uncancellable, 3000).StatusCode(), 200)
end function
@it("completes a cache hit, a request not sent or a cancellation before it starts with no message, MaxWaitMs 1")
function _()
port = CreateObject("roMessagePort")
cached = m.GetWithoutCacheEntry("/maxage/60/shared")
cached.Await()
cancellation = m.CreateCancellation()
cancellation.node.cancel = true
m.stubCall(HttpClient.CreateUrlTransfer, invalid)
for each pending in [cached.SendOn(port), HttpClient.Get(m.ServerUrl("/status/200")).SendOn(port), HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).SendOn(port)]
m.assertEqual(pending.MaxWaitMs(), 1)
m.assertNotInvalid(pending.Handle(invalid))
end for
m.assertInvalid(port.GetMessage())
end function
@describe("HttpClient cancellation") @describe("HttpClient cancellation")
@it("sends nothing when cancelled before Send") @it("sends nothing when cancelled before Send")
@@ -1523,6 +1653,22 @@ namespace Tests
pending.Await() pending.Await()
end function end function
@it("Await, Wait or Poll on a SendOn fetch")
function _()
port = CreateObject("roMessagePort")
pending = HttpClient.Get(m.ServerUrl("/status/200")).SendOn(port)
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Await()
end function, pending), "Await, Wait or Poll on a SendOn fetch")
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Wait(100)
end function, pending), "Await, Wait or Poll on a SendOn fetch")
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Poll()
end function, pending), "Await, Wait or Poll on a SendOn fetch")
pending.Cancel()
end function
@it("Text or Json on a response whose body was saved to a file") @it("Text or Json on a response whose body was saved to a file")
function _() function _()
response = HttpClient.Get(m.ServerUrl("/status/200")).SaveBodyToFile("tmp:/http-misuse.txt").Await() response = HttpClient.Get(m.ServerUrl("/status/200")).SaveBodyToFile("tmp:/http-misuse.txt").Await()
-6
View File
@@ -82,12 +82,6 @@ namespace Locale
ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile." ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile."
BackendSwitchedToPlayletTitle = "Backend changed" BackendSwitchedToPlayletTitle = "Backend changed"
BackendSwitchedToPlayletMessage = "Backend changed to Playlet, because no Invidious instance is set." BackendSwitchedToPlayletMessage = "Backend changed to Playlet, because no Invidious instance is set."
LoungeServiceSetupError = "Lounge service setup error"
LoungeFailedToGetScreenId = "Failed to get screen ID. Please restart Playlet to use the cast function."
LoungeNotAValidScreenId = "Not a valid screen id: %1"
LoungeFailedToGetLoungeToken = "Failed to get lounge token. Please restart Playlet to use the cast function."
LoungeInvalidResponse = "Invalid response: %1"
LoungeFailedToGetSessionData = "Failed to get session data. Please restart Playlet to use the cast function."
' YouTube login ' YouTube login
SelectServiceToLogin = "Select a service to login" SelectServiceToLogin = "Select a service to login"
LoginToYouTube = "Login to YouTube" LoginToYouTube = "Login to YouTube"