Skip to content

Open-source status page, incident response and uptime monitoring

7.7 KB
Raw Blame
import { Code, ConnectError, type ServiceImpl } from "@connectrpc/connect";
import type { MaintenanceService } from "@openstatus/proto/maintenance/v1";
import {
  addMaintenanceUpdate,
  createMaintenance,
  deleteMaintenance,
  deleteMaintenanceUpdate,
  getMaintenance,
  listMaintenances,
  notifyMaintenance,
  updateMaintenance,
  updateMaintenanceUpdate,
} from "@openstatus/services/maintenance";

import { toConnectError, toServiceCtx } from "../../adapter";
import { getRpcContext } from "../../interceptors";
import { parseDate as parseRpcDate, parseId as parseRpcId } from "../../parse";
import {
  dbMaintenanceToProto,
  dbMaintenanceToProtoSummary,
  dbMaintenanceUpdateToProto,
} from "./converters";
import {
  invalidDateFormatError,
  maintenanceIdRequiredError,
  maintenanceUpdateIdRequiredError,
} from "./errors";

function parseDate(dateString: string): Date {
  return parseRpcDate(dateString, () => invalidDateFormatError(dateString));
}

function parseId(value: string, label: string): number {
  return parseRpcId(
    value,
    () =>
      new ConnectError(`Invalid ${label}: "${value}"`, Code.InvalidArgument),
  );
}

function parsePageComponentIds(ids: ReadonlyArray<string>): number[] {
  return ids.map((id) => parseId(id, "page component id"));
}

export const maintenanceServiceImpl: ServiceImpl<typeof MaintenanceService> = {
  async createMaintenance(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      const sCtx = toServiceCtx(rpcCtx);

      const { maintenance: record, initialUpdate } = await createMaintenance({
        ctx: sCtx,
        input: {
          title: req.title,
          message: req.message,
          from: parseDate(req.from),
          to: parseDate(req.to),
          pageId: parseId(req.pageId, "page id"),
          pageComponentIds: parsePageComponentIds(req.pageComponentIds),
        },
      });

      if (req.notify) {
        // Intentional non-atomic step: `createMaintenance` already
        // committed the row, so a throw here surfaces as 500 to the
        // Connect client and a retry can produce a duplicate
        // maintenance. We accept that — wrapping the dispatch in the
        // write transaction would hold a row-level lock across the
        // external notification fan-out, which is a worse trade.
        // `status-report` takes the same shape (create → commit →
        // notify). The tRPC path avoids this by splitting into two
        // explicit client calls (`maintenance.new` +
        // `email.sendMaintenance`); the Connect surface doesn't have
        // that affordance.
        await notifyMaintenance({
          ctx: sCtx,
          input: { maintenanceUpdateId: initialUpdate.id },
        });
      }

      // Re-fetch so the response reflects stored IDs (dedup + validation
      // applied), not the raw request. Matches updateMaintenance and
      // createNotification.
      const full = await getMaintenance({
        ctx: sCtx,
        input: { id: record.id },
      });
      return {
        maintenance: dbMaintenanceToProto(
          full,
          full.pageComponentIds.map(String),
          full.updates,
        ),
      };
    } catch (err) {
      toConnectError(err);
    }
  },

  async getMaintenance(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      if (!req.id || req.id.trim() === "") {
        throw maintenanceIdRequiredError();
      }
      const full = await getMaintenance({
        ctx: toServiceCtx(rpcCtx),
        input: { id: parseId(req.id, "maintenance id") },
      });
      return {
        maintenance: dbMaintenanceToProto(
          full,
          full.pageComponentIds.map(String),
          full.updates,
        ),
      };
    } catch (err) {
      toConnectError(err);
    }
  },

  async listMaintenances(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);

      const pageId = req.pageId?.trim()
        ? parseId(req.pageId, "page id")
        : undefined;

      const { items, totalSize } = await listMaintenances({
        ctx: toServiceCtx(rpcCtx),
        input: {
          limit: Math.min(Math.max(req.limit ?? 50, 1), 100),
          offset: req.offset ?? 0,
          pageId,
          order: "desc",
        },
      });

      return {
        maintenances: items.map((r) =>
          dbMaintenanceToProtoSummary(r, r.pageComponentIds.map(String)),
        ),
        totalSize,
      };
    } catch (err) {
      toConnectError(err);
    }
  },

  async updateMaintenance(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      const sCtx = toServiceCtx(rpcCtx);
      if (!req.id || req.id.trim() === "") {
        throw maintenanceIdRequiredError();
      }

      const id = parseId(req.id, "maintenance id");
      await updateMaintenance({
        ctx: sCtx,
        input: {
          id,
          title:
            req.title !== undefined && req.title !== "" ? req.title : undefined,
          message:
            req.message !== undefined && req.message !== ""
              ? req.message
              : undefined,
          from: req.from ? parseDate(req.from) : undefined,
          to: req.to ? parseDate(req.to) : undefined,
          pageComponentIds: req.updatePageComponentIds
            ? parsePageComponentIds(req.pageComponentIds)
            : undefined,
        },
      });

      const full = await getMaintenance({ ctx: sCtx, input: { id } });
      return {
        maintenance: dbMaintenanceToProto(
          full,
          full.pageComponentIds.map(String),
          full.updates,
        ),
      };
    } catch (err) {
      toConnectError(err);
    }
  },

  async deleteMaintenance(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      if (!req.id || req.id.trim() === "") {
        throw maintenanceIdRequiredError();
      }
      await deleteMaintenance({
        ctx: toServiceCtx(rpcCtx),
        input: { id: parseId(req.id, "maintenance id") },
      });
      return { success: true };
    } catch (err) {
      toConnectError(err);
    }
  },

  async addMaintenanceUpdate(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      const sCtx = toServiceCtx(rpcCtx);
      if (!req.maintenanceId?.trim()) {
        throw maintenanceIdRequiredError();
      }
      const update = await addMaintenanceUpdate({
        ctx: sCtx,
        input: {
          maintenanceId: parseId(req.maintenanceId, "maintenance id"),
          message: req.message,
          date: req.date ? parseDate(req.date) : undefined,
        },
      });
      if (req.notify) {
        await notifyMaintenance({
          ctx: sCtx,
          input: { maintenanceUpdateId: update.id },
        });
      }
      return { maintenanceUpdate: dbMaintenanceUpdateToProto(update) };
    } catch (err) {
      toConnectError(err);
    }
  },

  async updateMaintenanceUpdate(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      if (!req.id?.trim()) {
        throw maintenanceUpdateIdRequiredError();
      }
      const update = await updateMaintenanceUpdate({
        ctx: toServiceCtx(rpcCtx),
        input: {
          id: parseId(req.id, "maintenance update id"),
          message: req.message,
          date: req.date ? parseDate(req.date) : undefined,
        },
      });
      return { maintenanceUpdate: dbMaintenanceUpdateToProto(update) };
    } catch (err) {
      toConnectError(err);
    }
  },

  async deleteMaintenanceUpdate(req, ctx) {
    try {
      const rpcCtx = getRpcContext(ctx);
      if (!req.id?.trim()) {
        throw maintenanceUpdateIdRequiredError();
      }
      await deleteMaintenanceUpdate({
        ctx: toServiceCtx(rpcCtx),
        input: { id: parseId(req.id, "maintenance update id") },
      });
      return { success: true };
    } catch (err) {
      toConnectError(err);
    }
  },
};