-
-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
255 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export { PromiseAgent } from "./promise-agent"; | ||
export { WorkerAgent } from "./worker-agent"; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import { createId as generateOperationId } from "@paralleldrive/cuid2"; | ||
import { Worker, WorkerOptions } from "node:worker_threads"; | ||
import { | ||
MessageFromWorker, | ||
MessageToWorker, | ||
WorkerData, | ||
workerModuleId | ||
} from "./protocol"; | ||
|
||
type PromiseResolver<T> = (value: T) => void; | ||
|
||
type PromiseRejector = (err: Error) => void; | ||
|
||
export class PromiseAgent<TInput, TOutput> { | ||
private readonly worker: Worker; | ||
|
||
private readonly operationPromiseHandlesByCorrelationId = new Map< | ||
string, | ||
[PromiseResolver<TOutput>, PromiseRejector] | ||
>(); | ||
|
||
private workerError?: Error; | ||
|
||
constructor(operationModuleId: string, logToConsole = false) { | ||
const workerData: WorkerData = { | ||
operationModuleId, | ||
logToConsole | ||
}; | ||
|
||
const workerOptions: WorkerOptions = { | ||
workerData | ||
}; | ||
|
||
this.worker = new Worker(workerModuleId, workerOptions) | ||
.on("message", this.handleWorkerMessage.bind(this)) | ||
.on("error", this.handleWorkerError.bind(this)) | ||
.on("messageerror", this.handleWorkerError.bind(this)); | ||
} | ||
|
||
private handleWorkerMessage(message: MessageFromWorker): void { | ||
const correlationId = message.correlationId; | ||
if (!correlationId) { | ||
throw new Error("The message has no correlation id!"); | ||
} | ||
|
||
const promiseHandles = | ||
this.operationPromiseHandlesByCorrelationId.get(correlationId); | ||
|
||
if (!promiseHandles) { | ||
throw new Error(`Unknown correlation id: '${message.correlationId}'`); | ||
} | ||
|
||
this.operationPromiseHandlesByCorrelationId.delete(correlationId); | ||
|
||
const [resolve, reject] = promiseHandles; | ||
|
||
switch (message.type) { | ||
case "operationOutput": | ||
resolve(message.value as TOutput); | ||
return; | ||
|
||
case "error": | ||
reject(new Error(message.formattedError)); | ||
return; | ||
} | ||
} | ||
|
||
private handleWorkerError(err: Error): void { | ||
this.workerError = err; | ||
|
||
for (const [ | ||
, | ||
reject | ||
] of this.operationPromiseHandlesByCorrelationId.values()) { | ||
reject(err); | ||
} | ||
|
||
this.operationPromiseHandlesByCorrelationId.clear(); | ||
} | ||
|
||
runOperation(input: TInput): Promise<TOutput> { | ||
if (this.workerError) { | ||
return Promise.reject(this.workerError); | ||
} | ||
|
||
return new Promise<TOutput>((resolve, reject) => { | ||
const correlationId = generateOperationId(); | ||
|
||
this.operationPromiseHandlesByCorrelationId.set(correlationId, [ | ||
resolve, | ||
reject | ||
]); | ||
|
||
const message: MessageToWorker = { | ||
type: "operationInput", | ||
correlationId, | ||
value: input | ||
}; | ||
this.worker.postMessage(message); | ||
}); | ||
} | ||
|
||
requestExit(): Promise<number> { | ||
if (this.workerError) { | ||
return Promise.resolve(1); | ||
} | ||
|
||
return new Promise<number>(resolve => { | ||
this.worker.on("exit", resolve); | ||
|
||
const message: MessageToWorker = { type: "end" }; | ||
this.worker.postMessage(message); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { join } from "node:path"; | ||
|
||
export const workerModuleId = join(__dirname, "worker"); | ||
|
||
export type WorkerData = { | ||
operationModuleId: string; | ||
logToConsole: boolean; | ||
}; | ||
|
||
export type MessageToWorker = | ||
| { | ||
type: "operationInput"; | ||
correlationId?: string; | ||
value: unknown; | ||
} | ||
| { | ||
type: "end"; | ||
}; | ||
|
||
export type MessageFromWorker = { correlationId?: string } & ( | ||
| { | ||
type: "operationOutput"; | ||
value: unknown; | ||
} | ||
| { | ||
type: "error"; | ||
formattedError: string; | ||
} | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import { Worker, WorkerOptions } from "node:worker_threads"; | ||
import { | ||
MessageFromWorker, | ||
MessageToWorker, | ||
WorkerData, | ||
workerModuleId | ||
} from "./protocol"; | ||
|
||
type GenericCallback = (...args: any[]) => void; | ||
|
||
type WorkerEventSubscriptionMethod = ( | ||
workerEvent: string, | ||
callback: GenericCallback | ||
) => void; | ||
|
||
export class WorkerAgent<TInput, TOutput> { | ||
private readonly worker: Worker; | ||
|
||
constructor(operationModuleId: string, logToConsole = false) { | ||
const workerData: WorkerData = { | ||
operationModuleId, | ||
logToConsole | ||
}; | ||
|
||
const workerOptions: WorkerOptions = { | ||
workerData | ||
}; | ||
|
||
this.worker = new Worker(workerModuleId, workerOptions); | ||
} | ||
|
||
runOperation(input: TInput): void { | ||
const message: MessageToWorker = { | ||
type: "operationInput", | ||
value: input | ||
}; | ||
this.worker.postMessage(message); | ||
} | ||
|
||
requestExit(): void { | ||
const message: MessageToWorker = { type: "end" }; | ||
this.worker.postMessage(message); | ||
} | ||
|
||
on( | ||
event: "result", | ||
callback: (err: Error | null, output: TOutput | null) => void | ||
): this; | ||
on(event: "error", callback: (error: Error) => void): this; | ||
on(event: "exit", callback: (exitCode: number) => void): this; | ||
|
||
on(event: string, callback: GenericCallback): this { | ||
return this.registerEventListener(this.worker.on, event, callback); | ||
} | ||
|
||
once( | ||
event: "result", | ||
callback: (err: Error | null, output: TOutput | null) => void | ||
): this; | ||
once(event: "error", callback: (error: Error) => void): this; | ||
once(event: "exit", callback: (exitCode: number) => void): this; | ||
|
||
once(event: string, callback: GenericCallback): this { | ||
return this.registerEventListener(this.worker.once, event, callback); | ||
} | ||
|
||
private registerEventListener( | ||
workerEventSubscriptionMethod: WorkerEventSubscriptionMethod, | ||
agentEvent: string, | ||
callback: GenericCallback | ||
): this { | ||
switch (agentEvent) { | ||
case "result": | ||
this.registerResultListener(workerEventSubscriptionMethod, callback); | ||
break; | ||
|
||
case "exit": | ||
case "error": | ||
workerEventSubscriptionMethod.call(this.worker, agentEvent, callback); | ||
break; | ||
} | ||
|
||
return this; | ||
} | ||
|
||
private registerResultListener( | ||
workerSubscriptionMethod: WorkerEventSubscriptionMethod, | ||
callback: GenericCallback | ||
): void { | ||
workerSubscriptionMethod.call( | ||
this.worker, | ||
"message", | ||
(message: MessageFromWorker) => { | ||
switch (message.type) { | ||
case "operationOutput": | ||
return callback(null, message.value); | ||
|
||
case "error": | ||
return callback(new Error(message.formattedError), null); | ||
} | ||
} | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters