(name: string, steps: FlowStep[], ctx: any)
| 21 | } |
| 22 | |
| 23 | export async function executeFlow(name: string, steps: FlowStep[], ctx: any): Promise<FlowResult> { |
| 24 | const completed: { step: string; compensation: ((c: any) => Promise<void>) | null }[] = []; |
| 25 | |
| 26 | for (const step of steps) { |
| 27 | try { |
| 28 | logger.info("flow_step_started", { event: name + "." + step.name }); |
| 29 | await step.action(ctx); |
| 30 | completed.push({ step: step.name, compensation: step.compensation }); |
| 31 | counter("flow.step_completed", { flow: name, step: step.name }); |
| 32 | } catch (e: any) { |
| 33 | logger.error("flow_step_failed", { event: name + "." + step.name, metadata: { error: e.message } }); |
| 34 | counter("flow.step_failed", { flow: name, step: step.name }); |
| 35 | |
| 36 | // Backward compensation in reverse order |
| 37 | const compensated: string[] = []; |
| 38 | for (const c of [...completed].reverse()) { |
| 39 | if (!c.compensation) continue; |
| 40 | try { |
| 41 | await c.compensation(ctx); |
| 42 | compensated.push(c.step); |
| 43 | logger.info("flow_compensated", { event: name + "." + c.step }); |
| 44 | } catch (compErr: any) { |
| 45 | logger.error("flow_compensation_failed", { event: name + "." + c.step, metadata: { error: compErr.message } }); |
| 46 | // Continue with other compensations even if one fails |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return { ok: false, failed_step: step.name, compensated, error: e.message }; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | counter("flow.completed", { flow: name }); |
| 55 | return { ok: true, compensated: [] }; |
| 56 | } |
| 57 | |
| 58 | // Flow: improvement_loop |
| 59 | // ctx must contain: { req, res, auth, client? } for transactional flows |
no test coverage detected