diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a434e50..74a6fd86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- [perf] Added a job system to control background tasks. + ### Fixed - Issue with deep linking not working due to session data race condition diff --git a/config/bsconfig.base.jsonc b/config/bsconfig.base.jsonc index a711596e..2b7b5ea0 100644 --- a/config/bsconfig.base.jsonc +++ b/config/bsconfig.base.jsonc @@ -83,6 +83,7 @@ "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", "../tools/bs-plugins/bindings-plugin.ts", diff --git a/config/bsconfig.tests.base.jsonc b/config/bsconfig.tests.base.jsonc index 33070c35..4ac299cc 100644 --- a/config/bsconfig.tests.base.jsonc +++ b/config/bsconfig.tests.base.jsonc @@ -21,6 +21,7 @@ "@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", "../tools/bs-plugins/bindings-plugin.ts", diff --git a/config/bslint.jsonc b/config/bslint.jsonc index 9c095d8f..0acef20a 100644 --- a/config/bslint.jsonc +++ b/config/bslint.jsonc @@ -12,7 +12,7 @@ "named-function-style": "no-sub", "anon-function-style": "no-sub", "aa-comma-style": "never", - "no-print": "warn", + "no-print": "off", "no-todo": "off", "no-stop": "error", "eol-last": "always", diff --git a/docs/plugins.md b/docs/plugins.md index 16df81a8..cc923b99 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -7,6 +7,7 @@ - [@oninit](#oninit) - [Bindings](#bindings) - [Async Task Generator](#async-task-generator) +- [Job System Generator](#job-system-generator) - [Tracking transpilied files](#tracking-transpilied-files) - [Logger](#logger) - [Type Gen](#type-gen) @@ -396,7 +397,7 @@ Notice how the function has `@oninit`, which means it will be called in the `Ini When the `bindings` field is set, the node registers itself to a global array of nodes that need binding. -Next, once all nodes are registered, we need to call a function called `AutoBindSceneGraph()`. This need to be called once from the root node's `Init()` (concretely, [here](https://github.com/iBicha/playlet/blob/bea7fb209b2bd42aff620d06b416cf1e45988190/playlet-lib/src/components/MainScene.bs#L17)) +Next, once all nodes are registered, we need to call a function called `AutoBindSceneGraph()`. This need to be called once from the root node's `Init()` (concretely, [here in MainScene.bs](https://github.com/iBicha/playlet/blob/bea7fb209b2bd42aff620d06b416cf1e45988190/playlet-lib/src/components/MainScene.bs#L17)) `AutoBindSceneGraph()` will loop through all the nodes that require binding, and use the information we assigned to `m.top.bindings` of each node to populate all the needed references. @@ -471,6 +472,13 @@ The rest will be taken care of by the plugin, which will generate an `xml` file 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. + ## Tracking transpilied files **[Source](/tools/bs-plugins/track-transpiled-plugin.ts)** diff --git a/playlet-app/src/source/Logger.bs b/playlet-app/src/source/Logger.bs index f984fed9..b84fbb5f 100644 --- a/playlet-app/src/source/Logger.bs +++ b/playlet-app/src/source/Logger.bs @@ -9,8 +9,7 @@ namespace Logger function Log(msg as string) msg = "[APP] " + msg - ' bs:disable-next-line LINT3012 - print(msg) + print msg buffer = CreateObject("roByteArray") buffer.FromAsciiString(msg + `\n`) @@ -39,8 +38,7 @@ namespace Logger msg += `console_log:\n${lastExitInfo.console_log}\n` msg += `********** End Last Exit Info **********\n` - ' bs:disable-next-line LINT3012 - print(msg) + print msg buffer = CreateObject("roByteArray") buffer.FromAsciiString(msg + `\n`) diff --git a/playlet-lib/src/components/ChannelView/ChannelView.bs b/playlet-lib/src/components/ChannelView/ChannelView.bs index d833fdd8..a93a3e19 100644 --- a/playlet-lib/src/components/ChannelView/ChannelView.bs +++ b/playlet-lib/src/components/ChannelView/ChannelView.bs @@ -1,8 +1,8 @@ import "pkg:/components/ContextMenu/ContextMenuUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs" +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" @@ -83,7 +83,7 @@ function OnContentSet() as void end if end if - content@.LoadChannel(m.invidious) + content@.LoadChannel(m.invidious, m.jobQueue) authorId = ValidString(content.authorId) author = ValidString(content._author) @@ -162,30 +162,34 @@ end function function OnDispose() m.rowList.dispose = true DisposeObservers() - if m.subscribeTask <> invalid - m.subscribeTask.cancel = true - m.subscribeTask = invalid + if m.subscribeJob <> invalid + m.subscribeJob.cancel = true + m.subscribeJob = invalid end if - if m.fetchSubscriptionStatusTask <> invalid - m.fetchSubscriptionStatusTask.cancel = true - m.fetchSubscriptionStatusTask = invalid + if m.fetchSubscriptionStatusJob <> invalid + m.fetchSubscriptionStatusJob.cancel = true + m.fetchSubscriptionStatusJob = invalid end if end function function OnSubscribeButtonSelected() - if m.subscribeTask <> invalid - m.subscribeTask.cancel = true + if m.subscribeJob <> invalid + m.subscribeJob.cancel = true end if - if m.fetchSubscriptionStatusTask <> invalid - m.fetchSubscriptionStatusTask.cancel = true + if m.fetchSubscriptionStatusJob <> invalid + m.fetchSubscriptionStatusJob.cancel = true end if - m.subscribeTask = AsyncTask.Start(Tasks.SubscribeTask, { + input = { channelView: m.top invidious: m.invidious ucid: m.authorId subscribe: not m.top.isSubscribed - }) + } + + callback = JobSystem.CreateCallback() + JobSystem.QueueJob(m.jobQueue, Jobs.SubscribeJob, input, callback) + m.subscribeJob = callback end function function OnBannerLoadStatus() as void @@ -392,20 +396,25 @@ function FetchSubscriptionStatus() as void return end if - if m.fetchSubscriptionStatusTask <> invalid + if m.fetchSubscriptionStatusJob <> invalid return end if - m.fetchSubscriptionStatusTask = AsyncTask.Start(Tasks.FetchSubscriptionStatusTask, { + input = { channelView: m.top ucid: authorId authToken: m.invidious.authToken invidious: m.invidious - }) + } + + callback = JobSystem.CreateCallback(OnFetchSubscriptionStatusDone) + JobSystem.QueueJob(m.jobQueue, Jobs.FetchSubscriptionStatusJob, input, callback) + m.fetchSubscriptionStatusJob = callback end function -function OnFetchSubscriptionStatusResult(_output as object) as void - m.fetchSubscriptionStatusTask = invalid +function OnFetchSubscriptionStatusDone(event as object) as void + JobSystem.UnobserveCallback(event.getRoSGNode()) + m.fetchSubscriptionStatusJob = invalid end function function OnSubscriptionChanged() diff --git a/playlet-lib/src/components/ChannelView/ChannelView.xml b/playlet-lib/src/components/ChannelView/ChannelView.xml index 561b370a..e0da0239 100644 --- a/playlet-lib/src/components/ChannelView/ChannelView.xml +++ b/playlet-lib/src/components/ChannelView/ChannelView.xml @@ -6,6 +6,7 @@ + diff --git a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs similarity index 64% rename from playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs rename to playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs index 8c60e72e..6eb4f978 100644 --- a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs +++ b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs @@ -1,37 +1,41 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" +import "pkg:/source/utils/CancellationUtils.bs" + +@job("FetchSubscriptionStatusJob") +function ExecuteJob() as void + input = JobGetInput() -@asynctask -function FetchSubscriptionStatusTask(input as object) as object channelView = input.channelView ucid = input.ucid invidiousNode = input.invidious authToken = input.authToken - if m.top.cancel - return invalid + if JobIsCancelled() + JobCancel() + return end if + cancallation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) isInnertubeProfile = authToken.profileNode.type = "youtube" if isInnertubeProfile subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, { - cancellation: m.top.cancellation + cancellation: cancallation accessToken: authToken.token onBehalfOfUser: authToken.activeIdentifyToken }) if subscriptionStatus.error <> invalid - LogError("Failed to fetch subscription status:", subscriptionStatus.error) - return invalid + JobError("Failed to fetch subscription status: " + ToString(subscriptionStatus.error)) + return end if channelView.isSubscribed = subscriptionStatus.isSubscribed else service = new Invidious.InvidiousService(invidiousNode) - subscriptionsRequest = service.GetSubscriptions(m.top.cancellation) + subscriptionsRequest = service.GetSubscriptions(cancallation) if not subscriptionsRequest.IsSuccess() - error = subscriptionsRequest.ErrorMessage() - LogError("Failed to fetch subscriptions:", error) - return invalid + JobError("Failed to fetch subscriptions: " + subscriptionsRequest.ErrorMessage()) + return end if subscriptions = subscriptionsRequest.Json() @@ -44,6 +48,4 @@ function FetchSubscriptionStatusTask(input as object) as object end for channelView.isSubscribed = isSubscribed end if - - return invalid end function diff --git a/playlet-lib/src/components/ChannelView/SubscribeJob.bs b/playlet-lib/src/components/ChannelView/SubscribeJob.bs new file mode 100644 index 00000000..1f8ecb67 --- /dev/null +++ b/playlet-lib/src/components/ChannelView/SubscribeJob.bs @@ -0,0 +1,32 @@ +import "pkg:/components/Services/Invidious/InvidiousService.bs" + +@job("SubscribeJob") +function ExecuteJob() as void + input = JobGetInput() + + channelView = input.channelView + invidiousNode = input.invidious + ucid = input.ucid + subscribe = input.subscribe + + if JobIsCancelled() + JobCancel() + return + end if + + cancallation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) + service = new Invidious.InvidiousService(invidiousNode) + + if subscribe + response = service.Subscribe(ucid, cancallation) + else + response = service.Unsubscribe(ucid, cancallation) + end if + + if not response.IsSuccess() + JobError("Failed to subscribe/unsubscribe to channel: " + response.ErrorMessage()) + return + end if + + channelView.isSubscribed = subscribe +end function diff --git a/playlet-lib/src/components/ChannelView/SubscribeTask.bs b/playlet-lib/src/components/ChannelView/SubscribeTask.bs deleted file mode 100644 index 9ab72d68..00000000 --- a/playlet-lib/src/components/ChannelView/SubscribeTask.bs +++ /dev/null @@ -1,30 +0,0 @@ -import "pkg:/components/Services/Invidious/InvidiousService.bs" - -@asynctask -function SubscribeTask(input as object) as object - channelView = input.channelView - invidiousNode = input.invidious - ucid = input.ucid - subscribe = input.subscribe - - if m.top.cancel - return invalid - end if - - service = new Invidious.InvidiousService(invidiousNode) - - if subscribe - response = service.Subscribe(ucid, m.top.cancellation) - else - response = service.Unsubscribe(ucid, m.top.cancellation) - end if - - if not response.IsSuccess() - error = response.ErrorMessage() - LogError("Failed to subscribe/unsubscribe to channel:", error) - return invalid - end if - - channelView.isSubscribed = subscribe - return invalid -end function diff --git a/playlet-lib/src/components/ContentNode/ChannelContentTask.bs b/playlet-lib/src/components/ContentNode/ChannelContentJob.bs similarity index 61% rename from playlet-lib/src/components/ContentNode/ChannelContentTask.bs rename to playlet-lib/src/components/ContentNode/ChannelContentJob.bs index 0c1c037b..00c7ecfd 100644 --- a/playlet-lib/src/components/ContentNode/ChannelContentTask.bs +++ b/playlet-lib/src/components/ContentNode/ChannelContentJob.bs @@ -1,39 +1,36 @@ import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" -@asynctask -function ChannelContentTask(input as object) as object +@job("ChannelContentJob") +function ExecuteJob() as void + input = JobGetInput() contentNode = input.content invidiousNode = input.invidious - if m.top.cancel + if JobIsCancelled() contentNode.loadState = FeedLoadState.None - return invalid + JobCancel() + return end if service = new Invidious.InvidiousService(invidiousNode) - response = service.GetChannel(contentNode.authorId, m.top.cancellation) + cancallation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true) + response = service.GetChannel(contentNode.authorId, cancallation) - if m.top.cancel + if JobIsCancelled() contentNode.loadState = FeedLoadState.None - return invalid + JobCancel() + return end if metadata = response.Json() if not response.IsSuccess() or metadata = invalid contentNode.loadState = FeedLoadState.Error - return { - success: false - error: response.ErrorMessage() - } + JobError(response.ErrorMessage()) + return end if InvidiousContent.ToChannelContentNode(contentNode, metadata) - contentNode.loadState = FeedLoadState.Loaded - - return { - success: true - } end function diff --git a/playlet-lib/src/components/ContentNode/ChannelContentNode.bs b/playlet-lib/src/components/ContentNode/ChannelContentNode.bs index 84935ae5..8b8c5608 100644 --- a/playlet-lib/src/components/ContentNode/ChannelContentNode.bs +++ b/playlet-lib/src/components/ContentNode/ChannelContentNode.bs @@ -1,50 +1,46 @@ import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/components/JobSystem/Jobs.bs" +import "pkg:/components/JobSystem/JobSystem.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/Locale.bs" import "pkg:/source/utils/Logging.bs" -function LoadChannel(invidiousNode as object) as void +function LoadChannel(invidiousNode as object, jobQueue as object) as void loadState = m.top.loadState if loadState = FeedLoadState.Loading or loadState = FeedLoadState.Loaded or loadState = FeedLoadState.Error return end if - if m.contentTask <> invalid - m.contentTask.cancel = true + if m.channelContentJob <> invalid + m.channelContentJob.cancel = true end if m.top.loadState = FeedLoadState.Loading - m.contentTask = AsyncTask.Start(Tasks.ChannelContentTask, { + + input = { content: m.top invidious: invidiousNode - }, OnChannelContentTaskResult) + } + + callback = JobSystem.CreateCallback(OnChannelContentJobDone) + JobSystem.QueueJob(jobQueue, Jobs.ChannelContentJob, input, callback) + m.channelContentJob = callback end function -function OnChannelContentTaskResult(output as object) as void - m.contentTask = invalid +function OnChannelContentJobDone(event as object) as void + callback = event.getRoSGNode() + JobSystem.UnobserveCallback(callback) + m.channelContentJob = invalid - if output.cancelled + if callback.cancel or callback.success 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) - authorId = output.task.input.content.authorId - message = Tr(Locale.Dialogs.FailedToLoadChannel).Replace("%1", authorId) + `\n${error}` - DialogUtils.ShowDialogEx({ - message: message - title: Tr(Locale.Dialogs.ChannelLoadError) - large: true - }) - end if + message = Tr(Locale.Dialogs.FailedToLoadChannel).Replace("%1", m.top.authorId) + `\n${callback.error}` + DialogUtils.ShowDialogEx({ + message: message + title: Tr(Locale.Dialogs.ChannelLoadError) + large: true + }) end function diff --git a/playlet-lib/src/components/JobSystem/BaseJob.bs b/playlet-lib/src/components/JobSystem/BaseJob.bs new file mode 100644 index 00000000..01acd62d --- /dev/null +++ b/playlet-lib/src/components/JobSystem/BaseJob.bs @@ -0,0 +1,106 @@ +import "pkg:/source/utils/AssertUtils.bs" +import "pkg:/source/utils/ErrorUtils.bs" +import "pkg:/source/utils/Logging.bs" +import "pkg:/source/utils/MessagePortUtils.bs" + +function JobGetInput() as dynamic + if m._input = invalid + m._input = m.top.input + end if + return m._input +end function + +function JobGetCallbackNode() as dynamic + if m._callback = invalid + input = JobGetInput() + if input = invalid + return invalid + end if + m._callback = input._callback + end if + + return m._callback +end function + +function JobSuccess() as void + callbackNode = JobGetCallbackNode() + if callbackNode = invalid + return + end if + callbackNode.success = true + callbackNode.done = true + m.jobStateSet = true +end function + +function JobError(error as dynamic) as void + error = ErrorUtils.Format(error) + LogError(error) + callbackNode = JobGetCallbackNode() + if callbackNode = invalid + return + end if + callbackNode.error = error + callbackNode.success = false + callbackNode.done = true + m.jobStateSet = true +end function + +function JobCancel() as void + callbackNode = JobGetCallbackNode() + if callbackNode = invalid + return + end if + + callbackNode.cancel = true + callbackNode.success = false + callbackNode.done = true + m.jobStateSet = true +end function + +function JobIsCancelled() as boolean + callbackNode = JobGetCallbackNode() + if callbackNode = invalid + return false + end if + + return callbackNode.cancel = true +end function + +function Execute(_unused as dynamic) as void + #if DEBUG + AssertNodeThreadInfo() + #end if + + callback = JobGetCallbackNode() + if callback <> invalid + callback.queueFields(true) + end if + + try + ExecuteJob() + catch error + JobError(error) + end try + if not m.jobStateSet = true + JobSuccess() + end if + + if callback <> invalid + callback.queueFields(false) + end if + + m._input = invalid + m._callback = invalid +end function + +function ExecuteJob() as void + throw "ExecuteJob abstract method must be implemented in derived class" +end function + +function AssertNodeThreadInfo() as void + threadInfo = m.top.threadInfo() + + Assert.AreEqual(threadInfo.currentThread.type, "Task", "threadInfo.currentThread.type must be 'Task' for this job. This is a bug.") + Assert.AreEqual(threadInfo.node.owningThread.id, threadInfo.currentThread.id, "This job must be executed on the same thread that created it. This is a bug.") + Assert.AreEqual(threadInfo.node.willRendezvousFromCurrentThread, "No", "threadInfo.node.willRendezvousFromCurrentThread must be 'No' for this job. This is a bug.") +end function diff --git a/playlet-lib/src/components/JobSystem/BaseJob.xml b/playlet-lib/src/components/JobSystem/BaseJob.xml new file mode 100644 index 00000000..81837410 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/BaseJob.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/JobSystem/JobCallback.xml b/playlet-lib/src/components/JobSystem/JobCallback.xml new file mode 100644 index 00000000..7d1ac136 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobCallback.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/JobSystem/JobQueue.bs b/playlet-lib/src/components/JobSystem/JobQueue.bs new file mode 100644 index 00000000..c4a38f6b --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobQueue.bs @@ -0,0 +1,55 @@ +import "pkg:/source/utils/MessagePortUtils.bs" +import "pkg:/source/utils/Types.bs" + +function Init() + m.jobQueueTaskReady = false + m.jobQueueTask = CreateObject("roSGNode", "JobQueueTask") + m.jobQueueTask.observeFieldScoped("ready", FuncName(OnJobQueueTaskReady)) + m.jobQueueTask.control = "run" + m.top.observeField("shutdown", FuncName(OnShutdown)) + m.top.observeField("request", FuncName(OnRequest)) +end function + +function OnJobQueueTaskReady(event as object) as void + jobQueueTask = event.getRoSGNode() + jobQueueTask.unobserveFieldScoped("ready") + + m.jobQueueTaskReady = true + + pendingRequestEvents = m.pendingRequestEvents + if pendingRequestEvents = invalid + return + end if + + m.pendingRequestEvents = invalid + for each requestEvent in pendingRequestEvents + OnRequest(requestEvent) + end for +end function + +function OnShutdown() as void + m.top.unobserveField("shutdown") + m.top.unobserveField("request") + m.jobQueueTaskReady = false + m.jobQueueTask.unobserveField("ready") + m.jobQueueTask.shutdown = true + m.jobQueueTask = invalid + m.pendingRequestEvents = invalid +end function + +function OnRequest(event as object) as void + if not m.jobQueueTaskReady + if m.pendingRequestEvents = invalid + m.pendingRequestEvents = [] + end if + m.pendingRequestEvents.push(event) + return + end if + + request = event.getData() + if not IsAssociativeArray(request) + return + end if + + m.jobQueueTask.request = request +end function diff --git a/playlet-lib/src/components/JobSystem/JobQueue.xml b/playlet-lib/src/components/JobSystem/JobQueue.xml new file mode 100644 index 00000000..6c5c96f9 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobQueue.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/JobSystem/JobQueueTask.bs b/playlet-lib/src/components/JobSystem/JobQueueTask.bs new file mode 100644 index 00000000..6e5e790f --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobQueueTask.bs @@ -0,0 +1,109 @@ +import "pkg:/source/utils/Logging.bs" +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 = 12 +' Minimum number of JobTasks that will be kept alive +const MIN_JOB_TASK_COUNT = 2 +' Time in milliseconds to wait before scaling down JobTasks +const SCALE_DOWN_THRESHOLD_MS = 10000 + +function Init() + m.top.functionName = "JobQueueTaskLoop" +end function + +function JobQueueTaskLoop() as void + messagePort = CreateObject("roMessagePort") + + m.top.observeField("shutdown", messagePort) + m.top.observeField("request", messagePort) + + m.top.ready = true + + m.busyJobTasks = {} + m.idleJobTasks = [] + + requests = [] + + while true + while requests.count() > 0 + if m.idleJobTasks.Count() > 0 + ScheduleRequest(requests.Shift(), m.idleJobTasks.Pop()) + continue while + end if + + if m.idleJobTasks.Count() + m.busyJobTasks.Count() < MAX_JOB_TASK_COUNT + LogDebug("Creating a new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count()) + jobTask = CreateObject("roSGNode", "JobTask") + jobTaskId = "JobTask-" + StringUtils.RandomId() + jobTask.id = jobTaskId + jobTaskObject = { + id: jobTaskId + node: jobTask + } + m.busyJobTasks[jobTaskId] = jobTaskObject + MessagePortUtils.ObserveFieldScopedExSafe(jobTask, "ready", messagePort) + jobTask.control = "run" + end if + + exit while + end while + + scaleDownThresholdMs = m.idleJobTasks.Count() > MIN_JOB_TASK_COUNT ? SCALE_DOWN_THRESHOLD_MS : 0 + message = wait(scaleDownThresholdMs, messagePort) + if message = invalid + if m.idleJobTasks.Count() > 0 + jobTaskObject = m.idleJobTasks.Pop() + jobTaskObject.node.UnobserveFieldScoped("ready") + jobTaskObject.node.shutdown = true + LogDebug("Scaled down JobTasks. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count()) + end if + continue while + end if + + messageType = Type(message) + if messageType = "roSGNodeEvent" + field = message.GetField() + + if field = "request" + request = message.GetData() + requests.Push(request) + else if field = "ready" and message.GetData() + jobTaskId = message.GetNode() + jobTaskObject = m.busyJobTasks[jobTaskId] + m.busyJobTasks.Delete(jobTaskId) + m.idleJobTasks.Push(jobTaskObject) + else if field = "shutdown" and message.GetData() + Shutdown() + return + end if + end if + end while +end function + +function ScheduleRequest(request as dynamic, jobTaskObject as dynamic) + m.busyJobTasks[jobTaskObject.id] = jobTaskObject + jobTaskObject.node.request = request +end function + +function Shutdown() + m.top.UnobserveFieldScoped("request") + m.top.UnobserveFieldScoped("shutdown") + m.top.request = invalid + m.top.ready = false + + for each jobTaskId in m.busyJobTasks + jobTask = m.busyJobTasks[jobTaskId] + jobTask.node.UnobserveFieldScoped("ready") + jobTask.node.shutdown = true + end for + + for each jobTask in m.idleJobTasks + jobTask.node.UnobserveFieldScoped("ready") + jobTask.node.shutdown = true + end for + + m.busyJobTasks = invalid + m.idleJobTasks = invalid +end function diff --git a/playlet-lib/src/components/JobSystem/JobQueueTask.xml b/playlet-lib/src/components/JobSystem/JobQueueTask.xml new file mode 100644 index 00000000..e5639cd6 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobQueueTask.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/JobSystem/JobSystem.bs b/playlet-lib/src/components/JobSystem/JobSystem.bs new file mode 100644 index 00000000..3bf32c89 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobSystem.bs @@ -0,0 +1,34 @@ +import "pkg:/source/utils/Types.bs" + +namespace JobSystem + + function CreateCallback(func = invalid as dynamic) as object + node = CreateObject("roSGNode", "JobCallback") + node.id = "JobCallback-" + StringUtils.RandomId() + if IsFunction(func) + node.observeFieldScoped("done", FuncName(func), ["success", "cancel", "error"]) + end if + return node + end function + + function UnobserveCallback(callbackNode as object) as void + if callbackNode <> invalid + callbackNode.UnobserveFieldScoped("done") + end if + end function + + function QueueJob(jobQueue as object, jobName as string, input = invalid as dynamic, callbackNode = invalid as dynamic) as void + if callbackNode <> invalid + if input = invalid + input = {} + end if + input._callback = callbackNode + end if + + jobQueue.request = { + "jobName": jobName + "input": input + } + end function + +end namespace diff --git a/playlet-lib/src/components/JobSystem/JobTask.bs b/playlet-lib/src/components/JobSystem/JobTask.bs new file mode 100644 index 00000000..18e8eb20 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobTask.bs @@ -0,0 +1,50 @@ +import "pkg:/source/utils/Logging.bs" +import "pkg:/source/utils/StringUtils.bs" + +function Init() + m.top.functionName = "JobTaskLoop" +end function + +function JobTaskLoop() as void + msgPort = CreateObject("roMessagePort") + + m.top.observeField("shutdown", msgPort) + m.top.observeField("request", msgPort) + + m.top.ready = true + + while true + msg = wait(0, msgPort) + msgType = type(msg) + + if msgType = "roSGNodeEvent" + field = msg.GetField() + if field = "shutdown" and msg.getData() + m.top.request = invalid + return + end if + if field = "request" + request = msg.getData() + ExecuteJobRequest(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 + + LogDebug("Executing job:", request.jobName) + job@.Execute() + job.input = invalid +end function diff --git a/playlet-lib/src/components/JobSystem/JobTask.xml b/playlet-lib/src/components/JobSystem/JobTask.xml new file mode 100644 index 00000000..ae78e661 --- /dev/null +++ b/playlet-lib/src/components/JobSystem/JobTask.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/JobSystem/tests/SimpleTestJob.bs b/playlet-lib/src/components/JobSystem/tests/SimpleTestJob.bs new file mode 100644 index 00000000..6c4913fe --- /dev/null +++ b/playlet-lib/src/components/JobSystem/tests/SimpleTestJob.bs @@ -0,0 +1,39 @@ +import "pkg:/source/utils/CancellationUtils.bs" +import "pkg:/source/utils/Logging.bs" + +@job("SimpleTestJob") +function ExecuteJob() as void + input = JobGetInput() + + if JobIsCancelled() + JobCancel() + LogInfo("Job cancelled before execution") + return + end if + + sleepTimeMs = ValidInt(input.sleep) + if sleepTimeMs > 0 + callback = JobGetCallbackNode() + if callback <> invalid + messagePort = CreateObject("roMessagePort") + cancellation = CancellationUtils.CreateCancellation(callback, "cancel", true) + CancellationUtils.ObserveCancellationScoped(cancellation, messagePort) + message = wait(sleepTimeMs, messagePort) + CancellationUtils.UnobserveCancellationScoped(cancellation) + if CancellationUtils.IsCancellationEvent(cancellation, message) + LogInfo("Job cancelled during execution") + JobCancel() + return + end if + else + sleep(sleepTimeMs) + end if + end if + + if not input.success + JobError("Simulated job error for testing purposes") + return + end if + + LogInfo("Simulated job success for testing purposes") +end function diff --git a/playlet-lib/src/components/Logger/Logger.bs b/playlet-lib/src/components/Logger/Logger.bs index 76258ae2..a6444259 100644 --- a/playlet-lib/src/components/Logger/Logger.bs +++ b/playlet-lib/src/components/Logger/Logger.bs @@ -3,6 +3,11 @@ import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" +const FOLDER = "cachefs:/logs" +const FILENAME = "app_logs.txt" +const FILENAME_PREVIOUS = "app_logs_previous.txt" +const FILENAME_STARTUP = "cachefs:/playlet_startup_logs.txt" + function Init() m.top.functionName = "LoggerLoop" @@ -44,19 +49,17 @@ function LoggerLoop() port = m.port buffer = CreateObject("roByteArray") - logsFile = m.top.folder + "/" + m.top.filename - previousLogsFile = m.top.folder + "/" + m.top.filenamePrevious - filenameStartup = m.top.filenameStartup + logsFile = FOLDER + "/" + FILENAME + previousLogsFile = FOLDER + "/" + FILENAME_PREVIOUS dateTime = CreateObject("roDateTime") - CreateDirectory(m.top.folder) + CreateDirectory(FOLDER) DeleteFile(previousLogsFile) MoveFile(logsFile, previousLogsFile) - startUpLogs = ReadAsciiFile(filenameStartup) + startUpLogs = ReadAsciiFile(FILENAME_STARTUP) if not StringUtils.IsNullOrEmpty(startUpLogs) line = `************* Startup Logs *************\n${startUpLogs}*********** End Startup Logs ***********\n` - ' bs:disable-next-line LINT3012 print line buffer.FromAsciiString(line) buffer.AppendFile(logsFile) @@ -93,9 +96,7 @@ end function function OnLineLog(event as object, dateTime as object, logsFile as string, buffer as object) line = FormatTime(dateTime) + event.getData() - ' bs:disable-next-line LINT3012 print line - buffer.FromAsciiString(line + `\n`) buffer.AppendFile(logsFile) end function @@ -106,9 +107,7 @@ function OnLineSysLog(event as object, dateTime as object, logsFile as string, b return end if line = FormatTime(dateTime) + "[ERROR][SysLog] " + ToString(info) - ' bs:disable-next-line LINT3012 print line - buffer.FromAsciiString(line + `\n`) buffer.AppendFile(logsFile) end function @@ -116,10 +115,7 @@ end function function OnLineLogMonitorMemoryWarning(event as object, dateTime as object, logsFile as string, buffer as object) as void info = event.getInfo() line = FormatTime(dateTime) + "[WARN][AppMonitorMemory] " + ToString(info) - - ' bs:disable-next-line LINT3012 print line - buffer.FromAsciiString(line + `\n`) buffer.AppendFile(logsFile) end function @@ -137,10 +133,7 @@ function OnLineLogDeviceInfoMemoryWarning(event as object, dateTime as object, l m.lastDeviceInfoMemoryLevel = info.generalMemoryLevel line = FormatTime(dateTime) + "[WARN][DeviceInfoMemory] " + ToString(info) - - ' bs:disable-next-line LINT3012 print line - buffer.FromAsciiString(line + `\n`) buffer.AppendFile(logsFile) end function diff --git a/playlet-lib/src/components/Logger/Logger.xml b/playlet-lib/src/components/Logger/Logger.xml index aa8e1529..123ccd0a 100644 --- a/playlet-lib/src/components/Logger/Logger.xml +++ b/playlet-lib/src/components/Logger/Logger.xml @@ -2,9 +2,5 @@ - - - - \ No newline at end of file diff --git a/playlet-lib/src/components/MainScene.transpiled.xml b/playlet-lib/src/components/MainScene.transpiled.xml index e19bc933..22cad120 100644 --- a/playlet-lib/src/components/MainScene.transpiled.xml +++ b/playlet-lib/src/components/MainScene.transpiled.xml @@ -21,6 +21,7 @@