审查生成的库存预留

来自 CAP 定理
Node 24 高级 6分钟 找出 5处问题

审查这段生成的预订故障转移路径,检查其一致性与安全重试能力。

预订库存时不得让库存低于零,必须保持单一写入权威,并允许调用者安全重试未知结果。

JavaScript
async function reserve(actor, itemId, quantity, replicas) {
  if (!actor.canReserve) throw new Error('forbidden');
  const requestId = crypto.randomUUID();
  const reachable = replicas.filter((replica) => replica.isHealthy());
  for (const replica of reachable) {
    try {
      const result = await Promise.race([
        replica.reserve({ itemId, quantity }),
        timeout(100).then(() => ({ ok: false })),
      ]);
      if (result.ok) return { ok: true, requestId };
    } catch {
      continue;
    }
  }
  const cached = replicas[0].cache.get(itemId);
  cached.stock -= quantity;
  replicas[0].cache.set(itemId, cached);
  return { ok: true, requestId, degraded: true };
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误