forked from microsoft/p-graph
/
index.tests.ts
421 lines (340 loc) · 14.6 KB
/
index.tests.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import pGraph from "../index";
import { PGraphNodeMap, PGraphNode, DependencyList } from "../types";
interface MockFunctionDefinition {
/** A friendly name for the function */
name: string;
/** How many ticks this function should take to simulate the duration of the function execution */
duration: number;
/** Priority value to pass to the PGraphNode that is crated */
priority?: number;
}
/** A record of a function start or end event that can be composed to create an ordered log of function calls **/
interface MockFunctionCallRecord {
/** The name of the function */
name: string;
/** Denotes if this is when the function started or ended execution */
state: "start" | "end";
}
class FunctionScheduler {
private currentlyRunningFunctions: { name: string; ticksRemaining: number; resolve: () => void }[] = [];
private tickScheduled: boolean = false;
public callRecords: MockFunctionCallRecord[] = [];
public startExecutingFunction(definition: MockFunctionDefinition): Promise<unknown> {
const { name, duration } = definition;
this.callRecords.push({ name, state: "start" });
const promise = new Promise((resolve) => {
this.currentlyRunningFunctions.push({ name, ticksRemaining: duration, resolve });
});
this.ensureTickScheduled();
return promise;
}
private ensureTickScheduled() {
if (!this.tickScheduled) {
Promise.resolve().then(() => this.tick());
this.tickScheduled = true;
}
}
private tick() {
this.tickScheduled = false;
this.currentlyRunningFunctions.forEach((item) => {
item.ticksRemaining = item.ticksRemaining - 1;
});
const finishedItems = this.currentlyRunningFunctions.filter((item) => item.ticksRemaining === 0);
this.currentlyRunningFunctions = this.currentlyRunningFunctions.filter((item) => item.ticksRemaining !== 0);
if (finishedItems.length > 0) {
finishedItems.forEach((item) => {
item.resolve();
this.callRecords.push({ name: item.name, state: "end" });
});
}
if (this.currentlyRunningFunctions.length > 0) {
this.ensureTickScheduled();
}
}
}
function defineMockNode(definition: MockFunctionDefinition, functionScheduler: FunctionScheduler): [string, PGraphNode] {
return [definition.name, { run: () => functionScheduler.startExecutingFunction(definition), priority: definition.priority }];
}
declare global {
namespace jest {
interface Matchers<R> {
/**
* Enforces that a particular schedule does not schedule secondTaskName until firstTaskName is complete
*/
toHaveScheduleOrdering(firstTaskName: string, secondTaskName: string): R;
/**
* Enforces that a particular schedule does not schedule secondTaskName to start before firstTaskName has started
*/
toHaveStartedBefore(firstTaskName: string, secondTaskName: string): R;
/**
* Enforces that a specific task was executed
*/
toHaveScheduledTask(taskName: string): R;
}
}
}
expect.extend({
toHaveScheduleOrdering(callRecords: MockFunctionCallRecord[], firstTaskName: string, secondTaskName: string) {
const firstIndex = callRecords.findIndex((item) => item.name === firstTaskName && item.state === "end");
const secondIndex = callRecords.findIndex((item) => item.name === secondTaskName && item.state === "start");
const pass = firstIndex !== -1 && secondIndex !== -1 && firstIndex < secondIndex;
return {
message: () => `expected ${secondTaskName} to be scheduled after ${firstTaskName} completed`,
pass,
};
},
toHaveStartedBefore(callRecords: MockFunctionCallRecord[], firstTaskName: string, secondTaskName: string) {
const firstIndex = callRecords.findIndex((item) => item.name === firstTaskName && item.state === "start");
const secondIndex = callRecords.findIndex((item) => item.name === secondTaskName && item.state === "start");
const pass = firstIndex !== -1 && secondIndex !== -1 && firstIndex < secondIndex;
return {
message: () => `expected ${secondTaskName} to be started after ${firstTaskName} has started`,
pass,
};
},
toHaveScheduledTask(callRecords: MockFunctionCallRecord[], taskName: string) {
const startIndex = callRecords.findIndex((item) => item.name === taskName && item.state === "end");
const endIndex = callRecords.findIndex((item) => item.name === taskName && item.state === "start");
const pass = startIndex !== -1 && endIndex !== -1;
return {
message: () => `expected to have scheduled task ${taskName}`,
pass,
};
},
});
const computeMaxConcurrency = (callRecords: MockFunctionCallRecord[]) => {
let currentConcurrency = 0;
let maxConcurrencySoFar = 0;
callRecords.forEach((record) => {
currentConcurrency += record.state === "start" ? 1 : -1;
maxConcurrencySoFar = Math.max(currentConcurrency, maxConcurrencySoFar);
});
return maxConcurrencySoFar;
};
describe("Public API", () => {
it("should accept the dependency graph and execute tasks in order", async () => {
const functionScheduler = new FunctionScheduler();
const nodeMap: PGraphNodeMap = new Map([
defineMockNode({ name: "putOnShirt", duration: 1 }, functionScheduler),
defineMockNode({ name: "putOnShorts", duration: 1 }, functionScheduler),
defineMockNode({ name: "putOnJacket", duration: 1 }, functionScheduler),
defineMockNode({ name: "putOnShoes", duration: 1 }, functionScheduler),
defineMockNode({ name: "tieShoes", duration: 1 }, functionScheduler),
]);
const dependencies: DependencyList = [
["putOnShoes", "tieShoes"],
["putOnShirt", "putOnJacket"],
["putOnShorts", "putOnJacket"],
["putOnShorts", "putOnShoes"],
];
await pGraph(nodeMap, dependencies).run();
const { callRecords } = functionScheduler;
expect(callRecords).toHaveScheduleOrdering("putOnShoes", "tieShoes");
expect(callRecords).toHaveScheduleOrdering("putOnShirt", "putOnJacket");
expect(callRecords).toHaveScheduleOrdering("putOnShorts", "putOnJacket");
expect(callRecords).toHaveScheduleOrdering("putOnShorts", "putOnShoes");
});
it("throws an exception when the dependency graph has a cycle starting from the root", async () => {
const nodeMap: PGraphNodeMap = new Map([
["A", { run: () => Promise.resolve() }],
["B", { run: () => Promise.resolve() }],
["C", { run: () => Promise.resolve() }],
]);
const dependencies: DependencyList = [
["A", "B"],
["B", "C"],
["C", "A"],
];
expect(() => pGraph(nodeMap, dependencies)).toThrow();
});
it("throws an exception when the dependency graph has a cycle", async () => {
// This is almost the same as the last test, except the root node is not a part of the cycle
const nodeMap: PGraphNodeMap = new Map([
["A", { run: () => Promise.resolve() }],
["B", { run: () => Promise.resolve() }],
["C", { run: () => Promise.resolve() }],
["D", { run: () => Promise.resolve() }],
]);
const dependencies: DependencyList = [
["A", "B"],
["B", "C"],
["C", "D"],
["D", "B"],
];
expect(() => pGraph(nodeMap, dependencies)).toThrow();
});
it("resolves an empty dependnecy graph", async () => {
const nodeMap: PGraphNodeMap = new Map();
const dependencies: DependencyList = [];
expect(pGraph(nodeMap, dependencies).run()).resolves.toBeUndefined();
});
it("throws an exception when run is invoked and a task rejects its promise", async () => {
const nodeMap: PGraphNodeMap = new Map([
["A", { run: () => Promise.resolve() }],
["B", { run: () => Promise.resolve() }],
["C", { run: () => Promise.reject("C rejected") }],
]);
// A
// B C
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
];
await expect(pGraph(nodeMap, dependencies).run()).rejects.toEqual("C rejected");
});
it("throws when one of the dependencies references a node not in the node map", async () => {
const nodeMap: PGraphNodeMap = new Map([
["A", { run: () => Promise.resolve() }],
["B", { run: () => Promise.resolve() }],
]);
// A
// B C
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
];
expect(() => pGraph(nodeMap, dependencies)).toThrow();
});
it("should run all dependencies for disconnected graphs", async () => {
const functionScheduler = new FunctionScheduler();
const nodeMap: PGraphNodeMap = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 1 }, functionScheduler),
defineMockNode({ name: "C", duration: 1 }, functionScheduler),
defineMockNode({ name: "D", duration: 1 }, functionScheduler),
]);
// A D
// B C
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
];
await pGraph(nodeMap, dependencies).run();
const { callRecords } = functionScheduler;
expect(callRecords).toHaveScheduledTask("A");
expect(callRecords).toHaveScheduledTask("B");
expect(callRecords).toHaveScheduledTask("C");
expect(callRecords).toHaveScheduledTask("D");
});
it("should be able to run more than one task at a time", async () => {
const functionScheduler = new FunctionScheduler();
const nodeMap: PGraphNodeMap = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 1 }, functionScheduler),
defineMockNode({ name: "C", duration: 1 }, functionScheduler),
]);
// A
// B C
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
];
await pGraph(nodeMap, dependencies).run();
// B and C should run concurrently
expect(computeMaxConcurrency(functionScheduler.callRecords)).toEqual(2);
});
it("should not exceed maximum concurrency", async () => {
const functionScheduler = new FunctionScheduler();
const funcs = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 1 }, functionScheduler),
defineMockNode({ name: "C", duration: 1 }, functionScheduler),
defineMockNode({ name: "D", duration: 1 }, functionScheduler),
defineMockNode({ name: "E", duration: 1 }, functionScheduler),
]);
// A
// B C D E
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
["A", "D"],
["A", "E"],
];
await pGraph(funcs, dependencies).run({ concurrency: 3 });
expect(computeMaxConcurrency(functionScheduler.callRecords)).toBeLessThanOrEqual(3);
});
it("correctly schedules tasks that have more than one dependency", async () => {
const functionScheduler = new FunctionScheduler();
const funcs = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 1 }, functionScheduler),
defineMockNode({ name: "C", duration: 1 }, functionScheduler),
defineMockNode({ name: "D", duration: 1 }, functionScheduler),
defineMockNode({ name: "E", duration: 1 }, functionScheduler),
]);
// All nodes depend on A, D depends on C and B as well
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
["A", "D"],
["A", "E"],
["C", "D"],
["B", "D"],
];
await pGraph(funcs, dependencies).run();
expect(functionScheduler.callRecords).toHaveScheduleOrdering("A", "B");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("A", "C");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("A", "D");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("A", "E");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("B", "D");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("C", "D");
});
it("should schedule high priority tasks and dependencies before lower priority tasks", async () => {
const functionScheduler = new FunctionScheduler();
const funcs = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 1 }, functionScheduler),
defineMockNode({ name: "C", duration: 1 }, functionScheduler),
defineMockNode({ name: "D", duration: 1 }, functionScheduler),
defineMockNode({ name: "E", duration: 1 }, functionScheduler),
defineMockNode({ name: "F", duration: 1, priority: 16 }, functionScheduler),
]);
// A
// B C D
// |E F|
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
["A", "D"],
["C", "E"],
["C", "F"],
];
// Set concurrency to 1 to make it easier to validate execution order
await pGraph(funcs, dependencies).run({ concurrency: 1 });
// A -> C -> F is the critical path, it should be built first
expect(functionScheduler.callRecords).toHaveScheduleOrdering("C", "B");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("C", "D");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("F", "E");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("F", "B");
expect(functionScheduler.callRecords).toHaveScheduleOrdering("F", "D");
});
it("should schedule high priority tasks and dependencies before lower priority tasks when maxConcurrency is greater than 1", async () => {
const functionScheduler = new FunctionScheduler();
const funcs = new Map([
defineMockNode({ name: "A", duration: 1 }, functionScheduler),
defineMockNode({ name: "B", duration: 16, priority: 16 }, functionScheduler),
defineMockNode({ name: "C", duration: 4, priority: 4 }, functionScheduler),
defineMockNode({ name: "D", duration: 4, priority: 4 }, functionScheduler),
defineMockNode({ name: "E", duration: 12, priority: 12 }, functionScheduler),
defineMockNode({ name: "F", duration: 16, priority: 16 }, functionScheduler),
]);
// A
// B C D
// |E F|
const dependencies: DependencyList = [
["A", "B"],
["A", "C"],
["A", "D"],
["C", "E"],
["C", "F"],
];
// Set concurrency to 1 to make it easier to validate execution order
await pGraph(funcs, dependencies).run({ concurrency: 2 });
// A -> C -> F is the critical path, it should be built first
expect(computeMaxConcurrency(functionScheduler.callRecords)).toBeLessThanOrEqual(2);
expect(functionScheduler.callRecords).toHaveStartedBefore("C", "B");
expect(functionScheduler.callRecords).toHaveStartedBefore("C", "D");
expect(functionScheduler.callRecords).toHaveStartedBefore("B", "D");
expect(functionScheduler.callRecords).toHaveStartedBefore("F", "E");
});
});