Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: integrate components from external services (#2205)
Colin Ozanne686aeb393f17
diff --git a/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsx b/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsxnew file mode 100644index 000000000..2a6f098f3--- /dev/null+++ b/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsx@@ -0,0 +1,306 @@+"use client";++import {+ ContentBoxDescription,+ ContentBoxLink,+ ContentBoxTitle,+} from "@/app/(landing)/content-box";+import { Grid } from "@/content/mdx-components/grid";+import { BASE_URL } from "@/lib/metadata/shared-metadata";+import { api } from "@/trpc/rq-client";++import { ExternalServicePill } from "../../external-service-pill";+import { formatRelative } from "../../utils";+import { HistoryBars } from "../history-bars";++function answerFor(args: {+ fullName: string;+ indicator: string;+ status: string;+ stale: boolean;+}): string {+ const { fullName, indicator, status, stale } = args;+ if (stale) {+ return `We don't have live data for ${fullName} right now — check the official status page below.`;+ }+ if (status === "under_maintenance") {+ return `${fullName} is currently undergoing scheduled maintenance.`;+ }+ switch (indicator) {+ case "none":+ return `No, ${fullName} is not down. It is operational.`;+ case "minor":+ return `${fullName} is up, but currently experiencing a minor issue.`;+ case "major":+ return `Yes, ${fullName} is experiencing a partial outage right now.`;+ case "critical":+ return `Yes, ${fullName} is down — a major outage is currently affecting it.`;+ default:+ return `The current status of ${fullName} is unknown — check the official status page below.`;+ }+}++function impactClass(impact: string | undefined): string {+ switch (impact) {+ case "critical":+ return "bg-destructive/20 text-destructive border-destructive/30";+ case "major":+ return "bg-destructive/15 text-destructive border-destructive/20";+ case "minor":+ return "bg-warning/15 text-warning border-warning/30";+ case "maintenance":+ return "bg-info/15 text-info border-info/30";+ default:+ return "bg-muted text-muted-foreground border-muted-foreground/20";+ }+}++function formatTimestamp(value: string | null | undefined): string | null {+ if (!value) return null;+ const ms = Date.parse(value);+ if (Number.isNaN(ms)) return null;+ return new Date(ms).toLocaleString(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+ });+}++function jsonLd(args: {+ serviceName: string;+ componentName: string;+ serviceUrl: string;+ componentUrl: string;+ answer: string;+}) {+ return {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ url: args.componentUrl,+ name: `${args.serviceName} ${args.componentName} Status`,+ },+ {+ "@type": "FAQPage",+ mainEntity: [+ {+ "@type": "Question",+ name: `Is ${args.serviceName} ${args.componentName} 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.serviceUrl,+ },+ {+ "@type": "ListItem",+ position: 3,+ name: args.componentName,+ item: args.componentUrl,+ },+ ],+ },+ ],+ };+}++function OtherComponents({+ serviceSlug,+ serviceName,+ currentSlug,+}: {+ serviceSlug: string;+ serviceName: string;+ currentSlug: string;+}) {+ // days:1 — this sibling nav only uses slug/name, so fetch the minimum history.+ const { data } = api.externalService.components.useQuery({+ slug: serviceSlug,+ days: 1,+ });+ const others =+ data?.components.filter((c) => c.slug !== currentSlug).slice(0, 12) ?? [];+ if (others.length === 0) return null;++ return (+ <>+ <h2>Other {serviceName} components</h2>+ <div className="not-prose flex flex-wrap gap-2">+ {others.map((c) => (+ <a+ key={c.slug}+ href={`/status/${serviceSlug}/${c.slug}`}+ className="inline-flex rounded-none border px-2.5 py-0.5 text-sm hover:bg-muted"+ >+ {c.name}+ </a>+ ))}+ </div>+ </>+ );+}++export function ComponentDetail({+ serviceSlug,+ componentSlug,+ days,+}: {+ serviceSlug: string;+ componentSlug: string;+ days: number;+}) {+ const [data] = api.externalService.component.useSuspenseQuery({+ serviceSlug,+ componentSlug,+ days,+ });++ if (!data.found || !data.service || !data.component) return null;+ const { service, component, history, incidents } = data;++ const fullName = `${service.name} ${component.name}`;+ const answer = answerFor({+ fullName,+ indicator: component.indicator,+ status: component.status,+ stale: component.stale,+ });++ const serviceUrl = `${BASE_URL}/status/${service.slug}`;+ const componentUrl = `${serviceUrl}/${component.slug}`;+ const ld = jsonLd({+ serviceName: service.name,+ componentName: component.name,+ serviceUrl,+ componentUrl,+ 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"),+ }}+ />++ <nav className="not-prose mb-4 text-muted-foreground text-sm">+ <a className="hover:underline" href="/status">+ External Status+ </a>+ {" / "}+ <a className="hover:underline" href={`/status/${service.slug}`}>+ {service.name}+ </a>+ {" / "}+ <span className="text-foreground">{component.name}</span>+ </nav>++ <h1>+ Is {service.name} {component.name} down?+ </h1>+ <p>+ {answer} Below you'll find the live {component.name} status, uptime over+ the last {days} days, and recent incidents affecting {component.name}.+ </p>++ <div className="not-prose flex flex-wrap items-center gap-6">+ <ExternalServicePill+ indicator={component.indicator}+ status={component.status}+ statusMessage={component.description ?? undefined}+ />+ {component.lastSeenAt > 0 ? (+ <span className="text-muted-foreground text-sm">+ Last updated {formatRelative(component.lastSeenAt)}+ {component.stale ? (+ <span className="ml-1 inline-flex px-2 py-0.5 text-warning text-xs">+ (stale)+ </span>+ ) : null}+ </span>+ ) : null}+ <a className="text-sm underline" href={`/status/${service.slug}`}>+ ← {service.name} status+ </a>+ <a+ className="text-sm underline"+ href={service.statusPageUrl}+ target="_blank"+ rel="noopener noreferrer"+ >+ Upstream status page+ </a>+ </div>++ {component.description ? <p>{component.description}</p> : null}++ <h2>+ {component.name} uptime — last {days} days+ </h2>+ <div className="not-prose">+ <HistoryBars daily={history} days={days} />+ </div>++ <h2>{component.name} recent incidents</h2>+ {incidents.length === 0 ? (+ <p className="text-muted-foreground">+ No incidents affecting {component.name} in the recent period.+ </p>+ ) : (+ <Grid cols={1} className="not-prose">+ {incidents.map((inc) => {+ const started = formatTimestamp(inc.startedAt ?? inc.createdAt);+ const resolved = formatTimestamp(inc.resolvedAt ?? null);+ const link =+ inc.shortlink ?? `${service.statusPageUrl}/incidents/${inc.id}`;+ return (+ <ContentBoxLink+ key={inc.id}+ href={link}+ className="flex flex-col gap-1"+ >+ <div className="flex items-center justify-between gap-3">+ <ContentBoxTitle className="m-0!">{inc.name}</ContentBoxTitle>+ <span+ className={`inline-flex items-center rounded-none border px-2.5 py-0.5 font-medium text-xs ${impactClass(inc.impact)}`}+ >+ {inc.impact === "none"+ ? "incident"+ : inc.impact ?? "incident"}+ </span>+ </div>+ <ContentBoxDescription className="m-0! text-sm">+ {started ? <>Started {started}</> : null}+ {started && resolved ? " · " : null}+ {resolved ? <>Resolved {resolved}</> : null}+ </ContentBoxDescription>+ </ContentBoxLink>+ );+ })}+ </Grid>+ )}++ <OtherComponents+ serviceSlug={service.slug}+ serviceName={service.name}+ currentSlug={component.slug}+ />+ </section>+ );+}diff --git a/apps/web/src/app/(landing)/status/[id]/[component]/page.tsx b/apps/web/src/app/(landing)/status/[id]/[component]/page.tsxnew file mode 100644index 000000000..5fc77dd1e--- /dev/null+++ b/apps/web/src/app/(landing)/status/[id]/[component]/page.tsx@@ -0,0 +1,130 @@+import type { Metadata } from "next";+import { notFound, permanentRedirect } from "next/navigation";+import { Suspense } from "react";++import { ButtonLink } from "@/content/mdx-components/button-link";+import { CustomLink } from "@/content/mdx-components/custom-link";+import { cachedGetExternalComponentBySlug } from "@/lib/external-service-cache";+import {+ APP_URL,+ BASE_URL,+ defaultMetadata,+ ogMetadata,+ twitterMetadata,+} from "@/lib/metadata/shared-metadata";+import { HydrateClient, api } from "@/trpc/rq-server";++import {+ ContentBoxContainer,+ ContentBoxDescription,+ ContentBoxTitle,+} from "../../../content-box";+import { ComponentDetail } from "./component-detail";++export const dynamic = "force-dynamic";++const HISTORY_DAYS = 45;++type RouteParams = { id: string; component: string };++export async function generateMetadata(args: {+ params: Promise<RouteParams>;+}): Promise<Metadata> {+ const { id, component: componentParam } = await args.params;+ const { service, component } = await cachedGetExternalComponentBySlug(+ id,+ componentParam,+ );+ if (!service || !component) {+ return { ...defaultMetadata, title: "Not Found" };+ }++ const fullName = `${service.name} ${component.name}`;+ const title = `Is ${fullName} Down? ${fullName} Status & History`;+ const description = `Is ${component.name} (${service.name}) down right now? Check the live status, uptime over the last ${HISTORY_DAYS} days, and recent incidents for ${component.name} tracked by OpenStatus.`;+ const canonicalUrl = `${BASE_URL}/status/${service.slug}/${component.slug}`;+ const ogImage = `${BASE_URL}/api/og/external-service?slug=${encodeURIComponent(service.slug)}&component=${encodeURIComponent(component.slug)}`;+ const indexable = service.deletedAt == null && !component.stale;++ return {+ ...defaultMetadata,+ title,+ description,+ alternates: { canonical: canonicalUrl },+ robots: { index: indexable, follow: true },+ openGraph: {+ ...ogMetadata,+ title,+ description,+ url: canonicalUrl,+ images: [ogImage],+ },+ twitter: { ...twitterMetadata, title, description, images: [ogImage] },+ };+}++export default async function Page(args: { params: Promise<RouteParams> }) {+ const { id, component: componentParam } = await args.params;+ const { service, component } = await cachedGetExternalComponentBySlug(+ id,+ componentParam,+ );+ if (!service || !component) notFound();++ if (service.slug !== id) {+ permanentRedirect(`/status/${service.slug}/${componentParam}`);+ }+ if (component.slug !== componentParam) {+ permanentRedirect(`/status/${service.slug}/${component.slug}`);+ }++ await api.externalService.component.prefetch({+ serviceSlug: service.slug,+ componentSlug: component.slug,+ days: HISTORY_DAYS,+ });++ return (+ <section className="prose dark:prose-invert mb-12 max-w-none">+ <ContentBoxContainer className="not-prose my-6 px-4 py-2 text-sm">+ <CustomLink+ href={`${APP_URL}?ref=status-component-top`}+ className="font-medium underline-offset-4 hover:underline"+ >+ Catch downtime instantly and keep your users in the loop with+ OpenStatus →+ </CustomLink>+ </ContentBoxContainer>++ <HydrateClient>+ <Suspense+ fallback={+ <section className="prose dark:prose-invert mb-12 max-w-none">+ <p className="text-muted-foreground">+ Loading {service.name} {component.name} status…+ </p>+ </section>+ }+ >+ <ComponentDetail+ serviceSlug={service.slug}+ componentSlug={component.slug}+ days={HISTORY_DAYS}+ />+ </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?+ </ContentBoxTitle>+ <ContentBoxDescription className="m-0! text-sm">+ Every service needs a status page. Run yours with OpenStatus.+ </ContentBoxDescription>+ <ButtonLink href={`${APP_URL}?ref=status-component-bottom`}>+ Create your status page+ </ButtonLink>+ </ContentBoxContainer>+ </section>+ );+}diff --git a/apps/web/src/app/(landing)/status/[id]/page.tsx b/apps/web/src/app/(landing)/status/[id]/page.tsxindex 51e894f3b..10689ef6a 100644--- a/apps/web/src/app/(landing)/status/[id]/page.tsx+++ b/apps/web/src/app/(landing)/status/[id]/page.tsx@@ -82,6 +82,10 @@ export default async function Page(args: { params: Promise<RouteParams> }) {days: HISTORY_DAYS,}),api.externalService.incidents.prefetch({ slug: service.slug }),+ api.externalService.components.prefetch({+ slug: service.slug,+ days: HISTORY_DAYS,+ }),]);return (diff --git a/apps/web/src/app/(landing)/status/[id]/service-components.tsx b/apps/web/src/app/(landing)/status/[id]/service-components.tsxnew file mode 100644index 000000000..bbaf6a574--- /dev/null+++ b/apps/web/src/app/(landing)/status/[id]/service-components.tsx@@ -0,0 +1,35 @@+"use client";++import { api } from "@/trpc/rq-client";++import { ExternalServiceComponents } from "../external-service-components";++export function ServiceComponents({+ slug,+ serviceName,+ days,+}: {+ slug: string;+ serviceName: string;+ days: number;+}) {+ const [data] = api.externalService.components.useSuspenseQuery({+ slug,+ days,+ });++ if (!data.supported || data.components.length === 0) return null;++ return (+ <>+ <h2>{serviceName} components</h2>+ <div className="not-prose">+ <ExternalServiceComponents+ components={data.components}+ days={days}+ hrefBase={`/status/${slug}`}+ />+ </div>+ </>+ );+}diff --git a/apps/web/src/app/(landing)/status/[id]/service-detail.tsx b/apps/web/src/app/(landing)/status/[id]/service-detail.tsxindex fcf83a1e5..78aa78aae 100644--- a/apps/web/src/app/(landing)/status/[id]/service-detail.tsx+++ b/apps/web/src/app/(landing)/status/[id]/service-detail.tsx@@ -9,6 +9,7 @@ import { ExternalServicePill } from "../external-service-pill";import { formatRelative, getStatusAnswer, isStale } from "../utils";import { HistoryBars } from "./history-bars";import { Incidents } from "./incidents";+import { ServiceComponents } from "./service-components";function jsonLd(args: {serviceName: string;@@ -139,6 +140,14 @@ export function ServiceDetail({ slug, days }: { slug: string; days: number }) {<HistoryBars daily={history} days={days} /></div>+ <Suspense fallback={null}>+ <ServiceComponents+ slug={service.slug}+ serviceName={service.name}+ days={days}+ />+ </Suspense>+<h2>{service.name} recent incidents</h2><Suspensefallback={diff --git a/apps/web/src/app/(landing)/status/external-service-components.tsx b/apps/web/src/app/(landing)/status/external-service-components.tsxnew file mode 100644index 000000000..c4c9166b3--- /dev/null+++ b/apps/web/src/app/(landing)/status/external-service-components.tsx@@ -0,0 +1,294 @@+"use client";++import { StatusBar } from "@openstatus/ui/components/blocks/status-bar";+import type {+ StatusBarData,+ StatusType,+} from "@openstatus/ui/components/blocks/status.types";+import { systemStatusLabels } from "@openstatus/ui/components/blocks/status.utils";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@openstatus/ui/components/ui/collapsible";+import { cn } from "@openstatus/ui/lib/utils";+import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";+import { useState } from "react";+import { ExternalServicePill } from "./external-service-pill";++export type ComponentHistoryDay = {+ day: string;+ worstIndicator: string;+ hadMaintenance: number;+ snapshotCount: number;+};++export type ExternalServiceComponentItem = {+ id: number;+ slug: string;+ name: string;+ description?: string | null;+ groupName?: string | null;+ position: number;+ indicator: string;+ status: string;+ history: ComponentHistoryDay[];+};++export type ExternalServiceComponentsProps = {+ components: ExternalServiceComponentItem[];+ days: number;+ // When set, each component name links to `${hrefBase}/${slug}`.+ hrefBase?: string;+};++// A lone, short section is worth showing open by default; multi-group or long+// lists (e.g. Cloudflare) stay collapsed so the page doesn't run away.+const AUTO_EXPAND_MAX_COMPONENTS = 10;++const INDICATOR_SEVERITY: Record<string, number> = {+ none: 0,+ minor: 1,+ major: 2,+ critical: 3,+};++function severityOf(indicator: string): number {+ return INDICATOR_SEVERITY[indicator] ?? -1;+}++function isIssue(component: ExternalServiceComponentItem): boolean {+ return severityOf(component.indicator) > 0;+}++// Maintenance maps to indicator "none" (severity 0), so it is not an issue —+// count it separately or a maintenance-only section reads "All operational".+function isMaintenance(component: ExternalServiceComponentItem): boolean {+ return component.status === "under_maintenance";+}++function indicatorToStatusType(args: {+ worstIndicator: string;+ hadMaintenance: number;+}): StatusType {+ if (args.hadMaintenance) return "info";+ switch (args.worstIndicator) {+ case "none":+ return "success";+ case "minor":+ return "degraded";+ case "major":+ case "critical":+ return "error";+ default:+ return "empty";+ }+}++function buildSeries(+ history: ComponentHistoryDay[],+ days: number,+): StatusBarData[] {+ const byDay = new Map<string, ComponentHistoryDay>();+ for (const r of history) byDay.set(r.day.slice(0, 10), r);++ const out: StatusBarData[] = [];+ const today = new Date();+ today.setUTCHours(0, 0, 0, 0);+ for (let i = days - 1; i >= 0; i--) {+ const date = new Date(today);+ date.setUTCDate(today.getUTCDate() - i);+ const iso = date.toISOString().slice(0, 10);+ const row = byDay.get(iso);+ const status: StatusType = row+ ? indicatorToStatusType({+ worstIndicator: row.worstIndicator,+ hadMaintenance: row.hadMaintenance,+ })+ : "empty";+ out.push({+ day: iso,+ bar: [{ status, height: 100 }],+ card: [{ status, value: systemStatusLabels[status].short }],+ events: [],+ });+ }+ return out;+}++type Section = {+ key: string;+ // null only for the ungrouped bucket; the label shown depends on whether it+ // is the page's sole section.+ name: string | null;+ components: ExternalServiceComponentItem[];+ worst: number;+};++function buildSections(components: ExternalServiceComponentItem[]): Section[] {+ const byGroup = new Map<string | null, ExternalServiceComponentItem[]>();+ for (const c of components) {+ const key = c.groupName ?? null;+ const list = byGroup.get(key);+ if (list) list.push(c);+ else byGroup.set(key, [c]);+ }++ const sections: Section[] = [];+ for (const [name, items] of byGroup) {+ const sorted = [...items].sort(+ (a, b) =>+ severityOf(b.indicator) - severityOf(a.indicator) ||+ a.position - b.position ||+ a.name.localeCompare(b.name),+ );+ sections.push({+ // Prefix grouped keys so a real group literally named like the ungrouped+ // sentinel can't collide (grouped keys always start with "group:").+ key: name === null ? "ungrouped" : `group:${name}`,+ name,+ components: sorted,+ worst: sorted.reduce((m, c) => Math.max(m, severityOf(c.indicator)), 0),+ });+ }++ // Named groups worst-first; the ungrouped bucket always trails.+ sections.sort((a, b) => {+ if (a.name === null) return 1;+ if (b.name === null) return -1;+ return b.worst - a.worst || a.name.localeCompare(b.name);+ });+ return sections;+}++function sectionLabel(section: Section, soleSection: boolean): string {+ if (section.name !== null) return section.name;+ return soleSection ? "Components" : "Other";+}++function ComponentRow({+ component,+ days,+ hrefBase,+}: {+ component: ExternalServiceComponentItem;+ days: number;+ hrefBase?: string;+}) {+ const series = buildSeries(component.history, days);+ return (+ <div className="flex flex-col gap-1 border-border/50 border-b py-2 last:border-b-0">+ <div className="flex flex-wrap items-center justify-between gap-2">+ {hrefBase ? (+ <a+ className="font-medium text-sm hover:underline"+ href={`${hrefBase}/${component.slug}`}+ >+ {component.name}+ </a>+ ) : (+ <span className="font-medium text-sm">{component.name}</span>+ )}+ <ExternalServicePill+ indicator={component.indicator}+ status={component.status}+ statusMessage={component.description ?? undefined}+ />+ </div>+ <div className="[&_[data-slot=status-bar-item]>div>div]:rounded-none [&_[data-slot=status-bar-item]>div]:rounded-none [&_[data-slot=status-bar-item]]:rounded-none">+ <StatusBar data={series} />+ </div>+ </div>+ );+}++function SectionBlock({+ section,+ soleSection,+ days,+ hrefBase,+}: {+ section: Section;+ soleSection: boolean;+ days: number;+ hrefBase?: string;+}) {+ const issues = section.components.filter(isIssue).length;+ const maintenance = section.components.filter(isMaintenance).length;+ const [open, setOpen] = useState(+ soleSection && section.components.length <= AUTO_EXPAND_MAX_COMPONENTS,+ );+ const label = sectionLabel(section, soleSection);++ return (+ <Collapsible+ open={open}+ onOpenChange={setOpen}+ className="border border-border"+ >+ <CollapsibleTrigger className="flex w-full items-center justify-between gap-3 px-3 py-2 text-left">+ <span className="flex items-center gap-2 font-medium text-sm">+ {open ? (+ <ChevronDownIcon className="size-4 shrink-0" />+ ) : (+ <ChevronRightIcon className="size-4 shrink-0" />+ )}+ {label}+ <span className="text-muted-foreground">+ ({section.components.length})+ </span>+ </span>+ <span+ className={cn(+ "shrink-0 text-xs",+ issues > 0+ ? "text-destructive"+ : maintenance > 0+ ? "text-info"+ : "text-muted-foreground",+ )}+ >+ {issues > 0+ ? `${issues} issue${issues === 1 ? "" : "s"}`+ : maintenance > 0+ ? `${maintenance} under maintenance`+ : "All operational"}+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent className="px-3 pb-2">+ {section.components.map((c) => (+ <ComponentRow+ key={c.id}+ component={c}+ days={days}+ hrefBase={hrefBase}+ />+ ))}+ </CollapsibleContent>+ </Collapsible>+ );+}++export function ExternalServiceComponents({+ components,+ days,+ hrefBase,+}: ExternalServiceComponentsProps) {+ if (components.length === 0) return null;+ const sections = buildSections(components);+ const soleSection = sections.length === 1;++ return (+ <div className="flex flex-col gap-2">+ {sections.map((section) => (+ <SectionBlock+ key={section.key}+ section={section}+ soleSection={soleSection}+ days={days}+ hrefBase={hrefBase}+ />+ ))}+ </div>+ );+}diff --git a/apps/web/src/app/(landing)/status/external-status-grid.tsx b/apps/web/src/app/(landing)/status/external-status-grid.tsxindex 72e1c9221..660d36161 100644--- a/apps/web/src/app/(landing)/status/external-status-grid.tsx+++ b/apps/web/src/app/(landing)/status/external-status-grid.tsx@@ -3,11 +3,12 @@import { useQueryState } from "nuqs";import { useMemo } from "react";+import { ExternalServicePill } from "./external-service-pill";+import { Grid } from "@/content/mdx-components/grid";import { api } from "@/trpc/rq-client";import { ContentBoxLink } from "../content-box";-import { ExternalServicePill } from "./external-service-pill";import { filterServices } from "./filter-services";import { qParser } from "./search-params";diff --git a/apps/web/src/app/api/og/external-service/route.tsx b/apps/web/src/app/api/og/external-service/route.tsxindex 0f81f7269..52d494808 100644--- a/apps/web/src/app/api/og/external-service/route.tsx+++ b/apps/web/src/app/api/og/external-service/route.tsx@@ -5,6 +5,7 @@ import { OSTinybird, safePipeData } from "@openstatus/tinybird";import { isStale } from "@/app/(landing)/status/utils";import { env } from "@/env";import {+ cachedGetExternalComponentBySlug,cachedGetExternalServiceBySlug,cachedListExternalServices,} from "@/lib/external-service-cache";@@ -19,8 +20,8 @@ const INDEX_TITLE = "External Status";const INDEX_DESCRIPTION ="Check if your external providers are working properly";-// Mirrors getPillStyle in (landing)/status/external-service-pill.tsx so the OG-// label matches the on-page pill.+// Mirrors getPillStyle in (landing)/status/external-service-pill so the OG label+// matches the on-page pill.function getStatus(args: { indicator: string; status: string }): {label: string;bg: string;@@ -93,48 +94,74 @@ export async function GET(req: Request) {const { searchParams } = new URL(req.url);const slug = searchParams.get("slug") || undefined;-- const service = slug ? await cachedGetExternalServiceBySlug(slug) : undefined;+ const componentParam = searchParams.get("component") || undefined;let category: string;let categoryDot: string | undefined;let title: string;let description: string;let footer: string;+ let isDetail = false;- if (!service) {- const services = await cachedListExternalServices();- category = "external status";- title = INDEX_TITLE;- description = `${services.length} providers monitored — ${INDEX_DESCRIPTION}`;- footer = FOOTER;- } else {- const aliasSlugs = Array.isArray(service.aliases) ? service.aliases : [];- const slugChain = [service.slug, ...aliasSlugs];-- const tb = new OSTinybird(env.TINY_BIRD_API_KEY);- const latestRes = await safePipeData(- tb.externalStatusLatest({ ids: slugChain }),- "externalStatusLatest (og)",- );- 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 fetchedAt = latest?.last_fetched_at ?? 0;- const stale = fetchedAt === 0 || isStale(fetchedAt);- const content = stale+ const componentResult =+ slug && componentParam+ ? await cachedGetExternalComponentBySlug(slug, componentParam)+ : null;++ if (componentResult?.service && componentResult.component) {+ const { service, component } = componentResult;+ isDetail = true;+ const content = component.stale? UNKNOWN: getStatus({- indicator: latest?.indicator ?? "",- status: latest?.status ?? "",+ indicator: component.indicator,+ status: component.status,});-category = content.label;categoryDot = content.bg;- title = `Is ${service.name} down?`;+ title = `Is ${service.name} ${component.name} down?`;description = "";- footer = `${FOOTER}/${service.slug}`;+ footer = `${FOOTER}/${service.slug}/${component.slug}`;+ } else {+ const service = slug+ ? await cachedGetExternalServiceBySlug(slug)+ : undefined;++ if (!service) {+ const services = await cachedListExternalServices();+ category = "external status";+ title = INDEX_TITLE;+ description = `${services.length} providers monitored — ${INDEX_DESCRIPTION}`;+ footer = FOOTER;+ } else {+ isDetail = true;+ const aliasSlugs = Array.isArray(service.aliases) ? service.aliases : [];+ const slugChain = [service.slug, ...aliasSlugs];++ const tb = new OSTinybird(env.TINY_BIRD_API_KEY);+ const latestRes = await safePipeData(+ tb.externalStatusLatest({ ids: slugChain }),+ "externalStatusLatest (og)",+ );+ 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 fetchedAt = latest?.last_fetched_at ?? 0;+ const stale = fetchedAt === 0 || isStale(fetchedAt);+ const content = stale+ ? UNKNOWN+ : getStatus({+ indicator: latest?.indicator ?? "",+ status: latest?.status ?? "",+ });++ category = content.label;+ categoryDot = content.bg;+ title = `Is ${service.name} down?`;+ description = "";+ footer = `${FOOTER}/${service.slug}`;+ }}return new ImageResponse(@@ -150,7 +177,7 @@ export async function GET(req: Request) {<div tw={cn("rounded-full h-5 w-5 mr-2", categoryDot)} />) : null}<p>{category}</p>]- {service+ {isDetail? ` | ${new Date().toLocaleDateString(undefined, {year: "numeric",month: "long",diff --git a/apps/web/src/app/sitemap.ts b/apps/web/src/app/sitemap.tsindex 54db171b8..cd94b6f4b 100644--- a/apps/web/src/app/sitemap.ts+++ b/apps/web/src/app/sitemap.ts@@ -11,7 +11,10 @@ import {getUnrelatedPages,getUseCasePages,} from "@/content/utils";-import { cachedListExternalServices } from "@/lib/external-service-cache";+import {+ cachedListExternalComponentsBySlug,+ cachedListExternalServices,+} from "@/lib/external-service-cache";import type { MetadataRoute } from "next";export const revalidate = 3600;@@ -49,6 +52,22 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {},];+ const componentEntriesByService = await Promise.all(+ externalServices+ .filter((s) => s.deletedAt == null)+ .map(async (s) => {+ const { components } = await cachedListExternalComponentsBySlug(s.slug);+ return components.map((c) => ({+ url: `https://www.openstatus.dev/status/${s.slug}/${c.slug}`,+ lastModified: c.lastSeenAt.toISOString().slice(0, 10),+ changeFrequency: "hourly" as const,+ priority: 0.6,+ }));+ }),+ );+ const externalServiceComponentEntries: MetadataRoute.Sitemap =+ componentEntriesByService.flat();+const blogs = allPosts.map((post) => ({url: `https://www.openstatus.dev/blog/${post.slug}`,lastModified: post.metadata.publishedAt, // date format should be YYYY-MM-DD@@ -222,5 +241,6 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {...customersIndex,...externalServicesIndex,...externalServiceEntries,+ ...externalServiceComponentEntries,];}diff --git a/apps/web/src/lib/external-service-cache.ts b/apps/web/src/lib/external-service-cache.tsindex 8350fc3f3..d092b2e99 100644--- a/apps/web/src/lib/external-service-cache.ts+++ b/apps/web/src/lib/external-service-cache.ts@@ -2,6 +2,10 @@ import {getExternalServiceBySlug,listExternalServices,} from "@openstatus/services/external-service";+import {+ getExternalComponentBySlug,+ listExternalComponentsBySlug,+} from "@openstatus/services/external-service-component";import { unstable_cache } from "next/cache";const REVALIDATE_SECONDS = 60;@@ -18,3 +22,16 @@ export const cachedGetExternalServiceBySlug = unstable_cache(["external-services:by-slug"],{ revalidate: REVALIDATE_SECONDS, tags: [TAG] },);++export const cachedListExternalComponentsBySlug = unstable_cache(+ async (slug: string) => listExternalComponentsBySlug({ slug }),+ ["external-service-components:by-service"],+ { revalidate: REVALIDATE_SECONDS, tags: [TAG] },+);++export const cachedGetExternalComponentBySlug = unstable_cache(+ async (serviceSlug: string, componentSlug: string) =>+ getExternalComponentBySlug({ serviceSlug, componentSlug }),+ ["external-service-components:by-slug"],+ { revalidate: REVALIDATE_SECONDS, tags: [TAG] },+);diff --git a/apps/workflows/src/cron/external-status.ts b/apps/workflows/src/cron/external-status.tsindex 934d9326b..a39e4e04e 100644--- a/apps/workflows/src/cron/external-status.ts+++ b/apps/workflows/src/cron/external-status.ts@@ -1,12 +1,17 @@import { getLogger } from "@logtape/logtape";import { listExternalServices } from "@openstatus/services/external-service";import type { ExternalServiceRow } from "@openstatus/services/external-service";+import {+ type UpsertExternalComponentInput,+ upsertExternalComponentsForService,+} from "@openstatus/services/external-service-component";import {type UpsertExternalIncidentInput,upsertExternalIncidentsForService,} from "@openstatus/services/external-service-incident";import { FetchError, fetchers } from "@openstatus/status-fetcher";import type {+ NormalizedComponent,NormalizedIncident,StatusFetcher,StatusPageEntry,@@ -24,7 +29,7 @@ const logger = getLogger(["workflow", "external-status"]);const tb = new OSTinybird(env().TINY_BIRD_API_KEY);-// 10 per phase × 2 phases = peak 20 concurrent HTTP requests upstream; keeps+// 10 per phase × 3 phases = peak 30 concurrent HTTP requests upstream; keeps// Atlassian/Incident.io CDNs comfortable while still parallelising heavily.const PHASE_CONCURRENCY = 10;@@ -80,10 +85,33 @@ function toUpsertInput(startedAt: incident.startedAt,createdAt: incident.createdAt,resolvedAt: incident.resolvedAt,+ affectedComponentIds: incident.affectedComponentIds,raw: incident.raw,};}+type ComponentSnapshot = {+ component_id: string;+ external_service_id: number;+ indicator: string;+ status: string;+ fetched_at: number;+};++function toComponentUpsertInput(+ component: NormalizedComponent,+): UpsertExternalComponentInput {+ return {+ upstreamComponentId: component.upstreamComponentId,+ name: component.name,+ description: component.description,+ groupName: component.groupName,+ position: component.position,+ indicator: component.severity,+ status: component.status,+ };+}+type PhaseCounts = {successCount: number;failureCount: number;@@ -101,6 +129,11 @@ type IncidentPhaseOutcome =| { kind: "skip"; slug: string }| { kind: "fail"; slug: string; reason: string };+type ComponentPhaseOutcome =+ | { kind: "ok"; slug: string; snapshots: ComponentSnapshot[] }+ | { kind: "skip"; slug: string }+ | { kind: "fail"; slug: string; reason: string };+type Triplet = {row: ExternalServiceRow;entry: StatusPageEntry;@@ -193,6 +226,73 @@ function runIncidentPhase();}+function runComponentPhase(+ triplets: Triplet[],+ tickStartedAt: Date,+ fetchedAt: number,+): Effect.Effect<ComponentPhaseOutcome[]> {+ return Effect.forEach(+ triplets,+ ({ row, entry, fetcher }) => {+ if (!fetcher || !fetcher.fetchComponents) {+ return Effect.succeed<ComponentPhaseOutcome>({+ kind: "skip",+ slug: entry.id,+ });+ }+ return fetcher.fetchComponents(entry).pipe(+ Effect.flatMap((components) =>+ Effect.tryPromise({+ try: () =>+ upsertExternalComponentsForService({+ ctx: { db },+ externalServiceId: row.id,+ components: components.map(toComponentUpsertInput),+ now: tickStartedAt,+ }),+ catch: (e) =>+ new FetchError({+ url: entry.status_page_url,+ fetcherName: fetcher.name,+ entryId: entry.id,+ cause: e instanceof Error ? e : new Error(String(e)),+ }),+ }).pipe(+ Effect.map((result): ComponentPhaseOutcome => {+ // History rows key on our PK, so the upstream→PK map from the+ // upsert turns each normalized component into a snapshot.+ const byUpstream = new Map(+ components.map((c) => [c.upstreamComponentId, c]),+ );+ const snapshots: ComponentSnapshot[] = [];+ for (const upserted of result.upserted) {+ const c = byUpstream.get(upserted.upstreamComponentId);+ if (!c) continue;+ snapshots.push({+ component_id: String(upserted.id),+ external_service_id: row.id,+ indicator: c.severity,+ status: c.status,+ fetched_at: fetchedAt,+ });+ }+ return { kind: "ok", slug: entry.id, snapshots };+ }),+ ),+ ),+ Effect.catchAll((err: FetchError) =>+ Effect.succeed<ComponentPhaseOutcome>({+ kind: "fail",+ slug: entry.id,+ reason: err.message,+ }),+ ),+ );+ },+ { concurrency: PHASE_CONCURRENCY },+ );+}+function summarizeStatus(outcomes: StatusPhaseOutcome[]): {counts: PhaseCounts;snapshots: Snapshot[];@@ -254,6 +354,39 @@ function summarizeIncidents(outcomes: IncidentPhaseOutcome[]): PhaseCounts {};}+function summarizeComponents(outcomes: ComponentPhaseOutcome[]): {+ counts: PhaseCounts;+ snapshots: ComponentSnapshot[];+} {+ const snapshots: ComponentSnapshot[] = [];+ let successCount = 0;+ let failureCount = 0;+ let skippedCount = 0;+ for (const o of outcomes) {+ if (o.kind === "ok") {+ successCount++;+ snapshots.push(...o.snapshots);+ } else if (o.kind === "skip") {+ skippedCount++;+ } else {+ failureCount++;+ logger.warn(+ "external-status components: failed for slug={slug}: {reason}",+ { slug: o.slug, reason: o.reason },+ );+ }+ }+ return {+ counts: {+ successCount,+ failureCount,+ skippedCount,+ total: outcomes.length,+ },+ snapshots,+ };+}+function buildTriplets(services: ExternalServiceRow[]): Triplet[] {return services.map((row) => {const entry = toStatusPageEntry(row);@@ -265,30 +398,41 @@ function buildTriplets(services: ExternalServiceRow[]): Triplet[] {export async function runExternalStatusTick(): Promise<{status: PhaseCounts;incidents: PhaseCounts;+ components: PhaseCounts;}> {const services = await listExternalServices({ ctx: { db } });const triplets = buildTriplets(services);const tickStartedAt = new Date();- const [statusOutcomes, incidentOutcomes] = await Effect.runPromise(- Effect.all(- [- runStatusPhase(triplets, tickStartedAt.getTime()),- runIncidentPhase(triplets, tickStartedAt),- ],- { concurrency: "unbounded" },- ),- );+ // The three phases are intentionally independent: each hits a different+ // upstream endpoint and store, so a failed status fetch must not suppress a+ // service's components (or vice versa). A tick can therefore persist+ // component history for a service whose status snapshot failed that tick.+ const [statusOutcomes, incidentOutcomes, componentOutcomes] =+ await Effect.runPromise(+ Effect.all(+ [+ runStatusPhase(triplets, tickStartedAt.getTime()),+ runIncidentPhase(triplets, tickStartedAt),+ runComponentPhase(triplets, tickStartedAt, tickStartedAt.getTime()),+ ],+ { concurrency: "unbounded" },+ ),+ );const status = summarizeStatus(statusOutcomes);const incidents = summarizeIncidents(incidentOutcomes);+ const components = summarizeComponents(componentOutcomes);if (status.snapshots.length > 0) {await tb.publishExternalStatus(status.snapshots);}+ if (components.snapshots.length > 0) {+ await tb.publishExternalStatusComponent(components.snapshots);+ }- return { status: status.counts, incidents };+ return { status: status.counts, incidents, components: components.counts };}export async function handleExternalStatusCron(c: Context) {@@ -309,7 +453,7 @@ export async function handleExternalStatusCron(c: Context) {Effect.tap((res) =>Effect.sync(() => {logger.info(- "external-status tick complete: status={statusOk}/{statusTotal} ({statusFail} failures, {statusSkip} skipped), incidents={incOk}/{incTotal} ({incFail} failures, {incSkip} skipped)",+ "external-status tick complete: status={statusOk}/{statusTotal} ({statusFail} failures, {statusSkip} skipped), incidents={incOk}/{incTotal} ({incFail} failures, {incSkip} skipped), components={compOk}/{compTotal} ({compFail} failures, {compSkip} skipped)",{statusOk: res.status.successCount,statusTotal: res.status.total,@@ -319,6 +463,10 @@ export async function handleExternalStatusCron(c: Context) {incTotal: res.incidents.total,incFail: res.incidents.failureCount,incSkip: res.incidents.skippedCount,+ compOk: res.components.successCount,+ compTotal: res.components.total,+ compFail: res.components.failureCount,+ compSkip: res.components.skippedCount,},);void cronCompleted();diff --git a/docs/adr/0007-store-external-service-components.md b/docs/adr/0007-store-external-service-components.mdnew file mode 100644index 000000000..b36d26ae6--- /dev/null+++ b/docs/adr/0007-store-external-service-components.md@@ -0,0 +1,136 @@+---+status: "accepted"+date: 2026-05-28+decision-makers: openstatus maintainers+---++# Store external-service components in Turso, their status history in Tinybird++## Context and Problem Statement++openstatus polls a public directory of third-party services (Atlassian,+Incident.io, …) on a cron. Each one's status page exposes not just a page-level+status but a list of **components** — Vercel's per-region edge entries, GitHub's+Actions / Pages sub-systems, and so on. Until now the cron kept only the+page-level status (a Tinybird snapshot) and the incident list (Turso, ADR-0006);+the components array was discarded.++We want to surface a per-component breakdown on `/status/<id>` with the same+45-day history bar the page-level status already has, and — later — let+customers embed a single external component (e.g. AWS `us-east-1`) onto their own+status page. A component has two faces: a **roster identity** (name, group,+appears/disappears) and a **status that changes over time**. Where does each+face live — Turso, Tinybird, or both?++## Decision Drivers++- ADR-0005 split the stores: a mutable, low-volume, relationally-read entity is a+ Turso entity; a high-volume, append-only time-series is a Tinybird entity.+- ADR-0006 already applied that to incidents (Turso, upserted on a stable+ upstream id) — components are the same kind of mutable, low-volume, stable-id+ roster and should reuse that pattern.+- The page wants **two different reads**: "the current roster for this service"+ (a row-store, join-to-service read) and "45 days of status per component" (a+ time-window aggregation).+- A component can disappear upstream (a region retired); the model must cope+ without leaving ghosts on the page.+- The breakdown must be **reusable** by a future customer status-page embed, so a+ component needs a stable identity to reference and the rendering must be+ app-agnostic (ADR-0003).++## Considered Options++- All-Turso: roster in one table, a second table appending a status row per tick.+- All-Tinybird: append roster + status together, dedup current state on read.+- **Split**: roster + current status in Turso (upserted), status history in+ Tinybird (append-only), linked by the Turso primary key.++## Decision Outcome++Chosen option: "split". A Turso `external_service_component` table (FK to+`external_service`) is **upserted on `(external_service_id, upstream_component_id)`**+each tick and holds the roster plus the *current* status — the row-store read the+page and the future dashboard picker need. Per-tick component snapshots are+published to a Tinybird datasource `external_status_component__v0` with a daily+materialized view — the time-series read the 45-day bars need. Each store runs+its native read shape, exactly as ADR-0005 prescribes.++The Tinybird rows are **keyed by the Turso primary key** (`component_id` = the+integer `external_service_component.id`, as a string). The PK is stable across+upstream renames, so component history needs no service slug-chain, and the same+key serves the public page, the dashboard picker, and the future customer embed.+The **current status is read from Turso, not from a Tinybird "latest" endpoint** —+Turso already holds it on the roster row.++A vanished component is handled by a `last_seen_at` filter at read time (the page+renders only components seen within 24h); there is no soft-delete column and no+prune cron. Only providers that implement `fetchComponents` (Atlassian,+Incident.io — same `components.json` shape) participate; others are skipped.++### Consequences++- Good, because each read hits the store built for it, reusing the incidents+ upsert pattern (ADR-0006) and the page-status time-series pattern (ADR-0005).+- Good, because the integer PK is a stable, app-agnostic handle: the same id keys+ Turso, Tinybird, and any future customer-status-page reference.+- Good, because `last_seen_at` filtering self-heals when upstream adds or drops a+ component, with no extra cron.+- Bad, because a component's roster (Turso) and its history (Tinybird) are written+ in the same tick to two stores, linked only by id — no cross-store transaction.+- Bad, because the upsert trusts each provider's component id to be stable; a+ provider that recycles ids would collide rows.+- Bad, because Tinybird volume scales with component count (a ~40-region service+ writes 40 rows per tick), bounded by the 60-day raw TTL + the daily MV.++### Confirmation++Component write / read logic lives in+`packages/services/src/external-service-component/` (per ADR-0001), using the+directory's light `{ db }` context — no workspace scope, audit row, or+`requireScope`, because external services are a global, public, cron-driven+catalogue (as established for incidents in ADR-0006). The reusable breakdown UI is+a presentational block in `@openstatus/ui` (ADR-0003). Tests cover upsert+idempotency, the `last_seen_at` read filter, and the Atlassian group/status+normalisation.++## Pros and Cons of the Options++### All-Turso (roster + a status-history table)++- Good, because one store, foreign keys, and a single transaction per tick.+- Bad, because the status-history table is an append-only time-series — exactly+ the high-volume, time-window-aggregated shape ADR-0005 keeps out of Turso.+- Bad, because 45-day-per-component aggregation in SQLite contends with+ transactional traffic.++### All-Tinybird (append roster + status together)++- Good, because components arrive in the same tick as the page-status snapshots+ already going to Tinybird — one store.+- Bad, because the roster is mutable (name/group change, components vanish);+ append-only keeps every version, so "current roster" needs a dedup pipe.+- Bad, because "the current components for this service" is a row-store read, and+ there is no relational handle for the future customer embed to FK to.++### Split (Turso roster + Tinybird history)++- Good, because the natural key gives idempotent upserts and one current row per+ component, and the PK is a stable cross-store / cross-app handle.+- Good, because the relational "current roster" read and the columnar "45-day+ history" read each run on the right store.+- Bad, because it splits a component across two stores linked only by id.++## More Information++- Schema: `packages/db/src/schema/external_services/external_service_component.ts`.+- Services: `packages/services/src/external-service-component/` — `upsert`, `list`.+- Normalisation: `packages/status-fetcher` — `fetchComponents` on the Atlassian /+ Incident.io fetchers (`/api/v2/components.json`).+- Time-series: `packages/tinybird` — `external_status_component__v0`,+ `mv__external_status_component_daily__v0`, the history endpoint, and the+ `publishExternalStatusComponent` / `externalStatusComponentHistory` accessors.+- Cron: the component phase in `apps/workflows/src/cron/external-status.ts`.+- Read: the `components` procedure in `packages/api/src/router/externalService.ts`.+- UI: `packages/ui` — `external-service-pill` and `external-service-components`.+- Related: ADR-0005 (the store-split rule), ADR-0006 (the incidents precedent this+ reuses), ADR-0003 (shared UI), ADR-0001 (services-layer logic).diff --git a/docs/adr/README.md b/docs/adr/README.mdindex f8a0eb13e..0dee58f9a 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -18,6 +18,7 @@ today; ADRs explain how those conventions came to be.| [0004](0004-go-for-the-probing-tier.md) | Go for the probing tier | accepted || [0005](0005-turso-for-app-data-tinybird-for-time-series.md) | Turso for application data, Tinybird for time-series | accepted || [0006](0006-persist-external-incidents-in-turso.md) | Persist external-service incidents in Turso, not Tinybird | accepted |+| [0007](0007-store-external-service-components.md) | Store external-service components in Turso, their status history in Tinybird | accepted |## When to write an ADRdiff --git a/packages/api/src/router/externalService.ts b/packages/api/src/router/externalService.tsindex dbcb60864..da26185d6 100644--- a/packages/api/src/router/externalService.ts+++ b/packages/api/src/router/externalService.ts@@ -5,7 +5,15 @@ import {getExternalServiceBySlug,listExternalServices,} from "@openstatus/services/external-service";-import { listExternalIncidentsBySlug } from "@openstatus/services/external-service-incident";+import {+ getExternalComponentBySlug,+ listExternalComponentsBySlug,+} from "@openstatus/services/external-service-component";+import {+ type ExternalIncidentListItem,+ listExternalIncidentsByComponent,+ listExternalIncidentsBySlug,+} from "@openstatus/services/external-service-incident";import { OSTinybird } from "@openstatus/tinybird";import { env } from "../env";@@ -16,6 +24,10 @@ const tb = new OSTinybird(env.TINY_BIRD_API_KEY);const DEFAULT_HISTORY_DAYS = 45;const INCIDENTS_LIMIT = 5;+// Logging here uses `console.*`, not `@logtape/logtape`: this router runs on the+// Next.js Edge runtime and `@openstatus/api` (like the edge-safe `services`+// package) deliberately takes no logtape dependency. The logtape-based logger is+// for Node contexts such as the `apps/workflows` cron. Matches every sibling router.async function safeData<T>(promise: Promise<{ data: T[] }>,label: string,@@ -74,6 +86,69 @@ const incidentSchema = z.object({resolvedAt: z.string().nullable().optional(),});+const componentItemSchema = z.object({+ id: z.number(),+ slug: z.string(),+ name: z.string(),+ description: z.string().nullable(),+ groupName: z.string().nullable(),+ position: z.number(),+ indicator: z.string(),+ status: z.string(),+ history: z.array(historyRowSchema),+});++const componentDetailSchema = z.object({+ found: z.boolean(),+ service: z+ .object({ slug: z.string(), name: z.string(), statusPageUrl: z.string() })+ .nullable(),+ component: z+ .object({+ id: z.number(),+ slug: z.string(),+ name: z.string(),+ description: z.string().nullable(),+ groupName: z.string().nullable(),+ indicator: z.string(),+ status: z.string(),+ lastSeenAt: z.number(),+ stale: z.boolean(),+ })+ .nullable(),+ history: z.array(historyRowSchema),+ incidents: z.array(incidentSchema),+});++type HistoryTbRow = {+ day: string;+ worst_indicator: string;+ had_maintenance: number;+ snapshot_count: number;+};++function toHistoryRow(r: HistoryTbRow) {+ return {+ day: r.day,+ worstIndicator: r.worst_indicator,+ hadMaintenance: r.had_maintenance,+ snapshotCount: r.snapshot_count,+ };+}++function toIncidentDTO(i: ExternalIncidentListItem) {+ return {+ id: i.providerIncidentId,+ name: i.name,+ status: i.status,+ impact: i.impact ?? undefined,+ shortlink: i.shortlink ?? undefined,+ startedAt: i.startedAt?.toISOString(),+ createdAt: i.createdAt.toISOString(),+ resolvedAt: i.resolvedAt?.toISOString() ?? null,+ };+}+export const externalServiceRouter = createTRPCRouter({grid: publicProcedure.output(z.array(gridItemSchema)).query(async () => {const [services, latestRows] = await Promise.all([@@ -160,12 +235,7 @@ export const externalServiceRouter = createTRPCRouter({apiConfigType: service.apiConfig?.type,},latest,- history: historyRows.map((r) => ({- day: r.day,- worstIndicator: r.worst_indicator,- hadMaintenance: r.had_maintenance,- snapshotCount: r.snapshot_count,- })),+ history: historyRows.map(toHistoryRow),};}),@@ -188,16 +258,7 @@ export const externalServiceRouter = createTRPCRouter({}return {supported: true,- incidents: incidents.map((i) => ({- id: i.providerIncidentId,- name: i.name,- status: i.status,- impact: i.impact ?? undefined,- shortlink: i.shortlink ?? undefined,- startedAt: i.startedAt?.toISOString(),- createdAt: i.createdAt.toISOString(),- resolvedAt: i.resolvedAt?.toISOString() ?? null,- })),+ incidents: incidents.map(toIncidentDTO),};} catch (err) {// matches the graceful-degrade pattern used by `grid` / `detail`:@@ -210,4 +271,138 @@ export const externalServiceRouter = createTRPCRouter({return { supported: false, incidents: [] };}}),++ components: publicProcedure+ .input(+ z.object({+ slug: z.string(),+ days: z.number().int().min(1).max(90).optional(),+ }),+ )+ .output(+ z.object({+ supported: z.boolean(),+ components: z.array(componentItemSchema),+ }),+ )+ .query(async ({ input }) => {+ try {+ const { supported, components } = await listExternalComponentsBySlug({+ slug: input.slug,+ });+ if (!supported || components.length === 0) {+ return { supported, components: [] };+ }++ const days = input.days ?? DEFAULT_HISTORY_DAYS;+ const componentIds = components.map((c) => String(c.id));+ const historyRows = await safeData(+ tb.externalStatusComponentHistory({+ component_ids: componentIds,+ days,+ }),+ "externalStatusComponentHistory",+ );++ const historyByComponent = new Map<string, typeof historyRows>();+ for (const row of historyRows) {+ const list = historyByComponent.get(row.component_id);+ if (list) list.push(row);+ else historyByComponent.set(row.component_id, [row]);+ }++ return {+ supported: true,+ components: components.map((c) => ({+ id: c.id,+ slug: c.slug,+ name: c.name,+ description: c.description,+ groupName: c.groupName,+ position: c.position,+ indicator: c.indicator,+ status: c.status,+ history: (historyByComponent.get(String(c.id)) ?? []).map(+ toHistoryRow,+ ),+ })),+ };+ } catch (err) {+ console.warn(+ `[external-service components] read failed for slug=${input.slug}:`,+ err,+ );+ return { supported: false, components: [] };+ }+ }),++ component: publicProcedure+ .input(+ z.object({+ serviceSlug: z.string(),+ componentSlug: z.string(),+ days: z.number().int().min(1).max(90).optional(),+ }),+ )+ .output(componentDetailSchema)+ .query(async ({ input }) => {+ const empty = {+ found: false as const,+ service: null,+ component: null,+ history: [],+ incidents: [],+ };+ try {+ const { service, component } = await getExternalComponentBySlug({+ serviceSlug: input.serviceSlug,+ componentSlug: input.componentSlug,+ });+ if (!service || !component) return empty;++ const days = input.days ?? DEFAULT_HISTORY_DAYS;+ const [historyRows, incidents] = await Promise.all([+ safeData(+ tb.externalStatusComponentHistory({+ component_ids: [String(component.id)],+ days,+ }),+ "externalStatusComponentHistory (component)",+ ),+ listExternalIncidentsByComponent({+ externalServiceId: service.id,+ upstreamComponentId: component.upstreamComponentId,+ limit: INCIDENTS_LIMIT,+ }),+ ]);++ return {+ found: true,+ service: {+ slug: service.slug,+ name: service.name,+ statusPageUrl: service.statusPageUrl,+ },+ component: {+ id: component.id,+ slug: component.slug,+ name: component.name,+ description: component.description,+ groupName: component.groupName,+ indicator: component.indicator,+ status: component.status,+ lastSeenAt: component.lastSeenAt.getTime(),+ stale: component.stale,+ },+ history: historyRows.map(toHistoryRow),+ incidents: incidents.map(toIncidentDTO),+ };+ } catch (err) {+ console.warn(+ `[external-service component] read failed for ${input.serviceSlug}/${input.componentSlug}:`,+ err,+ );+ return empty;+ }+ }),});diff --git a/packages/db/drizzle/0073_tiresome_doomsday.sql b/packages/db/drizzle/0073_tiresome_doomsday.sqlnew file mode 100644index 000000000..5a69e9dba--- /dev/null+++ b/packages/db/drizzle/0073_tiresome_doomsday.sql@@ -0,0 +1,22 @@+CREATE TABLE `external_service_component` (+ `id` integer PRIMARY KEY NOT NULL,+ `external_service_id` integer NOT NULL,+ `upstream_component_id` text NOT NULL,+ `slug` text NOT NULL,+ `aliases` text DEFAULT (json_array()) NOT NULL,+ `name` text NOT NULL,+ `description` text,+ `group_name` text,+ `position` integer DEFAULT 0 NOT NULL,+ `indicator` text NOT NULL,+ `status` text NOT NULL,+ `first_seen_at` integer DEFAULT (strftime('%s', 'now')) NOT NULL,+ `last_seen_at` integer DEFAULT (strftime('%s', 'now')) NOT NULL,+ `updated_at` integer DEFAULT (strftime('%s', 'now')) NOT NULL,+ FOREIGN KEY (`external_service_id`) REFERENCES `external_service`(`id`) ON UPDATE no action ON DELETE no action+);+--> statement-breakpoint+CREATE UNIQUE INDEX `external_service_component_unique_idx` ON `external_service_component` (`external_service_id`,`upstream_component_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `external_service_component_slug_unique_idx` ON `external_service_component` (`external_service_id`,`slug`);--> statement-breakpoint+CREATE INDEX `external_service_component_last_seen_at_idx` ON `external_service_component` (`external_service_id`,`last_seen_at`);--> statement-breakpoint+ALTER TABLE `external_service_incident` ADD `affected_component_ids` text DEFAULT (json_array()) NOT NULL;\ No newline at end of filediff --git a/packages/db/drizzle/meta/0073_snapshot.json b/packages/db/drizzle/meta/0073_snapshot.jsonnew file mode 100644index 000000000..08a54fdb9--- /dev/null+++ b/packages/db/drizzle/meta/0073_snapshot.json@@ -0,0 +1,4444 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "9ac2ec4e-1dd3-43fd-a727-40fd0ed8f3f2",+ "prevId": "92505161-27ae-4e83-a520-f156d29ba5e1",+ "tables": {+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "limits": {+ "name": "limits",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ },+ "workspace_id_dsn_unique": {+ "name": "workspace_id_dsn_unique",+ "columns": [+ "id",+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "account_provider_provider_account_id_pk": {+ "columns": [+ "provider",+ "provider_account_id"+ ],+ "name": "account_provider_provider_account_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "users_to_workspaces_workspace_id_idx": {+ "name": "users_to_workspaces_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ],+ "name": "users_to_workspaces_user_id_workspace_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification_token": {+ "name": "verification_token",+ "columns": {+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "verification_token_identifier_token_pk": {+ "columns": [+ "identifier",+ "token"+ ],+ "name": "verification_token_identifier_token_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report": {+ "name": "status_report",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_workspace_created_idx": {+ "name": "status_report_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "status_report_page_id_idx": {+ "name": "status_report_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_workspace_id_workspace_id_fk": {+ "name": "status_report_workspace_id_workspace_id_fk",+ "tableFrom": "status_report",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "status_report_page_id_page_id_fk": {+ "name": "status_report_page_id_page_id_fk",+ "tableFrom": "status_report",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report_update": {+ "name": "status_report_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_update_status_report_id_idx": {+ "name": "status_report_update_status_report_id_idx",+ "columns": [+ "status_report_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_update_status_report_id_status_report_id_fk": {+ "name": "status_report_update_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_update",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "integration_workspace_id_idx": {+ "name": "integration_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "force_theme": {+ "name": "force_theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "password": {+ "name": "password",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password_protected": {+ "name": "password_protected",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "access_type": {+ "name": "access_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'public'"+ },+ "auth_email_domains": {+ "name": "auth_email_domains",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allowed_ip_ranges": {+ "name": "allowed_ip_ranges",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "homepage_url": {+ "name": "homepage_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "contact_url": {+ "name": "contact_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "default_locale": {+ "name": "default_locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "locales": {+ "name": "locales",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_page": {+ "name": "legacy_page",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "configuration": {+ "name": "configuration",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allow_index": {+ "name": "allow_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "show_monitor_values": {+ "name": "show_monitor_values",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "page_lower_slug_idx": {+ "name": "page_lower_slug_idx",+ "columns": [+ "LOWER(\"slug\")"+ ],+ "isUnique": false+ },+ "page_lower_custom_domain_idx": {+ "name": "page_lower_custom_domain_idx",+ "columns": [+ "LOWER(\"custom_domain\")"+ ],+ "isUnique": false+ },+ "page_workspace_id_idx": {+ "name": "page_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'http'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(2048)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "external_name": {+ "name": "external_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "timeout": {+ "name": "timeout",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 45000+ },+ "degraded_after": {+ "name": "degraded_after",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "assertions": {+ "name": "assertions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_endpoint": {+ "name": "otel_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_headers": {+ "name": "otel_headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "public": {+ "name": "public",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "retry": {+ "name": "retry",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 3+ },+ "follow_redirects": {+ "name": "follow_redirects",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "monitor_workspace_id_active_idx": {+ "name": "monitor_workspace_id_active_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false,+ "where": "\"monitor\".\"deleted_at\" IS NULL"+ }+ },+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_subscriber": {+ "name": "page_subscriber",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "channel_type": {+ "name": "channel_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'email'"+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "channel_config": {+ "name": "channel_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'self_signup'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "unsubscribed_at": {+ "name": "unsubscribed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "idx_page_subscriber_email_page_active": {+ "name": "idx_page_subscriber_email_page_active",+ "columns": [+ "LOWER(\"email\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'email'"+ },+ "idx_page_subscriber_webhook_page_active": {+ "name": "idx_page_subscriber_webhook_page_active",+ "columns": [+ "LOWER(\"webhook_url\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'webhook'"+ }+ },+ "foreignKeys": {+ "page_subscriber_page_id_page_id_fk": {+ "name": "page_subscriber_page_id_page_id_fk",+ "tableFrom": "page_subscriber",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_subscriber_channel_check": {+ "name": "page_subscriber_channel_check",+ "value": "(\"page_subscriber\".\"channel_type\" = 'email' AND \"page_subscriber\".\"email\" IS NOT NULL AND \"page_subscriber\".\"webhook_url\" IS NULL) OR (\"page_subscriber\".\"channel_type\" = 'webhook' AND \"page_subscriber\".\"webhook_url\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL)"+ }+ }+ },+ "page_subscriber_to_page_component": {+ "name": "page_subscriber_to_page_component",+ "columns": {+ "page_subscriber_id": {+ "name": "page_subscriber_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk": {+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_subscriber",+ "columnsFrom": [+ "page_subscriber_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_subscriber_to_page_component_page_component_id_page_component_id_fk": {+ "name": "page_subscriber_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk": {+ "columns": [+ "page_subscriber_id",+ "page_component_id"+ ],+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification": {+ "name": "notification",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'{}'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "notification_workspace_id_idx": {+ "name": "notification_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "notification_workspace_id_workspace_id_fk": {+ "name": "notification_workspace_id_workspace_id_fk",+ "tableFrom": "notification",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification_trigger": {+ "name": "notification_trigger",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_id_monitor_id_crontimestampe": {+ "name": "notification_id_monitor_id_crontimestampe",+ "columns": [+ "notification_id",+ "monitor_id",+ "cron_timestamp"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "notification_trigger_monitor_id_monitor_id_fk": {+ "name": "notification_trigger_monitor_id_monitor_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_trigger_notification_id_notification_id_fk": {+ "name": "notification_trigger_notification_id_notification_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notifications_to_monitors": {+ "name": "notifications_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "notifications_to_monitors_notification_id_idx": {+ "name": "notifications_to_monitors_notification_id_idx",+ "columns": [+ "notification_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "notifications_to_monitors_monitor_id_monitor_id_fk": {+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notifications_to_monitors_notification_id_notification_id_fk": {+ "name": "notifications_to_monitors_notification_id_notification_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "notifications_to_monitors_monitor_id_notification_id_pk": {+ "columns": [+ "monitor_id",+ "notification_id"+ ],+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_status": {+ "name": "monitor_status",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_status_idx": {+ "name": "monitor_status_idx",+ "columns": [+ "monitor_id",+ "region"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_status_monitor_id_monitor_id_fk": {+ "name": "monitor_status_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_status",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_status_monitor_id_region_pk": {+ "columns": [+ "monitor_id",+ "region"+ ],+ "name": "monitor_status_monitor_id_region_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "invitation_workspace_id_idx": {+ "name": "invitation_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'triage'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "incident_screenshot_url": {+ "name": "incident_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recovery_screenshot_url": {+ "name": "recovery_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_resolved": {+ "name": "auto_resolved",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "incident_workspace_id_idx": {+ "name": "incident_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "incident_monitor_id_started_at_unique": {+ "name": "incident_monitor_id_started_at_unique",+ "columns": [+ "monitor_id",+ "started_at"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "incident_monitor_id_monitor_id_fk": {+ "name": "incident_monitor_id_monitor_id_fk",+ "tableFrom": "incident",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set default",+ "onUpdate": "no action"+ },+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_acknowledged_by_user_id_fk": {+ "name": "incident_acknowledged_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_resolved_by_user_id_fk": {+ "name": "incident_resolved_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag": {+ "name": "monitor_tag",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_tag_workspace_id_idx": {+ "name": "monitor_tag_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_tag_workspace_id_workspace_id_fk": {+ "name": "monitor_tag_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_tag",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag_to_monitor": {+ "name": "monitor_tag_to_monitor",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_tag_id": {+ "name": "monitor_tag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_tag_to_monitor_monitor_tag_id_idx": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_idx",+ "columns": [+ "monitor_tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor_tag",+ "columnsFrom": [+ "monitor_tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {+ "columns": [+ "monitor_id",+ "monitor_tag_id"+ ],+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "application": {+ "name": "application",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "application_dsn_unique": {+ "name": "application_dsn_unique",+ "columns": [+ "dsn"+ ],+ "isUnique": true+ },+ "application_workspace_id_idx": {+ "name": "application_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "application_workspace_id_workspace_id_fk": {+ "name": "application_workspace_id_workspace_id_fk",+ "tableFrom": "application",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance": {+ "name": "maintenance",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from": {+ "name": "from",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to": {+ "name": "to",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "maintenance_page_id_idx": {+ "name": "maintenance_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "maintenance_workspace_id_idx": {+ "name": "maintenance_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "maintenance_workspace_id_workspace_id_fk": {+ "name": "maintenance_workspace_id_workspace_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "maintenance_page_id_page_id_fk": {+ "name": "maintenance_page_id_page_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "check": {+ "name": "check",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(4096)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "count_requests": {+ "name": "count_requests",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "check_workspace_id_idx": {+ "name": "check_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "check_workspace_id_workspace_id_fk": {+ "name": "check_workspace_id_workspace_id_fk",+ "tableFrom": "check",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_run": {+ "name": "monitor_run",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "runned_at": {+ "name": "runned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_run_workspace_id_idx": {+ "name": "monitor_run_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_run_monitor_id_idx": {+ "name": "monitor_run_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_run_workspace_id_workspace_id_fk": {+ "name": "monitor_run_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "monitor_run_monitor_id_monitor_id_fk": {+ "name": "monitor_run_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location": {+ "name": "private_location",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "private_location_workspace_id_idx": {+ "name": "private_location_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "private_location_workspace_id_workspace_id_fk": {+ "name": "private_location_workspace_id_workspace_id_fk",+ "tableFrom": "private_location",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location_to_monitor": {+ "name": "private_location_to_monitor",+ "columns": {+ "private_location_id": {+ "name": "private_location_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "private_location_to_monitor_private_location_id_idx": {+ "name": "private_location_to_monitor_private_location_id_idx",+ "columns": [+ "private_location_id"+ ],+ "isUnique": false+ },+ "private_location_to_monitor_monitor_id_idx": {+ "name": "private_location_to_monitor_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "private_location_to_monitor_private_location_id_private_location_id_fk": {+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "private_location",+ "columnsFrom": [+ "private_location_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "private_location_to_monitor_monitor_id_monitor_id_fk": {+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_group": {+ "name": "monitor_group",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_group_workspace_id_idx": {+ "name": "monitor_group_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_group_page_id_idx": {+ "name": "monitor_group_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_group_workspace_id_workspace_id_fk": {+ "name": "monitor_group_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_group_page_id_page_id_fk": {+ "name": "monitor_group_page_id_page_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer": {+ "name": "viewer",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "viewer_email_unique": {+ "name": "viewer_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_accounts": {+ "name": "viewer_accounts",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerAccountId": {+ "name": "providerAccountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_accounts_user_id_viewer_id_fk": {+ "name": "viewer_accounts_user_id_viewer_id_fk",+ "tableFrom": "viewer_accounts",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "viewer_accounts_provider_providerAccountId_pk": {+ "columns": [+ "provider",+ "providerAccountId"+ ],+ "name": "viewer_accounts_provider_providerAccountId_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_session": {+ "name": "viewer_session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_session_user_id_viewer_id_fk": {+ "name": "viewer_session_user_id_viewer_id_fk",+ "tableFrom": "viewer_session",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "api_key": {+ "name": "api_key",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hashed_token": {+ "name": "hashed_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_id": {+ "name": "created_by_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[\"write\"]'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "api_key_prefix_unique": {+ "name": "api_key_prefix_unique",+ "columns": [+ "prefix"+ ],+ "isUnique": true+ },+ "api_key_hashed_token_unique": {+ "name": "api_key_hashed_token_unique",+ "columns": [+ "hashed_token"+ ],+ "isUnique": true+ },+ "api_key_prefix_idx": {+ "name": "api_key_prefix_idx",+ "columns": [+ "prefix"+ ],+ "isUnique": false+ },+ "api_key_workspace_id_idx": {+ "name": "api_key_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "api_key_workspace_id_workspace_id_fk": {+ "name": "api_key_workspace_id_workspace_id_fk",+ "tableFrom": "api_key",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "api_key_created_by_id_user_id_fk": {+ "name": "api_key_created_by_id_user_id_fk",+ "tableFrom": "api_key",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance_to_page_component": {+ "name": "maintenance_to_page_component",+ "columns": {+ "maintenance_id": {+ "name": "maintenance_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "maintenance_to_page_component_page_component_id_idx": {+ "name": "maintenance_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "maintenance_to_page_component_maintenance_id_maintenance_id_fk": {+ "name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "maintenance",+ "columnsFrom": [+ "maintenance_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "maintenance_to_page_component_page_component_id_page_component_id_fk": {+ "name": "maintenance_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "maintenance_to_page_component_maintenance_id_page_component_id_pk": {+ "columns": [+ "maintenance_id",+ "page_component_id"+ ],+ "name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component": {+ "name": "page_component",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'monitor'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_order": {+ "name": "group_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_component_workspace_id_idx": {+ "name": "page_component_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "page_component_page_id_monitor_id_unique": {+ "name": "page_component_page_id_monitor_id_unique",+ "columns": [+ "page_id",+ "monitor_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_component_workspace_id_workspace_id_fk": {+ "name": "page_component_workspace_id_workspace_id_fk",+ "tableFrom": "page_component",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_page_id_page_id_fk": {+ "name": "page_component_page_id_page_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_monitor_id_monitor_id_fk": {+ "name": "page_component_monitor_id_monitor_id_fk",+ "tableFrom": "page_component",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_group_id_page_component_groups_id_fk": {+ "name": "page_component_group_id_page_component_groups_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page_component_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_component_type_check": {+ "name": "page_component_type_check",+ "value": "\"page_component\".\"type\" = 'monitor' AND \"page_component\".\"monitor_id\" IS NOT NULL OR \"page_component\".\"type\" = 'static' AND \"page_component\".\"monitor_id\" IS NULL"+ }+ }+ },+ "status_report_to_page_component": {+ "name": "status_report_to_page_component",+ "columns": {+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_to_page_component_page_component_id_idx": {+ "name": "status_report_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_to_page_component_status_report_id_status_report_id_fk": {+ "name": "status_report_to_page_component_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_report_to_page_component_page_component_id_page_component_id_fk": {+ "name": "status_report_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_report_to_page_component_status_report_id_page_component_id_pk": {+ "columns": [+ "status_report_id",+ "page_component_id"+ ],+ "name": "status_report_to_page_component_status_report_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component_groups": {+ "name": "page_component_groups",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "default_open": {+ "name": "default_open",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_component_groups_page_id_idx": {+ "name": "page_component_groups_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "page_component_groups_workspace_id_idx": {+ "name": "page_component_groups_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "page_component_groups_workspace_id_workspace_id_fk": {+ "name": "page_component_groups_workspace_id_workspace_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_groups_page_id_page_id_fk": {+ "name": "page_component_groups_page_id_page_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "feedback": {+ "name": "feedback",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "blocker": {+ "name": "blocker",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "feedback_workspace_id_idx": {+ "name": "feedback_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "feedback_workspace_id_workspace_id_fk": {+ "name": "feedback_workspace_id_workspace_id_fk",+ "tableFrom": "feedback",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "feedback_user_id_user_id_fk": {+ "name": "feedback_user_id_user_id_fk",+ "tableFrom": "feedback",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_log": {+ "name": "audit_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_type": {+ "name": "entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_id": {+ "name": "entity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "before": {+ "name": "before",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "after": {+ "name": "after",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "changed_fields": {+ "name": "changed_fields",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_log_workspace_created_idx": {+ "name": "audit_log_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "audit_log_entity_idx": {+ "name": "audit_log_entity_idx",+ "columns": [+ "workspace_id",+ "entity_type",+ "entity_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "external_service": {+ "name": "external_service",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "aliases": {+ "name": "aliases",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(json_array())"+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_page_url": {+ "name": "status_page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "industry": {+ "name": "industry",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "api_config": {+ "name": "api_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "external_service_slug_unique": {+ "name": "external_service_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "external_service_deleted_at_idx": {+ "name": "external_service_deleted_at_idx",+ "columns": [+ "deleted_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "external_service_component": {+ "name": "external_service_component",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "external_service_id": {+ "name": "external_service_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "upstream_component_id": {+ "name": "upstream_component_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "aliases": {+ "name": "aliases",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(json_array())"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "indicator": {+ "name": "indicator",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "external_service_component_unique_idx": {+ "name": "external_service_component_unique_idx",+ "columns": [+ "external_service_id",+ "upstream_component_id"+ ],+ "isUnique": true+ },+ "external_service_component_slug_unique_idx": {+ "name": "external_service_component_slug_unique_idx",+ "columns": [+ "external_service_id",+ "slug"+ ],+ "isUnique": true+ },+ "external_service_component_last_seen_at_idx": {+ "name": "external_service_component_last_seen_at_idx",+ "columns": [+ "external_service_id",+ "last_seen_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "external_service_component_external_service_id_external_service_id_fk": {+ "name": "external_service_component_external_service_id_external_service_id_fk",+ "tableFrom": "external_service_component",+ "tableTo": "external_service",+ "columnsFrom": [+ "external_service_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "external_service_incident": {+ "name": "external_service_incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "external_service_id": {+ "name": "external_service_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_incident_id": {+ "name": "provider_incident_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impact": {+ "name": "impact",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shortlink": {+ "name": "shortlink",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "affected_component_ids": {+ "name": "affected_component_ids",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(json_array())"+ },+ "raw_payload": {+ "name": "raw_payload",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "raw_payload_purged_at": {+ "name": "raw_payload_purged_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "external_service_incident_unique_idx": {+ "name": "external_service_incident_unique_idx",+ "columns": [+ "external_service_id",+ "provider_incident_id"+ ],+ "isUnique": true+ },+ "external_service_incident_started_at_idx": {+ "name": "external_service_incident_started_at_idx",+ "columns": [+ "external_service_id",+ "started_at"+ ],+ "isUnique": false+ },+ "external_service_incident_resolved_at_idx": {+ "name": "external_service_incident_resolved_at_idx",+ "columns": [+ "resolved_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "external_service_incident_external_service_id_external_service_id_fk": {+ "name": "external_service_incident_external_service_id_external_service_id_fk",+ "tableFrom": "external_service_incident",+ "tableTo": "external_service",+ "columnsFrom": [+ "external_service_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "chat_session": {+ "name": "chat_session",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "messages": {+ "name": "messages",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "chat_session_workspace_user_updated_idx": {+ "name": "chat_session_workspace_user_updated_idx",+ "columns": [+ "workspace_id",+ "user_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "chat_session_workspace_id_workspace_id_fk": {+ "name": "chat_session_workspace_id_workspace_id_fk",+ "tableFrom": "chat_session",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_session_user_id_user_id_fk": {+ "name": "chat_session_user_id_user_id_fk",+ "tableFrom": "chat_session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {+ "page_lower_slug_idx": {+ "columns": {+ "LOWER(\"slug\")": {+ "isExpression": true+ }+ }+ },+ "page_lower_custom_domain_idx": {+ "columns": {+ "LOWER(\"custom_domain\")": {+ "isExpression": true+ }+ }+ },+ "idx_page_subscriber_email_page_active": {+ "columns": {+ "LOWER(\"email\")": {+ "isExpression": true+ }+ }+ },+ "idx_page_subscriber_webhook_page_active": {+ "columns": {+ "LOWER(\"webhook_url\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 263f16c56..384e23abb 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -512,6 +512,13 @@"when": 1779967971625,"tag": "0072_curvy_vulcan","breakpoints": true+ },+ {+ "idx": 73,+ "version": "6",+ "when": 1780560757326,+ "tag": "0073_tiresome_doomsday",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/external_services/external_service_component.ts b/packages/db/src/schema/external_services/external_service_component.tsnew file mode 100644index 000000000..2374ee84c--- /dev/null+++ b/packages/db/src/schema/external_services/external_service_component.ts@@ -0,0 +1,55 @@+import { sql } from "drizzle-orm";+import {+ index,+ integer,+ sqliteTable,+ text,+ uniqueIndex,+} from "drizzle-orm/sqlite-core";++import { externalService } from "./external_service";++export const externalServiceComponent = sqliteTable(+ "external_service_component",+ {+ id: integer("id").primaryKey(),+ externalServiceId: integer("external_service_id")+ .notNull()+ .references(() => externalService.id),+ upstreamComponentId: text("upstream_component_id").notNull(),+ slug: text("slug").notNull(),+ aliases: text("aliases", { mode: "json" })+ .$type<string[]>()+ .default(sql`(json_array())`)+ .notNull(),+ name: text("name").notNull(),+ description: text("description"),+ groupName: text("group_name"),+ position: integer("position").notNull().default(0),+ indicator: text("indicator").notNull(),+ status: text("status").notNull(),+ firstSeenAt: integer("first_seen_at", { mode: "timestamp" })+ .notNull()+ .default(sql`(strftime('%s', 'now'))`),+ lastSeenAt: integer("last_seen_at", { mode: "timestamp" })+ .notNull()+ .default(sql`(strftime('%s', 'now'))`),+ updatedAt: integer("updated_at", { mode: "timestamp" })+ .notNull()+ .default(sql`(strftime('%s', 'now'))`),+ },+ (t) => [+ uniqueIndex("external_service_component_unique_idx").on(+ t.externalServiceId,+ t.upstreamComponentId,+ ),+ uniqueIndex("external_service_component_slug_unique_idx").on(+ t.externalServiceId,+ t.slug,+ ),+ index("external_service_component_last_seen_at_idx").on(+ t.externalServiceId,+ t.lastSeenAt,+ ),+ ],+);diff --git a/packages/db/src/schema/external_services/external_service_incident.ts b/packages/db/src/schema/external_services/external_service_incident.tsindex ef0a53e46..48c9859ab 100644--- a/packages/db/src/schema/external_services/external_service_incident.ts+++ b/packages/db/src/schema/external_services/external_service_incident.ts@@ -24,6 +24,10 @@ export const externalServiceIncident = sqliteTable(startedAt: integer("started_at", { mode: "timestamp" }),createdAt: integer("created_at", { mode: "timestamp" }).notNull(),resolvedAt: integer("resolved_at", { mode: "timestamp" }),+ affectedComponentIds: text("affected_component_ids", { mode: "json" })+ .$type<string[]>()+ .default(sql`(json_array())`)+ .notNull(),rawPayload: text("raw_payload", { mode: "json" }),rawPayloadPurgedAt: integer("raw_payload_purged_at", { mode: "timestamp" }),firstSeenAt: integer("first_seen_at", { mode: "timestamp" })diff --git a/packages/db/src/schema/external_services/index.ts b/packages/db/src/schema/external_services/index.tsindex 1d1fd50ea..72b1a4a51 100644--- a/packages/db/src/schema/external_services/index.ts+++ b/packages/db/src/schema/external_services/index.ts@@ -1,4 +1,5 @@export * from "./constants";export * from "./external_service";+export * from "./external_service_component";export * from "./external_service_incident";export * from "./validation";diff --git a/packages/db/src/schema/external_services/validation.ts b/packages/db/src/schema/external_services/validation.tsindex ce660132d..d147b1c63 100644--- a/packages/db/src/schema/external_services/validation.ts+++ b/packages/db/src/schema/external_services/validation.ts@@ -2,6 +2,7 @@ import { createInsertSchema, createSelectSchema } from "drizzle-zod";import { z } from "zod";import { externalService } from "./external_service";+import { externalServiceComponent } from "./external_service_component";import { externalServiceIncident } from "./external_service_incident";export const externalServiceSlugRegex = /^[a-z0-9](-?[a-z0-9])*$/;@@ -35,3 +36,18 @@ export type ExternalServiceIncident = z.infer<export type InsertExternalServiceIncident = z.infer<typeof insertExternalServiceIncidentSchema>;++export const selectExternalServiceComponentSchema = createSelectSchema(+ externalServiceComponent,+);++export const insertExternalServiceComponentSchema = createInsertSchema(+ externalServiceComponent,+);++export type ExternalServiceComponent = z.infer<+ typeof selectExternalServiceComponentSchema+>;+export type InsertExternalServiceComponent = z.infer<+ typeof insertExternalServiceComponentSchema+>;diff --git a/packages/services/package.json b/packages/services/package.jsonindex 5764d9744..33ea801c9 100644--- a/packages/services/package.json+++ b/packages/services/package.json@@ -101,6 +101,10 @@"import": "./src/external-service-incident/index.ts","types": "./src/external-service-incident/index.ts"},+ "./external-service-component": {+ "import": "./src/external-service-component/index.ts",+ "types": "./src/external-service-component/index.ts"+ },"./test/helpers": {"import": "./test/helpers.ts","types": "./test/helpers.ts"diff --git a/packages/services/src/external-service-component/__tests__/external-service-component.test.ts b/packages/services/src/external-service-component/__tests__/external-service-component.test.tsnew file mode 100644index 000000000..6297590f1--- /dev/null+++ b/packages/services/src/external-service-component/__tests__/external-service-component.test.ts@@ -0,0 +1,338 @@+import { afterEach, describe, expect, test } from "bun:test";+import { and, db, eq, like } from "@openstatus/db";+import type { ApiConfigType } from "@openstatus/db/src/schema";+import {+ externalService,+ externalServiceComponent,+} from "@openstatus/db/src/schema";++import {+ getExternalComponentBySlug,+ listExternalComponentsBySlug,+ upsertExternalComponentsForService,+} from "../index";++const TEST_PREFIX = "svc-extcomponent-test";++afterEach(async () => {+ const ids = await db+ .select({ id: externalService.id })+ .from(externalService)+ .where(like(externalService.slug, `${TEST_PREFIX}-%`))+ .all();+ for (const { id } of ids) {+ await db+ .delete(externalServiceComponent)+ .where(eq(externalServiceComponent.externalServiceId, id))+ .run();+ }+ await db+ .delete(externalService)+ .where(like(externalService.slug, `${TEST_PREFIX}-%`))+ .run();+});++async function seedService(opts: {+ slug: string;+ aliases?: string[];+ apiConfigType?: ApiConfigType;+}): Promise<number> {+ const { slug, aliases = [], apiConfigType = "atlassian" } = opts;+ const rows = await db+ .insert(externalService)+ .values({+ slug,+ aliases,+ name: `Test ${slug}`,+ url: "https://example.com",+ statusPageUrl: "https://status.example.com",+ provider: "atlassian-statuspage",+ industry: ["saas"],+ apiConfig: { type: apiConfigType },+ })+ .returning({ id: externalService.id })+ .all();+ const id = rows[0]?.id;+ if (!id) throw new Error("failed to seed external_service");+ return id;+}++describe("upsertExternalComponentsForService", () => {+ test("inserts components and is idempotent on second call (update path)", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-upsert` });+ const baseDate = new Date("2024-06-01T12:00:00.000Z");++ const first = await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: baseDate,+ components: [+ {+ upstreamComponentId: "cmp-1",+ name: "fra1",+ groupName: "Regions",+ position: 1,+ indicator: "none",+ status: "operational",+ },+ ],+ });+ expect(first.upserted).toHaveLength(1);+ expect(first.upserted[0]?.upstreamComponentId).toBe("cmp-1");+ expect(first.upserted[0]?.id).toBeGreaterThan(0);++ const inserted = await db+ .select()+ .from(externalServiceComponent)+ .where(+ and(+ eq(externalServiceComponent.externalServiceId, serviceId),+ eq(externalServiceComponent.upstreamComponentId, "cmp-1"),+ ),+ )+ .all();+ expect(inserted).toHaveLength(1);+ expect(inserted[0]?.status).toBe("operational");+ expect(inserted[0]?.firstSeenAt.getTime()).toBe(baseDate.getTime());++ const laterDate = new Date("2024-06-01T13:00:00.000Z");+ const second = await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: laterDate,+ components: [+ {+ upstreamComponentId: "cmp-1",+ name: "fra1",+ groupName: "Regions",+ position: 1,+ indicator: "major",+ status: "partial_outage",+ },+ ],+ });+ expect(second.upserted).toHaveLength(1);++ const updated = await db+ .select()+ .from(externalServiceComponent)+ .where(+ and(+ eq(externalServiceComponent.externalServiceId, serviceId),+ eq(externalServiceComponent.upstreamComponentId, "cmp-1"),+ ),+ )+ .all();+ expect(updated).toHaveLength(1);+ expect(updated[0]?.status).toBe("partial_outage");+ expect(updated[0]?.indicator).toBe("major");+ expect(updated[0]?.firstSeenAt.getTime()).toBe(baseDate.getTime());+ expect(updated[0]?.lastSeenAt.getTime()).toBe(laterDate.getTime());+ });++ test("no-op when given an empty list", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-empty` });+ const res = await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ components: [],+ });+ expect(res.upserted).toEqual([]);+ });+});++describe("listExternalComponentsBySlug", () => {+ test("returns components ordered by position and supported=true", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-list` });++ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ components: [+ {+ upstreamComponentId: "b",+ name: "second",+ position: 2,+ indicator: "none",+ status: "operational",+ },+ {+ upstreamComponentId: "a",+ name: "first",+ position: 1,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const { service, supported, components } =+ await listExternalComponentsBySlug({ slug: `${TEST_PREFIX}-list` });+ expect(service).not.toBeNull();+ expect(supported).toBe(true);+ expect(components).toHaveLength(2);+ expect(components[0]?.upstreamComponentId).toBe("a");+ expect(components[1]?.upstreamComponentId).toBe("b");+ });++ test("resolves alias slug to canonical service", async () => {+ const serviceId = await seedService({+ slug: `${TEST_PREFIX}-canonical`,+ aliases: [`${TEST_PREFIX}-aliased`],+ });++ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ components: [+ {+ upstreamComponentId: "x",+ name: "via-alias",+ position: 0,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const viaAlias = await listExternalComponentsBySlug({+ slug: `${TEST_PREFIX}-aliased`,+ });+ expect(viaAlias.service?.id).toBe(serviceId);+ expect(viaAlias.components).toHaveLength(1);+ });++ test("hides components not seen within the 24h window", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-stale` });+ const longAgo = new Date("2024-01-01T00:00:00.000Z");++ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: longAgo,+ components: [+ {+ upstreamComponentId: "gone",+ name: "retired-region",+ position: 0,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const now = new Date("2024-06-01T00:00:00.000Z");+ const { components } = await listExternalComponentsBySlug({+ slug: `${TEST_PREFIX}-stale`,+ now,+ });+ expect(components).toHaveLength(0);+ });++ test("returns supported=false for a provider without component support", async () => {+ await seedService({+ slug: `${TEST_PREFIX}-custom`,+ apiConfigType: "custom",+ });+ const { supported, components } = await listExternalComponentsBySlug({+ slug: `${TEST_PREFIX}-custom`,+ });+ expect(supported).toBe(false);+ expect(components).toEqual([]);+ });++ test("returns null service for unknown slug", async () => {+ const { service, components } = await listExternalComponentsBySlug({+ slug: `${TEST_PREFIX}-missing`,+ });+ expect(service).toBeNull();+ expect(components).toEqual([]);+ });+});++describe("getExternalComponentBySlug", () => {+ test("resolves by current slug and by past alias after a rename", async () => {+ const serviceSlug = `${TEST_PREFIX}-getcomp`;+ const serviceId = await seedService({ slug: serviceSlug });++ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: new Date("2024-06-01T00:00:00.000Z"),+ components: [+ {+ upstreamComponentId: "r1",+ name: "Frankfurt",+ position: 0,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const byOriginal = await getExternalComponentBySlug({+ serviceSlug,+ componentSlug: "frankfurt",+ now: new Date("2024-06-01T00:05:00.000Z"),+ });+ expect(byOriginal.component?.slug).toBe("frankfurt");+ expect(byOriginal.component?.stale).toBe(false);++ // rename → slug becomes eu-central, "frankfurt" preserved as alias+ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: new Date("2024-06-01T00:10:00.000Z"),+ components: [+ {+ upstreamComponentId: "r1",+ name: "EU Central",+ position: 0,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const byCurrent = await getExternalComponentBySlug({+ serviceSlug,+ componentSlug: "eu-central",+ });+ expect(byCurrent.component?.slug).toBe("eu-central");++ const byAlias = await getExternalComponentBySlug({+ serviceSlug,+ componentSlug: "frankfurt",+ });+ expect(byAlias.component?.slug).toBe("eu-central");+ });++ test("flags a component stale when last seen beyond the 24h window", async () => {+ const serviceSlug = `${TEST_PREFIX}-getstale`;+ const serviceId = await seedService({ slug: serviceSlug });+ await upsertExternalComponentsForService({+ externalServiceId: serviceId,+ now: new Date("2024-01-01T00:00:00.000Z"),+ components: [+ {+ upstreamComponentId: "r1",+ name: "Frankfurt",+ position: 0,+ indicator: "none",+ status: "operational",+ },+ ],+ });++ const res = await getExternalComponentBySlug({+ serviceSlug,+ componentSlug: "frankfurt",+ now: new Date("2024-06-01T00:00:00.000Z"),+ });+ expect(res.component?.slug).toBe("frankfurt");+ expect(res.component?.stale).toBe(true);+ });++ test("returns null component for an unknown component slug", async () => {+ const serviceSlug = `${TEST_PREFIX}-getmissing`;+ await seedService({ slug: serviceSlug });+ const res = await getExternalComponentBySlug({+ serviceSlug,+ componentSlug: "nope",+ });+ expect(res.service).not.toBeNull();+ expect(res.component).toBeNull();+ });+});diff --git a/packages/services/src/external-service-component/__tests__/internal.test.ts b/packages/services/src/external-service-component/__tests__/internal.test.tsnew file mode 100644index 000000000..f219bb83f--- /dev/null+++ b/packages/services/src/external-service-component/__tests__/internal.test.ts@@ -0,0 +1,112 @@+import { describe, expect, test } from "bun:test";++import { assignComponentSlugs, slugifyComponentName } from "../internal";++describe("slugifyComponentName", () => {+ test("lowercases and hyphenates", () => {+ expect(slugifyComponentName("Frankfurt")).toBe("frankfurt");+ expect(slugifyComponentName("API / v2")).toBe("api-v2");+ });++ test("strips punctuation and collapses/trims hyphens", () => {+ expect(slugifyComponentName("US East (N. Virginia)")).toBe(+ "us-east-n-virginia",+ );+ expect(slugifyComponentName("Amsterdam, Netherlands - (AMS)")).toBe(+ "amsterdam-netherlands-ams",+ );+ expect(slugifyComponentName(" --weird-- ")).toBe("weird");+ });++ test("strips diacritics", () => {+ expect(slugifyComponentName("Zürich")).toBe("zurich");+ expect(slugifyComponentName("São Paulo")).toBe("sao-paulo");+ });++ test("falls back to 'component' when empty", () => {+ expect(slugifyComponentName("")).toBe("component");+ expect(slugifyComponentName("///")).toBe("component");+ });+});++describe("assignComponentSlugs", () => {+ test("assigns fresh slugs to new components", () => {+ const out = assignComponentSlugs({+ existing: [],+ incoming: [+ { upstreamComponentId: "a", name: "Frankfurt" },+ { upstreamComponentId: "b", name: "Stockholm" },+ ],+ });+ expect(out.get("a")).toEqual({ slug: "frankfurt", aliases: [] });+ expect(out.get("b")).toEqual({ slug: "stockholm", aliases: [] });+ });++ test("suffixes colliding slugs deterministically by upstream id", () => {+ const out = assignComponentSlugs({+ existing: [],+ incoming: [+ { upstreamComponentId: "b", name: "api" },+ { upstreamComponentId: "a", name: "API" },+ ],+ });+ // processed in upstream-id order: "a" → api, "b" → api-2+ expect(out.get("a")).toEqual({ slug: "api", aliases: [] });+ expect(out.get("b")).toEqual({ slug: "api-2", aliases: [] });+ });++ test("keeps slug while name is unchanged", () => {+ const out = assignComponentSlugs({+ existing: [+ {+ upstreamComponentId: "a",+ name: "Frankfurt",+ slug: "frankfurt",+ aliases: ["old-name"],+ },+ ],+ incoming: [{ upstreamComponentId: "a", name: "Frankfurt" }],+ });+ expect(out.get("a")).toEqual({ slug: "frankfurt", aliases: ["old-name"] });+ });++ test("on rename, pushes the old slug into aliases", () => {+ const out = assignComponentSlugs({+ existing: [+ {+ upstreamComponentId: "a",+ name: "Frankfurt",+ slug: "frankfurt",+ aliases: [],+ },+ ],+ incoming: [{ upstreamComponentId: "a", name: "EU Central" }],+ });+ expect(out.get("a")).toEqual({+ slug: "eu-central",+ aliases: ["frankfurt"],+ });+ });++ test("new component avoids colliding with another's alias", () => {+ const out = assignComponentSlugs({+ existing: [+ {+ upstreamComponentId: "a",+ name: "EU Central",+ slug: "eu-central",+ aliases: ["frankfurt"],+ },+ ],+ incoming: [+ { upstreamComponentId: "a", name: "EU Central" },+ { upstreamComponentId: "b", name: "Frankfurt" },+ ],+ });+ expect(out.get("a")).toEqual({+ slug: "eu-central",+ aliases: ["frankfurt"],+ });+ expect(out.get("b")).toEqual({ slug: "frankfurt-2", aliases: [] });+ });+});diff --git a/packages/services/src/external-service-component/index.ts b/packages/services/src/external-service-component/index.tsnew file mode 100644index 000000000..127215d27--- /dev/null+++ b/packages/services/src/external-service-component/index.ts@@ -0,0 +1,23 @@+export {+ type UpsertExternalComponentInput,+ type UpsertExternalComponentsResult,+ type UpsertedComponent,+ upsertExternalComponentsForService,+} from "./upsert";+export {+ type ExternalComponentDetail,+ type ExternalComponentListItem,+ type GetComponentBySlugResult,+ type ListComponentsBySlugResult,+ COMPONENT_SUPPORTED_API_CONFIG_TYPES,+ getExternalComponentBySlug,+ listExternalComponentsByServiceId,+ listExternalComponentsBySlug,+ supportsComponents,+} from "./list";+export {+ type ComponentSlugAssignment,+ type ExistingComponentSlug,+ assignComponentSlugs,+ slugifyComponentName,+} from "./internal";diff --git a/packages/services/src/external-service-component/internal.ts b/packages/services/src/external-service-component/internal.tsnew file mode 100644index 000000000..094596b10--- /dev/null+++ b/packages/services/src/external-service-component/internal.ts@@ -0,0 +1,87 @@+const MAX_SLUG_LENGTH = 64;++export function slugifyComponentName(name: string): string {+ const slug = name+ .normalize("NFKD")+ .replace(/\p{Mn}/gu, "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-|-$/g, "")+ .slice(0, MAX_SLUG_LENGTH)+ .replace(/-$/, "");+ return slug || "component";+}++export type ExistingComponentSlug = {+ upstreamComponentId: string;+ name: string;+ slug: string;+ aliases: string[];+};++export type ComponentSlugAssignment = {+ slug: string;+ aliases: string[];+};++function uniqueSlug(+ desired: string,+ reserved: Set<string>,+ owned: Set<string>,+): string {+ const isFree = (candidate: string) =>+ owned.has(candidate) || !reserved.has(candidate);+ if (isFree(desired)) return desired;+ let suffix = 2;+ while (!isFree(`${desired}-${suffix}`)) suffix++;+ return `${desired}-${suffix}`;+}++// Derives a stable, unique-per-service slug for each component. Existing+// components keep their slug while the name is unchanged; on rename the old slug+// is preserved in `aliases` (so old URLs 308 to the new one) and a fresh slug is+// assigned, suffixed (`-2`) when it would collide with another component's slug+// or alias. Processed in upstream-id order so collision suffixes stay stable.+export function assignComponentSlugs(args: {+ existing: ExistingComponentSlug[];+ incoming: Array<{ upstreamComponentId: string; name: string }>;+}): Map<string, ComponentSlugAssignment> {+ const existingByUpstream = new Map(+ args.existing.map((e) => [e.upstreamComponentId, e]),+ );++ const reserved = new Set<string>();+ for (const e of args.existing) {+ reserved.add(e.slug);+ for (const alias of e.aliases) reserved.add(alias);+ }++ const ordered = [...args.incoming].sort((a, b) =>+ a.upstreamComponentId.localeCompare(b.upstreamComponentId),+ );++ const out = new Map<string, ComponentSlugAssignment>();+ for (const c of ordered) {+ const prev = existingByUpstream.get(c.upstreamComponentId);++ if (prev && prev.name === c.name) {+ out.set(c.upstreamComponentId, {+ slug: prev.slug,+ aliases: prev.aliases,+ });+ continue;+ }++ const owned = new Set<string>(prev ? [prev.slug, ...prev.aliases] : []);+ const slug = uniqueSlug(slugifyComponentName(c.name), reserved, owned);++ const aliases = new Set<string>(prev?.aliases ?? []);+ if (prev && prev.slug !== slug) aliases.add(prev.slug);+ aliases.delete(slug);++ reserved.add(slug);+ out.set(c.upstreamComponentId, { slug, aliases: [...aliases] });+ }+ return out;+}diff --git a/packages/services/src/external-service-component/list.ts b/packages/services/src/external-service-component/list.tsnew file mode 100644index 000000000..f9989fc0a--- /dev/null+++ b/packages/services/src/external-service-component/list.ts@@ -0,0 +1,183 @@+import { and, asc, db as defaultDb, eq, gte, or, sql } from "@openstatus/db";+import type { ApiConfigType, ExternalService } from "@openstatus/db/src/schema";+import { externalServiceComponent } from "@openstatus/db/src/schema";++import { getExternalServiceBySlug } from "../external-service";+import type { GlobalReadContext } from "../external-service/internal";++export type ExternalComponentListItem = {+ id: number;+ externalServiceId: number;+ upstreamComponentId: string;+ slug: string;+ name: string;+ description: string | null;+ groupName: string | null;+ position: number;+ indicator: string;+ status: string;+ firstSeenAt: Date;+ lastSeenAt: Date;+};++// A component absent from upstream for longer than this is hidden from the page+// without being deleted (ADR-0007): the next tick that re-sees it brings it back.+const COMPONENT_STALE_MS = 24 * 60 * 60 * 1000;++// must stay in sync with fetchers that implement `fetchComponents` in @openstatus/status-fetcher+export const COMPONENT_SUPPORTED_API_CONFIG_TYPES = new Set<ApiConfigType>([+ "atlassian",+ "incidentio",+]);++export function supportsComponents(type: ApiConfigType | undefined): boolean {+ return type !== undefined && COMPONENT_SUPPORTED_API_CONFIG_TYPES.has(type);+}++export async function listExternalComponentsByServiceId(args: {+ ctx?: GlobalReadContext;+ externalServiceId: number;+ now?: Date;+}): Promise<ExternalComponentListItem[]> {+ const { ctx, externalServiceId } = args;+ const db = ctx?.db ?? defaultDb;+ const cutoff = new Date(+ (args.now ?? new Date()).getTime() - COMPONENT_STALE_MS,+ );++ const rows = await db+ .select({+ id: externalServiceComponent.id,+ externalServiceId: externalServiceComponent.externalServiceId,+ upstreamComponentId: externalServiceComponent.upstreamComponentId,+ slug: externalServiceComponent.slug,+ name: externalServiceComponent.name,+ description: externalServiceComponent.description,+ groupName: externalServiceComponent.groupName,+ position: externalServiceComponent.position,+ indicator: externalServiceComponent.indicator,+ status: externalServiceComponent.status,+ firstSeenAt: externalServiceComponent.firstSeenAt,+ lastSeenAt: externalServiceComponent.lastSeenAt,+ })+ .from(externalServiceComponent)+ .where(+ and(+ eq(externalServiceComponent.externalServiceId, externalServiceId),+ gte(externalServiceComponent.lastSeenAt, cutoff),+ ),+ )+ .orderBy(+ asc(externalServiceComponent.position),+ asc(externalServiceComponent.name),+ )+ .all();++ return rows;+}++export type ListComponentsBySlugResult = {+ service: { id: number; apiConfigType?: ApiConfigType } | null;+ supported: boolean;+ components: ExternalComponentListItem[];+};++export async function listExternalComponentsBySlug(args: {+ ctx?: GlobalReadContext;+ slug: string;+ now?: Date;+}): Promise<ListComponentsBySlugResult> {+ const { ctx, slug } = args;+ const service = await getExternalServiceBySlug({ ctx, slug });+ if (!service) {+ return { service: null, supported: false, components: [] };+ }++ const apiConfigType = service.apiConfig?.type;+ if (!supportsComponents(apiConfigType)) {+ return {+ service: { id: service.id, apiConfigType },+ supported: false,+ components: [],+ };+ }++ const components = await listExternalComponentsByServiceId({+ ctx,+ externalServiceId: service.id,+ now: args.now,+ });++ return {+ service: { id: service.id, apiConfigType },+ supported: true,+ components,+ };+}++export type ExternalComponentDetail = ExternalComponentListItem & {+ aliases: string[];+ stale: boolean;+};++export type GetComponentBySlugResult = {+ service: ExternalService | null;+ component: ExternalComponentDetail | null;+};++// Resolves a component within a service by its current slug OR a past alias,+// WITHOUT the staleness filter — old/renamed URLs still resolve (the page renders+// last-known + noindex when `stale`). Returns the service so the page can do the+// canonical-slug 308 checks for both segments.+export async function getExternalComponentBySlug(args: {+ ctx?: GlobalReadContext;+ serviceSlug: string;+ componentSlug: string;+ now?: Date;+}): Promise<GetComponentBySlugResult> {+ const { ctx, serviceSlug, componentSlug } = args;+ const db = ctx?.db ?? defaultDb;++ const service = await getExternalServiceBySlug({ ctx, slug: serviceSlug });+ if (!service) return { service: null, component: null };++ const rows = await db+ .select({+ id: externalServiceComponent.id,+ externalServiceId: externalServiceComponent.externalServiceId,+ upstreamComponentId: externalServiceComponent.upstreamComponentId,+ slug: externalServiceComponent.slug,+ aliases: externalServiceComponent.aliases,+ name: externalServiceComponent.name,+ description: externalServiceComponent.description,+ groupName: externalServiceComponent.groupName,+ position: externalServiceComponent.position,+ indicator: externalServiceComponent.indicator,+ status: externalServiceComponent.status,+ firstSeenAt: externalServiceComponent.firstSeenAt,+ lastSeenAt: externalServiceComponent.lastSeenAt,+ })+ .from(externalServiceComponent)+ .where(+ and(+ eq(externalServiceComponent.externalServiceId, service.id),+ or(+ eq(externalServiceComponent.slug, componentSlug),+ sql`EXISTS (SELECT 1 FROM json_each(${externalServiceComponent.aliases}) WHERE value = ${componentSlug})`,+ ),+ ),+ )+ .limit(1)+ .all();++ const row = rows[0];+ if (!row) return { service, component: null };++ const cutoff = new Date(+ (args.now ?? new Date()).getTime() - COMPONENT_STALE_MS,+ );+ return {+ service,+ component: { ...row, stale: row.lastSeenAt < cutoff },+ };+}diff --git a/packages/services/src/external-service-component/upsert.ts b/packages/services/src/external-service-component/upsert.tsnew file mode 100644index 000000000..f7023586a--- /dev/null+++ b/packages/services/src/external-service-component/upsert.ts@@ -0,0 +1,114 @@+import { db as defaultDb, eq, sql } from "@openstatus/db";+import { externalServiceComponent } from "@openstatus/db/src/schema";++import type { DB } from "../context";+import { withBusyRetry } from "../retry";+import { assignComponentSlugs } from "./internal";++export type UpsertExternalComponentInput = {+ upstreamComponentId: string;+ name: string;+ description?: string;+ groupName?: string;+ position: number;+ indicator: string;+ status: string;+};++export type UpsertedComponent = {+ id: number;+ upstreamComponentId: string;+};++export type UpsertExternalComponentsResult = {+ upserted: UpsertedComponent[];+};++export async function upsertExternalComponentsForService(args: {+ ctx?: { db?: DB };+ externalServiceId: number;+ components: UpsertExternalComponentInput[];+ now?: Date;+}): Promise<UpsertExternalComponentsResult> {+ const { ctx, externalServiceId, components } = args;+ if (components.length === 0) return { upserted: [] };++ const now = args.now ?? new Date();+ const db = ctx?.db ?? defaultDb;++ // No `withTransaction`/`emitAudit`: external services are a global, public,+ // cron-driven catalogue with no workspace scope or audit log (ADR-0006/0007),+ // mirroring `upsertExternalIncidentsForService`. `withBusyRetry` wraps the raw+ // transaction since the audit-aware helper expects a workspace ServiceContext.+ return withBusyRetry(() =>+ db.transaction(async (tx) => {+ const existing = await tx+ .select({+ upstreamComponentId: externalServiceComponent.upstreamComponentId,+ name: externalServiceComponent.name,+ slug: externalServiceComponent.slug,+ aliases: externalServiceComponent.aliases,+ })+ .from(externalServiceComponent)+ .where(+ eq(externalServiceComponent.externalServiceId, externalServiceId),+ )+ .all();++ const slugs = assignComponentSlugs({+ existing,+ incoming: components.map((c) => ({+ upstreamComponentId: c.upstreamComponentId,+ name: c.name,+ })),+ });++ const values = components.map((c) => {+ const assigned = slugs.get(c.upstreamComponentId);+ return {+ externalServiceId,+ upstreamComponentId: c.upstreamComponentId,+ slug: assigned?.slug ?? c.upstreamComponentId,+ aliases: assigned?.aliases ?? [],+ name: c.name,+ description: c.description,+ groupName: c.groupName,+ position: c.position,+ indicator: c.indicator,+ status: c.status,+ firstSeenAt: now,+ lastSeenAt: now,+ updatedAt: now,+ };+ });++ const rows = await tx+ .insert(externalServiceComponent)+ .values(values)+ .onConflictDoUpdate({+ target: [+ externalServiceComponent.externalServiceId,+ externalServiceComponent.upstreamComponentId,+ ],+ set: {+ slug: sql`excluded.slug`,+ aliases: sql`excluded.aliases`,+ name: sql`excluded.name`,+ description: sql`excluded.description`,+ groupName: sql`excluded.group_name`,+ position: sql`excluded.position`,+ indicator: sql`excluded.indicator`,+ status: sql`excluded.status`,+ lastSeenAt: now,+ updatedAt: now,+ },+ })+ .returning({+ id: externalServiceComponent.id,+ upstreamComponentId: externalServiceComponent.upstreamComponentId,+ })+ .all();+ return { upserted: rows };+ }),+ );+}diff --git a/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts b/packages/services/src/external-service-incident/__tests__/external-service-incident.test.tsindex a2ad30832..e9ea0a0d9 100644--- a/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts+++ b/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import {+ listExternalIncidentsByComponent,listExternalIncidentsBySlug,pruneStaleRawPayloads,upsertExternalIncidentsForService,@@ -274,6 +275,57 @@ describe("listExternalIncidentsBySlug", () => {});});+describe("listExternalIncidentsByComponent", () => {+ test("returns only incidents tagged with the upstream component id", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-bycomp` });++ await upsertExternalIncidentsForService({+ externalServiceId: serviceId,+ incidents: [+ {+ providerIncidentId: "i-fra",+ name: "Frankfurt outage",+ status: "resolved",+ createdAt: new Date("2024-06-01T00:00:00.000Z"),+ startedAt: new Date("2024-06-01T00:00:00.000Z"),+ resolvedAt: new Date("2024-06-01T01:00:00.000Z"),+ affectedComponentIds: ["cmp-fra", "cmp-shared"],+ raw: {},+ },+ {+ providerIncidentId: "i-other",+ name: "Stockholm only",+ status: "resolved",+ createdAt: new Date("2024-06-02T00:00:00.000Z"),+ startedAt: new Date("2024-06-02T00:00:00.000Z"),+ resolvedAt: new Date("2024-06-02T01:00:00.000Z"),+ affectedComponentIds: ["cmp-arn"],+ raw: {},+ },+ ],+ });++ const fra = await listExternalIncidentsByComponent({+ externalServiceId: serviceId,+ upstreamComponentId: "cmp-fra",+ });+ expect(fra).toHaveLength(1);+ expect(fra[0]?.providerIncidentId).toBe("i-fra");++ const shared = await listExternalIncidentsByComponent({+ externalServiceId: serviceId,+ upstreamComponentId: "cmp-shared",+ });+ expect(shared).toHaveLength(1);++ const none = await listExternalIncidentsByComponent({+ externalServiceId: serviceId,+ upstreamComponentId: "cmp-unknown",+ });+ expect(none).toHaveLength(0);+ });+});+describe("pruneStaleRawPayloads", () => {test("nulls raw_payload for resolved incidents past the TTL only", async () => {const serviceId = await seedService({ slug: `${TEST_PREFIX}-prune` });diff --git a/packages/services/src/external-service-incident/index.ts b/packages/services/src/external-service-incident/index.tsindex c72852679..2d1a6d5de 100644--- a/packages/services/src/external-service-incident/index.ts+++ b/packages/services/src/external-service-incident/index.ts@@ -7,6 +7,7 @@ export {type ExternalIncidentListItem,type ListBySlugResult,INCIDENT_SUPPORTED_API_CONFIG_TYPES,+ listExternalIncidentsByComponent,listExternalIncidentsByServiceId,listExternalIncidentsBySlug,supportsIncidents,diff --git a/packages/services/src/external-service-incident/list.ts b/packages/services/src/external-service-incident/list.tsindex 24a855958..b4427c32c 100644--- a/packages/services/src/external-service-incident/list.ts+++ b/packages/services/src/external-service-incident/list.ts@@ -1,4 +1,4 @@-import { db as defaultDb, desc, eq, sql } from "@openstatus/db";+import { and, db as defaultDb, desc, eq, sql } from "@openstatus/db";import type { ApiConfigType } from "@openstatus/db/src/schema";import { externalServiceIncident } from "@openstatus/db/src/schema";@@ -70,6 +70,52 @@ export async function listExternalIncidentsByServiceId(args: {return rows;}+// Incidents whose Atlassian `components[]` array tagged this component (matched+// by the upstream component id stored in `affected_component_ids`), recent-first.+export async function listExternalIncidentsByComponent(args: {+ ctx?: GlobalReadContext;+ externalServiceId: number;+ upstreamComponentId: string;+ limit?: number;+}): Promise<ExternalIncidentListItem[]> {+ const { ctx, externalServiceId, upstreamComponentId } = args;+ const db = ctx?.db ?? defaultDb;+ const limit = args.limit ?? DEFAULT_LIMIT;++ const rows = await db+ .select({+ id: externalServiceIncident.id,+ externalServiceId: externalServiceIncident.externalServiceId,+ providerIncidentId: externalServiceIncident.providerIncidentId,+ name: externalServiceIncident.name,+ status: externalServiceIncident.status,+ impact: externalServiceIncident.impact,+ shortlink: externalServiceIncident.shortlink,+ startedAt: externalServiceIncident.startedAt,+ createdAt: externalServiceIncident.createdAt,+ resolvedAt: externalServiceIncident.resolvedAt,+ firstSeenAt: externalServiceIncident.firstSeenAt,+ lastSeenAt: externalServiceIncident.lastSeenAt,+ })+ .from(externalServiceIncident)+ .where(+ and(+ eq(externalServiceIncident.externalServiceId, externalServiceId),+ sql`EXISTS (SELECT 1 FROM json_each(${externalServiceIncident.affectedComponentIds}) WHERE value = ${upstreamComponentId})`,+ ),+ )+ .orderBy(+ desc(+ sql`COALESCE(${externalServiceIncident.startedAt}, ${externalServiceIncident.createdAt})`,+ ),+ desc(externalServiceIncident.createdAt),+ )+ .limit(limit)+ .all();++ return rows;+}+export type ListBySlugResult = {service: { id: number; apiConfigType?: ApiConfigType } | null;supported: boolean;diff --git a/packages/services/src/external-service-incident/upsert.ts b/packages/services/src/external-service-incident/upsert.tsindex e906a6506..d2964ba50 100644--- a/packages/services/src/external-service-incident/upsert.ts+++ b/packages/services/src/external-service-incident/upsert.ts@@ -13,6 +13,7 @@ export type UpsertExternalIncidentInput = {startedAt?: Date;createdAt: Date;resolvedAt: Date | null;+ affectedComponentIds?: string[];raw: unknown;};@@ -42,6 +43,7 @@ export async function upsertExternalIncidentsForService(args: {startedAt: incident.startedAt,createdAt: incident.createdAt,resolvedAt: incident.resolvedAt,+ affectedComponentIds: incident.affectedComponentIds ?? [],rawPayload: incident.raw,rawPayloadPurgedAt: null,firstSeenAt: now,@@ -66,6 +68,7 @@ export async function upsertExternalIncidentsForService(args: {shortlink: sql`excluded.shortlink`,startedAt: sql`excluded.started_at`,resolvedAt: sql`excluded.resolved_at`,+ affectedComponentIds: sql`excluded.affected_component_ids`,rawPayload: sql`excluded.raw_payload`,rawPayloadPurgedAt: null,lastSeenAt: now,diff --git a/packages/status-fetcher/__tests__/fetchers/components.test.ts b/packages/status-fetcher/__tests__/fetchers/components.test.tsnew file mode 100644index 000000000..498847b47--- /dev/null+++ b/packages/status-fetcher/__tests__/fetchers/components.test.ts@@ -0,0 +1,157 @@+import { beforeEach, describe, expect, it } from "bun:test";+import { AtlassianFetcher } from "../../src/fetchers/atlassian";+import { IncidentioFetcher } from "../../src/fetchers/incidentio";+import type { StatusFetcher, StatusPageEntry } from "../../src/types";+import {+ expectComponentsFetchError,+ installMockFetch,+ runComponents,+ runComponentsExit,+} from "../helpers";++const atlassianEntry: StatusPageEntry = {+ id: "vercel",+ name: "Vercel",+ url: "https://vercel.com",+ status_page_url: "https://www.vercel-status.com",+ provider: "atlassian-statuspage",+ industry: ["development-tools"],+ api_config: { type: "atlassian" },+};++const incidentioEntry: StatusPageEntry = {+ id: "linear",+ name: "Linear",+ url: "https://linear.app",+ status_page_url: "https://status.linear.app",+ provider: "incidentio",+ industry: ["development-tools"],+ api_config: { type: "incidentio" },+};++const mockComponents = [+ {+ id: "grp",+ name: "Regions",+ status: "operational",+ group: true,+ group_id: null,+ position: 1,+ },+ {+ id: "fra1",+ name: "Frankfurt",+ description: "EU Central edge",+ status: "partial_outage",+ group: false,+ group_id: "grp",+ position: 3,+ },+ {+ id: "arn1",+ name: "Stockholm",+ status: "degraded_performance",+ group: false,+ group_id: "grp",+ position: 2,+ },+ {+ id: "api",+ name: "API",+ status: "under_maintenance",+ group: false,+ group_id: null,+ position: 5,+ },+];++function itNormalizes(+ label: string,+ fetcher: StatusFetcher,+ entry: StatusPageEntry,+) {+ it(`normalizes ${label} components and drops group containers`, async () => {+ const fetchMock = installMockFetch(() =>+ Promise.resolve({+ ok: true,+ json: async () => ({ components: mockComponents }),+ } as Response),+ );++ const components = await runComponents(fetcher, entry);++ expect(fetchMock).toHaveBeenCalledWith(+ `${entry.status_page_url}/api/v2/components.json`,+ expect.any(Object),+ );++ // group container "grp" is excluded; only the three leaves remain+ expect(components).toHaveLength(3);++ const byId = new Map(components.map((c) => [c.upstreamComponentId, c]));++ expect(byId.get("fra1")).toMatchObject({+ name: "Frankfurt",+ description: "EU Central edge",+ groupName: "Regions",+ position: 3,+ severity: "major",+ status: "partial_outage",+ });+ expect(byId.get("arn1")).toMatchObject({+ groupName: "Regions",+ severity: "minor",+ status: "degraded",+ });+ expect(byId.get("api")).toMatchObject({+ name: "API",+ groupName: undefined,+ severity: "none",+ status: "under_maintenance",+ });+ });+}++describe("fetchComponents", () => {+ let atlassian: AtlassianFetcher;++ beforeEach(() => {+ atlassian = new AtlassianFetcher();+ });++ describe("AtlassianFetcher", () => {+ itNormalizes("atlassian", new AtlassianFetcher(), atlassianEntry);++ it("fails with FetchError on malformed payload", async () => {+ installMockFetch(() =>+ Promise.resolve({+ ok: true,+ json: async () => ({ not: "an array" }),+ } as Response),+ );++ const exit = await runComponentsExit(atlassian, atlassianEntry);+ const err = expectComponentsFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);+ });++ it("fails with FetchError on non-200", async () => {+ installMockFetch(() =>+ Promise.resolve({+ ok: false,+ status: 503,+ statusText: "Service Unavailable",+ } as Response),+ );++ const exit = await runComponentsExit(atlassian, atlassianEntry);+ const err = expectComponentsFetchError(exit);+ expect(err.httpStatus).toBe(503);+ expect(err.fetcherName).toBe("atlassian");+ });+ });++ describe("IncidentioFetcher", () => {+ itNormalizes("incidentio", new IncidentioFetcher(), incidentioEntry);+ });+});diff --git a/packages/status-fetcher/__tests__/helpers.ts b/packages/status-fetcher/__tests__/helpers.tsindex 0cf67b22f..66c935016 100644--- a/packages/status-fetcher/__tests__/helpers.ts+++ b/packages/status-fetcher/__tests__/helpers.ts@@ -2,6 +2,7 @@ import { mock } from "bun:test";import { Cause, Effect, Exit, Option } from "effect";import type { FetchError } from "../src/fetch";import type {+ NormalizedComponent,NormalizedIncident,StatusFetcher,StatusPageEntry,@@ -71,3 +72,36 @@ export const expectIncidentsFetchError = (}return failure.value;};++export const runComponents = (+ fetcher: StatusFetcher,+ entry: StatusPageEntry,+): Promise<NormalizedComponent[]> => {+ if (!fetcher.fetchComponents) {+ throw new Error(`fetcher ${fetcher.name} has no fetchComponents`);+ }+ return Effect.runPromise(fetcher.fetchComponents(entry));+};++export const runComponentsExit = (+ fetcher: StatusFetcher,+ entry: StatusPageEntry,+) => {+ if (!fetcher.fetchComponents) {+ throw new Error(`fetcher ${fetcher.name} has no fetchComponents`);+ }+ return Effect.runPromiseExit(fetcher.fetchComponents(entry));+};++export const expectComponentsFetchError = (+ exit: Exit.Exit<NormalizedComponent[], FetchError>,+): FetchError => {+ if (!Exit.isFailure(exit)) {+ throw new Error("expected Exit.Failure, got Success");+ }+ const failure = Cause.failureOption(exit.cause);+ if (Option.isNone(failure)) {+ throw new Error("expected Cause.Fail, got defect");+ }+ return failure.value;+};diff --git a/packages/status-fetcher/src/components.ts b/packages/status-fetcher/src/components.tsnew file mode 100644index 000000000..55e2d2e77--- /dev/null+++ b/packages/status-fetcher/src/components.ts@@ -0,0 +1,85 @@+import { Effect } from "effect";+import { z } from "zod";+import { type FetchError, fetchJson } from "./fetch";+import type {+ NormalizedComponent,+ SeverityLevel,+ StatusPageEntry,+ StatusType,+} from "./types";++export const atlassianComponentSchema = z.object({+ id: z.string(),+ name: z.string(),+ status: z.string(),+ description: z.string().nullable().optional(),+ position: z.number().optional(),+ group: z.boolean().optional(),+ group_id: z.string().nullable().optional(),+});++export const atlassianComponentsResponseSchema = z.object({+ components: z.array(atlassianComponentSchema),+});++export type AtlassianComponent = z.infer<typeof atlassianComponentSchema>;++const STATUS_MAP: Record<+ string,+ { severity: SeverityLevel; status: StatusType }+> = {+ operational: { severity: "none", status: "operational" },+ degraded_performance: { severity: "minor", status: "degraded" },+ partial_outage: { severity: "major", status: "partial_outage" },+ major_outage: { severity: "critical", status: "major_outage" },+ under_maintenance: { severity: "none", status: "under_maintenance" },+};++function mapStatus(raw: string): {+ severity: SeverityLevel;+ status: StatusType;+} {+ return STATUS_MAP[raw] ?? { severity: "none", status: "operational" };+}++function normalizeAtlassianComponents(+ components: AtlassianComponent[],+): NormalizedComponent[] {+ const groupNameById = new Map<string, string>();+ for (const c of components) {+ if (c.group) groupNameById.set(c.id, c.name);+ }++ const out: NormalizedComponent[] = [];+ for (const c of components) {+ // Group containers become section headers in the UI, not rows.+ if (c.group) continue;+ const { severity, status } = mapStatus(c.status);+ out.push({+ upstreamComponentId: c.id,+ name: c.name,+ description: c.description ?? undefined,+ groupName: c.group_id ? groupNameById.get(c.group_id) : undefined,+ position: c.position ?? 0,+ severity,+ status,+ });+ }+ return out;+}++export const fetchAtlassianCompatibleComponents = (args: {+ entry: StatusPageEntry;+ fetcherName: string;+}): Effect.Effect<NormalizedComponent[], FetchError> => {+ const { entry, fetcherName } = args;+ // `api_config.endpoint` overrides the summary URL only; components always come+ // from the standard `/api/v2/components.json` path under status_page_url.+ const url = `${entry.status_page_url}/api/v2/components.json`;+ return fetchJson({+ url,+ schema: atlassianComponentsResponseSchema,+ fetcherName,+ entryId: entry.id,+ }).pipe(Effect.map((data) => normalizeAtlassianComponents(data.components)));+};diff --git a/packages/status-fetcher/src/fetchers/atlassian.ts b/packages/status-fetcher/src/fetchers/atlassian.tsindex 062808666..063c1f96e 100644--- a/packages/status-fetcher/src/fetchers/atlassian.ts+++ b/packages/status-fetcher/src/fetchers/atlassian.ts@@ -1,8 +1,10 @@import { Effect } from "effect";import { z } from "zod";+import { fetchAtlassianCompatibleComponents } from "../components";import { type FetchError, fetchJson } from "../fetch";import { fetchAtlassianCompatibleIncidents } from "../incidents";import type {+ NormalizedComponent,NormalizedIncident,StatusFetcher,StatusPageEntry,@@ -66,4 +68,13 @@ export class AtlassianFetcher implements StatusFetcher {): Effect.Effect<NormalizedIncident[], FetchError> {return fetchAtlassianCompatibleIncidents({ entry, fetcherName: this.name });}++ fetchComponents(+ entry: StatusPageEntry,+ ): Effect.Effect<NormalizedComponent[], FetchError> {+ return fetchAtlassianCompatibleComponents({+ entry,+ fetcherName: this.name,+ });+ }}diff --git a/packages/status-fetcher/src/fetchers/incidentio.ts b/packages/status-fetcher/src/fetchers/incidentio.tsindex 21200ca2c..40e6dcadc 100644--- a/packages/status-fetcher/src/fetchers/incidentio.ts+++ b/packages/status-fetcher/src/fetchers/incidentio.ts@@ -1,8 +1,10 @@import { Effect } from "effect";import { z } from "zod";+import { fetchAtlassianCompatibleComponents } from "../components";import { type FetchError, fetchJson } from "../fetch";import { fetchAtlassianCompatibleIncidents } from "../incidents";import type {+ NormalizedComponent,NormalizedIncident,StatusFetcher,StatusPageEntry,@@ -69,4 +71,13 @@ export class IncidentioFetcher implements StatusFetcher {): Effect.Effect<NormalizedIncident[], FetchError> {return fetchAtlassianCompatibleIncidents({ entry, fetcherName: this.name });}++ fetchComponents(+ entry: StatusPageEntry,+ ): Effect.Effect<NormalizedComponent[], FetchError> {+ return fetchAtlassianCompatibleComponents({+ entry,+ fetcherName: this.name,+ });+ }}diff --git a/packages/status-fetcher/src/incidents.ts b/packages/status-fetcher/src/incidents.tsindex 6354f0aaf..cfc0c6643 100644--- a/packages/status-fetcher/src/incidents.ts+++ b/packages/status-fetcher/src/incidents.ts@@ -12,6 +12,10 @@ export const atlassianIncidentSchema = z.object({started_at: z.string().optional(),created_at: z.string(),resolved_at: z.string().nullable().optional(),+ components: z+ .array(z.object({ id: z.string() }))+ .optional()+ .default([]),});export const atlassianIncidentsResponseSchema = z.object({@@ -43,6 +47,7 @@ const normalizeAtlassianIncident = (startedAt: parsed.started_at ? new Date(parsed.started_at) : undefined,createdAt: new Date(parsed.created_at),resolvedAt: parsed.resolved_at ? new Date(parsed.resolved_at) : null,+ affectedComponentIds: parsed.components.map((c) => c.id),raw,});diff --git a/packages/status-fetcher/src/index.ts b/packages/status-fetcher/src/index.tsindex 2e493a70d..c53c804c2 100644--- a/packages/status-fetcher/src/index.ts+++ b/packages/status-fetcher/src/index.ts@@ -8,4 +8,10 @@ export {fetchAtlassianCompatibleIncidents,} from "./incidents";export type { AtlassianIncident } from "./incidents";+export {+ atlassianComponentSchema,+ atlassianComponentsResponseSchema,+ fetchAtlassianCompatibleComponents,+} from "./components";+export type { AtlassianComponent } from "./components";export type { DirectoryEntry } from "./data/index";diff --git a/packages/status-fetcher/src/types.ts b/packages/status-fetcher/src/types.tsindex 02630fcdb..ac2927983 100644--- a/packages/status-fetcher/src/types.ts+++ b/packages/status-fetcher/src/types.ts@@ -124,9 +124,20 @@ export interface NormalizedIncident {startedAt?: Date;createdAt: Date;resolvedAt: Date | null;+ affectedComponentIds: string[];raw: JsonValue;}+export interface NormalizedComponent {+ upstreamComponentId: string;+ name: string;+ description?: string;+ groupName?: string;+ position: number;+ severity: SeverityLevel;+ status: StatusType;+}+export interface StatusFetcher {name: string;canHandle(entry: StatusPageEntry): boolean;@@ -134,4 +145,7 @@ export interface StatusFetcher {fetchIncidents?(entry: StatusPageEntry,): Effect.Effect<NormalizedIncident[], FetchError>;+ fetchComponents?(+ entry: StatusPageEntry,+ ): Effect.Effect<NormalizedComponent[], FetchError>;}diff --git a/packages/tinybird/datasources/external_status_component__v0.datasource b/packages/tinybird/datasources/external_status_component__v0.datasourcenew file mode 100644index 000000000..5b8f1ffae--- /dev/null+++ b/packages/tinybird/datasources/external_status_component__v0.datasource@@ -0,0 +1,14 @@+# `external_service_id` is denormalised for raw-row traceability only: in raw+# rows `component_id` is an opaque PK, so this lets ops trace a snapshot back to+# its service without a Turso join. Pipes/MV key on `component_id`.++SCHEMA >+ `component_id` String `json:$.component_id`,+ `external_service_id` Int64 `json:$.external_service_id`,+ `indicator` String `json:$.indicator`,+ `status` String `json:$.status`,+ `fetched_at` Int64 `json:$.fetched_at`++ENGINE "MergeTree"+ENGINE_SORTING_KEY "component_id, fetched_at"+ENGINE_TTL "toDateTime(fromUnixTimestamp64Milli(fetched_at)) + INTERVAL 60 DAY"diff --git a/packages/tinybird/datasources/mv__external_status_component_daily__v0.datasource b/packages/tinybird/datasources/mv__external_status_component_daily__v0.datasourcenew file mode 100644index 000000000..bb1e4160f--- /dev/null+++ b/packages/tinybird/datasources/mv__external_status_component_daily__v0.datasource@@ -0,0 +1,12 @@+# Data Source created from Pipe 'mv__external_status_component_daily__v0'++SCHEMA >+ `day` Date,+ `component_id` String,+ `worst_indicator` AggregateFunction(argMax, String, UInt8),+ `had_maintenance` AggregateFunction(max, UInt8),+ `snapshot_count` AggregateFunction(sum, UInt32)++ENGINE "AggregatingMergeTree"+ENGINE_PARTITION_KEY "toYYYYMM(day)"+ENGINE_SORTING_KEY "component_id, day"diff --git a/packages/tinybird/endpoints/endpoint__external_status_component_history__v0.pipe b/packages/tinybird/endpoints/endpoint__external_status_component_history__v0.pipenew file mode 100644index 000000000..d7b092554--- /dev/null+++ b/packages/tinybird/endpoints/endpoint__external_status_component_history__v0.pipe@@ -0,0 +1,21 @@+TAGS "external_status"++NODE history+SQL >++ %+ SELECT+ day,+ component_id,+ argMaxMerge(worst_indicator) AS worst_indicator,+ maxMerge(had_maintenance) AS had_maintenance,+ sumMerge(snapshot_count) AS snapshot_count+ FROM mv__external_status_component_daily__v0+ WHERE component_id IN {{ Array(component_ids, 'String') }}+ {% if defined(days) %}+ AND day >= today() - INTERVAL {{ Int16(days, 45) }} DAY+ {% end %}+ GROUP BY day, component_id+ ORDER BY day ASC++TYPE ENDPOINTdiff --git a/packages/tinybird/pipes/aggregate__external_status_component_daily__v0.pipe b/packages/tinybird/pipes/aggregate__external_status_component_daily__v0.pipenew file mode 100644index 000000000..46dfdf2fa--- /dev/null+++ b/packages/tinybird/pipes/aggregate__external_status_component_daily__v0.pipe@@ -0,0 +1,28 @@+TAGS "external_status"++NODE aggregate+SQL >++ SELECT+ toDate(toTimeZone(fromUnixTimestamp64Milli(fetched_at), 'UTC')) AS day,+ component_id,+ argMaxState(+ indicator,+ toUInt8(+ multiIf(+ indicator = 'critical', 3,+ indicator = 'major', 2,+ indicator = 'minor', 1,+ 0+ )+ )+ ) AS worst_indicator,+ maxState(toUInt8(status = 'under_maintenance')) AS had_maintenance,+ sumState(toUInt32(1)) AS snapshot_count+ FROM external_status_component__v0+ GROUP BY+ day,+ component_id++TYPE materialized+DATASOURCE mv__external_status_component_daily__v0diff --git a/packages/tinybird/src/client.ts b/packages/tinybird/src/client.tsindex 89b8fcc3f..5589a03f6 100644--- a/packages/tinybird/src/client.ts+++ b/packages/tinybird/src/client.ts@@ -12,6 +12,15 @@ const PUBLIC_CACHE = 300; // 5 * 60 = 300s = 5mconst DEV_CACHE = 10 * 60; // 10mconst REVALIDATE = process.env.NODE_ENV === "development" ? DEV_CACHE : 0;+// Daily-aggregate columns shared by the external-status history pipes (page-+// level and per-component). One shape so the `day` GMT-parse can't drift.+const externalStatusHistoryDailyShape = {+ day: z.string().transform((val) => new Date(`${val} GMT`).toISOString()),+ worst_indicator: z.string(),+ had_maintenance: z.int(),+ snapshot_count: z.int(),+};+export class OSTinybird {private readonly tb: Client;@@ -1808,13 +1817,36 @@ export class OSTinybird {days: z.int().min(1).max(90).optional(),}),data: z.object({- day: z.string().transform((val) => {- return new Date(`${val} GMT`).toISOString();- }),+ ...externalStatusHistoryDailyShape,id: z.string(),- worst_indicator: z.string(),- had_maintenance: z.int(),- snapshot_count: z.int(),+ }),+ opts: { next: { revalidate: REVALIDATE } },+ });+ }++ public get publishExternalStatusComponent() {+ return this.tb.buildIngestEndpoint({+ datasource: "external_status_component__v0",+ event: z.object({+ component_id: z.string(),+ external_service_id: z.int(),+ indicator: z.string(),+ status: z.string(),+ fetched_at: z.int(),+ }),+ });+ }++ public get externalStatusComponentHistory() {+ return this.tb.buildPipe({+ pipe: "endpoint__external_status_component_history__v0",+ parameters: z.object({+ component_ids: z.array(z.string()).min(1),+ days: z.int().min(1).max(90).optional(),+ }),+ data: z.object({+ ...externalStatusHistoryDailyShape,+ component_id: z.string(),}),opts: { next: { revalidate: REVALIDATE } },});