/
Farm.ts
186 lines (153 loc) · 4.68 KB
/
Farm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable local/ban-types-eventually */
import FifoQueue from './FifoQueue';
import {
CHILD_MESSAGE_CALL,
ChildMessage,
FarmOptions,
OnCustomMessage,
OnEnd,
OnStart,
PromiseWithCustomMessage,
QueueChildMessage,
TaskQueue,
WorkerInterface,
} from './types';
export default class Farm {
private readonly _computeWorkerKey: FarmOptions['computeWorkerKey'];
private readonly _workerSchedulingPolicy: NonNullable<
FarmOptions['workerSchedulingPolicy']
>;
private readonly _cacheKeys: Record<string, WorkerInterface> = Object.create(
null,
);
private readonly _locks: Array<boolean> = [];
private _offset = 0;
private readonly _taskQueue: TaskQueue;
constructor(
private _numOfWorkers: number,
private _callback: Function,
options: {
computeWorkerKey?: FarmOptions['computeWorkerKey'];
workerSchedulingPolicy?: FarmOptions['workerSchedulingPolicy'];
taskQueue?: TaskQueue;
} = {},
) {
this._computeWorkerKey = options.computeWorkerKey;
this._workerSchedulingPolicy =
options.workerSchedulingPolicy ?? 'round-robin';
this._taskQueue = options.taskQueue ?? new FifoQueue();
}
doWork(
method: string,
...args: Array<unknown>
): PromiseWithCustomMessage<unknown> {
const customMessageListeners = new Set<OnCustomMessage>();
const addCustomMessageListener = (listener: OnCustomMessage) => {
customMessageListeners.add(listener);
return () => {
customMessageListeners.delete(listener);
};
};
const onCustomMessage: OnCustomMessage = message => {
customMessageListeners.forEach(listener => listener(message));
};
const promise: PromiseWithCustomMessage<unknown> = new Promise(
(resolve, reject) => {
const computeWorkerKey = this._computeWorkerKey;
const request: ChildMessage = [CHILD_MESSAGE_CALL, false, method, args];
let worker: WorkerInterface | null = null;
let hash: string | null = null;
if (computeWorkerKey) {
hash = computeWorkerKey.call(this, method, ...args);
worker = hash == null ? null : this._cacheKeys[hash];
}
const onStart: OnStart = (worker: WorkerInterface) => {
if (hash != null) {
this._cacheKeys[hash] = worker;
}
};
const onEnd: OnEnd = (error: Error | null, result: unknown) => {
customMessageListeners.clear();
if (error) {
reject(error);
} else {
resolve(result);
}
};
const task = {onCustomMessage, onEnd, onStart, request};
if (worker) {
this._taskQueue.enqueue(task, worker.getWorkerId());
this._process(worker.getWorkerId());
} else {
this._push(task);
}
},
);
promise.UNSTABLE_onCustomMessage = addCustomMessageListener;
return promise;
}
private _process(workerId: number): Farm {
if (this._isLocked(workerId)) {
return this;
}
const task = this._taskQueue.dequeue(workerId);
if (!task) {
return this;
}
if (task.request[1]) {
throw new Error('Queue implementation returned processed task');
}
const onEnd = (error: Error | null, result: unknown) => {
task.onEnd(error, result);
this._unlock(workerId);
this._process(workerId);
};
task.request[1] = true;
this._lock(workerId);
this._callback(
workerId,
task.request,
task.onStart,
onEnd,
task.onCustomMessage,
);
return this;
}
private _push(task: QueueChildMessage): Farm {
this._taskQueue.enqueue(task);
const offset = this._getNextWorkerOffset();
for (let i = 0; i < this._numOfWorkers; i++) {
this._process((offset + i) % this._numOfWorkers);
if (task.request[1]) {
break;
}
}
return this;
}
// Typescript ensures that the switch statement is exhaustive.
// Adding an explicit return at the end would disable the exhaustive check void.
// eslint-disable-next-line consistent-return
private _getNextWorkerOffset(): number {
switch (this._workerSchedulingPolicy) {
case 'in-order':
return 0;
case 'round-robin':
return this._offset++;
}
}
private _lock(workerId: number): void {
this._locks[workerId] = true;
}
private _unlock(workerId: number): void {
this._locks[workerId] = false;
}
private _isLocked(workerId: number): boolean {
return this._locks[workerId];
}
}