Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: split workspace usage from get, tidy dashboard tRPC setup (#2542)
Maximilian Kaskee1aed597d72e
diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsxindex 0c86f1240..c3182ef09 100644--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx@@ -81,6 +81,7 @@ export function Client() {const [isPending, startTransition] = useTransition();const [{ success }, setSearchParams] = useQueryStates(searchParamsParsers);const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());+ const { data: usage } = useQuery(trpc.workspace.usage.queryOptions());const customerPortalMutation = useMutation(trpc.stripeRouter.getUserCustomerPortal.mutationOptions({onSuccess: (url) => {@@ -152,22 +153,22 @@ export function Client() {<div className="flex flex-col gap-2"><BillingProgresslabel="Monitors"- value={workspace.usage?.monitors ?? 0}+ value={usage?.monitors ?? 0}max={workspace.limits.monitors}/><BillingProgresslabel="Status Pages"- value={workspace.usage?.pages ?? 0}+ value={usage?.pages ?? 0}max={workspace.limits["status-pages"]}/><BillingProgresslabel="Page Components"- value={workspace.usage?.pageComponents ?? 0}+ value={usage?.pageComponents ?? 0}max={workspace.limits["page-components"]}/><BillingProgresslabel="Notifications"- value={workspace.usage?.notifications ?? 0}+ value={usage?.notifications ?? 0}max={workspace.limits["notification-channels"]}/><BillingProgressdiff --git a/apps/dashboard/src/app/(dashboard)/status-pages/create/client.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/create/client.tsxindex b26448ff0..3adfb8ccc 100644--- a/apps/dashboard/src/app/(dashboard)/status-pages/create/client.tsx+++ b/apps/dashboard/src/app/(dashboard)/status-pages/create/client.tsx@@ -28,9 +28,8 @@ export function Client() {trpc.page.new.mutationOptions({onSuccess: (data) => {refetch();- // NOTE: invalidate workspace to update the usagequeryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});startTransition(() => {router.push(`/status-pages/${data.id}/edit`);diff --git a/apps/dashboard/src/app/onboarding/client.tsx b/apps/dashboard/src/app/onboarding/client.tsxindex 81e2e2f74..ffc90cf62 100644--- a/apps/dashboard/src/app/onboarding/client.tsx+++ b/apps/dashboard/src/app/onboarding/client.tsx@@ -83,14 +83,14 @@ export function Client() {const { data: monitors } = useQuery(trpc.monitor.list.queryOptions());const { data: pages } = useQuery(trpc.page.list.queryOptions());- // Invalidate so workspace counts (sidebar quota, plan gates) stay fresh.+ // Invalidate so the getting-started counts stay fresh.const createMonitorMutation = useMutation(trpc.monitor.new.mutationOptions({onSuccess: async () => {await setSearchParams({ monitor: "completed" });await Promise.all([queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),}),queryClient.invalidateQueries({queryKey: trpc.monitor.list.queryKey(),@@ -105,7 +105,7 @@ export function Client() {await setSearchParams({ page: "completed" });await Promise.all([queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),}),queryClient.invalidateQueries({queryKey: trpc.page.list.queryKey(),diff --git a/apps/dashboard/src/components/data-table/monitors/data-table-action-bar.tsx b/apps/dashboard/src/components/data-table/monitors/data-table-action-bar.tsxindex 93423d78d..cc6d895a2 100644--- a/apps/dashboard/src/components/data-table/monitors/data-table-action-bar.tsx+++ b/apps/dashboard/src/components/data-table/monitors/data-table-action-bar.tsx@@ -65,7 +65,7 @@ export function MonitorDataTableActionBar({queryKey: trpc.monitor.list.queryKey(),});queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});// Clear selection once deletion succeedstable.toggleAllRowsSelected(false);diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsxindex 340eae0a1..10d10ab6d 100644--- a/apps/dashboard/src/components/forms/components/update.tsx+++ b/apps/dashboard/src/components/forms/components/update.tsx@@ -36,9 +36,9 @@ export function FormComponentsUpdate() {// "removed" (delete) and placeholders as "new" (create).const refetchAndRemount = async (...refetches: Promise<unknown>[]) => {await Promise.all(refetches);- // invalidate workspace to update the usage (getting-started checklist)+ // the getting-started checklist reads these countsqueryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});setFormKey((k) => k + 1);};diff --git a/apps/dashboard/src/components/forms/status-page/update.tsx b/apps/dashboard/src/components/forms/status-page/update.tsxindex 8f3c600f0..faeb9e5f0 100644--- a/apps/dashboard/src/components/forms/status-page/update.tsx+++ b/apps/dashboard/src/components/forms/status-page/update.tsx@@ -61,11 +61,9 @@ export function FormStatusPageUpdate() {trpc.page.delete.mutationOptions({onSuccess: () => {router.push("/status-pages");- // NOTE: invalidate workspace to update the usagequeryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});- // NOTE: invalidate status page list to update the usagequeryClient.invalidateQueries({queryKey: trpc.page.list.queryKey(),});diff --git a/apps/dashboard/src/components/nav/nav-banner-checklist.tsx b/apps/dashboard/src/components/nav/nav-banner-checklist.tsxindex 6f7820d39..b08269f55 100644--- a/apps/dashboard/src/components/nav/nav-banner-checklist.tsx+++ b/apps/dashboard/src/components/nav/nav-banner-checklist.tsx@@ -19,18 +19,20 @@ export function NavBannerChecklist({handleClose: () => void;}) {const trpc = useTRPC();- const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());+ const { data: usage } = useQuery(trpc.workspace.usage.queryOptions());const { data: pages } = useQuery(trpc.page.list.queryOptions());- if (!workspace) return null;+ // Hide until the counts land — every item would read as unchecked and the+ // banner would flash "0/5" before correcting itself.+ if (!usage) return null;const onlyPage = pages?.length === 1 ? pages[0] : undefined;- const hasMonitors = (workspace.usage?.monitors ?? 0) > 0;- const hasStatusPages = (workspace.usage?.pages ?? 0) > 0;- const hasPageComponents = (workspace.usage?.pageComponents ?? 0) > 0;- const hasNotifications = (workspace.usage?.notifications ?? 0) > 0;- const hasStatusReports = (workspace.usage?.statusReports ?? 0) > 0;+ const hasMonitors = usage.monitors > 0;+ const hasStatusPages = usage.pages > 0;+ const hasPageComponents = usage.pageComponents > 0;+ const hasNotifications = usage.notifications > 0;+ const hasStatusReports = usage.statusReports > 0;const items = [{diff --git a/apps/dashboard/src/components/nav/nav-monitors.tsx b/apps/dashboard/src/components/nav/nav-monitors.tsxindex a8618ba1e..8464b927e 100644--- a/apps/dashboard/src/components/nav/nav-monitors.tsx+++ b/apps/dashboard/src/components/nav/nav-monitors.tsx@@ -58,7 +58,7 @@ export function NavMonitors() {onSuccess: () => {refetch();queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});},}),@@ -68,7 +68,7 @@ export function NavMonitors() {onSuccess: (newMonitor) => {refetch();queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});router.push(`/monitors/${newMonitor.id}`);},diff --git a/apps/dashboard/src/components/nav/nav-status-pages.tsx b/apps/dashboard/src/components/nav/nav-status-pages.tsxindex 177c2b863..68ac1bda0 100644--- a/apps/dashboard/src/components/nav/nav-status-pages.tsx+++ b/apps/dashboard/src/components/nav/nav-status-pages.tsx@@ -54,7 +54,7 @@ export function NavStatusPages() {onSuccess: () => {refetch();queryClient.invalidateQueries({- queryKey: trpc.workspace.get.queryKey(),+ queryKey: trpc.workspace.usage.queryKey(),});},}),diff --git a/apps/dashboard/src/lib/trpc/client.tsx b/apps/dashboard/src/lib/trpc/client.tsxindex 6a98c272e..653d8b487 100644--- a/apps/dashboard/src/lib/trpc/client.tsx+++ b/apps/dashboard/src/lib/trpc/client.tsx@@ -1,27 +1,18 @@"use client";import type { AppRouter } from "@openstatus/api";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { QueryClient } from "@tanstack/react-query";+import { QueryClientProvider } from "@tanstack/react-query";import { createTRPCClient } from "@trpc/client";import { createTRPCContext } from "@trpc/tanstack-react-query";import { useState } from "react";+import { makeQueryClient } from "@/lib/trpc/query-client";import { endingLink, sentryLoggerLink } from "@/lib/trpc/shared";export const { TRPCProvider, useTRPC, useTRPCClient } =createTRPCContext<AppRouter>();-function makeQueryClient() {- return new QueryClient({- defaultOptions: {- queries: {- // With SSR, we usually want to set some default staleTime- // above 0 to avoid refetching immediately on the client- staleTime: 60 * 1000,- },- },- });-}let browserQueryClient: QueryClient | undefined = undefined;function getQueryClient() {if (typeof window === "undefined") {diff --git a/apps/dashboard/src/lib/trpc/server.tsx b/apps/dashboard/src/lib/trpc/server.tsxindex 2356eb073..6965fd79f 100644--- a/apps/dashboard/src/lib/trpc/server.tsx+++ b/apps/dashboard/src/lib/trpc/server.tsx@@ -2,7 +2,7 @@ import "server-only";import type { AppRouter } from "@openstatus/api";import { HydrationBoundary } from "@tanstack/react-query";import { dehydrate } from "@tanstack/react-query";-import { TRPCClientError, createTRPCClient } from "@trpc/client";+import { createTRPCClient } from "@trpc/client";import {type ResolverDef,type TRPCQueryOptions,@@ -91,6 +91,18 @@ export function batchPrefetch<T extends ReturnType<TRPCQueryOptions<any>>>(}}+// Duck-typed rather than `instanceof TRPCClientError`: that check fails across+// bundle boundaries, and an in-process caller throws `TRPCError` (bare `code`,+// no `data`). tRPC matches on the same fields internally for this reason.+function isNotFoundError(error: unknown): boolean {+ if (typeof error !== "object" || error === null) return false;+ const { code, data } = error as {+ code?: unknown;+ data?: { code?: unknown } | null;+ };+ return code === "NOT_FOUND" || data?.code === "NOT_FOUND";+}+/*** Fetches a query and calls `notFound()` if the server returns NOT_FOUND.* Use this for gating queries in layouts where the resource must exist.@@ -104,9 +116,7 @@ export async function fetchQueryOrNotFound<ReturnType<Extract<T["queryFn"], (...args: never[]) => unknown>>>;} catch (error) {- if (error instanceof TRPCClientError && error.data?.code === "NOT_FOUND") {- notFound();- }+ if (isNotFoundError(error)) notFound();throw error;}}diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.tsindex dc62ff93b..ec0fd9cea 100644--- a/packages/api/src/router/workspace.ts+++ b/packages/api/src/router/workspace.ts@@ -1,6 +1,6 @@import { Events } from "@openstatus/analytics";import {- getWorkspaceWithUsage,+ getWorkspaceUsage,updateWorkspaceName,} from "@openstatus/services/workspace";import { z } from "zod";@@ -9,9 +9,14 @@ import { toServiceCtx, toTRPCError } from "../service-adapter";import { createTRPCRouter, protectedProcedure } from "../trpc";export const workspaceRouter = createTRPCRouter({- get: protectedProcedure.query(async ({ ctx }) => {+ // The authed middleware already resolved and parsed this row; re-selecting+ // it would be the same query. Counts live in `usage` — the shell reads+ // `limits` on every route, the counts only on two surfaces.+ get: protectedProcedure.query(({ ctx }) => ctx.workspace),++ usage: protectedProcedure.query(async ({ ctx }) => {try {- return await getWorkspaceWithUsage({ ctx: toServiceCtx(ctx) });+ return await getWorkspaceUsage({ ctx: toServiceCtx(ctx) });} catch (err) {toTRPCError(err);}diff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.tsindex d000fedd3..e79a8669e 100644--- a/packages/services/src/workspace/__tests__/workspace.test.ts+++ b/packages/services/src/workspace/__tests__/workspace.test.ts@@ -26,7 +26,7 @@ import { ForbiddenError } from "../../errors";import {getWorkspace,getWorkspaceByStripeId,- getWorkspaceWithUsage,+ getWorkspaceUsage,listWorkspaces,updateWorkspaceName,updateWorkspacePlan,@@ -51,19 +51,18 @@ describe("getWorkspace", () => {});});-describe("getWorkspaceWithUsage", () => {- test("attaches a zero-or-positive usage block", async () => {+describe("getWorkspaceUsage", () => {+ test("returns a zero-or-positive count for every key", async () => {await withTestTransaction(async (tx) => {- const result = await getWorkspaceWithUsage({+ const result = await getWorkspaceUsage({ctx: { ...teamCtx, db: tx },});- expect(result.id).toBe(teamCtx.workspace.id);// Iterate the usage object *before* any `toMatchObject` call —// the `toMatchObject` implementation mutates the received// object in place, replacing number fields with the// `expect.any(Number)` asymmetric-matcher stub on the expected- // side. Subsequent reads of `result.usage.<key>` then return the+ // side. Subsequent reads of `result.<key>` then return the// matcher object (typeof "object"), not the original count. Do// the value-shape + non-negative check first.for (const key of [@@ -74,13 +73,13 @@ describe("getWorkspaceWithUsage", () => {"statusReports","checks",] as const) {- const value = result.usage[key];+ const value = result[key];expect(typeof value).toBe("number");if (typeof value === "number") {expect(value).toBeGreaterThanOrEqual(0);}}- expect(result.usage.checks).toBe(0);+ expect(result.checks).toBe(0);});});@@ -91,10 +90,10 @@ describe("getWorkspaceWithUsage", () => {status: "investigating",title: "svc-ws-test-status-report",});- const result = await getWorkspaceWithUsage({+ const result = await getWorkspaceUsage({ctx: { ...teamCtx, db: tx },});- expect(result.usage.statusReports).toBeGreaterThanOrEqual(1);+ expect(result.statusReports).toBeGreaterThanOrEqual(1);});});@@ -104,7 +103,7 @@ describe("getWorkspaceWithUsage", () => {await withTestTransaction(async (tx) => {const ctx = { ...teamCtx, db: tx };const workspaceId = teamCtx.workspace.id;- const before = (await getWorkspaceWithUsage({ ctx })).usage;+ const before = await getWorkspaceUsage({ ctx });await tx.insert(monitor).values([{ workspaceId, url: "https://a.example.dev", name: "svc-ws-usage-1" },@@ -149,7 +148,7 @@ describe("getWorkspaceWithUsage", () => {title: "svc-ws-usage-report",});- const after = (await getWorkspaceWithUsage({ ctx })).usage;+ const after = await getWorkspaceUsage({ ctx });expect(after.monitors).toBe(before.monitors + 2);expect(after.notifications).toBe(before.notifications + 1);expect(after.pages).toBe(before.pages + 1);@@ -163,7 +162,7 @@ describe("getWorkspaceWithUsage", () => {await withTestTransaction(async (tx) => {const ctx = { ...teamCtx, db: tx };const workspaceId = teamCtx.workspace.id;- const before = (await getWorkspaceWithUsage({ ctx })).usage.monitors;+ const before = (await getWorkspaceUsage({ ctx })).monitors;await tx.insert(monitor).values({workspaceId,@@ -172,7 +171,7 @@ describe("getWorkspaceWithUsage", () => {deletedAt: new Date(),});- const after = (await getWorkspaceWithUsage({ ctx })).usage.monitors;+ const after = (await getWorkspaceUsage({ ctx })).monitors;expect(after).toBe(before);});});@@ -180,7 +179,7 @@ describe("getWorkspaceWithUsage", () => {test("does not count another workspace's rows", async () => {await withTestTransaction(async (tx) => {const ctx = { ...teamCtx, db: tx };- const before = (await getWorkspaceWithUsage({ ctx })).usage;+ const before = await getWorkspaceUsage({ ctx });const [foreign] = await tx.insert(workspace)@@ -203,7 +202,7 @@ describe("getWorkspaceWithUsage", () => {title: "svc-ws-usage-foreign-report",});- const after = (await getWorkspaceWithUsage({ ctx })).usage;+ const after = await getWorkspaceUsage({ ctx });expect(after.monitors).toBe(before.monitors);expect(after.statusReports).toBe(before.statusReports);});diff --git a/packages/services/src/workspace/index.ts b/packages/services/src/workspace/index.tsindex 4e8e953ff..04d385a1a 100644--- a/packages/services/src/workspace/index.ts+++ b/packages/services/src/workspace/index.ts@@ -1,17 +1,16 @@export {getWorkspace,getWorkspaceByStripeId,- getWorkspaceWithUsage,+ getWorkspaceUsage,listWorkspaces,type WorkspaceUsage,- type WorkspaceWithUsage,} from "./list";export { downgradeWorkspaceToFree } from "./downgrade";export { updateWorkspaceName, updateWorkspacePlan } from "./update";export {GetWorkspaceByStripeIdInput,GetWorkspaceInput,- GetWorkspaceWithUsageInput,+ GetWorkspaceUsageInput,ListWorkspacesInput,UpdateWorkspaceNameInput,UpdateWorkspacePlanInput,diff --git a/packages/services/src/workspace/list.ts b/packages/services/src/workspace/list.tsindex 094d8744a..3f45e3fac 100644--- a/packages/services/src/workspace/list.ts+++ b/packages/services/src/workspace/list.ts@@ -15,7 +15,7 @@ import { NotFoundError } from "../errors";import type { Workspace } from "../types";import {GetWorkspaceByStripeIdInput,- type GetWorkspaceWithUsageInput,+ type GetWorkspaceUsageInput,ListWorkspacesInput,} from "./schemas";@@ -33,8 +33,6 @@ export type WorkspaceUsage = {checks: number;};-export type WorkspaceWithUsage = Workspace & { usage: WorkspaceUsage };-/** Load the workspace the caller is scoped to. */export async function getWorkspace(args: {ctx: ServiceContext;@@ -55,32 +53,12 @@ export async function getWorkspace(args: {return selectWorkspaceSchema.parse(result);}-/**- * Workspace plus the four usage counts the dashboard surfaces alongside plan- * limits. Active monitors only (`deletedAt IS NULL`); notifications / pages /- * page-components are unconditional counts scoped to the workspace.- */-export async function getWorkspaceWithUsage(args: {- ctx: ServiceContext;- input?: GetWorkspaceWithUsageInput;-}): Promise<WorkspaceWithUsage> {- const { ctx } = args;- const db = ctx.db ?? defaultDb;- const workspaceId = ctx.workspace.id;+// Counts, not rows: the previous relational read materialized every page,+// component, monitor (with its config blobs) and notification just to call+// `.length` on them. All five are single-table and index-covered.+function usageCountQueries(db: DB, workspaceId: number) {const total = sql<number>`count(*)`;-- // Counts, not rows: the previous relational read materialized every page,- // component, monitor (with its config blobs) and notification just to call- // `.length` on them.- const [- workspaceRows,- monitorRows,- notificationRows,- pageRows,- pageComponentRows,- statusReportRows,- ] = await batchReads(db, [- db.select().from(workspace).where(eq(workspace.id, workspaceId)),+ return [db.select({ count: total }).from(monitor)@@ -103,28 +81,36 @@ export async function getWorkspaceWithUsage(args: {.select({ count: total }).from(statusReport).where(eq(statusReport.workspaceId, workspaceId)),- ]);-- const result = workspaceRows[0];-- // Same guard as `getWorkspace` — unreachable in practice (workspace- // resolved upstream) but keeps the error shape consistent with every- // other service, rather than letting `parse(undefined)` surface as- // a `ZodError`.- if (!result) throw new NotFoundError("workspace", workspaceId);-- const usage: WorkspaceUsage = {- monitors: monitorRows[0]?.count ?? 0,- notifications: notificationRows[0]?.count ?? 0,- pages: pageRows[0]?.count ?? 0,- pageComponents: pageComponentRows[0]?.count ?? 0,- statusReports: statusReportRows[0]?.count ?? 0,+ ] as const;+}++function toUsage(rows: { count: number }[][]): WorkspaceUsage {+ const [monitors, notifications, pages, pageComponents, statusReports] = rows;+ return {+ monitors: monitors?.[0]?.count ?? 0,+ notifications: notifications?.[0]?.count ?? 0,+ pages: pages?.[0]?.count ?? 0,+ pageComponents: pageComponents?.[0]?.count ?? 0,+ statusReports: statusReports?.[0]?.count ?? 0,// Parity with the legacy router — checks usage was previously commented// out pending a real source and left as 0. Preserved here.checks: 0,};+}++/**+ * The usage counts the dashboard surfaces alongside plan limits. Active+ * monitors only (`deletedAt IS NULL`); notifications / pages / page-components+ * are unconditional counts scoped to the workspace.+ */+export async function getWorkspaceUsage(args: {+ ctx: ServiceContext;+ input?: GetWorkspaceUsageInput;+}): Promise<WorkspaceUsage> {+ const { ctx } = args;+ const db = ctx.db ?? defaultDb;- return { ...selectWorkspaceSchema.parse(result), usage };+ return toUsage(await batchReads(db, usageCountQueries(db, ctx.workspace.id)));}/**diff --git a/packages/services/src/workspace/schemas.ts b/packages/services/src/workspace/schemas.tsindex 33917227a..4a80811f7 100644--- a/packages/services/src/workspace/schemas.ts+++ b/packages/services/src/workspace/schemas.ts@@ -5,10 +5,8 @@ import { z } from "zod";export const GetWorkspaceInput = z.object({}).strict();export type GetWorkspaceInput = z.infer<typeof GetWorkspaceInput>;-export const GetWorkspaceWithUsageInput = z.object({}).strict();-export type GetWorkspaceWithUsageInput = z.infer<- typeof GetWorkspaceWithUsageInput->;+export const GetWorkspaceUsageInput = z.object({}).strict();+export type GetWorkspaceUsageInput = z.infer<typeof GetWorkspaceUsageInput>;export const ListWorkspacesInput = z.object({ userId: z.number().int() });export type ListWorkspacesInput = z.infer<typeof ListWorkspacesInput>;