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
| // services/workflow/WorkflowEngine.ts
interface WorkflowDefinition {
id: string;
name: string;
version: string;
description: string;
startEvent: string;
states: WorkflowState[];
timeouts?: TimeoutConfig;
}
interface WorkflowState {
id: string;
name: string;
type: 'task' | 'parallel' | 'choice' | 'wait' | 'event' | 'fork' | 'join';
next?: string | string[];
end?: boolean;
inputPath?: string;
outputPath?: string;
resource?: string;
timeout?: number;
retry?: RetryPolicy;
catch?: CatchConfig;
}
interface RetryPolicy {
maxAttempts: number;
backoff: {
type: 'fixed' | 'exponential';
delay: number;
};
}
interface CatchConfig {
errors: string[];
next: string;
}
class WorkflowEngine {
private eventBus: EventBus;
private eventStore: EventStore;
private workflows = new Map<string, WorkflowDefinition>();
private instances = new Map<string, WorkflowInstance>();
// 启动工作流实例
async startWorkflow(workflowId: string, input: any, metadata?: WorkflowMetadata): Promise<string> {
const workflow = this.workflows.get(workflowId);
if (!workflow) {
throw new Error(`Workflow not found: ${workflowId}`);
}
// 创建工作流实例
const instance: WorkflowInstance = {
id: this.generateId(),
workflowId,
version: workflow.version,
currentState: workflow.startEvent,
history: [],
input,
output: {},
status: 'running',
startedAt: Date.now(),
metadata
};
this.instances.set(instance.id, instance);
// 保存实例
await this.eventStore.append(`workflow:${instance.id}`, [{
id: this.generateId(),
type: 'workflow.started',
version: 1,
timestamp: Date.now(),
source: 'workflow-engine',
data: { instanceId: instance.id, workflowId, input }
}]);
// 执行第一个状态
await this.executeState(instance, workflow.startEvent);
return instance.id;
}
// 执行工作流状态
private async executeState(instance: WorkflowInstance, stateId: string): Promise<void> {
const workflow = this.workflows.get(instance.workflowId)!;
const state = workflow.states.find(s => s.id === stateId);
if (!state) {
throw new Error(`State not found: ${stateId}`);
}
try {
let result: StateResult;
switch (state.type) {
case 'task':
result = await this.executeTaskState(instance, state);
break;
case 'parallel':
result = await this.executeParallelState(instance, state);
break;
case 'choice':
result = await this.executeChoiceState(instance, state);
break;
case 'wait':
result = await this.executeWaitState(instance, state);
break;
case 'event':
result = await this.executeEventState(instance, state);
break;
case 'fork':
result = await this.executeForkState(instance, state);
break;
case 'join':
result = await this.executeJoinState(instance, state);
break;
default:
throw new Error(`Unknown state type: ${state.type}`);
}
// 记录历史
instance.history.push({
state: stateId,
result,
timestamp: Date.now()
});
// 更新实例
instance.currentState = state.next || '';
instance.output = { ...instance.output, ...result.output };
// 检查是否结束
if (state.end || !state.next) {
instance.status = 'completed';
instance.completedAt = Date.now();
await this.completeWorkflow(instance);
} else {
// 继续下一个状态
if (Array.isArray(state.next)) {
// 多个下一个状态(并行)
for (const nextState of state.next) {
await this.executeState(instance, nextState);
}
} else {
await this.executeState(instance, state.next);
}
}
} catch (error) {
// 错误处理
await this.handleStateError(instance, state, error);
}
}
// 任务状态执行
private async executeTaskState(instance: WorkflowInstance, state: WorkflowState): Promise<StateResult> {
const taskInput = state.inputPath
? this.extractPath(instance.output, state.inputPath)
: instance.input;
// 执行任务(可能带重试)
const taskOutput = await this.executeWithRetry(state, async () => {
return await this.executeTask(state.resource!, taskInput);
});
return {
output: state.outputPath
? { [state.outputPath]: taskOutput }
: taskOutput
};
}
// 带重试的执行
private async executeWithRetry<T>(state: WorkflowState, fn: () => Promise<T>): Promise<T> {
const retry = state.retry;
if (!retry) {
return await fn();
}
let lastError: Error;
const delay = retry.backoff.type === 'fixed'
? retry.backoff.delay
: retry.backoff.delay * Math.pow(2, 0);
for (let attempt = 0; attempt < retry.maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt < retry.maxAttempts - 1) {
await this.sleep(delay);
}
}
}
throw lastError!;
}
// 并行状态执行
private async executeParallelState(instance: WorkflowInstance, state: WorkflowState): Promise<StateResult> {
const branches = state.next as string[];
const input = state.inputPath
? this.extractPath(instance.output, state.inputPath)
: instance.input;
// 并行执行所有分支
const results = await Promise.all(
branches.map(async (branchId) => {
const branchState = this.getState(instance.workflowId, branchId);
return await this.executeTaskState(instance, branchState);
})
);
// 合并结果
const output = results.reduce((merged, result) => ({
...merged,
...result.output
}), {});
return { output };
}
// 选择状态执行
private async executeChoiceState(instance: WorkflowInstance, state: WorkflowState): Promise<StateResult> {
const input = state.inputPath
? this.extractPath(instance.output, state.inputPath)
: instance.input;
// 评估条件
const choice = this.evaluateChoice(state, input);
return {
output: { chosenPath: choice }
};
}
// 等待状态执行
private async executeWaitState(instance: WorkflowInstance, state: WorkflowState): Promise<StateResult> {
const seconds = state.timeout || 0;
if (seconds > 0) {
await this.sleep(seconds * 1000);
}
return { output: {} };
}
// 事件状态执行
private async executeEventState(instance: WorkflowInstance, state: WorkflowState): Promise<StateResult> {
// 等待特定事件
const eventType = state.resource;
const timeout = state.timeout || 30000;
const event = await this.waitForEvent(eventType, timeout);
return {
output: { event }
};
}
}
|