Skip to content

Commit

Permalink
fix: notify worker to not send response when main errors out
Browse files Browse the repository at this point in the history
  • Loading branch information
jedlikowski committed Sep 9, 2024
1 parent ad0879f commit 9f59e96
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
AnyAsyncFn,
AnyFn,
GlobalShim,
MainToWorkerAbortMessage,
MainToWorkerMessage,
Syncify,
ValueOf,
Expand Down Expand Up @@ -533,6 +534,8 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(
Atomics.store(sharedBufferView!, 0, 0)

if (!['ok', 'not-equal'].includes(status)) {
const abortMsg: MainToWorkerAbortMessage = { id: expectedId, abort: true }
port.postMessage(abortMsg)
throw new Error('Internal error: Atomics.wait() failed: ' + status)
}

Expand All @@ -542,9 +545,6 @@ function startWorkerThread<R, T extends AnyAsyncFn<R>>(

if (id < expectedId) {
const waitingTime = Date.now() - start
console.log(
`Received old message ${id}, keep waiting for ${expectedId}...`,
)
return receiveMessageWithId(
port,
expectedId,
Expand Down Expand Up @@ -609,12 +609,24 @@ export function runAsWorker<
({ id, args }: MainToWorkerMessage<Parameters<T>>) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
;(async () => {
let isAborted = false
const handleAbortMessage = (msg: MainToWorkerAbortMessage) => {
if (msg.id === id && msg.abort) {
isAborted = true
}
}
workerPort.on('message', handleAbortMessage)
let msg: WorkerToMainMessage<R>
try {
msg = { id, result: await fn(...args) }
} catch (error: unknown) {
msg = { id, error, properties: extractProperties(error) }
}
workerPort.off('message', handleAbortMessage)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (isAborted) {
return
}
workerPort.postMessage(msg)
Atomics.add(sharedBufferView, 0, 1)
Atomics.notify(sharedBufferView, 0)
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export interface MainToWorkerMessage<T extends unknown[]> {
args: T
}

export interface MainToWorkerAbortMessage {
id: number
abort: boolean
}

export interface WorkerData {
sharedBuffer: SharedArrayBuffer
workerPort: MessagePort
Expand Down

0 comments on commit 9f59e96

Please sign in to comment.