-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildPipeline.ts
170 lines (150 loc) · 4.42 KB
/
buildPipeline.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
import { PipelineError, PipelineRollbackError } from "error";
import { merge } from "lodash";
import type {
Pipeline,
PipelineInitializer,
PipelineMetadata,
PipelineMiddleware,
PipelineResultValidator,
PipelineStage,
PipelineStageConfiguration,
} from "types";
import { isPipelineStageConfiguration } from "utils";
interface BuildPipelineInput<
A extends object,
C extends object,
R extends object,
> {
name: string;
initializer: PipelineInitializer<C, A>;
stages: (PipelineStage<A, C, R> | PipelineStageConfiguration<A, C, R>)[];
resultsValidator: PipelineResultValidator<R>;
middleware?: PipelineMiddleware<A, C, R>[];
}
/**
* Generic pipeline constructor that takes in configuration information and returns a method to execute the pipeline
*/
export function buildPipeline<
A extends object,
C extends object,
R extends object,
>({
name,
initializer,
stages,
resultsValidator,
middleware: middlewares = [],
}: BuildPipelineInput<A, C, R>): Pipeline<A, R> {
return async (args) => {
const results: Partial<R> = {};
/** A context (or undefined) value used for catching/reporting errors */
let maybeContext: C | undefined = undefined;
const metadata: PipelineMetadata<A> = {
name,
arguments: args,
};
const context = await initializer(args);
/** All stages converted to configurations */
const stageConfigurations: PipelineStageConfiguration<A, C, R>[] =
stages.map((stage) => {
if (isPipelineStageConfiguration(stage)) {
return stage;
}
return {
execute: stage,
name: stage.name,
};
});
const potentiallyProcessedStages = [];
try {
const stageNames: string[] = stageConfigurations.map(
(s, idx) => s.name || `Stage ${idx}`,
);
maybeContext = context;
const reversedMiddleware = [...middlewares].reverse();
const wrapMiddleware = (
middleware: PipelineMiddleware<A, C, R>,
currentStage: string,
next: () => Promise<Partial<R>>,
) => {
return () => {
return middleware({
context,
metadata,
results,
stageNames,
currentStage,
next,
});
};
};
for (const [idx, stage] of stageConfigurations.entries()) {
// initialize next() with the stage itself
let next = () =>
stage.execute(context, metadata) as Promise<Partial<R>>;
// wrap stage with middleware such that the first middleware is the outermost function
for (const middleware of reversedMiddleware) {
// A stage name for the current index is assured to exist given it was built using the same collection we're iterating over now
next = wrapMiddleware(middleware, stageNames[idx]!, next);
}
// Add stage to a stack that can be rolled back if necessary
potentiallyProcessedStages.push(stage);
// invoke middleware-wrapped stage
const stageResults = await next();
// if the stage returns results, merge them onto the results object
if (stageResults) {
merge(results, stageResults);
}
}
if (!resultsValidator(results)) {
throw new Error("Results from pipeline failed validation");
}
return results;
} catch (cause) {
const pipelineError = new PipelineError(
String(cause),
maybeContext,
results,
metadata,
cause,
);
await rollback(
potentiallyProcessedStages,
context,
metadata,
results,
pipelineError,
);
// Throw error after rolling back all stages
throw pipelineError;
}
};
}
/**
* Rollback changes made by stages in reverse order
*/
async function rollback<A extends object, C extends object, R extends object>(
stages: PipelineStageConfiguration<A, C, R>[],
context: C,
metadata: PipelineMetadata<A>,
results: R,
originalPipelineError: PipelineError<A, C, R>,
) {
let stage;
while ((stage = stages.pop()) !== undefined) {
try {
if (stage.rollback) {
await stage.rollback(context, metadata);
}
} catch (rollbackCause) {
throw new PipelineRollbackError(
String(`Rollback failed for stage: ${stage.execute.name}`),
context,
results,
metadata,
originalPipelineError,
rollbackCause,
);
}
}
}