Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
workflow: improve notificaiton (#2630)
Thibault Le Ouay648e2913f973
diff --git a/apps/workflows/fly.toml b/apps/workflows/fly.tomlindex 458e9c2c9..9e670264a 100644--- a/apps/workflows/fly.toml+++ b/apps/workflows/fly.toml@@ -6,6 +6,10 @@app = 'openstatus-workflows'primary_region = 'ams'+# Long enough for shutdownOutbox to wait out an in-flight provider call+# (NOTIFICATION_TIMEOUT_MS + 5s) before Fly SIGKILLs.+kill_timeout = "25s"+[build]dockerfile = "./Dockerfile"diff --git a/apps/workflows/src/checker/alerting.ts b/apps/workflows/src/checker/alerting.tsindex 1e517c0c9..2db10c63c 100644--- a/apps/workflows/src/checker/alerting.ts+++ b/apps/workflows/src/checker/alerting.ts@@ -1,15 +1,14 @@import { getLogger } from "@logtape/logtape";-import { and, count, db, eq, gte, inArray, schema } from "@openstatus/db";-import type { Incident, MonitorStatus } from "@openstatus/db/src/schema";+import { db, eq, schema } from "@openstatus/db";+import type { Incident } from "@openstatus/db/src/schema";import {selectMonitorSchema,selectNotificationSchema,- selectWorkspaceSchema,} from "@openstatus/db/src/schema";-import type { Region } from "@openstatus/db/src/schema/constants";import { Effect, Schedule } from "effect";import { checkerAudit } from "../utils/audit-log";+import { loadSmsQuotaBlocked } from "./sms-quota";import { providerToFunction } from "./utils";const logger = getLogger("workflow");@@ -39,6 +38,7 @@ export const triggerNotifications = async ({});const triggered: { notificationId: number; provider: string }[] = [];+ const smsQuota = new Map<number, boolean>();let incident: Incident | undefined;if (incidentId) {@@ -70,52 +70,20 @@ export const triggerNotifications = async ({for (const notif of notifications) {// for sms check we are in the quotaif (notif.notification.provider === "sms") {- if (notif.notification.workspaceId === null) {+ const notificationWorkspaceId = notif.notification.workspaceId;+ if (notificationWorkspaceId === null) {continue;}-- const workspace = await db- .select()- .from(schema.workspace)- .where(eq(schema.workspace.id, notif.notification.workspaceId));-- if (workspace.length !== 1) {- continue;- }-- const data = selectWorkspaceSchema.parse(workspace[0]);-- const oneMonthAgo = new Date();- oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);-- const smsNotification = await db- .select()- .from(schema.notification)- .where(- and(- eq(schema.notification.workspaceId, notif.notification.workspaceId),- eq(schema.notification.provider, "sms"),- ),+ if (!smsQuota.has(notificationWorkspaceId)) {+ const blocked = await loadSmsQuotaBlocked([notificationWorkspaceId]);+ smsQuota.set(+ notificationWorkspaceId,+ blocked.get(notificationWorkspaceId) ?? true,);- const ids = smsNotification.map((notification) => notification.id);-- const smsSent = await db- .select({ count: count() })- .from(schema.notificationTrigger)- .where(- and(- gte(- schema.notificationTrigger.cronTimestamp,- Math.floor(oneMonthAgo.getTime() / 1000),- ),- inArray(schema.notificationTrigger.notificationId, ids),- ),- )- .all();-- if ((smsSent[0]?.count ?? 0) > data.limits["sms-limit"]) {+ }+ if (smsQuota.get(notificationWorkspaceId) === true) {logger.warn(- `SMS quota exceeded for workspace ${notif.notification.workspaceId}`,+ `SMS quota exceeded for workspace ${notificationWorkspaceId}`,);continue;}@@ -238,17 +206,28 @@ export const triggerNotifications = async ({break;}// ALPHA- await checkerAudit.publishAuditLog({- id: `monitor:${monitorId}`,- action: "notification.sent",- targets: [{ id: monitorId, type: "monitor" }],- metadata: {+ // Best-effort: the notification has been sent and its trigger row written,+ // so throwing here would make Cloud Tasks retry a send that already+ // happened — and the retry skips it on the trigger's unique index.+ try {+ await checkerAudit.publishAuditLog({+ id: `monitor:${monitorId}`,+ action: "notification.sent",+ targets: [{ id: monitorId, type: "monitor" }],+ metadata: {+ provider: notif.notification.provider,+ cronTimestamp,+ type: notifType,+ notificationId: notif.notification.id,+ },+ });+ } catch (err) {+ logger.warn("Failed to publish notification audit log", {+ monitor_id: monitorId,provider: notif.notification.provider,- cronTimestamp,- type: notifType,- notificationId: notif.notification.id,- },- });+ error_message: err instanceof Error ? err.message : String(err),+ });+ }}return triggered;@@ -272,31 +251,3 @@ const insertNotificationTrigger = async ({}).returning();};--export const upsertMonitorStatus = async ({- monitorId,- status,- region,-}: {- monitorId: string;- status: MonitorStatus;- region: Region;-}) => {- const newData = await db- .insert(schema.monitorStatusTable)- .values({ status, region, monitorId: Number(monitorId) })- .onConflictDoUpdate({- target: [- schema.monitorStatusTable.monitorId,- schema.monitorStatusTable.region,- ],- set: { status, updatedAt: new Date() },- })- .returning();- logger.debug("Upserted monitor status", {- monitor_id: monitorId,- region,- status,- updated_at: newData[0]?.updatedAt,- });-};diff --git a/apps/workflows/src/checker/index.ts b/apps/workflows/src/checker/index.tsindex 7feeac004..872915d00 100644--- a/apps/workflows/src/checker/index.ts+++ b/apps/workflows/src/checker/index.ts@@ -1,20 +1,16 @@import { getLogger } from "@logtape/logtape";-import { and, db, eq, inArray, schema } from "@openstatus/db";-import { incidentTable } from "@openstatus/db/src/schema";import { monitorRegions } from "@openstatus/db/src/schema/constants";-import {- monitorStatusSchema,- selectMonitorSchema,-} from "@openstatus/db/src/schema/monitors/validation";+import { monitorStatusSchema } from "@openstatus/db/src/schema/monitors/validation";import { Hono } from "hono";import { z } from "zod";import { env } from "../env";import type { Env } from "../index";import { checkerAudit } from "../utils/audit-log";-import { triggerNotifications, upsertMonitorStatus } from "./alerting";-import { findOpenIncident, resolveIncident } from "./incident-utils";+import { triggerNotifications } from "./alerting";+import { enqueueOutbox } from "./outbox";import { updateStatusPrivate } from "./private-location";+import { EVENT_TYPE, applyStatusTransition, isStaleCheck } from "./transition";export const checkerRoute = new Hono<Env>();@@ -30,19 +26,70 @@ const payloadSchema = z.object({latency: z.number().optional(),});+type Payload = z.infer<typeof payloadSchema>;+const logger = getLogger(["workflow"]);+async function publishStatusAudit(payload: Payload): Promise<void> {+ const { monitorId, region, statusCode, cronTimestamp, latency } = payload;+ const id = `monitor:${monitorId}`;+ const targets = [{ id: monitorId, type: "monitor" as const }];+ const metadata = {+ region,+ statusCode: statusCode ?? -1,+ cronTimestamp,+ latency,+ };++ // Best-effort, like publishIncidentAudit: the transition batch has already+ // committed, and throwing here would make Cloud Tasks retry a transition that+ // has landed. The retry short-circuits on the unchanged region status, so the+ // notification this request still owes would never be sent.+ try {+ switch (payload.status) {+ case "active":+ await checkerAudit.publishAuditLog({+ id,+ action: "monitor.recovered",+ targets,+ metadata,+ });+ break;+ case "degraded":+ await checkerAudit.publishAuditLog({+ id,+ action: "monitor.degraded",+ targets,+ metadata,+ });+ break;+ case "error":+ await checkerAudit.publishAuditLog({+ id,+ action: "monitor.failed",+ targets,+ metadata: { ...metadata, message: payload.message },+ });+ break;+ }+ } catch (error) {+ logger.warn("Failed to publish status audit log", {+ monitor_id: payload.monitorId,+ error_message: error instanceof Error ? error.message : String(error),+ });+ }+}+checkerRoute.post("/updateStatus", async (c) => {+ const config = env();const auth = c.req.header("Authorization");- if (auth !== `Basic ${env().CRON_SECRET}`) {+ if (auth !== `Basic ${config.CRON_SECRET}`) {logger.error("Unauthorized");return c.text("Unauthorized", 401);}const event = c.get("event");- const json = await c.req.json();-- const result = payloadSchema.safeParse(json);+ const result = payloadSchema.safeParse(await c.req.json());if (!result.success) {return c.text("Unprocessable Entity", 422);@@ -57,6 +104,7 @@ checkerRoute.post("/updateStatus", async (c) => {status,latency,} = result.data;+ const monitorIdNumber = Number(monitorId);logger.info("Updating monitor status", {monitor_id: monitorId,@@ -67,241 +115,88 @@ checkerRoute.post("/updateStatus", async (c) => {latency_ms: latency,});- // First we upsert the monitor status- await upsertMonitorStatus({- monitorId: monitorId,+ const statusUpdate: Record<string, unknown> = {status,- region: region,- });-- const currentMonitor = await db- .select()- .from(schema.monitor)- .where(eq(schema.monitor.id, Number(monitorId)))- .get();-- const monitor = selectMonitorSchema.parse(currentMonitor);- const numberOfRegions = monitor.regions.length;-- // Fetch all affected regions for notifications (single query)- const affectedRegions = await db- .select({ region: schema.monitorStatusTable.region })- .from(schema.monitorStatusTable)- .where(- and(- eq(schema.monitorStatusTable.monitorId, monitor.id),- eq(schema.monitorStatusTable.status, status),- inArray(schema.monitorStatusTable.region, monitor.regions),- ),- )- .all();-- const affectedRegionsList = affectedRegions.map((r) => r.region);- const affectedRegionCount = affectedRegionsList.length;-- event.status_update = {- status: result.data.status,- message: result.data.message,- region: result.data.region,- status_code: result.data.statusCode,- cron_timestamp: result.data.cronTimestamp,- latency_ms: result.data.latency,- affectedRegionsCount: affectedRegionCount,- monitorId: monitor.id,+ message,+ region,+ status_code: statusCode,+ cron_timestamp: cronTimestamp,+ latency_ms: latency,+ monitorId: monitorIdNumber,};+ if (event) event.status_update = statusUpdate;- if (affectedRegionCount === 0) {+ if (isStaleCheck(cronTimestamp, config.STALE_CHECK_MS)) {+ statusUpdate.stale = true;return c.json({ success: true }, 200);}- // audit log the current state of the ping+ const transition = await applyStatusTransition({+ monitorId: monitorIdNumber,+ region,+ status,+ cronTimestamp,+ statusCode,+ message,+ latency,+ deadlineSeconds: Math.floor(config.OUTBOX_DEADLINE_MS / 1000),+ rolloutPct: config.OUTBOX_ROLLOUT_PCT,+ });- switch (status) {- case "active":- await checkerAudit.publishAuditLog({- id: `monitor:${monitorId}`,- action: "monitor.recovered",- targets: [{ id: monitorId, type: "monitor" }],- metadata: {- region,- statusCode: statusCode ?? -1,- cronTimestamp,- latency,- },- });- break;- case "degraded":- await checkerAudit.publishAuditLog({- id: `monitor:${monitorId}`,- action: "monitor.degraded",- targets: [{ id: monitorId, type: "monitor" }],- metadata: {- region,- statusCode: statusCode ?? -1,- cronTimestamp,- latency,- },- });- break;- case "error":- await checkerAudit.publishAuditLog({- id: `monitor:${monitorId}`,- action: "monitor.failed",- targets: [{ id: monitorId, type: "monitor" }],- metadata: {- region,- statusCode: statusCode ?? -1,- message,- cronTimestamp,- latency,- },- });- break;+ if (transition.kind === "unchanged") {+ statusUpdate.fast_path_skipped = true;+ return c.json({ success: true }, 200);}- let triggeredNotifications: { notificationId: number; provider: string }[] =- [];-- if (affectedRegionCount >= numberOfRegions / 2 || numberOfRegions === 1) {- switch (status) {- case "active": {- if (monitor.status === "active") {- break;- }-- logger.info("Monitor status changed to active", {- monitor_id: monitor.id,- workspace_id: monitor.workspaceId,- });- await db- .update(schema.monitor)- .set({ status: "active" })- .where(eq(schema.monitor.id, monitor.id));-- let incident = null;- if (monitor.status === "error") {- const incidents = await resolveIncident({ monitorId, cronTimestamp });- incident = incidents[0] ?? null;- }-- triggeredNotifications = await triggerNotifications({- monitorId,- statusCode,- message,- notifType: "recovery",- cronTimestamp,- regions: affectedRegionsList,- latency,- incidentId: incident?.id,- });-- break;- }- case "degraded":- if (monitor.status === "degraded") {- break;- }-- logger.info("Monitor status changed to degraded", {- monitor_id: monitor.id,- workspace_id: monitor.workspaceId,- });-- await db- .update(schema.monitor)- .set({ status: "degraded" })- .where(eq(schema.monitor.id, monitor.id));-- let incident = null;- if (monitor.status === "error") {- const incidents = await resolveIncident({- monitorId,- cronTimestamp,- });- incident = incidents[0] ?? null;- }-- triggeredNotifications = await triggerNotifications({- monitorId,- statusCode,- message,- notifType: "degraded",- cronTimestamp,- latency,- regions: affectedRegionsList,- incidentId: incident?.id,- });-- break;- case "error":- if (monitor.status === "error") {- break;- }-- logger.info("Monitor status changed to error", {- monitor_id: monitor.id,- workspace_id: monitor.workspaceId,- });-- await db- .update(schema.monitor)- .set({ status: "error" })- .where(eq(schema.monitor.id, monitor.id));+ if (transition.kind === "monitor-missing") {+ statusUpdate.monitor_missing = true;+ return c.json({ success: true }, 200);+ }- try {- const existingIncident = await findOpenIncident(Number(monitorId));- if (existingIncident) {- logger.info("Already in incident", {- incident_id: existingIncident.id,- });- break;- }+ statusUpdate.affectedRegionsCount = transition.affectedRegions.length;+ statusUpdate.quorum_count = transition.quorumCount;+ statusUpdate.region_count = transition.regionCount;+ statusUpdate.transition_applied = transition.transitioned;+ statusUpdate.outbox_rows = transition.outboxRows.length;- const [newIncident] = await db- .insert(incidentTable)- .values({- monitorId: Number(monitorId),- workspaceId: monitor.workspaceId,- startedAt: new Date(cronTimestamp),- })- .returning();+ await publishStatusAudit(result.data);- if (!newIncident?.id) {- break;- }+ if (!transition.transitioned) {+ return c.text("Ok", 200);+ }- await checkerAudit.publishAuditLog({- id: `monitor:${monitorId}`,- action: "incident.created",- targets: [{ id: monitorId, type: "monitor" }],- metadata: { cronTimestamp, incidentId: newIncident.id },- });+ logger.info("Monitor status changed", {+ monitor_id: monitorIdNumber,+ status,+ });- triggeredNotifications = await triggerNotifications({- monitorId,- statusCode,- message,- notifType: "alert",- cronTimestamp,- latency,- regions: affectedRegionsList,- incidentId: newIncident.id,- });- } catch (error) {- logger.warning("Failed to create incident", { error });- }+ let triggeredNotifications: { notificationId: number; provider: string }[] =+ [];- break;- default:- logger.error("should not happen");- break;- }+ // Ownership is whatever the batch actually wrote, not a second copy of the+ // rollout formula: `pending` means the drainer owns it, `settled` with an+ // `inline` outcome means the inline sender does.+ if (transition.outboxRows.some((row) => row.deliveryStatus === "pending")) {+ enqueueOutbox(transition.outboxRows.map((row) => row.id));+ triggeredNotifications = transition.outboxRows.map((row) => ({+ notificationId: row.notificationId,+ provider: row.provider,+ }));+ } else if (transition.outboxRows.length > 0) {+ triggeredNotifications = await triggerNotifications({+ monitorId,+ statusCode,+ message,+ notifType: EVENT_TYPE[status],+ cronTimestamp,+ regions: transition.affectedRegions,+ latency,+ incidentId: transition.incidentId ?? undefined,+ });}- (event.status_update as Record<string, unknown>).notificationTriggered =- triggeredNotifications.length > 0;- (event.status_update as Record<string, unknown>).notifications =- triggeredNotifications;+ statusUpdate.notificationTriggered = triggeredNotifications.length > 0;+ statusUpdate.notifications = triggeredNotifications;return c.text("Ok", 200);});diff --git a/apps/workflows/src/checker/outbox.test.ts b/apps/workflows/src/checker/outbox.test.tsnew file mode 100644index 000000000..626d6a09d--- /dev/null+++ b/apps/workflows/src/checker/outbox.test.ts@@ -0,0 +1,560 @@+import { and, count, db, eq } from "@openstatus/db";+import type { NotificationOutboxPayload } from "@openstatus/db/src/schema";+import {+ notificationOutbox,+ monitor,+ notificationDeadLetter,+ notificationTrigger,+} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createNotification,+ createTestWorkspace,+ linkNotificationToMonitor,+} from "@openstatus/db/src/test/factories";+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ type Stub,+ stub,+ test,+} from "@openstatus/test-utils";++import { checkerAudit } from "../utils/audit-log";+import { drainOutbox, shutdownOutbox, sweepExpiredOutbox } from "./outbox";+import { providerToFunction } from "./utils";++// Deno has no module mocking; stub the singleton the drainer resolves at call+// time, as alerting.test.ts does.+// biome-ignore lint/suspicious/noExplicitAny: heterogeneous provider stubs+type AnyStub = Stub<any>;+let stubs: AnyStub[] = [];++let workspaceId: number;+let monitorId: number;+let notificationId: number;++const PAYLOAD: NotificationOutboxPayload = { regions: ["ams"] };++beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ workspaceId = workspace.id;+ const monitorRow = await createMonitor(workspaceId, { regions: "ams" });+ monitorId = monitorRow.id;+ const notif = await createNotification(workspaceId, { provider: "email" });+ notificationId = notif.id;+ await linkNotificationToMonitor(notificationId, monitorId);+});++afterAll(async () => {+ await db.delete(monitor).where(eq(monitor.workspaceId, workspaceId)).run();+});++beforeEach(() => {+ stubs = [];+ stubs.push(+ stub(checkerAudit, "publishAuditLog", () => Promise.resolve()) as AnyStub,+ );+});++afterEach(async () => {+ for (const s of stubs) s.restore();+ stubs = [];+ await db+ .delete(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .run();+ await db+ .delete(notificationDeadLetter)+ .where(eq(notificationDeadLetter.monitorId, monitorId))+ .run();+ await db+ .delete(notificationTrigger)+ .where(eq(notificationTrigger.monitorId, monitorId))+ .run();+});++async function insertOutboxRow(overrides: {+ cronTimestamp: number;+ eventType?: "alert" | "recovery";+ deadlineOffsetSeconds?: number;+ attempts?: number;+ lockedBy?: string;+ lockedUntilOffsetSeconds?: number;+}) {+ const now = Math.floor(Date.now() / 1000);+ const [row] = await db+ .insert(notificationOutbox)+ .values({+ dedupKey: `${overrides.cronTimestamp}:${monitorId}:test:${notificationId}`,+ monitorId,+ workspaceId,+ notificationId,+ provider: "email",+ eventType: overrides.eventType ?? "alert",+ fromStatus: "active",+ toStatus: "error",+ cronTimestamp: overrides.cronTimestamp,+ incidentId: null,+ payload: PAYLOAD,+ attempts: overrides.attempts ?? 0,+ lockedBy: overrides.lockedBy ?? null,+ lockedUntil:+ overrides.lockedUntilOffsetSeconds === undefined+ ? null+ : now + overrides.lockedUntilOffsetSeconds,+ nextAttemptAt: now,+ deadlineAt: now + (overrides.deadlineOffsetSeconds ?? 300),+ createdAt: now,+ })+ .returning();+ if (!row) throw new Error("outbox insert returned no row");+ return row;+}++describe("drainOutbox", () => {+ test("delivers a row, marks it done and records the send", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+ await insertOutboxRow({ cronTimestamp: Date.now() });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.delivered).toBe(1);+ expect(summary.dead).toBe(0);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("settled");+ expect(rows[0]?.deliveredAt).not.toBe(null);+ expect(rows[0]?.lockedUntil).toBe(null);++ const triggers = await db+ .select({ total: count() })+ .from(notificationTrigger)+ .where(eq(notificationTrigger.monitorId, monitorId))+ .all();+ expect(triggers[0]?.total).toBe(1);+ });++ test("dead-letters a row past its deadline and frees the channel", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () =>+ Promise.reject(new Error("provider down")),+ ),+ );+ await insertOutboxRow({+ cronTimestamp: Date.now(),+ deadlineOffsetSeconds: 1,+ });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.dead).toBe(1);++ const remaining = await db+ .select({ total: count() })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(remaining[0]?.total).toBe(0);++ const dead = await db+ .select()+ .from(notificationDeadLetter)+ .where(eq(notificationDeadLetter.monitorId, monitorId))+ .all();+ expect(dead.length).toBe(1);+ expect(dead[0]?.finalError).toContain("provider down");+ });++ test("a hanging provider is bounded by the timeout", async () => {+ stubs.push(+ stub(+ providerToFunction.email,+ "sendAlert",+ () => new Promise<void>(() => {}),+ ),+ );+ await insertOutboxRow({+ cronTimestamp: Date.now(),+ deadlineOffsetSeconds: 1,+ });++ const started = Date.now();+ const summary = await drainOutbox({+ timeoutMs: 100,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.dead).toBe(1);+ expect(Date.now() - started).toBeLessThan(5000);+ });++ test("claims only the oldest pending row per channel", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+ stubs.push(+ stub(providerToFunction.email, "sendRecovery", () => Promise.resolve()),+ );++ const base = Date.now();+ const first = await insertOutboxRow({+ cronTimestamp: base,+ eventType: "alert",+ });+ await insertOutboxRow({+ cronTimestamp: base + 1000,+ eventType: "recovery",+ });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });+ expect(summary.claimed).toBe(1);++ const done = await db+ .select({ id: notificationOutbox.id })+ .from(notificationOutbox)+ .where(+ and(+ eq(notificationOutbox.monitorId, monitorId),+ eq(notificationOutbox.deliveryStatus, "settled"),+ ),+ )+ .all();+ expect(done.length).toBe(1);+ expect(done[0]?.id).toBe(first.id);++ const second = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });+ expect(second.claimed).toBe(1);+ });++ test("an sms row over quota is recorded, not delivered", async () => {+ stubs.push(+ stub(providerToFunction.sms, "sendAlert", () => Promise.resolve()),+ );++ const { workspace: smsWorkspace } = await createTestWorkspace({+ plan: "free",+ });+ const smsMonitor = await createMonitor(smsWorkspace.id, {+ regions: "ams",+ });+ const smsNotification = await createNotification(smsWorkspace.id, {+ provider: "sms",+ data: JSON.stringify({ sms: "+10000000000" }),+ });+ await linkNotificationToMonitor(smsNotification.id, smsMonitor.id);++ // free plan allows zero SMS, so a single recorded send is already over.+ await db+ .insert(notificationTrigger)+ .values({+ monitorId: smsMonitor.id,+ notificationId: smsNotification.id,+ cronTimestamp: Date.now(),+ })+ .run();++ const now = Math.floor(Date.now() / 1000);+ await db+ .insert(notificationOutbox)+ .values({+ dedupKey: `sms:${smsMonitor.id}:${smsNotification.id}`,+ monitorId: smsMonitor.id,+ workspaceId: smsWorkspace.id,+ notificationId: smsNotification.id,+ provider: "sms",+ eventType: "alert",+ fromStatus: "active",+ toStatus: "error",+ cronTimestamp: Date.now(),+ payload: PAYLOAD,+ nextAttemptAt: now,+ deadlineAt: now + 300,+ createdAt: now,+ })+ .run();++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [smsMonitor.id],+ });+ expect(summary.skipped).toBe(1);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.notificationId, smsNotification.id))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("settled");+ expect(rows[0]?.deliveredAt).toBe(null);+ expect(rows[0]?.lastError).toBe("sms-quota-exceeded");++ await db.delete(monitor).where(eq(monitor.id, smsMonitor.id)).run();+ });+});++describe("retry", () => {+ test("a failed send is handed back with its backoff recorded", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () =>+ Promise.reject(new Error("provider down")),+ ),+ );+ await insertOutboxRow({ cronTimestamp: Date.now() });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.retried).toBe(1);+ expect(summary.dead).toBe(0);+ expect(summary.nextRetryMs).not.toBe(null);++ const now = Math.floor(Date.now() / 1000);+ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("pending");+ expect(rows[0]?.attempts).toBe(1);+ expect(rows[0]?.lockedBy).toBe(null);+ expect(rows[0]?.lockedUntil).toBe(null);+ expect(rows[0]?.lastError).toContain("provider down");+ expect(rows[0]?.nextAttemptAt).toBeGreaterThan(now);++ // The backoff is the claim predicate, so nothing is claimable until it ends.+ const again = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });+ expect(again.claimed).toBe(0);+ });++ test("a lapsed lease lets the other machine take the row over", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+ // A worker that died mid-attempt: still claimed, lease already expired.+ await insertOutboxRow({+ cronTimestamp: Date.now(),+ attempts: 1,+ lockedBy: "dead-worker",+ lockedUntilOffsetSeconds: -1,+ });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.delivered).toBe(1);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("settled");+ expect(rows[0]?.attempts).toBe(2);+ });++ test("a live lease is left alone", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+ await insertOutboxRow({+ cronTimestamp: Date.now(),+ attempts: 1,+ lockedBy: "peer-worker",+ lockedUntilOffsetSeconds: 60,+ });++ const summary = await drainOutbox({+ timeoutMs: 500,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ expect(summary.claimed).toBe(0);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.lockedBy).toBe("peer-worker");+ expect(rows[0]?.deliveryStatus).toBe("pending");+ });+});++describe("shutdownOutbox", () => {+ test("does not release a row whose send is already in flight", async () => {+ let dispatched = false;+ let release: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ release = resolve;+ });+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => {+ dispatched = true;+ return pending;+ }),+ );++ const row = await insertOutboxRow({ cronTimestamp: Date.now() });+ const drain = drainOutbox({+ timeoutMs: 5000,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });++ while (!dispatched) {+ await new Promise((resolve) => setTimeout(resolve, 5));+ }++ // Grace expires while the provider call is still outstanding.+ await shutdownOutbox(50);++ const during = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.id, row.id))+ .all();+ expect(during[0]?.lockedBy).not.toBe(null);+ expect(during[0]?.deliveryStatus).toBe("pending");+ // The lease covers one delivery batch, not the whole message.+ expect(during[0]?.lockedUntil).toBeLessThan(during[0]?.deadlineAt ?? 0);++ release();+ await drain;++ const after = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.id, row.id))+ .all();+ expect(after[0]?.deliveryStatus).toBe("settled");+ });++ test("hands claimed work back instead of delivering it", async () => {+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+ await insertOutboxRow({ cronTimestamp: Date.now() });++ await shutdownOutbox();++ const summary = await drainOutbox({+ timeoutMs: 100,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });+ expect(summary.released).toBe(1);+ expect(summary.delivered).toBe(0);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("pending");+ expect(rows[0]?.lockedBy).toBe(null);+ expect(rows[0]?.lockedUntil).toBe(null);+ });+});++describe("sweepExpiredOutbox", () => {+ test("never-owned rows are discarded, abandoned rows dead-letter", async () => {+ const twoHoursAgo = Math.floor(Date.now() / 1000) - 2 * 60 * 60;++ const [neverOwned] = await db+ .insert(notificationOutbox)+ .values({+ dedupKey: `expired-never:${monitorId}`,+ monitorId,+ workspaceId,+ notificationId,+ provider: "email",+ eventType: "alert",+ fromStatus: "active",+ toStatus: "error",+ cronTimestamp: Date.now(),+ payload: PAYLOAD,+ nextAttemptAt: twoHoursAgo,+ deadlineAt: twoHoursAgo,+ createdAt: twoHoursAgo,+ })+ .returning();++ await db+ .insert(notificationOutbox)+ .values({+ dedupKey: `expired-abandoned:${monitorId}`,+ monitorId,+ workspaceId,+ notificationId,+ provider: "email",+ eventType: "alert",+ fromStatus: "active",+ toStatus: "error",+ cronTimestamp: Date.now() + 1,+ payload: PAYLOAD,+ attempts: 2,+ nextAttemptAt: twoHoursAgo,+ deadlineAt: twoHoursAgo,+ createdAt: twoHoursAgo,+ })+ .run();++ await sweepExpiredOutbox();++ const remaining = await db+ .select({ total: count() })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(remaining[0]?.total).toBe(0);++ const dead = await db+ .select()+ .from(notificationDeadLetter)+ .where(eq(notificationDeadLetter.monitorId, monitorId))+ .all();+ expect(dead.length).toBe(1);+ expect(dead[0]?.attempts).toBe(2);+ expect(neverOwned).not.toBe(undefined);+ });+});diff --git a/apps/workflows/src/checker/outbox.ts b/apps/workflows/src/checker/outbox.tsnew file mode 100644index 000000000..05bbad81c--- /dev/null+++ b/apps/workflows/src/checker/outbox.ts@@ -0,0 +1,702 @@+import { getLogger } from "@logtape/logtape";+import { and, db, eq, inArray, lt, notInArray, sql } from "@openstatus/db";+import type {+ Incident,+ Monitor,+ Notification,+} from "@openstatus/db/src/schema";+import {+ notificationOutbox,+ incidentTable,+ monitor,+ notification,+ notificationDeadLetter,+ notificationTrigger,+ selectMonitorSchema,+ selectNotificationSchema,+} from "@openstatus/db/src/schema";+import { withBusyRetry } from "@openstatus/services";+import * as Sentry from "@sentry/deno";+import { Effect, Exit, Queue } from "effect";++import { env } from "../env";+import { checkerAudit } from "../utils/audit-log";+import { loadSmsQuotaBlocked } from "./sms-quota";+import { providerToFunction } from "./utils";++const logger = getLogger(["workflow"]);++const CLAIM_LIMIT = 20;+const DELIVERY_CONCURRENCY = 5;+const MAX_BACKOFF_MS = 30_000;++/**+ * A claim leases a row for one delivery attempt, not for the whole message: a+ * worker that dies mid-send has to hand the row back long before the deadline.+ * The lease still has to outlast the worst case for a claimed row, which is+ * waiting behind a full batch at the delivery concurrency, plus the commit.+ */+const LEASE_SLACK_MS = 5_000;++function leaseSeconds(limit: number, timeoutMs: number): number {+ const waves = Math.ceil(limit / DELIVERY_CONCURRENCY);+ return Math.ceil((waves * timeoutMs + LEASE_SLACK_MS) / 1000);+}++const workerId = crypto.randomUUID();++type OutboxRow = typeof notificationOutbox.$inferSelect;++type DeliveryOutcome =+ | { kind: "delivered"; row: OutboxRow }+ | { kind: "skipped"; row: OutboxRow; reason: string }+ | { kind: "released"; row: OutboxRow }+ | {+ kind: "retry";+ row: OutboxRow;+ error: string;+ delayMs: number;+ nextAttemptAt: number;+ }+ | { kind: "dead"; row: OutboxRow; error: string };++export type DrainSummary = {+ claimed: number;+ delivered: number;+ skipped: number;+ released: number;+ retried: number;+ dead: number;+ /** Time until the earliest backoff this drain wrote, so the caller can wake. */+ nextRetryMs: number | null;+};++let shuttingDown = false;++// Rows whose provider call has been dispatched and not yet resolved. Shutdown+// must not hand these to the peer machine: the send can still succeed after the+// row is released, and the peer would deliver it a second time.+const inFlightSends = new Set<number>();+const activeDrains = new Set<Promise<DrainSummary>>();++const SEND_METHOD = {+ alert: "sendAlert",+ recovery: "sendRecovery",+ degraded: "sendDegraded",+} as const;++function backoffMs(attempt: number): number {+ const ceiling = Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);+ return ceiling / 2 + Math.random() * (ceiling / 2);+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/**+ * Claims only the oldest pending row per (monitor, notification), so an alert+ * and the recovery behind it can never be delivered out of order, including+ * across machines. `rolloutPct` gates which monitors the drainer owns; at 0 the+ * inline sender is still authoritative and nothing here is claimable.+ */+async function claimRows(+ limit: number,+ rolloutPct: number,+ lease: number,+ monitorIds?: number[],+): Promise<OutboxRow[]> {+ const scope =+ monitorIds === undefined+ ? sql``+ : sql` AND o.monitor_id IN (${sql.join(+ monitorIds.map((id) => sql`${id}`),+ sql`, `,+ )})`;++ return withBusyRetry(() =>+ db+ .update(notificationOutbox)+ .set({+ lockedBy: workerId,+ lockedUntil: sql`min(unixepoch() + ${lease}, ${notificationOutbox.deadlineAt})`,+ attempts: sql`${notificationOutbox.attempts} + 1`,+ })+ .where(+ sql`${notificationOutbox.id} IN (+ SELECT o.id FROM ${notificationOutbox} o+ WHERE o.delivery_status = 'pending'+ AND (o.monitor_id % 100) < ${rolloutPct}+ AND o.next_attempt_at <= unixepoch()+ AND o.deadline_at > unixepoch()${scope}+ AND (o.locked_until IS NULL OR o.locked_until < unixepoch())+ AND NOT EXISTS (+ SELECT 1 FROM ${notificationOutbox} older+ WHERE older.monitor_id = o.monitor_id+ AND older.notification_id = o.notification_id+ AND older.delivery_status = 'pending'+ AND older.id < o.id)+ ORDER BY o.id LIMIT ${limit})`,+ )+ .returning(),+ );+}++type DeliveryDeps = {+ monitors: Map<number, Monitor>;+ notifications: Map<number, Notification>;+ incidents: Map<number, Incident>;+ smsBlocked: Map<number, boolean>;+};++async function loadDeps(rows: OutboxRow[]): Promise<DeliveryDeps> {+ const monitorIds = [...new Set(rows.map((row) => row.monitorId))];+ const notificationIds = [...new Set(rows.map((row) => row.notificationId))];+ const incidentIds = [+ ...new Set(+ rows+ .map((row) => row.incidentId)+ .filter((id): id is number => id !== null),+ ),+ ];++ const [monitorRows, notificationRows, incidentRows] = await withBusyRetry(+ () =>+ db.batch([+ db.select().from(monitor).where(inArray(monitor.id, monitorIds)),+ db+ .select()+ .from(notification)+ .where(inArray(notification.id, notificationIds)),+ db+ .select()+ .from(incidentTable)+ .where(+ incidentIds.length === 0+ ? sql`1 = 0`+ : inArray(incidentTable.id, incidentIds),+ ),+ ]),+ );++ const monitors = new Map<number, Monitor>();+ for (const row of monitorRows) {+ const parsed = selectMonitorSchema.safeParse(row);+ if (parsed.success) monitors.set(row.id, parsed.data);+ }++ const notifications = new Map<number, Notification>();+ for (const row of notificationRows) {+ const parsed = selectNotificationSchema.safeParse(row);+ if (parsed.success) notifications.set(row.id, parsed.data);+ }++ const incidents = new Map<number, Incident>();+ for (const row of incidentRows) {+ incidents.set(row.id, row);+ }++ const smsWorkspaces = [+ ...new Set(+ rows+ .filter((row) => row.provider === "sms")+ .map((row) => row.workspaceId)+ .filter((id): id is number => id !== null),+ ),+ ];+ const smsBlocked = await loadSmsQuotaBlocked(smsWorkspaces);++ return { monitors, notifications, incidents, smsBlocked };+}++function deliverRow(+ row: OutboxRow,+ deps: DeliveryDeps,+ timeoutMs: number,+): Effect.Effect<DeliveryOutcome> {+ return Effect.gen(function* () {+ if (shuttingDown) return { kind: "released", row } as const;++ const monitorRow = deps.monitors.get(row.monitorId);+ const notificationRow = deps.notifications.get(row.notificationId);+ if (!monitorRow || !notificationRow) {+ return {+ kind: "dead",+ row,+ error: "monitor or notification no longer exists",+ } as const;+ }++ if (row.provider === "sms" && row.workspaceId !== null) {+ if (deps.smsBlocked.get(row.workspaceId) === true) {+ return { kind: "skipped", row, reason: "sms-quota-exceeded" } as const;+ }+ }++ const send = providerToFunction[row.provider][SEND_METHOD[row.eventType]];+ const context = {+ monitor: monitorRow,+ notification: notificationRow,+ statusCode: row.payload.statusCode,+ message: row.payload.message,+ cronTimestamp: row.cronTimestamp,+ regions: row.payload.regions,+ latency: row.payload.latency,+ incident:+ row.incidentId === null+ ? undefined+ : deps.incidents.get(row.incidentId),+ };++ inFlightSends.add(row.id);+ const exit = yield* Effect.exit(+ Effect.tryPromise({+ try: () => send(context),+ catch: (error) => new Error(errorMessage(error)),+ }).pipe(Effect.timeout(timeoutMs)),+ );+ inFlightSends.delete(row.id);++ if (Exit.isSuccess(exit)) return { kind: "delivered", row } as const;++ // The backoff is written to the row rather than slept through, so a retry+ // survives this process and either machine can pick it up.+ const error = String(exit.cause);+ const delayMs = backoffMs(row.attempts);+ if (Date.now() + delayMs >= row.deadlineAt * 1000) {+ return { kind: "dead", row, error } as const;+ }++ return {+ kind: "retry",+ row,+ error,+ delayMs,+ nextAttemptAt: Math.ceil((Date.now() + delayMs) / 1000),+ } as const;+ });+}++async function commitDelivered(rows: OutboxRow[]): Promise<void> {+ if (rows.length === 0) return;+ const ids = rows.map((row) => row.id);++ await withBusyRetry(() =>+ db.batch([+ db+ .update(notificationOutbox)+ .set({+ deliveryStatus: "settled",+ outcome: "delivered",+ deliveredAt: Math.floor(Date.now() / 1000),+ lockedBy: null,+ lockedUntil: null,+ })+ .where(inArray(notificationOutbox.id, ids)),+ db+ .insert(notificationTrigger)+ .values(+ rows.map((row) => ({+ monitorId: row.monitorId,+ notificationId: row.notificationId,+ cronTimestamp: row.cronTimestamp,+ })),+ )+ .onConflictDoNothing(),+ ]),+ );++ // Best-effort: the rows are settled and the triggers written. Throwing here+ // would abort the rest of the drain's commits and take the consumer loop down+ // with it, for a telemetry write.+ try {+ await Promise.all(+ rows.map((row) =>+ checkerAudit.publishAuditLog({+ id: `monitor:${row.monitorId}`,+ action: "notification.sent",+ targets: [{ id: String(row.monitorId), type: "monitor" }],+ metadata: {+ provider: row.provider,+ cronTimestamp: row.cronTimestamp,+ type: row.eventType,+ notificationId: row.notificationId,+ },+ }),+ ),+ );+ } catch (error) {+ logger.warn("Failed to publish notification audit log", {+ delivered_count: rows.length,+ error_message: errorMessage(error),+ });+ }+}++async function commitSkipped(+ entries: { row: OutboxRow; reason: string }[],+): Promise<void> {+ const [first, ...rest] = entries.map((entry) =>+ db+ .update(notificationOutbox)+ .set({+ deliveryStatus: "settled",+ outcome: "skipped",+ lockedBy: null,+ lockedUntil: null,+ lastError: entry.reason,+ })+ .where(eq(notificationOutbox.id, entry.row.id)),+ );+ if (first === undefined) return;+ await withBusyRetry(() => db.batch([first, ...rest]));+}++/**+ * Hands the row back with its backoff recorded. `attempts` already counts this+ * claim, so the row carries how many sends it has cost across every worker.+ */+async function commitRetry(+ entries: { row: OutboxRow; error: string; nextAttemptAt: number }[],+): Promise<void> {+ const [first, ...rest] = entries.map((entry) =>+ db+ .update(notificationOutbox)+ .set({+ nextAttemptAt: entry.nextAttemptAt,+ lockedBy: null,+ lockedUntil: null,+ lastError: entry.error.slice(0, 2000),+ })+ .where(eq(notificationOutbox.id, entry.row.id)),+ );+ if (first === undefined) return;+ await withBusyRetry(() => db.batch([first, ...rest]));+}++async function commitReleased(rows: OutboxRow[]): Promise<void> {+ if (rows.length === 0) return;+ await withBusyRetry(() =>+ db+ .update(notificationOutbox)+ .set({ lockedBy: null, lockedUntil: null })+ .where(+ inArray(+ notificationOutbox.id,+ rows.map((row) => row.id),+ ),+ ),+ );+}++async function commitDead(+ entries: { row: OutboxRow; error: string }[],+): Promise<void> {+ if (entries.length === 0) return;+ const diedAt = Math.floor(Date.now() / 1000);++ await withBusyRetry(() =>+ db.batch([+ db.insert(notificationDeadLetter).values(+ entries.map(({ row, error }) => ({+ outboxId: row.id,+ dedupKey: row.dedupKey,+ monitorId: row.monitorId,+ workspaceId: row.workspaceId,+ notificationId: row.notificationId,+ provider: row.provider,+ eventType: row.eventType,+ fromStatus: row.fromStatus,+ toStatus: row.toStatus,+ cronTimestamp: row.cronTimestamp,+ incidentId: row.incidentId,+ payload: row.payload,+ attempts: row.attempts,+ finalError: error.slice(0, 2000),+ diedAt,+ })),+ ),+ db.delete(notificationOutbox).where(+ inArray(+ notificationOutbox.id,+ entries.map(({ row }) => row.id),+ ),+ ),+ ]),+ );++ for (const { row, error } of entries) {+ logger.error("Notification dead-lettered", {+ monitor_id: row.monitorId,+ notification_id: row.notificationId,+ provider: row.provider,+ event_type: row.eventType,+ attempts: row.attempts,+ error_message: error,+ });+ Sentry.captureException(+ new Error(+ `Notification dead-lettered: ${row.provider} for monitor ${row.monitorId}`,+ ),+ );+ }+}++export type DrainOptions = {+ limit?: number;+ timeoutMs?: number;+ rolloutPct?: number;+ /** Restrict the drain to these monitors. */+ monitorIds?: number[];+};++/** One claim-and-deliver cycle. Safe to run concurrently on both machines. */+export function drainOutbox(options: DrainOptions = {}): Promise<DrainSummary> {+ const drain = runDrain(options);+ activeDrains.add(drain);+ return drain.finally(() => {+ activeDrains.delete(drain);+ });+}++async function runDrain(options: DrainOptions): Promise<DrainSummary> {+ const limit = options.limit ?? CLAIM_LIMIT;+ const timeoutMs = options.timeoutMs ?? env().NOTIFICATION_TIMEOUT_MS;+ const rolloutPct = options.rolloutPct ?? env().OUTBOX_ROLLOUT_PCT;+ const rows = await claimRows(+ limit,+ rolloutPct,+ leaseSeconds(limit, timeoutMs),+ options.monitorIds,+ );+ if (rows.length === 0) {+ return {+ claimed: 0,+ delivered: 0,+ skipped: 0,+ released: 0,+ retried: 0,+ dead: 0,+ nextRetryMs: null,+ };+ }++ const deps = await loadDeps(rows);++ const outcomes = await Effect.runPromise(+ Effect.forEach(rows, (row) => deliverRow(row, deps, timeoutMs), {+ concurrency: DELIVERY_CONCURRENCY,+ }),+ );++ const delivered = outcomes+ .filter((outcome) => outcome.kind === "delivered")+ .map((outcome) => outcome.row);+ const skipped = outcomes.filter((outcome) => outcome.kind === "skipped");+ const released = outcomes+ .filter((outcome) => outcome.kind === "released")+ .map((outcome) => outcome.row);+ const retried = outcomes.filter((outcome) => outcome.kind === "retry");+ const dead = outcomes.filter((outcome) => outcome.kind === "dead");++ await commitDelivered(delivered);+ await commitSkipped(skipped);+ await commitReleased(released);+ await commitRetry(retried);+ await commitDead(dead);++ return {+ claimed: rows.length,+ delivered: delivered.length,+ skipped: skipped.length,+ released: released.length,+ retried: retried.length,+ dead: dead.length,+ nextRetryMs:+ retried.length === 0+ ? null+ : Math.min(...retried.map((outcome) => outcome.delayMs)),+ };+}++const EXPIRED_GRACE_SECONDS = 60 * 60;++/**+ * A row can expire without ever being claimed: the rollout gate excluded it, or+ * nothing drained for longer than the deadline. Claiming it later would page+ * someone about an outage that is long over, so the claim skips expired rows and+ * this sweep retires them. `attempts > 0` means a worker claimed it and it still+ * never landed, which is a dead letter; `attempts = 0` means we never owned it.+ */+export async function sweepExpiredOutbox(): Promise<{+ deadLettered: number;+ discarded: number;+}> {+ const cutoff = Math.floor(Date.now() / 1000) - EXPIRED_GRACE_SECONDS;++ const expired = await withBusyRetry(() =>+ db+ .select()+ .from(notificationOutbox)+ .where(+ and(+ eq(notificationOutbox.deliveryStatus, "pending"),+ lt(notificationOutbox.deadlineAt, cutoff),+ ),+ )+ .limit(200)+ .all(),+ );++ if (expired.length === 0) return { deadLettered: 0, discarded: 0 };++ const abandoned = expired.filter((row) => row.attempts > 0);+ const neverOwned = expired.filter((row) => row.attempts === 0);++ await commitDead(+ abandoned.map((row) => ({+ row,+ error: "expired before delivery completed",+ })),+ );++ if (neverOwned.length > 0) {+ await withBusyRetry(() =>+ db.delete(notificationOutbox).where(+ inArray(+ notificationOutbox.id,+ neverOwned.map((row) => row.id),+ ),+ ),+ );+ logger.info("Discarded outbox rows that were never owned", {+ count: neverOwned.length,+ });+ }++ return { deadLettered: abandoned.length, discarded: neverOwned.length };+}++/** Drains until the queue is empty, so one wake-up clears a whole burst. */+export async function drainUntilEmpty(+ options: DrainOptions = {},+): Promise<DrainSummary> {+ const total: DrainSummary = {+ claimed: 0,+ delivered: 0,+ skipped: 0,+ released: 0,+ retried: 0,+ dead: 0,+ nextRetryMs: null,+ };++ const resolved: DrainOptions = {+ limit: options.limit ?? CLAIM_LIMIT,+ timeoutMs: options.timeoutMs ?? env().NOTIFICATION_TIMEOUT_MS,+ rolloutPct: options.rolloutPct ?? env().OUTBOX_ROLLOUT_PCT,+ monitorIds: options.monitorIds,+ };++ while (!shuttingDown) {+ const summary = await drainOutbox(resolved);+ total.claimed += summary.claimed;+ total.delivered += summary.delivered;+ total.skipped += summary.skipped;+ total.released += summary.released;+ total.retried += summary.retried;+ total.dead += summary.dead;+ if (summary.nextRetryMs !== null) {+ total.nextRetryMs =+ total.nextRetryMs === null+ ? summary.nextRetryMs+ : Math.min(total.nextRetryMs, summary.nextRetryMs);+ }+ if (summary.claimed < (resolved.limit ?? CLAIM_LIMIT)) break;+ }++ return total;+}++const wakeQueue = Effect.runSync(Queue.make<number>());++/** The durable state is the outbox row; this only decides when we look. */+export function enqueueOutbox(ids: number[]): void {+ for (const id of ids) {+ Queue.offerUnsafe(wakeQueue, id);+ }+}++const retryTimers = new Set<ReturnType<typeof setTimeout>>();++/**+ * The backoff is already durable in `next_attempt_at` and the safety-net cron+ * would find it; this only makes the wait match the backoff instead of the cron.+ */+function scheduleRetryWake(delayMs: number): void {+ if (shuttingDown) return;+ const timer = setTimeout(() => {+ retryTimers.delete(timer);+ Queue.offerUnsafe(wakeQueue, 0);+ }, delayMs);+ retryTimers.add(timer);+}++export function startOutboxConsumer(): void {+ const loop = Effect.gen(function* () {+ while (!shuttingDown) {+ yield* Queue.takeAll(wakeQueue);+ const summary = yield* Effect.promise(() => drainUntilEmpty());+ if (summary.nextRetryMs !== null) scheduleRetryWake(summary.nextRetryMs);+ }+ });++ void Effect.runPromise(loop).catch((error) => {+ logger.error("Outbox consumer stopped", {+ error_message: errorMessage(error),+ });+ });+}++/**+ * Fly SIGTERMs on every deploy and on the daily restart. Releasing unstarted+ * claims hands them to the peer machine now instead of at lease expiry.+ */+export async function shutdownOutbox(graceMs?: number): Promise<void> {+ shuttingDown = true;+ for (const timer of retryTimers) clearTimeout(timer);+ retryTimers.clear();+ await Effect.runPromise(Queue.shutdown(wakeQueue));+ await waitForDrains(graceMs ?? env().NOTIFICATION_TIMEOUT_MS + 5_000);++ // Anything still sending keeps its lease: the provider call can succeed after+ // we stop watching, so the peer waits for the lease to lapse rather than+ // starting a second send while this one is outstanding.+ const stillSending = [...inFlightSends];+ await withBusyRetry(() =>+ db+ .update(notificationOutbox)+ .set({ lockedBy: null, lockedUntil: null })+ .where(+ stillSending.length === 0+ ? eq(notificationOutbox.lockedBy, workerId)+ : and(+ eq(notificationOutbox.lockedBy, workerId),+ notInArray(notificationOutbox.id, stillSending),+ ),+ ),+ );+}++async function waitForDrains(graceMs: number): Promise<void> {+ if (activeDrains.size === 0) return;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const grace = new Promise<void>((resolve) => {+ timer = setTimeout(resolve, graceMs);+ });+ await Promise.race([+ Promise.allSettled(activeDrains).then(() => undefined),+ grace,+ ]);+ if (timer !== undefined) clearTimeout(timer);+}diff --git a/apps/workflows/src/checker/quorum.ts b/apps/workflows/src/checker/quorum.tsnew file mode 100644index 000000000..e261f5ef5--- /dev/null+++ b/apps/workflows/src/checker/quorum.ts@@ -0,0 +1,50 @@+import { type SQL, sql } from "@openstatus/db";+import type { MonitorStatus } from "@openstatus/db/src/schema";+import { monitor, monitorStatusTable } from "@openstatus/db/src/schema";++export type QuorumParams = {+ toStatus: MonitorStatus;+ regionsJson: string;+ regionCount: number;+};++/**+ * The rule itself: `affected >= total / 2`, without floating point. Every other+ * expression in this file — and every caller — goes through it, so a change to+ * how quorum is decided happens here and nowhere else.+ */+export function quorumMetSql(affected: SQL, total: SQL): SQL {+ return sql`${affected} * 2 >= ${total}`;+}++/** Regions of this monitor currently reporting `toStatus`. Correlates on `monitor.id`. */+export function quorumCountSql({+ toStatus,+ regionsJson,+}: Pick<QuorumParams, "toStatus" | "regionsJson">): SQL {+ return sql`(SELECT count(*) FROM ${monitorStatusTable}+ WHERE ${monitorStatusTable.monitorId} = ${monitor.id}+ AND ${monitorStatusTable.status} = ${toStatus}+ AND ${monitorStatusTable.region} IN (SELECT value FROM json_each(${regionsJson})))`;+}++/** Hot path: the region list arrives as a bound JSON array. */+export function quorumGuardSql(params: QuorumParams): SQL {+ return sql`(${params.regionCount} > 0 AND ${quorumMetSql(+ quorumCountSql(params),+ sql`${params.regionCount}`,+ )})`;+}++/**+ * `monitor.regions` is a comma-joined text column. Deriving the count and+ * membership in SQL is only worth it where the monitor row is not already in+ * hand — currently just the drift sweep, which scans every monitor at once.+ */+export function csvRegionCountSql(): SQL {+ return sql`(length(${monitor.regions}) - length(replace(${monitor.regions}, ',', '')) + 1)`;+}++export function csvRegionMemberSql(region: SQL): SQL {+ return sql`instr(',' || ${monitor.regions} || ',', ',' || ${region} || ',') > 0`;+}diff --git a/apps/workflows/src/checker/sms-quota.ts b/apps/workflows/src/checker/sms-quota.tsnew file mode 100644index 000000000..7a93c6ba2--- /dev/null+++ b/apps/workflows/src/checker/sms-quota.ts@@ -0,0 +1,93 @@+import { and, count, db, eq, gte, inArray } from "@openstatus/db";+import {+ notification,+ notificationTrigger,+ selectWorkspaceSchema,+ workspace,+} from "@openstatus/db/src/schema";+import { withBusyRetry } from "@openstatus/services";++const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;++/**+ * `cron_timestamp` is stored in milliseconds; comparing it against a+ * seconds-resolution cutoff made the window unbounded, so every workspace that+ * had ever passed its limit stayed blocked.+ *+ * Two round trips regardless of how many workspaces are asked about.+ */+export async function loadSmsQuotaBlocked(+ workspaceIds: number[],+): Promise<Map<number, boolean>> {+ const blocked = new Map<number, boolean>();+ if (workspaceIds.length === 0) return blocked;++ const [workspaceRows, notificationRows] = await withBusyRetry(() =>+ db.batch([+ db.select().from(workspace).where(inArray(workspace.id, workspaceIds)),+ db+ .select({ id: notification.id, workspaceId: notification.workspaceId })+ .from(notification)+ .where(+ and(+ inArray(notification.workspaceId, workspaceIds),+ eq(notification.provider, "sms"),+ ),+ ),+ ]),+ );++ const notificationsByWorkspace = new Map<number, number[]>();+ for (const row of notificationRows) {+ if (row.workspaceId === null) continue;+ const ids = notificationsByWorkspace.get(row.workspaceId) ?? [];+ ids.push(row.id);+ notificationsByWorkspace.set(row.workspaceId, ids);+ }++ const notificationIds = notificationRows.map((row) => row.id);+ const sentRows =+ notificationIds.length === 0+ ? []+ : await withBusyRetry(() =>+ db+ .select({+ notificationId: notificationTrigger.notificationId,+ total: count(),+ })+ .from(notificationTrigger)+ .where(+ and(+ inArray(notificationTrigger.notificationId, notificationIds),+ gte(+ notificationTrigger.cronTimestamp,+ Date.now() - THIRTY_DAYS_MS,+ ),+ ),+ )+ .groupBy(notificationTrigger.notificationId)+ .all(),+ );++ const sentByNotification = new Map<number, number>();+ for (const row of sentRows) {+ if (row.notificationId === null) continue;+ sentByNotification.set(row.notificationId, row.total);+ }++ for (const row of workspaceRows) {+ const parsed = selectWorkspaceSchema.safeParse(row);+ if (!parsed.success) {+ blocked.set(row.id, true);+ continue;+ }+ const ids = notificationsByWorkspace.get(row.id) ?? [];+ const sent = ids.reduce(+ (total, id) => total + (sentByNotification.get(id) ?? 0),+ 0,+ );+ blocked.set(row.id, sent > parsed.data.limits["sms-limit"]);+ }++ return blocked;+}diff --git a/apps/workflows/src/checker/transition.test.ts b/apps/workflows/src/checker/transition.test.tsnew file mode 100644index 000000000..fe67e82ce--- /dev/null+++ b/apps/workflows/src/checker/transition.test.ts@@ -0,0 +1,409 @@+import { and, count, db, eq, isNull } from "@openstatus/db";+import {+ monitorTransition,+ notificationOutbox,+ incidentTable,+ monitor,+ monitorStatusTable,+} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createNotification,+ createTestWorkspace,+ linkNotificationToMonitor,+} from "@openstatus/db/src/test/factories";+import {+ afterAll,+ beforeAll,+ describe,+ expect,+ test,+} from "@openstatus/test-utils";++import { drainOutbox } from "./outbox";+import { applyStatusTransition, isStaleCheck } from "./transition";++const REGIONS = ["ams", "arn", "atl", "bog", "bom", "bos"] as const;+const DEADLINE_SECONDS = 300;++let workspaceId: number;++beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ workspaceId = workspace.id;+});++afterAll(async () => {+ await db.delete(monitor).where(eq(monitor.workspaceId, workspaceId)).run();+});++async function makeMonitor(regionCount: number, withNotification = true) {+ const regions = REGIONS.slice(0, regionCount);+ const row = await createMonitor(workspaceId, {+ regions: regions.join(","),+ });+ if (withNotification) {+ const notif = await createNotification(workspaceId);+ await linkNotificationToMonitor(notif.id, row.id);+ }+ return { monitorId: row.id, regions };+}++async function seedRegionStatus(+ monitorId: number,+ regions: readonly string[],+ status: "active" | "error" | "degraded",+) {+ if (regions.length === 0) return;+ await db+ .insert(monitorStatusTable)+ .values(+ regions.map((region) => ({+ monitorId,+ region,+ status,+ cronTimestamp: 0,+ })),+ )+ .run();+}++function transitionInput(+ monitorId: number,+ region: string,+ cronTimestamp: number,+) {+ return {+ monitorId,+ region,+ status: "error" as const,+ cronTimestamp,+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 100,+ };+}++describe("quorum", () => {+ const cases: { regions: number; affected: number }[] = [];+ for (let regions = 1; regions <= 6; regions++) {+ for (let affected = 1; affected <= regions; affected++) {+ cases.push({ regions, affected });+ }+ }++ for (const { regions, affected } of cases) {+ test(`${affected} of ${regions} regions in error`, async () => {+ const { monitorId, regions: list } = await makeMonitor(regions, false);+ await seedRegionStatus(monitorId, list.slice(0, affected - 1), "error");++ const result = await applyStatusTransition(+ transitionInput(monitorId, list[affected - 1], Date.now()),+ );++ // Matches the pre-existing `affected >= regions / 2 || regions === 1`.+ const expected = affected >= regions / 2 || regions === 1;++ expect(result.kind).toBe("evaluated");+ if (result.kind !== "evaluated") return;+ expect(result.quorumCount).toBe(affected);+ expect(result.regionCount).toBe(regions);+ expect(result.transitioned).toBe(expected);+ });+ }+});++describe("fast path", () => {+ test("an unchanged region status writes nothing and short-circuits", async () => {+ const { monitorId, regions } = await makeMonitor(1);+ const first = await applyStatusTransition(+ transitionInput(monitorId, regions[0], Date.now()),+ );+ expect(first.kind).toBe("evaluated");++ const second = await applyStatusTransition(+ transitionInput(monitorId, regions[0], Date.now() + 1),+ );+ expect(second.kind).toBe("unchanged");+ });++ test("an older cronTimestamp is rejected", async () => {+ const { monitorId, regions } = await makeMonitor(1);+ const now = Date.now();+ await applyStatusTransition(transitionInput(monitorId, regions[0], now));++ const stale = await applyStatusTransition({+ monitorId,+ region: regions[0],+ status: "active",+ cronTimestamp: now - 60_000,+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 100,+ });++ expect(stale.kind).toBe("unchanged");++ const rows = await db+ .select({ status: monitorStatusTable.status })+ .from(monitorStatusTable)+ .where(+ and(+ eq(monitorStatusTable.monitorId, monitorId),+ eq(monitorStatusTable.region, regions[0]),+ ),+ )+ .all();+ expect(rows[0]?.status).toBe("error");+ });+});++describe("replay", () => {+ test("repeating the same check produces one incident and one outbox row", async () => {+ const { monitorId, regions } = await makeMonitor(1);+ const cronTimestamp = Date.now();++ for (let i = 0; i < 5; i++) {+ await applyStatusTransition(+ transitionInput(monitorId, regions[0], cronTimestamp),+ );+ }++ const incidents = await db+ .select({ total: count() })+ .from(incidentTable)+ .where(+ and(+ eq(incidentTable.monitorId, monitorId),+ isNull(incidentTable.resolvedAt),+ ),+ )+ .all();+ expect(incidents[0]?.total).toBe(1);++ const outbox = await db+ .select({ total: count() })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(outbox[0]?.total).toBe(1);+ });+});++describe("decision journal", () => {+ test("records the quorum inputs and the outcome", async () => {+ const { monitorId, regions } = await makeMonitor(3);+ const cronTimestamp = Date.now();++ await applyStatusTransition(+ transitionInput(monitorId, regions[0], cronTimestamp),+ );++ const rows = await db+ .select()+ .from(monitorTransition)+ .where(eq(monitorTransition.monitorId, monitorId))+ .all();++ expect(rows.length).toBe(1);+ expect(rows[0]?.quorumCount).toBe(1);+ expect(rows[0]?.regionCount).toBe(3);+ expect(rows[0]?.transitioned).toBe(false);+ expect(rows[0]?.fromStatus).toBe("active");+ expect(rows[0]?.toStatus).toBe("error");+ });+});++describe("recovery", () => {+ test("resolves the open incident and enqueues a recovery", async () => {+ const { monitorId, regions } = await makeMonitor(1);+ const down = Date.now();+ await applyStatusTransition(transitionInput(monitorId, regions[0], down));++ const recovery = await applyStatusTransition({+ monitorId,+ region: regions[0],+ status: "active",+ cronTimestamp: down + 60_000,+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 100,+ });++ expect(recovery.kind).toBe("evaluated");+ if (recovery.kind !== "evaluated") return;+ expect(recovery.transitioned).toBe(true);+ expect(recovery.outboxRows.length).toBe(1);++ const open = await db+ .select({ total: count() })+ .from(incidentTable)+ .where(+ and(+ eq(incidentTable.monitorId, monitorId),+ isNull(incidentTable.resolvedAt),+ ),+ )+ .all();+ expect(open[0]?.total).toBe(0);++ const events = await db+ .select({ eventType: notificationOutbox.eventType })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(events.map((row) => row.eventType).sort()).toEqual([+ "alert",+ "recovery",+ ]);+ });+});++describe("concurrency", () => {+ test("parallel region failures produce exactly one incident", async () => {+ const { monitorId, regions } = await makeMonitor(4);+ const cronTimestamp = Date.now();++ await Promise.all(+ regions.map((region) =>+ applyStatusTransition(+ transitionInput(monitorId, region, cronTimestamp),+ ),+ ),+ );++ const incidents = await db+ .select({ total: count() })+ .from(incidentTable)+ .where(eq(incidentTable.monitorId, monitorId))+ .all();+ expect(incidents[0]?.total).toBe(1);++ const outbox = await db+ .select({ total: count() })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(outbox[0]?.total).toBe(1);++ const monitorRow = await db+ .select({ status: monitor.status })+ .from(monitor)+ .where(eq(monitor.id, monitorId))+ .all();+ expect(monitorRow[0]?.status).toBe("error");+ });+});++describe("isStaleCheck", () => {+ test("accepts a fresh payload and rejects an old one", () => {+ const now = 1_000_000;+ expect(isStaleCheck(now - 1000, 600_000, now)).toBe(false);+ expect(isStaleCheck(now - 700_000, 600_000, now)).toBe(true);+ });+});++describe("degraded", () => {+ test("enqueues a degraded notification and resolves an open incident", async () => {+ const { monitorId, regions } = await makeMonitor(1);+ const down = Date.now();+ await applyStatusTransition(transitionInput(monitorId, regions[0], down));++ const degraded = await applyStatusTransition({+ monitorId,+ region: regions[0],+ status: "degraded",+ cronTimestamp: down + 60_000,+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 100,+ });++ expect(degraded.kind).toBe("evaluated");+ if (degraded.kind !== "evaluated") return;+ expect(degraded.transitioned).toBe(true);+ expect(degraded.outboxRows.length).toBe(1);+ expect(degraded.incidentId).not.toBe(null);++ const events = await db+ .select({+ eventType: notificationOutbox.eventType,+ incidentId: notificationOutbox.incidentId,+ })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(events.map((row) => row.eventType).sort()).toEqual([+ "alert",+ "degraded",+ ]);+ // the degraded row captured the incident before it was resolved+ for (const row of events) expect(row.incidentId).not.toBe(null);++ const open = await db+ .select({ total: count() })+ .from(incidentTable)+ .where(+ and(+ eq(incidentTable.monitorId, monitorId),+ isNull(incidentTable.resolvedAt),+ ),+ )+ .all();+ expect(open[0]?.total).toBe(0);+ });+});++describe("rollout gate", () => {+ test("a row written outside the rollout is not redelivered when the gate opens", async () => {+ const { monitorId, regions } = await makeMonitor(1);++ const result = await applyStatusTransition({+ monitorId,+ region: regions[0],+ status: "error",+ cronTimestamp: Date.now(),+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 0,+ });++ expect(result.kind).toBe("evaluated");+ if (result.kind !== "evaluated") return;+ expect(result.transitioned).toBe(true);++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows.length).toBe(1);+ expect(rows[0]?.deliveryStatus).toBe("settled");+ expect(rows[0]?.outcome).toBe("inline");++ // The inline sender already delivered this one; opening the gate must not+ // make the drainer claim it a second time.+ const summary = await drainOutbox({+ timeoutMs: 100,+ rolloutPct: 100,+ monitorIds: [monitorId],+ });+ expect(summary.claimed).toBe(0);+ });++ test("a row written inside the rollout is claimable", async () => {+ const { monitorId, regions } = await makeMonitor(1);++ await applyStatusTransition({+ monitorId,+ region: regions[0],+ status: "error",+ cronTimestamp: Date.now(),+ deadlineSeconds: DEADLINE_SECONDS,+ rolloutPct: 100,+ });++ const rows = await db+ .select()+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .all();+ expect(rows[0]?.deliveryStatus).toBe("pending");+ expect(rows[0]?.outcome).toBe(null);+ });+});diff --git a/apps/workflows/src/checker/transition.ts b/apps/workflows/src/checker/transition.tsnew file mode 100644index 000000000..86ce13f02--- /dev/null+++ b/apps/workflows/src/checker/transition.ts@@ -0,0 +1,384 @@+import { getLogger } from "@logtape/logtape";+import { type SQL, and, db, eq, sql } from "@openstatus/db";+import type {+ NotificationOutboxPayload,+ MonitorStatus,+ NotificationProvider,+} from "@openstatus/db/src/schema";+import {+ monitorTransition,+ notificationOutbox,+ notificationOutboxEventType,+ incidentTable,+ monitor,+ monitorStatusTable,+ notification,+ notificationsToMonitors,+ selectMonitorSchema,+} from "@openstatus/db/src/schema";+import { withBusyRetry } from "@openstatus/services";++import { checkerAudit } from "../utils/audit-log";++const logger = getLogger(["workflow"]);+import { quorumCountSql, quorumGuardSql } from "./quorum";++export type EventType = (typeof notificationOutboxEventType)[number];++export const EVENT_TYPE: Record<MonitorStatus, EventType> = {+ active: "recovery",+ degraded: "degraded",+ error: "alert",+};++export type TransitionInput = {+ monitorId: number;+ region: string;+ status: MonitorStatus;+ cronTimestamp: number;+ statusCode?: number;+ message?: string;+ latency?: number;+ deadlineSeconds: number;+ /** Monitors outside this gate are still delivered by the inline sender. */+ rolloutPct: number;+};++export type OutboxRowRef = {+ id: number;+ notificationId: number;+ provider: NotificationProvider;+ /** `pending` means the drainer owns delivery; `settled` means the inline sender does. */+ deliveryStatus: "pending" | "settled";+};++export type TransitionResult =+ | { kind: "unchanged" }+ | { kind: "monitor-missing" }+ | {+ kind: "evaluated";+ transitioned: boolean;+ quorumCount: number;+ regionCount: number;+ affectedRegions: string[];+ outboxRows: OutboxRowRef[];+ incidentId: number | null;+ incidentCreatedId: number | null;+ incidentResolvedIds: number[];+ };++/**+ * A Cloud Tasks retry can land after a later check already reported. The stored+ * `cron_timestamp` only advances on a status change, so it cannot bound this on+ * its own.+ */+export function isStaleCheck(+ cronTimestamp: number,+ maxAgeMs: number,+ now = Date.now(),+): boolean {+ return now - cronTimestamp > maxAgeMs;+}++type JournalRow = { quorum_count: number; transitioned: number };+type OutboxInsertRow = {+ id: number;+ notification_id: number;+ incident_id: number | null;+ provider: NotificationProvider;+ delivery_status: "pending" | "settled";+};++function journalStatement(+ input: TransitionInput,+ regionsJson: string,+ regionCount: number,+ guard: SQL,+) {+ const count = quorumCountSql({+ toStatus: input.status,+ regionsJson,+ });+ const transitioning = sql`${guard} AND ${monitor.status} <> ${input.status}`;++ return db.all<JournalRow>(sql`+ INSERT INTO ${monitorTransition}+ (monitor_id, region, cron_timestamp, from_status, to_status,+ quorum_count, region_count, transitioned, outbox_rows, created_at)+ SELECT+ ${monitor.id}, ${input.region}, ${input.cronTimestamp},+ ${monitor.status}, ${input.status},+ ${count}, ${regionCount},+ CASE WHEN ${transitioning} THEN 1 ELSE 0 END,+ CASE WHEN ${transitioning} THEN+ (SELECT count(*) FROM ${notificationsToMonitors}+ WHERE ${notificationsToMonitors.monitorId} = ${monitor.id})+ ELSE 0 END,+ unixepoch()+ FROM ${monitor}+ WHERE ${monitor.id} = ${input.monitorId}+ RETURNING quorum_count, transitioned+ `);+}++function createIncidentStatement(input: TransitionInput, guard: SQL) {+ return db.all<{ id: number }>(sql`+ INSERT INTO ${incidentTable} (monitor_id, workspace_id, started_at)+ SELECT ${monitor.id}, ${monitor.workspaceId}, ${Math.floor(input.cronTimestamp / 1000)}+ FROM ${monitor}+ WHERE ${monitor.id} = ${input.monitorId}+ AND ${monitor.status} <> ${input.status}+ AND ${guard}+ AND NOT EXISTS (+ SELECT 1 FROM ${incidentTable}+ WHERE ${incidentTable.monitorId} = ${monitor.id}+ AND ${incidentTable.resolvedAt} IS NULL)+ ON CONFLICT DO NOTHING+ RETURNING id+ `);+}++function resolveIncidentStatement(input: TransitionInput, guard: SQL) {+ return db.all<{ id: number }>(sql`+ UPDATE ${incidentTable}+ SET resolved_at = ${Math.floor(input.cronTimestamp / 1000)}, auto_resolved = 1+ WHERE ${incidentTable.monitorId} = ${input.monitorId}+ AND ${incidentTable.resolvedAt} IS NULL+ AND EXISTS (+ SELECT 1 FROM ${monitor}+ WHERE ${monitor.id} = ${input.monitorId}+ AND ${monitor.status} <> ${input.status}+ AND ${guard})+ RETURNING id+ `);+}++function outboxStatement(+ input: TransitionInput,+ payload: NotificationOutboxPayload,+ guard: SQL,+) {+ const dedupPrefix = `${input.cronTimestamp}:${input.monitorId}:${input.status}:`;+ // Outside the rollout the inline sender owns this delivery, so the row is+ // written already consumed: it still feeds the shadow diff, but raising+ // OUTBOX_ROLLOUT_PCT can never make the drainer re-send it.+ const owned = sql`(${monitor.id} % 100) < ${input.rolloutPct}`;++ return db.all<OutboxInsertRow>(sql`+ INSERT INTO ${notificationOutbox}+ (dedup_key, monitor_id, workspace_id, notification_id, provider, event_type,+ from_status, to_status, cron_timestamp, incident_id, payload,+ delivery_status, outcome, next_attempt_at, deadline_at, created_at)+ SELECT+ ${dedupPrefix} || ${notification.id},+ ${monitor.id}, ${monitor.workspaceId}, ${notification.id},+ ${notification.provider}, ${EVENT_TYPE[input.status]},+ ${monitor.status}, ${input.status}, ${input.cronTimestamp},+ (SELECT id FROM ${incidentTable}+ WHERE ${incidentTable.monitorId} = ${monitor.id}+ AND ${incidentTable.resolvedAt} IS NULL+ ORDER BY id DESC LIMIT 1),+ ${JSON.stringify(payload)},+ CASE WHEN ${owned} THEN 'pending' ELSE 'settled' END,+ CASE WHEN ${owned} THEN NULL ELSE 'inline' END,+ unixepoch(), unixepoch() + ${input.deadlineSeconds}, unixepoch()+ FROM ${monitor}+ JOIN ${notificationsToMonitors}+ ON ${notificationsToMonitors.monitorId} = ${monitor.id}+ JOIN ${notification}+ ON ${notification.id} = ${notificationsToMonitors.notificationId}+ WHERE ${monitor.id} = ${input.monitorId}+ AND ${monitor.status} <> ${input.status}+ AND ${guard}+ ON CONFLICT (dedup_key) DO NOTHING+ RETURNING id, notification_id, incident_id, provider, delivery_status+ `);+}++function casStatement(input: TransitionInput, guard: SQL) {+ return db.all<{ id: number }>(sql`+ UPDATE ${monitor}+ SET status = ${input.status}, updated_at = unixepoch()+ WHERE ${monitor.id} = ${input.monitorId}+ AND ${monitor.status} <> ${input.status}+ AND ${guard}+ RETURNING id+ `);+}++/**+ * Writes the region status and, only when that changed something, evaluates the+ * monitor transition as one atomic batch. An outbox row exists iff the+ * compare-and-swap matched, so a notification is owed exactly once.+ */+export async function applyStatusTransition(+ input: TransitionInput,+): Promise<TransitionResult> {+ const changed = await withBusyRetry(() =>+ db.all<{ region: string }>(sql`+ INSERT INTO ${monitorStatusTable}+ (monitor_id, region, status, cron_timestamp, updated_at)+ VALUES (${input.monitorId}, ${input.region}, ${input.status}, ${input.cronTimestamp}, unixepoch())+ ON CONFLICT (monitor_id, region) DO UPDATE+ SET status = excluded.status,+ cron_timestamp = excluded.cron_timestamp,+ updated_at = unixepoch()+ WHERE ${monitorStatusTable.status} <> excluded.status+ AND excluded.cron_timestamp > ${monitorStatusTable.cronTimestamp}+ RETURNING region+ `),+ );++ if (changed.length === 0) return { kind: "unchanged" };++ return evaluateTransition(input);+}++/**+ * The transition half, without the region write. Exported as the repair entry+ * point: the region write and this evaluation are separate transactions, so a+ * crash or a failed batch between them leaves `monitor.status` behind, and the+ * fast path means replaying the same check will not re-evaluate it.+ */+export async function evaluateTransition(+ input: TransitionInput,+): Promise<TransitionResult> {+ const [monitorRows, statusRows] = await withBusyRetry(() =>+ db.batch([+ db.select().from(monitor).where(eq(monitor.id, input.monitorId)),+ db+ .select({ region: monitorStatusTable.region })+ .from(monitorStatusTable)+ .where(+ and(+ eq(monitorStatusTable.monitorId, input.monitorId),+ eq(monitorStatusTable.status, input.status),+ ),+ ),+ ]),+ );++ const parsed = selectMonitorSchema.safeParse(monitorRows[0]);+ if (!parsed.success) return { kind: "monitor-missing" };++ const regions = parsed.data.regions;+ const regionsJson = JSON.stringify(regions);+ const regionCount = regions.length;+ const configuredRegions = new Set<string>(regions);+ const affectedRegions = statusRows+ .map((row) => row.region)+ .filter((region) => configuredRegions.has(region));++ const payload: NotificationOutboxPayload = {+ regions: affectedRegions,+ statusCode: input.statusCode,+ message: input.message,+ latency: input.latency,+ };++ const guard = quorumGuardSql({+ toStatus: input.status,+ regionsJson,+ regionCount,+ });+ const journal = journalStatement(input, regionsJson, regionCount, guard);+ const outbox = outboxStatement(input, payload, guard);+ const cas = casStatement(input, guard);++ let journalRows: JournalRow[];+ let outboxRows: OutboxInsertRow[];+ let incidentRows: { id: number }[] = [];++ // All three statuses enqueue notifications; only the incident statement moves.+ // The outbox row reads incident_id by subquery, so it must run after the+ // incident is created but before an existing one is resolved.+ if (input.status === "error") {+ const [journalResult, incidentResult, outboxResult] = await withBusyRetry(+ () =>+ db.batch([journal, createIncidentStatement(input, guard), outbox, cas]),+ );+ journalRows = journalResult;+ outboxRows = outboxResult;+ incidentRows = incidentResult;+ } else {+ const [journalResult, outboxResult, incidentResult] = await withBusyRetry(+ () =>+ db.batch([+ journal,+ outbox,+ resolveIncidentStatement(input, guard),+ cas,+ ]),+ );+ journalRows = journalResult;+ outboxRows = outboxResult;+ incidentRows = incidentResult;+ }++ const incidentCreatedId =+ input.status === "error" ? (incidentRows[0]?.id ?? null) : null;+ const incidentResolvedIds =+ input.status === "error" ? [] : incidentRows.map((row) => row.id);++ // Published here rather than in the route so drift repair keeps the trail too.+ await publishIncidentAudit(input, incidentCreatedId, incidentResolvedIds);++ return {+ kind: "evaluated",+ transitioned: (journalRows[0]?.transitioned ?? 0) === 1,+ quorumCount: journalRows[0]?.quorum_count ?? 0,+ regionCount,+ affectedRegions,+ outboxRows: outboxRows.map((row) => ({+ id: row.id,+ notificationId: row.notification_id,+ provider: row.provider,+ deliveryStatus: row.delivery_status,+ })),+ incidentId: outboxRows[0]?.incident_id ?? null,+ incidentCreatedId,+ incidentResolvedIds,+ };+}++async function publishIncidentAudit(+ input: TransitionInput,+ createdId: number | null,+ resolvedIds: number[],+): Promise<void> {+ const targets = [{ id: String(input.monitorId), type: "monitor" as const }];+ const entries: Promise<unknown>[] = [];++ if (createdId !== null) {+ entries.push(+ checkerAudit.publishAuditLog({+ id: `monitor:${input.monitorId}`,+ action: "incident.created",+ targets,+ metadata: { cronTimestamp: input.cronTimestamp, incidentId: createdId },+ }),+ );+ }++ for (const incidentId of resolvedIds) {+ entries.push(+ checkerAudit.publishAuditLog({+ id: `monitor:${input.monitorId}`,+ action: "incident.resolved",+ targets,+ metadata: { cronTimestamp: input.cronTimestamp, incidentId },+ }),+ );+ }++ // Best-effort: the incident is already committed, and failing here would make+ // Cloud Tasks retry a transition that has landed.+ try {+ await Promise.all(entries);+ } catch (error) {+ logger.warn("Failed to publish incident audit log", {+ monitor_id: input.monitorId,+ error_message: error instanceof Error ? error.message : String(error),+ });+ }+}diff --git a/apps/workflows/src/checker/update-status.test.ts b/apps/workflows/src/checker/update-status.test.tsnew file mode 100644index 000000000..b0a975b2d--- /dev/null+++ b/apps/workflows/src/checker/update-status.test.ts@@ -0,0 +1,130 @@+import { db, eq } from "@openstatus/db";+import {+ incidentTable,+ monitor,+ notificationOutbox,+ notificationTrigger,+} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createNotification,+ createTestWorkspace,+ linkNotificationToMonitor,+} from "@openstatus/db/src/test/factories";+import {+ afterAll,+ afterEach,+ assertSpyCalls,+ beforeAll,+ beforeEach,+ describe,+ expect,+ type Stub,+ stub,+ test,+} from "@openstatus/test-utils";++import { env } from "../env";+import { checkerAudit } from "../utils/audit-log";+import { checkerRoute } from "./index";+import { providerToFunction } from "./utils";++// biome-ignore lint/suspicious/noExplicitAny: heterogeneous provider stubs+type AnyStub = Stub<any>;+let stubs: AnyStub[] = [];++let workspaceId: number;+let monitorId: number;+let notificationId: number;++const cronSecret = env().CRON_SECRET;++beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ workspaceId = workspace.id;+ const monitorRow = await createMonitor(workspaceId, {+ regions: "ams",+ status: "active",+ });+ monitorId = monitorRow.id;+ const notif = await createNotification(workspaceId, { provider: "email" });+ notificationId = notif.id;+ await linkNotificationToMonitor(notificationId, monitorId);+});++afterAll(async () => {+ await db.delete(monitor).where(eq(monitor.workspaceId, workspaceId)).run();+});++beforeEach(() => {+ stubs = [];+});++afterEach(async () => {+ for (const s of stubs) s.restore();+ stubs = [];+ await db+ .delete(notificationTrigger)+ .where(eq(notificationTrigger.monitorId, monitorId))+ .run();+ await db+ .delete(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorId))+ .run();+ await db+ .delete(incidentTable)+ .where(eq(incidentTable.monitorId, monitorId))+ .run();+ await db+ .update(monitor)+ .set({ status: "active" })+ .where(eq(monitor.id, monitorId))+ .run();+});++function post(payload: Record<string, unknown>) {+ return checkerRoute.request("/updateStatus", {+ method: "POST",+ headers: {+ Authorization: `Basic ${cronSecret}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ });+}++describe("updateStatus audit failures", () => {+ test("a failing audit log does not cost the notification", async () => {+ // Tinybird is down: every audit publish rejects, including the status one+ // that runs after the transition batch has committed.+ stubs.push(+ stub(checkerAudit, "publishAuditLog", () =>+ Promise.reject(new Error("tinybird unavailable")),+ ) as AnyStub,+ );+ const sendAlert = stub(providerToFunction.email, "sendAlert", () =>+ Promise.resolve(),+ );+ stubs.push(sendAlert as AnyStub);++ const res = await post({+ monitorId: String(monitorId),+ region: "ams",+ status: "error",+ cronTimestamp: Date.now(),+ statusCode: 500,+ });++ // Retrying this transition is useless — the region status is already+ // written, so the retry takes the fast path and sends nothing.+ expect(res.status).toBe(200);+ assertSpyCalls(sendAlert, 1);++ const rows = await db+ .select()+ .from(monitor)+ .where(eq(monitor.id, monitorId))+ .all();+ expect(rows[0]?.status).toBe("error");+ });+});diff --git a/apps/workflows/src/cron/index.ts b/apps/workflows/src/cron/index.tsindex 4b0df286f..0768ac6e3 100644--- a/apps/workflows/src/cron/index.ts+++ b/apps/workflows/src/cron/index.ts@@ -16,7 +16,13 @@ import {StepPaused,workflowStepSchema,} from "./monitor";+import {+ handleOutboxDrainCron,+ handleOutboxRetentionCron,+ handleOutboxShadowCron,+} from "./outbox";import { handlePrivateLocationHealthCron } from "./private-location-health";+import { handleStatusDriftCron } from "./status-drift";import { handleUptimeFreezeCron } from "./uptime-freeze";const app = new Hono({ strict: false });@@ -162,4 +168,24 @@ app.get("/monitors/:step", async (c) => {return c.json({ success: true }, 200);});+app.get("/outbox/drain", async (c) => {+ const summary = await handleOutboxDrainCron();+ return c.json({ success: true, ...summary }, 200);+});++app.get("/outbox/retention", async (c) => {+ const summary = await handleOutboxRetentionCron();+ return c.json({ success: true, ...summary }, 200);+});++app.get("/outbox/shadow", async (c) => {+ const result = await handleOutboxShadowCron();+ return c.json({ success: true, ...result }, 200);+});++app.get("/status-drift", async (c) => {+ const result = await handleStatusDriftCron();+ return c.json({ success: true, ...result }, 200);+});+export { app as cronRouter };diff --git a/apps/workflows/src/cron/outbox.ts b/apps/workflows/src/cron/outbox.tsnew file mode 100644index 000000000..8e0d2b5fb--- /dev/null+++ b/apps/workflows/src/cron/outbox.ts@@ -0,0 +1,131 @@+import { getLogger } from "@logtape/logtape";+import { and, db, lt, sql } from "@openstatus/db";+import {+ monitorTransition,+ notificationOutbox,+ notificationTrigger,+} from "@openstatus/db/src/schema";+import { withBusyRetry } from "@openstatus/services";+import * as Sentry from "@sentry/deno";++import { drainUntilEmpty, sweepExpiredOutbox } from "../checker/outbox";++const logger = getLogger(["workflow"]);++const OUTBOX_RETENTION_DAYS = 45;+const DECISION_RETENTION_DAYS = 90;+const SHADOW_WINDOW_MS = 15 * 60 * 1000;++export async function handleOutboxDrainCron() {+ const summary = await drainUntilEmpty();+ const expired = await sweepExpiredOutbox();+ if (+ summary.claimed > 0 ||+ expired.deadLettered > 0 ||+ expired.discarded > 0+ ) {+ logger.info("Outbox safety-net drain", { ...summary, ...expired });+ }+ return { ...summary, ...expired };+}++export async function handleOutboxRetentionCron() {+ const nowSeconds = Math.floor(Date.now() / 1000);+ const outboxCutoff = nowSeconds - OUTBOX_RETENTION_DAYS * 24 * 60 * 60;+ const decisionCutoff = nowSeconds - DECISION_RETENTION_DAYS * 24 * 60 * 60;++ const [outboxDeleted, decisionsDeleted] = await withBusyRetry(() =>+ db.batch([+ // Pending rows older than the retention window are unreachable: the+ // delivery deadline is minutes, not weeks.+ db+ .delete(notificationOutbox)+ .where(lt(notificationOutbox.createdAt, outboxCutoff))+ .returning({ id: notificationOutbox.id }),+ db+ .delete(monitorTransition)+ .where(lt(monitorTransition.createdAt, decisionCutoff))+ .returning({ id: monitorTransition.id }),+ ]),+ );++ logger.info("Outbox retention", {+ outbox_deleted: outboxDeleted.length,+ decisions_deleted: decisionsDeleted.length,+ });++ return {+ outboxDeleted: outboxDeleted.length,+ decisionsDeleted: decisionsDeleted.length,+ };+}++/**+ * Shadow gate: while the inline sender still delivers, every outbox row must+ * have a matching notification_trigger and vice versa. A mismatch means the SQL+ * quorum and the TypeScript quorum disagree on real data.+ */+export async function handleOutboxShadowCron() {+ const since = Date.now() - SHADOW_WINDOW_MS;++ const missingTrigger = await withBusyRetry(() =>+ db+ .select({+ monitorId: notificationOutbox.monitorId,+ notificationId: notificationOutbox.notificationId,+ cronTimestamp: notificationOutbox.cronTimestamp,+ })+ .from(notificationOutbox)+ .where(+ and(+ sql`${notificationOutbox.cronTimestamp} >= ${since}`,+ sql`NOT EXISTS (+ SELECT 1 FROM ${notificationTrigger}+ WHERE ${notificationTrigger.monitorId} = ${notificationOutbox.monitorId}+ AND ${notificationTrigger.notificationId} = ${notificationOutbox.notificationId}+ AND ${notificationTrigger.cronTimestamp} = ${notificationOutbox.cronTimestamp})`,+ ),+ )+ .all(),+ );++ const missingOutbox = await withBusyRetry(() =>+ db+ .select({+ monitorId: notificationTrigger.monitorId,+ notificationId: notificationTrigger.notificationId,+ cronTimestamp: notificationTrigger.cronTimestamp,+ })+ .from(notificationTrigger)+ .where(+ and(+ sql`${notificationTrigger.cronTimestamp} >= ${since}`,+ sql`NOT EXISTS (+ SELECT 1 FROM ${notificationOutbox}+ WHERE ${notificationOutbox.monitorId} = ${notificationTrigger.monitorId}+ AND ${notificationOutbox.notificationId} = ${notificationTrigger.notificationId}+ AND ${notificationOutbox.cronTimestamp} = ${notificationTrigger.cronTimestamp})`,+ ),+ )+ .all(),+ );++ const result = {+ missingTrigger: missingTrigger.length,+ missingOutbox: missingOutbox.length,+ };++ if (missingTrigger.length > 0 || missingOutbox.length > 0) {+ logger.error("Outbox shadow mismatch", {+ ...result,+ sample_missing_trigger: missingTrigger.slice(0, 5),+ sample_missing_outbox: missingOutbox.slice(0, 5),+ });+ Sentry.captureMessage(+ `Outbox shadow mismatch: ${missingTrigger.length} outbox rows without a trigger, ${missingOutbox.length} triggers without an outbox row`,+ "error",+ );+ }++ return result;+}diff --git a/apps/workflows/src/cron/scheduler.test.ts b/apps/workflows/src/cron/scheduler.test.tsnew file mode 100644index 000000000..517e7c367--- /dev/null+++ b/apps/workflows/src/cron/scheduler.test.ts@@ -0,0 +1,18 @@+import { describe, expect, test } from "@openstatus/test-utils";+import { Cron, Result } from "effect";++import { SCHEDULED_TASKS } from "./scheduler";++describe("SCHEDULED_TASKS", () => {+ test("every expression parses", () => {+ for (const task of SCHEDULED_TASKS) {+ const parsed = Cron.parse(task.expression);+ expect(Result.isSuccess(parsed)).toBe(true);+ }+ });++ test("task names are unique", () => {+ const names = SCHEDULED_TASKS.map((task) => task.name);+ expect(new Set(names).size).toBe(names.length);+ });+});diff --git a/apps/workflows/src/cron/scheduler.ts b/apps/workflows/src/cron/scheduler.tsnew file mode 100644index 000000000..fe5414149--- /dev/null+++ b/apps/workflows/src/cron/scheduler.ts@@ -0,0 +1,95 @@+import { getLogger } from "@logtape/logtape";+import * as Sentry from "@sentry/deno";+import { Effect, Fiber, Schedule } from "effect";++import { handleOutboxDrainCron, handleOutboxRetentionCron } from "./outbox";+import { handleStatusDriftCron } from "./status-drift";++const logger = getLogger(["workflow"]);++type ScheduledTask = {+ name: string;+ expression: string;+ run: () => Promise<unknown>;+};++/**+ * Internal maintenance only, so it runs in-process rather than needing a+ * schedule added outside this repo. Every task is safe to run on both machines+ * at once: the outbox claim is atomic, drift repair is guarded by the same+ * compare-and-swap as a live check, and retention deletes are idempotent.+ */+export const SCHEDULED_TASKS: ScheduledTask[] = [+ {+ name: "outbox-drain",+ expression: "* * * * *",+ run: handleOutboxDrainCron,+ },+ {+ name: "status-drift",+ expression: "*/5 * * * *",+ run: handleStatusDriftCron,+ },+ {+ name: "outbox-retention",+ expression: "17 3 * * *",+ run: handleOutboxRetentionCron,+ },+];++type RunningTask = Fiber.Fiber<unknown, unknown>;++let running: RunningTask[] = [];++function scheduleTask(task: ScheduledTask): RunningTask {+ const body = Effect.tryPromise({+ try: () => task.run(),+ catch: (error) =>+ error instanceof Error ? error : new Error(String(error)),+ }).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ logger.error("Scheduled task failed", {+ task: task.name,+ error_message: error.message,+ });+ Sentry.captureException(error);+ }),+ ),+ );++ return Effect.runFork(+ Effect.repeat(body, Schedule.cron(task.expression)).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ logger.error("Scheduled task stopped", {+ task: task.name,+ error_message: String(error),+ });+ Sentry.captureException(+ new Error(`Scheduled task ${task.name} stopped: ${String(error)}`),+ );+ }),+ ),+ ),+ );+}++export function startScheduler(): void {+ if (running.length > 0) return;+ running = SCHEDULED_TASKS.map(scheduleTask);+ logger.info("Started in-process scheduler", {+ tasks: SCHEDULED_TASKS.map((task) => `${task.name}@${task.expression}`),+ });+}++export async function stopScheduler(): Promise<void> {+ const fibers = running;+ running = [];+ await Effect.runPromise(+ Effect.forEach(fibers, (fiber) => Fiber.interrupt(fiber), {+ concurrency: "unbounded",+ discard: true,+ }),+ );+}diff --git a/apps/workflows/src/cron/status-drift.test.ts b/apps/workflows/src/cron/status-drift.test.tsnew file mode 100644index 000000000..7a032fc40--- /dev/null+++ b/apps/workflows/src/cron/status-drift.test.ts@@ -0,0 +1,192 @@+import { and, count, db, eq, isNull } from "@openstatus/db";+import {+ notificationOutbox,+ incidentTable,+ monitor,+ monitorStatusTable,+} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createNotification,+ createTestWorkspace,+ linkNotificationToMonitor,+} from "@openstatus/db/src/test/factories";+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ type Stub,+ stub,+ test,+} from "@openstatus/test-utils";++import { applyStatusTransition } from "../checker/transition";+import { providerToFunction } from "../checker/utils";+import { checkerAudit } from "../utils/audit-log";+import { handleStatusDriftCron } from "./status-drift";++// biome-ignore lint/suspicious/noExplicitAny: heterogeneous provider stubs+type AnyStub = Stub<any>;+let stubs: AnyStub[] = [];+let workspaceId: number;++beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ workspaceId = workspace.id;+});++beforeEach(() => {+ stubs = [];+ stubs.push(+ stub(checkerAudit, "publishAuditLog", () => Promise.resolve()) as AnyStub,+ );+ stubs.push(+ stub(providerToFunction.email, "sendAlert", () => Promise.resolve()),+ );+});++afterEach(() => {+ for (const s of stubs) s.restore();+ stubs = [];+});++afterAll(async () => {+ await db.delete(monitor).where(eq(monitor.workspaceId, workspaceId)).run();+});++describe("handleStatusDriftCron", () => {+ test("re-evaluates a monitor whose region write landed without its transition", async () => {+ const monitorRow = await createMonitor(workspaceId, {+ regions: "ams",+ active: true,+ });+ const notif = await createNotification(workspaceId);+ await linkNotificationToMonitor(notif.id, monitorRow.id);++ // Exactly the state a crash between the region write and the batch leaves:+ // the region says error, the monitor still says active.+ await db+ .insert(monitorStatusTable)+ .values({+ monitorId: monitorRow.id,+ region: "ams",+ status: "error",+ cronTimestamp: Date.now(),+ })+ .run();++ // A replay of the same check cannot recover it: the region status is+ // unchanged, so the fast path short-circuits.+ const replay = await applyStatusTransition({+ monitorId: monitorRow.id,+ region: "ams",+ status: "error",+ cronTimestamp: Date.now() + 1000,+ deadlineSeconds: 300,+ rolloutPct: 100,+ });+ expect(replay.kind).toBe("unchanged");++ const beforeRepair = await db+ .select({ status: monitor.status })+ .from(monitor)+ .where(eq(monitor.id, monitorRow.id))+ .all();+ expect(beforeRepair[0]?.status).toBe("active");++ const result = await handleStatusDriftCron();+ expect(result.repaired).toBeGreaterThanOrEqual(1);++ const afterRepair = await db+ .select({ status: monitor.status })+ .from(monitor)+ .where(eq(monitor.id, monitorRow.id))+ .all();+ expect(afterRepair[0]?.status).toBe("error");++ const incidents = await db+ .select({ total: count() })+ .from(incidentTable)+ .where(+ and(+ eq(incidentTable.monitorId, monitorRow.id),+ isNull(incidentTable.resolvedAt),+ ),+ )+ .all();+ expect(incidents[0]?.total).toBe(1);++ const outbox = await db+ .select({ total: count() })+ .from(notificationOutbox)+ .where(eq(notificationOutbox.monitorId, monitorRow.id))+ .all();+ expect(outbox[0]?.total).toBe(1);+ });++ test("a monitor below quorum is not a drift candidate", async () => {+ const monitorRow = await createMonitor(workspaceId, {+ regions: "ams,arn,atl,bog",+ active: true,+ });++ await db+ .insert(monitorStatusTable)+ .values({+ monitorId: monitorRow.id,+ region: "ams",+ status: "error",+ cronTimestamp: Date.now(),+ })+ .run();++ await handleStatusDriftCron();++ const after = await db+ .select({ status: monitor.status })+ .from(monitor)+ .where(eq(monitor.id, monitorRow.id))+ .all();+ expect(after[0]?.status).toBe("active");+ });+});++describe("drift repair delivery", () => {+ test("sends the notification the repair is recovering", async () => {+ const sent: string[] = [];+ for (const s of stubs) s.restore();+ stubs = [+ stub(checkerAudit, "publishAuditLog", () => Promise.resolve()) as AnyStub,+ stub(providerToFunction.email, "sendAlert", () => {+ sent.push("alert");+ return Promise.resolve();+ }),+ ];++ const monitorRow = await createMonitor(workspaceId, {+ regions: "ams",+ active: true,+ });+ const notif = await createNotification(workspaceId);+ await linkNotificationToMonitor(notif.id, monitorRow.id);++ await db+ .insert(monitorStatusTable)+ .values({+ monitorId: monitorRow.id,+ region: "ams",+ status: "error",+ cronTimestamp: Date.now(),+ })+ .run();++ // OUTBOX_ROLLOUT_PCT defaults to 0, so the repair must fall back to the+ // inline sender rather than writing a row nobody delivers.+ const result = await handleStatusDriftCron();+ expect(result.repaired).toBeGreaterThanOrEqual(1);+ expect(sent.length).toBeGreaterThanOrEqual(1);+ });+});diff --git a/apps/workflows/src/cron/status-drift.ts b/apps/workflows/src/cron/status-drift.tsnew file mode 100644index 000000000..d936a55ee--- /dev/null+++ b/apps/workflows/src/cron/status-drift.ts@@ -0,0 +1,100 @@+import { getLogger } from "@logtape/logtape";+import { db, sql } from "@openstatus/db";+import type { MonitorStatus } from "@openstatus/db/src/schema";+import { monitor, monitorStatusTable } from "@openstatus/db/src/schema";+import { withBusyRetry } from "@openstatus/services";+import * as Sentry from "@sentry/deno";++import { triggerNotifications } from "../checker/alerting";+import { enqueueOutbox } from "../checker/outbox";+import {+ csvRegionCountSql,+ csvRegionMemberSql,+ quorumMetSql,+} from "../checker/quorum";+import { EVENT_TYPE, evaluateTransition } from "../checker/transition";+import { env } from "../env";++const logger = getLogger(["workflow"]);++const CANDIDATE_LIMIT = 200;++type DriftRow = { monitor_id: number; status: MonitorStatus };++/**+ * Finds monitors whose regions already carry a quorum for a status the monitor+ * itself does not have, using the same quorum rule as a live check.+ */+async function findDrift(): Promise<DriftRow[]> {+ return withBusyRetry(() =>+ db.all<DriftRow>(sql`+ SELECT ${monitorStatusTable.monitorId} AS monitor_id,+ ${monitorStatusTable.status} AS status+ FROM ${monitorStatusTable}+ JOIN ${monitor} ON ${monitor.id} = ${monitorStatusTable.monitorId}+ WHERE ${monitor.deletedAt} IS NULL+ AND ${monitor.active} = 1+ AND ${monitor.regions} <> ''+ AND ${monitorStatusTable.status} <> ${monitor.status}+ AND ${csvRegionMemberSql(sql`${monitorStatusTable.region}`)}+ GROUP BY ${monitorStatusTable.monitorId}, ${monitorStatusTable.status}+ HAVING ${quorumMetSql(sql`count(*)`, csvRegionCountSql())}+ LIMIT ${CANDIDATE_LIMIT}+ `),+ );+}++/**+ * Safety net for the gap between the region write and the transition batch:+ * they are separate transactions, so a crash or a failed batch can leave a+ * monitor whose regions say "down" but whose status still says "up", which no+ * later check will re-evaluate because the region status stopped changing.+ */+export async function handleStatusDriftCron() {+ const candidates = await findDrift();+ if (candidates.length === 0) return { candidates: 0, repaired: 0 };++ let repaired = 0;++ for (const candidate of candidates) {+ const result = await evaluateTransition({+ monitorId: candidate.monitor_id,+ region: "drift-repair",+ status: candidate.status,+ cronTimestamp: Date.now(),+ deadlineSeconds: Math.floor(env().OUTBOX_DEADLINE_MS / 1000),+ rolloutPct: env().OUTBOX_ROLLOUT_PCT,+ });++ if (result.kind !== "evaluated" || !result.transitioned) continue;++ repaired += 1;+ logger.warn("Repaired monitor status drift", {+ monitor_id: candidate.monitor_id,+ status: candidate.status,+ outbox_rows: result.outboxRows.length,+ });++ // A repair that does not deliver is the failure it exists to fix.+ if (result.outboxRows.some((row) => row.deliveryStatus === "pending")) {+ enqueueOutbox(result.outboxRows.map((row) => row.id));+ } else if (result.outboxRows.length > 0) {+ await triggerNotifications({+ monitorId: String(candidate.monitor_id),+ notifType: EVENT_TYPE[candidate.status],+ cronTimestamp: Date.now(),+ regions: result.affectedRegions,+ incidentId: result.incidentId ?? undefined,+ });+ }+ }++ if (repaired > 0) {+ Sentry.captureMessage(+ `Repaired ${repaired} monitor(s) whose status had drifted from their region quorum`,+ "warning",+ );+ }++ return { candidates: candidates.length, repaired };+}diff --git a/apps/workflows/src/env.ts b/apps/workflows/src/env.tsindex 42e57785c..f245135d2 100644--- a/apps/workflows/src/env.ts+++ b/apps/workflows/src/env.ts@@ -24,5 +24,9 @@ export const env = () =>SENTRY_DSN: z.string().prefault(""),AXIOM_TOKEN: z.string().prefault(""),AXIOM_DATASET: z.string().prefault(""),+ STALE_CHECK_MS: z.coerce.number().prefault(600_000),+ OUTBOX_DEADLINE_MS: z.coerce.number().prefault(300_000),+ NOTIFICATION_TIMEOUT_MS: z.coerce.number().prefault(10_000),+ OUTBOX_ROLLOUT_PCT: z.coerce.number().min(0).max(100).prefault(0),}).parse(process.env);diff --git a/apps/workflows/src/scripts/outbox-preflight.ts b/apps/workflows/src/scripts/outbox-preflight.tsnew file mode 100644index 000000000..8656537a0--- /dev/null+++ b/apps/workflows/src/scripts/outbox-preflight.ts@@ -0,0 +1,185 @@+import {+ and,+ count,+ db,+ eq,+ gte,+ inArray,+ isNotNull,+ isNull,+ sql,+} from "@openstatus/db";+import {+ incidentTable,+ monitor,+ notification,+ notificationTrigger,+ notificationsToMonitors,+ selectWorkspaceSchema,+ workspace,+} from "@openstatus/db/src/schema";++const CHECKS_PER_REGION_PER_DAY: Record<string, number> = {+ "30s": 2880,+ "1m": 1440,+ "5m": 288,+ "10m": 144,+ "30m": 48,+ "1h": 24,+ other: 0,+};++const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;++async function duplicateOpenIncidents() {+ const rows = await db+ .select({+ monitorId: incidentTable.monitorId,+ openCount: count(incidentTable.id),+ })+ .from(incidentTable)+ // NULLs are distinct in a SQLite unique index, so incidents with no monitor+ // can never collide with incident_open_idx however many are open.+ .where(+ and(isNull(incidentTable.resolvedAt), isNotNull(incidentTable.monitorId)),+ )+ .groupBy(incidentTable.monitorId)+ .having(sql`count(${incidentTable.id}) > 1`)+ .all();++ console.log(+ `\n[1] Monitors with more than one open incident: ${rows.length}`,+ );+ for (const row of rows) {+ console.log(` monitor ${row.monitorId}: ${row.openCount} open`);+ }+ if (rows.length > 0) {+ console.log(+ " -> migration 0085 will FAIL until these are resolved (unique incident_open_idx)",+ );+ }+}++async function smsQuotaBlastRadius() {+ const smsNotifications = await db+ .select({ id: notification.id, workspaceId: notification.workspaceId })+ .from(notification)+ .where(eq(notification.provider, "sms"))+ .all();++ const byWorkspace = new Map<number, number[]>();+ for (const row of smsNotifications) {+ if (row.workspaceId === null) continue;+ const ids = byWorkspace.get(row.workspaceId) ?? [];+ ids.push(row.id);+ byWorkspace.set(row.workspaceId, ids);+ }++ console.log(`\n[2] Workspaces with SMS notifications: ${byWorkspace.size}`);++ const cutoffMs = Date.now() - THIRTY_DAYS_MS;+ let blocked = 0;++ for (const [workspaceId, notificationIds] of byWorkspace) {+ const rows = await db+ .select()+ .from(workspace)+ .where(eq(workspace.id, workspaceId))+ .all();+ const parsed = selectWorkspaceSchema.safeParse(rows[0]);+ if (!parsed.success) continue;+ const limit = parsed.data.limits["sms-limit"];++ const allTime = await db+ .select({ total: count() })+ .from(notificationTrigger)+ .where(inArray(notificationTrigger.notificationId, notificationIds))+ .all();++ const lastMonth = await db+ .select({ total: count() })+ .from(notificationTrigger)+ .where(+ and(+ inArray(notificationTrigger.notificationId, notificationIds),+ gte(notificationTrigger.cronTimestamp, cutoffMs),+ ),+ )+ .all();++ const allTimeCount = allTime[0]?.total ?? 0;+ const lastMonthCount = lastMonth[0]?.total ?? 0;++ if (allTimeCount > limit && lastMonthCount <= limit) {+ blocked += 1;+ console.log(+ ` workspace ${workspaceId}: limit ${limit}, all-time ${allTimeCount}, real 30d ${lastMonthCount} -> UNBLOCKS on fix`,+ );+ }+ }++ console.log(+ ` -> ${blocked} workspace(s) currently blocked by the ms/s bug and will resume sending SMS`,+ );+}++async function writeVolumeBaseline() {+ const monitors = await db+ .select({+ id: monitor.id,+ regions: monitor.regions,+ periodicity: monitor.periodicity,+ })+ .from(monitor)+ .where(eq(monitor.active, true))+ .all();++ let checksPerDay = 0;+ for (const row of monitors) {+ const regionCount = row.regions.split(",").filter(Boolean).length;+ checksPerDay +=+ regionCount * (CHECKS_PER_REGION_PER_DAY[row.periodicity] ?? 0);+ }++ console.log(`\n[3] Active monitors: ${monitors.length}`);+ console.log(` Checks per day: ${checksPerDay.toLocaleString()}`);+ console.log(+ ` Current monitor_status writes per day: ${checksPerDay.toLocaleString()} (one per check)`,+ );+ console.log(+ ` After the conditional upsert these become zero-row statements.`,+ );+}++async function averageChannelsPerMonitor() {+ const rows = await db+ .select({+ links: count(notificationsToMonitors.notificationId),+ monitors: sql<number>`count(distinct ${notificationsToMonitors.monitorId})`,+ })+ .from(notificationsToMonitors)+ .all();++ const links = rows[0]?.links ?? 0;+ const monitors = rows[0]?.monitors ?? 0;+ const average = monitors === 0 ? 0 : links / monitors;++ console.log(`\n[4] Notification links: ${links} across ${monitors} monitors`);+ console.log(+ ` C (avg channels per notified monitor): ${average.toFixed(2)}`,+ );+ console.log(+ ` Writes per transition (4C + 4): ${(4 * average + 4).toFixed(1)} rows`,+ );+}++async function main() {+ console.log("checker outbox preflight");+ await duplicateOpenIncidents();+ await smsQuotaBlastRadius();+ await writeVolumeBaseline();+ await averageChannelsPerMonitor();+ console.log("");+}++await main();diff --git a/apps/workflows/src/serve.ts b/apps/workflows/src/serve.tsindex 6f5205629..12c5df1ea 100644--- a/apps/workflows/src/serve.ts+++ b/apps/workflows/src/serve.ts@@ -2,14 +2,30 @@import { getLogger } from "@logtape/logtape";+import { shutdownOutbox, startOutboxConsumer } from "./checker/outbox";+import { startScheduler, stopScheduler } from "./cron/scheduler";import { env } from "./env";import { app } from "./index";const { NODE_ENV, PORT } = env();-getLogger(["workflow"]).info("Starting server", {+const logger = getLogger(["workflow"]);++logger.info("Starting server", {port: PORT,environment: NODE_ENV,});-Deno.serve({ port: PORT }, app.fetch);+startOutboxConsumer();+startScheduler();++const server = Deno.serve({ port: PORT }, app.fetch);++Deno.addSignalListener("SIGTERM", () => {+ void (async () => {+ logger.info("SIGTERM received, releasing outbox claims");+ await stopScheduler();+ await shutdownOutbox();+ await server.shutdown();+ })();+});diff --git a/packages/db/drizzle/0085_daily_glorian.sql b/packages/db/drizzle/0085_daily_glorian.sqlnew file mode 100644index 000000000..1c31471e1--- /dev/null+++ b/packages/db/drizzle/0085_daily_glorian.sql@@ -0,0 +1,100 @@+CREATE TABLE `notification_dead_letter` (+ `id` integer PRIMARY KEY NOT NULL,+ `outbox_id` integer NOT NULL,+ `dedup_key` text NOT NULL,+ `monitor_id` integer NOT NULL,+ `workspace_id` integer,+ `notification_id` integer NOT NULL,+ `provider` text NOT NULL,+ `event_type` text NOT NULL,+ `from_status` text NOT NULL,+ `to_status` text NOT NULL,+ `cron_timestamp` integer NOT NULL,+ `incident_id` integer,+ `payload` text NOT NULL,+ `attempts` integer NOT NULL,+ `final_error` text,+ `died_at` integer NOT NULL,+ FOREIGN KEY (`monitor_id`) REFERENCES `monitor`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE no action+);+--> statement-breakpoint+CREATE UNIQUE INDEX `notification_dead_letter_dedup_key_idx` ON `notification_dead_letter` (`dedup_key`);--> statement-breakpoint+CREATE INDEX `notification_dead_letter_workspace_id_died_at_idx` ON `notification_dead_letter` (`workspace_id`,`died_at`);--> statement-breakpoint+CREATE TABLE `notification_outbox` (+ `id` integer PRIMARY KEY NOT NULL,+ `dedup_key` text NOT NULL,+ `monitor_id` integer NOT NULL,+ `workspace_id` integer,+ `notification_id` integer NOT NULL,+ `provider` text NOT NULL,+ `event_type` text NOT NULL,+ `from_status` text NOT NULL,+ `to_status` text NOT NULL,+ `cron_timestamp` integer NOT NULL,+ `incident_id` integer,+ `payload` text NOT NULL,+ `delivery_status` text DEFAULT 'pending' NOT NULL,+ `outcome` text,+ `attempts` integer DEFAULT 0 NOT NULL,+ `next_attempt_at` integer NOT NULL,+ `deadline_at` integer NOT NULL,+ `locked_by` text,+ `locked_until` integer,+ `delivered_at` integer,+ `last_error` text,+ `created_at` integer NOT NULL,+ FOREIGN KEY (`monitor_id`) REFERENCES `monitor`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE no action,+ FOREIGN KEY (`notification_id`) REFERENCES `notification`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`incident_id`) REFERENCES `incident`(`id`) ON UPDATE no action ON DELETE set null+);+--> statement-breakpoint+CREATE UNIQUE INDEX `notification_outbox_dedup_key_idx` ON `notification_outbox` (`dedup_key`);--> statement-breakpoint+CREATE INDEX `notification_outbox_claim_idx` ON `notification_outbox` (`next_attempt_at`) WHERE "notification_outbox"."delivery_status" = 'pending';--> statement-breakpoint+CREATE INDEX `notification_outbox_notification_id_cron_timestamp_idx` ON `notification_outbox` (`notification_id`,`cron_timestamp`);--> statement-breakpoint+CREATE INDEX `notification_outbox_channel_idx` ON `notification_outbox` (`monitor_id`,`notification_id`) WHERE "notification_outbox"."delivery_status" = 'pending';--> statement-breakpoint+CREATE TABLE `monitor_transition` (+ `id` integer PRIMARY KEY NOT NULL,+ `monitor_id` integer NOT NULL,+ `region` text NOT NULL,+ `cron_timestamp` integer NOT NULL,+ `from_status` text NOT NULL,+ `to_status` text NOT NULL,+ `quorum_count` integer NOT NULL,+ `region_count` integer NOT NULL,+ `transitioned` integer NOT NULL,+ `outbox_rows` integer DEFAULT 0 NOT NULL,+ `created_at` integer NOT NULL,+ FOREIGN KEY (`monitor_id`) REFERENCES `monitor`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `monitor_transition_monitor_id_cron_timestamp_idx` ON `monitor_transition` (`monitor_id`,`cron_timestamp`);--> statement-breakpoint+CREATE INDEX `monitor_transition_created_at_idx` ON `monitor_transition` (`created_at`);--> statement-breakpoint+-- The check-then-act race in createIncident left monitors with several open+-- incidents, which the partial unique index below would reject. Keep the newest+-- open incident per monitor and resolve the ones it superseded, at the keeper's+-- start (never before their own). The keeper set is an uncorrelated subquery, so+-- it is materialised once and does not shift as rows are resolved.+UPDATE `incident`+SET `resolved_at` = max(+ `started_at`,+ coalesce(+ (SELECT k.`started_at`+ FROM `incident` k+ WHERE k.`monitor_id` = `incident`.`monitor_id`+ AND k.`id` IN (SELECT max(x.`id`) FROM `incident` x+ WHERE x.`resolved_at` IS NULL+ AND x.`monitor_id` IS NOT NULL+ GROUP BY x.`monitor_id`)),+ `started_at`)),+ `auto_resolved` = 1+WHERE `resolved_at` IS NULL+ AND `monitor_id` IS NOT NULL+ AND `id` NOT IN (SELECT max(x.`id`) FROM `incident` x+ WHERE x.`resolved_at` IS NULL+ AND x.`monitor_id` IS NOT NULL+ GROUP BY x.`monitor_id`);--> statement-breakpoint+DROP INDEX `incident_open_idx`;--> statement-breakpoint+CREATE UNIQUE INDEX `incident_open_idx` ON `incident` (`monitor_id`) WHERE "incident"."resolved_at" IS NULL;--> statement-breakpoint+ALTER TABLE `monitor_status` ADD `cron_timestamp` integer DEFAULT 0 NOT NULL;\ No newline at end of filediff --git a/packages/db/drizzle/meta/0085_snapshot.json b/packages/db/drizzle/meta/0085_snapshot.jsonnew file mode 100644index 000000000..ab1b795d9--- /dev/null+++ b/packages/db/drizzle/meta/0085_snapshot.json@@ -0,0 +1,5519 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "10787b50-ac75-4913-ba21-f3d2da7acc6e",+ "prevId": "b39ead3f-410d-45d6-8d9d-b169d00d0039",+ "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": "'{}'"+ },+ "workos_organization_id": {+ "name": "workos_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sso_enabled": {+ "name": "sso_enabled",+ "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'))"+ },+ "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_workos_organization_id_unique": {+ "name": "workspace_workos_organization_id_unique",+ "columns": [+ "workos_organization_id"+ ],+ "isUnique": true+ },+ "workspace_id_dsn_unique": {+ "name": "workspace_id_dsn_unique",+ "columns": [+ "id",+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "workspace_sso_domain": {+ "name": "workspace_sso_domain",+ "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+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "verified_at": {+ "name": "verified_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": {+ "workspace_sso_domain_domain_unique": {+ "name": "workspace_sso_domain_domain_unique",+ "columns": [+ "domain"+ ],+ "isUnique": true+ },+ "workspace_sso_domain_workspace_id_idx": {+ "name": "workspace_sso_domain_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "workspace_sso_domain_workspace_id_workspace_id_fk": {+ "name": "workspace_sso_domain_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_sso_domain",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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": {+ "session_user_id_idx": {+ "name": "session_user_id_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "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+ },+ "user_email_idx": {+ "name": "user_email_idx",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "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'"+ },+ "custom_theme": {+ "name": "custom_theme",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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+ },+ "grpc_service": {+ "name": "grpc_service",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "grpc_tls": {+ "name": "grpc_tls",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'tls'"+ },+ "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+ },+ "slack_channel_id": {+ "name": "slack_channel_id",+ "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": {+ "page_subscriber_page_id_idx": {+ "name": "page_subscriber_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "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'"+ },+ "idx_page_subscriber_slack_channel_page_active": {+ "name": "idx_page_subscriber_slack_channel_page_active",+ "columns": [+ "slack_channel_id",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'slack'"+ }+ },+ "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) OR (\"page_subscriber\".\"channel_type\" = 'slack' AND \"page_subscriber\".\"slack_channel_id\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL AND \"page_subscriber\".\"webhook_url\" 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": {}+ },+ "notification_dead_letter": {+ "name": "notification_dead_letter",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "outbox_id": {+ "name": "outbox_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dedup_key": {+ "name": "dedup_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from_status": {+ "name": "from_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to_status": {+ "name": "to_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "final_error": {+ "name": "final_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "died_at": {+ "name": "died_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_dead_letter_dedup_key_idx": {+ "name": "notification_dead_letter_dedup_key_idx",+ "columns": [+ "dedup_key"+ ],+ "isUnique": true+ },+ "notification_dead_letter_workspace_id_died_at_idx": {+ "name": "notification_dead_letter_workspace_id_died_at_idx",+ "columns": [+ "workspace_id",+ "died_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "notification_dead_letter_monitor_id_monitor_id_fk": {+ "name": "notification_dead_letter_monitor_id_monitor_id_fk",+ "tableFrom": "notification_dead_letter",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_dead_letter_workspace_id_workspace_id_fk": {+ "name": "notification_dead_letter_workspace_id_workspace_id_fk",+ "tableFrom": "notification_dead_letter",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification_outbox": {+ "name": "notification_outbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "dedup_key": {+ "name": "dedup_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from_status": {+ "name": "from_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to_status": {+ "name": "to_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "delivery_status": {+ "name": "delivery_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "deadline_at": {+ "name": "deadline_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_by": {+ "name": "locked_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "locked_until": {+ "name": "locked_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_outbox_dedup_key_idx": {+ "name": "notification_outbox_dedup_key_idx",+ "columns": [+ "dedup_key"+ ],+ "isUnique": true+ },+ "notification_outbox_claim_idx": {+ "name": "notification_outbox_claim_idx",+ "columns": [+ "next_attempt_at"+ ],+ "isUnique": false,+ "where": "\"notification_outbox\".\"delivery_status\" = 'pending'"+ },+ "notification_outbox_notification_id_cron_timestamp_idx": {+ "name": "notification_outbox_notification_id_cron_timestamp_idx",+ "columns": [+ "notification_id",+ "cron_timestamp"+ ],+ "isUnique": false+ },+ "notification_outbox_channel_idx": {+ "name": "notification_outbox_channel_idx",+ "columns": [+ "monitor_id",+ "notification_id"+ ],+ "isUnique": false,+ "where": "\"notification_outbox\".\"delivery_status\" = 'pending'"+ }+ },+ "foreignKeys": {+ "notification_outbox_monitor_id_monitor_id_fk": {+ "name": "notification_outbox_monitor_id_monitor_id_fk",+ "tableFrom": "notification_outbox",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_outbox_workspace_id_workspace_id_fk": {+ "name": "notification_outbox_workspace_id_workspace_id_fk",+ "tableFrom": "notification_outbox",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "notification_outbox_notification_id_notification_id_fk": {+ "name": "notification_outbox_notification_id_notification_id_fk",+ "tableFrom": "notification_outbox",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_outbox_incident_id_incident_id_fk": {+ "name": "notification_outbox_incident_id_incident_id_fk",+ "tableFrom": "notification_outbox",+ "tableTo": "incident",+ "columnsFrom": [+ "incident_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "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'"+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "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": {+ "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_started_at_idx": {+ "name": "incident_workspace_id_started_at_idx",+ "columns": [+ "workspace_id",+ "started_at"+ ],+ "isUnique": false+ },+ "incident_open_idx": {+ "name": "incident_open_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": true,+ "where": "\"incident\".\"resolved_at\" IS NULL"+ },+ "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_created_at_idx": {+ "name": "monitor_run_workspace_id_created_at_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "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_monitor_status": {+ "name": "private_location_monitor_status",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "private_location_id": {+ "name": "private_location_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "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": {+ "private_location_monitor_status_pl_id_idx": {+ "name": "private_location_monitor_status_pl_id_idx",+ "columns": [+ "private_location_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "private_location_monitor_status_monitor_id_monitor_id_fk": {+ "name": "private_location_monitor_status_monitor_id_monitor_id_fk",+ "tableFrom": "private_location_monitor_status",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "private_location_monitor_status_private_location_id_private_location_id_fk": {+ "name": "private_location_monitor_status_private_location_id_private_location_id_fk",+ "tableFrom": "private_location_monitor_status",+ "tableTo": "private_location",+ "columnsFrom": [+ "private_location_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "private_location_monitor_status_monitor_id_private_location_id_pk": {+ "columns": [+ "monitor_id",+ "private_location_id"+ ],+ "name": "private_location_monitor_status_monitor_id_private_location_id_pk"+ }+ },+ "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+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'error'"+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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_update_to_page_component": {+ "name": "status_report_update_to_page_component",+ "columns": {+ "status_report_update_id": {+ "name": "status_report_update_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impact": {+ "name": "impact",+ "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'))"+ }+ },+ "indexes": {+ "status_report_update_to_page_component_page_component_id_idx": {+ "name": "status_report_update_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_update_to_page_component_status_report_update_id_status_report_update_id_fk": {+ "name": "status_report_update_to_page_component_status_report_update_id_status_report_update_id_fk",+ "tableFrom": "status_report_update_to_page_component",+ "tableTo": "status_report_update",+ "columnsFrom": [+ "status_report_update_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_report_update_to_page_component_page_component_id_page_component_id_fk": {+ "name": "status_report_update_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "status_report_update_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_report_update_to_page_component_status_report_update_id_page_component_id_pk": {+ "columns": [+ "status_report_update_id",+ "page_component_id"+ ],+ "name": "status_report_update_to_page_component_status_report_update_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "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'))"+ },+ "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+ }+ },+ "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": "'[]'"+ },+ "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'))"+ },+ "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": {}+ },+ "external_service_report": {+ "name": "external_service_report",+ "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+ },+ "external_service_component_id": {+ "name": "external_service_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reporter_hash": {+ "name": "reporter_hash",+ "type": "text(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "country": {+ "name": "country",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "external_service_report_service_idx": {+ "name": "external_service_report_service_idx",+ "columns": [+ "external_service_id",+ "created_at"+ ],+ "isUnique": false+ },+ "external_service_report_component_idx": {+ "name": "external_service_report_component_idx",+ "columns": [+ "external_service_component_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "external_service_report_external_service_id_external_service_id_fk": {+ "name": "external_service_report_external_service_id_external_service_id_fk",+ "tableFrom": "external_service_report",+ "tableTo": "external_service",+ "columnsFrom": [+ "external_service_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "external_service_report_external_service_component_id_external_service_component_id_fk": {+ "name": "external_service_report_external_service_component_id_external_service_component_id_fk",+ "tableFrom": "external_service_report",+ "tableTo": "external_service_component",+ "columnsFrom": [+ "external_service_component_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": {}+ },+ "frozen_monitor_uptime": {+ "name": "frozen_monitor_uptime",+ "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+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "month": {+ "name": "month",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "days": {+ "name": "days",+ "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'))"+ }+ },+ "indexes": {+ "frozen_monitor_uptime_workspace_id_idx": {+ "name": "frozen_monitor_uptime_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "frozen_monitor_uptime_monitor_id_month_unique": {+ "name": "frozen_monitor_uptime_monitor_id_month_unique",+ "columns": [+ "monitor_id",+ "month"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "frozen_monitor_uptime_workspace_id_workspace_id_fk": {+ "name": "frozen_monitor_uptime_workspace_id_workspace_id_fk",+ "tableFrom": "frozen_monitor_uptime",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "frozen_monitor_uptime_monitor_id_monitor_id_fk": {+ "name": "frozen_monitor_uptime_monitor_id_monitor_id_fk",+ "tableFrom": "frozen_monitor_uptime",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_transition": {+ "name": "monitor_transition",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from_status": {+ "name": "from_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to_status": {+ "name": "to_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "quorum_count": {+ "name": "quorum_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region_count": {+ "name": "region_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transitioned": {+ "name": "transitioned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "outbox_rows": {+ "name": "outbox_rows",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "monitor_transition_monitor_id_cron_timestamp_idx": {+ "name": "monitor_transition_monitor_id_cron_timestamp_idx",+ "columns": [+ "monitor_id",+ "cron_timestamp"+ ],+ "isUnique": false+ },+ "monitor_transition_created_at_idx": {+ "name": "monitor_transition_created_at_idx",+ "columns": [+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_transition_monitor_id_monitor_id_fk": {+ "name": "monitor_transition_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_transition",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_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 02b53c507..54eb81185 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -596,6 +596,13 @@"when": 1787773726456,"tag": "0084_flaky_thundra","breakpoints": true+ },+ {+ "idx": 85,+ "version": "6",+ "when": 1788374582005,+ "tag": "0085_daily_glorian",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/incidents/incident.ts b/packages/db/src/schema/incidents/incident.tsindex 9823274cf..d15204253 100644--- a/packages/db/src/schema/incidents/incident.ts+++ b/packages/db/src/schema/incidents/incident.ts@@ -5,6 +5,7 @@ import {sqliteTable,text,unique,+ uniqueIndex,} from "drizzle-orm/sqlite-core";import { monitor } from "../monitors";@@ -68,8 +69,8 @@ export const incidentTable = sqliteTable(table.startedAt,),// Partial: open incidents are looked up on every check result, every region,- // every minute. Keeps that b-tree small enough to stay hot.- index("incident_open_idx")+ // every minute. Unique so a monitor cannot hold two open incidents at once.+ uniqueIndex("incident_open_idx").on(table.monitorId).where(sql`${table.resolvedAt} IS NULL`),],diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex ddc5bece5..7dd0664a3 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -26,3 +26,4 @@ export * from "./audit_logs";export * from "./external_services";export * from "./chat_sessions";export * from "./frozen_uptime";+export * from "./monitor_transition";diff --git a/packages/db/src/schema/monitor_status/monitor_status.ts b/packages/db/src/schema/monitor_status/monitor_status.tsindex 7690d6148..25f3dc7ca 100644--- a/packages/db/src/schema/monitor_status/monitor_status.ts+++ b/packages/db/src/schema/monitor_status/monitor_status.ts@@ -19,6 +19,7 @@ export const monitorStatusTable = sqliteTable(status: text("status", { enum: monitorStatusEnum }).default("active").notNull(),+ cronTimestamp: integer("cron_timestamp").notNull().default(0),createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(strftime('%s', 'now'))`,diff --git a/packages/db/src/schema/monitor_transition/index.ts b/packages/db/src/schema/monitor_transition/index.tsnew file mode 100644index 000000000..615e01bec--- /dev/null+++ b/packages/db/src/schema/monitor_transition/index.ts@@ -0,0 +1,3 @@+export * from "./monitor_transition";+export * from "./validation";+export type * from "./validation";diff --git a/packages/db/src/schema/monitor_transition/monitor_transition.ts b/packages/db/src/schema/monitor_transition/monitor_transition.tsnew file mode 100644index 000000000..902c9dccc--- /dev/null+++ b/packages/db/src/schema/monitor_transition/monitor_transition.ts@@ -0,0 +1,41 @@+import { relations } from "drizzle-orm";+import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";++import { monitorStatus } from "../monitors/constants";+import { monitor } from "../monitors/monitor";++export const monitorTransition = sqliteTable(+ "monitor_transition",+ {+ id: integer("id").primaryKey(),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => monitor.id, { onDelete: "cascade" }),+ region: text("region").notNull(),+ cronTimestamp: integer("cron_timestamp").notNull(),+ fromStatus: text("from_status", { enum: monitorStatus }).notNull(),+ toStatus: text("to_status", { enum: monitorStatus }).notNull(),+ quorumCount: integer("quorum_count").notNull(),+ regionCount: integer("region_count").notNull(),+ transitioned: integer("transitioned", { mode: "boolean" }).notNull(),+ outboxRows: integer("outbox_rows").default(0).notNull(),+ createdAt: integer("created_at").notNull(),+ },+ (t) => [+ index("monitor_transition_monitor_id_cron_timestamp_idx").on(+ t.monitorId,+ t.cronTimestamp,+ ),+ index("monitor_transition_created_at_idx").on(t.createdAt),+ ],+);++export const monitorTransitionRelations = relations(+ monitorTransition,+ ({ one }) => ({+ monitor: one(monitor, {+ fields: [monitorTransition.monitorId],+ references: [monitor.id],+ }),+ }),+);diff --git a/packages/db/src/schema/monitor_transition/validation.ts b/packages/db/src/schema/monitor_transition/validation.tsnew file mode 100644index 000000000..df06661a7--- /dev/null+++ b/packages/db/src/schema/monitor_transition/validation.ts@@ -0,0 +1,8 @@+import { createSelectSchema } from "drizzle-zod";++import { monitorTransition } from "./monitor_transition";++export const selectMonitorTransitionSchema =+ createSelectSchema(monitorTransition);++export type MonitorTransitionRow = typeof monitorTransition.$inferSelect;diff --git a/packages/db/src/schema/notifications/index.ts b/packages/db/src/schema/notifications/index.tsindex fadeb49ae..2a8d29cbd 100644--- a/packages/db/src/schema/notifications/index.ts+++ b/packages/db/src/schema/notifications/index.ts@@ -1,4 +1,5 @@export * from "./constants";export * from "./notification";+export * from "./outbox";export * from "./validation";export type * from "./validation";diff --git a/packages/db/src/schema/notifications/outbox.ts b/packages/db/src/schema/notifications/outbox.tsnew file mode 100644index 000000000..36e242430--- /dev/null+++ b/packages/db/src/schema/notifications/outbox.ts@@ -0,0 +1,142 @@+import { relations, sql } from "drizzle-orm";+import {+ index,+ integer,+ sqliteTable,+ text,+ uniqueIndex,+} from "drizzle-orm/sqlite-core";++import { incidentTable } from "../incidents/incident";+import { monitorStatus } from "../monitors/constants";+import { monitor } from "../monitors/monitor";+import { workspace } from "../workspaces/workspace";+import { notificationProvider } from "./constants";+import { notification } from "./notification";+import type { NotificationOutboxPayload } from "./validation";++export const notificationOutboxEventType = [+ "alert",+ "recovery",+ "degraded",+] as const;++export const notificationOutboxDeliveryStatus = ["pending", "settled"] as const;++/**+ * How a settled row ended: delivered by the drainer, deliberately skipped, or+ * never ours because the inline sender owned the monitor at write time.+ */+export const notificationOutboxOutcome = [+ "delivered",+ "skipped",+ "inline",+] as const;++export const notificationOutbox = sqliteTable(+ "notification_outbox",+ {+ id: integer("id").primaryKey(),+ dedupKey: text("dedup_key").notNull(),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => monitor.id, { onDelete: "cascade" }),+ workspaceId: integer("workspace_id").references(() => workspace.id),+ notificationId: integer("notification_id")+ .notNull()+ .references(() => notification.id, { onDelete: "cascade" }),+ provider: text("provider", { enum: notificationProvider }).notNull(),+ eventType: text("event_type", {+ enum: notificationOutboxEventType,+ }).notNull(),+ fromStatus: text("from_status", { enum: monitorStatus }).notNull(),+ toStatus: text("to_status", { enum: monitorStatus }).notNull(),+ cronTimestamp: integer("cron_timestamp").notNull(),+ incidentId: integer("incident_id").references(() => incidentTable.id, {+ onDelete: "set null",+ }),+ payload: text("payload", { mode: "json" })+ .$type<NotificationOutboxPayload>()+ .notNull(),+ deliveryStatus: text("delivery_status", {+ enum: notificationOutboxDeliveryStatus,+ })+ .default("pending")+ .notNull(),+ outcome: text("outcome", { enum: notificationOutboxOutcome }),+ attempts: integer("attempts").default(0).notNull(),+ nextAttemptAt: integer("next_attempt_at").notNull(),+ deadlineAt: integer("deadline_at").notNull(),+ lockedBy: text("locked_by"),+ lockedUntil: integer("locked_until"),+ deliveredAt: integer("delivered_at"),+ lastError: text("last_error"),+ createdAt: integer("created_at").notNull(),+ },+ (t) => [+ uniqueIndex("notification_outbox_dedup_key_idx").on(t.dedupKey),+ index("notification_outbox_claim_idx")+ .on(t.nextAttemptAt)+ .where(sql`${t.deliveryStatus} = 'pending'`),+ index("notification_outbox_notification_id_cron_timestamp_idx").on(+ t.notificationId,+ t.cronTimestamp,+ ),+ index("notification_outbox_channel_idx")+ .on(t.monitorId, t.notificationId)+ .where(sql`${t.deliveryStatus} = 'pending'`),+ ],+);++export const notificationDeadLetter = sqliteTable(+ "notification_dead_letter",+ {+ id: integer("id").primaryKey(),+ outboxId: integer("outbox_id").notNull(),+ dedupKey: text("dedup_key").notNull(),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => monitor.id, { onDelete: "cascade" }),+ workspaceId: integer("workspace_id").references(() => workspace.id),+ notificationId: integer("notification_id").notNull(),+ provider: text("provider", { enum: notificationProvider }).notNull(),+ eventType: text("event_type", {+ enum: notificationOutboxEventType,+ }).notNull(),+ fromStatus: text("from_status", { enum: monitorStatus }).notNull(),+ toStatus: text("to_status", { enum: monitorStatus }).notNull(),+ cronTimestamp: integer("cron_timestamp").notNull(),+ incidentId: integer("incident_id"),+ payload: text("payload", { mode: "json" })+ .$type<NotificationOutboxPayload>()+ .notNull(),+ attempts: integer("attempts").notNull(),+ finalError: text("final_error"),+ diedAt: integer("died_at").notNull(),+ },+ (t) => [+ uniqueIndex("notification_dead_letter_dedup_key_idx").on(t.dedupKey),+ index("notification_dead_letter_workspace_id_died_at_idx").on(+ t.workspaceId,+ t.diedAt,+ ),+ ],+);++export const notificationOutboxRelations = relations(+ notificationOutbox,+ ({ one }) => ({+ monitor: one(monitor, {+ fields: [notificationOutbox.monitorId],+ references: [monitor.id],+ }),+ notification: one(notification, {+ fields: [notificationOutbox.notificationId],+ references: [notification.id],+ }),+ incident: one(incidentTable, {+ fields: [notificationOutbox.incidentId],+ references: [incidentTable.id],+ }),+ }),+);diff --git a/packages/db/src/schema/notifications/validation.ts b/packages/db/src/schema/notifications/validation.tsindex 3095acf76..7e67d0e6f 100644--- a/packages/db/src/schema/notifications/validation.ts+++ b/packages/db/src/schema/notifications/validation.ts@@ -4,6 +4,7 @@ import * as z from "zod";import { notificationProvider } from "./constants";import { notification } from "./notification";+import { notificationDeadLetter, notificationOutbox } from "./outbox";export const notificationProviderSchema = z.enum(notificationProvider);@@ -189,3 +190,24 @@ export const InsertNotificationWithDataSchema = z.discriminatedUnion(export type InsertNotificationWithData = z.infer<typeof InsertNotificationWithDataSchema>;++export const notificationOutboxPayloadSchema = z.object({+ regions: z.array(z.string()),+ statusCode: z.number().optional(),+ message: z.string().optional(),+ latency: z.number().optional(),+});++export type NotificationOutboxPayload = z.infer<+ typeof notificationOutboxPayloadSchema+>;++export const selectNotificationOutboxSchema =+ createSelectSchema(notificationOutbox);+export const selectNotificationDeadLetterSchema = createSelectSchema(+ notificationDeadLetter,+);++export type NotificationOutboxRow = typeof notificationOutbox.$inferSelect;+export type NotificationDeadLetterRow =+ typeof notificationDeadLetter.$inferSelect;diff --git a/packages/services/AGENTS.md b/packages/services/AGENTS.mdindex 17da257ce..51e4009c4 100644--- a/packages/services/AGENTS.md+++ b/packages/services/AGENTS.md@@ -3,6 +3,14 @@Every workspace-scoped mutation lives here, not in a tRPC router or a Honohandler. Routers validate input, call a verb, map errors.+One documented exception: the checker ingest path+(`apps/workflows/src/checker/transition.ts`) writes `monitor_status`,+`incident` and the outbox directly. `ServiceContext` requires a `Workspace` that+path would have to load on every check, `withTransaction` opens an interactive+transaction where it needs a single atomic `db.batch()`, and a fail-closed+`emitAudit` would roll back a real status transition because an audit insert+failed. Do not "fix" it by routing it through a verb.+## Shape of a verb- **One file per verb** under `packages/services/src/<entity>/` (`create.ts`,diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.tsindex db0028beb..439b26fa1 100644--- a/packages/services/src/incident/__tests__/incident.test.ts+++ b/packages/services/src/incident/__tests__/incident.test.ts@@ -292,9 +292,12 @@ describe("list / get", () => {workspaceId: teamCtx.workspace.id,monitorId: testMonitorId,});+ // Only one incident per monitor may be open at a time+ // (partial unique index `incident_open_idx`), so the second is resolved.const b = await insertIncident(tx, {workspaceId: teamCtx.workspace.id,monitorId: testMonitorId,+ resolvedAt: new Date(),});const { items } = await listIncidents({