Skip to content

Open-source status page, incident response and uptime monitoring

10.6 KB
Raw Blame
"use client";

import type { RouterOutputs } from "@openstatus/api";
import { monitorRegions } from "@openstatus/db/src/schema/constants";
import { startOfDay, subDays } from "date-fns";

import type { MetricCard } from "@/components/metric/metric-card";
import { formatMilliseconds } from "@/lib/formatter";

import type { RegionMetric } from "./region-metrics";

export const STATUS = ["success", "error", "degraded"] as const;
export const PERIODS = ["1d", "7d", "14d", "30d", "90d"] as const;
// 14d+ require a paid plan; the dropdown gates them for free workspaces.
export const PAID_PERIODS = ["14d", "30d", "90d"] as const;

// longest window a free workspace may view; paid periods snap back to this.
export const FREE_MAX_PERIOD = "7d" as const;

export type Period = (typeof PERIODS)[number];
export type PaidPeriod = (typeof PAID_PERIODS)[number];

// widen to string[] so any Period can be tested, not just the paid literals
export function isPaidPeriod(period: string): period is PaidPeriod {
  return (PAID_PERIODS as readonly string[]).includes(period);
}
export const REGIONS =
  monitorRegions as unknown as (typeof monitorRegions)[number][];
export const PERCENTILES = ["p50", "p75", "p90", "p95", "p99"] as const;
export const INTERVALS = [5, 15, 30, 60, 120, 240, 480, 1440] as const;
export const TRIGGER = ["api", "cron"] as const;

const PERCENTILE_MAP = {
  p50: "p50Latency",
  p75: "p75Latency",
  p90: "p90Latency",
  p95: "p95Latency",
  p99: "p99Latency",
} as const;

// FIXME: rename pipe return values

export function mapMetrics(metrics: RouterOutputs["tinybird"]["metrics"]) {
  return metrics.data?.map((metric) => {
    return {
      p50: metric.p50Latency,
      p75: metric.p75Latency,
      p90: metric.p90Latency,
      p95: metric.p95Latency,
      p99: metric.p99Latency,
      total: metric.count,
      uptime: (metric.success + metric.degraded) / metric.count,
      degraded: metric.degraded,
      error: metric.error,
      lastTimestamp: metric.lastTimestamp,
    };
  });
}

/** The current row carries a lastTimestamp; the previous one never does. */
/** Only the current-window row carries a lastTimestamp; the previous-window row never does. */
export function hasMetricsData(metrics: RouterOutputs["tinybird"]["metrics"]) {
  return (mapMetrics(metrics) ?? []).some((row) => !!row.lastTimestamp);
}

export const metricsCards = {
  uptime: {
    label: "UPTIME",
    variant: "success",
  },
  degraded: {
    label: "DEGRADED",
    variant: "warning",
  },
  error: {
    label: "FAILING",
    variant: "destructive",
  },
  total: {
    label: "REQUESTS",
    variant: "default",
  },
  lastTimestamp: {
    label: "LAST CHECKED",
    variant: "ghost",
  },
  p50: {
    label: "P50",
    variant: "default",
  },
  p75: {
    label: "P75",
    variant: "default",
  },
  p90: {
    label: "P90",
    variant: "default",
  },
  p95: {
    label: "P95",
    variant: "default",
  },
  p99: {
    label: "P99",
    variant: "default",
  },
} as const satisfies Record<
  keyof ReturnType<typeof mapMetrics>[number],
  {
    label: string;
    variant: React.ComponentProps<typeof MetricCard>["variant"];
  }
>;

export function mapUptime(status: RouterOutputs["tinybird"]["uptime"]) {
  return status.data
    .map((status) => {
      return {
        ...status,
        ok: status.success,
        interval: status.interval.getTime(),
        total: status.success + status.error + status.degraded,
      };
    })
    .reverse();
}

/**
 * Transform Tinybird `metricsRegions` response into RegionMetric[] for UI.
 * Every requested region is returned, with `buckets: 0` when it has no data.
 */
