Functional Weave
Code in Python

monitor.alert-mute@1.0.0

impl/typescript.ts

1,568 bytes · the TypeScript implementation · view raw

import { type AlertMute, type MutePolicy } from "./monitor_alert_mute_types.ts";

/**
 * Hold an alert back, as Alertmanager's silences and inhibit rules do: during
 * its component's maintenance if its kind is one maintenance mutes, or while
 * an alert that inhibits it fires on the same component. The whole policy is
 * checked every time, so a mistake in it fails loudly rather than silently
 * never muting. The caller passes `condition && !muted` to monitor.alert-state.
 */
export function muteAlert(kind: string, underMaintenance: boolean, firingKinds: readonly string[], policy: MutePolicy): AlertMute {
  if (kind === "") throw new RangeError("kind must not be empty");
  for (const k of policy.maintenance) {
    if (k === "") throw new RangeError("maintenance kinds must not be empty");
  }
  for (const rule of policy.inhibit) {
    if (rule.source === "") throw new RangeError("inhibition source must not be empty");
    if (rule.target === "") throw new RangeError("inhibition target must not be empty");
    if (rule.source === rule.target) throw new RangeError(`an alert kind cannot inhibit itself: ${rule.source}`);
  }
  if (underMaintenance && policy.maintenance.includes(kind)) return { muted: true, reason: "maintenance", by: null };
  for (const rule of policy.inhibit) {
    // source !== target, so an alert listed among firingKinds never inhibits itself.
    if (rule.target === kind && firingKinds.includes(rule.source)) return { muted: true, reason: "inhibited", by: rule.source };
  }
  return { muted: false, reason: null, by: null };
}