Skip to content

Open-source status page, incident response and uptime monitoring

14.0 KB
Raw Blame
import type { PageConfiguration as DBPageConfiguration } from "@openstatus/db/src/schema";
import { defaultLocale, type Locale } from "@openstatus/locales";
import type {
  CustomTheme,
  PageComponent,
  PageComponentGroup,
  PageConfiguration,
  PageSubscriber,
  StatusPage,
  StatusPageSummary,
  WebhookChannelHeader,
} from "@openstatus/proto/status_page/v1";
import {
  ComponentDayStatus,
  ComponentEventStatus,
  ComponentEventType,
  PageAccessType,
  PageBarType,
  PageComponentType,
  PageMetricType,
  PageTheme,
  Locale as ProtoLocale,
  SubscriberSource,
} from "@openstatus/proto/status_page/v1";
import {
  type CustomTheme as DbCustomTheme,
  hasCustomTheme,
} from "@openstatus/theme-store";

/**
 * Database types
 */
type DBPage = {
  id: number;
  title: string;
  description: string;
  slug: string;
  customDomain: string;
  published: boolean | null;
  forceTheme: "system" | "light" | "dark";
  accessType: "public" | "password" | "email-domain" | "ip-restriction" | null;
  homepageUrl: string | null;
  contactUrl: string | null;
  icon: string | null;
  password: string | null;
  authEmailDomains: string | null;
  allowedIpRanges: string | null;
  defaultLocale: Locale;
  locales: Locale[] | null;
  allowIndex: boolean;
  customTheme?: DbCustomTheme | null;
  createdAt: Date | null;
  updatedAt: Date | null;
};

type DBPageComponent = {
  id: number;
  pageId: number;
  name: string;
  description: string | null;
  type: "static" | "monitor";
  monitorId: number | null;
  order: number | null;
  groupId: number | null;
  groupOrder: number | null;
  createdAt: Date | null;
  updatedAt: Date | null;
};

type DBPageComponentGroup = {
  id: number;
  pageId: number;
  name: string;
  defaultOpen: boolean | null;
  createdAt: Date | null;
  updatedAt: Date | null;
};

export type DBPageSubscriber = {
  id: number;
  pageId: number;
  email: string | null;
  acceptedAt: Date | null;
  unsubscribedAt: Date | null;
  createdAt: Date | null;
  updatedAt: Date | null;
  source: "self_signup" | "vendor" | "import";
  name: string | null;
  channelType: "email" | "webhook" | "slack";
  webhookUrl: string | null;
  channelConfig: string | null;
  componentIds?: number[];
};

/**
 * Convert DB access type string to proto enum.
 */
export function dbAccessTypeToProto(
  accessType: "public" | "password" | "email-domain" | "ip-restriction" | null,
): PageAccessType {
  switch (accessType) {
    case "public":
      return PageAccessType.PUBLIC;
    case "password":
      return PageAccessType.PASSWORD_PROTECTED;
    case "email-domain":
      return PageAccessType.AUTHENTICATED;
    case "ip-restriction":
      return PageAccessType.IP_RESTRICTED;
    default:
      return PageAccessType.PUBLIC;
  }
}

/**
 * Convert proto access type enum to DB string.
 */
export function protoAccessTypeToDb(
  accessType: PageAccessType,
): "public" | "password" | "email-domain" | "ip-restriction" {
  switch (accessType) {
    case PageAccessType.PUBLIC:
      return "public";
    case PageAccessType.PASSWORD_PROTECTED:
      return "password";
    case PageAccessType.AUTHENTICATED:
      return "email-domain";
    case PageAccessType.IP_RESTRICTED:
      return "ip-restriction";
    default:
      return "public";
  }
}

/**
 * Convert DB theme string to proto enum.
 */
export function dbThemeToProto(theme: "system" | "light" | "dark"): PageTheme {
  switch (theme) {
    case "system":
      return PageTheme.SYSTEM;
    case "light":
      return PageTheme.LIGHT;
    case "dark":
      return PageTheme.DARK;
    default:
      return PageTheme.SYSTEM;
  }
}

