1 import type { AbstractPoolWorker
} from
'../abstract-pool-worker'
2 import { AbstractWorkerChoiceStrategy
} from
'./abstract-worker-choice-strategy'
3 import type { RequiredStatistics
} from
'./selection-strategies-types'
6 * Worker virtual task timestamp.
8 type WorkerVirtualTaskTimestamp
= {
14 * Selects the next worker with a fair share scheduling algorithm.
15 * Loosely modeled after the fair queueing algorithm: https://en.wikipedia.org/wiki/Fair_queuing.
17 * @template Worker Type of worker which manages the strategy.
18 * @template Data Type of data sent to the worker. This can only be serializable data.
19 * @template Response Type of response of execution. This can only be serializable data.
21 export class FairShareWorkerChoiceStrategy
<
22 Worker
extends AbstractPoolWorker
,
25 > extends AbstractWorkerChoiceStrategy
<Worker
, Data
, Response
> {
27 public requiredStatistics
: RequiredStatistics
= {
32 * Worker last virtual task execution timestamp.
34 private workerLastVirtualTaskTimestamp
: Map
<
36 WorkerVirtualTaskTimestamp
37 > = new Map
<Worker
, WorkerVirtualTaskTimestamp
>()
40 public choose (): Worker
{
41 this.updateWorkerLastVirtualTaskTimestamp()
42 let minWorkerVirtualTaskEndTimestamp
= Infinity
43 let chosenWorker
!: Worker
44 for (const worker
of this.pool
.workers
) {
45 const workerLastVirtualTaskEndTimestamp
=
46 this.workerLastVirtualTaskTimestamp
.get(worker
)?.end
?? 0
48 workerLastVirtualTaskEndTimestamp
< minWorkerVirtualTaskEndTimestamp
50 minWorkerVirtualTaskEndTimestamp
= workerLastVirtualTaskEndTimestamp
58 * Compute workers last virtual task timestamp.
60 private updateWorkerLastVirtualTaskTimestamp () {
61 for (const worker
of this.pool
.workers
) {
62 const workerVirtualTaskStartTimestamp
= Math.max(
64 this.workerLastVirtualTaskTimestamp
.get(worker
)?.end
?? -Infinity
66 const workerVirtualTaskEndTimestamp
=
67 workerVirtualTaskStartTimestamp
+
68 (this.pool
.getWorkerAverageTasksRunTime(worker
) ?? 0)
69 this.workerLastVirtualTaskTimestamp
.set(worker
, {
70 start
: workerVirtualTaskStartTimestamp
,
71 end
: workerVirtualTaskEndTimestamp