generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
queue.ts
402 lines (362 loc) · 10 KB
/
queue.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
* Lighter version of
* Heap.ts from https://github.com/ignlg/heap-js/blob/master/src/Heap.ts
* heap-js by @ignlg
*/
export type Comparator<T> = (a: T, b: T) => number;
export type IsEqual<T> = (e: T, o: T) => boolean;
export const toInt = (n: number): number => ~~n;
/**
* Heap
* @type {Class}
*/
export class Heap<T> {
heapArray: Array<T> = [];
_limit = 0;
/**
* Heap instance constructor.
* @param {Function} compare Optional comparison function, defaults to Heap.minComparator<number>
*/
constructor(public compare: Comparator<T>) {}
/*
Static methods
*/
/**
* Gets children indices for given index.
* @param {Number} idx Parent index
* @return {Array(Number)} Array of children indices
*/
static getChildrenIndexOf(idx: number): Array<number> {
return [idx * 2 + 1, idx * 2 + 2];
}
/**
* Gets parent index for given index.
* @param {Number} idx Children index
* @return {Number | undefined} Parent index, -1 if idx is 0
*/
static getParentIndexOf(idx: number): number {
if (idx <= 0) {
return -1;
}
const whichChildren = idx % 2 ? 1 : 2;
return Math.floor((idx - whichChildren) / 2);
}
/*
Instance methods
*/
/**
* Adds an element to the heap. Aliases: `offer`.
* Same as: push(element)
* @param {any} element Element to be added
* @return {Boolean} true
*/
push(element: T): boolean {
this._sortNodeUp(this.heapArray.push(element) - 1);
return true;
}
/**
* Length of the heap.
* @return {Number}
*/
length(): number {
return this.heapArray.length;
}
/**
* Top node. Aliases: `element`.
* Same as: `top(1)[0]`
* @return {any} Top node
*/
peek(): T | undefined {
return this.heapArray[0];
}
/**
* Extract the top node (root). Aliases: `poll`.
* @return {any} Extracted top node, undefined if empty
*/
pop(): T | undefined {
const last = this.heapArray.pop();
if (this.length() > 0 && last !== undefined) {
return this.replace(last);
}
return last;
}
/**
* Pop the current peek value, and add the new item.
* @param {any} element Element to replace peek
* @return {any} Old peek
*/
replace(element: T): T {
const peek = this.heapArray[0];
this.heapArray[0] = element;
this._sortNodeDown(0);
return peek;
}
/**
* Size of the heap
* @return {Number}
*/
size(): number {
return this.length();
}
/**
* Move a node to a new index, switching places
* @param {Number} j First node index
* @param {Number} k Another node index
*/
_moveNode(j: number, k: number): void {
[this.heapArray[j], this.heapArray[k]] = [
this.heapArray[k],
this.heapArray[j],
];
}
/**
* Move a node down the tree (to the leaves) to find a place where the heap is sorted.
* @param {Number} i Index of the node
*/
_sortNodeDown(i: number): void {
let moveIt = i < this.heapArray.length - 1;
const self = this.heapArray[i];
const getPotentialParent = (best: number, j: number) => {
if (
this.heapArray.length > j &&
this.compare(this.heapArray[j], this.heapArray[best]) < 0
) {
best = j;
}
return best;
};
while (moveIt) {
const childrenIdx = Heap.getChildrenIndexOf(i);
const bestChildIndex = childrenIdx.reduce(
getPotentialParent,
childrenIdx[0]
);
const bestChild = this.heapArray[bestChildIndex];
if (
typeof bestChild !== 'undefined' &&
this.compare(self, bestChild) > 0
) {
this._moveNode(i, bestChildIndex);
i = bestChildIndex;
} else {
moveIt = false;
}
}
}
/**
* Move a node up the tree (to the root) to find a place where the heap is sorted.
* @param {Number} i Index of the node
*/
_sortNodeUp(i: number): void {
let moveIt = i > 0;
while (moveIt) {
const pi = Heap.getParentIndexOf(i);
if (pi >= 0 && this.compare(this.heapArray[pi], this.heapArray[i]) > 0) {
this._moveNode(i, pi);
i = pi;
} else {
moveIt = false;
}
}
}
}
// This is the central part of the concept:
// using a Promise<void> as a semaphore
interface Semaphore {
wait: Promise<void>;
signal: () => void;
}
interface JobWaiting<T> {
hash: T;
prio: number;
counter: number;
start: Semaphore;
}
interface JobRunning<T> {
hash: T;
prio: number;
finish: Semaphore;
}
/**
* @type QueueStats {running: number, waiting: number, last: number}
*/
interface QueueStats {
running: number;
waiting: number;
last: number;
}
function prioCompare<T>(a: JobWaiting<T>, b: JobWaiting<T>) {
return a.prio - b.prio || a.counter - b.counter;
}
export class Queue<T = unknown> {
maxConcurrent: number;
minCycle: number;
queueRunning: Map<T, JobRunning<T>>;
queueWaiting: Heap<JobWaiting<T>>;
lastRun: number;
nextTimer: Promise<void> | null;
counter: number;
/**
* @class Queue
*
* Priority queue with rate limiting<br>
* See the medium article:<br>
* https://mmomtchev.medium.com/parallelizing-download-loops-in-js-with-async-await-queue-670420880cd6
* (the code has changed a lot since that article but the basic idea of using Promises as locks remains the same)
*
* @param {number} [maxConcurrent=1] Number of tasks allowed to run simultaneously
* @param {number} [minCycle=0] Minimum number of milliseconds between two consecutive tasks
*/
constructor(maxConcurrent?: number, minCycle?: number) {
this.maxConcurrent = maxConcurrent || 1;
this.minCycle = minCycle || 0;
this.queueRunning = new Map<T, JobRunning<T>>();
this.queueWaiting = new Heap<JobWaiting<T>>(prioCompare);
this.lastRun = 0;
this.nextTimer = null;
this.counter = 0;
}
/**
* @private
*/
tryRun(): void {
while (
this.queueWaiting.size() > 0 &&
this.queueRunning.size < this.maxConcurrent
) {
/* Wait if it is too soon */
if (Date.now() - this.lastRun < this.minCycle) {
if (this.nextTimer === null) {
this.nextTimer = new Promise((resolve) =>
activeWindow.setTimeout(() => {
this.nextTimer = null;
this.tryRun();
resolve();
}, this.minCycle - Date.now() + this.lastRun)
);
}
return;
}
/* Choose the next task to run and unblock its promise */
const next = this.queueWaiting.pop();
if (next !== undefined) {
let finishSignal;
const finishWait = new Promise<void>((resolve) => {
finishSignal = resolve;
});
const finish = { wait: finishWait, signal: finishSignal } as Semaphore;
const nextRunning = {
hash: next.hash,
prio: next.prio,
finish,
} as JobRunning<T>;
if (this.queueRunning.has(next.hash)) {
throw new Error('async-await-queue: duplicate hash ' + next.hash);
}
this.queueRunning.set(next.hash, nextRunning);
this.lastRun = Date.now();
next.start.signal();
}
}
}
/**
* Signal that the task `hash` has finished.<br>
* Frees its slot in the queue
*
* @method end
* @param {any} hash Unique hash identifying the task, Symbol() works very well
*/
end(hash: T): void {
const me = this.queueRunning.get(hash);
if (me === undefined)
throw new Error('async-await-queue: queue desync for ' + hash);
this.queueRunning.delete(hash);
me.finish.signal();
this.tryRun();
}
/**
* Wait for a slot in the queue
*
* @method wait
* @param {any} hash Unique hash identifying the task
* @param {number} [priority=0] Optional priority, -1 is higher priority than 1
* @return {Promise<void>} Resolved when the task is ready to run
*/
async wait(hash: T, priority?: number): Promise<void> {
const prio = priority ?? 0;
/* Are we allowed to run? */
/* This promise will be unlocked from the outside */
/* and it cannot reject */
let signal;
const wait = new Promise<void>((resolve) => {
signal = resolve;
});
/* Us on the queue */
const meWaiting: JobWaiting<T> = {
hash,
prio,
start: { signal, wait },
counter: this.counter++,
};
/* Get in the line */
this.queueWaiting.push(meWaiting);
this.tryRun();
await wait;
this.lastRun = Date.now();
}
/**
* Run a job (equivalent to calling Queue.wait(), fn() and then Queue.end())<br>
* fn can be both synchronous or asynchronous function
*
* @method run
* @param {Function} job The job
* @param {number} [priority=0] Optional priority, -1 is higher priority than 1
* @return {Promise<any>} Resolved when the task has finished with the return value of fn
*/
run<U>(job: () => Promise<U>, priority?: number): Promise<U> {
const prio = priority ?? 0;
const id = Symbol();
return this.wait(id as T, prio)
.then(job)
.finally(() => {
this.end(id as T);
});
}
/**
* Return the number of running and waiting jobs
*
* @method stat
* @return {QueueStats} running, waiting, last
*/
stat(): QueueStats {
return {
running: this.queueRunning.size,
waiting: this.queueWaiting.size(),
last: this.lastRun,
};
}
/**
* Returns a promise that resolves when the queue is empty
* (or there are no more than <maxWaiting> waiting tasks
* if the argument is provided)
*
* @method flush
* @return {Promise<void>}
*/
async flush(maxWaiting?: number): Promise<void> {
while (this.queueRunning.size > 0 || this.queueWaiting.size() > 0) {
const waiting = this.queueWaiting.peek();
if (waiting) {
await waiting.start.wait;
}
if (maxWaiting !== undefined && this.queueWaiting.size() < maxWaiting)
return;
if (this.queueRunning.size > 0) {
const running = this.queueRunning.values().next()
.value as JobRunning<T>;
await running.finish.wait;
}
}
}
}
export const ZQueue = new Queue(1);