Functional Weave
Code in TypeScript

monitor.check-status@1.0.0

impl/typescript.ts

1,015 bytes · the TypeScript implementation · view raw

import { type CheckStatus } from "./monitor_check_status_types.ts";

/**
 * One status for a target probed from several places. Down needs a quorum,
 * so one location with a broken route cannot page anyone; a down vote below
 * the quorum still counts as degraded, because something is wrong somewhere.
 */
export function aggregateStatus(statuses: readonly CheckStatus[], downQuorum: number): CheckStatus {
  if (statuses.length === 0) throw new RangeError("statuses must not be empty");
  if (!Number.isSafeInteger(downQuorum) || downQuorum < 1 || downQuorum > statuses.length) {
    throw new RangeError(`downQuorum must be 1 to ${statuses.length}, received ${downQuorum}`);
  }
  let down = 0;
  let degraded = 0;
  for (const s of statuses) {
    if (s === "down") down += 1;
    else if (s === "degraded") degraded += 1;
    else if (s !== "up") throw new RangeError(`unknown check status: ${String(s)}`);
  }
  if (down >= downQuorum) return "down";
  return down > 0 || degraded > 0 ? "degraded" : "up";
}