workerNode.registerOnceWorkerEventHandler(
'error',
(rawWorkerError: unknown) => {
- workerError =
- rawWorkerError instanceof Error
- ? rawWorkerError
- : new Error(
- typeof rawWorkerError === 'string'
- ? rawWorkerError
- : 'Worker failed with a non-Error value',
- { cause: rawWorkerError }
- )
+ if (rawWorkerError instanceof Error) {
+ workerError = rawWorkerError
+ } else {
+ const message =
+ typeof rawWorkerError === 'string'
+ ? rawWorkerError
+ : 'Worker failed with a non-Error value'
+ workerError = new Error(message, { cause: rawWorkerError })
+ }
taskResponses = this.captureTaskResponses(workerNode, taskResponses)
workerNode.info.ready = false
this.emitter?.emit(PoolEvents.error, rawWorkerError)
const workerNodeKey = this.workerNodes.indexOf(workerNode)
for (const [taskId, promiseResponse] of this.promiseResponseMap) {
if (promiseResponse.workerNodeKey === workerNodeKey) {
- ;(workerNodeTasks ??= new Map()).set(taskId, promiseResponse)
+ workerNodeTasks ??= new Map()
+ workerNodeTasks.set(taskId, promiseResponse)
}
}
}
const message = response.message as MessageValue<Response>
if (message.taskId != null) {
this.checkMessageWorkerId(message)
- ;(taskResponses ??= []).push(message)
+ taskResponses ??= []
+ taskResponses.push(message)
} else if (message.taskFunctionOperationStatus != null) {
workerNode.messageChannel.port1.emit('message', message)
}
abortSignal?: AbortSignal
): Error => {
const abortError = abortSignal?.reason as Error | string
- return abortError instanceof Error
- ? abortError
- : typeof abortError === 'string'
- ? new Error(abortError)
- : new Error(`Task '${taskName}' id '${taskId ?? randomUUID()}' aborted`)
+ if (abortError instanceof Error) {
+ return abortError
+ }
+ const message =
+ typeof abortError === 'string'
+ ? abortError
+ : `Task '${taskName}' id '${taskId ?? randomUUID()}' aborted`
+ return new Error(message)
}
private getQueuedTasks (): number {
public abstract readonly name: WorkerChoiceStrategy
/** @inheritDoc */
- public retriesCount: number
+ public retriesCount = 0
/** @inheritDoc */
public readonly strategyPolicy: StrategyPolicy = Object.freeze({
/**
* The next worker node key.
*/
- protected nextWorkerNodeKey: number | undefined
+ protected nextWorkerNodeKey: number | undefined = 0
/**
* The previous worker node key.
*/
- protected previousWorkerNodeKey: number
+ protected previousWorkerNodeKey = 0
/**
* Constructs a worker choice strategy bound to the pool.
protected readonly pool: IPool<Worker, Data, Response>,
protected opts?: WorkerChoiceStrategyOptions
) {
- this.retriesCount = 0
- this.nextWorkerNodeKey = 0
- this.previousWorkerNodeKey = 0
this.choose = this.choose.bind(this)
this.setOptions(this.opts)
}
opts = structuredClone(opts ?? {})
opts.weights = opts.weights ?? getDefaultWeights(pool.info.maxSize)
return {
- ...{
- elu: { median: false },
- runTime: { median: false },
- waitTime: { median: false },
- },
+ elu: { median: false },
+ runTime: { median: false },
+ waitTime: { median: false },
...opts,
}
}
* @returns `true` if the removal is successful, `false` otherwise.
*/
public remove (workerNodeKey: number): boolean {
- return Array.from(
- this.workerChoiceStrategies,
- ([_, workerChoiceStrategy]) => workerChoiceStrategy.remove(workerNodeKey)
- ).every(r => r)
+ let removed = true
+ for (const workerChoiceStrategy of this.workerChoiceStrategies.values()) {
+ if (!workerChoiceStrategy.remove(workerNodeKey)) {
+ removed = false
+ }
+ }
+ return removed
}
/**
* @returns `true` if the update is successful, `false` otherwise.
*/
public update (workerNodeKey: number): boolean {
- return Array.from(
- this.workerChoiceStrategies,
- ([_, workerChoiceStrategy]) => workerChoiceStrategy.update(workerNodeKey)
- ).every(r => r)
+ let updated = true
+ for (const workerChoiceStrategy of this.workerChoiceStrategies.values()) {
+ if (!workerChoiceStrategy.update(workerNodeKey)) {
+ updated = false
+ }
+ }
+ return updated
}
/**
*/
const SELECTION_DEPTH_FACTOR = 2
+/**
+ * Sorts the inclusive range in place using insertion sort.
+ * @param data - Array to sort.
+ * @param left - First index in the range.
+ * @param right - Last index in the range.
+ */
+const sortSmallRange = (
+ data: Float32Array,
+ left: number,
+ right: number
+): void => {
+ for (let i = left + 1; i <= right; i++) {
+ const value = data[i]
+ let j = i - 1
+ while (j >= left && data[j] > value) {
+ data[j + 1] = data[j]
+ --j
+ }
+ data[j + 1] = value
+ }
+}
+
+/**
+ * Moves the median of the first, middle and last values to the right end.
+ * @param data - Array containing the pivot candidates.
+ * @param left - First index in the range.
+ * @param right - Last index in the range.
+ * @returns The pivot value.
+ */
+const movePivotToEnd = (
+ data: Float32Array,
+ left: number,
+ right: number
+): number => {
+ const middle = (left + right) >> 1
+ if (data[middle] < data[left]) swap(data, middle, left)
+ if (data[right] < data[middle]) {
+ swap(data, middle, right)
+ if (data[middle] < data[left]) swap(data, middle, left)
+ }
+ const pivot = data[middle]
+ swap(data, middle, right)
+ return pivot
+}
+
+/**
+ * Moves values below the pivot to the start, excluding the pivot slot.
+ * @param data - Array to partition.
+ * @param left - First index in the range.
+ * @param right - Index of the pivot, excluded from partitioning.
+ * @param pivot - Pivot value.
+ * @returns The first index after the values below the pivot.
+ */
+const partitionBelowPivot = (
+ data: Float32Array,
+ left: number,
+ right: number,
+ pivot: number
+): number => {
+ let lessEnd = left
+ for (let i = left; i < right; i++) {
+ if (data[i] < pivot) {
+ swap(data, i, lessEnd)
+ ++lessEnd
+ }
+ }
+ return lessEnd
+}
+
/**
* Selects the value at rank `k` of `data[0, size)` in place (partial sort).
* Quickselect with median-of-three pivot, insertion cutoff and a depth limit
for (;;) {
const width = right - left + 1
if (width <= SELECTION_INSERTION_CUTOFF) {
- for (let i = left + 1; i <= right; i++) {
- const value = data[i]
- let j = i - 1
- while (j >= left && data[j] > value) {
- data[j + 1] = data[j]
- --j
- }
- data[j + 1] = value
- }
+ sortSmallRange(data, left, right)
return data[k]
}
if (--depthLeft < 0) {
data.subarray(left, right + 1).sort()
return data[k]
}
- // Median-of-three pivot, stashed at the right end.
- const middle = (left + right) >> 1
- if (data[middle] < data[left]) swap(data, middle, left)
- if (data[right] < data[middle]) {
- swap(data, middle, right)
- if (data[middle] < data[left]) swap(data, middle, left)
- }
- const pivot = data[middle]
- swap(data, middle, right)
- let lessEnd = left
- for (let i = left; i < right; i++) {
- if (data[i] < pivot) {
- swap(data, i, lessEnd)
- ++lessEnd
- }
- }
+ const pivot = movePivotToEnd(data, left, right)
+ const lessEnd = partitionBelowPivot(data, left, right, pivot)
let equalEnd = lessEnd
for (let i = lessEnd; i < right; i++) {
if (data[i] === pivot) {
expect(chosenWorkerKey).toBe(1)
})
+ it.each([
+ ['remove', false],
+ ['remove', true],
+ ['update', false],
+ ['update', true],
+ ])(
+ 'Verify that %s() visits every strategy when the first returns %s',
+ (operation, firstResult) => {
+ const context = new WorkerChoiceStrategiesContext(fixedPool, [
+ WorkerChoiceStrategies.LEAST_USED,
+ WorkerChoiceStrategies.ROUND_ROBIN,
+ ])
+ const first = stub(
+ context.workerChoiceStrategies.get(WorkerChoiceStrategies.LEAST_USED),
+ operation
+ ).returns(firstResult)
+ const second = stub(
+ context.workerChoiceStrategies.get(WorkerChoiceStrategies.ROUND_ROBIN),
+ operation
+ ).returns(true)
+ const workerNodeKey = 1
+
+ expect(context[operation](workerNodeKey)).toBe(firstResult)
+ expect(first.calledOnceWithExactly(workerNodeKey)).toBe(true)
+ expect(second.calledOnceWithExactly(workerNodeKey)).toBe(true)
+ expect(first.calledBefore(second)).toBe(true)
+ }
+ )
+
it('Verify that execute() with workerNodeKeys affinity filters worker selection', () => {
const workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext(
fixedPool