diff --git a/playlet-lib/src/components/Services/LoungeService/HttpChunkedDecoder.bs b/playlet-lib/src/components/Services/LoungeService/HttpChunkedDecoder.bs
deleted file mode 100644
index 03025717..00000000
--- a/playlet-lib/src/components/Services/LoungeService/HttpChunkedDecoder.bs
+++ /dev/null
@@ -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
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs
index 88ea8ab4..622c7af0 100644
--- a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs
@@ -1,8 +1,6 @@
-import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LoungeBackchannel.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/LoungeVideoQueue.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/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
-import "pkg:/source/utils/UrlUtils.bs"
+import "pkg:/source/utils/Types.bs"
const COMMAND_HANDLER_PREFIX = "_Handle_"
@@ -37,14 +35,14 @@ class LoungeApi
' Set by a send's failure, until the next bind.
public sessionGone = false
public tokenExpired = false
+ public backchannel as LoungeBackchannel
private ofs
- private lastProcessedCommandIndex = -1
- private backchannel
+ private messagePort
private pendingOutgoingMessages
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.videoQueueNode = videoQueueNode
m.notificationsNode = notificationsNode
@@ -55,7 +53,8 @@ class LoungeApi
m.deviceName = deviceName
m.screenName = deviceName
m.ofs = 0
- m.backchannel = invalid
+ m.messagePort = messagePort
+ m.backchannel = new LoungeBackchannel()
m.pendingOutgoingMessages = []
m.devices = {}
@@ -119,23 +118,13 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
- error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n${response.ErrorMessage()}`
- LogError(error)
- DialogUtils.ShowDialogEx({
- message: error
- title: Tr(Locale.Dialogs.LoungeServiceSetupError)
- })
+ LogError(`Failed to get lounge screen ID\n${response.ErrorMessage()}`)
return invalid
end if
id = response.Text()
- if not IsString(id)
- error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n` = Tr(Locale.Dialogs.LoungeNotAValidScreenId).Replace("%1", `${id}`)
- LogError(error)
- DialogUtils.ShowDialogEx({
- message: error
- title: Tr(Locale.Dialogs.LoungeServiceSetupError)
- })
+ if StringUtils.IsNullOrEmpty(id)
+ LogError("Failed to get lounge screen ID: empty response")
return invalid
end if
@@ -155,24 +144,14 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
- error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n${response.ErrorMessage()}`
- LogError(error)
- DialogUtils.ShowDialogEx({
- message: error
- title: Tr(Locale.Dialogs.LoungeServiceSetupError)
- })
+ LogError(`Failed to get lounge token\n${response.ErrorMessage()}`)
return invalid
end if
json = response.Json()
- screens = json.screens
+ screens = ValidAssociativeArray(json).screens
if not IsArray(screens) or screens.Count() <> 1
- error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n` + Tr(Locale.Dialogs.LoungeInvalidResponse).Replace("%1", `${json}`)
- LogError(error)
- DialogUtils.ShowDialogEx({
- message: error
- title: Tr(Locale.Dialogs.LoungeServiceSetupError)
- })
+ LogError(`Failed to get lounge token: invalid response\nBody: ${response.Text()}`)
return invalid
end if
@@ -181,8 +160,8 @@ class LoungeApi
return m.loungeToken
end function
- function GetSessionData() as boolean
- queryParams = {
+ private function BindQueryParams(loungeData as object) as object
+ return {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": "vsp"
@@ -191,13 +170,16 @@ class LoungeApi
"v": "2"
"t": "1"
"app": "lb-v4"
- "RID": "1337"
+ "name": loungeData.screenName
+ "id": loungeData.deviceId
+ "loungeIdToken": loungeData.loungeToken
+ "zx": m.Zx()
}
+ end function
- queryParams["name"] = m.screenName
- queryParams["id"] = m.deviceId
- queryParams["loungeIdToken"] = m.loungeToken
- queryParams["zx"] = m.Zx()
+ function GetSessionData() as boolean
+ queryParams = m.BindQueryParams(m)
+ queryParams["RID"] = "1337"
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
@@ -207,28 +189,16 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
- error = Tr(Locale.Dialogs.LoungeFailedToGetSessionData) + `\n${response.ErrorMessage()}`
- LogError(error)
- DialogUtils.ShowDialogEx({
- message: error
- title: Tr(Locale.Dialogs.LoungeServiceSetupError)
- })
+ LogError(`Failed to get lounge session data\n${response.ErrorMessage()}`)
return false
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.sessionGone = false
m.tokenExpired = false
messagesToSend = []
- result = LoungeFraming.Extract(body, 0)
- for each frame in result.frames
- m.ProcessFrame(frame, messagesToSend)
+ for each command in m.backchannel.StartSession(response.Text())
+ m.ProcessCommand(command, messagesToSend)
end for
if StringUtils.IsNullOrEmpty(m.sessionId) or StringUtils.IsNullOrEmpty(m.gSessionId)
LogTelemetryEvent({
@@ -241,52 +211,35 @@ class LoungeApi
return true
end function
- function FetchCommandsRpc(messagePort as object) as void
- ' Plain HTTP: LoungeBackchannel streams this response over a raw socket, which has no TLS
- baseUrl = "http://www.youtube.com/api/lounge/bc/bind"
- 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
+ function StartPoll() as void
+ queryParams = m.BindQueryParams(m)
+ queryParams["RID"] = "rpc"
queryParams["SID"] = m.sessionId
queryParams["gsessionid"] = m.gSessionId
- queryParams["zx"] = m.Zx()
+ queryParams["CI"] = "1"
+ queryParams["TYPE"] = "xmlhttp"
- url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
-
- if m.backchannel = invalid
- m.backchannel = new LoungeBackchannel()
- end if
-
- m.backchannel.Open(url, messagePort)
+ request = HttpClient.Get("https://www.youtube.com/api/lounge/bc/bind")
+ request.QueryParams(queryParams)
+ m.backchannel.Open(request, m.messagePort)
end function
- function Poll(socketMessages as object, messagesToSend as object) as boolean
- frames = m.backchannel.Poll(socketMessages)
- for each frame in frames
- m.ProcessFrame(frame, messagesToSend)
+ function HandleMessage(message as dynamic, messagesToSend as object) as void
+ for each command in m.backchannel.Handle(message)
+ m.ProcessCommand(command, messagesToSend)
end for
-
- return m.backchannel.IsOpen()
+ m.HandleSends(message)
end function
- function GetCloseInfo() as object
- if m.backchannel = invalid
- return { statusCode: 0, reason: "", target: "" }
- end if
- return { statusCode: m.backchannel.statusCode, reason: m.backchannel.closeReason, target: m.backchannel.redirectTarget }
+ function MaxWaitMs() as integer
+ waitMs = m.backchannel.MaxWaitMs()
+ for each pending in m.pendingOutgoingMessages
+ pendingWaitMs = pending.MaxWaitMs()
+ if waitMs = 0 or pendingWaitMs < waitMs
+ waitMs = pendingWaitMs
+ end if
+ end for
+ return waitMs
end function
function RefreshToken() as dynamic
@@ -303,10 +256,7 @@ class LoungeApi
end function
function Rebind(withNewToken as boolean) as boolean
- for each pending in m.pendingOutgoingMessages
- pending.Cancel()
- end for
- m.pendingOutgoingMessages = []
+ m.CancelSends()
if withNewToken
LogWarnNoTelemetry("Lounge token expired, refreshing")
@@ -319,58 +269,38 @@ class LoungeApi
return m.Bind()
end function
- function ProcessFrame(frame as string, messagesToSend as object) as void
- commands = StringUtils.ParseJsonSafe(frame)
- if not IsArray(commands)
- LogTelemetryEvent({
- 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)
+ function EndSession() as void
+ m.backchannel.Close()
+ m.CancelSends()
+ m.loungeToken = invalid
end function
- function ProcessCommands(commands as object, messagesToSend as object) as void
- for each command in commands
- if not IsArray(command) or command.Count() <> 2
- 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
+ private function CancelSends() as void
+ for each pending in m.pendingOutgoingMessages
+ pending.Cancel()
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
function HandleIgnoreCommand(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object)
@@ -387,20 +317,11 @@ class LoungeApi
LogInfo("gSessionId:", m.gSessionId)
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
-
- message = LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext)
- message["commandId"] = commandId
- messagesToSend.Push(message)
-
- message = LoungeMessages.NowPlaying(player)
- message["commandId"] = commandId
- messagesToSend.Push(message)
-
- message = LoungeMessages.OnStateChange(player)
- message["commandId"] = commandId
- messagesToSend.Push(message)
+ messagesToSend.Push(LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext))
+ messagesToSend.Push(LoungeMessages.NowPlaying(player))
+ messagesToSend.Push(LoungeMessages.OnStateChange(player))
end function
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))
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
if player = invalid
return
@@ -572,39 +493,23 @@ class LoungeApi
speed = 1.0
end if
- message = LoungeMessages.OnPlaybackSpeedChanged(speed)
- message["commandId"] = commandId
- messagesToSend.Push(message)
+ messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed))
end function
function SendMessages(messages as object) as void
if messages.Count() = 0
return
end if
- m.pendingOutgoingMessages.Push(m.SendMessagesTo(m, messages))
+ m.pendingOutgoingMessages.Push(m.SendRequest(m, messages, m.backchannel.ackedCommandIndex).SendOn(m.messagePort))
end function
- private function SendMessagesTo(loungeData as object, messages as object) as HttpClient.PendingResponse
- queryParams = {
- "device": "LOUNGE_SCREEN"
- "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
+ private function SendRequest(loungeData as object, messages as object, ackedCommandIndex as integer) as HttpClient.Request
+ queryParams = m.BindQueryParams(loungeData)
+ queryParams["RID"] = "1337"
queryParams["SID"] = loungeData.sessionId
queryParams["gsessionid"] = loungeData.gSessionId
- queryParams["zx"] = m.Zx()
- if messages[0].commandId <> invalid
- queryParams["AID"] = messages[0].commandId
+ if ackedCommandIndex >= 0
+ queryParams["AID"] = ackedCommandIndex
end if
postData = [
@@ -633,64 +538,51 @@ class LoungeApi
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
request.FormBody(postData)
- return request.Send()
+ return request
end function
- function HasPendingOutgoingMessages() as boolean
- return m.pendingOutgoingMessages.Count() > 0
- end function
-
- function ProcessPendingOutgoingMessages() as object
- 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
- })
-
+ private function HandleSends(message as dynamic) as void
+ for i = m.pendingOutgoingMessages.Count() - 1 to 0 step -1
+ response = m.pendingOutgoingMessages[i].Handle(message)
+ if response <> invalid
+ m.pendingOutgoingMessages.Delete(i)
if not response.IsSuccess()
- isGone = response.StatusCode() = 410
- 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
+ m.OnSendFailed(response)
end if
end if
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
function SaveCurrentLoungeData() as void
@@ -750,7 +642,7 @@ class LoungeApi
' This is the last message we'll be sending to this lounge.
loungeData.ofs = 99999999
' 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 class
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs b/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs
index 85a318bb..8925f39e 100644
--- a/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs
@@ -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/LoungeService.types.bs"
+import "pkg:/source/services/HttpClient.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.
-const LOUNGE_BACKCHANNEL_TIMEOUT_MS = 60000
-const LOUNGE_BACKCHANNEL_BODY_COMPACT = 32768
-const LOUNGE_BACKCHANNEL_MAX_REDIRECTS = 10
+' 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.
+' 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_POLL_TIMEOUT_MS = 40000
-' Raw socket on plain HTTP: roUrlTransfer can't read a streaming body incrementally, and
-' roStreamSocket has no TLS.
class LoungeBackchannel
public statusCode = 0
- public closeReason = ""
- public redirectTarget = ""
+ public closeReason as LoungeCloseReason
+ public ackedCommandIndex = -1
+ public stalledPolls = 0
+ public pollTimeoutMs = LOUNGE_POLL_TIMEOUT_MS
- private socket
- private decoder
- private body
- private bodyCursor = 0
- private timer
- private url = ""
- private messagePort
- private redirectCount = 0
+ private pending = invalid
+ private polledCommandIndex = -1
- function new()
- m.timer = CreateObject("roTimespan")
+ ' A new session restarts command indices from 0.
+ function StartSession(bindResponseText as string) as LoungeCommand[]
+ m.ackedCommandIndex = -1
+ m.stalledPolls = 0
+ return m.Receive(m.ExtractFrames(bindResponseText))
end function
- function Open(url as string, messagePort as object) as boolean
- 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
+ function Open(request as HttpClient.Request, messagePort as object) as void
m.statusCode = 0
- m.closeReason = ""
-
- urlObject = UrlUtils.ParseUrl(url)
- 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
+ m.closeReason = invalid
+ m.polledCommandIndex = m.ackedCommandIndex
+ m.pending = request.QueryParam("AID", m.ackedCommandIndex).NoCache().RetryCount(0).AttemptTimeoutMs(m.pollTimeoutMs).SendOn(messagePort)
end function
function Close() as void
- m.CloseWith("closed")
- end function
-
- 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
+ if m.pending <> invalid
+ m.pending.Cancel()
+ m.pending = invalid
end if
end function
- private function CompactBody() as void
- if m.bodyCursor = 0
- return
+ function IsPolling() as boolean
+ return m.pending <> invalid
+ end function
+
+ function MaxWaitMs() as integer
+ if m.pending = invalid
+ return 0
end if
- if m.bodyCursor >= m.body.Count()
- m.body.Clear()
- else if m.bodyCursor >= LOUNGE_BACKCHANNEL_BODY_COMPACT
- m.body = LoungeBytes.Tail(m.body, m.bodyCursor)
+ return m.pending.MaxWaitMs()
+ end function
+
+ 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
- return
+ m.closeReason = LoungeCloseReason.Complete
+ m.stalledPolls = 0
end if
- m.bodyCursor = 0
+ return commands
end function
- private function FollowRedirect() as object
- frames = []
-
- location = m.decoder.Location()
- if not IsString(location) or location = ""
- m.CloseWith("redirect_no_location")
- return frames
+ function CloseLabel() as string
+ if m.closeReason = LoungeCloseReason.Curl or m.closeReason = LoungeCloseReason.Http
+ return `${m.closeReason}_${Abs(m.statusCode)}`
end if
+ return m.closeReason
+ end function
- nextUrl = LoungeRedirect.Resolve(m.url, location)
- m.redirectTarget = nextUrl
-
- m.redirectCount += 1
- if m.redirectCount > LOUNGE_BACKCHANNEL_MAX_REDIRECTS
- m.CloseWith("redirect_limit")
- return frames
+ private function ExtractFrames(text as string) as object
+ body = CreateObject("roByteArray")
+ body.FromAsciiString(text)
+ result = LoungeFraming.Extract(body, 0)
+ if result.nextPos < body.Count()
+ LogTelemetryEvent({
+ level: "warning"
+ message: `Lounge answer ended mid-frame, ${body.Count() - result.nextPos} bytes left: ${text}`
+ fingerprint: "lounge-partial-frame"
+ })
end if
+ return result.frames
+ end function
- LogInfo("Lounge backchannel following redirect to", m.redirectTarget)
- m.Connect(nextUrl)
- return frames
+ private function Receive(frames as object) as LoungeCommand[]
+ commands = []
+ 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 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
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs b/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs
index 75b96bf8..0e171c21 100644
--- a/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs
@@ -6,16 +6,6 @@ namespace LoungeBytes
return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString()
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
last = bytes.Count() - 1
for i = fromIndex to last
@@ -26,8 +16,4 @@ namespace LoungeBytes
return -1
end function
- function Tail(bytes as object, fromIndex as integer) as object
- return ByteArrayUtils.Slice(bytes, fromIndex)
- end function
-
end namespace
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeService.bs b/playlet-lib/src/components/Services/LoungeService/LoungeService.bs
index 580dbb07..b425e098 100644
--- a/playlet-lib/src/components/Services/LoungeService/LoungeService.bs
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeService.bs
@@ -1,8 +1,7 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
-
-const IDLE_WAIT_MS = 60000
-const SENDS_IN_FLIGHT_WAIT_MS = 500
+import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
+import "pkg:/components/Services/LoungeService/LoungeSession.bs"
function Init()
m.top.functionName = "LoungeServiceLoop"
@@ -21,6 +20,7 @@ function StartService(_unused as dynamic) as boolean
return true
end if
+ m.top.isRunning = true
m.top.control = "run"
return true
end function
@@ -34,65 +34,83 @@ function StopService(_unused as dynamic) as void
end function
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.
' 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.
api.DisconnectFromLastLounge()
- messagePort = CreateObject("roMessagePort")
-
' We do not join a lounge until something asks us to like
' - A remote connects through DIAL
' - 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)
- 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")
+ return joinRequested
+end function
-
+function RunSession(api as LoungeApi, messagePort as object) as boolean
screenId = api.GetScreenId()
if StringUtils.IsNullOrEmpty(screenId)
- Shutdown("No screen ID found")
- return
+ LogInfo("Lounge session ended: no screen ID")
+ return false
end if
m.top.screenId = screenId
loungeToken = api.GetToken()
if StringUtils.IsNullOrEmpty(loungeToken)
- Shutdown("No lounge token found")
- return
+ LogInfo("Lounge session ended: no lounge token")
+ return false
end if
m.top.loungeToken = loungeToken
m.top.observeField("outgoingMessages", messagePort)
if not api.Bind()
- Shutdown("Failed to bind")
- return
+ LogInfo("Lounge session ended: bind failed")
+ return false
end if
- api.FetchCommandsRpc(messagePort)
+ api.StartPoll()
- m.top.shouldQuit = false
- isOpen = false
+ backchannel = api.backchannel
reconnectAttempts = 0
+ sinceDelivered = CreateObject("roTimespan")
outgoingLoungeMessages = []
portMessages = []
- socketMessages = []
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.Push(message)
+ portMessages.Push(wait(api.MaxWaitMs(), messagePort))
' 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
@@ -100,75 +118,81 @@ function LoungeServiceLoop() as void
while messagePort.PeekMessage() <> invalid
portMessages.Push(messagePort.GetMessage())
end while
+ if IsQuitRequested(portMessages)
+ return true
+ end if
' At this point:
' - 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
' - Finally, we send the outgoing messages to the lounge in one go
outgoingLoungeMessages.Clear()
- socketMessages.Clear()
-
for each portMessage in portMessages
- messageType = type(portMessage)
- if messageType = "roSocketEvent"
- socketMessages.Push(portMessage)
- else if messageType = "roSGNodeEvent"
- field = portMessage.GetField()
- if field = "outgoingMessages"
- messages = portMessage.GetData()
- outgoingLoungeMessages.Append(messages)
- end if
+ if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "outgoingMessages"
+ outgoingLoungeMessages.Append(portMessage.GetData())
end if
+ api.HandleMessage(portMessage, outgoingLoungeMessages)
end for
- isOpen = api.Poll(socketMessages, 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 not isOpen
- 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
+ if backchannel.IsPolling()
+ continue while
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
- Shutdown("Service stopped")
+ return false
end function
-function Shutdown(reason as string)
- LogInfo("Shutting down:", reason)
- m.top.unobserveField("outgoingMessages")
- m.top.isRunning = false
+function IsQuitRequested(portMessages as object) as boolean
+ for each portMessage in portMessages
+ if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "shouldQuit" and portMessage.GetData() = true
+ return true
+ end if
+ end for
+ return false
end function
' 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
return 500 + Int(Rnd(0) * windowMs)
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
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs b/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs
new file mode 100644
index 00000000..ba0807ed
--- /dev/null
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs
@@ -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
diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeSession.bs b/playlet-lib/src/components/Services/LoungeService/LoungeSession.bs
new file mode 100644
index 00000000..8fde2cfe
--- /dev/null
+++ b/playlet-lib/src/components/Services/LoungeService/LoungeSession.bs
@@ -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
diff --git a/playlet-lib/src/locale/de_DE/translations.ts b/playlet-lib/src/locale/de_DE/translations.ts
index 4c4cf149..c8b25575 100644
--- a/playlet-lib/src/locale/de_DE/translations.ts
+++ b/playlet-lib/src/locale/de_DE/translations.ts
@@ -68,14 +68,6 @@
Premieres in 1 minutePremiere in 1 Minute
-
- Lounge service setup error
- Fehler beim Setup des Lounge-Services
-
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- Lounge Token konnte nicht geladen werden. Bitte starten Sie Playlet erneut, um die Cast-Funktion nutzen zu können.
- nameName
@@ -424,22 +416,6 @@
Failed to load feedFeed konnte nicht geladen werden
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.
-
-
- Not a valid screen id: %1
- Ungültige Bildschirm-ID: %1
-
-
- Invalid response: %1
- Ungültige Antwort: %1
-
-
- Failed to get session data. Please restart Playlet to use the cast function.
- Session-Daten konnten nicht geladen werden. Bitte starten Sie Playlet neu, um die Cast-Funktion nutzen zu können.
- Invidious custom instanceBenutzerdefinierte Invidious-Instanz
diff --git a/playlet-lib/src/locale/en_US/translations.ts b/playlet-lib/src/locale/en_US/translations.ts
index bdcb9ef4..034dc50f 100644
--- a/playlet-lib/src/locale/en_US/translations.ts
+++ b/playlet-lib/src/locale/en_US/translations.ts
@@ -248,30 +248,6 @@
Backend changed to Playlet, because no Invidious instance is set.Backend changed to Playlet, because no Invidious instance is set.
-
- Lounge service setup error
- Lounge service setup error
-
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- Failed to get screen ID. Please restart Playlet to use the cast function.
-
-
- Not a valid screen id: %1
- Not a valid screen id: %1
-
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- Failed to get lounge token. Please restart Playlet to use the cast function.
-
-
- Invalid response: %1
- Invalid response: %1
-
-
- Failed to get session data. Please restart Playlet to use the cast function.
- Failed to get session data. Please restart Playlet to use the cast function.
- Select a service to loginSelect a service to login
diff --git a/playlet-lib/src/locale/es_ES/translations.ts b/playlet-lib/src/locale/es_ES/translations.ts
index 5c55899e..8417ebee 100644
--- a/playlet-lib/src/locale/es_ES/translations.ts
+++ b/playlet-lib/src/locale/es_ES/translations.ts
@@ -208,30 +208,6 @@
Failed to load feedFallo al cargar el feed
-
- Lounge service setup error
- Error de configuración del servicio Lounge
-
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.
-
-
- Not a valid screen id: %1
- Id de pantalla no válida: %1
-
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- No se ha podido obtener el token dela sala. Por favor, reinicia Playlet para utilizar la función de la transmisión.
-
-
- Failed to get session data. Please restart Playlet to use the cast function.
- No se han podido obtener los datos de la sesión. Por favor, reinicia Playlet para utilizar la función de transmisión.
-
-
- Invalid response: %1
- Respuesta no válida: %1
- Invidious custom instanceInstancia personalizada de Invidious
diff --git a/playlet-lib/src/locale/es_MX/translations.ts b/playlet-lib/src/locale/es_MX/translations.ts
index 9ebc185c..a43a34af 100644
--- a/playlet-lib/src/locale/es_MX/translations.ts
+++ b/playlet-lib/src/locale/es_MX/translations.ts
@@ -840,18 +840,6 @@
Failed to load Invidious public instancesNo se pudieron cargar las instancias públicas de Invidious
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.
-
-
- Not a valid screen id: %1
- La ID de pantalla no es válida: %1
-
-
- Invalid response: %1
- Respuesta inválida: %1
- Invidious public instancesInstancias públicas de Invidious
@@ -944,14 +932,6 @@
Latest (default)Más reciente (por defecto)
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- No se ha podido obtener el token de Lounge. Por favor reinicia Playlet para usar la función de transmión.
-
-
- Failed to get session data. Please restart Playlet to use the cast function.
- No se han podido obtener los datos de sesión. Por favor reinicia Playlet para usar la función de transmisión.
- Invidious custom instanceInstancia personalizada de Invidious
@@ -1020,10 +1000,6 @@
Invalid caption data from %1 (response is not a valid vtt file)Datos de subtítulos inválidos de %1 (la respuesta no es un archivo vtt válido)
-
- Lounge service setup error
- Error de configuración del servicio Lounge
- signupregistro
diff --git a/playlet-lib/src/locale/fr_CA/translations.ts b/playlet-lib/src/locale/fr_CA/translations.ts
index 49e4e49c..d28aec48 100644
--- a/playlet-lib/src/locale/fr_CA/translations.ts
+++ b/playlet-lib/src/locale/fr_CA/translations.ts
@@ -208,30 +208,6 @@
Failed to load feedÉchec du chargement du flux
-
- Lounge service setup error
- Erreur de configuration du service Lounge
-
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- Impossible d'obtenir l'identifiant de l'écran. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.
-
-
- Not a valid screen id: %1
- Identifiant d'écran non valide : %1
-
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- Échec de l'obtention du jeton Lounge. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.
-
-
- Invalid response: %1
- Réponse non valide : %1
-
-
- Failed to get session data. Please restart Playlet to use the cast function.
- Échec de l'obtention des données de session. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.
- Invidious custom instanceInstance personnalisée d'Invidious
diff --git a/playlet-lib/src/locale/pt_BR/translations.ts b/playlet-lib/src/locale/pt_BR/translations.ts
index 6aca1eea..58d95460 100644
--- a/playlet-lib/src/locale/pt_BR/translations.ts
+++ b/playlet-lib/src/locale/pt_BR/translations.ts
@@ -128,10 +128,6 @@
Failed to load channel %1Falha ao carregar o canal %1
-
- Failed to get lounge token. Please restart Playlet to use the cast function.
- Não conseguiu obter token lounge. Por favor, reinicie Playlet para usar a função de transmitir.
- SubscriptionsInscrições
@@ -216,18 +212,6 @@
Failed to load feedErro ao carregar o feed
-
- Lounge service setup error
- Erro ao configurar o serviço de lounge
-
-
- Failed to get screen ID. Please restart Playlet to use the cast function.
- Falha ao obter o ID da tela. Por favor, reinicie Playlet para usar a função de transmitir.
-
-
- Not a valid screen id: %1
- Não é um id de tela válido: %1
- Invidious instance to use. Example: https://example.com. Find more instances at %INVIDIOUS_PUBLIC_INSTANCES%Instância Invidious para usar. Exemplo: https://example.com. Encontre mais casos em %INVIDIOUS_PUBLIC_INSTANCES%
@@ -504,10 +488,6 @@
This will restart Playlet.Isso vai reiniciar o Playlet.
-
- Invalid response: %1
- Resposta inválida: %1
- TestTeste
@@ -712,10 +692,6 @@
Queue PlaylistLista dereprodução em fila
-
- Failed to get session data. Please restart Playlet to use the cast function.
- Não conseguimos obter dados da sessão. Por favor, reinicie Playlet para usar a função transmitir.
- Invalid JSON from %1 (couldn't read %2)JSON inválido de %1 (Não conseguiu ler %2)
diff --git a/playlet-lib/src/source/components/tests/HttpChunkedDecoder.spec.bs b/playlet-lib/src/source/components/tests/HttpChunkedDecoder.spec.bs
deleted file mode 100644
index 16a84a5f..00000000
--- a/playlet-lib/src/source/components/tests/HttpChunkedDecoder.spec.bs
+++ /dev/null
@@ -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
diff --git a/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs b/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs
new file mode 100644
index 00000000..7c029093
--- /dev/null
+++ b/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs
@@ -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
diff --git a/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs b/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs
index 6bde11ec..9013e113 100644
--- a/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs
+++ b/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs
@@ -15,18 +15,6 @@ namespace Tests
m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe)
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")
function indexOfByte()
bytes = m.Bytes("a,b,c")
@@ -35,12 +23,6 @@ namespace Tests
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1)
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
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
diff --git a/playlet-lib/src/source/components/tests/LoungeRedirect.spec.bs b/playlet-lib/src/source/components/tests/LoungeRedirect.spec.bs
deleted file mode 100644
index 2b738a49..00000000
--- a/playlet-lib/src/source/components/tests/LoungeRedirect.spec.bs
+++ /dev/null
@@ -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
diff --git a/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs b/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs
index 1923ab60..5b9bea8a 100644
--- a/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs
+++ b/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs
@@ -51,23 +51,39 @@ namespace Tests
end function
@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 _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
- results = []
+ api.StartPoll()
+ m.assertTrue(api.backchannel.IsPolling())
timer = CreateObject("roTimespan")
- while results.Count() = 0 and timer.TotalMilliseconds() < 10000
- results.Append(api.ProcessPendingOutgoingMessages())
- sleep(50)
- end while
- m.assertNotEmpty(results, "no outgoing message completed")
- for each result in results
- m.assertEqual(result.status, 200, result.error)
- end for
+ m.RunLoop(api, 50000, function(api as object) as boolean
+ return not api.backchannel.IsPolling()
+ end function)
+ m.assertEqual(api.backchannel.closeReason, LoungeCloseReason.Complete, `status ${api.backchannel.statusCode}`)
+ m.assertEqual(api.backchannel.statusCode, 200)
+ m.assertTrue(timer.TotalMilliseconds() > 5000, `answered after ${timer.TotalMilliseconds()} ms: AID didn't acknowledge the bind's commands`)
end function
@slow(30000)
@@ -77,27 +93,37 @@ namespace Tests
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
- m.assertTrue(api.HasPendingOutgoingMessages(), "the bind sent no messages")
replacedSends = []
replacedSends.Append(api.pendingOutgoingMessages)
+ m.assertNotEmpty(replacedSends, "the bind sent no messages")
m.assertTrue(api.Rebind(true), "rebind failed")
- m.assertNotEmpty(replacedSends)
for each pending in replacedSends
- m.assertTrue(pending.Poll().IsCancelled(), "a send of the replaced session was not cancelled")
+ m.assertTrue(pending.Handle(invalid).IsCancelled(), "a send of the replaced session was not cancelled")
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")
- while api.HasPendingOutgoingMessages() and timer.TotalMilliseconds() < 10000
- results.Append(api.ProcessPendingOutgoingMessages())
- sleep(50)
+ while not done(api) and timer.TotalMilliseconds() < limitMs
+ api.HandleMessage(wait(api.MaxWaitMs(), m.messagePort), [])
end while
- m.assertFalse(api.HasPendingOutgoingMessages(), "the new session's sends did not complete")
- m.assertNotEmpty(results, "the rebind sent no messages")
- for each result in results
- m.assertEqual(result.status, 200, result.error)
+ end function
+
+ private function AssertSendsSucceeded(sends as object) as void
+ 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 function
@@ -111,7 +137,8 @@ namespace Tests
queueStub = CreateObject("roSGNode", "Node")
queueStub.addFields({ hasPrevious: false, hasNext: false })
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 class
diff --git a/playlet-lib/src/source/components/tests/LoungeSession.spec.bs b/playlet-lib/src/source/components/tests/LoungeSession.spec.bs
new file mode 100644
index 00000000..adde14dd
--- /dev/null
+++ b/playlet-lib/src/source/components/tests/LoungeSession.spec.bs
@@ -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
diff --git a/playlet-lib/src/source/services/HttpClient.bs b/playlet-lib/src/source/services/HttpClient.bs
index ada779d1..6f101cfb 100644
--- a/playlet-lib/src/source/services/HttpClient.bs
+++ b/playlet-lib/src/source/services/HttpClient.bs
@@ -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.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
-' message = wait(500, port)
-' response = pending.Poll() ' at each wake: the response once it is in, up to 500ms late
+' message = wait(pending.MaxWaitMs(), port) ' wakes for the answer, the attempt's deadline or a retry
+' response = pending.Handle(message) ' the response once it is in; the loop's messages are ignored
' ... ' 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
const COMPRESSION_ENABLED = true
const DEFAULT_ATTEMPT_TIMEOUT_MS = 30000
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
' 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
' be dropped when its task ends, and its retries never run.
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.
cancellationObserver = invalid
if m._cancellation <> invalid
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
' NodeObserver to the render thread, after which each access to it is a rendezvous.
cancellationObserver.ObserveField("changed", messagePort)
@@ -397,13 +410,13 @@ namespace HttpClient
end if
startedFetch = new Fetch(m, messagePort)
startedFetch.Start()
- return new PendingResponse(startedFetch, messagePort, m._cancellation, cancellationObserver)
+ return new PendingResponse(startedFetch, messagePort, ownsPort, m._cancellation, cancellationObserver)
end function
end class
- ' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send returns.
- ' It reads the request as it goes, so the request isn't changed after it is sent. Its port is its own: it gets
- ' only the attempts' answers and the cancellation's events.
+ ' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send or SendOn
+ ' returns. It reads the request as it goes, so the request isn't changed after it is sent. Of the messages it is
+ ' handed, it takes only its current attempt's answer.
class Fetch
function new(request as Request, messagePort as object)
m._request = request
@@ -446,10 +459,14 @@ namespace HttpClient
m.StartAttempt()
end function
- ' How long a wait on the port may last before the next HandleMessage, while the response isn't in: until the
- ' attempt's deadline while it is sent, until the retry is due between attempts. At least 1, as wait(0) has no
+ ' How long a wait on the port may last before the next HandleMessage: until the attempt's deadline while it is
+ ' 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.
function MaxWaitMs() as integer
+ if m._response <> invalid
+ return 1
+ end if
if m._urlTransfer <> invalid
waitMs = m._attemptDeadlineMs - m._clock.TotalMilliseconds()
else
@@ -689,12 +706,14 @@ namespace HttpClient
end function
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.
- ' Whoever sends the request takes its response or calls Cancel(): either ends the observation of its cancellation.
+ ' 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
+ ' 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
- 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._messagePort = messagePort
+ m._ownsPort = ownsPort
m._cancellation = cancellation
m._cancellationObserver = cancellationObserver
m._clock = CreateObject("roTimespan")
@@ -716,6 +735,27 @@ namespace HttpClient
return m.WaitForResponse(0)
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
m._fetch.Cancel()
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.
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()
' Messages already on the port go first: an answer there is taken even past the deadline.
- message = m._messagePort.GetMessage()
- while m._response = invalid
- ' The port's only node events are the cancellation observer's.
- if type(message) = "roSGNodeEvent" and CancellationUtils.IsCancelled(m._cancellation)
- m._fetch.Cancel()
- end if
- m._response = m._fetch.HandleMessage(message)
- if m._response = invalid
- message = m._messagePort.GetMessage()
- if message = invalid
- waitMs = m._fetch.MaxWaitMs()
- if timeoutMs >= 0
- remainingMs = timeoutMs - m._clock.TotalMilliseconds()
- if remainingMs <= 0
- return invalid
- end if
- if remainingMs < waitMs
- waitMs = remainingMs
- end if
+ response = m.Handle(m._messagePort.GetMessage())
+ while response = invalid
+ message = m._messagePort.GetMessage()
+ if message = invalid
+ waitMs = m.MaxWaitMs()
+ if timeoutMs >= 0
+ remainingMs = timeoutMs - m._clock.TotalMilliseconds()
+ if remainingMs <= 0
+ return invalid
+ end if
+ if remainingMs < waitMs
+ waitMs = remainingMs
end if
- message = wait(waitMs, m._messagePort)
end if
+ message = wait(waitMs, m._messagePort)
end if
+ response = m.Handle(message)
end while
- m.StopObservingCancellation()
- return m._response
+ return response
end function
private function StopObservingCancellation() as void
diff --git a/playlet-lib/src/source/services/HttpClient.spec.bs b/playlet-lib/src/source/services/HttpClient.spec.bs
index 66882842..fb430d6c 100644
--- a/playlet-lib/src/source/services/HttpClient.spec.bs
+++ b/playlet-lib/src/source/services/HttpClient.spec.bs
@@ -122,6 +122,26 @@ namespace Tests
return invalid
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
return HttpCache.GetFilePath(request.GetFullUrl(), request.GetHeaders(), request._saveBodyToFilePath)
end function
@@ -762,6 +782,8 @@ namespace Tests
cancellation.node.cancel = true
pending.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)
end function
@@ -864,6 +886,114 @@ namespace Tests
m.assertTrue(loop.pings > 1)
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")
@it("sends nothing when cancelled before Send")
@@ -1523,6 +1653,22 @@ namespace Tests
pending.Await()
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")
function _()
response = HttpClient.Get(m.ServerUrl("/status/200")).SaveBodyToFile("tmp:/http-misuse.txt").Await()
diff --git a/playlet-lib/src/source/utils/Locale.bs b/playlet-lib/src/source/utils/Locale.bs
index a16c3194..fa804f93 100644
--- a/playlet-lib/src/source/utils/Locale.bs
+++ b/playlet-lib/src/source/utils/Locale.bs
@@ -82,12 +82,6 @@ namespace Locale
ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile."
BackendSwitchedToPlayletTitle = "Backend changed"
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
SelectServiceToLogin = "Select a service to login"
LoginToYouTube = "Login to YouTube"