Skip to content

Open-source status page, incident response and uptime monitoring

3.7 KB
Raw Blame
"use client";

import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@openstatus/ui/components/ui/chart";
import { useQuery } from "@tanstack/react-query";
import { endOfDay } from "date-fns";
import {
  Area,
  AreaChart,
  CartesianGrid,
  Label,
  ReferenceLine,
  XAxis,
  YAxis,
} from "recharts";

import {
  type INTERVALS,
  type PERCENTILES,
  type PERIODS,
  mapLatency,
} from "@/data/metrics.client";
import { periodToFromDate } from "@/data/metrics.client";
import { formatAxisTick, formatDateTime } from "@/lib/formatter";
import { useTRPC } from "@/lib/trpc/client";

import { ChartTooltipNumber } from "./chart-tooltip-number";

const chartConfig = {
  latency: {
    label: "Latency",
    color: "var(--success)",
  },
} satisfies ChartConfig;

// TODO: create new pipes for timing phase metrics

export function ChartAreaLatency({
  monitorId,
  degradedAfter,
  period,
  type,
  percentile,
  interval,
  regions,
}: {
  monitorId: string;
  degradedAfter: number | null;
  percentile: (typeof PERCENTILES)[number];
  period: (typeof PERIODS)[number];
  interval: (typeof INTERVALS)[number];
  type: "http" | "tcp" | "dns" | "icmp" | "grpc";
  regions: string[] | undefined;
}) {
  const trpc = useTRPC();
  const fromDate = periodToFromDate(period);
  const toDate = endOfDay(new Date());

  const { data: latency } = useQuery(
    trpc.tinybird.metricsLatency.queryOptions({
      monitorId,
      period,
      type,
      interval,
      regions,
      fromDate: fromDate.toISOString(),
      toDate: toDate.toISOString(),
    }),
  );

  const refinedLatency = latency ? mapLatency(latency, percentile) : [];

  return (
    <ChartContainer config={chartConfig} className="h-[250px] w-full">
      <AreaChart accessibilityLayer data={refinedLatency}>
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey="timestamp"
          tickLine={false}
          axisLine={false}
          tickMargin={8}
          tickFormatter={(value) =>
            formatAxisTick(new Date(value), period, interval)
          }
        />
        <ChartTooltip
          cursor={false}
          content={
            <ChartTooltipContent
              indicator="dot"
              labelFormatter={(_, payload) =>
                formatDateTime(new Date(payload[0]?.payload.timestamp))
              }
              formatter={(value, name) => (
                <ChartTooltipNumber
                  chartConfig={chartConfig}
                  value={value}
                  name={name}
                />
              )}
            />
          }
        />
        <Area
          dataKey="latency"
          type="monotone"
          fill="var(--color-latency)"
          fillOpacity={0.4}
          stroke="var(--color-latency)"
          stackId="a"
        />
        {degradedAfter ? (
          <ReferenceLine
            y={degradedAfter}
            stroke="var(--warning)"
            strokeDasharray="3 3"
          >
            <Label
              value="Degraded"
              position="insideBottomRight"
              fill="var(--warning)"
            />
          </ReferenceLine>
        ) : null}
        <YAxis
          domain={[
            "dataMin",
            // show the degraded line unless it would squash the series below half height
            (dataMax: number) =>
              degradedAfter && degradedAfter <= dataMax * 2
                ? degradedAfter
                : dataMax,
          ]}
          tickLine={false}
          axisLine={false}
          tickMargin={8}
          orientation="right"
          tickFormatter={(value) => `${value}ms`}
        />
        <ChartLegend content={<ChartLegendContent />} />
      </AreaChart>
    </ChartContainer>
  );
}