Live stream fixes, http client rewrite, telemetry improvements

This commit is contained in:
Brahim Hadriche committed 2026-10-13 17:13:12 -04:00
1 parent df4e16b846
commit 9200bd1c74
63 files changed
+4382 -1157

No files matched your search

@@ -42,6 +42,26 @@ namespace Tests
m.assertFalse(StringUtils.IsNullOrEmpty(api.gSessionId), "no gSessionId after rebind")
end function
@slow(30000)
@it("sends the messages a bind calls for, and reports each one's status once it completes")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
results = []
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
end function
private function CreateLiveApi() as object
loungeServiceNode = CreateObject("roSGNode", "Node")
loungeServiceNode.addFields({
@@ -22,6 +22,18 @@ namespace Tests
m.assertFalse(Innertube.IsTerminalRefreshError(invalid))
end function
@describe("Innertube.RefreshRetryReason")
@it("Retries a failed refresh with its error, unless the token endpoint rejected the credential or the client")
function _()
transient = new HttpClient.Response({ statusCode: 503, text: `{"error":"backend_error"}` })
m.assertEqual(Innertube.RefreshRetryReason(transient), transient.ErrorMessage())
m.assertNotEqual(transient.ErrorMessage(), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 400, text: `{"error":"invalid_grant"}` })), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 401, text: `{"error":"invalid_client"}` })), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 200, text: `{"access_token":"ya29.abc"}` })), "")
end function
end class
end namespace
@@ -0,0 +1,104 @@
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' Responses to GET requests, kept on disk until they expire. An entry is one file: a JSON line
' { expiresAt, statusCode, headers }, then the body as is.
namespace HttpCache
' An entry per url, headers and file the body is saved to.
function GetFilePath(url as string, headers as object, bodyFilePath as dynamic) as string
key = url + FormatJson(headers)
if bodyFilePath <> invalid
key += bodyFilePath
end if
return `cachefs:/request_v3_${CryptoUtils.GetMd5(key)}.json`
end function
' The entry as { statusCode, headers, text }; invalid when there is none, it expired, or the file its body was
' saved to is gone. Such an entry, or a corrupt one, is deleted; a corrupt one warns, whether its body file exists
' or not.
function Read(filePath as string, bodyFilePath as dynamic) as dynamic
' ReadAsciiFile prints an error to the console for a file that doesn't exist.
fileSystem = CreateObject("roFileSystem")
if fileSystem = invalid or not fileSystem.Exists(filePath)
return invalid
end if
text = ReadAsciiFile(filePath)
metadataEnd = text.InStr(`\n`)
if metadataEnd = -1
LogWarn("Failed to parse cache.")
DeleteFile(filePath)
return invalid
end if
metadata = StringUtils.ParseJsonSafe(text.Left(metadataEnd))
if not IsAssociativeArray(metadata) or not IsInt(metadata.expiresAt) or not IsInt(metadata.statusCode)
LogWarn("Failed to parse metadata from cache.")
DeleteFile(filePath)
return invalid
end if
if not IsAssociativeArray(metadata.headers)
LogWarn("Failed to parse headers from cache.")
DeleteFile(filePath)
return invalid
end if
if metadata.expiresAt < CreateObject("roDateTime").AsSeconds()
DeleteFile(filePath)
return invalid
end if
if bodyFilePath <> invalid and not fileSystem.Exists(bodyFilePath)
DeleteFile(filePath)
return invalid
end if
' ParseJson's keys are case-sensitive; a response's headers aren't.
headers = {}
headers.Append(metadata.headers)
return {
statusCode: metadata.statusCode
headers: headers
text: text.Mid(metadataEnd + 1)
}
end function
' cacheSeconds: invalid for the headers' Cache-Control max-age; without one, nothing is written.
function Write(filePath as string, cacheSeconds as dynamic, statusCode as integer, headers as object, body as string) as void
if cacheSeconds = invalid
cacheSeconds = ParseMaxAgeSeconds(headers)
if cacheSeconds = invalid
return
end if
end if
metadata = FormatJson({
expiresAt: CreateObject("roDateTime").AsSeconds() + cacheSeconds
statusCode: statusCode
headers: headers
})
WriteAsciiFile(filePath, metadata + `\n` + body)
end function
' Cache-Control's max-age, invalid when absent or when no-store/no-cache forbid caching.
function ParseMaxAgeSeconds(headers as object) as dynamic
cacheControl = headers["cache-control"]
if not IsString(cacheControl)
return invalid
end if
maxAgeSeconds = invalid
for each directive in cacheControl.Split(",")
parts = directive.Trim().Split("=")
name = LCase(parts[0].Trim())
if name = "no-store" or name = "no-cache"
return invalid
else if name = "max-age" and parts.Count() > 1
maxAgeSeconds = parts[1].Trim().ToInt()
end if
end for
if maxAgeSeconds = invalid or maxAgeSeconds <= 0
return invalid
end if
return maxAgeSeconds
end function
end namespace
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
import "pkg:/source/utils/Types.bs"
namespace Tests
const HTTP_TEST_SERVER_PORT = 54125
function StartHttpTestServer() as object
server = CreateObject("roSGNode", "HttpTestServer")
server.port = HTTP_TEST_SERVER_PORT
server.control = "run"
timer = CreateObject("roTimespan")
while server.isRunning <> true and timer.TotalMilliseconds() < 3000
sleep(10)
end while
return server
end function
function StopHttpTestServer(server as object) as void
server.shouldQuit = true
timer = CreateObject("roTimespan")
while server.isRunning = true and timer.TotalMilliseconds() < 3000
sleep(10)
end while
end function
function HttpTestServerUrl(path as string) as string
return `http://127.0.0.1:${HTTP_TEST_SERVER_PORT}${path}`
end function
' How many requests the server answered for a path or url, its query included.
function HttpTestServerHits(server as object, pathOrUrl as string) as integer
path = pathOrUrl.Replace(HttpTestServerUrl(""), "")
return ValidInt(ValidAssociativeArray(server.hits)[path])
end function
end namespace
@@ -20,4 +20,23 @@ namespace Tests
return logLevel
end function
' The lines logged while action(subject) runs.
function LogLines(action as function, subject as dynamic) as string[]
logPort = CreateObject("roMessagePort")
m.global.logger.ObserveFieldScoped("logLine", logPort)
action(subject)
m.global.logger.UnobserveFieldScoped("logLine")
lines = [] as string[]
message = logPort.GetMessage()
while message <> invalid
lines.Push(message.GetData())
message = logPort.GetMessage()
end while
return lines
end function
function LogLineMessage(line as string) as string
return line.Mid(line.InStr(" ") + 1).Replace(Chr(27) + "[0m", "")
end function
end namespace
@@ -0,0 +1,228 @@
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/tests/Services/Dash/LiveHeadFakes.bs"
namespace Tests
@suite
class LiveHeadChecksTests 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()
end function
function NewChecks(answers as object) as object
checks = new LiveHeadChecks("https://example.googlevideo.com/videoplayback?rn=0")
Tests.FakeLiveHeadChecks(checks, answers)
return checks
end function
function Seqnums(heads as object) as object
seqnums = []
for each head in heads
seqnums.Push(head.seqnum)
end for
return seqnums
end function
@describe("LiveHeadChecks.Refresh")
@it("returns a check answered within the wait at once")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630 }])
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertEqual(checks.counts["answered_after_wait"], 0)
end function
@it("keeps a check unanswered within the wait in flight, and returns it at the refresh after its answer")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630, pending: true }])
m.assertEmpty(checks.Refresh())
Tests.AnswerLiveHeadChecks(checks)
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertEqual(checks.counts["answered_after_wait"], 1)
m.assertEqual(checks.inFlight.Count(), 1)
end function
@it("sends no check while LIVE_HEAD_MAX_CHECKS_IN_FLIGHT are in flight")
function _()
answers = []
for i = 0 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
answers.Push({ seqnum: 10 + i, timeMs: 18630, pending: true })
end for
checks = m.NewChecks(answers)
for i = 0 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
checks.Refresh()
end for
m.assertEqual(checks.counts["checks_sent"], LIVE_HEAD_MAX_CHECKS_IN_FLIGHT)
end function
@it("sends a check at the refresh that collects a check given up")
function _()
answers = []
for i = 1 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT + 1
answers.Push({ seqnum: -1, timeMs: invalid, pending: true })
end for
checks = m.NewChecks(answers)
for i = 1 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
checks.Refresh()
end for
oldest = checks.inFlight[0].pending.answer
oldest.pending = false
oldest.timedOut = true
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["checks_sent"], LIVE_HEAD_MAX_CHECKS_IN_FLIGHT + 1)
end function
@it("cancels the checks sent before one that answers with a head, and none sent after it")
function _()
checks = m.NewChecks([
{ seqnum: 10, timeMs: 18630, pending: true }
{ seqnum: 11, timeMs: 20630, pending: true }
{ seqnum: 12, timeMs: 22630, pending: true }
{ seqnum: 13, timeMs: 24630, pending: true }
])
for i = 1 to 3
checks.Refresh()
end for
first = checks.inFlight[0].pending.answer
second = checks.inFlight[1].pending.answer
third = checks.inFlight[2].pending.answer
second.pending = false
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertTrue(ValidBool(first.cancelled))
m.assertFalse(ValidBool(third.cancelled))
m.assertEqual(checks.inFlight.Count(), 2)
m.assertEqual(checks.counts["checks_sent"], 4)
end function
@it("cancels the checks in flight when the refresh's own check answers with a head within the wait")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630 }])
checks.Refresh()
first = checks.inFlight[0].pending.answer
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertTrue(ValidBool(first.cancelled))
m.assertEmpty(checks.inFlight)
end function
@it("cancels no check for an answer without a head")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: -1, timeMs: invalid }])
checks.Refresh()
first = checks.inFlight[0].pending.answer
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertFalse(ValidBool(first.cancelled))
m.assertEqual(checks.inFlight.Count(), 1)
end function
@it("counts a check given up as timed out, not as answered")
function _()
checks = m.NewChecks([{ seqnum: -1, timeMs: invalid, timedOut: true }])
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["timed_out"], 1)
m.assertEqual(checks.counts["answered_without_head"], 0)
end function
@it("counts an answer without a head")
function _()
checks = m.NewChecks([{ seqnum: -1, timeMs: invalid }])
checks.Refresh()
m.assertEqual(checks.counts["answered_without_head"], 1)
end function
@it("counts the longest run of refreshes that returned no head newer than the newest seen")
function _()
checks = m.NewChecks([{ seqnum: 11, timeMs: 20630 }, { seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }, { seqnum: 12, timeMs: 22630 }, { seqnum: -1, timeMs: invalid }])
for i = 1 to 5
checks.Refresh()
end for
m.assertEqual(checks.counts["refreshes_without_newer_head_max_streak"], 2)
end function
@describe("LiveHeadChecks against HttpTestServer")
' Head checks against the test server's `path`, which answers X-Head-Seqnum `seqnum` after `delayMs`.
function NewServedChecks(path as string, seqnum as integer, delayMs as integer) as object
m.ServeHead(path, seqnum, delayMs)
return new LiveHeadChecks(Tests.HttpTestServerUrl(`${path}?rn=0`))
end function
function ServeHead(path as string, seqnum as integer, delayMs as integer)
routes = {}
routes[path] = { status: 200, headers: { "X-Head-Seqnum": seqnum.ToStr(), "X-Head-Time-Millis": (seqnum * 2000).ToStr() }, delayMs: delayMs }
m.server.routes = routes
end function
@it("returns a check answered within the wait without waiting it out")
function _()
checks = m.NewServedChecks("/live/fast-head", 10, 0)
timer = CreateObject("roTimespan")
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertTrue(timer.TotalMilliseconds() < LIVE_HEAD_WAIT_MS \ 2, `${timer.TotalMilliseconds()} ms`)
end function
@it("waits LIVE_HEAD_WAIT_MS on a slow check, then returns it at the next refresh with that refresh's own check")
function _()
checks = m.NewServedChecks("/live/slow-head", 10, LIVE_HEAD_WAIT_MS + 1000)
timer = CreateObject("roTimespan")
m.assertEmpty(checks.Refresh())
elapsedMs = timer.TotalMilliseconds()
m.assertTrue(elapsedMs >= LIVE_HEAD_WAIT_MS and elapsedMs < LIVE_HEAD_WAIT_MS + 1000, `${elapsedMs} ms`)
m.assertEqual(checks.inFlight.Count(), 1)
m.ServeHead("/live/slow-head", 11, 0)
sleep(1500)
m.assertEqual(m.Seqnums(checks.Refresh()), [10, 11])
m.assertEqual(checks.inFlight.Count(), 0)
m.assertEqual(checks.counts["checks_sent"], 2)
m.assertEqual(checks.counts["answered_after_wait"], 1)
m.assertEqual(Tests.HttpTestServerHits(m.server, "/live/slow-head?rn=0"), 2)
end function
@it("sends a check answering without X-Head-* once: the next refresh checks again")
function _()
m.server.routes = { "/live/headless": { status: 200 } }
checks = new LiveHeadChecks(Tests.HttpTestServerUrl("/live/headless?rn=0"))
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["answered_without_head"], 1)
m.assertEqual(Tests.HttpTestServerHits(m.server, "/live/headless?rn=0"), 1)
end function
@it("cancels a slow check, and drops its transfer, once a later one answers with a head")
function _()
checks = m.NewServedChecks("/live/overtaken-head", 10, 10000)
m.assertEmpty(checks.Refresh())
slow = checks.inFlight[0].pending
m.ServeHead("/live/overtaken-head", 11, 0)
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertEmpty(checks.inFlight)
m.assertInvalid(slow["_fetch"]["_urlTransfer"])
m.assertTrue(slow.Poll().IsCancelled())
end function
@it("Cancel cancels the checks in flight and drops their transfers")
function _()
checks = m.NewServedChecks("/live/hung-head", 10, 10000)
checks.Refresh()
pending = checks.inFlight[0].pending
m.assertNotInvalid(pending["_fetch"]["_urlTransfer"])
checks.Cancel()
m.assertEmpty(checks.inFlight)
m.assertInvalid(pending["_fetch"]["_urlTransfer"])
m.assertTrue(pending.Poll().IsCancelled())
end function
end class
end namespace
@@ -0,0 +1,60 @@
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Types.bs"
namespace Tests
' Makes `checks` send fake head checks answering `answers` in order: { seqnum, timeMs } (seqnum -1:
' no X-Head-* headers, a 403), `pending: true` to stay unanswered until AnswerLiveHeadChecks,
' `timedOut: true` to be given up.
function FakeLiveHeadChecks(checks as object, answers as object)
checks.answers = answers
checks.Send = function() as object
return Tests.FakeLiveHeadPending(m.answers.Shift())
end function
end function
function AnswerLiveHeadChecks(checks as object)
for each check in checks.inFlight
check.pending.answer.pending = false
end for
end function
' A PendingResponse answering `answer` once it isn't pending.
function FakeLiveHeadPending(answer as object) as object
return {
answer: answer
Wait: function(_timeoutMs as integer) as dynamic
return m.Poll()
end function
Poll: function() as dynamic
if ValidBool(m.answer.pending)
return invalid
end if
return Tests.FakeLiveHeadResponse(m.answer)
end function
Cancel: function() as void
m.answer.cancelled = true
end function
}
end function
function FakeLiveHeadResponse(answer as object) as HttpClient.Response
if ValidBool(answer.timedOut)
return new HttpClient.Response({ timedOut: true })
end if
headers = {}
if answer.seqnum >= 0
headers["X-Head-Seqnum"] = answer.seqnum.ToStr()
end if
if answer.timeMs <> invalid
headers["X-Head-Time-Millis"] = FormatJson(answer.timeMs)
end if
status = 200
if answer.seqnum < 0
status = 403
end if
return new HttpClient.Response({ statusCode: status, headers: headers })
end function
end namespace
@@ -0,0 +1,61 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InnertubeRequestsTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Innertube requests")
@it("are JSON POSTs carrying the client's context and headers")
function _()
requests = [
Innertube.CreateBrowseRequest("FEwhat_to_watch", Innertube.ClientType.Tv)
Innertube.CreateNextRequest({ "videoId": "v" })
Innertube.CreateResolveUrlRequest("https://www.youtube.com/@handle")
Innertube.CreateSubscribeRequest("UC")
Innertube.CreateUnsubscribeRequest("UC")
Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, { "videoId": "v" })
Innertube.CreateGetDrmLicenceRequest({ "videoId": "v" })
]
for each request in requests
m.assertEqual(request.GetMethod(), "POST")
m.AssertContains(request.GetFullUrl(), "https://www.youtube.com/youtubei/v1/")
headers = request.GetHeaders()
m.assertEqual(headers["Content-Type"], "application/json")
m.assertNotInvalid(headers["x-youtube-client-name"])
m.assertTrue(IsAssociativeArray(StringUtils.ParseJsonSafe(request.GetTextBody()).context))
end for
end function
@it("report a parser warning with the request's curl command")
function _()
request = Innertube.CreateBrowseRequest("FEwhat_to_watch", Innertube.ClientType.Tv)
Innertube.Warning("Unknown node", { "someRenderer": {} }, { request: request })
event = m.global.telemetry.LogEvent
m.assertEqual(event.attachments[1].filename, "request.txt")
m.assertEqual(event.attachments[1].data, request.ToCurlCommand())
m.AssertContains(event.attachments[1].data, "FEwhat_to_watch")
end function
@it("tell telemetry a LOGIN_REQUIRED response came to a request sent with an access token")
function _()
request = Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, { "videoId": "v" })
request.Header("Authorization", "Bearer token")
Innertube.ParsePlayerResponseForError({ "playabilityStatus": { "status": "LOGIN_REQUIRED" } }, request)
m.AssertContains(m.global.telemetry.LogEvent.message, "LOGIN_REQUIRED: hasAccessToken=true hasCtt=false")
end function
end class
end namespace
@@ -1,10 +1,26 @@
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class LiveStreamInfoTests 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
' availabilityStartTime + the timeline offset place the first segment's start so that the head
' segment ends a cushion behind now.
function AssertAnchored(timeline as object, nowSec as integer, nowMs as integer, cushionMs as integer)
@@ -117,40 +133,62 @@ namespace Tests
m.AssertAnchored(timeline, 2000000000, 900, 5400)
end function
@describe("Innertube.GetLiveStreamInfo")
@it("reads the timeline from the head check's X-Head-* headers")
function _()
m.server.routes = { "/live/head": { status: 200, headers: { "X-Head-Seqnum": "100", "X-Head-Time-Millis": "200000" } } }
formatUrl = Tests.HttpTestServerUrl("/live/head?itag=1")
parsedResponse = {}
Innertube.GetLiveStreamInfo(parsedResponse, [{ url: formatUrl, targetDurationSec: 2 }], 0, "cpn1", invalid)
m.assertInvalid(parsedResponse.error)
m.assertEqual(parsedResponse.liveHeadSeqnum, 100)
m.assertEqual(parsedResponse.liveSegmentDurationMs, 2000)
m.assertEqual(parsedResponse.liveHeadUrl, Innertube.GetLiveHeadUrl(formatUrl, "cpn1"))
m.assertEqual(Tests.HttpTestServerHits(m.server, parsedResponse.liveHeadUrl), 1)
end function
@it("checks the head again when a response lacks X-Head-*, a success included, then fails the load with the cause")
function _()
m.server.routes = { "/live/headless": { status: 200 } }
formatUrl = Tests.HttpTestServerUrl("/live/headless?itag=1")
parsedResponse = {}
Innertube.GetLiveStreamInfo(parsedResponse, [{ url: formatUrl, targetDurationSec: 2 }], 0, invalid, invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, Innertube.GetLiveHeadUrl(formatUrl, invalid)), 2)
m.assertEqual(m.global.telemetry.LogEvent.level, "warning")
m.assertEqual(m.global.telemetry.LogEvent.message, "no X-Head-* in the response (HTTP 200)")
m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`)
end function
@describe("Innertube.ReadLiveHeadSeqnum")
@it("reads X-Head-Seqnum")
function _()
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Head-Seqnum": "9059091" })), 9059091)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({ "X-Head-Seqnum": "9059091" })), 9059091)
end function
@it("returns -1 without the header")
function _()
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Walltime-Ms": "1791305190669" })), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse(invalid)), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({ "X-Walltime-Ms": "1791305190669" })), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({})), -1)
end function
@describe("Innertube.ReadLiveHeadTimeMs")
@it("reads X-Head-Time-Millis past 32 bits")
function _()
m.assertEqual(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
m.assertEqual(Innertube.ReadLiveHeadTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
end function
@it("returns invalid without X-Head-Time-Millis, X-Head-Time-Sec or not")
function _()
m.assertInvalid(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" })))
m.assertEqual(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123" })))
m.assertInvalid(Innertube.ReadLiveHeadTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })))
m.assertEqual(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" })))
end function
function FakeResponse(headers as dynamic) as object
return {
headerData: headers
Headers: function() as dynamic
return m.headerData
end function
}
function ResponseWithHeaders(headers as object) as HttpClient.Response
return new HttpClient.Response({ headers: headers })
end function
end class
@@ -0,0 +1,101 @@
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class OTFSegmentInfoTests 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 Formats(path as string, count as integer) as object
formats = []
for i = 1 to count
formats.Push({ itag: i, url: Tests.HttpTestServerUrl(`${path}?itag=${i}`) })
end for
return formats
end function
function HitsUnder(prefix as string) as integer
hits = 0
serverHits = ValidAssociativeArray(m.server.hits)
for each path in serverHits
if path.StartsWith(prefix)
hits += serverHits[path]
end if
end for
return hits
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Innertube.OTFGetSegmentInfo")
@it("reads every format's segment durations from its init segment, saved to a file")
function _()
m.server.routes = { "/otf/init": { status: 200, body: `init bytes\r\nSegment-Count: 3\r\nSegment-Durations-Ms: 5333,5334(r=1),\r\n` } }
formats = m.Formats("/otf/init", 10)
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, invalid, "{}")
for each format in formats
m.assertEqual(format.otfSegmentDurations, [{ d: 5333 }, { d: 5334, r: 1 }])
end for
m.assertEqual(m.HitsUnder("/otf/init?"), 10)
m.assertEmpty(m.global.telemetry.LogEvent)
end function
@it("probes a DRM format whose init segment failed, and reports both")
function _()
m.server.routes = { "/otf/drm": { status: 404 } }
formats = m.Formats("/otf/drm", 1)
formats[0].drmFamilies = ["WIDEVINE"]
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, invalid, `{"player":1}`)
event = m.global.telemetry.LogEvent
m.assertEqual(event.level, "error")
m.AssertContains(event.message, "Failed to get segment info for itag 1")
m.AssertContains(event.message, "drm probe itag=1 drmFamilies=WIDEVINE")
for each variant in ["GET bare", "GET Range header", "GET range param", "GET sq=0", "POST empty range param", "POST {15:0} range param"]
m.AssertContains(event.message, `${variant} -> 404`)
end for
m.assertEqual(event.attachments[0].data, `{"player":1}`)
m.assertInvalid(formats[0].otfSegmentDurations)
end function
@it("stops at a cancellation set mid-flight")
function _()
canceller = CreateObject("roSGNode", "CancelLaterTask")
canceller.control = "run"
timer = CreateObject("roTimespan")
while canceller.cancellationNode = invalid and timer.TotalMilliseconds() < 3000
sleep(10)
end while
cancellation = CancellationUtils.CreateCancellation(canceller.cancellationNode, "cancel", true)
formats = m.Formats("/delay/3000", 10)
canceller.cancelAfterMs = 300
timer.Mark()
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, cancellation, "{}")
elapsedMs = timer.TotalMilliseconds()
m.assertTrue(elapsedMs >= 250 and elapsedMs < 800, `took ${elapsedMs} ms`)
for each format in formats
m.assertInvalid(format.otfSegmentDurations)
end for
m.assertEmpty(m.global.telemetry.LogEvent)
end function
end class
end namespace
@@ -0,0 +1,57 @@
import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class PostLiveDvrInfoTests 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
@describe("Innertube.FetchPostLiveDvrHead")
@it("reads a HEAD's status and headers")
function _()
m.server.routes = { "/dvr/head": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/head?itag=1"), invalid, "cpn1", Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 200)
m.assertTrue(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 1)
end function
@it("sends a failed HEAD once more")
function _()
m.server.routes = { "/dvr/failing": { status: 503 } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/failing?itag=1"), "0", invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 503)
m.assertFalse(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 2)
end function
@describe("Innertube.GetPostLiveDvrInfo")
@it("reads the duration and segment count from the live edge's head")
function _()
m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function
end class
end namespace
@@ -1,10 +1,116 @@
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InvidiousServiceTests 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 CreateService(backend = "invidious" as string) as object
return new Invidious.InvidiousService({
preferences: { "backend.selected": backend, "invidious.instance": Tests.HttpTestServerUrl("/inv") }
apiDefinitions: {
cached: { url: "/api/v1/cached/{id}", cacheSeconds: 60 }
flaky: { url: "/api/v1/flaky", tryCount: 2 }
video_info: { url: "/api/v1/videos/{id}", responseHandler: "VideoInfoHandler" }
}
})
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Invidious.InvidiousService.MakeRequest")
@it("serves an endpoint from the cache for its cacheSeconds")
function _()
DeleteFile(HttpCache.GetFilePath(Tests.HttpTestServerUrl("/inv/api/v1/cached/x"), {}, invalid))
m.server.routes = { "/inv/api/v1/cached/x": { status: 200, body: "[1,2]" } }
service = m.CreateService()
m.assertEqual(service.MakeRequest({ endpoint: "cached", pathParams: { id: "x" } }).result.items, [1, 2])
m.assertEqual(service.MakeRequest({ endpoint: "cached", pathParams: { id: "x" } }).result.items, [1, 2])
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/cached/x"), 1)
end function
@it("makes an endpoint's tryCount attempts, then fails with the last one's error")
function _()
m.server.routes = { "/inv/api/v1/flaky": { status: 503, body: "busy" } }
result = m.CreateService().MakeRequest({ endpoint: "flaky" })
m.assertFalse(result.success)
m.assertFalse(result.cancelled)
m.AssertContains(result.error, "StatusCode: 503")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/flaky"), 2)
end function
@it("succeeds with the placeholder a handler makes of a failed response")
function _()
m.server.routes = { "/inv/api/v1/videos/gone": { status: 500 } }
result = m.CreateService().MakeRequest({ endpoint: "video_info", pathParams: { id: "gone" } })
m.assertTrue(result.success)
m.assertEqual(result.result.items[0].videoId, "gone")
m.assertEqual(result.result.items[0].title, "[Video not available]")
end function
@it("asks the web server for the built-in backend's response, without the network")
function _()
httpServer = {
calls: []
ProcessRequestLocal: function(method as string, uri as string, _headers as object, body as string) as object
m.calls.Push({ method: method, uri: uri, body: body })
responseBody = CreateObject("roByteArray")
responseBody.FromAsciiString("[3]")
return { http_code: 200, headers: {}, body: responseBody }
end function
}
result = m.CreateService("playlet").MakeRequest({ endpoint: "cached", pathParams: { id: "local" } }, { httpServer: httpServer })
m.assertEqual(result.result.items, [3])
m.assertEqual(httpServer.calls, [{ method: "GET", uri: "/playlet-invidious-backend/api/v1/cached/local", body: "" }])
end function
@it("fails with the built-in backend's status and body")
function _()
httpServer = {
ProcessRequestLocal: function(_method as string, _uri as string, _headers as object, _body as string) as object
responseBody = CreateObject("roByteArray")
responseBody.FromAsciiString("backend down")
return { http_code: 500, headers: {}, body: responseBody }
end function
}
result = m.CreateService("playlet").MakeRequest({ endpoint: "cached", pathParams: { id: "failing" } }, { httpServer: httpServer })
m.assertFalse(result.success)
m.assertEqual(result.error, `StatusCode: 500\nBody: backend down`)
end function
@describe("Invidious.InvidiousService.GetVideoMetadata")
@it("doesn't retry a failure other than curl's HTTP/0.9 error, and reports it")
function _()
m.server.routes = { "/inv/api/v1/videos/missing": { status: 500 } }
metadata = m.CreateService().GetVideoMetadata("missing")
m.AssertContains(metadata.error, "StatusCode: 500")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/videos/missing"), 1)
event = m.global.telemetry.LogEvent
m.assertEqual(event.level, "warning")
m.assertEqual(event.message, metadata.error)
m.AssertContains(event.attachments[0].data, "/inv/api/v1/videos/missing")
end function
@describe("Invidious.NeedsLiveStreamInfo")
@it("needs the live timeline for a live response from an Invidious server")
@@ -0,0 +1,57 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockConfig.bs"
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class SponsorBlockServiceTests 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()
config = new SponsorBlock.SponsorBlockConfig()
config.config = { serverAddress: Tests.HttpTestServerUrl("/sb") }
m.service = new SponsorBlock.SponsorBlockService(config)
end function
function RouteSkipSegments(videoId as string, route as object)
routes = {}
routes[`/sb/api/skipSegments/${CryptoUtils.GetSha256(videoId).Left(4)}`] = route
m.server.routes = routes
end function
@describe("SponsorBlock.SponsorBlockService")
@it("finds the video's segments in its hash prefix's list")
function _()
m.RouteSkipSegments("video1", { status: 200, body: `[{"videoId":"other","segments":[]},{"videoId":"video1","segments":[{"segment":[1,2]}]}]` })
segments = m.service.GetSkipSegmentsForVideo("video1")
m.assertEqual(segments[0].segment, [1, 2])
end function
@it("has no segments when the server fails")
function _()
m.RouteSkipSegments("video2", { status: 500 })
m.assertInvalid(m.service.GetSkipSegmentsForVideo("video2"))
end function
@it("posts a viewed segment's UUID")
function _()
m.server.routes = { "/sb/api/viewedVideoSponsorTime": { status: 200 } }
m.service.PostSegmentViewed("segment1")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/sb/api/viewedVideoSponsorTime?UUID=segment1"), 1)
end function
end class
end namespace
@@ -0,0 +1,255 @@
import "pkg:/components/Telemetry/Sentry.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
' Nothing listens on port 1: a request there fails without an answer.
const UNREACHABLE_ENVELOPE_URL = "http://127.0.0.1:1/envelope"
' Stands in for HttpClient.CreateUrlTransfer, sending to the urls Serve set in place of the support server's and the fallback's.
function SentryUrlTransfer(url as string, headers as object, messagePort as object) as object
urls = GetGlobalAA().sentryEnvelopeUrls
url = url.Replace(SUPPORT_SERVER_ENVELOPE_URL, urls.supportServer).Replace(SENTRY_FALLBACK_ENVELOPE_URL, urls.fallback)
urlTransfer = CreateObject("roUrlTransfer")
urlTransfer.RetainBodyOnError(true)
urlTransfer.SetUrl(url)
urlTransfer.SetHeaders(headers)
urlTransfer.SetMessagePort(messagePort)
return urlTransfer
end function
@suite
class SentrySendEventsTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
' BuildEnvelope gives an event without an event_id one from the Telemetry task's m.deviceInfo.
GetGlobalAA().deviceInfo = CreateObject("roDeviceInfo")
end function
protected override function tearDown()
GetGlobalAA().Delete("deviceInfo")
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.stubCall(HttpClient.CreateUrlTransfer, Tests.SentryUrlTransfer)
end function
protected override function afterEach()
GetGlobalAA().Delete("sentryEnvelopeUrls")
end function
' Points the support server and the fallback at routes of the test server under id; invalid for one nothing answers.
function Serve(id as string, supportServerRoute as dynamic, fallbackRoute as dynamic) as void
m.supportServerPath = `/support/${id}`
m.fallbackPath = `/sentry/${id}/`
routes = {}
urls = { supportServer: UNREACHABLE_ENVELOPE_URL, fallback: UNREACHABLE_ENVELOPE_URL }
if supportServerRoute <> invalid
routes[m.supportServerPath] = supportServerRoute
urls.supportServer = Tests.HttpTestServerUrl(m.supportServerPath)
end if
if fallbackRoute <> invalid
routes[m.fallbackPath] = fallbackRoute
urls.fallback = Tests.HttpTestServerUrl(m.fallbackPath)
end if
m.server.routes = routes
GetGlobalAA().sentryEnvelopeUrls = urls
end function
' SendEvents' result for one event, and the lines it logged.
function Send(message as string) as object
result = {
events: [{
level: "error"
message: message
release: "1.0.0-test"
tags: { session_id: "session1" }
userId: "user1"
}]
retryAfter: invalid
}
result.lines = Tests.LogLines(function(result as object) as void
result.retryAfter = Sentry.SendEvents(result.events)
end function, result)
return result
end function
function SupportServerHits() as integer
return Tests.HttpTestServerHits(m.server, m.supportServerPath)
end function
function FallbackHits() as integer
return Tests.HttpTestServerHits(m.server, `${m.fallbackPath}?sentry_key=${SENTRY_FALLBACK_KEY}`)
end function
function Messages(lines as string[], level as string) as string[]
messages = [] as string[]
for each line in lines
if line.InStr(`[${level}]`) <> -1
messages.Push(Tests.LogLineMessage(line))
end if
end for
return messages
end function
' The one error logged.
function ErrorLogged(lines as string[]) as string
errors = m.Messages(lines, "ERROR")
m.assertEqual(errors.Count(), 1, FormatJson(lines))
return errors[0]
end function
' The events' envelope the test server read last: one JSON item per line, ending with a line break.
function LastEnvelopeLines() as object
request = m.server.lastRequest
m.assertEqual(request.method, "POST")
m.assertEqual(request.headers["content-type"], "application/x-sentry-envelope")
return request.body.Split(`\n`)
end function
@describe("Sentry.SendEvents")
@it("sends the events to the support server, holding nothing back")
function _()
m.Serve("sent", { status: 200 }, { status: 200 })
result = m.Send("sent event")
m.assertEqual(result.retryAfter, 0)
m.assertEmpty(m.Messages(result.lines, "ERROR"))
m.assertEmpty(m.Messages(result.lines, "WARN"))
m.assertEqual(m.SupportServerHits(), 1)
m.assertEqual(m.FallbackHits(), 0)
lines = m.LastEnvelopeLines()
m.assertEqual(lines.Count(), 4)
m.assertEqual(ParseJson(lines[0]).sdk.name, "sentry.roku.playlet")
m.assertEqual(lines[1], `{"type":"event"}`)
event = ParseJson(lines[2])
m.assertEqual(event.logentry.formatted, "sent event")
m.assertEqual(event.level, "error")
m.assertEqual(event.release, "1.0.0-test")
m.assertEqual(event.tags, { session_id: "session1" })
m.assertEqual(event.user, { id: "user1" })
m.assertEqual(event.event_id, result.events[0].event_id)
m.assertEqual(lines[3], "")
end function
@it("sends the Sentry fallback, with its key, a warning that the support server is unreachable, the unsent envelope attached")
function _()
m.Serve("unreachable", invalid, { status: 200 })
result = m.Send("unsent event")
m.assertEqual(result.retryAfter, 0)
m.assertEmpty(m.Messages(result.lines, "ERROR"))
m.assertEqual(m.FallbackHits(), 1)
warningPrefix = "Support server unreachable, sending events to the Sentry fallback: "
errorMessage = invalid
for each warning in m.Messages(result.lines, "WARN")
if warning.StartsWith(warningPrefix)
errorMessage = warning.Mid(warningPrefix.Len())
end if
end for
m.assertNotInvalid(errorMessage, FormatJson(result.lines))
m.assertNotEqual(errorMessage.InStr("StatusCode: -"), -1, errorMessage)
lines = m.LastEnvelopeLines()
m.assertEqual(lines[1], `{"type":"event"}`)
event = ParseJson(lines[2])
m.assertEqual(event.logentry.formatted, `Support server unreachable: ${errorMessage}`)
m.assertEqual(event.level, "warning")
m.assertEqual(event.fingerprint, ["support server unreachable"])
m.assertEqual(event.release, "1.0.0-test")
m.assertEqual(event.tags, { session_id: "session1" })
m.assertEqual(event.user, { id: "user1" })
m.assertInvalid(event.extra)
attachment = ParseJson(lines[3])
m.assertEqual(attachment.type, "attachment")
m.assertEqual(attachment.filename, "envelope.txt")
m.assertEqual(attachment.content_type, "text/plain")
attachedOffset = lines[0].Len() + lines[1].Len() + lines[2].Len() + lines[3].Len() + 4
attached = m.server.lastRequest.body.Mid(attachedOffset)
m.assertEqual(attachment.length, attached.Len() - 1)
attachedLines = attached.Split(`\n`)
m.assertEqual(attachedLines[1], `{"type":"event"}`)
unsentEvent = ParseJson(attachedLines[2])
m.assertEqual(unsentEvent.logentry.formatted, "unsent event")
m.assertEqual(unsentEvent.event_id, result.events[0].event_id)
end function
@it("holds the events back for the fallback's Retry-After when it rate-limits them")
function _()
m.Serve("fallbackratelimited", invalid, { status: 429, headers: { "Retry-After": "45" } })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 45)
m.assertEqual(m.FallbackHits(), 1)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SENTRY_FALLBACK_ENVELOPE_URL}?sentry_key=${SENTRY_FALLBACK_KEY} Retry after 45 seconds`)
end function
@it("holds the events back for 60 seconds when the fallback fails too")
function _()
testCases = [
{ id: "answered", route: { status: 500 } }
{ id: "unreachable", route: invalid }
]
for each testCase in testCases
m.Serve(`fallbackfailed${testCase.id}`, invalid, testCase.route)
result = m.Send("failed event")
m.assertEqual(result.retryAfter, 60, testCase.id)
errorLogged = m.ErrorLogged(result.lines)
m.assertTrue(errorLogged.StartsWith(`Failed to send events to ${SENTRY_FALLBACK_ENVELOPE_URL}?sentry_key=${SENTRY_FALLBACK_KEY} `), errorLogged)
m.assertTrue(errorLogged.EndsWith(` \nRetry after 60 seconds`), errorLogged)
end for
end function
@it("holds the events back for the support server's Retry-After when it rate-limits them, sending the fallback nothing")
function _()
m.Serve("ratelimited", { status: 429, headers: { "Retry-After": "120" } }, { status: 200 })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 120)
m.assertEqual(m.SupportServerHits(), 1)
m.assertEqual(m.FallbackHits(), 0)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SUPPORT_SERVER_ENVELOPE_URL} Retry after 120 seconds`)
end function
@it("holds the events back for 60 seconds on a 429 whose Retry-After is absent, zero or a date")
function _()
testCases = [
{ id: "absent", headers: {} }
{ id: "zero", headers: { "Retry-After": "0" } }
{ id: "date", headers: { "Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT" } }
]
for each testCase in testCases
m.Serve(`ratelimited${testCase.id}`, { status: 429, headers: testCase.headers }, { status: 200 })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 60, testCase.id)
m.assertEqual(m.FallbackHits(), 0, testCase.id)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SUPPORT_SERVER_ENVELOPE_URL} Retry after 60 seconds`, testCase.id)
end for
end function
@it("holds the events back for the Retry-After of a failure the support server answers, or 60 seconds, sending the fallback nothing")
function _()
testCases = [
{ id: "500", route: { status: 500 }, retryAfter: 60 }
{ id: "503", route: { status: 503, headers: { "Retry-After": "30" } }, retryAfter: 30 }
]
for each testCase in testCases
m.Serve(`failed${testCase.id}`, testCase.route, { status: 200 })
result = m.Send("failed event")
m.assertEqual(result.retryAfter, testCase.retryAfter, testCase.id)
m.assertEqual(m.SupportServerHits(), 1, testCase.id)
m.assertEqual(m.FallbackHits(), 0, testCase.id)
errorLogged = m.ErrorLogged(result.lines)
m.assertTrue(errorLogged.StartsWith(`Failed to send events to ${SUPPORT_SERVER_ENVELOPE_URL} `), errorLogged)
m.assertNotEqual(errorLogged.InStr(`StatusCode: ${testCase.id}`), -1, errorLogged)
m.assertTrue(errorLogged.EndsWith(` \nRetry after ${testCase.retryAfter} seconds`), errorLogged)
end for
end function
end class
end namespace
@@ -85,9 +85,10 @@ namespace Tests
m.State(VideoState.Playing)
m.StartInfo("init")
summary = m.SendAt(62000)
m.assertEqual(m.SortedKeys(summary), ["backend", "first_playing_at_ms", "lifetime_ms", "metadata_done_at_ms", "outcome", "play_start_count", "play_start_infos", "playing_ms", "stream_source"])
m.assertEqual(m.SortedKeys(summary), ["backend", "first_playing_at_ms", "lifetime_ms", "metadata_done_at_ms", "outcome", "play_start_count", "play_start_infos", "playing_ms", "stream_source", "video_id"])
m.assertEqual(summary.backend, "playlet")
m.assertEqual(summary.stream_source, "adaptiveFormats")
m.assertEqual(summary.video_id, "vid1")
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.metadata_done_at_ms, 1000)
m.assertEqual(summary.first_playing_at_ms, 2000)
@@ -121,7 +122,6 @@ namespace Tests
m.assertEqual(summary.underrun_samples[9].ms, 1000)
m.assertTrue(summary.live)
m.assertFalse(summary.DoesExist("ended_in_underrun"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering whose first bufferingStatus is no underrun is not counted")
@@ -152,7 +152,7 @@ namespace Tests
m.assertEqual(summary.underrun_samples[0], { at_ms: 100, ms: 2000 })
end function
@it("a buffering with no valid bufferingStatus is counted as one, with the video id")
@it("a buffering with no valid bufferingStatus is counted as one")
function _()
m.At(1000)
m.State(VideoState.Playing)
@@ -165,7 +165,6 @@ namespace Tests
m.assertEqual(summary.bufferings_without_status_count, 1)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.playing_ms, 4850)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering cut short before any status is not counted: a pause, an error, the close")
@@ -210,7 +209,6 @@ namespace Tests
summary = m.SendAt(7000)
m.assertEqual(summary.is_underrun_change_count, 2)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a bufferingStatus outside a buffering is ignored")
@@ -273,7 +271,7 @@ namespace Tests
m.assertEqual(summary.play_start_infos[1].start_type, "cseek")
end function
@it("a video that never played: -1 for what never happened, with its video id")
@it("a video that never played: -1 for what never happened")
function _()
m.At(100)
m.State(VideoState.Buffering)
@@ -283,7 +281,6 @@ namespace Tests
m.assertFalse(summary.DoesExist("bufferings_without_status_count"), "a buffering open at the close never reached playing")
m.assertFalse(summary.DoesExist("play_start_infos"))
m.assertFalse(summary.DoesExist("playing_ms"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("DRM content from the DASH manifest url, after a retry")
@@ -316,7 +313,6 @@ namespace Tests
m.assertEqual(summary.outcome, "error")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.playing_ms, 1000)
m.assertEqual(summary.video_id, "vid1")
end function
@it("playing under the error dialog: recovered, so the error did not end it")
@@ -329,7 +325,6 @@ namespace Tests
summary = m.SendAt(4000)
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a finished video ends in finished")
@@ -342,7 +337,6 @@ namespace Tests
summary = m.SendAt(9000)
m.assertEqual(summary.outcome, "finished")
m.assertEqual(summary.playing_ms, 8000)
m.assertFalse(summary.DoesExist("video_id"), "a clean finish carries no video id")
end function
@it("heals: all counted, the first 3 sampled, no event of their own")
@@ -361,10 +355,9 @@ namespace Tests
m.assertEqual(summary.heal_count, 5)
m.assertEqual(summary.heal_samples.Count(), 3)
m.assertEqual(summary.heal_samples[0], { at_ms: 1000, source: "OnPosition", mode: TransportController.Mode.Scrub, position_ms: 51200, cursor_ms: 48000, floor_ms: -1 })
m.assertEqual(summary.video_id, "vid1")
end function
@it("tail resolves: all counted, the first 3 sampled, no event of their own, no video id")
@it("tail resolves: all counted, the first 3 sampled, no event of their own")
function _()
m.fakeTransport.isLive = true
m.fakeTransport.cursorMs = 6134000
@@ -384,7 +377,6 @@ namespace Tests
m.assertEqual(summary.tail_resolve_count, 4)
m.assertEqual(summary.tail_resolve_samples.Count(), 3)
m.assertEqual(summary.tail_resolve_samples[0], { at_ms: 1000, source: "OnVideoState", position_ms: 6137000, cursor_ms: 6134000, floor_ms: 6134000, edge_ms: 6640000 })
m.assertFalse(summary.DoesExist("video_id"))
end function
@it("no content: an unknown backend, no content fields")
@@ -396,6 +388,68 @@ namespace Tests
m.assertFalse(summary.DoesExist("stream_source"))
end function
@it("the live head check counts of the video load, without defaults, read once")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": "live1", "counts": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } }))
summary = m.SendAt(1000)
m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 })
m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_HEAD_COUNTS_PATH), "read once")
m.assertFalse(m.SendAt(2000).DoesExist("live_head"))
end function
@it("a live play without live head check counts has none")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
DeleteFile(LIVE_HEAD_COUNTS_PATH)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
end function
@it("leaves the live head check counts of another video load")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
handoff = FormatJson({ "video_load_id": "live2", "counts": { "checks_sent": 6 } })
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, handoff)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
m.assertEqual(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH), handoff)
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end function
@it("a live play: the first video segment's bitrate and the network's at the first playing")
function _()
m.fakeTransport.isLive = true
m.fakeTop.streamInfo = { measuredBitrate: 5000000, streamBitrate: 1200000 }
m.State(VideoState.Buffering)
m.assertFalse(m.recorder.OnStreamingSegment({ segType: SegmentType.Audio, segBitrateBps: 128000 }), "audio")
m.assertTrue(m.recorder.OnStreamingSegment({ segType: SegmentType.Video, segBitrateBps: 1200000 }), "video")
m.At(1000)
m.State(VideoState.Playing)
m.fakeTop.streamInfo = { measuredBitrate: 9000000 }
m.State(VideoState.Buffering)
m.State(VideoState.Playing)
summary = m.SendAt(2000)
m.assertEqual(summary.start_segment_bitrate_bps, 1200000)
m.assertEqual(summary.start_measured_bitrate_bps, 5000000)
end function
@it("a muxed segment carries video; a segment without a type does not")
function _()
m.assertFalse(m.recorder.OnStreamingSegment({ segBitrateBps: 1 }))
m.assertFalse(m.recorder.OnStreamingSegment(invalid))
m.assertTrue(m.recorder.OnStreamingSegment({ segType: SegmentType.Mux, segBitrateBps: 800000 }))
end function
@it("a live play that never streamed video omits the starting bitrates")
function _()
m.fakeTransport.isLive = true
summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("start_segment_bitrate_bps"))
m.assertFalse(summary.DoesExist("start_measured_bitrate_bps"))
end function
@it("a video error report: its level, fingerprint and the summary's error count")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet", playletStreamUrls: ["http://a", "http://b"] }
@@ -246,10 +246,8 @@ namespace Tests
"heal_samples": heals
"tail_resolve_count": tailCount
"tail_resolve_samples": tails
"video_id": "vid1"
}
if firstPlayingAtMs < 0 or underrunCount > 0 or withoutStatus > 0 or changes > 0 or errorCount > 0 or healCount > 0 or outcome = "error"
expected["video_id"] = "vid1"
end if
return m.WithoutDefaults(expected)
end function
@@ -1,11 +1,22 @@
import "pkg:/components/Web/PlayletWebServer/Middleware/DashRouter.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/tests/Services/Dash/LiveHeadFakes.bs"
namespace Tests
@suite
class DashRouterTests 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.content = CreateObject("roSGNode", "Node")
@@ -20,6 +31,10 @@ namespace Tests
})
end function
protected override function afterEach()
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end function
' What VideoContentJob sets on the player's content for a video load.
function PushLoad(videoLoadId as string, metadata as object)
m.content.metadata = metadata
@@ -61,7 +76,7 @@ namespace Tests
' A live load whose head was 2 at 2630 ms (a 0.63s first segment, then 2s: the
' load-time average is 1315 ms), with `overrides` on its metadata and head checks
' answering `heads` in order ({ seqnum, timeMs }) and always due.
' answering `heads` in order (Tests.FakeLiveHeadChecks) and always due.
function LoadLive(heads as object, overrides = {} as object)
metadata = {
videoId: "v"
@@ -77,21 +92,7 @@ namespace Tests
metadata.Append(overrides)
m.PushLoad("live1", metadata)
m.router.GetMetadata("live1")
m.router.heads = heads
m.router.headChecks = 0
m.router.CheckLiveHead = function() as object
m.headChecks += 1
head = m.heads.Shift()
head.response = {
StatusCode: function() as integer
return 403
end function
ErrorMessage: function(_includeBody = true as boolean) as string
return "Reason:Forbidden"
end function
}
return head
end function
Tests.FakeLiveHeadChecks(m.router.liveHeadChecks, heads)
end function
function RefreshDue()
@@ -117,13 +118,13 @@ namespace Tests
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: 11, timeMs: 20630 }])
m.router.RefreshLiveHead()
m.router.RefreshLiveHead()
m.assertEqual(m.router.headChecks, 1)
m.assertEqual(m.router.liveHeadChecks.counts["checks_sent"], 1)
m.assertEqual(m.router.liveHeadSeqnum, 10)
end function
@it("keeps the head on a failed check, reporting the first failure of a video load only")
function _()
m.LoadLive([{ seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }])
m.LoadLive([{ seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }])
m.global.telemetry.LogEvent = {}
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 2)
@@ -134,10 +135,54 @@ namespace Tests
' a new video load reports again
m.PushLoad("live2", { videoId: "v", adaptiveFormats: [], liveHeadUrl: "https://example.googlevideo.com/videoplayback?rn=0" })
m.router.GetMetadata("live2")
Tests.FakeLiveHeadChecks(m.router.liveHeadChecks, [{ seqnum: -1, timeMs: invalid }])
m.RefreshDue()
m.assertNotEmpty(m.global.telemetry.LogEvent)
end function
@it("takes a check answered after the wait at a later refresh")
function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630, pending: true }])
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 2)
Tests.AnswerLiveHeadChecks(m.router.liveHeadChecks)
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 10)
end function
@it("takes the newest head among the checks answered since the last refresh")
function _()
m.LoadLive([{ seqnum: 12, timeMs: 22630, pending: true }, { seqnum: 10, timeMs: 18630 }])
m.RefreshDue()
Tests.AnswerLiveHeadChecks(m.router.liveHeadChecks)
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 12)
end function
@it("a new video load cancels the checks the previous one left in flight")
function _()
m.server.routes = { "/live/hung-head": { status: 200, headers: { "X-Head-Seqnum": "10" }, delayMs: 10000 } }
m.PushLoad("live1", { videoId: "v", adaptiveFormats: [], liveHeadUrl: Tests.HttpTestServerUrl("/live/hung-head?rn=0") })
m.router.GetMetadata("live1")
m.RefreshDue()
pending = m.router.liveHeadChecks.inFlight[0].pending
m.PushMetadata("vod1", "v2")
m.router.GetMetadata("vod1")
m.assertTrue(pending.Poll().IsCancelled())
m.assertInvalid(pending["_fetch"]["_urlTransfer"])
end function
@it("writes the load's head check counts at every refresh")
function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }])
m.RefreshDue()
m.RefreshDue()
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH))
m.assertEqual(handoff["video_load_id"], "live1")
m.assertEqual(handoff["counts"]["checks_sent"], 2)
m.assertEqual(handoff["counts"]["answered_without_head"], 1)
end function
@it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead")
function _()
' the load head (2) ended at 3 x 1315; head 7 ends 10000 ms later, at 13945, but is
@@ -287,6 +332,42 @@ namespace Tests
m.assertEqual(m.router.liveLeadMs, 300)
end function
@describe("DashRouter.GenerateDashManifestAppendStoryboards")
function AppendStoryboards(path as string) as object
m.content.metadata = { storyboards: [{ interval: 2000, storyboardWidth: 5, storyboardHeight: 5, storyboardCount: 2, width: 160, height: 90, count: 40, templateUrl: "https://i.ytimg.com/sb/v/$M.jpg" }] }
response = {
SetBodyDataString: function(data as string) as void
m.body = data
end function
ContentType: function(mimeType as string) as void
m.contentType = mimeType
end function
Redirect: function(where as string) as void
m.redirect = where
end function
}
m.router.GenerateDashManifestAppendStoryboards({ request: { query: { url: Tests.HttpTestServerUrl(path) } }, response: response })
return response
end function
@it("adds the storyboards to the fetched manifest's period")
function _()
m.server.routes = { "/dash/manifest.mpd": { status: 200, body: "<MPD><Period><AdaptationSet id=""0""/></Period></MPD>" } }
response = m.AppendStoryboards("/dash/manifest.mpd")
m.assertEqual(response.http_code, 200)
m.assertEqual(response.contentType, "application/dash+xml")
m.assertTrue(response.body.StartsWith("<MPD><Period><AdaptationSet id=""0""/><AdaptationSet"), response.body)
m.assertTrue(response.body.EndsWith("</Period></MPD>"), response.body)
end function
@it("redirects to the manifest it couldn't fetch")
function _()
response = m.AppendStoryboards("/status/503")
m.assertEqual(response.redirect, Tests.HttpTestServerUrl("/status/503"))
m.assertInvalid(response.body)
end function
end class
end namespace
@@ -0,0 +1,82 @@
import "pkg:/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InnertubeRouterTests 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.router = new Http.InnertubeRouter({ sceneNodes: { innertube: invalid, profilesService: invalid } })
end function
function Proxy(args as object) as object
response = {
Json: function(value as object) as void
m.json = value
end function
Default: function(code as integer, _message as string) as void
m.code = code
end function
}
m.router.ProxyRequest({
request: {
args: args
BodyJson: function() as object
return m.args
end function
}
response: response
})
return response
end function
function UniquePath(prefix as string) as string
return prefix + CreateObject("roDeviceInfo").GetRandomUUID()
end function
@describe("Http.InnertubeRouter.ProxyRequest")
@it("sends the method, headers and body, with our User-Agent when it has none")
function _()
proxied = m.Proxy({ Method: "POST", Url: Tests.HttpTestServerUrl("/echo"), Headers: { "X-A": "1" }, Body: "body", CacheSeconds: -1 }).json
m.assertEqual(proxied.status, 200)
echo = StringUtils.ParseJsonSafe(proxied.body)
m.assertEqual(echo.method, "POST")
m.assertEqual(echo.headers["x-a"], "1")
m.assertEqual(echo.headers["user-agent"], VIDEO_PLAYER_USER_AGENT)
m.assertEqual(echo.body, "body")
end function
@it("caches a GET for its max-age, unless CacheSeconds is negative")
function _()
cached = m.UniquePath("/maxage/60/")
m.Proxy({ Url: Tests.HttpTestServerUrl(cached), Headers: {} })
m.Proxy({ Url: Tests.HttpTestServerUrl(cached), Headers: {} })
m.assertEqual(Tests.HttpTestServerHits(m.server, cached), 1)
uncached = m.UniquePath("/maxage/60/")
m.Proxy({ Url: Tests.HttpTestServerUrl(uncached), Headers: {}, CacheSeconds: -1 })
m.Proxy({ Url: Tests.HttpTestServerUrl(uncached), Headers: {}, CacheSeconds: -1 })
m.assertEqual(Tests.HttpTestServerHits(m.server, uncached), 2)
end function
@it("rejects a key it doesn't take")
function _()
m.assertEqual(m.Proxy({ Url: Tests.HttpTestServerUrl("/echo"), Headers: {}, Timeout: 1 }).code, 400)
end function
end class
end namespace