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.
54 kB ยท 1621 lines
TypeScript
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622import { 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: { monitorIncidents: 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?.monitorIncidents ?? [], 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.monitorIncidents ?? [], 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.monitorIncidents ?? [], ), 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, monitorIncidents: [] } } : c, ) : pageComponents;
return selectPublicPageSchemaWithRelation.parse({ ..._page, customTheme, monitors: monitorsWithPrivateLocationCount, monitorGroups, trackers, incidents: monitorsWithPrivateLocationCount.flatMap((m) => m.monitorIncidents) ?? [], 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: { monitorIncidents: 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?.monitorIncidents ?? [], );
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: { monitorIncidents: 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?.monitorIncidents ?? [], 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; } }),});