Skip to content

Open-source status page, incident response and uptime monitoring

refactor: tinybird structure (#1070)

Maximilian Kaskee475b2a08d20
diff --git a/apps/server/src/v1/monitors/results/get.ts b/apps/server/src/v1/monitors/results/get.ts
index 2efb42026..099f3d7ae 100644
--- a/apps/server/src/v1/monitors/results/get.ts
+++ b/apps/server/src/v1/monitors/results/get.ts
@@ -11,7 +11,7 @@ import { openApiErrorResponses } from "../../../libs/errors/openapi-error-respon
import type { monitorsApi } from "../index";
import { ParamsSchema, ResultRun } from "../schema";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
const getMonitorStats = createRoute({
method: "get",
@@ -69,15 +69,15 @@ export function registerGetMonitorResult(api: typeof monitorsApi) {
throw new HTTPException(404, { message: "Not Found" });
}
// Fetch result from tb pipe
- const data = await tb.getResultForOnDemandCheckHttp()({
+ const data = await tb.getResultForOnDemandCheckHttp({
monitorId: _monitor.id,
timestamp: _monitorRun.runnedAt?.getTime(),
url: _monitor.url,
});
// return array of results
- if (!data) {
+ if (!data || data.data.length === 0) {
throw new HTTPException(404, { message: "Not Found" });
}
- return c.json(data, 200);
+ return c.json(data.data, 200);
});
}
diff --git a/apps/server/src/v1/monitors/summary/get.ts b/apps/server/src/v1/monitors/summary/get.ts
index 5abceefed..134c53413 100644
--- a/apps/server/src/v1/monitors/summary/get.ts
+++ b/apps/server/src/v1/monitors/summary/get.ts
@@ -12,7 +12,7 @@ import { isoDate } from "../../utils";
import type { monitorsApi } from "../index";
import { ParamsSchema } from "../schema";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
const redis = Redis.fromEnv();
const dailyStatsSchema = z.object({
@@ -82,17 +82,14 @@ export function registerGetMonitorSummary(api: typeof monitorsApi) {
return c.json({ data: cache }, 200);
}
- // FIXME: we should use the OSTinybird client
console.log("fetching from tinybird");
- const res = await tb.endpointStatusPeriod("45d")({
- monitorId: id,
- });
+ const res = await tb.httpStatus45d({ monitorId: id });
- if (res === undefined) {
+ if (!res || res.data.length === 0) {
throw new HTTPException(404, { message: "Not Found" });
}
await redis.set(`${id}-daily-stats`, res, { ex: 600 });
- return c.json({ data: res }, 200);
+ return c.json({ data: res.data }, 200);
});
}
diff --git a/apps/web/src/app/(content)/features/_components/tracker-example.tsx b/apps/web/src/app/(content)/features/_components/tracker-example.tsx
index 08bf5fad2..8410dfe2a 100644
--- a/apps/web/src/app/(content)/features/_components/tracker-example.tsx
+++ b/apps/web/src/app/(content)/features/_components/tracker-example.tsx
@@ -8,7 +8,7 @@ import { mockTrackerData } from "../mock";
export function TrackerWithVisibilityToggle() {
const [visible, setVisible] = useState(true);
return (
- <div className="flex flex-col gap-8 my-auto">
+ <div className="my-auto flex flex-col gap-8">
<div className="items-top flex space-x-2">
<Checkbox
id="visibility"
@@ -18,11 +18,11 @@ export function TrackerWithVisibilityToggle() {
<div className="grid gap-1.5 leading-none">
<label
htmlFor="visibility"
- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ className="font-medium text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Show values
</label>
- <p className="text-sm text-muted-foreground">
+ <p className="text-muted-foreground text-sm">
Share the uptime and number of requests.
</p>
</div>
diff --git a/apps/web/src/app/(content)/features/monitoring/page.tsx b/apps/web/src/app/(content)/features/monitoring/page.tsx
index e26d84879..277d3cc1b 100644
--- a/apps/web/src/app/(content)/features/monitoring/page.tsx
+++ b/apps/web/src/app/(content)/features/monitoring/page.tsx
@@ -8,8 +8,7 @@ import { Chart } from "@/components/monitor-charts/chart";
import { RegionsPreset } from "@/components/monitor-dashboard/region-preset";
import { ResponseDetailTabs } from "@/components/ping-response-analysis/response-detail-tabs";
import { marketingProductPagesConfig } from "@/config/pages";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
-import type { Region } from "@openstatus/tinybird";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
import { Button } from "@openstatus/ui/src/components/button";
import { Skeleton } from "@openstatus/ui/src/components/skeleton";
import { allUnrelateds } from "contentlayer/generated";
diff --git a/apps/web/src/app/_components/event-table.tsx b/apps/web/src/app/_components/event-table.tsx
deleted file mode 100644
index 47217070e..000000000
--- a/apps/web/src/app/_components/event-table.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-"use client";
-
-import { formatDistance } from "date-fns";
-import React from "react";
-
-import type { Ping } from "@openstatus/tinybird";
-import {
- Badge,
- Button,
- Table,
- TableBody,
- TableCaption,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-import { cn } from "@/lib/utils";
-
-export function EventTable({ events }: { events: Ping[] }) {
- const [open, toggle] = React.useReducer((state) => !state, false);
- return (
- <div className="relative max-h-56 overflow-hidden">
- <div className="relative max-h-56 overflow-y-scroll">
- <Table>
- <TableCaption>
- A list of the latest {events.length} pings.
- </TableCaption>
- <TableHeader>
- <TableRow className="sticky top-0">
- <TableHead>Time</TableHead>
- <TableHead>Status</TableHead>
- <TableHead>Latency (ms)</TableHead>
- <TableHead className="text-right">Region</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {events.map((event) => {
- const isOk = event.statusCode === 200;
- return (
- <TableRow key={`${event.timestamp}-${event.region}`}>
- <TableCell className="font-medium">
- {formatDistance(new Date(event.timestamp), new Date(), {
- addSuffix: true,
- includeSeconds: true,
- })}
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
- className={cn(
- "px-2 py-0.5 text-xs",
- isOk
- ? "border-green-500/20 bg-green-500/10"
- : "border-red-500/20 bg-red-500/10",
- )}
- >
- {event.statusCode}
- <div
- className={cn(
- "ml-1 h-1.5 w-1.5 rounded-full bg-foreground",
- isOk ? "bg-green-500" : "bg-red-500",
- )}
- />
- </Badge>
- </TableCell>
- <TableCell className="font-light text-muted-foreground">
- {event.latency}
- </TableCell>
- <TableCell className="truncate text-right text-muted-foreground">
- {event.region}
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- </div>
- {!open && (
- <div className="absolute inset-0 flex items-end justify-center bg-gradient bg-gradient-to-b from-20% from-transparent to-background">
- <Button
- onClick={toggle}
- variant="outline"
- size="sm"
- className="rounded-full backdrop-blur-sm"
- >
- A total of {events.length} events.
- </Button>
- </div>
- )}
- </div>
- );
-}
diff --git a/apps/web/src/app/_components/input-search.tsx b/apps/web/src/app/_components/input-search.tsx
deleted file mode 100644
index e758ca882..000000000
--- a/apps/web/src/app/_components/input-search.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-/// <reference lib="dom" />
-
-"use client";
-
-import { Command as CommandPrimitive, useCommandState } from "cmdk";
-import React, { useEffect, useMemo, useRef, useState } from "react";
-
-import type { Ping } from "@openstatus/tinybird";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandItem,
- CommandList,
-} from "@openstatus/ui";
-
-// TODO: once stable, use the shallow route to store the search params inside of the search params
-
-export function InputSearch({
- events,
- onSearch,
-}: {
- onSearch(value: Record<string, string>): void;
- events: Ping[];
-}) {
- const inputRef = useRef<HTMLInputElement>(null);
- const [open, setOpen] = useState<boolean>(false);
- const [inputValue, setInputValue] = useState<string>("");
- const [currentWord, setCurrentWord] = useState("");
-
- // TODO: check if there is a move efficient way
- useEffect(() => {
- const searchparams = inputValue
- .trim()
- .split(" ")
- .reduce(
- (prev, curr) => {
- const [name, value] = curr.split(":");
- if (value && name && curr !== currentWord) {
- // TODO: support multiple value with value.split(",")
- prev[name] = value;
- }
- return prev;
- },
- {} as Record<string, string>,
- );
- onSearch(searchparams);
- }, [onSearch, inputValue, currentWord]);
-
- // DEFINE YOUR SEARCH PARAMETERS
- const search = useMemo(
- () =>
- events.reduce(
- (prev, curr) => {
- return {
- // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
- ...prev,
- status: [...new Set([curr.statusCode, ...(prev.status || [])])],
- region: [...new Set([curr.region, ...(prev.region || [])])],
- };
- },
- // defaultState
- { limit: [10, 25, 50], status: [], region: [] } as {
- status: (number | null)[];
- limit: number[];
- region: string[];
- },
- ),
- [events],
- );
-
- type SearchKey = keyof typeof search;
-
- return (
- <Command
- className="overflow-visible bg-transparent"
- filter={(value) => {
- if (value.includes(currentWord.toLowerCase())) return 1;
- return 0;
- }}
- >
- <CommandPrimitive.Input
- ref={inputRef}
- value={inputValue}
- onValueChange={setInputValue}
- onKeyDown={(e) => {
- if (e.key === "Escape") inputRef?.current?.blur();
- }}
- onBlur={() => setOpen(false)}
- onFocus={() => setOpen(true)}
- onInput={(e) => {
- const caretPositionStart = e.currentTarget?.selectionStart || -1;
- const inputValue = e.currentTarget?.value || "";
-
- let start = caretPositionStart;
- let end = caretPositionStart;
-
- while (start > 0 && inputValue[start - 1] !== " ") {
- start--;
- }
- while (end < inputValue.length && inputValue[end] !== " ") {
- end++;
- }
-
- const word = inputValue.substring(start, end);
- setCurrentWord(word);
- }}
- placeholder={`${events.length} total logs found...`}
- className="flex-1 rounded-md border border-input bg-transparent px-3 py-2 text-sm outline-none ring-offset-background placeholder:text-muted-foreground focus:ring-2 focus:ring-ring focus:ring-offset-2"
- />
- <div className="relative mt-2">
- {open ? (
- <div className="absolute top-0 z-10 w-full animate-in rounded-md border bg-popover text-popover-foreground shadow-md outline-none">
- <CommandList>
- <CommandGroup className="max-h-64 overflow-auto">
- {Object.keys(search).map((key) => {
- if (
- inputValue.includes(`${key}:`) &&
- !currentWord.includes(`${key}:`)
- )
- return null;
- return (
- <React.Fragment key={key}>
- <CommandItem
- value={key}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onSelect={(value) => {
- setInputValue((prev) => {
- if (currentWord.trim() === "") {
- const input = `${prev}${value}`;
- return `${input}:`;
- }
- // lots of cheat
- const isStarting = currentWord === prev;
- const prefix = isStarting ? "" : " ";
- const input = prev.replace(
- `${prefix}${currentWord}`,
- `${prefix}${value}`,
- );
- return `${input}:`;
- });
- setCurrentWord(`${value}:`);
- }}
- className="group"
- >
- {key}
- <span className="ml-1 hidden truncate text-muted-foreground/90 group-aria-[selected=true]:block">
- {search[key as SearchKey]
- .map((str) => `[${str}]`)
- .join(" ")}
- </span>
- </CommandItem>
- {search[key as SearchKey].map((option) => {
- return (
- <SubItem
- key={option}
- value={`${key}:${option}`}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onSelect={(value) => {
- setInputValue((prev) => {
- const input = prev.replace(currentWord, value);
- return `${input.trim()} `;
- });
- setCurrentWord("");
- }}
- {...{ currentWord }}
- >
- {option}
- </SubItem>
- );
- })}
- </React.Fragment>
- );
- })}
- </CommandGroup>
- <CommandEmpty>No results found.</CommandEmpty>
- </CommandList>
- </div>
- ) : null}
- </div>
- </Command>
- );
-}
-
-interface SubItemProps
- extends React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item> {
- currentWord: string;
-}
-
-const SubItem = ({ currentWord, ...props }: SubItemProps) => {
- const search = useCommandState((state) => state.search);
- if (!search.includes(":") || !currentWord.includes(":")) return null;
- return <CommandItem {...props} />;
-};
diff --git a/apps/web/src/app/_components/table-input-container.tsx b/apps/web/src/app/_components/table-input-container.tsx
deleted file mode 100644
index 7e3e1c7d3..000000000
--- a/apps/web/src/app/_components/table-input-container.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-"use client";
-
-import React from "react";
-
-import type { Ping } from "@openstatus/tinybird";
-
-import { EventTable } from "./event-table";
-import { InputSearch } from "./input-search";
-
-// TODO: once stable, use the shallow route to store the search params inside of the search params
-
-export function TableInputContainer({ events }: { events: Ping[] }) {
- const [search, setSearch] = React.useState<Record<string, string>>({});
-
- const filteredEvents = events
- .filter((event) => {
- if (search?.status && event.statusCode !== Number(search.status)) {
- return false;
- }
- if (search?.region && event.region !== search.region) {
- return false;
- }
- return true;
- })
- .slice(0, search.limit ? Number(search.limit) : 100);
-
- return (
- <>
- <InputSearch events={events} onSearch={setSearch} />
- <EventTable events={filteredEvents} />
- </>
- );
-}
diff --git a/apps/web/src/app/api/checker/test/route.ts b/apps/web/src/app/api/checker/test/route.ts
deleted file mode 100644
index d5fc8d405..000000000
--- a/apps/web/src/app/api/checker/test/route.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-
-import { monitorFlyRegionSchema } from "@openstatus/db/src/schema/constants";
-
-import { checkRegion } from "@/components/ping-response-analysis/utils";
-import { httpPayloadSchema } from "@openstatus/utils";
-import { isAnInvalidTestUrl } from "../utils";
-
-export const runtime = "edge";
-export const preferredRegion = "auto";
-export const dynamic = "force-dynamic";
-export const revalidate = 0;
-
-export function GET() {
- return NextResponse.json({ success: true });
-}
-
-export async function POST(request: Request) {
- try {
- const json = await request.json();
- const _valid = httpPayloadSchema
- .pick({ url: true, method: true, headers: true, body: true })
- .merge(z.object({ region: monitorFlyRegionSchema.default("ams") }))
- .safeParse(json);
-
- if (!_valid.success) {
- return NextResponse.json({ success: false }, { status: 400 });
- }
-
- const { url, region, method, headers, body } = _valid.data;
- // 🧑‍💻 for the smart one who want to create a loop hole
- if (isAnInvalidTestUrl(url)) {
- return NextResponse.json({ success: true }, { status: 200 });
- }
-
- const res = await checkRegion(url, region, { method, headers, body });
-
- return NextResponse.json(res);
- } catch (e) {
- console.error(e);
- return NextResponse.json({ success: false }, { status: 400 });
- }
-}
diff --git a/apps/web/src/app/api/checker/test/tcp/route.ts b/apps/web/src/app/api/checker/test/tcp/route.ts
index df8abd299..56d7004e2 100644
--- a/apps/web/src/app/api/checker/test/tcp/route.ts
+++ b/apps/web/src/app/api/checker/test/tcp/route.ts
@@ -21,6 +21,7 @@ export async function POST(request: Request) {
try {
const json = await request.json();
const _valid = tcpPayload
+ .pick({ url: true })
.merge(z.object({ region: monitorFlyRegionSchema.default("ams") }))
.safeParse(json);
@@ -40,7 +41,7 @@ export async function POST(request: Request) {
}
async function checkTCP(url: string, region: MonitorFlyRegion) {
//
- const res = await fetch(`https://checker.openstatus.dev/ping/tcp/${region}`, {
+ const res = await fetch(`https://checker.openstatus.dev/tcp/${region}`, {
headers: {
Authorization: `Basic ${process.env.CRON_SECRET}`,
"Content-Type": "application/json",
@@ -58,7 +59,6 @@ async function checkTCP(url: string, region: MonitorFlyRegion) {
const data = TCPResponse.safeParse(json);
if (!data.success) {
- console.log(json);
console.error(
`something went wrong with result ${json} request to ${url} error ${data.error.message}`,
);
diff --git a/apps/web/src/app/api/checker/test/tcp/schema.ts b/apps/web/src/app/api/checker/test/tcp/schema.ts
index af234693a..f1b52fdf9 100644
--- a/apps/web/src/app/api/checker/test/tcp/schema.ts
+++ b/apps/web/src/app/api/checker/test/tcp/schema.ts
@@ -12,9 +12,9 @@ export const tcpPayload = z.object({
});
export const TCPResponse = z.object({
- requestId: z.string().optional(),
- workspaceId: z.string(),
- monitorId: z.string(),
+ requestId: z.number().optional(),
+ workspaceId: z.number().optional(),
+ monitorId: z.number().optional(),
timestamp: z.number(),
timing: z.object({
tcpStart: z.number(),
diff --git a/apps/web/src/app/api/og/_components/tracker.tsx b/apps/web/src/app/api/og/_components/tracker.tsx
index 9d3cfc86f..952dbdfb3 100644
--- a/apps/web/src/app/api/og/_components/tracker.tsx
+++ b/apps/web/src/app/api/og/_components/tracker.tsx
@@ -1,9 +1,13 @@
-import type { Monitor } from "@openstatus/tinybird";
import { Tracker as OSTracker, classNames } from "@openstatus/tracker";
+import type { ResponseStatusTracker } from "@/lib/tb";
import { cn, formatDate } from "@/lib/utils";
-export function Tracker({ data }: { data: Monitor[] }) {
+interface TrackerProps {
+ data: ResponseStatusTracker[];
+}
+
+export function Tracker({ data }: TrackerProps) {
const tracker = new OSTracker({ data });
return (
diff --git a/apps/web/src/app/api/og/monitor/route.tsx b/apps/web/src/app/api/og/monitor/route.tsx
index e15facbfa..d4be6f6ad 100644
--- a/apps/web/src/app/api/og/monitor/route.tsx
+++ b/apps/web/src/app/api/og/monitor/route.tsx
@@ -8,7 +8,7 @@ import { BasicLayout } from "../_components/basic-layout";
import { Tracker } from "../_components/tracker";
import { SIZE, calSemiBold, interLight, interRegular } from "../utils";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
export const runtime = "edge";
@@ -29,20 +29,20 @@ export async function GET(req: Request) {
const monitorId =
(searchParams.has("id") && searchParams.get("id")) || undefined;
- const data =
- (monitorId &&
- (await tb.endpointStatusPeriod("45d")({
- monitorId,
- }))) ||
- [];
+ // TODO: we need to pass the monitor type here
+
+ const res = (monitorId &&
+ (await tb.httpStatus45d({
+ monitorId,
+ }))) || { data: [] };
return new ImageResponse(
<BasicLayout
title={title}
description={description}
- tw={data.length === 0 ? "mt-32" : undefined}
+ tw={res.data.length === 0 ? "mt-32" : undefined}
>
- {data.length ? <Tracker data={data} /> : null}
+ {res.data.length ? <Tracker data={res.data} /> : null}
</BasicLayout>,
{
...SIZE,
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 857c2d4ce..e95759374 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
@@ -1,18 +1,15 @@
import Link from "next/link";
-import { OSTinybird } from "@openstatus/tinybird";
import { Button } from "@openstatus/ui/src/components/button";
import { EmptyState } from "@/components/dashboard/empty-state";
import { Limit } from "@/components/dashboard/limit";
import { columns } from "@/components/data-table/monitor/columns";
import { DataTable } from "@/components/data-table/monitor/data-table";
-import { env } from "@/env";
+import { prepareMetricsByPeriod, prepareStatusByPeriod } from "@/lib/tb";
import { api } from "@/trpc/server";
import { searchParamsCache } from "./search-params";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export default async function MonitorPage({
searchParams,
}: {
@@ -46,22 +43,17 @@ export default async function MonitorPage({
// use Suspense and Client call instead?
const monitorsWithData = await Promise.all(
monitors.map(async (monitor) => {
+ const type = monitor.jobType as "http" | "tcp";
const [metrics, data] = await Promise.all([
- tb.endpointMetrics("1d")(
- {
- monitorId: String(monitor.id),
- },
- { cache: "no-store", revalidate: 0 },
- ),
- tb.endpointStatusPeriod("7d")(
- {
- monitorId: String(monitor.id),
- },
- { cache: "no-store", revalidate: 0 },
- ),
+ prepareMetricsByPeriod("1d", type).getData({
+ monitorId: String(monitor.id),
+ }),
+ prepareStatusByPeriod("7d", type).getData({
+ monitorId: String(monitor.id),
+ }),
]);
- const [current] = metrics?.sort((a, b) =>
+ const [current] = metrics.data?.sort((a, b) =>
(a.lastTimestamp || 0) - (b.lastTimestamp || 0) < 0 ? 1 : -1,
) || [undefined];
@@ -80,7 +72,7 @@ export default async function MonitorPage({
return {
monitor,
metrics: current,
- data,
+ data: data.data,
incidents,
maintenances,
tags,
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
index 0bfeb41a8..a1f590bda 100644
--- 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
@@ -11,7 +11,6 @@ import type {
import { Suspense, use } from "react";
import * as assertions from "@openstatus/assertions";
-import type { OSTinybird } from "@openstatus/tinybird";
import { CopyToClipboardButton } from "@/components/dashboard/copy-to-clipboard-button";
import { columns } from "@/components/data-table/columns";
@@ -23,22 +22,17 @@ import { api } from "@/trpc/client";
import type { monitorFlyRegionSchema } from "@openstatus/db/src/schema/constants";
import type { z } from "zod";
-// EXAMPLE: get the type of the response of the endpoint
-// biome-ignore lint/correctness/noUnusedVariables: <explanation>
-type T = Awaited<ReturnType<ReturnType<OSTinybird["endpointList"]>>>;
-
// FIXME: use proper type
export type Monitor = {
+ type: "http" | "tcp";
monitorId: string;
- url: string;
latency: number;
region: z.infer<typeof monitorFlyRegionSchema>;
- statusCode: number | null;
+ statusCode?: number | null;
timestamp: number;
workspaceId: string;
cronTimestamp: number | null;
error: boolean;
- assertions?: string | null;
trigger: Trigger | null;
};
@@ -55,10 +49,14 @@ export function DataTableWrapper({
<DataTable
columns={columns}
data={data}
- getRowCanExpand={() => true}
+ // REMINDER: we currently only support HTTP monitors with more details
+ getRowCanExpand={(row) => row.original.type === "http"}
renderSubComponent={renderSubComponent}
defaultColumnFilters={filters}
defaultPagination={pagination}
+ defaultVisibility={
+ data.length && data[0].type === "tcp" ? { statusCode: false } : {}
+ }
/>
);
}
@@ -77,26 +75,25 @@ function renderSubComponent({ row }: { row: Row<Monitor> }) {
);
}
+// REMINDER: only HTTP monitors have more details
function Details({ row }: { row: Row<Monitor> }) {
const data = use(
- api.tinybird.responseDetails.query({
+ api.tinybird.httpGetMonthly.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>;
+ if (!data.data || data.data.length === 0) return <p>Something went wrong</p>;
- const first = data?.[0];
+ const first = data.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">
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 0296f3f4e..5eec61725 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
@@ -1,16 +1,12 @@
import { notFound } from "next/navigation";
import * as React from "react";
-import { OSTinybird } from "@openstatus/tinybird";
-
import { DatePickerPreset } from "@/components/monitor-dashboard/date-picker-preset";
-import { env } from "@/env";
+import { prepareListByPeriod } from "@/lib/tb";
import { api } from "@/trpc/server";
import { DataTableWrapper } from "./_components/data-table-wrapper";
import { searchParamsCache } from "./search-params";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export default async function Page({
params,
searchParams,
@@ -27,12 +23,17 @@ export default async function Page({
if (!monitor) return notFound();
- const allowedPeriods = ["1h", "1d", "3d", "7d"] as const;
+ const type = monitor.jobType as "http" | "tcp";
+
+ // FIXME: make it dynamic based on the workspace plan
+ const allowedPeriods = ["1d", "7d", "14d"] as const;
const period = allowedPeriods.find((i) => i === search.period) || "1d";
- const data = await tb.endpointList(period)({ monitorId: id });
+ const res = await prepareListByPeriod(period, type).getData({
+ monitorId: id,
+ });
- if (!data) return null;
+ if (!res.data || res.data.length === 0) return null;
return (
<div className="grid gap-4">
@@ -47,7 +48,7 @@ export default async function Page({
</div>
{/* FIXME: we display all the regions even though a user might not have all supported in their plan */}
<DataTableWrapper
- data={data}
+ data={res.data}
filters={[
{ id: "statusCode", value: search.statusCode },
{ id: "region", value: search.regions },
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 c39ef9c89..029fafc40 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
@@ -23,7 +23,7 @@ export default async function Details({
await api.monitor.getMonitorById.query({
id: Number.parseInt(search.monitorId),
});
- return <ResponseDetails {...search} />;
+ return <ResponseDetails type="http" {...search} />;
} catch (_e) {
return <PageEmptyState />;
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/page.tsx
index ef2375e97..bbd4718d2 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/overview/page.tsx
@@ -1,18 +1,20 @@
import { notFound } from "next/navigation";
import * as React from "react";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
-import type { Region } from "@openstatus/tinybird";
-import { OSTinybird } from "@openstatus/tinybird";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
import { Separator } from "@openstatus/ui";
import { CombinedChartWrapper } from "@/components/monitor-charts/combined-chart-wrapper";
import { ButtonReset } from "@/components/monitor-dashboard/button-reset";
import { DatePickerPreset } from "@/components/monitor-dashboard/date-picker-preset";
import { Metrics } from "@/components/monitor-dashboard/metrics";
-import { env } from "@/env";
import { getMinutesByInterval, periods } from "@/lib/monitor/utils";
import { getPreferredSettings } from "@/lib/preferred-settings/server";
+import {
+ prepareMetricByIntervalByPeriod,
+ prepareMetricByRegionByPeriod,
+ prepareMetricsByPeriod,
+} from "@/lib/tb";
import { api } from "@/trpc/server";
import {
DEFAULT_INTERVAL,
@@ -21,8 +23,6 @@ import {
searchParamsCache,
} from "./search-params";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export default async function Page({
params,
searchParams,
@@ -42,6 +42,7 @@ export default async function Page({
if (!monitor) return notFound();
const { period, quantile, interval, regions } = search;
+ const type = monitor.jobType as "http" | "tcp";
// TODO: work it out easier
const intervalMinutes = getMinutesByInterval(interval);
@@ -51,12 +52,14 @@ export default async function Page({
const minutes = isQuantileDisabled ? periodicityMinutes : intervalMinutes;
const [metrics, data, metricsByRegion] = await Promise.all([
- tb.endpointMetrics(period)({ monitorId: id }),
- tb.endpointChart(period)({
+ prepareMetricsByPeriod(period, type).getData({
+ monitorId: id,
+ }),
+ prepareMetricByIntervalByPeriod(period, type).getData({
monitorId: id,
interval: minutes,
}),
- tb.endpointMetricsByRegion(period)({
+ prepareMetricByRegionByPeriod(period, type).getData({
monitorId: id,
}),
]);
@@ -84,17 +87,17 @@ export default async function Page({
<DatePickerPreset defaultValue={period} values={periods} />
{isDirty ? <ButtonReset /> : null}
</div>
- <Metrics metrics={metrics} period={period} showErrorLink />
+ <Metrics metrics={metrics.data} period={period} showErrorLink />
<Separator className="my-8" />
<CombinedChartWrapper
- data={data}
+ data={data.data}
period={period}
quantile={quantile}
interval={interval}
regions={regions.length ? (regions as Region[]) : monitor.regions} // FIXME: not properly reseted after filtered
monitor={monitor}
isQuantileDisabled={isQuantileDisabled}
- metricsByRegion={metricsByRegion}
+ metricsByRegion={metricsByRegion.data}
preferredSettings={preferredSettings}
/>
</div>
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/_components/refresh-widget.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/_components/refresh-widget.tsx
deleted file mode 100644
index 7e05805d3..000000000
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/_components/refresh-widget.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-
-import { Button } from "@openstatus/ui/src/components/button";
-
-import { api } from "@/trpc/client";
-
-// TODO: instead of setInterval, use staleWhileRevalidate method to fetch latest data
-// also fetch data on page focus
-
-export function RefreshWidget({ defaultValue }: { defaultValue?: number }) {
- const [refresh, setRefresh] = useState(false);
- const [value, setValue] = useState(defaultValue);
- const router = useRouter();
-
- useEffect(() => {
- const intervalId = setInterval(async () => {
- if (refresh) return;
- const data = await api.tinybird.lastCronTimestamp.query();
- if (data && data?.length > 0) {
- const { cronTimestamp } = data[0];
- setValue(cronTimestamp);
- if (value && cronTimestamp > value) setRefresh(true);
- }
- }, 30_000);
- return () => {
- clearInterval(intervalId);
- };
- }, [refresh, value]);
-
- if (!refresh) return null;
-
- return (
- <div>
- <Button
- onClick={() => {
- router.refresh();
- setRefresh(false);
- }}
- variant="outline"
- >
- Refresh
- </Button>
- </div>
- );
-}
diff --git a/apps/web/src/app/play/checker/_components/checker-form.tsx b/apps/web/src/app/play/checker/_components/checker-form.tsx
index 396d8003f..b750c2e8b 100644
--- a/apps/web/src/app/play/checker/_components/checker-form.tsx
+++ b/apps/web/src/app/play/checker/_components/checker-form.tsx
@@ -7,9 +7,6 @@ import { useForm } from "react-hook-form";
import * as z from "zod";
import {
- Alert,
- AlertDescription,
- AlertTitle,
Button,
Checkbox,
Form,
@@ -27,7 +24,6 @@ import {
SelectValue,
Table,
TableBody,
- TableCaption,
TableCell,
TableHead,
TableHeader,
@@ -253,13 +249,13 @@ export function CheckerForm({ defaultValues, defaultData }: CheckerFormProps) {
)}
/>
<div className="col-span-full mt-2 sm:col-span-1">
- <Button disabled={isPending} className="h-10 w-full group">
+ <Button disabled={isPending} className="group h-10 w-full">
{isPending ? (
<LoadingAnimation />
) : (
<>
Check{" "}
- <Gauge className="ml-1 h-4 w-4 [&>*:first-child]:transition-transform [&>*:first-child]:origin-[12px_14px] [&>*:first-child]:-rotate-90 [&>*:first-child]:group-hover:rotate-0 [&>*:first-child]:duration-500 [&>*:first-child]:ease-out" />
+ <Gauge className="[&>*:first-child]:-rotate-90 ml-1 h-4 w-4 [&>*:first-child]:origin-[12px_14px] [&>*:first-child]:transition-transform [&>*:first-child]:duration-500 [&>*:first-child]:ease-out [&>*:first-child]:group-hover:rotate-0" />
</>
)}
</Button>
diff --git a/apps/web/src/app/play/checker/api/mock.ts b/apps/web/src/app/play/checker/api/mock.ts
index 3e5950cbd..990d87d51 100644
--- a/apps/web/src/app/play/checker/api/mock.ts
+++ b/apps/web/src/app/play/checker/api/mock.ts
@@ -1,6 +1,6 @@
import type { RegionChecker } from "@/components/ping-response-analysis/utils";
import { wait } from "@/lib/utils";
-import type { Region } from "@openstatus/tinybird";
+import type { Region } from "@openstatus/db/src/schema/constants";
export async function mockCheckRegion(region: Region) {
const response = data.checks.find((check) => check.region === region);
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 6cbbd81d1..3142dd377 100644
--- a/apps/web/src/app/play/status/_components/status-play.tsx
+++ b/apps/web/src/app/play/status/_components/status-play.tsx
@@ -1,5 +1,3 @@
-import { OSTinybird } from "@openstatus/tinybird";
-
import {
CardContainer,
CardDescription,
@@ -9,20 +7,11 @@ import {
} from "@/components/marketing/card";
import { Tracker } from "@/components/tracker/tracker";
import { env } from "@/env";
+import { prepareStatusByPeriod } from "@/lib/tb";
import { getServerTimezoneFormat } from "@/lib/timezone";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export default async function StatusPlay() {
- const data = await tb.endpointStatusPeriod("45d")(
- {
- monitorId: "1",
- },
- {
- revalidate: 600, // 10 minutes
- },
- );
-
+ const res = await prepareStatusByPeriod("45d").getData({ monitorId: "1" });
const formattedServerDate = getServerTimezoneFormat();
return (
@@ -37,7 +26,9 @@ export default async function StatusPlay() {
</CardHeader>
<div className="relative grid gap-4">
<div className="mx-auto w-full max-w-md">
- {data && <Tracker data={data} name="Ping" description="Pong" />}
+ {res.data && (
+ <Tracker data={res.data} name="Ping" description="Pong" />
+ )}
</div>
<p className="text-center text-muted-foreground text-sm">
{formattedServerDate}
diff --git a/apps/web/src/app/public/monitors/[id]/page.tsx b/apps/web/src/app/public/monitors/[id]/page.tsx
index 84ae2b9c0..a30f13566 100644
--- a/apps/web/src/app/public/monitors/[id]/page.tsx
+++ b/apps/web/src/app/public/monitors/[id]/page.tsx
@@ -1,9 +1,7 @@
import { notFound } from "next/navigation";
import * as React from "react";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
-import type { Region } from "@openstatus/tinybird";
-import { OSTinybird } from "@openstatus/tinybird";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
import { Separator } from "@openstatus/ui";
import { Shell } from "@/components/dashboard/shell";
@@ -11,9 +9,13 @@ import { CombinedChartWrapper } from "@/components/monitor-charts/combined-chart
import { ButtonReset } from "@/components/monitor-dashboard/button-reset";
import { DatePickerPreset } from "@/components/monitor-dashboard/date-picker-preset";
import { Metrics } from "@/components/monitor-dashboard/metrics";
-import { env } from "@/env";
import { getMinutesByInterval } from "@/lib/monitor/utils";
import { getPreferredSettings } from "@/lib/preferred-settings/server";
+import {
+ prepareMetricByIntervalByPeriod,
+ prepareMetricByRegionByPeriod,
+ prepareMetricsByPeriod,
+} from "@/lib/tb";
import { api } from "@/trpc/server";
import {
DEFAULT_INTERVAL,
@@ -23,8 +25,6 @@ import {
searchParamsCache,
} from "./search-params";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export default async function Page({
params,
searchParams,
@@ -43,6 +43,7 @@ export default async function Page({
if (!monitor) return notFound();
const { period, quantile, interval, regions } = search;
+ const type = monitor.jobType as "http" | "tcp";
// TODO: work it out easier
const intervalMinutes = getMinutesByInterval(interval);
@@ -52,12 +53,14 @@ export default async function Page({
const minutes = isQuantileDisabled ? periodicityMinutes : intervalMinutes;
const [metrics, data, metricsByRegion] = await Promise.all([
- tb.endpointMetrics(period)({ monitorId: id }),
- await tb.endpointChart(period)({
+ prepareMetricsByPeriod(period, type).getData({
+ monitorId: id,
+ }),
+ prepareMetricByIntervalByPeriod(period, type).getData({
monitorId: id,
interval: minutes,
}),
- tb.endpointMetricsByRegion(period)({
+ prepareMetricByRegionByPeriod(period, type).getData({
monitorId: id,
}),
]);
@@ -90,17 +93,17 @@ export default async function Page({
</div>
</Shell>
<Shell className="grid gap-4">
- <Metrics metrics={metrics} period={period} />
+ <Metrics metrics={metrics.data} period={period} />
<Separator className="my-8" />
<CombinedChartWrapper
- data={data}
+ data={data.data}
period={period}
quantile={quantile}
interval={interval}
regions={regions.length ? (regions as Region[]) : monitor.regions} // FIXME: not properly reseted after filtered
monitor={monitor}
isQuantileDisabled={isQuantileDisabled}
- metricsByRegion={metricsByRegion}
+ metricsByRegion={metricsByRegion.data}
preferredSettings={preferredSettings}
/>
</Shell>
diff --git a/apps/web/src/app/status-page/[domain]/monitors/[id]/page.tsx b/apps/web/src/app/status-page/[domain]/monitors/[id]/page.tsx
index 1c7f353c8..78a2fd352 100644
--- a/apps/web/src/app/status-page/[domain]/monitors/[id]/page.tsx
+++ b/apps/web/src/app/status-page/[domain]/monitors/[id]/page.tsx
@@ -1,9 +1,7 @@
import { notFound } from "next/navigation";
import * as React from "react";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
-import type { Region } from "@openstatus/tinybird";
-import { OSTinybird } from "@openstatus/tinybird";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
import { Separator } from "@openstatus/ui/src/components/separator";
import { Header } from "@/components/dashboard/header";
@@ -11,9 +9,13 @@ import { CombinedChartWrapper } from "@/components/monitor-charts/combined-chart
import { ButtonReset } from "@/components/monitor-dashboard/button-reset";
import { DatePickerPreset } from "@/components/monitor-dashboard/date-picker-preset";
import { Metrics } from "@/components/monitor-dashboard/metrics";
-import { env } from "@/env";
import { getMinutesByInterval } from "@/lib/monitor/utils";
import { getPreferredSettings } from "@/lib/preferred-settings/server";
+import {
+ prepareMetricByIntervalByPeriod,
+ prepareMetricByRegionByPeriod,
+ prepareMetricsByPeriod,
+} from "@/lib/tb";
import { api } from "@/trpc/server";
import {
DEFAULT_INTERVAL,
@@ -23,8 +25,6 @@ import {
searchParamsCache,
} from "./search-params";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export const revalidate = 120;
export default async function Page({
@@ -46,6 +46,7 @@ export default async function Page({
if (!monitor) return notFound();
const { period, quantile, interval, regions } = search;
+ const type = monitor.jobType as "http" | "tcp";
// TODO: work it out easier
const intervalMinutes = getMinutesByInterval(interval);
@@ -55,12 +56,12 @@ export default async function Page({
const minutes = isQuantileDisabled ? periodicityMinutes : intervalMinutes;
const [metrics, data, metricsByRegion] = await Promise.all([
- tb.endpointMetrics(period)({ monitorId: id }),
- tb.endpointChart(period)({
+ prepareMetricsByPeriod(period, type).getData({ monitorId: id }),
+ prepareMetricByIntervalByPeriod(period, type).getData({
monitorId: id,
interval: minutes,
}),
- tb.endpointMetricsByRegion(period)({
+ prepareMetricByRegionByPeriod(period, type).getData({
monitorId: id,
}),
]);
@@ -73,6 +74,8 @@ export default async function Page({
interval !== DEFAULT_INTERVAL ||
flyRegions.length !== regions.length;
+ console.log({ metrics: metrics.data });
+
return (
<div className="relative flex w-full flex-col gap-6">
<Header title={monitor.name} description={monitor.url} />
@@ -80,17 +83,17 @@ export default async function Page({
<DatePickerPreset defaultValue={period} values={periods} />
{isDirty ? <ButtonReset /> : null}
</div>
- <Metrics metrics={metrics} period={period} />
+ <Metrics metrics={metrics.data} period={period} />
<Separator className="my-8" />
<CombinedChartWrapper
- data={data}
+ data={data.data}
period={period}
quantile={quantile}
interval={interval}
regions={regions.length ? (regions as Region[]) : monitor.regions} // FIXME: not properly reseted after filtered
monitor={monitor}
isQuantileDisabled={isQuantileDisabled}
- metricsByRegion={metricsByRegion}
+ metricsByRegion={metricsByRegion.data}
preferredSettings={preferredSettings}
/>
</div>
diff --git a/apps/web/src/app/status-page/[domain]/monitors/[id]/search-params.ts b/apps/web/src/app/status-page/[domain]/monitors/[id]/search-params.ts
index d68907c87..a704e0d3d 100644
--- a/apps/web/src/app/status-page/[domain]/monitors/[id]/search-params.ts
+++ b/apps/web/src/app/status-page/[domain]/monitors/[id]/search-params.ts
@@ -11,7 +11,7 @@ export const DEFAULT_QUANTILE = "p95";
export const DEFAULT_INTERVAL = "30m";
export const DEFAULT_PERIOD = "1d";
-export const periods = ["1d", "7d"] as const;
+export const periods = ["1d", "7d", "14d"] as const;
export const searchParamsParsers = {
statusCode: parseAsInteger,
diff --git a/apps/web/src/app/status-page/[domain]/monitors/page.tsx b/apps/web/src/app/status-page/[domain]/monitors/page.tsx
index beb396ce6..6cefa4465 100644
--- a/apps/web/src/app/status-page/[domain]/monitors/page.tsx
+++ b/apps/web/src/app/status-page/[domain]/monitors/page.tsx
@@ -2,21 +2,18 @@ import { ChevronRight } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";
-import { OSTinybird } from "@openstatus/tinybird";
import { Button } from "@openstatus/ui/src/components/button";
import { EmptyState } from "@/components/dashboard/empty-state";
import { Header } from "@/components/dashboard/header";
import { SimpleChart } from "@/components/monitor-charts/simple-chart";
import { groupDataByTimestamp } from "@/components/monitor-charts/utils";
-import { env } from "@/env";
+import { prepareMetricByIntervalByPeriod } from "@/lib/tb";
import { api } from "@/trpc/server";
import { searchParamsCache } from "./search-params";
// Add loading page
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
-
export const revalidate = 120;
export default async function Page({
@@ -39,8 +36,13 @@ export default async function Page({
publicMonitors.length > 0
? await Promise.all(
publicMonitors?.map(async (monitor) => {
- const data = await tb.endpointChartAllRegions(period)({
+ const type = monitor.jobType as "http" | "tcp";
+ const data = await prepareMetricByIntervalByPeriod(
+ period,
+ type,
+ ).getData({
monitorId: String(monitor.id),
+ interval: 60,
});
return { monitor, data };
@@ -70,12 +72,7 @@ export default async function Page({
<ul className="grid gap-6">
{monitorsWithData?.map(({ monitor, data }) => {
const group =
- data &&
- groupDataByTimestamp(
- data.map((data) => ({ ...data, region: "ams" })),
- period,
- quantile,
- );
+ data.data && groupDataByTimestamp(data.data, period, quantile);
return (
<li key={monitor.id} className="grid gap-2">
<div className="flex w-full min-w-0 items-center justify-between gap-3">
diff --git a/apps/web/src/components/billing/pro-banner.tsx b/apps/web/src/components/billing/pro-banner.tsx
index fe82660d6..5f23398fc 100644
--- a/apps/web/src/components/billing/pro-banner.tsx
+++ b/apps/web/src/components/billing/pro-banner.tsx
@@ -52,7 +52,7 @@ export function ProBanner() {
variant="ghost"
size="icon"
onClick={onClick}
- className="w-7 h-7"
+ className="h-7 w-7"
>
<X className="h-4 w-4" />
</Button>
diff --git a/apps/web/src/components/billing/pro-feature-hover-card.tsx b/apps/web/src/components/billing/pro-feature-hover-card.tsx
index 36728d4e8..087a29554 100644
--- a/apps/web/src/components/billing/pro-feature-hover-card.tsx
+++ b/apps/web/src/components/billing/pro-feature-hover-card.tsx
@@ -37,7 +37,7 @@ export function ProFeatureHoverCard({
<HoverCard openDelay={0} open={open} onOpenChange={setOpen}>
<HoverCardTrigger
onClick={() => setOpen(true)}
- className="opacity-70 cursor-not-allowed relative"
+ className="relative cursor-not-allowed opacity-70"
asChild
>
{children}
diff --git a/apps/web/src/components/data-table/columns.tsx b/apps/web/src/components/data-table/columns.tsx
index 77d97b0dd..6488022b1 100644
--- a/apps/web/src/components/data-table/columns.tsx
+++ b/apps/web/src/components/data-table/columns.tsx
@@ -2,23 +2,30 @@
import type { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
-import * as z from "zod";
+import type * as z from "zod";
-import type { Ping } from "@openstatus/tinybird";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
import { flyRegionsDict } from "@openstatus/utils";
import type { Trigger } from "@/lib/monitor/utils";
+import type { monitorFlyRegionSchema } from "@openstatus/db/src/schema/constants";
import { TriggerIconWithTooltip } from "../monitor/trigger-icon-with-tooltip";
import { DataTableColumnHeader } from "./data-table-column-header";
import { DataTableStatusBadge } from "./data-table-status-badge";
-export const columns: ColumnDef<Ping>[] = [
+export type Check = {
+ type: "http" | "tcp";
+ monitorId: string;
+ latency: number;
+ region: z.infer<typeof monitorFlyRegionSchema>;
+ statusCode?: number | null;
+ timestamp: number;
+ workspaceId: string;
+ cronTimestamp: number | null;
+ error: boolean;
+ trigger: Trigger | null;
+};
+
+export const columns: ColumnDef<Check>[] = [
{
accessorKey: "error",
header: () => null,
@@ -48,28 +55,16 @@ export const columns: ColumnDef<Ping>[] = [
<DataTableColumnHeader column={column} title="Status" />
),
cell: ({ row }) => {
- const unsafe_StatusCode = row.getValue("statusCode");
- const statusCode = z.number().nullable().parse(unsafe_StatusCode);
- const message = row.original.message;
+ const statusCode = row.getValue("statusCode") as
+ | number
+ | null
+ | undefined;
- if (statusCode !== null) {
+ if (statusCode) {
return <DataTableStatusBadge {...{ statusCode }} />;
}
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <DataTableStatusBadge {...{ statusCode }} />
- </TooltipTrigger>
- <TooltipContent>
- <p className="max-w-xs text-muted-foreground sm:max-w-sm">
- {message}
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
+ return <div className="text-muted-foreground">N/A</div>;
},
filterFn: (row, id, value) => {
// get the first digit of the status code
diff --git a/apps/web/src/components/data-table/data-table-row-action.tsx b/apps/web/src/components/data-table/data-table-row-action.tsx
index 363c6e582..3cbb9f475 100644
--- a/apps/web/src/components/data-table/data-table-row-action.tsx
+++ b/apps/web/src/components/data-table/data-table-row-action.tsx
@@ -4,7 +4,6 @@ import type { Row } from "@tanstack/react-table";
import { MoreHorizontal } from "lucide-react";
import Link from "next/link";
-import { tbBuildResponseList } from "@openstatus/tinybird";
import {
Button,
DropdownMenu,
@@ -12,6 +11,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@openstatus/ui";
+import { z } from "zod";
interface DataTableRowActionsProps<TData> {
row: Row<TData>;
@@ -21,7 +21,13 @@ export function DataTableRowActions<TData>({
row,
}: DataTableRowActionsProps<TData>) {
// FIXME: DRY - this is a duplicate of the OSTinybird endpoint
- const ping = tbBuildResponseList.parse(row.original);
+ const ping = z
+ .object({
+ monitorId: z.string(),
+ cronTimestamp: z.number(),
+ region: z.string(),
+ })
+ .parse(row.original);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/apps/web/src/components/data-table/data-table-status-badge.tsx b/apps/web/src/components/data-table/data-table-status-badge.tsx
index f9dd4a546..d178ef53d 100644
--- a/apps/web/src/components/data-table/data-table-status-badge.tsx
+++ b/apps/web/src/components/data-table/data-table-status-badge.tsx
@@ -1,12 +1,11 @@
-import type { Ping } from "@openstatus/tinybird";
import { Badge } from "@openstatus/ui/src/components/badge";
-import { StatusCodeBadge } from "../monitor/status-code-badge";
+import { StatusCodeBadge } from "@/components/monitor/status-code-badge";
export function DataTableStatusBadge({
statusCode,
}: {
- statusCode: Ping["statusCode"];
+ statusCode?: number | null;
}) {
if (!statusCode) {
return <Badge variant="destructive">Error</Badge>;
diff --git a/apps/web/src/components/data-table/data-table-toolbar.tsx b/apps/web/src/components/data-table/data-table-toolbar.tsx
index f9d146c0c..41d6abf02 100644
--- a/apps/web/src/components/data-table/data-table-toolbar.tsx
+++ b/apps/web/src/components/data-table/data-table-toolbar.tsx
@@ -27,7 +27,7 @@ export function DataTableToolbar<TData>({
return (
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-1 flex-wrap items-center gap-2">
- {table.getColumn("statusCode") && (
+ {table.getColumn("statusCode")?.getIsVisible() && (
<DataTableFacetedFilter
column={table.getColumn("statusCode")}
title="Status Code"
diff --git a/apps/web/src/components/data-table/data-table.tsx b/apps/web/src/components/data-table/data-table.tsx
index 9f1e8f076..242efdbb3 100644
--- a/apps/web/src/components/data-table/data-table.tsx
+++ b/apps/web/src/components/data-table/data-table.tsx
@@ -7,6 +7,7 @@ import type {
PaginationState,
Row,
SortingState,
+ VisibilityState,
} from "@tanstack/react-table";
import {
flexRender,
@@ -28,6 +29,7 @@ import {
TableRow,
} from "@openstatus/ui";
+import { cn } from "@/lib/utils";
import { DataTablePagination } from "./data-table-pagination";
import { DataTableToolbar } from "./data-table-toolbar";
@@ -39,6 +41,8 @@ interface DataTableProps<TData, TValue> {
autoResetExpanded?: boolean;
defaultColumnFilters?: ColumnFiltersState;
defaultPagination?: PaginationState;
+ defaultVisibility?: VisibilityState;
+ // allowedPeriods?: Period[]; REMIDNER: disabled unallowed periods
}
export function DataTable<TData, TValue>({
@@ -49,6 +53,7 @@ export function DataTable<TData, TValue>({
autoResetExpanded,
defaultColumnFilters = [],
defaultPagination = { pageIndex: 0, pageSize: 10 },
+ defaultVisibility = {},
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] =
@@ -56,6 +61,8 @@ export function DataTable<TData, TValue>({
const [expanded, setExpanded] = React.useState<ExpandedState>({});
const [pagination, setPagination] =
React.useState<PaginationState>(defaultPagination);
+ const [columnVisibility, setColumnVisibility] =
+ React.useState<VisibilityState>(defaultVisibility);
const table = useReactTable({
data,
@@ -69,6 +76,7 @@ export function DataTable<TData, TValue>({
getFilteredRowModel: getFilteredRowModel(),
onExpandedChange: setExpanded,
getExpandedRowModel: getExpandedRowModel(),
+ onColumnVisibilityChange: setColumnVisibility,
getRowCanExpand,
autoResetExpanded,
state: {
@@ -76,6 +84,7 @@ export function DataTable<TData, TValue>({
columnFilters,
expanded,
pagination,
+ columnVisibility,
},
});
@@ -111,11 +120,12 @@ export function DataTable<TData, TValue>({
(row.getIsSelected() || row.getIsExpanded()) && "selected"
}
onClick={() => {
+ if (!row.getCanExpand()) return;
// REMINDER: this is a workaround for single row expansion
if (!row.getIsExpanded()) table.resetExpanded();
row.toggleExpanded();
}}
- className="cursor-pointer"
+ className={cn(row.getCanExpand() && "cursor-pointer")}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
diff --git a/apps/web/src/components/data-table/monitor/columns.tsx b/apps/web/src/components/data-table/monitor/columns.tsx
index 338906f73..18d935bd6 100644
--- a/apps/web/src/components/data-table/monitor/columns.tsx
+++ b/apps/web/src/components/data-table/monitor/columns.tsx
@@ -10,10 +10,6 @@ import type {
Monitor,
MonitorTag,
} from "@openstatus/db/src/schema";
-import type {
- Monitor as MonitorTracker,
- ResponseTimeMetrics,
-} from "@openstatus/tinybird";
import { Tracker } from "@openstatus/tracker";
import {
Badge,
@@ -29,15 +25,18 @@ import { TagBadgeWithTooltip } from "@/components/monitor/tag-badge-with-tooltip
import { Bar } from "@/components/tracker/tracker";
import { isActiveMaintenance } from "@/lib/maintenances/utils";
+import type { ResponseStatusTracker, ResponseTimeMetrics } from "@/lib/tb";
import { Eye, EyeOff, Radio, View } from "lucide-react";
import type { ReactNode } from "react";
import { DataTableColumnHeader } from "./data-table-column-header";
import { DataTableRowActions } from "./data-table-row-actions";
+// EXAMPLE: get the type of the response of the endpoint
+
export const columns: ColumnDef<{
monitor: Monitor;
metrics?: ResponseTimeMetrics;
- data?: MonitorTracker[];
+ data?: ResponseStatusTracker[];
incidents?: Incident[];
maintenances?: Maintenance[];
tags?: MonitorTag[];
diff --git a/apps/web/src/components/data-table/rum/columns.tsx b/apps/web/src/components/data-table/rum/columns.tsx
deleted file mode 100644
index 4c85c5536..000000000
--- a/apps/web/src/components/data-table/rum/columns.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import Link from "next/link";
-
-import type { responseRumPageQuery } from "@openstatus/tinybird/src/validation";
-import type { z } from "zod";
-
-export const columns: ColumnDef<z.infer<typeof responseRumPageQuery>>[] = [
- {
- accessorKey: "path",
- header: "Page",
- cell: ({ row }) => {
- return (
- <Link
- href={`./rum/overview?path=${encodeURIComponent(row.original.path)}`}
- className="w-8 max-w-8 hover:underline"
- >
- <span className="truncate">{row.getValue("path")}</span>
- </Link>
- );
- },
- },
- {
- accessorKey: "totalSession",
- header: "Total Session",
- cell: ({ row }) => {
- return <>{row.original.totalSession}</>;
- },
- },
- {
- accessorKey: "cls",
- header: "CLS",
- cell: ({ row }) => {
- return (
- <code>{row.original.cls ? row.original.cls.toFixed(2) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "fcp",
- header: "FCP",
- cell: ({ row }) => {
- return (
- <code>{row.original.fcp ? row.original.fcp.toFixed(0) : "-"} </code>
- );
- },
- },
- {
- accessorKey: "inp",
- header: "INP",
- cell: ({ row }) => {
- return (
- <code>{row.original.inp ? row.original.inp.toFixed(0) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "lcp",
- header: "LCP",
- cell: ({ row }) => {
- return (
- <code>{row.original.lcp ? row.original.lcp.toFixed(0) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "ttfb",
- header: "TTFB",
- cell: ({ row }) => {
- return (
- <code>{row.original.ttfb ? row.original.ttfb.toFixed(0) : "-"}</code>
- );
- },
- },
- // {
- // accessorKey: "updatedAt",
- // header: "Last Updated",
- // cell: ({ row }) => {
- // return <span>{formatDate(row.getValue("updatedAt"))}</span>;
- // },
- // },
-];
diff --git a/apps/web/src/components/data-table/rum/data-table.tsx b/apps/web/src/components/data-table/rum/data-table.tsx
deleted file mode 100644
index d7e57ef59..000000000
--- a/apps/web/src/components/data-table/rum/data-table.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import * as React from "react";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <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>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/session/columns.tsx b/apps/web/src/components/data-table/session/columns.tsx
deleted file mode 100644
index 757310f39..000000000
--- a/apps/web/src/components/data-table/session/columns.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import Link from "next/link";
-
-import type { sessionRumPageQuery } from "@openstatus/tinybird/src/validation";
-import type { z } from "zod";
-
-export const columns: ColumnDef<z.infer<typeof sessionRumPageQuery>>[] = [
- {
- accessorKey: "session",
- header: "Session",
- cell: ({ row }) => {
- return <>{row.original.session_id}</>;
- },
- },
- {
- accessorKey: "cls",
- header: "CLS",
- cell: ({ row }) => {
- return (
- <code>{row.original.cls ? row.original.cls.toFixed(2) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "fcp",
- header: "FCP",
- cell: ({ row }) => {
- return (
- <code>{row.original.fcp ? row.original.fcp.toFixed(0) : "-"} </code>
- );
- },
- },
- {
- accessorKey: "inp",
- header: "INP",
- cell: ({ row }) => {
- return (
- <code>{row.original.inp ? row.original.inp.toFixed(0) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "lcp",
- header: "LCP",
- cell: ({ row }) => {
- return (
- <code>{row.original.lcp ? row.original.lcp.toFixed(0) : "-"}</code>
- );
- },
- },
- {
- accessorKey: "ttfb",
- header: "TTFB",
- cell: ({ row }) => {
- return (
- <code>{row.original.ttfb ? row.original.ttfb.toFixed(0) : "-"}</code>
- );
- },
- },
- // {
- // accessorKey: "updatedAt",
- // header: "Last Updated",
- // cell: ({ row }) => {
- // return <span>{formatDate(row.getValue("updatedAt"))}</span>;
- // },
- // },
-];
diff --git a/apps/web/src/components/data-table/session/data-table.tsx b/apps/web/src/components/data-table/session/data-table.tsx
deleted file mode 100644
index d7e57ef59..000000000
--- a/apps/web/src/components/data-table/session/data-table.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import * as React from "react";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <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>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/single-region/columns.tsx b/apps/web/src/components/data-table/single-region/columns.tsx
index 751619346..f78aad31c 100644
--- a/apps/web/src/components/data-table/single-region/columns.tsx
+++ b/apps/web/src/components/data-table/single-region/columns.tsx
@@ -2,7 +2,8 @@
import { SimpleChart } from "@/components/monitor-charts/simple-chart";
import { formatNumber } from "@/components/monitor-dashboard/metrics-card";
-import type { Region, ResponseTimeMetricsByRegion } from "@openstatus/tinybird";
+import type { ResponseTimeMetricsByRegion } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { flyRegionsDict } from "@openstatus/utils";
import type { ColumnDef } from "@tanstack/react-table";
import { DataTableColumnHeader } from "./data-table-column-header";
diff --git a/apps/web/src/components/forms/monitor/form.tsx b/apps/web/src/components/forms/monitor/form.tsx
index 0ad1890ce..58a670e6a 100644
--- a/apps/web/src/components/forms/monitor/form.tsx
+++ b/apps/web/src/components/forms/monitor/form.tsx
@@ -185,8 +185,8 @@ export function MonitorForm({
} = form.getValues();
// FIXME: add support for TCP
- if (jobType !== "http")
- return { error: "Only HTTP tests are supported. Coming soon..." };
+ // if (jobType !== "http")
+ // return { error: "Only HTTP tests are supported. Coming soon..." };
if (
body &&
@@ -201,7 +201,7 @@ export function MonitorForm({
}
}
- const res = await fetch("/api/checker/test", {
+ const res = await fetch(`/api/checker/test/${jobType}`, {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
diff --git a/apps/web/src/components/forms/monitor/select-region.tsx b/apps/web/src/components/forms/monitor/select-region.tsx
index 7e8e04272..fe695c349 100644
--- a/apps/web/src/components/forms/monitor/select-region.tsx
+++ b/apps/web/src/components/forms/monitor/select-region.tsx
@@ -3,7 +3,6 @@
import { Check, ChevronsUpDown, Globe2 } from "lucide-react";
import * as React from "react";
-import type { Region } from "@openstatus/tinybird";
import { Button, type ButtonProps } from "@openstatus/ui/src/components/button";
import {
Command,
@@ -26,7 +25,7 @@ import {
} from "@openstatus/utils";
import { cn } from "@/lib/utils";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
interface SelectRegionProps extends Omit<ButtonProps, "onChange"> {
allowedRegions: Region[];
diff --git a/apps/web/src/components/forms/status-page/section-advanced.tsx b/apps/web/src/components/forms/status-page/section-advanced.tsx
index b2dfc6c8b..6276c0fa7 100644
--- a/apps/web/src/components/forms/status-page/section-advanced.tsx
+++ b/apps/web/src/components/forms/status-page/section-advanced.tsx
@@ -161,7 +161,7 @@ export function SectionAdvanced({ form }: Props) {
</FormItem>
)}
/>
- <div className="grid w-full gap-4 md:grid-rows-2 md:grid-cols-3 md:col-span-full">
+ <div className="grid w-full gap-4 md:col-span-full md:grid-cols-3 md:grid-rows-2">
<SectionHeader
title="Monitor Values Visibility"
description={
@@ -177,12 +177,12 @@ export function SectionAdvanced({ form }: Props) {
}
className="md:col-span-2"
/>
- <div className="group md:row-span-2 flex flex-col justify-center gap-1 border border-dashed rounded-md p-3">
- <div className="flex flex-row gap-2 items-center justify-center text-muted-foreground group-hover:text-foreground">
+ <div className="group flex flex-col justify-center gap-1 rounded-md border border-dashed p-3 md:row-span-2">
+ <div className="flex flex-row items-center justify-center gap-2 text-muted-foreground group-hover:text-foreground">
<MousePointer2 className="h-3 w-3" />
<p className="text-sm">Hover State</p>
</div>
- <div className="max-w-[15rem] mx-auto">
+ <div className="mx-auto max-w-[15rem]">
<BarDescription
label="Operational"
day={new Date().toISOString()}
@@ -190,7 +190,7 @@ export function SectionAdvanced({ form }: Props) {
ok={5569}
showValues={!!form.getValues("showMonitorValues")}
barClassName="bg-status-operational"
- className="md:col-span-1 bg-popover text-popover-foreground rounded-md border p-2 shadow-md"
+ className="rounded-md border bg-popover p-2 text-popover-foreground shadow-md md:col-span-1"
/>
</div>
</div>
diff --git a/apps/web/src/components/layout/header/user-nav.tsx b/apps/web/src/components/layout/header/user-nav.tsx
index 71c752191..c9e3890a4 100644
--- a/apps/web/src/components/layout/header/user-nav.tsx
+++ b/apps/web/src/components/layout/header/user-nav.tsx
@@ -74,8 +74,8 @@ export function UserNav() {
<DropdownMenuGroup>
<DropdownMenuSub>
{/* REMINDER: consider using that the data-state styles as default */}
- <DropdownMenuSubTrigger className="gap-1 [&_svg]:data-[state=open]:text-foreground [&_svg]:data-[highlighted]:text-foreground [&_svg]:text-muted-foreground">
- <div className="w-full flex flex-row items-center justify-between">
+ <DropdownMenuSubTrigger className="gap-1 [&_svg]:text-muted-foreground [&_svg]:data-[highlighted]:text-foreground [&_svg]:data-[state=open]:text-foreground">
+ <div className="flex w-full flex-row items-center justify-between">
<span>Switch theme</span>
<ThemeIcon theme={theme} />
</div>
@@ -88,7 +88,7 @@ export function UserNav() {
key={option}
checked={theme === option}
onClick={() => setTheme(option)}
- className="capitalize justify-between [&_svg]:data-[state=open]:text-foreground [&_svg]:data-[highlighted]:text-foreground [&_svg]:text-muted-foreground"
+ className="justify-between capitalize [&_svg]:text-muted-foreground [&_svg]:data-[highlighted]:text-foreground [&_svg]:data-[state=open]:text-foreground"
>
{option}
<ThemeIcon theme={option} />
diff --git a/apps/web/src/components/marketing/pricing/pricing-slider.tsx b/apps/web/src/components/marketing/pricing/pricing-slider.tsx
index 6d17fdb53..5539ed456 100644
--- a/apps/web/src/components/marketing/pricing/pricing-slider.tsx
+++ b/apps/web/src/components/marketing/pricing/pricing-slider.tsx
@@ -58,7 +58,7 @@ export function PricingSlider() {
max={MAX_REGIONS}
step={1}
trailing="regions"
- className="text-right font-mono bg-background"
+ className="bg-background text-right font-mono"
value={inputValue}
onChange={(e) =>
setInputValue(Number.parseInt(e.target.value) || 0)
diff --git a/apps/web/src/components/marketing/pricing/pricing-table.tsx b/apps/web/src/components/marketing/pricing/pricing-table.tsx
index 8e3e9fa2d..c940ceb8d 100644
--- a/apps/web/src/components/marketing/pricing/pricing-table.tsx
+++ b/apps/web/src/components/marketing/pricing/pricing-table.tsx
@@ -123,7 +123,7 @@ export function PricingTable({
return (
<TableRow key={key + label}>
<TableCell>
- <div className="flex gap-2 items-center">
+ <div className="flex items-center gap-2">
{label}
{badge ? (
<Badge variant="secondary">{badge}</Badge>
@@ -132,7 +132,7 @@ export function PricingTable({
<TooltipProvider delayDuration={200}>
<Tooltip>
<TooltipTrigger className="ml-auto data-[state=closed]:text-muted-foreground">
- <Info className="w-4 h-4" />
+ <Info className="h-4 w-4" />
</TooltipTrigger>
<TooltipContent className="w-64">
{description}
diff --git a/apps/web/src/components/marketing/speed-checker-button.tsx b/apps/web/src/components/marketing/speed-checker-button.tsx
index 2af2ee7df..a8758279b 100644
--- a/apps/web/src/components/marketing/speed-checker-button.tsx
+++ b/apps/web/src/components/marketing/speed-checker-button.tsx
@@ -5,10 +5,10 @@ import { Icons } from "../icons";
export function SpeedCheckerButton({ className, ...props }: ButtonProps) {
return (
- <Button className={cn("rounded-full group", className)} asChild {...props}>
+ <Button className={cn("group rounded-full", className)} asChild {...props}>
<Link href="/play/checker">
Speed Checker{" "}
- <Icons.gauge className="ml-1 h-4 w-4 [&>*:first-child]:transition-transform [&>*:first-child]:origin-[12px_14px] [&>*:first-child]:-rotate-90 [&>*:first-child]:group-hover:rotate-0 [&>*:first-child]:duration-500 [&>*:first-child]:ease-out" />
+ <Icons.gauge className="[&>*:first-child]:-rotate-90 ml-1 h-4 w-4 [&>*:first-child]:origin-[12px_14px] [&>*:first-child]:transition-transform [&>*:first-child]:duration-500 [&>*:first-child]:ease-out [&>*:first-child]:group-hover:rotate-0" />
</Link>
</Button>
);
diff --git a/apps/web/src/components/marketing/stats.tsx b/apps/web/src/components/marketing/stats.tsx
index 12ec19e6e..177711732 100644
--- a/apps/web/src/components/marketing/stats.tsx
+++ b/apps/web/src/components/marketing/stats.tsx
@@ -1,10 +1,13 @@
import { Shell } from "@/components/dashboard/shell";
-import { getHomeStatsData } from "@/lib/tb";
+import { env } from "@/env";
import { numberFormatter } from "@/lib/utils";
+import { OSTinybird } from "@openstatus/tinybird";
+
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
export async function Stats() {
- const tbTotalStats = await getHomeStatsData({});
- const tbLastHourStats = await getHomeStatsData({ period: "1h" });
+ const tbTotalStats = await tb.homeStats({});
+ const tbLastHourStats = await tb.homeStats({ period: "1h" });
// const totalActiveMonitors = await api.monitor.getTotalActiveMonitors.query();
return (
@@ -12,13 +15,13 @@ export async function Stats() {
<div className="grid grid-cols-1 gap-8 sm:grid-cols-3 sm:gap-16">
<div className="text-center">
<h3 className="font-cal text-3xl">
- {numberFormatter(tbTotalStats?.[0].count || 0)}
+ {numberFormatter(tbTotalStats?.data?.[0]?.count || 0)}
</h3>
<p className="font-light text-muted-foreground">Total pings</p>
</div>
<div className="text-center">
<h3 className="font-cal text-3xl">
- {numberFormatter(tbLastHourStats?.[0].count || 62000000)}
+ {numberFormatter(tbLastHourStats?.data?.[0]?.count || 0)}
</h3>
<p className="font-light text-muted-foreground">
Pings in the last hour
@@ -27,7 +30,7 @@ export async function Stats() {
<div className="text-center">
<h3 className="font-cal text-3xl">
{/* {numberFormatter(totalActiveMonitors)} */}
- 2400+
+ 3400+
</h3>
<p className="font-light text-muted-foreground">Active monitors</p>
</div>
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 d8768d5df..384abd1c2 100644
--- a/apps/web/src/components/marketing/status-page/tracker-example.tsx
+++ b/apps/web/src/components/marketing/status-page/tracker-example.tsx
@@ -1,13 +1,10 @@
import Link from "next/link";
import { Suspense } from "react";
-import { OSTinybird } from "@openstatus/tinybird";
import { Button } from "@openstatus/ui/src/components/button";
import { Tracker } from "@/components/tracker/tracker";
-import { env } from "@/env";
-
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+import { prepareStatusByPeriod } from "@/lib/tb";
export async function TrackerExample() {
return (
@@ -29,15 +26,10 @@ function ExampleTrackerFallback() {
}
async function ExampleTracker() {
- const data = await tb.endpointStatusPeriod("45d")(
- {
- monitorId: "1",
- },
- {
- revalidate: 600, // 10 minutes
- },
- );
+ const res = await prepareStatusByPeriod("45d").getData({
+ monitorId: "1",
+ });
- if (!data) return null;
- return <Tracker data={data} name="Ping" description="Pong" />;
+ if (!res.data) return null;
+ return <Tracker data={res.data} name="Ping" description="Pong" />;
}
diff --git a/apps/web/src/components/monitor-charts/chart-wrapper.tsx b/apps/web/src/components/monitor-charts/chart-wrapper.tsx
index eaa0102be..cd80626c5 100644
--- a/apps/web/src/components/monitor-charts/chart-wrapper.tsx
+++ b/apps/web/src/components/monitor-charts/chart-wrapper.tsx
@@ -1,6 +1,5 @@
-import type { ResponseGraph } from "@openstatus/tinybird";
-
import type { Period, Quantile } from "@/lib/monitor/utils";
+import type { ResponseGraph } from "@/lib/tb";
import { Chart } from "./chart";
import { groupDataByTimestamp } from "./utils";
diff --git a/apps/web/src/components/monitor-charts/chart.tsx b/apps/web/src/components/monitor-charts/chart.tsx
index ccb3bcefb..7c596f0e1 100644
--- a/apps/web/src/components/monitor-charts/chart.tsx
+++ b/apps/web/src/components/monitor-charts/chart.tsx
@@ -4,9 +4,8 @@ import type { CustomTooltipProps, EventProps } from "@tremor/react";
import { LineChart } from "@tremor/react";
import { useState } from "react";
-import type { Region } from "@openstatus/tinybird";
-
import { cn } from "@/lib/utils";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { dataFormatter, regionFormatter } from "./utils";
interface ChartProps {
diff --git a/apps/web/src/components/monitor-charts/combined-chart-wrapper.tsx b/apps/web/src/components/monitor-charts/combined-chart-wrapper.tsx
index 750bfe43b..9b26667fd 100644
--- a/apps/web/src/components/monitor-charts/combined-chart-wrapper.tsx
+++ b/apps/web/src/components/monitor-charts/combined-chart-wrapper.tsx
@@ -4,11 +4,7 @@ import { LineChart } from "lucide-react";
import { useMemo } from "react";
import type { Monitor, PublicMonitor } from "@openstatus/db/src/schema";
-import type {
- Region,
- ResponseGraph,
- ResponseTimeMetricsByRegion,
-} from "@openstatus/tinybird";
+
import { Toggle } from "@openstatus/ui";
import { columns } from "@/components/data-table/single-region/columns";
@@ -19,6 +15,8 @@ import { RegionsPreset } from "@/components/monitor-dashboard/region-preset";
import type { Interval, Period, Quantile } from "@/lib/monitor/utils";
import { usePreferredSettings } from "@/lib/preferred-settings/client";
import type { PreferredSettings } from "@/lib/preferred-settings/server";
+import type { ResponseGraph, ResponseTimeMetricsByRegion } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { Chart } from "./chart";
import { groupDataByTimestamp } from "./utils";
diff --git a/apps/web/src/components/monitor-charts/region-table.tsx b/apps/web/src/components/monitor-charts/region-table.tsx
index 638eb5262..999a1aff8 100644
--- a/apps/web/src/components/monitor-charts/region-table.tsx
+++ b/apps/web/src/components/monitor-charts/region-table.tsx
@@ -1,4 +1,3 @@
-import type { Region, ResponseTimeMetricsByRegion } from "@openstatus/tinybird";
import {
Table,
TableBody,
@@ -11,6 +10,8 @@ import {
import { flyRegionsDict } from "@openstatus/utils";
import { formatNumber } from "@/components/monitor-dashboard/metrics-card";
+import type { ResponseTimeMetricsByRegion } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { SimpleChart } from "./simple-chart";
export interface RegionTableProps {
diff --git a/apps/web/src/components/monitor-charts/simple-chart-wrapper.tsx b/apps/web/src/components/monitor-charts/simple-chart-wrapper.tsx
index 271e5b12f..b62a883c6 100644
--- a/apps/web/src/components/monitor-charts/simple-chart-wrapper.tsx
+++ b/apps/web/src/components/monitor-charts/simple-chart-wrapper.tsx
@@ -1,6 +1,6 @@
-import type { Region, ResponseGraph } from "@openstatus/tinybird";
-
import type { Period, Quantile } from "@/lib/monitor/utils";
+import type { ResponseGraph } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
import { SimpleChart } from "./simple-chart";
import { groupDataByTimestamp } from "./utils";
diff --git a/apps/web/src/components/monitor-charts/utils.tsx b/apps/web/src/components/monitor-charts/utils.tsx
index a7bc5f509..32b3170dc 100644
--- a/apps/web/src/components/monitor-charts/utils.tsx
+++ b/apps/web/src/components/monitor-charts/utils.tsx
@@ -1,9 +1,10 @@
import { format } from "date-fns";
-import type { Region, ResponseGraph } from "@openstatus/tinybird";
import { flyRegionsDict } from "@openstatus/utils";
import type { Period, Quantile } from "@/lib/monitor/utils";
+import type { ResponseGraph } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
/**
*
diff --git a/apps/web/src/components/monitor-dashboard/metrics.tsx b/apps/web/src/components/monitor-dashboard/metrics.tsx
index d781aa6ad..7cd91cfe2 100644
--- a/apps/web/src/components/monitor-dashboard/metrics.tsx
+++ b/apps/web/src/components/monitor-dashboard/metrics.tsx
@@ -1,10 +1,9 @@
import { formatDistanceToNowStrict } from "date-fns";
import Link from "next/link";
-import type { LatencyMetric, ResponseTimeMetrics } from "@openstatus/tinybird";
-
import { periodFormatter } from "@/lib/monitor/utils";
import type { Period } from "@/lib/monitor/utils";
+import type { ResponseTimeMetrics } from "@/lib/tb";
import { MetricsCard } from "./metrics-card";
const metricsOrder = [
@@ -13,7 +12,7 @@ const metricsOrder = [
"p90Latency",
"p95Latency",
"p99Latency",
-] satisfies LatencyMetric[];
+] as const;
export function Metrics({
metrics,
diff --git a/apps/web/src/components/monitor-dashboard/region-preset.tsx b/apps/web/src/components/monitor-dashboard/region-preset.tsx
index 76ca53ca5..fb2ce9ad4 100644
--- a/apps/web/src/components/monitor-dashboard/region-preset.tsx
+++ b/apps/web/src/components/monitor-dashboard/region-preset.tsx
@@ -3,7 +3,6 @@
import { Check, ChevronsUpDown, Globe2 } from "lucide-react";
import * as React from "react";
-import type { Region } from "@openstatus/tinybird";
import { Button, type ButtonProps } from "@openstatus/ui/src/components/button";
import {
Command,
@@ -26,7 +25,7 @@ import {
} from "@openstatus/utils";
import { cn } from "@/lib/utils";
-import { flyRegions } from "@openstatus/db/src/schema/constants";
+import { type Region, flyRegions } from "@openstatus/db/src/schema/constants";
import { parseAsArrayOf, parseAsStringLiteral, useQueryState } from "nuqs";
interface RegionsPresetProps extends ButtonProps {
diff --git a/apps/web/src/components/monitor-dashboard/response-details.tsx b/apps/web/src/components/monitor-dashboard/response-details.tsx
index 4bb1406b0..ec2288c88 100644
--- a/apps/web/src/components/monitor-dashboard/response-details.tsx
+++ b/apps/web/src/components/monitor-dashboard/response-details.tsx
@@ -1,8 +1,5 @@
// TODO: move to `ping-response-analysis`
-import { OSTinybird } from "@openstatus/tinybird";
-import type { ResponseDetailsParams } from "@openstatus/tinybird";
-
import {
Tabs,
TabsContent,
@@ -12,16 +9,30 @@ import {
import { RegionInfo } from "@/components/ping-response-analysis/region-info";
import { ResponseHeaderTable } from "@/components/ping-response-analysis/response-header-table";
import { ResponseTimingTable } from "@/components/ping-response-analysis/response-timing-table";
-import { env } from "@/env";
+import { prepareGetByPeriod } from "@/lib/tb";
+import type { Region } from "@openstatus/db/src/schema/constants";
+
+interface ResponseDetailsProps {
+ monitorId: string;
+ url?: string | undefined;
+ region?: Region;
+ cronTimestamp?: number | undefined;
+ type: "http" | "tcp";
+}
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+export async function ResponseDetails({
+ type,
+ ...props
+}: ResponseDetailsProps) {
+ // FIXME: this has to be dynamic
+ const details = await prepareGetByPeriod("30d", type).getData(props);
-export async function ResponseDetails(props: ResponseDetailsParams) {
- const details = await tb.endpointResponseDetails("45d")(props);
+ if (!details.data || details.data.length === 0) return null;
- if (!details || details?.length === 0) return null;
+ const response = details.data[0];
- const response = details[0];
+ // FIXME: return the proper infos regarding TCP - but there are non right now anyways
+ if (response.type === "tcp") return null;
const { timing, headers, message, statusCode } = response;
diff --git a/apps/web/src/components/ping-response-analysis/multi-region-tabs.tsx b/apps/web/src/components/ping-response-analysis/multi-region-tabs.tsx
index d17f98cdd..7e6769bdd 100644
--- a/apps/web/src/components/ping-response-analysis/multi-region-tabs.tsx
+++ b/apps/web/src/components/ping-response-analysis/multi-region-tabs.tsx
@@ -2,7 +2,7 @@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@openstatus/ui";
-import type { Region } from "@openstatus/tinybird";
+import type { Region } from "@openstatus/db/src/schema/constants";
import type { Row } from "@tanstack/react-table";
import { RegionsPreset } from "../monitor-dashboard/region-preset";
import { columns } from "./columns";
diff --git a/apps/web/src/components/status-page/monitor.tsx b/apps/web/src/components/status-page/monitor.tsx
index a5a63d5a0..77c41f5c8 100644
--- a/apps/web/src/components/status-page/monitor.tsx
+++ b/apps/web/src/components/status-page/monitor.tsx
@@ -6,12 +6,9 @@ import type {
PublicMonitor,
selectPublicStatusReportSchemaWithRelation,
} from "@openstatus/db/src/schema";
-import { OSTinybird } from "@openstatus/tinybird";
import { Tracker } from "@/components/tracker/tracker";
-import { env } from "@/env";
-
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+import { prepareStatusByPeriod } from "@/lib/tb";
export const Monitor = async ({
monitor,
@@ -26,17 +23,20 @@ export const Monitor = async ({
maintenances: Maintenance[];
showValues?: boolean;
}) => {
- const data = await tb.endpointStatusPeriod("45d")({
+ const res = await prepareStatusByPeriod(
+ "45d",
+ monitor.jobType as "http" | "tcp",
+ ).getData({
monitorId: String(monitor.id),
});
// TODO: we could handle the `statusReports` here instead of passing it down to the tracker
- if (!data) return <div>Something went wrong</div>;
+ if (!res.data) return <div>Something went wrong</div>;
return (
<Tracker
- data={data}
+ data={res.data}
reports={statusReports}
incidents={incidents}
maintenances={maintenances}
diff --git a/apps/web/src/components/tracker/tracker.tsx b/apps/web/src/components/tracker/tracker.tsx
index 08f67933c..5f9c2fed3 100644
--- a/apps/web/src/components/tracker/tracker.tsx
+++ b/apps/web/src/components/tracker/tracker.tsx
@@ -12,7 +12,6 @@ import type {
StatusReport,
StatusReportUpdate,
} from "@openstatus/db/src/schema";
-import type { Monitor } from "@openstatus/tinybird";
import {
Tracker as OSTracker,
classNames,
@@ -26,6 +25,7 @@ import {
TooltipTrigger,
} from "@openstatus/ui/src/components/tooltip";
+import type { ResponseStatusTracker } from "@/lib/tb";
import { cn } from "@/lib/utils";
import {
HoverCard,
@@ -57,7 +57,7 @@ const tracker = cva("h-10 rounded-full flex-1", {
});
interface TrackerProps {
- data: Monitor[];
+ data: ResponseStatusTracker[];
name: string;
description?: string;
reports?: (StatusReport & { statusReportUpdates: StatusReportUpdate[] })[];
diff --git a/apps/web/src/components/workspace/select-workspace.tsx b/apps/web/src/components/workspace/select-workspace.tsx
index 37b25eb61..631a88fe3 100644
--- a/apps/web/src/components/workspace/select-workspace.tsx
+++ b/apps/web/src/components/workspace/select-workspace.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Check, ChevronsUpDown, Plus } from "lucide-react";
+import { Check, ChevronsUpDown, Copy, CopyCheck, Plus } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import * as React from "react";
@@ -17,12 +17,22 @@ import {
} from "@openstatus/ui/src/components/dropdown-menu";
import { Skeleton } from "@openstatus/ui/src/components/skeleton";
+import { copyToClipboard } from "@/lib/utils";
import { api } from "@/trpc/client";
export function SelectWorkspace() {
const [workspaces, setWorkspaces] = React.useState<Workspace[]>([]);
const [active, setActive] = React.useState<string>();
const pathname = usePathname();
+ const [hasCopied, setHasCopied] = React.useState(false);
+
+ React.useEffect(() => {
+ if (hasCopied) {
+ setTimeout(() => {
+ setHasCopied(false);
+ }, 2000);
+ }
+ }, [hasCopied]);
React.useEffect(() => {
if (pathname?.split("/")?.[2] && workspaces.length > 0) {
@@ -63,11 +73,29 @@ export function SelectWorkspace() {
<DropdownMenuItem key={workspace.id} asChild>
<a
href={`/app/${workspace.slug}/monitors`}
- className="justify-between"
+ className="group justify-between"
>
<span className="truncate">{workspace.slug}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="mx-0.5 hidden h-5 w-5 group-hover:block"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ copyToClipboard(workspace.slug);
+ setHasCopied(true);
+ }}
+ >
+ {!hasCopied ? (
+ <Copy className="h-3 w-3" />
+ ) : (
+ <CopyCheck className="h-3 w-3" />
+ )}
+ </Button>
{active === workspace.slug ? (
- <Check className="ml-2 h-4 w-4" />
+ <Check className="ml-2 h-4 w-4 shrink-0" />
) : null}
</a>
</DropdownMenuItem>
diff --git a/apps/web/src/config/pricing-table.tsx b/apps/web/src/config/pricing-table.tsx
index 2bc3678dc..9a4e3a459 100644
--- a/apps/web/src/config/pricing-table.tsx
+++ b/apps/web/src/config/pricing-table.tsx
@@ -12,7 +12,7 @@ function renderChangelogDescription(slug: Changelog["slug"]) {
{changelog?.description}{" "}
<Link
href={`/changelog/${changelog.slug}`}
- className="underline underline-offset-4 text-nowrap"
+ className="text-nowrap underline underline-offset-4"
>
Learn more
</Link>
diff --git a/apps/web/src/lib/monitor/utils.ts b/apps/web/src/lib/monitor/utils.ts
index 40dfae91c..23bceae65 100644
--- a/apps/web/src/lib/monitor/utils.ts
+++ b/apps/web/src/lib/monitor/utils.ts
@@ -9,7 +9,7 @@ import {
import type { MonitorPeriodicity } from "@openstatus/db/src/schema";
-export const periods = ["1h", "1d", "3d", "7d", "14d"] as const; // If neeeded (e.g. Pro plans), "7d", "30d"
+export const periods = ["1d", "7d", "14d"] as const; // If neeeded (e.g. Pro plans), "7d", "30d"
export const quantiles = ["p99", "p95", "p90", "p75", "p50"] as const;
export const intervals = ["1m", "10m", "30m", "1h"] as const;
export const triggers = ["cron", "api"] as const;
@@ -21,21 +21,11 @@ export type Trigger = (typeof triggers)[number];
export function getDateByPeriod(period: Period) {
switch (period) {
- case "1h":
- return {
- from: subHours(startOfHour(new Date()), 1),
- to: endOfHour(new Date()),
- };
case "1d":
return {
from: subDays(startOfHour(new Date()), 1),
to: endOfDay(new Date()),
};
- case "3d":
- return {
- from: subDays(startOfDay(new Date()), 3),
- to: endOfDay(new Date()),
- };
case "7d":
return {
from: subDays(startOfDay(new Date()), 7),
@@ -55,12 +45,8 @@ export function getDateByPeriod(period: Period) {
export function getHoursByPeriod(period: Period) {
switch (period) {
- case "1h":
- return 1;
case "1d":
return 24;
- case "3d":
- return 72;
case "7d":
return 168;
case "14d":
@@ -74,12 +60,8 @@ export function getHoursByPeriod(period: Period) {
export function periodFormatter(period: Period) {
switch (period) {
- case "1h":
- return "Last hour";
case "1d":
return "Last day";
- case "3d":
- return "Last 3 days";
case "7d":
return "Last 7 days";
case "14d":
diff --git a/apps/web/src/lib/tb.ts b/apps/web/src/lib/tb.ts
index e45c3d9e7..b2d1e3422 100644
--- a/apps/web/src/lib/tb.ts
+++ b/apps/web/src/lib/tb.ts
@@ -1,17 +1,219 @@
-import type { HomeStatsParams } from "@openstatus/tinybird";
-import { Tinybird, getHomeStats } from "@openstatus/tinybird";
+import { OSTinybird } 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 });
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
-export async function getHomeStatsData(props: Partial<HomeStatsParams>) {
- try {
- const res = await getHomeStats(tb)(props);
- return res.data;
- } catch (e) {
- console.error(e);
+// REMINDER: we could extend the limits (WorkspacePlan) by
+// knowing which plan the user is on and disable some periods
+const periods = ["1d", "7d", "14d"] as const;
+const types = ["http", "tcp"] as const;
+
+// FIXME: check we we can also use Period from elswhere
+type Period = (typeof periods)[number];
+// FIMXE: use JobType instead!
+type Type = (typeof types)[number];
+
+// REMINDER: extend if needed
+export function prepareListByPeriod(period: Period, type: Type = "http") {
+ switch (period) {
+ case "1d": {
+ const getData = {
+ http: tb.httpListDaily,
+ tcp: tb.tcpListDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "7d": {
+ const getData = {
+ http: tb.httpListWeekly,
+ tcp: tb.tcpListWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "14d": {
+ const getData = {
+ http: tb.httpListBiweekly,
+ tcp: tb.tcpListBiweekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpListDaily,
+ tcp: tb.tcpListDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ }
+}
+
+export function prepareMetricsByPeriod(period: Period, type: Type = "http") {
+ switch (period) {
+ case "1d": {
+ const getData = {
+ http: tb.httpMetricsDaily,
+ tcp: tb.tcpMetricsDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "7d": {
+ const getData = {
+ http: tb.httpMetricsWeekly,
+ tcp: tb.tcpMetricsWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "14d": {
+ const getData = {
+ http: tb.httpMetricsBiweekly,
+ tcp: tb.tcpMetricsBiweekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpMetricsDaily,
+ tcp: tb.tcpMetricsDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ }
+}
+
+export function prepareMetricByRegionByPeriod(
+ period: Period,
+ type: Type = "http",
+) {
+ switch (period) {
+ case "1d": {
+ const getData = {
+ http: tb.httpMetricsByRegionDaily,
+ tcp: tb.tcpMetricsByRegionDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "7d": {
+ const getData = {
+ http: tb.httpMetricsByRegionWeekly,
+ tcp: tb.tcpMetricsByRegionWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "14d": {
+ const getData = {
+ http: tb.httpMetricsByRegionBiweekly,
+ tcp: tb.tcpMetricsByRegionBiweekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpMetricsByRegionDaily,
+ tcp: tb.tcpMetricsByRegionDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ }
+}
+
+export function prepareMetricByIntervalByPeriod(
+ period: Period,
+ type: Type = "http",
+) {
+ switch (period) {
+ case "1d": {
+ const getData = {
+ http: tb.httpMetricsByIntervalDaily,
+ tcp: tb.tcpMetricsByIntervalDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "7d": {
+ const getData = {
+ http: tb.httpMetricsByIntervalWeekly,
+ tcp: tb.tcpMetricsByIntervalWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "14d": {
+ const getData = {
+ http: tb.httpMetricsByIntervalBiweekly,
+ tcp: tb.tcpMetricsByIntervalBiweekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpMetricsByIntervalDaily,
+ tcp: tb.tcpMetricsByIntervalDaily,
+ } as const;
+ return { getData: getData[type] };
+ }
}
- return;
}
+
+export function prepareStatusByPeriod(
+ period: "7d" | "45d",
+ type: Type = "http",
+) {
+ switch (period) {
+ case "7d": {
+ const getData = {
+ http: tb.httpStatusWeekly,
+ tcp: tb.tcpStatusWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ case "45d": {
+ const getData = {
+ http: tb.httpStatus45d,
+ tcp: tb.tcpStatus45d,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpStatusWeekly,
+ tcp: tb.tcpStatusWeekly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ }
+}
+
+export function prepareGetByPeriod(period: "30d", type: Type = "http") {
+ switch (period) {
+ case "30d": {
+ const getData = {
+ http: tb.httpGetMonthly,
+ tcp: tb.tcpGetMonthly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ default: {
+ const getData = {
+ http: tb.httpGetMonthly,
+ tcp: tb.tcpGetMonthly,
+ } as const;
+ return { getData: getData[type] };
+ }
+ }
+}
+
+// FOR MIGRATION
+export type ResponseTimeMetrics = Awaited<
+ ReturnType<OSTinybird["httpMetricsDaily"]>
+>["data"][number];
+
+export type ResponseTimeMetricsByRegion = Awaited<
+ ReturnType<OSTinybird["httpMetricsByRegionDaily"]>
+>["data"][number];
+
+export type ResponseGraph = Awaited<
+ ReturnType<OSTinybird["httpMetricsByIntervalDaily"]>
+>["data"][number];
+
+export type ResponseStatusTracker = Awaited<
+ ReturnType<OSTinybird["httpStatusWeekly"]>
+>["data"][number];
diff --git a/apps/web/src/trpc/rq-server.ts b/apps/web/src/trpc/rq-server.ts
index 9021f5297..6bd68a472 100644
--- a/apps/web/src/trpc/rq-server.ts
+++ b/apps/web/src/trpc/rq-server.ts
@@ -9,7 +9,7 @@ import { cache } from "react";
import { makeQueryClient } from "./query-client";
const createContextCached = cache(
- async (...args: unknown[]): Promise<Context> => {
+ async (..._args: unknown[]): Promise<Context> => {
const session = await auth();
return {
diff --git a/packages/api/src/router/tinybird/index.ts b/packages/api/src/router/tinybird/index.ts
index 59a8a7c0b..beefabfd0 100644
--- a/packages/api/src/router/tinybird/index.ts
+++ b/packages/api/src/router/tinybird/index.ts
@@ -6,66 +6,20 @@ import { flyRegions } from "@openstatus/db/src/schema/constants";
import { env } from "../../env";
import { createTRPCRouter, protectedProcedure } from "../../trpc";
-const tb = new OSTinybird({ token: env.TINY_BIRD_API_KEY });
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
// WORK IN PROGRESS - we can create a tb router to call it via TRPC server and client
export const tinybirdRouter = createTRPCRouter({
- lastCronTimestamp: protectedProcedure.query(async (opts) => {
- const workspaceId = String(opts.ctx.workspace.id);
- return await tb.endpointLastCronTimestamp("workspace")({ workspaceId });
- }),
-
- monitorMetricsFromWorkspace: protectedProcedure
- .input(z.object({ period: z.string() }))
- .query(async (opts) => {
- const _workspaceId = String(opts.ctx.workspace.id);
- }),
-
- responseDetails: protectedProcedure
+ httpGetMonthly: protectedProcedure
.input(
z.object({
- monitorId: z.string().default("").optional(),
- url: z.string().url().optional(),
+ monitorId: z.string(),
region: z.enum(flyRegions).optional(),
cronTimestamp: z.number().int().optional(),
}),
)
.query(async (opts) => {
- return await tb.endpointResponseDetails("7d")(opts.input);
- }),
-
- totalRumMetricsForApplication: protectedProcedure
- .input(z.object({ dsn: z.string(), period: z.enum(["24h", "7d", "30d"]) }))
- .query(async (opts) => {
- return await tb.applicationRUMMetrics()(opts.input);
- }),
- rumMetricsForApplicationPerPage: protectedProcedure
- .input(z.object({ dsn: z.string(), period: z.enum(["24h", "7d", "30d"]) }))
- .query(async (opts) => {
- return await tb.applicationRUMMetricsPerPage()(opts.input);
- }),
-
- rumMetricsForPath: protectedProcedure
- .input(
- z.object({
- dsn: z.string(),
- path: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- }),
- )
- .query(async (opts) => {
- return await tb.applicationRUMMetricsForPath()(opts.input);
- }),
- sessionRumMetricsForPath: protectedProcedure
- .input(
- z.object({
- dsn: z.string(),
- path: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- }),
- )
- .query(async (opts) => {
- return await tb.applicationSessionMetricsPerPath()(opts.input);
+ return await tb.httpGetMonthly(opts.input);
}),
});
diff --git a/packages/db/src/schema/constants.ts b/packages/db/src/schema/constants.ts
index a3b837003..be335a7b8 100644
--- a/packages/db/src/schema/constants.ts
+++ b/packages/db/src/schema/constants.ts
@@ -52,4 +52,6 @@ export const monitorRegions = [...flyRegions] as const;
export const monitorPeriodicitySchema = z.enum(monitorPeriodicity);
export const monitorRegionSchema = z.enum(monitorRegions);
export const monitorFlyRegionSchema = z.enum(flyRegions);
+
export type MonitorFlyRegion = z.infer<typeof monitorFlyRegionSchema>;
+export type Region = z.infer<typeof monitorFlyRegionSchema>;
diff --git a/packages/tinybird/README.md b/packages/tinybird/README.md
index 00a23b079..d0a7b6320 100644
--- a/packages/tinybird/README.md
+++ b/packages/tinybird/README.md
@@ -33,3 +33,20 @@ tb pipe rm tb_datasource_union.pipe --yes
Link to the [issue](https://github.com/openstatusHQ/openstatus/issues/278) from
Gonzalo as reference.
+
+
+<!-- FIXME: more content -->
+
+```bash
+python3 -m venv .venv
+source .venv/bin/activate
+pip install tinybird-cli
+tb auth -i
+```
+
+```bash
+tb pull
+tb push aggregate_*.pipe --populate
+tb push endpoint_*.pipe
+...
+```
\ No newline at end of file
diff --git a/packages/tinybird/pipes/aggregate__http_14d.pipe b/packages/tinybird/pipes/aggregate__http_14d.pipe
new file mode 100644
index 000000000..e546109c7
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_14d.pipe
@@ -0,0 +1,28 @@
+VERSION 0
+
+TAGS http
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM ping_response__v8
+
+TYPE materialized
+DATASOURCE mv__http_14d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(14)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__http_1d.pipe b/packages/tinybird/pipes/aggregate__http_1d.pipe
new file mode 100644
index 000000000..cfb10ba85
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_1d.pipe
@@ -0,0 +1,28 @@
+VERSION 0
+
+TAGS http
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM ping_response__v8
+
+TYPE materialized
+DATASOURCE mv__http_1d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(1)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__http_30d.pipe b/packages/tinybird/pipes/aggregate__http_30d.pipe
new file mode 100644
index 000000000..47e0f8fe2
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_30d.pipe
@@ -0,0 +1,28 @@
+VERSION 0
+
+TAGS http
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM ping_response__v8
+
+TYPE materialized
+DATASOURCE mv__http_30d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(30)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__http_7d.pipe b/packages/tinybird/pipes/aggregate__http_7d.pipe
new file mode 100644
index 000000000..d28c19f4d
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_7d.pipe
@@ -0,0 +1,28 @@
+VERSION 0
+
+TAGS http
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM ping_response__v8
+
+TYPE materialized
+DATASOURCE mv__http_7d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(7)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__http_full_30d.pipe b/packages/tinybird/pipes/aggregate__http_full_30d.pipe
new file mode 100644
index 000000000..02bb4c066
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_full_30d.pipe
@@ -0,0 +1,23 @@
+VERSION 0
+DESCRIPTION >
+ Stores all the data from the http_response table for the last 30 days, mainly used for accessing the data details.
+
+
+TAGS http, full
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ *
+ FROM ping_response__v8
+
+TYPE materialized
+DATASOURCE mv__http_full_30d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(30)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__http_status_45d.pipe b/packages/tinybird/pipes/aggregate__http_status_45d.pipe
new file mode 100644
index 000000000..847160958
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_status_45d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS http, statuspage
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toStartOfDay(toTimeZone(fromUnixTimestamp64Milli(cronTimestamp), 'UTC')) AS time,
+ monitorId,
+ countState() AS count,
+ countState(if(error = 0, 1, NULL)) AS ok
+ FROM ping_response__v8
+ GROUP BY
+ time,
+ monitorId
+
+TYPE materialized
+DATASOURCE mv__http_status_45d__v0
+ENGINE "AggregatingMergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(45)"
+
diff --git a/packages/tinybird/pipes/aggregate__http_status_7d.pipe b/packages/tinybird/pipes/aggregate__http_status_7d.pipe
new file mode 100644
index 000000000..e40538586
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__http_status_7d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS http, statuspage
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toStartOfDay(toTimeZone(fromUnixTimestamp64Milli(cronTimestamp), 'UTC')) AS time,
+ monitorId,
+ countState() AS count,
+ countState(if(error = 0, 1, NULL)) AS ok
+ FROM ping_response__v8
+ GROUP BY
+ time,
+ monitorId
+
+TYPE materialized
+DATASOURCE mv__http_status_7d__v0
+ENGINE "AggregatingMergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(7)"
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_14d.pipe b/packages/tinybird/pipes/aggregate__tcp_14d.pipe
new file mode 100644
index 000000000..8ca2e6107
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_14d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM tcp_response__v0
+
+TYPE materialized
+DATASOURCE mv__tcp_14d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(14)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_1d.pipe b/packages/tinybird/pipes/aggregate__tcp_1d.pipe
new file mode 100644
index 000000000..d8ab99284
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_1d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM tcp_response__v0
+
+TYPE materialized
+DATASOURCE mv__tcp_1d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(1)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_30d.pipe b/packages/tinybird/pipes/aggregate__tcp_30d.pipe
new file mode 100644
index 000000000..b7dd911c6
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_30d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM tcp_response__v0
+
+TYPE materialized
+DATASOURCE mv__tcp_30d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(30)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_7d.pipe b/packages/tinybird/pipes/aggregate__tcp_7d.pipe
new file mode 100644
index 000000000..659d2be49
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_7d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ workspaceId
+ FROM tcp_response__v0
+
+TYPE materialized
+DATASOURCE mv__tcp_7d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(7)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_full_30d.pipe b/packages/tinybird/pipes/aggregate__tcp_full_30d.pipe
new file mode 100644
index 000000000..c89b65410
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_full_30d.pipe
@@ -0,0 +1,23 @@
+VERSION 0
+DESCRIPTION >
+ Stores all the data from the http_response table for the last 30 days, mainly used for accessing the data details.
+
+
+TAGS tcp, full
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ *
+ FROM tcp_response__v0
+
+TYPE materialized
+DATASOURCE mv__tcp_full_30d__v0
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(30)"
+
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_status_45d.pipe b/packages/tinybird/pipes/aggregate__tcp_status_45d.pipe
new file mode 100644
index 000000000..b6159db04
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_status_45d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS tcp, statuspage
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toStartOfDay(toTimeZone(fromUnixTimestamp64Milli(cronTimestamp), 'UTC')) AS time,
+ monitorId,
+ countState() AS count,
+ countState(if(error = 0, 1, NULL)) AS ok
+ FROM tcp_response__v0
+ GROUP BY
+ time,
+ monitorId
+
+TYPE materialized
+DATASOURCE mv__tcp_status_45d__v0
+ENGINE "AggregatingMergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(45)"
+
diff --git a/packages/tinybird/pipes/aggregate__tcp_status_7d.pipe b/packages/tinybird/pipes/aggregate__tcp_status_7d.pipe
new file mode 100644
index 000000000..bd16b1867
--- /dev/null
+++ b/packages/tinybird/pipes/aggregate__tcp_status_7d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS tcp, statuspage
+
+NODE aggregate
+SQL >
+
+ SELECT
+ toStartOfDay(toTimeZone(fromUnixTimestamp64Milli(cronTimestamp), 'UTC')) AS time,
+ monitorId,
+ countState() AS count,
+ countState(if(error = 0, 1, NULL)) AS ok
+ FROM tcp_response__v0
+ GROUP BY
+ time,
+ monitorId
+
+TYPE materialized
+DATASOURCE mv__tcp_status_7d__v0
+ENGINE "AggregatingMergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(7)"
+
diff --git a/packages/tinybird/pipes/dashboard_request.pipe b/packages/tinybird/pipes/dashboard_request.pipe
deleted file mode 100644
index 431968645..000000000
--- a/packages/tinybird/pipes/dashboard_request.pipe
+++ /dev/null
@@ -1,17 +0,0 @@
-VERSION 0
-NODE dashboard_request_0
-SQL >
-
- %
- SELECT * FROM monitor_request_count_7d_mv
- WHERE monitorId = {{ String(monitorId, '1') }}
- {% if defined(url) %} AND url = {{ String(url) }} {% end %}
-
-
-
-NODE dashboard_request_1
-SQL >
-
- SELECT * FROM dashboard_request_0
-
-
diff --git a/packages/tinybird/pipes/endpoint__http_get_30d.pipe b/packages/tinybird/pipes/endpoint__http_get_30d.pipe
new file mode 100644
index 000000000..b9405fb0e
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_get_30d.pipe
@@ -0,0 +1,18 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT *
+ FROM mv__http_full_30d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND cronTimestamp = {{ Int64(cronTimestamp, 1709477432205, required=True) }}
+ AND region = {{ String(region, 'ams', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_list_14d.pipe b/packages/tinybird/pipes/endpoint__http_list_14d.pipe
new file mode 100644
index 000000000..21f6d74fa
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_list_14d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__http_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_list_1d.pipe b/packages/tinybird/pipes/endpoint__http_list_1d.pipe
new file mode 100644
index 000000000..396ae8bd2
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_list_1d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__http_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_list_7d.pipe b/packages/tinybird/pipes/endpoint__http_list_7d.pipe
new file mode 100644
index 000000000..6df42e341
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_list_7d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__http_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_14d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_14d.pipe
new file mode 100644
index 000000000..b2526a18f
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_14d.pipe
@@ -0,0 +1,38 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__http_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 14 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__http_30d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 28 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 14 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_1d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_1d.pipe
new file mode 100644
index 000000000..299302e99
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_1d.pipe
@@ -0,0 +1,38 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__http_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 1 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__http_7d__v0 -- REMINDER: this will increase the processed data compared to 3d
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 2 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 1 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_7d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_7d.pipe
new file mode 100644
index 000000000..482638b11
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_7d.pipe
@@ -0,0 +1,38 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__http_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 7 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__http_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 14 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 7 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_interval_14d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_14d.pipe
new file mode 100644
index 000000000..19288eefa
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_14d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__http_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_interval_1d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_1d.pipe
new file mode 100644
index 000000000..f92d9fd60
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_1d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__http_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_interval_7d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_7d.pipe
new file mode 100644
index 000000000..e8daaf42a
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_interval_7d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__http_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_region_14d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_region_14d.pipe
new file mode 100644
index 000000000..e4451473b
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_region_14d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__http_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_region_1d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_region_1d.pipe
new file mode 100644
index 000000000..1390411b0
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_region_1d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__http_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_metrics_by_region_7d.pipe b/packages/tinybird/pipes/endpoint__http_metrics_by_region_7d.pipe
new file mode 100644
index 000000000..2ea818314
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_metrics_by_region_7d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__http_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_status_45d.pipe b/packages/tinybird/pipes/endpoint__http_status_45d.pipe
new file mode 100644
index 000000000..2ceece2aa
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_status_45d.pipe
@@ -0,0 +1,22 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT time as day, countMerge(count) as count, countMerge(ok) as ok
+ FROM mv__http_status_45d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY day
+ ORDER BY day DESC
+ WITH FILL
+ FROM
+ toStartOfDay(toStartOfDay(toTimeZone(now(), 'UTC')))
+ TO toStartOfDay(
+ date_sub(DAY, 45, now())
+ ) STEP INTERVAL -1 DAY
+
+
diff --git a/packages/tinybird/pipes/endpoint__http_status_7d.pipe b/packages/tinybird/pipes/endpoint__http_status_7d.pipe
new file mode 100644
index 000000000..9a01ad6a3
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__http_status_7d.pipe
@@ -0,0 +1,22 @@
+VERSION 0
+
+TAGS http
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT time as day, countMerge(count) as count, countMerge(ok) as ok
+ FROM mv__http_status_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY day
+ ORDER BY day DESC
+ WITH FILL
+ FROM
+ toStartOfDay(toStartOfDay(toTimeZone(now(), 'UTC')))
+ TO toStartOfDay(
+ date_sub(DAY, 7, now())
+ ) STEP INTERVAL -1 DAY
+
+
diff --git a/packages/tinybird/pipes/endpoint__stats_global.pipe b/packages/tinybird/pipes/endpoint__stats_global.pipe
new file mode 100644
index 000000000..37a270a83
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__stats_global.pipe
@@ -0,0 +1,18 @@
+VERSION 0
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT COUNT(*) as count
+ FROM ping_response__v8
+ {% if defined(period) %}
+ {% if String(period) == "1h" %}
+ WHERE cronTimestamp > toUnixTimestamp(now() - INTERVAL 1 HOUR) * 1000
+ {% elif String(period) == "10m" %}
+ WHERE cronTimestamp > toUnixTimestamp(now() - INTERVAL 10 MINUTE) * 1000
+ {% else %}
+ WHERE cronTimestamp > 0
+ {% end %}
+ {% end %}
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_get_30d.pipe b/packages/tinybird/pipes/endpoint__tcp_get_30d.pipe
new file mode 100644
index 000000000..b4b1e59dd
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_get_30d.pipe
@@ -0,0 +1,18 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT *
+ FROM mv__tcp_full_30d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND cronTimestamp = {{ Int64(cronTimestamp, 1709477432205, required=True) }}
+ AND region = {{ String(region, 'ams', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_list_14d.pipe b/packages/tinybird/pipes/endpoint__tcp_list_14d.pipe
new file mode 100644
index 000000000..490123de0
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_list_14d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__tcp_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_list_1d.pipe b/packages/tinybird/pipes/endpoint__tcp_list_1d.pipe
new file mode 100644
index 000000000..4f63aa1a9
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_list_1d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__tcp_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_list_7d.pipe b/packages/tinybird/pipes/endpoint__tcp_list_7d.pipe
new file mode 100644
index 000000000..88e043795
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_list_7d.pipe
@@ -0,0 +1,14 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT * FROM mv__tcp_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ ORDER BY cronTimestamp DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_14d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_14d.pipe
new file mode 100644
index 000000000..9fdf8db5c
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_14d.pipe
@@ -0,0 +1,41 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__tcp_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ -- FIXME: we can reduce the data processed by using removing it entirely
+ -- because the query is useless as we are in the 14d context
+ -- TODO: check where we can reduce the data processed
+ AND time >= toDateTime64(now() - INTERVAL 14 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__tcp_30d__v0 -- REMINDER: this will increase the processed data compared to 3d
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 28 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 14 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_1d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_1d.pipe
new file mode 100644
index 000000000..a1e600433
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_1d.pipe
@@ -0,0 +1,38 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__tcp_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 1 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__tcp_7d__v0 -- REMINDER: this will increase the processed data compared to 3d
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 2 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 1 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_7d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_7d.pipe
new file mode 100644
index 000000000..3a009c1de
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_7d.pipe
@@ -0,0 +1,38 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ max(cronTimestamp) AS lastTimestamp
+ FROM mv__tcp_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 7 DAY, 3)
+ UNION ALL
+ SELECT
+ round(quantile(0.50)(latency)) AS p50Latency,
+ round(quantile(0.75)(latency)) AS p75Latency,
+ round(quantile(0.90)(latency)) AS p90Latency,
+ round(quantile(0.95)(latency)) AS p95Latency,
+ round(quantile(0.99)(latency)) AS p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok,
+ NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant
+ FROM mv__tcp_14d__v0 -- REMINDER: this will increase the processed data compared to 3d
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ AND time >= toDateTime64(now() - INTERVAL 14 DAY, 3)
+ AND time < toDateTime64(now() - INTERVAL 7 DAY, 3)
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_14d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_14d.pipe
new file mode 100644
index 000000000..590acbc13
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_14d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__tcp_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_1d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_1d.pipe
new file mode 100644
index 000000000..6ce080204
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_1d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__tcp_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_7d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_7d.pipe
new file mode 100644
index 000000000..143621973
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_interval_7d.pipe
@@ -0,0 +1,27 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ toStartOfInterval(
+ toDateTime(cronTimestamp / 1000),
+ INTERVAL {{ Int64(interval, 30) }} MINUTE -- use 2880 (2d) in case you want the 1d summary for the regions
+ ) as h,
+ toUnixTimestamp64Milli(toDateTime64(h, 3)) as timestamp,
+ round(quantile(0.50)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.90)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency
+ FROM mv__tcp_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY h, region
+ ORDER BY h DESC
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_14d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_14d.pipe
new file mode 100644
index 000000000..dda3021d8
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_14d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__tcp_14d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_1d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_1d.pipe
new file mode 100644
index 000000000..44b93ca14
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_1d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__tcp_1d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_7d.pipe b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_7d.pipe
new file mode 100644
index 000000000..b0f59a2de
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_metrics_by_region_7d.pipe
@@ -0,0 +1,24 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ region,
+ round(quantile(0.5)(latency)) as p50Latency,
+ round(quantile(0.75)(latency)) as p75Latency,
+ round(quantile(0.9)(latency)) as p90Latency,
+ round(quantile(0.95)(latency)) as p95Latency,
+ round(quantile(0.99)(latency)) as p99Latency,
+ count() as count,
+ count(if(error = 0, 1, NULL)) AS ok
+ FROM mv__tcp_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY region
+
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_status_45d.pipe b/packages/tinybird/pipes/endpoint__tcp_status_45d.pipe
new file mode 100644
index 000000000..63d8707f7
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_status_45d.pipe
@@ -0,0 +1,22 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT time as day, countMerge(count) as count, countMerge(ok) as ok
+ FROM mv__tcp_status_45d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY day
+ ORDER BY day DESC
+ WITH FILL
+ FROM
+ toStartOfDay(toStartOfDay(toTimeZone(now(), 'UTC')))
+ TO toStartOfDay(
+ date_sub(DAY, 45, now())
+ ) STEP INTERVAL -1 DAY
+
+
diff --git a/packages/tinybird/pipes/endpoint__tcp_status_7d.pipe b/packages/tinybird/pipes/endpoint__tcp_status_7d.pipe
new file mode 100644
index 000000000..f5fc07d99
--- /dev/null
+++ b/packages/tinybird/pipes/endpoint__tcp_status_7d.pipe
@@ -0,0 +1,22 @@
+VERSION 0
+
+TAGS tcp
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT time as day, countMerge(count) as count, countMerge(ok) as ok
+ FROM mv__tcp_status_7d__v0
+ WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ GROUP BY day
+ ORDER BY day DESC
+ WITH FILL
+ FROM
+ toStartOfDay(toStartOfDay(toTimeZone(now(), 'UTC')))
+ TO toStartOfDay(
+ date_sub(DAY, 7, now())
+ ) STEP INTERVAL -1 DAY
+
+
diff --git a/packages/tinybird/pipes/home_stats.pipe b/packages/tinybird/pipes/home_stats.pipe
index f9e48c15d..bdf885305 100644
--- a/packages/tinybird/pipes/home_stats.pipe
+++ b/packages/tinybird/pipes/home_stats.pipe
@@ -5,7 +5,7 @@ SQL >
%
SELECT COUNT(*) as count
- FROM ping_response__v7
+ FROM ping_response__v8
{% if defined(period) %}
{% if String(period) == "1h" %}
WHERE cronTimestamp > toUnixTimestamp(now() - INTERVAL 1 HOUR) * 1000
diff --git a/packages/tinybird/src/client.ts b/packages/tinybird/src/client.ts
index 1b00ca3bc..b6a41e7c8 100644
--- a/packages/tinybird/src/client.ts
+++ b/packages/tinybird/src/client.ts
@@ -1,60 +1,682 @@
-import { Tinybird } from "@chronark/zod-bird";
-
-import {
- tbBuildHomeStats,
- tbBuildMonitorList,
- tbBuildPublicStatus,
- tbIngestPingResponse,
- tbParameterHomeStats,
- tbParameterMonitorList,
- tbParameterPublicStatus,
-} from "./validation";
-
-// REMINDER:
-const tb = new Tinybird({ token: process.env.TINY_BIRD_API_KEY || "" });
-
-export const publishPingResponse = tb.buildIngestEndpoint({
- datasource: "ping_response__v6",
- event: tbIngestPingResponse,
-});
-
-/**
- * @deprecated but still used in server - please use OSTinybird.endpointStatusPeriod
- */
-export function getMonitorList(tb: Tinybird) {
- return tb.buildPipe({
- pipe: "status_timezone__v1",
- parameters: tbParameterMonitorList,
- data: tbBuildMonitorList,
- opts: {
- // cache: "no-store",
- next: {
- revalidate: 600, // 10 min cache
- },
- },
- });
-}
+import { Tinybird as Client, NoopTinybird } from "@chronark/zod-bird";
+import { z } from "zod";
+import { flyRegions } from "../../db/src/schema/constants";
+import { headersSchema, timingSchema, triggers } from "./schema";
+
+export class OSTinybird {
+ private readonly tb: Client;
-/**
- * Homepage stats used for our marketing page
- */
-export function getHomeStats(tb: Tinybird) {
- return tb.buildPipe({
- pipe: "home_stats__v0",
- parameters: tbParameterHomeStats,
- data: tbBuildHomeStats,
- opts: {
- next: {
- revalidate: 43200, // 60 * 60 * 24 = 86400s = 12h
+ constructor(token: string) {
+ // if (process.env.NODE_ENV === "development") {
+ // this.tb = new NoopTinybird();
+ // } else {
+ this.tb = new Client({ token });
+ // }
+ }
+
+ public get homeStats() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__stats_global__v0",
+ parameters: z.object({
+ cronTimestamp: z.number().int().optional(),
+ period: z.enum(["total", "1h", "10m"]).optional(),
+ }),
+ data: z.object({
+ count: z.number().int(),
+ }),
+ opts: {
+ next: {
+ revalidate: 43200, // 60 * 60 * 24 = 86400s = 12h
+ },
},
- },
- });
-}
+ });
+ }
+
+ public get httpListDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_1d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("http").default("http"),
+ latency: z.number().int(),
+ statusCode: z.number().int().nullable(),
+ monitorId: z.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpListWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("http").default("http"),
+ latency: z.number().int(),
+ statusCode: z.number().int().nullable(),
+ monitorId: z.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpListBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_14d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("http").default("http"),
+ latency: z.number().int(),
+ statusCode: z.number().int().nullable(),
+ monitorId: z.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_1d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_7d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_14d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByIntervalDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_interval_1d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByIntervalWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_interval_7d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByIntervalBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_interval_14d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByRegionDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_region_1d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByRegionWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_region_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpMetricsByRegionBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_metrics_by_region_14d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpStatusWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_status_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ day: z.string().transform((val) => {
+ // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
+ return new Date(`${val} GMT`).toISOString();
+ }),
+ count: z.number().default(0),
+ ok: z.number().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpStatus45d() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_status_45d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ day: z.string().transform((val) => {
+ // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
+ return new Date(`${val} GMT`).toISOString();
+ }),
+ count: z.number().default(0),
+ ok: z.number().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get httpGetMonthly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_get_30d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ region: z.enum(flyRegions).optional(),
+ cronTimestamp: z.number().int().optional(),
+ }),
+ data: z.object({
+ type: z.literal("http").default("http"),
+ latency: z.number().int(),
+ statusCode: z.number().int().nullable(),
+ monitorId: z.string(),
+ url: z.string().url(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ message: z.string().nullable(),
+ headers: headersSchema,
+ timing: timingSchema,
+ assertions: z.string().nullable(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ // FIXME: rename to same convension
+ public get getResultForOnDemandCheckHttp() {
+ return this.tb.buildPipe({
+ pipe: "get_result_for_on_demand_check_http",
+ parameters: z.object({
+ monitorId: z.number().int(),
+ timestamp: z.number(),
+ url: z.string(),
+ }),
+ 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(),
+ error: z
+ .number()
+ .default(0)
+ .transform((val) => val !== 0),
+ region: z.enum(flyRegions),
+ timestamp: z.number().int().optional(),
+ message: z.string().nullable().optional(),
+ timing: timingSchema,
+ // TODO: make sure to include all data!
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+ // TODO: add tcpChartDaily, tcpChartWeekly
+
+ public get tcpListDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_1d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("tcp").default("tcp"),
+ latency: z.number().int(),
+ monitorId: z.coerce.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.coerce.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpListWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("tcp").default("tcp"),
+ latency: z.number().int(),
+ monitorId: z.coerce.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.coerce.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpListBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_14d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ type: z.literal("tcp").default("tcp"),
+ latency: z.number().int(),
+ monitorId: z.coerce.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.coerce.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_1d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_7d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_14d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ count: z.number().int(),
+ ok: z.number().int(),
+ lastTimestamp: z.number().int().nullable(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByIntervalDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_interval_1d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByIntervalWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_interval_7d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByIntervalBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_interval_14d__v0",
+ parameters: z.object({
+ interval: z.number().int().optional(),
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ timestamp: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByRegionDaily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_region_1d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByRegionWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_region_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpMetricsByRegionBiweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_metrics_by_region_14d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ region: z.enum(flyRegions),
+ count: z.number().int(),
+ ok: z.number().int(),
+ p50Latency: z.number().nullable().default(0),
+ p75Latency: z.number().nullable().default(0),
+ p90Latency: z.number().nullable().default(0),
+ p95Latency: z.number().nullable().default(0),
+ p99Latency: z.number().nullable().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpStatusWeekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_status_7d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ day: z.string().transform((val) => {
+ // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
+ return new Date(`${val} GMT`).toISOString();
+ }),
+ count: z.number().default(0),
+ ok: z.number().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
+
+ public get tcpStatus45d() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_status_45d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ }),
+ data: z.object({
+ day: z.string().transform((val) => {
+ // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
+ return new Date(`${val} GMT`).toISOString();
+ }),
+ count: z.number().default(0),
+ ok: z.number().default(0),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
-export function getPublicStatus(tb: Tinybird) {
- return tb.buildPipe({
- pipe: "public_status__v0",
- parameters: tbParameterPublicStatus,
- data: tbBuildPublicStatus,
- });
+ public get tcpGetMonthly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_get_30d__v0",
+ parameters: z.object({
+ monitorId: z.string(),
+ region: z.enum(flyRegions).optional(),
+ cronTimestamp: z.number().int().optional(),
+ }),
+ data: z.object({
+ type: z.literal("tcp").default("tcp"),
+ latency: z.number().int(),
+ monitorId: z.string(),
+ error: z.coerce.boolean(),
+ region: z.enum(flyRegions),
+ cronTimestamp: z.number().int(),
+ trigger: z.enum(triggers).nullable().default("cron"),
+ timestamp: z.number(),
+ workspaceId: z.string(),
+ }),
+ opts: { cache: "no-store" },
+ });
+ }
}
diff --git a/packages/tinybird/src/index.ts b/packages/tinybird/src/index.ts
index d00db5067..9991ce7fa 100644
--- a/packages/tinybird/src/index.ts
+++ b/packages/tinybird/src/index.ts
@@ -1,7 +1,3 @@
export * from "./client";
-export * from "./validation";
export * from "./audit-log";
export * from "@chronark/zod-bird";
-
-// OSTinybird: for specific pipes
-export * from "./os-client";
diff --git a/packages/tinybird/src/os-client.ts b/packages/tinybird/src/os-client.ts
deleted file mode 100644
index e21dc3005..000000000
--- a/packages/tinybird/src/os-client.ts
+++ /dev/null
@@ -1,514 +0,0 @@
-import { NoopTinybird, Tinybird } from "@chronark/zod-bird";
-import { z } from "zod";
-
-import { flyRegions } from "../../db/src/schema/constants";
-
-import type { tbIngestWebVitalsArray } from "./validation";
-import {
- responseRumPageQuery,
- sessionRumPageQuery,
- tbIngestWebVitals,
-} from "./validation";
-
-const isProd = process.env.NODE_ENV === "production";
-
-const DEV_CACHE = 3_600; // 1h
-
-const MIN_CACHE = isProd ? 60 : DEV_CACHE; // 60s
-const DEFAULT_CACHE = isProd ? 120 : DEV_CACHE; // 2min
-const _MAX_CACHE = 86_400; // 1d
-
-const VERSION = "v1";
-
-export const latencySchema = z.object({
- p50Latency: z.number().int().nullable(),
- p75Latency: z.number().int().nullable(),
- p90Latency: z.number().int().nullable(),
- p95Latency: z.number().int().nullable(),
- p99Latency: z.number().int().nullable(),
-});
-
-export const timingSchema = z.object({
- dnsStart: z.number(),
- dnsDone: z.number(),
- connectStart: z.number(),
- connectDone: z.number(),
- tlsHandshakeStart: z.number(),
- tlsHandshakeDone: z.number(),
- firstByteStart: z.number(),
- firstByteDone: z.number(),
- transferStart: z.number(),
- transferDone: z.number(),
-});
-
-export class OSTinybird {
- private tb: Tinybird;
-
- // FIXME: use Tinybird instead with super(args) maybe
- // how about passing here the `opts: {revalidate}` to access it within the functions?
- constructor(private args: { token: string; baseUrl?: string | undefined }) {
- if (process.env.NODE_ENV === "development") {
- this.tb = new NoopTinybird();
- } else {
- this.tb = new Tinybird(args);
- }
- }
-
- endpointChart(period: "1h" | "1d" | "3d" | "7d" | "14d") {
- const parameters = z.object({
- interval: z.number().int().optional(),
- monitorId: z.string(),
- });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_chart_get__${VERSION}`,
- parameters,
- data: z
- .object({
- region: z.enum(flyRegions),
- timestamp: z.number().int(),
- })
- .merge(latencySchema),
- opts: {
- cache: "no-store",
- // next: {
- // revalidate: DEFAULT_CACHE,
- // },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointChartAllRegions(period: "7d" | "14d") {
- const parameters = z.object({
- monitorId: z.string(),
- });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_chart_all_regions_get__${VERSION}`, // TODO: add pipe to @openstatus/tinybird
- parameters,
- data: z.object({ timestamp: z.number().int() }).merge(latencySchema),
- opts: {
- cache: "no-store",
- // next: {
- // revalidate: DEFAULT_CACHE,
- // },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointMetrics(period: "1h" | "1d" | "3d" | "7d" | "14d") {
- const parameters = z.object({ monitorId: z.string() });
-
- return async (
- props: z.infer<typeof parameters>,
- opts?: {
- cache?: RequestCache | undefined;
- revalidate: number | undefined;
- }, // RETHINK: not the best way to handle it
- ) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_metrics_get__${VERSION}`,
- parameters,
- data: z
- .object({
- region: z.enum(flyRegions).default("ams"), // FIXME: default
- count: z.number().default(0),
- ok: z.number().default(0),
- lastTimestamp: z.number().int().nullable(),
- })
- .merge(latencySchema),
- opts: {
- cache: opts?.cache,
- next: {
- revalidate: opts?.revalidate || DEFAULT_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointMetricsByRegion(period: "1h" | "1d" | "3d" | "7d" | "14d") {
- const parameters = z.object({ monitorId: z.string() });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_metrics_get_by_region__${VERSION}`,
- parameters,
- data: z
- .object({
- region: z.enum(flyRegions),
- count: z.number().default(0),
- ok: z.number().default(0),
- lastTimestamp: z.number().int().optional(), // FIXME: optional
- })
- .merge(latencySchema),
- opts: {
- cache: "no-store",
- // next: {
- // revalidate: DEFAULT_CACHE,
- // },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointStatusPeriod(
- period: "7d" | "45d",
- timezone: "UTC" = "UTC", // "EST" | "PST" | "CET"
- ) {
- const parameters = z.object({ monitorId: z.string() });
-
- return async (
- props: z.infer<typeof parameters>,
- opts?: {
- cache?: RequestCache | undefined;
- revalidate: number | undefined;
- }, // RETHINK: not the best way to handle it
- ) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_count_${timezone.toLowerCase()}_get__${VERSION}`,
- parameters,
- data: z.object({
- day: z.string().transform((val) => {
- // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
- return new Date(`${val} GMT`).toISOString();
- }),
- count: z.number().default(0),
- ok: z.number().default(0),
- }),
- opts: {
- cache: opts?.cache,
- next: {
- revalidate: opts?.revalidate || DEFAULT_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointList(period: "1h" | "1d" | "3d" | "7d") {
- const parameters = z.object({
- monitorId: z.string(),
- });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_${period}_list_get__${VERSION}`,
- parameters,
- data: z.object({
- latency: z.number().int(), // in ms
- monitorId: z.string(),
- region: z.enum(flyRegions),
- error: z
- .number()
- .default(0)
- .transform((val) => val !== 0),
- statusCode: z.number().int().nullable().default(null),
- timestamp: z.number().int(),
- url: z.string().url(),
- workspaceId: z.string(),
- cronTimestamp: z.number().int().nullable().default(Date.now()),
- assertions: z.string().nullable().optional(),
- trigger: z
- .enum(["cron", "api"])
- .optional()
- .nullable()
- .default("cron"),
- }),
- opts: {
- cache: "no-store",
- // next: {
- // revalidate: DEFAULT_CACHE,
- // },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- // FEATURE: include a simple Widget for the user to refresh the page or display on the top of the page
- // type: "workspace" | "monitor"
- endpointLastCronTimestamp(type: "workspace") {
- const parameters = z.object({ workspaceId: z.string() });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: `__ttl_1h_last_timestamp_${type}_get__${VERSION}`,
- parameters,
- data: z.object({ cronTimestamp: z.number().int() }),
- opts: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- endpointResponseDetails(period: "7d" | "45d") {
- const parameters = z.object({
- monitorId: z.string().default("").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__${VERSION}`,
- 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(),
- error: z
- .number()
- .default(0)
- .transform((val) => val !== 0),
- 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;
- }),
- assertions: z.string().nullable().optional(), // REMINDER: maybe include Assertions.serialize here
- }),
- opts: {
- cache: "no-store",
- // next: {
- // revalidate: MAX_CACHE,
- // },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
- ingestWebVitals(data: z.infer<typeof tbIngestWebVitalsArray>) {
- return this.tb.buildIngestEndpoint({
- datasource: "web_vitals__v0",
- event: tbIngestWebVitals,
- })(data);
- }
-
- applicationRUMMetrics() {
- const parameters = z.object({
- dsn: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- });
-
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: "rum_total_query",
- parameters,
- data: z.object({
- cls: z.number(),
- fcp: z.number(),
- // fid: z.number(),
- lcp: z.number(),
- inp: z.number(),
- ttfb: z.number(),
- }),
- opts: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data[0];
- } catch (e) {
- console.error(e);
- }
- };
- }
- applicationRUMMetricsPerPage() {
- const parameters = z.object({
- dsn: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- });
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: "rum_page_query",
- parameters,
- data: responseRumPageQuery,
- opts: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
- applicationSessionMetricsPerPath() {
- const parameters = z.object({
- dsn: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- path: z.string(),
- });
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: "rum_page_query_per_path",
- parameters,
- data: sessionRumPageQuery,
- opts: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
- applicationRUMMetricsForPath() {
- const parameters = z.object({
- dsn: z.string(),
- path: z.string(),
- period: z.enum(["24h", "7d", "30d"]),
- });
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: "rum_total_query_per_path",
- parameters,
- data: z.object({
- cls: z.number(),
- fcp: z.number(),
- // fid: z.number(),
- lcp: z.number(),
- inp: z.number(),
- ttfb: z.number(),
- }),
- opts: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data[0];
- } catch (e) {
- console.error(e);
- }
- };
- }
-
- getResultForOnDemandCheckHttp() {
- const parameters = z.object({
- monitorId: z.number().int(),
- timestamp: z.number(),
- url: z.string(),
- });
- return async (props: z.infer<typeof parameters>) => {
- try {
- const res = await this.tb.buildPipe({
- pipe: "get_result_for_on_demand_check_http",
- 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(),
- error: z
- .number()
- .default(0)
- .transform((val) => val !== 0),
- region: z.enum(flyRegions),
- timestamp: z.number().int().optional(),
- message: z.string().nullable().optional(),
- 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: {
- next: {
- revalidate: MIN_CACHE,
- },
- },
- })(props);
- return res.data;
- } catch (e) {
- console.error(e);
- }
- };
- }
-}
-
-/**
- * TODO: if it would be possible to...
- */
diff --git a/packages/tinybird/src/schema.ts b/packages/tinybird/src/schema.ts
new file mode 100644
index 000000000..9fd895bda
--- /dev/null
+++ b/packages/tinybird/src/schema.ts
@@ -0,0 +1,48 @@
+import { z } from "zod";
+
+export const jobTypes = ["http", "tcp", "imcp", "udp", "dns", "ssl"] as const;
+export const jobTypeEnum = z.enum(jobTypes);
+export type JobType = z.infer<typeof jobTypeEnum>;
+
+export const periods = ["1h", "1d", "3d", "7d", "14d", "45d"] as const;
+export const periodEnum = z.enum(periods);
+export type Period = z.infer<typeof periodEnum>;
+
+export const triggers = ["cron", "api"] as const;
+export const triggerEnum = z.enum(triggers);
+export type Trigger = z.infer<typeof triggerEnum>;
+
+export const headersSchema = 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;
+ });
+
+export const httpTimingSchema = z.object({
+ dnsStart: z.number(),
+ dnsDone: z.number(),
+ connectStart: z.number(),
+ connectDone: z.number(),
+ tlsHandshakeStart: z.number(),
+ tlsHandshakeDone: z.number(),
+ firstByteStart: z.number(),
+ firstByteDone: z.number(),
+ transferStart: z.number(),
+ transferDone: z.number(),
+});
+
+export const timingSchema = z
+ .string()
+ .nullable()
+ .optional()
+ .transform((val) => {
+ if (!val) return null;
+ const value = httpTimingSchema.safeParse(JSON.parse(val));
+ if (value.success) return value.data;
+ return null;
+ });
diff --git a/packages/tinybird/src/validation.ts b/packages/tinybird/src/validation.ts
deleted file mode 100644
index e769212f8..000000000
--- a/packages/tinybird/src/validation.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import * as z from "zod";
-import { monitorFlyRegionSchema } from "../../db/src/schema/constants";
-import type { flyRegions } from "../../db/src/schema/constants";
-
-export const tbIngestWebVitals = z.object({
- dsn: z.string(),
- href: z.string(),
- speed: z.string(),
- path: z.string(),
- screen: z.string(),
- name: z.string(),
- rating: z.string().optional(),
- value: z.number(),
- id: z.string(),
- session_id: z.string(),
- browser: z.string().default(""),
- city: z.string().default(""),
- country: z.string().default(""),
- continent: z.string().default(""),
- device: z.string().default(""),
- region_code: z.string().default(""),
- timezone: z.string().default(""),
- os: z.string(),
- timestamp: z.number().int(),
-});
-
-export const responseRumPageQuery = z.object({
- path: z.string(),
- totalSession: z.number(),
- cls: z.number(),
- fcp: z.number(),
- // fid: z.number(),
- inp: z.number(),
- lcp: z.number(),
- ttfb: z.number(),
-});
-
-export const sessionRumPageQuery = z.object({
- session_id: z.string(),
- cls: z.number(),
- fcp: z.number(),
- // fid: z.number(),
- inp: z.number(),
- lcp: z.number(),
- ttfb: z.number(),
-});
-
-export const tbIngestWebVitalsArray = z.array(tbIngestWebVitals);
-/**
- * Values for the datasource ping_response
- */
-export const tbIngestPingResponse = z.object({
- workspaceId: z.string(),
- monitorId: z.string(),
- timestamp: z.number().int(),
- statusCode: z.number().int().nullable().optional(),
- latency: z.number(), // in ms
- cronTimestamp: z.number().int().optional().nullable().default(Date.now()),
- url: z.string().url(),
- region: z.string().min(3).max(4), // REMINDER: won't work on fy
- message: z.string().nullable().optional(),
- headers: z.record(z.string(), z.string()).nullable().optional(),
- timing: z
- .object({
- dnsStart: z.number().int(),
- dnsDone: z.number().int(),
- connectStart: z.number().int(),
- connectDone: z.number().int(),
- tlsHandshakeStart: z.number().int(),
- tlsHandshakeDone: z.number().int(),
- firstByteStart: z.number().int(),
- firstByteDone: z.number().int(),
- transferStart: z.number().int(),
- transferDone: z.number().int(),
- })
- .nullable()
- .optional(),
-});
-
-/**
- * Values from the pipe response_list
- */
-export const tbBuildResponseList = z.object({
- workspaceId: z.string(),
- monitorId: z.string(),
- timestamp: z.number().int(),
- error: z
- .number()
- .default(0)
- .transform((val) => val !== 0),
- statusCode: z.number().int().nullable().default(null),
- latency: z.number().int(), // in ms
- cronTimestamp: z.number().int().nullable().default(Date.now()),
- url: z.string().url(),
- region: monitorFlyRegionSchema,
- message: z.string().nullable().optional(),
- assertions: z.string().nullable().optional(),
- trigger: z.enum(["cron", "api"]).optional().nullable().default("cron"),
-});
-
-/**
- * Params for pipe response_list
- */
-export const tbParameterResponseList = z.object({
- monitorId: z.string().default(""), // REMINDER: remove default once alpha
- url: z.string().url().optional(),
- fromDate: z.number().int().default(0), // always start from a date
- toDate: z.number().int().optional(),
- limit: z.number().int().optional().default(7500), // one day has 2448 pings (17 (regions) * 6 (per hour) * 24) * 3 days for historical data
- region: monitorFlyRegionSchema.optional(),
- cronTimestamp: z.number().int().optional(),
-});
-
-/**
- * Params for pipe response_details
- */
-export const tbParameterResponseDetails = tbParameterResponseList.pick({
- monitorId: true,
- url: true,
- cronTimestamp: true,
- region: true,
-});
-
-export const responseHeadersSchema = z.record(z.string(), z.string());
-export const responseTimingSchema = z.object({
- dnsStart: z.number(),
- dnsDone: z.number(),
- connectStart: z.number(),
- connectDone: z.number(),
- tlsHandshakeStart: z.number(),
- tlsHandshakeDone: z.number(),
- firstByteStart: z.number(),
- firstByteDone: z.number(),
- transferStart: z.number(),
- transferDone: z.number(),
-});
-
-/**
- * Values from the pipe response_details
- */
-export const tbBuildResponseDetails = tbBuildResponseList.extend({
- message: z.string().nullable().optional(),
- headers: z
- .string()
- .nullable()
- .optional()
- .transform((val) => {
- if (!val) return null;
- const value = responseHeadersSchema.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 = responseTimingSchema.safeParse(JSON.parse(val));
- if (value.success) return value.data;
- return null;
- }),
-});
-
-export const latencyMetrics = z.object({
- p50Latency: z.number().int().nullable(),
- p75Latency: z.number().int().nullable(),
- p90Latency: z.number().int().nullable(),
- p95Latency: z.number().int().nullable(),
- p99Latency: z.number().int().nullable(),
-});
-
-/**
- * Values from pipe response_graph
- */
-export const tbBuildResponseGraph = z
- .object({
- region: monitorFlyRegionSchema,
- timestamp: z.number().int(),
- })
- .merge(latencyMetrics);
-
-/**
- * Params for pipe response_graph
- */
-export const tbParameterResponseGraph = z.object({
- monitorId: z.string().default(""),
- url: z.string().url().optional(),
- interval: z.number().int().default(10),
- fromDate: z.number().int().default(0),
- toDate: z.number().int().optional(),
-});
-
-/**
- * Params for pipe status_timezone
- */
-export const tbParameterMonitorList = z.object({
- monitorId: z.string(),
- url: z.string().url().optional(),
- timezone: z.string().optional(),
- limit: z.number().int().default(46).optional(), // 46 days
-});
-
-/**
- * Values from the pipe status_timezone
- */
-export const tbBuildMonitorList = z.object({
- count: z.number().int(),
- ok: z.number().int(),
- day: z.string().transform((val) => {
- // That's a hack because clickhouse return the date in UTC but in shitty format (2021-09-01 00:00:00)
- return new Date(`${val} GMT`).toISOString();
- }),
-});
-
-/**
- * Params for pipe home_stats
- */
-export const tbParameterHomeStats = z.object({
- cronTimestamp: z.number().int().optional(),
- period: z.enum(["total", "1h", "10m"]).optional(),
-});
-
-/**
- * Values from the pipe home_stats
- */
-export const tbBuildHomeStats = z.object({
- count: z.number().int(),
-});
-
-/**
- * Params for pipe public_status (used for our API /public/status/[slug])
- */
-export const tbParameterPublicStatus = z.object({
- monitorId: z.string(),
- url: z.string().url().optional(),
- limit: z.number().int().default(5).optional(), // 5 last cronTimestamps
-});
-
-/**
- * Values from the pipe public_status (used for our API /public/status/[slug])
- */
-export const tbBuildPublicStatus = z.object({
- ok: z.number().int(),
- count: z.number().int(),
- cronTimestamp: z.number().int(),
-});
-
-/**
- * Params for pipe response_time_metrics
- */
-export const tbParameterResponseTimeMetrics = z.object({
- monitorId: z.string(),
- url: z.string().url().optional(),
- interval: z.number().int().default(24), // 24 hours
-});
-
-/**
- * Values from the pipe response_time_metrics
- */
-export const tbBuildResponseTimeMetrics = z
- .object({
- count: z.number().int(),
- ok: z.number().int(),
- lastTimestamp: z.number().int().nullable().optional(),
- })
- .merge(latencyMetrics);
-
-/**
- * Params for pipe response_time_metrics_by_region
- */
-export const tbParameterResponseTimeMetricsByRegion = z.object({
- monitorId: z.string(),
- url: z.string().url().optional(),
- interval: z.number().int().default(24), // 24 hours
-});
-
-/**
- * Values from the pipe response_time_metrics_by_region
- */
-export const tbBuildResponseTimeMetricsByRegion = z
- .object({
- region: monitorFlyRegionSchema,
- })
- .merge(latencyMetrics);
-
-export type Ping = z.infer<typeof tbBuildResponseList>;
-export type Region = (typeof flyRegions)[number]; // TODO: rename type AvailabeRegion
-export type Monitor = z.infer<typeof tbBuildMonitorList>;
-export type HomeStats = z.infer<typeof tbBuildHomeStats>;
-export type ResponseGraph = z.infer<typeof tbBuildResponseGraph>; // TODO: rename to ResponseQuantileChart
-export type ResponseListParams = z.infer<typeof tbParameterResponseList>;
-export type ResponseGraphParams = z.infer<typeof tbParameterResponseGraph>;
-export type MonitorListParams = z.infer<typeof tbParameterMonitorList>;
-export type HomeStatsParams = z.infer<typeof tbParameterHomeStats>;
-export type ResponseDetails = z.infer<typeof tbBuildResponseDetails>;
-export type ResponseDetailsParams = z.infer<typeof tbParameterResponseDetails>;
-export type LatencyMetric = keyof z.infer<typeof latencyMetrics>;
-export type ResponseTimeMetrics = z.infer<typeof tbBuildResponseTimeMetrics>;
-export type ResponseTimeMetricsParams = z.infer<
- typeof tbParameterResponseTimeMetrics
->;
-export type ResponseTimeMetricsByRegion = z.infer<
- typeof tbBuildResponseTimeMetricsByRegion
->;
-export type ResponseTimeMetricsByRegionParams = z.infer<
- typeof tbParameterResponseTimeMetricsByRegion
->;
diff --git a/packages/tracker/src/tracker.ts b/packages/tracker/src/tracker.ts
index 6384bd7f7..e96bec6fc 100644
--- a/packages/tracker/src/tracker.ts
+++ b/packages/tracker/src/tracker.ts
@@ -4,7 +4,6 @@ import type {
StatusReport,
StatusReportUpdate,
} from "@openstatus/db/src/schema";
-import type { Monitor } from "@openstatus/tinybird";
import { isInBlacklist } from "./blacklist";
import { classNames, statusDetails } from "./config";
@@ -12,7 +11,11 @@ import type { StatusDetails, StatusVariant } from "./types";
import { Status } from "./types";
import { endOfDay, isSameDay, startOfDay } from "./utils";
-type Monitors = Monitor[];
+type Monitor = {
+ count: number;
+ ok: number;
+ day: string;
+};
type StatusReports = (StatusReport & {
statusReportUpdates?: StatusReportUpdate[];
})[];
@@ -26,13 +29,13 @@ type Maintenances = Maintenance[];
* StatusPage with multiple Monitors.
*/
export class Tracker {
- private data: Monitors = [];
+ private data: Monitor[] = [];
private statusReports: StatusReports = [];
private incidents: Incidents = [];
private maintenances: Maintenances = [];
constructor(arg: {
- data?: Monitors;
+ data?: Monitor[];
statusReports?: StatusReports;
incidents?: Incidents;
maintenances?: Maintenance[];