/**
 * Convert proto theme enum to DB string.
 */
export function protoThemeToDb(theme: PageTheme): "system" | "light" | "dark" {
  switch (theme) {
    case PageTheme.SYSTEM:
      return "system";
    case PageTheme.LIGHT:
      return "light";
    case PageTheme.DARK:
      return "dark";
    default:
      return "system";
  }
}

function metricTypeToProto(
  value: DBPageConfiguration["value"],
): PageMetricType {
  switch (value) {
    case "duration":
      return PageMetricType.DURATION;
    case "requests":
      return PageMetricType.REQUESTS;
    case "manual":
      return PageMetricType.MANUAL;
    default:
      return PageMetricType.UNSPECIFIED;
  }
}

function barTypeToProto(type: DBPageConfiguration["type"]): PageBarType {
  switch (type) {
    case "absolute":
      return PageBarType.ABSOLUTE;
    case "manual":
      return PageBarType.MANUAL;
    default:
      return PageBarType.UNSPECIFIED;
  }
}

/**
 * Convert the DB page configuration (parsed via pageConfigurationSchema) to proto.
 */
export function dbConfigurationToProto(
  configuration: DBPageConfiguration,
): PageConfiguration {
  return {
    $typeName: "openstatus.status_page.v1.PageConfiguration" as const,
    metricType: metricTypeToProto(configuration.value),
    barType: barTypeToProto(configuration.type),
    showUptime: configuration.uptime,
    themeKey: configuration.theme,
    days: configuration.days,
  };
}

/**
 * Convert DB component type string to proto enum.
 */
export function dbComponentTypeToProto(
  type: "static" | "monitor",
): PageComponentType {
  switch (type) {
    case "monitor":
      return PageComponentType.MONITOR;
    case "static":
      return PageComponentType.STATIC;
    default:
      return PageComponentType.UNSPECIFIED;
  }
}

/**
 * Convert proto component type enum to DB string.
 */
export function protoComponentTypeToDb(
  type: PageComponentType,
): "static" | "monitor" {
  switch (type) {
    case PageComponentType.MONITOR:
      return "monitor";
    case PageComponentType.STATIC:
      return "static";
    default:
      return "static";
  }
}

/**
 * Convert a resolved per-day component status to proto enum.
 */
export function dayStatusToProto(
  status: "operational" | "degraded" | "down" | "maintenance" | "empty",
): ComponentDayStatus {
  switch (status) {
    case "operational":
      return ComponentDayStatus.OPERATIONAL;
    case "degraded":
      return ComponentDayStatus.DEGRADED;
    case "down":
      return ComponentDayStatus.DOWN;
    case "maintenance":
      return ComponentDayStatus.MAINTENANCE;
    case "empty":
      return ComponentDayStatus.EMPTY;
    default:
      return ComponentDayStatus.UNSPECIFIED;
  }
}

/**
 * Convert a timeline event type to proto enum.
 */
export function eventTypeToProto(
  type: "maintenance" | "incident" | "report",
): ComponentEventType {
  switch (type) {
    case "maintenance":
      return ComponentEventType.MAINTENANCE;
    case "incident":
      return ComponentEventType.INCIDENT;
    case "report":
      return ComponentEventType.REPORT;
    default:
      return ComponentEventType.UNSPECIFIED;
  }
}

/**
 * Convert an event's projected status to proto enum.
 */
export function eventStatusToProto(
  status: "success" | "degraded" | "error" | "info",
): ComponentEventStatus {
  switch (status) {
    case "success":
      return ComponentEventStatus.OPERATIONAL;
    case "degraded":
      return ComponentEventStatus.DEGRADED;
    case "error":
      return ComponentEventStatus.DOWN;
    case "info":
      return ComponentEventStatus.MAINTENANCE;
    default:
      return ComponentEventStatus.UNSPECIFIED;
  }
}

