🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor uptime API imports to use uptimeSchema for better organization
Bill Yang7f98254ccd33
diff --git a/server/src/api/uptime/createMonitor.ts b/server/src/api/uptime/createMonitor.tsindex 0293721bf..30417d704 100644--- a/server/src/api/uptime/createMonitor.ts+++ b/server/src/api/uptime/createMonitor.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";import { createMonitorSchema, type CreateMonitorInput } from "./schemas.js";diff --git a/server/src/api/uptime/deleteMonitor.ts b/server/src/api/uptime/deleteMonitor.tsindex 62c8108f8..927c31803 100644--- a/server/src/api/uptime/deleteMonitor.ts+++ b/server/src/api/uptime/deleteMonitor.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";diff --git a/server/src/api/uptime/getMonitor.ts b/server/src/api/uptime/getMonitor.tsindex 4a4214d1a..48d4a7e6b 100644--- a/server/src/api/uptime/getMonitor.ts+++ b/server/src/api/uptime/getMonitor.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";interface GetMonitorParams {diff --git a/server/src/api/uptime/getMonitorEvents.ts b/server/src/api/uptime/getMonitorEvents.tsindex 136c72366..53ec59a55 100644--- a/server/src/api/uptime/getMonitorEvents.ts+++ b/server/src/api/uptime/getMonitorEvents.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorStats.ts b/server/src/api/uptime/getMonitorStats.tsindex ad9dff6a5..a0668620a 100644--- a/server/src/api/uptime/getMonitorStats.ts+++ b/server/src/api/uptime/getMonitorStats.ts@@ -2,7 +2,8 @@ import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { db } from "../../db/postgres/postgres.js";-import { member, uptimeMonitors } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults, TimeBucketToFn } from "../analytics/utils.js";import { getMonitorStatsQuerySchema, type GetMonitorStatsQuery } from "./schemas.js";diff --git a/server/src/api/uptime/getMonitorStatus.ts b/server/src/api/uptime/getMonitorStatus.tsindex a994ec8ac..843eee9e1 100644--- a/server/src/api/uptime/getMonitorStatus.ts+++ b/server/src/api/uptime/getMonitorStatus.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorUptime.ts b/server/src/api/uptime/getMonitorUptime.tsindex 1fd9cdec2..b74d2c2f9 100644--- a/server/src/api/uptime/getMonitorUptime.ts+++ b/server/src/api/uptime/getMonitorUptime.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorUptimeBuckets.ts b/server/src/api/uptime/getMonitorUptimeBuckets.tsindex c53556bf0..8fd126db8 100644--- a/server/src/api/uptime/getMonitorUptimeBuckets.ts+++ b/server/src/api/uptime/getMonitorUptimeBuckets.ts@@ -3,7 +3,8 @@ import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { db } from "../../db/postgres/postgres.js";-import { member, uptimeMonitors } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitors.ts b/server/src/api/uptime/getMonitors.tsindex ba1924681..a6c24d539 100644--- a/server/src/api/uptime/getMonitors.ts+++ b/server/src/api/uptime/getMonitors.ts@@ -2,7 +2,8 @@ import { and, eq, inArray, desc } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { DateTime } from "luxon";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getRegions.ts b/server/src/api/uptime/getRegions.tsindex d4a8b42b1..b9b165327 100644--- a/server/src/api/uptime/getRegions.ts+++ b/server/src/api/uptime/getRegions.ts@@ -1,7 +1,7 @@import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { agentRegions } from "../../db/postgres/schema.js";+import { agentRegions } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";export async function getRegions(diff --git a/server/src/api/uptime/incidents.ts b/server/src/api/uptime/incidents.tsindex f3b7ca940..fefaab9bf 100644--- a/server/src/api/uptime/incidents.ts+++ b/server/src/api/uptime/incidents.ts@@ -2,7 +2,7 @@ import { and, desc, eq, inArray, sql } from "drizzle-orm";import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { db } from "../../db/postgres/postgres.js";-import { uptimeIncidents, uptimeMonitors } from "../../db/postgres/schema.js";+import { uptimeIncidents, uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { getUserOrganizations } from "./utils.js";diff --git a/server/src/api/uptime/notifications.ts b/server/src/api/uptime/notifications.tsindex bff870465..3e1116401 100644--- a/server/src/api/uptime/notifications.ts+++ b/server/src/api/uptime/notifications.ts@@ -3,7 +3,7 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";import { DateTime } from "luxon";import { z } from "zod";import { db } from "../../db/postgres/postgres.js";-import { notificationChannels } from "../../db/postgres/schema.js";+import { notificationChannels } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { NotificationService } from "../../services/uptime/notificationService.js";import { getUserOrganizations } from "./utils.js";diff --git a/server/src/api/uptime/updateMonitor.ts b/server/src/api/uptime/updateMonitor.tsindex 8b6495b13..e84de1d23 100644--- a/server/src/api/uptime/updateMonitor.ts+++ b/server/src/api/uptime/updateMonitor.ts@@ -1,7 +1,8 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, member } from "../../db/postgres/schema.js";+import { member } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";import { updateMonitorSchema, type UpdateMonitorInput } from "./schemas.js";diff --git a/server/src/db/postgres/postgres.ts b/server/src/db/postgres/postgres.tsindex 72a8f76e8..a813d2940 100644--- a/server/src/db/postgres/postgres.ts+++ b/server/src/db/postgres/postgres.ts@@ -2,6 +2,7 @@ import dotenv from "dotenv";import { drizzle } from "drizzle-orm/postgres-js";import postgres from "postgres";import * as schema from "./schema.js";+import * as uptimeSchema from "./uptimeSchema.js";dotenv.config();@@ -17,7 +18,7 @@ const client = postgres({});// Create drizzle ORM instance-export const db = drizzle(client, { schema });+export const db = drizzle(client, { schema: { ...schema, ...uptimeSchema } });// For compatibility with raw SQL if neededexport const sql = client;diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 375362fcd..40e7db173 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -264,321 +264,3 @@ export const telemetry = pgTable("telemetry", {tableCounts: jsonb("table_counts").notNull().$type<Record<string, number>>(),clickhouseSizeGb: real("clickhouse_size_gb").notNull(),});--// Uptime monitor definitions-export const uptimeMonitors = pgTable(- "uptime_monitors",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- name: text("name"),- monitorType: text("monitor_type").notNull(), // 'http', 'tcp'-- // Common settings- intervalSeconds: integer("interval_seconds").notNull(),- enabled: boolean("enabled").default(true),-- // HTTP/HTTPS specific configuration- httpConfig: jsonb("http_config").$type<{- url: string;- method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";- headers?: Record<string, string>;- body?: string;- auth?: {- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";- credentials?: {- username?: string;- password?: string;- token?: string;- headerName?: string;- headerValue?: string;- };- };- followRedirects?: boolean;- timeoutMs?: number;- ipVersion?: "any" | "ipv4" | "ipv6";- userAgent?: string;- }>(),-- // TCP specific configuration- tcpConfig: jsonb("tcp_config").$type<{- host: string;- port: number;- timeoutMs?: number;- }>(),-- // Validation rules- validationRules: jsonb("validation_rules").notNull().default([]).$type<- Array<- | {- type: "status_code";- operator: "equals" | "not_equals" | "in" | "not_in";- value: number | number[];- }- | {- type: "response_time";- operator: "less_than" | "greater_than";- value: number;- }- | {- type: "response_body_contains" | "response_body_not_contains";- value: string;- caseSensitive?: boolean;- }- | {- type: "header_exists";- header: string;- }- | {- type: "header_value";- header: string;- operator: "equals" | "contains";- value: string;- }- | {- type: "response_size";- operator: "less_than" | "greater_than";- value: number;- }- >- >(),-- // Multi-region configuration- monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'- selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),-- // Metadata- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- createdBy: text("created_by")- .notNull()- .references(() => user.id),- },- (table) => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "uptime_monitors_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.createdBy],- foreignColumns: [user.id],- name: "uptime_monitors_created_by_user_id_fk",- }),- ],-);--// Monitor status tracking-export const uptimeMonitorStatus = pgTable(- "uptime_monitor_status",- {- monitorId: integer("monitor_id")- .primaryKey()- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- lastCheckedAt: timestamp("last_checked_at", { mode: "string" }),- nextCheckAt: timestamp("next_check_at", { mode: "string" }),- currentStatus: text("current_status").default("unknown"), // 'up', 'down', 'unknown'- consecutiveFailures: integer("consecutive_failures").default(0),- consecutiveSuccesses: integer("consecutive_successes").default(0),- uptimePercentage24h: real("uptime_percentage_24h"),- uptimePercentage7d: real("uptime_percentage_7d"),- uptimePercentage30d: real("uptime_percentage_30d"),- averageResponseTime24h: real("average_response_time_24h"),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- },- (table) => [- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",- }),- check("uptime_monitor_status_current_status_check", sql`current_status IN ('up', 'down', 'unknown')`),- check("uptime_monitor_status_uptime_24h_check", sql`uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100`),- check("uptime_monitor_status_uptime_7d_check", sql`uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100`),- check("uptime_monitor_status_uptime_30d_check", sql`uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100`),- index("uptime_monitor_status_updated_at_idx").on(table.updatedAt),- ],-);--// Alert configuration (scaffolding)-export const uptimeAlerts = pgTable(- "uptime_alerts",- {- id: serial("id").primaryKey().notNull(),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- alertType: text("alert_type").notNull(), // 'email', 'webhook', 'slack', etc.- alertConfig: jsonb("alert_config").notNull(), // Type-specific configuration- conditions: jsonb("conditions").notNull().$type<{- consecutiveFailures?: number;- responseTimeThresholdMs?: number;- uptimePercentageThreshold?: number;- }>(),- enabled: boolean("enabled").default(true),- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- },- (table) => [- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_alerts_monitor_id_uptime_monitors_id_fk",- }),- ],-);--// Alert history (scaffolding)-export const uptimeAlertHistory = pgTable(- "uptime_alert_history",- {- id: serial("id").primaryKey().notNull(),- alertId: integer("alert_id")- .notNull()- .references(() => uptimeAlerts.id, { onDelete: "cascade" }),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- triggeredAt: timestamp("triggered_at", { mode: "string" }).defaultNow(),- resolvedAt: timestamp("resolved_at", { mode: "string" }),- alertData: jsonb("alert_data"), // Context about what triggered the alert- },- (table) => [- foreignKey({- columns: [table.alertId],- foreignColumns: [uptimeAlerts.id],- name: "uptime_alert_history_alert_id_uptime_alerts_id_fk",- }),- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_alert_history_monitor_id_uptime_monitors_id_fk",- }),- ],-);--// Agent regions for VPS-based monitoring-export const agentRegions = pgTable("agent_regions", {- code: text("code").primaryKey().notNull(), // Region code (e.g., 'us-east', 'europe')- name: text("name").notNull(), // Region display name- endpointUrl: text("endpoint_url").notNull(), // Agent endpoint URL- enabled: boolean("enabled").default(true),- lastHealthCheck: timestamp("last_health_check", { mode: "string" }),- isHealthy: boolean("is_healthy").default(true),-});--// Uptime incidents table-export const uptimeIncidents = pgTable(- "uptime_incidents",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- region: text("region"), // Region where incident occurred-- // Incident timing- startTime: timestamp("start_time", { mode: "string" }).notNull(),- endTime: timestamp("end_time", { mode: "string" }), // null if ongoing-- // Status- status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'-- // Acknowledgement details- acknowledgedBy: text("acknowledged_by").references(() => user.id),- acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),-- // Resolution details- resolvedBy: text("resolved_by").references(() => user.id),- resolvedAt: timestamp("resolved_at", { mode: "string" }),-- // Error details- lastError: text("last_error"),- lastErrorType: text("last_error_type"),- failureCount: integer("failure_count").default(1),- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- },- (table) => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "uptime_incidents_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_incidents_monitor_id_uptime_monitors_id_fk",- }),- foreignKey({- columns: [table.acknowledgedBy],- foreignColumns: [user.id],- name: "uptime_incidents_acknowledged_by_user_id_fk",- }),- foreignKey({- columns: [table.resolvedBy],- foreignColumns: [user.id],- name: "uptime_incidents_resolved_by_user_id_fk",- }),- ],-);--// Notification channels table-export const notificationChannels = pgTable(- "notification_channels",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'- name: text("name").notNull(),- enabled: boolean("enabled").default(true),-- // Channel-specific configuration- config: jsonb("config").notNull().$type<{- // Email config- email?: string;-- // Discord config- webhookUrl?: string;-- // Slack config- slackWebhookUrl?: string;- slackChannel?: string;-- // SMS config (placeholder)- phoneNumber?: string;- provider?: string;- }>(),-- // Monitor selection and notification settings- monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors- triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'- cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications- lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),-- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- createdBy: text("created_by")- .notNull()- .references(() => user.id),- },- (table) => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "notification_channels_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.createdBy],- foreignColumns: [user.id],- name: "notification_channels_created_by_user_id_fk",- }),- ],-);diff --git a/server/src/db/postgres/uptimeSchema.ts b/server/src/db/postgres/uptimeSchema.tsnew file mode 100644index 000000000..38e23553a--- /dev/null+++ b/server/src/db/postgres/uptimeSchema.ts@@ -0,0 +1,333 @@+import {+ boolean,+ integer,+ jsonb,+ pgTable,+ serial,+ text,+ timestamp,+ foreignKey,+ real,+ check,+ index,+} from "drizzle-orm/pg-core";+import { sql } from "drizzle-orm";+import { organization, user } from "./schema.js";++// Uptime monitor definitions+export const uptimeMonitors = pgTable(+ "uptime_monitors",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ name: text("name"),+ monitorType: text("monitor_type").notNull(), // 'http', 'tcp'++ // Common settings+ intervalSeconds: integer("interval_seconds").notNull(),+ enabled: boolean("enabled").default(true),++ // HTTP/HTTPS specific configuration+ httpConfig: jsonb("http_config").$type<{+ url: string;+ method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";+ headers?: Record<string, string>;+ body?: string;+ auth?: {+ type: "none" | "basic" | "bearer" | "api_key" | "custom_header";+ credentials?: {+ username?: string;+ password?: string;+ token?: string;+ headerName?: string;+ headerValue?: string;+ };+ };+ followRedirects?: boolean;+ timeoutMs?: number;+ ipVersion?: "any" | "ipv4" | "ipv6";+ userAgent?: string;+ }>(),++ // TCP specific configuration+ tcpConfig: jsonb("tcp_config").$type<{+ host: string;+ port: number;+ timeoutMs?: number;+ }>(),++ // Validation rules+ validationRules: jsonb("validation_rules").notNull().default([]).$type<+ Array<+ | {+ type: "status_code";+ operator: "equals" | "not_equals" | "in" | "not_in";+ value: number | number[];+ }+ | {+ type: "response_time";+ operator: "less_than" | "greater_than";+ value: number;+ }+ | {+ type: "response_body_contains" | "response_body_not_contains";+ value: string;+ caseSensitive?: boolean;+ }+ | {+ type: "header_exists";+ header: string;+ }+ | {+ type: "header_value";+ header: string;+ operator: "equals" | "contains";+ value: string;+ }+ | {+ type: "response_size";+ operator: "less_than" | "greater_than";+ value: number;+ }+ >+ >(),++ // Multi-region configuration+ monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'+ selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),++ // Metadata+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ createdBy: text("created_by")+ .notNull()+ .references(() => user.id),+ },+ (table) => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "uptime_monitors_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.createdBy],+ foreignColumns: [user.id],+ name: "uptime_monitors_created_by_user_id_fk",+ }),+ ],+);++// Monitor status tracking+export const uptimeMonitorStatus = pgTable(+ "uptime_monitor_status",+ {+ monitorId: integer("monitor_id")+ .primaryKey()+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ lastCheckedAt: timestamp("last_checked_at", { mode: "string" }),+ nextCheckAt: timestamp("next_check_at", { mode: "string" }),+ currentStatus: text("current_status").default("unknown"), // 'up', 'down', 'unknown'+ consecutiveFailures: integer("consecutive_failures").default(0),+ consecutiveSuccesses: integer("consecutive_successes").default(0),+ uptimePercentage24h: real("uptime_percentage_24h"),+ uptimePercentage7d: real("uptime_percentage_7d"),+ uptimePercentage30d: real("uptime_percentage_30d"),+ averageResponseTime24h: real("average_response_time_24h"),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ },+ (table) => [+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",+ }),+ check("uptime_monitor_status_current_status_check", sql`current_status IN ('up', 'down', 'unknown')`),+ check("uptime_monitor_status_uptime_24h_check", sql`uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100`),+ check("uptime_monitor_status_uptime_7d_check", sql`uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100`),+ check("uptime_monitor_status_uptime_30d_check", sql`uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100`),+ index("uptime_monitor_status_updated_at_idx").on(table.updatedAt),+ ],+);++// Alert configuration (scaffolding)+export const uptimeAlerts = pgTable(+ "uptime_alerts",+ {+ id: serial("id").primaryKey().notNull(),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ alertType: text("alert_type").notNull(), // 'email', 'webhook', 'slack', etc.+ alertConfig: jsonb("alert_config").notNull(), // Type-specific configuration+ conditions: jsonb("conditions").notNull().$type<{+ consecutiveFailures?: number;+ responseTimeThresholdMs?: number;+ uptimePercentageThreshold?: number;+ }>(),+ enabled: boolean("enabled").default(true),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ },+ (table) => [+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_alerts_monitor_id_uptime_monitors_id_fk",+ }),+ ],+);++// Alert history (scaffolding)+export const uptimeAlertHistory = pgTable(+ "uptime_alert_history",+ {+ id: serial("id").primaryKey().notNull(),+ alertId: integer("alert_id")+ .notNull()+ .references(() => uptimeAlerts.id, { onDelete: "cascade" }),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ triggeredAt: timestamp("triggered_at", { mode: "string" }).defaultNow(),+ resolvedAt: timestamp("resolved_at", { mode: "string" }),+ alertData: jsonb("alert_data"), // Context about what triggered the alert+ },+ (table) => [+ foreignKey({+ columns: [table.alertId],+ foreignColumns: [uptimeAlerts.id],+ name: "uptime_alert_history_alert_id_uptime_alerts_id_fk",+ }),+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_alert_history_monitor_id_uptime_monitors_id_fk",+ }),+ ],+);++// Agent regions for VPS-based monitoring+export const agentRegions = pgTable("agent_regions", {+ code: text("code").primaryKey().notNull(), // Region code (e.g., 'us-east', 'europe')+ name: text("name").notNull(), // Region display name+ endpointUrl: text("endpoint_url").notNull(), // Agent endpoint URL+ enabled: boolean("enabled").default(true),+ lastHealthCheck: timestamp("last_health_check", { mode: "string" }),+ isHealthy: boolean("is_healthy").default(true),+});++// Uptime incidents table+export const uptimeIncidents = pgTable(+ "uptime_incidents",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ region: text("region"), // Region where incident occurred++ // Incident timing+ startTime: timestamp("start_time", { mode: "string" }).notNull(),+ endTime: timestamp("end_time", { mode: "string" }), // null if ongoing++ // Status+ status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'++ // Acknowledgement details+ acknowledgedBy: text("acknowledged_by").references(() => user.id),+ acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),++ // Resolution details+ resolvedBy: text("resolved_by").references(() => user.id),+ resolvedAt: timestamp("resolved_at", { mode: "string" }),++ // Error details+ lastError: text("last_error"),+ lastErrorType: text("last_error_type"),+ failureCount: integer("failure_count").default(1),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ },+ (table) => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "uptime_incidents_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_incidents_monitor_id_uptime_monitors_id_fk",+ }),+ foreignKey({+ columns: [table.acknowledgedBy],+ foreignColumns: [user.id],+ name: "uptime_incidents_acknowledged_by_user_id_fk",+ }),+ foreignKey({+ columns: [table.resolvedBy],+ foreignColumns: [user.id],+ name: "uptime_incidents_resolved_by_user_id_fk",+ }),+ ],+);++// Notification channels table+export const notificationChannels = pgTable(+ "notification_channels",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'+ name: text("name").notNull(),+ enabled: boolean("enabled").default(true),++ // Channel-specific configuration+ config: jsonb("config").notNull().$type<{+ // Email config+ email?: string;++ // Discord config+ webhookUrl?: string;++ // Slack config+ slackWebhookUrl?: string;+ slackChannel?: string;++ // SMS config (placeholder)+ phoneNumber?: string;+ provider?: string;+ }>(),++ // Monitor selection and notification settings+ monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors+ triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'+ cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications+ lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),++ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ createdBy: text("created_by")+ .notNull()+ .references(() => user.id),+ },+ (table) => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "notification_channels_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.createdBy],+ foreignColumns: [user.id],+ name: "notification_channels_created_by_user_id_fk",+ }),+ ],+);\ No newline at end of filediff --git a/server/src/services/uptime/monitorExecutor.ts b/server/src/services/uptime/monitorExecutor.tsindex 6a1ba7d92..9de150bd5 100644--- a/server/src/services/uptime/monitorExecutor.ts+++ b/server/src/services/uptime/monitorExecutor.ts@@ -2,7 +2,7 @@ import { Worker, Job } from "bullmq";import { eq, and, inArray } from "drizzle-orm";import { DateTime } from "luxon";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, agentRegions, uptimeIncidents } from "../../db/postgres/schema.js";+import { uptimeMonitors, uptimeMonitorStatus, agentRegions, uptimeIncidents } from "../../db/postgres/uptimeSchema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { MonitorCheckJob, HttpCheckResult, TcpCheckResult, MonitorEvent } from "./types.js";import { performHttpCheck } from "./checks/httpCheck.js";diff --git a/server/src/services/uptime/monitorScheduler.ts b/server/src/services/uptime/monitorScheduler.tsindex ed6837784..0f390019a 100644--- a/server/src/services/uptime/monitorScheduler.ts+++ b/server/src/services/uptime/monitorScheduler.ts@@ -1,7 +1,7 @@import { Queue, QueueEvents } from "bullmq";import { eq } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors } from "../../db/postgres/schema.js";+import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";import { createServiceLogger } from "../../lib/logger/logger.js";import { MonitorCheckJob } from "./types.js";diff --git a/server/src/services/uptime/notificationService.ts b/server/src/services/uptime/notificationService.tsindex 652514e13..fc9678b68 100644--- a/server/src/services/uptime/notificationService.ts+++ b/server/src/services/uptime/notificationService.ts@@ -1,7 +1,7 @@import { DateTime } from "luxon";import { and, eq, InferSelectModel } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { notificationChannels } from "../../db/postgres/schema.js";+import { notificationChannels } from "../../db/postgres/uptimeSchema.js";import { createServiceLogger } from "../../lib/logger/logger.js";import { sendEmail } from "../../lib/resend.js";import { sendSMS } from "../../lib/twilio.js";diff --git a/server/src/services/uptime/regionHealthChecker.ts b/server/src/services/uptime/regionHealthChecker.tsindex d841a05f1..25210186b 100644--- a/server/src/services/uptime/regionHealthChecker.ts+++ b/server/src/services/uptime/regionHealthChecker.ts@@ -1,6 +1,6 @@import { eq } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { agentRegions } from "../../db/postgres/schema.js";+import { agentRegions } from "../../db/postgres/uptimeSchema.js";import { createServiceLogger } from "../../lib/logger/logger.js";export class RegionHealthChecker {