Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
🚀use incidents instead (#658)
Thibault Le Ouayf7b34254497c
diff --git a/apps/server/src/public/status.ts b/apps/server/src/public/status.tsindex 5267ccac8..f4c186097 100644--- a/apps/server/src/public/status.ts+++ b/apps/server/src/public/status.ts@@ -1,8 +1,9 @@import { Hono } from "hono";import { endTime, setMetric, startTime } from "hono/timing";-import { and, db, eq, inArray } from "@openstatus/db";+import { and, db, eq, inArray, isNull } from "@openstatus/db";import {+ incidentTable,monitor,monitorsToPages,monitorsToStatusReport,@@ -10,23 +11,20 @@ import {pagesToStatusReports,statusReport,} from "@openstatus/db/src/schema";-import { getPublicStatus, Tinybird } from "@openstatus/tinybird";import { Redis } from "@openstatus/upstash";-import { env } from "../env";import { notEmpty } from "../utils/not-empty";// TODO: include ratelimiting-const tb = new Tinybird({ token: env.TINY_BIRD_API_KEY });const redis = Redis.fromEnv();enum Status {Operational = "operational",DegradedPerformance = "degraded_performance",- PartialOutage = "partial_outage",- MajorOutage = "major_outage",- UnderMaintenance = "under_maintenance",+ PartialOutage = "partial_outage", // not used+ MajorOutage = "major_outage", // not used+ UnderMaintenance = "under_maintenance", // not usedUnknown = "unknown",Incident = "incident",}@@ -44,64 +42,34 @@ status.get("/:slug", async (c) => {}startTime(c, "database");- const { monitorData, pageStatusReportData, monitorStatusReportData } =- await getStatusPageData(slug);+ const {+ monitorData,+ pageStatusReportData,+ monitorStatusReportData,+ ongoingIncidents,+ } = await getStatusPageData(slug);endTime(c, "database");- const isIncident = [...pageStatusReportData, ...monitorStatusReportData].some(- (data) => {- if (!data.status_report) return false;- return !["monitoring", "resolved"].includes(data.status_report.status);- },- );-- startTime(c, "clickhouse");- const lastMonitorPings = await Promise.allSettled(- monitorData.map(async ({ monitors_to_pages }) => {- return await getPublicStatus(tb)({- monitorId: String(monitors_to_pages.monitorId),- });- }),- );- endTime(c, "clickhouse");-- const data = lastMonitorPings.reduce(- (prev, curr) => {- if (curr.status === "fulfilled") {- const { ok, count } = curr.value.data.reduce(- (p, c) => {- p.ok += c.ok;- p.count += c.count;- return p;- },- { ok: 0, count: 0 },- );- prev.ok += ok;- prev.count += count;- }- return prev;- },- { ok: 0, count: 0 },- );-- const ratio = data.ok / data.count;-- const status: Status = isIncident ? Status.Incident : getStatus(ratio);+ const isStatusReport = [+ ...pageStatusReportData,+ ...monitorStatusReportData,+ ].some((data) => {+ if (!data.status_report) return false;+ return !["monitoring", "resolved"].includes(data.status_report.status);+ });++ function getStatus() {+ if (isStatusReport) return Status.Incident;+ // if (monitorData.length === 0) return Status.Unknown;+ if (ongoingIncidents.length > 0) return Status.DegradedPerformance;+ return Status.Operational;+ }+ const status = getStatus();await redis.set(slug, status, { ex: 60 }); // 1m cache-return c.json({ status });});-function getStatus(ratio: number) {- if (isNaN(ratio)) return Status.Unknown;- if (ratio >= 0.98) return Status.Operational;- if (ratio >= 0.6) return Status.DegradedPerformance;- if (ratio >= 0.3) return Status.PartialOutage;- if (ratio >= 0) return Status.MajorOutage;- return Status.Unknown;-}-async function getStatusPageData(slug: string) {const monitorData = await db.select()@@ -116,8 +84,16 @@ async function getStatusPageData(slug: string) {.all();const monitorIds = monitorData.map((i) => i.monitor?.id).filter(notEmpty);+ if (monitorIds.length === 0) {+ return {+ monitorData,+ pageStatusReportData: [],+ monitorStatusReportData: [],+ ongoingIncidents: [],+ };+ }- const monitorStatusReportData = await db+ const monitorStatusReportQuery = db.select().from(monitorsToStatusReport).leftJoin(@@ -128,7 +104,7 @@ async function getStatusPageData(slug: string) {.all();// REMINDER: the query can overlap with the previous one- const pageStatusReportData = await db+ const pageStatusReportDataQuery = db.select().from(pagesToStatusReports).leftJoin(@@ -139,9 +115,28 @@ async function getStatusPageData(slug: string) {.where(eq(page.slug, slug)).all();+ const ongoingIncidentsQuery = db+ .select()+ .from(incidentTable)+ .where(+ and(+ isNull(incidentTable.resolvedAt),+ inArray(incidentTable.monitorId, monitorIds),+ ),+ )+ .all();++ const [monitorStatusReportData, pageStatusReportData, ongoingIncidents] =+ await Promise.all([+ monitorStatusReportQuery,+ pageStatusReportDataQuery,+ ongoingIncidentsQuery,+ ]);+return {monitorData,pageStatusReportData,monitorStatusReportData,+ ongoingIncidents,};}diff --git a/apps/web/src/app/api/og/_components/status-check.tsx b/apps/web/src/app/api/og/_components/status-check.tsxindex 628c3b211..a8786659d 100644--- a/apps/web/src/app/api/og/_components/status-check.tsx+++ b/apps/web/src/app/api/og/_components/status-check.tsx@@ -1,28 +1,24 @@import type { StatusVariant } from "@/lib/tracker";import { cn } from "@/lib/utils";-export function StatusCheck({- variant,-}: {- variant: StatusVariant | "incident";-}) {+export function StatusCheck({ variant }: { variant: StatusVariant }) {function getVariant() {switch (variant) {case "down":return {- color: "bg-red-500",+ color: "bg-rose-500",label: "Major Outage",icon: Minus,};case "degraded":return {- color: "bg-yellow-500",+ color: "bg-amber-500",label: "Systems Degraded",icon: Minus,};case "incident":return {- color: "bg-yellow-500",+ color: "bg-amber-500",label: "Incident Ongoing",icon: Alert,};diff --git a/apps/web/src/app/api/og/_components/tracker.tsx b/apps/web/src/app/api/og/_components/tracker.tsxindex ef163e8ac..366e58777 100644--- a/apps/web/src/app/api/og/_components/tracker.tsx+++ b/apps/web/src/app/api/og/_components/tracker.tsx@@ -2,7 +2,7 @@ import type { Monitor } from "@openstatus/tinybird";import {addBlackListInfo,- getStatus,+ getStatusByRatio,getTotalUptimeString,} from "@/lib/tracker";import { cn, formatDate } from "@/lib/utils";@@ -25,7 +25,7 @@ export function Tracker({ data }: { data: Monitor[] }) {})}<div tw="flex flex-row-reverse absolute left-0">{_data.map((item, i) => {- const { variant } = getStatus(item.ok / item.count);+ const { variant } = getStatusByRatio(item.ok / item.count);const isBlackListed = Boolean(item.blacklist);if (isBlackListed) {return (@@ -38,7 +38,7 @@ export function Tracker({ data }: { data: Monitor[] }) {tw={cn("h-16 w-3 rounded-full mr-1", {"bg-green-500": variant === "up","bg-red-500": variant === "down",- "bg-yellow-500": variant === "degraded",+ "bg-amber-500": variant === "degraded",})}/>);diff --git a/apps/web/src/app/api/og/checker/route.tsx b/apps/web/src/app/api/og/checker/route.tsxindex bedbfb21b..c134baf8f 100644--- a/apps/web/src/app/api/og/checker/route.tsx+++ b/apps/web/src/app/api/og/checker/route.tsx@@ -49,7 +49,7 @@ export async function GET(req: Request) {if (blue) return "border-blue-300 bg-blue-50 text-blue-700";const red =String(statusCode).startsWith("4") || String(statusCode).startsWith("5");- if (red) return "border-red-300 bg-red-50 text-red-700";+ if (red) return "border-rose-300 bg-rose-50 text-rose-700";return "border-gray-300 bg-gray-50 text-gray-700";}diff --git a/apps/web/src/app/api/og/page/route.tsx b/apps/web/src/app/api/og/page/route.tsxindex 48c234559..1df4c8d48 100644--- a/apps/web/src/app/api/og/page/route.tsx+++ b/apps/web/src/app/api/og/page/route.tsx@@ -1,9 +1,7 @@import { ImageResponse } from "next/og";import { DESCRIPTION, TITLE } from "@/app/shared-metadata";-import { getResponseListData } from "@/lib/tb";-import { calcStatus } from "@/lib/tracker";-import { notEmpty } from "@/lib/utils";+import { getStatusByRatio, incidentStatus } from "@/lib/tracker";import { api } from "@/trpc/server";import { BasicLayout } from "../_components/basic-layout";import { StatusCheck } from "../_components/status-check";@@ -25,27 +23,22 @@ export async function GET(req: Request) {const title = page ? page.title : TITLE;const description = page ? "" : DESCRIPTION;- const isIncident = page?.statusReports.some(+ const isStatusReport = page?.statusReports.some((incident) => !["monitoring", "resolved"].includes(incident.status),);- const monitorsData = (- await Promise.all(- page?.monitors.map((monitor) => {- return getResponseListData({- monitorId: String(monitor.id),- limit: 10,- });- }) || [],- )- ).filter(notEmpty);+ const isIncident = page?.incidents.some(+ (incident) => incident.resolvedAt === null,+ );- const status = calcStatus(monitorsData);+ const status = isStatusReport+ ? incidentStatus+ : getStatusByRatio(isIncident ? 0.5 : 1);return new ImageResponse((<BasicLayout title={title} description={description} tw="py-24 px-24">- <StatusCheck variant={isIncident ? "incident" : status.variant} />+ <StatusCheck variant={status.variant} /></BasicLayout>),{diff --git a/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx b/apps/web/src/app/play/checker/[id]/_components/status-badge.tsxindex ad57ba90d..a9e6be43c 100644--- a/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx+++ b/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";export function StatusBadge({ statusCode }: { statusCode: number }) {const green = String(statusCode).startsWith("2");const blue = String(statusCode).startsWith("3");- const red =+ const rose =String(statusCode).startsWith("4") || String(statusCode).startsWith("5");return (<Badge@@ -15,7 +15,8 @@ export function StatusBadge({ statusCode }: { statusCode: number }) {green,"border-blue-500/20 bg-blue-500/10 text-blue-800 dark:text-blue-300":blue,- "border-red-500/20 bg-red-500/10 text-red-800 dark:text-red-300": red,+ "border-rose-500/20 bg-rose-500/10 text-rose-800 dark:text-rose-300":+ rose,})}>{statusCode}diff --git a/apps/web/src/app/play/status/_components/status-play.tsx b/apps/web/src/app/play/status/_components/status-play.tsxindex 98bc5bea2..fb3d29dd4 100644--- a/apps/web/src/app/play/status/_components/status-play.tsx+++ b/apps/web/src/app/play/status/_components/status-play.tsx@@ -1,7 +1,7 @@import { Label } from "@openstatus/ui";import { Shell } from "@/components/dashboard/shell";-import { Tracker } from "@/components/tracker";+import { Tracker } from "@/components/tracker/tracker";import { getHomeMonitorListData } from "@/lib/tb";import { convertTimezoneToGMT, getRequestHeaderTimezone } from "@/lib/timezone";import { HeaderPlay } from "../../_components/header-play";@@ -21,14 +21,7 @@ export default async function StatusPlay({ timezone }: { timezone?: string }) {description="Gain the trust of your users by showing them the uptime of your API or website."/><div className="mx-auto w-full max-w-md">- {data && (- <Tracker- data={data}- id={1}- name="Ping"- url="https://www.openstatus.dev/api/ping"- />- )}+ {data && <Tracker data={data} name="Ping" description="Pong" />}</div><div className="mt-6 flex justify-start"><div className="grid items-center gap-1">diff --git a/apps/web/src/app/status-page/[domain]/page.tsx b/apps/web/src/app/status-page/[domain]/page.tsxindex e1636d2d8..648ff5445 100644--- a/apps/web/src/app/status-page/[domain]/page.tsx+++ b/apps/web/src/app/status-page/[domain]/page.tsx@@ -51,11 +51,12 @@ export default async function Page({ params }: Props) {<><StatusCheckstatusReports={page.statusReports}- monitors={page.monitors}+ incidents={page.incidents}/><MonitorListmonitors={page.monitors}statusReports={page.statusReports}+ incidents={page.incidents}/>{/* TODO: rename to StatusReportList */}<IncidentListdiff --git a/apps/web/src/app/status/utils.ts b/apps/web/src/app/status/utils.tsindex e7f6e8941..dfc998be5 100644--- a/apps/web/src/app/status/utils.ts+++ b/apps/web/src/app/status/utils.ts@@ -36,15 +36,15 @@ export function getClassname(status: ExternalStatus) {case "All Systems Operational":return "text-green-500";case "Major System Outage":- return "text-red-500";+ return "text-rose-500";case "Partial System Outage":return "text-orange-500";case "Minor Service Outage":- return "text-yellow-500";+ return "text-amber-500";case "Degraded System Service":- return "text-yellow-500";+ return "text-amber-500";case "Partially Degraded Service":- return "text-yellow-500";+ return "text-amber-500";case "Service Under Maintenance":return "text-blue-500";default:diff --git a/apps/web/src/components/layout/app-page-layout.tsx b/apps/web/src/components/layout/app-page-layout.tsxindex adf830ea2..a86152029 100644--- a/apps/web/src/components/layout/app-page-layout.tsx+++ b/apps/web/src/components/layout/app-page-layout.tsx@@ -18,7 +18,11 @@ export default function AppPageLayout({>{children}</div>- {withHelpCallout ? <HelpCallout /> : null}+ {withHelpCallout ? (+ <div className="mt-4">+ <HelpCallout />+ </div>+ ) : null}</Shell>);}diff --git a/apps/web/src/components/marketing/alert/timeline.tsx b/apps/web/src/components/marketing/alert/timeline.tsxindex 273f083ba..d9e18f0dc 100644--- a/apps/web/src/components/marketing/alert/timeline.tsx+++ b/apps/web/src/components/marketing/alert/timeline.tsx@@ -90,8 +90,8 @@ const timeline = [message: "3 incoming notifications from Grafana.",icon: {name: "webhook",- textColor: "text-yellow-500",- borderColor: "border-yellow-500/40",+ textColor: "text-amber-500",+ borderColor: "border-amber-500/40",},},{diff --git a/apps/web/src/components/marketing/status-page/tracker-example.tsx b/apps/web/src/components/marketing/status-page/tracker-example.tsxindex 8ea400a04..5c6a1162a 100644--- a/apps/web/src/components/marketing/status-page/tracker-example.tsx+++ b/apps/web/src/components/marketing/status-page/tracker-example.tsx@@ -3,7 +3,7 @@ import Link from "next/link";import { Button } from "@openstatus/ui";-import { Tracker } from "@/components/tracker";+import { Tracker } from "@/components/tracker/tracker";import { getHomeMonitorListData } from "@/lib/tb";import { convertTimezoneToGMT } from "@/lib/timezone";@@ -23,27 +23,12 @@ export async function TrackerExample() {}function ExampleTrackerFallback() {- return (- <Tracker- data={[]}- id={1}- name="Ping"- url="https://www.openstatus.dev/api/ping"- />- );+ return <Tracker data={[]} name="Ping" description="Pong" />;}async function ExampleTracker() {const gmt = convertTimezoneToGMT();const data = await getHomeMonitorListData({ timezone: gmt });if (!data) return null;- return (- <Tracker- data={data}- id={1}- name="Ping"- context="play"- url="https://www.openstatus.dev/api/ping"- />- );+ return <Tracker data={data} name="Ping" description="Pong" />;}diff --git a/apps/web/src/components/status-page/monitor-list.tsx b/apps/web/src/components/status-page/monitor-list.tsxindex 401b80589..040ad0c05 100644--- a/apps/web/src/components/status-page/monitor-list.tsx+++ b/apps/web/src/components/status-page/monitor-list.tsx@@ -1,6 +1,7 @@import type { z } from "zod";import type {+ selectIncidentPageSchema,selectPublicMonitorSchema,selectPublicStatusReportSchemaWithRelation,} from "@openstatus/db/src/schema";@@ -10,9 +11,11 @@ import { Monitor } from "./monitor";export const MonitorList = ({monitors,statusReports,+ incidents,}: {monitors: z.infer<typeof selectPublicMonitorSchema>[];statusReports: z.infer<typeof selectPublicStatusReportSchemaWithRelation>[];+ incidents: z.infer<typeof selectIncidentPageSchema>;}) => {return (<div className="grid gap-4">@@ -22,11 +25,15 @@ export const MonitorList = ({(i) => i.monitor.id === monitor.id,),);+ const monitorIncidents = incidents.filter(+ (incident) => incident.monitorId === monitor.id,+ );return (<Monitorkey={index}monitor={monitor}statusReports={monitorStatusReport}+ incidents={monitorIncidents}/>);})}diff --git a/apps/web/src/components/status-page/monitor.tsx b/apps/web/src/components/status-page/monitor.tsxindex ac3126794..4a99b412f 100644--- a/apps/web/src/components/status-page/monitor.tsx+++ b/apps/web/src/components/status-page/monitor.tsx@@ -1,20 +1,23 @@import type { z } from "zod";import type {+ selectIncidentPageSchema,selectPublicMonitorSchema,selectPublicStatusReportSchemaWithRelation,} from "@openstatus/db/src/schema";+import { Tracker } from "@/components/tracker/tracker";import { getMonitorListData } from "@/lib/tb";import { convertTimezoneToGMT } from "@/lib/timezone";-import { Tracker } from "../tracker";export const Monitor = async ({monitor,statusReports,+ incidents,}: {monitor: z.infer<typeof selectPublicMonitorSchema>;statusReports: z.infer<typeof selectPublicStatusReportSchemaWithRelation>[];+ incidents: z.infer<typeof selectIncidentPageSchema>;}) => {const gmt = convertTimezoneToGMT();const data = await getMonitorListData({@@ -27,5 +30,12 @@ export const Monitor = async ({if (!data) return <div>Something went wrong</div>;- return <Tracker data={data} reports={statusReports} {...monitor} />;+ return (+ <Tracker+ data={data}+ reports={statusReports}+ incidents={incidents}+ {...monitor}+ />+ );};diff --git a/apps/web/src/components/status-page/status-check.tsx b/apps/web/src/components/status-page/status-check.tsxindex eae35e74b..6d8b1183c 100644--- a/apps/web/src/components/status-page/status-check.tsx+++ b/apps/web/src/components/status-page/status-check.tsx@@ -2,24 +2,23 @@ import { cva } from "class-variance-authority";import type { z } from "zod";import type {- selectPublicMonitorSchema,+ selectIncidentPageSchema,selectStatusReportPageSchema,} from "@openstatus/db/src/schema";-import { getResponseListData } from "@/lib/tb";+import { getStatusByRatio, incidentStatus } from "@/lib/tracker";import type { StatusVariant } from "@/lib/tracker";-import { calcStatus } from "@/lib/tracker";-import { cn, notEmpty } from "@/lib/utils";+import { cn } from "@/lib/utils";import { Icons } from "../icons";-const check = cva("border-border rounded-full border p-1.5", {+const check = cva("rounded-full border p-1.5", {variants: {variant: {up: "bg-green-500/80 border-green-500",- down: "bg-red-500/80 border-red-500",- degraded: "bg-yellow-500/80 border-yellow-500",+ down: "bg-rose-500/80 border-rose-500",+ degraded: "bg-amber-500/80 border-amber-500",empty: "bg-gray-500/80 border-gray-500",- incident: "bg-yellow-500/80 border-yellow-500",+ incident: "bg-amber-500/80 border-amber-500",},},defaultVariants: {@@ -29,35 +28,20 @@ const check = cva("border-border rounded-full border p-1.5", {export async function StatusCheck({statusReports,- monitors,+ incidents,}: {statusReports: z.infer<typeof selectStatusReportPageSchema>;- monitors: z.infer<typeof selectPublicMonitorSchema>[];+ incidents: z.infer<typeof selectIncidentPageSchema>;}) {- const isIncident = statusReports.some(+ const isStatusReport = statusReports.some((incident) => !["monitoring", "resolved"].includes(incident.status),);+ const isIncident = incidents.some((incident) => incident.resolvedAt === null);- const monitorsData = (- await Promise.all(- monitors.map((monitor) => {- return getResponseListData({- monitorId: String(monitor.id),- url: monitor.url,- limit: 10,- });- }),- )- ).filter(notEmpty);+ // Forcing the status to be either 'degraded' or 'up'+ const status = getStatusByRatio(isIncident ? 0.5 : 1);- const status = calcStatus(monitorsData);-- const incident = {- label: "Incident",- variant: "incident",- } as const;-- const { label, variant } = isIncident ? incident : status;+ const { label, variant } = isStatusReport ? incidentStatus : status;return (<div className="flex flex-col items-center gap-2">@@ -72,24 +56,22 @@ export async function StatusCheck({);}-interface StatusIconProps {+export interface StatusIconProps {variant: StatusVariant | "incident";className?: string;}-function StatusIcon({ variant, className }: StatusIconProps) {+export function StatusIcon({ variant, className }: StatusIconProps) {const rootClassName = cn("h-5 w-5 text-background", className);- const MinusIcon = Icons["minus"];- const CheckIcon = Icons["check"];- const AlertTriangleIcon = Icons["alert-triangle"];if (variant === "incident") {+ const AlertTriangleIcon = Icons["alert-triangle"];return <AlertTriangleIcon className={rootClassName} />;}if (variant === "degraded") {- return <MinusIcon className={rootClassName} />;+ return <Icons.minus className={rootClassName} />;}if (variant === "down") {- return <MinusIcon className={rootClassName} />;+ return <Icons.minus className={rootClassName} />;}- return <CheckIcon className={rootClassName} />;+ return <Icons.check className={rootClassName} />;}diff --git a/apps/web/src/components/status-update/status-badge.tsx b/apps/web/src/components/status-update/status-badge.tsxindex aa90d5604..d84708823 100644--- a/apps/web/src/components/status-update/status-badge.tsx+++ b/apps/web/src/components/status-update/status-badge.tsx@@ -19,9 +19,9 @@ export function StatusBadge({className={cn("font-normal",{- "border-red-500/20 bg-red-500/10 text-red-500":+ "border-rose-500/20 bg-rose-500/10 text-rose-500":status === "investigating",- "border-yellow-500/20 bg-yellow-500/10 text-yellow-500":+ "border-amber-500/20 bg-amber-500/10 text-amber-500":status === "identified","border-blue-500/20 bg-blue-500/10 text-blue-500":status === "monitoring",diff --git a/apps/web/src/components/tracker.tsx b/apps/web/src/components/tracker.tsxdeleted file mode 100644index fd1d11ef5..000000000--- a/apps/web/src/components/tracker.tsx+++ /dev/null@@ -1,243 +0,0 @@-"use client";--import * as React from "react";-import Link from "next/link";-import { cva } from "class-variance-authority";-import { format } from "date-fns";-import { ChevronRight, Eye, Info } from "lucide-react";--import type {- StatusReport,- StatusReportUpdate,-} from "@openstatus/db/src/schema";-import type { Monitor } from "@openstatus/tinybird";-import {- HoverCard,- HoverCardContent,- HoverCardTrigger,- Separator,- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@openstatus/ui";--import {- addBlackListInfo,- areDatesEqualByDayMonthYear,- getStatus,- getTotalUptimeString,-} from "@/lib/tracker";--// What would be cool is tracker that turn from green to red depending on the number of errors-const tracker = cva("h-10 rounded-full flex-1", {- variants: {- variant: {- up: "bg-green-500/90 data-[state=open]:bg-green-500",- down: "bg-red-500/90 data-[state=open]:bg-red-500",- degraded: "bg-yellow-500/90 data-[state=open]:bg-yellow-500",- empty: "bg-muted-foreground/20 data-[state=open]:bg-muted-foreground/30",- blacklist: "bg-green-500/80 data-[state=open]:bg-green-500",- },- report: {- 0: "",- 30: "bg-gradient-to-t from-blue-500/90 hover:from-blue-500 from-30% to-transparent to-30%",- },- },- defaultVariants: {- variant: "empty",- report: 0,- },-});--interface TrackerProps {- data: Monitor[];- url: string;- id: string | number;- name: string;- description?: string;- context?: "play" | "status-page"; // TODO: we might need to extract those two different use cases - for now it's ok I'd say.- reports?: (StatusReport & { statusReportUpdates: StatusReportUpdate[] })[];-}--export function Tracker({- data,- url,- id,- name,- context = "status-page",- description,- reports,-}: TrackerProps) {- const uptime = getTotalUptimeString(data);- const _data = addBlackListInfo(data);-- return (- <div className="flex flex-col">- <div className="mb-2 flex justify-between text-sm">- <div className="flex items-center gap-2">- <p className="text-foreground line-clamp-1 font-semibold">{name}</p>- {description ? (- <MoreInfo {...{ url, id, context, description }} />- ) : null}- </div>- <p className="text-muted-foreground shrink-0 font-light">{uptime}</p>- </div>- <div className="relative h-full w-full">- <div className="flex flex-row-reverse gap-px sm:gap-0.5">- {_data.map((props, i) => {- const dateReports = reports?.filter((report) => {- const firstStatusReportUpdate = report.statusReportUpdates.sort(- (a, b) => a.date.getTime() - b.date.getTime(),- )?.[0];-- if (!firstStatusReportUpdate) return false;-- return areDatesEqualByDayMonthYear(- firstStatusReportUpdate.date,- new Date(props.day),- );- });-- return (- <Bar key={i} context={context} reports={dateReports} {...props} />- );- })}- </div>- </div>- </div>- );-}--const MoreInfo = ({- url,- id,- context,- description,-}: Pick<TrackerProps, "url" | "id" | "context" | "description">) => {- const [open, setOpen] = React.useState(false);- const formattedURL = new URL(url);- const link = `${formattedURL.host}${formattedURL.pathname}`;-- if (description == null && context !== "play") {- return;- }-- return (- <TooltipProvider>- <Tooltip open={open} onOpenChange={setOpen}>- <TooltipTrigger onClick={() => setOpen(true)} asChild>- <Info className="h-4 w-4" />- </TooltipTrigger>- <TooltipContent>- <p className="text-muted-foreground">- {context === "play" ? (- <Link href={`/monitor/${id}`} className="hover:text-foreground">- {link}- </Link>- ) : (- description- )}- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- );-};--type BarProps = Monitor & { blacklist?: string } & Pick<- TrackerProps,- "context" | "reports"- >;--const Bar = ({- count,- ok,- p95Latency,- day,- blacklist,- context,- reports,-}: BarProps) => {- const [open, setOpen] = React.useState(false);- const ratio = ok / count;- const cronTimestamp = new Date(day).getTime();- const date = new Date(cronTimestamp);- const toDate = date.setDate(date.getDate() + 1);- const dateFormat = "dd/MM/yy";-- const className = tracker({- report: reports && reports.length > 0 ? 30 : undefined,- variant: blacklist ? "blacklist" : getStatus(ratio).variant,- });-- return (- <HoverCard- openDelay={100}- closeDelay={100}- open={open}- onOpenChange={setOpen}- >- <HoverCardTrigger onClick={() => setOpen(true)} asChild>- <div className={className} />- </HoverCardTrigger>- <HoverCardContent side="top" className="w-64">- {blacklist ? (- <p className="text-muted-foreground text-xs">{blacklist}</p>- ) : (- <>- <div className="flex justify-between">- <p className="text-sm font-semibold">{getStatus(ratio).label}</p>- {context === "play" ? (- <Link- href={`/monitor/1?fromDate=${cronTimestamp}&toDate=${toDate}`}- className="text-muted-foreground hover:text-foreground"- >- <Eye className="h-4 w-4" />- </Link>- ) : null}- </div>- <ul className="my-1.5">- {reports?.map((report) => (- <li key={report.id} className="text-muted-foreground text-sm">- <Link- // TODO: include setPrefixUrl for local development- href={`./incidents/${report.id}`}- className="hover:text-foreground group flex items-center justify-between gap-2"- >- <span className="truncate">{report.title}</span>- <ChevronRight className="h-4 w-4" />- </Link>- </li>- ))}- </ul>- <div className="flex justify-between">- <p className="text-xs">- {format(new Date(cronTimestamp), dateFormat)}- </p>- <p className="text-muted-foreground text-xs font-light">- p95{" "}- <span className="font-mono font-medium">{p95Latency}ms</span>- </p>- </div>- <Separator className="my-1.5" />- <div className="grid grid-cols-2">- <p className="text-left text-xs">- <span className="font-mono text-green-600">{count}</span>{" "}- <span className="text-muted-foreground font-light">- total requests- </span>- </p>- <p className="text-right text-xs">- <span className="font-mono text-red-600">{count - ok}</span>{" "}- <span className="text-muted-foreground font-light">- failed requests- </span>- </p>- </div>- </>- )}- </HoverCardContent>- </HoverCard>- );-};diff --git a/apps/web/src/components/tracker/tracker.tsx b/apps/web/src/components/tracker/tracker.tsxnew file mode 100644index 000000000..8e2487d43--- /dev/null+++ b/apps/web/src/components/tracker/tracker.tsx@@ -0,0 +1,296 @@+"use client";++import * as React from "react";+import Link from "next/link";+import { cva } from "class-variance-authority";+import { endOfDay, format, formatDuration, startOfDay } from "date-fns";+import { ChevronRight, Info } from "lucide-react";+import type { z } from "zod";++import type {+ selectIncidentPageSchema,+ StatusReport,+ StatusReportUpdate,+} from "@openstatus/db/src/schema";+import type { Monitor } from "@openstatus/tinybird";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ Separator,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@openstatus/ui";++import {+ addBlackListInfo,+ areDatesEqualByDayMonthYear,+ getStatusByRatio,+ getTotalUptimeString,+ incidentStatus,+} from "@/lib/tracker";+import { cn } from "@/lib/utils";++// What would be cool is tracker that turn from green to red depending on the number of errors+const tracker = cva("h-10 rounded-full flex-1", {+ variants: {+ variant: {+ up: "bg-green-500/90 data-[state=open]:bg-green-500",+ down: "bg-rose-500/90 data-[state=open]:bg-rose-500",+ degraded: "bg-amber-500/90 data-[state=open]:bg-amber-500",+ empty: "bg-muted-foreground/20 data-[state=open]:bg-muted-foreground/30",+ blacklist: "bg-green-500/80 data-[state=open]:bg-green-500",+ incident: "bg-rose-500/90 data-[state=open]:bg-rose-500",+ },+ report: {+ 0: "",+ // IDEA: data-[state=open]:from-40% data-[state=open]:to-40%+ 30: "bg-gradient-to-t from-blue-500/90 hover:from-blue-500 from-30% to-transparent to-30%",+ },+ },+ defaultVariants: {+ variant: "empty",+ report: 0,+ },+});++// FIXME:+type Incidents = z.infer<typeof selectIncidentPageSchema>;++interface TrackerProps {+ data: Monitor[];+ name: string;+ description?: string;+ reports?: (StatusReport & { statusReportUpdates: StatusReportUpdate[] })[];+ incidents?: Incidents;+}++export function Tracker({+ data,+ name,+ description,+ reports,+ incidents,+}: TrackerProps) {+ const uptime = getTotalUptimeString(data);+ const _data = addBlackListInfo(data);++ console.log({ incidents });++ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex justify-between text-sm">+ <div className="flex items-center gap-2">+ <p className="text-foreground line-clamp-1 font-semibold">{name}</p>+ {description ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Info className="h-4 w-4" />+ </TooltipTrigger>+ <TooltipContent>+ <p className="text-muted-foreground">{description}</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : null}+ </div>+ <p className="text-muted-foreground shrink-0 font-light">{uptime}</p>+ </div>+ <div className="relative h-full w-full">+ <div className="flex flex-row-reverse gap-px sm:gap-0.5">+ {_data.map((props, i) => {+ const dateReports = reports?.filter((report) => {+ const firstStatusReportUpdate = report.statusReportUpdates.sort(+ (a, b) => a.date.getTime() - b.date.getTime(),+ )?.[0];++ if (!firstStatusReportUpdate) return false;++ return areDatesEqualByDayMonthYear(+ firstStatusReportUpdate.date,+ new Date(props.day),+ );+ });++ const dateIncidents = incidents?.filter((incident) => {+ const { startedAt, resolvedAt } = incident;+ const day = new Date(props.day);+ const eod = endOfDay(day);+ const sod = startOfDay(day);++ if (!startedAt) return false; // not started+ if (!resolvedAt) return true; // still ongoing++ const hasResolvedBeforeStartOfDay =+ resolvedAt.getTime() <= sod.getTime();++ if (hasResolvedBeforeStartOfDay) return false;++ const hasStartedBeforeEndOfDay =+ startedAt.getTime() <= eod.getTime();++ const hasResolvedBeforeEndOfDay =+ resolvedAt.getTime() <= eod.getTime();++ if (hasStartedBeforeEndOfDay || hasResolvedBeforeEndOfDay)+ return true;++ if (hasResolvedBeforeEndOfDay) return true;++ return false;+ });++ return (+ <Bar+ key={i}+ reports={dateReports}+ incidents={dateIncidents}+ {...props}+ />+ );+ })}+ </div>+ </div>+ <div className="text-muted-foreground flex items-center justify-between text-xs font-light">+ <p>{_data.length - 1} days ago</p>+ <p>Today</p>+ </div>+ </div>+ );+}++type BarProps = Monitor & { blacklist?: string } & Pick<+ TrackerProps,+ "reports" | "incidents"+ >;++const Bar = ({ count, ok, day, blacklist, reports, incidents }: BarProps) => {+ const [open, setOpen] = React.useState(false);+ const status = getStatusByRatio(ok / count);+ const isIncident = incidents && incidents.length > 0;++ const { label, variant } = isIncident ? incidentStatus : status;++ const className = tracker({+ report: reports && reports.length > 0 ? 30 : undefined,+ variant: blacklist ? "blacklist" : variant,+ });++ return (+ <HoverCard+ openDelay={100}+ closeDelay={100}+ open={open}+ onOpenChange={setOpen}+ >+ <HoverCardTrigger onClick={() => setOpen(true)} asChild>+ <div className={className} />+ </HoverCardTrigger>+ <HoverCardContent side="top" className="w-auto max-w-[16rem] p-2">+ {blacklist ? (+ <p className="text-muted-foreground text-sm">{blacklist}</p>+ ) : (+ <div>+ <div className="flex gap-2">+ <div+ className={cn(className, "h-auto w-1 flex-none rounded-full")}+ />+ <div className="grid flex-1 gap-1">+ <div className="flex justify-between gap-8 text-sm">+ <p className="font-semibold">{label}</p>+ <p className="text-muted-foreground">+ {format(new Date(day), "MMM d")}+ </p>+ </div>+ <div className="text-muted-foreground flex justify-between gap-8 text-xs font-light">+ <p>+ <code className="text-green-500">{count}</code> requests+ </p>+ <p>+ <code className="text-red-500">{count - ok}</code> failed+ </p>+ </div>+ </div>+ </div>+ {reports && reports.length > 0 ? (+ <>+ <Separator className="my-1.5" />+ <StatusReportList reports={reports} />+ </>+ ) : null}+ {incidents && incidents.length > 0 ? (+ <>+ <Separator className="my-1.5" />+ <DowntimeText incidents={incidents} day={day} />+ </>+ ) : null}+ </div>+ )}+ </HoverCardContent>+ </HoverCard>+ );+};++export function StatusReportList({ reports }: { reports: StatusReport[] }) {+ return (+ <ul>+ {reports?.map((report) => (+ <li key={report.id} className="text-muted-foreground text-sm">+ <Link+ // TODO: include setPrefixUrl for local development+ href={`./incidents/${report.id}`}+ className="hover:text-foreground group flex items-center justify-between gap-2"+ >+ <span className="truncate">{report.title}</span>+ <ChevronRight className="h-4 w-4" />+ </Link>+ </li>+ ))}+ </ul>+ );+}++export function DowntimeText({+ incidents,+ day,+}: {+ incidents: Incidents;+ day: string; // TODO: use Date+}) {+ const startOfDayDate = startOfDay(new Date(day));+ const endOfDayDate = endOfDay(new Date(day));++ const incidentLength = incidents+ ?.map((incident) => {+ const { startedAt, resolvedAt } = incident;+ if (!startedAt) return 0;+ if (!resolvedAt)+ return (+ endOfDayDate.getTime() -+ Math.max(startOfDayDate.getTime(), startedAt.getTime())+ );+ return (+ Math.min(resolvedAt.getTime(), endOfDayDate.getTime()) -+ Math.max(startOfDayDate.getTime(), startedAt.getTime())+ );+ })+ // add 1 second because end of day is 23:59:59+ .reduce((acc, curr) => acc + 1 + curr, 0);++ const days = Math.floor(incidentLength / (1000 * 60 * 60 * 24));+ const minutes = Math.floor((incidentLength / (1000 * 60)) % 60);+ const hours = Math.floor((incidentLength / (1000 * 60 * 60)) % 24);++ return (+ <p className="text-muted-foreground text-xs">+ Down for{" "}+ {formatDuration(+ { minutes, hours, days },+ { format: ["days", "hours", "minutes", "seconds"], zero: false },+ )}+ </p>+ );+}diff --git a/apps/web/src/lib/tracker.ts b/apps/web/src/lib/tracker.tsindex 4653c14d1..d0b295b0d 100644--- a/apps/web/src/lib/tracker.ts+++ b/apps/web/src/lib/tracker.ts@@ -1,18 +1,23 @@import type { Monitor, Ping } from "@openstatus/tinybird";-export type StatusVariant = "up" | "degraded" | "down" | "empty";+export type StatusVariant = "up" | "degraded" | "down" | "empty" | "incident";type GetStatusReturnType = {label: string;variant: StatusVariant;};+export const incidentStatus: GetStatusReturnType = {+ label: "Incident",+ variant: "incident",+};+/*** Get the status of a monitor based on its ratio* @param ratio* @returns*/-export const getStatus = (ratio: number): GetStatusReturnType => {+export const getStatusByRatio = (ratio: number): GetStatusReturnType => {if (isNaN(ratio))return {label: "Missing",@@ -103,8 +108,8 @@ export function calcStatus(data: Ping[][]) {{ count: 0, ok: 0 },);const ratio = ok / count;- if (isNaN(ratio)) return getStatus(1); // outsmart caching issue- return getStatus(ratio);+ if (isNaN(ratio)) return getStatusByRatio(1); // outsmart caching issue+ return getStatusByRatio(ratio);}/**diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 69e376040..750982464 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { and, eq, inArray, or, sql } from "@openstatus/db";import {+ incidentTable,insertPageSchema,monitor,monitorsToPages,@@ -155,6 +156,7 @@ export const pageRouter = createTRPCRouter({// public if we use trpc hooks to get the page from the urlgetPageBySlug: publicProcedure.input(z.object({ slug: z.string().toLowerCase() }))+ .output(selectPublicPageSchemaWithRelation.optional()).query(async (opts) => {console.log(opts.input.slug);const result = await opts.ctx.db.query.page.findFirst({@@ -237,9 +239,21 @@ export const pageRouter = createTRPCRouter({.all(): [];+ const incidents = await opts.ctx.db+ .select()+ .from(incidentTable)+ .where(+ inArray(+ incidentTable.monitorId,+ monitors.map((m) => m.id),+ ),+ )+ .all();+return selectPublicPageSchemaWithRelation.parse({...result,monitors,+ incidents,statusReports,workspacePlan: workspaceResult?.plan,});diff --git a/packages/db/src/schema/incidents/incident.ts b/packages/db/src/schema/incidents/incident.tsindex 512eb7992..5f7220804 100644--- a/packages/db/src/schema/incidents/incident.ts+++ b/packages/db/src/schema/incidents/incident.ts@@ -35,7 +35,7 @@ export const incidentTable = sqliteTable(startedAt: integer("started_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),- // Who has acknoledge the incident+ // Who has acknowledged the incidentacknowledgedAt: integer("acknowledged_at", { mode: "timestamp" }),acknowledgedBy: integer("acknowledged_by").references(() => user.id),diff --git a/packages/db/src/schema/shared.ts b/packages/db/src/schema/shared.tsindex 0ef246197..ca574418b 100644--- a/packages/db/src/schema/shared.ts+++ b/packages/db/src/schema/shared.ts@@ -1,5 +1,6 @@import { z } from "zod";+import { selectIncidentSchema } from "./incidents/validation";import { selectMonitorSchema } from "./monitors";import { selectPageSchema } from "./pages";import {@@ -36,10 +37,24 @@ export const selectPageSchemaWithRelation = selectPageSchema.extend({statusReports: selectStatusReportPageSchema,});+export const selectIncidentPageSchema = z+ .array(+ selectIncidentSchema.pick({+ id: true,+ monitorId: true,+ status: true,+ startedAt: true,+ acknowledgedAt: true,+ resolvedAt: true,+ }),+ )+ .default([]);+export const selectPublicPageSchemaWithRelation = selectPageSchema.extend({monitors: z.array(selectPublicMonitorSchema),statusReports: selectStatusReportPageSchema,+ incidents: selectIncidentPageSchema,workspacePlan: workspacePlanSchema.nullable().default("free")diff --git a/packages/tinybird/pipes/status_timezone.pipe b/packages/tinybird/pipes/status_timezone.pipeindex c0b013a9d..2b133e8ec 100644--- a/packages/tinybird/pipes/status_timezone.pipe+++ b/packages/tinybird/pipes/status_timezone.pipe@@ -12,8 +12,8 @@ SQL >toDateTime(cronTimestamp / 1000, 'UTC') AS day,toTimezone(day, {{ String(timezone, 'Europe/London') }}) as with_timezone,toStartOfDay(with_timezone) as start_of_day,- statusCode,- latency+ -- latency,+ statusCodeFROM ping_response__v7{% if defined(url) %} AND url = {{ String(url) }} {% end %}WHERE monitorId = {{ String(monitorId, '1') }}@@ -28,14 +28,14 @@ SQL >%SELECT+ -- round(avg(latency)) as avgLatency,+ -- round(quantile(0.75)(latency)) as p75Latency,+ -- round(quantile(0.9)(latency)) as p90Latency,+ -- round(quantile(0.95)(latency)) as p95Latency,+ -- round(quantile(0.99)(latency)) as p99Latency,start_of_day as day,count() AS count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,- round(avg(latency)) as avgLatency,- round(quantile(0.75)(latency)) as p75Latency,- round(quantile(0.9)(latency)) as p90Latency,- round(quantile(0.95)(latency)) as p95Latency,- round(quantile(0.99)(latency)) as p99Latency+ count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS okFROM group_by_cronTimestampGROUP BY start_of_dayORDER BY start_of_daydiff --git a/packages/tinybird/src/validation.ts b/packages/tinybird/src/validation.tsindex 294ad21c5..879def3e2 100644--- a/packages/tinybird/src/validation.ts+++ b/packages/tinybird/src/validation.ts@@ -154,16 +154,14 @@ export const tbParameterMonitorList = z.object({/*** Values from the pipe status_timezone*/-export const tbBuildMonitorList = z- .object({- count: z.number().int(),- ok: z.number().int(),- day: z.string().transform((val) => {- // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)- return new Date(`${val} GMT`).toISOString();- }),- })- .merge(latencyMetrics);+export const tbBuildMonitorList = z.object({+ count: z.number().int(),+ ok: z.number().int(),+ day: z.string().transform((val) => {+ // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)+ return new Date(`${val} GMT`).toISOString();+ }),+});/*** Params for pipe home_stats