Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
perf: dedupe and batch the dashboard shell queries (#2541)
Maximilian Kaske24bdb1f73f08
diff --git a/apps/dashboard/src/components/nav/nav-status-pages.tsx b/apps/dashboard/src/components/nav/nav-status-pages.tsxindex 33508c884..177c2b863 100644--- a/apps/dashboard/src/components/nav/nav-status-pages.tsx+++ b/apps/dashboard/src/components/nav/nav-status-pages.tsx@@ -119,10 +119,6 @@ export function NavStatusPages() {toast.success("Status Page ID copied to clipboard");},});- const hasActiveStatusReport = item.statusReports.some(- (report) => report.status !== "resolved",- );-return (<SidebarMenuItem key={item.id}><SidebarMenuButton@@ -150,7 +146,9 @@ export function NavStatusPages() {className={cn("absolute top-1/2 left-1/2 h-2 w-2 -translate-x-1/2 -translate-y-1/2 rounded-full",STATUS[- hasActiveStatusReport ? "degraded" : "operational"+ item.hasActiveStatusReport+ ? "degraded"+ : "operational"],)}/>diff --git a/packages/api/src/auth/resolve-active-workspace.ts b/packages/api/src/auth/resolve-active-workspace.tsindex 400ac9f01..46cdedc7d 100644--- a/packages/api/src/auth/resolve-active-workspace.ts+++ b/packages/api/src/auth/resolve-active-workspace.ts@@ -3,11 +3,17 @@ import type { User, Workspace } from "@openstatus/db/src/schema";/*** Result of resolving the active workspace for an authenticated user.- * Both fields are guaranteed non-null on success.+ * All fields are guaranteed non-null on success.*/export type ActiveWorkspace = {user: User;workspace: Workspace;+ /**+ * Every workspace the user belongs to — the resolver already joins them+ * to pick the active one, so `workspace.list` needs no query of its own.+ * Always contains `workspace`.+ */+ workspaces: Workspace[];};export type ResolveActiveWorkspaceFailure =@@ -54,5 +60,8 @@ export async function resolveActiveWorkspace(args: {const user = schema.selectUserSchema.parse(userProps);const workspace = schema.selectWorkspaceSchema.parse(activeWorkspace);- return { ok: true, value: { user, workspace } };+ const workspaces = (usersToWorkspaces ?? []).map((row) =>+ schema.selectWorkspaceSchema.parse(row.workspace),+ );+ return { ok: true, value: { user, workspace, workspaces } };}diff --git a/packages/api/src/router/user.ts b/packages/api/src/router/user.tsindex bf18a9a6e..06d92e355 100644--- a/packages/api/src/router/user.ts+++ b/packages/api/src/router/user.ts@@ -1,19 +1,14 @@-import { deleteAccount, getUser } from "@openstatus/services/user";+import { deleteAccount } from "@openstatus/services/user";import { toServiceCtx, toTRPCError } from "../service-adapter";import { createTRPCRouter, protectedProcedure } from "../trpc";export const userRouter = createTRPCRouter({- get: protectedProcedure.query(async ({ ctx }) => {- try {- return await getUser({- ctx: toServiceCtx(ctx),- input: { userId: ctx.user.id },- });- } catch (err) {- toTRPCError(err);- }- }),+ // The authed middleware already loaded this row; re-selecting it would be+ // the same query. `undefined` for a soft-deleted user matches `getUser`.+ get: protectedProcedure.query(({ ctx }) =>+ ctx.user.deletedAt ? undefined : ctx.user,+ ),deleteAccount: protectedProcedure.mutation(async ({ ctx }) => {try {diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.tsindex 71ac0fa86..dc62ff93b 100644--- a/packages/api/src/router/workspace.ts+++ b/packages/api/src/router/workspace.ts@@ -1,7 +1,6 @@import { Events } from "@openstatus/analytics";import {getWorkspaceWithUsage,- listWorkspaces,updateWorkspaceName,} from "@openstatus/services/workspace";import { z } from "zod";@@ -18,16 +17,9 @@ export const workspaceRouter = createTRPCRouter({}}),- list: protectedProcedure.query(async ({ ctx }) => {- try {- return await listWorkspaces({- ctx: toServiceCtx(ctx),- input: { userId: ctx.user.id },- });- } catch (err) {- toTRPCError(err);- }- }),+ // `resolveActiveWorkspace` already joined the user's workspaces to pick the+ // active one, so this is the same rows the service would re-query.+ list: protectedProcedure.query(({ ctx }) => ctx.workspaces),updateName: protectedProcedure.meta({ track: Events.UpdateWorkspace })diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.tsindex 1dfefc638..a10d20f70 100644--- a/packages/api/src/trpc.ts+++ b/packages/api/src/trpc.ts@@ -36,6 +36,7 @@ type Session = {type CreateContextOptions = {session: Session | null;workspace?: Workspace | null;+ workspaces?: Workspace[] | null;user?: User | null;req?: NextRequest;metadata?: {@@ -79,6 +80,7 @@ export const createTRPCContext = async (opts: {// Use provided auth function or return null sessionconst session = opts.auth ? await opts.auth() : null;const workspace = null;+ const workspaces = null;const user = null;// Context is per HTTP request while middleware runs per procedure — a@@ -95,6 +97,7 @@ export const createTRPCContext = async (opts: {return createInnerTRPCContext({session,workspace,+ workspaces,user,resolveWorkspace,req: opts.req,@@ -198,7 +201,12 @@ const enforceUserIsAuthed = t.middleware(async (opts) => {ctx.user != null) {return opts.next({- ctx: { ...ctx, user: ctx.user, workspace: ctx.workspace },+ ctx: {+ ...ctx,+ user: ctx.user,+ workspace: ctx.workspace,+ workspaces: ctx.workspaces ?? [ctx.workspace],+ },});}@@ -226,14 +234,16 @@ const enforceUserIsAuthed = t.middleware(async (opts) => {});}- const { user, workspace } = resolved.value;+ const { user, workspace, workspaces } = resolved.value;if (workspace.slug !== workspaceSlug) {// properly set the workspace slug cookiectx.req?.cookies.set("workspace-slug", workspace.slug);}- const result = await opts.next({ ctx: { ...ctx, user, workspace } });+ const result = await opts.next({+ ctx: { ...ctx, user, workspace, workspaces },+ });if (process.env.NODE_ENV === "test") {return result;diff --git a/packages/services/src/__tests__/context.test.ts b/packages/services/src/__tests__/context.test.tsnew file mode 100644index 000000000..c285add6a--- /dev/null+++ b/packages/services/src/__tests__/context.test.ts@@ -0,0 +1,128 @@+import { db, eq } from "@openstatus/db";+import { monitor, page } from "@openstatus/db/src/schema";+import { expect } from "@std/expect";+import { beforeAll, describe, test } from "@std/testing/bdd";++import {+ createWorkspaceFixture,+ withTestTransaction,+} from "../../test/helpers";+import { type DB, batchReads, isTx } from "../context";++// `batchReads` has two implementations behind one signature: `db.batch()`+// (one libsql round-trip) outside a transaction, `Promise.all` inside one.+// Every other suite runs its body in `withTestTransaction`, so the batch+// branch would never be covered — these tests drive the committed db on+// purpose so both branches are exercised and compared.++let workspaceId: number;++beforeAll(async () => {+ const fixture = await createWorkspaceFixture("team");+ workspaceId = fixture.workspace.id;++ await db.insert(page).values([+ {+ workspaceId,+ title: "batch-reads-a",+ description: "",+ slug: `svc-batch-a-${workspaceId}`,+ customDomain: "",+ },+ {+ workspaceId,+ title: "batch-reads-b",+ description: "",+ slug: `svc-batch-b-${workspaceId}`,+ customDomain: "",+ },+ ]);+ await db.insert(monitor).values({+ workspaceId,+ url: "https://example.openstatus.dev",+ name: "batch-reads-monitor",+ });+});++const pagesOf = (conn: DB) =>+ conn.select().from(page).where(eq(page.workspaceId, workspaceId));++const monitorsOf = (conn: DB) =>+ conn.select().from(monitor).where(eq(monitor.workspaceId, workspaceId));++describe("batchReads", () => {+ test("the committed client is not a tx, the test wrapper's handle is", async () => {+ // Guards the premise of every other case here: if this flipped, the+ // batch branch would silently stop being covered.+ expect(isTx(db)).toBe(false);+ await withTestTransaction(async (tx) => {+ expect(isTx(tx)).toBe(true);+ });+ });++ test("returns one result per query, positionally", async () => {+ const [pages, monitors] = await batchReads(db, [+ pagesOf(db),+ monitorsOf(db),+ ]);++ expect(pages).toHaveLength(2);+ expect(monitors).toHaveLength(1);+ // Shape, not just length — a transposed batch would still be 2 then 1+ // if both tables happened to have matching row counts.+ expect(pages.every((r) => "slug" in r)).toBe(true);+ expect(monitors.every((r) => "periodicity" in r)).toBe(true);+ });++ test("batch path matches awaiting each query on its own", async () => {+ const [batchedPages, batchedMonitors] = await batchReads(db, [+ pagesOf(db),+ monitorsOf(db),+ ]);+ const serialPages = await pagesOf(db);+ const serialMonitors = await monitorsOf(db);++ expect(batchedPages.map((p) => p.id)).toEqual(serialPages.map((p) => p.id));+ expect(batchedMonitors.map((m) => m.id)).toEqual(+ serialMonitors.map((m) => m.id),+ );+ });++ test("in-transaction fallback returns the same results as the batch path", async () => {+ const [batchedPages, batchedMonitors] = await batchReads(db, [+ pagesOf(db),+ monitorsOf(db),+ ]);++ await withTestTransaction(async (tx) => {+ const [txPages, txMonitors] = await batchReads(tx, [+ pagesOf(tx),+ monitorsOf(tx),+ ]);+ expect(txPages.map((p) => p.id)).toEqual(batchedPages.map((p) => p.id));+ expect(txMonitors.map((m) => m.id)).toEqual(+ batchedMonitors.map((m) => m.id),+ );+ });+ });++ test("inside a tx it observes writes made earlier in that tx", async () => {+ await withTestTransaction(async (tx) => {+ const [before] = await batchReads(tx, [pagesOf(tx)]);+ await tx.insert(page).values({+ workspaceId,+ title: "batch-reads-in-tx",+ description: "",+ slug: `svc-batch-tx-${workspaceId}`,+ customDomain: "",+ });+ const [after] = await batchReads(tx, [pagesOf(tx)]);+ expect(after).toHaveLength(before.length + 1);+ });+ });++ test("accepts a single-query batch", async () => {+ const [pages] = await batchReads(db, [pagesOf(db)]);+ expect(pages).toHaveLength(2);+ });+});diff --git a/packages/services/src/context.ts b/packages/services/src/context.tsindex 8a4bc6f4d..75361b61b 100644--- a/packages/services/src/context.ts+++ b/packages/services/src/context.ts@@ -68,6 +68,34 @@ export function getReadDb(ctx: ServiceContext): DB {return ctx.db ?? defaultDb;}+type BatchItemLike = Parameters<DrizzleClient["batch"]>[0][number];++type BatchResults<T extends readonly unknown[]> = {+ -readonly [K in keyof T]: Awaited<T[K]>;+};++/**+ * Run independent reads as one libsql round-trip instead of one HTTP+ * request per statement. Every query must be independent — the driver+ * sends them together, so none can consume another's result.+ *+ * Inside an interactive transaction there is no batch endpoint (the+ * session is baton-chained), so it degrades to `Promise.all`.+ *+ * Both casts are shape-preserving: drizzle types `batch()` as returning+ * `Awaited<T[K]>` per element, which is exactly what `Promise.all` on the+ * same thenables yields, but neither branch unifies with the generic+ * mapped type without help.+ */+export async function batchReads<+ T extends readonly [BatchItemLike, ...BatchItemLike[]],+>(db: DB, queries: T): Promise<BatchResults<T>> {+ if (isTx(db)) {+ return (await Promise.all(queries)) as BatchResults<T>;+ }+ return (await (db as DrizzleClient).batch(queries)) as BatchResults<T>;+}+export function extractActorId(actor: Actor): string {switch (actor.type) {case "user":diff --git a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.tsindex 47361a40c..1f8e4712a 100644--- a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts+++ b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts@@ -1,5 +1,5 @@import { eq } from "@openstatus/db";-import { monitorTag } from "@openstatus/db/src/schema";+import { monitorTag, workspace } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";@@ -214,3 +214,54 @@ describe("syncMonitorTags", () => {});});});++describe("listMonitorTags", () => {+ test("returns flat tag rows, without the monitor join", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ await syncMonitorTags({+ ctx,+ input: { tags: [{ name: "flat", color: "red" }] },+ });++ const rows = await listMonitorTags({ ctx });+ const row = rows.find((r) => r.name === "flat");+ expect(row).toBeDefined();+ // The join used to ship a full second copy of the monitor table in the+ // same batch as `monitor.list`; no consumer ever read it.+ expect(row && "monitor" in row).toBe(false);+ expect(row?.color).toBe("red");+ expect(row?.workspaceId).toBe(teamCtx.workspace.id);+ });+ });++ test("is scoped to the caller's workspace", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ await syncMonitorTags({+ ctx,+ input: { tags: [{ name: "scoped", color: "green" }] },+ });++ const [foreign] = await tx+ .insert(workspace)+ .values({+ slug: `svc-tag-foreign-${teamCtx.workspace.id}`,+ name: "Foreign",+ stripeId: `svc-tag-stripe-${teamCtx.workspace.id}`,+ plan: "team",+ })+ .returning();+ if (!foreign) throw new Error("workspace insert returned no row");+ await tx.insert(monitorTag).values({+ workspaceId: foreign.id,+ name: "foreign-tag",+ color: "blue",+ });++ const rows = await listMonitorTags({ ctx });+ expect(rows.some((r) => r.name === "scoped")).toBe(true);+ expect(rows.some((r) => r.name === "foreign-tag")).toBe(false);+ });+ });+});diff --git a/packages/services/src/monitor-tag/list.ts b/packages/services/src/monitor-tag/list.tsindex a68bedd6d..f668a63b9 100644--- a/packages/services/src/monitor-tag/list.ts+++ b/packages/services/src/monitor-tag/list.ts@@ -1,31 +1,23 @@import { eq } from "@openstatus/db";-import { monitorTag } from "@openstatus/db/src/schema";+import { monitorTag, selectMonitorTagSchema } from "@openstatus/db/src/schema";-import { type DrizzleClient, type ServiceContext, getReadDb } from "../context";+import { type ServiceContext, getReadDb } from "../context";+import type { MonitorTag } from "../types";import { ListMonitorTagsInput } from "./schemas";-/**- * List tags for the caller's workspace, with the join rows linking each- * tag to its monitors. Return type is drizzle's relational inference —- * the join target is `monitor_tag_to_monitor`, which has no exported- * select schema, so re-parsing through Zod here would only mirror the- * Drizzle inference at the cost of an extra round-trip. Flat-row services- * (e.g. invitation, member) do parse via `selectXSchema`; this list is- * deliberately the relational-query exception.- */+/** List tags for the caller's workspace. */export async function listMonitorTags(args: {ctx: ServiceContext;input?: ListMonitorTagsInput;-}) {+}): Promise<MonitorTag[]> {ListMonitorTagsInput.parse(args.input ?? {});- // Cast through `DrizzleClient` so the relational `query` API preserves- // its inferred return type. `DB = DrizzleClient | DrizzleTx` widens- // the call result to `unknown` under the union; runtime is identical- // (both expose the same `.query.<table>.findMany` shape).- const db = getReadDb(args.ctx) as DrizzleClient;+ const db = getReadDb(args.ctx);- return db.query.monitorTag.findMany({- where: eq(monitorTag.workspaceId, args.ctx.workspace.id),- with: { monitor: true },- });+ const rows = await db+ .select()+ .from(monitorTag)+ .where(eq(monitorTag.workspaceId, args.ctx.workspace.id))+ .all();++ return rows.map((r) => selectMonitorTagSchema.parse(r));}diff --git a/packages/services/src/monitor/__tests__/monitor.test.ts b/packages/services/src/monitor/__tests__/monitor.test.tsindex d8af1b469..44eaaa043 100644--- a/packages/services/src/monitor/__tests__/monitor.test.ts+++ b/packages/services/src/monitor/__tests__/monitor.test.ts@@ -1,4 +1,4 @@-import { db, eq, inArray } from "@openstatus/db";+import { and, db, eq, inArray, isNull } from "@openstatus/db";import {monitor,monitorTag,@@ -20,7 +20,7 @@ import {readAuditLog,withTestTransaction,} from "../../../test/helpers";-import type { ServiceContext } from "../../context";+import type { DrizzleTx, ServiceContext } from "../../context";import { ForbiddenError, NotFoundError } from "../../errors";import { cloneMonitor } from "../clone";import { createMonitor } from "../create";@@ -545,6 +545,112 @@ describe("list / get", () => {});});+// `totalSize` is derived from the page length whenever that is unambiguous,+// and only falls back to `count(*)` when it isn't. The derivation must agree+// with the count in every case, including past the end of the result set.+describe("listMonitors totalSize", () => {+ /** Seed `n` monitors and return the workspace's true monitor count. */+ const seed = async (tx: DrizzleTx, ctx: ServiceContext, n: number) => {+ for (let i = 0; i < n; i++) {+ await createMonitor({+ ctx,+ input: {+ name: `${TEST_PREFIX}-total-${i}`,+ jobType: "http",+ url: "https://example.com",+ method: "GET",+ headers: [],+ assertions: [],+ active: true,+ },+ });+ }+ const rows = await tx+ .select({ id: monitor.id })+ .from(monitor)+ .where(+ and(+ eq(monitor.workspaceId, ctx.workspace.id),+ isNull(monitor.deletedAt),+ ),+ )+ .all();+ return rows.length;+ };++ test("a short page derives the total from offset + rows", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listMonitors({+ ctx,+ input: { limit: total + 10, offset: 0, order: "desc" },+ });+ expect(items).toHaveLength(total);+ expect(totalSize).toBe(total);+ });+ });++ test("a full page falls back to count(*)", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listMonitors({+ ctx,+ input: { limit: 1, offset: 0, order: "desc" },+ });+ expect(items).toHaveLength(1);+ // Derivation alone would say 1; only the count knows the real total.+ expect(totalSize).toBe(total);+ });+ });++ test("a mid-list page reports the full total, not the page end", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { totalSize } = await listMonitors({+ ctx,+ input: { limit: 2, offset: 1, order: "desc" },+ });+ expect(totalSize).toBe(total);+ });+ });++ test("an offset past the end still reports the true total", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listMonitors({+ ctx,+ input: { limit: 10, offset: total + 50, order: "desc" },+ });+ expect(items).toHaveLength(0);+ // Regression: deriving `offset + rows.length` here would report the+ // offset itself as the total.+ expect(totalSize).toBe(total);+ });+ });++ test("an empty result at offset 0 reports zero", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...freeCtx, db: tx };+ const total = await seed(tx, ctx, 0);++ const { items, totalSize } = await listMonitors({+ ctx,+ input: { limit: 100, offset: 0, order: "desc" },+ });+ expect(items).toHaveLength(total);+ expect(totalSize).toBe(total);+ });+ });+});+describe("updateMonitorGeneral", () => {test("updates name / url / assertions and audits", async () => {await withTestTransaction(async (tx) => {diff --git a/packages/services/src/monitor/list.ts b/packages/services/src/monitor/list.tsindex 6b1affecd..77d14e5e4 100644--- a/packages/services/src/monitor/list.ts+++ b/packages/services/src/monitor/list.ts@@ -200,28 +200,32 @@ export async function listMonitors(args: {];const whereClause = and(...conditions);- const [countRow, rows] = await Promise.all([- db+ const rows = await db+ .select()+ .from(monitor)+ .where(whereClause)+ .orderBy(+ input.order === "asc" ? asc(monitor.active) : desc(monitor.active),+ input.order === "asc" ? asc(monitor.createdAt) : desc(monitor.createdAt),+ )+ .limit(input.limit)+ .offset(input.offset)+ .all();++ // A short page is the last page, so the total is already known and the+ // extra `count(*)` is only paid when a full page comes back — or when an+ // empty page leaves it ambiguous whether we ran off the end. The tRPC+ // `list` procedure discards `totalSize` entirely.+ let totalSize = input.offset + rows.length;+ if (rows.length === input.limit || (rows.length === 0 && input.offset > 0)) {+ const countRow = await db.select({ count: sql<number>`count(*)` }).from(monitor).where(whereClause)- .get(),- db- .select()- .from(monitor)- .where(whereClause)- .orderBy(- input.order === "asc" ? asc(monitor.active) : desc(monitor.active),- input.order === "asc"- ? asc(monitor.createdAt)- : desc(monitor.createdAt),- )- .limit(input.limit)- .offset(input.offset)- .all(),- ]);+ .get();+ totalSize = countRow?.count ?? totalSize;+ }- const totalSize = countRow?.count ?? 0;const enriched = await enrichMonitorsBatch(db, rows, ctx.workspace.id);// `list` only exposes tags + incidents to match the tRPC `list` shape.const items: MonitorListItem[] = enriched.map(diff --git a/packages/services/src/page/__tests__/page.test.ts b/packages/services/src/page/__tests__/page.test.tsindex fd1a5b7c8..84e6ed4e5 100644--- a/packages/services/src/page/__tests__/page.test.ts+++ b/packages/services/src/page/__tests__/page.test.ts@@ -4,6 +4,7 @@ import {page as pageTable,pageComponent,selectWorkspaceSchema,+ statusReport,workspace,} from "@openstatus/db/src/schema";import { getLimits } from "@openstatus/db/src/schema/plan/utils";@@ -17,7 +18,7 @@ import {makeUserCtx,withTestTransaction,} from "../../../test/helpers";-import type { ServiceContext } from "../../context";+import type { DrizzleTx, ServiceContext } from "../../context";import {ConflictError,ForbiddenError,@@ -466,6 +467,100 @@ describe("list / get / getSlugAvailable", () => {});});+describe("listPages hasActiveStatusReport", () => {+ const addReport = async (+ tx: DrizzleTx,+ pageId: number,+ workspaceId: number,+ status: "investigating" | "resolved",+ ) =>+ tx.insert(statusReport).values({+ workspaceId,+ pageId,+ status,+ title: `${TEST_PREFIX}-report-${status}`,+ });++ const flagFor = async (ctx: ServiceContext, pageId: number) => {+ const items = await listPages({ ctx, input: { order: "desc" } });+ return items.find((p) => p.id === pageId)?.hasActiveStatusReport;+ };++ test("false when the page has no status reports", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const p = await newPage({+ ctx,+ input: { title: "No reports", slug: uniqueSlug("flag-none") },+ });+ expect(await flagFor(ctx, p.id)).toBe(false);+ });+ });++ test("true when the page has a non-resolved report", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const p = await newPage({+ ctx,+ input: { title: "Active", slug: uniqueSlug("flag-active") },+ });+ await addReport(tx, p.id, teamCtx.workspace.id, "investigating");+ expect(await flagFor(ctx, p.id)).toBe(true);+ });+ });++ test("false once every report on the page is resolved", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const p = await newPage({+ ctx,+ input: { title: "Resolved", slug: uniqueSlug("flag-resolved") },+ });+ await addReport(tx, p.id, teamCtx.workspace.id, "resolved");+ await addReport(tx, p.id, teamCtx.workspace.id, "resolved");+ expect(await flagFor(ctx, p.id)).toBe(false);+ });+ });++ test("an active report on one page does not flag its siblings", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const noisy = await newPage({+ ctx,+ input: { title: "Noisy", slug: uniqueSlug("flag-noisy") },+ });+ const quiet = await newPage({+ ctx,+ input: { title: "Quiet", slug: uniqueSlug("flag-quiet") },+ });+ await addReport(tx, noisy.id, teamCtx.workspace.id, "investigating");++ expect(await flagFor(ctx, noisy.id)).toBe(true);+ expect(await flagFor(ctx, quiet.id)).toBe(false);+ });+ });++ test("the probe is workspace-scoped", async () => {+ await withTestTransaction(async (tx) => {+ const teamCtxTx = { ...teamCtx, db: tx };+ const freeCtxTx = { ...freeCtx, db: tx };+ const foreign = await newPage({+ ctx: freeCtxTx,+ input: { title: "Foreign", slug: uniqueSlug("flag-foreign") },+ });+ // Active report owned by the *other* workspace, pointing at its page.+ await addReport(tx, foreign.id, freeCtx.workspace.id, "investigating");++ const teamItems = await listPages({+ ctx: teamCtxTx,+ input: { order: "desc" },+ });+ expect(teamItems.some((p) => p.hasActiveStatusReport)).toBe(false);+ expect(await flagFor(freeCtxTx, foreign.id)).toBe(true);+ });+ });+});+describe("getPageBySlug", () => {test("returns the row when slug exists", async () => {await withTestTransaction(async (tx) => {diff --git a/packages/services/src/page/list.ts b/packages/services/src/page/list.tsindex d7edce8ca..8defa684a 100644--- a/packages/services/src/page/list.ts+++ b/packages/services/src/page/list.ts@@ -1,12 +1,4 @@-import {- and,- asc,- db as defaultDb,- desc,- eq,- inArray,- sql,-} from "@openstatus/db";+import { and, asc, db as defaultDb, desc, eq, ne, sql } from "@openstatus/db";import {maintenance,page,@@ -16,21 +8,26 @@ import {selectPageComponentGroupSchema,selectPageComponentSchema,selectPageSchema,- selectStatusReportSchema,statusReport,} from "@openstatus/db/src/schema";import { subdomainSafeList } from "@openstatus/db/src/schema/pages/constants";-import { type DB, type ServiceContext, getReadDb } from "../context";+import {+ type DB,+ type ServiceContext,+ batchReads,+ getReadDb,+} from "../context";import { NotFoundError } from "../errors";-import type { Maintenance, Page, PageComponent, StatusReport } from "../types";+import type { Maintenance, Page, PageComponent } from "../types";import { getPageInWorkspace } from "./internal";import { GetPageInput, GetSlugAvailableInput, ListPagesInput } from "./schemas";type PageComponentGroupRow = typeof pageComponentGroup.$inferSelect;export type PageListItem = Page & {- statusReports: StatusReport[];+ /** Any non-resolved status report on this page — drives the sidebar dot. */+ hasActiveStatusReport: boolean;};export type PageWithRelations = Page & {@@ -48,40 +45,37 @@ export async function listPages(args: {const db = getReadDb(ctx);const dir = input.order === "asc" ? asc : desc;- const pageRows = await db- .select()- .from(page)- .where(eq(page.workspaceId, ctx.workspace.id))- // id tiebreaker: createdAt ties would make offset pagination unstable- .orderBy(dir(page.createdAt), dir(page.id))- .all();- if (pageRows.length === 0) return [];- const pageIds = pageRows.map((p) => p.id);-- const reportRows = await db- .select()- .from(statusReport)- .where(- and(- eq(statusReport.workspaceId, ctx.workspace.id),- inArray(statusReport.pageId, pageIds),+ // The probe is workspace-scoped, so it doesn't depend on the page ids and+ // both statements go out together. Distinct page ids of unresolved reports+ // rather than the reports themselves — the list view only needs the flag,+ // and the full history is unbounded.+ const [pageRows, unresolvedRows] = await batchReads(db, [+ db+ .select()+ .from(page)+ .where(eq(page.workspaceId, ctx.workspace.id))+ // id tiebreaker: createdAt ties would make offset pagination unstable+ .orderBy(dir(page.createdAt), dir(page.id)),+ db+ .selectDistinct({ pageId: statusReport.pageId })+ .from(statusReport)+ .where(+ and(+ eq(statusReport.workspaceId, ctx.workspace.id),+ ne(statusReport.status, "resolved"),+ ),),- )- .all();+ ]);- const reportsByPage = new Map<number, StatusReport[]>();- for (const r of reportRows) {- if (r.pageId == null) continue;- const arr = reportsByPage.get(r.pageId);- const parsed = selectStatusReportSchema.parse(r);- if (arr) arr.push(parsed);- else reportsByPage.set(r.pageId, [parsed]);+ const pagesWithActiveReport = new Set<number>();+ for (const r of unresolvedRows) {+ if (r.pageId != null) pagesWithActiveReport.add(r.pageId);}return pageRows.map((p) => ({...selectPageSchema.parse(p),- statusReports: reportsByPage.get(p.id) ?? [],+ hasActiveStatusReport: pagesWithActiveReport.has(p.id),}));}diff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.tsindex 571cf47fc..8d08e1fc1 100644--- a/packages/services/src/status-report/__tests__/status-report.test.ts+++ b/packages/services/src/status-report/__tests__/status-report.test.ts@@ -622,6 +622,73 @@ describe("notifyStatusReport", () => {});});+// Same derivation as `listMonitors` — a second copy of the logic, so it gets+// its own regression coverage rather than relying on the monitor suite.+describe("listStatusReports totalSize", () => {+ const seed = async (tx: DB, ctx: ServiceContext, n: number) => {+ for (let i = 0; i < n; i++) {+ await createStatusReport({+ ctx,+ input: {+ title: `${TEST_PREFIX}-total-${i}`,+ status: "investigating",+ message: "m",+ date: new Date(),+ pageId: testPageId,+ pageComponentIds: [],+ },+ });+ }+ const rows = await tx+ .select({ id: statusReport.id })+ .from(statusReport)+ .where(eq(statusReport.workspaceId, ctx.workspace.id))+ .all();+ return rows.length;+ };++ const listPage = (ctx: ServiceContext, limit: number, offset: number) =>+ listStatusReports({+ ctx,+ input: { limit, offset, statuses: [], order: "desc" },+ });++ test("a short page derives the total from offset + rows", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listPage(ctx, total + 10, 0);+ expect(items).toHaveLength(total);+ expect(totalSize).toBe(total);+ });+ });++ test("a full page falls back to count(*)", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listPage(ctx, 1, 0);+ expect(items).toHaveLength(1);+ expect(totalSize).toBe(total);+ });+ });++ test("an offset past the end still reports the true total", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const total = await seed(tx, ctx, 3);++ const { items, totalSize } = await listPage(ctx, 10, total + 50);+ expect(items).toHaveLength(0);+ // Regression: deriving `offset + rows.length` here would report the+ // offset itself as the total.+ expect(totalSize).toBe(total);+ });+ });+});+describe("slack actor path", () => {test("createStatusReport succeeds with a slack actor", async () => {await withTestTransaction(async (tx) => {diff --git a/packages/services/src/status-report/list.ts b/packages/services/src/status-report/list.tsindex 865b02a80..15f59f9ec 100644--- a/packages/services/src/status-report/list.ts+++ b/packages/services/src/status-report/list.ts@@ -21,7 +21,7 @@ import {statusReportsToPageComponents,} from "@openstatus/db/src/schema";-import type { DB, ServiceContext } from "../context";+import { type DB, type ServiceContext, batchReads } from "../context";import type {Page,PageComponent,@@ -71,9 +71,8 @@ export type ListStatusReportsResult = {};/**- * Load relations for a set of status reports in three batched queries- * (updates, component associations, pages + page components) regardless of- * how many reports were passed in. Avoids the O(N) per-row pattern that+ * Load relations for a set of status reports in two round-trips regardless+ * of how many reports were passed in. Avoids the O(N) per-row pattern that* pairs badly with the dashboard's effectively-unlimited list request.*/async function enrichReportsBatch(@@ -86,14 +85,39 @@ async function enrichReportsBatch(const pageIdsSet = new Set<number>();for (const r of rows) if (r.pageId != null) pageIdsSet.add(r.pageId);const pageIds = Array.from(pageIdsSet);+ // Keeps the batch a fixed four statements when no report carries a pageId;+ // `inArray` with an empty list is not a valid predicate.+ const anyPage = pageIds.length > 0 ? inArray(pageTable.id, pageIds) : sql`0`;+ const anyPageComponent =+ pageIds.length > 0 ? inArray(pageComponent.pageId, pageIds) : sql`0`;- // One query: all updates for all reports, newest-first.- const allUpdates = await db- .select()- .from(statusReportUpdate)- .where(inArray(statusReportUpdate.statusReportId, reportIds))- .orderBy(desc(statusReportUpdate.date))- .all();+ // Everything that keys off the reports themselves — updates, component+ // associations, owning pages and their component rosters — in one+ // round-trip. Only the impact rows below depend on a prior result.+ const [allUpdates, assocRows, pageRows, pageSiblings] = await batchReads(db, [+ db+ .select()+ .from(statusReportUpdate)+ .where(inArray(statusReportUpdate.statusReportId, reportIds))+ .orderBy(desc(statusReportUpdate.date)),+ // Explicit column selection with aliases avoids depending on drizzle's+ // auto-derived `row.<object_name>` keys — those are named after the+ // exported JS variable, so a rename in the schema silently breaks the+ // row shape at runtime.+ db+ .select({+ reportId: statusReportsToPageComponents.statusReportId,+ component: pageComponent,+ })+ .from(pageComponent)+ .innerJoin(+ statusReportsToPageComponents,+ eq(statusReportsToPageComponents.pageComponentId, pageComponent.id),+ )+ .where(inArray(statusReportsToPageComponents.statusReportId, reportIds)),+ db.select().from(pageTable).where(anyPage),+ db.select().from(pageComponent).where(anyPageComponent),+ ]);// One query: all impact rows for all updates.const updateIds = allUpdates.map((u) => u.id);@@ -140,23 +164,6 @@ async function enrichReportsBatch(else updatesByReport.set(u.statusReportId, [withImpacts]);}- // One query: all component associations joined to their components.- // Explicit column selection with aliases avoids depending on drizzle's- // auto-derived `row.<object_name>` keys — those are named after the- // exported JS variable, so a rename in the schema silently breaks the- // row shape at runtime.- const assocRows = await db- .select({- reportId: statusReportsToPageComponents.statusReportId,- component: pageComponent,- })- .from(pageComponent)- .innerJoin(- statusReportsToPageComponents,- eq(statusReportsToPageComponents.pageComponentId, pageComponent.id),- )- .where(inArray(statusReportsToPageComponents.statusReportId, reportIds))- .all();const componentsByReport = new Map<number, PageComponent[]>();for (const row of assocRows) {const component = selectPageComponentSchema.parse(row.component);@@ -165,34 +172,23 @@ async function enrichReportsBatch(else componentsByReport.set(row.reportId, [component]);}- // Two queries: distinct pages + their component rosters. Keyed by pageId so- // multiple reports sharing a page share the same Page object.+ // Keyed by pageId so multiple reports sharing a page share the same Page.const pageById = new Map<number,Page & { pageComponents: PageComponent[] }>();- if (pageIds.length > 0) {- const [pageRows, pageSiblings] = await Promise.all([- db.select().from(pageTable).where(inArray(pageTable.id, pageIds)).all(),- db- .select()- .from(pageComponent)- .where(inArray(pageComponent.pageId, pageIds))- .all(),- ]);- const siblingsByPageId = new Map<number, PageComponent[]>();- for (const c of pageSiblings) {- const parsed = selectPageComponentSchema.parse(c);- const arr = siblingsByPageId.get(parsed.pageId);- if (arr) arr.push(parsed);- else siblingsByPageId.set(parsed.pageId, [parsed]);- }- for (const p of pageRows) {- pageById.set(p.id, {- ...selectPageSchema.parse(p),- pageComponents: siblingsByPageId.get(p.id) ?? [],- });- }+ const siblingsByPageId = new Map<number, PageComponent[]>();+ for (const c of pageSiblings) {+ const parsed = selectPageComponentSchema.parse(c);+ const arr = siblingsByPageId.get(parsed.pageId);+ if (arr) arr.push(parsed);+ else siblingsByPageId.set(parsed.pageId, [parsed]);+ }+ for (const p of pageRows) {+ pageById.set(p.id, {+ ...selectPageSchema.parse(p),+ pageComponents: siblingsByPageId.get(p.id) ?? [],+ });}return rows.map((r) => {@@ -227,27 +223,33 @@ export async function listStatusReports(args: {}const whereClause = and(...conditions);- const [countRow, rows] = await Promise.all([- db+ const rows = await db+ .select()+ .from(statusReport)+ .where(whereClause)+ .orderBy(+ input.order === "asc"+ ? asc(statusReport.createdAt)+ : desc(statusReport.createdAt),+ )+ .limit(input.limit)+ .offset(input.offset)+ .all();++ // A short page is the last page, so the total is already known and the+ // extra `count(*)` is only paid when a full page comes back — or when an+ // empty page leaves it ambiguous whether we ran off the end. Both tRPC+ // consumers discard `totalSize` entirely.+ let totalSize = input.offset + rows.length;+ if (rows.length === input.limit || (rows.length === 0 && input.offset > 0)) {+ const countRow = await db.select({ count: sql<number>`count(*)` }).from(statusReport).where(whereClause)- .get(),- db- .select()- .from(statusReport)- .where(whereClause)- .orderBy(- input.order === "asc"- ? asc(statusReport.createdAt)- : desc(statusReport.createdAt),- )- .limit(input.limit)- .offset(input.offset)- .all(),- ]);+ .get();+ totalSize = countRow?.count ?? totalSize;+ }- const totalSize = countRow?.count ?? 0;const items = await enrichReportsBatch(db, rows);return { items, totalSize };}diff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.tsindex cebd7c9d3..d000fedd3 100644--- a/packages/services/src/workspace/__tests__/workspace.test.ts+++ b/packages/services/src/workspace/__tests__/workspace.test.ts@@ -1,5 +1,9 @@import { eq } from "@openstatus/db";import {+ monitor,+ notification,+ page,+ pageComponent,selectWorkspaceSchema,statusReport,workspace,@@ -93,6 +97,117 @@ describe("getWorkspaceWithUsage", () => {expect(result.usage.statusReports).toBeGreaterThanOrEqual(1);});});++ // The usage block is six independent counts rather than a relational read;+ // each one must move by exactly the number of rows inserted.+ test("each count moves by exactly the rows added", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const workspaceId = teamCtx.workspace.id;+ const before = (await getWorkspaceWithUsage({ ctx })).usage;++ await tx.insert(monitor).values([+ { workspaceId, url: "https://a.example.dev", name: "svc-ws-usage-1" },+ { workspaceId, url: "https://b.example.dev", name: "svc-ws-usage-2" },+ ]);+ await tx.insert(notification).values({+ workspaceId,+ name: "svc-ws-usage-notif",+ provider: "email",+ data: JSON.stringify({ email: "[email protected]" }),+ });+ const [pageRow] = await tx+ .insert(page)+ .values({+ workspaceId,+ title: "svc-ws-usage-page",+ description: "",+ slug: `svc-ws-usage-${workspaceId}`,+ customDomain: "",+ })+ .returning();+ if (!pageRow) throw new Error("page insert returned no row");+ await tx.insert(pageComponent).values([+ {+ workspaceId,+ pageId: pageRow.id,+ type: "static",+ name: "svc-ws-usage-c1",+ order: 0,+ },+ {+ workspaceId,+ pageId: pageRow.id,+ type: "static",+ name: "svc-ws-usage-c2",+ order: 1,+ },+ ]);+ await tx.insert(statusReport).values({+ workspaceId,+ status: "investigating",+ title: "svc-ws-usage-report",+ });++ const after = (await getWorkspaceWithUsage({ ctx })).usage;+ expect(after.monitors).toBe(before.monitors + 2);+ expect(after.notifications).toBe(before.notifications + 1);+ expect(after.pages).toBe(before.pages + 1);+ expect(after.pageComponents).toBe(before.pageComponents + 2);+ expect(after.statusReports).toBe(before.statusReports + 1);+ expect(after.checks).toBe(0);+ });+ });++ test("excludes soft-deleted monitors from the monitor count", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const workspaceId = teamCtx.workspace.id;+ const before = (await getWorkspaceWithUsage({ ctx })).usage.monitors;++ await tx.insert(monitor).values({+ workspaceId,+ url: "https://deleted.example.dev",+ name: "svc-ws-usage-deleted",+ deletedAt: new Date(),+ });++ const after = (await getWorkspaceWithUsage({ ctx })).usage.monitors;+ expect(after).toBe(before);+ });+ });++ 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 [foreign] = await tx+ .insert(workspace)+ .values({+ slug: `svc-ws-usage-foreign-${teamCtx.workspace.id}`,+ name: "Foreign",+ stripeId: `svc-ws-usage-stripe-${teamCtx.workspace.id}`,+ plan: "team",+ })+ .returning();+ if (!foreign) throw new Error("workspace insert returned no row");+ await tx.insert(monitor).values({+ workspaceId: foreign.id,+ url: "https://foreign.example.dev",+ name: "svc-ws-usage-foreign-monitor",+ });+ await tx.insert(statusReport).values({+ workspaceId: foreign.id,+ status: "investigating",+ title: "svc-ws-usage-foreign-report",+ });++ const after = (await getWorkspaceWithUsage({ ctx })).usage;+ expect(after.monitors).toBe(before.monitors);+ expect(after.statusReports).toBe(before.statusReports);+ });+ });});describe("listWorkspaces", () => {diff --git a/packages/services/src/workspace/list.ts b/packages/services/src/workspace/list.tsindex 6606a7208..094d8744a 100644--- a/packages/services/src/workspace/list.ts+++ b/packages/services/src/workspace/list.ts@@ -1,12 +1,16 @@-import { db as defaultDb, eq, isNull } from "@openstatus/db";+import { and, db as defaultDb, eq, isNull, sql } from "@openstatus/db";import {monitor,+ notification,+ page,+ pageComponent,selectWorkspaceSchema,+ statusReport,usersToWorkspaces,workspace,} from "@openstatus/db/src/schema";-import type { DB, ServiceContext } from "../context";+import { type DB, type ServiceContext, batchReads } from "../context";import { NotFoundError } from "../errors";import type { Workspace } from "../types";import {@@ -62,34 +66,59 @@ export async function getWorkspaceWithUsage(args: {}): Promise<WorkspaceWithUsage> {const { ctx } = args;const db = ctx.db ?? defaultDb;-- const result = await db.query.workspace.findFirst({- where: eq(workspace.id, ctx.workspace.id),- with: {- pages: {- with: { pageComponents: true },- },- monitors: {- where: isNull(monitor.deletedAt),- },- notifications: true,- statusReports: { columns: { id: true } },- },- });+ const workspaceId = ctx.workspace.id;+ 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)),+ db+ .select({ count: total })+ .from(monitor)+ .where(+ and(eq(monitor.workspaceId, workspaceId), isNull(monitor.deletedAt)),+ ),+ db+ .select({ count: total })+ .from(notification)+ .where(eq(notification.workspaceId, workspaceId)),+ db+ .select({ count: total })+ .from(page)+ .where(eq(page.workspaceId, workspaceId)),+ db+ .select({ count: total })+ .from(pageComponent)+ .where(eq(pageComponent.workspaceId, workspaceId)),+ db+ .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", ctx.workspace.id);+ if (!result) throw new NotFoundError("workspace", workspaceId);const usage: WorkspaceUsage = {- monitors: result.monitors?.length ?? 0,- notifications: result.notifications?.length ?? 0,- pages: result.pages?.length ?? 0,- pageComponents:- result.pages?.flatMap((page) => page.pageComponents)?.length ?? 0,- statusReports: result.statusReports?.length ?? 0,+ 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,// Parity with the legacy router — checks usage was previously commented// out pending a real source and left as 0. Preserved here.checks: 0,