Lounge: use buffered mode, restore https connection

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

No files matched your search

@@ -1,176 +0,0 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
namespace Tests
@suite
class HttpChunkedDecoderTests extends Rooibos.BaseTestSuite
@describe("HttpChunkedDecoder.Pump")
@it("decodes a single-chunk 200 response and reaches Done")
function singleChunk()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
m.assertEqual(r.decoder.statusCode, 200)
m.assertTrue(r.decoder.IsDone())
m.assertFalse(r.decoder.IsError())
end function
@it("concatenates multiple chunks into one body")
function multipleChunks()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
' A chunk boundary need not align with a socket read: the same response delivered one byte
' per read must reassemble identically.
@it("reassembles a response delivered one byte per socket read")
function bytewise()
r = m.Drive(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`, 1)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
@it("parses a hex chunk size greater than 9")
function hexChunkSize()
payload = "0123456789abcdef" ' 16 bytes -> chunk size "10" in hex
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10\r\n` + payload + `\r\n0\r\n\r\n`)
m.assertEqual(r.body, payload)
end function
@it("ignores chunk-size extensions after a semicolon")
function chunkExtensions()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;foo=bar\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
end function
@it("extracts a chunk byte-exactly when the body holds multi-byte UTF-8")
function utf8Chunk()
' "café" is 4 characters but 5 UTF-8 bytes; the chunk size counts bytes.
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\ncafé\r\n0\r\n\r\n`)
m.assertEqual(r.body, "café")
m.assertTrue(r.decoder.IsDone())
end function
@it("flags a non-200 status as an error carrying the code")
@params("410 Gone", 410)
@params("400 Bad Request", 400)
@params("401 Unauthorized", 401)
function non200(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.errorReason, "", "an HTTP status error is fingerprinted by code, not a slug")
end function
@it("surfaces a 3xx as a redirect carrying the Location, not an error")
@params("301 Moved Permanently", 301)
@params("302 Found", 302)
@params("303 See Other", 303)
@params("307 Temporary Redirect", 307)
@params("308 Permanent Redirect", 308)
function redirect(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\nLocation: https://rr4.youtube.com/api/lounge/bc/bind?SID=x\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.Location(), "https://rr4.youtube.com/api/lounge/bc/bind?SID=x")
end function
@it("treats an HTTP/1.0 307 as a redirect")
function redirectHttp10()
r = m.DecodeWhole(`HTTP/1.0 307 Temporary Redirect\r\nLocation: http://portal.example/login\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertEqual(r.decoder.Location(), "http://portal.example/login")
end function
@it("flags a 200 response that is not chunked as an error rather than crashing")
function nonChunked()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "unsupported_encoding")
end function
@it("flags a malformed status line with a stable error reason")
function malformedStatus()
r = m.DecodeWhole(`HELLO not http\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "malformed_status")
end function
@it("waits for more bytes when the status line is incomplete")
function partialStatus()
r = m.Drive("HTTP/1.1 20", 0)
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.body, "")
end function
@it("errors on a chunk size that overflows a 32-bit int")
function chunkOverflow()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFFF\r\nx`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "chunk_overflow")
end function
function DecodeWhole(response as string) as object
return m.Drive(response, 0)
end function
function Drive(response as string, readSize as integer) as object
decoder = new HttpChunkedDecoder()
socket = new LoungeMockSocket(m.Bytes(response), readSize)
out = CreateObject("roByteArray")
while socket.GetCountRcvBuf() > 0 and not decoder.IsDone() and not decoder.IsError() and not decoder.IsRedirect()
decoder.Pump(socket, out)
end while
return { decoder: decoder, body: out.ToAsciiString() }
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
end class
' Feeds `bytes` to the decoder, at most `readSize` per Receive (0 = all at once), so a test
' can drive fragmented reads.
class LoungeMockSocket
private data
private readPos = 0
private readSize = 0
function new(bytes as object, readSize as integer)
m.data = bytes
m.readSize = readSize
end function
function GetCountRcvBuf() as integer
remaining = m.data.Count() - m.readPos
if remaining <= 0
return 0
end if
if m.readSize > 0 and m.readSize < remaining
return m.readSize
end if
return remaining
end function
function Receive(ba as object, index as integer, length as integer) as integer
count = 0
while count < length and m.readPos < m.data.Count()
ba[index + count] = m.data[m.readPos]
count += 1
m.readPos += 1
end while
return count
end function
end class
end namespace
@@ -0,0 +1,209 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class LoungeBackchannelTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function PollOnce(backchannel as LoungeBackchannel, path as string, route as dynamic) as object
if route <> invalid
routes = {}
routes[path] = route
m.server.routes = routes
end if
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl(path)), port)
commands = []
timer = CreateObject("roTimespan")
while backchannel.IsPolling() and timer.TotalMilliseconds() < 5000
commands.Append(backchannel.Handle(wait(backchannel.MaxWaitMs(), port)))
end while
return commands
end function
function Frame(json as string) as string
body = CreateObject("roByteArray")
body.FromAsciiString(json)
return `${body.Count()}\n${json}`
end function
@describe("LoungeBackchannel")
@it("returns the commands of a 2xx answer, complete, and acknowledges the last one in the next poll")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]\n`) + m.Frame(`[[8,["seekTo",{"newTime":"12"}]]]\n`) + `\n`
commands = m.PollOnce(backchannel, "/lounge/frames", { status: 200, body: body })
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].index, 7)
m.assertEqual(commands[0].type, "noop")
m.assertInvalid(commands[0].args)
m.assertEqual(commands[1].index, 8)
m.assertEqual(commands[1].type, "seekTo")
m.assertEqual(commands[1].args, { newTime: "12" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.statusCode, 200)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(m.global.telemetry.LogEvent)
m.PollOnce(backchannel, "/lounge/next", { status: 200, body: m.Frame(`[[9,["noop"]]]`) })
m.assertEqual(Tests.HttpTestServerHits(m.server, "/lounge/next?AID=8"), 1)
end function
@it("ends a 2xx answer without frames as empty")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/empty", { status: 200, body: "" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Empty)
end function
@it("returns the commands of the whole frames of an answer that ends mid-frame, and reports what is left")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/partial", { status: 200, body: m.Frame(`[[7,["noop"]]]`) + `40\n[[8,` })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 7)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
event = m.global.telemetry.LogEvent
m.assertEqual(event.fingerprint, "lounge-partial-frame")
m.assertTrue(event.message.InStr("7 bytes left") <> -1, event.message)
end function
@it("skips the commands it already received")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/first", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
commands = m.PollOnce(backchannel, "/lounge/resent", { status: 200, body: m.Frame(`[[7,["noop"]],[8,["play"]]]`) })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
end function
@it("acknowledges a malformed command it can read the index of, and reports it")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/malformed", { status: 200, body: m.Frame(`[[7],[8,{"not":"an array"}]]`) })
m.assertEmpty(commands)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-malformed-command")
end function
@it("ends a 2xx answer that acknowledges nothing as stalled")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]`)
m.PollOnce(backchannel, "/lounge/stalled", { status: 200, body: body })
m.assertEmpty(m.PollOnce(backchannel, "/lounge/stalled", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 1)
m.assertEqual(backchannel.ackedCommandIndex, 7)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unparseable", { status: 200, body: m.Frame(`[[8,["noop"]`) }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 2)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-unparseable-frame")
m.PollOnce(backchannel, "/lounge/unstalled", { status: 200, body: m.Frame(`[[8,["noop"]]]`) })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("restarts the acknowledged index for the session a bind starts")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/old-session", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
m.PollOnce(backchannel, "/lounge/old-session", invalid)
commands = backchannel.StartSession(m.Frame(`[[0,["c","SID"]],[1,["S","GSID"]]]`))
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].type, "c")
m.assertEqual(commands[0].args, "SID")
m.assertEqual(backchannel.ackedCommandIndex, 1)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("ends a non-2xx answer with its status")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unknownsid", { status: 400, body: "Unknown SID" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
m.assertEqual(backchannel.CloseLabel(), "http_400")
m.assertEqual(backchannel.statusCode, 400)
end function
@it("ends a poll the server drops with its curl code")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/dropped", { drop: true }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Curl)
m.assertEqual(backchannel.CloseLabel(), "curl_52")
m.assertEqual(backchannel.statusCode, HttpClient.CurlErrors.CURLE_GOT_NOTHING)
end function
@it("ends a poll the server holds past the poll timeout as timeout")
function _()
backchannel = new LoungeBackchannel()
backchannel.pollTimeoutMs = 300
m.assertEmpty(m.PollOnce(backchannel, "/delay/3000", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Timeout)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("ends a poll that can't be sent as not_sent")
function _()
backchannel = new LoungeBackchannel()
' A transfer already in progress refuses another.
busyTransfer = CreateObject("roUrlTransfer")
busyTransfer.SetUrl(Tests.HttpTestServerUrl("/delay/2000"))
busyTransfer.SetMessagePort(CreateObject("roMessagePort"))
busyTransfer.AsyncGetToString()
m.stubCall(HttpClient.CreateUrlTransfer, busyTransfer)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/not-sent", invalid))
busyTransfer.AsyncCancel()
m.assertEqual(backchannel.closeReason, LoungeCloseReason.NotSent)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("cancels the poll in flight when closed")
function _()
backchannel = new LoungeBackchannel()
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), port)
backchannel.Close()
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(backchannel.Handle(wait(500, port)))
m.assertInvalid(backchannel.closeReason)
end function
@it("resets the status and reason of the previous poll when it opens the next")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/gone", { status: 410, body: "" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), CreateObject("roMessagePort"))
m.assertTrue(backchannel.IsPolling())
m.assertInvalid(backchannel.closeReason)
m.assertEqual(backchannel.statusCode, 0)
end function
end class
end namespace
@@ -15,18 +15,6 @@ namespace Tests
m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe)
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)
@@ -1,44 +0,0 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
namespace Tests
@suite
class LoungeRedirectTests extends Rooibos.BaseTestSuite
@describe("LoungeRedirect.Resolve")
@it("downgrades an https target to http, keeping host, path and query")
function downgradesHttps()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "https://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
m.assertEqual(resolved, "http://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
end function
@it("keeps an http target as-is")
function keepsHttp()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/x", "http://other.host/y?z=1")
m.assertEqual(resolved, "http://other.host/y?z=1")
end function
@it("drops a default 80 or 443 port")
@params("https://host:443/p", "http://host/p")
@params("http://host:80/p", "http://host/p")
@params("http://host:8080/p", "http://host:8080/p")
function dropsDefaultPort(location as string, expected as string)
m.assertEqual(LoungeRedirect.Resolve("http://www.youtube.com/x", location), expected)
end function
@it("resolves a root-relative Location against the current host")
function relativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "/api/lounge/bc/bind?SID=a&AID=5")
m.assertEqual(resolved, "http://www.youtube.com/api/lounge/bc/bind?SID=a&AID=5")
end function
@it("prefixes a slash onto a bare relative Location")
function bareRelativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind", "elsewhere?x=1")
m.assertEqual(resolved, "http://www.youtube.com/elsewhere?x=1")
end function
end class
end namespace
@@ -51,23 +51,39 @@ namespace Tests
end function
@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
@@ -0,0 +1,63 @@
import "pkg:/components/Services/LoungeService/LoungeSession.bs"
namespace Tests
@suite
class LoungeSessionTests extends Rooibos.BaseTestSuite
@describe("LoungeSession.StepAfterPoll")
@it("polls again after a complete poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, 0), LoungeSessionStep.Poll)
end function
@it("retries a failed poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Timeout, 0, 0, false, false, 40000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Http, 503, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Empty, 200, 0, false, false, 1000), LoungeSessionStep.Retry)
end function
@it("retries the first stall, and rebinds on the second in a row")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 1, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 2, false, false, 2000), LoungeSessionStep.Rebind)
end function
@it("rebinds a session the server no longer has")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Http, 410, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, true, false, 0), LoungeSessionStep.Rebind)
end function
@it("rebinds with a new token when the token expired")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, 1000), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, true, 0), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, true, 1000), LoungeSessionStep.RebindWithNewToken)
end function
@it("drops a session that delivered no poll for the give-up time, whatever the failure")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 3, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS - 1), LoungeSessionStep.Retry)
end function
@it("never drops a session whose poll just delivered")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Poll)
end function
function step(closeReason as LoungeCloseReason, statusCode as integer, stalledPolls as integer, sessionGone as boolean, tokenExpired as boolean, msSinceDelivered as integer) as LoungeSessionStep
return LoungeSession.StepAfterPoll(closeReason, statusCode, stalledPolls, sessionGone, tokenExpired, msSinceDelivered)
end function
end class
end namespace
+72 -36
View File
@@ -23,18 +23,21 @@ import "pkg:/source/utils/UrlUtils.bs"
' response = pending.Wait(2000) ' the response, or invalid after 2s; the fetch goes on
' response = pending.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
@@ -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()
-6
View File
@@ -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"