Skip to content

Open-source status page, incident response and uptime monitoring

feat: update response details endpoint and table row collapsable (#710)

Maximilian Kaske8fa8d517562c
diff --git a/apps/web/src/app/api/og/monitor/route.tsx b/apps/web/src/app/api/og/monitor/route.tsx
index f1c44b417..9935dad9d 100644
--- a/apps/web/src/app/api/og/monitor/route.tsx
+++ b/apps/web/src/app/api/og/monitor/route.tsx
@@ -1,12 +1,15 @@
import { ImageResponse } from "next/og";
+import { OSTinybird } from "@openstatus/tinybird";
+
import { DESCRIPTION, TITLE } from "@/app/shared-metadata";
-import { getMonitorListData } from "@/lib/tb";
-import { convertTimezoneToGMT } from "@/lib/timezone";
+import { env } from "@/env";
import { BasicLayout } from "../_components/basic-layout";
import { Tracker } from "../_components/tracker";
import { calSemiBold, interLight, interRegular, SIZE } from "../utils";
+const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+
export const runtime = "edge";
export async function GET(req: Request) {
@@ -26,13 +29,10 @@ export async function GET(req: Request) {
const monitorId =
(searchParams.has("id") && searchParams.get("id")) || undefined;
- const timezone = convertTimezoneToGMT();
-
const data =
(monitorId &&
- (await getMonitorListData({
+ (await tb.endpointStatusPeriod("45d")({
monitorId,
- timezone,
}))) ||
[];
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/_components/response-details.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/_components/response-details.tsx
index cdd8a8e8e..12a3acd5f 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/_components/response-details.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/_components/response-details.tsx
@@ -1,3 +1,4 @@
+import { OSTinybird } from "@openstatus/tinybird";
import type { ResponseDetailsParams } from "@openstatus/tinybird";
import { RegionInfo } from "@/app/play/checker/[id]/_components/region-info";
@@ -9,10 +10,12 @@ import {
TabsList,
TabsTrigger,
} from "@/components/dashboard/tabs";
-import { getResponseDetailsData } from "@/lib/tb";
+import { env } from "@/env";
+
+const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
export async function ResponseDetails(props: ResponseDetailsParams) {
- const details = await getResponseDetailsData(props);
+ const details = await tb.endpointResponseDetails("45d")(props);
if (!details || details?.length === 0) return null;
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx
new file mode 100644
index 000000000..f1ddbcd34
--- /dev/null
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx
@@ -0,0 +1,91 @@
+// HACK: because the `getRowCanExpand` `renderSubComponent` functions
+// have to be in a Client Component
+
+"use client";
+
+import { Suspense, use } from "react";
+import type { Row } from "@tanstack/react-table";
+
+import type { OSTinybird } from "@openstatus/tinybird";
+
+import { ResponseDetailTabs } from "@/app/play/checker/[id]/_components/response-detail-tabs";
+import { CopyToClipboardButton } from "@/components/dashboard/copy-to-clipboard-button";
+import { columns } from "@/components/data-table/columns";
+import { DataTable } from "@/components/data-table/data-table";
+import { LoadingAnimation } from "@/components/loading-animation";
+import { api } from "@/trpc/client";
+
+// EXAMPLE: get the type of the response of the endpoint
+type T = Awaited<ReturnType<ReturnType<OSTinybird["endpointList"]>>>;
+
+// FIXME: use proper type
+type Monitor = {
+ monitorId: string;
+ url: string;
+ latency: number;
+ region: "ams" | "iad" | "hkg" | "jnb" | "syd" | "gru";
+ statusCode: number | null;
+ timestamp: number;
+ workspaceId: string;
+ cronTimestamp: number | null;
+};
+
+export function DataTableWrapper({ data }: { data: Monitor[] }) {
+ return (
+ <DataTable
+ columns={columns}
+ data={data}
+ getRowCanExpand={() => true}
+ renderSubComponent={renderSubComponent}
+ />
+ );
+}
+
+function renderSubComponent({ row }: { row: Row<Monitor> }) {
+ return (
+ <Suspense
+ fallback={
+ <div className="py-4">
+ <LoadingAnimation variant="inverse" />
+ </div>
+ }
+ >
+ <Details row={row} />
+ </Suspense>
+ );
+}
+
+function Details({ row }: { row: Row<Monitor> }) {
+ const data = use(
+ api.tinybird.responseDetails.query({
+ monitorId: row.original.monitorId,
+ url: row.original.url,
+ region: row.original.region,
+ cronTimestamp: row.original.cronTimestamp || undefined,
+ }),
+ );
+
+ if (!data || data.length === 0) return <p>Something went wrong</p>;
+
+ const first = data?.[0];
+
+ // FIXME: ugly hack
+ const url = new URL(window.location.href.replace("/data", "/details"));
+ url.searchParams.set("monitorId", row.original.monitorId);
+ url.searchParams.set("region", row.original.region);
+ url.searchParams.set("cronTimestamp", String(row.original.cronTimestamp));
+ url.searchParams.set("url", row.original.url);
+
+ return (
+ <div className="relative">
+ <div className="absolute right-0 top-1">
+ <CopyToClipboardButton text={url.toString()} tooltipText="Copy link" />
+ </div>
+ <ResponseDetailTabs
+ timing={first.timing}
+ headers={first.headers}
+ message={first.message}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/layout.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/layout.tsx
index 7356e03e3..765aa40e7 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/layout.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/layout.tsx
@@ -1,16 +1,17 @@
import * as React from "react";
+// replacing intercepting route for expanded table rows
+
export default function DataTableLayout({
- children,
- modal,
+ children, // modal,
}: {
children: React.ReactNode;
- modal: React.ReactNode;
+ // modal: React.ReactNode;
}) {
return (
<>
{children}
- {modal}
+ {/* {modal} */}
</>
);
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/page.tsx
index c0c169a9b..20d018010 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/page.tsx
@@ -4,12 +4,11 @@ import * as z from "zod";
import { OSTinybird } from "@openstatus/tinybird";
-import { columns } from "@/components/data-table/columns";
-import { DataTable } from "@/components/data-table/data-table";
import { env } from "@/env";
import { api } from "@/trpc/server";
import { DatePickerPreset } from "../_components/date-picker-preset";
import { periods } from "../utils";
+import { DataTableWrapper } from "./_components/data-table-wrapper";
const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
@@ -38,7 +37,6 @@ export default async function Page({
return notFound();
}
- // FIXME: the other pipes are missing and mv need to include `timestamp` in the data
const allowedPeriods = ["1h", "1d"] as const;
const period = allowedPeriods.find((i) => i === search.data.period) || "1d";
@@ -54,7 +52,7 @@ export default async function Page({
<div className="flex flex-wrap items-center gap-2 sm:justify-end">
<DatePickerPreset defaultValue={period} values={allowedPeriods} />
</div>
- <DataTable columns={columns} data={data} />
+ <DataTableWrapper data={data} />
</div>
);
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/details/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/details/page.tsx
index 2e0c1c5d3..2767d8822 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/details/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/details/page.tsx
@@ -5,6 +5,7 @@ import { Button } from "@openstatus/ui";
import { flyRegions } from "@openstatus/utils";
import { EmptyState } from "@/components/dashboard/empty-state";
+import { api } from "@/trpc/server";
import { ResponseDetails } from "../_components/response-details";
//
@@ -14,6 +15,7 @@ import { ResponseDetails } from "../_components/response-details";
*/
const searchParamsSchema = z.object({
monitorId: z.string(),
+ url: z.string(),
region: z.enum(flyRegions).optional(),
cronTimestamp: z.coerce.number(),
});
@@ -22,24 +24,34 @@ export default async function Details({
params,
searchParams,
}: {
- params: { id: string };
+ params: { id: string; workspaceSlug: string };
searchParams: { [key: string]: string | string[] | undefined };
}) {
const search = searchParamsSchema.safeParse(searchParams);
- if (!search.success)
- return (
- <EmptyState
- title="No log found"
- description="Seems like we couldn't find what you are looking for."
- icon="alert-triangle"
- action={
- <Button asChild>
- <Link href="./data">Response Logs</Link>
- </Button>
- }
- />
- );
-
- return <ResponseDetails {...search.data} />;
+ if (!search.success) return <PageEmptyState />;
+
+ try {
+ await api.monitor.getMonitorById.query({
+ id: parseInt(search.data.monitorId),
+ });
+ return <ResponseDetails {...search.data} />;
+ } catch (e) {
+ return <PageEmptyState />;
+ }
+}
+
+function PageEmptyState() {
+ return (
+ <EmptyState
+ title="No log found"
+ description="Seems like we couldn't find what you are looking for."
+ icon="alert-triangle"
+ action={
+ <Button asChild>
+ <Link href="./data">Response Logs</Link>
+ </Button>
+ }
+ />
+ );
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/layout.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/layout.tsx
index 7ccc70be5..65f14eb26 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/layout.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/layout.tsx
@@ -29,8 +29,8 @@ export default async function Layout({
<Header
title={monitor.name}
description={
- <div className="text-muted-foreground flex items-center gap-2">
- <span>{monitor.url}</span>
+ <div className="text-muted-foreground flex flex-wrap items-center gap-2">
+ <span className="max-w-xs truncate md:max-w-md">{monitor.url}</span>
<span className="text-muted-foreground/50 text-xs">•</span>
<StatusDotWithTooltip
active={monitor.active}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/_components/chart.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/_components/chart.tsx
index b4c396820..0bcada5c9 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/_components/chart.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/_components/chart.tsx
@@ -1,10 +1,12 @@
"use client";
-import type { CustomTooltipProps } from "@tremor/react";
+import { useState } from "react";
+import type { CustomTooltipProps, EventProps } from "@tremor/react";
import { LineChart } from "@tremor/react";
import type { Region } from "@openstatus/tinybird";
+import { cn } from "@/lib/utils";
import { dataFormatter, regionFormatter } from "./utils";
interface ChartProps {
@@ -13,6 +15,7 @@ interface ChartProps {
}
export function Chart({ data, regions }: ChartProps) {
+ const [value, setValue] = useState<EventProps | null>(null);
return (
<LineChart
data={data}
@@ -38,18 +41,22 @@ export function Chart({ data, regions }: ChartProps) {
"pink",
"emerald",
]}
- onValueChange={(v) => void 0} // that prop makes the chart interactive
+ onValueChange={setValue}
valueFormatter={dataFormatter}
curveType="monotone"
intervalType="equidistantPreserveStart"
- customTooltip={customTooltip}
+ customTooltip={(props) => customTooltip({ ...props, value })}
showAnimation={true}
/>
);
}
-// TBD: add custom tooltip
-const customTooltip = ({ payload, active, label }: CustomTooltipProps) => {
+const customTooltip = ({
+ payload,
+ active,
+ label,
+ value,
+}: CustomTooltipProps & { value: EventProps }) => {
if (!active || !payload) return null;
return (
<div className="rounded-tremor-default text-tremor-default dark:text-dark-tremor-default bg-tremor-background dark:bg-dark-tremor-background shadow-tremor-dropdown border-tremor-border dark:border-dark-tremor-border border p-2">
@@ -59,21 +66,29 @@ const customTooltip = ({ payload, active, label }: CustomTooltipProps) => {
</p>
{payload
.filter((category) => category.type !== undefined) // tremor adds additional data to the payload, we don't want that
- .map((category, idx) => (
- <div key={idx} className="flex flex-1 gap-2">
+ .map((category, idx) => {
+ const isActive = value
+ ? value.categoryClicked === category.dataKey
+ : true;
+ return (
<div
- className={`flex w-1 flex-col bg-${category.color}-500 rounded`}
- />
- <div className="flex w-full justify-between gap-2">
- <p className="text-tremor-content dark:text-dark-tremor-content shrink-0">
- {regionFormatter(category.dataKey as Region)}
- </p>
- <p className="text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis font-mono font-medium">
- {dataFormatter(category.value as number)}
- </p>
+ key={idx}
+ className={cn("flex flex-1 gap-2", !isActive && "opacity-60")}
+ >
+ <div
+ className={`flex w-1 flex-col bg-${category.color}-500 rounded`}
+ />
+ <div className="flex w-full justify-between gap-2">
+ <p className="text-tremor-content dark:text-dark-tremor-content shrink-0">
+ {regionFormatter(category.dataKey as Region)}
+ </p>
+ <p className="text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis font-mono font-medium">
+ {dataFormatter(category.value as number)}
+ </p>
+ </div>
</div>
- </div>
- ))}
+ );
+ })}
</div>
</div>
);
diff --git a/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx b/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx
index dd0866154..b0bbe5afd 100644
--- a/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx
+++ b/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx
@@ -11,21 +11,36 @@ import { ResponseTimingTable } from "./response-timing-table";
export async function ResponseDetailTabs({
timing,
headers,
+ message,
}: {
- timing: Timing;
- headers: Record<string, string>;
+ timing: Timing | null;
+ headers: Record<string, string> | null;
+ message?: string | null;
}) {
return (
<Tabs defaultValue="headers">
<TabsList>
<TabsTrigger value="headers">Headers</TabsTrigger>
<TabsTrigger value="timing">Timing</TabsTrigger>
+ <TabsTrigger value="message" disabled={!message}>
+ Message
+ </TabsTrigger>
</TabsList>
<TabsContent value="headers">
{headers ? <ResponseHeaderTable headers={headers} /> : null}
</TabsContent>
<TabsContent value="timing">
- {timing ? <ResponseTimingTable timing={timing} /> : null}
+ {timing ? <ResponseTimingTable timing={timing} hideInfo /> : null}
+ </TabsContent>
+ <TabsContent value="message">
+ {message ? (
+ <div>
+ <pre className="bg-muted rounded-md p-4 text-sm">{message}</pre>
+ <p className="text-muted-foreground mt-4 text-center text-sm">
+ Response Message
+ </p>
+ </div>
+ ) : null}
</TabsContent>
</Tabs>
);
diff --git a/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx
index 35f012cad..7ac483246 100644
--- a/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx
+++ b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx
@@ -17,7 +17,7 @@ export function ResponseHeaderTable({
}) {
return (
<Table>
- <TableCaption>Response Headers</TableCaption>
+ <TableCaption className="mt-2">Response Headers</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="md:min-w-[200px]">Key</TableHead>
diff --git a/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx b/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx
index 75c0bdd2a..d0b8ee071 100644
--- a/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx
+++ b/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx
@@ -28,7 +28,7 @@ export function ResponseTimingTable({
const timingPhases = getTimingPhases(timing);
return (
<Table>
- <TableCaption>Response Timing</TableCaption>
+ <TableCaption className="mt-2">Response Timing</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="w-[120px] md:w-[150px]">Timing</TableHead>
diff --git a/apps/web/src/app/play/status/_components/status-play.tsx b/apps/web/src/app/play/status/_components/status-play.tsx
index fb3d29dd4..4e7d6f8ed 100644
--- a/apps/web/src/app/play/status/_components/status-play.tsx
+++ b/apps/web/src/app/play/status/_components/status-play.tsx
@@ -1,17 +1,25 @@
-import { Label } from "@openstatus/ui";
+import { OSTinybird } from "@openstatus/tinybird";
import { Shell } from "@/components/dashboard/shell";
import { Tracker } from "@/components/tracker/tracker";
-import { getHomeMonitorListData } from "@/lib/tb";
-import { convertTimezoneToGMT, getRequestHeaderTimezone } from "@/lib/timezone";
+import { env } from "@/env";
+import { getServerTimezoneFormat } from "@/lib/timezone";
import { HeaderPlay } from "../../_components/header-play";
-import { TimezoneCombobox } from "./timezone-combobox";
-export default async function StatusPlay({ timezone }: { timezone?: string }) {
- const requestTimezone = getRequestHeaderTimezone();
- const gmt = convertTimezoneToGMT(timezone);
+const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
- const data = await getHomeMonitorListData({ timezone: gmt });
+export default async function StatusPlay() {
+ const data = await tb.endpointStatusPeriod("45d")(
+ {
+ monitorId: "1",
+ url: "https://www.openstatus.dev",
+ },
+ {
+ revalidate: 600, // 10 minutes
+ },
+ );
+
+ const formattedServerDate = getServerTimezoneFormat();
return (
<Shell>
@@ -23,14 +31,10 @@ export default async function StatusPlay({ timezone }: { timezone?: string }) {
<div className="mx-auto w-full max-w-md">
{data && <Tracker data={data} name="Ping" description="Pong" />}
</div>
- <div className="mt-6 flex justify-start">
- <div className="grid items-center gap-1">
- <Label className="text-muted-foreground text-xs">Timezone</Label>
- <TimezoneCombobox
- defaultValue={timezone || requestTimezone || undefined}
- />
- </div>
- </div>
+ <p className="text-muted-foreground text-center text-sm">
+ {formattedServerDate}
+ </p>
+ {/* REMINDER: more playground component */}
</div>
</Shell>
);
diff --git a/apps/web/src/app/play/status/page.tsx b/apps/web/src/app/play/status/page.tsx
index 40e217f57..d7bffb42e 100644
--- a/apps/web/src/app/play/status/page.tsx
+++ b/apps/web/src/app/play/status/page.tsx
@@ -1,16 +1,8 @@
import type { Metadata } from "next";
-import * as z from "zod";
import { BackButton } from "@/components/layout/back-button";
import StatusPlay from "./_components/status-play";
-/**
- * allowed URL search params
- */
-const searchParamsSchema = z.object({
- timezone: z.string().optional(),
-});
-
export const metadata: Metadata = {
title: "Status Page Preview",
description: "Display your status page with real time data.",
@@ -21,18 +13,13 @@ export const metadata: Metadata = {
},
};
-export default async function PlayPage({
- searchParams,
-}: {
- searchParams: { [key: string]: string | string[] | undefined };
-}) {
- const search = searchParamsSchema.safeParse(searchParams);
- const timezone = search.success ? search.data.timezone : undefined;
+export const revalidate = 600;
+export default async function PlayPage() {
return (
<>
<BackButton href="/" />
- <StatusPlay timezone={timezone} />
+ <StatusPlay />
</>
);
}
diff --git a/apps/web/src/components/dashboard/copy-to-clipboard-button.tsx b/apps/web/src/components/dashboard/copy-to-clipboard-button.tsx
new file mode 100644
index 000000000..f0f6519e9
--- /dev/null
+++ b/apps/web/src/components/dashboard/copy-to-clipboard-button.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import * as React from "react";
+
+import {
+ Button,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui";
+
+import { Icons } from "@/components/icons";
+import { copyToClipboard } from "@/lib/utils";
+
+export function CopyToClipboardButton({
+ text,
+ tooltipText,
+}: {
+ text: string;
+ tooltipText: string;
+}) {
+ const [hasCopied, setHasCopied] = React.useState(false);
+
+ React.useEffect(() => {
+ if (hasCopied) {
+ setTimeout(() => {
+ setHasCopied(false);
+ }, 2000);
+ }
+ }, [hasCopied]);
+
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ onClick={() => {
+ copyToClipboard(text);
+ setHasCopied(true);
+ }}
+ >
+ {!hasCopied ? (
+ <Icons.link className="h-4 w-4" />
+ ) : (
+ <Icons.check className="h-4 w-4" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{tooltipText}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/apps/web/src/components/dashboard/tabs.tsx b/apps/web/src/components/dashboard/tabs.tsx
index 7783abc76..ba04076d0 100644
--- a/apps/web/src/components/dashboard/tabs.tsx
+++ b/apps/web/src/components/dashboard/tabs.tsx
@@ -33,7 +33,7 @@ export function TabsTrigger({
return (
<ShadcnTabsTrigger
className={cn(
- "text-muted-foreground hover:text-primary data-[state=active]:border-b-primary data-[state=active]:text-foreground relative rounded-none border-b-4 border-b-transparent bg-transparent px-4 pb-3 pt-2 shadow-none transition-none data-[state=active]:shadow-none",
+ "text-muted-foreground hover:text-primary data-[state=active]:border-b-primary data-[state=active]:text-foreground relative rounded-none border-b-4 border-b-transparent bg-transparent px-4 pb-3 pt-2 shadow-none transition-none data-[state=active]:bg-transparent data-[state=active]:shadow-none",
className,
)}
{...props}
diff --git a/apps/web/src/components/data-table/columns.tsx b/apps/web/src/components/data-table/columns.tsx
index bc6ab627e..c336bca9b 100644
--- a/apps/web/src/components/data-table/columns.tsx
+++ b/apps/web/src/components/data-table/columns.tsx
@@ -14,7 +14,6 @@ import {
import { regionsDict } from "@openstatus/utils";
import { DataTableColumnHeader } from "./data-table-column-header";
-import { DataTableRowActions } from "./data-table-row-action";
import { DataTableStatusBadge } from "./data-table-status-badge";
export const columns: ColumnDef<Ping>[] = [
@@ -90,14 +89,4 @@ export const columns: ColumnDef<Ping>[] = [
return value.includes(row.getValue(id));
},
},
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
];
diff --git a/apps/web/src/components/data-table/data-table.tsx b/apps/web/src/components/data-table/data-table.tsx
index c512b5589..1e59e4bff 100644
--- a/apps/web/src/components/data-table/data-table.tsx
+++ b/apps/web/src/components/data-table/data-table.tsx
@@ -4,11 +4,14 @@ import * as React from "react";
import type {
ColumnDef,
ColumnFiltersState,
+ ExpandedState,
+ Row,
SortingState,
} from "@tanstack/react-table";
import {
flexRender,
getCoreRowModel,
+ getExpandedRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
@@ -30,17 +33,23 @@ import { DataTableToolbar } from "./data-table-toolbar";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
- // filters?: ColumnFiltersState; could also be an idea
+ renderSubComponent(props: { row: Row<TData> }): React.ReactElement;
+ getRowCanExpand(row: Row<TData>): boolean;
+ autoResetExpanded?: boolean;
}
export function DataTable<TData, TValue>({
columns,
data,
+ renderSubComponent,
+ getRowCanExpand,
+ autoResetExpanded,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[],
);
+ const [expanded, setExpanded] = React.useState<ExpandedState>({});
const table = useReactTable({
data,
@@ -51,9 +60,14 @@ export function DataTable<TData, TValue>({
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
+ onExpandedChange: setExpanded,
+ getExpandedRowModel: getExpandedRowModel(),
+ getRowCanExpand,
+ autoResetExpanded,
state: {
sorting,
columnFilters,
+ expanded,
},
});
@@ -83,19 +97,43 @@ export function DataTable<TData, TValue>({
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
- </TableCell>
- ))}
- </TableRow>
+ <React.Fragment key={row.id}>
+ <TableRow
+ data-state={
+ (row.getIsSelected() || row.getIsExpanded()) && "selected"
+ }
+ onClick={() => {
+ // FIXME: this is a workaround for single row expansion
+ if (row.getIsExpanded()) {
+ row.toggleExpanded();
+ } else {
+ table.resetExpanded();
+ row.toggleExpanded();
+ }
+ }}
+ className="cursor-pointer"
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ {row.getIsExpanded() && (
+ <TableRow
+ data-state="expanded"
+ className="data-[state=expanded]:bg-muted/10 hover:bg-muted/10"
+ >
+ {/* 2nd row is a custom 1 cell row */}
+ <TableCell colSpan={row.getVisibleCells().length}>
+ {renderSubComponent({ row })}
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
))
) : (
<TableRow>
diff --git a/apps/web/src/components/layout/login-button.tsx b/apps/web/src/components/layout/login-button.tsx
new file mode 100644
index 000000000..7b15f15cc
--- /dev/null
+++ b/apps/web/src/components/layout/login-button.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import Link from "next/link";
+import { useUser } from "@clerk/nextjs";
+
+import type { ButtonProps } from "@openstatus/ui";
+import { Button } from "@openstatus/ui";
+
+import { cn } from "@/lib/utils";
+
+export function LoginButton({ className, ...props }: ButtonProps) {
+ const { isSignedIn } = useUser();
+
+ return (
+ <Button asChild className={cn("rounded-full", className)} {...props}>
+ {isSignedIn ? (
+ <Link href="/app">Dashboard</Link>
+ ) : (
+ <Link href="/app/sign-up">Sign Up</Link>
+ )}
+ </Button>
+ );
+}
diff --git a/apps/web/src/components/layout/marketing-header.tsx b/apps/web/src/components/layout/marketing-header.tsx
index df53a3a52..3caa87d06 100644
--- a/apps/web/src/components/layout/marketing-header.tsx
+++ b/apps/web/src/components/layout/marketing-header.tsx
@@ -9,6 +9,7 @@ import { Button } from "@openstatus/ui";
import { marketingPagesConfig } from "@/config/pages";
import { cn } from "@/lib/utils";
import { BrandName } from "./brand-name";
+import { LoginButton } from "./login-button";
import { MarketingMenu } from "./marketing-menu";
interface Props {
@@ -49,13 +50,7 @@ export function MarketingHeader({ className }: Props) {
<div className="block md:hidden">
<MarketingMenu />
</div>
- <Button asChild className="rounded-full">
- {isSignedIn ? (
- <Link href="/app">Dashboard</Link>
- ) : (
- <Link href="/app/sign-up">Sign Up</Link>
- )}
- </Button>
+ <LoginButton />
</div>
</header>
);
diff --git a/apps/web/src/components/layout/marketing-menu.tsx b/apps/web/src/components/layout/marketing-menu.tsx
index 60320804c..c4b5d8325 100644
--- a/apps/web/src/components/layout/marketing-menu.tsx
+++ b/apps/web/src/components/layout/marketing-menu.tsx
@@ -16,6 +16,7 @@ import {
import { marketingPagesConfig } from "@/config/pages";
import { socialsConfig } from "@/config/socials";
import { AppLink } from "./app-link";
+import { LoginButton } from "./login-button";
import { SocialIconButton } from "./social-icon-button";
export function MarketingMenu() {
@@ -61,13 +62,16 @@ export function MarketingMenu() {
);
})}
</ul>
- <ul className="flex gap-2">
- {socialsConfig.map((props, i) => (
- <li key={i}>
- <SocialIconButton {...props} />
- </li>
- ))}
- </ul>
+ <div className="flex justify-between gap-2">
+ <ul className="flex flex-wrap gap-2">
+ {socialsConfig.map((props, i) => (
+ <li key={i}>
+ <SocialIconButton {...props} />
+ </li>
+ ))}
+ </ul>
+ <LoginButton variant="outline" />
+ </div>
</div>
</SheetContent>
</Sheet>
diff --git a/apps/web/src/components/marketing/status-page/tracker-example.tsx b/apps/web/src/components/marketing/status-page/tracker-example.tsx
index 5c6a1162a..5d19d081e 100644
--- a/apps/web/src/components/marketing/status-page/tracker-example.tsx
+++ b/apps/web/src/components/marketing/status-page/tracker-example.tsx
@@ -1,11 +1,13 @@
import { Suspense } from "react";
import Link from "next/link";
+import { OSTinybird } from "@openstatus/tinybird";
import { Button } from "@openstatus/ui";
import { Tracker } from "@/components/tracker/tracker";
-import { getHomeMonitorListData } from "@/lib/tb";
-import { convertTimezoneToGMT } from "@/lib/timezone";
+import { env } from "@/env";
+
+const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
export async function TrackerExample() {
return (
@@ -27,8 +29,16 @@ function ExampleTrackerFallback() {
}
async function ExampleTracker() {
- const gmt = convertTimezoneToGMT();
- const data = await getHomeMonitorListData({ timezone: gmt });
+ const data = await tb.endpointStatusPeriod("45d")(
+ {
+ monitorId: "1",
+ url: "https://www.openstatus.dev",
+ },
+ {
+ revalidate: 600, // 10 minutes
+ },
+ );
+
if (!data) return null;
return <Tracker data={data} name="Ping" description="Pong" />;
}
diff --git a/apps/web/src/components/status-page/monitor.tsx b/apps/web/src/components/status-page/monitor.tsx
index e36dba728..13ea9a10c 100644
--- a/apps/web/src/components/status-page/monitor.tsx
+++ b/apps/web/src/components/status-page/monitor.tsx
@@ -5,10 +5,12 @@ import type {
PublicMonitor,
selectPublicStatusReportSchemaWithRelation,
} from "@openstatus/db/src/schema";
+import { OSTinybird } from "@openstatus/tinybird";
import { Tracker } from "@/components/tracker/tracker";
-import { getMonitorListData } from "@/lib/tb";
-import { convertTimezoneToGMT } from "@/lib/timezone";
+import { env } from "@/env";
+
+const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
export const Monitor = async ({
monitor,
@@ -19,10 +21,8 @@ export const Monitor = async ({
statusReports: z.infer<typeof selectPublicStatusReportSchemaWithRelation>[];
incidents: Incident[];
}) => {
- const gmt = convertTimezoneToGMT();
- const data = await getMonitorListData({
+ const data = await tb.endpointStatusPeriod("45d")({
monitorId: String(monitor.id),
- timezone: gmt,
url: monitor.url,
});
diff --git a/apps/web/src/components/status-page/status-check.tsx b/apps/web/src/components/status-page/status-check.tsx
index 7b8c76005..c4496b0e3 100644
--- a/apps/web/src/components/status-page/status-check.tsx
+++ b/apps/web/src/components/status-page/status-check.tsx
@@ -2,6 +2,7 @@ import type { Incident, StatusReport } from "@openstatus/db/src/schema";
import type { StatusVariant } from "@openstatus/tracker";
import { Tracker } from "@openstatus/tracker";
+import { getServerTimezoneFormat } from "@/lib/timezone";
import { cn } from "@/lib/utils";
import { Icons } from "../icons";
@@ -16,15 +17,20 @@ export async function StatusCheck({
const className = tracker.currentClassName;
const details = tracker.currentDetails;
+ const formattedServerDate = getServerTimezoneFormat();
+
return (
- <div className="flex flex-col items-center gap-2">
+ <div className="flex flex-col items-center gap-3">
<div className="flex items-center gap-3">
<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>
+ <p className="text-muted-foreground text-xs">
+ Status Check <span className="text-muted-foreground/50 text-xs">•</span>{" "}
+ {formattedServerDate}
+ </p>
</div>
);
}
diff --git a/apps/web/src/components/status-page/status-report-list.tsx b/apps/web/src/components/status-page/status-report-list.tsx
index c29755752..4dec40692 100644
--- a/apps/web/src/components/status-page/status-report-list.tsx
+++ b/apps/web/src/components/status-page/status-report-list.tsx
@@ -29,15 +29,21 @@ export const StatusReportList = ({
const params = useParams<{ domain: string }>();
const lastWeek = Date.now() - 1000 * 60 * 60 * 24 * 7;
- function getLastWeeksIncidents() {
+ function getLastWeekOrOpenIncidents() {
return statusReports.filter((incident) => {
- return incident.statusReportUpdates.some(
+ const hasLastWeekReports = incident.statusReportUpdates.some(
(update) => update.date.getTime() > lastWeek,
);
+ const hasOpenIncident = ["identified", "investigating"].includes(
+ incident.status,
+ );
+
+ return hasLastWeekReports || hasOpenIncident;
});
}
- const reports = context === "all" ? statusReports : getLastWeeksIncidents();
+ const reports =
+ context === "all" ? statusReports : getLastWeekOrOpenIncidents();
reports.sort((a, b) => {
if (a.updatedAt == undefined) return 1;
diff --git a/apps/web/src/components/tracker/tracker.tsx b/apps/web/src/components/tracker/tracker.tsx
index 14ca5fbd1..bc0712f8b 100644
--- a/apps/web/src/components/tracker/tracker.tsx
+++ b/apps/web/src/components/tracker/tracker.tsx
@@ -93,7 +93,7 @@ export function Tracker({
</div>
</div>
<div className="text-muted-foreground flex items-center justify-between text-xs font-light">
- <p>{tracker.days.length - 1} days ago</p>
+ <p>{tracker.days.length} days ago</p>
<p>Today</p>
</div>
</div>
diff --git a/apps/web/src/lib/tb.ts b/apps/web/src/lib/tb.ts
index bbac9031b..df3356afb 100644
--- a/apps/web/src/lib/tb.ts
+++ b/apps/web/src/lib/tb.ts
@@ -1,62 +1,11 @@
-import type {
- HomeStatsParams,
- MonitorListParams,
- ResponseDetailsParams,
-} from "@openstatus/tinybird";
-import {
- getHomeMonitorList,
- getHomeStats,
- getMonitorList,
- getResponseDetails,
- Tinybird,
-} from "@openstatus/tinybird";
+import type { HomeStatsParams } from "@openstatus/tinybird";
+import { getHomeStats, Tinybird } from "@openstatus/tinybird";
import { env } from "@/env";
// @depreciated in favor to use the OSTinybird client directly
const tb = new Tinybird({ token: env.TINY_BIRD_API_KEY });
-// TODO: not yet converted to new mv
-export async function getResponseDetailsData(
- props: Partial<ResponseDetailsParams>,
-) {
- try {
- const res = await getResponseDetails(tb)(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- return;
-}
-
-// REMINDER: includes yet timezone
-export async function getMonitorListData(props: MonitorListParams) {
- try {
- const res = await getMonitorList(tb)(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- return;
-}
-
-// REMINDER: includes yet timezone
-export async function getHomeMonitorListData(
- props: Pick<MonitorListParams, "timezone">,
-) {
- try {
- const res = await getHomeMonitorList(tb)({
- monitorId: "1",
- ...props,
- url: "https://www.openstatus.dev",
- });
- return res.data;
- } catch (e) {
- console.error(e);
- }
- return;
-}
-
export async function getHomeStatsData(props: Partial<HomeStatsParams>) {
try {
const res = await getHomeStats(tb)(props);
diff --git a/apps/web/src/lib/timezone.ts b/apps/web/src/lib/timezone.ts
index 31f1d11b0..4d9364d95 100644
--- a/apps/web/src/lib/timezone.ts
+++ b/apps/web/src/lib/timezone.ts
@@ -1,5 +1,5 @@
import { headers } from "next/headers";
-import { getTimezoneOffset } from "date-fns-tz";
+import { format, getTimezoneOffset, zonedTimeToUtc } from "date-fns-tz";
export function getRequestHeaderTimezone() {
const headersList = headers();
@@ -34,6 +34,10 @@ export function convertTimezoneToGMT(defaultTimezone?: string) {
return `Etc/GMT${offset}` as const;
}
+export function getServerTimezoneFormat() {
+ return format(new Date(), "LLL dd, y HH:mm:ss zzz", { timeZone: "UTC" });
+}
+
/**
* All supported browser / node timezones
*/
diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.ts
index d01a2fd59..07d0802ab 100644
--- a/packages/api/src/router/monitor.ts
+++ b/packages/api/src/router/monitor.ts
@@ -127,6 +127,15 @@ export const monitorRouter = createTRPCRouter({
),
)
.get();
+
+ const parsedMonitor = selectMonitorSchema.safeParse(currentMonitor);
+
+ if (!parsedMonitor.success) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "You are not allowed to access the monitor.",
+ });
+ }
return selectMonitorSchema.parse(currentMonitor);
}),
diff --git a/packages/api/src/router/tinybird/index.ts b/packages/api/src/router/tinybird/index.ts
index a6801b34e..225719c42 100644
--- a/packages/api/src/router/tinybird/index.ts
+++ b/packages/api/src/router/tinybird/index.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { flyRegions } from "@openstatus/db/src/schema";
import { OSTinybird } from "@openstatus/tinybird";
import { env } from "../../env";
@@ -20,4 +21,17 @@ export const tinybirdRouter = createTRPCRouter({
.query(async (opts) => {
const workspaceId = String(opts.ctx.workspace.id);
}),
+
+ responseDetails: protectedProcedure
+ .input(
+ z.object({
+ monitorId: z.string().default("").optional(),
+ url: z.string().url().optional(),
+ region: z.enum(flyRegions).optional(),
+ cronTimestamp: z.number().int().optional(),
+ }),
+ )
+ .query(async (opts) => {
+ return await tb.endpointResponseDetails("7d")(opts.input);
+ }),
});
diff --git a/packages/tinybird/datasources/__ttl_45d_all_mv.datasource b/packages/tinybird/datasources/__ttl_45d_all_mv.datasource
new file mode 100644
index 000000000..1e4ed03ec
--- /dev/null
+++ b/packages/tinybird/datasources/__ttl_45d_all_mv.datasource
@@ -0,0 +1,22 @@
+VERSION 0
+
+# Data Source created from Pipe '__ttl_45d_all__v0'
+
+SCHEMA >
+ `time` DateTime,
+ `latency` Int64,
+ `monitorId` String,
+ `region` LowCardinality(String),
+ `statusCode` Nullable(Int16),
+ `timestamp` Int64,
+ `url` String,
+ `workspaceId` String,
+ `cronTimestamp` Int64,
+ `message` Nullable(String),
+ `timing` Nullable(String),
+ `headers` Nullable(String)
+
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, cronTimestamp, time"
+ENGINE_TTL "time + toIntervalDay(45)"
diff --git a/packages/tinybird/datasources/__ttl_7d_all_mv.datasource b/packages/tinybird/datasources/__ttl_7d_all_mv.datasource
new file mode 100644
index 000000000..c024fe107
--- /dev/null
+++ b/packages/tinybird/datasources/__ttl_7d_all_mv.datasource
@@ -0,0 +1,22 @@
+VERSION 0
+
+# Data Source created from Pipe '__ttl_7d_all__v0'
+
+SCHEMA >
+ `time` DateTime,
+ `latency` Int64,
+ `monitorId` String,
+ `region` LowCardinality(String),
+ `statusCode` Nullable(Int16),
+ `timestamp` Int64,
+ `url` String,
+ `workspaceId` String,
+ `cronTimestamp` Int64,
+ `message` Nullable(String),
+ `timing` Nullable(String),
+ `headers` Nullable(String)
+
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, cronTimestamp, time"
+ENGINE_TTL "time + toIntervalDay(7)"
diff --git a/packages/tinybird/pipes/__ttl_45d_all.pipe b/packages/tinybird/pipes/__ttl_45d_all.pipe
new file mode 100644
index 000000000..a24b5c19b
--- /dev/null
+++ b/packages/tinybird/pipes/__ttl_45d_all.pipe
@@ -0,0 +1,11 @@
+VERSION 0
+
+NODE __ttl_45d_all_0
+SQL >
+
+ SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v7
+
+TYPE materialized
+DATASOURCE __ttl_45d_all_mv__v0
+
+
diff --git a/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe b/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe
new file mode 100644
index 000000000..1db5c96c2
--- /dev/null
+++ b/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe
@@ -0,0 +1,17 @@
+VERSION 0
+
+TOKEN "__ttl_45d_all_details_get__v0_endpoint_read_7742" READ
+
+NODE __ttl_45d_all_details_get_0
+SQL >
+
+ %
+ SELECT *
+ from __ttl_45d_all_mv__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1') }}
+ {% if defined(url) %} AND url = {{ String(url) }} {% end %}
+ AND cronTimestamp = {{ Int64(cronTimestamp, 1709477432205) }}
+ AND region = {{ String(region, 'ams') }}
+
+
diff --git a/packages/tinybird/pipes/__ttl_7d_all.pipe b/packages/tinybird/pipes/__ttl_7d_all.pipe
new file mode 100644
index 000000000..365d0710a
--- /dev/null
+++ b/packages/tinybird/pipes/__ttl_7d_all.pipe
@@ -0,0 +1,11 @@
+VERSION 0
+
+NODE __ttl_7d_all_0
+SQL >
+
+ SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v7
+
+TYPE materialized
+DATASOURCE __ttl_7d_all_mv__v0
+
+
diff --git a/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe b/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe
new file mode 100644
index 000000000..61a402fdf
--- /dev/null
+++ b/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe
@@ -0,0 +1,17 @@
+VERSION 0
+
+TOKEN "__ttl_7d_all_details_get__v0_endpoint_read_7052" READ
+
+NODE __ttl_7d_all_details_get_0
+SQL >
+
+ %
+ SELECT *
+ from __ttl_7d_all_mv__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1') }}
+ {% if defined(url) %} AND url = {{ String(url) }} {% end %}
+ AND cronTimestamp = {{ Int64(cronTimestamp, 1709477432205) }}
+ AND region = {{ String(region, 'ams') }}
+
+
diff --git a/packages/tinybird/src/client.ts b/packages/tinybird/src/client.ts
index 5e83b9577..4d2f56455 100644
--- a/packages/tinybird/src/client.ts
+++ b/packages/tinybird/src/client.ts
@@ -4,12 +4,10 @@ import {
tbBuildHomeStats,
tbBuildMonitorList,
tbBuildPublicStatus,
- tbBuildResponseDetails,
tbIngestPingResponse,
tbParameterHomeStats,
tbParameterMonitorList,
tbParameterPublicStatus,
- tbParameterResponseDetails,
} from "./validation";
// REMINDER:
@@ -20,17 +18,6 @@ export const publishPingResponse = tb.buildIngestEndpoint({
event: tbIngestPingResponse,
});
-export function getResponseDetails(tb: Tinybird) {
- return tb.buildPipe({
- pipe: "response_details__v0",
- parameters: tbParameterResponseDetails,
- data: tbBuildResponseDetails,
- opts: {
- cache: "force-cache",
- },
- });
-}
-
export function getMonitorList(tb: Tinybird) {
return tb.buildPipe({
pipe: "status_timezone__v1",
diff --git a/packages/tinybird/src/os-client.ts b/packages/tinybird/src/os-client.ts
index fbb8cf4c5..73901b625 100644
--- a/packages/tinybird/src/os-client.ts
+++ b/packages/tinybird/src/os-client.ts
@@ -5,6 +5,7 @@ import { flyRegions } from "@openstatus/utils";
const MIN_CACHE = 30; // 30s
const DEFAULT_CACHE = 120; // 2min
+const MAX_CACHE = 86400; // 1d
export const latencySchema = z.object({
p50Latency: z.number().int().nullable(),
@@ -130,7 +131,10 @@ export class OSTinybird {
url: z.string().optional(),
});
- return async (props: z.infer<typeof parameters>) => {
+ return async (
+ props: z.infer<typeof parameters>,
+ opts?: { revalidate: number | undefined }, // RETHINK: not the best way to handle it
+ ) => {
try {
const res = await this.tb.buildPipe({
pipe: `__ttl_${period}_count_get__v0`,
@@ -144,7 +148,7 @@ export class OSTinybird {
ok: z.number().default(0),
}),
opts: {
- revalidate: DEFAULT_CACHE,
+ revalidate: opts?.revalidate || DEFAULT_CACHE,
},
})(props);
return res.data;
@@ -210,48 +214,59 @@ export class OSTinybird {
};
}
- endpointResponseDetails() {
- return this.tb.buildPipe({
- pipe: "response_details__v0", // TODO: make it also a bit dynamic to avoid query through too much data
- parameters: z.object({
- monitorId: z.string().default(""),
- url: z.string().url().optional(),
- region: z.enum(flyRegions).optional(),
- cronTimestamp: z.number().int().optional(),
- }),
- data: z.object({
- monitorId: z.string().default(""),
- url: z.string().url().optional(),
- region: z.enum(flyRegions).optional(),
- cronTimestamp: z.number().int().optional(),
- message: z.string().nullable().optional(),
- headers: z
- .string()
- .nullable()
- .optional()
- .transform((val) => {
- if (!val) return null;
- const value = z
- .record(z.string(), z.string())
- .safeParse(JSON.parse(val));
- if (value.success) return value.data;
- return null;
- }),
- timing: z
- .string()
- .nullable()
- .optional()
- .transform((val) => {
- if (!val) return null;
- const value = timingSchema.safeParse(JSON.parse(val));
- if (value.success) return value.data;
- return null;
- }),
- }),
- opts: {
- revalidate: DEFAULT_CACHE,
- },
+ endpointResponseDetails(period: "7d" | "45d") {
+ const parameters = z.object({
+ monitorId: z.string().default("").optional(),
+ url: z.string().url().optional(),
+ region: z.enum(flyRegions).optional(),
+ cronTimestamp: z.number().int().optional(),
});
+
+ return async (props: z.infer<typeof parameters>) => {
+ try {
+ const res = await this.tb.buildPipe({
+ pipe: `__ttl_${period}_all_details_get__v0`, // TODO: make it also a bit dynamic to avoid query through too much data
+ parameters,
+ data: z.object({
+ latency: z.number().int(), // in ms
+ statusCode: z.number().int().nullable().default(null),
+ monitorId: z.string().default(""),
+ url: z.string().url().optional(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int().optional(),
+ message: z.string().nullable().optional(),
+ headers: z
+ .string()
+ .nullable()
+ .optional()
+ .transform((val) => {
+ if (!val) return null;
+ const value = z
+ .record(z.string(), z.string())
+ .safeParse(JSON.parse(val));
+ if (value.success) return value.data;
+ return null;
+ }),
+ timing: z
+ .string()
+ .nullable()
+ .optional()
+ .transform((val) => {
+ if (!val) return null;
+ const value = timingSchema.safeParse(JSON.parse(val));
+ if (value.success) return value.data;
+ return null;
+ }),
+ }),
+ opts: {
+ revalidate: MAX_CACHE,
+ },
+ })(props);
+ return res.data;
+ } catch (e) {
+ console.error(e);
+ }
+ };
}
}