-
Notifications
You must be signed in to change notification settings - Fork 267
/
nodes.ts
383 lines (322 loc) · 11 KB
/
nodes.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
/*
* Copyright (C) 2018-2023 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import type { Task, TaskResultType, ValidResultType } from "../tasks/base.js"
import { GraphError, InternalError, toGardenError } from "../exceptions.js"
import type { GraphResult, GraphResultFromTask } from "./results.js"
import { GraphResults } from "./results.js"
import type { GraphSolver } from "./solver.js"
import chalk from "chalk"
import { metadataForLog } from "./common.js"
import { Profile } from "../util/profiling.js"
export interface InternalNodeTypes {
status: StatusTaskNode
process: ProcessTaskNode
}
export interface NodeTypes extends InternalNodeTypes {
request: RequestTaskNode
}
export type NodeType = keyof NodeTypes
export interface TaskNodeParams<T extends Task> {
solver: GraphSolver
task: T
dependant?: TaskNode
statusOnly: boolean
}
@Profile()
export abstract class TaskNode<T extends Task = Task> {
abstract readonly executionType: NodeType
public readonly type: string
public startedAt?: Date
public readonly task: T
public readonly statusOnly: boolean
protected solver: GraphSolver
protected dependants: { [key: string]: TaskNode }
protected result?: GraphResult<any>
constructor({ solver, task, statusOnly }: TaskNodeParams<T>) {
this.task = task
this.type = task.type
this.solver = solver
this.statusOnly = statusOnly
this.dependants = {}
}
abstract describe(): string
abstract getDependencies(): TaskNode[]
abstract execute(): Promise<TaskResultType<T> | null>
getKey() {
return getNodeKey(this.task, this.executionType)
}
addDependant(node: TaskNode) {
const key = node.getKey()
if (!this.dependants[key]) {
this.dependants[key] = node
}
}
/**
* Returns all dependencies that does not yet have a result, i.e. is not resolved.
*/
getRemainingDependencies(): TaskNode[] {
return this.getDependencies().filter((d) => this.getDependencyResult(d) === undefined)
}
/**
* Get the result for the given dependency node. Returns undefined if result is not yet set.
*/
getDependencyResult<A extends Task>(node: TaskNode<A>): GraphResult<TaskResultType<T>> | undefined {
return node.getResult()
}
/**
* Returns all dependency results.
*/
getDependencyResults(): GraphResults {
const deps = this.getDependencies()
const results = new GraphResults(deps.map((d) => d.task))
for (const dep of deps) {
const result = this.getDependencyResult(dep)
result && results.setResult(dep.task, result)
}
return results
}
isComplete() {
return !!this.result
}
/**
* Completes the node, setting its result and propagating it to each dependant node.
*
* If the node is aborted or an error is set, dependants are aborted.
*
* If the node was already completed, this is a no-op (may e.g. happen if the node has been completed
* but a dependency fails and is aborting dependants).
*/
complete({ startedAt, error, result, aborted, abortedKeys }: CompleteTaskParams): GraphResult<TaskResultType<T>> {
if (this.result) {
return this.result
}
const task = this.task
const dependencyResults = this.getDependencyResults()
const inputVersion = task.getInputVersion()
task.log.silly({
msg: `Completing node ${chalk.underline(this.getKey())}. aborted=${aborted}, error=${
error ? error.message : null
}`,
metadata: metadataForLog(task, error ? "error" : "success", inputVersion),
})
this.result = {
type: task.type,
description: task.getDescription(),
key: task.getKey(),
name: task.getName(),
result,
dependencyResults: dependencyResults.filterForGraphResult(),
aborted,
startedAt,
completedAt: new Date(),
error,
inputVersion,
outputs: result?.outputs,
task,
processed: this.executionType === "process",
success: !error && !aborted,
attached: !!result?.attached,
}
if (aborted || error) {
// We abort every dependant, and complete the corresponding request node for the failed node with an error.
const keys = abortedKeys || new Set<string>([task.getKey()])
for (const d of Object.values(this.dependants)) {
const depKey = d.task.getKey()
let depAborted: boolean
let depError: Error | null
if (depKey === task.getKey() && d.executionType === "request" && error) {
depAborted = false
depError = new GraphNodeError({ resultError: error, node: d })
} else {
depAborted = true
depError = null
if (!keys.has(depKey)) {
d.task.log.info({
msg: `Aborting because upstream dependency failed.`,
metadata: metadataForLog(d.task, "error", inputVersion),
})
keys.add(depKey)
}
}
d.complete({
startedAt,
aborted: depAborted,
result: null,
error: depError,
abortedKeys: keys,
})
}
}
return this.result!
}
/**
* Returns the task result if the task is completed. Returns undefined if result is not available.
*/
getResult() {
return this.result
}
getInputVersion() {
return this.task.getInputVersion()
}
protected getNode<NT extends keyof InternalNodeTypes>(type: NT, task: Task): InternalNodeTypes[NT] {
return this.solver.getNode({ type, task, statusOnly: this.statusOnly })
}
}
export interface TaskRequestParams<T extends Task = Task> extends TaskNodeParams<T> {
batchId: string
statusOnly: boolean
completeHandler: CompleteHandler<TaskResultType<T>>
}
@Profile()
export class RequestTaskNode<TaskType extends Task = Task> extends TaskNode<TaskType> {
// FIXME: this is a bit of a TS oddity, but it does work...
executionType = <NodeType>"request"
public readonly requestedAt: Date
public readonly batchId: string
private completeHandler: CompleteHandler<TaskResultType<TaskType>>
constructor(params: TaskRequestParams<TaskType>) {
super(params)
this.requestedAt = new Date()
this.batchId = params.batchId
this.completeHandler = params.completeHandler
}
describe() {
return this.task.getDescription()
}
override getKey() {
return `${this.task.getBaseKey()}:request:${this.batchId}`
}
getDependencies(): TaskNode[] {
if (this.statusOnly) {
return [this.getNode("status", this.task)]
} else {
return [this.getNode("process", this.task)]
}
}
override complete(params: CompleteTaskParams): GraphResult<TaskResultType<TaskType>> {
const result = super.complete(params)
this.completeHandler(result)
return result
}
// NOT USED
async execute() {
return null
}
}
@Profile()
export class ProcessTaskNode<T extends Task = Task> extends TaskNode<T> {
executionType = <NodeType>"process"
describe() {
return `processing ${this.task.getDescription()}`
}
getDependencies() {
const statusTask = this.getNode("status", this.task)
const statusResult = this.getDependencyResult(statusTask) as GraphResult<any>
if (statusResult === undefined) {
// Status is still missing
return [statusTask]
}
// Either forcing, or status is not ready
const processDeps = this.task.getProcessDependencies({ status: statusResult.result })
return processDeps.map((task) => this.getNode("process", task))
}
async execute() {
this.task.log.silly(`Executing node ${chalk.underline(this.getKey())}`)
const statusTask = this.getNode("status", this.task)
// TODO: make this more type-safe
const statusResult = this.getDependencyResult(statusTask) as GraphResultFromTask<T>
if (statusResult === undefined) {
throw new InternalError({
message: `Attempted to execute ${this.describe()} before resolving status.`,
})
}
const status = statusResult?.result
if (!this.task.force && status?.state === "ready") {
return status
}
const dependencyResults = this.getDependencyResults()
try {
const processResult: TaskResultType<T> = await this.task.process({
status,
dependencyResults,
statusOnly: false,
})
this.task.emit("processed", { result: processResult })
if (processResult.state === "ready") {
const msg = `${this.task.getDescription()} is ready.`
this.statusOnly || this.task.type === "resolve-action" ? this.task.log.debug(msg) : this.task.log.verbose(msg)
}
return processResult
} catch (error) {
this.task.emit("processed", { error: toGardenError(error) })
throw error
}
}
}
@Profile()
export class StatusTaskNode<T extends Task = Task> extends TaskNode<T> {
executionType = <NodeType>"status"
describe() {
return `resolving status for ${this.task.getDescription()}`
}
getDependencies() {
const statusDeps = this.task.getStatusDependencies()
// Note: We need to _process_ the status dependencies
return statusDeps.map((task) => this.getNode("process", task))
}
async execute() {
this.task.log.silly(`Executing node ${chalk.underline(this.getKey())}`)
const dependencyResults = this.getDependencyResults()
try {
const result: TaskResultType<T> = await this.task.getStatus({
statusOnly: this.statusOnly,
dependencyResults,
})
this.task.emit("statusResolved", { result })
if (!this.task.force && result?.state === "ready") {
const msg = `${this.task.getDescription()} status is ready.`
this.statusOnly || this.task.type === "resolve-action" ? this.task.log.debug(msg) : this.task.log.verbose(msg)
}
return result
} catch (error) {
this.task.emit("statusResolved", { error: toGardenError(error) })
throw error
}
}
}
export function getNodeKey(task: Task, type: NodeType) {
return `${task.getKey()}:${type}`
}
export type CompleteHandler<R extends ValidResultType> = (result: GraphResult<R>) => void
export interface CompleteTaskParams {
startedAt: Date | null
error: Error | null
result: ValidResultType | null
aborted: boolean
// Used to track the unique task keys that have been aborted when a dependency fails and we recursively cancel
// its dependants (see `TaskNode#complete`). This helps us log each aborted key only once (since we may need to
// cancel e.g. both a request node and a process node for the same key).
abortedKeys?: Set<string>
}
export interface GraphNodeErrorParams {
resultError: Error
node: TaskNode
}
export class GraphNodeError extends GraphError {
node: TaskNode
constructor({ resultError, node }: GraphNodeErrorParams) {
const message = `${node.describe()} failed: ${resultError}`
const wrappedErrors = [toGardenError(resultError)]
super({
message,
wrappedErrors,
taskType: node.task.type,
})
this.node = node
}
}