-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue-manager-async.ts
More file actions
235 lines (204 loc) · 6.18 KB
/
queue-manager-async.ts
File metadata and controls
235 lines (204 loc) · 6.18 KB
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
export type QueueManagerOptions = {
parallelism?: number;
};
export type QueueManagerDeadlineOptions = QueueManagerOptions & {
deadline: number;
};
export type WaitForTurnOptions = {
signal: AbortSignal;
};
export type Task<T = unknown> = (options: WaitForTurnOptions) => Promise<T> | T;
function withResolvers<T>(): {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: unknown) => void;
} {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
class Entry<T = unknown> {
fn: Task<T>;
abortController: AbortController;
constructor(fn: Task<T>, abortController: AbortController = new AbortController()) {
this.fn = fn;
this.abortController = abortController;
}
}
const abortError: Error & { isAbortError?: boolean } = new Error('abort');
abortError.isAbortError = true;
export class QueueManager extends EventTarget {
parallelism: number;
runningEntries: Entry<any>[];
queue: Entry<any>[];
constructor({
parallelism = 1,
}: QueueManagerOptions = {}) {
super();
this.parallelism = parallelism;
this.runningEntries = [];
this.queue = [];
}
isIdle(): boolean {
return this.runningEntries.length === 0;
}
next(n: number = 1): boolean {
let i: number;
for (i = 0; i < n; i++) {
const entry = this.runningEntries.shift();
if (entry) {
entry.abortController.abort(abortError);
continue;
}
}
// return whether we were able to abort all the entries
return i === n;
}
async waitForTurn<T>(fn: Task<T>): Promise<T> {
const entry = new Entry<T>(fn);
return await this.#waitForTurnEntry(entry);
}
waitUntilIdle(): Promise<void> {
if (this.isIdle()) {
return Promise.resolve();
}
const { promise, resolve } = withResolvers<void>();
const onIdleChange = (e: Event) => {
const { idle } = (e as MessageEvent<{ idle: boolean }>).data;
if (idle) {
this.removeEventListener('idlechange', onIdleChange);
resolve();
}
};
this.addEventListener('idlechange', onIdleChange);
return promise;
}
async #waitForTurnEntry<T>(entry: Entry<T>): Promise<T> {
if (this.runningEntries.length < this.parallelism) {
this.runningEntries.push(entry as unknown as Entry<any>);
if (this.runningEntries.length === 1) {
this.dispatchEvent(new MessageEvent('idlechange', {
data: {
idle: false,
},
}));
}
let result!: T;
let error: unknown;
try {
const { fn, abortController } = entry;
const { signal } = abortController;
result = await fn({
signal,
});
} catch (err) {
error = err;
}
const index = this.runningEntries.indexOf(entry as unknown as Entry<any>);
if (index !== -1) {
this.runningEntries.splice(index, 1);
}
if (this.queue.length > 0) {
const nextEntry = this.queue.shift();
if (nextEntry) {
// Fire and forget; no need to await
this.#waitForTurnEntry(nextEntry);
}
} else {
if (this.runningEntries.length === 0) {
this.dispatchEvent(new MessageEvent('idlechange', {
data: {
idle: true,
},
}));
}
}
if (error === undefined || error === abortError) {
return result;
} else {
throw error;
}
} else {
const { fn, abortController } = entry;
const { promise, resolve, reject } = withResolvers<T>();
const fn2: Task<T> = async (options) => {
try {
const r = await fn(options);
resolve(r);
return r;
} catch (err) {
reject(err);
throw err;
}
};
const entry2 = new Entry<T>(fn2, abortController);
this.queue.push(entry2 as unknown as Entry<any>);
const result = await promise;
return result;
}
}
}
export class QueueManagerAbortError extends Error {}
export class QueueManagerDeadline extends QueueManager {
deadline: number;
private pendingAfterDeadlineRejects: Array<(reason?: unknown) => void> = [];
private idleAbortListenerAttached = false;
constructor(opts: QueueManagerDeadlineOptions) {
super(opts);
this.deadline = opts.deadline;
}
private ensureIdleAbortListener() {
if (this.idleAbortListenerAttached) return;
this.idleAbortListenerAttached = true;
const onIdleChange = (e: Event) => {
const { idle } = (e as MessageEvent<{ idle: boolean }>).data;
if (idle) {
this.removeEventListener('idlechange', onIdleChange);
this.idleAbortListenerAttached = false;
for (const r of this.pendingAfterDeadlineRejects) {
r(new QueueManagerAbortError('QueueManagerDeadline: deadline passed'));
}
this.pendingAfterDeadlineRejects.length = 0;
}
};
this.addEventListener('idlechange', onIdleChange);
}
async waitForTurn<T>(fn: Task<T>): Promise<T> {
return await super.waitForTurn(async (options) => {
if (Date.now() <= this.deadline) {
return await fn(options);
} else {
this.ensureIdleAbortListener();
const { promise, reject } = withResolvers<T>();
this.pendingAfterDeadlineRejects.push(reject);
return await promise;
}
});
}
}
export class MultiQueueManager {
opts: QueueManagerOptions;
queueManagers: Map<string, QueueManager>;
constructor(opts: QueueManagerOptions = {}) {
this.opts = opts;
this.queueManagers = new Map();
}
async waitForTurn<T>(key: string, fn: Task<T>): Promise<T> {
let queueManager = this.queueManagers.get(key);
if (!queueManager) {
queueManager = new QueueManager(this.opts);
this.queueManagers.set(key, queueManager);
queueManager.addEventListener('idlechange', (e: Event) => {
const { idle } = (e as MessageEvent<{ idle: boolean }>).data;
if (idle) {
this.queueManagers.delete(key);
}
});
}
return await queueManager.waitForTurn(fn);
}
}