Skip to content

Open-source status page, incident response and uptime monitoring

refactor(external-services): use tRPC + Tanstack Query (#2180)

Colin Ozanne5d7a1c942fe7
diff --git a/apps/web/src/app/(landing)/status/[id]/history-bars.tsx b/apps/web/src/app/(landing)/status/[id]/history-bars.tsx
index d0b0096b8..3ffd46395 100644
--- a/apps/web/src/app/(landing)/status/[id]/history-bars.tsx
+++ b/apps/web/src/app/(landing)/status/[id]/history-bars.tsx
@@ -8,17 +8,17 @@ import type {
type DailyRow = {
day: string;
- worst_indicator: string;
- had_maintenance: number;
- snapshot_count: number;
+ worstIndicator: string;
+ hadMaintenance: number;
+ snapshotCount: number;
};
function indicatorToStatusType(args: {
- worst_indicator: string;
- had_maintenance: number;
+ worstIndicator: string;
+ hadMaintenance: number;
}): StatusType {
- if (args.had_maintenance) return "info";
- switch (args.worst_indicator) {
+ if (args.hadMaintenance) return "info";
+ switch (args.worstIndicator) {
case "none":
return "success";
case "minor":
@@ -76,15 +76,15 @@ function buildSeries(props: HistoryBarsProps): StatusBarData[] {
}
byDay.set(key, {
day: prev.day,
- worst_indicator:
- severityOf(r.worst_indicator) > severityOf(prev.worst_indicator)
- ? r.worst_indicator
- : prev.worst_indicator,
- had_maintenance:
- severityOf(r.worst_indicator) > severityOf(prev.worst_indicator)
- ? r.had_maintenance
- : prev.had_maintenance,
- snapshot_count: prev.snapshot_count + r.snapshot_count,
+ worstIndicator:
+ severityOf(r.worstIndicator) > severityOf(prev.worstIndicator)
+ ? r.worstIndicator
+ : prev.worstIndicator,
+ hadMaintenance:
+ severityOf(r.worstIndicator) > severityOf(prev.worstIndicator)
+ ? r.hadMaintenance
+ : prev.hadMaintenance,
+ snapshotCount: prev.snapshotCount + r.snapshotCount,
});
}
const out: StatusBarData[] = [];
@@ -97,8 +97,8 @@ function buildSeries(props: HistoryBarsProps): StatusBarData[] {
const row = byDay.get(iso);
const status: StatusType = row
? indicatorToStatusType({
- worst_indicator: row.worst_indicator,
- had_maintenance: row.had_maintenance,
+ worstIndicator: row.worstIndicator,
+ hadMaintenance: row.hadMaintenance,
})
: "empty";
out.push({
diff --git a/apps/web/src/app/(landing)/status/[id]/incidents.tsx b/apps/web/src/app/(landing)/status/[id]/incidents.tsx
index 1ec14fab3..c0075a5ff 100644
--- a/apps/web/src/app/(landing)/status/[id]/incidents.tsx
+++ b/apps/web/src/app/(landing)/status/[id]/incidents.tsx
@@ -1,31 +1,12 @@
-import { z } from "zod";
+"use client";
import {
ContentBoxDescription,
ContentBoxLink,
ContentBoxTitle,
} from "@/app/(landing)/content-box";
-import { components } from "@/content/mdx";
-
-const atlassianIncidentSchema = z.object({
- id: z.string(),
- name: z.string(),
- status: z.string(),
- impact: z.string().optional(),
- shortlink: z.string().optional(),
- started_at: z.string().optional(),
- created_at: z.string(),
- resolved_at: z.string().nullable().optional(),
-});
-
-const atlassianIncidentsResponseSchema = z.object({
- incidents: z.array(atlassianIncidentSchema),
-});
-
-type Incident = z.infer<typeof atlassianIncidentSchema>;
-
-const TIMEOUT_MS = 5000;
-const MAX_INCIDENTS = 5;
+import { Grid } from "@/content/mdx-components/grid";
+import { api } from "@/trpc/rq-client";
function impactClass(impact: string | undefined): string {
switch (impact) {
@@ -52,48 +33,10 @@ function formatTimestamp(value: string | null | undefined): string | null {
});
}
-async function fetchIncidents(
- statusPageUrl: string,
-): Promise<Incident[] | null> {
- const url = `${statusPageUrl}/api/v2/incidents.json`;
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
- try {
- const res = await fetch(url, {
- signal: controller.signal,
- headers: { Accept: "application/json" },
- next: { revalidate: 60 },
- });
- if (!res.ok) {
- console.warn(
- `[external-status incidents] non-200 from ${url}: ${res.status}`,
- );
- return null;
- }
- const json = await res.json();
- const parsed = atlassianIncidentsResponseSchema.safeParse(json);
- if (!parsed.success) {
- console.warn(
- `[external-status incidents] invalid payload from ${url}`,
- parsed.error.issues,
- );
- return null;
- }
- return parsed.data.incidents.slice(0, MAX_INCIDENTS);
- } catch (err) {
- console.warn(
- `[external-status incidents] fetch failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,
- );
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
-
export type IncidentsProps = {
- statusPageUrl: string;
+ slug: string;
serviceName: string;
- apiConfigType?: string;
+ statusPageUrl: string;
};
function UpstreamFallback({
@@ -119,21 +62,14 @@ function UpstreamFallback({
);
}
-export async function Incidents({
- statusPageUrl,
+export function Incidents({
+ slug,
serviceName,
- apiConfigType,
+ statusPageUrl,
}: IncidentsProps) {
- if (apiConfigType !== "atlassian") {
- return (
- <UpstreamFallback
- serviceName={serviceName}
- statusPageUrl={statusPageUrl}
- />
- );
- }
- const incidents = await fetchIncidents(statusPageUrl);
- if (!incidents) {
+ const [data] = api.externalService.incidents.useSuspenseQuery({ slug });
+
+ if (!data.supported || data.unavailable) {
return (
<UpstreamFallback
serviceName={serviceName}
@@ -142,7 +78,7 @@ export async function Incidents({
);
}
- if (incidents.length === 0) {
+ if (data.incidents.length === 0) {
return (
<p className="text-muted-foreground">
No {serviceName} incidents reported in the recent period.
@@ -151,10 +87,10 @@ export async function Incidents({
}
return (
- <components.Grid cols={1} className="not-prose">
- {incidents.map((inc) => {
- const started = formatTimestamp(inc.started_at ?? inc.created_at);
- const resolved = formatTimestamp(inc.resolved_at ?? null);
+ <Grid cols={1} className="not-prose">
+ {data.incidents.map((inc) => {
+ const started = formatTimestamp(inc.startedAt ?? inc.createdAt);
+ const resolved = formatTimestamp(inc.resolvedAt ?? null);
const link = inc.shortlink ?? `${statusPageUrl}/incidents/${inc.id}`;
return (
<ContentBoxLink
@@ -178,6 +114,6 @@ export async function Incidents({
</ContentBoxLink>
);
})}
- </components.Grid>
+ </Grid>
);
}
diff --git a/apps/web/src/app/(landing)/status/[id]/page.tsx b/apps/web/src/app/(landing)/status/[id]/page.tsx
index 00010ddfc..51e894f3b 100644
--- a/apps/web/src/app/(landing)/status/[id]/page.tsx
+++ b/apps/web/src/app/(landing)/status/[id]/page.tsx
@@ -2,10 +2,8 @@ import type { Metadata } from "next";
import { notFound, permanentRedirect } from "next/navigation";
import { Suspense } from "react";
-import { ExternalServicePill } from "@/app/(landing)/status/external-service-pill";
import { ButtonLink } from "@/content/mdx-components/button-link";
import { CustomLink } from "@/content/mdx-components/custom-link";
-import { env } from "@/env";
import { cachedGetExternalServiceBySlug } from "@/lib/external-service-cache";
import {
APP_URL,
@@ -14,16 +12,14 @@ import {
ogMetadata,
twitterMetadata,
} from "@/lib/metadata/shared-metadata";
-import { OSTinybird, safePipeData } from "@openstatus/tinybird";
+import { HydrateClient, api } from "@/trpc/rq-server";
import {
ContentBoxContainer,
ContentBoxDescription,
ContentBoxTitle,
} from "../../content-box";
-import { formatRelative, getStatusAnswer, isStale } from "../utils";
-import { HistoryBars } from "./history-bars";
-import { Incidents } from "./incidents";
+import { ServiceDetail } from "./service-detail";
export const dynamic = "force-dynamic";
@@ -71,59 +67,6 @@ export async function generateMetadata(args: {
};
}
-function jsonLd(args: {
- serviceName: string;
- serviceUrl: string;
- canonicalUrl: string;
- answer: string;
-}) {
- return {
- "@context": "https://schema.org",
- "@graph": [
- {
- "@type": "Service",
- name: args.serviceName,
- url: args.serviceUrl,
- },
- {
- "@type": "WebPage",
- url: args.canonicalUrl,
- name: `${args.serviceName} Status`,
- },
- {
- "@type": "FAQPage",
- mainEntity: [
- {
- "@type": "Question",
- name: `Is ${args.serviceName} down?`,
- acceptedAnswer: {
- "@type": "Answer",
- text: args.answer,
- },
- },
- ],
- },
- {
- "@type": "BreadcrumbList",
- itemListElement: [
- {
- "@type": "ListItem",
- position: 1,
- name: "External Status",
- item: `${BASE_URL}/status`,
- },
- {
- "@type": "ListItem",
- position: 2,
- name: args.serviceName,
- item: args.canonicalUrl,
- },
- ],
- },
- ],
- };
-}
-
export default async function Page(args: { params: Promise<RouteParams> }) {
const { id } = await args.params;
const service = await cachedGetExternalServiceBySlug(id);
@@ -133,57 +76,16 @@ export default async function Page(args: { params: Promise<RouteParams> }) {
permanentRedirect(`/status/${service.slug}`);
}
- const aliasSlugs = Array.isArray(service.aliases) ? service.aliases : [];
- const slugChain = [service.slug, ...aliasSlugs];
-
- const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
- const [latestRes, historyRes] = await Promise.all([
- safePipeData(
- tb.externalStatusLatest({ ids: slugChain }),
- "externalStatusLatest",
- ),
- safePipeData(
- tb.externalStatusHistory({ ids: slugChain, days: HISTORY_DAYS }),
- "externalStatusHistory",
- ),
+ await Promise.all([
+ api.externalService.detail.prefetch({
+ slug: service.slug,
+ days: HISTORY_DAYS,
+ }),
+ api.externalService.incidents.prefetch({ slug: service.slug }),
]);
- const latestRows = Array.isArray(latestRes.data) ? latestRes.data : [];
- latestRows.sort((a, b) => b.last_fetched_at - a.last_fetched_at);
- const latest = latestRows[0];
-
- const historyRows = Array.isArray(historyRes.data) ? historyRes.data : [];
-
- const indicator = latest?.indicator ?? "";
- const status = latest?.status ?? "";
- const statusMessage = latest?.status_message ?? undefined;
- const fetchedAt = latest?.last_fetched_at ?? 0;
- const stale = fetchedAt > 0 && isStale(fetchedAt);
- const hasLiveData = fetchedAt > 0 && !stale;
- const answer = getStatusAnswer({
- name: service.name,
- indicator,
- status,
- hasLiveData,
- });
-
- const canonicalUrl = `${BASE_URL}/status/${service.slug}`;
- const ld = jsonLd({
- serviceName: service.name,
- serviceUrl: service.url,
- canonicalUrl,
- answer,
- });
-
return (
<section className="prose dark:prose-invert mb-12 max-w-none">
- <script
- type="application/ld+json"
- // biome-ignore lint/security/noDangerouslySetInnerHtml: JSON-LD requires literal JSON
- dangerouslySetInnerHTML={{
- __html: JSON.stringify(ld).replace(/</g, "\\u003c"),
- }}
- />
<ContentBoxContainer className="not-prose my-6 px-4 py-2 text-sm">
<CustomLink
href={`${APP_URL}?ref=status-service-top`}
@@ -193,62 +95,21 @@ export default async function Page(args: { params: Promise<RouteParams> }) {
OpenStatus →
</CustomLink>
</ContentBoxContainer>
- <h1>Is {service.name} down?</h1>
- <p>
- {answer} Below you'll find the live {service.name} status, uptime over
- the last {HISTORY_DAYS} days, and recent {service.name} incidents.
- </p>
- <div className="not-prose flex flex-wrap items-center gap-6">
- <ExternalServicePill
- indicator={indicator}
- status={status}
- statusMessage={statusMessage}
- />
- {fetchedAt > 0 ? (
- <span className="text-muted-foreground text-sm">
- Last updated {formatRelative(fetchedAt)}
- {stale ? (
- <span className="ml-1 inline-flex px-2 py-0.5 text-warning text-xs">
- (stale)
- </span>
- ) : null}
- </span>
- ) : (
- <span className="text-muted-foreground text-sm">
- No data yet — tracking begins after first poll.
- </span>
- )}
- <a
- className="text-sm underline"
- href={service.statusPageUrl}
- target="_blank"
- rel="noopener noreferrer"
- >
- Upstream status page
- </a>
- </div>
- <h2>
- {service.name} uptime — last {HISTORY_DAYS} days
- </h2>
- <div className="not-prose">
- <HistoryBars daily={historyRows} days={HISTORY_DAYS} />
- </div>
+ <HydrateClient>
+ <Suspense
+ fallback={
+ <section className="prose dark:prose-invert mb-12 max-w-none">
+ <p className="text-muted-foreground">
+ Loading {service.name} status…
+ </p>
+ </section>
+ }
+ >
+ <ServiceDetail slug={service.slug} days={HISTORY_DAYS} />
+ </Suspense>
+ </HydrateClient>
- <h2>{service.name} recent incidents</h2>
- <Suspense
- fallback={
- <p className="text-muted-foreground">
- Loading recent {service.name} incidents…
- </p>
- }
- >
- <Incidents
- statusPageUrl={service.statusPageUrl}
- serviceName={service.name}
- apiConfigType={service.apiConfig?.type}
- />
- </Suspense>
<ContentBoxContainer className="not-prose mt-10 flex flex-col items-start gap-3 bg-muted/30">
<ContentBoxTitle className="m-0! text-lg">
Looking for a status page?
diff --git a/apps/web/src/app/(landing)/status/[id]/service-detail.tsx b/apps/web/src/app/(landing)/status/[id]/service-detail.tsx
new file mode 100644
index 000000000..fcf83a1e5
--- /dev/null
+++ b/apps/web/src/app/(landing)/status/[id]/service-detail.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import { Suspense } from "react";
+
+import { BASE_URL } from "@/lib/metadata/shared-metadata";
+import { api } from "@/trpc/rq-client";
+
+import { ExternalServicePill } from "../external-service-pill";
+import { formatRelative, getStatusAnswer, isStale } from "../utils";
+import { HistoryBars } from "./history-bars";
+import { Incidents } from "./incidents";
+
+function jsonLd(args: {
+ serviceName: string;
+ serviceUrl: string;
+ canonicalUrl: string;
+ answer: string;
+}) {
+ return {
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "Service",
+ name: args.serviceName,
+ url: args.serviceUrl,
+ },
+ {
+ "@type": "WebPage",
+ url: args.canonicalUrl,
+ name: `${args.serviceName} Status`,
+ },
+ {
+ "@type": "FAQPage",
+ mainEntity: [
+ {
+ "@type": "Question",
+ name: `Is ${args.serviceName} down?`,
+ acceptedAnswer: {
+ "@type": "Answer",
+ text: args.answer,
+ },
+ },
+ ],
+ },
+ {
+ "@type": "BreadcrumbList",
+ itemListElement: [
+ {
+ "@type": "ListItem",
+ position: 1,
+ name: "External Status",
+ item: `${BASE_URL}/status`,
+ },
+ {
+ "@type": "ListItem",
+ position: 2,
+ name: args.serviceName,
+ item: args.canonicalUrl,
+ },
+ ],
+ },
+ ],
+ };
+}
+
+export function ServiceDetail({ slug, days }: { slug: string; days: number }) {
+ const [data] = api.externalService.detail.useSuspenseQuery({ slug, days });
+ const { service, latest, history } = data;
+
+ const indicator = latest?.indicator ?? "";
+ const status = latest?.status ?? "";
+ const statusMessage = latest?.statusMessage || undefined;
+ const fetchedAt = latest?.lastFetchedAt ?? 0;
+ const stale = fetchedAt > 0 && isStale(fetchedAt);
+ const hasLiveData = fetchedAt > 0 && !stale;
+ const answer = getStatusAnswer({
+ name: service.name,
+ indicator,
+ status,
+ hasLiveData,
+ });
+
+ const canonicalUrl = `${BASE_URL}/status/${service.slug}`;
+ const ld = jsonLd({
+ serviceName: service.name,
+ serviceUrl: service.url,
+ canonicalUrl,
+ answer,
+ });
+
+ return (
+ <section className="prose dark:prose-invert mb-12 max-w-none">
+ <script
+ type="application/ld+json"
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: JSON-LD requires literal JSON
+ dangerouslySetInnerHTML={{
+ __html: JSON.stringify(ld).replace(/</g, "\\u003c"),
+ }}
+ />
+ <h1>Is {service.name} down?</h1>
+ <p>
+ {answer} Below you'll find the live {service.name} status, uptime over
+ the last {days} days, and recent {service.name} incidents.
+ </p>
+ <div className="not-prose flex flex-wrap items-center gap-6">
+ <ExternalServicePill
+ indicator={indicator}
+ status={status}
+ statusMessage={statusMessage}
+ />
+ {fetchedAt > 0 ? (
+ <span className="text-muted-foreground text-sm">
+ Last updated {formatRelative(fetchedAt)}
+ {stale ? (
+ <span className="ml-1 inline-flex px-2 py-0.5 text-warning text-xs">
+ (stale)
+ </span>
+ ) : null}
+ </span>
+ ) : (
+ <span className="text-muted-foreground text-sm">
+ No data yet — tracking begins after first poll.
+ </span>
+ )}
+ <a
+ className="text-sm underline"
+ href={service.statusPageUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Upstream status page
+ </a>
+ </div>
+
+ <h2>
+ {service.name} uptime — last {days} days
+ </h2>
+ <div className="not-prose">
+ <HistoryBars daily={history} days={days} />
+ </div>
+
+ <h2>{service.name} recent incidents</h2>
+ <Suspense
+ fallback={
+ <p className="text-muted-foreground">
+ Loading recent {service.name} incidents…
+ </p>
+ }
+ >
+ <Incidents
+ slug={service.slug}
+ serviceName={service.name}
+ statusPageUrl={service.statusPageUrl}
+ />
+ </Suspense>
+ </section>
+ );
+}
diff --git a/apps/web/src/app/(landing)/status/external-status-grid.tsx b/apps/web/src/app/(landing)/status/external-status-grid.tsx
new file mode 100644
index 000000000..1e02e0631
--- /dev/null
+++ b/apps/web/src/app/(landing)/status/external-status-grid.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import { Grid } from "@/content/mdx-components/grid";
+import { api } from "@/trpc/rq-client";
+
+import { ContentBoxLink } from "../content-box";
+import { ExternalServicePill } from "./external-service-pill";
+
+export function ExternalStatusGrid() {
+ const [services] = api.externalService.grid.useSuspenseQuery();
+
+ return (
+ <Grid cols={2}>
+ {services.map((service) => (
+ <ContentBoxLink
+ key={service.slug}
+ href={`/status/${service.slug}`}
+ className="flex flex-col gap-2"
+ >
+ <p className="m-0! font-semibold">{service.name}</p>
+ <ExternalServicePill
+ indicator={service.indicator}
+ status={service.status}
+ statusMessage={service.statusMessage || undefined}
+ className="self-start"
+ />
+ </ContentBoxLink>
+ ))}
+ </Grid>
+ );
+}
diff --git a/apps/web/src/app/(landing)/status/page.tsx b/apps/web/src/app/(landing)/status/page.tsx
index f22492e31..3a4a2f537 100644
--- a/apps/web/src/app/(landing)/status/page.tsx
+++ b/apps/web/src/app/(landing)/status/page.tsx
@@ -1,11 +1,8 @@
import type { Metadata } from "next";
+import { Suspense } from "react";
-import { ExternalServicePill } from "@/app/(landing)/status/external-service-pill";
-import { components } from "@/content/mdx";
import { ButtonLink } from "@/content/mdx-components/button-link";
import { CustomLink } from "@/content/mdx-components/custom-link";
-import { env } from "@/env";
-import { cachedListExternalServices } from "@/lib/external-service-cache";
import {
APP_URL,
BASE_URL,
@@ -13,14 +10,15 @@ import {
ogMetadata,
twitterMetadata,
} from "@/lib/metadata/shared-metadata";
-import { OSTinybird, safePipeData } from "@openstatus/tinybird";
+import { HydrateClient, api } from "@/trpc/rq-server";
import {
ContentBoxContainer,
ContentBoxDescription,
- ContentBoxLink,
ContentBoxTitle,
} from "../content-box";
+import { ExternalStatusGrid } from "./external-status-grid";
+
export const dynamic = "force-dynamic";
const TITLE = "External Status";
@@ -48,33 +46,8 @@ export const metadata: Metadata = {
},
};
-type LatestSnapshot = {
- id: string;
- indicator: string;
- status: string;
- status_message: string;
- last_fetched_at: number;
-};
-
-const UNKNOWN_SNAPSHOT: Omit<LatestSnapshot, "id"> = {
- indicator: "",
- status: "",
- status_message: "Status unavailable",
- last_fetched_at: 0,
-};
-
export default async function Page() {
- const services = await cachedListExternalServices();
- const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
- const latestRes = await safePipeData(
- tb.externalStatusLatest({}),
- "externalStatusLatest (list)",
- );
- const latestRows = Array.isArray(latestRes.data) ? latestRes.data : [];
- const latestById = new Map<string, LatestSnapshot>();
- for (const row of latestRows) {
- latestById.set(row.id, row);
- }
+ await api.externalService.grid.prefetch();
return (
<section className="prose dark:prose-invert mb-12 max-w-none">
@@ -87,27 +60,17 @@ export default async function Page() {
OpenStatus →
</CustomLink>
</ContentBoxContainer>
- <h1>External Status</h1>
- <components.Grid cols={2}>
- {services.map((service) => {
- const snap = latestById.get(service.slug) ?? UNKNOWN_SNAPSHOT;
- return (
- <ContentBoxLink
- key={service.slug}
- href={`/status/${service.slug}`}
- className="flex flex-col gap-2"
- >
- <p className="m-0! font-semibold">{service.name}</p>
- <ExternalServicePill
- indicator={snap.indicator}
- status={snap.status}
- statusMessage={snap.status_message || undefined}
- className="self-start"
- />
- </ContentBoxLink>
- );
- })}
- </components.Grid>
+
+ <HydrateClient>
+ <Suspense
+ fallback={
+ <p className="text-muted-foreground">Loading external status…</p>
+ }
+ >
+ <ExternalStatusGrid />
+ </Suspense>
+ </HydrateClient>
+
<ContentBoxContainer className="not-prose mt-10 flex flex-col items-start gap-3 bg-muted/30">
<ContentBoxTitle className="m-0! text-lg">
Looking for a status page?
diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.ts
index a78c2ea2e..d64a6a155 100644
--- a/packages/api/src/edge.ts
+++ b/packages/api/src/edge.ts
@@ -2,6 +2,7 @@ import { auditLogRouter } from "./router/auditLog";
import { chatSessionRouter } from "./router/chatSession";
import { checkerRouter } from "./router/checker";
import { domainRouter } from "./router/domain";
+import { externalServiceRouter } from "./router/externalService";
import { feedbackRouter } from "./router/feedback";
import { importRouter } from "./router/import";
import { incidentRouter } from "./router/incident";
@@ -30,6 +31,7 @@ export const edgeRouter = createTRPCRouter({
pageComponent: pageComponentRouter,
statusReport: statusReportRouter,
domain: domainRouter,
+ externalService: externalServiceRouter,
user: userRouter,
notification: notificationRouter,
invitation: invitationRouter,
diff --git a/packages/api/src/router/externalService.ts b/packages/api/src/router/externalService.ts
new file mode 100644
index 000000000..bc4364340
--- /dev/null
+++ b/packages/api/src/router/externalService.ts
@@ -0,0 +1,249 @@
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+
+import {
+ getExternalServiceBySlug,
+ listExternalServices,
+} from "@openstatus/services/external-service";
+import { OSTinybird } from "@openstatus/tinybird";
+
+import { env } from "../env";
+import { createTRPCRouter, publicProcedure } from "../trpc";
+
+const tb = new OSTinybird(env.TINY_BIRD_API_KEY);
+
+const DEFAULT_HISTORY_DAYS = 45;
+const INCIDENTS_TIMEOUT_MS = 5000;
+const MAX_INCIDENTS = 5;
+
+async function safeData<T>(
+ promise: Promise<{ data: T[] }>,
+ label: string,
+): Promise<T[]> {
+ try {
+ const { data } = await promise;
+ return data;
+ } catch (err) {
+ console.error(`[external-service] ${label} failed, returning empty:`, err);
+ return [];
+ }
+}
+
+const gridItemSchema = z.object({
+ slug: z.string(),
+ name: z.string(),
+ url: z.string(),
+ indicator: z.string(),
+ status: z.string(),
+ statusMessage: z.string(),
+});
+
+const detailServiceSchema = z.object({
+ slug: z.string(),
+ name: z.string(),
+ url: z.string(),
+ statusPageUrl: z.string(),
+ aliases: z.array(z.string()),
+ apiConfigType: z.string().optional(),
+});
+
+const latestSchema = z.object({
+ indicator: z.string(),
+ status: z.string(),
+ statusMessage: z.string(),
+ timeZone: z.string(),
+ lastFetchedAt: z.number(),
+});
+
+const historyRowSchema = z.object({
+ day: z.string(),
+ worstIndicator: z.string(),
+ hadMaintenance: z.number(),
+ snapshotCount: z.number(),
+});
+
+const incidentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ status: z.string(),
+ impact: z.string().optional(),
+ shortlink: z.string().optional(),
+ startedAt: z.string().optional(),
+ createdAt: z.string(),
+ resolvedAt: z.string().nullable().optional(),
+});
+
+const atlassianIncidentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ status: z.string(),
+ impact: z.string().optional(),
+ shortlink: z.string().optional(),
+ started_at: z.string().optional(),
+ created_at: z.string(),
+ resolved_at: z.string().nullable().optional(),
+});
+
+const atlassianIncidentsResponseSchema = z.object({
+ incidents: z.array(atlassianIncidentSchema),
+});
+
+export const externalServiceRouter = createTRPCRouter({
+ grid: publicProcedure.output(z.array(gridItemSchema)).query(async () => {
+ const [services, latestRows] = await Promise.all([
+ listExternalServices({}),
+ safeData(tb.externalStatusLatest({}), "externalStatusLatest (grid)"),
+ ]);
+
+ const byId = new Map<string, (typeof latestRows)[number]>();
+ for (const row of latestRows) byId.set(row.id, row);
+
+ return services.map((s) => {
+ const snap = byId.get(s.slug);
+ return {
+ slug: s.slug,
+ name: s.name,
+ url: s.url,
+ indicator: snap?.indicator ?? "",
+ status: snap?.status ?? "",
+ statusMessage: snap?.status_message ?? "Status unavailable",
+ };
+ });
+ }),
+
+ detail: publicProcedure
+ .input(
+ z.object({
+ slug: z.string(),
+ days: z.number().int().min(1).max(90).optional(),
+ }),
+ )
+ .output(
+ z.object({
+ service: detailServiceSchema,
+ latest: latestSchema.nullable(),
+ history: z.array(historyRowSchema),
+ }),
+ )
+ .query(async ({ input }) => {
+ const service = await getExternalServiceBySlug({ slug: input.slug });
+ if (!service) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "External service not found",
+ });
+ }
+
+ const aliasSlugs = Array.isArray(service.aliases) ? service.aliases : [];
+ const slugChain = [service.slug, ...aliasSlugs];
+ const days = input.days ?? DEFAULT_HISTORY_DAYS;
+
+ const [latestRows, historyRows] = await Promise.all([
+ safeData(
+ tb.externalStatusLatest({ ids: slugChain }),
+ "externalStatusLatest",
+ ),
+ safeData(
+ tb.externalStatusHistory({ ids: slugChain, days }),
+ "externalStatusHistory",
+ ),
+ ]);
+
+ const newest = [...latestRows].sort(
+ (a, b) => b.last_fetched_at - a.last_fetched_at,
+ )[0];
+
+ const latest = newest
+ ? {
+ indicator: newest.indicator,
+ status: newest.status,
+ statusMessage: newest.status_message,
+ timeZone: newest.time_zone,
+ lastFetchedAt: newest.last_fetched_at,
+ }
+ : null;
+
+ return {
+ service: {
+ slug: service.slug,
+ name: service.name,
+ url: service.url,
+ statusPageUrl: service.statusPageUrl,
+ aliases: aliasSlugs,
+ apiConfigType: service.apiConfig?.type,
+ },
+ latest,
+ history: historyRows.map((r) => ({
+ day: r.day,
+ worstIndicator: r.worst_indicator,
+ hadMaintenance: r.had_maintenance,
+ snapshotCount: r.snapshot_count,
+ })),
+ };
+ }),
+
+ incidents: publicProcedure
+ .input(z.object({ slug: z.string() }))
+ .output(
+ z.object({
+ supported: z.boolean(),
+ unavailable: z.boolean().optional(),
+ incidents: z.array(incidentSchema),
+ }),
+ )
+ .query(async ({ input }) => {
+ const service = await getExternalServiceBySlug({ slug: input.slug });
+ if (!service || service.apiConfig?.type !== "atlassian") {
+ return { supported: false, incidents: [] };
+ }
+
+ const url = `${service.statusPageUrl}/api/v2/incidents.json`;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), INCIDENTS_TIMEOUT_MS);
+ try {
+ // packages/api carries no Next types; widen the init so the Next data
+ // cache hint survives without an `as` cast.
+ const init: RequestInit & { next?: { revalidate?: number } } = {
+ signal: controller.signal,
+ headers: { Accept: "application/json" },
+ next: { revalidate: 60 },
+ };
+ const res = await fetch(url, init);
+ if (!res.ok) {
+ console.warn(
+ `[external-service incidents] non-200 from ${url}: ${res.status}`,
+ );
+ return { supported: true, unavailable: true, incidents: [] };
+ }
+ const json = await res.json();
+ const parsed = atlassianIncidentsResponseSchema.safeParse(json);
+ if (!parsed.success) {
+ console.warn(
+ `[external-service incidents] invalid payload from ${url}`,
+ parsed.error.issues,
+ );
+ return { supported: true, unavailable: true, incidents: [] };
+ }
+ const incidents = parsed.data.incidents
+ .slice(0, MAX_INCIDENTS)
+ .map((i) => ({
+ id: i.id,
+ name: i.name,
+ status: i.status,
+ impact: i.impact,
+ shortlink: i.shortlink,
+ startedAt: i.started_at,
+ createdAt: i.created_at,
+ resolvedAt: i.resolved_at ?? null,
+ }));
+ return { supported: true, incidents };
+ } catch (err) {
+ console.warn(
+ `[external-service incidents] fetch failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ return { supported: true, unavailable: true, incidents: [] };
+ } finally {
+ clearTimeout(timer);
+ }
+ }),
+});