Skip to content

Commit

Permalink
feat(troika-worker-utils): add a terminateWorker function
Browse files Browse the repository at this point in the history
This allows terminating the backing Worker for modules registered
with a given workerId.
  • Loading branch information
lojjic committed Sep 16, 2021
1 parent eef5652 commit 33b8455
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 26 additions & 0 deletions packages/troika-worker-utils/src/WorkerModules.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ let _workerModuleId = 0
let _messageId = 0
let _allowInitAsString = false
const workers = Object.create(null)
const registeredModules = Object.create(null) //workerId -> Set<unregisterFn>
const openRequests = /*#__PURE__*/(() => {
const obj = Object.create(null)
obj._count = 0
Expand Down Expand Up @@ -66,6 +67,11 @@ export function defineWorkerModule(options) {
// Register this module if needed
if (!registrationThenable) {
registrationThenable = callWorker(workerId,'registerModule', moduleFunc.workerModuleData)
const unregister = () => {
registrationThenable = null
registeredModules[workerId].delete(unregister)
}
;(registeredModules[workerId] || (registeredModules[workerId] = new Set())).add(unregister)
}

// Invoke the module, returning a thenable
Expand All @@ -88,6 +94,26 @@ export function defineWorkerModule(options) {
return moduleFunc
}

/**
* Terminate an active Worker by a workerId that was passed to defineWorkerModule.
* This only terminates the Worker itself; the worker module will remain available
* and if you call it again its Worker will be respawned.
* @param {string} workerId
*/
export function terminateWorker(workerId) {
// Unregister all modules that were registered in that worker
if (registeredModules[workerId]) {
registeredModules[workerId].forEach(unregister => {
unregister()
})
}
// Terminate the Worker object
if (workers[workerId]) {
workers[workerId].terminate()
delete workers[workerId]
}
}

/**
* Stringifies a function into a form that can be deserialized in the worker
* @param fn
Expand Down
2 changes: 1 addition & 1 deletion packages/troika-worker-utils/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Troika worker utility exports

export {defineWorkerModule, stringifyFunction} from './WorkerModules.js'
export {defineWorkerModule, terminateWorker, stringifyFunction} from './WorkerModules.js'
export {default as Thenable} from './Thenable.js'
export {default as ThenableWorkerModule} from './ThenableWorkerModule.js'

0 comments on commit 33b8455

Please sign in to comment.