diff --git a/CHANGELOG.md b/CHANGELOG.md index 974f405c..92944172 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Small security fixes - SponsorBlock skip looping back to the start of a segment on some devices, and overlapping segments +- Live streams buffering on slow networks ### Changed @@ -20,11 +21,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- Backend changes from Invidious to Playlet if no instance url is set. This is to avoid playback errors. +- Backend changes from Invidious to Playlet if no instance url is set. This is to avoid playback errors ### Fixed -- Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters. +- Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters ## [0.48.7] - 2026-10-05 @@ -47,7 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Issue with start up tasks that might have caused "Failed to fetch session data" errors. +- Issue with start up tasks that might have caused "Failed to fetch session data" errors ## [0.48.4] - 2026-09-24 @@ -61,7 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Display issues for 720p devices - Attempt to fix session data fetch errors -- Remove volume handing from cast, to avoid a possible "mute softlock" - feature will be added back later. +- Remove volume handing from cast, to avoid a possible "mute softlock" - feature will be added back later ## [0.48.2] - 2026-07-11 @@ -89,7 +90,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Trending back (Gaming and Live) for Playlet backend and Invidious - to avoid a blank home screen when not logged in. +- Trending back (Gaming and Live) for Playlet backend and Invidious - to avoid a blank home screen when not logged in ### Fixed @@ -198,7 +199,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Always use `signatureTimestamp` in `/player` calls to prevent "reload page" errors. This affects watch history. +- Always use `signatureTimestamp` in `/player` calls to prevent "reload page" errors. This affects watch history - Attempt 2 to fix watch history and watch progress ## [0.44.7] - 2026-04-23 @@ -249,7 +250,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Small change in post-live dvr detection - Issue where recommended videos are all "UPCOMING" paid content -- Errors related to loading the trending feeds. Trending will be removed from Playlet in a future release. +- Errors related to loading the trending feeds. Trending will be removed from Playlet in a future release ## [0.44.0] - 2025-11-09 @@ -534,13 +535,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Telemetry to collect anonymous diagnostics data. Can be turned off from the settings. +- Telemetry to collect anonymous diagnostics data. Can be turned off from the settings ## [0.40.15] - 2025-08-28 ### Fixed -- Shorts being merged with subscription videos, regardless of "Disable Shorts" preference. +- Shorts being merged with subscription videos, regardless of "Disable Shorts" preference - Gracefully handle STS_MISMATCH errors ## [0.40.14] - 2025-08-22 @@ -559,17 +560,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Attempt to fix `no valid bitrates` and `Sign in to confirm you're not a bot` errors. +- Attempt to fix `no valid bitrates` and `Sign in to confirm you're not a bot` errors - Introduced a "Playlet support server" to allow handling sig/nsig decoding. These are not possible to do without a Javascript execution environment, so this was necessary. - Live videos are not affected by this fix yet, but hopefully it reduce the amount of errors. - Videos longer than 5 hours now work [https://github.com/iBicha/playlet/issues/500](https://github.com/iBicha/playlet/issues/500) -- Age restricted videos should play normally if logged in using a YouTube account. +- Age restricted videos should play normally if logged in using a YouTube account ## [0.40.10] - 2025-07-19 ### Added -- An option to export Playlet's state from the web app for easier debugging. +- An option to export Playlet's state from the web app for easier debugging - This is a zip file that contains logs, the app state, and the registry (local storage) ### Fixed @@ -618,7 +619,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [perf] Added a job system to control background tasks. +- [perf] Added a job system to control background tasks ### Fixed @@ -640,7 +641,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Added a "hint" in the error message when playing a video and login is required. +- Added a "hint" in the error message when playing a video and login is required - Various performance improvements ## [0.40.2] - 2025-06-12 @@ -765,7 +766,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [advanced users]: the Playlet web server's CORS headers are no longer set to `*`, for security reasons. +- [advanced users]: the Playlet web server's CORS headers are no longer set to `*`, for security reasons ## [0.36.7] - 2025-05-04 @@ -893,7 +894,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed -- [YouTube.js](https://github.com/LuanRT/YouTube.js) from web app. It is no longer needed, so this reduces app size. +- [YouTube.js](https://github.com/LuanRT/YouTube.js) from web app. It is no longer needed, so this reduces app size ## [0.35.0] - 2024-12-24 @@ -952,7 +953,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Improved on issue with long videos (10+ hours) showing as 2:30 only. They now show about 5 hours. +- Improved on issue with long videos (10+ hours) showing as 2:30 only. They now show about 5 hours ## [0.32.1] - 2024-12-03 @@ -975,7 +976,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Support for Trickplay thumbnails in Playlet backend. Done by parsing storyboards and injecting them into HLS manifest. +- Support for Trickplay thumbnails in Playlet backend. Done by parsing storyboards and injecting them into HLS manifest ## [0.30.0] - 2024-11-22 @@ -1044,7 +1045,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Support for casting clips from web app -- A workaround for video loading errors: uses Playlet Web app and [YouTube.js](https://github.com/LuanRT/YouTube.js) to load streaming data. This workaround is limited, and might not work. It doesn't have closed captions, nor trickplay thumbnails (storyboards). +- A workaround for video loading errors: uses Playlet Web app and [YouTube.js](https://github.com/LuanRT/YouTube.js) to load streaming data. This workaround is limited, and might not work. It doesn't have closed captions, nor trickplay thumbnails (storyboards) - **How To use**: Open the web app, click on a video, and choose "Play on (HOT FIX)". ## [0.25.6] - 2024-09-12 @@ -1231,7 +1232,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Loading Playlet lib as squashfs, with fallback to the zip file. This significantly decreases load times. +- Loading Playlet lib as squashfs, with fallback to the zip file. This significantly decreases load times ### Changed @@ -1299,12 +1300,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Support for multiple profiles. You can now use multiple Invidious accounts. +- Support for multiple profiles. You can now use multiple Invidious accounts - When a video error dialog shows, a timer with 10 seconds starts to play the next video ### Fixed -- A bug where the loading screen does not disappear if search results are empty. +- A bug where the loading screen does not disappear if search results are empty - Empty invidious instance in preferences when default instance is being used ## [0.20.2] - 2024-02-26 @@ -1350,12 +1351,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- The queue no longer contains playlists. When a playlist is added to the queue, the entire playlist is loaded. +- The queue no longer contains playlists. When a playlist is added to the queue, the entire playlist is loaded - It can take a few seconds to load large playlist before it can be added to the queue - This is done to be more compatible more the lounge, which does not contain "Playlists in the queue" concept. - The `Web App` tab is now called `Remote`. It can be used to open the web app, or connect using Lounge (cast from YouTube) - Removed `fields` from Invidious requests, as per [https://github.com/iv-org/invidious/pull/4276](https://github.com/iv-org/invidious/pull/4276) -- The `POST /api/queue/` no longer returns the current queue. Instead it returns a 204. +- The `POST /api/queue/` no longer returns the current queue. Instead it returns a 204 ### Fixed @@ -1389,7 +1390,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- A home screen editor allowing to enable/disable feeds, and change their order. +- A home screen editor allowing to enable/disable feeds, and change their order - The editor can be accessed from the Settings screen. ### Fixed @@ -1409,7 +1410,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed -- `Funny` and `News` from the Home screen. +- `Funny` and `News` from the Home screen - These are not standard feeds (like `Trending`), and are just search results for `Funny` and `News`. They were added in earlier Playlet versions to have more content in the Home screen. - If you like to add these two feeds to your bookmarks: - Search for `Funny` (or `News`) @@ -1511,7 +1512,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Bookmarks: different items can now be bookmarked, and be found in the `Bookmarks` screen. +- Bookmarks: different items can now be bookmarked, and be found in the `Bookmarks` screen Things that can be bookmarked: - A video - A channel @@ -1538,7 +1539,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Layout in channel view so that the upload time and view count of videos is visible - A few things in the logger -- A bug where channels show "0 videos". Channel handle is shown instead. +- A bug where channels show "0 videos". Channel handle is shown instead ### Changed @@ -1610,7 +1611,7 @@ This version went through a major refactor, which resulted in a different arcite ### Added -- The concept of a `Queue`. Videos can now be queued to play one after another. +- The concept of a `Queue`. Videos can now be queued to play one after another - Currently the queue is funcitonal, but no proper UI to support it, such as seeing the queue, clearing it, and so on. - UI for the `Queue` will be introduced in a future version. - Videos and playlists can be queued from the web app @@ -1648,7 +1649,7 @@ This version went through a major refactor, which resulted in a different arcite - The web server is now decoupled from Playlet specific logic - When not logged in, authenticated feed (like user Subscriptions and Playlists) show a "Login to view X" message, with a QR Code that redirects to the login screen - [Breaking change] web apis changed a bit (for example the `/api/command` endpoint is removed) refer to the [Open API spec](docs/playlet-web-api.yml) -- If the Invidious auth token is missing permissions (A token aquired using a previous version of Playlet) you will be auto logged out. +- If the Invidious auth token is missing permissions (A token aquired using a previous version of Playlet) you will be auto logged out ### Removed @@ -1660,7 +1661,7 @@ This version went through a major refactor, which resulted in a different arcite - Excessive logging without a way to toggle it, or redirect it to a file - Some unused parts of the code (Like basic auth in the server, WebSockets, RegistryRouter, Kanji QR Code) - These were unused and/or feature flagged features. Things can be restored as needed. -- The video player loading spinner when the video is minimized: this added too much hacky code with minimum value. +- The video player loading spinner when the video is minimized: this added too much hacky code with minimum value ### Fixed @@ -1672,7 +1673,7 @@ This version went through a major refactor, which resulted in a different arcite ### Added -- Support for saved playlists. By adding a playlist from a youtube channel to your Invidious profile, you can see the playlist on Playlet. +- Support for saved playlists. By adding a playlist from a youtube channel to your Invidious profile, you can see the playlist on Playlet ## [0.10.2] - 2023-07-10 @@ -1681,7 +1682,7 @@ This version went through a major refactor, which resulted in a different arcite - Links to the app info in web app - Loading indicator for search page in web app - Feedback link through email -- Scopes and expire fields to the Invidious auth token. This is to detect when a token is close to expiry, or if we have missing permissions. +- Scopes and expire fields to the Invidious auth token. This is to detect when a token is close to expiry, or if we have missing permissions ### Fixed @@ -1823,7 +1824,7 @@ This version went through a major refactor, which resulted in a different arcite ### Fixed -- Bug where playing and exiting a video too quickly would cause the video to play in the background. +- Bug where playing and exiting a video too quickly would cause the video to play in the background - Bug where logging in causes issues if a video is already playing - Bug where casting from web app while playing a video from the search - Spinner for the video @@ -1844,7 +1845,7 @@ This version went through a major refactor, which resulted in a different arcite ### Fixed -- Bug where Settings page and home page are both visible, if settings page is selected, and user logs in. +- Bug where Settings page and home page are both visible, if settings page is selected, and user logs in ## [0.3.0] - 2022-11-19 diff --git a/config/bsconfig.tests.base.jsonc b/config/bsconfig.tests.base.jsonc index 4912d0f8..21cca224 100644 --- a/config/bsconfig.tests.base.jsonc +++ b/config/bsconfig.tests.base.jsonc @@ -35,6 +35,7 @@ "rooibos": { "logLevel": 2, "tags": ["!integration"], + "isGlobalMethodMockingEnabled": true, "isRecordingCodeCoverage": false, "printTestTimes": true, "showOnlyFailures": true, diff --git a/playlet-lib/src/components/Screens/SettingsScreen/InvidiousInstance/InvidiousInstanceTesting/InvidiousInstanceTestingJob.bs b/playlet-lib/src/components/Screens/SettingsScreen/InvidiousInstance/InvidiousInstanceTesting/InvidiousInstanceTestingJob.bs index 79227f72..f18fc0e4 100644 --- a/playlet-lib/src/components/Screens/SettingsScreen/InvidiousInstance/InvidiousInstanceTesting/InvidiousInstanceTestingJob.bs +++ b/playlet-lib/src/components/Screens/SettingsScreen/InvidiousInstance/InvidiousInstanceTesting/InvidiousInstanceTestingJob.bs @@ -303,7 +303,7 @@ function CanFetchVideoThumbails(instance as string, testNode as object, cancella response = HttpClient.Get(thumbnail).NoCache().Cancellation(cancellation).Await() if not response.IsSuccess() testNode.state = "failed" - testNode.details = Tr(Locale.InvidiousTesting.ThumbnailNotReachable).Replace("%1", thumbnail) + `\n` + response.ErrorMessage(false) + testNode.details = Tr(Locale.InvidiousTesting.ThumbnailNotReachable).Replace("%1", thumbnail) + `\n` + response.ErrorMessage() return end if diff --git a/playlet-lib/src/components/Services/Dash/LiveHeadChecks.bs b/playlet-lib/src/components/Services/Dash/LiveHeadChecks.bs new file mode 100644 index 00000000..02e3a9b3 --- /dev/null +++ b/playlet-lib/src/components/Services/Dash/LiveHeadChecks.bs @@ -0,0 +1,119 @@ +import "pkg:/components/Services/Dash/LiveTimeline.types.bs" +import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" +import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/MathUtils.bs" + +' Roku waits over 10s on a manifest refresh, but the response holds every route of the web server +' meanwhile, and from 5s Roku sends a second request (measured). +const LIVE_HEAD_WAIT_MS = 2000 +' One check per LIVE_MANIFEST_REFRESH_MS over HttpClient's 30s default attempt timeout. +const LIVE_HEAD_MAX_CHECKS_IN_FLIGHT = 3 + +class LiveHeadChecks + public counts as object + + private headUrl as string + private inFlight as LiveHeadCheck[] + private refreshes as integer = 0 + private refreshesWithoutNewerHead as integer = 0 + private newestSeqnum as integer = -1 + + function new(headUrl as string) + m.headUrl = headUrl + m.inFlight = [] + m.counts = { + "checks_sent": 0 + "answered_after_wait": 0 + "timed_out": 0 + "answered_without_head": 0 + "refreshes_without_newer_head_max_streak": 0 + } + end function + + ' A check unanswered within LIVE_HEAD_WAIT_MS stays in flight; a later refresh returns its answer. A check that + ' answers with a head cancels the checks sent before it: they can only answer with an older one. + function Refresh() as LiveHeadReading[] + m.refreshes += 1 + answers = m.CollectAnswers() + if m.inFlight.Count() < LIVE_HEAD_MAX_CHECKS_IN_FLIGHT + check = { pending: m.Send(), sentAtRefresh: m.refreshes } + m.counts["checks_sent"] += 1 + response = check.pending.Wait(LIVE_HEAD_WAIT_MS) + ' Earlier checks answered during the wait. + answers.Append(m.CollectAnswers()) + if response = invalid + m.inFlight.Push(check) + else + head = m.Read(check, response) + answers.Push(head) + if head.seqnum >= 0 + m.Cancel() + end if + end if + end if + + m.refreshesWithoutNewerHead += 1 + for each head in answers + if head.seqnum > m.newestSeqnum + m.newestSeqnum = head.seqnum + m.refreshesWithoutNewerHead = 0 + end if + end for + m.counts["refreshes_without_newer_head_max_streak"] = MathUtils.Max(m.counts["refreshes_without_newer_head_max_streak"], m.refreshesWithoutNewerHead) + return answers + end function + + ' Cancels the checks in flight: the video load they were sent for is over, or a newer check answered. + function Cancel() as void + for each check in m.inFlight + check.pending.Cancel() + end for + m.inFlight = [] + end function + + private function Send() as HttpClient.PendingResponse + return Innertube.CreateLiveHeadRequest(m.headUrl).Send() + end function + + ' The answers of the checks in flight, in the order they were sent. + private function CollectAnswers() as LiveHeadReading[] + answers = [] + stillInFlight = [] + for each check in m.inFlight + response = check.pending.Poll() + if response = invalid + stillInFlight.Push(check) + else + head = m.Read(check, response) + answers.Push(head) + if head.seqnum >= 0 + for each sentBefore in stillInFlight + sentBefore.pending.Cancel() + end for + stillInFlight = [] + end if + end if + end for + m.inFlight = stillInFlight + return answers + end function + + private function Read(check as LiveHeadCheck, response as HttpClient.Response) as LiveHeadReading + head = { + seqnum: Innertube.ReadLiveHeadSeqnum(response) + timeMs: Innertube.ReadLiveHeadTimeMs(response) + response: response + } + if response.IsTimedOut() + m.counts["timed_out"] += 1 + return head + end if + if check.sentAtRefresh < m.refreshes + m.counts["answered_after_wait"] += 1 + end if + if head.seqnum < 0 + m.counts["answered_without_head"] += 1 + end if + return head + end function +end class diff --git a/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs b/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs new file mode 100644 index 00000000..a7665c61 --- /dev/null +++ b/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs @@ -0,0 +1,3 @@ +' The head check counts of the latest live video load, as { video_load_id, counts }. One file, +' overwritten by each live load: tmp:/ lasts as long as the app. +const LIVE_HEAD_COUNTS_PATH = "tmp:/live_head_counts.json" diff --git a/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs b/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs index aef9c84d..4c8bc250 100644 --- a/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs +++ b/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs @@ -1,3 +1,5 @@ +import "pkg:/source/services/HttpClient.bs" + ' Segments fromSeqnum up to the next run's fromSeqnum, each durationMs long, the first ' starting at startMs on the live timeline. A run starts at or after the previous one's end. interface LiveDurationRun @@ -12,3 +14,8 @@ interface LiveHeadReading timeMs as dynamic response as object end interface + +interface LiveHeadCheck + pending as HttpClient.PendingResponse + sentAtRefresh as integer +end interface diff --git a/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs b/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs index 4b245175..e6118c95 100644 --- a/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs @@ -5,7 +5,7 @@ import "pkg:/source/utils/StringUtils.bs" namespace Innertube - function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as object + function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as HttpClient.Request params = OptionUtils.GetOrDefault(options, "params", "") continuation = OptionUtils.GetOrDefault(options, "continuation", "") @@ -24,7 +24,7 @@ namespace Innertube end if end if - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(clienType)) return request diff --git a/playlet-lib/src/components/Services/Innertube/GetDrmLicenseEndpoint.bs b/playlet-lib/src/components/Services/Innertube/GetDrmLicenseEndpoint.bs index a2749f1b..b9b5314f 100644 --- a/playlet-lib/src/components/Services/Innertube/GetDrmLicenseEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/GetDrmLicenseEndpoint.bs @@ -1,6 +1,6 @@ namespace Innertube - function CreateGetDrmLicenceRequest(options as object) as object + function CreateGetDrmLicenceRequest(options as object) as HttpClient.Request videoId = OptionUtils.Get(options, "videoId") licenseRequest = OptionUtils.Get(options, "licenseRequest") drmParams = OptionUtils.Get(options, "drmParams") @@ -26,7 +26,7 @@ namespace Innertube "drmVideoFeature": "DRM_VIDEO_FEATURE_SDR" } - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player/get_drm_license?alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/player/get_drm_license?alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(ClientType.Tv)) if not StringUtils.IsNullOrEmpty(accessToken) diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index 9f7355d8..e61ca65c 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -23,37 +23,34 @@ namespace InnertubeService function GetVideoMetadata(videoId as string, options = invalid as object) as object options["videoId"] = videoId + if not OptionUtils.GetOrDefault(options, "fetchNext", true) + return GetPlayerMetadata(videoId, options) + end if + + raw = OptionUtils.GetOrDefault(options, "raw", false) + nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options) + nextRequest.Cancellation(OptionUtils.Get(options, "cancellation")) + if raw + nextRequest.LogCurlCommand() + end if + pendingNext = nextRequest.Send() + + return AwaitAndParseNextResponse(raw, GetPlayerMetadata(videoId, options), nextRequest, pendingNext) + end function + + ' The parsed player response (raw: { playerResponse }), or { error }. + function GetPlayerMetadata(videoId as string, options as object) as object cancellation = OptionUtils.Get(options, "cancellation") - fetchNext = OptionUtils.GetOrDefault(options, "fetchNext", true) accessToken = OptionUtils.Get(options, "accessToken") raw = OptionUtils.GetOrDefault(options, "raw", false) - nextRequest = invalid - if fetchNext - nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options) - nextRequest.Cancellation(cancellation) - if raw - nextRequest.LogCurlCommand(true) - end if - nextRequest.Send() - end if - - playerResponseJson = invalid client = Innertube.ClientType.Tv - totalPlayerRequests = 0 triedReloadRefresh = false - while true - ' We shouldn't be making more than 3 requests: - ' 1. Make request with TV client. - ' 2. Make request, but STS_MISMATCH error -> retry with new STS. - ' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs. - if totalPlayerRequests >= 3 - LogError("Too many player requests, aborting.") - return { - error: "Too many player requests" - } - end if - totalPlayerRequests += 1 + ' We shouldn't be making more than 3 requests: + ' 1. Make request with TV client. + ' 2. Make request, but STS_MISMATCH error -> retry with new STS. + ' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs. + for playerRequestCount = 1 to 3 stsResult = Innertube.GetSignatureTimestamp(cancellation) if CancellationUtils.IsCancelled(cancellation) return { @@ -70,7 +67,7 @@ namespace InnertubeService end if playerRequest.Cancellation(cancellation) if raw - playerRequest.LogCurlCommand(true) + playerRequest.LogCurlCommand() end if playerResponse = playerRequest.Await() @@ -82,11 +79,9 @@ namespace InnertubeService end if if not playerResponse.IsSuccess() - parsedResponse = { + return { error: playerResponse.ErrorMessage() } - parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest) - return parsedResponse end if playerResponseJson = playerResponse.Json() @@ -96,7 +91,7 @@ namespace InnertubeService if client = Innertube.ClientType.Tv and IsSabrLocked(playerResponseJson) LogInfo("SABR-locked response, retrying with downgraded TV client...") client = Innertube.ClientType.TvDowngraded - continue while + continue for else if client = Innertube.ClientType.TvDowngraded and not HasUsableAdaptiveUrl(playerResponseJson) LogError("Downgraded TV client did not recover SABR-withheld format URLs") end if @@ -104,18 +99,26 @@ namespace InnertubeService parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation) if parsedResponse.error = invalid - exit while + if raw + return { + "playerResponse": playerResponseJson + } + end if + if StringUtils.IsNullOrEmpty(parsedResponse.videoId) + parsedResponse["videoId"] = videoId + end if + return parsedResponse end if if parsedResponse.errorCode <> invalid if parsedResponse.errorCode = "STS_MISMATCH" LogInfo("STS_MISMATCH error, retrying...") - continue while + continue for else if parsedResponse.errorCode = "RELOAD_PAGE" and not triedReloadRefresh triedReloadRefresh = true LogInfo("RELOAD_PAGE: clearing stale STS cache and retrying...") DeleteFile("tmp:/sts_cache.json") - continue while + continue for else if parsedResponse.errorCode = "MISSING_FORMAT_FIELD" useServerDrivenAbr = `${ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])}` LogTelemetryEvent({ @@ -135,25 +138,13 @@ namespace InnertubeService end if end if - parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest) return parsedResponse - end while + end for - if raw - rawResponse = { - "playerResponse": playerResponseJson - } - rawResponse = AwaitAndParseNextResponse(fetchNext, raw, rawResponse, nextRequest) - return rawResponse - end if - - parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest) - - if StringUtils.IsNullOrEmpty(parsedResponse.videoId) - parsedResponse["videoId"] = videoId - end if - - return parsedResponse + LogError("Too many player requests, aborting.") + return { + error: "Too many player requests" + } end function ' True when the TV client's response is SABR-locked: server-driven ABR signaled with no usable @@ -186,12 +177,8 @@ namespace InnertubeService return false end function - function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object - if not fetchNext - return parsedResponse - end if - - nextResponse = nextRequest.Await() + function AwaitAndParseNextResponse(raw as boolean, parsedResponse as object, nextRequest as HttpClient.Request, pendingNext as HttpClient.PendingResponse) as object + nextResponse = pendingNext.Await() if not nextResponse.IsSuccess() if nextResponse.IsCancelled() @@ -213,7 +200,7 @@ namespace InnertubeService return parsedResponse end if - return Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse, nextResponse) + return Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse, nextRequest) end function function GetVideoInfoBatched(videoIds as object, options = invalid as object) as object @@ -272,7 +259,7 @@ namespace InnertubeService end if feeds = Innertube.ParseResponseDataForFeeds(responseData, { - response: response + request: request }) if videoIds.Count() > 1 @@ -325,8 +312,7 @@ namespace InnertubeService request.Cancellation(cancellation) if raw - request.LogCurlCommand(true) - request.NoCache() + request.LogCurlCommand() end if response = request.Await() @@ -341,7 +327,7 @@ namespace InnertubeService end if feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { - response: response + request: request disableCreatorOnTheRise: true disableShorts: disableShorts browseId: browseId @@ -395,7 +381,7 @@ namespace InnertubeService end if feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { - response: response + request: request disableShorts: disableShorts browseId: browseId }) @@ -551,8 +537,7 @@ namespace InnertubeService request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options) request.Cancellation(cancellation) if raw - request.LogCurlCommand(true) - request.NoCache() + request.LogCurlCommand() end if response = request.Await() @@ -566,7 +551,7 @@ namespace InnertubeService return response.Json() end if - result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), response) + result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), request) if result.authorId = invalid and result.error = invalid result["authorId"] = channelId end if @@ -693,8 +678,7 @@ namespace InnertubeService request.Header("Authorization", "Bearer " + accessToken) end if if raw - request.LogCurlCommand(true) - request.NoCache() + request.LogCurlCommand() end if response = request.Await() @@ -708,7 +692,7 @@ namespace InnertubeService return response.Json() end if - result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), response) + result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), request) if result.playlistId = invalid and result.error = invalid result["playlistId"] = playlistId @@ -734,8 +718,7 @@ namespace InnertubeService request = Innertube.CreateNextRequest(args) request.Cancellation(cancellation) if raw - request.LogCurlCommand(true) - request.NoCache() + request.LogCurlCommand() end if response = request.Await() @@ -749,7 +732,7 @@ namespace InnertubeService return response.Json() end if - result = Innertube.ParseMixPageResponseData(response.Json(), response) + result = Innertube.ParseMixPageResponseData(response.Json(), request) cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid diff --git a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs index 343e1003..f3d608ba 100644 --- a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs @@ -34,10 +34,12 @@ namespace Innertube headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn) request = CreateLiveHeadRequest(headUrl) - request.TryCount(2) - request.RetryCallback(function(context as object) as boolean - response = context.response - return Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid) + request.RetryCount(1) + request.RetryIf(function(response as HttpClient.Response) as string + if Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid) + return `no X-Head-* in the response (HTTP ${response.StatusCode()})` + end if + return "" end function) request.Cancellation(cancellation) response = request.Await() @@ -49,7 +51,7 @@ namespace Innertube averagedTimeMs = ReadLiveHeadTimeSecAsMs(response) end if if headSeqnum < 0 or averagedTimeMs = invalid - parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage(false)}` + parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}` return end if @@ -136,7 +138,7 @@ namespace Innertube return UrlUtils.SetQueryParams(formatUrl, queryComponents) end function - function CreateLiveHeadRequest(headUrl as string) as object + function CreateLiveHeadRequest(headUrl as string) as HttpClient.Request request = HttpClient.Head(headUrl) request.Headers({ "origin": "https://www.youtube.com" @@ -149,9 +151,9 @@ namespace Innertube ' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a ' head check can come back non-2xx yet still carry the X-Head-* headers ' (observed: one stream returns 500, another 200; both include them). - function ReadLiveHeadSeqnum(response as object) as integer + function ReadLiveHeadSeqnum(response as HttpClient.Response) as integer headers = response.Headers() - if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Seqnum") + if not headers.DoesExist("X-Head-Seqnum") return -1 end if return ValidString(headers["X-Head-Seqnum"]).ToInt() @@ -161,19 +163,15 @@ namespace Innertube ' long-running stream's (e.g. 207 days = 1.79e10 ms) overflows BrightScript's 32-bit ' int: ParseJson keeps it as a LongInteger, which .ToInt() and Cdbl() would truncate ' (measured). - function ReadLiveHeadTimeMs(response as object) as dynamic - headers = response.Headers() - if not IsAssociativeArray(headers) - return invalid - end if - return StringUtils.ParseJsonSafe(ValidString(headers["X-Head-Time-Millis"])) + function ReadLiveHeadTimeMs(response as HttpClient.Response) as dynamic + return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"])) end function ' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a ' young stream's few segments or to time the head between checks. - function ReadLiveHeadTimeSecAsMs(response as object) as dynamic + function ReadLiveHeadTimeSecAsMs(response as HttpClient.Response) as dynamic headers = response.Headers() - if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Time-Sec") + if not headers.DoesExist("X-Head-Time-Sec") return invalid end if return ValidString(headers["X-Head-Time-Sec"]).ToInt() * 1000& diff --git a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs index 91229959..b743ded1 100644 --- a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs @@ -8,7 +8,7 @@ import "pkg:/source/utils/Types.bs" namespace Innertube - function CreateNextRequest(payloadArgs as object, options = invalid as object) as object + function CreateNextRequest(payloadArgs as object, options = invalid as object) as HttpClient.Request deviceInfo = CreateObject("roDeviceInfo") context = Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, options) @@ -18,7 +18,7 @@ namespace Innertube } payload.Append(payloadArgs) - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Web)) return request @@ -34,7 +34,7 @@ namespace Innertube }) end function - function ParseInnertubeNextResponse(payload as object, parsedResponse as object, httpResponse as object) as object + function ParseInnertubeNextResponse(payload as object, parsedResponse as object, request as HttpClient.Request) as object if not IsAssociativeArray(payload) LogWarn("Invalid payload", payload) return parsedResponse @@ -49,7 +49,7 @@ namespace Innertube endscreen = playerOverlayRenderer["endScreen"] feeds = Innertube.ParseResponseDataForFeeds(endscreen, { - response: httpResponse + request: request noContainers: true }) if feeds.Count() > 0 diff --git a/playlet-lib/src/components/Services/Innertube/NodesParser.bs b/playlet-lib/src/components/Services/Innertube/NodesParser.bs index 3ff11718..626df6dc 100644 --- a/playlet-lib/src/components/Services/Innertube/NodesParser.bs +++ b/playlet-lib/src/components/Services/Innertube/NodesParser.bs @@ -2250,7 +2250,7 @@ namespace Innertube }, { filename: "request.txt" content_type: "text/plain" - data: context.response.request.ToCurlCommand() + data: context.request.ToCurlCommand() }] }) end function diff --git a/playlet-lib/src/components/Services/Innertube/OAuth.bs b/playlet-lib/src/components/Services/Innertube/OAuth.bs index 636fbcf7..c679e423 100644 --- a/playlet-lib/src/components/Services/Innertube/OAuth.bs +++ b/playlet-lib/src/components/Services/Innertube/OAuth.bs @@ -21,6 +21,14 @@ namespace Innertube return oauthError = RefreshErrorCode.InvalidGrant or oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient end function + ' A failed refresh is retried, unless the token endpoint rejected the credential or the client. + function RefreshRetryReason(response as HttpClient.Response) as string + if response.IsSuccess() or IsTerminalRefreshError(response.Json()) + return "" + end if + return response.ErrorMessage() + end function + function GetClientIdentity(cancellation = invalid as dynamic) as object request = HttpClient.Get("https://www.youtube.com/tv") request.Headers({ @@ -87,7 +95,7 @@ namespace Innertube "device_model": "ytlr::" } - request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/device/code", payload) + request = HttpClient.Post("https://www.youtube.com/o/oauth2/device/code").JsonBody(payload) request.Cancellation(cancellation) response = request.Await() @@ -123,7 +131,7 @@ namespace Innertube intervalMs = deviceAndUserCode.interval * 1000 while true - request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload) + request = HttpClient.Post("https://www.youtube.com/o/oauth2/token").JsonBody(payload) request.Cancellation(cancellation) response = request.Await() @@ -181,12 +189,10 @@ namespace Innertube "grant_type": "refresh_token" } - request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload) + request = HttpClient.Post("https://www.youtube.com/o/oauth2/token").JsonBody(payload) request.Cancellation(cancellation) - request.TryCount(3) - request.RetryCallback(function(context as object) as boolean - return not Innertube.IsTerminalRefreshError(context.response.Json()) - end function) + request.RetryCount(2) + request.RetryIf(Innertube.RefreshRetryReason) response = request.Await() if not response.IsSuccess() @@ -215,7 +221,7 @@ namespace Innertube end function function RevokeToken(token as string, cancellation = invalid as dynamic) as boolean - request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/revoke", { + request = HttpClient.Post("https://www.youtube.com/o/oauth2/revoke").JsonBody({ "token": token }) request.Cancellation(cancellation) @@ -240,7 +246,7 @@ namespace Innertube } } - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/account/accounts_list", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/account/accounts_list").JsonBody(payload) headers = { "Authorization": `Bearer ${accessToken}` } diff --git a/playlet-lib/src/components/Services/Innertube/OTFDrmProbe.bs b/playlet-lib/src/components/Services/Innertube/OTFDrmProbe.bs index 5583f2a0..aa482f66 100644 --- a/playlet-lib/src/components/Services/Innertube/OTFDrmProbe.bs +++ b/playlet-lib/src/components/Services/Innertube/OTFDrmProbe.bs @@ -29,19 +29,20 @@ namespace Innertube ' Bare and sq responses are full media on a healthy URL — stream those to files ' instead of buffering them into strings. variants = [ - { name: "GET bare", request: HttpClient.Get(url).ToFile(`${Innertube.DRM_PROBE_DIR}/bare.bin`) } + { name: "GET bare", request: HttpClient.Get(url).SaveBodyToFile(`${Innertube.DRM_PROBE_DIR}/bare.bin`) } { name: "GET Range header", request: HttpClient.Get(url).Header("Range", "bytes=0-16383") } { name: "GET range param", request: HttpClient.Get(rangeUrl) } - { name: "GET sq=0", request: HttpClient.Get(sqUrl).ToFile(`${Innertube.DRM_PROBE_DIR}/sq.bin`) } - { name: "POST empty range param", request: HttpClient.Post(rangeUrl, "") } - { name: "POST {15:0} range param", request: HttpClient.Post(rangeUrl, "").FromFile(`${Innertube.DRM_PROBE_DIR}/post_body.bin`) } + { name: "GET sq=0", request: HttpClient.Get(sqUrl).SaveBodyToFile(`${Innertube.DRM_PROBE_DIR}/sq.bin`) } + { name: "POST empty range param", request: HttpClient.Post(rangeUrl) } + { name: "POST {15:0} range param", request: HttpClient.Post(rangeUrl).FileBody(`${Innertube.DRM_PROBE_DIR}/post_body.bin`) } ] for each variant in variants variant.request.Headers(requestHeaders) - variant.request.TimeoutSeconds(Innertube.DRM_PROBE_TIMEOUT_SECONDS) + variant.request.AttemptTimeoutMs(Innertube.DRM_PROBE_TIMEOUT_SECONDS * 1000) variant.request.Cancellation(cancellation) - variant.request.Send() + variant.request.NoCache() + variant.pending = variant.request.Send() end for lines = [`drm probe itag=${format.itag} drmFamilies=${ValidArray(format.drmFamilies).Join(",")}`] @@ -62,7 +63,7 @@ namespace Innertube function DrmProbeCollect(variant as object) as string name = variant.name - response = variant.request.Await() + response = variant.pending.Await() if response.IsCancelled() return `${name} -> cancelled` @@ -72,12 +73,7 @@ namespace Innertube return `${name} -> timed out after ${Innertube.DRM_PROBE_TIMEOUT_SECONDS}s` end if - line = `${name} -> ${response.StatusCode()}` - responseHeaders = response.Headers() - if IsAssociativeArray(responseHeaders) - line += ` headers=${ToString(responseHeaders)}` - end if - return line + return `${name} -> ${response.StatusCode()} headers=${ToString(response.Headers())}` end function end namespace diff --git a/playlet-lib/src/components/Services/Innertube/OTFSegmentInfo.bs b/playlet-lib/src/components/Services/Innertube/OTFSegmentInfo.bs index c06df041..c031d183 100644 --- a/playlet-lib/src/components/Services/Innertube/OTFSegmentInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/OTFSegmentInfo.bs @@ -49,9 +49,9 @@ namespace Innertube while true while formatsToProcess.Count() > 0 and pendingFormats.Count() < OTF_MAX_REQUEST_COUNT formatToProcess = formatsToProcess.Pop() - request = OTFMakeSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation) - if request <> invalid - formatToProcess.request = request + pending = OTFSendSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation) + if pending <> invalid + formatToProcess.pending = pending pendingFormats.Push(formatToProcess) end if end while @@ -62,10 +62,13 @@ namespace Innertube pendingFormat = pendingFormats.Shift() ' returns false if processing should stop (e.g., cancelled) - if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.request, pendingFormat.filePath, segmentDurationsRegex, errors, requestHeaders, cancellation) + if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.pending, pendingFormat.filePath, segmentDurationsRegex, errors, requestHeaders, cancellation) exit while end if end while + for each pendingFormat in pendingFormats + pendingFormat.pending.Cancel() + end for fs.Delete("tmp:/otf_segments") @@ -87,7 +90,7 @@ namespace Innertube end if end function - function OTFMakeSegmentInfoRequest(format as object, filePath as string, requestHeaders as object, errors as object, cancellation as object) as object + function OTFSendSegmentInfoRequest(format as object, filePath as string, requestHeaders as object, errors as object, cancellation as object) as dynamic url = format.url if StringUtils.IsNullOrEmpty(url) errors.message += `URL is empty for itag ${format.itag}.\n` @@ -101,15 +104,14 @@ namespace Innertube request = HttpClient.Get(otfUrl) request.Headers(requestHeaders) - request.ToFile(filePath) + request.SaveBodyToFile(filePath) + request.NoCache() request.Cancellation(cancellation) - request.Send() - - return request + return request.Send() end function - function OTFProcessPendingFormat(format as object, request as object, filePath as string, segmentDurationsRegex as object, errors as object, requestHeaders as object, cancellation as object) as boolean - response = request.Await() + function OTFProcessPendingFormat(format as object, pending as HttpClient.PendingResponse, filePath as string, segmentDurationsRegex as object, errors as object, requestHeaders as object, cancellation as object) as boolean + response = pending.Await() if response.IsCancelled() return false diff --git a/playlet-lib/src/components/Services/Innertube/Parser.bs b/playlet-lib/src/components/Services/Innertube/Parser.bs index 8b9294fe..33ab4c8d 100644 --- a/playlet-lib/src/components/Services/Innertube/Parser.bs +++ b/playlet-lib/src/components/Services/Innertube/Parser.bs @@ -1,4 +1,5 @@ import "pkg:/components/Services/Innertube/NodesParser.bs" +import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" @@ -44,7 +45,7 @@ namespace Innertube return context.feeds end function - function ParseChannelPageResponseData(browseId as string, responseData as object, response as object) as object + function ParseChannelPageResponseData(browseId as string, responseData as object, request as HttpClient.Request) as object if responseData = invalid return { error: "Invalid response data" @@ -149,7 +150,7 @@ namespace Innertube continuation = invalid sortOptions = invalid feeds = ParseResponseDataForFeeds(responseData, { - response: response + request: request "currentAuthor": author "currentAuthorId": authorId browseId: browseId @@ -187,7 +188,7 @@ namespace Innertube return channel end function - function ParsePlaylistPageResponseData(browseId as string, responseData as object, response as object) as object + function ParsePlaylistPageResponseData(browseId as string, responseData as object, request as HttpClient.Request) as object if responseData = invalid return { error: "Invalid response data" @@ -285,7 +286,7 @@ namespace Innertube end if feeds = ParseResponseDataForFeeds(responseData, { - response: response + request: request browseId: browseId }) if feeds.Count() > 0 @@ -302,7 +303,7 @@ namespace Innertube return playlist end function - function ParseMixPageResponseData(responseData as object, response as object) as object + function ParseMixPageResponseData(responseData as object, request as HttpClient.Request) as object if responseData = invalid return { error: "Invalid response data" @@ -348,7 +349,7 @@ namespace Innertube } feeds = ParseResponseDataForFeeds(playlist, { - response: response + request: request }) if feeds.Count() > 0 result["videos"] = ValidArray(feeds[0].items) @@ -395,12 +396,12 @@ namespace Innertube return error end function - function ParseResponseForCacheControl(response as object) as dynamic + function ParseResponseForCacheControl(response as HttpClient.Response) as dynamic if not response.IsSuccess() return invalid end if - headers = ValidAssociativeArray(response.Headers()) + headers = response.Headers() if headers.DoesExist("cache-control") return headers["cache-control"] end if diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index 60c75be2..c068a7c3 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -11,7 +11,7 @@ import "pkg:/source/utils/UrlUtils.bs" namespace Innertube - function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as object + function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as HttpClient.Request videoId = OptionUtils.Get(options, "videoId") visitorData = OptionUtils.Get(options, "visitorData") accessToken = OptionUtils.Get(options, "accessToken") @@ -63,7 +63,7 @@ namespace Innertube payload["playbackContext"]["contentPlaybackContext"]["isLivingRoomDeeplink"] = true end if - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(client)) if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken @@ -86,7 +86,7 @@ namespace Innertube return request end function - function ParseInnertubePlayerResponse(playerRequest as dynamic, playerResponse as dynamic, client as Innertube.ClientType, cancellation as object) as object + function ParseInnertubePlayerResponse(playerRequest as HttpClient.Request, playerResponse as HttpClient.Response, client as Innertube.ClientType, cancellation as object) as object WriteAsciiFile("cachefs:/last_player_response.json", playerResponse.Text()) parsedResponse = {} payload = playerResponse.Json() @@ -206,7 +206,7 @@ namespace Innertube return parsedResponse end function - function ParsePlayerResponseForError(payload as object, playerRequest as object) as string + function ParsePlayerResponseForError(payload as object, playerRequest as HttpClient.Request) as string if not IsAssociativeArray(payload) return "Invalid payload" end if @@ -244,7 +244,7 @@ namespace Innertube errorLines.Push("Hint: Log in to the YouTube app on your phone, then cast the video to Playlet.") hasAccessToken = ValidString(playerRequest.GetHeaders()["Authorization"]).Len() > "Bearer ".Len() - hasCtt = ValidString(playerRequest.GetBody()).InStr("credentialTransferTokens") <> -1 + hasCtt = ValidString(playerRequest.GetTextBody()).InStr("credentialTransferTokens") <> -1 if hasAccessToken or hasCtt LogTelemetryEvent({ @@ -508,7 +508,7 @@ namespace Innertube request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`) request.Cancellation(cancellation) - request.TryCount(3) + request.RetryCount(2) request.NoCache() response = request.Await() if not response.IsSuccess() @@ -583,9 +583,8 @@ namespace Innertube body["poToken"] = poToken end if - request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body) + request = HttpClient.Post(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`).JsonBody(body) request.Cancellation(cancellation) - request.LogCurlCommand(false) response = request.Await() diff --git a/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs b/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs index 07cbe3ec..fac2ef4b 100644 --- a/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs @@ -76,7 +76,7 @@ namespace Innertube requestHeaders["referer"] = "https://www.youtube.com" requestHeaders["DNT"] = "?1" request.Headers(requestHeaders) - request.TryCount(2) + request.RetryCount(1) request.Cancellation(cancellation) response = request.Await() diff --git a/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs b/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs index ac4e6ad3..6ab8a1f6 100644 --- a/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs @@ -2,7 +2,7 @@ import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/source/services/HttpClient.bs" namespace Innertube - function CreateResolveUrlRequest(url as string) as object + function CreateResolveUrlRequest(url as string) as HttpClient.Request deviceInfo = CreateObject("roDeviceInfo") payload = { @@ -10,7 +10,7 @@ namespace Innertube "url": url } - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(ClientType.Web)) return request diff --git a/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs index d5d091cd..9840eabd 100644 --- a/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs @@ -32,13 +32,12 @@ namespace Innertube end if end if - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(ClientType.Web)) request.Cancellation(cancellation) if raw - request.NoCache() - request.LogCurlCommand(true) + request.LogCurlCommand() end if response = request.Await() @@ -53,7 +52,7 @@ namespace Innertube end if feeds = ParseResponseDataForFeeds(response.Json(), { - response: response + request: request disableShorts: disableShorts }) diff --git a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs index 685b222c..8f6108a7 100644 --- a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs @@ -4,7 +4,7 @@ import "pkg:/source/utils/Types.bs" namespace Innertube - function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as object + function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as HttpClient.Request deviceInfo = CreateObject("roDeviceInfo") payload = { @@ -16,13 +16,13 @@ namespace Innertube end if payload["channelIds"] = channelIds - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) return request end function - function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as object + function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as HttpClient.Request deviceInfo = CreateObject("roDeviceInfo") payload = { @@ -34,7 +34,7 @@ namespace Innertube end if payload["channelIds"] = channelIds - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json", payload) + request = HttpClient.Post("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json").JsonBody(payload) request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) return request diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index cfbdc5ab..d1207983 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -106,7 +106,7 @@ namespace Invidious end if url = `${auth.serverUrl}${Invidious.HISTORY_ENDPOINT}/${videoId}` - request = HttpClient.Post(url, "") + request = HttpClient.Post(url) request.Headers(m.GetAuthenticationHeaders(auth.token)) request.Cancellation(cancellation) response = request.Await() @@ -120,7 +120,7 @@ namespace Invidious request = HttpClient.Get(url) request.QueryParam("region", m.GetUserCountryCode()) request.QueryParam("q", q) - request.CacheSeconds(60 * 60 * 24) + request.CacheForSeconds(60 * 60 * 24) request.Cancellation(cancellation) @@ -136,31 +136,23 @@ namespace Invidious function GetVideoMetadata(videoId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") - tryCount = OptionUtils.GetOrDefault(options, "tryCount", 2) + retryCount = OptionUtils.GetOrDefault(options, "retryCount", 1) instance = m.GetInstance() url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}` request = HttpClient.Get(url) - request.Cancellation(cancellation) - - if tryCount > 1 - request.TryCount(tryCount) - request.RetryCallback(function(context as object) as boolean - response = context.response - ' In some cases, video info requests return "HTTP/0.9 when not allowed" errors. - ' Retrying should usually fix the issue. - if response.StatusCode() = HttpClient.CurlErrors.CURLE_UNSUPPORTED_PROTOCOL - errorMessage = response.ErrorMessage() - if errorMessage.InStr("HTTP/0.9") <> -1 - return true - end if - end if - - return false - end function) - end if + request.RetryCount(retryCount) + ' In some cases, video info requests return "HTTP/0.9 when not allowed" errors. + ' Retrying should usually fix the issue. + request.RetryIf(function(response as HttpClient.Response) as string + errorMessage = response.ErrorMessage() + if response.StatusCode() = HttpClient.CurlErrors.CURLE_UNSUPPORTED_PROTOCOL and errorMessage.InStr("HTTP/0.9") <> -1 + return errorMessage + end if + return "" + end function) response = request.Await() if not response.IsSuccess() @@ -227,8 +219,8 @@ namespace Invidious request = HttpClient.Get(url) request.Cancellation(cancellation) - request.CacheSeconds(60 * 60 * 24)' 24 hours - request.TryCount(3) + request.CacheForSeconds(60 * 60 * 24)' 24 hours + request.RetryCount(2) return request.Await() end function @@ -297,10 +289,6 @@ namespace Invidious } end if - instance = m.GetInstance() - - request = HttpClient.Get(instance + endpoint.url) - profile = invalid if endpoint.authenticated = true @@ -315,11 +303,13 @@ namespace Invidious error: ERROR_NOT_AUTHENTICATED } end if - request.Url(auth.serverUrl + endpoint.url) + request = HttpClient.Get(auth.serverUrl + endpoint.url) request.Headers(m.GetAuthenticationHeaders(auth.token)) if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken) request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken) end if + else + request = HttpClient.Get(m.GetInstance() + endpoint.url) end if if endpoint.queryParams <> invalid @@ -342,15 +332,15 @@ namespace Invidious end if if feedSource.cacheSeconds <> invalid - request.CacheSeconds(feedSource.cacheSeconds) + request.CacheForSeconds(feedSource.cacheSeconds) else if endpoint.cacheSeconds <> invalid - request.CacheSeconds(endpoint.cacheSeconds) + request.CacheForSeconds(endpoint.cacheSeconds) end if if feedSource.tryCount <> invalid - request.TryCount(feedSource.tryCount) + request.RetryCount(feedSource.tryCount - 1) else if endpoint.tryCount <> invalid - request.TryCount(endpoint.tryCount) + request.RetryCount(endpoint.tryCount - 1) end if if feedSource.queryParams <> invalid @@ -382,7 +372,7 @@ namespace Invidious profile: profile }) - if response.IsSuccess() and result <> invalid + if result <> invalid return { success: true result: result @@ -396,32 +386,28 @@ namespace Invidious end if end function - function SendRequest(request as HttpClient.HttpRequest, httpServer as dynamic) as dynamic + function SendRequest(request as HttpClient.Request, httpServer as dynamic) as HttpClient.Response if httpServer = invalid return request.Await() end if - url = request.BuildUrl() + url = request.GetFullUrl() isUrlToLocalServer = url.StartsWith("http://127.0.0.1:8888") or url.StartsWith(m.invidiousNode.webServer@.GetServerAddress()) if not isUrlToLocalServer return request.Await() end if parsedUrl = UrlUtils.ParseUrl(url) - method = request.GetMethod() - uri = parsedUrl.path - headers = request.GetHeaders() - body = ValidString(request.GetBody()) - responseObj = httpServer.ProcessRequestLocal(method, uri, headers, body) - response = new HttpClient.HttpResponse(request, invalid) - response.OverrideStatusCode(responseObj.http_code) - response.OverrideHeaders(responseObj.headers) + responseObj = httpServer.ProcessRequestLocal(request.GetMethod(), parsedUrl.path, request.GetHeaders(), ValidString(request.GetTextBody())) body = "" if responseObj.body <> invalid body = responseObj.body.ToAsciiString() end if - response.OverrideText(body) - return response + return new HttpClient.Response({ + statusCode: responseObj.http_code + headers: responseObj.headers + text: body + }) end function function DefaultHandler(context as object) as object @@ -450,7 +436,6 @@ namespace Invidious if not response.IsSuccess() ' Similar to VideoInfoHandler, we can return a valid response ' in case of a deleted playlist. - response.OverrideStatusCode(200) return { isLastPage: true items: [{ @@ -481,7 +466,6 @@ namespace Invidious if not response.IsSuccess() ' Similar to VideoInfoHandler, we can return a valid response ' in case of a deleted channel. - response.OverrideStatusCode(200) return { isLastPage: true items: [{ @@ -534,7 +518,6 @@ namespace Invidious ' with just a video id, which will allow us to show a valid thumbnail if possible. ' This is to makes it possible to load a bookmarked video and delete it even if ' it is no longer valid. - response.OverrideStatusCode(200) return { items: [{ "type": "video" @@ -561,7 +544,6 @@ namespace Invidious if not response.IsSuccess() ' Similar to VideoInfoHandler, we can return a valid response ' in case of a deleted playlist. - response.OverrideStatusCode(200) return { items: [{ "type": "playlist" @@ -590,7 +572,6 @@ namespace Invidious if not response.IsSuccess() ' Similar to VideoInfoHandler, we can return a valid response ' in case of a deleted channel. - response.OverrideStatusCode(200) return { items: [{ "type": "channel" @@ -701,12 +682,12 @@ namespace Invidious return json end function - function MarkNeedsReauthIfCredentialsRejected(response as object, profile as object) as void + function MarkNeedsReauthIfCredentialsRejected(response as HttpClient.Response, profile as object) as void if response.StatusCode() <> 403 return end if - body = ValidString(response.Text()) + body = response.Text() LogWarn(`Invidious instance responded with 403: ${body}`) if profile = invalid or profile.type <> "invidious" return @@ -743,7 +724,7 @@ namespace Invidious function UnregisterToken(instance as string, token as string) as object url = `${instance}${Invidious.AUTH_TOKENS_UNREGISTER}` - request = HttpClient.Post(url, token) + request = HttpClient.Post(url).TextBody(token) request.Headers(m.GetAuthenticationHeaders(token)) request.Header("Content-Type", "application/json") @@ -787,7 +768,7 @@ namespace Invidious function Subscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` - request = HttpClient.Post(url, "") + request = HttpClient.Post(url) if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken) request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken) end if diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs index 6750db66..3c4c94e4 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs @@ -38,7 +38,7 @@ class LoungeApi private ofs private lastProcessedCommandIndex = -1 private backchannel - private outgoingMessagesRequests + private pendingOutgoingMessages function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object) m.loungeServiceNode = loungeServiceNode @@ -52,7 +52,7 @@ class LoungeApi m.screenName = deviceName m.ofs = 0 m.backchannel = invalid - m.outgoingMessagesRequests = {} + m.pendingOutgoingMessages = [] m.devices = {} commandHandlers = {} @@ -144,8 +144,8 @@ class LoungeApi return m.loungeToken end if - request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_lounge_token_batch", "") - request.UrlEncodedForm({ + request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_lounge_token_batch") + request.FormBody({ "screen_ids": m.screenId }) @@ -195,9 +195,9 @@ class LoungeApi queryParams["loungeIdToken"] = m.loungeToken queryParams["zx"] = m.Zx() - request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind", "") + request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind") request.QueryParams(queryParams) - request.UrlEncodedForm({ + request.FormBody({ "count": 0 }) @@ -599,25 +599,20 @@ class LoungeApi LogDebug("Sending messages:", postData) - request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind", "") + request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind") request.QueryParams(queryParams) - request.UrlEncodedForm(postData) - - request.Send() - - ' we do not need to wait for requests to finish, we check on them later - ' to avoid blocking the thread. - ' This is specific to sent lounge messages, since we're not waiting for a response. - requestId = request.urlTransfer.GetIdentity().ToStr() - m.outgoingMessagesRequests[requestId] = request + request.FormBody(postData) + m.pendingOutgoingMessages.Push(request.Send()) end function function ProcessPendingOutgoingMessages() as object results = [] - for each key in m.outgoingMessagesRequests - request = m.outgoingMessagesRequests[key] - if request.IsCompleted() - response = request.Await() + stillPending = [] + for each pending in m.pendingOutgoingMessages + response = pending.Poll() + if response = invalid + stillPending.Push(pending) + else status = response.StatusCode() error = response.ErrorMessage() @@ -651,10 +646,9 @@ class LoungeApi }) end if end if - - m.outgoingMessagesRequests.Delete(key) end if end for + m.pendingOutgoingMessages = stillPending return results end function diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeGenerateManualPairingCodeJob.bs b/playlet-lib/src/components/Services/LoungeService/LoungeGenerateManualPairingCodeJob.bs index f4752e03..dd894da6 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeGenerateManualPairingCodeJob.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeGenerateManualPairingCodeJob.bs @@ -42,8 +42,8 @@ function ExecuteJob() as void form["app"] = "Playlet" cancellation = JobGetCancellation() - request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_pairing_code?ctx=pair", "") - request.UrlEncodedForm(form) + request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_pairing_code?ctx=pair") + request.FormBody(form) request.Cancellation(cancellation) response = request.Await() diff --git a/playlet-lib/src/components/Services/SponsorBlock/SponsorBlockService.bs b/playlet-lib/src/components/Services/SponsorBlock/SponsorBlockService.bs index ecfd7a84..28d698a7 100644 --- a/playlet-lib/src/components/Services/SponsorBlock/SponsorBlockService.bs +++ b/playlet-lib/src/components/Services/SponsorBlock/SponsorBlockService.bs @@ -62,7 +62,7 @@ namespace SponsorBlock end if url = `${serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}` - HttpClient.Post(url, "").Cancellation(cancellation).Await() + HttpClient.Post(url).Cancellation(cancellation).Await() end function function GenerateProgressBarBackground(segments as object, timeline as SponsorBlockTimeline, lengthSeconds as integer, path as string) diff --git a/playlet-lib/src/components/Telemetry/Sentry.bs b/playlet-lib/src/components/Telemetry/Sentry.bs index 73965fda..30849c61 100644 --- a/playlet-lib/src/components/Telemetry/Sentry.bs +++ b/playlet-lib/src/components/Telemetry/Sentry.bs @@ -9,32 +9,32 @@ namespace Sentry function SendEvents(events as object) as integer payload = BuildEnvelope(events, false) - request = HttpClient.Post(SUPPORT_SERVER_ENVELOPE_URL, payload) + request = HttpClient.Post(SUPPORT_SERVER_ENVELOPE_URL).TextBody(payload) request.Header("Content-Type", "application/x-sentry-envelope") response = request.Await() ' Only when the server never answered: its own failures hit every device at once and would exhaust the fallback's quota if response.StatusCode() <= 0 LogWarnNoTelemetry("Support server unreachable, sending events to the Sentry fallback:", response.ErrorMessage()) - request = HttpClient.Post(SENTRY_FALLBACK_ENVELOPE_URL, BuildEnvelope([CreateSupportServerUnreachableEvent(events[0], payload, response.ErrorMessage())], true)) + request = HttpClient.Post(SENTRY_FALLBACK_ENVELOPE_URL).TextBody(BuildEnvelope([CreateSupportServerUnreachableEvent(events[0], payload, response.ErrorMessage())], true)) request.Header("Content-Type", "application/x-sentry-envelope") request.QueryParam("sentry_key", SENTRY_FALLBACK_KEY) response = request.Await() end if if response.IsSuccess() - LogDebug("Sent events to", request.BuildUrl(), "Response:", response.Text()) + LogDebug("Sent events to", request.GetFullUrl(), "Response:", response.Text()) return 0 end if - retryAfter = ValidString(response.Headers()["Retry-After"]).ToInt() - if retryAfter = 0 + retryAfter = response.RetryAfterSeconds() + if retryAfter = invalid or retryAfter = 0 retryAfter = 60 end if if response.StatusCode() = 429 - LogErrorNoTelemetry("Rate limited by", request.BuildUrl(), "Retry after", retryAfter, "seconds") + LogErrorNoTelemetry("Rate limited by", request.GetFullUrl(), "Retry after", retryAfter, "seconds") else - LogErrorNoTelemetry("Failed to send events to", request.BuildUrl(), response.ErrorMessage(), `\nRetry after`, retryAfter, "seconds") + LogErrorNoTelemetry("Failed to send events to", request.GetFullUrl(), response.ErrorMessage(), `\nRetry after`, retryAfter, "seconds") end if return retryAfter end function diff --git a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs index 1c8f9fa6..e7ab50dd 100644 --- a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs +++ b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs @@ -1,3 +1,4 @@ +import "pkg:/components/Services/Dash/LiveHeadCounts.bs" import "pkg:/components/VideoPlayerDev/VideoNode.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Locale.bs" @@ -105,6 +106,8 @@ namespace PlaybackTelemetry private healSamples as object = invalid private tailResolveCount as integer = 0 private tailResolveSamples as object = invalid + private startSegmentBitrateBps as integer = 0 + private startMeasuredBitrateBps as integer = 0 function new(deps as object) m.playerTimer = deps.playerTimer @@ -128,6 +131,7 @@ namespace PlaybackTelemetry m.span = PlaybackTelemetry.Span.Playing if m.firstPlayingAtMs < 0 m.firstPlayingAtMs = nowMs + m.startMeasuredBitrateBps = ValidInt(ValidAssociativeArray(m.top.streamInfo).measuredBitrate) end if ' playing under an error dialog: the playback recovered, so the error did not end it. if m.outcome = PlaybackTelemetry.Outcome.Error @@ -170,6 +174,18 @@ namespace PlaybackTelemetry end if end function + ' True once the first segment carrying video started streaming: its bitrate is the one kept. + function OnStreamingSegment(segment as object) as boolean + if segment = invalid or not IsInt(segment.segType) + return false + end if + if segment.segType <> SegmentType.Mux and segment.segType <> SegmentType.Video + return false + end if + m.startSegmentBitrateBps = ValidInt(segment.segBitrateBps) + return true + end function + function OnErrorDialog() as void m.outcome = PlaybackTelemetry.Outcome.Error end function @@ -328,13 +344,20 @@ namespace PlaybackTelemetry "tail_resolve_count": m.tailResolveCount "tail_resolve_samples": m.tailResolveSamples } + if m.transport.isLive + liveHead = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH)) + if liveHead <> invalid and liveHead["video_load_id"] = summary["video_load_id"] + summary["live_head"] = liveHead["counts"] + DeleteFile(LIVE_HEAD_COUNTS_PATH) + end if + summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps + summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps + end if if content <> invalid + summary["video_id"] = content.videoId summary["stream_source"] = content.playletStreamSource summary["drm"] = not StringUtils.IsNullOrEmpty(ValidAssociativeArray(content.drmParams).keySystem) summary["stream_url_index"] = content.playletStreamUrlIndex - if m.firstPlayingAtMs < 0 or m.underrunCount > 0 or m.bufferingsWithoutStatusCount > 0 or m.isUnderrunChangeCount > 0 or m.errorCount > 0 or m.healCount > 0 or m.outcome = PlaybackTelemetry.Outcome.Error - summary["video_id"] = content.videoId - end if end if LogTelemetryEvent({ level: "info" diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoNode.bs b/playlet-lib/src/components/VideoPlayerDev/VideoNode.bs index 2fd8b43b..b193c5bc 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoNode.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoNode.bs @@ -1,5 +1,5 @@ ' The Roku Video node's `state` and `control` field values (see Video node reference). String-valued so members -' compare and assign directly against m.top.state / m.top.control. +' compare and assign directly against m.top.state / m.top.control. SegmentType is `streamingSegment.segType`. enum VideoState None = "none" @@ -22,3 +22,10 @@ enum VideoControl Prebuffer = "prebuffer" SkipContent = "skipcontent" end enum + +enum SegmentType + Mux = 0 + Audio = 1 + Video = 2 + Captions = 3 +end enum diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs index 199aba0b..d7c9cc07 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs @@ -171,6 +171,7 @@ function OnNodeReady() m.top.ObserveField("setSeek", FuncName(OnSetSeek)) m.top.ObserveField("bufferingStatus", FuncName(OnBufferingStatus)) m.top.ObserveField("playStartInfo", FuncName(OnPlayStartInfo)) + m.top.ObserveField("streamingSegment", FuncName(OnStreamingSegment)) ' a player that starts minimized shows the PiP hint (1s after the shrink settles, auto-hides after 5s). m.showFullScreenHint = not m.container.fullscreen @@ -805,6 +806,16 @@ function OnPlayStartInfo(event as object) as void m.playbackTelemetry.OnPlayStartInfo(event.getData()) end function +' Only the first video segment is wanted: no callback per segment for the rest of the play. +function OnStreamingSegment(event as object) as void + if m.onCloseCalled = true + return + end if + if m.playbackTelemetry.OnStreamingSegment(event.getData()) + m.top.unobserveField("streamingSegment") + end if +end function + ' A transport freezes the video; if the device is playing under an active transport (Roku resumes a paused ' Video on a seek, or a freeze command was dropped), re-pause. The transport stays active so the bif stays ' visible over the now-paused video. Called from OnVideoState (the change edge) and OnPosition (the net — @@ -1506,6 +1517,7 @@ function OnClose() as void m.top.unobserveField("setSeek") m.top.unobserveField("bufferingStatus") m.top.unobserveField("playStartInfo") + m.top.unobserveField("streamingSegment") m.top.unobserveField("close") content = m.top.content if content <> invalid diff --git a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs index b15dd461..dc45b2c2 100644 --- a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs +++ b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs @@ -73,7 +73,7 @@ function TestSetup() as void ' nudge counter above — stacked observers fire a handler once per prior TestSetup on every write, ' and OnPosition's latency learning reads two identical fires as a CONFIRMED min-gap, poisoning ' LiveEdgeMs for any live test that runs after another test in the suite. - for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control", "setSeek", "bufferingStatus", "playStartInfo"] + for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control", "setSeek", "bufferingStatus", "playStartInfo", "streamingSegment"] m.top.unobserveField(deviceField) end for diff --git a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.xml b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.xml index 53505e1d..38897a46 100644 --- a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.xml +++ b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.xml @@ -28,6 +28,8 @@ + + diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs index fde657e1..8f84a03b 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs @@ -1,7 +1,6 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" -import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/MathUtils.bs" @@ -28,9 +27,8 @@ function ExecuteJob() as void end if requestOptions = { - cacheSeconds: 8640000 ' 100 days cancellation: cancellation - tryCount: 1 + retryCount: 0 fetchNext: false visitorData: visitorData } diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs index ac824dbe..aa2f0caa 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs @@ -1,4 +1,6 @@ import "pkg:/components/Services/Dash/DashManifest.bs" +import "pkg:/components/Services/Dash/LiveHeadChecks.bs" +import "pkg:/components/Services/Dash/LiveHeadCounts.bs" import "pkg:/components/Services/Dash/LiveTimeline.types.bs" import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" @@ -10,8 +12,6 @@ import "pkg:/source/utils/Types.bs" ' Manifest requests closer together than this (Roku re-fetching after an error) share one live head check. const LIVE_HEAD_MIN_INTERVAL_MS = 500 -' The manifest response waits on the head check; past this it lists the last known head. -const LIVE_HEAD_TIMEOUT_SECONDS = 2 ' Head time leaping this far past the listed timeline within one head check is a stall. const LIVE_STALL_JUMP_MS = 10000 @@ -40,6 +40,7 @@ namespace Http m.cachedMetadata = invalid m.liveHeadUrl = "" m.liveHeadTimer = invalid ' since the last head check; invalid = never checked + m.liveHeadChecks = invalid m.liveHeadSeqnum = 0 m.liveLoadHeadSeqnum = 0 m.liveLoadHeadTimeMs = invalid @@ -175,8 +176,7 @@ namespace Http return true end if - dashRequest = HttpClient.Get(url) - dashResponse = dashRequest.Await() + dashResponse = HttpClient.Get(url).Await() if not dashResponse.IsSuccess() LogError("Failed to fetch DASH manifest from URL", dashResponse.ErrorMessage()) @@ -184,7 +184,7 @@ namespace Http return true end if - dashContent = ValidString(dashResponse.Text()) + dashContent = dashResponse.Text() storyboardIndex = dashContent.InStr("") if storyboardIndex = -1 response.Redirect(url) @@ -229,8 +229,8 @@ namespace Http return xmlContent end function - ' Raise the live head to the stream's newest segment. On failure the timeline - ' keeps its end, and the player holds at it until a later check succeeds. + ' Raise the live head to the newest one answered. Until a check answers with a newer head, the + ' timeline keeps its end and the player holds at it. function RefreshLiveHead() as void if StringUtils.IsNullOrEmpty(m.liveHeadUrl) return @@ -242,28 +242,21 @@ namespace Http end if m.liveHeadTimer.Mark() - head = m.CheckLiveHead() - if head.seqnum < 0 - m.ReportLiveHeadFailure(head.response) - return - end if - ' Listed segments can't be withdrawn: the head only moves forward. - if head.seqnum > m.liveHeadSeqnum - m.AlignLiveTimeline(head) - m.liveHeadSeqnum = head.seqnum - end if - end function + newest = invalid + for each head in m.liveHeadChecks.Refresh() + if head.seqnum < 0 + m.ReportLiveHeadFailure(head.response) + else if newest = invalid or head.seqnum > newest.seqnum + newest = head + end if + end for + WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts })) - ' A no-sq HEAD: googlevideo answers at once with the X-Head-* headers. - function CheckLiveHead() as LiveHeadReading - request = Innertube.CreateLiveHeadRequest(m.liveHeadUrl) - request.TimeoutSeconds(LIVE_HEAD_TIMEOUT_SECONDS) - response = request.Await() - return { - seqnum: Innertube.ReadLiveHeadSeqnum(response) - timeMs: Innertube.ReadLiveHeadTimeMs(response) - response: response - } + ' Listed segments can't be withdrawn: the head only moves forward. + if newest <> invalid and newest.seqnum > m.liveHeadSeqnum + m.AlignLiveTimeline(newest) + m.liveHeadSeqnum = newest.seqnum + end if end function ' Segments are listed at the duration at load, the stream's lifetime average: off @@ -353,11 +346,10 @@ namespace Http }) end function - ' Until a head check succeeds, the listed timeline stops growing and the player - ' holds at its end. Telemetry once per video load. - function ReportLiveHeadFailure(response as object) as void + ' Telemetry once per video load. + function ReportLiveHeadFailure(response as HttpClient.Response) as void statusText = Str(response.StatusCode()).Trim() - LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, "); head stays at", m.liveHeadSeqnum) + LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, ")") if m.reportedLiveHeadFailure return end if @@ -375,7 +367,7 @@ namespace Http `video_load_id: ${ValidString(m.cachedVideoLoadId)}` `head: ${m.liveHeadSeqnum}` `status: ${statusText}` - `error: ${response.ErrorMessage(false)}` + `error: ${response.ErrorMessage()}` `url: ${m.liveHeadUrl}` ].Join(`\n`) }] @@ -384,6 +376,10 @@ namespace Http function ResetLiveState(metadata as object) as void m.liveHeadUrl = ValidString(metadata.liveHeadUrl) + if m.liveHeadChecks <> invalid + m.liveHeadChecks.Cancel() + end if + m.liveHeadChecks = new LiveHeadChecks(m.liveHeadUrl) m.liveHeadTimer = invalid m.liveHeadSeqnum = ValidInt(metadata.liveHeadSeqnum) m.liveLoadHeadSeqnum = m.liveHeadSeqnum diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DialRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DialRouter.bs index 22284095..a3e681e5 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DialRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DialRouter.bs @@ -81,8 +81,8 @@ namespace Http end if end if - req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code", "") - req.UrlEncodedForm({ + req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code") + req.FormBody({ "pairing_code": pairingCode "screen_id": m.loungeService.screenId "screen_name": m.deviceName diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs index c5cce061..d6a1c666 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs @@ -128,8 +128,23 @@ namespace Http requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT end if - httpReq = HttpClient.FromObject(requestArgs) - httpRes = httpReq.Await() + method = "GET" + if requestArgs.Method <> invalid + method = requestArgs.Method + end if + proxyRequest = new HttpClient.Request(method, requestArgs.Url) + proxyRequest.Headers(requestHeaders) + if requestArgs.Body <> invalid + proxyRequest.TextBody(requestArgs.Body) + end if + if requestArgs.CacheSeconds <> invalid + if requestArgs.CacheSeconds > 0 + proxyRequest.CacheForSeconds(requestArgs.CacheSeconds) + else + proxyRequest.NoCache() + end if + end if + httpRes = proxyRequest.Await() result = { "status": httpRes.StatusCode() diff --git a/playlet-lib/src/components/Web/tests/AwaitInTask.bs b/playlet-lib/src/components/Web/tests/AwaitInTask.bs new file mode 100644 index 00000000..479febf1 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/AwaitInTask.bs @@ -0,0 +1,13 @@ +import "pkg:/source/services/HttpClient.bs" + +' Awaits url on this task's thread, as a job does, cancellable through cancellationNode.cancel. +function Init() + m.top.functionName = "AwaitUrl" +end function + +function AwaitUrl() as void + cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true) + pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send() + m.top.sending = true + m.top.cancelled = pending.Await().IsCancelled() +end function diff --git a/playlet-lib/src/components/Web/tests/AwaitInTask.xml b/playlet-lib/src/components/Web/tests/AwaitInTask.xml new file mode 100644 index 00000000..58a5c985 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/AwaitInTask.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/playlet-lib/src/components/Web/tests/CancelLaterTask.bs b/playlet-lib/src/components/Web/tests/CancelLaterTask.bs new file mode 100644 index 00000000..6ad943c4 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/CancelLaterTask.bs @@ -0,0 +1,17 @@ +' Sets cancellationNode.cancel cancelAfterMs after that field is set, while the caller's thread blocks. +function Init() + m.top.functionName = "CancelLater" +end function + +function CancelLater() as void + node = CreateObject("roSGNode", "Node") + node.addField("cancel", "boolean", false) + port = CreateObject("roMessagePort") + m.top.ObserveField("cancelAfterMs", port) + m.top.cancellationNode = node + ' Waiting on the port lets other threads rendezvous with this one. + while type(wait(0, port)) <> "roSGNodeEvent" + end while + wait(m.top.cancelAfterMs, port) + node.cancel = true +end function diff --git a/playlet-lib/src/components/Web/tests/CancelLaterTask.xml b/playlet-lib/src/components/Web/tests/CancelLaterTask.xml new file mode 100644 index 00000000..4caef437 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/CancelLaterTask.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/playlet-lib/src/components/Web/tests/HttpTestServer.bs b/playlet-lib/src/components/Web/tests/HttpTestServer.bs new file mode 100644 index 00000000..8a6586ab --- /dev/null +++ b/playlet-lib/src/components/Web/tests/HttpTestServer.bs @@ -0,0 +1,220 @@ +import "pkg:/source/utils/Types.bs" + +' Responds to one request per connection, by path: +' /status/ the status +' /seq//,,... the next status in the list for that path, then its last one; +' @ responds after +' /delay/ 200 after +' /echo 200 with the request's { method, path, headers, body } as JSON +' /maxage// 200 with Cache-Control: max-age= +' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }. +' A route { drop: true } closes the connection without a response. +' Every response carries X-Hit, the request's count for its path. Connections are read and responded to +' without blocking each other, so a slow or abandoned one holds up nothing. +' The last request read is in lastRequest: { method, path, headers, body }. + +' Roku's roUrlTransfer sometimes never completes when the whole response and the close reach it over +' loopback within a millisecond of its request (9 of 8000 such requests; 0 of 16000 at 5ms or 20ms). +const MIN_RESPONSE_DELAY_MS = 5 +' A connection whose request isn't complete by then is dropped. +const READ_TIMEOUT_MS = 2000 + +function Init() + m.top.functionName = "Serve" +end function + +function Serve() as void + messagePort = CreateObject("roMessagePort") + listener = CreateObject("roStreamSocket") + listener.SetReuseAddr(true) + address = CreateObject("roSocketAddress") + address.SetAddress(`127.0.0.1:${m.top.port}`) + listener.SetAddress(address) + listener.SetMessagePort(messagePort) + listener.NotifyReadable(true) + if not listener.Listen(8) + return + end if + m.top.ObserveField("shouldQuit", messagePort) + m.hits = {} + m.clock = CreateObject("roTimespan") + reading = [] + responses = [] + m.top.isRunning = true + + while true + ' 0: no deadline, wait for the next socket event. + waitMs = 0 + for each item in reading + waitMs = ShorterWaitMs(waitMs, item.sinceMs + READ_TIMEOUT_MS) + end for + for each response in responses + waitMs = ShorterWaitMs(waitMs, response.sendAtMs) + end for + message = wait(waitMs, messagePort) + if type(message) = "roSGNodeEvent" + exit while + end if + + if listener.IsReadable() + connection = listener.Accept() + while connection <> invalid + connection.SetMessagePort(messagePort) + connection.NotifyReadable(true) + reading.Push({ connection: connection, data: "", byteCount: 0, sinceMs: m.clock.TotalMilliseconds() }) + connection = listener.Accept() + end while + end if + + stillReading = [] + for each item in reading + connection = item.connection + closed = false + if connection.IsReadable() + count = connection.GetCountRcvBuf() + if count > 0 + ' ReceiveStr ends at a NUL byte; a binary body is counted in bytes, read as text up to its first NUL. + bytes = CreateObject("roByteArray") + bytes[count - 1] = 0 + item.byteCount += connection.Receive(bytes, 0, count) + item.data += bytes.ToAsciiString() + else + ' Readable with nothing to read: the peer closed. + closed = true + end if + end if + response = BuildResponse(item) + if response <> invalid + connection.NotifyReadable(false) + responses.Push(response) + else if closed or m.clock.TotalMilliseconds() - item.sinceMs >= READ_TIMEOUT_MS + connection.Close() + else + stillReading.Push(item) + end if + end for + reading = stillReading + + unsent = [] + for each response in responses + if response.sendAtMs <= m.clock.TotalMilliseconds() + response.connection.SendStr(response.text) + response.connection.Close() + else + unsent.Push(response) + end if + end for + responses = unsent + end while + + for each item in reading + item.connection.Close() + end for + for each response in responses + response.connection.Close() + end for + listener.Close() + m.top.isRunning = false +end function + +' The wait until deadlineMs, or waitMs if that is shorter; 0 means no wait limit yet. +function ShorterWaitMs(waitMs as integer, deadlineMs as integer) as integer + untilDeadlineMs = deadlineMs - m.clock.TotalMilliseconds() + if untilDeadlineMs < 1 + untilDeadlineMs = 1 + end if + if waitMs = 0 or untilDeadlineMs < waitMs + return untilDeadlineMs + end if + return waitMs +end function + +' The response to the connection's request and when to send it, or invalid until the request is complete. +function BuildResponse(item as object) as object + headEnd = item.data.InStr(`\r\n\r\n`) + if headEnd = -1 + return invalid + end if + head = item.data.Left(headEnd) + headers = {} + for each line in head.Split(`\r\n`) + colon = line.InStr(":") + if colon > 0 + headers[LCase(line.Left(colon))] = line.Mid(colon + 1).Trim() + end if + end for + requestBody = item.data.Mid(headEnd + 4) + if item.byteCount - headEnd - 4 < ValidString(headers["content-length"]).ToInt() + return invalid + end if + + requestLine = head.Split(`\r\n`)[0].Split(" ") + if requestLine.Count() < 2 + return invalid + end if + method = requestLine[0] + path = requestLine[1] + + m.hits[path] = ValidInt(m.hits[path]) + 1 + hit = m.hits[path] + m.top.hits = m.hits + request = { method: method, path: path, headers: headers, body: requestBody } + m.top.lastRequest = request + + delayMs = MIN_RESPONSE_DELAY_MS + route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]] + if route <> invalid + if ValidInt(route.delayMs) > delayMs + delayMs = route.delayMs + end if + if route.drop = true + return { connection: item.connection, text: "", sendAtMs: m.clock.TotalMilliseconds() + delayMs } + end if + text = `HTTP/1.1 ${route.status} Test\r\nContent-Length: ${ValidString(route.body).Len()}\r\nX-Hit: ${hit}\r\nConnection: close\r\n` + for each name in ValidAssociativeArray(route.headers) + text += `${name}: ${route.headers[name]}\r\n` + end for + text += `\r\n` + if method <> "HEAD" + text += ValidString(route.body) + end if + return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs } + end if + + status = 404 + segments = path.Split("?")[0].Split("/") + if segments.Count() = 3 and segments[1] = "status" + status = segments[2].ToInt() + else if segments.Count() = 4 and segments[1] = "seq" + codes = segments[3].Split(",") + index = hit - 1 + if index >= codes.Count() + index = codes.Count() - 1 + end if + entry = codes[index].Split("@") + status = entry[0].ToInt() + if entry.Count() > 1 + delayMs = entry[1].ToInt() + end if + else if segments.Count() = 3 and segments[1] = "delay" + delayMs = segments[2].ToInt() + status = 200 + else if segments.Count() = 2 and segments[1] = "echo" + status = 200 + else if segments.Count() = 4 and segments[1] = "maxage" + status = 200 + end if + + body = `hit ${hit}` + extraHeaders = "" + if segments[1] = "echo" + body = FormatJson(request) + else if segments[1] = "maxage" + extraHeaders = `Cache-Control: max-age=${segments[2]}\r\n` + end if + text = `HTTP/1.1 ${status} Test\r\nContent-Type: text/plain\r\nContent-Length: ${body.Len()}\r\nX-Hit: ${hit}\r\n${extraHeaders}Connection: close\r\n\r\n` + if method <> "HEAD" + text += body + end if + return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs } +end function diff --git a/playlet-lib/src/components/Web/tests/HttpTestServer.xml b/playlet-lib/src/components/Web/tests/HttpTestServer.xml new file mode 100644 index 00000000..2fa80de4 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/HttpTestServer.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/playlet-lib/src/components/Web/tests/PollInTask.bs b/playlet-lib/src/components/Web/tests/PollInTask.bs new file mode 100644 index 00000000..cf40f5f1 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/PollInTask.bs @@ -0,0 +1,19 @@ +import "pkg:/source/services/HttpClient.bs" + +' Polls url's response on this task's thread without ever waiting on a port, cancellable through cancellationNode.cancel. +function Init() + m.top.functionName = "PollUrl" +end function + +function PollUrl() as void + cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true) + pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send() + m.top.sending = true + response = invalid + timer = CreateObject("roTimespan") + while response = invalid and timer.TotalMilliseconds() < 5000 + response = pending.Poll() + sleep(10) + end while + m.top.cancelled = response <> invalid and response.IsCancelled() +end function diff --git a/playlet-lib/src/components/Web/tests/PollInTask.xml b/playlet-lib/src/components/Web/tests/PollInTask.xml new file mode 100644 index 00000000..391d7b20 --- /dev/null +++ b/playlet-lib/src/components/Web/tests/PollInTask.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs b/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs index 4cce36b9..db295024 100644 --- a/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs +++ b/playlet-lib/src/source/components/tests/LoungeRefreshTokenIntegration.spec.bs @@ -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({ diff --git a/playlet-lib/src/source/components/tests/OAuth.spec.bs b/playlet-lib/src/source/components/tests/OAuth.spec.bs index 2adf43db..5c8c358d 100644 --- a/playlet-lib/src/source/components/tests/OAuth.spec.bs +++ b/playlet-lib/src/source/components/tests/OAuth.spec.bs @@ -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 diff --git a/playlet-lib/src/source/services/HttpCache.bs b/playlet-lib/src/source/services/HttpCache.bs new file mode 100644 index 00000000..981f5574 --- /dev/null +++ b/playlet-lib/src/source/services/HttpCache.bs @@ -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 diff --git a/playlet-lib/src/source/services/HttpClient.bs b/playlet-lib/src/source/services/HttpClient.bs index 5e9a48fd..78963e38 100644 --- a/playlet-lib/src/source/services/HttpClient.bs +++ b/playlet-lib/src/source/services/HttpClient.bs @@ -5,8 +5,9 @@ ' Only use this for debugging purposes. #const NETWORK_THROTTLE = false +import "pkg:/source/services/HttpCache.bs" +import "pkg:/source/utils/AssertUtils.bs" import "pkg:/source/utils/CancellationUtils.bs" -import "pkg:/source/utils/CryptoUtils.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Locale.bs" import "pkg:/source/utils/Logging.bs" @@ -14,9 +15,26 @@ import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/UrlUtils.bs" +' A Request holds what to send. Sending it starts a Fetch, which ends in one Response: +' +' response = HttpClient.Get(url).Await() ' blocks until the response +' +' pending = HttpClient.Get(url).Send() ' a Fetch on a port of its own +' 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 +' while true +' message = wait(500, port) +' response = pending.Poll() ' at each wake: the response once it is in, up to 500ms late +' ... ' the loop's own messages +' +' Retries run inside the fetch, on the thread that started it, while Await, Wait or Poll runs. namespace HttpClient const COMPRESSION_ENABLED = true + const DEFAULT_ATTEMPT_TIMEOUT_MS = 30000 + const DEFAULT_RETRY_DELAY_MS = 1000 ' 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 @@ -92,892 +110,798 @@ namespace HttpClient CURLE_SSL_SHUTDOWN_FAILED = -80 end enum - function Get(url as string) as HttpRequest - return (new HttpRequest()).Method("GET").Url(url) + function Get(url as string) as Request + return new Request("GET", url) end function - function Post(url as string, data as string) as HttpRequest - return (new HttpRequest()).Method("POST").Url(url).Body(data) + function Head(url as string) as Request + return new Request("HEAD", url) end function - function PostJson(url as string, data as object) as HttpRequest - return (new HttpRequest()).Method("POST").Url(url).Json(data) + function Post(url as string) as Request + return new Request("POST", url) end function - function Put(url as string, data as string) as HttpRequest - return (new HttpRequest()).Method("PUT").Url(url).Body(data) + function Put(url as string) as Request + return new Request("PUT", url) end function - function PutJson(url as string, data as object) as HttpRequest - return (new HttpRequest()).Method("PUT").Url(url).Json(data) + function Delete(url as string) as Request + return new Request("DELETE", url) end function - function Delete(url as string) as HttpRequest - return (new HttpRequest()).Method("DELETE").Url(url) - end function - - function Head(url as string) as HttpRequest - return (new HttpRequest()).Method("HEAD").Url(url) - end function - - function FromObject(obj as object) as HttpRequest - request = new HttpRequest() - - for each key in obj - if IsFunction(request[key]) - request[key](obj[key]) - else - throw `Invalid key: "${key}" in object passed to HttpClient.FromObject` - end if - end for - - return request - end function - - class HttpRequest - - public urlTransfer as object - - function new() - m._timeoutSeconds = 30 - m._tryCount = 1 - m._method = "GET" + class Request + ' For any method, such as a proxied request's; Get, Head, Post, Put and Delete are shorter. + function new(method as string, url as string) + m._method = UCase(method) + m._url = url + m._headers = {} + m._attemptTimeoutMs = DEFAULT_ATTEMPT_TIMEOUT_MS + m._retryCount = 0 + m._retryDelayMs = DEFAULT_RETRY_DELAY_MS end function - function Method(method as string) as HttpRequest - m._method = Ucase(method) + function Header(key as string, value as string) as Request + m._headers[key] = value return m end function + function Headers(headers as object) as Request + m._headers.Append(headers) + return m + end function + + function QueryParam(key as string, value as dynamic) as Request + #if DEBUG + Assert.IsValid(value, `QueryParam("${key}", invalid): the value can't be invalid`) + #end if + if m._queryParams = invalid + m._queryParams = {} + end if + m._queryParams[key] = value + m._fullUrl = invalid + return m + end function + + function QueryParams(queryParams as object) as Request + if m._queryParams = invalid + m._queryParams = {} + end if + m._queryParams.Append(queryParams) + m._fullUrl = invalid + return m + end function + + function QueryParamArray(key as string, values as object, arrayType as UrlUtils.QueryParamArrayType) as Request + #if DEBUG + Assert.IsValid(values, `QueryParamArray("${key}", invalid): the values can't be invalid`) + #end if + return m.QueryParam(key, { value: values, arrayType: arrayType }) + end function + + ' Fills {key} in the url. + function PathParam(key as string, value as string) as Request + if m._pathParams = invalid + m._pathParams = {} + end if + m._pathParams[key] = value + m._fullUrl = invalid + return m + end function + + function PathParams(pathParams as object) as Request + if m._pathParams = invalid + m._pathParams = {} + end if + m._pathParams.Append(pathParams) + m._fullUrl = invalid + return m + end function + + function TextBody(text as string) as Request + #if DEBUG + Assert.IsTrue(m._method <> "GET" and m._method <> "HEAD", `TextBody on a ${m._method} request: ${m._method} sends no body`) + #end if + m._textBody = text + m._fileBodyPath = invalid + return m + end function + + function JsonBody(value as object) as Request + #if DEBUG + Assert.IsTrue(m._method <> "GET" and m._method <> "HEAD", `JsonBody on a ${m._method} request: ${m._method} sends no body`) + #end if + m._textBody = FormatJson(value) + m._fileBodyPath = invalid + m._headers["Content-Type"] = "application/json" + return m + end function + + ' fields: an AA, or an array of { key, value } where the order matters. + function FormBody(fields as object) as Request + #if DEBUG + Assert.IsTrue(m._method <> "GET" and m._method <> "HEAD", `FormBody on a ${m._method} request: ${m._method} sends no body`) + #end if + m._textBody = UrlUtils.GetUrlEncodedForm(fields) + m._fileBodyPath = invalid + m._headers["Content-Type"] = "application/x-www-form-urlencoded" + return m + end function + + function FileBody(filePath as string) as Request + #if DEBUG + Assert.IsTrue(m._method <> "GET" and m._method <> "HEAD", `FileBody on a ${m._method} request: ${m._method} sends no body`) + #end if + m._fileBodyPath = filePath + m._textBody = invalid + return m + end function + + ' How long one attempt may take, from when it is sent. The deadline is checked only when the response is + ' waited on or polled, after the answer already in, if any: that answer is returned even if it came after the + ' deadline, as an roUrlEvent carries no arrival time. Await and Wait time out on time; a late Poll can return + ' a late answer, for the caller to judge whether it is too stale. + function AttemptTimeoutMs(timeoutMs as integer) as Request + #if DEBUG + Assert.IsTrue(timeoutMs > 0, `AttemptTimeoutMs(${timeoutMs}): the timeout must be above 0`) + #end if + m._attemptTimeoutMs = timeoutMs + return m + end function + + ' How many more attempts may follow a failed one. A timed-out attempt is never retried: after AttemptTimeoutMs + ' the user needs an answer, not another wait. The first attempt is retried on any failure (anything not 2xx + ' or 3xx) except a request roUrlTransfer couldn't send, which completes at once; a later one only on a 5xx or a + ' network failure, as a 2xx-4xx answer to a retry is final. RetryIf picks among those. + function RetryCount(retryCount as integer) as Request + #if DEBUG + Assert.IsTrue(retryCount >= 0, `RetryCount(${retryCount}): the count can't be negative`) + #end if + m._retryCount = retryCount + return m + end function + + ' Each retry is sent delayMs to 2 × delayMs after the previous attempt ended. + function RetryDelayMs(delayMs as integer) as Request + #if DEBUG + Assert.IsTrue(delayMs >= 0, `RetryDelayMs(${delayMs}): the delay can't be negative`) + #end if + m._retryDelayMs = delayMs + return m + end function + + ' Picks the attempts to retry instead of every failed one: predicate(response) returns the reason to retry, + ' which the retry's warning reports, or "" or invalid not to. It sees the attempts RetryCount allows to retry, + ' the first one's success included. A cancelled fetch never retries. A predicate that throws is logged as an + ' error, and its attempt retries if it failed; DEBUG builds rethrow. + function RetryIf(predicate as function) as Request + m._retryPredicate = predicate + return m + end function + + ' A retried attempt, or a failure RetryIf declines to retry, is logged without a telemetry event: for requests + ' where failing and retrying is normal. + function NoTelemetry() as Request + m._noTelemetry = true + return m + end function + + ' A successful GET is served from disk for that many seconds, instead of its Cache-Control max-age. + function CacheForSeconds(seconds as integer) as Request + #if DEBUG + Assert.AreEqual("GET", m._method, `CacheForSeconds on a ${m._method} request: only GET can`) + Assert.IsTrue(seconds > 0, `CacheForSeconds(${seconds}): the duration must be above 0`) + #end if + m._cacheSeconds = seconds + return m + end function + + ' A successful GET is served from disk for its Cache-Control max-age by default; NoCache turns that off, + ' CacheForSeconds included. + function NoCache() as Request + m._noCache = true + return m + end function + + ' The response's body goes to filePath instead of its Text. + function SaveBodyToFile(filePath as string) as Request + #if DEBUG + Assert.AreEqual("GET", m._method, `SaveBodyToFile on a ${m._method} request: only GET can`) + #end if + m._saveBodyToFilePath = filePath + return m + end function + + ' cancellation: from CancellationUtils.CreateCancellation, or invalid for none. + function Cancellation(cancellation as dynamic) as Request + #if DEBUG + Assert.IsTrue(cancellation = invalid or (IsAssociativeArray(cancellation) and cancellation.node <> invalid and IsString(cancellation.field)), "Cancellation takes CancellationUtils.CreateCancellation(node, field, value), or invalid") + #end if + m._cancellation = cancellation + return m + end function + + function LogCurlCommand(enabled = true as boolean) as Request + m._logCurlCommand = enabled + return m + end function + + ' The url as given, with its path params filled in and its query params appended. + function GetFullUrl() as string + if m._fullUrl = invalid + m._fullUrl = UrlUtils.BuildUrl(m._url, m._pathParams, m._queryParams) + end if + return m._fullUrl + end function + function GetMethod() as string return m._method end function - function Url(url as string) as HttpRequest - m._url = url - return m - end function - - function QueryParam(key as string, value as dynamic) as HttpRequest - if value = invalid - return m - end if - if m._queryParams = invalid - m._queryParams = {} - end if - m._queryParams[key] = value - return m - end function - - function QueryParamArray(key as string, valueArray as dynamic, arrayType as UrlUtils.QueryParamArrayType) as HttpRequest - if valueArray = invalid - return m - end if - if m._queryParams = invalid - m._queryParams = {} - end if - - m._queryParams[key] = { - value: valueArray - arrayType: arrayType - } - - return m - end function - - function QueryParams(queryParams as object) as HttpRequest - if m._queryParams = invalid - m._queryParams = {} - end if - m._queryParams.append(queryParams) - return m - end function - - function PathParam(key as string, value as string) as HttpRequest - if m._pathParams = invalid - m._pathParams = {} - end if - m._pathParams[key] = value - return m - end function - - function PathParams(pathParams as object) as HttpRequest - if m._pathParams = invalid - m._pathParams = {} - end if - m._pathParams.append(pathParams) - return m - end function - - function Header(key as string, value as string) as HttpRequest - if m._headers = invalid - m._headers = {} - end if - m._headers[key] = value - return m - end function - - function Headers(headers as object) as HttpRequest - if m._headers = invalid - m._headers = {} - end if - m._headers.append(headers) - return m - end function - function GetHeaders() as object - if m._headers = invalid - m._headers = {} - end if return m._headers end function - function Body(body as dynamic) as HttpRequest - m._body = ValidString(body) - return m - end function - - function GetBody() as dynamic - return m._body - end function - - function FromFile(filePath as string) as HttpRequest - m._bodyFilePath = filePath - return m - end function - - function Json(body as object) as HttpRequest - m.Body(FormatJson(body)) - m.Header("Content-Type", "application/json") - return m - end function - - function UrlEncodedForm(form as object) as HttpRequest - m.Body(UrlUtils.GetUrlEncodedForm(form)) - m.Header("Content-Type", "application/x-www-form-urlencoded") - return m - end function - - function TimeoutSeconds(timeoutSeconds as integer) as HttpRequest - m._timeoutSeconds = timeoutSeconds - return m - end function - - function TryCount(tryCount as integer) as HttpRequest - m._tryCount = ValidInt(tryCount) - if m._tryCount < 1 - m._tryCount = 1 - end if - return m - end function - - function RetryCallback(callback as function) as HttpRequest - m._retryCallback = callback - return m - end function - - function NoCache() as HttpRequest - m._noCache = true - return m - end function - - function CacheSeconds(expireSeconds as integer) as HttpRequest - m._expireSeconds = expireSeconds - if expireSeconds < 0 - m.NoCache() - end if - return m - end function - - function UseHttp2() as HttpRequest - m._useHttp2 = true - return m - end function - - function Cancellation(cancellation as object) as HttpRequest - m._cancellation = cancellation - return m - end function - - function LogCurlCommand(doLog as boolean) as HttpRequest - m._logCurlCommand = doLog - return m - end function - - function ToFile(filePath as string) as HttpRequest - m._toFilePath = filePath - return m + ' invalid when the body is a file, or there is none. + function GetTextBody() as dynamic + return m._textBody end function function ToCurlCommand() as string - command = `curl "${m.BuildUrl()}"` + command = `curl "${m.GetFullUrl()}"` if m._method = "HEAD" command += ` \\\n --head` else if m._method <> "GET" command += ` \\\n --request ${m._method}` end if - - command += ` \\\n --max-time ${m._timeoutSeconds}` - command += ` \\\n --location` - command += ` \\\n --show-error` - + command += ` \\\n --max-time ${m._attemptTimeoutMs / 1000}` + command += ` \\\n --location \\\n --show-error` if COMPRESSION_ENABLED command += ` \\\n --compressed` end if - - if m._useHttp2 = true - command += ` \\\n --http2` + for each key in m._headers + value = m._headers[key] + #if DEBUG + #else + if LCase(key) = "authorization" + value = "" + end if + #end if + command += ` \\\n -H '${key}: ${value}'` + end for + if not StringUtils.IsNullOrEmpty(m._textBody) + command += ` \\\n -d '${m._textBody}'` end if - - if m._headers <> invalid - for each key in m._headers - #if DEBUG - command += ` \\\n -H '${key}: ${m._headers[key]}'` - #else - if LCase(key) = "authorization" - command += ` \\\n -H '${key}: '` - else - command += ` \\\n -H '${key}: ${m._headers[key]}'` - end if - #end if - end for + if m._fileBodyPath <> invalid + command += ` \\\n --data-binary @${m._fileBodyPath}` end if - - if not StringUtils.IsNullOrEmpty(m._body) - command += ` \\\n -d '${m._body}'` - end if - - if not StringUtils.IsNullOrEmpty(m._bodyFilePath) - command += ` \\\n --data-binary @${m._bodyFilePath}` - end if - return command end function - ' Note: Calling Send() only without Await() will not guarentee a request will be sent. - ' If a Task finishes before the request is sent, the request might be dropped. - function Send() as HttpRequest - if m.urlTransfer <> invalid or m._cache <> invalid - return m + function Await() as Response + return m.Send().Await() + end function + + ' 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") + ' 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") + ' 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) + cancellationObserver.target = { node: m._cancellation.node, fieldName: m._cancellation.field } + end if + startedFetch = new Fetch(m, messagePort) + startedFetch.Start() + return new PendingResponse(startedFetch, messagePort, 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. + class Fetch + function new(request as Request, messagePort as object) + m._request = request + m._messagePort = messagePort + m._attemptCount = 0 + m._transferId = invalid + end function + + function Start() as void + m._clock = CreateObject("roTimespan") + request = m._request + + if CancellationUtils.IsCancelled(request._cancellation) + m.Cancel() + return end if + cacheable = request._method = "GET" and request._noCache <> true #if DISABLE_CACHE #if DEBUG - m._noCache = true + cacheable = false #end if #end if - - if m._noCache <> true - cache = HttpClientCache.Get(m) - if cache <> invalid - LogInfo("Cache hit", m._method, m.BuildUrl()) - m._cache = cache - return m + if cacheable + m._cacheFilePath = HttpCache.GetFilePath(request.GetFullUrl(), request._headers, request._saveBodyToFilePath) + cached = HttpCache.Read(m._cacheFilePath, request._saveBodyToFilePath) + if cached <> invalid + m._response = m.NewResponse({ + cached: true + statusCode: cached.statusCode + headers: cached.headers + text: cached.text + bodyFilePath: request._saveBodyToFilePath + }) + LogInfo("Cache hit", request._method, request.GetFullUrl()) + m.Throttle() + return end if end if + m.StartAttempt() + end function - m.urlTransfer = m.CreateRoUrlTransfer() - if m.urlTransfer = invalid - LogError("Failed to create roUrlTransfer. We're probably not in a background thread.") - return m + ' 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 + ' time limit. + function MaxWaitMs() as integer + if m._urlTransfer <> invalid + waitMs = m._attemptDeadlineMs - m._clock.TotalMilliseconds() + else + waitMs = m._retryAtMs - m._clock.TotalMilliseconds() + end if + if waitMs < 1 + return 1 + end if + return waitMs + end function + + ' message: what was taken from the port, invalid when nothing was. The deadline is checked after the message: + ' an answer is taken even past the deadline; past it, any other message, or none, times the attempt out. + ' Returns the response once the fetch completed, invalid until then. + function HandleMessage(message as dynamic) as dynamic + if m._response = invalid + ' GetInt() is 1 when the transfer completed; an earlier attempt's transfer has another identity. + if type(message) = "roUrlEvent" and m._urlTransfer <> invalid and message.GetInt() = 1 and message.GetSourceIdentity() = m._urlTransfer.GetIdentity() + m.OnAttemptEnded(m.NewResponse({ urlEvent: message, bodyFilePath: m._request._saveBodyToFilePath })) + end if + if m._urlTransfer <> invalid and m._clock.TotalMilliseconds() >= m._attemptDeadlineMs + m.OnAttemptTimeout() + end if + if m._response = invalid and m._urlTransfer = invalid and m._clock.TotalMilliseconds() >= m._retryAtMs + ' Read here too, as its event may never come. + if CancellationUtils.IsCancelled(m._request._cancellation) + m.Cancel() + else + m.StartAttempt() + end if + end if + end if + return m._response + end function + + ' Completes the fetch as cancelled, unless it already completed. + function Cancel() as void + if m._response <> invalid + return + end if + if m._urlTransfer <> invalid + m._urlTransfer.AsyncCancel() + m._urlTransfer = invalid + else + ' Cancelled before an attempt was sent, or between two. + m._transferId = invalid + end if + LogInfo("Cancelled", m.Describe()) + m.Complete(m.NewResponse({ cancelled: true })) + end function + + private function StartAttempt() as void + m._attemptCount += 1 + m._transferId = invalid + request = m._request + method = request._method + urlTransfer = CreateUrlTransfer(request.GetFullUrl(), request._headers, m._messagePort) + if urlTransfer = invalid + LogError("Failed to create roUrlTransfer") + m.Throttle() + m.Complete(m.NewResponse({ notSentReason: "roUrlTransfer couldn't be created" })) + return end if - m.urlTransfer.setUrl(m.BuildUrl()) - if m._headers <> invalid - m.urlTransfer.SetHeaders(m._headers) - end if - - m.urlTransfer.SetMessagePort(CreateObject("roMessagePort")) - - LogInfo("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity()) - + LogInfo("Sending", method, request.GetFullUrl(), "ID:", urlTransfer.GetIdentity()) #if DEBUG - if m._logCurlCommand <> false - LogDebug(`======== curl command ========\n${m.ToCurlCommand()}\n==============================`) + if request._logCurlCommand <> false + LogDebug(`======== curl command ========\n${request.ToCurlCommand()}\n==============================`) end if #else - if m._logCurlCommand = true - LogInfo(`======== curl command ========\n${m.ToCurlCommand()}\n==============================`) + if request._logCurlCommand = true + LogInfo(`======== curl command ========\n${request.ToCurlCommand()}\n==============================`) end if #end if - if m._toFilePath <> invalid and m._method <> "GET" - throw "ToFile() can only be used with GET requests." - end if - - if m._bodyFilePath <> invalid and m._method <> "POST" - throw "FromFile() can only be used with POST requests." - end if - - if m._method = "POST" - if m._bodyFilePath <> invalid - m._sent = m.urlTransfer.AsyncPostFromFile(m._bodyFilePath) + if method = "GET" + if request._saveBodyToFilePath <> invalid + sent = urlTransfer.AsyncGetToFile(request._saveBodyToFilePath) else - body = m._body - if body = invalid - body = "" - end if - m._sent = m.urlTransfer.AsyncPostFromString(body) + sent = urlTransfer.AsyncGetToString() end if - else if m._method = "GET" - if m._toFilePath <> invalid - m._sent = m.urlTransfer.AsyncGetToFile(m._toFilePath) - else - m._sent = m.urlTransfer.AsyncGetToString() - end if - else if m._method = "HEAD" - m._sent = m.urlTransfer.AsyncHead() + else if method = "HEAD" + sent = urlTransfer.AsyncHead() else - m.urlTransfer.SetRequest(m._method) - body = m._body - if body = invalid - body = "" + if method <> "POST" + urlTransfer.SetRequest(method) + end if + if request._fileBodyPath <> invalid + sent = urlTransfer.AsyncPostFromFile(request._fileBodyPath) + else + sent = urlTransfer.AsyncPostFromString(ValidString(request._textBody)) end if - m._sent = m.urlTransfer.AsyncPostFromString(body) end if - if m._sent <> true + if not sent LogError("Failed to send request") - else - m._timer = CreateObject("roTimeSpan") + m.Throttle() + m.Complete(m.NewResponse({ notSentReason: "roUrlTransfer refused the request" })) + return end if - - return m + m._urlTransfer = urlTransfer + m._transferId = urlTransfer.GetIdentity() + m._attemptDeadlineMs = m._clock.TotalMilliseconds() + request._attemptTimeoutMs end function - function IsCancelled() as boolean - if m._cancelled = true - return m._cancelled - end if - - if CancellationUtils.IsCancelled(m._cancellation) - m._cancelled = true - end if - - return m._cancelled = true + ' A response that reads the request's cancellation when asked whether it is cancelled. + private function NewResponse(properties as object) as Response + properties.cancellation = m._request._cancellation + return new Response(properties) end function - function Await() as HttpResponse - triesLeft = m._tryCount - response = invalid - - response = m.AwaitInternal() - if response.IsSuccess() or response.IsTimedOut() or response.IsCancelled() - return response - end if - triesLeft -= 1 - - while triesLeft > 0 - tryNumber = m._tryCount - triesLeft + 1 - shouldRetry = true - if IsFunction(m._retryCallback) - try - callbackResult = m._retryCallback({ - tryNumber: tryNumber - tryCount: m._tryCount - request: m - response: response - }) - shouldRetry = not IsBool(callbackResult) or callbackResult - catch error - #if DEBUG - throw error - #else - LogError("Retry callback failed:", ErrorUtils.Format(error)) - #end if - end try - end if - - backoffMs = 1000 + Rnd(2000) - if shouldRetry - LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms") - else - LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nNot retrying: the retry callback declined`) - end if - LogTelemetryEvent({ - level: "warning" - message: response.ErrorMessage() - attachments: [{ - filename: "request.txt" - content_type: "text/plain" - data: m.ToCurlCommand() - }] - }) - if not shouldRetry - return response - end if - - m.urlTransfer = invalid - m._cache = invalid - m._sent = invalid - - sleep(backoffMs) - - response = m.AwaitInternal() - if response.IsTimedOut() or response.IsCancelled() or (response.StatusCode() >= 200 and response.StatusCode() < 500) - return response - end if - triesLeft -= 1 - end while - - return response + private function OnAttemptTimeout() as void + LogInfo("Timeout", m.Describe(), "after", m._request._attemptTimeoutMs, "ms") + m._urlTransfer.AsyncCancel() + m.OnAttemptEnded(m.NewResponse({ timedOut: true })) end function - private function AwaitInternal() as HttpResponse - if m.urlTransfer = invalid and m._cache = invalid - m.Send() + private function OnAttemptEnded(response as Response) as void + m._urlTransfer = invalid + m.Throttle() + request = m._request + ' No retry can follow: complete without reading the cancellation, a rendezvous. + if m._attemptCount > request._retryCount or not m.MayRetry(response) or (request._retryPredicate = invalid and response.IsSuccess()) + m.Complete(response) + return + end if + ' Cancelled before its event was read: neither retried nor reported. + if response.IsCancelled() + m.Complete(response) + return + end if + retryReason = m.RetryReason(response) + if retryReason = "" + if not response.IsSuccess() + m.ReportAttempt(response.ErrorMessage(), `\nNot retrying: the retry callback declined`) + end if + m.Complete(response) + return end if - if m._sent <> true or m._cache <> invalid - #if NETWORK_THROTTLE - #if DEBUG - sleep(1000 + Rnd(2000)) - #end if - #end if + delayMs = request._retryDelayMs + Rnd(request._retryDelayMs + 1) - 1 + m.ReportAttempt(retryReason, `\nRetrying in ${delayMs} ms`) + m._retryAtMs = m._clock.TotalMilliseconds() + delayMs + end function - return new HttpResponse(m, invalid) + ' A warning, and a telemetry event unless NoTelemetry, for an attempt that could have been retried. + private function ReportAttempt(message as string, outcome as string) as void + request = m._request + LogWarnNoTelemetry(m.Describe(), "attempt", m._attemptCount, "ended:", message, outcome) + if request._noTelemetry = true + return end if + LogTelemetryEvent({ + level: "warning" + message: message + attachments: [{ + filename: "request.txt" + content_type: "text/plain" + data: request.ToCurlCommand() + }] + }) + end function - if m.IsCancelled() - return new HttpResponse(m, invalid) - end if - - messagePort = m.urlTransfer.GetMessagePort() - if messagePort = invalid - throw "Can't await request without a message port. use Send(andForget=false) in order to await request." - end if - - CancellationUtils.ObserveCancellationScoped(m._cancellation, messagePort) - - msg = wait(m._timeoutSeconds * 1000, messagePort) - + ' NETWORK_THROTTLE: a cache hit, an attempt not sent, and every attempt's end come 1 to 3s late. + private function Throttle() as void #if NETWORK_THROTTLE #if DEBUG sleep(1000 + Rnd(2000)) #end if #end if - - CancellationUtils.UnobserveCancellationScoped(m._cancellation) - - if msg = invalid - ' timeout - LogInfo("Timeout", "ID:", m.urlTransfer.GetIdentity()) - m.urlTransfer.AsyncCancel() - else - eventType = type(msg) - if eventType = "roUrlEvent" - LogInfo("Finished ID:", m.urlTransfer.GetIdentity(), "after", m._timer.TotalMilliseconds(), "ms") - else if CancellationUtils.IsCancellationEvent(m._cancellation, msg) - LogInfo("Cancelled", "ID:", m.urlTransfer.GetIdentity()) - m._cancelled = true - m.urlTransfer.AsyncCancel() - end if - end if - - response = new HttpResponse(m, msg) - - if m.IsCancelled() - return response - end if - - HttpClientCache.Set(response) - return response end function - function IsCompleted() as boolean - if m.urlTransfer = invalid + ' The attempts RetryCount allows to retry: not a timed-out one; after the first, only a 5xx or a network failure. + private function MayRetry(response as Response) as boolean + if response.IsTimedOut() return false end if - - messagePort = m.urlTransfer.GetMessagePort() - message = messagePort.PeekMessage() - if message <> invalid + if m._attemptCount = 1 return true end if + statusCode = response.StatusCode() + return statusCode < 200 or statusCode >= 500 + end function - if m._timer <> invalid - elapsedMs = m._timer.TotalMilliseconds() - if elapsedMs > m._timeoutSeconds * 1000 - return true + ' Why to retry the attempt, "" not to: RetryIf's reason, or else the failure's error message. + private function RetryReason(response as Response) as string + ' Called through a local, so the predicate's m isn't the request. + retryPredicate = m._request._retryPredicate + if retryPredicate = invalid + return response.ErrorMessage() + end if + try + reason = retryPredicate(response) + catch error + #if DEBUG + throw error + #else + LogError("RetryIf failed:", ErrorUtils.Format(error)) + return response.ErrorMessage() + #end if + end try + #if DEBUG + Assert.IsTrue(IsString(reason) or type(reason) = "Invalid", `RetryIf returned a ${type(reason)}: it returns the reason to retry, "" or invalid not to`) + #end if + if not IsString(reason) + return "" + end if + return reason + end function + + ' The method and url, then the transfer ID of the attempt sent last, the RequestId of its error message: none + ' for a cache hit, an attempt not sent, or a cancellation outside an attempt. + private function Describe() as string + description = `${m._request._method} ${m._request.GetFullUrl()}` + if m._transferId <> invalid + description += ` ID: ${m._transferId}` + end if + return description + end function + + private function Complete(response as Response) as void + m._response = response + LogInfo("Completed", m.Describe(), response.StatusCode(), "after", m._clock.TotalMilliseconds(), "ms,", m._attemptCount, "attempt(s)") + ' A 3xx counts as a success, but isn't cached. + if m._cacheFilePath = invalid or response.StatusCode() < 200 or response.StatusCode() >= 300 + return + end if + ' A body saved to a file is in the file; an empty text body isn't cached. + body = "" + if response._bodyFilePath = invalid + body = response.Text() + if body = "" + return end if end if - - return false - end function - - private function CreateRoUrlTransfer() as object - urlTransfer = CreateObject("roUrlTransfer") - if urlTransfer = invalid - return invalid - end if - - if COMPRESSION_ENABLED - ' Enables gzip encoding of transfers - urlTransfer.EnableEncodings(true) - end if - - urlTransfer.RetainBodyOnError(true) - if LCase(left(m._url, 6)).StartsWith("https:") - urlTransfer.SetCertificatesFile("common:/certs/ca-bundle.crt") - urlTransfer.InitClientCertificates() - end if - - if m._useHttp2 = true - urlTransfer.SetHttpVersion("http2") - end if - - return urlTransfer - end function - - function BuildUrl() as string - if m._fullUrl <> invalid - return m._fullUrl - end if - - m._fullUrl = UrlUtils.BuildUrl(m._url, m._pathParams, m._queryParams) - return m._fullUrl + HttpCache.Write(m._cacheFilePath, m._request._cacheSeconds, response.StatusCode(), response.Headers(), body) end function end class - class HttpResponse - - public request as HttpRequest - public event as object - - function new(request as HttpRequest, event as object) - m.request = request - m.event = event + ' 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. + class PendingResponse + function new(startedFetch as Fetch, messagePort as object, cancellation as dynamic, cancellationObserver as dynamic) + m._fetch = startedFetch + m._messagePort = messagePort + m._cancellation = cancellation + m._cancellationObserver = cancellationObserver + m._clock = CreateObject("roTimespan") end function + function Await() as Response + return m.WaitForResponse(-1) + end function + + ' The response, or invalid if it isn't in within timeoutMs. + function Wait(timeoutMs as integer) as dynamic + #if DEBUG + Assert.IsTrue(timeoutMs > 0, `Wait(${timeoutMs}): timeoutMs must be above 0; Poll() checks without blocking`) + #end if + return m.WaitForResponse(timeoutMs) + end function + + function Poll() as dynamic + return m.WaitForResponse(0) + end function + + function Cancel() as void + m._fetch.Cancel() + m.StopObservingCancellation() + end function + + ' 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 + 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 + end if + message = wait(waitMs, m._messagePort) + end if + end if + end while + m.StopObservingCancellation() + return m._response + end function + + private function StopObservingCancellation() as void + if m._cancellationObserver <> invalid + m._cancellationObserver.nodeDestroy = true + m._cancellationObserver = invalid + end if + end function + end class + + class Response + function new(properties as object) + m._urlEvent = properties.urlEvent + m._statusCode = properties.statusCode + m._headers = properties.headers + m._text = properties.text + m._bodyFilePath = properties.bodyFilePath + m._cached = properties.cached = true + m._timedOut = properties.timedOut = true + m._cancelled = properties.cancelled = true + m._cancellation = properties.cancellation + m._notSentReason = properties.notSentReason + end function + + ' The HTTP status; 0 when no response came, a negative curl code when the transfer failed. function StatusCode() as integer - if m._statusCode <> invalid - return m._statusCode + if m._statusCode = invalid + if m._urlEvent <> invalid + m._statusCode = m._urlEvent.GetResponseCode() + else + m._statusCode = 0 + end if end if - - if m.IsCached() - m._statusCode = m.request._cache.statusCode - return m._statusCode - end if - - if type(m.event) <> "roUrlEvent" - m._statusCode = 0 - else - m._statusCode = m.event.GetResponseCode() - end if - return m._statusCode end function - function OverrideStatusCode(statusCode as integer) - m._statusCode = statusCode - end function - - function OverrideText(text as string) - m._text = text - end function - - function OverrideJson(json as object) - m._json = json - end function - - function OverrideHeaders(headers as object) - m._headers = headers - end function - - function OverrideErrorMessage(errorMessage as string) - m._errorMessage = errorMessage - end function - + ' A 2xx or 3xx status. Redirects are followed, so a 3xx is one that couldn't be. function IsSuccess() as boolean statusCode = m.StatusCode() return statusCode >= 200 and statusCode < 400 end function - function IsCached() as boolean - return m.request._cache <> invalid - end function - function IsTimedOut() as boolean - return not m.IsCached() and m.event = invalid + return m._timedOut end function + ' Cancelled by its fetch, or since: the request's cancellation is read at each call, so an answer taken before + ' a later cancel reads as cancelled too. Once it reads as cancelled it stays so, the cancellation reset or not. function IsCancelled() as boolean - return m.request.IsCancelled() + if not m._cancelled and CancellationUtils.IsCancelled(m._cancellation) + m._cancelled = true + end if + return m._cancelled end function - function Text() as dynamic - if m._text <> invalid - return m._text - end if - - if m.IsCached() - m._text = m.request._cache.body - return m._text - end if - - if type(m.event) <> "roUrlEvent" - return invalid - else - m._text = m.event.GetString() - end if - return m._text - end function - - function Json() as object - if m._json <> invalid - return m._json - end if - - text = m.Text() - if text = invalid - return invalid - end if - m._json = StringUtils.ParseJsonSafe(text) - return m._json + function IsCached() as boolean + return m._cached end function + ' Case-insensitive keys. function Headers() as object - if m._headers <> invalid - return m._headers - end if - - if m.IsCached() - m._headers = m.request._cache.headers - return m._headers - end if - - if type(m.event) = "roUrlEvent" - m._headers = m.event.GetResponseHeaders() - else - m._headers = {} + if m._headers = invalid + if m._urlEvent <> invalid + m._headers = m._urlEvent.GetResponseHeaders() + else + m._headers = {} + end if end if return m._headers end function - function ErrorMessage(includeBody = true as boolean) as string - if m._errorMessage <> invalid - return m._errorMessage + ' The Retry-After header in seconds; invalid when it is absent or an HTTP date. + function RetryAfterSeconds() as dynamic + retryAfter = m.Headers()["retry-after"] + if not IsString(retryAfter) + return invalid end if - - if m.IsSuccess() - m._errorMessage = "" - else - if m.request._sent <> true - m._errorMessage = Tr(Locale.HttpClient.RequestNotSent) - else if m.IsCancelled() - m._errorMessage = Tr(Locale.HttpClient.RequestCancelled) - else if m.IsTimedOut() - m._errorMessage = Tr(Locale.HttpClient.RequestTimedOut) - else if type(m.event) = "roUrlEvent" - m._errorMessage = `${Tr(Locale.HttpClient.Reason)}:${m.event.GetFailureReason() }\nStatusCode: ${m.StatusCode()}\nRequestId: ${m.event.GetSourceIdentity()}` - if includeBody - m._errorMessage += `\nBody: ${m.event.GetString()}` - end if - end if + retryAfter = retryAfter.Trim() + seconds = retryAfter.ToInt() + if seconds < 0 or seconds.ToStr() <> retryAfter + return invalid end if - - return m._errorMessage + return seconds end function + function Text() as string + #if DEBUG + Assert.IsTrue(m._bodyFilePath = invalid, `Text and Json on a SaveBodyToFile response: the body is in ${m._bodyFilePath}`) + #end if + if m._text = invalid + if m._urlEvent <> invalid + m._text = m._urlEvent.GetString() + else + m._text = "" + end if + end if + return m._text + end function + + ' The parsed body; invalid when it isn't JSON. + function Json() as dynamic + if m._json = invalid + m._json = StringUtils.ParseJsonSafe(m.Text()) + end if + return m._json + end function + + ' Empty on success. + function ErrorMessage() as string + if m.IsSuccess() + return "" + end if + if m._notSentReason <> invalid + return `${Tr(Locale.HttpClient.RequestNotSent)} ${m._notSentReason}` + end if + if m.IsCancelled() + return Tr(Locale.HttpClient.RequestCancelled) + end if + if m._timedOut + return Tr(Locale.HttpClient.RequestTimedOut) + end if + ' A response built in the app, such as the built-in Invidious backend's, has no transfer to report. + if m._urlEvent = invalid + message = `StatusCode: ${m.StatusCode()}` + else + message = `${Tr(Locale.HttpClient.Reason)}:${m._urlEvent.GetFailureReason()}\nStatusCode: ${m.StatusCode()}\nRequestId: ${m._urlEvent.GetSourceIdentity()}` + end if + if m._bodyFilePath = invalid + message += `\nBody: ${m.Text()}` + end if + return message + end function end class -end namespace - -namespace HttpClientCache - function GetLocation(request as HttpClient.HttpRequest) as dynamic - if request._cacheLocation <> invalid - return request._cacheLocation - end if - cacheKey = request.BuildUrl() - if request._headers <> invalid - headersString = FormatJson(request._headers) - cacheKey = cacheKey + headersString - end if - - hash = CryptoUtils.GetMd5(cacheKey) - request._cacheLocation = `cachefs:/request_v2_${hash}.json` - return request._cacheLocation - end function - - function GetFileSystem(request as HttpClient.HttpRequest) as object - if request._fileSystem = invalid - request._fileSystem = CreateObject("roFileSystem") - end if - return request._fileSystem - end function - - function Exists(request as HttpClient.HttpRequest) as boolean - fileSystem = GetFileSystem(request) - if fileSystem = invalid - return false - end if - cacheLocation = GetLocation(request) - return fileSystem.Exists(cacheLocation) - end function - - function Get(request as HttpClient.HttpRequest) as object - if request._noCache = true - return invalid - end if - - if request._method <> "GET" - return invalid - end if - - if not Exists(request) - return invalid - end if - - cacheLocation = GetLocation(request) - cacheText = ReadAsciiFile(cacheLocation) - if cacheText = "" - return invalid - end if - - firstLineIndex = cacheText.InStr(`\n`) - if firstLineIndex = -1 - LogWarn("Failed to parse cache.") - Delete(request) - return invalid - end if - - metadataText = cacheText.Left(firstLineIndex) - metadata = StringUtils.ParseJsonSafe(metadataText) - if metadata = invalid - LogWarn("Failed to parse metadata from cache.") - Delete(request) - return invalid - end if - - headersText = cacheText.Mid(firstLineIndex + 1, metadata.headers) - headers = StringUtils.ParseJsonSafe(headersText) - if headers = invalid - LogWarn("Failed to parse headers from cache.") - Delete(request) - return invalid - end if - - expireSeconds = request._expireSeconds - - if expireSeconds = invalid and headers <> invalid - expireSeconds = ParseHeadersForCacheControl(headers) - end if - - if expireSeconds = invalid - return invalid - end if - - date = CreateObject("roDateTime") - nowTimestamp = date.AsSeconds() - if metadata.timestamp + expireSeconds < nowTimestamp - Delete(request) + function CreateUrlTransfer(url as string, headers as object, messagePort as object) as object + urlTransfer = CreateObject("roUrlTransfer") + if urlTransfer = invalid return invalid - end if - - body = "" - if metadata.body > 0 - body = cacheText.Mid(firstLineIndex + 1 + metadata.headers, metadata.body) - end if - - return { - statusCode: metadata.statusCode - headers: headers - body: body - } - end function - - function Set(response as HttpClient.HttpResponse) as void - if response.request._noCache = true or response.request._method <> "GET" - return - end if - - if not response.IsSuccess() - return - end if - - if response.request._expireSeconds = invalid - headers = response.Headers() - if headers = invalid - return - end if - if ParseHeadersForCacheControl(headers) = invalid - return - end if - end if - - fileSystem = GetFileSystem(response.request) - if fileSystem = invalid - return end if - - body = ValidString(response.Text()) - if body = "" - return + if COMPRESSION_ENABLED + urlTransfer.EnableEncodings(true) end if - - date = CreateObject("roDateTime") - timestamp = date.AsSeconds() - - ' Cache file format: - ' First line is a json payload of metadata: - ' { - ' timestamp: number, - ' statusCode: number, - ' headers: number, ' this is the size of the headers json array in chars - ' body: number ' this is the size of the body in chars - ' } - ' {headers} ' a json objects with headers, string size matching metadata.headers - ' {body} ' the body as is, string size matching metadata.body - - jsonHeaders = FormatJson(response.Headers()) - - cacheMetadata = { - timestamp: timestamp - statusCode: response.StatusCode() - headers: jsonHeaders.Len() - body: body.Len() - } - - jsonMetadata = FormatJson(cacheMetadata) - - cacheLocation = GetLocation(response.request) - - WriteAsciiFile(cacheLocation, jsonMetadata + `\n` + jsonHeaders + body) - end function - - function Delete(request as HttpClient.HttpRequest) as boolean - fileSystem = GetFileSystem(request) - if fileSystem = invalid - return false + urlTransfer.RetainBodyOnError(true) + if LCase(Left(url, 6)) = "https:" + urlTransfer.SetCertificatesFile("common:/certs/ca-bundle.crt") + urlTransfer.InitClientCertificates() end if - - cacheLocation = GetLocation(request) - return fileSystem.Delete(cacheLocation) + urlTransfer.SetUrl(url) + urlTransfer.SetHeaders(headers) + urlTransfer.SetMessagePort(messagePort) + return urlTransfer end function - - function ParseHeadersForCacheControl(headers as object) as dynamic - cacheControl = headers["cache-control"] - if cacheControl = invalid - return invalid - end if - - cacheControlDirectives = cacheControl.split(",") - for each cacheControlDirective in cacheControlDirectives - keyValue = cacheControlDirective.Trim().split("=") - name = keyValue[0].Trim() - if keyValue.Count() > 1 - value = keyValue[1].Trim() - else - value = invalid - end if - if name = "no-store" or name = "no-cache" - return invalid - else if name = "max-age" - return val(value) - end if - end for - - return invalid - end function end namespace diff --git a/playlet-lib/src/source/services/HttpClient.spec.bs b/playlet-lib/src/source/services/HttpClient.spec.bs index 8a19c8d4..66882842 100644 --- a/playlet-lib/src/source/services/HttpClient.spec.bs +++ b/playlet-lib/src/source/services/HttpClient.spec.bs @@ -1,4 +1,5 @@ import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/tests/HttpTestServer.bs" import "pkg:/source/tests/LoggingGlobals.bs" namespace Tests @@ -6,48 +7,1531 @@ namespace Tests @suite class HttpClientTests 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 - ' Nothing listens on port 1: the connection is refused, a failure that is not a timeout. - function RefusedRequest(retryCallback as function) as HttpClient.HttpRequest - return HttpClient.Head("http://127.0.0.1:1/").NoCache().TryCount(2).RetryCallback(retryCallback) + function ServerUrl(path as string) as string + return Tests.HttpTestServerUrl(path) end function - @describe("HttpClient.HttpRequest.Await") + function Hits(path as string) as integer + return Tests.HttpTestServerHits(m.server, path) + end function - @it("reports a failed attempt the retry callback declines, without retrying") - function _() - request = m.RefusedRequest(function(context as object) as boolean - context.request.declinedError = context.response.ErrorMessage() - return false - end function) + function AssertNotSentOnce(lines as string[], errorMessage as string) + errors = [] as string[] + for each line in lines + m.assertEqual(line.InStr("[WARN]"), -1, line) + if line.InStr("[ERROR]") <> -1 + errors.Push(line) + end if + end for + m.assertEqual(errors.Count(), 1) + m.assertEqual(Tests.LogLineMessage(errors[0]), errorMessage) + m.assertEqual(m.global.telemetry.LogError, errors[0]) + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + function AssertLogged(lines as string[], part as string) as void + for each line in lines + if line.InStr(part) <> -1 + return + end if + end for + m.fail(`no line logged contains "${part}" in ${FormatJson(lines)}`) + end function + + function AssertNotLogged(lines as string[], part as string) + for each line in lines + m.assertEqual(line.InStr(part), -1, line) + end for + end function + + ' The message action(subject) throws, invalid if it throws none. + function ThrownMessage(action as function, subject as object) as dynamic + try + action(subject) + catch error + return error.message + end try + return invalid + end function + + function AssertTook(timer as object, fromMs as integer, toMs as integer) + elapsedMs = timer.TotalMilliseconds() + m.assertTrue(elapsedMs >= fromMs and elapsedMs < toMs, `took ${elapsedMs} ms, expected ${fromMs}-${toMs}`) + end function + + function AssertContains(text as string, part as string) + m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`) + end function + + function CountOf(text as string, part as string) as integer + count = 0 + index = text.InStr(part) + while index <> -1 + count += 1 + index = text.InStr(index + part.Len(), part) + end while + return count + end function + + function CreateCancellation() as object + node = CreateObject("roSGNode", "Node") + node.addField("cancel", "boolean", false) + return CancellationUtils.CreateCancellation(node, "cancel", true) + end function + + ' A task loop's port, with a node field of its own observed on it. + function CreateLoop() as object + node = CreateObject("roSGNode", "Node") + node.addField("ping", "integer", true) + port = CreateObject("roMessagePort") + node.ObserveField("ping", port) + return { node: node, port: port, pings: 0, pingEveryMessage: false } + end function + + ' Waits on the loop's own port the way a task loop does, at most wakeMs at a time, and polls the pending + ' response at every wake, until it returns the response or limitMs passed. + function RunLoop(loop as object, pending as object, wakeMs as integer, limitMs as integer) as dynamic timer = CreateObject("roTimespan") + while timer.TotalMilliseconds() < limitMs + message = wait(wakeMs, loop.port) + if type(message) = "roSGNodeEvent" + loop.pings += 1 + end if + response = pending.Poll() + 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 + + ' A GET whose cache entry was deleted. + function GetWithoutCacheEntry(path as string) as HttpClient.Request + request = HttpClient.Get(m.ServerUrl(path)) + DeleteFile(m.CacheFilePath(request)) + return request + end function + + @describe("HttpClient.Request") + + @it("sends the method, headers, query and path params, and a JSON body") + function _() + response = HttpClient.Post(m.ServerUrl("/{route}")).PathParam("route", "echo").QueryParam("q", "a b").QueryParams({ n: 2 }).Header("X-One", "1").JsonBody({ key: "value" }).Await() + echo = response.Json() + m.assertEqual(echo.method, "POST") + m.AssertContains(echo.path, "/echo?") + m.AssertContains(echo.path, "q=a%20b") + m.AssertContains(echo.path, "n=2") + m.assertEqual(echo.headers["x-one"], "1") + m.assertEqual(echo.headers["content-type"], "application/json") + m.assertEqual(StringUtils.ParseJsonSafe(echo.body).key, "value") + end function + + @it("sends an array query param as given") + function _() + echo = HttpClient.Get(m.ServerUrl("/echo")).QueryParamArray("ids", ["a", "b"], UrlUtils.QueryParamArrayType.CommaSeparated).Await().Json() + m.assertEqual(echo.path, "/echo?ids=a,b") + end function + + @it("sends a form in the order given") + function _() + echo = HttpClient.Post(m.ServerUrl("/echo")).FormBody([{ key: "z", value: "1" }, { key: "a", value: "x y" }]).Await().Json() + m.assertEqual(echo.body, "z=1&a=x%20y") + m.assertEqual(echo.headers["content-type"], "application/x-www-form-urlencoded") + end function + + @it("sends a body from a file") + function _() + WriteAsciiFile("tmp:/http-body.txt", "from a file") + echo = HttpClient.Put(m.ServerUrl("/echo")).FileBody("tmp:/http-body.txt").Await().Json() + m.assertEqual(echo.method, "PUT") + m.assertEqual(echo.body, "from a file") + end function + + @it("sends DELETE and HEAD") + function _() + m.assertEqual(HttpClient.Delete(m.ServerUrl("/echo")).Await().Json().method, "DELETE") + response = HttpClient.Head(m.ServerUrl("/echo")).Await() + m.assertEqual(response.StatusCode(), 200) + m.assertEqual(response.Text(), "") + end function + + @it("sends a text body as given") + function _() + echo = HttpClient.Post(m.ServerUrl("/echo")).TextBody("plain text").Await().Json() + m.assertEqual(echo.method, "POST") + m.assertEqual(echo.body, "plain text") + end function + + @it("sends a JSON array body") + function _() + echo = HttpClient.Post(m.ServerUrl("/echo")).JsonBody([1, 2, 3]).Await().Json() + m.assertEqual(echo.body, "[1,2,3]") + m.assertEqual(echo.headers["content-type"], "application/json") + end function + + @it("sends a form given as an AA") + function _() + echo = HttpClient.Post(m.ServerUrl("/echo")).FormBody({ a: "x y" }).Await().Json() + m.assertEqual(echo.body, "a=x%20y") + m.assertEqual(echo.headers["content-type"], "application/x-www-form-urlencoded") + end function + + @it("sends headers and path params given as AAs") + function _() + echo = HttpClient.Get(m.ServerUrl("/{route}")).PathParams({ route: "echo" }).Headers({ "X-One": "1", "X-Two": "2" }).Await().Json() + m.assertEqual(echo.path, "/echo") + m.assertEqual(echo.headers["x-one"], "1") + m.assertEqual(echo.headers["x-two"], "2") + end function + + @it("sends an array query param repeated") + function _() + echo = HttpClient.Get(m.ServerUrl("/echo")).QueryParamArray("ids", [1, 2, 3], UrlUtils.QueryParamArrayType.Repeated).Await().Json() + m.assertEqual(echo.path, "/echo?ids=1&ids=2&ids=3") + end function + + @it("asks for a compressed response") + function _() + echo = HttpClient.Get(m.ServerUrl("/echo")).Await().Json() + m.AssertContains(ValidString(echo.headers["accept-encoding"]), "gzip") + end function + + @it("builds its url again after a param changes, and sends the url built last") + function _() + request = HttpClient.Get("http://example.com/{id}").PathParam("id", "1") + m.assertEqual(request.GetFullUrl(), "http://example.com/1") + request.QueryParam("a", "1") + m.assertEqual(request.GetFullUrl(), "http://example.com/1?a=1") + request.PathParams({ id: "2" }) + m.assertEqual(request.GetFullUrl(), "http://example.com/2?a=1") + request.QueryParams({ a: "2" }) + m.assertEqual(request.GetFullUrl(), "http://example.com/2?a=2") + request.PathParam("id", "3") + m.assertEqual(request.GetFullUrl(), "http://example.com/3?a=2") + + sent = HttpClient.Get(m.ServerUrl("/echo")).QueryParam("v", "1") + m.assertEqual(sent.Await().Json().path, "/echo?v=1") + sent.QueryParam("v", "2") + m.assertEqual(sent.Await().Json().path, "/echo?v=2") + end function + + @it("writes a curl command for a GET, with its headers") + function _() + command = HttpClient.Get("http://example.com/a").QueryParam("q", "1").Header("X-Test", "true").ToCurlCommand() + expected = `curl "http://example.com/a?q=1" \\ + --max-time 30 \\ + --location \\ + --show-error \\ + --compressed \\ + -H 'X-Test: true'` + m.assertEqual(command, expected) + end function + + @it("writes a curl command for a HEAD") + function _() + command = HttpClient.Head("http://example.com").AttemptTimeoutMs(1500).ToCurlCommand() + expected = `curl "http://example.com" \\ + --head \\ + --max-time 1.5 \\ + --location \\ + --show-error \\ + --compressed` + m.assertEqual(command, expected) + end function + + @it("writes a curl command for a POST, with its text or file body") + function _() + command = HttpClient.Post("http://example.com").TextBody("body").ToCurlCommand() + expected = `curl "http://example.com" \\ + --request POST \\ + --max-time 30 \\ + --location \\ + --show-error \\ + --compressed \\ + -d 'body'` + m.assertEqual(command, expected) + m.AssertContains(HttpClient.Put("http://example.com").FileBody("tmp:/body.bin").ToCurlCommand(), ` \\\n --data-binary @tmp:/body.bin`) + end function + + @it("reads back its method, headers and text body") + function _() + request = new HttpClient.Request("patch", "http://x/") + request.Header("X-One", "1").JsonBody({ key: "value" }) + m.assertEqual(request.GetMethod(), "PATCH") + m.assertEqual(request.GetHeaders()["x-one"], "1") + m.assertEqual(request.GetTextBody(), `{"key":"value"}`) + m.assertInvalid(HttpClient.Post("http://x/").GetTextBody()) + m.assertInvalid(HttpClient.Post("http://x/").TextBody("x").FileBody("tmp:/x").GetTextBody()) + end function + + @it("logs the curl command of every attempt it sends in DEBUG, unless LogCurlCommand(false)") + function _() + logPort = CreateObject("roMessagePort") + m.global.logger.ObserveFieldScoped("logLine", logPort) + HttpClient.Get(m.ServerUrl("/echo")).QueryParam("curl", "default").Await() + HttpClient.Get(m.ServerUrl("/echo")).QueryParam("curl", "off").LogCurlCommand(false).Await() + cached = m.GetWithoutCacheEntry("/maxage/60/curl") + cached.Await() + m.assertTrue(cached.Await().IsCached()) + HttpClient.Get(m.ServerUrl("/seq/curl/503,200")).RetryCount(1).RetryDelayMs(0).NoTelemetry().Await() + loggedText = "" + message = wait(100, logPort) + while message <> invalid + loggedText += message.GetData() + message = wait(100, logPort) + end while + m.global.logger.UnobserveFieldScoped("logLine") + m.AssertContains(loggedText, `curl "${m.ServerUrl("/echo?curl=default")}"`) + m.assertEqual(loggedText.InStr(`curl "${m.ServerUrl("/echo?curl=off")}"`), -1) + m.assertEqual(m.CountOf(loggedText, `curl "${m.ServerUrl("/maxage/60/curl")}"`), 1) + m.assertEqual(m.CountOf(loggedText, `curl "${m.ServerUrl("/seq/curl/503,200")}"`), 2) + end function + + @it("logs every attempt it sends at info, and none on a cache hit") + function _() + url = m.ServerUrl("/seq/sending/503,200") + sendingCount = 0 + for each line in Tests.LogLines(function(url as string) as void + HttpClient.Get(url).RetryCount(1).RetryDelayMs(0).NoTelemetry().Await() + end function, url) + if line.InStr(`Sending GET ${url} ID:`) <> -1 + m.AssertContains(line, "[INFO]") + sendingCount += 1 + end if + end for + m.assertEqual(sendingCount, 2) + + m.GetWithoutCacheEntry("/maxage/60/sending").Await() + for each line in Tests.LogLines(function(url as string) as void + HttpClient.Get(url).Await() + end function, m.ServerUrl("/maxage/60/sending")) + m.assertEqual(line.InStr("Sending "), -1, line) + end for + end function + + @it("logs each attempt's transfer ID beside its method and url, and none outside a transfer") + function _() + url = m.ServerUrl("/seq/transferids/503,200") + lines = Tests.LogLines(function(url as string) as void + HttpClient.Get(url).RetryCount(1).RetryDelayMs(0).NoTelemetry().Await() + end function, url) + ids = [] as string[] + for each line in lines + sending = `Sending GET ${url} ID: ` + if line.InStr(sending) <> -1 + ids.Push(Tests.LogLineMessage(line).Mid(Tests.LogLineMessage(line).InStr(sending) + sending.Len()).Trim()) + end if + end for + m.assertEqual(ids.Count(), 2) + m.assertNotEqual(ids[0], ids[1]) + m.AssertLogged(lines, `GET ${url} ID: ${ids[0]} attempt 1 ended: `) + m.AssertLogged(lines, `Completed GET ${url} ID: ${ids[1]} 200 after `) + + url = m.ServerUrl("/delay/2000") + lines = Tests.LogLines(function(url as string) as void + HttpClient.Get(url).AttemptTimeoutMs(300).Await() + end function, url) + m.AssertLogged(lines, `Timeout GET ${url} ID: `) + m.AssertLogged(lines, `Completed GET ${url} ID: `) + + cancellation = m.CreateCancellation() + cancellation.node.cancel = true + url = m.ServerUrl("/seq/transferidcancelled/200") + lines = Tests.LogLines(function(request as object) as void + request.Await() + end function, HttpClient.Get(url).Cancellation(cancellation)) + m.AssertLogged(lines, `Cancelled GET ${url}`) + m.AssertNotLogged(lines, " ID: ") + m.AssertLogged(lines, `Completed GET ${url} 0 after `) + + m.GetWithoutCacheEntry("/maxage/60/transferids").Await() + url = m.ServerUrl("/maxage/60/transferids") + lines = Tests.LogLines(function(url as string) as void + HttpClient.Get(url).Await() + end function, url) + m.AssertLogged(lines, `Cache hit GET ${url}`) + m.AssertNotLogged(lines, " ID: ") + end function + + @it("completes a request roUrlTransfer can't be created for at once, logging an error, whatever its RetryCount") + function _() + m.stubCall(HttpClient.CreateUrlTransfer, invalid) + result = { url: m.ServerUrl("/seq/uncreated/200"), response: invalid } + lines = Tests.LogLines(function(result as object) as void + result.response = HttpClient.Get(result.url).RetryCount(2).RetryDelayMs(0).Await() + end function, result) + m.AssertNotSentOnce(lines, "Failed to create roUrlTransfer") + m.assertEqual(result.response.ErrorMessage(), `${Tr(Locale.HttpClient.RequestNotSent)} roUrlTransfer couldn't be created`) + m.assertEqual(m.Hits("/seq/uncreated/200"), 0) + end function + + @it("completes a request roUrlTransfer refuses at once, logging an error, whatever its RetryCount") + function _() + ' A transfer already in progress refuses another. + busyTransfer = CreateObject("roUrlTransfer") + busyTransfer.SetUrl(m.ServerUrl("/delay/2000")) + busyTransfer.SetMessagePort(CreateObject("roMessagePort")) + busyTransfer.AsyncGetToString() + m.stubCall(HttpClient.CreateUrlTransfer, busyTransfer) + result = { url: m.ServerUrl("/seq/refused/200"), response: invalid } + lines = Tests.LogLines(function(result as object) as void + result.response = HttpClient.Get(result.url).RetryCount(2).RetryDelayMs(0).Await() + end function, result) + busyTransfer.AsyncCancel() + m.AssertNotSentOnce(lines, "Failed to send request") + m.assertEqual(result.response.ErrorMessage(), `${Tr(Locale.HttpClient.RequestNotSent)} roUrlTransfer refused the request`) + m.assertEqual(m.Hits("/seq/refused/200"), 0) + end function + + @describe("HttpClient.PendingResponse.Await") + + @it("returns the status, headers and body") + function _() + response = HttpClient.Get(m.ServerUrl("/status/201")).Await() + m.assertEqual(response.StatusCode(), 201) + m.assertTrue(response.IsSuccess()) + m.assertEqual(response.Headers()["x-hit"], "1") + m.assertEqual(response.Text(), "hit 1") + m.assertEqual(response.ErrorMessage(), "") + end function + + @it("counts a 3xx it can't follow as a success, retried and cached by no one") + function _() + request = m.GetWithoutCacheEntry("/seq/unfollowed/300").CacheForSeconds(60).RetryCount(1).RetryDelayMs(0) response = request.Await() - ' A retry waits at least 1000 ms before its second attempt. - m.assertTrue(timer.TotalMilliseconds() < 1000, `took ${timer.TotalMilliseconds()} ms`) - m.assertFalse(response.IsSuccess()) - event = m.global.telemetry.LogEvent - m.assertEqual(event.level, "warning") - m.assertEqual(event.message, request.declinedError) - m.assertEqual(event.attachments[0].filename, "request.txt") + m.assertEqual(response.StatusCode(), 300) + m.assertTrue(response.IsSuccess()) + m.assertEqual(response.ErrorMessage(), "") + m.assertFalse(request.Await().IsCached()) + m.assertEqual(m.Hits("/seq/unfollowed/300"), 2) end function - @it("reports a failed attempt before retrying it") + @it("succeeds on a 2xx, a 204 with no body") + @params(200, "Hello, world!") + @params(201, "Hello, world!") + @params(202, "Hello, world!") + @params(203, "Hello, world!") + @params(204, "") + function _(statusCode as integer, expectedBody as string) + path = `/succeeded/${statusCode}` + routes = {} + routes[path] = { status: statusCode, body: "Hello, world!" } + m.server.routes = routes + response = HttpClient.Get(m.ServerUrl(path)).Await() + m.assertTrue(response.IsSuccess()) + m.assertEqual(response.StatusCode(), statusCode) + m.assertEqual(response.Text(), expectedBody) + m.assertEqual(response.ErrorMessage(), "") + end function + + @it("fails with roUrlTransfer's reason for the status, the status, the transfer ID and the body") + @params(400, "Bad request") + @params(401, "Not authorized") + @params(403, "Forbidden") + @params(404, "Not found") + @params(409, "Conflict") + @params(429, "HTTP 429 error") + @params(500, "Internal server error") + @params(501, "Not implemented") + @params(502, "Bad gateway") + @params(503, "Service unavailable") + function _(statusCode as integer, reason as string) + path = `/failed/${statusCode}` + routes = {} + routes[path] = { status: statusCode, body: "failed" } + m.server.routes = routes + response = HttpClient.Get(m.ServerUrl(path)).Await() + message = response.ErrorMessage() + m.assertFalse(response.IsSuccess()) + m.assertEqual(response.StatusCode(), statusCode) + m.assertEqual(response.Text(), "failed") + m.assertTrue(message.StartsWith(`${Tr(Locale.HttpClient.Reason)}:${reason}`), message) + m.AssertContains(message, `\nStatusCode: ${statusCode}\nRequestId: `) + m.assertTrue(message.EndsWith(`\nBody: failed`), message) + end function + + @it("follows a redirect; a 3xx it can't follow is a success, its body read") + function _() + m.server.routes = { + "/moved": { status: 302, headers: { "Location": "/landed" } } + "/landed": { status: 200, body: "landed" } + "/nowhere": { status: 302, body: "no Location" } + } + response = HttpClient.Get(m.ServerUrl("/moved")).Await() + m.assertEqual(response.StatusCode(), 200) + m.assertEqual(response.Text(), "landed") + m.assertEqual(m.Hits("/landed"), 1) + + response = HttpClient.Get(m.ServerUrl("/nowhere")).Await() + m.assertEqual(response.StatusCode(), 302) + m.assertTrue(response.IsSuccess()) + m.assertEqual(response.Text(), "no Location") + end function + + @it("fails after too many redirects") + function _() + m.server.routes = { "/loop": { status: 302, headers: { "Location": "/loop" } } } + response = HttpClient.Get(m.ServerUrl("/loop")).Await() + m.assertFalse(response.IsSuccess()) + m.assertEqual(response.StatusCode(), HttpClient.CurlErrors.CURLE_TOO_MANY_REDIRECTS) + m.AssertContains(response.ErrorMessage(), `StatusCode: ${HttpClient.CurlErrors.CURLE_TOO_MANY_REDIRECTS}`) + end function + + @it("fails on a connection the server closes without an answer") + function _() + m.server.routes = { "/dropped": { drop: true } } + response = HttpClient.Get(m.ServerUrl("/dropped")).Await() + m.assertFalse(response.IsSuccess()) + m.assertEqual(response.StatusCode(), HttpClient.CurlErrors.CURLE_GOT_NOTHING) + m.assertEqual(response.Text(), "") + m.AssertContains(response.ErrorMessage(), "Empty reply from server") + end function + + @it("fails on a host that doesn't resolve") + function _() + response = HttpClient.Get("http://playlet-test.invalid/").Await() + m.assertFalse(response.IsSuccess()) + m.assertEqual(response.StatusCode(), HttpClient.CurlErrors.CURLE_COULDNT_RESOLVE_HOST) + m.AssertContains(response.ErrorMessage(), `StatusCode: ${HttpClient.CurlErrors.CURLE_COULDNT_RESOLVE_HOST}`) + end function + + @it("makes one attempt by default, even on a 503") + function _() + response = HttpClient.Get(m.ServerUrl("/seq/once/503,200")).Await() + m.assertEqual(response.StatusCode(), 503) + m.assertEqual(m.Hits("/seq/once/503,200"), 1) + end function + + @it("retries a first failure, a 4xx included, then a 5xx until one succeeds") + function _() + response = HttpClient.Get(m.ServerUrl("/seq/failures/404,503,502,200")).RetryCount(3).RetryDelayMs(0).Await() + m.assertEqual(response.StatusCode(), 200) + m.assertEqual(m.Hits("/seq/failures/404,503,502,200"), 4) + end function + + @it("takes a 4xx answer to a retry as final") + function _() + response = HttpClient.Get(m.ServerUrl("/seq/final4xx/503,404,200")).RetryCount(3).RetryDelayMs(0).Await() + m.assertEqual(response.StatusCode(), 404) + m.assertEqual(m.Hits("/seq/final4xx/503,404,200"), 2) + end function + + @it("never retries a timed-out attempt, first or later") + function _() + first = HttpClient.Get(m.ServerUrl("/seq/firsttimeout/200@2000,200")).AttemptTimeoutMs(300).RetryCount(2).RetryDelayMs(0).Await() + m.assertTrue(first.IsTimedOut()) + m.assertEqual(m.Hits("/seq/firsttimeout/200@2000,200"), 1) + later = HttpClient.Get(m.ServerUrl("/seq/latertimeout/503,200@2000,200")).AttemptTimeoutMs(300).RetryCount(2).RetryDelayMs(0).Await() + m.assertTrue(later.IsTimedOut()) + m.assertEqual(m.Hits("/seq/latertimeout/503,200@2000,200"), 2) + end function + + @it("retries a refused connection") function _() - request = m.RefusedRequest(function(context as object) as boolean - context.request.retriedError = context.response.ErrorMessage() - return true - end function) timer = CreateObject("roTimespan") - request.Await() - m.assertTrue(timer.TotalMilliseconds() >= 1000, `took ${timer.TotalMilliseconds()} ms`) + response = HttpClient.Get("http://127.0.0.1:1/").RetryCount(1).RetryDelayMs(300).Await() + m.assertTrue(response.StatusCode() < 0) + m.AssertTook(timer, 300, 750) + end function + + @it("returns the last attempt once the retries are spent") + function _() + response = HttpClient.Get(m.ServerUrl("/seq/spent/503")).RetryCount(2).RetryDelayMs(0).Await() + m.assertEqual(response.StatusCode(), 503) + m.assertEqual(m.Hits("/seq/spent/503"), 3) + end function + + @it("reports a retried attempt to telemetry, unless NoTelemetry") + function _() + HttpClient.Get(m.ServerUrl("/seq/reported/503,200")).RetryCount(1).RetryDelayMs(0).Await() event = m.global.telemetry.LogEvent m.assertEqual(event.level, "warning") - m.assertEqual(event.message, request.retriedError) - m.assertEqual(event.attachments[0].filename, "request.txt") + m.AssertContains(event.message, "503") + m.AssertContains(event.attachments[0].data, "/seq/reported/503,200") + + m.global.telemetry.LogEvent = {} + HttpClient.Get(m.ServerUrl("/seq/unreported/503,200")).RetryCount(1).RetryDelayMs(0).NoTelemetry().Await() + m.assertEqual(m.Hits("/seq/unreported/503,200"), 2) + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("retries on the reason RetryIf gives, a success included, and reports that reason") + function _() + lines = Tests.LogLines(function(url as string) as void + response = HttpClient.Get(url).RetryCount(1).RetryDelayMs(0).RetryIf(function(response as HttpClient.Response) as dynamic + if response.Headers()["x-hit"] = "1" + return "the first hit" + end if + return "" + end function).Await() + GetGlobalAA().retriedResponse = response + end function, m.ServerUrl("/seq/retryif/200,200")) + m.assertEqual(GetGlobalAA().retriedResponse.Headers()["x-hit"], "2") + warnings = [] as string[] + for each line in lines + if line.InStr("[WARN]") <> -1 + warnings.Push(line) + end if + end for + m.assertEqual(warnings.Count(), 1) + m.AssertContains(warnings[0], "attempt 1 ended: the first hit") + m.assertEqual(m.global.telemetry.LogEvent.message, "the first hit") + end function + + @it("doesn't retry when RetryIf gives an empty reason or invalid") + function _() + empty = HttpClient.Get(m.ServerUrl("/seq/retryifempty/503,200")).RetryCount(1).RetryDelayMs(0).RetryIf(function(_response as HttpClient.Response) as dynamic + return "" + end function).Await() + m.assertEqual(empty.StatusCode(), 503) + m.assertEqual(m.Hits("/seq/retryifempty/503,200"), 1) + none = HttpClient.Get(m.ServerUrl("/seq/retryifinvalid/503,200")).RetryCount(1).RetryDelayMs(0).RetryIf(function(_response as HttpClient.Response) as dynamic + return invalid + end function).Await() + m.assertEqual(none.StatusCode(), 503) + m.assertEqual(m.Hits("/seq/retryifinvalid/503,200"), 1) + end function + + @it("reports a failure RetryIf declines to retry, unless NoTelemetry, and not a success or a last attempt") + function _() + decline = function(_response as HttpClient.Response) as dynamic + return "" + end function + lines = Tests.LogLines(function(request as object) as void + request.Await() + end function, HttpClient.Get(m.ServerUrl("/seq/declined/503,200")).RetryCount(1).RetryDelayMs(0).RetryIf(decline)) + warnings = [] as string[] + for each line in lines + if line.InStr("[WARN]") <> -1 + warnings.Push(line) + end if + end for + m.assertEqual(warnings.Count(), 1) + m.AssertContains(warnings[0], "attempt 1 ended: ") + m.AssertContains(warnings[0], "StatusCode: 503") + m.AssertContains(warnings[0], `\nNot retrying: the retry callback declined`) + event = m.global.telemetry.LogEvent + m.assertEqual(event.level, "warning") + m.AssertContains(event.message, "StatusCode: 503") + m.AssertContains(event.attachments[0].data, "/seq/declined/503,200") + + m.global.telemetry.LogEvent = {} + HttpClient.Get(m.ServerUrl("/seq/declinedquiet/503,200")).RetryCount(1).RetryDelayMs(0).RetryIf(decline).NoTelemetry().Await() + HttpClient.Get(m.ServerUrl("/seq/declinedsuccess/200")).RetryCount(1).RetryDelayMs(0).RetryIf(decline).Await() + HttpClient.Get(m.ServerUrl("/seq/declinedlast/503")).RetryIf(decline).Await() + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("asks RetryIf only about the attempts RetryCount allows to retry") + function _() + ' RetryIf calls it through a local: its m is the global AA. + GetGlobalAA().retryIfCalls = 0 + alwaysRetry = function(_response as HttpClient.Response) as dynamic + GetGlobalAA().retryIfCalls += 1 + return "always" + end function + timedOut = HttpClient.Get(m.ServerUrl("/seq/retryiftimeout/200@2000,200")).AttemptTimeoutMs(300).RetryCount(1).RetryDelayMs(0).RetryIf(alwaysRetry).Await() + m.assertTrue(timedOut.IsTimedOut()) + m.assertEqual(GetGlobalAA().retryIfCalls, 0) + final4xx = HttpClient.Get(m.ServerUrl("/seq/retryiflater/503,404,200")).RetryCount(3).RetryDelayMs(0).RetryIf(alwaysRetry).Await() + m.assertEqual(final4xx.StatusCode(), 404) + m.assertEqual(GetGlobalAA().retryIfCalls, 1) + end function + + @it("rethrows what RetryIf throws, in DEBUG") + function _() + message = m.ThrownMessage(function(url as object) as void + HttpClient.Get(url).RetryCount(1).RetryDelayMs(0).RetryIf(function(_response as object) as dynamic + throw "RetryIf threw" + end function).Await() + end function, m.ServerUrl("/seq/retryifthrows/503,200")) + m.assertEqual(message, "RetryIf threw") + m.assertEqual(m.Hits("/seq/retryifthrows/503,200"), 1) + end function + + @it("sends a retry RetryDelayMs to 2 × RetryDelayMs after the failed attempt") + function _() + timer = CreateObject("roTimespan") + response = HttpClient.Get(m.ServerUrl("/seq/delayed/503,200")).RetryCount(1).RetryDelayMs(300).Await() + m.assertEqual(response.StatusCode(), 200) + m.AssertTook(timer, 300, 750) + end function + + @it("times out an attempt AttemptTimeoutMs after it was sent") + function _() + timer = CreateObject("roTimespan") + response = HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(300).Await() + m.AssertTook(timer, 300, 450) + m.assertTrue(response.IsTimedOut()) + m.assertFalse(response.IsSuccess()) + m.assertEqual(response.StatusCode(), 0) + m.assertEqual(response.ErrorMessage(), Tr(Locale.HttpClient.RequestTimedOut)) + end function + + @it("reports a refused connection with its curl code") + function _() + response = HttpClient.Get("http://127.0.0.1:1/").Await() + m.assertTrue(response.StatusCode() < 0) + m.AssertContains(response.ErrorMessage(), `StatusCode: ${response.StatusCode()}`) + end function + + @it("reports a failure with its status and body") + function _() + response = HttpClient.Get(m.ServerUrl("/status/404")).Await() + message = response.ErrorMessage() + m.AssertContains(message, "StatusCode: 404") + m.AssertContains(message, "Body: hit 1") + end function + + @it("reports a failure without a body with an empty Body line") + function _() + message = HttpClient.Head(m.ServerUrl("/status/404")).Await().ErrorMessage() + m.AssertContains(message, "StatusCode: 404") + m.assertTrue(message.EndsWith(`\nBody: `), `"${message}" doesn't end with an empty Body line`) + end function + + @it("reports a failure whose body went to a file without a Body line") + function _() + DeleteFile("tmp:/http-failed-body.txt") + message = HttpClient.Get(m.ServerUrl("/status/404")).SaveBodyToFile("tmp:/http-failed-body.txt").Await().ErrorMessage() + m.AssertContains(message, "StatusCode: 404") + m.assertEqual(message.InStr("Body:"), -1, message) + DeleteFile("tmp:/http-failed-body.txt") + end function + + @it("returns the same response to every later Await, Wait and Poll") + function _() + pending = HttpClient.Get(m.ServerUrl("/status/200")).Send() + pending.Await().Headers()["x-marker"] = "same" + m.assertEqual(pending.Await().Headers()["x-marker"], "same") + m.assertEqual(pending.Poll().Headers()["x-marker"], "same") + m.assertEqual(pending.Wait(100).Headers()["x-marker"], "same") + m.assertEqual(m.Hits("/status/200"), 1) + end function + + @it("runs several fetches at once") + function _() + timer = CreateObject("roTimespan") + slow = HttpClient.Get(m.ServerUrl("/delay/600")).Send() + fast = HttpClient.Get(m.ServerUrl("/delay/100")).Send() + m.assertEqual(slow.Await().StatusCode(), 200) + m.assertEqual(fast.Await().StatusCode(), 200) + m.AssertTook(timer, 600, 900) + end function + + @it("keeps a response readable once its fetch is gone") + function _() + response = HttpClient.Get(m.ServerUrl("/seq/collected/200")).Await() + RunGarbageCollector() + m.assertEqual(response.Text(), "hit 1") + m.assertEqual(response.Headers()["x-hit"], "1") + end function + + @it("leaves no reference cycle behind, on any path") + function _() + HttpClient.Get(m.ServerUrl("/seq/cycleretry/503,200")).RetryCount(1).RetryDelayMs(0).Await() + HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(100).Await() + cached = m.GetWithoutCacheEntry("/maxage/60/cycle") + cached.Await() + cached.Await() + HttpClient.Get(m.ServerUrl("/delay/2000")).Send().Cancel() + cancellation = m.CreateCancellation() + pending = HttpClient.Get(m.ServerUrl("/delay/2000")).Cancellation(cancellation).Send() + cancellation.node.cancel = true + pending.Await() + HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await() + m.assertEqual(RunGarbageCollector().orphaned, 0) + end function + + @describe("HttpClient.PendingResponse.Wait and Poll") + + @it("Wait returns invalid at waitMs, then the response as soon as it is in") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/800")).Send() + timer = CreateObject("roTimespan") + m.assertInvalid(pending.Wait(200)) + m.AssertTook(timer, 200, 300) + response = pending.Wait(3000) + m.assertEqual(response.StatusCode(), 200) + m.AssertTook(timer, 800, 1000) + end function + + @it("Poll never blocks") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/500")).Send() + timer = CreateObject("roTimespan") + m.assertInvalid(pending.Poll()) + m.AssertTook(timer, 0, 30) + m.assertEqual(pending.Await().StatusCode(), 200) + end function + + @it("Poll runs the retries, without blocking on the delay") + function _() + pending = HttpClient.Get(m.ServerUrl("/seq/polled/503,200")).RetryCount(1).RetryDelayMs(300).Send() + response = invalid + polls = 0 + while response = invalid and polls < 400 + timer = CreateObject("roTimespan") + response = pending.Poll() + m.AssertTook(timer, 0, 50) + polls += 1 + sleep(10) + end while + m.assertEqual(response.StatusCode(), 200) + m.assertEqual(m.Hits("/seq/polled/503,200"), 2) + end function + + @it("Wait runs the retries within its bound") + function _() + pending = HttpClient.Get(m.ServerUrl("/seq/waited/503,200")).RetryCount(1).RetryDelayMs(300).Send() + timer = CreateObject("roTimespan") + response = pending.Wait(3000) + m.assertEqual(response.StatusCode(), 200) + m.AssertTook(timer, 300, 750) + end function + + @it("a late Poll takes an answer already on the port, even past the deadline") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/100")).AttemptTimeoutMs(500).Send() + sleep(1000) + response = pending.Poll() + m.assertEqual(response.StatusCode(), 200) + m.assertFalse(response.IsTimedOut()) + end function + + @it("a late Poll takes an answer that arrived after the deadline") + function _() + pending = HttpClient.Get(m.ServerUrl("/seq/arrivedlate/201@600")).AttemptTimeoutMs(300).Send() + sleep(1500) + response = pending.Poll() + m.assertEqual(response.StatusCode(), 201) + m.assertEqual(response.Text(), "hit 1") + m.assertFalse(response.IsTimedOut()) + m.assertEqual(m.Hits("/seq/arrivedlate/201@600"), 1) + end function + + @it("a late Poll reports a timeout that passed") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(300).Send() + sleep(600) + m.assertTrue(pending.Poll().IsTimedOut()) + end function + + @it("a task loop takes the response at the first Poll after it is in, its own messages left to it") + function _() + loop = m.CreateLoop() + timer = CreateObject("roTimespan") + pending = HttpClient.Get(m.ServerUrl("/delay/200")).Send() + loop.node.ping = 1 + response = m.RunLoop(loop, pending, 100, 3000) + m.assertEqual(response.StatusCode(), 200) + m.AssertTook(timer, 200, 400) + m.assertEqual(loop.pings, 1) + end function + + @it("a task loop takes the timeout at the first Poll past the deadline, its port busy with its own messages") + function _() + loop = m.CreateLoop() + loop.pingEveryMessage = true + timer = CreateObject("roTimespan") + pending = HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(300).Send() + loop.node.ping = 1 + response = m.RunLoop(loop, pending, 500, 3000) + m.AssertTook(timer, 300, 450) + m.assertTrue(response.IsTimedOut()) + m.assertTrue(loop.pings > 1) + end function + + @describe("HttpClient cancellation") + + @it("sends nothing when cancelled before Send") + function _() + cancellation = m.CreateCancellation() + cancellation.node.cancel = true + response = HttpClient.Get(m.ServerUrl("/seq/precancelled/200")).Cancellation(cancellation).Await() + m.assertTrue(response.IsCancelled()) + m.assertEqual(response.ErrorMessage(), Tr(Locale.HttpClient.RequestCancelled)) + m.assertEqual(m.Hits("/seq/precancelled/200"), 0) + end function + + @it("wakes a blocked Await when another thread cancels") + 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) + pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).Send() + canceller.cancelAfterMs = 300 + timer = CreateObject("roTimespan") + m.assertTrue(pending.Await().IsCancelled()) + m.AssertTook(timer, 250, 600) + end function + + @it("wakes an Await blocked in a task when another thread cancels") + function _() + task = CreateObject("roSGNode", "AwaitInTask") + task.url = m.ServerUrl("/delay/3000") + task.cancellationNode = m.CreateCancellation().node + task.control = "run" + timer = CreateObject("roTimespan") + while task.sending <> true and timer.TotalMilliseconds() < 3000 + sleep(10) + end while + sleep(200) + timer.Mark() + task.cancellationNode.cancel = true + while task.state <> "stop" and timer.TotalMilliseconds() < 3000 + sleep(10) + end while + m.assertTrue(task.cancelled) + m.AssertTook(timer, 0, 300) + end function + + @it("is cancelled at a Poll in a task that never waits, when another thread cancels") + function _() + task = CreateObject("roSGNode", "PollInTask") + task.url = m.ServerUrl("/delay/3000") + task.cancellationNode = m.CreateCancellation().node + task.control = "run" + timer = CreateObject("roTimespan") + while task.sending <> true and timer.TotalMilliseconds() < 3000 + sleep(10) + end while + sleep(200) + timer.Mark() + task.cancellationNode.cancel = true + while task.state <> "stop" and timer.TotalMilliseconds() < 5000 + sleep(10) + end while + m.assertTrue(task.cancelled) + m.AssertTook(timer, 0, 1000) + end function + + @it("is cancelled at the next Poll after its cancellation is set") + function _() + cancellation = m.CreateCancellation() + pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).Send() + m.assertInvalid(pending.Poll()) + cancellation.node.cancel = true + m.assertTrue(pending.Poll().IsCancelled()) + end function + + @it("isn't cancelled by its cancellation field set to another value") + function _() + node = CreateObject("roSGNode", "Node") + node.addField("state", "string", false) + cancellation = CancellationUtils.CreateCancellation(node, "state", "cancel") + node.state = "done" + before = HttpClient.Get(m.ServerUrl("/seq/othervaluebefore/200")).Cancellation(cancellation).Await() + m.assertEqual(before.StatusCode(), 200) + m.assertFalse(before.IsCancelled()) + + pending = HttpClient.Get(m.ServerUrl("/delay/300")).Cancellation(cancellation).Send() + m.assertInvalid(pending.Poll()) + node.state = "running" + during = pending.Await() + m.assertEqual(during.StatusCode(), 200) + m.assertFalse(during.IsCancelled()) + end function + + @it("reads as cancelled once its cancellation is set, though the answer came before") + function _() + cancellation = m.CreateCancellation() + response = HttpClient.Get(m.ServerUrl("/seq/cancelledafter/200")).Cancellation(cancellation).Await() + m.assertEqual(response.StatusCode(), 200) + m.assertFalse(response.IsCancelled()) + cancellation.node.cancel = true + m.assertTrue(response.IsCancelled()) + end function + + @it("never reads as cancelled while its cancellation isn't set") + function _() + m.assertFalse(HttpClient.Get(m.ServerUrl("/seq/nocancellation/200")).Await().IsCancelled()) + node = CreateObject("roSGNode", "Node") + node.addField("state", "string", false) + cancellation = CancellationUtils.CreateCancellation(node, "state", "cancel") + response = HttpClient.Get(m.ServerUrl("/seq/unsetcancellation/200")).Cancellation(cancellation).Await() + m.assertFalse(response.IsCancelled()) + node.state = "done" + m.assertFalse(response.IsCancelled()) + end function + + @it("reads as cancelled when its fetch was cancelled") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Send() + pending.Cancel() + m.assertTrue(pending.Await().IsCancelled()) + cancellation = m.CreateCancellation() + cancellation.node.cancel = true + m.assertTrue(HttpClient.Get(m.ServerUrl("/seq/cancelledfetch/200")).Cancellation(cancellation).Await().IsCancelled()) + m.assertEqual(m.Hits("/seq/cancelledfetch/200"), 0) + end function + + @it("stays cancelled once read as cancelled, though its cancellation is reset") + function _() + cancellation = m.CreateCancellation() + response = HttpClient.Get(m.ServerUrl("/seq/cancelledreset/200")).Cancellation(cancellation).Await() + cancellation.node.cancel = true + m.assertTrue(response.IsCancelled()) + cancellation.node.cancel = false + m.assertTrue(response.IsCancelled()) + end function + + @it("reports a failure as cancelled once its cancellation is set, though the answer came before") + function _() + cancellation = m.CreateCancellation() + response = HttpClient.Get(m.ServerUrl("/seq/failedcancelledafter/404")).Cancellation(cancellation).Await() + m.AssertContains(response.ErrorMessage(), "StatusCode: 404") + cancellation.node.cancel = true + m.assertEqual(response.ErrorMessage(), Tr(Locale.HttpClient.RequestCancelled)) + end function + + @it("ends the delay before a retry when cancelled") + function _() + cancellation = m.CreateCancellation() + pending = HttpClient.Get(m.ServerUrl("/seq/cancelretry/503,200")).RetryCount(1).RetryDelayMs(3000).Cancellation(cancellation).Send() + m.assertInvalid(pending.Wait(300)) + cancellation.node.cancel = true + timer = CreateObject("roTimespan") + m.assertTrue(pending.Await().IsCancelled()) + m.AssertTook(timer, 0, 50) + m.assertEqual(m.Hits("/seq/cancelretry/503,200"), 1) + end function + + @it("neither retries nor reports a failed attempt whose cancellation was set before its answer was read") + function _() + ' RetryIf calls it through a local: its m is the global AA. + GetGlobalAA().retryIfCalls = 0 + alwaysRetry = function(_response as HttpClient.Response) as dynamic + GetGlobalAA().retryIfCalls += 1 + return "always" + end function + requests = [ + HttpClient.Get(m.ServerUrl("/seq/cancelunread/503,200")) + HttpClient.Get(m.ServerUrl("/seq/cancelunreadretryif/503,200")).RetryIf(alwaysRetry) + ] + for each request in requests + request.RetryCount(1).RetryDelayMs(0).Cancellation(m.CreateCancellation()) + end for + lines = Tests.LogLines(function(requests as object) as void + responses = [] + for each request in requests + pending = request.Send() + ' The 503 reaches the port before the cancellation's event. + sleep(300) + request._cancellation.node.cancel = true + responses.Push(pending.Await()) + end for + GetGlobalAA().unreadResponses = responses + end function, requests) + for each response in GetGlobalAA().unreadResponses + m.assertTrue(response.IsCancelled()) + m.assertEqual(response.StatusCode(), 503) + end for + m.assertEqual(m.Hits("/seq/cancelunread/503,200"), 1) + m.assertEqual(m.Hits("/seq/cancelunreadretryif/503,200"), 1) + m.assertEqual(GetGlobalAA().retryIfCalls, 0) + m.AssertNotLogged(lines, "[WARN]") + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("sends no retry once its cancellation is set, though the cancellation's event never comes") + function _() + cancellation = m.CreateCancellation() + pending = HttpClient.Get(m.ServerUrl("/seq/cancelretrylost/503,200")).RetryCount(1).RetryDelayMs(500).Cancellation(cancellation).Send() + m.assertInvalid(pending.Wait(300)) + pending._cancellationObserver.UnobserveField("changed") + cancellation.node.cancel = true + m.assertTrue(pending.Await().IsCancelled()) + m.assertEqual(m.Hits("/seq/cancelretrylost/503,200"), 1) + end function + + @it("Cancel completes it as cancelled") + function _() + pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Send() + pending.Cancel() + timer = CreateObject("roTimespan") + m.assertTrue(pending.Await().IsCancelled()) + m.AssertTook(timer, 0, 50) + end function + + @it("leaves the caller's own observer of the cancellation in place") + function _() + cancellation = m.CreateCancellation() + callerPort = CreateObject("roMessagePort") + cancellation.node.ObserveFieldScoped("cancel", callerPort) + m.assertEqual(HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await().StatusCode(), 200) + cancellation.node.cancel = true + m.assertEqual(type(callerPort.GetMessage()), "roSGNodeEvent") + end function + + @it("stops observing its cancellation once the response is taken, or on Cancel") + function _() + cancellation = m.CreateCancellation() + taken = HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Send() + takenObserver = taken["_cancellationObserver"] + m.assertFalse(takenObserver.nodeDestroy) + taken.Await() + m.assertTrue(takenObserver.nodeDestroy) + + cancelled = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).Send() + cancelledObserver = cancelled["_cancellationObserver"] + cancelled.Cancel() + m.assertTrue(cancelledObserver.nodeDestroy) + + cancellation.node.cancel = true + precancelled = HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Send() + precancelledObserver = precancelled["_cancellationObserver"] + m.assertTrue(precancelled.Poll().IsCancelled()) + m.assertTrue(precancelledObserver.nodeDestroy) + end function + + @it("cancels every fetch sharing a cancellation") + function _() + cancellation = m.CreateCancellation() + first = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).Send() + finished = HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await() + second = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).Send() + m.assertEqual(finished.StatusCode(), 200) + cancellation.node.cancel = true + m.assertTrue(first.Await().IsCancelled()) + m.assertTrue(second.Await().IsCancelled()) + end function + + @describe("HttpClient cache") + + @it("serves a GET from the cache for its Cache-Control max-age, by default") + function _() + request = m.GetWithoutCacheEntry("/maxage/60/served") + m.assertFalse(request.Await().IsCached()) + response = request.Await() + m.assertTrue(response.IsCached()) + m.assertEqual(response.StatusCode(), 200) + m.assertEqual(response.Text(), "hit 1") + m.assertEqual(response.Headers()["X-Hit"], "1") + m.assertEqual(m.Hits("/maxage/60/served"), 1) + end function + + @it("returns a cached response at the first Poll") + function _() + request = m.GetWithoutCacheEntry("/maxage/60/polled") + request.Await() + m.assertTrue(request.Send().Poll().IsCached()) + end function + + @it("keeps an entry in a request_v3_ file, one per url, headers and file the body is saved to") + function _() + path = HttpCache.GetFilePath("http://x/", {}, invalid) + m.assertTrue(path.StartsWith("cachefs:/request_v3_"), path) + m.assertNotEqual(HttpCache.GetFilePath("http://y/", {}, invalid), path) + m.assertNotEqual(HttpCache.GetFilePath("http://x/", { "X-A": "1" }, invalid), path) + m.assertNotEqual(HttpCache.GetFilePath("http://x/", {}, "tmp:/body.txt"), path) + request = m.GetWithoutCacheEntry("/maxage/60/filename") + request.Await() + m.assertTrue(CreateObject("roFileSystem").Exists(m.CacheFilePath(request))) + end function + + @it("reads no entry that isn't there, quietly") + function _() + path = "cachefs:/request_v3_missing.json" + DeleteFile(path) + lines = Tests.LogLines(function(path as string) as void + GetGlobalAA().missingEntry = HttpCache.Read(path, invalid) + end function, path) + m.assertInvalid(GetGlobalAA().missingEntry) + m.assertEmpty(lines) + end function + + @it("warns of an empty entry and deletes it") + function _() + entryPath = "cachefs:/request_v3_empty.json" + WriteAsciiFile(entryPath, "") + m.assertTrue(CreateObject("roFileSystem").Exists(entryPath)) + m.global.telemetry.LogWarn = "" + warnings = [] as string[] + for each line in Tests.LogLines(function(entryPath as string) as void + GetGlobalAA().emptyEntry = HttpCache.Read(entryPath, invalid) + end function, entryPath) + if line.InStr("[WARN]") <> -1 + warnings.Push(line) + end if + end for + m.assertInvalid(GetGlobalAA().emptyEntry) + m.assertEqual(warnings.Count(), 1) + m.assertEqual(Tests.LogLineMessage(warnings[0]), "Failed to parse cache.") + m.assertEqual(m.global.telemetry.LogWarn, warnings[0]) + m.assertFalse(CreateObject("roFileSystem").Exists(entryPath)) + end function + + @it("warns of a corrupt entry and deletes it, though its body file is gone") + function _() + entryPath = "cachefs:/request_v3_corruptgone.json" + WriteAsciiFile(entryPath, "not a cache entry") + DeleteFile("tmp:/http-corruptgone.txt") + warnings = [] as string[] + for each line in Tests.LogLines(function(entryPath as string) as void + GetGlobalAA().goneEntry = HttpCache.Read(entryPath, "tmp:/http-corruptgone.txt") + end function, entryPath) + if line.InStr("[WARN]") <> -1 + warnings.Push(Tests.LogLineMessage(line)) + end if + end for + m.assertInvalid(GetGlobalAA().goneEntry) + m.assertEqual(warnings, ["Failed to parse cache."]) + m.assertFalse(CreateObject("roFileSystem").Exists(entryPath)) + end function + + @it("deletes an expired entry whose body file is gone") + function _() + entryPath = "cachefs:/request_v3_expiredgone.json" + WriteAsciiFile(entryPath, `{"expiresAt":1,"statusCode":200,"headers":{}}\n`) + DeleteFile("tmp:/http-expiredgone.txt") + m.assertInvalid(HttpCache.Read(entryPath, "tmp:/http-expiredgone.txt")) + m.assertFalse(CreateObject("roFileSystem").Exists(entryPath)) + end function + + @it("deletes a valid entry whose body file is gone, so the request is sent again") + function _() + path = "tmp:/http-validgone.txt" + request = HttpClient.Get(m.ServerUrl("/maxage/60/validgone")).SaveBodyToFile(path) + DeleteFile(m.CacheFilePath(request)) + request.Await() + m.assertTrue(request.Await().IsCached()) + DeleteFile(path) + m.assertInvalid(HttpCache.Read(m.CacheFilePath(request), path)) + m.assertFalse(CreateObject("roFileSystem").Exists(m.CacheFilePath(request))) + response = request.Await() + m.assertFalse(response.IsCached()) + m.assertEqual(ReadAsciiFile(path), "hit 2") + m.assertEqual(m.Hits("/maxage/60/validgone"), 2) + DeleteFile(path) + end function + + @it("doesn't cache what Cache-Control's no-store or no-cache forbid, unless CacheForSeconds") + function _() + m.server.routes = { + "/nostore": { status: 200, headers: { "Cache-Control": "no-store" }, body: "no-store" } + "/nocache": { status: 200, headers: { "Cache-Control": "max-age=60, no-cache" }, body: "no-cache" } + } + for each path in ["/nostore", "/nocache"] + request = m.GetWithoutCacheEntry(path) + m.assertEqual(request.Await().StatusCode(), 200) + m.assertFalse(CreateObject("roFileSystem").Exists(m.CacheFilePath(request)), path) + m.assertFalse(request.Await().IsCached(), path) + end for + forSeconds = m.GetWithoutCacheEntry("/nostore").CacheForSeconds(60) + forSeconds.Await() + response = forSeconds.Await() + m.assertTrue(response.IsCached()) + m.assertEqual(response.Text(), "no-store") + m.assertEqual(m.Hits("/nostore"), 3) + end function + + @it("reads Cache-Control in any case, and a cached response's headers in any case") + function _() + m.server.routes = { "/mixedcase": { status: 200, headers: { "cAcHe-CoNtRoL": "max-age=60", "X-Echo-Test": "true" }, body: "cached" } } + request = m.GetWithoutCacheEntry("/mixedcase") + first = request.Await() + m.assertFalse(first.IsCached()) + m.assertEqual(first.Headers()["X-Echo-Test"], "true") + m.assertEqual(first.Headers()["x-echo-test"], "true") + cached = request.Await() + m.assertTrue(cached.IsCached()) + m.assertEqual(cached.Text(), "cached") + m.assertEqual(cached.Headers()["X-Echo-Test"], "true") + m.assertEqual(cached.Headers()["x-echo-test"], "true") + m.assertEqual(cached.Headers()["CACHE-CONTROL"], "max-age=60") + m.assertEqual(m.Hits("/mixedcase"), 1) + end function + + @it("caches for CacheForSeconds whatever the response says") + function _() + request = m.GetWithoutCacheEntry("/seq/forseconds/200").CacheForSeconds(60) + request.Await() + m.assertTrue(request.Await().IsCached()) + end function + + @it("doesn't cache without max-age, with max-age=0, or a failure") + function _() + noMaxAge = m.GetWithoutCacheEntry("/seq/nomaxage/200") + noMaxAge.Await() + m.assertFalse(noMaxAge.Await().IsCached()) + failed = m.GetWithoutCacheEntry("/seq/cachedfailure/503").CacheForSeconds(60) + failed.Await() + m.assertFalse(failed.Await().IsCached()) + maxAgeZero = m.GetWithoutCacheEntry("/maxage/0/uncached") + maxAgeZero.Await() + m.assertFalse(maxAgeZero.Await().IsCached()) + end function + + @it("caches only a GET") + function _() + head = HttpClient.Head(m.ServerUrl("/maxage/60/head")) + head.Await() + m.assertFalse(head.Await().IsCached()) + post = HttpClient.Post(m.ServerUrl("/maxage/60/post")) + post.Await() + m.assertFalse(post.Await().IsCached()) + m.assertEqual(m.Hits("/maxage/60/head"), 2) + m.assertEqual(m.Hits("/maxage/60/post"), 2) + end function + + @it("NoCache neither reads nor writes the cache, CacheForSeconds included") + function _() + request = m.GetWithoutCacheEntry("/maxage/60/nocache") + request.Await() + m.assertFalse(HttpClient.Get(m.ServerUrl("/maxage/60/nocache")).NoCache().Await().IsCached()) + DeleteFile(m.CacheFilePath(request)) + HttpClient.Get(m.ServerUrl("/maxage/60/nocache")).CacheForSeconds(60).NoCache().Await() + m.assertFalse(request.Await().IsCached()) + m.assertEqual(m.Hits("/maxage/60/nocache"), 4) + end function + + @it("warns of a corrupt entry with what failed to parse, then replaces it") + function _() + request = m.GetWithoutCacheEntry("/maxage/60/corrupt") + corruptEntries = [ + { text: "not a cache entry", warning: "Failed to parse cache." } + { text: `{"expiresAt":\nhit 0`, warning: "Failed to parse metadata from cache." } + { text: `{"expiresAt":2000000000,"statusCode":200,"headers":"none"}\nhit 0`, warning: "Failed to parse headers from cache." } + ] + for each corrupt in corruptEntries + WriteAsciiFile(m.CacheFilePath(request), corrupt.text) + GetGlobalAA().corruptResponse = invalid + lines = Tests.LogLines(function(request as object) as void + GetGlobalAA().corruptResponse = request.Await() + end function, request) + response = GetGlobalAA().corruptResponse + m.assertFalse(response.IsCached()) + m.assertEqual(response.StatusCode(), 200) + warnings = [] as string[] + for each line in lines + if line.InStr("[WARN]") <> -1 + warnings.Push(line) + end if + end for + m.assertEqual(warnings.Count(), 1) + m.assertEqual(Tests.LogLineMessage(warnings[0]), corrupt.warning) + m.assertEqual(m.global.telemetry.LogWarn, warnings[0]) + m.assertTrue(request.Await().IsCached()) + end for + end function + + @it("expires an entry") + function _() + request = m.GetWithoutCacheEntry("/maxage/1/expires") + request.Await() + sleep(2100) + m.assertFalse(request.Await().IsCached()) + end function + + @it("keeps an entry for the time it was written with, whatever the request reading it sets") + function _() + request = m.GetWithoutCacheEntry("/maxage/1/writtenexpiry") + request.Await() + longer = HttpClient.Get(m.ServerUrl("/maxage/1/writtenexpiry")).CacheForSeconds(60) + m.assertTrue(longer.Await().IsCached()) + sleep(2100) + m.assertFalse(longer.Await().IsCached()) + + m.GetWithoutCacheEntry("/seq/writtenforseconds/200").CacheForSeconds(60).Await() + m.assertTrue(HttpClient.Get(m.ServerUrl("/seq/writtenforseconds/200")).Await().IsCached()) + m.assertEqual(m.Hits("/seq/writtenforseconds/200"), 1) + end function + + @it("keeps an answer taken before its cancellation was set") + function _() + cancellation = m.CreateCancellation() + request = m.GetWithoutCacheEntry("/maxage/60/cancelledafter") + response = request.Cancellation(cancellation).Await() + cancellation.node.cancel = true + m.assertTrue(response.IsCancelled()) + m.assertTrue(request.Cancellation(invalid).Await().IsCached()) + m.assertEqual(m.Hits("/maxage/60/cancelledafter"), 1) + end function + + @it("doesn't cache an empty body, unless it went to a file") + function _() + m.server.routes = { "/emptybody": { status: 200, headers: { "Cache-Control": "max-age=60" }, body: "" } } + request = m.GetWithoutCacheEntry("/emptybody") + m.assertEqual(request.Await().Text(), "") + m.assertFalse(request.Await().IsCached()) + m.assertEqual(m.Hits("/emptybody"), 2) + + path = "tmp:/http-empty-download.txt" + DeleteFile(path) + toFile = HttpClient.Get(m.ServerUrl("/emptybody")).SaveBodyToFile(path) + DeleteFile(m.CacheFilePath(toFile)) + m.assertEqual(toFile.Await().StatusCode(), 200) + m.assertTrue(toFile.Await().IsCached()) + DeleteFile(path) + end function + + @it("caches a body saved to a file while the file exists") + function _() + path = "tmp:/http-download.txt" + request = HttpClient.Get(m.ServerUrl("/maxage/60/download")).SaveBodyToFile(path) + DeleteFile(m.CacheFilePath(request)) + DeleteFile(path) + m.assertEqual(request.Await().StatusCode(), 200) + m.assertEqual(ReadAsciiFile(path), "hit 1") + m.assertTrue(request.Await().IsCached()) + DeleteFile(path) + m.assertFalse(request.Await().IsCached()) + m.assertEqual(ReadAsciiFile(path), "hit 2") + end function + + @describe("HttpClient.Response") + + @it("builds from statusCode, headers and text") + function _() + response = new HttpClient.Response({ statusCode: 404, headers: { "X-A": "b" }, text: `{"a":1}` }) + m.assertEqual(response.StatusCode(), 404) + m.assertEqual(response.Headers()["x-a"], "b") + m.assertEqual(response.Json().a, 1) + m.assertEqual(response.ErrorMessage(), `StatusCode: 404\nBody: {"a":1}`) + m.assertEqual((new HttpClient.Response({ statusCode: 500 })).ErrorMessage(), `StatusCode: 500\nBody: `) + end function + + @it("reads Retry-After in seconds") + function _() + retryAfterSeconds = function(retryAfter as dynamic) as dynamic + response = new HttpClient.Response({ headers: { "Retry-After": retryAfter } }) + return response.RetryAfterSeconds() + end function + m.assertEqual(retryAfterSeconds(" 120 "), 120) + m.assertEqual(retryAfterSeconds("0"), 0) + m.assertInvalid(retryAfterSeconds("Wed, 21 Oct 2026 07:28:00 GMT")) + m.assertInvalid(retryAfterSeconds(invalid)) + end function + + @it("reads Retry-After off a 429") + function _() + m.server.routes = { "/busy": { status: 429, headers: { "Retry-After": "120" }, body: "busy" } } + response = HttpClient.Get(m.ServerUrl("/busy")).Await() + m.assertEqual(response.StatusCode(), 429) + m.assertEqual(response.RetryAfterSeconds(), 120) + m.AssertContains(response.ErrorMessage(), "HTTP 429 error") + end function + + @it("parses invalid JSON as invalid") + function _() + m.assertInvalid(HttpClient.Get(m.ServerUrl("/status/200")).Await().Json()) + end function + + @describe("HttpClient misuse, asserted in DEBUG") + + @it("a body on GET or HEAD") + function _() + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.TextBody("x") + end function, HttpClient.Get("http://x/")), "TextBody on a GET request") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.JsonBody({}) + end function, HttpClient.Head("http://x/")), "JsonBody on a HEAD request") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.FormBody({}) + end function, HttpClient.Get("http://x/")), "FormBody on a GET request") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.FileBody("tmp:/x") + end function, HttpClient.Get("http://x/")), "FileBody on a GET request") + end function + + @it("caching or saving the body to a file on anything but GET") + function _() + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.CacheForSeconds(60) + end function, HttpClient.Put("http://x/")), "CacheForSeconds on a PUT request") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.SaveBodyToFile("tmp:/x") + end function, HttpClient.Head("http://x/")), "SaveBodyToFile on a HEAD request") + end function + + @it("out of range numbers") + function _() + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.AttemptTimeoutMs(0) + end function, HttpClient.Get("http://x/")), "AttemptTimeoutMs(0)") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.RetryCount(-1) + end function, HttpClient.Get("http://x/")), "RetryCount(-1)") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.RetryDelayMs(-1) + end function, HttpClient.Get("http://x/")), "RetryDelayMs(-1)") + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.CacheForSeconds(0) + end function, HttpClient.Get("http://x/")), "CacheForSeconds(0)") + end function + + @it("an invalid query param value") + function _() + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.QueryParam("q", invalid) + end function, HttpClient.Get("http://x/")), `QueryParam("q", invalid)`) + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.QueryParamArray("ids", invalid, UrlUtils.QueryParamArrayType.CommaSeparated) + end function, HttpClient.Get("http://x/")), `QueryParamArray("ids", invalid)`) + end function + + @it("a RetryIf that returns no reason") + function _() + m.AssertContains(m.ThrownMessage(function(url as object) as void + HttpClient.Get(url).RetryCount(1).RetryDelayMs(0).RetryIf(function(_response as object) as dynamic + return true + end function).Await() + end function, m.ServerUrl("/seq/retryifboolean/503,200")), "RetryIf returned a Boolean") + end function + + @it("a cancellation that isn't one") + function _() + m.AssertContains(m.ThrownMessage(function(request as object) as void + request.Cancellation({ node: invalid }) + end function, HttpClient.Get("http://x/")), "Cancellation takes") + end function + + @it("Wait(0): wait(0) blocks forever on Roku") + function _() + pending = HttpClient.Get(m.ServerUrl("/status/200")).Send() + m.AssertContains(m.ThrownMessage(function(pending as object) as void + pending.Wait(0) + end function, pending), "Wait(0)") + pending.Await() + 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() + m.AssertContains(m.ThrownMessage(function(response as object) as void + response.Text() + end function, response), "Text and Json on a SaveBodyToFile response") + m.AssertContains(m.ThrownMessage(function(response as object) as void + response.Json() + end function, response), "Text and Json on a SaveBodyToFile response") end function end class diff --git a/playlet-lib/src/source/tests/HttpTestServer.bs b/playlet-lib/src/source/tests/HttpTestServer.bs new file mode 100644 index 00000000..e6a7779b --- /dev/null +++ b/playlet-lib/src/source/tests/HttpTestServer.bs @@ -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 diff --git a/playlet-lib/src/source/tests/LoggingGlobals.bs b/playlet-lib/src/source/tests/LoggingGlobals.bs index dfb5d414..9df024ff 100644 --- a/playlet-lib/src/source/tests/LoggingGlobals.bs +++ b/playlet-lib/src/source/tests/LoggingGlobals.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Dash/LiveHeadChecks.spec.bs b/playlet-lib/src/source/tests/Services/Dash/LiveHeadChecks.spec.bs new file mode 100644 index 00000000..2601ea00 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Dash/LiveHeadChecks.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Dash/LiveHeadFakes.bs b/playlet-lib/src/source/tests/Services/Dash/LiveHeadFakes.bs new file mode 100644 index 00000000..61c7cf91 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Dash/LiveHeadFakes.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Innertube/InnertubeRequests.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/InnertubeRequests.spec.bs new file mode 100644 index 00000000..abfaa0f4 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Innertube/InnertubeRequests.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs index 779463e8..a435545e 100644 --- a/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs +++ b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Innertube/OTFSegmentInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/OTFSegmentInfo.spec.bs new file mode 100644 index 00000000..c549bd48 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Innertube/OTFSegmentInfo.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs new file mode 100644 index 00000000..c643a168 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs b/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs index bb36bb9f..412f0c50 100644 --- a/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs +++ b/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs @@ -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") diff --git a/playlet-lib/src/source/tests/Services/SponsorBlock/SponsorBlockService.spec.bs b/playlet-lib/src/source/tests/Services/SponsorBlock/SponsorBlockService.spec.bs new file mode 100644 index 00000000..fb4c393d --- /dev/null +++ b/playlet-lib/src/source/tests/Services/SponsorBlock/SponsorBlockService.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Telemetry/Sentry.spec.bs b/playlet-lib/src/source/tests/Telemetry/Sentry.spec.bs new file mode 100644 index 00000000..6039121d --- /dev/null +++ b/playlet-lib/src/source/tests/Telemetry/Sentry.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs index b89f2813..a17721f8 100644 --- a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs +++ b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs @@ -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"] } diff --git a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetryCompleteness.spec.bs b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetryCompleteness.spec.bs index 4c88cd18..7fdd1179 100644 --- a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetryCompleteness.spec.bs +++ b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetryCompleteness.spec.bs @@ -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 diff --git a/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs index aeaf0c64..454890cb 100644 --- a/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs +++ b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs @@ -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: "" } } + response = m.AppendStoryboards("/dash/manifest.mpd") + m.assertEqual(response.http_code, 200) + m.assertEqual(response.contentType, "application/dash+xml") + m.assertTrue(response.body.StartsWith(""), 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 diff --git a/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/InnertubeRouter.spec.bs b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/InnertubeRouter.spec.bs new file mode 100644 index 00000000..4b7bb43e --- /dev/null +++ b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/InnertubeRouter.spec.bs @@ -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