Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/openstatusHQ/openstatus. ๐ซ Status page with uptime monitoring & API monitoring as code ๐ซ openstatus.dev
bun drizzle-orm monitoring monitoring-as-code nextjs observability on-call open-source shadcn-ui status-page statuspage synthetic-monitoring tinybird turso uptime uptime-checker uptime-monitor
Something went wrong. Try again.
53 kB ยท 1620 lines
TypeScript
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621import { Events } from "@openstatus/analytics";import { and, eq, inArray, isNull, sql } from "@openstatus/db";import { maintenance, page, pageComponent, pageConfigurationSchema, privateLocationToMonitors, selectMaintenancePageSchema, selectPageComponentWithMonitorRelation, selectPageSchema, selectPublicMonitorSchema, selectPublicPageLightSchemaWithRelation, selectPublicPageSchemaWithRelation, selectStatusReportPageSchema, selectWorkspaceSchema, statusReport,} from "@openstatus/db/src/schema";import { constantTimeEqual } from "@openstatus/services/page-access";import { getSubscriberByToken, hasPendingSubscriber, unsubscribeSubscriber, updateSubscriberScope, upsertSelfSignupSubscriber, verifySelfSignupSubscriber,} from "@openstatus/services/page-subscriber";import { TRPCError } from "@trpc/server";import { endOfDay, startOfDay, subDays } from "date-fns";import { z } from "zod";
import { assertPageAccess, resolvePageAccess, visitorFromCtx,} from "../lib/page-access";import { createTRPCRouter, publicProcedure } from "../trpc";import { type StatusData, activeReportStatus, fillStatusDataFor45Days, fillStatusDataFor45DaysNoop, getEvents, getUptime, getWorstVariant, isMonitorComponent, setDataByType, withTinybirdFallback,} from "./statusPage.utils";import { getMetricsLatencyMultiProcedure, getMetricsLatencyProcedure, getMetricsRegionsProcedure, getStatusProcedure, getUptimeProcedure,} from "./tinybird";
// NOTE: publicProcedure is used to get the status page// TODO: improve performance of SQL query (make a single query with joins)
// IMPORTANT: we cannot use the tinybird procedure because it has protectedProcedure// instead, we should add TB logic in here!!!!
// NOTE: this router is used on status pages only - do not confuse with the page router which is used in the dashboard for the config
// Gate fields for getGate, reusing selectPageSchema's stringToArray transforms// so authEmailDomains / allowedIpRanges come back as arrays like getLight.const gateFieldsSchema = selectPageSchema.pick({ slug: true, customDomain: true, accessType: true, authEmailDomains: true, allowedIpRanges: true, homepageUrl: true, contactUrl: true,});
// Password for cookie-less server callers (feeds, `?pw=` links).const queryPasswordSchema = z.string().nullish();
export const statusPageRouter = createTRPCRouter({ get: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), pw: queryPasswordSchema, // NOTE: override the defaults we are getting from the page configuration cardType: z .enum(["requests", "duration", "dominant", "manual"]) .nullish(), barType: z.enum(["absolute", "dominant", "manual"]).nullish(), }), ) .output(selectPublicPageSchemaWithRelation.nullish()) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, with: { workspace: true, statusReports: { // TODO: we need to order the based on statusReportUpdates instead // orderBy: (reports, { desc }) => desc(reports.createdAt), with: { statusReportUpdates: { orderBy: (reports, { desc }) => desc(reports.date), with: { statusReportUpdateToPageComponents: true }, }, statusReportsToPageComponents: { with: { pageComponent: true } }, }, }, maintenances: { with: { maintenancesToPageComponents: { with: { pageComponent: true } }, }, orderBy: (maintenances, { desc }) => desc(maintenances.from), }, pageComponents: { with: { monitor: { with: { incidents: true, }, }, group: true, }, orderBy: (pageComponents, { asc }) => asc(pageComponents.order), }, pageComponentGroups: true, }, });
if (!_page) return null;
// Denied visitors still need the page chrome (login, layout, OG). if (!resolvePageAccess(opts.ctx, _page, opts.input.pw).ok) { _page.statusReports = []; _page.maintenances = []; _page.pageComponents = []; _page.pageComponentGroups = []; }
const ws = selectWorkspaceSchema.safeParse(_page.workspace); const pageComponents = selectPageComponentWithMonitorRelation .array() .parse(_page.pageComponents);
const configuration = pageConfigurationSchema.safeParse( _page.configuration ?? {}, );
if (!configuration.success) { console.error("Invalid configuration", configuration.error); return null; }
const barType = opts.input.barType ?? configuration.data.type; // const cardType = opts.input.cardType ?? configuration.data.value;
const monitorComponents = pageComponents.filter(isMonitorComponent);
// Transform all page components (both monitor and static types) const components = pageComponents.map((c) => { const events = getEvents({ maintenances: _page.maintenances, incidents: c.monitor?.incidents ?? [], reports: _page.statusReports, pageComponentId: c.id, monitorId: c.monitorId ?? undefined, componentType: c.type, });
// Calculate status based on component type let status: "success" | "degraded" | "error" | "info";
// impact-aware: an active report colors the component by its derived // status (major โ error); legacy reports keep flat degraded const reportStatus = activeReportStatus(events);
if (c.type === "static") { // Static: only reports and maintenances affect status status = reportStatus ?? (events.some( (e) => e.type === "maintenance" && e.to && e.from.getTime() <= new Date().getTime() && e.to.getTime() >= new Date().getTime(), ) ? "info" : "success"); } else { // Monitor: incidents, reports, and maintenances affect status status = events.some((e) => e.type === "incident" && !e.to) && barType !== "manual" ? "error" : (reportStatus ?? (events.some( (e) => e.type === "maintenance" && e.to && e.from.getTime() <= new Date().getTime() && e.to.getTime() >= new Date().getTime(), ) ? "info" : "success")); }
return { ...c, status, events, }; });
// Keep monitors for backward compatibility with existing fields const monitors = monitorComponents.map((c) => { const events = getEvents({ maintenances: _page.maintenances, incidents: c.monitor.incidents ?? [], reports: _page.statusReports, monitorId: c.monitor.id, }); const status = events.some((e) => e.type === "incident" && !e.to) && barType !== "manual" ? "error" : (activeReportStatus(events) ?? (events.some( (e) => e.type === "maintenance" && e.to && e.from.getTime() <= new Date().getTime() && e.to.getTime() >= new Date().getTime(), ) ? "info" : "success")); return { ...c.monitor, status, events, monitorGroupId: c.groupId, order: c.order, groupOrder: c.groupOrder, }; });
// Add privateLocationCount to each monitor const privateLocationCounts = new Map<number, number>(); if (monitors.length > 0) { const monitorIds = monitors.map((m) => m.id); const privateLocations = await opts.ctx.db.query.privateLocationToMonitors.findMany({ where: and( inArray(privateLocationToMonitors.monitorId, monitorIds), isNull(privateLocationToMonitors.deletedAt), ), columns: { monitorId: true, }, });
// Count private locations per monitor for (const pl of privateLocations) { if (pl.monitorId === null) continue; privateLocationCounts.set( pl.monitorId, (privateLocationCounts.get(pl.monitorId) ?? 0) + 1, ); } }
// Create new array with privateLocationCount included (no mutation/cast) const monitorsWithPrivateLocationCount = monitors.map((m) => ({ ...m, privateLocationCount: privateLocationCounts.get(m.id) ?? 0, }));
// Sort monitors to match trackers behavior: group by monitorGroupId, order // groups by minimum order, sort within groups by groupOrder, and sort // ungrouped monitors by order const groupMinOrderMap = new Map<number, number>(); for (const monitor of monitorsWithPrivateLocationCount) { const groupId = monitor.monitorGroupId; if (groupId !== null) { const order = monitor.order ?? 0; const currentMin = groupMinOrderMap.get(groupId) ?? Number.MAX_SAFE_INTEGER; groupMinOrderMap.set(groupId, Math.min(currentMin, order)); } }
monitorsWithPrivateLocationCount.sort((a, b) => { const aGroupId = a.monitorGroupId ?? null; const bGroupId = b.monitorGroupId ?? null;
// If both monitors are in the same group (or both ungrouped with null) if (aGroupId === bGroupId) { if (aGroupId === null) { // Both ungrouped - sort by order return (a.order ?? 0) - (b.order ?? 0); } // Both in same group - sort by groupOrder within the group return (a.groupOrder ?? 0) - (b.groupOrder ?? 0); }
// Different groups or one is ungrouped - sort by group position // For grouped monitors, use precomputed minimum order of the group // For ungrouped monitors, use their own order const aGroupMinOrder = aGroupId !== null ? (groupMinOrderMap.get(aGroupId) ?? 0) : (a.order ?? 0); const bGroupMinOrder = bGroupId !== null ? (groupMinOrderMap.get(bGroupId) ?? 0) : (b.order ?? 0);
return aGroupMinOrder - bGroupMinOrder; });
// no barType gate: incident-driven error is already suppressed per // monitor in manual mode; report-driven error (major_outage) must show const status = monitorsWithPrivateLocationCount.some( (m) => m.status === "error", ) ? "error" : monitorsWithPrivateLocationCount.some((m) => m.status === "degraded") ? "degraded" : monitorsWithPrivateLocationCount.some((m) => m.status === "info") ? "info" : "success";
// Get page-wide events (not tied to specific monitors) const pageEvents = getEvents({ maintenances: _page.maintenances, incidents: monitorComponents.flatMap((c) => c.monitor.incidents ?? []), reports: _page.statusReports, // No monitorId provided, so we get all events for the page });
const threshold = new Date().getTime() - 7 * 24 * 60 * 60 * 1000; const lastEvents = pageEvents .filter((e) => { if (e.type === "incident") return false; if (!e.from || e.from.getTime() >= threshold) return true; if (e.type === "report" && e.status !== "success") return true; return false; }) .sort((a, b) => a.from.getTime() - b.from.getTime());
const openEvents = pageEvents.filter((event) => { if (event.type === "incident" && barType !== "manual") { if (!event.to) return true; if (event.to < new Date()) return false; return false; } if (event.type === "report") { if (!event.to) return true; if (event.to < new Date()) return false; return false; } if (event.type === "maintenance") { if (!event.to) return false; // NOTE: this never happens if (event.from <= new Date() && event.to >= new Date()) return true; return false; } return false; });
const monitorGroups = _page.pageComponentGroups;
// Create trackers array with grouped and ungrouped components const groupedMap = new Map< number | null, { groupId: number | null; groupName: string | null; defaultOpen: boolean; components: typeof components; minOrder: number; } >();
components.forEach((component) => { const groupId = component.groupId ?? null; const group = groupId ? monitorGroups.find((g) => g?.id === groupId) : null; const groupName = group?.name ?? null; const defaultOpen = group?.defaultOpen ?? false;
if (!groupedMap.has(groupId)) { groupedMap.set(groupId, { groupId, groupName, defaultOpen, components: [], minOrder: component.order ?? 0, }); } const currentGroup = groupedMap.get(groupId); if (currentGroup) { currentGroup.components.push(component); currentGroup.minOrder = Math.min( currentGroup.minOrder, component.order ?? 0, ); } });
// Convert to trackers array type PageComponentTracker = { type: "component"; component: (typeof components)[number]; order: number; };
type GroupTracker = { type: "group"; groupId: number; groupName: string; defaultOpen: boolean; components: typeof components; status: "success" | "degraded" | "error" | "info" | "empty"; order: number; };
type Tracker = PageComponentTracker | GroupTracker;
const trackers: Tracker[] = Array.from(groupedMap.values()) .flatMap((group): Tracker[] => { if (group.groupId === null) { // Ungrouped components - return as individual trackers return group.components.map( (component): PageComponentTracker => ({ type: "component", component, order: component.order ?? 0, }), ); } // Grouped components - return as single group tracker const sortedComponents = group.components.sort( (a, b) => (a.groupOrder ?? 0) - (b.groupOrder ?? 0), ); return [ { type: "group", groupId: group.groupId, groupName: group.groupName ?? "", defaultOpen: group.defaultOpen, components: sortedComponents, status: getWorstVariant( group.components.map( (c) => c.status as "success" | "degraded" | "error" | "info", ), ), order: group.minOrder, }, ]; }) .sort((a, b) => a.order - b.order);
const whiteLabel = ws.data?.limits["white-label"] ?? false; // stored custom theme stops applying when the plan no longer includes it const customTheme = ws.data?.limits["custom-theme"] ? _page.customTheme : null;
const statusReports = _page.statusReports.sort((a, b) => { // Sort reports without updates to the beginning if ( a.statusReportUpdates.length === 0 && b.statusReportUpdates.length === 0 ) return 0; if (a.statusReportUpdates.length === 0) return -1; if (b.statusReportUpdates.length === 0) return -1; return ( b.statusReportUpdates[ b.statusReportUpdates.length - 1 ].date.getTime() - a.statusReportUpdates[a.statusReportUpdates.length - 1].date.getTime() ); });
const maintenances = _page.maintenances.sort( (a, b) => b.from.getTime() - a.from.getTime(), );
// In "manual" mode the page only surfaces user-authored events, so drop // monitor-derived incidents from the components consumers read (e.g. the // calendar). Mirrors the bar/uptime gating in statusPage.utils.ts. const publicPageComponents = barType === "manual" ? pageComponents.map((c) => c.monitor ? { ...c, monitor: { ...c.monitor, incidents: [] } } : c, ) : pageComponents;
return selectPublicPageSchemaWithRelation.parse({ ..._page, customTheme, monitors: monitorsWithPrivateLocationCount, monitorGroups, trackers, incidents: monitorsWithPrivateLocationCount.flatMap((m) => m.incidents) ?? [], statusReports, maintenances, workspacePlan: _page.workspace.plan, status, lastEvents, openEvents, pageComponents: publicPageComponents, pageComponentGroups: _page.pageComponentGroups, whiteLabel, }); }),
getLight: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), pw: queryPasswordSchema, }), ) .query(async (opts) => { if (!opts.input.slug) return null;
// Single query with all relations const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, with: { workspace: true, statusReports: { with: { statusReportUpdates: { orderBy: (reports, { desc }) => desc(reports.date), with: { statusReportUpdateToPageComponents: true }, }, statusReportsToPageComponents: { with: { pageComponent: true } }, }, }, maintenances: { with: { maintenancesToPageComponents: { with: { pageComponent: true } }, }, orderBy: (maintenances, { desc }) => desc(maintenances.from), }, pageComponents: { with: { monitor: { with: { incidents: true } }, group: true, }, orderBy: (pageComponents, { asc }) => asc(pageComponents.order), }, pageComponentGroups: true, }, });
if (!_page) return null;
// Denied visitors still need the page chrome (login, layout, OG). if (!resolvePageAccess(opts.ctx, _page, opts.input.pw).ok) { _page.statusReports = []; _page.maintenances = []; _page.pageComponents = []; _page.pageComponentGroups = []; }
// Extract monitor components for backwards compatibility const monitorComponents = _page.pageComponents.filter( (c) => c.type === "monitor" && c.monitor && c.monitor.active && !c.monitor.deletedAt, );
// Build legacy monitors array (sorted by order) const monitors = monitorComponents .map((c) => ({ ...c.monitor, // the page component carries the public-facing name/description; // clear externalName so the schema transform keeps the override. // description: NULL means never backfilled โ fall back to the // monitor's own; "" is a deliberately cleared field โ stays blank. name: c.name, description: c.description ?? c.monitor?.description ?? "", externalName: null, })) .sort((a, b) => { const aComp = monitorComponents.find((m) => m.monitor?.id === a.id); const bComp = monitorComponents.find((m) => m.monitor?.id === b.id); return (aComp?.order ?? 0) - (bComp?.order ?? 0); });
// Extract all incidents from monitor components const incidents = monitorComponents.flatMap( (c) => c.monitor?.incidents ?? [], );
const ws = selectWorkspaceSchema.safeParse(_page.workspace); const whiteLabel = ws.data?.limits["white-label"] ?? false; // stored custom theme stops applying when the plan no longer includes it const customTheme = ws.data?.limits["custom-theme"] ? _page.customTheme : null;
return selectPublicPageLightSchemaWithRelation.parse({ ..._page, customTheme, monitors, incidents, statusReports: _page.statusReports, maintenances: _page.maintenances, pageComponents: _page.pageComponents, pageComponentGroups: _page.pageComponentGroups, workspacePlan: _page.workspace.plan, whiteLabel, }); }),
// Narrow access-check query for the markdown detail routes: returns only the // gate + chrome fields, skipping the full reports/maintenances/components graph // that getLight loads. getGate: publicProcedure .input(z.object({ slug: z.string().toLowerCase() })) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, columns: { slug: true, customDomain: true, accessType: true, authEmailDomains: true, allowedIpRanges: true, homepageUrl: true, contactUrl: true, }, with: { workspace: true }, });
if (!_page) return null;
const ws = selectWorkspaceSchema.safeParse(_page.workspace); const whiteLabel = ws.data?.limits["white-label"] ?? false;
const { workspace: _workspace, ...rest } = _page; const gate = gateFieldsSchema.parse(rest); return { ...gate, whiteLabel }; }),
getMaintenance: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), id: z.number(), pw: queryPasswordSchema, }), ) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db .select() .from(page) .where( sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, ) .get();
if (!_page) return null;
assertPageAccess(opts.ctx, _page, opts.input.pw);
const _maintenance = await opts.ctx.db.query.maintenance.findFirst({ where: and( eq(maintenance.id, opts.input.id), eq(maintenance.pageId, _page.id), ), with: { maintenancesToPageComponents: { with: { pageComponent: { with: { monitor: true } } }, }, }, });
if (!_maintenance) return null;
const props: z.infer<typeof selectMaintenancePageSchema> = _maintenance; return selectMaintenancePageSchema.parse(props); }),
getUptime: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), pw: queryPasswordSchema, pageComponentIds: z.string().array(), cardType: z .enum(["requests", "duration", "dominant", "manual"]) .prefault("requests"), barType: z .enum(["absolute", "dominant", "manual"]) .prefault("dominant"), // preview override for the floating-button config; falls back to the // page's stored `configuration.days` when omitted days: z.union([z.literal(30), z.literal(45)]).optional(), }), ) .query(async (opts) => { const input = opts.input; if (!input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${input.slug} OR lower(${page.customDomain}) = ${input.slug}`, with: { maintenances: { with: { maintenancesToPageComponents: { with: { pageComponent: true } }, }, }, statusReports: { with: { statusReportsToPageComponents: { with: { pageComponent: true } }, statusReportUpdates: { with: { statusReportUpdateToPageComponents: true }, }, }, }, pageComponents: { where: inArray( pageComponent.id, input.pageComponentIds.map(Number), ), with: { monitor: { with: { incidents: true, }, }, }, }, }, });
if (!_page) return null;
assertPageAccess(opts.ctx, _page, input.pw);
const pageComponents = selectPageComponentWithMonitorRelation .array() .parse(_page.pageComponents);
// Early return if no components to process if (pageComponents.length === 0) return [];
const monitors = pageComponents.filter(isMonitorComponent);
const monitorsByType = { http: monitors.filter((c) => c.monitor.jobType === "http"), tcp: monitors.filter((c) => c.monitor.jobType === "tcp"), dns: monitors.filter((c) => c.monitor.jobType === "dns"), icmp: monitors.filter((c) => c.monitor.jobType === "icmp"), grpc: monitors.filter((c) => c.monitor.jobType === "grpc"), };
const proceduresByType = { http: getStatusProcedure("45d", "http"), tcp: getStatusProcedure("45d", "tcp"), dns: getStatusProcedure("45d", "dns"), icmp: getStatusProcedure("45d", "icmp"), grpc: getStatusProcedure("45d", "grpc"), };
// Manual mode never touches Tinybird. Otherwise race the reads against // the fallback budget: a slow (>5s) or erroring Tinybird degrades the // whole page to manual mode so bars still render from DB events. const tinybird = await withTinybirdFallback(() => input.barType === "manual" ? Promise.resolve([null, null, null, null, null]) : Promise.all( Object.entries(proceduresByType).map(([type, procedure]) => { const monitorIds = monitorsByType[ type as keyof typeof proceduresByType ].map((c) => c.monitor.id.toString()); if (monitorIds.length === 0) return null; return procedure({ monitorIds }); }), ), );
const tinybirdUnhealthy = !tinybird.ok; const [statusHttp, statusTcp, statusDns, statusIcmp, statusGrpc] = tinybird.data ?? [null, null, null, null, null];
const statusDataByMonitorId = new Map< string, | Awaited<ReturnType<(typeof proceduresByType)["http"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["tcp"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["dns"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["icmp"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["grpc"]>>["data"] >();
// Consolidate status data from all monitor types into the map for (const statusResult of [ statusHttp, statusTcp, statusDns, statusIcmp, statusGrpc, ]) { if (statusResult?.data) { statusResult.data.forEach((status) => { const monitorId = status.monitorId; if (!statusDataByMonitorId.has(monitorId)) { statusDataByMonitorId.set(monitorId, []); } statusDataByMonitorId.get(monitorId)?.push(status); }); } }
const parsedConfiguration = pageConfigurationSchema.safeParse( _page.configuration ?? {}, ); const lookbackPeriod = input.days ?? (parsedConfiguration.success ? parsedConfiguration.data.days : 45);
return pageComponents.map((c) => { const events = getEvents({ maintenances: _page.maintenances, incidents: c.monitor?.incidents ?? [], reports: _page.statusReports, pageComponentId: c.id, monitorId: c.monitorId ?? undefined, componentType: c.type, });
// Determine whether to use real Tinybird data or synthetic data const shouldUseRealData = c.type === "monitor" && c.monitor && input.barType !== "manual" && !tinybirdUnhealthy && process.env.NOOP_UPTIME !== "true";
let filledData: StatusData[]; if (shouldUseRealData) { // Monitor components with real data: use Tinybird data const monitorId = c.monitor?.id.toString() || ""; const rawData = statusDataByMonitorId.get(monitorId) || []; filledData = fillStatusDataFor45Days( rawData, monitorId, lookbackPeriod, ); } else { // Static components, manual mode, or NOOP mode: use synthetic data filledData = fillStatusDataFor45DaysNoop({ errorDays: [], degradedDays: [], lookbackPeriod, }); }
// Static components have no monitoring data; a degraded Tinybird forces // every component into manual mode so bars/cards still render. const forceManual = c.type === "static" || tinybirdUnhealthy; const effectiveBarType = forceManual ? "manual" : input.barType; const effectiveCardType = forceManual ? "manual" : input.cardType;
const processedData = setDataByType({ events, data: filledData, cardType: effectiveCardType, barType: effectiveBarType, }); const uptime = getUptime({ data: filledData, events, barType: effectiveBarType, cardType: effectiveCardType, });
return { id: c.id, pageComponentId: c.id, name: c.name, description: c.description, type: c.type, // For monitor-type components, include monitor fields ...(c.monitor ? { monitor: c.monitor } : {}), data: processedData, uptime, }; }); }),
// NOTE: used for the theme store getNoopUptime: publicProcedure.query(async () => { const data = fillStatusDataFor45DaysNoop({ errorDays: [4], degradedDays: [40], }); const processedData = setDataByType({ events: [ { type: "maintenance", from: new Date(new Date().setDate(new Date().getDate() - 10)), to: new Date(new Date().setDate(new Date().getDate() - 10)), name: "DB migration", id: 1, status: "info", }, ], data, cardType: "requests", barType: "dominant", }); return { data: processedData, uptime: "100%", }; }),
getReport: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), id: z.number(), pw: queryPasswordSchema, }), ) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db .select() .from(page) .where( sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, ) .get();
if (!_page) return null;
assertPageAccess(opts.ctx, _page, opts.input.pw);
const _report = await opts.ctx.db.query.statusReport.findFirst({ where: and( eq(statusReport.id, opts.input.id), eq(statusReport.pageId, _page.id), ), with: { statusReportsToPageComponents: { with: { pageComponent: { with: { monitor: true } } }, }, statusReportUpdates: { orderBy: (reports, { desc }) => desc(reports.date), with: { statusReportUpdateToPageComponents: true }, }, }, });
if (!_report) return null;
const result: z.infer<typeof selectStatusReportPageSchema> = _report; return selectStatusReportPageSchema.parse(result); }),
getNoopReport: publicProcedure.query(async () => { const date = new Date(new Date().setDate(new Date().getDate() - 4));
const resolvedDate = new Date(date.setMinutes(date.getMinutes() - 81)); const monitoringDate = new Date(date.setMinutes(date.getMinutes() - 54)); const identifiedDate = new Date(date.setMinutes(date.getMinutes() - 32)); const investigatingDate = new Date(date.setMinutes(date.getMinutes() - 4));
const props: z.input<typeof selectStatusReportPageSchema> = { id: 1, pageId: 1, workspaceId: 1, status: "investigating" as const, title: "API Latency Issues", createdAt: new Date(new Date().setDate(new Date().getDate() - 2)), updatedAt: new Date(new Date().setDate(new Date().getDate() - 1)), statusReportsToPageComponents: [ { pageComponentId: 1, statusReportId: 1, pageComponent: { workspaceId: 1, pageId: 1, id: 1, name: "API Monitor", type: "monitor" as const, monitorId: 1, order: 1, groupId: null, groupOrder: null, description: "Main API endpoint", createdAt: new Date(new Date().setDate(new Date().getDate() - 30)), updatedAt: new Date(new Date().setDate(new Date().getDate() - 30)), }, }, ], statusReportUpdates: [ { id: 4, statusReportId: 1, status: "resolved" as const, message: "All systems are operating normally. The issue has been fully resolved.", date: resolvedDate, createdAt: resolvedDate, updatedAt: resolvedDate, }, { id: 3, statusReportId: 1, status: "monitoring" as const, message: "We are continuing to monitor the situation to ensure that the issue is resolved.", date: monitoringDate, createdAt: monitoringDate, updatedAt: monitoringDate, }, { id: 2, statusReportId: 1, status: "identified" as const, message: "The issue has been identified and a fix is being deployed.", date: identifiedDate, createdAt: identifiedDate, updatedAt: identifiedDate, }, { id: 1, statusReportId: 1, status: "investigating" as const, message: "We are investigating reports of increased latency on our API endpoints.", date: investigatingDate, createdAt: investigatingDate, updatedAt: investigatingDate, }, ], };
return selectStatusReportPageSchema.parse(props); }),
getMonitors: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), pw: queryPasswordSchema }), ) .query(async (opts) => { if (!opts.input.slug) return null;
// NOTE: revalidate the public monitors first const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, with: { pageComponents: { with: { monitor: true, }, }, }, });
if (!_page) return null;
assertPageAccess(opts.ctx, _page, opts.input.pw);
const pageComponents = selectPageComponentWithMonitorRelation .array() .parse(_page.pageComponents);
const publicMonitors = pageComponents .filter(isMonitorComponent) .filter((c) => c.monitor?.public);
const monitorsByType = { http: publicMonitors.filter((c) => c.monitor.jobType === "http"), tcp: publicMonitors.filter((c) => c.monitor.jobType === "tcp"), dns: publicMonitors.filter((c) => c.monitor.jobType === "dns"), icmp: publicMonitors.filter((c) => c.monitor.jobType === "icmp"), grpc: publicMonitors.filter((c) => c.monitor.jobType === "grpc"), };
const proceduresByType = { http: getMetricsLatencyMultiProcedure("1d", "http"), tcp: getMetricsLatencyMultiProcedure("1d", "tcp"), dns: getMetricsLatencyMultiProcedure("1d", "dns"), icmp: getMetricsLatencyMultiProcedure("1d", "icmp"), grpc: getMetricsLatencyMultiProcedure("1d", "grpc"), };
// Slow/erroring Tinybird โ empty latency data so the page still renders. const metrics = await withTinybirdFallback(() => Promise.all( Object.entries(proceduresByType).map(([type, procedure]) => { const monitorIds = monitorsByType[ type as keyof typeof proceduresByType ].map((c) => c.monitor.id.toString()); if (monitorIds.length === 0) return null; return procedure({ monitorIds }); }), ), );
const [ metricsLatencyMultiHttp, metricsLatencyMultiTcp, metricsLatencyMultiDns, metricsLatencyMultiIcmp, metricsLatencyMultiGrpc, ] = metrics.data ?? [null, null, null, null, null];
const metricsDataByMonitorId = new Map< string, | Awaited<ReturnType<(typeof proceduresByType)["http"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["tcp"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["dns"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["icmp"]>>["data"] | Awaited<ReturnType<(typeof proceduresByType)["grpc"]>>["data"] >();
if (metricsLatencyMultiHttp?.data) { metricsLatencyMultiHttp.data.forEach((metric) => { const monitorId = metric.monitorId; if (!metricsDataByMonitorId.has(monitorId)) { metricsDataByMonitorId.set(monitorId, []); } metricsDataByMonitorId.get(monitorId)?.push(metric); }); }
if (metricsLatencyMultiTcp?.data) { metricsLatencyMultiTcp.data.forEach((metric) => { const monitorId = metric.monitorId; if (!metricsDataByMonitorId.has(monitorId)) { metricsDataByMonitorId.set(monitorId, []); } metricsDataByMonitorId.get(monitorId)?.push(metric); }); }
if (metricsLatencyMultiDns?.data) { metricsLatencyMultiDns.data.forEach((metric) => { const monitorId = metric.monitorId; if (!metricsDataByMonitorId.has(monitorId)) { metricsDataByMonitorId.set(monitorId, []); } metricsDataByMonitorId.get(monitorId)?.push(metric); }); }
if (metricsLatencyMultiIcmp?.data) { metricsLatencyMultiIcmp.data.forEach((metric) => { const monitorId = metric.monitorId; if (!metricsDataByMonitorId.has(monitorId)) { metricsDataByMonitorId.set(monitorId, []); } metricsDataByMonitorId.get(monitorId)?.push(metric); }); }
if (metricsLatencyMultiGrpc?.data) { metricsLatencyMultiGrpc.data.forEach((metric) => { const monitorId = metric.monitorId; if (!metricsDataByMonitorId.has(monitorId)) { metricsDataByMonitorId.set(monitorId, []); } metricsDataByMonitorId.get(monitorId)?.push(metric); }); }
return publicMonitors.map((c) => { const monitorId = c.monitor.id.toString(); const data = metricsDataByMonitorId.get(monitorId) || [];
return { ...selectPublicMonitorSchema.parse(c.monitor), data, }; }); }),
getMonitor: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), id: z.number(), pw: queryPasswordSchema, }), ) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, with: { pageComponents: { where: eq(pageComponent.monitorId, opts.input.id), with: { monitor: true, }, }, }, });
if (!_page) return null;
assertPageAccess(opts.ctx, _page, opts.input.pw);
const pageComponents = selectPageComponentWithMonitorRelation .array() .parse(_page.pageComponents);
const monitorComponents = pageComponents.filter(isMonitorComponent);
const _monitor = monitorComponents.find( (c) => c.monitor.id === opts.input.id, )?.monitor;
if (!_monitor) return null; if (!_monitor.public) return null; if (_monitor.deletedAt) return null;
const proceduresByType = { http: { latency: getMetricsLatencyProcedure("7d", "http"), regions: getMetricsRegionsProcedure("7d", "http"), uptime: getUptimeProcedure("7d", "http"), }, tcp: { latency: getMetricsLatencyProcedure("7d", "tcp"), regions: getMetricsRegionsProcedure("7d", "tcp"), uptime: getUptimeProcedure("7d", "tcp"), }, dns: { latency: getMetricsLatencyProcedure("7d", "dns"), regions: getMetricsRegionsProcedure("7d", "dns"), uptime: getUptimeProcedure("7d", "dns"), }, icmp: { latency: getMetricsLatencyProcedure("7d", "icmp"), regions: getMetricsRegionsProcedure("7d", "icmp"), uptime: getUptimeProcedure("7d", "icmp"), }, grpc: { latency: getMetricsLatencyProcedure("7d", "grpc"), regions: getMetricsRegionsProcedure("7d", "grpc"), uptime: getUptimeProcedure("7d", "grpc"), }, };
// `udp` and `ssl` are monitor job types with no Tinybird pipes. Looking the // key up instead of asserting the type means such a monitor renders with // empty charts โ the same shape a Tinybird outage produces โ rather than // throwing on a missing key. const procedures = proceduresByType[_monitor.jobType as keyof typeof proceduresByType] ?? null;
const fromDate = startOfDay(subDays(new Date(), 7)).toISOString(); const toDate = endOfDay(new Date()).toISOString();
// Slow/erroring Tinybird โ empty chart data so the page still renders. const metrics = !procedures ? { ok: false as const, data: null } : await withTinybirdFallback(() => Promise.all([ procedures.latency({ monitorId: _monitor.id.toString(), fromDate, toDate, }), procedures.regions({ monitorId: _monitor.id.toString(), fromDate, toDate, }), procedures.uptime({ monitorId: _monitor.id.toString(), interval: 240, fromDate, toDate, }), ]), );
const [latency, regions, uptime] = metrics.data ?? [ { data: [] }, { data: [] }, { data: [] }, ];
return { ...selectPublicMonitorSchema.parse(_monitor), data: { latency, regions, uptime, }, }; }),
subscribe: publicProcedure .meta({ track: Events.SubscribePage, trackProps: ["slug", "email"] }) .input( z.object({ slug: z.string().toLowerCase(), email: z.email(), subscribeComponents: z.boolean(), pageComponents: z.array(z.number().int().positive()), }), ) .mutation(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, with: { workspace: true, }, });
if (!_page) { throw new TRPCError({ code: "NOT_FOUND", message: "Page not found", }); }
assertPageAccess(opts.ctx, _page);
const workspace = selectWorkspaceSchema.safeParse(_page.workspace);
if (!workspace.success) { throw new TRPCError({ code: "BAD_REQUEST", message: "Workspace data is invalid", }); }
if (!workspace.data.limits["status-subscribers"]) { throw new TRPCError({ code: "FORBIDDEN", message: "Upgrade to use status subscribers", }); }
// Guard against email spam: reject if a pending (unverified, unexpired) subscription exists const isPending = await hasPendingSubscriber({ input: { email: opts.input.email, pageId: _page.id }, // gated by `assertPageAccess` above visitor: null, }); if (isPending) { throw new TRPCError({ code: "BAD_REQUEST", message: "A confirmation link was already sent. Please check your email or wait until it expires to request a new one.", }); }
const subscription = await upsertSelfSignupSubscriber({ input: { email: opts.input.email, pageId: _page.id, componentIds: opts.input.subscribeComponents ? opts.input.pageComponents : [], }, visitor: visitorFromCtx(opts.ctx), });
// Already verified โ no need to send another verification email if (subscription.acceptedAt) { throw new TRPCError({ code: "BAD_REQUEST", message: "Email already subscribed", }); }
return { id: subscription.id, token: subscription.token }; }),
getSubscriptionByToken: publicProcedure .input(z.object({ slug: z.string().toLowerCase(), token: z.uuid() })) .query(async (opts) => { if (!opts.input.slug) return null;
const subscription = await getSubscriberByToken({ input: { token: opts.input.token, domain: opts.input.slug }, });
if (!subscription) { throw new TRPCError({ code: "NOT_FOUND", message: "Subscription not found", }); }
return subscription; }),
updateSubscription: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), token: z.uuid(), subscribeComponents: z.boolean(), pageComponents: z.array(z.number().int().positive()), }), ) .mutation(async (opts) => { if (!opts.input.slug) return null;
try { await updateSubscriberScope({ input: { token: opts.input.token, componentIds: opts.input.subscribeComponents ? opts.input.pageComponents : [], domain: opts.input.slug, }, }); } catch (error) { if (error instanceof Error) { const code = error.message.toLowerCase().includes("not found") ? "NOT_FOUND" : "BAD_REQUEST"; throw new TRPCError({ code, message: error.message }); } throw error; }
return { success: true }; }),
validateEmailDomain: publicProcedure .meta({ track: Events.ValidateEmailDomain, trackProps: ["slug", "email"] }) .input(z.object({ slug: z.string().toLowerCase(), email: z.string() })) .query(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, });
if (!_page) { throw new TRPCError({ code: "NOT_FOUND", message: "Page not found", }); }
if (_page.accessType !== "email-domain") { throw new TRPCError({ code: "BAD_REQUEST", message: "Page is not configured to allow email domain authentication", }); }
const allowedDomains = _page.authEmailDomains?.split(",") ?? [];
if (!allowedDomains.includes(opts.input.email.split("@")[1])) { throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid email domain", }); }
return { email: opts.input.email, slug: opts.input.slug, page: _page, }; }),
verifyEmail: publicProcedure .meta({ track: Events.VerifySubscribePage, trackProps: ["slug"] }) .input(z.object({ slug: z.string().toLowerCase(), token: z.uuid() })) .mutation(async (opts) => { if (!opts.input.slug) return null;
try { const subscription = await verifySelfSignupSubscriber({ input: { token: opts.input.token, domain: opts.input.slug }, });
if (!subscription) { throw new TRPCError({ code: "NOT_FOUND", message: "Subscription not found", }); }
return subscription; } catch (error) { if (error instanceof TRPCError) throw error; if (error instanceof Error) { throw new TRPCError({ code: "BAD_REQUEST", message: error.message }); } throw error; } }),
verifyPassword: publicProcedure .input(z.object({ slug: z.string().toLowerCase(), password: z.string() })) .mutation(async (opts) => { if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, });
if (!_page) { throw new TRPCError({ code: "NOT_FOUND", message: "Page not found", }); }
if (_page.accessType !== "password") { throw new TRPCError({ code: "BAD_REQUEST", message: "Page is not configured to allow password authentication", }); }
if (!constantTimeEqual(_page.password, opts.input.password)) { throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid password", }); }
return true; }),
// Server-side password gate for the public `/api/*` routes. Returns a boolean // so the stored password never leaves the server (the `get` output omits it). isPasswordAuthorized: publicProcedure .input( z.object({ slug: z.string().toLowerCase(), queryPassword: z.string().nullish(), cookiePassword: z.string().nullish(), }), ) .query(async (opts) => { const _page = await opts.ctx.db.query.page.findFirst({ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`, columns: { password: true, accessType: true }, }); if (!_page || _page.accessType !== "password") return false; // TODO: rate-limit โ an unauthenticated caller can brute-force guesses here. // Query param wins over cookie: a present-but-wrong `?pw=` must not fall // through to a valid cookie. Mirrors isPasswordAuthorized on the proxy. const submitted = opts.input.queryPassword ?? opts.input.cookiePassword; return constantTimeEqual(_page.password, submitted); }),
getSubscriberByToken: publicProcedure .input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() })) .query(async (opts) => { const subscription = await getSubscriberByToken({ input: { token: opts.input.token, domain: opts.input.domain }, });
if ( !subscription || subscription.unsubscribedAt || subscription.channelType !== "email" ) { return null; }
return { pageName: subscription.pageName, maskedEmail: subscription.email, }; }),
unsubscribe: publicProcedure .input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() })) .mutation(async (opts) => { try { await unsubscribeSubscriber({ input: { token: opts.input.token, domain: opts.input.domain }, }); return { success: true }; } catch (error) { if (error instanceof Error) { throw new TRPCError({ code: "BAD_REQUEST", message: error.message }); } throw error; } }),});