forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackgroundLoop.ts
More file actions
254 lines (226 loc) · 7.87 KB
/
backgroundLoop.ts
File metadata and controls
254 lines (226 loc) · 7.87 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { createDeferred } from './async';
import { IDisposable } from './resourceLifecycle';
type RequestID = number;
type RunFunc = () => Promise<void>;
type NotifyFunc = () => void;
/**
* This helps avoid running duplicate expensive operations.
*
* The key aspect is that already running or queue requests can be
* re-used instead of creating a duplicate request.
*/
export class BackgroundRequestLooper implements IDisposable {
private readonly opts: {
runDefault: RunFunc;
};
private started = false;
private stopped = false;
private readonly done = createDeferred<void>();
private readonly loopRunning = createDeferred<void>();
private waitUntilReady = createDeferred<void>();
private running: RequestID | undefined;
// For now we don't worry about a max queue size.
private readonly queue: RequestID[] = [];
private readonly requests: Record<RequestID, [RunFunc, Promise<void>, NotifyFunc]> = {};
private lastID: number | undefined;
constructor(
opts: {
runDefault?: RunFunc | null;
} = {},
) {
this.opts = {
runDefault:
opts.runDefault ??
(async () => {
throw Error('no default operation provided');
}),
};
}
public async dispose(): Promise<void> {
if (this.started) {
await this.stop();
}
}
/**
* Start the request execution loop.
*
* Currently it does not support being re-started.
*/
public start(): void {
if (this.stopped) {
throw Error('already stopped');
}
if (this.started) {
return;
}
this.started = true;
this.runLoop().ignoreErrors();
}
/**
* Stop the loop (assuming it was already started.)
*
* @returns - a promise that resolves once the loop has stopped.
*/
public stop(): Promise<void> {
if (this.stopped) {
return this.loopRunning.promise;
}
if (!this.started) {
throw Error('not started yet');
}
this.stopped = true;
this.done.resolve();
// It is conceivable that a separate "waitUntilStopped"
// operation would be useful. If it turned out to be desirable
// then at the point we could add such a method separately.
// It would do nothing more than `await this.loopRunning`.
// Currently there is no need for a separate method since
// returning the promise here is sufficient.
return this.loopRunning.promise;
}
/**
* Return the most recent active request, if any.
*
* If there are no pending requests then this is the currently
* running one (if one is running).
*
* @returns - the ID of the request and its completion promise;
* if there are no active requests then you get `undefined`
*/
public getLastRequest(): [RequestID, Promise<void>] | undefined {
let reqID: RequestID;
if (this.queue.length > 0) {
reqID = this.queue[this.queue.length - 1];
} else if (this.running !== undefined) {
reqID = this.running;
} else {
return undefined;
}
// The req cannot be undefined since every queued ID has a request.
const [, promise] = this.requests[reqID];
if (reqID === undefined) {
// The queue must be empty.
return undefined;
}
return [reqID, promise];
}
/**
* Return the request that is waiting to run next, if any.
*
* The request is the next one that will be run. This implies that
* there is one already running.
*
* @returns - the ID of the request and its completion promise;
* if there are no pending requests then you get `undefined`
*/
public getNextRequest(): [RequestID, Promise<void>] | undefined {
if (this.queue.length === 0) {
return undefined;
}
const reqID = this.queue[0];
// The req cannot be undefined since every queued ID has a request.
const [, promise] = this.requests[reqID]!;
return [reqID, promise];
}
/**
* Request that a function be run.
*
* If one is already running then the new request is added to the
* end of the queue. Otherwise it is run immediately.
*
* @returns - the ID of the new request and its completion promise;
* the promise resolves once the request has completed
*/
public addRequest(run?: RunFunc): [RequestID, Promise<void>] {
const reqID = this.getNextID();
// This is the only method that adds requests to the queue
// and `getNextID()` keeps us from having collisions here.
// So we are guaranteed that there are no matching requests
// in the queue.
const running = createDeferred<void>();
this.requests[reqID] = [
// [RunFunc, "done" promise, NotifyFunc]
run ?? this.opts.runDefault,
running.promise,
() => running.resolve(),
];
this.queue.push(reqID);
if (this.queue.length === 1) {
// `waitUntilReady` will get replaced with a new deferred
// in the loop once the existing one gets used.
// We let the queue clear out before triggering the loop
// again.
this.waitUntilReady.resolve();
}
return [reqID, running.promise];
}
/**
* This is the actual loop where the queue is managed and waiting happens.
*/
private async runLoop(): Promise<void> {
const getWinner = () => {
const promises = [
// These are the competing operations.
// Note that the losers keep running in the background.
this.done.promise.then(() => 0),
this.waitUntilReady.promise.then(() => 1),
];
return Promise.race(promises);
};
let winner = await getWinner();
while (!this.done.completed) {
if (winner === 1) {
this.waitUntilReady = createDeferred<void>();
await this.flush();
} else {
// This should not be reachable.
throw Error(`unsupported winner ${winner}`);
}
winner = await getWinner();
}
this.loopRunning.resolve();
}
/**
* Run all pending requests, in queue order.
*
* Each request's completion promise resolves once that request
* finishes.
*/
private async flush(): Promise<void> {
if (this.running !== undefined) {
// We must be flushing the queue already.
return;
}
// Run every request in the queue.
while (this.queue.length > 0) {
const reqID = this.queue[0];
this.running = reqID;
// We pop the request off the queue here so it doesn't show
// up as both running and pending.
this.queue.shift();
const [run, , notify] = this.requests[reqID];
await run();
// We leave the request until right before `notify()`
// for the sake of any calls to `getLastRequest()`.
delete this.requests[reqID];
notify();
}
this.running = undefined;
}
/**
* Provide the request ID to use next.
*/
private getNextID(): RequestID {
// For now there is no way to queue up a request with
// an ID that did not originate here. So we don't need
// to worry about collisions.
if (this.lastID === undefined) {
this.lastID = 1;
} else {
this.lastID += 1;
}
return this.lastID;
}
}