export function mapRegionMetrics(
  timeline: RouterOutputs["tinybird"]["metricsRegions"] | undefined,
  regions: string[],
): RegionMetric[] {
  const map = new Map<string, RegionMetric>(
    [...regions]
      .sort((a, b) => a.localeCompare(b))
      .map((region) => [
        region,
        { region, p50: 0, p75: 0, p90: 0, p95: 0, p99: 0, buckets: 0 },
      ]),
  );

  for (const row of timeline?.data ?? []) {
    const entry = map.get(row.region);
    if (!entry) continue;
    entry.p50 += row.p50Latency ?? 0;
    entry.p75 += row.p75Latency ?? 0;
    entry.p90 += row.p90Latency ?? 0;
    entry.p95 += row.p95Latency ?? 0;
    entry.p99 += row.p99Latency ?? 0;
    entry.buckets++;
  }

  for (const entry of map.values()) {
    const count = entry.buckets || 1;
    entry.p50 = Math.round(entry.p50 / count);
    entry.p75 = Math.round(entry.p75 / count);
    entry.p90 = Math.round(entry.p90 / count);
    entry.p95 = Math.round(entry.p95 / count);
    entry.p99 = Math.round(entry.p99 / count);
  }

  return Array.from(map.values());
}

/**
 * Shared axis end for the regions range plot, rounded up to a readable value.
 * A P99 more than twice the median P99 is an outlier: the axis ignores it
 * instead of squashing every other region to the left, plus 10% headroom for
 * the overflow badge. Every P90 fits. An outlier that still lands under the
 * rounded axis is drawn normally; the cell flags only `p99 > max`.
 */
export function getRegionAxisMax(metrics: RegionMetric[]) {
  const reporting = metrics.filter((m) => m.buckets > 0);
  if (!reporting.length) return 100;
  const p99s = reporting.map((m) => m.p99).sort((a, b) => a - b);
  const mid = p99s.length / 2;
  const median =
    p99s.length % 2 ? p99s[Math.floor(mid)] : (p99s[mid - 1] + p99s[mid]) / 2;
  const fits = p99s.filter((p99) => p99 <= median * 2);
  // headroom on the right keeps the overflow badge clear of the markers
  const value =
    Math.max(...fits, ...reporting.map((m) => m.p90)) *
    (fits.length < p99s.length ? 1.1 : 1);
  if (value <= 0) return 100;
  const step = 10 ** Math.floor(Math.log10(value));
  return Math.ceil(value / step) * step;
}

export function mapGlobalMetrics(
  metrics: RouterOutputs["tinybird"]["globalMetrics"],
) {
  return metrics.data?.map((metric) => {
    return {
      p50: metric.p50Latency,
      p75: metric.p75Latency,
      p90: metric.p90Latency,
      p95: metric.p95Latency,
      p99: metric.p99Latency,
      total: metric.count,
      monitorId: metric.monitorId,
    };
  });
}

export type MonitorListMetric = {
  title: string;
  key: "degraded" | "error" | "active" | "inactive" | "p95";
  value: number | string | undefined;
  variant: React.ComponentProps<typeof MetricCard>["variant"];
};

export const globalCards = [
  "active",
  "degraded",
  "error",
  "inactive",
  "p95",
] as const;

export const metricsGlobalCards: Record<
  (typeof globalCards)[number],
  {
    title: string;
    key: (typeof globalCards)[number];
  }
> = {
  active: {
    title: "Normal",
    key: "active" as const,
  },
  degraded: {
    title: "Degraded",
    key: "degraded" as const,
  },
  error: {
    title: "Failing",
    key: "error" as const,
  },
  inactive: {
    title: "Inactive",
    key: "inactive" as const,
  },
  p95: {
    title: "Slowest P95",
    key: "p95" as const,
  },
};

/**
 * Build the metric cards data that is shown on the monitors list page.
 */
