From 82dea9af379dcf1bda56b91c217a2feea2055a55 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Sun, 22 Jun 2025 17:39:58 -0400 Subject: [PATCH] Remove asynctask code (#666) * Remove asynctask code * add job test example * Fix testing * Fix a couple of imports --- CHANGELOG.md | 1 + config/bsconfig.base.jsonc | 1 - config/bsconfig.tests.base.jsonc | 1 - docs/plugins.md | 96 +++++----- .../src/components/JobSystem/JobQueueTask.bs | 6 +- .../src/components/JobSystem/JobRequest.bs | 42 +++++ .../src/components/JobSystem/JobSystem.bs | 1 + .../src/components/JobSystem/JobTask.bs | 29 +-- playlet-lib/src/components/Logger/Logger.bs | 18 +- .../components/PlaylistView/PlaylistView.bs | 2 - .../QrCodePoster/GenerateQrCodeJob.bs | 1 + .../Screens/AppInfoScreen/AppInfoScreen.bs | 2 +- .../Services/Innertube/NodesParser.bs | 6 +- .../components/Services/Innertube/OAuth.bs | 3 + .../Innertube/SubscriptionEndpoint.bs | 1 + .../Services/Invidious/Invidious.bs | 2 - .../Services/Invidious/InvidiousService.bs | 2 - .../src/components/VideoFeed/VideoRowList.bs | 2 - ...VideoContentTask.bs => VideoContentJob.bs} | 44 ++--- .../src/components/VideoPlayer/VideoPlayer.bs | 65 ++++--- ...ontentTaskDev.bs => VideoContentDevJob.bs} | 29 ++- .../VideoPlayerDev/VideoPlayerDev.bs | 44 +++-- .../VideoPlayerDev/VideoPlayerDev.xml | 1 + .../src/components/VideoQueue/VideoQueue.bs | 2 - .../components/VideoQueue/VideoQueueView.bs | 21 ++- .../components/VideoQueue/VideoQueueView.xml | 1 + ...entTask.bs => VideoQueueViewContentJob.bs} | 21 ++- .../VideoQueue/VideoQueueViewUtils.bs | 1 + .../Middleware/InnertubeRouter.bs | 1 + playlet-lib/src/source/AsyncTask/AsyncTask.bs | 49 ----- .../tests/GenerateQrCodeJob.spec.bs | 42 +++++ .../source/components/tests/JobSystem.spec.bs | 35 +++- playlet-lib/src/source/utils/AssertUtils.bs | 13 ++ playlet-lib/src/source/utils/UrlUtils.bs | 1 + tools/bs-plugins/asynctask-plugin.ts | 177 ------------------ tools/bs-plugins/import-validation-plugin.ts | 5 + 36 files changed, 325 insertions(+), 443 deletions(-) create mode 100644 playlet-lib/src/components/JobSystem/JobRequest.bs rename playlet-lib/src/components/VideoPlayer/{VideoContentTask.bs => VideoContentJob.bs} (92%) rename playlet-lib/src/components/VideoPlayerDev/{VideoContentTaskDev.bs => VideoContentDevJob.bs} (84%) rename playlet-lib/src/components/VideoQueue/{VideoQueueViewContentTask.bs => VideoQueueViewContentJob.bs} (87%) delete mode 100644 playlet-lib/src/source/AsyncTask/AsyncTask.bs create mode 100644 playlet-lib/src/source/components/tests/GenerateQrCodeJob.spec.bs delete mode 100644 tools/bs-plugins/asynctask-plugin.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 64d29b36..63c6af2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed - "Use dev video player" option from the settings +- `@asynctask` in favor of newer job system ## [0.40.7] - 2025-06-21 diff --git a/config/bsconfig.base.jsonc b/config/bsconfig.base.jsonc index 2b7b5ea0..60329f12 100644 --- a/config/bsconfig.base.jsonc +++ b/config/bsconfig.base.jsonc @@ -82,7 +82,6 @@ "lintConfig": "./config/bslint.jsonc", "plugins": [ "@rokucommunity/bslint", - "../tools/bs-plugins/asynctask-plugin.ts", "../tools/bs-plugins/jobsystem-plugin.ts", "../tools/bs-plugins/manifest-edit-plugin.ts", "../tools/bs-plugins/component-includes-plugin.ts", diff --git a/config/bsconfig.tests.base.jsonc b/config/bsconfig.tests.base.jsonc index 4ac299cc..c4f49f6a 100644 --- a/config/bsconfig.tests.base.jsonc +++ b/config/bsconfig.tests.base.jsonc @@ -20,7 +20,6 @@ "plugins": [ "@rokucommunity/bslint", "rooibos-roku", - "../tools/bs-plugins/asynctask-plugin.ts", "../tools/bs-plugins/jobsystem-plugin.ts", "../tools/bs-plugins/manifest-edit-plugin.ts", "../tools/bs-plugins/component-includes-plugin.ts", diff --git a/docs/plugins.md b/docs/plugins.md index cc923b99..dbb09b6d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -6,7 +6,6 @@ - [Includes](#includes) - [@oninit](#oninit) - [Bindings](#bindings) -- [Async Task Generator](#async-task-generator) - [Job System Generator](#job-system-generator) - [Tracking transpilied files](#tracking-transpilied-files) - [Logger](#logger) @@ -422,62 +421,53 @@ myNode@.BindNode() calling `BindNode` will trigger all the binding steps just for this node. But it is expected that all its dependencies are already in the scene and can be found. -## Async Task Generator - -**[Source](/tools/bs-plugins/asynctask-plugin.ts)** - -This plugin generates `Task` components a scripts that makes it simpler to call a function in a background thread, and get the result in a callback function. - -### Why - -To implement functionality that runs in background threads, [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md)s must be used. - -Setting up a task involves lots of boilerplate: setting up the task in an xml file, defining inputs and outputs, code to listen for a task to finish, and so on. - -Additionally, there's no standard way to do error handling, cancellation, and so on. - -### How - -Use a function with the attribute `@asynctask`. - -In a separate file, define the task function: - -```brighterscript -@asynctask -function MyBackgroundTask(input as object) as object - myVar = input.myVar - - value = DoWork(myVar) - - return { - value: value - } -end function -``` - -And use the function like so - -```brighterscript -import "pkg:/source/AsyncTask/Tasks.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" - -AsyncTask.Start(Tasks.MyBackgroundTask, {myVar: "some input"}, function(output as object) as void - if output.success - print(output.result.value) - end if -end function) -``` - -The rest will be taken care of by the plugin, which will generate an `xml` file containing the task component, and a script that handles calling the function. - -Although very useful, this pattern might not be the best for long running tasks (like the Web Server) or other tasks that require task reuse. This is because `AsyncTask.Start` create a new instance of the task every time. - ## Job System Generator **[Source](/tools/bs-plugins/jobsystem-plugin.ts)** -This plugin is very similar to the `Async Task Generator` and aims to be a replacement for it. -A work in progress for now. +The Job System simplifies the creation of background jobs without the risk of creating too many threads. +It manages a number of Tasks which are capable of executing jobs from a queue. + +### Why + +To implement functionality that runs in background threads, [Tasks](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md) must be used. + +Setting up a task involves lots of boilerplate: setting up the task in an xml file, defining inputs and outputs, code to listen for a task to finish, and so on. + +Additionally, there's no standard way to do error handling and cancellation. + +Another concern is managing too many threads across the application, and managing rendezvous(s). + +### How + +Define a function in its own file called `ExecuteJob` annotated with `@job("JobName")`: + +```brighterscript +@job("MyJob") +function ExecuteJob() as void + ' input is an associative array set when the job is queued. + input = JobGetInput() + + value = DoWork(myVar) + + JobSuccessData({result: value}) +end function +``` + +by doing this, the generator will generate a component named "MyJob" and will inherit from "BaseJob". + +The job can now queued for execution: + +```brighterscript +callback = JobSystem.CreateCallback() +JobSystem.QueueJob(m.jobQueue, Jobs.MyJob, input, callback) +``` + +And the job system will take care of queueing, scheduling, and scaling up the available tasks in order to execute jobs. +The job system creates job nodes inside task threads, which reduces the amount of rendezvous necessary. Some rendezvous are still necessary, such as when a task node is signaling that it is ready to take on a new job, or when the job is returning results to render thread. +The job system will auto scale up to a maximum number of tasks, in order to avoid `Too many threads` errors. Once the job system activity settles down, the job system will release task nodes that has been idle for a certain amount of time. + +Although very useful, this pattern might not be the best for long running tasks (like the Web Server) and it is simpler to create dedicated tasks for those. ## Tracking transpilied files diff --git a/playlet-lib/src/components/JobSystem/JobQueueTask.bs b/playlet-lib/src/components/JobSystem/JobQueueTask.bs index 26643321..944ffe9d 100644 --- a/playlet-lib/src/components/JobSystem/JobQueueTask.bs +++ b/playlet-lib/src/components/JobSystem/JobQueueTask.bs @@ -3,7 +3,7 @@ import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/StringUtils.bs" ' Maximum number of JobTasks that can be created -const MAX_JOB_TASK_COUNT = 20 +const MAX_JOB_TASK_COUNT = 25 ' Minimum number of JobTasks that will be kept alive const MIN_JOB_TASK_COUNT = 2 ' Time in milliseconds to wait before scaling down JobTasks @@ -45,6 +45,10 @@ function JobQueueTaskLoop() as void m.busyJobTasks[jobTaskId] = jobTaskObject MessagePortUtils.ObserveFieldScopedExSafe(jobTask, "ready", messagePort) jobTask.control = "run" + else + #if DEBUG + LogWarn("Cannot create new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count()) + #end if end if exit while diff --git a/playlet-lib/src/components/JobSystem/JobRequest.bs b/playlet-lib/src/components/JobSystem/JobRequest.bs new file mode 100644 index 00000000..a35282f5 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobRequest.bs @@ -0,0 +1,42 @@ +import "pkg:/source/utils/AssertUtils.bs" +import "pkg:/source/utils/StringUtils.bs" + +namespace JobRequest + function Execute(request as object) as void + #if DEBUG + Assert.NotNullOrEmpty(request, "JobRequest.Execute: request cannot be null or empty") + Assert.NotNullOrEmpty(request.jobName, "JobRequest.Execute: request cannot be null or empty") + #end if + + job = CreateObject("roSGNode", request.jobName) + if job = invalid + error = "Failed to create job node: " + request.jobName + LogError(error) + ' Usually callback is fired by the job itself, but if it fails to create, we can call it here + if request.input <> invalid and request.input._callback <> invalid + request.input._callback.error = error + request.input._callback.success = false + request.input._callback.done = true + end if + return + end if + job.id = request.jobName + "-" + StringUtils.RandomId() + + if request.input <> invalid + job.input = request.input + end if + + #if DEBUG + LogDebug("Executing job:", request.jobName) + time = CreateObject("roTimespan") + #end if + + job@.Execute() + + #if DEBUG + LogDebug("Job executed:", request.jobName, "in", time.TotalMilliseconds(), "ms") + #end if + + job.input = invalid + end function +end namespace diff --git a/playlet-lib/src/components/JobSystem/JobSystem.bs b/playlet-lib/src/components/JobSystem/JobSystem.bs index 54bc9b71..55356626 100644 --- a/playlet-lib/src/components/JobSystem/JobSystem.bs +++ b/playlet-lib/src/components/JobSystem/JobSystem.bs @@ -1,3 +1,4 @@ +import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" namespace JobSystem diff --git a/playlet-lib/src/components/JobSystem/JobTask.bs b/playlet-lib/src/components/JobSystem/JobTask.bs index edde1c3b..56d0382c 100644 --- a/playlet-lib/src/components/JobSystem/JobTask.bs +++ b/playlet-lib/src/components/JobSystem/JobTask.bs @@ -1,3 +1,4 @@ +import "pkg:/components/JobSystem/JobRequest.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/StringUtils.bs" @@ -25,35 +26,9 @@ function JobTaskLoop() as void end if if field = "request" request = msg.getData() - ExecuteJobRequest(request) + JobRequest.Execute(request) m.top.ready = true end if end if end while end function - -function ExecuteJobRequest(request as object) as void - job = CreateObject("roSGNode", request.jobName) - job.id = request.jobName + "-" + StringUtils.RandomId() - if job = invalid - LogError("Failed to create job node:", request.jobName) - return - end if - - if request.input <> invalid - job.input = request.input - end if - - #if DEBUG - LogDebug("Executing job:", request.jobName) - time = CreateObject("roTimespan") - #end if - - job@.Execute() - - #if DEBUG - LogDebug("Job executed:", request.jobName, "in", time.TotalMilliseconds(), "ms") - #end if - - job.input = invalid -end function diff --git a/playlet-lib/src/components/Logger/Logger.bs b/playlet-lib/src/components/Logger/Logger.bs index a6444259..29479bff 100644 --- a/playlet-lib/src/components/Logger/Logger.bs +++ b/playlet-lib/src/components/Logger/Logger.bs @@ -16,14 +16,16 @@ function Init() m.top.ObserveField("logLine", port) scene = m.top.getScene() - MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port) - if scene.hasField("enableSystemLogType") - scene.enableSystemLogType = "http.error" - #if DEBUG - scene.enableSystemLogType = "http.connect" - scene.enableSystemLogType = "http.complete" - scene.enableSystemLogType = "bandwidth.minute" - #end if + if scene.hasField("systemLogEvent") + MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port) + if scene.hasField("enableSystemLogType") + scene.enableSystemLogType = "http.error" + #if DEBUG + scene.enableSystemLogType = "http.connect" + scene.enableSystemLogType = "http.complete" + scene.enableSystemLogType = "bandwidth.minute" + #end if + end if end if m.port = port diff --git a/playlet-lib/src/components/PlaylistView/PlaylistView.bs b/playlet-lib/src/components/PlaylistView/PlaylistView.bs index 8f919267..966e94cf 100644 --- a/playlet-lib/src/components/PlaylistView/PlaylistView.bs +++ b/playlet-lib/src/components/PlaylistView/PlaylistView.bs @@ -3,8 +3,6 @@ import "pkg:/components/ContextMenu/ContextMenuUtils.bs" import "pkg:/components/Navigation/LongPress.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" import "pkg:/components/VideoFeed/FeedLoadState.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/FocusManagement.bs" import "pkg:/source/utils/Logging.bs" diff --git a/playlet-lib/src/components/QrCodePoster/GenerateQrCodeJob.bs b/playlet-lib/src/components/QrCodePoster/GenerateQrCodeJob.bs index 111d6bff..9a59dda3 100644 --- a/playlet-lib/src/components/QrCodePoster/GenerateQrCodeJob.bs +++ b/playlet-lib/src/components/QrCodePoster/GenerateQrCodeJob.bs @@ -1,4 +1,5 @@ import "pkg:/source/QrCode/QrImage.bs" +import "pkg:/source/QrCode/QrMode.bs" import "pkg:/source/utils/StringUtils.bs" @job("GenerateQrCodeJob") diff --git a/playlet-lib/src/components/Screens/AppInfoScreen/AppInfoScreen.bs b/playlet-lib/src/components/Screens/AppInfoScreen/AppInfoScreen.bs index 79574869..214d2b2c 100644 --- a/playlet-lib/src/components/Screens/AppInfoScreen/AppInfoScreen.bs +++ b/playlet-lib/src/components/Screens/AppInfoScreen/AppInfoScreen.bs @@ -1,4 +1,4 @@ -import "pkg:/source/AsyncTask/AsyncTask.bs" +import "pkg:/source/utils/Types.bs" function Init() ' TODO:P2 Add tooltip to each field with description of what it means diff --git a/playlet-lib/src/components/Services/Innertube/NodesParser.bs b/playlet-lib/src/components/Services/Innertube/NodesParser.bs index d8ed90b0..aeeb4afc 100644 --- a/playlet-lib/src/components/Services/Innertube/NodesParser.bs +++ b/playlet-lib/src/components/Services/Innertube/NodesParser.bs @@ -591,7 +591,11 @@ namespace Innertube if not IsString(videoId) videoId = ObjectUtils.Dig(nodeData, ["updatedMetadataEndpoint", "updatedMetadataEndpoint", "videoId"]) if not IsString(videoId) - LogWarn("Invalid video ID", `\n`, FormatJson(nodeData)) + #if DEBUG + LogWarn("Invalid video ID in videoPrimaryInfoRenderer", `\n`, FormatJson(nodeData)) + #else + LogWarn("Invalid video ID in videoPrimaryInfoRenderer") + #end if return invalid end if end if diff --git a/playlet-lib/src/components/Services/Innertube/OAuth.bs b/playlet-lib/src/components/Services/Innertube/OAuth.bs index 84253ca7..93426aff 100644 --- a/playlet-lib/src/components/Services/Innertube/OAuth.bs +++ b/playlet-lib/src/components/Services/Innertube/OAuth.bs @@ -1,3 +1,6 @@ +import "pkg:/components/Services/Innertube/Constants.bs" +import "pkg:/components/Services/Innertube/Context.bs" +import "pkg:/components/Services/Innertube/NodesParser.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/TimeUtils.bs" diff --git a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs index 5b5a9e05..685b222c 100644 --- a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs @@ -1,4 +1,5 @@ import "pkg:/components/Services/Innertube/Context.bs" +import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/Types.bs" namespace Innertube diff --git a/playlet-lib/src/components/Services/Invidious/Invidious.bs b/playlet-lib/src/components/Services/Invidious/Invidious.bs index 1299d0d0..9c45e1b2 100644 --- a/playlet-lib/src/components/Services/Invidious/Invidious.bs +++ b/playlet-lib/src/components/Services/Invidious/Invidious.bs @@ -1,6 +1,4 @@ import "InvidiousService.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" function Init() m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml")) diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index 415dbd7b..0db41138 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -1,8 +1,6 @@ import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/VideoFeed/PaginationType.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/CryptoUtils.bs" import "pkg:/source/utils/Logging.bs" diff --git a/playlet-lib/src/components/VideoFeed/VideoRowList.bs b/playlet-lib/src/components/VideoFeed/VideoRowList.bs index 9b1bb78f..21ca3818 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowList.bs +++ b/playlet-lib/src/components/VideoFeed/VideoRowList.bs @@ -6,8 +6,6 @@ import "pkg:/components/Navigation/LongPress.bs" import "pkg:/components/PlaylistView/PlaylistUtils.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" import "pkg:/components/VideoFeed/FeedLoadState.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/DisposableObserve.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Logging.bs" diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs similarity index 92% rename from playlet-lib/src/components/VideoPlayer/VideoContentTask.bs rename to playlet-lib/src/components/VideoPlayer/VideoContentJob.bs index 090aa16d..12feeaf8 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs @@ -1,8 +1,10 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" -@asynctask -function VideoContentTask(input as object) as object +@job("VideoContentJob") +function ExecuteJob() as void + input = JobGetInput() + contentNode = input.content invidiousNode = input.invidious innertubeNode = input.innertube @@ -10,12 +12,14 @@ function VideoContentTask(input as object) as object loungeServiceNode = input.loungeService playletServerPort = input.playletServerPort - if m.top.cancel - return invalid + if JobIsCancelled() + JobCancel() + return end if if StringUtils.IsNullOrEmpty(contentNode.videoId) - throw "Can't load video information: videoId is missing" + JobError("Can't load video information: videoId is missing") + return end if service = new Invidious.InvidiousService(invidiousNode) @@ -23,6 +27,7 @@ function VideoContentTask(input as object) as object metadata = contentNode.metadata if not IsAssociativeArray(metadata) + cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) if backend = "playlet" visitorData = innertubeNode.visitorData if StringUtils.IsNullOrEmpty(visitorData) @@ -32,16 +37,14 @@ function VideoContentTask(input as object) as object message = wait(20000, messagePort) innertubeNode.unobserveFieldScoped("visitorData") if message = invalid - return { - success: false - error: "Failed to get visitor data. Please try again later." - } + JobError("Failed to get visitor data. Please try again later.") + return end if visitorData = message.getData() end if metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { - "cancellation": m.top.cancellation + "cancellation": cancellation "credentialTransferToken": loungeServiceNode.credentialTransferToken "visitorData": visitorData }) @@ -51,14 +54,12 @@ function VideoContentTask(input as object) as object end if if metadata = invalid - return { - success: false - error: "Failed to get video metadata" - } + JobError("Failed to get video metadata") end if - if m.top.cancel - return invalid + if JobIsCancelled() + JobCancel() + return end if contentNode.title = metadata.title @@ -68,11 +69,8 @@ function VideoContentTask(input as object) as object if metadata.error <> invalid ' Adding metadata allows us to play next recommended video after displaying the error contentNode.addFields({ metadata: metadata }) - - return { - success: false - error: metadata.error - } + JobError(metadata.error) + return end if streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort) @@ -95,10 +93,6 @@ function VideoContentTask(input as object) as object if metadata.liveNow = true contentNode.Live = true end if - - return { - success: true - } end function function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object diff --git a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs index 078072a7..5cb6bae0 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs @@ -1,14 +1,14 @@ #const DEBUG_LOG_VIDEO_QUALITY = false import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/components/JobSystem/Jobs.bs" +import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" import "pkg:/components/VideoPlayer/Lounge.bs" import "pkg:/components/VideoPlayer/SponsorBlock.bs" import "pkg:/components/VideoPlayer/VideoPlayerStyle.bs" import "pkg:/components/VideoQueue/VideoQueueUtils.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/RemoteKeys.bs" @@ -46,7 +46,7 @@ function Init() ' It is set to true because stopping synchronously causes timeout and crash ' Usually we would need to wait for the video state to move to "stopping" then to "stopped" ' before considering the video node closed, and creating a new one. - ' However, since we have a task to load video details, there should be enough time for the + ' However, since we have a job to load video details, there should be enough time for the ' video node to close before we create a new one. if m.top.hasField("asyncStopSemantics") m.top.asyncStopSemantics = true @@ -144,60 +144,63 @@ function PlayWithContent(contentNode as object) videoContentNode.AddFields({ metadata: metadata }) end if - StartVideoContentTask(videoContentNode) + StartVideoContentJob(videoContentNode) Lounge.SendNowPlayingLoading(contentNode.videoId) end function -function StartVideoContentTask(videoContentNode as object) - if m.videoContentTask <> invalid - m.videoContentTask.cancel = true +function StartVideoContentJob(videoContentNode as object) + if m.videoContentJob <> invalid + m.videoContentJob.cancel = true end if m.top.content = videoContentNode - m.videoContentTask = AsyncTask.Start(Tasks.VideoContentTask, { + + input = { content: videoContentNode invidious: m.top.invidious innertube: m.top.innertube preferences: m.top.preferences loungeService: m.top.loungeService playletServerPort: m.top.webServer.port - }, OnVideoContentTaskResults) + } + + m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone) + JobSystem.QueueJob(m.jobQueue, Jobs.VideoContentJob, input, m.videoContentJob) end function -function OnVideoContentTaskResults(output as object) as void - m.videoContentTask = invalid - if output.cancelled or m.onCloseCalled = true +function OnVideoContentJobDone(event as object) as void + JobSystem.UnobserveCallback(event.getRoSGNode()) + m.videoContentJob = invalid + + info = event.getInfo() + if info.cancel or m.onCloseCalled = true return end if - if not output.success or not output.result.success - ' output.error for unhandled exception - error = output.error - if error = invalid - ' output.result.error for network errors - error = output.result.error + content = m.top.content + + if not info.success + videoId = "" + if content <> invalid + videoId = content.videoId end if - error = ErrorUtils.Format(error) - LogError(error) - videoId = `${output.task.input.content.videoId}` title = Tr(Locale.VideoPlayer.VideoLoadError) - message = Tr(Locale.VideoPlayer.VideoLoadErrorMessage).Replace("%1", videoId) + `\n${error}` + message = Tr(Locale.VideoPlayer.VideoLoadErrorMessage).Replace("%1", videoId) + `\n${info.error}` buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)] dialog = DialogUtils.ShowTimedDialogButtons(message, title, buttons, 0, 10, true) if dialog <> invalid - dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse)) + dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse)) else - OnVideoContentTaskErrorDialogResponse(invalid) + OnVideoContentJobErrorDialogResponse(invalid) end if Lounge.SendOnStateChange() return end if - content = m.top.content SponsorBlock.FetchSponsorBlock(content.metadata) SeekToInitialPosition(content) @@ -302,7 +305,7 @@ function OnPreviousPlayerState(event as object) as void end if end function -function OnVideoContentTaskErrorDialogResponse(event as object) +function OnVideoContentJobErrorDialogResponse(event as object) shouldPlayNext = false if event <> invalid dialog = event.getRoSGNode() @@ -380,9 +383,9 @@ function OnClose() m.markVideoWatchedJob.cancel = true m.markVideoWatchedJob = invalid end if - if m.videoContentTask <> invalid - m.videoContentTask.cancel = true - m.videoContentTask = invalid + if m.videoContentJob <> invalid + m.videoContentJob.cancel = true + m.videoContentJob = invalid end if if m.sponsorBlockSegmentsJob <> invalid m.sponsorBlockSegmentsJob.cancel = true @@ -495,9 +498,9 @@ function OnVideoPlayerStateChange() as void dialog = DialogUtils.ShowTimedDialogButtons(messageLines, title, buttons, 0, 10, true) if dialog <> invalid - dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse)) + dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse)) else - OnVideoContentTaskErrorDialogResponse(invalid) + OnVideoContentJobErrorDialogResponse(invalid) end if m.ignoreNextFinishedState = true end if diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoContentDevJob.bs similarity index 84% rename from playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs rename to playlet-lib/src/components/VideoPlayerDev/VideoContentDevJob.bs index 972447c2..738ba44d 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoContentTaskDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoContentDevJob.bs @@ -2,8 +2,10 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" -@asynctask -function VideoContentTaskDev(input as object) as object +@job("VideoContentDevJob") +function ExecuteJob() as void + input = JobGetInput() + titleLabel = input.titleLabel secondaryTitleLabel = input.secondaryTitleLabel backgroundPoster = input.backgroundPoster @@ -17,7 +19,8 @@ function VideoContentTaskDev(input as object) as object videoId = contentNode.videoId if StringUtils.IsNullOrEmpty(videoId) - throw "Can't load video information: videoId is missing" + JobError("Can't load video information: videoId is missing") + return end if service = new Invidious.InvidiousService(invidiousNode) @@ -25,22 +28,22 @@ function VideoContentTaskDev(input as object) as object backgroundPoster.uri = `${instance}/vi/${videoId}/maxresdefault.jpg` + cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) backend = preferencesNode["backend.selected"] if backend = "playlet" - metadata = InnertubeService.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) + metadata = InnertubeService.GetVideoMetadata(videoId, { cancellation: cancellation }) else - metadata = service.GetVideoMetadata(videoId, { cancellation: m.top.cancellation }) + metadata = service.GetVideoMetadata(videoId, { cancellation: cancellation }) end if - if m.top.cancel - return invalid + if JobIsCancelled() + JobCancel() + return end if if metadata.error <> invalid - return { - success: false - error: metadata.error - } + JobError(metadata.error) + return end if contentNode.title = metadata.title @@ -69,10 +72,6 @@ function VideoContentTaskDev(input as object) as object playletStreamUrls: streamUrls playletStreamUrlIndex: 0 }) - - return { - success: true - } end function function CreateStreamUrls(metadata as object) as object diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs index 9e33256c..9562eeb6 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs @@ -1,10 +1,10 @@ +import "pkg:/components/JobSystem/Jobs.bs" +import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/Navigation/Navigation.bs" import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/VideoPlayerDev/PictureInPicture.bs" import "pkg:/components/VideoPlayerDev/PlayerUi.bs" import "pkg:/components/VideoQueue/VideoQueueUtils.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/DisposableObserve.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/FocusManagement.bs" @@ -76,12 +76,12 @@ function PlayWithContent(contentNode as object) m.backgroundPosterSmall.uri = thumbnail end if - StartVideoContentTask(videoContentNode) + StartVideoContentDevJob(videoContentNode) end function -function StartVideoContentTask(videoContentNode as object) - if m.videoContentTask <> invalid - m.videoContentTask.cancel = true +function StartVideoContentDevJob(videoContentNode as object) + if m.videoContentDevJob <> invalid + m.videoContentDevJob.cancel = true end if m.top.content = videoContentNode @@ -91,31 +91,29 @@ function StartVideoContentTask(videoContentNode as object) m.loadingUi.visible = true m.loadingSpinner.control = "start" - m.videoContentTask = AsyncTask.Start(Tasks.VideoContentTaskDev, { + input = { titleLabel: m.titleLabel secondaryTitleLabel: m.secondaryTitleLabel content: videoContentNode invidious: m.top.invidious preferences: m.top.preferences backgroundPoster: m.backgroundPoster - }, OnVideoContentTaskResults) + } + + m.videoContentDevJob = JobSystem.CreateCallback(OnVideoContentDevJobDone) + JobSystem.QueueJob(m.jobQueue, Jobs.VideoContentDevJob, input, m.videoContentDevJob) end function -function OnVideoContentTaskResults(output as object) as void - m.videoContentTask = invalid - if output.cancelled +function OnVideoContentDevJobDone(event as object) as void + JobSystem.UnobserveCallback(event.getRoSGNode()) + m.videoContentDevJob = invalid + + info = event.getInfo() + if info.cancel return end if - if not output.success or not output.result.success - ' output.error for unhandled exception - error = output.error - if error = invalid - ' output.result.error for network errors - error = output.result.error - end if - error = ErrorUtils.Format(error) - LogError(error) + if not info.success m.top.close = true return end if @@ -126,9 +124,9 @@ end function function OnClose() m.top.previousPlayer = invalid - if m.videoContentTask <> invalid - m.videoContentTask.cancel = true - m.videoContentTask = invalid + if m.videoContentDevJob <> invalid + m.videoContentDevJob.cancel = true + m.videoContentDevJob = invalid end if parent = m.top.getParent() diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.xml b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.xml index 16cdb827..288add58 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.xml +++ b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.xml @@ -7,6 +7,7 @@ --> + diff --git a/playlet-lib/src/components/VideoQueue/VideoQueue.bs b/playlet-lib/src/components/VideoQueue/VideoQueue.bs index a0d03042..d05bb33e 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueue.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueue.bs @@ -3,8 +3,6 @@ import "pkg:/components/Services/LoungeService/LoungeMessages.bs" import "pkg:/components/VideoFeed/FeedLoadState.bs" import "pkg:/components/VideoQueue/Notifications/VideoQueueNotificationUtils.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/FocusManagement.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/MathUtils.bs" diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueView.bs b/playlet-lib/src/components/VideoQueue/VideoQueueView.bs index d7d7c2f0..0b8a1e3c 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueView.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueView.bs @@ -1,6 +1,6 @@ +import "pkg:/components/JobSystem/Jobs.bs" +import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/Navigation/Navigation.bs" -import "pkg:/source/AsyncTask/AsyncTask.bs" -import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/utils/DisposableObserve.bs" import "pkg:/source/utils/FocusManagement.bs" import "pkg:/source/utils/Locale.bs" @@ -37,9 +37,9 @@ end function function OnContentSet() as void content = m.top.content if content = invalid - if m.loadDetailsTask <> invalid - m.loadDetailsTask.cancel = true - m.loadDetailsTask = invalid + if m.videoQueueViewContentJob <> invalid + m.videoQueueViewContentJob.cancel = true + m.videoQueueViewContentJob = invalid end if return end if @@ -141,17 +141,20 @@ function LoadVideoDetailsIfNeeded() as void LogInfo("Loading video details for", m.videosDetailsToLoad.Count(), "videos") - if m.loadDetailsTask <> invalid - m.loadDetailsTask.cancel = true + if m.videoQueueViewContentJob <> invalid + m.videoQueueViewContentJob.cancel = true end if - m.loadDetailsTask = AsyncTask.Start(Tasks.VideoQueueViewContentTask, { + input = { videoNodes: m.videosDetailsToLoad innertube: m.top.innertube invidious: m.top.invidious preferences: m.top.preferences index: indexInLoadingArray - }) + } + + m.videoQueueViewContentJob = JobSystem.CreateCallback() + JobSystem.QueueJob(m.jobQueue, Jobs.VideoQueueViewContentJob, input, m.videoQueueViewContentJob) end function function AdjustFocus(videoCount as integer) diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueView.xml b/playlet-lib/src/components/VideoQueue/VideoQueueView.xml index 7a409484..d02dd626 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueView.xml +++ b/playlet-lib/src/components/VideoQueue/VideoQueueView.xml @@ -4,6 +4,7 @@ + diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs similarity index 87% rename from playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs rename to playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs index 86d2dec4..18e8fbcf 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentTask.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs @@ -2,17 +2,20 @@ 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" -@asynctask -function VideoQueueViewContentTask(input as object) as object +@job("VideoQueueViewContentJob") +function ExecuteJob() as void + input = JobGetInput() + videoNodes = input.videoNodes innertubeNode = input.innertube invidiousNode = input.invidious preferencesNode = input.preferences service = new Invidious.InvidiousService(invidiousNode) instance = service.GetInstance() - cancellation = m.top.cancellation + cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) index = MathUtils.Clamp(input.index - 2, 0, videoNodes.Count() - 1) @@ -38,8 +41,9 @@ function VideoQueueViewContentTask(input as object) as object sleep(500) end if - if m.top.cancel = true - return invalid + if JobIsCancelled() + JobCancel() + return end if end for @@ -50,12 +54,13 @@ function VideoQueueViewContentTask(input as object) as object sleep(1000) end if - if m.top.cancel = true - return invalid + if JobIsCancelled() + JobCancel() + return end if end for - return invalid + return end function function LoadVideoDetail(videoNode as object, service as object, instance as string, requestOptions as object, backend as string) as boolean diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewUtils.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewUtils.bs index 423e2911..250d2478 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewUtils.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewUtils.bs @@ -6,6 +6,7 @@ namespace VideoQueueViewUtils videoQueueView = CreateObject("roSGNode", "VideoQueueView") videoQueueView.videoQueue = videoQueue videoQueueView.appController = appController + videoQueueView.jobQueue = videoQueue.jobQueue videoQueueView.innertube = videoQueue.innertube videoQueueView.invidious = videoQueue.invidious videoQueueView.preferences = videoQueue.preferences diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs index ac6bd5a4..98505082 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs @@ -1,4 +1,5 @@ import "pkg:/components/Services/Innertube/SessionData.bs" +import "pkg:/components/Web/WebServer/Http/HttpRouter.bs" import "pkg:/source/services/HttpClient.bs" namespace Http diff --git a/playlet-lib/src/source/AsyncTask/AsyncTask.bs b/playlet-lib/src/source/AsyncTask/AsyncTask.bs deleted file mode 100644 index 2f0f2a0e..00000000 --- a/playlet-lib/src/source/AsyncTask/AsyncTask.bs +++ /dev/null @@ -1,49 +0,0 @@ -import "pkg:/source/utils/StringUtils.bs" -import "pkg:/source/utils/Types.bs" - -namespace AsyncTask - - function Start(taskName as string, input as object, callback = invalid as object) as object - task = Create(taskName, input, callback) - task.control = "RUN" - return task - end function - - function Create(taskName as string, input as object, callback = invalid as object) as object - id = StringUtils.RandomId() - task = createObject("roSGNode", taskName) - task.id = id - task.input = input - - m[`asynctask_${id}`] = task - m[`asynctask_${id}_callback`] = callback - task.ObserveFieldScoped("state", FuncName(internal_OnTaskState)) - - return task - end function - - function internal_OnTaskState(e as object) as void - task = e.getRoSGNode() - if task.state = "init" or task.state = "run" - return - end if - - task.UnobserveFieldScoped("state") - - id = task.id - output = task.output - ' if output is invalid, it means the task was interrupted before the result is ready - if output <> invalid - callback = m[`asynctask_${id}_callback`] - if callback <> invalid - callback(output) - end if - end if - - task.input = invalid - task.output = invalid - m.delete(`asynctask_${id}`) - m.delete(`asynctask_${id}_callback`) - end function - -end namespace diff --git a/playlet-lib/src/source/components/tests/GenerateQrCodeJob.spec.bs b/playlet-lib/src/source/components/tests/GenerateQrCodeJob.spec.bs new file mode 100644 index 00000000..20570108 --- /dev/null +++ b/playlet-lib/src/source/components/tests/GenerateQrCodeJob.spec.bs @@ -0,0 +1,42 @@ +import "pkg:/components/JobSystem/JobRequest.bs" +import "pkg:/components/JobSystem/JobSystem.bs" + +namespace Tests + + @suite + class GenerateQrCodeJobTests extends Rooibos.BaseTestSuite + + protected override function setup() + m.logger = CreateObject("roSGNode", "Logger") + m.logger.logLevel = -1 + end function + + @describe("GenerateQrCodeJob") + @it("Generates QR codes correctly") + function _() + poster = CreateObject("roSGNode", "Node") + poster.addField("uri", "uri", false) + + JobRequest.Execute({ + jobName: "GenerateQrCodeJob" + input: { + poster: poster + text: "http://127.0.0.1:1234/some/path/to/resource?query=string" + size: 300 + padding: 10 + } + }) + + m.assertNotEmpty(poster.uri, "Poster URI should not be empty after generating QR code") + + buffer = CreateObject("roByteArray") + buffer.ReadFile(poster.uri) + digest = CreateObject("roEVPDigest") + digest.Setup("md5") + md5 = digest.Process(buffer) + + m.assertEqual(md5, "45ad1dbc361f47d267ab89e23d45a1d5") + end function + end class + +end namespace diff --git a/playlet-lib/src/source/components/tests/JobSystem.spec.bs b/playlet-lib/src/source/components/tests/JobSystem.spec.bs index 87a54b97..e3ce6d49 100644 --- a/playlet-lib/src/source/components/tests/JobSystem.spec.bs +++ b/playlet-lib/src/source/components/tests/JobSystem.spec.bs @@ -8,6 +8,7 @@ namespace Tests protected override function setup() m.logger = CreateObject("roSGNode", "Logger") + m.logger.logLevel = -1 end function protected override function beforeEach() @@ -28,7 +29,7 @@ namespace Tests messagePort = CreateObject("roMessagePort") for i = 1 to 100 - callbackNode = CreateObject("roSGNode", "JobCallback") + callbackNode = JobSystem.CreateCallback() callbackNode.observeField("done", messagePort, ["success"]) JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 50, success: i mod 2 = 0 }, callbackNode) end for @@ -66,7 +67,7 @@ namespace Tests callbacks = [] for i = 1 to 10 - callbackNode = CreateObject("roSGNode", "JobCallback") + callbackNode = JobSystem.CreateCallback() callbackNode.observeField("done", messagePort, ["success", "cancel"]) callbacks.push(callbackNode) JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 5000, success: true }, callbackNode) @@ -114,7 +115,7 @@ namespace Tests callbacks = [] for i = 1 to 10 - callbackNode = CreateObject("roSGNode", "JobCallback") + callbackNode = JobSystem.CreateCallback() callbackNode.observeField("done", messagePort, ["success", "cancel"]) callbacks.push(callbackNode) JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 5000, success: true }, callbackNode) @@ -147,6 +148,34 @@ namespace Tests end while end function + @it("Handles invalid job names gracefully") + function _() + messagePort = CreateObject("roMessagePort") + callbackNode = JobSystem.CreateCallback() + callbackNode.observeField("done", messagePort, ["success", "error"]) + + ' Attempt to queue a job with an invalid name + JobSystem.QueueJob(m.jobQueue, "InvalidJobName", {}, callbackNode) + + ' Wait for the error message + msg = wait(1000, messagePort) + + if msg = invalid + m.testSuite.fail("Waiting for job error message timed out after 1000ms") + end if + + if type(msg) <> "roSGNodeEvent" or msg.getField() <> "done" + m.testSuite.fail("Expected a done event for the job error") + end if + + done = msg.getData() + info = msg.getInfo() + + m.assertTrue(done, "Job should be done") + m.assertFalse(info.success, "Job should not succeed with an invalid job name") + m.assertNotEmpty(info.error, "Error message should not be empty") + end function + end class end namespace diff --git a/playlet-lib/src/source/utils/AssertUtils.bs b/playlet-lib/src/source/utils/AssertUtils.bs index e7b2ccd1..15555436 100644 --- a/playlet-lib/src/source/utils/AssertUtils.bs +++ b/playlet-lib/src/source/utils/AssertUtils.bs @@ -35,4 +35,17 @@ namespace Assert throw "Assertion failed: Node does not have field '" + field + "'. " + ToString(message) end if end function + + function NotNullOrEmpty(value as dynamic, message = invalid as dynamic) as void + if value = invalid + throw "Assertion failed: Value is invalid. " + ToString(message) + end if + if IsString(value) and (Len(value) = 0) + throw "Assertion failed: Value is an empty string. " + ToString(message) + else if IsArray(value) and (value.Count() = 0) + throw "Assertion failed: Value is an empty array. " + ToString(message) + else if IsAssociativeArray(value) and (value.ifAssociativeArray.count() = 0) + throw "Assertion failed: Value is an empty associative array. " + ToString(message) + end if + end function end namespace diff --git a/playlet-lib/src/source/utils/UrlUtils.bs b/playlet-lib/src/source/utils/UrlUtils.bs index f5633997..3bb76974 100644 --- a/playlet-lib/src/source/utils/UrlUtils.bs +++ b/playlet-lib/src/source/utils/UrlUtils.bs @@ -1,3 +1,4 @@ +import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" namespace UrlUtils diff --git a/tools/bs-plugins/asynctask-plugin.ts b/tools/bs-plugins/asynctask-plugin.ts deleted file mode 100644 index fe64104e..00000000 --- a/tools/bs-plugins/asynctask-plugin.ts +++ /dev/null @@ -1,177 +0,0 @@ -// This plugin generates a task component for each function annotated with @asynctask - -import { - CompilerPlugin, - BscFile, - isBrsFile, - WalkMode, - createVisitor, - Program, - FunctionStatement, - DiagnosticSeverity, -} from 'brighterscript'; - -export class AsyncTaskPlugin implements CompilerPlugin { - public name = 'AsyncTaskPlugin'; - - afterFileParse(file: BscFile) { - if (!isBrsFile(file)) { - return - } - - const program = file.program - - file.ast.walk(createVisitor({ - FunctionExpression: (func) => { - if (!this.isAsyncTask(func.functionStatement)) { - return - } - - const functionName = func.functionStatement!.name.text - const hasParams = func.functionStatement!.func.parameters.length > 0 - const taskName = `${functionName}_AsyncTask` - - const bs = this.generateBsTask(functionName, hasParams, file) - const bsFile = `components/AsyncTask/generated/${taskName}.bs` - - const xml = this.generateXmlTask(taskName, bsFile) - const xmlFile = `components/AsyncTask/generated/${taskName}.xml` - - if (program.hasFile(xmlFile)) { - const currentContent = program.getFile(xmlFile).fileContents - if (currentContent !== xml) { - file.addDiagnostics([{ - file: file, - range: func.range, - message: `AsyncTaskPlugin: file ${xmlFile} already exists`, - severity: DiagnosticSeverity.Error, - code: 'ASYNC_TASK_FILE_EXISTS', - }]); - } - } - file.program.setFile(xmlFile, xml) - - if (program.hasFile(bsFile)) { - const currentContent = program.getFile(bsFile).fileContents - if (currentContent !== bs) { - file.addDiagnostics([{ - file: file, - range: func.range, - message: `AsyncTaskPlugin: file ${bsFile} already exists`, - severity: DiagnosticSeverity.Error, - code: 'ASYNC_TASK_FILE_EXISTS', - }]); - } - } - file.program.setFile(bsFile, bs) - }, - }), { - walkMode: WalkMode.visitExpressionsRecursive - }); - } - - beforeProgramValidate(program: Program) { - this.generateTaskListEnum(program); - } - - isAsyncTask(functionStatement: FunctionStatement | undefined) { - const annotations = functionStatement?.annotations - if (!annotations || annotations.length === 0) { - return false - } - for (let index = 0; index < annotations.length; index++) { - const annotation = annotations[index]; - if (annotation.name === "asynctask") { - return true - } - } - return false - } - - generateBsTask(functionName: string, hasInput: boolean, file: BscFile): string { - return ` -import "pkg:/${file.pkgPath}" -import "pkg:/source/utils/ErrorUtils.bs" - -function Init() - m.top.functionName = "TaskMain" - m.top.cancellation = { - node: m.top - field: "cancel" - value: true - } -end function - -function TaskMain() - try - result = ${functionName}(${(hasInput ? "m.top.input" : "")}) - m.top.setField("output", { - success: true - task: m.top - cancelled: m.top.cancel - result: result - }) - catch e - #if DEBUG - print "ERROR in ${functionName}: " - print ErrorUtils.Format(e) - #end if - m.top.setField("output", { - success: false - task: m.top - cancelled: m.top.cancel - error: e - }) - end try -end function -` - } - - generateXmlTask(taskName: string, bsFile: string): string { - - return ` - - - - - - - - -` - } - - generateTaskListEnum(program: Program) { - const asyncTasks = Object.values(program.files).reduce((acc, file) => { - if (!isBrsFile(file)) { - return acc - } - - file.ast.walk(createVisitor({ - FunctionExpression: (func) => { - if (!this.isAsyncTask(func.functionStatement)) { - return - } - - acc.add(func.functionStatement!.name.text) - }, - }), { - walkMode: WalkMode.visitExpressionsRecursive - }); - - return acc - }, new Set()); - - const enumItems = Array.from(asyncTasks).map((task) => { - return `${task} = "${task}_AsyncTask"` - }) - - const content = 'enum Tasks\n ' + enumItems.join('\n ') + '\nend enum\n'; - - program.setFile('source/AsyncTask/Tasks.bs', content); - } -} - -export default () => { - return new AsyncTaskPlugin(); -}; diff --git a/tools/bs-plugins/import-validation-plugin.ts b/tools/bs-plugins/import-validation-plugin.ts index abcb0c1f..b2c20270 100644 --- a/tools/bs-plugins/import-validation-plugin.ts +++ b/tools/bs-plugins/import-validation-plugin.ts @@ -24,6 +24,11 @@ export class ImportValidationPlugin implements CompilerPlugin { return; } + // Skip job files + if (file.srcPath.endsWith('Job.bs')) { + return; + } + this.generateXmlComponent(file); }