Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: checker playground (#581)
Maximilian Kaske7291a3b383b5
diff --git a/apps/checker/Dockerfile b/apps/checker/Dockerfileindex 6bc505d65..e61cb2ae7 100644--- a/apps/checker/Dockerfile+++ b/apps/checker/Dockerfile@@ -16,6 +16,7 @@ RUN go build -o openstatus-checker ./cmdFROM golang:1.21COPY --from=builder /go/src/github.com/openstatushq/openstatus/apps/checker/openstatus-checker /usr/local/bin/openstatus-checker-+# Set gin to release mode+ENV GIN_MODE=releaseCMD ["/usr/local/bin/openstatus-checker"]\ No newline at end of filediff --git a/apps/checker/cmd/main.go b/apps/checker/cmd/main.goindex 9deab4349..2d00178c3 100644--- a/apps/checker/cmd/main.go+++ b/apps/checker/cmd/main.go@@ -79,10 +79,16 @@ func main() {c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})return}+ // We need a new client for each request to avoid connection reuse.+ requestClient := &http.Client{+ Timeout: 45 * time.Second,+ }+ defer requestClient.CloseIdleConnections()+var called intop := func() error {called++- res, err := checker.Ping(ctx, httpClient, req)+ res, err := checker.Ping(ctx, requestClient, req)if err != nil {return fmt.Errorf("unable to ping: %w", err)}@@ -93,7 +99,7 @@ func main() {return fmt.Errorf("unable to ping: %v with status %v", res, res.StatusCode)}- if !statusCode.IsSuccessful() {+ if !statusCode.IsSuccessful() && req.Status == "active" {// Q: Why here we do not check if the status was previously active?checker.UpdateStatus(ctx, checker.UpdateData{MonitorId: req.MonitorID,@@ -158,10 +164,11 @@ func main() {c.String(http.StatusBadRequest, "region is required")return}+ fmt.Printf("Start of /ping/%s\n", region)+apiKey := c.GetHeader("x-openstatus-key")if apiKey == "" {c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})-return}@@ -180,6 +187,11 @@ func main() {c.String(http.StatusAccepted, "Forwarding request to %s", region)return}+ // We need a new client for each request to avoid connection reuse.+ requestClient := &http.Client{+ Timeout: 45 * time.Second,+ }+ defer requestClient.CloseIdleConnections()var req request.PingRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -188,7 +200,7 @@ func main() {return}- res, err := checker.SinglePing(c.Request.Context(), httpClient, req)+ res, err := checker.SinglePing(c.Request.Context(), requestClient, req)if err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})returndiff --git a/apps/docs/api-reference/checker.mdx b/apps/docs/api-reference/checker.mdxnew file mode 100644index 000000000..4fb71cbf1--- /dev/null+++ b/apps/docs/api-reference/checker.mdx@@ -0,0 +1,89 @@+---+title: Checker+---++You can use the checker to check the status of your services. The checker is a+global service that runs on Fly.io machines and is available in the following+supported regions:++- `ams` (Amsterdam)+- `hkg` (Hong-Kong)+- `iad` (Northern Virginia)+- `gru` (São Paulo)+- `syd` (Sydney)+- `jnb` (Johannesburg)++Send a `POST` request to `https://checker.openstatus.dev/ping/[region]` with the+`url` and `method` as `body` props.++<Note>+ You might want to define the `prefer-fly-region: [region]` header+ additionally.+</Note>++### Example++```bash+curl --request POST \+ --url https://checker.openstatus.dev/ping/ams \+ --header 'Content-Type: application/json' \+ --header 'x-openstatus-key: <YOUR_API_KEY>' \+ --header 'prefer-fly-region: ams' \+ --data '{+ "url": "https://api.openstatus.dev/ping",+ "method": "GET"+}'+```++Response:++```json+{+ "status": 200,+ "latency": 18,+ "headers": {+ "Content-Type": "application/json; charset=UTF-8",+ "Date": "Sat, 20 Jan 2024 16:31:18 GMT",+ "Fly-Request-Id": "01HMKVCQ9P2CBDS5GPFBN8EVYP-ams",+ "Server": "Fly/f9c163a6 (2024-01-16)",+ "Via": "2 fly.io"+ },+ "time": 1705768279337,+ "timing": {+ "dnsStart": 1705768279337,+ "dnsDone": 1705768279343,+ "connectStart": 1705768279343,+ "connectDone": 1705768279343,+ "tlsHandshakeStart": 1705768279343,+ "tlsHandshakeDone": 1705768279350,+ "firstByteStart": 1705768279350,+ "firstByteDone": 1705768279355,+ "transferStart": 1705768279355,+ "transferDone": 1705768279355+ }+}+```++All timestamps are in UNIX epoch milliseconds. The response `headers` are+unknown key value string pairs. All other props are fixed.++```ts+type CheckerResponse = {+ status: number;+ latency: number;+ headers: Record<string, string>;+ time: number;+ timing: {+ dnsStart: number;+ dnsDone: number;+ connectStart: number;+ connectDone: number;+ tlsHandshakeStart: number;+ tlsHandshakeDone: number;+ firstByteStart: number;+ firstByteDone: number;+ transferStart: number;+ transferDone: number;+ };+};+```diff --git a/apps/docs/mint.json b/apps/docs/mint.jsonindex d0d05a8ce..9b7408648 100644--- a/apps/docs/mint.json+++ b/apps/docs/mint.json@@ -140,7 +140,8 @@"api-reference/status_report_update/get-status_report_update:id","api-reference/status_report_update/post-status_report_update"]- }+ },+ "api-reference/checker"]}],diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 8f3965ff8..89677cb13 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -72,3 +72,5 @@ GCP_PRIVATE_KEY=CRON_SECRET=EXTERNAL_API_URL=++PLAYGROUND_UNKEY_API_KEY=\ No newline at end of filediff --git a/apps/web/public/assets/changelog/checker-playground.png b/apps/web/public/assets/changelog/checker-playground.pngnew file mode 100644index 000000000..d14bb7573Binary files /dev/null and b/apps/web/public/assets/changelog/checker-playground.png differdiff --git a/apps/web/src/app/play/_components/header-play.tsx b/apps/web/src/app/play/_components/header-play.tsxnew file mode 100644index 000000000..1c3f3e713--- /dev/null+++ b/apps/web/src/app/play/_components/header-play.tsx@@ -0,0 +1,11 @@+export function HeaderPlay({+ title,+ description,+}: Record<"title" | "description", string>) {+ return (+ <div className="mx-auto grid max-w-md gap-4 text-center">+ <p className="font-cal mb-1 text-3xl">{title}</p>+ <p className="text-muted-foreground">{description}</p>+ </div>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/copy-link-button.tsx b/apps/web/src/app/play/checker/[id]/_components/copy-link-button.tsxnew file mode 100644index 000000000..605c44fc4--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/copy-link-button.tsx@@ -0,0 +1,50 @@+"use client";++import * as React from "react";++import {+ Button,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@openstatus/ui";++import { Icons } from "@/components/icons";+import { copyToClipboard } from "@/lib/utils";++export function CopyLinkButton() {+ const [hasCopied, setHasCopied] = React.useState(false);++ React.useEffect(() => {+ if (hasCopied) {+ setTimeout(() => {+ setHasCopied(false);+ }, 2000);+ }+ }, [hasCopied]);+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={() => {+ if (typeof window === "undefined") return;+ copyToClipboard(window.location.href);+ setHasCopied(true);+ }}+ size="icon"+ variant="ghost"+ >+ {!hasCopied ? (+ <Icons.link className="h-4 w-4" />+ ) : (+ <Icons.check className="h-4 w-4" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>Copy link</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/copy-to-clipboard-button.tsx b/apps/web/src/app/play/checker/[id]/_components/copy-to-clipboard-button.tsxnew file mode 100644index 000000000..596f80d47--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/copy-to-clipboard-button.tsx@@ -0,0 +1,39 @@+"use client";++import * as React from "react";++import { Icons } from "@/components/icons";+import { cn, copyToClipboard } from "@/lib/utils";++// TODO: make a generic copy to clipboard button++interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {+ copyValue: string;+}++export function CopyToClipboardButton({ copyValue, className }: Props) {+ const [hasCopied, setHasCopied] = React.useState(false);++ React.useEffect(() => {+ if (hasCopied) {+ setTimeout(() => {+ setHasCopied(false);+ }, 2000);+ }+ }, [hasCopied]);+ return (+ <button+ onClick={() => {+ copyToClipboard(copyValue);+ setHasCopied(true);+ }}+ className={cn("text-muted-foreground hover:text-foreground", className)}+ >+ {!hasCopied ? (+ <Icons.copy className="h-3 w-3" />+ ) : (+ <Icons.check className="h-3 w-3" />+ )}+ </button>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/multi-region-chart.tsx b/apps/web/src/app/play/checker/[id]/_components/multi-region-chart.tsxnew file mode 100644index 000000000..304805f66--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/multi-region-chart.tsx@@ -0,0 +1,34 @@+"use client";++import { BarChart } from "@tremor/react";++import type { RegionChecker } from "../utils";+import { getTimingPhases, latencyFormatter, regionFormatter } from "../utils";++export function MultiRegionChart({ regions }: { regions: RegionChecker[] }) {+ const data = regions.map((item) => {+ const { dns, connection, tls, ttfb, transfer } = getTimingPhases(+ item.timing,+ );+ return {+ region: regionFormatter(item.region),+ dns,+ connection,+ tls,+ ttfb,+ transfer,+ };+ });+ return (+ <BarChart+ data={data}+ index="region"+ categories={["dns", "connection", "tls", "ttfb", "transfer"]}+ colors={["blue", "teal", "amber", "slate", "indigo"]}+ valueFormatter={latencyFormatter}+ stack+ layout="vertical"+ yAxisWidth={65}+ />+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsx b/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsxnew file mode 100644index 000000000..565740acc--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsx@@ -0,0 +1,71 @@+import {+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui";++import type { RegionChecker } from "../utils";+import {+ getTimingPhases,+ getTotalLatency,+ latencyFormatter,+ regionFormatter,+} from "../utils";+import { StatusBadge } from "./status-badge";++// TBD: add the popover infos about timing details++export function MultiRegionTable({ regions }: { regions: RegionChecker[] }) {+ return (+ <Table>+ <TableCaption>Multi Regions</TableCaption>+ <TableHeader>+ <TableRow>+ <TableHead>Region</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>DNS</TableHead>+ <TableHead>Connect</TableHead>+ <TableHead>TLS</TableHead>+ <TableHead>TTFB</TableHead>+ <TableHead>Total</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {regions.map(({ region, status, timing }) => {+ const { dns, connection, tls, ttfb, transfer } =+ getTimingPhases(timing);+ const total = getTotalLatency(timing);+ return (+ <TableRow key={region}>+ <TableCell className="font-medium">+ {regionFormatter(region)}+ </TableCell>+ <TableCell>+ <StatusBadge statusCode={status} />+ </TableCell>+ <TableCell className="text-muted-foreground">+ <code>{latencyFormatter(dns)}</code>+ </TableCell>+ <TableCell className="text-muted-foreground">+ <code>{latencyFormatter(connection)}</code>+ </TableCell>+ <TableCell className="text-muted-foreground">+ <code>{latencyFormatter(tls)}</code>+ </TableCell>+ <TableCell className="text-muted-foreground">+ <code>{latencyFormatter(ttfb)}</code>+ </TableCell>+ <TableCell>+ <code>{latencyFormatter(total)}</code>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/multi-region-tabs.tsx b/apps/web/src/app/play/checker/[id]/_components/multi-region-tabs.tsxnew file mode 100644index 000000000..6c4363501--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/multi-region-tabs.tsx@@ -0,0 +1,22 @@+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@openstatus/ui";++import type { RegionChecker } from "../utils";+import { MultiRegionChart } from "./multi-region-chart";+import { MultiRegionTable } from "./multi-region-table";++export function MultiRegionTabs({ regions }: { regions: RegionChecker[] }) {+ return (+ <Tabs defaultValue="chart">+ <TabsList>+ <TabsTrigger value="chart">Chart</TabsTrigger>+ <TabsTrigger value="table">Table</TabsTrigger>+ </TabsList>+ <TabsContent value="chart">+ <MultiRegionChart regions={regions} />+ </TabsContent>+ <TabsContent value="table">+ <MultiRegionTable regions={regions} />+ </TabsContent>+ </Tabs>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/region-info.tsx b/apps/web/src/app/play/checker/[id]/_components/region-info.tsxnew file mode 100644index 000000000..3faff144a--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/region-info.tsx@@ -0,0 +1,40 @@+import {+ latencyFormatter,+ regionFormatter,+ timestampFormatter,+} from "../utils";+import type { RegionChecker } from "../utils";+import { StatusBadge } from "./status-badge";++export function RegionInfo({ check }: { check: RegionChecker }) {+ return (+ <div className="grid grid-cols-4 gap-2 text-sm sm:grid-cols-6">+ <div className="col-span-1">+ <p className="text-muted-foreground">Time:</p>+ </div>+ <div className="col-span-3 sm:col-span-5">+ <p>{timestampFormatter(check.time)}</p>+ </div>+ <div className="col-span-1">+ <p className="text-muted-foreground">Region:</p>+ </div>+ <div className="col-span-3 sm:col-span-5">+ <p>{regionFormatter(check.region)}</p>+ </div>+ <div className="col-span-1">+ <p className="text-muted-foreground">Latency:</p>+ </div>+ <div className="col-span-3 sm:col-span-5">+ <p>+ <code>{latencyFormatter(check.latency)}</code>+ </p>+ </div>+ <div className="col-span-1">+ <p className="text-muted-foreground">Status:</p>+ </div>+ <div className="col-span-3 sm:col-span-5">+ <StatusBadge statusCode={check.status} />+ </div>+ </div>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsxnew file mode 100644index 000000000..f3a532525--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx@@ -0,0 +1,55 @@+import { Copy } from "lucide-react";++import {+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui";++import { CopyToClipboardButton } from "./copy-to-clipboard-button";++export function ResponseHeaderTable({+ headers,+}: {+ headers: Record<string, string>;+}) {+ return (+ <Table>+ <TableCaption>Response Headers</TableCaption>+ <TableHeader>+ <TableRow>+ <TableHead className="md:min-w-[200px]">Key</TableHead>+ <TableHead>Value</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {Object.entries(headers).map(([key, value]) => (+ <TableRow key={key}>+ <TableCell className="group">+ <div className="flex items-center justify-between gap-4">+ <code className="font-medium">{key}</code>+ <CopyToClipboardButton+ copyValue={key}+ className="invisible group-hover:visible"+ />+ </div>+ </TableCell>+ <TableCell className="group">+ <div className="flex items-center justify-between gap-4">+ <code>{value}</code>+ <CopyToClipboardButton+ copyValue={value}+ className="invisible group-hover:visible"+ />+ </div>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx b/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsxnew file mode 100644index 000000000..fbee15407--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/response-timing-table.tsx@@ -0,0 +1,73 @@+import { Info } from "lucide-react";++import {+ Popover,+ PopoverContent,+ PopoverTrigger,+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui";++import { timingDict } from "../config";+import type { Timing } from "../utils";+import { getTimingPhases, getTotalLatency } from "../utils";++export function ResponseTimingTable({ timing }: { timing: Timing }) {+ const total = getTotalLatency(timing);+ const timingPhases = getTimingPhases(timing);+ return (+ <Table>+ <TableCaption>Response Timing</TableCaption>+ <TableHeader>+ <TableRow>+ <TableHead className="w-[120px] md:w-[150px]">Timing</TableHead>+ <TableHead className="w-[120px] md:w-[150px]">Duration</TableHead>+ <TableHead></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {Object.entries(timingPhases).map(([key, value]) => {+ const { short, long, description } =+ timingDict[key as keyof typeof timingPhases];+ return (+ <TableRow key={key}>+ <TableCell>+ <div className="flex w-[80px] items-center justify-between gap-2">+ <p className="text-muted-foreground">{short}</p>+ <Popover>+ <PopoverTrigger className="text-muted-foreground hover:text-foreground data-[state=open]:text-foreground">+ <Info className="h-4 w-4" />+ </PopoverTrigger>+ <PopoverContent>+ <p className="font-medium">{long}</p>+ <p className="text-muted-foreground text-sm">+ {description}+ </p>+ </PopoverContent>+ </Popover>+ </div>+ </TableCell>+ <TableCell>+ <code>{value}ms</code>+ </TableCell>+ <TableCell>+ <div+ className="bg-foreground h-3 rounded-md"+ style={{+ width: `${(value / total) * 100}%`,+ minWidth: "1px",+ }}+ />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/select-region.tsx b/apps/web/src/app/play/checker/[id]/_components/select-region.tsxnew file mode 100644index 000000000..777640ddb--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/select-region.tsx@@ -0,0 +1,59 @@+"use client";++import { usePathname, useRouter } from "next/navigation";++import type { MonitorFlyRegion } from "@openstatus/db/src/schema";+import { flyRegions } from "@openstatus/db/src/schema";+import {+ Label,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@openstatus/ui";++import useUpdateSearchParams from "@/hooks/use-update-search-params";+import { regionFormatter } from "../utils";++export function SelectRegion({+ defaultValue,+}: {+ defaultValue?: MonitorFlyRegion;+}) {+ const router = useRouter();+ const pathname = usePathname();+ const updateSearchParams = useUpdateSearchParams();++ function onSelect(value: string) {+ const searchParams = updateSearchParams({ region: value });+ router.replace(`${pathname}?${searchParams}`, { scroll: false });+ }++ return (+ <div className="grid gap-1.5">+ <Label htmlFor="region">Region</Label>+ <Select onValueChange={onSelect} defaultValue={defaultValue}>+ <SelectTrigger+ id="region"+ name="region"+ className="w-full sm:w-[240px]"+ >+ <span className="flex items-center gap-2">+ <SelectValue />+ </span>+ </SelectTrigger>+ <SelectContent>+ {flyRegions.map((region) => (+ <SelectItem key={region} value={region}>+ {regionFormatter(region, "long")}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-muted-foreground text-sm">+ Select a region to inspect closer+ </p>+ </div>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx b/apps/web/src/app/play/checker/[id]/_components/status-badge.tsxnew file mode 100644index 000000000..ad57ba90d--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx@@ -0,0 +1,24 @@+import { Badge } from "@openstatus/ui";++import { cn } from "@/lib/utils";++export function StatusBadge({ statusCode }: { statusCode: number }) {+ const green = String(statusCode).startsWith("2");+ const blue = String(statusCode).startsWith("3");+ const red =+ String(statusCode).startsWith("4") || String(statusCode).startsWith("5");+ return (+ <Badge+ variant="outline"+ className={cn("font-mono", {+ "border-green-500/20 bg-green-500/10 text-green-800 dark:text-green-300":+ green,+ "border-blue-500/20 bg-blue-500/10 text-blue-800 dark:text-blue-300":+ blue,+ "border-red-500/20 bg-red-500/10 text-red-800 dark:text-red-300": red,+ })}+ >+ {statusCode}+ </Badge>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/config.ts b/apps/web/src/app/play/checker/[id]/config.tsnew file mode 100644index 000000000..6d85de246--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/config.ts@@ -0,0 +1,32 @@+export const timingDict = {+ dns: {+ short: "DNS",+ long: "DNS Lookup",+ description:+ "Time spent performing the DNS lookup. DNS lookup resolves domain names to IP addresses. Every new domain requires a full round trip to do the DNS lookup. There is no DNS lookup when the destination is already an IP address.",+ },+ connection: {+ short: "TCP",+ long: "Initial Connection",+ description:+ "Time it took to establish TCP connection between a source host and destination host. Connections must be properly established in a multi-step handshake process. TCP connection is managed by an operating system, if the underlying TCP connection cannot be established, the OS-wide TCP connection timeout will overrule the timeout config of our application.",+ },+ tls: {+ short: "TLS",+ long: "TLS Handshake",+ description:+ "Time spent completing a TLS handshake. During the handshake process endpoints exchange authentication and keys to establish or resume secure sessions. There is no TLS handshake with a not HTTPS request.",+ },+ ttfb: {+ short: "TTFB",+ long: "Time to First Byte",+ description:+ "Time spent waiting for the initial response. This time captures the latency of a round trip to the server in addition to the time spent waiting for the server to process the request and deliver the response.",+ },+ transfer: {+ short: "Transfer",+ long: "Content Transfer",+ description:+ "Time spent receiving the response data. The size of the response data and the available network bandwidth determinates its duration.",+ },+} as const;diff --git a/apps/web/src/app/play/checker/[id]/page.tsx b/apps/web/src/app/play/checker/[id]/page.tsxnew file mode 100644index 000000000..85630792f--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/page.tsx@@ -0,0 +1,92 @@+import Link from "next/link";+import { redirect } from "next/navigation";+import * as z from "zod";++import { monitorFlyRegionSchema } from "@openstatus/db/src/schema";+import { Separator } from "@openstatus/ui";++import { Shell } from "@/components/dashboard/shell";+import { BackButton } from "@/components/layout/back-button";+import { CopyLinkButton } from "./_components/copy-link-button";+import { MultiRegionTabs } from "./_components/multi-region-tabs";+import { RegionInfo } from "./_components/region-info";+import { ResponseHeaderTable } from "./_components/response-header-table";+import { ResponseTimingTable } from "./_components/response-timing-table";+import { SelectRegion } from "./_components/select-region";+import { getCheckerDataById, timestampFormatter } from "./utils";++/**+ * allowed URL search params+ */+const searchParamsSchema = z.object({+ region: monitorFlyRegionSchema.optional(),+});++export default async function CheckPage({+ params,+ searchParams,+}: {+ params: { id: string };+ searchParams: { [key: string]: string | string[] | undefined };+}) {+ const search = searchParamsSchema.safeParse(searchParams);++ const selectedRegion = search.success ? search.data.region : undefined;++ const data = await getCheckerDataById(params.id);++ if (!data) redirect("/play/checker");++ const check =+ data.checks.find((i) => i.region === selectedRegion) || data.checks?.[0];++ const { status, region, headers, latency, timing } = check;++ return (+ <>+ <BackButton href="/play/checker" />+ <Shell className="grid gap-8">+ <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col gap-1">+ <h1 className="text-3xl font-semibold">+ <span className="truncate">{data.url}</span>+ </h1>+ <p className="text-muted-foreground">+ {timestampFormatter(data.time)}+ </p>+ </div>+ <div>+ <CopyLinkButton />+ </div>+ </div>+ <MultiRegionTabs regions={data.checks} />+ <Separator />+ <div className="grid gap-8">+ <div className="grid gap-8 md:grid-cols-2">+ <div>+ <SelectRegion defaultValue={region} />+ </div>+ <div>+ <RegionInfo check={check} />+ </div>+ </div>+ <ResponseTimingTable timing={timing} />+ <ResponseHeaderTable headers={headers} />+ </div>+ <Separator />+ <p className="text-muted-foreground text-sm">+ The data will be stored for{" "}+ <span className="text-foreground">1 day</span>. If you want to persist+ the data,{" "}+ <Link+ href="/app/sign-in"+ className="text-foreground underline underline-offset-4 hover:no-underline"+ >+ login+ </Link>{" "}+ to your account.+ </p>+ </Shell>+ </>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/utils.ts b/apps/web/src/app/play/checker/[id]/utils.tsnew file mode 100644index 000000000..00acce63c--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/utils.ts@@ -0,0 +1,159 @@+import { Redis } from "@upstash/redis";+import { z } from "zod";++import { flyRegions, monitorFlyRegionSchema } from "@openstatus/db/src/schema";+import type { MonitorFlyRegion } from "@openstatus/db/src/schema";+import { flyRegionsDict } from "@openstatus/utils";++export function latencyFormatter(value: number) {+ return `${new Intl.NumberFormat("us").format(value).toString()}ms`;+}++export function timestampFormatter(timestamp: number) {+ return new Date(timestamp).toLocaleString(); // TODO: properly format the date+}++export function regionFormatter(+ region: MonitorFlyRegion,+ type: "short" | "long" = "short",+) {+ const { code, flag, location } = flyRegionsDict[region];+ if (type === "short") return `${code} ${flag}`;+ return `${location}`;+}++export function getTotalLatency(timing: Timing) {+ const { dns, connection, tls, ttfb, transfer } = getTimingPhases(timing);+ return dns + connection + tls + ttfb + transfer;+}++export function getTimingPhases(timing: Timing) {+ const dns = timing.dnsDone - timing.dnsStart;+ const connection = timing.connectDone - timing.connectStart;+ const tls = timing.tlsHandshakeDone - timing.tlsHandshakeStart;+ const ttfb = timing.firstByteDone - timing.firstByteStart;+ const transfer = timing.transferDone - timing.transferStart;++ return {+ dns,+ connection,+ tls,+ ttfb,+ transfer,+ };+}++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 const checkerSchema = z.object({+ status: z.number(),+ latency: z.number(),+ headers: z.record(z.string()),+ time: z.number(),+ timing: timingSchema,+});++export const cachedCheckerSchema = z.object({+ url: z.string(),+ time: z.number(),+ method: z.enum(["GET", "POST", "PUT", "DELETE"]).default("GET"),+ checks: checkerSchema.extend({ region: monitorFlyRegionSchema }).array(),+});++export type Timing = z.infer<typeof timingSchema>;+export type Checker = z.infer<typeof checkerSchema>;+export type RegionChecker = Checker & { region: MonitorFlyRegion };+export type Method = "GET" | "POST" | "PUT" | "DELETE";++export async function checkRegion(+ url: string,+ region: MonitorFlyRegion,+ opts?: { method: Method },+) {+ //+ const res = await fetch(`https://checker.openstatus.dev/ping/${region}`, {+ headers: {+ "Content-Type": "application/json",+ // TODO: move to @/env+ "x-openstatus-key": process.env.PLAYGROUND_UNKEY_API_KEY!,+ "fly-prefer-region": region,+ },+ method: "POST",+ body: JSON.stringify({ url, method: opts?.method || "GET" }),+ // cache: "force-cache",+ next: { revalidate: 0 },+ });++ const json = await res.json();++ const data = checkerSchema.safeParse(json);++ if (!data.success) {+ throw new Error(data.error.message);+ }++ return {+ region,+ ...data.data,+ };+}++export async function checkAllRegions(url: string, opts?: { method: Method }) {+ // TODO: settleAll+ return await Promise.all(+ flyRegions.map(async (region) => {+ const check = await checkRegion(url, region, opts);+ return check;+ }),+ );+}++// TODO: add opts: { method: Method }+export async function setCheckerData(url: string, opts?: { method: Method }) {+ const redis = Redis.fromEnv();+ const time = new Date().getTime();+ const checks = await checkAllRegions(url, opts);+ const { method } = opts || {};++ const cache = { time, url, checks, method };++ const uuid = crypto.randomUUID().replace(/-/g, "");++ const parsed = cachedCheckerSchema.safeParse(cache);++ if (!parsed.success) {+ throw new Error(parsed.error.message);+ }++ await redis.set(uuid, JSON.stringify(parsed.data), { ex: 86_400 }); // 60 * 60 * 24 = 1d++ return uuid;+}++export async function getCheckerDataById(id: string) {+ const redis = Redis.fromEnv();+ const cache = await redis.get(id);++ if (!cache) {+ return null;+ }++ const parsed = cachedCheckerSchema.safeParse(cache);++ if (!parsed.success) {+ throw new Error(parsed.error.message);+ }++ return parsed.data;+}diff --git a/apps/web/src/app/play/checker/_components/checker-form.tsx b/apps/web/src/app/play/checker/_components/checker-form.tsxnew file mode 100644index 000000000..83ef7216f--- /dev/null+++ b/apps/web/src/app/play/checker/_components/checker-form.tsx@@ -0,0 +1,117 @@+"use client";++import { useTransition } from "react";+import { useRouter } from "next/navigation";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import * as z from "zod";++import {+ Button,+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@openstatus/ui";++import { LoadingAnimation } from "@/components/loading-animation";++const METHODS = ["GET", "POST", "PUT", "DELETE"] as const;++const formSchema = z.object({+ url: z.string().url(), // add pattern and use InputWithAddon `https://`+ method: z.enum(METHODS).default("GET"),+});++type FormSchema = z.infer<typeof formSchema>;++export function CheckerForm() {+ const router = useRouter();+ const [isPending, startTransition] = useTransition();+ const form = useForm<FormSchema>({+ resolver: zodResolver(formSchema),+ defaultValues: { method: "GET", url: "" },+ });++ function onSubmit(data: FormSchema) {+ startTransition(async () => {+ const { url, method } = data;+ try {+ const res = await fetch("/play/checker/api", {+ method: "POST",+ body: JSON.stringify({ url, method }),+ });+ const { uuid } = (await res.json()) as { uuid?: string };+ if (typeof uuid === "string") {+ router.push(`/play/checker/${uuid}`);+ }+ } catch {+ // TODO: better error handling, including e.g. toast+ form.setError("url", { message: "Something went wrong" });+ }+ });+ }++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <div className="grid grid-cols-4 gap-2 sm:grid-cols-5">+ <FormField+ control={form.control}+ name="method"+ render={({ field }) => (+ <FormItem className="col-span-1">+ <FormLabel className="sr-only">Method</FormLabel>+ <Select+ onValueChange={field.onChange}+ defaultValue={field.value}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {METHODS.map((method) => (+ <SelectItem key={method} value={method}>+ {method}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="url"+ render={({ field }) => (+ <FormItem className="col-span-3">+ <FormLabel className="sr-only">URL</FormLabel>+ <FormControl>+ <Input placeholder="https://documenso.com" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <div className="col-span-full mt-2 sm:col-span-1">+ <Button disabled={isPending} className="h-10 w-full">+ {isPending ? <LoadingAnimation /> : "Check"}+ </Button>+ </div>+ </div>+ </form>+ </Form>+ );+}diff --git a/apps/web/src/app/play/checker/_components/checker-play.tsx b/apps/web/src/app/play/checker/_components/checker-play.tsxnew file mode 100644index 000000000..6cbc52d62--- /dev/null+++ b/apps/web/src/app/play/checker/_components/checker-play.tsx@@ -0,0 +1,17 @@+import { Shell } from "@/components/dashboard/shell";+import { HeaderPlay } from "../../_components/header-play";+import { CheckerForm } from "./checker-form";++export default async function CheckerPlay() {+ return (+ <Shell className="grid gap-8">+ <HeaderPlay+ title="Monitoring"+ description="Experience the performance of your application from the different continents."+ />+ <div className="mx-auto grid w-full max-w-xl gap-6">+ <CheckerForm />+ </div>+ </Shell>+ );+}diff --git a/apps/web/src/app/play/checker/api/route.ts b/apps/web/src/app/play/checker/api/route.tsnew file mode 100644index 000000000..b514736c2--- /dev/null+++ b/apps/web/src/app/play/checker/api/route.ts@@ -0,0 +1,17 @@+import { setCheckerData } from "../[id]/utils";++export const runtime = "edge";++export async function POST(request: Request) {+ const json = await request.json();++ const { url, method } = json;++ try {+ const uuid = await setCheckerData(url, { method });+ return new Response(JSON.stringify({ uuid }));+ } catch (e) {+ console.log(e);+ return new Response("Internal Server Error", { status: 500 });+ }+}diff --git a/apps/web/src/app/play/checker/page.tsx b/apps/web/src/app/play/checker/page.tsxnew file mode 100644index 000000000..036ce90f1--- /dev/null+++ b/apps/web/src/app/play/checker/page.tsx@@ -0,0 +1,19 @@+import type { Metadata } from "next";++import { BackButton } from "@/components/layout/back-button";+import CheckerPlay from "./_components/checker-play";++export const metadata: Metadata = {+ title: "Speed Checker",+ description:+ "Get speed insights for your api, website from multiple regions.",+};++export default async function PlayPage() {+ return (+ <>+ <BackButton href="/" />+ <CheckerPlay />+ </>+ );+}diff --git a/apps/web/src/app/play/layout.tsx b/apps/web/src/app/play/layout.tsxindex 40ba3a6f4..889896477 100644--- a/apps/web/src/app/play/layout.tsx+++ b/apps/web/src/app/play/layout.tsx@@ -6,8 +6,6 @@ import {ogMetadata,twitterMetadata,} from "@/app/shared-metadata";-import { Shell } from "@/components/dashboard/shell";-import { BackButton } from "@/components/layout/back-button";import { MarketingLayout } from "@/components/layout/marketing-layout";export const metadata: Metadata = {@@ -31,11 +29,8 @@ export default function PlayLayout({}) {return (<MarketingLayout>- <BackButton href="/" />- <Shell>- {children}- {modal}- </Shell>+ {children}+ {modal}</MarketingLayout>);}diff --git a/apps/web/src/app/play/page.tsx b/apps/web/src/app/play/page.tsxindex 7623a7f81..fd62da1e6 100644--- a/apps/web/src/app/play/page.tsx+++ b/apps/web/src/app/play/page.tsx@@ -1,11 +1,8 @@import * as z from "zod";-import { Label } from "@openstatus/ui";--import { Tracker } from "@/components/tracker";-import { getHomeMonitorListData } from "@/lib/tb";-import { convertTimezoneToGMT, getRequestHeaderTimezone } from "@/lib/timezone";-import { TimezoneCombobox } from "./_components/timezone-combobox";+import { BackButton } from "@/components/layout/back-button";+import CheckerPlay from "./checker/_components/checker-play";+import StatusPlay from "./status/_components/status-play";/*** allowed URL search params@@ -20,41 +17,15 @@ export default async function PlayPage({searchParams: { [key: string]: string | string[] | undefined };}) {const search = searchParamsSchema.safeParse(searchParams);- const requestTimezone = getRequestHeaderTimezone();-const timezone = search.success ? search.data.timezone : undefined;- const gmt = convertTimezoneToGMT(timezone);-- const data = await getHomeMonitorListData({ timezone: gmt });-return (- <div className="relative grid gap-4">- <div className="mx-auto grid gap-4 text-center">- <p className="font-cal mb-1 text-3xl">Status</p>- <p className="text-muted-foreground text-lg font-light">- Build your own within seconds.- </p>- </div>- <div className="mx-auto w-full max-w-md">- {data && (- <Tracker- data={data}- id={1}- name="Ping"- url="https://www.openstatus.dev/api/ping"- context="play"- />- )}- </div>- <div className="mt-6 flex justify-start">- <div className="grid items-center gap-1">- <Label className="text-muted-foreground text-xs">Timezone</Label>- <TimezoneCombobox- defaultValue={timezone || requestTimezone || undefined}- />- </div>+ <>+ <BackButton href="/" />+ <div className="grid w-full gap-4">+ <StatusPlay timezone={timezone} />+ <CheckerPlay /></div>- </div>+ </>);}diff --git a/apps/web/src/app/play/status/_components/status-play.tsx b/apps/web/src/app/play/status/_components/status-play.tsxnew file mode 100644index 000000000..98bc5bea2--- /dev/null+++ b/apps/web/src/app/play/status/_components/status-play.tsx@@ -0,0 +1,44 @@+import { Label } from "@openstatus/ui";++import { Shell } from "@/components/dashboard/shell";+import { Tracker } from "@/components/tracker";+import { getHomeMonitorListData } from "@/lib/tb";+import { convertTimezoneToGMT, getRequestHeaderTimezone } from "@/lib/timezone";+import { HeaderPlay } from "../../_components/header-play";+import { TimezoneCombobox } from "./timezone-combobox";++export default async function StatusPlay({ timezone }: { timezone?: string }) {+ const requestTimezone = getRequestHeaderTimezone();+ const gmt = convertTimezoneToGMT(timezone);++ const data = await getHomeMonitorListData({ timezone: gmt });++ return (+ <Shell>+ <div className="relative grid gap-4">+ <HeaderPlay+ title="Status Page"+ description="Gain the trust of your users by showing them the uptime of your API or website."+ />+ <div className="mx-auto w-full max-w-md">+ {data && (+ <Tracker+ data={data}+ id={1}+ name="Ping"+ url="https://www.openstatus.dev/api/ping"+ />+ )}+ </div>+ <div className="mt-6 flex justify-start">+ <div className="grid items-center gap-1">+ <Label className="text-muted-foreground text-xs">Timezone</Label>+ <TimezoneCombobox+ defaultValue={timezone || requestTimezone || undefined}+ />+ </div>+ </div>+ </div>+ </Shell>+ );+}diff --git a/apps/web/src/app/play/_components/timezone-combobox.tsx b/apps/web/src/app/play/status/_components/timezone-combobox.tsxsimilarity index 100%rename from apps/web/src/app/play/_components/timezone-combobox.tsxrename to apps/web/src/app/play/status/_components/timezone-combobox.tsxdiff --git a/apps/web/src/app/play/status/page.tsx b/apps/web/src/app/play/status/page.tsxnew file mode 100644index 000000000..18350da65--- /dev/null+++ b/apps/web/src/app/play/status/page.tsx@@ -0,0 +1,27 @@+import * as z from "zod";++import { BackButton } from "@/components/layout/back-button";+import StatusPlay from "./_components/status-play";++/**+ * allowed URL search params+ */+const searchParamsSchema = z.object({+ timezone: z.string().optional(),+});++export default async function PlayPage({+ searchParams,+}: {+ searchParams: { [key: string]: string | string[] | undefined };+}) {+ const search = searchParamsSchema.safeParse(searchParams);+ const timezone = search.success ? search.data.timezone : undefined;++ return (+ <>+ <BackButton href="/" />+ <StatusPlay timezone={timezone} />+ </>+ );+}diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsxindex a08564fe2..08f4e432c 100644--- a/apps/web/src/components/icons.tsx+++ b/apps/web/src/components/icons.tsx@@ -5,6 +5,7 @@ import {Bot,Calendar,Check,+ Clock,Cog,Copy,Fingerprint,@@ -29,6 +30,7 @@ import {SunMedium,Table,Tag,+ Timer,ToyBrick,Trash,TwitterIcon,@@ -76,6 +78,8 @@ export const Icons = {moon: Moon,laptop: Laptop,sparkles: Sparkles,+ timer: Timer,+ clock: Clock,discord: ({ ...props }: LucideProps) => (<svg viewBox="0 0 640 512" {...props}><pathdiff --git a/apps/web/src/components/layout/marketing-header.tsx b/apps/web/src/components/layout/marketing-header.tsxindex 1e3f33b26..0c6d382f0 100644--- a/apps/web/src/components/layout/marketing-header.tsx+++ b/apps/web/src/components/layout/marketing-header.tsx@@ -2,7 +2,6 @@import Link from "next/link";import { useUser } from "@clerk/nextjs";-import { ArrowUpRight } from "lucide-react";import { Button } from "@openstatus/ui";@@ -24,10 +23,13 @@ export function MarketingHeader({ className }: Props) {<div className="flex items-center sm:col-span-1"><BrandName /></div>- <div className="hidden items-center justify-center sm:col-span-3 sm:flex sm:gap-3">+ <div className="hidden items-center justify-center sm:col-span-3 sm:flex sm:gap-1"><Button variant="link" asChild><Link href="/blog">Blog</Link></Button>+ <Button variant="link" asChild>+ <Link href="/play">Playground</Link>+ </Button><Button variant="link" asChild><Link href="/changelog">Changelog</Link></Button>@@ -37,7 +39,6 @@ export function MarketingHeader({ className }: Props) {<Button variant="link" asChild><Link href="https://docs.openstatus.dev" target="_blank">Docs- <ArrowUpRight className="ml-1 h-4 w-4 flex-shrink-0" /></Link></Button></div>diff --git a/apps/web/src/components/marketing/monitor/card.tsx b/apps/web/src/components/marketing/monitor/card.tsxindex f50ed61f3..6aa920eeb 100644--- a/apps/web/src/components/marketing/monitor/card.tsx+++ b/apps/web/src/components/marketing/monitor/card.tsx@@ -1,3 +1,7 @@+import Link from "next/link";++import { Button } from "@openstatus/ui";+import { cardConfig } from "@/config/features";import {CardContainer,@@ -22,6 +26,11 @@ export function MonitoringCard() {<Globe /><CardFeatureContainer>{features?.map((feature, i) => <CardFeature key={i} {...feature} />)}+ <div className="text-center">+ <Button asChild variant="outline" className="rounded-full">+ <Link href="/play/checker">Playground</Link>+ </Button>+ </div></CardFeatureContainer></CardContent></CardContainer>diff --git a/apps/web/src/components/marketing/status-page/tracker-example.tsx b/apps/web/src/components/marketing/status-page/tracker-example.tsxindex ede39e899..8ea400a04 100644--- a/apps/web/src/components/marketing/status-page/tracker-example.tsx+++ b/apps/web/src/components/marketing/status-page/tracker-example.tsx@@ -16,7 +16,7 @@ export async function TrackerExample() {</Suspense></div><Button asChild variant="outline" className="rounded-full">- <Link href="/play">Playground</Link>+ <Link href="/play/status">Playground</Link></Button></div>);diff --git a/apps/web/src/content/changelog/checker-playground.mdx b/apps/web/src/content/changelog/checker-playground.mdxnew file mode 100644index 000000000..d063cfe14--- /dev/null+++ b/apps/web/src/content/changelog/checker-playground.mdx@@ -0,0 +1,34 @@+---+title: Checker Playground+description: Test your API or website from multiple regions around the world.+image: /assets/changelog/checker-playground.png+publishedAt: 2024-01-20+---++You can now test your API or website from multiple regions around the world and+experience the performance of your application from the different continents.++Learn more about `dns`, `tls`, `ttfb` and more metrics that are collected by the+checker.++Go to the **[Playground](/play/checker)** to test your endpoint.++But there is more: use the `https://checker.openstatus.dev/ping` API endpoint to+get the metrics by yourself.++For example:++```bash+curl --request POST \+ --url https://checker.openstatus.dev/ping/ams \+ --header 'Content-Type: application/json' \+ --header 'x-openstatus-key: <YOUR_API_KEY>' \+ --header 'prefer-fly-region: ams' \+ --data '{+ "url": "https://api.openstatus.dev/ping",+ "method": "GET"+}'+```++Read more about the+[Checker API](https://docs.openstatus.dev/api-reference/checker) in our docs.