export function getMonitorListMetrics(
  monitors: RouterOutputs["monitor"]["list"] = [],
  data: {
    p95Latency: number;
    monitorId: string;
  }[] = [],
): readonly MonitorListMetric[] {
  const variantMap: Record<
    (typeof globalCards)[number],
    React.ComponentProps<typeof MetricCard>["variant"]
  > = {
    active: "success",
    degraded: "warning",
    error: "destructive",
    inactive: "default",
    p95: "ghost",
  } as const;

  return globalCards.map((key) => {
    let value: number | string | undefined;
    switch (key) {
      case "active":
        value = monitors.filter(
          (m) => m.status === "active" && m.active,
        ).length;
        break;
      case "degraded":
        value = monitors.filter(
          (m) => m.status === "degraded" && m.active,
        ).length;
        break;
      case "error":
        value = monitors.filter((m) => m.status === "error" && m.active).length;
        break;
      case "inactive":
        value = monitors.filter((m) => m.active === false).length;
        break;
      case "p95":
        const p95 = [...data].sort((a, b) => b.p95Latency - a.p95Latency)[0]
          ?.p95Latency;
        value = p95 != null ? formatMilliseconds(p95) : "—";
        break;
    }

    return {
      title: metricsGlobalCards[key].title,
      key,
      // a count of nothing is not a zero
      value: monitors.length === 0 ? "—" : value,
      variant: variantMap[key],
    } as const;
  }) as readonly MonitorListMetric[];
}

export function mapLatency(
  latency: RouterOutputs["tinybird"]["metricsLatency"],
  percentile: (typeof PERCENTILES)[number],
) {
  // pipes disagree on ORDER BY; the chart needs oldest → newest
  return [...(latency.data ?? [])]
    .sort(
      (a, b) =>
        new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
    )
    .map((metric) => ({
      timestamp: metric.timestamp,
      latency: metric[PERCENTILE_MAP[percentile]],
    }));
}

export function mapTimingPhases(
  timingPhases: RouterOutputs["tinybird"]["metricsTimingPhases"],
  percentile: (typeof PERCENTILES)[number],
) {
  return [...(timingPhases.data ?? [])]
    .sort(
      (a, b) =>
        new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
    )
    .map((metric) => {
      return {
        timestamp: metric.timestamp,
        dns: metric[`${percentile}Dns`],
        ttfb: metric[`${percentile}Ttfb`],
        transfer: metric[`${percentile}Transfer`],
        connect: metric[`${percentile}Connect`],
        tls: metric[`${percentile}Tls`],
      };
    });
}

export const periodToInterval = {
  "1d": 60,
  "7d": 240,
  "14d": 480,
  "30d": 1440,
  "90d": 1440,
} satisfies Record<(typeof PERIODS)[number], number>;

const periodToDays = {
  "1d": 1,
  "7d": 7,
  "14d": 14,
  "30d": 30,
  "90d": 90,
} satisfies Record<(typeof PERIODS)[number], number>;

// computed per call so a tab left open past midnight keeps sliding its window
export function periodToFromDate(period: (typeof PERIODS)[number]) {
  return startOfDay(subDays(new Date(), periodToDays[period]));
}

// Minimum selectable resolution (minutes) per period. Long windows floor the
// interval so charts stay readable and queries bounded. Mirrors the server-side
// clamp in `@openstatus/api` tinybird router — keep the two in sync.
export const periodToMinInterval = {
  "1d": 5,
  "7d": 5,
  "14d": 5,
  "30d": 240,
  "90d": 1440,
} satisfies Record<(typeof PERIODS)[number], (typeof INTERVALS)[number]>;

// Coarsest useful resolution per period: a 1d window at 8h/1d buckets is 1–3 points.
export const periodToMaxInterval = {
  "1d": 240,
  "7d": 1440,
  "14d": 1440,
  "30d": 1440,
  "90d": 1440,
} satisfies Record<(typeof PERIODS)[number], (typeof INTERVALS)[number]>;