// Keyed by `Locale`, so adding a language to `@openstatus/locales` fails to
// compile until the proto enum gains a matching value — a missing case here
// used to silently fold the locale to EN and produce duplicates on read.
const DB_LOCALE_TO_PROTO: Record<Locale, ProtoLocale> = {
  en: ProtoLocale.EN,
  fr: ProtoLocale.FR,
  de: ProtoLocale.DE,
  tr: ProtoLocale.TR,
  hi: ProtoLocale.HI,
  ko: ProtoLocale.KO,
  ja: ProtoLocale.JA,
};

const PROTO_LOCALE_TO_DB: Record<ProtoLocale, Locale | null> = {
  [ProtoLocale.UNSPECIFIED]: null,
  [ProtoLocale.EN]: "en",
  [ProtoLocale.FR]: "fr",
  [ProtoLocale.DE]: "de",
  [ProtoLocale.TR]: "tr",
  [ProtoLocale.HI]: "hi",
  [ProtoLocale.KO]: "ko",
  [ProtoLocale.JA]: "ja",
};

/**
 * Convert DB locale string to proto enum.
 */
export function dbLocaleToProto(locale: Locale): ProtoLocale {
  return DB_LOCALE_TO_PROTO[locale] ?? ProtoLocale.UNSPECIFIED;
}

/**
 * Convert proto locale enum to DB string. Unknown/unspecified values fall back
 * to the default locale.
 */
export function protoLocaleToDb(locale: ProtoLocale): Locale {
  return PROTO_LOCALE_TO_DB[locale] ?? defaultLocale;
}

/**
 * Convert a DB status page to full proto format.
 */
export function dbPageToProto(page: DBPage): StatusPage {
  return {
    $typeName: "openstatus.status_page.v1.StatusPage" as const,
    id: String(page.id),
    title: page.title,
    description: page.description,
    slug: page.slug,
    customDomain: page.customDomain ?? "",
    published: page.published ?? false,
    accessType: dbAccessTypeToProto(page.accessType),
    theme: dbThemeToProto(page.forceTheme),
    homepageUrl: page.homepageUrl ?? "",
    contactUrl: page.contactUrl ?? "",
    icon: page.icon ?? "",
    createdAt: page.createdAt?.toISOString() ?? "",
    updatedAt: page.updatedAt?.toISOString() ?? "",
    defaultLocale: dbLocaleToProto(page.defaultLocale),
    locales: page.locales
      ? [...new Set(page.locales.map(dbLocaleToProto))]
      : [],
    password: page.password ?? "",
    authEmailDomains: page.authEmailDomains?.split(",").filter(Boolean) ?? [],
    allowIndex: page.allowIndex ?? true,
    allowedIpRanges: page.allowedIpRanges ?? "",
    customTheme: dbCustomThemeToProto(page.customTheme),
  };
}

export function dbCustomThemeToProto(
  customTheme: DbCustomTheme | null | undefined,
): CustomTheme | undefined {
  if (!hasCustomTheme(customTheme)) return undefined;
  // ThemeVars values are `string | undefined`; proto maps require `string`.
  const pick = (vars?: Record<string, string | undefined>) => {
    const out: Record<string, string> = {};
    for (const [name, value] of Object.entries(vars ?? {})) {
      if (typeof value === "string") out[name] = value;
    }
    return out;
  };
  return {
    $typeName: "openstatus.status_page.v1.CustomTheme" as const,
    light: pick(customTheme.light),
    dark: pick(customTheme.dark),
  };
}

/**
 * Convert a DB status page to summary proto format.
 */
export function dbPageToProtoSummary(page: DBPage): StatusPageSummary {
  return {
    $typeName: "openstatus.status_page.v1.StatusPageSummary" as const,
    id: String(page.id),
    title: page.title,
    slug: page.slug,
    published: page.published ?? false,
    createdAt: page.createdAt?.toISOString() ?? "",
    updatedAt: page.updatedAt?.toISOString() ?? "",
    customDomain: page.customDomain ?? "",
  };
}

