Skip to content

Open-source status page, incident response and uptime monitoring

feat: tracker class (#689)

Maximilian Kaskeacd61eb52a1b
diff --git a/apps/server/package.json b/apps/server/package.json
index d09aa82eb..510a04dc0 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -21,6 +21,7 @@
"@openstatus/notification-twillio-sms": "workspace:*",
"@openstatus/plans": "workspace:*",
"@openstatus/tinybird": "workspace:*",
+ "@openstatus/tracker": "workspace:*",
"@openstatus/upstash": "workspace:*",
"@openstatus/utils": "workspace:*",
"@t3-oss/env-core": "0.7.1",
diff --git a/apps/server/src/public/status.ts b/apps/server/src/public/status.ts
index cc4fb8284..0a639db21 100644
--- a/apps/server/src/public/status.ts
+++ b/apps/server/src/public/status.ts
@@ -11,6 +11,7 @@ import {
pagesToStatusReports,
statusReport,
} from "@openstatus/db/src/schema";
+import { Status, Tracker } from "@openstatus/tracker";
import { Redis } from "@openstatus/upstash";
import { notEmpty } from "../utils/not-empty";
@@ -19,16 +20,6 @@ import { notEmpty } from "../utils/not-empty";
const redis = Redis.fromEnv();
-enum Status {
- Operational = "operational",
- DegradedPerformance = "degraded_performance",
- PartialOutage = "partial_outage", // not used
- MajorOutage = "major_outage", // not used
- UnderMaintenance = "under_maintenance", // not used
- Unknown = "unknown",
- Incident = "incident",
-}
-
export const status = new Hono();
status.get("/:slug", async (c) => {
@@ -49,7 +40,6 @@ status.get("/:slug", async (c) => {
.where(eq(page.slug, slug))
.get();
- console.log(currentPage);
if (!currentPage) {
return c.json({ status: Status.Unknown });
}
@@ -58,22 +48,18 @@ status.get("/:slug", async (c) => {
await getStatusPageData(currentPage.id);
endTime(c, "database");
- const isStatusReport = [
+ const statusReports = [
...pageStatusReportData,
...monitorStatusReportData,
- ].some((data) => {
- if (!data.status_report) return false;
- return !["monitoring", "resolved"].includes(data.status_report.status);
+ ].map((item) => {
+ return item.status_report;
});
- 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();
+ const tracker = new Tracker({ incidents: ongoingIncidents, statusReports });
+
+ const status = tracker.currentStatus;
await redis.set(slug, status, { ex: 60 }); // 1m cache
+
return c.json({ status });
});
diff --git a/apps/web/package.json b/apps/web/package.json
index d5ca4af0a..1d9186388 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -24,6 +24,7 @@
"@openstatus/plans": "workspace:*",
"@openstatus/react": "workspace:*",
"@openstatus/tinybird": "workspace:*",
+ "@openstatus/tracker": "workspace:*",
"@openstatus/ui": "workspace:*",
"@openstatus/upstash": "workspace:*",
"@openstatus/utils": "workspace:*",
diff --git a/apps/web/src/app/api/og/_components/status-check.tsx b/apps/web/src/app/api/og/_components/status-check.tsx
index a8786659d..2cc69644d 100644
--- a/apps/web/src/app/api/og/_components/status-check.tsx
+++ b/apps/web/src/app/api/og/_components/status-check.tsx
@@ -1,43 +1,34 @@
-import type { StatusVariant } from "@/lib/tracker";
+import type { Tracker } from "@openstatus/tracker";
+
import { cn } from "@/lib/utils";
-export function StatusCheck({ variant }: { variant: StatusVariant }) {
+export function StatusCheck({ tracker }: { tracker: Tracker }) {
+ const details = tracker.currentDetails;
+ const className = tracker.currentClassName;
+
+ // FIXME: move icons into @openstatus/tracker lib
function getVariant() {
- switch (variant) {
+ switch (details.variant) {
case "down":
- return {
- color: "bg-rose-500",
- label: "Major Outage",
- icon: Minus,
- };
+ return Minus;
case "degraded":
- return {
- color: "bg-amber-500",
- label: "Systems Degraded",
- icon: Minus,
- };
+ return Minus;
case "incident":
- return {
- color: "bg-amber-500",
- label: "Incident Ongoing",
- icon: Alert,
- };
+ return Alert;
default:
- return {
- color: "bg-green-500",
- label: "All Systems Operational",
- icon: Check,
- };
+ return Check;
}
}
- const { icon, color, label } = getVariant();
+ const Icon = getVariant();
return (
<div tw="flex flex-col justify-center items-center gap-2 w-full">
- <div tw={cn("flex text-white rounded-full p-3", color)}>{icon()}</div>
+ <div tw={cn("flex text-white rounded-full p-3 border-2", className)}>
+ <Icon />
+ </div>
<p style={{ fontFamily: "Cal" }} tw="text-4xl">
- {label}
+ {details.long}
</p>
</div>
);
diff --git a/apps/web/src/app/api/og/_components/tracker.tsx b/apps/web/src/app/api/og/_components/tracker.tsx
index 366e58777..a6f182d54 100644
--- a/apps/web/src/app/api/og/_components/tracker.tsx
+++ b/apps/web/src/app/api/og/_components/tracker.tsx
@@ -1,22 +1,17 @@
import type { Monitor } from "@openstatus/tinybird";
+import { classNames, Tracker as OSTracker } from "@openstatus/tracker";
-import {
- addBlackListInfo,
- getStatusByRatio,
- getTotalUptimeString,
-} from "@/lib/tracker";
import { cn, formatDate } from "@/lib/utils";
export function Tracker({ data }: { data: Monitor[] }) {
- const _data = addBlackListInfo(data);
- const uptime = getTotalUptimeString(data);
+ const tracker = new OSTracker({ data });
return (
<div tw="flex flex-col w-full my-12">
<div tw="flex flex-col mx-auto">
<div tw="flex flex-row items-center justify-between -mb-1 text-black font-light">
<p></p>
- <p tw="font-medium">{uptime}</p>
+ <p tw="font-medium">{tracker.totalUptime}%</p>
</div>
{/* Empty State */}
<div tw="flex flex-row relative">
@@ -24,8 +19,7 @@ export function Tracker({ data }: { data: Monitor[] }) {
return <div key={i} tw="h-16 w-3 rounded-full mr-1 bg-black/20" />;
})}
<div tw="flex flex-row-reverse absolute left-0">
- {_data.map((item, i) => {
- const { variant } = getStatusByRatio(item.ok / item.count);
+ {tracker.days.map((item, i) => {
const isBlackListed = Boolean(item.blacklist);
if (isBlackListed) {
return (
@@ -35,11 +29,10 @@ export function Tracker({ data }: { data: Monitor[] }) {
return (
<div
key={i}
- tw={cn("h-16 w-3 rounded-full mr-1", {
- "bg-green-500": variant === "up",
- "bg-red-500": variant === "down",
- "bg-amber-500": variant === "degraded",
- })}
+ tw={cn(
+ "h-16 w-3 rounded-full mr-1",
+ classNames[item.variant],
+ )}
/>
);
})}
diff --git a/apps/web/src/app/api/og/page/route.tsx b/apps/web/src/app/api/og/page/route.tsx
index 1df4c8d48..797354ce9 100644
--- a/apps/web/src/app/api/og/page/route.tsx
+++ b/apps/web/src/app/api/og/page/route.tsx
@@ -1,7 +1,8 @@
import { ImageResponse } from "next/og";
+import { Tracker } from "@openstatus/tracker";
+
import { DESCRIPTION, TITLE } from "@/app/shared-metadata";
-import { getStatusByRatio, incidentStatus } from "@/lib/tracker";
import { api } from "@/trpc/server";
import { BasicLayout } from "../_components/basic-layout";
import { StatusCheck } from "../_components/status-check";
@@ -23,22 +24,17 @@ export async function GET(req: Request) {
const title = page ? page.title : TITLE;
const description = page ? "" : DESCRIPTION;
- const isStatusReport = page?.statusReports.some(
- (incident) => !["monitoring", "resolved"].includes(incident.status),
- );
-
- const isIncident = page?.incidents.some(
- (incident) => incident.resolvedAt === null,
- );
+ const tracker = new Tracker({
+ incidents: page?.incidents,
+ statusReports: page?.statusReports,
+ });
- const status = isStatusReport
- ? incidentStatus
- : getStatusByRatio(isIncident ? 0.5 : 1);
+ // const status = tracker.currentStatus;
return new ImageResponse(
(
<BasicLayout title={title} description={description} tw="py-24 px-24">
- <StatusCheck variant={status.variant} />
+ <StatusCheck tracker={tracker} />
</BasicLayout>
),
{
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/incidents/(overview)/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/incidents/(overview)/page.tsx
index 78e7eef1e..305cebee8 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/incidents/(overview)/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/incidents/(overview)/page.tsx
@@ -6,13 +6,13 @@ import { DataTable } from "@/components/data-table/incident/data-table";
import { api } from "@/trpc/server";
export default async function IncidentPage() {
- const incidents = await api.incident.getAllIncidents.query();
+ const incidents = await api.incident.getIncidentsByWorkspace.query();
if (incidents?.length === 0)
return (
<EmptyState
- icon="activity"
- title="No Incidents"
+ icon="siren"
+ title="No incidents"
description="Hopefully you will see this screen for a long time."
action={undefined}
/>
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/(overview)/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/(overview)/page.tsx
index 1993fa51d..84b7f968f 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/(overview)/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/(overview)/page.tsx
@@ -31,6 +31,8 @@ export default async function MonitorPage() {
const gmt = convertTimezoneToGMT();
+ const _incidents = await api.incident.getIncidentsByWorkspace.query();
+
// maybe not very efficient?
// use Suspense and Client call instead?
const monitorsWithData = await Promise.all(
@@ -41,7 +43,7 @@ export default async function MonitorPage() {
interval: 24,
});
- const tracker = await getMonitorListData({
+ const data = await getMonitorListData({
monitorId: String(monitor.id),
url: monitor.url,
timezone: gmt,
@@ -51,7 +53,11 @@ export default async function MonitorPage() {
? metrics.sort((a, b) => (a.time - b.time < 0 ? 1 : -1))
: [undefined];
- return { monitor, metrics: current, tracker };
+ const incidents = _incidents.filter(
+ (incident) => incident.monitorId === monitor.id,
+ );
+
+ return { monitor, metrics: current, data, incidents };
}),
);
diff --git a/apps/web/src/app/status-page/[domain]/incidents/page.tsx b/apps/web/src/app/status-page/[domain]/incidents/page.tsx
index 7e9848db1..30404539c 100644
--- a/apps/web/src/app/status-page/[domain]/incidents/page.tsx
+++ b/apps/web/src/app/status-page/[domain]/incidents/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { Header } from "@/components/dashboard/header";
-import { IncidentList } from "@/components/status-page/incident-list";
+import { StatusReportList } from "@/components/status-page/status-report-list";
import { api } from "@/trpc/server";
type Props = {
@@ -22,7 +22,10 @@ export default async function Page({ params }: Props) {
description={page.description}
className="text-left"
/>
- <IncidentList incidents={page.statusReports} monitors={page.monitors} />
+ <StatusReportList
+ statusReports={page.statusReports}
+ monitors={page.monitors}
+ />
</div>
);
}
diff --git a/apps/web/src/app/status-page/[domain]/page.tsx b/apps/web/src/app/status-page/[domain]/page.tsx
index 648ff5445..2e6656c8c 100644
--- a/apps/web/src/app/status-page/[domain]/page.tsx
+++ b/apps/web/src/app/status-page/[domain]/page.tsx
@@ -5,9 +5,9 @@ import { Button } from "@openstatus/ui";
import { EmptyState } from "@/components/dashboard/empty-state";
import { Header } from "@/components/dashboard/header";
-import { IncidentList } from "@/components/status-page/incident-list";
import { MonitorList } from "@/components/status-page/monitor-list";
import { StatusCheck } from "@/components/status-page/status-check";
+import { StatusReportList } from "@/components/status-page/status-report-list";
import { api } from "@/trpc/server";
const url =
@@ -58,9 +58,8 @@ export default async function Page({ params }: Props) {
statusReports={page.statusReports}
incidents={page.incidents}
/>
- {/* TODO: rename to StatusReportList */}
- <IncidentList
- incidents={page.statusReports}
+ <StatusReportList
+ statusReports={page.statusReports}
monitors={page.monitors}
context="latest"
/>
diff --git a/apps/web/src/components/data-table/monitor/columns.tsx b/apps/web/src/components/data-table/monitor/columns.tsx
index 8c0812773..ed0a0304f 100644
--- a/apps/web/src/components/data-table/monitor/columns.tsx
+++ b/apps/web/src/components/data-table/monitor/columns.tsx
@@ -2,13 +2,14 @@
import Link from "next/link";
import type { ColumnDef } from "@tanstack/react-table";
-import { formatDistanceToNow } from "date-fns";
+import { formatDistanceToNowStrict } from "date-fns";
-import type { Monitor } from "@openstatus/db/src/schema";
+import type { Incident, Monitor } from "@openstatus/db/src/schema";
import type {
Monitor as MonitorTracker,
ResponseTimeMetrics,
} from "@openstatus/tinybird";
+import { Tracker } from "@openstatus/tracker";
import {
Tooltip,
TooltipContent,
@@ -23,7 +24,8 @@ import { DataTableRowActions } from "./data-table-row-actions";
export const columns: ColumnDef<{
monitor: Monitor;
metrics?: ResponseTimeMetrics;
- tracker?: MonitorTracker[];
+ data?: MonitorTracker[];
+ incidents?: Incident[];
}>[] = [
{
accessorKey: "name",
@@ -45,10 +47,13 @@ export const columns: ColumnDef<{
accessorKey: "tracker",
header: "Last 7 days",
cell: ({ row }) => {
- const tracker = row.original.tracker?.slice(0, 7).reverse();
+ const tracker = new Tracker({
+ data: row.original.data?.slice(0, 7).reverse(),
+ incidents: row.original.incidents,
+ });
return (
<div className="flex w-24 gap-1">
- {tracker?.map((tracker) => (
+ {tracker.days?.map((tracker) => (
<Bar key={tracker.day} className="h-5" {...tracker} />
))}
</div>
@@ -61,12 +66,13 @@ export const columns: ColumnDef<{
cell: ({ row }) => {
const timestamp = row.original.metrics?.lastTimestamp;
if (timestamp) {
- const distance = formatDistanceToNow(new Date(timestamp));
+ const distance = formatDistanceToNowStrict(new Date(timestamp), {
+ addSuffix: true,
+ });
return (
- <Number
- value={parseInt(distance.split(" ")[0])}
- suffix={`${distance.split(" ")[1]} ago`}
- />
+ <div className="text-muted-foreground flex max-w-[84px] sm:max-w-none">
+ <span className="truncate">{distance}</span>
+ </div>
);
}
return <span className="text-muted-foreground">-</span>;
@@ -129,7 +135,7 @@ function HeaderTooltip({ children }: { children: string }) {
function Number({ value, suffix }: { value: number; suffix: string }) {
return (
<span className="font-mono">
- {new Intl.NumberFormat("us").format(value).toString()}{" "}
+ {new Intl.NumberFormat("us").format(value).toString()}
<span className="text-muted-foreground text-xs font-normal">
{suffix}
</span>
diff --git a/apps/web/src/components/status-page/monitor-list.tsx b/apps/web/src/components/status-page/monitor-list.tsx
index 040ad0c05..5b561d0c9 100644
--- a/apps/web/src/components/status-page/monitor-list.tsx
+++ b/apps/web/src/components/status-page/monitor-list.tsx
@@ -1,8 +1,8 @@
import type { z } from "zod";
import type {
- selectIncidentPageSchema,
- selectPublicMonitorSchema,
+ Incident,
+ PublicMonitor,
selectPublicStatusReportSchemaWithRelation,
} from "@openstatus/db/src/schema";
@@ -13,9 +13,9 @@ export const MonitorList = ({
statusReports,
incidents,
}: {
- monitors: z.infer<typeof selectPublicMonitorSchema>[];
+ monitors: PublicMonitor[];
statusReports: z.infer<typeof selectPublicStatusReportSchemaWithRelation>[];
- incidents: z.infer<typeof selectIncidentPageSchema>;
+ incidents: Incident[];
}) => {
return (
<div className="grid gap-4">
diff --git a/apps/web/src/components/status-page/monitor.tsx b/apps/web/src/components/status-page/monitor.tsx
index 4a99b412f..e36dba728 100644
--- a/apps/web/src/components/status-page/monitor.tsx
+++ b/apps/web/src/components/status-page/monitor.tsx
@@ -1,8 +1,8 @@
import type { z } from "zod";
import type {
- selectIncidentPageSchema,
- selectPublicMonitorSchema,
+ Incident,
+ PublicMonitor,
selectPublicStatusReportSchemaWithRelation,
} from "@openstatus/db/src/schema";
@@ -15,9 +15,9 @@ export const Monitor = async ({
statusReports,
incidents,
}: {
- monitor: z.infer<typeof selectPublicMonitorSchema>;
+ monitor: PublicMonitor;
statusReports: z.infer<typeof selectPublicStatusReportSchemaWithRelation>[];
- incidents: z.infer<typeof selectIncidentPageSchema>;
+ incidents: Incident[];
}) => {
const gmt = convertTimezoneToGMT();
const data = await getMonitorListData({
diff --git a/apps/web/src/components/status-page/status-check.tsx b/apps/web/src/components/status-page/status-check.tsx
index 6d8b1183c..7b8c76005 100644
--- a/apps/web/src/components/status-page/status-check.tsx
+++ b/apps/web/src/components/status-page/status-check.tsx
@@ -1,54 +1,27 @@
-import { cva } from "class-variance-authority";
-import type { z } from "zod";
+import type { Incident, StatusReport } from "@openstatus/db/src/schema";
+import type { StatusVariant } from "@openstatus/tracker";
+import { Tracker } from "@openstatus/tracker";
-import type {
- selectIncidentPageSchema,
- selectStatusReportPageSchema,
-} from "@openstatus/db/src/schema";
-
-import { getStatusByRatio, incidentStatus } from "@/lib/tracker";
-import type { StatusVariant } from "@/lib/tracker";
import { cn } from "@/lib/utils";
import { Icons } from "../icons";
-const check = cva("rounded-full border p-1.5", {
- variants: {
- variant: {
- up: "bg-green-500/80 border-green-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-amber-500/80 border-amber-500",
- },
- },
- defaultVariants: {
- variant: "up",
- },
-});
-
export async function StatusCheck({
statusReports,
incidents,
}: {
- statusReports: z.infer<typeof selectStatusReportPageSchema>;
- incidents: z.infer<typeof selectIncidentPageSchema>;
+ statusReports: StatusReport[];
+ incidents: Incident[];
}) {
- const isStatusReport = statusReports.some(
- (incident) => !["monitoring", "resolved"].includes(incident.status),
- );
- const isIncident = incidents.some((incident) => incident.resolvedAt === null);
-
- // Forcing the status to be either 'degraded' or 'up'
- const status = getStatusByRatio(isIncident ? 0.5 : 1);
-
- const { label, variant } = isStatusReport ? incidentStatus : status;
+ const tracker = new Tracker({ statusReports, incidents });
+ const className = tracker.currentClassName;
+ const details = tracker.currentDetails;
return (
<div className="flex flex-col items-center gap-2">
<div className="flex items-center gap-3">
- <p className="text-lg font-semibold">{label}</p>
- <span className={check({ variant })}>
- <StatusIcon variant={variant} />
+ <p className="text-lg font-semibold">{details.long}</p>
+ <span className={cn("rounded-full border p-1.5", className)}>
+ <StatusIcon variant={details.variant} />
</span>
</div>
<p className="text-muted-foreground text-xs">Status Check</p>
@@ -56,22 +29,16 @@ export async function StatusCheck({
);
}
-export interface StatusIconProps {
- variant: StatusVariant | "incident";
- className?: string;
-}
-
-export function StatusIcon({ variant, className }: StatusIconProps) {
- const rootClassName = cn("h-5 w-5 text-background", className);
+export function StatusIcon({ variant }: { variant: StatusVariant }) {
if (variant === "incident") {
const AlertTriangleIcon = Icons["alert-triangle"];
- return <AlertTriangleIcon className={rootClassName} />;
+ return <AlertTriangleIcon className="text-background h-5 w-5" />;
}
if (variant === "degraded") {
- return <Icons.minus className={rootClassName} />;
+ return <Icons.minus className="text-background h-5 w-5" />;
}
if (variant === "down") {
- return <Icons.minus className={rootClassName} />;
+ return <Icons.minus className="text-background h-5 w-5" />;
}
- return <Icons.check className={rootClassName} />;
+ return <Icons.check className="text-background h-5 w-5" />;
}
diff --git a/apps/web/src/components/status-page/incident-list.tsx b/apps/web/src/components/status-page/status-report-list.tsx
similarity index 72%
rename from apps/web/src/components/status-page/incident-list.tsx
rename to apps/web/src/components/status-page/status-report-list.tsx
index a57c95a50..c29755752 100644
--- a/apps/web/src/components/status-page/incident-list.tsx
+++ b/apps/web/src/components/status-page/status-report-list.tsx
@@ -3,11 +3,10 @@
import Link from "next/link";
import { useParams } from "next/navigation";
import { ChevronRight } from "lucide-react";
-import type { z } from "zod";
import type {
- selectPublicMonitorSchema,
- selectStatusReportPageSchema,
+ PublicMonitor,
+ StatusReportWithUpdates,
} from "@openstatus/db/src/schema";
import { Button, Separator } from "@openstatus/ui";
@@ -18,29 +17,29 @@ import { Summary } from "../status-update/summary";
// TODO: change layout - it is too packed with data rn
-export const IncidentList = ({
- incidents,
+export const StatusReportList = ({
+ statusReports,
monitors,
context = "all",
}: {
- incidents: z.infer<typeof selectStatusReportPageSchema>;
- monitors: z.infer<typeof selectPublicMonitorSchema>[];
+ statusReports: StatusReportWithUpdates[];
+ monitors: PublicMonitor[];
context?: "all" | "latest"; // latest 7 days
}) => {
const params = useParams<{ domain: string }>();
const lastWeek = Date.now() - 1000 * 60 * 60 * 24 * 7;
function getLastWeeksIncidents() {
- return incidents.filter((incident) => {
+ return statusReports.filter((incident) => {
return incident.statusReportUpdates.some(
(update) => update.date.getTime() > lastWeek,
);
});
}
- const _incidents = context === "all" ? incidents : getLastWeeksIncidents();
+ const reports = context === "all" ? statusReports : getLastWeeksIncidents();
- _incidents.sort((a, b) => {
+ reports.sort((a, b) => {
if (a.updatedAt == undefined) return 1;
if (b.updatedAt == undefined) return -1;
return b.updatedAt.getTime() - a.updatedAt.getTime();
@@ -48,23 +47,23 @@ export const IncidentList = ({
return (
<>
- {_incidents?.length > 0 ? (
+ {reports?.length > 0 ? (
<div className="grid gap-3">
<p className="text-muted-foreground text-sm font-light">
{context === "all" ? "All incidents" : "Latest incidents"}
</p>
<div className="grid gap-8">
- {_incidents.map((incident) => {
- const affectedMonitors = incident.monitorsToStatusReports
+ {reports.map((report) => {
+ const affectedMonitors = report.monitorsToStatusReports
.map(({ monitorId }) => {
const monitor = monitors.find(({ id }) => monitorId === id);
return monitor || undefined;
})
.filter(notEmpty);
return (
- <div key={incident.id} className="group grid gap-4 text-left">
+ <div key={report.id} className="group grid gap-4 text-left">
<div className="flex items-center gap-1">
- <h3 className="text-xl font-semibold">{incident.title}</h3>
+ <h3 className="text-xl font-semibold">{report.title}</h3>
<Button
variant="ghost"
size="icon"
@@ -72,16 +71,16 @@ export const IncidentList = ({
asChild
>
<Link
- href={setPrefixUrl(`/incidents/${incident.id}`, params)}
+ href={setPrefixUrl(`/incidents/${report.id}`, params)}
>
<ChevronRight className="h-4 w-4" />
</Link>
</Button>
</div>
- <Summary report={incident} monitors={affectedMonitors} />
+ <Summary report={report} monitors={affectedMonitors} />
<Separator />
<Events
- statusReportUpdates={incident.statusReportUpdates}
+ statusReportUpdates={report.statusReportUpdates}
collabsible
/>
</div>
diff --git a/apps/web/src/components/tracker/tracker.tsx b/apps/web/src/components/tracker/tracker.tsx
index 921092482..14ca5fbd1 100644
--- a/apps/web/src/components/tracker/tracker.tsx
+++ b/apps/web/src/components/tracker/tracker.tsx
@@ -5,14 +5,14 @@ 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,
+ Incident,
StatusReport,
StatusReportUpdate,
} from "@openstatus/db/src/schema";
import type { Monitor } from "@openstatus/tinybird";
+import { classNames, Tracker as OSTracker } from "@openstatus/tracker";
import {
HoverCard,
HoverCardContent,
@@ -24,25 +24,13 @@ import {
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",
+ ...classNames,
},
report: {
0: "",
@@ -56,15 +44,12 @@ const tracker = cva("h-10 rounded-full flex-1", {
},
});
-// FIXME:
-type Incidents = z.infer<typeof selectIncidentPageSchema>;
-
interface TrackerProps {
data: Monitor[];
name: string;
description?: string;
reports?: (StatusReport & { statusReportUpdates: StatusReportUpdate[] })[];
- incidents?: Incidents;
+ incidents?: Incident[];
}
export function Tracker({
@@ -74,8 +59,9 @@ export function Tracker({
reports,
incidents,
}: TrackerProps) {
- const uptime = getTotalUptimeString(data);
- const _data = addBlackListInfo(data);
+ const tracker = new OSTracker({ data, statusReports: reports, incidents });
+ const uptime = tracker.totalUptime;
+ const isMissing = tracker.isDataMissing;
return (
<div className="flex flex-col gap-1.5">
@@ -95,95 +81,44 @@ export function Tracker({
</TooltipProvider>
) : null}
</div>
- <p className="text-muted-foreground shrink-0 font-light">{uptime}</p>
+ {!isMissing ? (
+ <p className="text-muted-foreground shrink-0 font-light">{uptime}%</p>
+ ) : null}
</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}
- />
- );
+ {tracker.days.map((props, i) => {
+ return <Bar key={i} {...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>{tracker.days.length - 1} days ago</p>
<p>Today</p>
</div>
</div>
);
}
-type BarProps = Monitor & { blacklist?: string } & Pick<
- TrackerProps,
- "reports" | "incidents"
- > & {
- className?: string;
- };
+type BarProps = OSTracker["days"][number] & {
+ className?: string;
+};
export const Bar = ({
count,
ok,
day,
+ variant,
+ label,
blacklist,
- reports,
+ statusReports,
incidents,
className,
}: 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 rootClassName = tracker({
- report: reports && reports.length > 0 ? 30 : undefined,
+ report: statusReports && statusReports.length > 0 ? 30 : undefined,
variant: blacklist ? "blacklist" : variant,
});
@@ -212,7 +147,7 @@ export const Bar = ({
<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">
+ <p className="text-muted-foreground flex-shrink-0">
{format(new Date(day), "MMM d")}
</p>
</div>
@@ -226,10 +161,10 @@ export const Bar = ({
</div>
</div>
</div>
- {reports && reports.length > 0 ? (
+ {statusReports && statusReports.length > 0 ? (
<>
<Separator className="my-1.5" />
- <StatusReportList reports={reports} />
+ <StatusReportList reports={statusReports} />
</>
) : null}
{incidents && incidents.length > 0 ? (
@@ -268,9 +203,10 @@ export function DowntimeText({
incidents,
day,
}: {
- incidents: Incidents;
+ incidents: Incident[];
day: string; // TODO: use Date
}) {
+ // TODO: MOVE INTO TRACKER CLASS?
const startOfDayDate = startOfDay(new Date(day));
const endOfDayDate = endOfDay(new Date(day));
@@ -280,7 +216,7 @@ export function DowntimeText({
if (!startedAt) return 0;
if (!resolvedAt)
return (
- endOfDayDate.getTime() -
+ Math.min(endOfDayDate.getTime(), new Date().getTime()) -
Math.max(startOfDayDate.getTime(), startedAt.getTime())
);
return (
diff --git a/apps/web/src/lib/tracker.ts b/apps/web/src/lib/tracker.ts
deleted file mode 100644
index d0b295b0d..000000000
--- a/apps/web/src/lib/tracker.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import type { Monitor, Ping } from "@openstatus/tinybird";
-
-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 getStatusByRatio = (ratio: number): GetStatusReturnType => {
- if (isNaN(ratio))
- return {
- label: "Missing",
- variant: "empty",
- };
- if (ratio >= 0.98)
- return {
- label: "Operational",
- variant: "up",
- };
- if (ratio >= 0.5)
- return {
- label: "Degraded",
- variant: "degraded",
- };
- return {
- label: "Downtime",
- variant: "down",
- };
-};
-
-// TODO: move into Class component sharing the same `data`
-
-/**
- * equal days - fixes issue with daylight saving
- * @param date1
- * @param date2
- * @returns
- */
-export function areDatesEqualByDayMonthYear(date1: Date, date2: Date) {
- date1.setDate(date1.getDate());
- date1.setHours(0, 0, 0, 0);
-
- date2.setDate(date2.getDate());
- date2.setHours(0, 0, 0, 0);
-
- return date1.toUTCString() === date2.toUTCString();
-}
-
-export function addBlackListInfo(data: Monitor[]) {
- return data.map((monitor) => {
- const blacklist = isInBlacklist(new Date(monitor.day).getTime());
- return { ...monitor, blacklist };
- });
-}
-
-export function getTotalUptime(data: { ok: number; count: number }[]) {
- const reducedData = data.reduce(
- (prev, curr) => {
- prev.ok += curr.ok;
- prev.count += curr.count;
- return prev;
- },
- {
- count: 0,
- ok: 0,
- },
- );
- return reducedData;
-}
-
-export function getTotalUptimeString(data: { ok: number; count: number }[]) {
- const reducedData = getTotalUptime(data);
- const uptime = (reducedData.ok / reducedData.count) * 100;
-
- if (isNaN(uptime)) return "";
-
- return `${uptime.toFixed(2)}% uptime`;
-}
-
-export function isInBlacklist(timestamp: number) {
- const el = Object.keys(blacklistDates).find((date) =>
- areDatesEqualByDayMonthYear(new Date(date), new Date(timestamp)),
- );
- return el ? blacklistDates[el] : undefined;
-}
-
-/**
- * Calculate the overall status of a page based on all the monitor data
- */
-export function calcStatus(data: Ping[][]) {
- const { count, ok } = data.flat(1).reduce(
- (prev, curr) => {
- if (!curr.statusCode) return prev; // TODO: handle this better
- const isOk = curr.statusCode <= 299 && curr.statusCode >= 200;
- return { count: prev.count + 1, ok: prev.ok + (isOk ? 1 : 0) };
- },
- { count: 0, ok: 0 },
- );
- const ratio = ok / count;
- if (isNaN(ratio)) return getStatusByRatio(1); // outsmart caching issue
- return getStatusByRatio(ratio);
-}
-
-/**
- * Blacklist dates where we had issues with data collection
- */
-export const blacklistDates: Record<string, string> = {
- "Fri Aug 25 2023":
- "OpenStatus faced issues between 24.08. and 27.08., preventing data collection.",
- "Sat Aug 26 2023":
- "OpenStatus faced issues between 24.08. and 27.08., preventing data collection.",
- "Wed Oct 18 2023":
- "OpenStatus migrated from Vercel to Fly to improve the performance of the checker.",
-};
diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.ts
index bea28c54b..a6212698e 100644
--- a/apps/web/tailwind.config.ts
+++ b/apps/web/tailwind.config.ts
@@ -14,6 +14,7 @@ module.exports = {
// our vercel integration
"../../packages/integrations/**/*.{ts,tsx}",
"../../packages/ui/**/*.{ts,tsx}",
+ "../../packages/tracker/**/*.{ts,tsx}",
"./node_modules/@openstatus/react/**/*.{js,ts,jsx,tsx}",
],
theme: {
diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.ts
index 10006635e..9de7cfde6 100644
--- a/packages/api/src/router/incident.ts
+++ b/packages/api/src/router/incident.ts
@@ -6,7 +6,8 @@ import { selectIncidentSchema } from "@openstatus/db/src/schema";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const incidentRouter = createTRPCRouter({
- getAllIncidents: protectedProcedure
+ // TODO: rename getIncidentsByWorkspace to make it consistent with the other methods
+ getIncidentsByWorkspace: protectedProcedure
.output(z.array(selectIncidentSchema))
.query(async (opts) => {
const result = await opts.ctx.db
diff --git a/packages/db/src/schema/shared.ts b/packages/db/src/schema/shared.ts
index ca574418b..3478347a4 100644
--- a/packages/db/src/schema/shared.ts
+++ b/packages/db/src/schema/shared.ts
@@ -18,43 +18,29 @@ export const selectPublicMonitorSchema = selectMonitorSchema.omit({
method: true,
});
-export const selectStatusReportPageSchema = z.array(
- selectStatusReportSchema.extend({
- statusReportUpdates: z.array(selectStatusReportUpdateSchema).default([]),
- monitorsToStatusReports: z
- .array(
- z.object({
- monitorId: z.number(),
- statusReportId: z.number(),
- monitor: selectPublicMonitorSchema,
- }),
- )
- .default([]),
- }),
-);
+export const selectStatusReportPageSchema = selectStatusReportSchema.extend({
+ statusReportUpdates: z.array(selectStatusReportUpdateSchema).default([]),
+ monitorsToStatusReports: z
+ .array(
+ z.object({
+ monitorId: z.number(),
+ statusReportId: z.number(),
+ monitor: selectPublicMonitorSchema,
+ }),
+ )
+ .default([]),
+});
+
export const selectPageSchemaWithRelation = selectPageSchema.extend({
monitors: z.array(selectMonitorSchema),
- statusReports: selectStatusReportPageSchema,
+ statusReports: z.array(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,
+ statusReports: z.array(selectStatusReportPageSchema),
+ incidents: z.array(selectIncidentSchema),
workspacePlan: workspacePlanSchema
.nullable()
.default("free")
@@ -72,3 +58,8 @@ export const selectPublicStatusReportSchemaWithRelation =
.default([]),
statusReportUpdates: z.array(selectStatusReportUpdateSchema),
});
+
+export type StatusReportWithUpdates = z.infer<
+ typeof selectStatusReportPageSchema
+>;
+export type PublicMonitor = z.infer<typeof selectPublicMonitorSchema>;
diff --git a/packages/tinybird/src/client.ts b/packages/tinybird/src/client.ts
index 93ad9ebc1..99255bc4a 100644
--- a/packages/tinybird/src/client.ts
+++ b/packages/tinybird/src/client.ts
@@ -28,6 +28,8 @@ export const publishPingResponse = tb.buildIngestEndpoint({
event: tbIngestPingResponse,
});
+// TODO: add longer cache for NODE_ENV === "development"
+
export function getResponseList(tb: Tinybird) {
return tb.buildPipe({
pipe: "response_list__v2",
diff --git a/packages/tracker/README.md b/packages/tracker/README.md
new file mode 100644
index 000000000..f1146e40a
--- /dev/null
+++ b/packages/tracker/README.md
@@ -0,0 +1,9 @@
+TODO: Update the different component/files to use the package as source of
+truth!
+
+- [x] public/status
+- [ ] package/react dev deps
+- [x] `status-check` on status page
+- [x] tracker `bar` on status page
+- [x] og image api `status-check`
+- [x] monitor (overview) dasboard
diff --git a/packages/tracker/package.json b/packages/tracker/package.json
new file mode 100644
index 000000000..e63aa8426
--- /dev/null
+++ b/packages/tracker/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "@openstatus/tracker",
+ "version": "1.0.0",
+ "description": "",
+ "main": "src/index.ts",
+ "scripts": {},
+ "dependencies": {
+ "@openstatus/db": "workspace:*",
+ "@openstatus/tinybird": "workspace:*",
+ "zod": "3.22.2"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "typescript": "5.2.2"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC"
+}
diff --git a/packages/tracker/src/blacklist.ts b/packages/tracker/src/blacklist.ts
new file mode 100644
index 000000000..2dd4ab898
--- /dev/null
+++ b/packages/tracker/src/blacklist.ts
@@ -0,0 +1,20 @@
+import { isSameDay } from "./utils";
+
+/**
+ * Blacklist dates where we had issues with data collection
+ */
+export const blacklistDates: Record<string, string> = {
+ "Fri Aug 25 2023":
+ "OpenStatus faced issues between 24.08. and 27.08., preventing data collection.",
+ "Sat Aug 26 2023":
+ "OpenStatus faced issues between 24.08. and 27.08., preventing data collection.",
+ "Wed Oct 18 2023":
+ "OpenStatus migrated from Vercel to Fly to improve the performance of the checker.",
+};
+
+export function isInBlacklist(day: Date) {
+ const el = Object.keys(blacklistDates).find((date) =>
+ isSameDay(new Date(date), day),
+ );
+ return el ? blacklistDates[el] : undefined;
+}
diff --git a/packages/tracker/src/config.ts b/packages/tracker/src/config.ts
new file mode 100644
index 000000000..175098405
--- /dev/null
+++ b/packages/tracker/src/config.ts
@@ -0,0 +1,49 @@
+import type { StatusDetails, StatusVariant } from "./types";
+import { Status } from "./types";
+
+export const statusDetails: Record<Status, StatusDetails> = {
+ [Status.Operational]: {
+ long: "All Systems Operational",
+ short: "Operational",
+ variant: "up",
+ },
+ [Status.DegradedPerformance]: {
+ long: "Degraded Performance",
+ short: "Degraded",
+ variant: "degraded",
+ },
+ [Status.PartialOutage]: {
+ long: "Partial Outage",
+ short: "Outage",
+ variant: "down",
+ },
+ [Status.MajorOutage]: {
+ long: "Major Outage",
+ short: "Outage",
+ variant: "down",
+ },
+ [Status.UnderMaintenance]: {
+ long: "Under Maintenance",
+ short: "Maintenance",
+ variant: "empty",
+ },
+ [Status.Unknown]: {
+ long: "Unknown",
+ short: "Unknown",
+ variant: "empty",
+ },
+ [Status.Incident]: {
+ long: "Downtime",
+ short: "Downtime",
+ variant: "incident",
+ },
+};
+
+// REMINDER: add `@openstatus/tracker/src/**/*.ts into tailwindcss content prop */
+export const classNames: Record<StatusVariant, string> = {
+ up: "bg-green-500/90 data-[state=open]:bg-green-500 border-green-500",
+ degraded: "bg-amber-500/90 data-[state=open]:bg-amber-500 border-amber-500",
+ down: "bg-red-500/90 data-[state=open]:bg-red-500 border-red-500",
+ empty: "bg-muted-foreground/20 data-[state=open]:bg-muted-foreground/30",
+ incident: "bg-red-500/90 data-[state=open]:bg-red-500 border-red-500",
+};
diff --git a/packages/tracker/src/index.ts b/packages/tracker/src/index.ts
new file mode 100644
index 000000000..57a6ca030
--- /dev/null
+++ b/packages/tracker/src/index.ts
@@ -0,0 +1,3 @@
+export * from "./tracker";
+export * from "./types";
+export * from "./config";
diff --git a/packages/tracker/src/mock.ts b/packages/tracker/src/mock.ts
new file mode 100644
index 000000000..5f338e46b
--- /dev/null
+++ b/packages/tracker/src/mock.ts
@@ -0,0 +1,55 @@
+import type { Monitor } from "@openstatus/tinybird";
+
+import { Tracker } from "./tracker";
+
+export const mockMonitor: Monitor[] = [
+ { day: "2024-02-21 00:00:00", count: 762, ok: 762 },
+ { day: "2024-02-20 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-19 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-18 00:00:00", count: 834, ok: 834 },
+ { day: "2024-02-17 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-16 00:00:00", count: 863, ok: 863 },
+ { day: "2024-02-15 00:00:00", count: 862, ok: 862 },
+ { day: "2024-02-14 00:00:00", count: 876, ok: 876 },
+ { day: "2024-02-13 00:00:00", count: 876, ok: 876 },
+ { day: "2024-02-12 00:00:00", count: 882, ok: 882 },
+ { day: "2024-02-11 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-10 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-09 00:00:00", count: 846, ok: 846 },
+ { day: "2024-02-08 00:00:00", count: 870, ok: 870 },
+ { day: "2024-02-07 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-06 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-05 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-04 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-03 00:00:00", count: 858, ok: 858 },
+ { day: "2024-02-02 00:00:00", count: 864, ok: 864 },
+ { day: "2024-02-01 00:00:00", count: 870, ok: 870 },
+ { day: "2024-01-31 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-30 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-29 00:00:00", count: 859, ok: 859 },
+ { day: "2024-01-28 00:00:00", count: 860, ok: 860 },
+ { day: "2024-01-27 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-26 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-25 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-24 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-23 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-22 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-21 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-20 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-19 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-18 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-17 00:00:00", count: 863, ok: 862 },
+ { day: "2024-01-16 00:00:00", count: 795, ok: 795 },
+ { day: "2024-01-15 00:00:00", count: 846, ok: 846 },
+ { day: "2024-01-14 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-13 00:00:00", count: 852, ok: 852 },
+ { day: "2024-01-12 00:00:00", count: 864, ok: 857 },
+ { day: "2024-01-11 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-10 00:00:00", count: 865, ok: 864 },
+ { day: "2024-01-09 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-08 00:00:00", count: 864, ok: 864 },
+ { day: "2024-01-07 00:00:00", count: 671, ok: 671 },
+];
+
+const tracker = new Tracker({ data: mockMonitor });
+console.log(tracker.totalUptime);
diff --git a/packages/tracker/src/tracker.ts b/packages/tracker/src/tracker.ts
new file mode 100644
index 000000000..8984f3c7d
--- /dev/null
+++ b/packages/tracker/src/tracker.ts
@@ -0,0 +1,187 @@
+import type {
+ Incident,
+ StatusReport,
+ StatusReportUpdate,
+} from "@openstatus/db/src/schema";
+import type { Monitor } from "@openstatus/tinybird";
+
+import { isInBlacklist } from "./blacklist";
+import { classNames, statusDetails } from "./config";
+import type { StatusDetails, StatusVariant } from "./types";
+import { Status } from "./types";
+import { endOfDay, isSameDay, startOfDay } from "./utils";
+
+type Monitors = Monitor[];
+type StatusReports = (StatusReport & {
+ statusReportUpdates?: StatusReportUpdate[];
+})[];
+type Incidents = Incident[];
+
+/**
+ * Tracker Class is supposed to handle the data and calculate from a single monitor.
+ * But we use it to handle the StatusCheck as well (with no data for a single monitor).
+ * We can create Inheritence to handle the StatusCheck and Monitor separately and even
+ * StatusPage with multiple Monitors.
+ */
+export class Tracker {
+ private data: Monitors = [];
+ private statusReports: StatusReports = [];
+ private incidents: Incidents = [];
+
+ constructor(arg: {
+ data?: Monitors;
+ statusReports?: StatusReports;
+ incidents?: Incidents;
+ }) {
+ this.data = arg.data || []; // TODO: use another Class to handle a single Day
+ this.statusReports = arg.statusReports || [];
+ this.incidents = arg.incidents || [];
+ }
+
+ private calculateUptime(data: { ok: number; count: number }[]) {
+ const { count, ok } = this.aggregatedData(data);
+ if (count === 0) return 100; // starting with 100% uptime
+ return Math.round((ok / count) * 10_000) / 100; // round to 2 decimal places
+ }
+
+ private aggregatedData(data: { ok: number; count: number }[]) {
+ return data.reduce(
+ (prev, curr) => {
+ prev.ok += curr.ok;
+ prev.count += curr.count;
+ return prev;
+ },
+ { count: 0, ok: 0 },
+ );
+ }
+
+ get isDataMissing() {
+ const { count } = this.aggregatedData(this.data);
+ return count === 0;
+ }
+
+ private calculateUptimeStatus(data: { ok: number; count: number }[]): Status {
+ const uptime = this.calculateUptime(data);
+ if (uptime >= 99.8) return Status.Operational;
+ if (uptime >= 95) return Status.DegradedPerformance;
+ if (uptime > 50) return Status.PartialOutage;
+ return Status.MajorOutage;
+ }
+
+ private isOngoingIncident() {
+ return this.incidents.some((incident) => !incident.resolvedAt);
+ }
+
+ private isOngoingReport() {
+ const resolved: StatusReport["status"][] = ["monitoring", "resolved"];
+ return this.statusReports.some(
+ (report) => !resolved.includes(report.status),
+ );
+ }
+
+ get totalUptime(): number {
+ return this.calculateUptime(this.data);
+ }
+
+ get currentStatus(): Status {
+ if (this.isOngoingReport()) return Status.DegradedPerformance;
+ if (this.isOngoingIncident()) return Status.Incident;
+ return this.calculateUptimeStatus(this.data);
+ }
+
+ get currentVariant(): StatusVariant {
+ return statusDetails[this.currentStatus].variant;
+ }
+
+ get currentDetails(): StatusDetails {
+ return statusDetails[this.currentStatus];
+ }
+
+ get currentClassName(): string {
+ return classNames[this.currentVariant];
+ }
+
+ // HACK: this is a temporary solution to get the incidents
+ private getIncidentsByDay(day: Date): Incidents {
+ const incidents = this.incidents?.filter((incident) => {
+ const { startedAt, resolvedAt } = incident;
+ const eod = endOfDay(day);
+ const sod = startOfDay(day);
+
+ if (!startedAt) return false; // not started
+
+ const hasStartedAfterEndOfDay = startedAt.getTime() >= eod.getTime();
+
+ if (hasStartedAfterEndOfDay) return false;
+
+ 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;
+
+ return false;
+ });
+
+ return incidents;
+ }
+
+ // HACK: this is a temporary solution to get the status reports
+ private getStatusReportsByDay(props: Monitor): StatusReports {
+ const statusReports = this.statusReports?.filter((report) => {
+ const firstStatusReportUpdate = report?.statusReportUpdates?.sort(
+ (a, b) => a.date.getTime() - b.date.getTime(),
+ )?.[0];
+
+ if (!firstStatusReportUpdate) return false;
+
+ const day = new Date(props.day);
+ return isSameDay(firstStatusReportUpdate.date, day);
+ });
+ return statusReports;
+ }
+
+ // TODO: it would be great to create a class to handle a single day
+ // FIXME: will be always generated on each tracker.days call - needs to be in the constructor?
+ get days() {
+ const data = this.data.map((props) => {
+ const day = new Date(props.day);
+ const blacklist = isInBlacklist(day);
+ const incidents = this.getIncidentsByDay(day);
+ const statusReports = this.getStatusReportsByDay(props);
+
+ const isMissingData = props.count === 0;
+
+ // FIXME:
+ const status = incidents.length
+ ? Status.Incident
+ : isMissingData
+ ? Status.Unknown
+ : this.calculateUptimeStatus([props]);
+
+ const variant = statusDetails[status].variant;
+ const label = statusDetails[status].short;
+
+ return {
+ ...props,
+ blacklist,
+ incidents,
+ statusReports,
+ status,
+ variant,
+ label: isMissingData ? "Missing" : label,
+ };
+ });
+ return data;
+ }
+
+ get toString() {
+ return statusDetails[this.currentStatus].short;
+ }
+}
diff --git a/packages/tracker/src/types.ts b/packages/tracker/src/types.ts
new file mode 100644
index 000000000..87060d450
--- /dev/null
+++ b/packages/tracker/src/types.ts
@@ -0,0 +1,33 @@
+import type { Incident, StatusReport } from "@openstatus/db/src/schema";
+
+// DO NOT CHANGE!
+export enum Status {
+ Operational = "operational",
+ DegradedPerformance = "degraded_performance",
+ PartialOutage = "partial_outage",
+ MajorOutage = "major_outage",
+ UnderMaintenance = "under_maintenance", // not used
+ Unknown = "unknown",
+ Incident = "incident",
+}
+
+export type StatusVariant = "up" | "degraded" | "down" | "empty" | "incident";
+
+export type StatusDetails = {
+ long: string;
+ short: string;
+ variant: StatusVariant;
+};
+
+/**
+ * Data used for the `Bar` component within the `Tracker` component.
+ */
+export type TrackerData = {
+ ok: number;
+ count: number;
+ date: Date;
+ incidents: Incident[];
+ statusReports: StatusReport[];
+ status: Status;
+ variant: StatusVariant;
+};
diff --git a/packages/tracker/src/utils.ts b/packages/tracker/src/utils.ts
new file mode 100644
index 000000000..c6e5c4a91
--- /dev/null
+++ b/packages/tracker/src/utils.ts
@@ -0,0 +1,32 @@
+export function endOfDay(date: Date): Date {
+ // Create a new Date object to avoid mutating the original date
+ const newDate = new Date(date);
+
+ // Set hours, minutes, seconds, and milliseconds to end of day
+ newDate.setHours(23, 59, 59, 999);
+
+ return newDate;
+}
+
+export function startOfDay(date: Date): Date {
+ // Create a new Date object to avoid mutating the original date
+ const newDate = new Date(date);
+
+ // Set hours, minutes, seconds, and milliseconds to start of day
+ newDate.setHours(0, 0, 0, 0);
+
+ return newDate;
+}
+
+export function isSameDay(date1: Date, date2: Date) {
+ const newDate1 = new Date(date1);
+ const newDate2 = new Date(date2);
+
+ newDate1.setDate(newDate1.getDate());
+ newDate1.setHours(0, 0, 0, 0);
+
+ newDate2.setDate(newDate2.getDate());
+ newDate2.setHours(0, 0, 0, 0);
+
+ return newDate1.toUTCString() === newDate2.toUTCString();
+}
diff --git a/packages/tracker/tsconfig.json b/packages/tracker/tsconfig.json
new file mode 100644
index 000000000..bded80f35
--- /dev/null
+++ b/packages/tracker/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "@openstatus/tsconfig/base.json",
+ "include": ["src", "*.ts"],
+ "compilerOptions": {
+ "target": "ES2021"
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ce50d1eb8..336200bb3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -67,6 +67,9 @@ importers:
'@openstatus/tinybird':
specifier: workspace:*
version: link:../../packages/tinybird
+ '@openstatus/tracker':
+ specifier: workspace:*
+ version: link:../../packages/tracker
'@openstatus/upstash':
specifier: workspace:*
version: link:../../packages/upstash
@@ -146,6 +149,9 @@ importers:
'@openstatus/tinybird':
specifier: workspace:*
version: link:../../packages/tinybird
+ '@openstatus/tracker':
+ specifier: workspace:*
+ version: link:../../packages/tracker
'@openstatus/ui':
specifier: workspace:*
version: link:../../packages/ui
@@ -739,6 +745,25 @@ importers:
specifier: 5.2.2
version: 5.2.2
+ packages/tracker:
+ dependencies:
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../db
+ '@openstatus/tinybird':
+ specifier: workspace:*
+ version: link:../tinybird
+ zod:
+ specifier: 3.22.2
+ version: 3.22.2
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ typescript:
+ specifier: 5.2.2
+ version: 5.2.2
+
packages/tsconfig: {}
packages/ui:
@@ -1358,6 +1383,10 @@ packages:
peerDependencies:
'@effect-ts/otel-node': '*'
peerDependenciesMeta:
+ '@effect-ts/core':
+ optional: true
+ '@effect-ts/otel':
+ optional: true
'@effect-ts/otel-node':
optional: true
dependencies: