示例工程 47-crash-recovery

47-crash-recovery/demo-02-crash-history/history.ts

typescript · 2.2 KB

type CrashRow = {
  id: string;
  at: number;
  reason: string;
  exitCode: number;
  recovered: boolean;
  recoveryMs: number;
};

function appendCrash(
  history: CrashRow[],
  row: CrashRow,
  limit = 50,
): CrashRow[] {
  return [row, ...history].slice(0, limit);
}

function shouldEnterSafeMode(
  history: CrashRow[],
  now: number,
  windowMs = 60_000,
  threshold = 3,
): boolean {
  const recent = history.filter((row) => now - row.at < windowMs);
  return recent.length >= threshold;
}

function parseHistory(raw: string): CrashRow[] {
  try {
    const parsed = JSON.parse(raw) as unknown;
    if (!Array.isArray(parsed)) return [];
    return parsed.filter((row): row is CrashRow => {
      if (typeof row !== "object" || row === null) return false;
      const item = row as Partial<CrashRow>;
      return (
        typeof item.id === "string" &&
        typeof item.at === "number" &&
        typeof item.reason === "string" &&
        typeof item.exitCode === "number" &&
        typeof item.recovered === "boolean" &&
        typeof item.recoveryMs === "number"
      );
    });
  } catch {
    return [];
  }
}

const now = 1_800_000_000_000;
const base: CrashRow = {
  id: "a",
  at: now,
  reason: "crashed",
  exitCode: 133,
  recovered: true,
  recoveryMs: 420,
};

const one = appendCrash([], base);
const two = appendCrash(one, { ...base, id: "b", at: now - 1000 });
const four = [
  base,
  { ...base, id: "b" },
  { ...base, id: "c" },
  { ...base, id: "d" },
];
const old = [{ ...base, at: now - 120_000 }];
const parsed = parseHistory(JSON.stringify(two));
const corrupt = parseHistory("{ not json");
const wrongShape = parseHistory(JSON.stringify([{ id: 1 }, null, base]));

const ok =
  one.length === 1 &&
  two[0]?.id === "b" &&
  shouldEnterSafeMode(four, now) &&
  !shouldEnterSafeMode(two, now) &&
  !shouldEnterSafeMode(old, now) &&
  parsed.length === 2 &&
  corrupt.length === 0 &&
  wrongShape.length === 1 &&
  wrongShape[0]?.id === "a";

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    appended: two.length,
    safeMode: shouldEnterSafeMode(four, now),
    oldIgnored: !shouldEnterSafeMode(old, now),
    parsed: parsed.length,
    corrupt: corrupt.length,
    wrongShape: wrongShape.length,
  }),
);