/**
 * Convert a DB page component to proto format.
 */
export function dbComponentToProto(component: DBPageComponent): PageComponent {
  return {
    $typeName: "openstatus.status_page.v1.PageComponent" as const,
    id: String(component.id),
    pageId: String(component.pageId),
    name: component.name,
    description: component.description ?? "",
    type: dbComponentTypeToProto(component.type),
    monitorId: component.monitorId != null ? String(component.monitorId) : "",
    order: component.order ?? 0,
    groupId: component.groupId != null ? String(component.groupId) : "",
    groupOrder: component.groupOrder ?? 0,
    createdAt: component.createdAt?.toISOString() ?? "",
    updatedAt: component.updatedAt?.toISOString() ?? "",
  };
}

/**
 * Convert a DB component group to proto format.
 */
export function dbGroupToProto(
  group: DBPageComponentGroup,
): PageComponentGroup {
  return {
    $typeName: "openstatus.status_page.v1.PageComponentGroup" as const,
    id: String(group.id),
    pageId: String(group.pageId),
    name: group.name,
    defaultOpen: group.defaultOpen ?? false,
    createdAt: group.createdAt?.toISOString() ?? "",
    updatedAt: group.updatedAt?.toISOString() ?? "",
  };
}

/**
 * Normalize proto WebhookChannelHeader[] into plain {key,value}[].
 *
 * Drops runtime-only fields like `$typeName` so nothing proto-specific
 * reaches the DB. Mirrors the pattern used by `headersToDbJson` in the
 * monitor converters (`monitor/converters/headers.ts`).
 */
export function protoHeadersToPlain(
  headers: WebhookChannelHeader[] | undefined,
): { key: string; value: string }[] {
  return (headers ?? []).map((h) => ({ key: h.key, value: h.value }));
}

/**
 * Convert a DB subscriber-source string to proto enum.
 */
export function dbSubscriberSourceToProto(
  source: "self_signup" | "vendor" | "import",
): SubscriberSource {
  switch (source) {
    case "self_signup":
      return SubscriberSource.SELF_SIGNUP;
    case "vendor":
      return SubscriberSource.VENDOR;
    case "import":
      return SubscriberSource.IMPORT;
    default:
      return SubscriberSource.UNSPECIFIED;
  }
}

/**
 * Convert a DB subscriber to proto format.
 *
 * Mirrors the tRPC `list` behavior: non-vendor rows get the webhook URL
 * reduced to origin-only and no `channelConfig`. Vendor-owned rows get
 * the full URL + config because the vendor is the one who configured them.
 */
function webhookUrlForProto(
  source: DBPageSubscriber["source"],
  webhookUrl: string | null,
): string | undefined {
  if (!webhookUrl) return undefined;
  if (source === "vendor") return webhookUrl;
  try {
    return new URL(webhookUrl).origin;
  } catch {
    return undefined;
  }
}

export function dbSubscriberToProto(
  subscriber: DBPageSubscriber,
): PageSubscriber {
  const isVendor = subscriber.source === "vendor";
  return {
    $typeName: "openstatus.status_page.v1.PageSubscriber" as const,
    id: String(subscriber.id),
    pageId: String(subscriber.pageId),
    email: subscriber.email ?? "",
    acceptedAt: subscriber.acceptedAt?.toISOString() ?? "",
    unsubscribedAt: subscriber.unsubscribedAt?.toISOString() ?? "",
    createdAt: subscriber.createdAt?.toISOString() ?? "",
    updatedAt: subscriber.updatedAt?.toISOString() ?? "",
    source: dbSubscriberSourceToProto(subscriber.source),
    name: subscriber.name ?? undefined,
    channelType: subscriber.channelType,
    webhookUrl: webhookUrlForProto(subscriber.source, subscriber.webhookUrl),
    channelConfig: isVendor
      ? (subscriber.channelConfig ?? undefined)
      : undefined,
    componentIds: (subscriber.componentIds ?? []).map(String),
  };
}