Functional Weave
Code in TypeScript

monitor.uptime-bars@1.0.0

impl/typescript.ts

1,628 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type Check } from "./monitor_check_status.ts";  ← from monitor.check-status ^1.0.0 · built alongside by fune
import { uptime } from "./monitor_uptime.ts";  ← from monitor.uptime ^1.0.0 · built alongside by fune
import { unixToIso } from "./time_unix_to_iso.ts";  ← from time.unix-to-iso ^1.0.0 · built alongside by fune
import { type BarState, type DayBar } from "./monitor_uptime_bars_types.ts";

const DAY = 86400;

/**
 * The last `days` UTC days ending with today, oldest first, each measured by
 * monitor.uptime. Today's bar ends at `now`, so it never shows the rest of
 * today as unknown.
 */
export function uptimeBars(checks: readonly Check[], now: number, days: number, maxGapSeconds: number): readonly DayBar[] {
  if (!Number.isSafeInteger(now)) throw new RangeError("now must be whole seconds");
  if (!Number.isSafeInteger(days) || days < 1 || days > 366) throw new RangeError(`days must be 1 to 366, received ${days}`);
  // Floored, not truncated: before 1970 today starts on the earlier midnight.
  const todayStart = now - (((now % DAY) + DAY) % DAY);
  const bars: DayBar[] = [];
  for (let i = days - 1; i >= 0; i--) {
    const start = todayStart - i * DAY;
    const end = i === 0 ? now : start + DAY;
    const r = uptime(checks, start, end, maxGapSeconds);
    let state: BarState;
    if (r.uptimeBasisPoints === null) state = "no-data";
    else if (r.downSeconds > 0) state = "outage";
    else if (r.degradedSeconds > 0) state = "degraded";
    else state = "operational";
    bars.push({
      date: unixToIso(start).slice(0, 10),
      uptimeBasisPoints: r.uptimeBasisPoints,
      upSeconds: r.upSeconds,
      degradedSeconds: r.degradedSeconds,
      downSeconds: r.downSeconds,
      unknownSeconds: r.unknownSeconds,
      state,
    });
  }
  return bars;
}