-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
task-orchestrator.ts
455 lines (392 loc) · 12 KB
/
task-orchestrator.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import { Workspaces } from '../config/workspaces';
import { performance } from 'perf_hooks';
import { Hasher } from '../hasher/hasher';
import { ForkedProcessTaskRunner } from './forked-process-task-runner';
import { workspaceRoot } from '../utils/app-root';
import { Cache } from './cache';
import { DefaultTasksRunnerOptions } from './default-tasks-runner';
import { TaskStatus } from './tasks-runner';
import {
calculateReverseDeps,
getExecutorForTask,
getOutputs,
isCacheableTask,
removeTasksFromTaskGraph,
shouldStreamOutput,
} from './utils';
import { Batch, TasksSchedule } from './tasks-schedule';
import { TaskMetadata } from './life-cycle';
import { ProjectGraph } from '../config/project-graph';
import { Task, TaskGraph } from '../config/task-graph';
export class TaskOrchestrator {
private cache = new Cache(this.options);
private workspace = new Workspaces(workspaceRoot);
private forkedProcessTaskRunner = new ForkedProcessTaskRunner(this.options);
private tasksSchedule = new TasksSchedule(
this.hasher,
this.projectGraph,
this.taskGraph,
this.workspace,
this.options
);
// region internal state
private reverseTaskDeps = calculateReverseDeps(this.taskGraph);
private completedTasks: {
[id: string]: TaskStatus;
} = {};
private waitingForTasks: Function[] = [];
private groups = [];
// endregion internal state
constructor(
private readonly hasher: Hasher,
private readonly initiatingProject: string | undefined,
private readonly projectGraph: ProjectGraph,
private readonly taskGraph: TaskGraph,
private readonly options: DefaultTasksRunnerOptions
) {}
async run() {
// initial scheduling
await this.tasksSchedule.scheduleNextTasks();
performance.mark('task-execution-begins');
const threads = [];
// initial seeding of the queue
for (let i = 0; i < this.options.parallel; ++i) {
threads.push(this.executeNextBatchOfTasksUsingTaskSchedule());
}
await Promise.all(threads);
performance.mark('task-execution-ends');
performance.measure(
'command-execution',
'task-execution-begins',
'task-execution-ends'
);
this.cache.removeOldCacheRecords();
return this.completedTasks;
}
private async executeNextBatchOfTasksUsingTaskSchedule() {
// completed all the tasks
if (!this.tasksSchedule.hasTasks()) {
return null;
}
const doNotSkipCache =
this.options.skipNxCache === false ||
this.options.skipNxCache === undefined;
const batch = this.tasksSchedule.nextBatch();
if (batch) {
const groupId = this.closeGroup();
await this.applyFromCacheOrRunBatch(doNotSkipCache, batch, groupId);
this.openGroup(groupId);
return this.executeNextBatchOfTasksUsingTaskSchedule();
}
const task = this.tasksSchedule.nextTask();
if (task) {
const groupId = this.closeGroup();
await this.applyFromCacheOrRunTask(doNotSkipCache, task, groupId);
this.openGroup(groupId);
return this.executeNextBatchOfTasksUsingTaskSchedule();
}
// block until some other task completes, then try again
return new Promise((res) => this.waitingForTasks.push(res)).then(() =>
this.executeNextBatchOfTasksUsingTaskSchedule()
);
}
// region Applying Cache
private async applyCachedResults(tasks: Task[]): Promise<
{
task: Task;
status: 'local-cache' | 'local-cache-kept-existing' | 'remote-cache';
}[]
> {
const cacheableTasks = tasks.filter((t) =>
isCacheableTask(t, this.options)
);
const res = await Promise.all(
cacheableTasks.map((t) => this.applyCachedResult(t))
);
return res.filter((r) => r !== null);
}
private async applyCachedResult(task: Task): Promise<{
task: Task;
status: 'local-cache' | 'local-cache-kept-existing' | 'remote-cache';
}> {
const cachedResult = await this.cache.get(task);
if (!cachedResult || cachedResult.code !== 0) return null;
const outputs = getOutputs(this.projectGraph.nodes, task);
const shouldCopyOutputsFromCache =
!!outputs.length &&
(await this.cache.shouldCopyOutputsFromCache(
{ task, cachedResult },
outputs
));
if (shouldCopyOutputsFromCache) {
await this.cache.copyFilesFromCache(task.hash, cachedResult, outputs);
}
const status = cachedResult.remote
? 'remote-cache'
: shouldCopyOutputsFromCache
? 'local-cache'
: 'local-cache-kept-existing';
this.options.lifeCycle.printTaskTerminalOutput(
task,
status,
cachedResult.terminalOutput
);
return {
task,
status,
};
}
// endregion Applying Cache
// region Batch
private async applyFromCacheOrRunBatch(
doNotSkipCache: boolean,
batch: Batch,
groupId: number
) {
const taskEntries = Object.entries(batch.taskGraph.tasks);
const tasks = taskEntries.map(([, task]) => task);
await this.preRunSteps(tasks, { groupId });
let results: {
task: Task;
status: TaskStatus;
terminalOutput?: string;
}[] = doNotSkipCache ? await this.applyCachedResults(tasks) : [];
// Run tasks that were not cached
if (results.length !== taskEntries.length) {
const unrunTaskGraph = removeTasksFromTaskGraph(
batch.taskGraph,
results.map(({ task }) => task.id)
);
// cache prep
for (const task of Object.values(unrunTaskGraph.tasks)) {
const taskOutputs = getOutputs(this.projectGraph.nodes, task);
await this.cache.removeRecordedOutputsHashes(taskOutputs);
}
const batchResults = await this.runBatch({
executorName: batch.executorName,
taskGraph: unrunTaskGraph,
});
results.push(...batchResults);
}
await this.postRunSteps(results, { groupId });
const tasksCompleted = taskEntries.filter(
([taskId]) => this.completedTasks[taskId]
);
// Batch is still not done, run it again
if (tasksCompleted.length !== taskEntries.length) {
await this.applyFromCacheOrRunBatch(
doNotSkipCache,
{
executorName: batch.executorName,
taskGraph: removeTasksFromTaskGraph(
batch.taskGraph,
tasksCompleted.map(([taskId]) => taskId)
),
},
groupId
);
}
}
private async runBatch(batch: Batch) {
try {
const results = await this.forkedProcessTaskRunner.forkProcessForBatch(
batch
);
const batchResultEntries = Object.entries(results);
return batchResultEntries.map(([taskId, result]) => ({
task: this.taskGraph.tasks[taskId],
status: (result.success ? 'success' : 'failure') as TaskStatus,
terminalOutput: result.terminalOutput,
}));
} catch (e) {
return batch.taskGraph.roots.map((rootTaskId) => ({
task: this.taskGraph.tasks[rootTaskId],
status: 'failure' as TaskStatus,
}));
}
}
// endregion Batch
// region Single Task
private async applyFromCacheOrRunTask(
doNotSkipCache: boolean,
task: Task,
groupId: number
) {
await this.preRunSteps([task], { groupId });
// hash the task here
let results: {
task: Task;
status: TaskStatus;
terminalOutput?: string;
}[] = doNotSkipCache ? await this.applyCachedResults([task]) : [];
// the task wasn't cached
if (results.length === 0) {
// cache prep
const taskOutputs = getOutputs(this.projectGraph.nodes, task);
await this.cache.removeRecordedOutputsHashes(taskOutputs);
const { code, terminalOutput } = await this.runTaskInForkedProcess(task);
results.push({
task,
status: code === 0 ? 'success' : 'failure',
terminalOutput,
});
}
await this.postRunSteps(results, { groupId });
}
private async runTaskInForkedProcess(task: Task) {
try {
// obtain metadata
const temporaryOutputPath = this.cache.temporaryOutputPath(task);
const streamOutput = shouldStreamOutput(
task,
this.initiatingProject,
this.options
);
const pipeOutput = this.pipeOutputCapture(task);
// execution
const { code, terminalOutput } = pipeOutput
? await this.forkedProcessTaskRunner.forkProcessPipeOutputCapture(
task,
{
temporaryOutputPath,
streamOutput,
}
)
: await this.forkedProcessTaskRunner.forkProcessDirectOutputCapture(
task,
{
temporaryOutputPath,
streamOutput,
}
);
return {
code,
terminalOutput,
};
} catch (e) {
return {
code: 1,
};
}
}
// endregion Single Task
// region Lifecycle
private async preRunSteps(tasks: Task[], metadata: TaskMetadata) {
this.options.lifeCycle.startTasks(tasks, metadata);
}
private async postRunSteps(
results: {
task: Task;
status: TaskStatus;
terminalOutput?: string;
}[],
{ groupId }: { groupId: number }
) {
// cache the results
await Promise.all(
results
.filter(
({ status }) =>
status !== 'local-cache' &&
status !== 'local-cache-kept-existing' &&
status !== 'remote-cache' &&
status !== 'skipped'
)
.map((result) => ({
...result,
code:
result.status === 'local-cache' ||
result.status === 'local-cache-kept-existing' ||
result.status === 'remote-cache' ||
result.status === 'success'
? 0
: 1,
outputs: getOutputs(this.projectGraph.nodes, result.task),
}))
.filter(({ task, code }) => this.shouldCacheTaskResult(task, code))
.filter(({ terminalOutput, outputs }) => terminalOutput || outputs)
.map(async ({ task, code, terminalOutput, outputs }) => {
await this.cache.put(task, terminalOutput, outputs, code);
})
);
this.options.lifeCycle.endTasks(
results.map((result) => {
const code =
result.status === 'success' ||
result.status === 'local-cache' ||
result.status === 'local-cache-kept-existing' ||
result.status === 'remote-cache'
? 0
: 1;
return {
task: result.task,
status: result.status,
code,
};
}),
{ groupId }
);
this.complete(
results.map(({ task, status }) => {
return {
taskId: task.id,
status,
};
})
);
await this.tasksSchedule.scheduleNextTasks();
// release blocked threads
this.waitingForTasks.forEach((f) => f(null));
this.waitingForTasks.length = 0;
}
private complete(
taskResults: {
taskId: string;
status: TaskStatus;
}[]
) {
this.tasksSchedule.complete(taskResults.map(({ taskId }) => taskId));
for (const { taskId, status } of taskResults) {
if (this.completedTasks[taskId] === undefined) {
this.completedTasks[taskId] = status;
}
if (status === 'failure' || status === 'skipped') {
this.complete(
this.reverseTaskDeps[taskId].map((depTaskId) => ({
taskId: depTaskId,
status: 'skipped',
}))
);
}
}
}
//endregion Lifecycle
// region utils
private pipeOutputCapture(task: Task) {
try {
return (
getExecutorForTask(task, this.workspace).schema.outputCapture === 'pipe'
);
} catch (e) {
return false;
}
}
private shouldCacheTaskResult(task: Task, code: number) {
return (
isCacheableTask(task, this.options) &&
(process.env.NX_CACHE_FAILURES == 'true' ? true : code === 0)
);
}
private closeGroup() {
for (let i = 0; i < this.options.parallel; i++) {
if (!this.groups[i]) {
this.groups[i] = true;
return i;
}
}
}
private openGroup(id: number) {
this.groups[id] = false;
}
// endregion utils
}