Skip to content

Open-source status page, incident response and uptime monitoring

Feat/onboarding (#310)

Maximilian Kaske167e83eebbfb
diff --git a/apps/web/src/app/api/analytics/route.ts b/apps/web/src/app/api/analytics/route.ts
new file mode 100644
index 000000000..0cce8bc7b
--- /dev/null
+++ b/apps/web/src/app/api/analytics/route.ts
@@ -0,0 +1,19 @@
+import { auth } from "@clerk/nextjs";
+
+import { analytics, trackAnalytics } from "@openstatus/analytics";
+
+/**
+ * Simple Jitsu Event
+ */
+export async function GET() {
+ const { userId } = auth();
+
+ await analytics.identify(userId, {
+ userId: userId,
+ });
+ await trackAnalytics({
+ event: "User Vercel Beta",
+ });
+
+ return new Response("OK", { status: 200 });
+}
diff --git a/apps/web/src/app/api/checker/regions/_checker.ts b/apps/web/src/app/api/checker/regions/_checker.ts
index a03779fc1..f24d933c7 100644
--- a/apps/web/src/app/api/checker/regions/_checker.ts
+++ b/apps/web/src/app/api/checker/regions/_checker.ts
@@ -9,6 +9,7 @@ import {
} from "@openstatus/tinybird";
import { env } from "@/env";
+import type { Payload } from "../schema";
import { payloadSchema } from "../schema";
export const monitorSchema = tbIngestPingResponse.pick({
@@ -78,23 +79,9 @@ export const checker = async (request: Request, region: string) => {
throw new Error("Invalid response body");
}
- const headers =
- result.data?.headers?.reduce((o, v) => ({ ...o, [v.key]: v.value }), {}) ||
- {};
-
try {
const startTime = Date.now();
- const res = await fetch(result.data?.url, {
- method: result.data?.method,
- cache: "no-store",
- headers: {
- "OpenStatus-Ping": "true",
- ...headers,
- },
- // Avoid having "TypeError: Request with a GET or HEAD method cannot have a body." error
- ...(result.data.method !== "GET" && { body: result.data?.body }),
- });
-
+ const res = await ping(result.data);
const endTime = Date.now();
const latency = endTime - startTime;
await monitor(res, result.data, region, latency);
@@ -111,3 +98,26 @@ export const checker = async (request: Request, region: string) => {
}
}
};
+
+export const ping = async (
+ data: Pick<Payload, "headers" | "body" | "method" | "url">,
+) => {
+ const headers =
+ data?.headers?.reduce((o, v) => {
+ if (v.key.trim() === "") return o; // removes empty keys from the header
+ return { ...o, [v.key]: v.value };
+ }, {}) || {};
+
+ const res = await fetch(data?.url, {
+ method: data?.method,
+ cache: "no-store",
+ headers: {
+ "OpenStatus-Ping": "true",
+ ...headers,
+ },
+ // Avoid having "TypeError: Request with a GET or HEAD method cannot have a body." error
+ ...(data.method !== "GET" && { body: data?.body }),
+ });
+
+ return res;
+};
diff --git a/apps/web/src/app/api/checker/schema.ts b/apps/web/src/app/api/checker/schema.ts
index e568f9ede..b5dad10bf 100644
--- a/apps/web/src/app/api/checker/schema.ts
+++ b/apps/web/src/app/api/checker/schema.ts
@@ -12,3 +12,5 @@ export const payloadSchema = z.object({
cronTimestamp: z.number(),
pageIds: z.array(z.string()),
});
+
+export type Payload = z.infer<typeof payloadSchema>;
diff --git a/apps/web/src/app/api/checker/test/route.ts b/apps/web/src/app/api/checker/test/route.ts
new file mode 100644
index 000000000..e6d2c8919
--- /dev/null
+++ b/apps/web/src/app/api/checker/test/route.ts
@@ -0,0 +1,30 @@
+import { NextResponse } from "next/server";
+
+import { ping } from "../regions/_checker";
+import { payloadSchema } from "../schema";
+
+export const runtime = "edge";
+export const preferredRegion = "auto";
+export const dynamic = "force-dynamic";
+// Fix is a random region let's figure where does vercel push it
+
+export async function POST(request: Request) {
+ const json = await request.json();
+ const _valid = payloadSchema
+ .pick({ url: true, method: true, headers: true, body: true })
+ .safeParse(json);
+
+ if (!_valid.success) {
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+
+ const check = await ping(_valid.data);
+
+ console.log(check.status);
+
+ if (!check.ok) {
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+
+ return NextResponse.json({ success: true });
+}
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx
index fe2266a4a..114588386 100644
--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx
@@ -24,7 +24,7 @@ export default async function AppLayout({
<div className="container relative mx-auto flex min-h-screen w-full flex-col items-center justify-center gap-6 p-4 lg:p-8">
<AppHeader />
<div className="flex w-full flex-1 gap-6 lg:gap-8">
- <Shell className="hidden max-h-[calc(100vh-9rem)] max-w-min shrink-0 lg:sticky lg:top-20 lg:block">
+ <Shell className="hidden max-h-[calc(100vh-9rem)] max-w-min shrink-0 lg:sticky lg:top-28 lg:block">
<AppSidebar />
</Shell>
<main className="z-10 flex w-full flex-1 flex-col items-start justify-center">
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx
index 6b6a75c6f..78474f78f 100644
--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx
@@ -2,9 +2,7 @@ import { notFound } from "next/navigation";
import * as z from "zod";
import { Header } from "@/components/dashboard/header";
-import { AdvancedMonitorForm } from "@/components/forms/advanced-monitor-form";
import { MonitorForm } from "@/components/forms/montitor-form";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/trpc/server";
/**
@@ -38,36 +36,11 @@ export default async function EditPage({
<div className="grid gap-6 md:grid-cols-2 md:gap-8">
<Header title="Monitor" description="Upsert your monitor." />
<div className="col-span-full">
- <Tabs defaultValue="settings" className="relative mr-auto w-full">
- <TabsList className="h-9 w-full justify-start rounded-none border-b bg-transparent p-0">
- <TabsTrigger
- className="text-muted-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground relative h-9 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold shadow-none transition-none data-[state=active]:shadow-none"
- value="settings"
- >
- Settings
- </TabsTrigger>
- <TabsTrigger
- className="text-muted-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground relative h-9 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold shadow-none transition-none data-[state=active]:shadow-none"
- value="advanced"
- disabled={!monitor}
- >
- Advanced
- </TabsTrigger>
- </TabsList>
- <TabsContent value="settings" className="pt-3">
- <MonitorForm
- workspaceSlug={params.workspaceSlug}
- defaultValues={monitor || undefined}
- plan={workspace?.plan}
- />
- </TabsContent>
- <TabsContent value="advanced" className="pt-3">
- <AdvancedMonitorForm
- workspaceSlug={params.workspaceSlug}
- defaultValues={monitor || undefined}
- />
- </TabsContent>
- </Tabs>
+ <MonitorForm
+ workspaceSlug={params.workspaceSlug}
+ defaultValues={monitor || undefined}
+ plan={workspace?.plan}
+ />
</div>
</div>
);
diff --git a/apps/web/src/app/app/(dashboard)/onboarding/_components/description.tsx b/apps/web/src/app/app/(dashboard)/onboarding/_components/description.tsx
new file mode 100644
index 000000000..df58fd480
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/onboarding/_components/description.tsx
@@ -0,0 +1,84 @@
+import { Icons } from "@/components/icons";
+import { cn } from "@/lib/utils";
+
+const steps = ["monitor", "status-page"] as const;
+// potentially move to `config/onboarding`
+const onboardingConfig = {
+ monitor: {
+ icon: "activity",
+ name: "Monitor",
+ description: [
+ {
+ title: "What is a monitor?",
+ text: "A monitor is a website or api endpoint that you are going to ping on a regular basis.",
+ },
+ {
+ title: "How to create monitors?",
+ text: "You can create a monitor like you are about to via our dashboard or with our API. E.g. you can create a monitor for every instance you deploy programmatically.",
+ },
+ ],
+ },
+ "status-page": {
+ icon: "panel-top",
+ name: "Status Page",
+ description: [
+ {
+ title: "How to use status pages?",
+ text: "Add the monitors you'd like to track to a status page and inform your users if your services are down.",
+ },
+ {
+ title: "Subdomain or custom domains?",
+ text: "Start with a unique subdomain slug and move to your own custom domains afterwards by updating the DNS settings.",
+ },
+ ],
+ },
+} as const;
+
+export function Description({
+ step,
+}: {
+ step?: keyof typeof onboardingConfig;
+}) {
+ const config = step && onboardingConfig[step];
+ return (
+ <div className="border-border flex h-full flex-col gap-6 border-l pl-6 md:pl-8">
+ <div className="flex gap-5">
+ {steps.map((item, i) => {
+ const { icon, name } = onboardingConfig[item];
+ const StepIcon = Icons[icon];
+ const active = step === item;
+ return (
+ <div key={i} className="flex items-center gap-2">
+ <div
+ className={cn(
+ "border-border max-w-max rounded-full border p-2",
+ active && "border-accent-foreground",
+ )}
+ >
+ <StepIcon className="h-4 w-4" />
+ </div>
+ <p
+ className={cn(
+ "text-xs",
+ active
+ ? "text-foreground font-semibold"
+ : "text-muted-foreground",
+ )}
+ >
+ {name}
+ </p>
+ </div>
+ );
+ })}
+ </div>
+ {config?.description.map(({ title, text }, i) => {
+ return (
+ <dl key={i} className="grid gap-2">
+ <dt>{title}</dt>
+ <dd className="text-muted-foreground text-sm">{text}</dd>
+ </dl>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/app/(dashboard)/onboarding/_components/path.tsx b/apps/web/src/app/app/(dashboard)/onboarding/_components/path.tsx
new file mode 100644
index 000000000..e40120c8a
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/onboarding/_components/path.tsx
@@ -0,0 +1,115 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import useUpdateSearchParams from "@/hooks/use-update-search-params";
+
+export function Path() {
+ return (
+ <div className="grid gap-6 md:grid-cols-4">
+ <HttpCard />
+ <VercelCard />
+ </div>
+ );
+}
+
+function HttpCard() {
+ const updateSearchParams = useUpdateSearchParams();
+ const router = useRouter();
+ return (
+ <Card className="relative flex flex-col justify-between md:col-span-2">
+ <Badge
+ variant="secondary"
+ className="bg-background text-muted-foreground absolute -top-3 right-2"
+ >
+ Standard
+ </Badge>
+ <CardHeader>
+ <CardTitle>HTTP Endpoint</CardTitle>
+ <CardDescription>
+ Monitor your API or website via POST or GET requests including custom
+ headers and body payload.
+ </CardDescription>
+ </CardHeader>
+ <CardFooter>
+ <Button
+ size="lg"
+ onClick={() => {
+ router.push(`?${updateSearchParams({ path: "http" })}`);
+ }}
+ >
+ Continue
+ </Button>
+ </CardFooter>
+ </Card>
+ );
+}
+
+function VercelCard() {
+ async function trackEvent() {
+ await fetch("/api/analytics");
+ }
+
+ return (
+ <Card className="relative flex flex-col justify-between md:col-span-2">
+ <Badge
+ variant="secondary"
+ className="bg-background text-muted-foreground absolute -top-3 right-2"
+ >
+ Beta
+ </Badge>
+ <CardHeader>
+ <CardTitle>Vercel Integration</CardTitle>
+ <CardDescription>
+ Monitor your Vercel applications with ease.
+ </CardDescription>
+ </CardHeader>
+ <CardFooter>
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button size="lg" onClick={trackEvent}>
+ Continue
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ Vercel Integration <Badge>Beta</Badge>
+ </DialogTitle>
+ <DialogDescription>
+ The integration is currently in closed beta.
+ </DialogDescription>
+ </DialogHeader>
+ <div>
+ <p className="">
+ Please contact us:{" "}
+ <Button variant="link" className="font-mono" asChild>
+ <a href="mailto:[email protected]">
+ </a>
+ </Button>
+ </p>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </CardFooter>
+ </Card>
+ );
+}
diff --git a/apps/web/src/app/app/(dashboard)/onboarding/layout.tsx b/apps/web/src/app/app/(dashboard)/onboarding/layout.tsx
new file mode 100644
index 000000000..619d63f92
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/onboarding/layout.tsx
@@ -0,0 +1,22 @@
+import * as React from "react";
+
+import { Shell } from "@/components/dashboard/shell";
+import { AppHeader } from "@/components/layout/app-header";
+
+// TODO: make the container min-h-screen and the footer below!
+export default async function AppLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="container relative mx-auto flex min-h-screen w-full flex-col items-center justify-center gap-6 p-4 lg:p-8">
+ <AppHeader />
+ <div className="flex w-full flex-1 gap-6 lg:gap-8">
+ <main className="z-10 flex w-full flex-1 flex-col items-start justify-center">
+ <Shell className="relative flex-1">{children}</Shell>
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/app/(dashboard)/onboarding/page.tsx b/apps/web/src/app/app/(dashboard)/onboarding/page.tsx
new file mode 100644
index 000000000..57d27ad05
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/onboarding/page.tsx
@@ -0,0 +1,117 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import * as z from "zod";
+
+import { Header } from "@/components/dashboard/header";
+import { MonitorForm } from "@/components/forms/montitor-form";
+import { StatusPageForm } from "@/components/forms/status-page-form";
+import { Button } from "@/components/ui/button";
+import { api } from "@/trpc/server";
+import { Description } from "./_components/description";
+import { Path } from "./_components/path";
+
+/**
+ * allowed URL search params
+ */
+const searchParamsSchema = z.object({
+ path: z.string().optional(), // "vercel" | "http"
+ id: z.coerce.number().optional(), // monitorId
+ workspaceSlug: z.string().optional(),
+});
+
+export default async function Onboarding({
+ searchParams,
+}: {
+ searchParams: { [key: string]: string | string[] | undefined };
+}) {
+ const search = searchParamsSchema.safeParse(searchParams);
+
+ if (!search.success) {
+ return notFound();
+ }
+
+ // Instead of having the workspaceSlug in the search params, we can get it from the auth user
+ const { workspaceSlug, id: monitorId, path } = search.data;
+
+ if (!workspaceSlug) {
+ return "Waiting for Slug";
+ }
+
+ if (!path) {
+ return (
+ <div className="flex h-full w-full flex-col gap-6 md:gap-8">
+ <Header
+ title="Get Started"
+ description="Create your first status page."
+ actions={
+ <Button variant="link" className="text-muted-foreground">
+ <Link href={`/app/${workspaceSlug}/monitors`}>Skip</Link>
+ </Button>
+ }
+ />
+ <div className="grid h-full w-full gap-6 md:grid-cols-3 md:gap-8">
+ <div className="md:col-span-2">
+ <Path />
+ </div>
+ <div className="hidden h-full md:col-span-1 md:block">
+ <Description />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const allMonitors = await api.monitor.getMonitorsByWorkspace.query({
+ workspaceSlug,
+ });
+
+ if (!monitorId) {
+ return (
+ <div className="flex h-full w-full flex-col gap-6 md:gap-8">
+ <Header
+ title="Get Started"
+ description="Create your first monitor."
+ actions={
+ <Button variant="link" className="text-muted-foreground">
+ <Link href={`/app/${workspaceSlug}/monitors`}>Skip</Link>
+ </Button>
+ }
+ />
+ <div className="grid h-full w-full gap-6 md:grid-cols-3 md:gap-8">
+ <div className="md:col-span-2">
+ <MonitorForm {...{ workspaceSlug }} />
+ </div>
+ <div className="hidden h-full md:col-span-1 md:block">
+ <Description step="monitor" />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full w-full flex-col gap-6 md:gap-8">
+ <Header
+ title="Get Started"
+ description="Create your first status page."
+ actions={
+ <Button variant="link" className="text-muted-foreground">
+ <Link href={`/app/${workspaceSlug}/monitors`}>Skip</Link>
+ </Button>
+ }
+ />
+ <div className="grid h-full w-full gap-6 md:grid-cols-3 md:gap-8">
+ <div className="md:col-span-2">
+ <StatusPageForm
+ {...{ workspaceSlug, allMonitors }}
+ nextUrl={`/app/${workspaceSlug}/status-pages`}
+ checkAllMonitors
+ />
+ </div>
+ <div className="hidden h-full md:col-span-1 md:block">
+ <Description step="status-page" />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/app/page.tsx b/apps/web/src/app/app/page.tsx
index e74dcce7a..1f5ed5539 100644
--- a/apps/web/src/app/app/page.tsx
+++ b/apps/web/src/app/app/page.tsx
@@ -4,6 +4,7 @@ import * as React from "react";
import { useRouter } from "next/navigation";
import { Shell } from "@/components/dashboard/shell";
+import { AppHeader } from "@/components/layout/app-header";
import { LoadingAnimation } from "@/components/loading-animation";
// TODO: discuss how to make that page a bit more enjoyable
@@ -14,14 +15,23 @@ export default function Page() {
setTimeout(() => router.refresh(), 1000);
return (
- <div className="flex min-h-screen flex-col items-center justify-center">
- <Shell className="mx-auto grid w-auto gap-4">
- <div className="grid gap-1 text-center">
- <p className="text-lg font-bold">Creating Workspace</p>
- <p className="text-muted-foreground">Should be done in a second.</p>
- </div>
- <LoadingAnimation variant="inverse" size="lg" />
- </Shell>
+ <div className="container relative mx-auto flex min-h-screen w-full flex-col items-center justify-center gap-6 p-4 lg:p-8">
+ <AppHeader />
+ <div className="flex w-full flex-1 gap-6 lg:gap-8">
+ <main className="z-10 flex w-full flex-1 flex-col items-start justify-center">
+ <Shell className="relative flex flex-1 flex-col items-center justify-center">
+ <div className="grid gap-4">
+ <div className="text-center">
+ <p className="mb-1 text-lg font-bold">Creating Workspace</p>
+ <p className="text-muted-foreground">
+ Should be done in a second.
+ </p>
+ </div>
+ <LoadingAnimation variant="inverse" size="lg" />
+ </div>
+ </Shell>
+ </main>
+ </div>
</div>
);
}
diff --git a/apps/web/src/app/status-page/[domain]/_components/user-button.tsx b/apps/web/src/app/status-page/[domain]/_components/user-button.tsx
new file mode 100644
index 000000000..5d76e611b
--- /dev/null
+++ b/apps/web/src/app/status-page/[domain]/_components/user-button.tsx
@@ -0,0 +1,19 @@
+"use client";
+
+import Link from "next/link";
+import { useUser } from "@clerk/nextjs";
+
+import { Button } from "@/components/ui/button";
+
+// Create a button only displayed if you are logged in and are the owner of the status page
+export function UserButton() {
+ const { isSignedIn } = useUser();
+ if (isSignedIn) {
+ return (
+ <Button asChild>
+ <Link href="https://openstatus.dev/app">OpenStatus Dashboard</Link>
+ </Button>
+ );
+ }
+ return null;
+}
diff --git a/apps/web/src/app/status-page/[domain]/layout.tsx b/apps/web/src/app/status-page/[domain]/layout.tsx
index f88b1a017..496c0cc64 100644
--- a/apps/web/src/app/status-page/[domain]/layout.tsx
+++ b/apps/web/src/app/status-page/[domain]/layout.tsx
@@ -1,5 +1,6 @@
import { Shell } from "@/components/dashboard/shell";
import NavigationLink from "./_components/navigation-link";
+import { UserButton } from "./_components/user-button";
export default function StatusPageLayout({
children,
diff --git a/apps/web/src/components/forms/custom-domain-form.tsx b/apps/web/src/components/forms/custom-domain-form.tsx
index 23c2506a0..b7815c631 100644
--- a/apps/web/src/components/forms/custom-domain-form.tsx
+++ b/apps/web/src/components/forms/custom-domain-form.tsx
@@ -115,7 +115,7 @@ export function CustomDomainForm({ defaultValues }: { defaultValues: Schema }) {
)}
/>
<div className="sm:col-span-full">
- <Button className="w-full sm:w-auto">
+ <Button className="w-full sm:w-auto" size="lg">
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
</div>
diff --git a/apps/web/src/components/forms/incident-form.tsx b/apps/web/src/components/forms/incident-form.tsx
index 429bda6ee..47507e359 100644
--- a/apps/web/src/components/forms/incident-form.tsx
+++ b/apps/web/src/components/forms/incident-form.tsx
@@ -287,7 +287,7 @@ export function IncidentForm({
)}
/>
<div className="sm:col-span-full">
- <Button className="w-full sm:w-auto">
+ <Button className="w-full sm:w-auto" size="lg">
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
</div>
diff --git a/apps/web/src/components/forms/incident-update-form.tsx b/apps/web/src/components/forms/incident-update-form.tsx
index 7329e1f35..897e4ca14 100644
--- a/apps/web/src/components/forms/incident-update-form.tsx
+++ b/apps/web/src/components/forms/incident-update-form.tsx
@@ -176,7 +176,7 @@ export function IncidentUpdateForm({
)}
/>
<div className="sm:col-span-full">
- <Button className="w-full sm:w-auto">
+ <Button className="w-full sm:w-auto" size="lg">
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
</div>
diff --git a/apps/web/src/components/forms/montitor-form.tsx b/apps/web/src/components/forms/montitor-form.tsx
index d61893de2..428d3d7cc 100644
--- a/apps/web/src/components/forms/montitor-form.tsx
+++ b/apps/web/src/components/forms/montitor-form.tsx
@@ -1,11 +1,12 @@
"use client";
+import { METHODS } from "http";
import * as React from "react";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
-import { Check, ChevronsUpDown } from "lucide-react";
-import { useForm } from "react-hook-form";
-import type * as z from "zod";
+import { Check, ChevronsUpDown, Wand2, X } from "lucide-react";
+import { useFieldArray, useForm } from "react-hook-form";
+import * as z from "zod";
import {
insertMonitorSchema,
@@ -44,11 +45,20 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { regionsDict } from "@/data/regions-dictionary";
import { useToastAction } from "@/hooks/use-toast-action";
+import useUpdateSearchParams from "@/hooks/use-update-search-params";
import { cn } from "@/lib/utils";
import { api } from "@/trpc/client";
import { LoadingAnimation } from "../loading-animation";
+import { InputWithAddons } from "../ui/input-with-addons";
const cronJobs = [
{ value: "1m", label: "1 minute" },
@@ -58,7 +68,22 @@ const cronJobs = [
{ value: "1h", label: "1 hour" },
] as const;
-type MonitorProps = z.infer<typeof insertMonitorSchema>;
+const methods = ["POST", "GET"] as const;
+const methodsEnum = z.enum(methods);
+
+const headersSchema = z
+ .array(z.object({ key: z.string(), value: z.string() }))
+ .optional();
+
+const advancedSchema = z.object({
+ method: methodsEnum,
+ body: z.string().optional(),
+ headers: headersSchema,
+});
+
+const mergedSchema = insertMonitorSchema.merge(advancedSchema);
+
+type MonitorProps = z.infer<typeof mergedSchema>;
interface Props {
defaultValues?: MonitorProps;
@@ -72,7 +97,7 @@ export function MonitorForm({
plan = "free",
}: Props) {
const form = useForm<MonitorProps>({
- resolver: zodResolver(insertMonitorSchema), // too much - we should only validate the values we ask inside of the form!
+ resolver: zodResolver(mergedSchema), // too much - we should only validate the values we ask inside of the form!
defaultValues: {
url: defaultValues?.url || "",
name: defaultValues?.name || "",
@@ -81,11 +106,24 @@ export function MonitorForm({
active: defaultValues?.active ?? true,
id: defaultValues?.id || undefined,
regions: defaultValues?.regions || [],
+ headers: Boolean(defaultValues?.headers?.length)
+ ? defaultValues?.headers
+ : [{ key: "", value: "" }],
+ body: defaultValues?.body ?? "",
+ method: defaultValues?.method ?? "GET",
},
});
const router = useRouter();
const [isPending, startTransition] = React.useTransition();
+ const [isTestPending, startTestTransition] = React.useTransition();
const { toast } = useToastAction();
+ const watchMethod = form.watch("method");
+ const updateSearchParams = useUpdateSearchParams();
+
+ const { fields, append, remove } = useFieldArray({
+ name: "headers",
+ control: form.control,
+ });
const onSubmit = ({ ...props }: MonitorProps) => {
startTransition(async () => {
@@ -98,7 +136,8 @@ export function MonitorForm({
data: props,
workspaceSlug,
});
- router.replace(`./edit?id=${monitor?.id}`); // to stay on same page and enable 'Advanced' tab
+ const id = monitor?.id || null;
+ router.replace(`?${updateSearchParams({ id })}`);
}
router.refresh();
toast("saved");
@@ -108,6 +147,51 @@ export function MonitorForm({
});
};
+ const validateJSON = (value?: string) => {
+ if (!value) return;
+ try {
+ const obj = JSON.parse(value) as Record<string, unknown>;
+ form.clearErrors("body");
+ return obj;
+ } catch (e) {
+ form.setError("body", {
+ message: "Not a valid JSON object",
+ });
+ return false;
+ }
+ };
+
+ const onPrettifyJSON = () => {
+ const body = form.getValues("body");
+ const obj = validateJSON(body);
+ if (obj) {
+ const pretty = JSON.stringify(obj, undefined, 4);
+ form.setValue("body", pretty);
+ }
+ };
+
+ const sendTestPing = () => {
+ startTestTransition(async () => {
+ const res = await fetch(`/api/checker/test`, {
+ method: "POST",
+ headers: new Headers({
+ "Content-Type": "application/json",
+ }),
+ body: JSON.stringify({
+ url: form.getValues("url"),
+ body: form.getValues("body"),
+ method: form.getValues("method"),
+ headers: form.getValues("headers"),
+ }),
+ });
+ if (res.ok) {
+ toast("test-success");
+ } else {
+ toast("test-error");
+ }
+ });
+ };
+
const limit = allPlans[plan].limits.periodicity;
return (
@@ -125,28 +209,25 @@ export function MonitorForm({
<FormControl>
<Input placeholder="Documenso" {...field} />
</FormControl>
- <FormDescription>
- The name of the monitor displayed on the status page.
- </FormDescription>
+ <FormDescription>Displayed on the status page.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
- name="url"
+ name="description"
render={({ field }) => (
- <FormItem className="sm:col-span-4">
- <FormLabel>URL</FormLabel>
+ <FormItem className="sm:col-span-5">
+ <FormLabel>Description</FormLabel>
<FormControl>
- {/* Should we use `InputWithAddons here? */}
<Input
- placeholder="https://documenso.com/api/health"
+ placeholder="Determines the api health of our services."
{...field}
/>
</FormControl>
<FormDescription>
- Here is the URL you want to monitor.{" "}
+ Provide your users with information about it.{" "}
</FormDescription>
<FormMessage />
</FormItem>
@@ -154,28 +235,165 @@ export function MonitorForm({
/>
<FormField
control={form.control}
- name="description"
+ name="method"
render={({ field }) => (
- <FormItem className="sm:col-span-5">
- <FormLabel>Description</FormLabel>
+ <FormItem className="sm:col-span-1 sm:col-start-1 sm:self-baseline">
+ <FormLabel>Method</FormLabel>
+ <Select
+ onValueChange={(value) => {
+ field.onChange(methodsEnum.parse(value));
+ form.resetField("body", { defaultValue: "" });
+ }}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select" />
+ </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="sm:col-span-4">
+ <FormLabel>URL</FormLabel>
<FormControl>
+ {/* <InputWithAddons
+ leading="https://"
+ placeholder="documenso.com/api/health"
+ {...field}
+ /> */}
<Input
- placeholder="Determines the api health of our services."
+ placeholder="https://documenso.com/api/health"
{...field}
/>
</FormControl>
<FormDescription>
- Provide your users with information about it.{" "}
+ Here is the URL you want to monitor.{" "}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
+ <div className="space-y-2 sm:col-span-full">
+ {/* TODO: add FormDescription for latest key/value */}
+ <FormLabel>Request Header</FormLabel>
+ {fields.map((field, index) => (
+ <div key={field.id} className="grid grid-cols-6 gap-6">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="key" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <div className="col-span-4 flex items-center space-x-2">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="w-full">
+ <FormControl>
+ <Input placeholder="value" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ onClick={() => remove(Number(field.id))}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => append({ key: "", value: "" })}
+ >
+ Add Custom Header
+ </Button>
+ </div>
+ </div>
+ {watchMethod === "POST" && (
+ <div className="sm:col-span-4 sm:col-start-1">
+ <FormField
+ control={form.control}
+ name="body"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-end justify-between">
+ <FormLabel>Body</FormLabel>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={onPrettifyJSON}
+ >
+ <Wand2 className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Prettify JSON</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <FormControl>
+ <Textarea
+ rows={8}
+ placeholder='{ "hello": "world" }'
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>Write your json payload.</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ )}
+ <div className="sm:col-span-2 sm:col-start-1">
+ <Button
+ type="button"
+ variant="default"
+ className="w-full md:w-auto"
+ size="lg"
+ onClick={sendTestPing}
+ >
+ {!isTestPending ? "Test Request" : <LoadingAnimation />}
+ </Button>
+ </div>
<FormField
control={form.control}
name="periodicity"
render={({ field }) => (
- <FormItem className="sm:col-span-3 sm:self-baseline">
+ <FormItem className="sm:col-span-3 sm:col-start-1 sm:self-baseline">
<FormLabel>Frequency</FormLabel>
<Select
onValueChange={(value) =>
@@ -276,7 +494,7 @@ export function MonitorForm({
control={form.control}
name="active"
render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between sm:col-span-3">
+ <FormItem className="flex flex-row items-center justify-between sm:col-span-4">
<div className="space-y-0.5">
<FormLabel>Active</FormLabel>
<FormDescription>
@@ -295,7 +513,12 @@ export function MonitorForm({
)}
/>
<div className="sm:col-span-full">
- <Button className="w-full sm:w-auto">
+ {/*
+ * We could think of having a 'double confirmation' one,
+ * to check if the endpoint works and approve afterwards
+ * and confirm anyways even if endpoint failed
+ */}
+ <Button className="w-full sm:w-auto" size="lg" disabled={isPending}>
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
</div>
diff --git a/apps/web/src/components/forms/status-page-form.tsx b/apps/web/src/components/forms/status-page-form.tsx
index 43d134168..aaf6ec269 100644
--- a/apps/web/src/components/forms/status-page-form.tsx
+++ b/apps/web/src/components/forms/status-page-form.tsx
@@ -27,6 +27,7 @@ import { Input } from "@/components/ui/input";
import { InputWithAddons } from "@/components/ui/input-with-addons";
import { useDebounce } from "@/hooks/use-debounce";
import { useToastAction } from "@/hooks/use-toast-action";
+import useUpdateSearchParams from "@/hooks/use-update-search-params";
import { slugify } from "@/lib/utils";
import { api } from "@/trpc/client";
import { LoadingAnimation } from "../loading-animation";
@@ -39,12 +40,22 @@ interface Props {
defaultValues?: Schema;
workspaceSlug: string;
allMonitors?: z.infer<typeof allMonitorsExtendedSchema>;
+ /**
+ * gives the possibility to check all the monitors
+ */
+ checkAllMonitors?: boolean;
+ /**
+ * on submit, allows to push a url
+ */
+ nextUrl?: string;
}
export function StatusPageForm({
defaultValues,
workspaceSlug,
allMonitors,
+ checkAllMonitors,
+ nextUrl,
}: Props) {
const form = useForm<Schema>({
resolver: zodResolver(insertPageSchemaWithMonitors),
@@ -54,8 +65,11 @@ export function StatusPageForm({
description: defaultValues?.description || "",
workspaceId: defaultValues?.workspaceId || 0,
id: defaultValues?.id || 0,
- monitors: defaultValues?.monitors ?? [],
- customDomain: defaultValues?.customDomain || "", // HOTFIX: we need to keep all the other overwrites. Ideally, we append it in the api.update({ ...defaultValues, ...props })
+ monitors:
+ checkAllMonitors && allMonitors
+ ? allMonitors.map(({ id }) => id)
+ : defaultValues?.monitors ?? [],
+ customDomain: defaultValues?.customDomain || "",
workspaceSlug: "",
icon: defaultValues?.icon || "",
},
@@ -67,6 +81,8 @@ export function StatusPageForm({
const watchTitle = form.watch("title");
const debouncedSlug = useDebounce(watchSlug, 1000); // using debounce to not exhaust the server
const { toast } = useToastAction();
+ const updateSearchParams = useUpdateSearchParams();
+
const checkUniqueSlug = useCallback(async () => {
const isUnique = await api.page.getSlugUniqueness.query({
slug: debouncedSlug,
@@ -112,9 +128,13 @@ export function StatusPageForm({
...props,
workspaceSlug,
});
- router.replace(`./edit?id=${page?.id}`); // to stay on same page and enable 'Advanced' tab
+ const id = page?.id || null;
+ router.replace(`?${updateSearchParams({ id })}`); // to stay on same page and enable 'Advanced' tab
}
toast("saved");
+ if (nextUrl) {
+ router.push(nextUrl);
+ }
router.refresh();
} catch {
toast("error");
@@ -294,7 +314,7 @@ export function StatusPageForm({
<FormLabel className="font-normal">
{item.name}
</FormLabel>
- <FormDescription>{item.description}</FormDescription>
+ <FormDescription>{item.url}</FormDescription>
</div>
</FormItem>
);
@@ -306,7 +326,7 @@ export function StatusPageForm({
)}
/>
<div className="sm:col-span-full">
- <Button className="w-full sm:w-auto">
+ <Button className="w-full sm:w-auto" size="lg">
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
</div>
diff --git a/apps/web/src/components/layout/app-header.tsx b/apps/web/src/components/layout/app-header.tsx
index e8a6ea00d..a4270aa3f 100644
--- a/apps/web/src/components/layout/app-header.tsx
+++ b/apps/web/src/components/layout/app-header.tsx
@@ -21,7 +21,7 @@ export function AppHeader() {
const { isLoaded, isSignedIn } = useUser();
return (
- <header className="border-border sticky top-3 z-50 w-full">
+ <header className="border-border sticky top-3 z-50 w-full md:top-6">
<Shell className="bg-background/70 flex w-full items-center justify-between px-3 py-3 backdrop-blur-lg md:px-6 md:py-3">
<Link
href="/"
diff --git a/apps/web/src/hooks/use-toast-action.tsx b/apps/web/src/hooks/use-toast-action.tsx
index 86d4cdc4a..066feae02 100644
--- a/apps/web/src/hooks/use-toast-action.tsx
+++ b/apps/web/src/hooks/use-toast-action.tsx
@@ -22,6 +22,14 @@ const config = {
success: { title: "Success" },
deleted: { title: "Deleted successfully." }, // TODO: we are not informing the user besides the visual changes when an entry has been deleted
saved: { title: "Saved successfully." },
+ "test-error": {
+ title: "Endpoint configuration failed.",
+ // description: "Be sure to include the auth headers.",
+ variant: "destructive",
+ },
+ "test-success": {
+ title: "Endpoint configuration passed.",
+ },
} as const satisfies Record<string, Toast>;
type ToastAction = keyof typeof config;
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index 1accb3cd5..af1496493 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -3,7 +3,12 @@ import { NextResponse } from "next/server";
import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
import { db, eq } from "@openstatus/db";
-import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
+import {
+ monitor,
+ user,
+ usersToWorkspaces,
+ workspace,
+} from "@openstatus/db/src/schema";
import { env } from "./env";
@@ -108,6 +113,21 @@ export default authMiddleware({
.where(eq(workspace.id, result[0].users_to_workspaces.workspaceId))
.get();
if (currentWorkspace) {
+ const firstMonitor = await db
+ .select()
+ .from(monitor)
+ .where(eq(monitor.workspaceId, currentWorkspace.id))
+ .get();
+
+ if (!firstMonitor) {
+ console.log(`>>> Redirecting to onboarding`);
+ const onboarding = new URL(
+ `/app/onboarding?workspaceSlug=${currentWorkspace.slug}`,
+ req.url,
+ );
+ return NextResponse.redirect(onboarding);
+ }
+
const orgSelection = new URL(
`/app/${currentWorkspace.slug}/monitors`,
req.url,
@@ -163,5 +183,6 @@ export const config = {
"/app/integrations/vercel/configure",
"/(api/webhook|api/trpc)(.*)",
"/(!api/checker/:path*|!api/og|!api/ping)",
+ "/api/analytics", // used for tracking vercel beta integration click events
],
};
diff --git a/packages/analytics/src/type.ts b/packages/analytics/src/type.ts
index 22a07f250..604a498c1 100644
--- a/packages/analytics/src/type.ts
+++ b/packages/analytics/src/type.ts
@@ -14,4 +14,5 @@ export type AnalyticsEvents =
slug: string;
}
| { event: "User Upgraded"; email: string }
- | { event: "User Signed In" };
+ | { event: "User Signed In" }
+ | { event: "User Vercel Beta" };
diff --git a/packages/db/src/schema/monitor.ts b/packages/db/src/schema/monitor.ts
index 5b8264ffa..f84007c48 100644
--- a/packages/db/src/schema/monitor.ts
+++ b/packages/db/src/schema/monitor.ts
@@ -117,7 +117,7 @@ export const insertMonitorSchema = createInsertSchema(monitor, {
active: z.boolean().default(false),
regions: z.array(RegionEnum).default([]).optional(),
method: z.enum(METHODS).default("GET"),
- body: z.string().default(""),
+ body: z.string().default("").optional(),
headers: z
.array(z.object({ key: z.string(), value: z.string() }))
.default([]),