任务
按流水线顺序逐个检查结果,遇到第一个 fail 即停,输出拦截环节、其之前的环节以及处理器是否执行。
契约
- 输入:JSON 对象:{ pipeline: string[], results: { [stage]: “pass” | “fail” } }
- 输出:JSON 对象:{ blockedBy, ranBefore: string[], handlerRan: boolean }
样例
- 输入
{"pipeline":["rate-limit","auth","validate","handler"],"results":{"rate-limit":"pass","auth":"fail","validate":"pass"}}-> 期望{"blockedBy":"auth","ranBefore":["rate-limit"],"handlerRan":false}。鉴权在限流之后失败,因此校验与处理器都不会执行。 - 输入
{"pipeline":["auth","validate","handler"],"results":{"auth":"pass","validate":"pass"}}-> 期望{"blockedBy":null,"ranBefore":["auth","validate"],"handlerRan":true}。所有关卡都通过,处理器被调用。
参考实现
function solve({ pipeline, results }) {
const ranBefore = [];
for (const stage of pipeline) {
if (stage === 'handler') return { blockedBy: null, ranBefore, handlerRan: true };
if (results[stage] === 'fail') return { blockedBy: stage, ranBefore, handlerRan: false };
ranBefore.push(stage);
}
return { blockedBy: null, ranBefore, handlerRan: false };
}
为什么有效
生产后端会在第一个失败的中间件处短路。把流水线当作数据来读,能让顺序可审计,也能防止处理器在未鉴权的请求上运行。
失败关卡之后的环节不得出现在 ranBefore 中;只要有环节拦截,handlerRan 就是 false。