Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Uptime (#496)

Bill Yangc8aa1a496f8b
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 585d4833f..e91fc2fe2 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -21,7 +21,14 @@
"Bash(cat:*)",
"Bash(find:*)",
"Bash(clickhouse-client:*)",
- "Bash(curl:*)"
+ "Bash(curl:*)",
+ "Bash(npm uninstall:*)",
+ "Bash(pkill:*)",
+ "Bash(psql:*)",
+ "Bash(source .env)",
+ "Bash(POSTGRES_PASSWORD=carbink node src/test-pgboss.js)",
+ "Bash(tsc)",
+ "Bash(touch:*)"
]
},
"enableAllProjectMcpServers": false
diff --git a/CLAUDE.md b/CLAUDE.md
index cf63cde70..5186f3a79 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3,6 +3,7 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Commands
+
- Client: `cd client && npm run dev` (NextJS with Turbopack on port 3002)
- Server: `cd server && npm run dev` (TypeScript backend)
- Lint: `cd client && npm run lint` or `cd server && npm run build`
@@ -10,12 +11,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
- Database: `cd server && npm run db:push` (update DB schema)
## Code Conventions
+
- TypeScript with strict typing throughout both client and server
- Client: React functional components with minimal useEffect and inline functions
-- Frontend: Next.js, Tailwind CSS, Shadcn UI, Tanstack Query, Zustand, Luxon, Nivo
-- Backend: Fastify, Drizzle ORM (Postgres), ClickHouse
+- Frontend: Next.js, Tailwind CSS, Shadcn UI, Tanstack Query, Zustand, Luxon, Nivo, react-hook-form
+- Backend: Fastify, Drizzle ORM (Postgres), ClickHouse, Zod
- Error handling: Use try/catch blocks with specific error types
- Naming: camelCase for variables/functions, PascalCase for components/types
- Imports: Group by external, then internal (alphabetical within groups)
- File organization: Related functionality in same directory
-- Dark mode is default theme
\ No newline at end of file
+- Dark mode is default theme
+- Never run any database migration scripts
diff --git a/client/package-lock.json b/client/package-lock.json
index 563d03096..fd1d14db1 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -17,6 +17,7 @@
"@number-flow/react": "0.5.9",
"@phosphor-icons/react": "2.1.7",
"@radix-ui/react-alert-dialog": "1.1.13",
+ "@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-dialog": "1.1.13",
"@radix-ui/react-dropdown-menu": "2.1.14",
"@radix-ui/react-label": "2.1.6",
@@ -44,6 +45,7 @@
"boring-avatars": "1.11.2",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
+ "cmdk": "^1.1.1",
"countries-list": "3.1.1",
"country-flag-icons": "1.5.19",
"d3": "7.9.0",
@@ -3089,6 +3091,7 @@
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.2.tgz",
"integrity": "sha512-yd+dI56KZqawxKZrJ31eENUwqc1QSqg4OZ15rybGjF2ZNwMO+wCyHzAVLRp9qoYJf7kYy0YpZ2b0JCzJ42HZpA==",
+ "license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.2",
"@radix-ui/react-compose-refs": "1.1.2",
@@ -7023,6 +7026,22 @@
"node": ">=6"
}
},
+ "node_modules/cmdk": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz",
+ "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "^1.1.1",
+ "@radix-ui/react-dialog": "^1.1.6",
+ "@radix-ui/react-id": "^1.1.0",
+ "@radix-ui/react-primitive": "^2.0.2"
+ },
+ "peerDependencies": {
+ "react": "^18 || ^19 || ^19.0.0-rc",
+ "react-dom": "^18 || ^19 || ^19.0.0-rc"
+ }
+ },
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
diff --git a/client/package.json b/client/package.json
index c74fd80bd..a979a658f 100644
--- a/client/package.json
+++ b/client/package.json
@@ -19,6 +19,7 @@
"@number-flow/react": "0.5.9",
"@phosphor-icons/react": "2.1.7",
"@radix-ui/react-alert-dialog": "1.1.13",
+ "@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-dialog": "1.1.13",
"@radix-ui/react-dropdown-menu": "2.1.14",
"@radix-ui/react-label": "2.1.6",
@@ -46,6 +47,7 @@
"boring-avatars": "1.11.2",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
+ "cmdk": "^1.1.1",
"countries-list": "3.1.1",
"country-flag-icons": "1.5.19",
"d3": "7.9.0",
diff --git a/client/src/api/uptime/incidents.ts b/client/src/api/uptime/incidents.ts
new file mode 100644
index 000000000..162bce9a3
--- /dev/null
+++ b/client/src/api/uptime/incidents.ts
@@ -0,0 +1,94 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { authedFetch } from "../utils";
+
+export interface UptimeIncident {
+ id: number;
+ organizationId: string;
+ monitorId: number;
+ monitorName: string;
+ region?: string;
+ affectedRegions?: string[];
+ startTime: string;
+ endTime?: string;
+ status: "active" | "acknowledged" | "resolved";
+ acknowledgedBy?: string;
+ acknowledgedAt?: string;
+ resolvedBy?: string;
+ resolvedAt?: string;
+ lastError?: string;
+ lastErrorType?: string;
+ failureCount: number;
+ createdAt: string;
+ updatedAt: string;
+}
+
+interface GetIncidentsParams {
+ status?: "active" | "acknowledged" | "resolved" | "all";
+ limit?: number;
+ offset?: number;
+}
+
+async function getIncidents(params?: GetIncidentsParams) {
+ const queryParams = new URLSearchParams();
+ if (params?.status) queryParams.append("status", params.status);
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
+ if (params?.offset) queryParams.append("offset", params.offset.toString());
+
+ const queryString = queryParams.toString();
+ const url = queryString ? `/uptime/incidents?${queryString}` : "/uptime/incidents";
+
+ return authedFetch<{
+ incidents: UptimeIncident[];
+ pagination: {
+ total: number;
+ limit: number;
+ offset: number;
+ };
+ }>(url);
+}
+
+async function acknowledgeIncident(incidentId: number) {
+ return authedFetch(
+ `/uptime/incidents/${incidentId}/acknowledge`,
+ undefined,
+ { method: 'PATCH', data: {} }
+ );
+}
+
+async function resolveIncident(incidentId: number) {
+ return authedFetch(
+ `/uptime/incidents/${incidentId}/resolve`,
+ undefined,
+ { method: 'PATCH', data: {} }
+ );
+}
+
+// Hooks
+export function useIncidents(params?: GetIncidentsParams) {
+ return useQuery({
+ queryKey: ["uptime-incidents", params],
+ queryFn: () => getIncidents(params),
+ });
+}
+
+export function useAcknowledgeIncident() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: acknowledgeIncident,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["uptime-incidents"] });
+ },
+ });
+}
+
+export function useResolveIncident() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: resolveIncident,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["uptime-incidents"] });
+ },
+ });
+}
\ No newline at end of file
diff --git a/client/src/api/uptime/monitors.ts b/client/src/api/uptime/monitors.ts
new file mode 100644
index 000000000..6bedb8784
--- /dev/null
+++ b/client/src/api/uptime/monitors.ts
@@ -0,0 +1,435 @@
+import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { authedFetch } from "../utils";
+import { timeZone } from "../../lib/dateTimeUtils";
+
+// Validation rule types
+export type ValidationRule =
+ | {
+ 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;
+ };
+
+export interface UptimeMonitor {
+ id: number;
+ organizationId: string;
+ name: string;
+ monitorType: "http" | "tcp";
+ intervalSeconds: number;
+ enabled: boolean;
+ httpConfig?: {
+ url: string;
+ method: string;
+ 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;
+ };
+ tcpConfig?: {
+ host: string;
+ port: number;
+ timeoutMs?: number;
+ };
+ validationRules: ValidationRule[];
+ monitoringType: "local" | "global";
+ selectedRegions: string[];
+ createdAt: string;
+ updatedAt: string;
+ createdBy: string;
+ status?: {
+ monitorId: number;
+ lastCheckedAt?: string;
+ currentStatus: "up" | "down" | "unknown";
+ consecutiveFailures: number;
+ consecutiveSuccesses: number;
+ uptimePercentage24h?: number;
+ uptimePercentage7d?: number;
+ uptimePercentage30d?: number;
+ updatedAt: string;
+ };
+}
+
+export interface MonitorStats {
+ hours: number;
+ startTime: string;
+ endTime: string;
+ region?: string;
+ bucket?: string;
+ monitorType?: string;
+ stats: {
+ totalChecks: number;
+ successfulChecks: number;
+ failedChecks: number;
+ timeoutChecks: number;
+ uptimePercentage: number;
+ responseTime: {
+ avg: number;
+ min: number;
+ max: number;
+ p50: number;
+ p75: number;
+ p90: number;
+ p95: number;
+ p99: number;
+ };
+ };
+ distribution: Array<{
+ hour: string;
+ avg_response_time: number;
+ avg_dns_time?: number;
+ avg_tcp_time?: number;
+ avg_tls_time?: number;
+ avg_ttfb?: number;
+ avg_transfer_time?: number;
+ check_count: number;
+ success_count: number;
+ }>;
+}
+
+export interface MonitorUptime {
+ monitorId: number;
+ totalUptimeSeconds: number;
+ currentUptimeSeconds: number;
+ totalMonitoringSeconds: number;
+ lastDowntime: {
+ timestamp: string;
+ error?: string;
+ errorType?: string;
+ status: string;
+ } | null;
+ monitoringSince: string | null;
+ lastCheck: string | null;
+ uptimePercentage: number;
+ totalChecks: number;
+ failedChecks: number;
+}
+
+export interface MonitorEvent {
+ monitor_id: number;
+ organization_id: string;
+ timestamp: string;
+ monitor_type: string;
+ monitor_url: string;
+ monitor_name: string;
+ region: string;
+ status: "success" | "failure" | "timeout";
+ status_code?: number;
+ response_time_ms: number;
+ dns_time_ms?: number;
+ tcp_time_ms?: number;
+ tls_time_ms?: number;
+ ttfb_ms?: number;
+ transfer_time_ms?: number;
+ validation_errors?: string[];
+ response_headers?: Record<string, string>;
+ response_size_bytes?: number;
+ port?: number;
+ error_message?: string;
+ error_type?: string;
+}
+
+async function getMonitors(params?: {
+ organizationId?: string;
+ enabled?: boolean;
+ monitorType?: "http" | "tcp";
+ limit?: number;
+ offset?: number;
+}) {
+ const queryParams = new URLSearchParams();
+ if (params?.organizationId) queryParams.append("organizationId", params.organizationId);
+ if (params?.enabled !== undefined) queryParams.append("enabled", params.enabled.toString());
+ if (params?.monitorType) queryParams.append("monitorType", params.monitorType);
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
+ if (params?.offset) queryParams.append("offset", params.offset.toString());
+
+ const queryString = queryParams.toString();
+ const url = queryString ? `/uptime/monitors?${queryString}` : "/uptime/monitors";
+
+ return authedFetch<UptimeMonitor[]>(url);
+}
+
+async function getMonitor(monitorId: number) {
+ return authedFetch<UptimeMonitor>(`/uptime/monitors/${monitorId}`);
+}
+
+async function getMonitorStats(
+ monitorId: number,
+ params?: {
+ startTime?: string;
+ endTime?: string;
+ region?: string;
+ hours?: number;
+ bucket?: "minute" | "five_minutes" | "ten_minutes" | "fifteen_minutes" | "hour" | "day" | "week" | "month" | "year";
+ }
+) {
+ const queryParams = new URLSearchParams();
+
+ if (params?.region) queryParams.append("region", params.region);
+ if (params?.hours) queryParams.append("hours", params.hours.toString());
+ if (params?.bucket) queryParams.append("bucket", params.bucket);
+
+ const queryString = queryParams.toString();
+ const url = queryString
+ ? `/uptime/monitors/${monitorId}/stats?${queryString}`
+ : `/uptime/monitors/${monitorId}/stats`;
+
+ return authedFetch<MonitorStats>(url);
+}
+
+async function getMonitorEvents(
+ monitorId: number,
+ params?: {
+ status?: "success" | "failure" | "timeout";
+ region?: string;
+ limit?: number;
+ offset?: number;
+ }
+) {
+ const queryParams = new URLSearchParams();
+ if (params?.status) queryParams.append("status", params.status);
+ if (params?.region) queryParams.append("region", params.region);
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
+ if (params?.offset) queryParams.append("offset", params.offset.toString());
+
+ const queryString = queryParams.toString();
+ const url = queryString
+ ? `/uptime/monitors/${monitorId}/events?${queryString}`
+ : `/uptime/monitors/${monitorId}/events`;
+
+ return authedFetch<{
+ events: MonitorEvent[];
+ pagination: {
+ total: number;
+ limit: number;
+ offset: number;
+ };
+ }>(url);
+}
+
+async function getMonitorUptime(monitorId: number) {
+ return authedFetch<MonitorUptime>(`/uptime/monitors/${monitorId}/uptime`);
+}
+
+async function getMonitorUptimeBuckets(
+ monitorId: number,
+ params?: {
+ bucket?: "hour" | "day" | "week";
+ days?: number;
+ }
+) {
+ const queryParams = new URLSearchParams();
+ if (params?.bucket) queryParams.append("bucket", params.bucket);
+ if (params?.days) queryParams.append("days", params.days.toString());
+
+ queryParams.append("timeZone", timeZone);
+
+ const queryString = queryParams.toString();
+ const url = queryString
+ ? `/uptime/monitors/${monitorId}/buckets?${queryString}`
+ : `/uptime/monitors/${monitorId}/buckets`;
+
+ return authedFetch<{
+ buckets: Array<{
+ bucket_time: string;
+ bucket_formatted: string;
+ total_checks: number;
+ successful_checks: number;
+ failed_checks: number;
+ timeout_checks: number;
+ uptime_percentage: number;
+ }>;
+ bucket: string;
+ days: number;
+ monitorId: number;
+ }>(url);
+}
+
+// Hooks
+export function useMonitors(params?: Parameters<typeof getMonitors>[0]) {
+ return useQuery({
+ queryKey: ["uptime-monitors", params],
+ queryFn: () => getMonitors(params),
+ });
+}
+
+export function useMonitor(monitorId: number | undefined) {
+ return useQuery({
+ queryKey: ["uptime-monitor", monitorId],
+ queryFn: () => (monitorId ? getMonitor(monitorId) : Promise.reject("No monitor ID")),
+ enabled: !!monitorId,
+ });
+}
+
+export function useMonitorStats(monitorId: number | undefined, params?: Parameters<typeof getMonitorStats>[1]) {
+ return useQuery({
+ queryKey: ["uptime-monitor-stats", monitorId, params],
+ queryFn: () => (monitorId ? getMonitorStats(monitorId, params) : Promise.reject("No monitor ID")),
+ enabled: !!monitorId,
+ });
+}
+
+export function useMonitorEvents(monitorId: number | undefined, params?: Parameters<typeof getMonitorEvents>[1]) {
+ return useQuery({
+ queryKey: ["uptime-monitor-events", monitorId, params],
+ queryFn: () => (monitorId ? getMonitorEvents(monitorId, params) : Promise.reject("No monitor ID")),
+ enabled: !!monitorId,
+ });
+}
+
+export function useMonitorEventsInfinite(
+ monitorId: number | undefined,
+ params?: Omit<Parameters<typeof getMonitorEvents>[1], "offset">
+) {
+ return useInfiniteQuery({
+ queryKey: ["uptime-monitor-events-infinite", monitorId, params],
+ queryFn: ({ pageParam = 0 }) =>
+ monitorId
+ ? getMonitorEvents(monitorId, { ...params, offset: pageParam, limit: 100 })
+ : Promise.reject("No monitor ID"),
+ getNextPageParam: (lastPage, pages) => {
+ const currentOffset = (pages.length - 1) * 100;
+ const hasMore = currentOffset + lastPage.events.length < lastPage.pagination.total;
+ return hasMore ? currentOffset + 100 : undefined;
+ },
+ enabled: !!monitorId,
+ initialPageParam: 0,
+ });
+}
+
+export function useMonitorUptime(monitorId: number | undefined) {
+ return useQuery({
+ queryKey: ["uptime-monitor-uptime", monitorId],
+ queryFn: () => (monitorId ? getMonitorUptime(monitorId) : Promise.reject("No monitor ID")),
+ enabled: !!monitorId,
+ });
+}
+
+export function useMonitorUptimeBuckets(
+ monitorId: number | undefined,
+ params?: Parameters<typeof getMonitorUptimeBuckets>[1]
+) {
+ return useQuery({
+ queryKey: ["uptime-monitor-buckets", monitorId, params],
+ queryFn: () => (monitorId ? getMonitorUptimeBuckets(monitorId, params) : Promise.reject("No monitor ID")),
+ enabled: !!monitorId,
+ });
+}
+
+// Mutations
+export interface CreateMonitorInput {
+ organizationId: string;
+ name: string;
+ monitorType: "http" | "tcp";
+ intervalSeconds: number;
+ enabled?: boolean;
+ httpConfig?: UptimeMonitor["httpConfig"];
+ tcpConfig?: UptimeMonitor["tcpConfig"];
+ validationRules?: ValidationRule[];
+ regions?: string[];
+}
+
+export interface UpdateMonitorInput {
+ name?: string;
+ intervalSeconds?: number;
+ enabled?: boolean;
+ httpConfig?: UptimeMonitor["httpConfig"];
+ tcpConfig?: UptimeMonitor["tcpConfig"];
+ validationRules?: ValidationRule[];
+ regions?: string[];
+}
+
+async function createMonitor(data: CreateMonitorInput) {
+ return authedFetch(
+ `/uptime/monitors`,
+ undefined,
+ { method: 'POST', data }
+ );
+}
+
+async function updateMonitor(monitorId: number, data: UpdateMonitorInput) {
+ return authedFetch(
+ `/uptime/monitors/${monitorId}`,
+ undefined,
+ { method: 'PUT', data }
+ );
+}
+
+async function deleteMonitor(monitorId: number) {
+ return authedFetch(
+ `/uptime/monitors/${monitorId}`,
+ undefined,
+ { method: 'DELETE' }
+ );
+}
+
+export function useCreateMonitor() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: createMonitor,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
+ },
+ });
+}
+
+export function useUpdateMonitor() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ monitorId, data }: { monitorId: number; data: UpdateMonitorInput }) =>
+ updateMonitor(monitorId, data),
+ onSuccess: (_, variables) => {
+ queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
+ queryClient.invalidateQueries({ queryKey: ["uptime-monitor", variables.monitorId] });
+ },
+ });
+}
+
+export function useDeleteMonitor() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: deleteMonitor,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
+ },
+ });
+}
diff --git a/client/src/api/uptime/notifications.ts b/client/src/api/uptime/notifications.ts
new file mode 100644
index 000000000..258e359e0
--- /dev/null
+++ b/client/src/api/uptime/notifications.ts
@@ -0,0 +1,128 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { authedFetch } from "../utils";
+
+export interface NotificationChannel {
+ id: number;
+ organizationId: string;
+ type: "email" | "discord" | "slack" | "sms";
+ name: string;
+ enabled: boolean;
+ config: {
+ email?: string;
+ webhookUrl?: string;
+ slackWebhookUrl?: string;
+ slackChannel?: string;
+ phoneNumber?: string;
+ provider?: string;
+ };
+ monitorIds: number[] | null; // null = all monitors
+ triggerEvents: string[];
+ cooldownMinutes: number;
+ lastNotifiedAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+ createdBy: string;
+}
+
+// Channels API
+async function getChannels() {
+ return authedFetch<{ channels: NotificationChannel[] }>("/uptime/notification-channels");
+}
+
+async function createChannel(data: {
+ type: NotificationChannel["type"];
+ name: string;
+ config: NotificationChannel["config"];
+ monitorIds?: number[] | null;
+ triggerEvents?: string[];
+ cooldownMinutes?: number;
+}) {
+ return authedFetch(
+ `/uptime/notification-channels`,
+ undefined,
+ { method: 'POST', data }
+ );
+}
+
+async function updateChannel(
+ id: number,
+ data: {
+ name?: string;
+ enabled?: boolean;
+ config?: NotificationChannel["config"];
+ monitorIds?: number[] | null;
+ triggerEvents?: string[];
+ cooldownMinutes?: number;
+ }
+) {
+ return authedFetch(
+ `/uptime/notification-channels/${id}`,
+ undefined,
+ { method: 'PUT', data }
+ );
+}
+
+async function deleteChannel(id: number) {
+ return authedFetch(
+ `/uptime/notification-channels/${id}`,
+ undefined,
+ { method: 'DELETE' }
+ );
+}
+
+async function testChannel(id: number) {
+ return authedFetch(
+ `/uptime/notification-channels/${id}/test`,
+ undefined,
+ { method: 'POST', data: {} }
+ );
+}
+
+
+// Hooks
+export function useNotificationChannels() {
+ return useQuery({
+ queryKey: ["notification-channels"],
+ queryFn: getChannels,
+ });
+}
+
+export function useCreateChannel() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: createChannel,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
+ },
+ });
+}
+
+export function useUpdateChannel() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ id, data }: { id: number; data: Parameters<typeof updateChannel>[1] }) =>
+ updateChannel(id, data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
+ },
+ });
+}
+
+export function useDeleteChannel() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: deleteChannel,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
+ },
+ });
+}
+
+export function useTestChannel() {
+ return useMutation({
+ mutationFn: testChannel,
+ });
+}
\ No newline at end of file
diff --git a/client/src/components/MobileSidebar.tsx b/client/src/app/[site]/components/Sidebar/MobileSidebar.tsx
similarity index 62%
rename from client/src/components/MobileSidebar.tsx
rename to client/src/app/[site]/components/Sidebar/MobileSidebar.tsx
index c5a469c00..68d5edd88 100644
--- a/client/src/components/MobileSidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/MobileSidebar.tsx
@@ -1,20 +1,15 @@
"use client";
import { usePathname } from "next/navigation";
-import { useGetSite } from "../api/admin/sites";
-import { Sidebar } from "../app/[site]/components/Sidebar/Sidebar";
-import { Button } from "./ui/button";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetTrigger,
-} from "./ui/sheet";
+import { useGetSite } from "../../../../api/admin/sites";
+import { Sidebar } from "./Sidebar";
+import { Button } from "../../../../components/ui/button";
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "../../../../components/ui/sheet";
import { Menu } from "lucide-react";
import { VisuallyHidden } from "radix-ui";
-import { Favicon } from "./Favicon";
+import { Favicon } from "../../../../components/Favicon";
+import { AppSidebar } from "../../../../components/AppSidebar";
export function MobileSidebar() {
const pathname = usePathname();
@@ -33,7 +28,8 @@ export function MobileSidebar() {
<SheetTitle>Rybbit Sidebar</SheetTitle>
</SheetHeader>
</VisuallyHidden.Root>
- <SheetContent side="left" className="p-0 w-[223px]" showClose={false}>
+ <SheetContent side="left" className="p-0 w-[240px] flex gap-0" showClose={false}>
+ <AppSidebar />
<Sidebar />
</SheetContent>
</Sheet>
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
index a96a93c20..87b3b806d 100644
--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
@@ -44,15 +44,13 @@ export function Sidebar() {
};
return (
- <div className="w-56 bg-neutral-900 border-r border-neutral-800 flex flex-col justify-between">
+ <div className="w-56 bg-neutral-900 border-r border-neutral-800 flex flex-col justify-between h-screen">
<div className="flex flex-col">
<div className="flex flex-col p-3 border-b border-neutral-800">
<SiteSelector />
</div>
<div className="flex flex-col p-3">
- <div className="text-xs text-neutral-400 mt-0 mb-1 mx-3 font-medium">
- Web Analytics
- </div>
+ <div className="text-xs text-neutral-400 mt-0 mb-1 mx-3 font-medium">Web Analytics</div>
<SidebarLink
label="Main"
active={isActiveTab("main")}
@@ -65,7 +63,6 @@ export function Sidebar() {
href={getTabPath("realtime")}
icon={<Earth className="w-4 h-4" />}
/>
-
<SidebarLink
label="Map"
active={isActiveTab("map")}
@@ -94,9 +91,7 @@ export function Sidebar() {
href={getTabPath("goals")}
icon={<Target weight="bold" />}
/>
- <div className="text-xs text-neutral-400 mt-3 mb-1 mx-3 font-medium">
- Product Analytics
- </div>
+ <div className="text-xs text-neutral-400 mt-3 mb-1 mx-3 font-medium">Product Analytics</div>
<div className="hidden md:block">
<SidebarLink
label="Replay"
@@ -123,9 +118,7 @@ export function Sidebar() {
href={getTabPath("retention")}
icon={<ChartColumnDecreasing className="w-4 h-4" />}
/>
- <div className="text-xs text-neutral-400 mt-3 mb-1 mx-3 font-medium">
- Behavior
- </div>
+ <div className="text-xs text-neutral-400 mt-3 mb-1 mx-3 font-medium">Behavior</div>
<SidebarLink
label="Sessions"
active={isActiveTab("sessions")}
@@ -194,9 +187,7 @@ function SidebarLink({
<div
className={cn(
"px-3 py-2 rounded-lg transition-colors w-full",
- active
- ? "bg-neutral-800 text-white"
- : "text-neutral-200 hover:text-white hover:bg-neutral-800/50"
+ active ? "bg-neutral-800 text-white" : "text-neutral-200 hover:text-white hover:bg-neutral-800/50"
)}
>
<div className="flex items-center gap-2">
diff --git a/client/src/app/[site]/components/SubHeader/SubHeader.tsx b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
index 761be37e0..ce4cc24dc 100644
--- a/client/src/app/[site]/components/SubHeader/SubHeader.tsx
+++ b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
@@ -8,9 +8,9 @@ import { Filters } from "./Filters/Filters";
import { DateSelector } from "../../../../components/DateSelector/DateSelector";
import { Time } from "../../../../components/DateSelector/types";
-import { MobileSidebar } from "../../../../components/MobileSidebar";
import { NewFilterButton } from "./Filters/NewFilterButton";
import { LiveUserCount } from "./LiveUserCount";
+import { MobileSidebar } from "../Sidebar/MobileSidebar";
const canGoForward = (time: Time) => {
const currentDay = DateTime.now().startOf("day");
@@ -37,11 +37,7 @@ const canGoForward = (time: Time) => {
return false;
};
-export function SubHeader({
- availableFilters,
-}: {
- availableFilters?: FilterParameter[];
-}) {
+export function SubHeader({ availableFilters }: { availableFilters?: FilterParameter[] }) {
const { time, setTime } = useStore();
return (
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index f12212940..a74f724c1 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -4,12 +4,12 @@ import { SavedFunnel, useGetFunnels } from "../../../api/analytics/funnels/useGe
import { Skeleton } from "@/components/ui/skeleton";
import { useStore } from "@/lib/store";
import { ArrowRight, FilterIcon } from "lucide-react";
-import { MobileSidebar } from "../../../components/MobileSidebar";
import { NothingFound } from "../../../components/NothingFound";
import { CreateFunnelDialog } from "./components/CreateFunnel";
import { FunnelRow } from "./components/FunnelRow";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
// Skeleton for the funnel row component
const FunnelRowSkeleton = () => (
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 6256f94fe..dd3c7a047 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -13,9 +13,9 @@ import { useGetSite } from "../../../api/admin/sites";
import { DateSelector } from "../../../components/DateSelector/DateSelector";
import { DateRangeMode, Time } from "../../../components/DateSelector/types";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { MobileSidebar } from "../../../components/MobileSidebar";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { timeZone } from "../../../lib/dateTimeUtils";
+import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
const MAX_LINK_HEIGHT = 100;
diff --git a/client/src/app/[site]/layout.tsx b/client/src/app/[site]/layout.tsx
index aa7454645..e9fa81078 100644
--- a/client/src/app/[site]/layout.tsx
+++ b/client/src/app/[site]/layout.tsx
@@ -2,19 +2,15 @@
import { useWindowSize } from "@uidotdev/usehooks";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
-import { useGetSite, useSiteHasData } from "../../api/admin/sites";
+import { AppSidebar } from "../../components/AppSidebar";
import { TopBar } from "../../components/TopBar";
import { useStore } from "../../lib/store";
import { useSyncStateWithUrl } from "../../lib/urlParams";
+import { Footer } from "../components/Footer";
import { Header } from "./components/Header/Header";
import { Sidebar } from "./components/Sidebar/Sidebar";
-import { Footer } from "../components/Footer";
-export default function SiteLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function SiteLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const { setSite, site } = useStore();
@@ -22,11 +18,7 @@ export default function SiteLayout({
useSyncStateWithUrl();
useEffect(() => {
- if (
- pathname.includes("/") &&
- pathname.split("/")[1] !== site &&
- !isNaN(Number(pathname.split("/")[1]))
- ) {
+ if (pathname.includes("/") && pathname.split("/")[1] !== site && !isNaN(Number(pathname.split("/")[1]))) {
setSite(pathname.split("/")[1]);
}
}, [pathname]);
@@ -44,8 +36,8 @@ export default function SiteLayout({
}
return (
- <div className="flex flex-col h-screen">
- <TopBar />
+ <div className="flex flex-row h-screen">
+ <AppSidebar />
<div className="flex flex-1 overflow-hidden">
<div className="hidden md:flex">
<Sidebar />
@@ -55,9 +47,9 @@ export default function SiteLayout({
{/* <div className="px-4 py-2 max-w-[1400px] mx-auto w-full mb-4"> */}
<Header />
<div>{children}</div>
- {!pathname.includes("/map") &&
- !pathname.includes("/realtime") &&
- !pathname.includes("/replay") && <Footer />}
+ {!pathname.includes("/map") && !pathname.includes("/realtime") && !pathname.includes("/replay") && (
+ <Footer />
+ )}
</div>
</div>
</div>
diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsx
index 4c22b4dca..c21889235 100644
--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx
@@ -12,20 +12,11 @@ import { useState } from "react";
import { useGetPerformanceTimeSeries } from "../../../../api/analytics/performance/useGetPerformanceTimeSeries";
import { BucketSelection } from "../../../../components/BucketSelection";
import { authClient } from "../../../../lib/auth";
-import {
- formatChartDateTime,
- hour12,
- userLocale,
-} from "../../../../lib/dateTimeUtils";
+import { formatChartDateTime, hour12, userLocale } from "../../../../lib/dateTimeUtils";
import { useStore } from "../../../../lib/store";
import { cn } from "../../../../lib/utils";
import { usePerformanceStore } from "../performanceStore";
-import {
- formatMetricValue,
- getMetricUnit,
- getPerformanceThresholds,
- METRIC_LABELS,
-} from "../utils/performanceUtils";
+import { formatMetricValue, getMetricUnit, getPerformanceThresholds, METRIC_LABELS } from "../utils/performanceUtils";
const tilt_wrap = Tilt_Warp({
subsets: ["latin"],
@@ -35,13 +26,10 @@ const tilt_wrap = Tilt_Warp({
export function PerformanceChart() {
const session = authClient.useSession();
const { site, bucket } = useStore();
- const { selectedPerformanceMetric, selectedPercentile } =
- usePerformanceStore();
+ const { selectedPerformanceMetric, selectedPercentile } = usePerformanceStore();
// State for toggling percentile visibility
- const [visiblePercentiles, setVisiblePercentiles] = useState<Set<string>>(
- new Set(["P50", "P75", "P90", "P99"])
- );
+ const [visiblePercentiles, setVisiblePercentiles] = useState<Set<string>>(new Set(["P50", "P75", "P90", "P99"]));
const togglePercentile = (percentile: string) => {
setVisiblePercentiles((prev) => {
@@ -134,85 +122,7 @@ export function PerformanceChart() {
}))
.filter((point) => point.y !== null),
},
- ].filter(
- (series) => series.data.length > 0 && visiblePercentiles.has(series.id)
- );
-
- // Gradient definitions for each percentile line
- const chartPropsDefs = [
- {
- id: "P50",
- type: "linearGradient",
- colors: [
- {
- offset: 0,
- color: percentileColors.p50,
- opacity: 0.3,
- },
- {
- offset: 100,
- color: percentileColors.p50,
- opacity: 0,
- },
- ],
- },
- {
- id: "P75",
- type: "linearGradient",
- colors: [
- {
- offset: 0,
- color: percentileColors.p75,
- opacity: 0.3,
- },
- {
- offset: 100,
- color: percentileColors.p75,
- opacity: 0,
- },
- ],
- },
- {
- id: "P90",
- type: "linearGradient",
- colors: [
- {
- offset: 0,
- color: percentileColors.p90,
- opacity: 0.3,
- },
- {
- offset: 100,
- color: percentileColors.p90,
- opacity: 0,
- },
- ],
- },
- {
- id: "P99",
- type: "linearGradient",
- colors: [
- {
- offset: 0,
- color: percentileColors.p99,
- opacity: 0.3,
- },
- {
- offset: 100,
- color: percentileColors.p99,
- opacity: 0,
- },
- ],
- },
- ];
-
- // Fill configuration to apply gradients
- const chartPropsFill = [
- { id: "P50", match: { id: "P50" } },
- { id: "P75", match: { id: "P75" } },
- { id: "P90", match: { id: "P90" } },
- { id: "P99", match: { id: "P99" } },
- ];
+ ].filter((series) => series.data.length > 0 && visiblePercentiles.has(series.id));
const formatXAxisValue = (value: any) => {
const dt = DateTime.fromJSDate(value).setLocale(userLocale);
@@ -229,10 +139,7 @@ export function PerformanceChart() {
};
const formatTooltipValue = (value: number) => {
- return `${formatMetricValue(
- selectedPerformanceMetric,
- value
- )}${getMetricUnit(selectedPerformanceMetric, value)}`;
+ return `${formatMetricValue(selectedPerformanceMetric, value)}${getMetricUnit(selectedPerformanceMetric, value)}`;
};
// Get performance thresholds for the current metric
@@ -249,10 +156,10 @@ export function PerformanceChart() {
strokeWidth: 1,
strokeDasharray: "8 8",
},
- legend: `Good (≀${formatMetricValue(
+ legend: `Good (≀${formatMetricValue(selectedPerformanceMetric, thresholds.good)}${getMetricUnit(
selectedPerformanceMetric,
thresholds.good
- )}${getMetricUnit(selectedPerformanceMetric, thresholds.good)})`,
+ )})`,
legendPosition: "top-left" as const,
legendOrientation: "horizontal" as const,
textStyle: {
@@ -271,10 +178,7 @@ export function PerformanceChart() {
legend: `Needs Improvement (≀${formatMetricValue(
selectedPerformanceMetric,
thresholds.needs_improvement
- )}${getMetricUnit(
- selectedPerformanceMetric,
- thresholds.needs_improvement
- )})`,
+ )}${getMetricUnit(selectedPerformanceMetric, thresholds.needs_improvement)})`,
legendPosition: "top-left" as const,
legendOrientation: "horizontal" as const,
textStyle: {
@@ -293,19 +197,14 @@ export function PerformanceChart() {
<div className="flex items-center space-x-4">
<Link
href={session.data ? "/" : "https://rybbit.io"}
- className={cn(
- "text-lg font-semibold flex items-center gap-1.5 opacity-75",
- tilt_wrap.className
- )}
+ className={cn("text-lg font-semibold flex items-center gap-1.5 opacity-75", tilt_wrap.className)}
>
<Image src="/rybbit.svg" alt="Rybbit" width={20} height={20} />
rybbit.io
</Link>
</div>
<div className="flex items-center space-x-4">
- <span className="text-sm text-neutral-200">
- {METRIC_LABELS[selectedPerformanceMetric]}
- </span>
+ <span className="text-sm text-neutral-200">{METRIC_LABELS[selectedPerformanceMetric]}</span>
<div className="flex items-center space-x-2">
{(["P50", "P75", "P90", "P99"] as const).map((percentile) => {
const colors = {
@@ -322,16 +221,11 @@ export function PerformanceChart() {
onClick={() => togglePercentile(percentile)}
className={cn(
"flex items-center space-x-1.5 px-2 py-1 rounded text-xs font-medium transition-all",
- isVisible
- ? "bg-neutral-800 text-white"
- : "bg-neutral-900 text-neutral-500 hover:text-neutral-400"
+ isVisible ? "bg-neutral-800 text-white" : "bg-neutral-900 text-neutral-500 hover:text-neutral-400"
)}
>
<div
- className={cn(
- "w-3 h-3 rounded-sm transition-opacity",
- isVisible ? "opacity-100" : "opacity-30"
- )}
+ className={cn("w-3 h-3 rounded-sm transition-opacity", isVisible ? "opacity-100" : "opacity-30")}
style={{ backgroundColor: colors[percentile] }}
/>
<span>{percentile}</span>
@@ -349,12 +243,8 @@ export function PerformanceChart() {
) : data.length === 0 ? (
<div className="h-[300px] w-full flex items-center justify-center">
<div className="text-center text-neutral-500">
- <p className="text-lg font-medium">
- No performance data available
- </p>
- <p className="text-sm">
- Try adjusting your date range or filters
- </p>
+ <p className="text-lg font-medium">No performance data available</p>
+ <p className="text-sm">Try adjusting your date range or filters</p>
</div>
</div>
) : (
@@ -393,8 +283,7 @@ export function PerformanceChart() {
tickRotation: 0,
truncateTickAt: 0,
tickValues: 5,
- format: (value) =>
- formatMetricValue(selectedPerformanceMetric, value),
+ format: (value) => formatMetricValue(selectedPerformanceMetric, value),
}}
colors={(d) => d.color}
enableTouchCrosshair={true}
@@ -405,9 +294,7 @@ export function PerformanceChart() {
enableArea={false}
markers={markers}
sliceTooltip={({ slice }: any) => {
- const currentTime = DateTime.fromJSDate(
- new Date(slice.points[0].data.x)
- );
+ const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x));
return (
<div className="text-sm bg-neutral-850 p-3 rounded-md min-w-[150px] border border-neutral-750">
@@ -415,24 +302,14 @@ export function PerformanceChart() {
<div className="space-y-2 mt-2">
{slice.points.map((point: any) => {
return (
- <div
- key={point.seriesId}
- className="flex justify-between items-center"
- >
+ <div key={point.seriesId} className="flex justify-between items-center">
<div className="flex items-center gap-2">
- <div
- className="w-3 h-3 rounded-full"
- style={{ backgroundColor: point.seriesColor }}
- />
- <span className="text-neutral-200 font-medium">
- {point.seriesId}
- </span>
+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: point.seriesColor }} />
+ <span className="text-neutral-200 font-medium">{point.seriesId}</span>
</div>
<span className="text-white">
{point.serieId}
- {formatTooltipValue(
- Number(point.data.yFormatted)
- )}
+ {formatTooltipValue(Number(point.data.yFormatted))}
</span>
</div>
);
diff --git a/client/src/app/[site]/realtime/page.tsx b/client/src/app/[site]/realtime/page.tsx
index ecf9209f2..9f2247515 100644
--- a/client/src/app/[site]/realtime/page.tsx
+++ b/client/src/app/[site]/realtime/page.tsx
@@ -4,7 +4,6 @@ import NumberFlow from "@number-flow/react";
import { useMeasure } from "@uidotdev/usehooks";
import { useAtom } from "jotai";
import { useGetLiveUsercount } from "../../../api/analytics/useLiveUserCount";
-import { MobileSidebar } from "../../../components/MobileSidebar";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { RealtimeChart } from "./RealtimeChart/RealtimeChart";
@@ -12,6 +11,7 @@ import { RealtimeEvents } from "./RealtimeEvents/RealtimeEvents";
import { World } from "./RealtimeGlobe/RealtimeGlobe";
import { minutesAtom, MinutesType } from "./realtimeStore";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
export default function RealtimePage() {
useSetPageTitle("Rybbit Β· Realtime");
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index 45ba15242..d4426fabb 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -4,7 +4,6 @@ import { DateTime } from "luxon"; // Import Luxon for date formatting
import { Fragment, useMemo, useState } from "react";
import { RetentionMode, useGetRetention } from "../../../api/analytics/useGetRetention";
import { ThreeDotLoader } from "../../../components/Loaders";
-import { MobileSidebar } from "../../../components/MobileSidebar";
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";
@@ -12,6 +11,7 @@ import { RetentionChart } from "./RetentionChart";
import { NothingFound } from "../../../components/NothingFound";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
// Available time range options (in days)
const RANGE_OPTIONS = [
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index c66c2b706..16a1777ba 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -17,7 +17,6 @@ import { DateTime } from "luxon";
import { useParams, useRouter } from "next/navigation";
import { useUserInfo } from "../../../../api/analytics/userInfo";
import { useGetUserSessionCount } from "../../../../api/analytics/userSessions";
-import { MobileSidebar } from "../../../../components/MobileSidebar";
import { Button } from "../../../../components/ui/button";
import { Skeleton } from "../../../../components/ui/skeleton";
import { useSetPageTitle } from "../../../../hooks/useSetPageTitle";
@@ -29,6 +28,7 @@ import { CountryFlag } from "../../components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
import { VisitCalendar } from "./components/Calendar";
import { Avatar } from "../../../../components/Avatar";
+import { MobileSidebar } from "../../components/Sidebar/MobileSidebar";
export default function UserPage() {
useSetPageTitle("Rybbit Β· User");
@@ -98,47 +98,31 @@ export default function UserPage() {
{data?.country ? getCountryName(data.country) : "N/A"}
</div>
<span className=" text-neutral-100">Region:</span>
- <div className="text-neutral-300">
- {data?.region ? getRegionName(data.region) : "N/A"}
- </div>
+ <div className="text-neutral-300">{data?.region ? getRegionName(data.region) : "N/A"}</div>
<span className=" text-neutral-100">City:</span>
<div className="text-neutral-300">{data?.city ?? "N/A"}</div>
<span className=" text-neutral-100">Language:</span>
- <div className="text-neutral-300">
- {data?.language ? getLanguageName(data.language) : "N/A"}
- </div>
+ <div className="text-neutral-300">{data?.language ? getLanguageName(data.language) : "N/A"}</div>
</div>
<div className="grid grid-cols-[110px_1fr] gap-2">
<span className=" text-neutral-100">Device Type:</span>
<div className="text-neutral-300 flex gap-1 items-center">
- {data?.device_type === "Desktop" && (
- <Monitor className="w-4 h-4" />
- )}
- {data?.device_type === "Mobile" && (
- <Smartphone className="w-4 h-4" />
- )}
- {data?.device_type === "Tablet" && (
- <Tablet className="w-4 h-4" />
- )}
+ {data?.device_type === "Desktop" && <Monitor className="w-4 h-4" />}
+ {data?.device_type === "Mobile" && <Smartphone className="w-4 h-4" />}
+ {data?.device_type === "Tablet" && <Tablet className="w-4 h-4" />}
{data?.device_type}
</div>
<span className=" text-neutral-100">Browser:</span>
<div className="flex gap-1 text-neutral-300 items-center">
<Browser browser={data?.browser || "Unknown"} />
{data?.browser}
- {data?.browser_version && (
- <span className="ml-1">v{data?.browser_version}</span>
- )}
+ {data?.browser_version && <span className="ml-1">v{data?.browser_version}</span>}
</div>
<span className="text-neutral-100">OS:</span>
<div className="flex gap-1 text-neutral-300 items-center">
<OperatingSystem os={data?.operating_system || ""} />
{data?.operating_system}
- {data?.operating_system_version && (
- <span className="ml-1">
- v{data?.operating_system_version}
- </span>
- )}
+ {data?.operating_system_version && <span className="ml-1">v{data?.operating_system_version}</span>}
</div>
<span className="text-neutral-100">Screen Size:</span>
<div className="flex gap-1 text-neutral-300">
@@ -173,9 +157,7 @@ export default function UserPage() {
<Clock className="w-4 h-4" />
Avg. Session Duration
</div>
- <div className="font-semibold">
- {data?.duration ? formatDuration(data.duration) : "N/A"}
- </div>
+ <div className="font-semibold">{data?.duration ? formatDuration(data.duration) : "N/A"}</div>
</div>
<div className="bg-neutral-900 p-3 rounded-lg flex flex-col gap-1 border border-neutral-800 flex-grow">
<div className="text-xs text-neutral-400 flex items-center gap-1">
diff --git a/client/src/app/account/page.tsx b/client/src/app/account/page.tsx
deleted file mode 100644
index 72b67d83c..000000000
--- a/client/src/app/account/page.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client";
-
-import { useSetPageTitle } from "../../hooks/useSetPageTitle";
-import { StandardPage } from "../../components/StandardPage";
-import { AccountInner } from "./components/AccountInner";
-import { authClient } from "../../lib/auth";
-
-export default function AccountPage() {
- useSetPageTitle("Rybbit Β· Account");
- const session = authClient.useSession();
-
- return (
- <StandardPage>
- <div className="space-y-6">
- <div>
- <h1 className="text-3xl font-bold tracking-tight">
- Account Settings
- </h1>
- <p className="text-gray-500 dark:text-gray-400">
- Manage your personal account settings
- </p>
- </div>
- <AccountInner session={session} />
- </div>
- </StandardPage>
- );
-}
diff --git a/client/src/app/account/components/AccountInner.tsx b/client/src/app/settings/account/components/AccountInner.tsx
similarity index 84%
rename from client/src/app/account/components/AccountInner.tsx
rename to client/src/app/settings/account/components/AccountInner.tsx
index ed17e8fef..bf6962c3d 100644
--- a/client/src/app/account/components/AccountInner.tsx
+++ b/client/src/app/settings/account/components/AccountInner.tsx
@@ -1,21 +1,31 @@
"use client";
import { authClient } from "@/lib/auth";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { Button } from "../../../components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
-import { Input } from "../../../components/ui/input";
+import { Button } from "../../../../components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
+import { Input } from "../../../../components/ui/input";
import { ChangePassword } from "./ChangePassword";
import { DeleteAccount } from "./DeleteAccount";
-import { validateEmail } from "../../../lib/auth-utils";
+import { validateEmail } from "../../../../lib/auth-utils";
+import { useRouter } from "next/navigation";
+import { useQueryClient } from "@tanstack/react-query";
export function AccountInner({ session }: { session: ReturnType<typeof authClient.useSession> }) {
+ const router = useRouter();
+ const queryClient = useQueryClient();
+
const [email, setEmail] = useState(session.data?.user.email ?? "");
const [name, setName] = useState(session.data?.user.name ?? "");
const [isUpdatingEmail, setIsUpdatingEmail] = useState(false);
const [isUpdatingName, setIsUpdatingName] = useState(false);
+ useEffect(() => {
+ setEmail(session.data?.user.email ?? "");
+ setName(session.data?.user.name ?? "");
+ }, [session]);
+
const handleNameUpdate = async () => {
if (!name) {
toast.error("Name cannot be empty");
@@ -116,6 +126,17 @@ export function AccountInner({ session }: { session: ReturnType<typeof authClien
</Button>
</div>
</div>
+ <Button
+ variant="outline"
+ onClick={async () => {
+ // Clear the query cache before signing out
+ queryClient.clear();
+ await authClient.signOut();
+ router.push("/login");
+ }}
+ >
+ Sign out
+ </Button>
</CardContent>
</Card>
diff --git a/client/src/app/account/components/ChangePassword.tsx b/client/src/app/settings/account/components/ChangePassword.tsx
similarity index 80%
rename from client/src/app/account/components/ChangePassword.tsx
rename to client/src/app/settings/account/components/ChangePassword.tsx
index 2136a1c52..2e85b7d3a 100644
--- a/client/src/app/account/components/ChangePassword.tsx
+++ b/client/src/app/settings/account/components/ChangePassword.tsx
@@ -1,16 +1,10 @@
"use client";
import { cn } from "@/lib/utils";
-import {
- CheckCircle2,
- KeyRound,
- ShieldAlert,
- ShieldCheck,
- XCircle,
-} from "lucide-react";
+import { CheckCircle2, KeyRound, ShieldAlert, ShieldCheck, XCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { Button } from "../../../components/ui/button";
+import { Button } from "../../../../components/ui/button";
import {
Dialog,
DialogClose,
@@ -20,10 +14,10 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from "../../../components/ui/dialog";
-import { Input } from "../../../components/ui/input";
-import { Label } from "../../../components/ui/label";
-import { authClient } from "../../../lib/auth";
+} from "../../../../components/ui/dialog";
+import { Input } from "../../../../components/ui/input";
+import { Label } from "../../../../components/ui/label";
+import { authClient } from "../../../../lib/auth";
export function ChangePassword() {
const [open, setOpen] = useState(false);
@@ -66,20 +60,14 @@ export function ChangePassword() {
} else if (strength >= 3 && newPassword.length >= 8) {
feedback = "Good password";
} else if (newPassword.length >= 8) {
- feedback =
- "Add uppercase, lowercase, numbers, or symbols for a stronger password";
+ feedback = "Add uppercase, lowercase, numbers, or symbols for a stronger password";
}
setPasswordStrength(strength);
setPasswordFeedback(feedback);
}, [newPassword]);
- const canSubmit =
- currentPassword &&
- newPassword &&
- confirmPassword &&
- passwordsMatch &&
- passwordStrength >= 3;
+ const canSubmit = currentPassword && newPassword && confirmPassword && passwordsMatch && passwordStrength >= 3;
const resetForm = () => {
setCurrentPassword("");
@@ -148,17 +136,12 @@ export function ChangePassword() {
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Change Password</DialogTitle>
- <DialogDescription>
- Update your password to keep your account secure
- </DialogDescription>
+ <DialogDescription>Update your password to keep your account secure</DialogDescription>
</DialogHeader>
<div className="space-y-5 py-4">
<div className="space-y-2">
- <Label
- htmlFor="currentPassword"
- className="text-sm font-medium flex items-center"
- >
+ <Label htmlFor="currentPassword" className="text-sm font-medium flex items-center">
Current Password
</Label>
<div className="relative">
@@ -179,10 +162,7 @@ export function ChangePassword() {
</div>
<div className="space-y-2">
- <Label
- htmlFor="newPassword"
- className="text-sm font-medium flex items-center justify-between"
- >
+ <Label htmlFor="newPassword" className="text-sm font-medium flex items-center justify-between">
<span>New Password</span>
{passwordStrength > 0 && (
<span
@@ -195,11 +175,7 @@ export function ChangePassword() {
: "text-green-500"
)}
>
- {passwordStrength <= 2
- ? "Weak"
- : passwordStrength === 3
- ? "Good"
- : "Strong"}
+ {passwordStrength <= 2 ? "Weak" : passwordStrength === 3 ? "Good" : "Strong"}
</span>
)}
</Label>
@@ -232,9 +208,7 @@ export function ChangePassword() {
key={index}
className={cn(
"h-1.5 w-1/4 rounded-full transition-colors duration-300",
- index <= passwordStrength
- ? getStrengthColor()
- : "bg-neutral-200 dark:bg-neutral-700"
+ index <= passwordStrength ? getStrengthColor() : "bg-neutral-200 dark:bg-neutral-700"
)}
/>
))}
@@ -258,10 +232,7 @@ export function ChangePassword() {
</div>
<div className="space-y-2">
- <Label
- htmlFor="confirmPassword"
- className="text-sm font-medium flex items-center"
- >
+ <Label htmlFor="confirmPassword" className="text-sm font-medium flex items-center">
Confirm Password
</Label>
<div className="relative">
@@ -283,11 +254,7 @@ export function ChangePassword() {
</div>
)}
</div>
- {!passwordsMatch && confirmPassword && (
- <p className="text-xs text-red-500 mt-1">
- Passwords do not match
- </p>
- )}
+ {!passwordsMatch && confirmPassword && <p className="text-xs text-red-500 mt-1">Passwords do not match</p>}
</div>
</div>
@@ -297,12 +264,7 @@ export function ChangePassword() {
Cancel
</Button>
</DialogClose>
- <Button
- onClick={handleSubmit}
- disabled={!canSubmit || isSubmitting}
- variant="success"
- className="sm:flex-1"
- >
+ <Button onClick={handleSubmit} disabled={!canSubmit || isSubmitting} variant="success" className="sm:flex-1">
{isSubmitting ? "Changing..." : "Change Password"}
</Button>
</DialogFooter>
diff --git a/client/src/app/account/components/DeleteAccount.tsx b/client/src/app/settings/account/components/DeleteAccount.tsx
similarity index 78%
rename from client/src/app/account/components/DeleteAccount.tsx
rename to client/src/app/settings/account/components/DeleteAccount.tsx
index 232e65caa..0ae97989a 100644
--- a/client/src/app/account/components/DeleteAccount.tsx
+++ b/client/src/app/settings/account/components/DeleteAccount.tsx
@@ -15,12 +15,12 @@ import {
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
-} from "../../../components/ui/alert-dialog";
-import { Button } from "../../../components/ui/button";
-import { Input } from "../../../components/ui/input";
-import { Label } from "../../../components/ui/label";
-import { authClient } from "../../../lib/auth";
-import { cn } from "../../../lib/utils";
+} from "../../../../components/ui/alert-dialog";
+import { Button } from "../../../../components/ui/button";
+import { Input } from "../../../../components/ui/input";
+import { Label } from "../../../../components/ui/label";
+import { authClient } from "../../../../lib/auth";
+import { cn } from "../../../../lib/utils";
export function DeleteAccount() {
const [isDeleting, setIsDeleting] = useState(false);
@@ -44,15 +44,8 @@ export function DeleteAccount() {
});
if (response.error) {
- toast.error(
- `Failed to delete account: ${
- response.error.message || "Unknown error"
- }`
- );
- if (
- response.error.message &&
- response.error.message.toLowerCase().includes("password")
- ) {
+ toast.error(`Failed to delete account: ${response.error.message || "Unknown error"}`);
+ if (response.error.message && response.error.message.toLowerCase().includes("password")) {
setPasswordError("Incorrect password");
}
return;
@@ -77,11 +70,7 @@ export function DeleteAccount() {
return (
<AlertDialog open={isOpen} onOpenChange={setIsOpen}>
<AlertDialogTrigger asChild>
- <Button
- variant="destructive"
- className="w-full"
- onClick={() => setIsOpen(true)}
- >
+ <Button variant="destructive" className="w-full" onClick={() => setIsOpen(true)}>
Delete Account
</Button>
</AlertDialogTrigger>
@@ -92,8 +81,8 @@ export function DeleteAccount() {
Delete your account?
</AlertDialogTitle>
<AlertDialogDescription>
- This action cannot be undone. This will permanently delete your
- account and remove all your data from our servers.
+ This action cannot be undone. This will permanently delete your account and remove all your data from our
+ servers.
</AlertDialogDescription>
</AlertDialogHeader>
@@ -110,9 +99,7 @@ export function DeleteAccount() {
className={cn("mt-1", passwordError && "border-red-500")}
disabled={isDeleting}
/>
- {passwordError && (
- <p className="text-sm text-red-500 mt-1">{passwordError}</p>
- )}
+ {passwordError && <p className="text-sm text-red-500 mt-1">{passwordError}</p>}
</div>
<AlertDialogFooter>
diff --git a/client/src/app/settings/account/page.tsx b/client/src/app/settings/account/page.tsx
new file mode 100644
index 000000000..b55f42143
--- /dev/null
+++ b/client/src/app/settings/account/page.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { authClient } from "../../../lib/auth";
+import { AccountInner } from "./components/AccountInner";
+
+export default function AccountPage() {
+ useSetPageTitle("Rybbit Β· Account");
+ const session = authClient.useSession();
+
+ return (
+ <>
+ <div className="mb-4">
+ <h1 className="text-3xl font-bold tracking-tight">Account Settings</h1>
+ <p className="text-gray-500 dark:text-gray-400">Manage your personal account settings</p>
+ </div>
+ <AccountInner session={session} />
+ </>
+ );
+}
diff --git a/client/src/app/settings/components/MobileSidebar.tsx b/client/src/app/settings/components/MobileSidebar.tsx
new file mode 100644
index 000000000..3b42d2668
--- /dev/null
+++ b/client/src/app/settings/components/MobileSidebar.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { Button } from "../../../components/ui/button";
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "../../../components/ui/sheet";
+
+import { Menu } from "lucide-react";
+import { VisuallyHidden } from "radix-ui";
+import { AppSidebar } from "../../../components/AppSidebar";
+import { Sidebar } from "./SIdebar";
+
+export function MobileSidebar() {
+ return (
+ <div className="md:hidden flex items-center gap-2">
+ <Sheet>
+ <SheetTrigger asChild>
+ <Button size="icon" variant="outline">
+ <Menu />
+ </Button>
+ </SheetTrigger>
+ <VisuallyHidden.Root>
+ <SheetHeader>
+ <SheetTitle>Rybbit Sidebar</SheetTitle>
+ </SheetHeader>
+ </VisuallyHidden.Root>
+ <SheetContent side="left" className="p-0 w-[240px] flex gap-0" showClose={false}>
+ <AppSidebar />
+ <Sidebar />
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+}
diff --git a/client/src/app/settings/components/SIdebar.tsx b/client/src/app/settings/components/SIdebar.tsx
new file mode 100644
index 000000000..50aa25ea7
--- /dev/null
+++ b/client/src/app/settings/components/SIdebar.tsx
@@ -0,0 +1,64 @@
+"use client";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { Building2, CreditCard, UserCircle } from "lucide-react";
+import { cn } from "../../../lib/utils";
+
+export function Sidebar() {
+ const pathname = usePathname();
+
+ return (
+ <div className="w-56 bg-neutral-900 border-r border-neutral-800 flex flex-col justify-between">
+ <div className="flex flex-col p-3">
+ <div className="text-base text-neutral-100 mt-2 mb-4 mx-1 font-medium">Settings</div>
+ <SidebarLink
+ label="Account"
+ active={pathname.startsWith("/settings/account")}
+ href={"/settings/account"}
+ icon={<UserCircle className="w-4 h-4" />}
+ />
+ <SidebarLink
+ label="Organization"
+ active={pathname.startsWith("/settings/organization/members")}
+ href={"/settings/organization"}
+ icon={<Building2 className="w-4 h-4" />}
+ />
+ <SidebarLink
+ label="Subscription"
+ active={pathname.startsWith("/settings/organization/subscription")}
+ href={"/settings/organization/subscription"}
+ icon={<CreditCard className="w-4 h-4" />}
+ />
+ </div>
+ </div>
+ );
+}
+
+// Sidebar Link component
+function SidebarLink({
+ label,
+ active = false,
+ href,
+ icon,
+}: {
+ label: string;
+ active?: boolean;
+ href: string;
+ icon?: React.ReactNode;
+}) {
+ return (
+ <Link href={href} className="focus:outline-none">
+ <div
+ className={cn(
+ "px-3 py-2 rounded-lg transition-colors w-full",
+ active ? "bg-neutral-800 text-white" : "text-neutral-200 hover:text-white hover:bg-neutral-800/50"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {icon}
+ <span className="text-sm">{label}</span>
+ </div>
+ </div>
+ </Link>
+ );
+}
diff --git a/client/src/app/settings/layout.tsx b/client/src/app/settings/layout.tsx
new file mode 100644
index 000000000..d10d3dae2
--- /dev/null
+++ b/client/src/app/settings/layout.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useWindowSize } from "@uidotdev/usehooks";
+import { AppSidebar } from "../../components/AppSidebar";
+import { StandardPage } from "../../components/StandardPage";
+import { MobileSidebar } from "./components/MobileSidebar";
+import { Sidebar } from "./components/SIdebar";
+
+export default function SettingsLayout({ children }: { children: React.ReactNode }) {
+ const { width } = useWindowSize();
+
+ if (width && width < 768) {
+ return (
+ <StandardPage showSidebar={false}>
+ <MobileSidebar />
+ <div className="mt-4">{children}</div>
+ </StandardPage>
+ );
+ }
+
+ return (
+ <div className="flex h-full">
+ <AppSidebar />
+ <Sidebar />
+ <StandardPage showSidebar={false}>
+ <div className="flex-1 overflow-auto mt-4">{children}</div>
+ </StandardPage>
+ </div>
+ );
+}
diff --git a/client/src/app/organization/layout.tsx b/client/src/app/settings/organization/layout.tsx
similarity index 75%
rename from client/src/app/organization/layout.tsx
rename to client/src/app/settings/organization/layout.tsx
index 66abd2880..c0e370971 100644
--- a/client/src/app/organization/layout.tsx
+++ b/client/src/app/settings/organization/layout.tsx
@@ -3,12 +3,11 @@
import { CreditCard, Users } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
-import { CreateOrganizationDialog } from "../../components/CreateOrganizationDialog";
-import { OrganizationSelector } from "../../components/OrganizationSelector";
-import { StandardPage } from "../../components/StandardPage";
-import { Button } from "../../components/ui/button";
-import { Tabs, TabsList, TabsTrigger } from "../../components/ui/tabs";
-import { IS_CLOUD } from "../../lib/const";
+import { CreateOrganizationDialog } from "../../../components/CreateOrganizationDialog";
+import { OrganizationSelector } from "../../../components/OrganizationSelector";
+import { Button } from "../../../components/ui/button";
+import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";
+import { IS_CLOUD } from "../../../lib/const";
export default function OrganizationLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
@@ -20,15 +19,15 @@ export default function OrganizationLayout({ children }: { children: React.React
const handleTabChange = (value: string) => {
if (value === "members") {
- router.push("/organization/members");
+ router.push("/settings/organization/members");
} else if (value === "subscription") {
- router.push("/organization/subscription");
+ router.push("/settings/organization/subscription");
}
};
return (
- <StandardPage>
- <div className="space-y-6">
+ <>
+ <div className="space-y-5">
<div>
<h1 className="text-3xl font-bold tracking-tight">Organization Settings</h1>
<p className="text-gray-500 dark:text-gray-400">Manage your organization settings and members</p>
@@ -60,6 +59,6 @@ export default function OrganizationLayout({ children }: { children: React.React
<div className="mt-6">{children}</div>
</div>
- </StandardPage>
+ </>
);
}
diff --git a/client/src/app/organization/members/components/CreateUserDialog.tsx b/client/src/app/settings/organization/members/components/CreateUserDialog.tsx
similarity index 95%
rename from client/src/app/organization/members/components/CreateUserDialog.tsx
rename to client/src/app/settings/organization/members/components/CreateUserDialog.tsx
index df5bf1afd..b7b49325e 100644
--- a/client/src/app/organization/members/components/CreateUserDialog.tsx
+++ b/client/src/app/settings/organization/members/components/CreateUserDialog.tsx
@@ -16,10 +16,10 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { UserPlus } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
-import { Alert } from "../../../../components/ui/alert";
-import { authClient } from "../../../../lib/auth";
-import { authedFetch } from "../../../../api/utils";
-import { validateEmail } from "../../../../lib/auth-utils";
+import { Alert } from "../../../../../components/ui/alert";
+import { authClient } from "../../../../../lib/auth";
+import { authedFetch } from "../../../../../api/utils";
+import { validateEmail } from "../../../../../lib/auth-utils";
interface CreateUserDialogProps {
organizationId: string;
diff --git a/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx b/client/src/app/settings/organization/members/components/DeleteOrganizationDialog.tsx
similarity index 97%
rename from client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
rename to client/src/app/settings/organization/members/components/DeleteOrganizationDialog.tsx
index 24c541f39..a47c0dcd4 100644
--- a/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
+++ b/client/src/app/settings/organization/members/components/DeleteOrganizationDialog.tsx
@@ -14,7 +14,7 @@ import { AlertTriangle, Trash } from "lucide-react";
import { authClient } from "@/lib/auth";
import { toast } from "sonner";
import { Organization } from "../page";
-import { USER_ORGANIZATIONS_QUERY_KEY } from "../../../../api/admin/organizations";
+import { USER_ORGANIZATIONS_QUERY_KEY } from "../../../../../api/admin/organizations";
import { useQueryClient } from "@tanstack/react-query";
interface DeleteOrganizationDialogProps {
diff --git a/client/src/app/organization/members/components/EditOrganizationDialog.tsx b/client/src/app/settings/organization/members/components/EditOrganizationDialog.tsx
similarity index 100%
rename from client/src/app/organization/members/components/EditOrganizationDialog.tsx
rename to client/src/app/settings/organization/members/components/EditOrganizationDialog.tsx
diff --git a/client/src/app/organization/members/components/Invitations.tsx b/client/src/app/settings/organization/members/components/Invitations.tsx
similarity index 78%
rename from client/src/app/organization/members/components/Invitations.tsx
rename to client/src/app/settings/organization/members/components/Invitations.tsx
index 155f1ddfe..8f4f74527 100644
--- a/client/src/app/organization/members/components/Invitations.tsx
+++ b/client/src/app/settings/organization/members/components/Invitations.tsx
@@ -1,26 +1,13 @@
"use client";
import { DateTime } from "luxon";
-import { useQuery } from "@tanstack/react-query";
-import { authClient } from "../../../../lib/auth";
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from "../../../../components/ui/card";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "../../../../components/ui/table";
-import { Badge } from "../../../../components/ui/badge";
-import { Button } from "../../../../components/ui/button";
import { useState } from "react";
import { toast } from "sonner";
-import { useOrganizationInvitations } from "../../../../api/admin/organizations";
+import { useOrganizationInvitations } from "../../../../../api/admin/organizations";
+import { Badge } from "../../../../../components/ui/badge";
+import { Button } from "../../../../../components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../../../components/ui/card";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../components/ui/table";
+import { authClient } from "../../../../../lib/auth";
interface InvitationsProps {
organizationId: string;
@@ -28,9 +15,7 @@ interface InvitationsProps {
}
export function Invitations({ organizationId, isOwner }: InvitationsProps) {
- const [loadingInvitationId, setLoadingInvitationId] = useState<string | null>(
- null
- );
+ const [loadingInvitationId, setLoadingInvitationId] = useState<string | null>(null);
const {
data: invitations,
@@ -133,18 +118,12 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
invitations.map((invitation) => (
<TableRow key={invitation.id}>
<TableCell>{invitation.email}</TableCell>
- <TableCell className="capitalize">
- {invitation.role}
- </TableCell>
+ <TableCell className="capitalize">{invitation.role}</TableCell>
<TableCell>
- <Badge variant={getBadgeVariant(invitation.status)}>
- {invitation.status}
- </Badge>
+ <Badge variant={getBadgeVariant(invitation.status)}>{invitation.status}</Badge>
</TableCell>
<TableCell>
- {DateTime.fromJSDate(
- new Date(invitation.expiresAt)
- ).toLocaleString(DateTime.DATE_SHORT)}
+ {DateTime.fromJSDate(new Date(invitation.expiresAt)).toLocaleString(DateTime.DATE_SHORT)}
</TableCell>
{isOwner && (
<TableCell className="text-right">
@@ -153,13 +132,9 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
variant="default"
size="sm"
disabled={loadingInvitationId === invitation.id}
- onClick={() =>
- handleCancelInvitation(invitation.id)
- }
+ onClick={() => handleCancelInvitation(invitation.id)}
>
- {loadingInvitationId === invitation.id
- ? "Processing..."
- : "Cancel"}
+ {loadingInvitationId === invitation.id ? "Processing..." : "Cancel"}
</Button>
)}
{invitation.status === "canceled" && (
@@ -169,9 +144,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
disabled={loadingInvitationId === invitation.id}
onClick={() => handleResendInvitation(invitation)}
>
- {loadingInvitationId === invitation.id
- ? "Processing..."
- : "Resend"}
+ {loadingInvitationId === invitation.id ? "Processing..." : "Resend"}
</Button>
)}
</TableCell>
@@ -180,10 +153,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
))
) : (
<TableRow>
- <TableCell
- colSpan={isOwner ? 5 : 4}
- className="text-center py-6 text-muted-foreground"
- >
+ <TableCell colSpan={isOwner ? 5 : 4} className="text-center py-6 text-muted-foreground">
No pending invitations
</TableCell>
</TableRow>
diff --git a/client/src/app/organization/members/components/InviteMemberDialog.tsx b/client/src/app/settings/organization/members/components/InviteMemberDialog.tsx
similarity index 82%
rename from client/src/app/organization/members/components/InviteMemberDialog.tsx
rename to client/src/app/settings/organization/members/components/InviteMemberDialog.tsx
index 47c5ec67d..3703c5244 100644
--- a/client/src/app/organization/members/components/InviteMemberDialog.tsx
+++ b/client/src/app/settings/organization/members/components/InviteMemberDialog.tsx
@@ -12,28 +12,19 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { UserPlus } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
-import { Alert } from "../../../../components/ui/alert";
-import { authClient } from "../../../../lib/auth";
+import { Alert } from "../../../../../components/ui/alert";
+import { authClient } from "../../../../../lib/auth";
interface InviteMemberDialogProps {
organizationId: string;
onSuccess: () => void;
}
-export function InviteMemberDialog({
- organizationId,
- onSuccess,
-}: InviteMemberDialogProps) {
+export function InviteMemberDialog({ organizationId, onSuccess }: InviteMemberDialogProps) {
const [email, setEmail] = useState("");
const [role, setRole] = useState<"admin" | "member">("member");
@@ -79,9 +70,7 @@ export function InviteMemberDialog({
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Invite a new member</DialogTitle>
- <DialogDescription>
- Invite a new member to this organization.
- </DialogDescription>
+ <DialogDescription>Invite a new member to this organization.</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
@@ -91,17 +80,12 @@ export function InviteMemberDialog({
type="email"
placeholder="[email protected]"
value={email}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
- setEmail(e.target.value)
- }
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="role">Role</Label>
- <Select
- value={role}
- onValueChange={(value) => setRole(value as "admin" | "member")}
- >
+ <Select value={role} onValueChange={(value) => setRole(value as "admin" | "member")}>
<SelectTrigger>
<SelectValue placeholder="Select a role" />
</SelectTrigger>
diff --git a/client/src/app/organization/members/components/RemoveMemberDialog.tsx b/client/src/app/settings/organization/members/components/RemoveMemberDialog.tsx
similarity index 100%
rename from client/src/app/organization/members/components/RemoveMemberDialog.tsx
rename to client/src/app/settings/organization/members/components/RemoveMemberDialog.tsx
diff --git a/client/src/app/organization/members/page.tsx b/client/src/app/settings/organization/members/page.tsx
similarity index 92%
rename from client/src/app/organization/members/page.tsx
rename to client/src/app/settings/organization/members/page.tsx
index 50057b9bd..c40e82d24 100644
--- a/client/src/app/organization/members/page.tsx
+++ b/client/src/app/settings/organization/members/page.tsx
@@ -1,19 +1,19 @@
"use client";
import { DateTime } from "luxon";
-import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../components/ui/table";
-import { authClient } from "../../../lib/auth";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../components/ui/table";
+import { authClient } from "../../../../lib/auth";
-import { useOrganizationMembers } from "../../../api/admin/auth";
-import { useOrganizationInvitations } from "../../../api/admin/organizations";
-import { NoOrganization } from "../../../components/NoOrganization";
+import { useOrganizationMembers } from "../../../../api/admin/auth";
+import { useOrganizationInvitations } from "../../../../api/admin/organizations";
+import { NoOrganization } from "../../../../components/NoOrganization";
import { InviteMemberDialog } from "./components/InviteMemberDialog";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { useSetPageTitle } from "../../../../hooks/useSetPageTitle";
import { EditOrganizationDialog } from "./components/EditOrganizationDialog";
import { DeleteOrganizationDialog } from "./components/DeleteOrganizationDialog";
import { RemoveMemberDialog } from "./components/RemoveMemberDialog";
import { Invitations } from "./components/Invitations";
-import { IS_CLOUD } from "../../../lib/const";
+import { IS_CLOUD } from "../../../../lib/const";
import { CreateUserDialog } from "./components/CreateUserDialog";
// Types for our component
diff --git a/client/src/app/organization/page.tsx b/client/src/app/settings/organization/page.tsx
similarity index 83%
rename from client/src/app/organization/page.tsx
rename to client/src/app/settings/organization/page.tsx
index 7ad46be0b..dfad57080 100644
--- a/client/src/app/organization/page.tsx
+++ b/client/src/app/settings/organization/page.tsx
@@ -8,7 +8,7 @@ export default function OrganizationPage() {
useEffect(() => {
// Redirect to members page by default
- router.replace("/organization/members");
+ router.replace("/settings/organization/members");
}, [router]);
return null;
diff --git a/client/src/app/organization/subscription/page.tsx b/client/src/app/settings/organization/subscription/page.tsx
similarity index 71%
rename from client/src/app/organization/subscription/page.tsx
rename to client/src/app/settings/organization/subscription/page.tsx
index 63dd68ac6..e881d7edc 100644
--- a/client/src/app/organization/subscription/page.tsx
+++ b/client/src/app/settings/organization/subscription/page.tsx
@@ -1,34 +1,26 @@
"use client";
-import {
- Card,
- CardContent,
- CardDescription,
- CardTitle,
-} from "@/components/ui/card";
+import { Card, CardContent, CardDescription, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
-import { ProPlan } from "../../../components/subscription/ProPlan";
-import { useStripeSubscription } from "../../../lib/subscription/useStripeSubscription";
-import { NoOrganization } from "../../../components/NoOrganization";
-import { TrialPlan } from "../../../components/subscription/TrialPlan";
-import { ExpiredTrialPlan } from "../../../components/subscription/ExpiredTrialPlan";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { FreePlan } from "../../../components/subscription/FreePlan";
+import { ProPlan } from "../../../../components/subscription/ProPlan";
+import { useStripeSubscription } from "../../../../lib/subscription/useStripeSubscription";
+import { NoOrganization } from "../../../../components/NoOrganization";
+import { TrialPlan } from "../../../../components/subscription/TrialPlan";
+import { ExpiredTrialPlan } from "../../../../components/subscription/ExpiredTrialPlan";
+import { useSetPageTitle } from "../../../../hooks/useSetPageTitle";
+import { FreePlan } from "../../../../components/subscription/FreePlan";
import { Building } from "lucide-react";
import { authClient } from "@/lib/auth";
export default function OrganizationSubscriptionPage() {
useSetPageTitle("Rybbit Β· Organization Subscription");
- const { data: activeSubscription, isLoading: isLoadingSubscription } =
- useStripeSubscription();
+ const { data: activeSubscription, isLoading: isLoadingSubscription } = useStripeSubscription();
const { data: activeOrg, isPending } = authClient.useActiveOrganization();
const { data: session } = authClient.useSession();
// Check if the current user is an owner by looking at the members in the active organization
- const currentUserMember = activeOrg?.members?.find(
- (member) => member.userId === session?.user?.id
- );
+ const currentUserMember = activeOrg?.members?.find((member) => member.userId === session?.user?.id);
const isOwner = currentUserMember?.role === "owner";
const isLoading = isLoadingSubscription || isPending;
@@ -36,9 +28,7 @@ export default function OrganizationSubscriptionPage() {
// Determine which plan to display
const renderPlanComponent = () => {
if (!activeOrg && !isPending) {
- return (
- <NoOrganization message="You need to select an organization to manage your subscription." />
- );
+ return <NoOrganization message="You need to select an organization to manage your subscription." />;
}
if (!isOwner) {
diff --git a/client/src/app/settings/page.tsx b/client/src/app/settings/page.tsx
new file mode 100644
index 000000000..fcdbab9c0
--- /dev/null
+++ b/client/src/app/settings/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useEffect } from "react";
+
+export default function SettingsPage() {
+ const router = useRouter();
+
+ useEffect(() => {
+ router.replace("/settings/account");
+ }, [router]);
+
+ return null;
+}
diff --git a/client/src/app/uptime/incidents/page.tsx b/client/src/app/uptime/incidents/page.tsx
new file mode 100644
index 000000000..2cdbab77d
--- /dev/null
+++ b/client/src/app/uptime/incidents/page.tsx
@@ -0,0 +1,247 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { cn } from "@/lib/utils";
+import { AlertCircle, CheckCircle, MoreHorizontal } from "lucide-react";
+import { DateTime } from "luxon";
+import { useState } from "react";
+import { toast } from "sonner";
+import {
+ UptimeIncident,
+ useAcknowledgeIncident,
+ useIncidents,
+ useResolveIncident,
+} from "../../../api/uptime/incidents";
+
+const formatStartTime = (timestamp: string) => {
+ const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).toLocal();
+ return dt.toRelative() || dt.toFormat("MMM dd, HH:mm");
+};
+
+const getStatusIcon = (status: UptimeIncident["status"]) => {
+ switch (status) {
+ case "active":
+ return (
+ <div className="p-2 rounded-lg bg-red-500/10">
+ <AlertCircle className="w-4 h-4 text-red-500" />
+ </div>
+ );
+ case "acknowledged":
+ return (
+ <div className="p-2 rounded-lg bg-yellow-500/10">
+ <AlertCircle className="w-4 h-4 text-yellow-500" />
+ </div>
+ );
+ case "resolved":
+ return (
+ <div className="p-2 rounded-lg bg-green-500/10">
+ <CheckCircle className="w-4 h-4 text-green-500" />
+ </div>
+ );
+ }
+};
+
+const formatDuration = (startTime: string, endTime: string | null): string => {
+ const start = DateTime.fromSQL(startTime, { zone: "UTC" });
+ const end = endTime ? DateTime.fromSQL(endTime, { zone: "UTC" }) : DateTime.now().toUTC();
+ const diff = end.diff(start, ["days", "hours", "minutes", "seconds"]);
+
+ const days = Math.floor(diff.days);
+ const hours = Math.floor(diff.hours);
+ const minutes = Math.floor(diff.minutes);
+ const seconds = Math.floor(diff.seconds);
+
+ let result = "";
+ if (days > 0) {
+ result = `${days}d ${hours % 24}h`;
+ } else if (hours > 0) {
+ result = `${hours}h ${minutes % 60}m`;
+ } else if (minutes > 0) {
+ result = `${minutes}m`;
+ } else {
+ result = `${seconds}s`;
+ }
+
+ return endTime ? result : `${result} (ongoing)`;
+};
+
+export default function IncidentsPage() {
+ const [statusFilter, setStatusFilter] = useState<"active" | "acknowledged" | "resolved" | "all">("active");
+
+ const { data, isLoading } = useIncidents({ status: statusFilter });
+
+ const acknowledgeIncident = useAcknowledgeIncident();
+ const resolveIncident = useResolveIncident();
+
+ const handleAcknowledge = async (incident: UptimeIncident) => {
+ try {
+ await acknowledgeIncident.mutateAsync(incident.id);
+ toast.success("Incident acknowledged");
+ } catch (error) {
+ toast.error("Failed to acknowledge incident");
+ }
+ };
+
+ const handleResolve = async (incident: UptimeIncident) => {
+ try {
+ await resolveIncident.mutateAsync(incident.id);
+ toast.success("Incident resolved");
+ } catch (error) {
+ toast.error("Failed to resolve incident");
+ }
+ };
+
+ return (
+ <>
+ <div className="flex items-center justify-between mb-6">
+ <h1 className="text-2xl font-semibold">Incidents</h1>
+
+ <Tabs value={statusFilter} onValueChange={(value) => setStatusFilter(value as any)}>
+ <TabsList>
+ <TabsTrigger value="active">Active</TabsTrigger>
+ <TabsTrigger value="acknowledged">Acknowledged</TabsTrigger>
+ <TabsTrigger value="resolved">Resolved</TabsTrigger>
+ <TabsTrigger value="all">All</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+
+ <div className="rounded-lg border border-neutral-800">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10"></TableHead>
+ <TableHead>Monitor Name</TableHead>
+ <TableHead>Affected Regions</TableHead>
+ <TableHead>Start Time</TableHead>
+ <TableHead>Duration</TableHead>
+ <TableHead className="w-10"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ Array.from({ length: 5 }).map((_, i) => (
+ <TableRow key={`skeleton-${i}`}>
+ <TableCell>
+ <Skeleton className="h-4 w-4 rounded-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-48" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-32" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-32" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-8 w-8" />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : data?.incidents?.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={6} className="text-center py-8 text-neutral-500">
+ No incidents found
+ </TableCell>
+ </TableRow>
+ ) : (
+ data?.incidents?.map((incident) => (
+ <TableRow key={incident.id}>
+ <TableCell>{getStatusIcon(incident.status)}</TableCell>
+ <TableCell>
+ <div className="font-medium">{incident.monitorName}</div>
+ </TableCell>
+ <TableCell>
+ {incident.affectedRegions && incident.affectedRegions.length > 0 ? (
+ <div className="flex flex-wrap gap-1">
+ {incident.affectedRegions.length > 3 ? (
+ <>
+ {incident.affectedRegions.slice(0, 3).map((region) => (
+ <span
+ key={region}
+ className={cn(
+ "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
+ region === "global" ? "bg-red-500/20 text-red-400" : "bg-neutral-700 text-neutral-300"
+ )}
+ >
+ {region.toUpperCase()}
+ </span>
+ ))}
+ <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full bg-neutral-700 text-neutral-300">
+ +{incident.affectedRegions.length - 3} more
+ </span>
+ </>
+ ) : (
+ incident.affectedRegions.map((region) => (
+ <span
+ key={region}
+ className={cn(
+ "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
+ region === "global" ? "bg-red-500/20 text-red-400" : "bg-neutral-700 text-neutral-300"
+ )}
+ >
+ {region.toUpperCase()}
+ </span>
+ ))
+ )}
+ </div>
+ ) : incident.region ? (
+ <span
+ className={cn(
+ "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
+ incident.region === "global"
+ ? "bg-red-500/20 text-red-400"
+ : "bg-neutral-700 text-neutral-300"
+ )}
+ >
+ {incident.region.toUpperCase()}
+ </span>
+ ) : (
+ <span className="text-neutral-500">-</span>
+ )}
+ </TableCell>
+ <TableCell className="text-sm text-neutral-300">{formatStartTime(incident.startTime)}</TableCell>
+ <TableCell>
+ <div className="text-sm text-neutral-300">
+ {formatDuration(incident.startTime, incident.endTime || null)}
+ </div>
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild disabled={incident.status === "resolved"}>
+ <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {incident.status === "active" && (
+ <DropdownMenuItem onClick={() => handleAcknowledge(incident)}>Acknowledge</DropdownMenuItem>
+ )}
+ {incident.status !== "resolved" && (
+ <DropdownMenuItem onClick={() => handleResolve(incident)}>Resolve</DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ </>
+ );
+}
diff --git a/client/src/app/uptime/layout.tsx b/client/src/app/uptime/layout.tsx
new file mode 100644
index 000000000..e62c032dd
--- /dev/null
+++ b/client/src/app/uptime/layout.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useWindowSize } from "@uidotdev/usehooks";
+import { AppSidebar } from "../../components/AppSidebar";
+import { MobileSidebar } from "./monitors/components/Sidebar/MobileSidebar";
+import { StandardPage } from "../../components/StandardPage";
+import { Sidebar } from "./monitors/components/Sidebar/Sidebar";
+
+export default function UptimeLayout({ children }: { children: React.ReactNode }) {
+ const { width } = useWindowSize();
+
+ if (width && width < 768) {
+ return (
+ <StandardPage showSidebar={false}>
+ <MobileSidebar />
+ <div className="mt-4">{children}</div>
+ </StandardPage>
+ );
+ }
+
+ return (
+ <div className="flex h-full">
+ <AppSidebar />
+ <Sidebar />
+ <StandardPage showSidebar={false}>
+ <div className="flex-1 overflow-auto mt-4">{children}</div>
+ </StandardPage>
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx
new file mode 100644
index 000000000..cc5a20dd2
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { MonitorEvent } from "@/api/uptime/monitors";
+import { TimingWaterfall } from "./TimingWaterfall";
+
+interface EventDetailsRowProps {
+ event: MonitorEvent;
+}
+
+export function EventDetailsRow({ event }: EventDetailsRowProps) {
+ return (
+ <div className="bg-neutral-900 border-t border-neutral-800 p-6">
+ <div className="space-y-6">
+ {/* Timing Waterfall */}
+ {event.monitor_type === "http" && (
+ <div className="mb-6">
+ <TimingWaterfall event={event} />
+ </div>
+ )}
+
+ {/* Error Message */}
+ {event.error_message && (
+ <div>
+ <h4 className="text-sm font-medium text-red-500 mb-2">Error Message</h4>
+ <div className="text-sm text-neutral-400 bg-neutral-900 p-3 rounded whitespace-pre-wrap font-mono">
+ {event.error_message}
+ </div>
+ </div>
+ )}
+
+ {/* Headers Table */}
+ {event.response_headers && Object.keys(event.response_headers).length > 0 && (
+ <div>
+ <h4 className="text-sm font-medium mb-2">Response Headers</h4>
+ <div className="border border-neutral-800 rounded overflow-hidden">
+ <table className="w-full text-xs">
+ <tbody>
+ {Object.entries(event.response_headers).map(([key, value], index) => (
+ <tr
+ key={key}
+ className={cn(
+ "border-b border-neutral-800",
+ index === Object.keys(event.response_headers!).length - 1 && "border-b-0"
+ )}
+ >
+ <td className="px-4 py-2 text-neutral-400 font-mono w-1/3 bg-neutral-900/50">{key}</td>
+ <td className="px-4 py-2 text-neutral-200 font-mono break-all">{value}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
new file mode 100644
index 000000000..574b3ed40
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
@@ -0,0 +1,263 @@
+"use client";
+
+import {
+ createColumnHelper,
+ flexRender,
+ getCoreRowModel,
+ getFilteredRowModel,
+ getSortedRowModel,
+ SortingState,
+ useReactTable,
+} from "@tanstack/react-table";
+import { Loader2 } from "lucide-react";
+import { DateTime } from "luxon";
+import React, { useMemo, useState } from "react";
+import { MonitorEvent, UptimeMonitor, useMonitorEventsInfinite } from "../../../../../api/uptime/monitors";
+import { Badge } from "../../../../../components/ui/badge";
+import { Button } from "../../../../../components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../../../components/ui/card";
+import { Skeleton } from "../../../../../components/ui/skeleton";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../components/ui/table";
+import { CountryFlag } from "../../../../[site]/components/shared/icons/CountryFlag";
+import { useUptimeStore } from "../../components/uptimeStore";
+import { REGIONS } from "../../const";
+import { EventDetailsRow } from "./EventDetailsRow";
+import { InlineTimingWaterfall } from "./InlineTimingWaterfall";
+
+const columnHelper = createColumnHelper<MonitorEvent>();
+
+export function EventsTable({ monitor, monitorId }: { monitor?: UptimeMonitor; monitorId: number }) {
+ const [sorting, setSorting] = useState<SortingState>([]);
+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
+ const { selectedRegion } = useUptimeStore();
+
+ const {
+ data,
+ isLoading: isLoadingEvents,
+ isFetchingNextPage,
+ hasNextPage,
+ fetchNextPage,
+ } = useMonitorEventsInfinite(monitorId, {
+ region: selectedRegion,
+ });
+
+ // Flatten all pages of events
+ const allEvents = useMemo(() => {
+ return data?.pages.flatMap((page) => page.events) || [];
+ }, [data]);
+
+ const toggleRow = (rowId: string) => {
+ const newExpanded = new Set(expandedRows);
+ if (newExpanded.has(rowId)) {
+ newExpanded.delete(rowId);
+ } else {
+ newExpanded.add(rowId);
+ }
+ setExpandedRows(newExpanded);
+ };
+
+ const columns = useMemo(
+ () => [
+ columnHelper.display({
+ id: "status",
+ header: () => <div className="w-8"></div>,
+ cell: ({ row }) => (
+ <div className="flex justify-center">
+ {row.original.status === "success" ? (
+ <div className="w-2 h-2 bg-green-500 rounded-full" />
+ ) : (
+ <div className="w-2 h-2 bg-red-500 rounded-full" />
+ )}
+ </div>
+ ),
+ size: 40,
+ }),
+ columnHelper.accessor("timestamp", {
+ header: "Time",
+ cell: ({ row }) => {
+ const timestamp = DateTime.fromSQL(row.original.timestamp, { zone: "utc" });
+ return (
+ <div className="text-sm">
+ <div className="">{timestamp.toLocal().toFormat("MMM dd, HH:mm:ss")}</div>
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("status_code", {
+ header: "Status",
+ cell: ({ row }) => {
+ const code = row.original.status_code;
+ if (!code) return <span className="text-neutral-500">-</span>;
+
+ if (code >= 500) {
+ return <Badge variant="destructive">{code}</Badge>;
+ }
+ if (code >= 400) {
+ return <Badge variant="warning">{code}</Badge>;
+ }
+ if (code >= 300) {
+ return <Badge variant="info">{code}</Badge>;
+ }
+ if (code >= 200) {
+ return <Badge variant="success">{code}</Badge>;
+ }
+ return <Badge variant="secondary">{code}</Badge>;
+ },
+ }),
+ columnHelper.accessor("response_time_ms", {
+ header: "Latency",
+ cell: ({ row }) => (
+ <span className="font-mono text-sm">
+ {row.original.response_time_ms ? `${Math.round(row.original.response_time_ms)}ms` : "-"}
+ </span>
+ ),
+ }),
+ columnHelper.display({
+ id: "timings",
+ header: "Timings",
+ cell: ({ row }) => <InlineTimingWaterfall event={row.original} />,
+ }),
+ // Conditionally add region column for global monitoring
+ ...(monitor?.monitoringType === "global"
+ ? [
+ columnHelper.accessor("region", {
+ header: "Region",
+ cell: ({ row }) => {
+ const region = REGIONS.find((r) => r.code === row.original.region);
+ return (
+ <span className="text-sm flex items-center gap-2">
+ <CountryFlag country={region?.countryCode || "US"} className="w-5 h-5" />
+ <span className="text-sm">{region?.name || "-"}</span>
+ </span>
+ );
+ },
+ }),
+ ]
+ : []),
+ ],
+ [monitor?.monitoringType]
+ );
+
+ // Create table instance
+ const table = useReactTable({
+ data: allEvents,
+ columns,
+ state: {
+ sorting,
+ },
+ onSortingChange: setSorting,
+ getCoreRowModel: getCoreRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ manualPagination: true,
+ });
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Recent Events</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="rounded-lg border border-neutral-800">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead
+ key={header.id}
+ style={{
+ width: header.getSize() === 150 ? undefined : header.getSize(),
+ }}
+ >
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {isLoadingEvents ? (
+ Array.from({ length: 10 }).map((_, i) => (
+ <TableRow key={`skeleton-${i}`}>
+ {/* Status dot */}
+ <TableCell className="w-10">
+ <div className="flex justify-center">
+ <Skeleton className="h-2 w-2 rounded-full" />
+ </div>
+ </TableCell>
+ {/* Time */}
+ <TableCell>
+ <Skeleton className="h-4 w-32" />
+ </TableCell>
+ {/* Status Code */}
+ <TableCell>
+ <Skeleton className="h-6 w-12" />
+ </TableCell>
+ {/* Latency */}
+ <TableCell>
+ <Skeleton className="h-4 w-16" />
+ </TableCell>
+ {/* Timings */}
+ <TableCell>
+ <Skeleton className="h-3 w-24" />
+ </TableCell>
+ {/* Region - only show for global monitoring */}
+ {monitor?.monitoringType === "global" && (
+ <TableCell>
+ <Skeleton className="h-4 w-12" />
+ </TableCell>
+ )}
+ </TableRow>
+ ))
+ ) : table.getRowModel().rows.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="text-center text-neutral-500 py-8">
+ No events found
+ </TableCell>
+ </TableRow>
+ ) : (
+ table.getRowModel().rows.map((row) => (
+ <React.Fragment key={row.id}>
+ <TableRow className="cursor-pointer hover:bg-neutral-900/50" onClick={() => toggleRow(row.id)}>
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
+ ))}
+ </TableRow>
+
+ {expandedRows.has(row.id) && (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="p-0">
+ <EventDetailsRow event={row.original} />
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+
+ {/* Infinite scroll loader */}
+ {isFetchingNextPage && (
+ <div className="flex justify-center">
+ <Button variant="ghost" size="sm" disabled>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Loading more events...
+ </Button>
+ </div>
+ )}
+
+ {/* Load more button (as fallback) */}
+ {hasNextPage && !isFetchingNextPage && (
+ <div className="flex justify-center">
+ <Button variant="outline" size="sm" onClick={() => fetchNextPage()}>
+ Load More
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx b/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx
new file mode 100644
index 000000000..ce82f9466
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { CountryFlag } from "@/app/[site]/components/shared/icons/CountryFlag";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Earth } from "lucide-react";
+import { UptimeMonitor } from "../../../../../api/uptime/monitors";
+import { TIME_RANGES, useUptimeStore } from "../../components/uptimeStore";
+import { REGIONS } from "../../const";
+
+interface FilterBarProps {
+ monitor?: UptimeMonitor;
+ isLoading: boolean;
+}
+
+export function FilterBar({ monitor, isLoading }: FilterBarProps) {
+ const { timeRange, setTimeRange, selectedRegion, setSelectedRegion } = useUptimeStore();
+
+ // Only show region filter for global monitors (multi-region)
+ const showRegionFilter = monitor?.monitoringType === "global";
+
+ return (
+ <div className="flex items-center gap-2 justify-between">
+ {/* Time Range Selector */}
+ <div className="flex items-center gap-1">
+ {TIME_RANGES.map((range) => (
+ <Button
+ key={range.value}
+ variant={timeRange === range.value ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setTimeRange(range.value)}
+ className="h-7 px-2 text-xs"
+ >
+ {range.label}
+ </Button>
+ ))}
+ </div>
+
+ {/* Region Filter - only show for multi-region monitors */}
+ {showRegionFilter && !isLoading && (
+ <Select
+ value={selectedRegion || "all"}
+ onValueChange={(value) => setSelectedRegion(value === "all" ? undefined : value)}
+ >
+ <SelectTrigger size="sm" className="w-[140px] ml-2">
+ <SelectValue placeholder="Select region" />
+ </SelectTrigger>
+ <SelectContent size="sm">
+ {REGIONS.filter((region, i) => i === 0 || monitor?.selectedRegions.includes(region.code)).map((region) => (
+ <SelectItem key={region.code} value={region.code} size="sm">
+ <div className="flex items-center gap-2">
+ {region.countryCode ? (
+ <CountryFlag country={region.countryCode} className="w-4 h-3" />
+ ) : (
+ <Earth className="w-4 h-4" />
+ )}
+ <span>{region.name}</span>
+ </div>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx b/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx
new file mode 100644
index 000000000..3d102c809
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { MonitorEvent } from "@/api/uptime/monitors";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { getTimingSegments, renderTimingSegments, TimingSegment } from "./timingUtils";
+
+interface InlineTimingWaterfallProps {
+ event: MonitorEvent;
+}
+
+function renderInlineSegment(
+ timing: TimingSegment,
+ props: { left: number; width: number; zIndex: number; index: number }
+) {
+ return (
+ <Tooltip key={timing.label}>
+ <TooltipTrigger asChild>
+ <div
+ className={cn("absolute h-full", timing.color)}
+ style={{
+ left: `${props.left}%`,
+ width: `${props.width}%`,
+ zIndex: props.zIndex,
+ }}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-xs">
+ <div className="font-medium">{timing.label}</div>
+ <div className="font-mono">{timing.time}ms</div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+export function InlineTimingWaterfall({ event }: InlineTimingWaterfallProps) {
+ const timings = getTimingSegments(event);
+ const totalTime = event.response_time_ms || 0;
+
+ if (timings.length === 0 || totalTime === 0) {
+ return <div className="w-24 h-3" />;
+ }
+
+ return (
+ <TooltipProvider>
+ <div className="relative h-3 w-40 bg-neutral-800 rounded overflow-hidden">
+ {renderTimingSegments(timings, totalTime, renderInlineSegment)}
+ </div>
+ </TooltipProvider>
+ );
+}
\ No newline at end of file
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx b/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx
new file mode 100644
index 000000000..87e2ff633
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { MonitorEvent } from "@/api/uptime/monitors";
+import { getTimingSegments, renderTimingSegments, TimingSegment } from "./timingUtils";
+
+interface TimingWaterfallProps {
+ event: MonitorEvent;
+}
+
+function renderWaterfallSegment(
+ timing: TimingSegment,
+ props: { left: number; width: number; zIndex: number; index: number }
+) {
+ return (
+ <div
+ key={timing.label}
+ className={cn("absolute h-full", timing.color)}
+ style={{
+ left: `${props.left}%`,
+ width: `${props.width}%`,
+ zIndex: props.zIndex,
+ }}
+ title={`${timing.label}: ${timing.time}ms`}
+ />
+ );
+}
+
+function TimingLegendItem({ timing }: { timing: TimingSegment }) {
+ return (
+ <div className="flex items-center gap-1 text-xs">
+ <div className={cn("w-3 h-3 rounded", timing.color)} />
+ <span className="text-neutral-400">{timing.label}:</span>
+ <span className="font-mono">{timing.time}ms</span>
+ </div>
+ );
+}
+
+export function TimingWaterfall({ event }: TimingWaterfallProps) {
+ const timings = getTimingSegments(event);
+ const totalTime = event.response_time_ms || 0;
+
+ if (timings.length === 0 || totalTime === 0) {
+ return null;
+ }
+
+ return (
+ <div className="w-full">
+ <div className="text-sm font-medium mb-2">Timings</div>
+ <div className="relative h-6 bg-neutral-800 rounded overflow-hidden">
+ {renderTimingSegments(timings, totalTime, renderWaterfallSegment)}
+ </div>
+ <div className="flex flex-wrap gap-2 mt-2">
+ {timings.map((timing) => (
+ <TimingLegendItem key={timing.label} timing={timing} />
+ ))}
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts b/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts
new file mode 100644
index 000000000..a609e78fe
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts
@@ -0,0 +1,78 @@
+import { MonitorEvent } from "@/api/uptime/monitors";
+
+export interface TimingSegment {
+ label: string;
+ time: number | undefined;
+ color: string;
+}
+
+export const TIMING_COLORS = {
+ dns: "bg-emerald-500", // Green - similar to hsl(160, 70%, 50%)
+ tcp: "bg-teal-500", // Turquoise - similar to hsl(180, 70%, 45%)
+ tls: "bg-sky-500", // Light Blue - similar to hsl(200, 70%, 45%)
+ ttfb: "bg-blue-500", // Blue - for TTFB (not in chart but fits the gradient)
+ transfer: "bg-indigo-500", // Deeper Blue - similar to hsl(220, 70%, 50%)
+} as const;
+
+export function getTimingSegments(event: MonitorEvent): TimingSegment[] {
+ return [
+ { label: "DNS", time: event.dns_time_ms, color: TIMING_COLORS.dns },
+ { label: "TCP", time: event.tcp_time_ms, color: TIMING_COLORS.tcp },
+ { label: "TLS", time: event.tls_time_ms, color: TIMING_COLORS.tls },
+ { label: "TTFB", time: event.ttfb_ms, color: TIMING_COLORS.ttfb },
+ { label: "Transfer", time: event.transfer_time_ms, color: TIMING_COLORS.transfer },
+ ].filter((t) => t.time && t.time > 0);
+}
+
+export function calculateTimingMetrics(timings: TimingSegment[], totalTime: number) {
+ const sumOfTimings = timings.reduce((sum, t) => sum + (t.time || 0), 0);
+ const needsNormalization = sumOfTimings > totalTime;
+
+ return {
+ sumOfTimings,
+ needsNormalization,
+ };
+}
+
+export function calculateSegmentWidth(
+ timing: TimingSegment,
+ totalTime: number,
+ sumOfTimings: number,
+ needsNormalization: boolean
+): number {
+ if (!timing.time) return 0;
+
+ return needsNormalization ? (timing.time / sumOfTimings) * 100 : (timing.time / totalTime) * 100;
+}
+
+export function renderTimingSegments(
+ timings: TimingSegment[],
+ totalTime: number,
+ renderSegment: (
+ segment: TimingSegment,
+ props: {
+ left: number;
+ width: number;
+ zIndex: number;
+ index: number;
+ }
+ ) => React.ReactNode
+): React.ReactNode[] {
+ const { sumOfTimings, needsNormalization } = calculateTimingMetrics(timings, totalTime);
+
+ let left = 0;
+ return timings.map((timing, index) => {
+ const width = calculateSegmentWidth(timing, totalTime, sumOfTimings, needsNormalization);
+ const adjustedWidth = Math.min(width, 100 - left);
+
+ const element = renderSegment(timing, {
+ left,
+ width: adjustedWidth,
+ zIndex: timings.length - index,
+ index,
+ });
+
+ left += adjustedWidth;
+ return element;
+ });
+}
diff --git a/client/src/app/uptime/monitors/[monitorId]/page.tsx b/client/src/app/uptime/monitors/[monitorId]/page.tsx
new file mode 100644
index 000000000..828bd11ef
--- /dev/null
+++ b/client/src/app/uptime/monitors/[monitorId]/page.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { cn } from "@/lib/utils";
+import { ArrowLeft } from "lucide-react";
+import { useParams, useRouter } from "next/navigation";
+import { UptimeMonitor, useMonitor, useMonitorStats, useMonitorUptime } from "../../../../api/uptime/monitors";
+import { StandardPage } from "../../../../components/StandardPage";
+import { INTERVAL_OPTIONS } from "../components/dialog/GeneralTab";
+import { MonitorActions } from "../components/MonitorActions";
+import { MonitorResponseTimeChart } from "../components/MonitorResponseTimeChart";
+import { StatusOrb } from "../components/StatusOrb";
+import { useUptimeStore } from "../components/uptimeStore";
+import { getHoursFromTimeRange } from "../components/utils";
+import { EventsTable } from "./components/EventsTable";
+import { FilterBar } from "./components/FilterBar";
+
+interface StatCardProps {
+ label: string;
+ value: string;
+ isLoading?: boolean;
+}
+
+const formatResponseTime = (value?: number) => {
+ if (!value) return "-";
+ return `${Math.round(value)}ms`;
+};
+
+const formatPercentage = (value?: number) => {
+ if (!value) return "-";
+ return `${value.toFixed(1)}%`;
+};
+
+const formatUptime = (seconds?: number) => {
+ if (!seconds) return "-";
+ const days = Math.floor(seconds / 86400);
+ const hours = Math.floor((seconds % 86400) / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+
+ if (days > 0) {
+ return `${days}d ${hours}h`;
+ }
+ if (hours > 0) {
+ return `${hours}h ${minutes}m`;
+ }
+ return `${minutes}m`;
+};
+
+const formatInterval = (seconds?: number) => {
+ const interval = INTERVAL_OPTIONS.find((interval) => interval.value === seconds);
+ return interval?.label || `${seconds}s`;
+};
+
+function StatCard({ label, value, isLoading }: StatCardProps) {
+ return (
+ <div className="bg-neutral-900 rounded-lg border border-neutral-850">
+ <div className="p-3 pb-0 text-sm text-neutral-500 flex items-center gap-2 font-normal">{label}</div>
+ <div className="p-3 py-2">
+ {isLoading ? <Skeleton className="h-7 w-24" /> : <p className="text-xl font-semibold">{value}</p>}
+ </div>
+ </div>
+ );
+}
+
+const getMonitorName = (monitor: UptimeMonitor) => {
+ return (
+ monitor.name ||
+ (monitor.monitorType === "http" ? monitor.httpConfig?.url : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`)
+ );
+};
+
+const MonitorHeader = ({ monitor, isLoadingMonitor }: { monitor?: UptimeMonitor; isLoadingMonitor: boolean }) => {
+ if (isLoadingMonitor) {
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-7 w-64" /> {/* Monitor name */}
+ <Skeleton className="h-4 w-4 rounded-full" /> {/* Status orb */}
+ </div>
+ <div className="flex items-center gap-2 mt-1">
+ <Skeleton className="h-4 w-4" /> {/* Status text */}
+ <span className="text-neutral-500">β€’</span>
+ <Skeleton className="h-4 w-40" /> {/* URL/host */}
+ <span className="text-neutral-500">β€’</span>
+ <Skeleton className="h-4 w-28" /> {/* Interval */}
+ </div>
+ </div>
+ );
+ }
+ if (!monitor) return null;
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-3">
+ <h1 className="text-2xl font-semibold">{getMonitorName(monitor)}</h1>
+ <StatusOrb status={monitor.status?.currentStatus || "unknown"} size="lg" />
+ </div>
+ <p className="text-sm text-neutral-300 mt-1 flex items-center gap-2">
+ <span
+ className={cn("font-medium", monitor.status?.currentStatus === "up" ? "text-green-400" : "text-red-500/80")}
+ >
+ {monitor.status?.currentStatus === "up" ? "Up" : "Down"}
+ </span>
+ β€’
+ <span>
+ {monitor.monitorType === "http"
+ ? monitor.httpConfig?.url
+ : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`}
+ </span>
+ β€’<span>every {formatInterval(monitor.intervalSeconds)}</span>
+ </p>
+ </div>
+ );
+};
+
+export default function MonitorDetailPage() {
+ const params = useParams();
+ const router = useRouter();
+ const monitorId = parseInt(params.monitorId as string);
+
+ const { timeRange, selectedRegion } = useUptimeStore();
+ const { data: monitor, isLoading: isLoadingMonitor } = useMonitor(monitorId);
+ const { data: stats, isLoading: isLoadingStats } = useMonitorStats(monitorId, {
+ hours: getHoursFromTimeRange(timeRange),
+ region: selectedRegion,
+ });
+
+ const { data: uptimeData, isLoading: isLoadingUptime } = useMonitorUptime(monitorId);
+
+ if (!monitor && !isLoadingMonitor) {
+ return (
+ <StandardPage showSidebar={false}>
+ <div className="text-center py-12">
+ <h2 className="text-xl font-semibold mb-2">Monitor not found</h2>
+ <Button onClick={() => router.push("/uptime")} variant="outline">
+ Back to Monitors
+ </Button>
+ </div>
+ </StandardPage>
+ );
+ }
+
+ return (
+ <>
+ <div className="space-y-4">
+ {/* Header */}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => router.push("/uptime/monitors")}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ <div className="flex items-start justify-between">
+ <MonitorHeader monitor={monitor} isLoadingMonitor={isLoadingMonitor} />
+ <MonitorActions monitor={monitor} />
+ </div>
+ <FilterBar monitor={monitor} isLoading={isLoadingMonitor} />
+
+ {/* Stats Grid */}
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
+ <StatCard label="Uptime" value={formatPercentage(stats?.stats.uptimePercentage)} isLoading={isLoadingStats} />
+ <StatCard
+ label="Current Uptime"
+ value={formatUptime(uptimeData?.currentUptimeSeconds)}
+ isLoading={isLoadingUptime}
+ />
+ <StatCard label="P50" value={formatResponseTime(stats?.stats.responseTime.p50)} isLoading={isLoadingStats} />
+ <StatCard label="P90" value={formatResponseTime(stats?.stats.responseTime.p90)} isLoading={isLoadingStats} />
+ <StatCard label="P95" value={formatResponseTime(stats?.stats.responseTime.p95)} isLoading={isLoadingStats} />
+ <StatCard label="P99" value={formatResponseTime(stats?.stats.responseTime.p99)} isLoading={isLoadingStats} />
+ </div>
+
+ {/* Response Time Chart */}
+ <MonitorResponseTimeChart monitor={monitor} monitorId={monitorId} isLoading={isLoadingMonitor} />
+ <EventsTable monitor={monitor} monitorId={monitorId} />
+ </div>
+ </>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/MonitorActions.tsx b/client/src/app/uptime/monitors/components/MonitorActions.tsx
new file mode 100644
index 000000000..503ee5667
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/MonitorActions.tsx
@@ -0,0 +1,127 @@
+import { Edit2, MoreVertical, Power, Trash2 } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { UptimeMonitor, useDeleteMonitor, useUpdateMonitor } from "../../../../api/uptime/monitors";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "../../../../components/ui/alert-dialog";
+import { Button } from "../../../../components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "../../../../components/ui/dropdown-menu";
+import { cn } from "../../../../lib/utils";
+import { MonitorDialog } from "./dialog";
+
+export function MonitorActions({ monitor }: { monitor?: UptimeMonitor }) {
+ const router = useRouter();
+ const [showEditDialog, setShowEditDialog] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [isToggling, setIsToggling] = useState(false);
+
+ const deleteMonitor = useDeleteMonitor();
+ const updateMonitor = useUpdateMonitor();
+
+ const handleToggle = async () => {
+ if (!monitor) return;
+
+ setIsToggling(true);
+ try {
+ await updateMonitor.mutateAsync({
+ monitorId: monitor.id,
+ data: { enabled: !monitor.enabled },
+ });
+ toast.success(`Monitor ${monitor.enabled ? "disabled" : "enabled"} successfully`);
+ } catch (error: any) {
+ toast.error(error.response?.data?.error || "Failed to update monitor");
+ } finally {
+ setIsToggling(false);
+ }
+ };
+
+ const handleDelete = async () => {
+ try {
+ await deleteMonitor.mutateAsync(monitor?.id ?? 0);
+ toast.success("Monitor deleted successfully");
+ router.push("/uptime/monitors");
+ } catch (error: any) {
+ toast.error(error.response?.data?.error || "Failed to delete monitor");
+ }
+ };
+
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ {monitor && (
+ <Button
+ size="sm"
+ onClick={handleToggle}
+ disabled={isToggling || !monitor}
+ className={cn(
+ "flex items-center gap-2",
+ monitor?.enabled
+ ? "dark:text-green-500 hover:dark:text-green-600"
+ : "text-neutral-500 hover:text-neutral-400"
+ )}
+ >
+ <Power className="h-4 w-4" />
+ {monitor?.enabled ? "On" : "Off"}
+ </Button>
+ )}
+ <Button size="sm" onClick={() => setShowEditDialog(true)} className="flex items-center gap-2">
+ <Edit2 className="h-4 w-4" />
+ Edit
+ </Button>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
+ <MoreVertical className="h-4 w-4" />
+ <span className="sr-only">Open menu</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setShowDeleteDialog(true)} className="text-red-500 focus:text-red-600">
+ <Trash2 className="mr-2 h-4 w-4" />
+ Delete Monitor
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ {monitor && <MonitorDialog monitor={monitor} open={showEditDialog} onOpenChange={setShowEditDialog} />}
+
+ {/* Delete Confirmation */}
+ <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Are you sure?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will permanently delete the monitor "
+ {monitor?.name ||
+ (monitor?.monitorType === "http"
+ ? monitor?.httpConfig?.url
+ : `${monitor?.tcpConfig?.host}:${monitor?.tcpConfig?.port}`)}
+ " and all its historical data. This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={handleDelete} variant={"destructive"}>
+ Delete Monitor
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx b/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
new file mode 100644
index 000000000..fd9da91e7
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
@@ -0,0 +1,421 @@
+"use client";
+
+import { UptimeMonitor, useMonitorStats } from "@/api/uptime/monitors";
+import { Card, CardContent } from "@/components/ui/card";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
+import { nivoTheme } from "@/lib/nivo";
+import { cn } from "@/lib/utils";
+import { ResponsiveLine } from "@nivo/line";
+import { DateTime } from "luxon";
+import { useEffect, useState } from "react";
+import { UptimeBucketSelection } from "./UptimeBucketSelection";
+import { useUptimeStore } from "./uptimeStore";
+import { getHoursFromTimeRange } from "./utils";
+
+const MONITOR_COLORS = {
+ dns: "hsl(160, 70%, 50%)",
+ connection: "hsl(180, 70%, 45%)",
+ tls: "hsl(200, 70%, 45%)",
+ transfer: "hsl(220, 70%, 50%)",
+} as const;
+
+// HTTP timing metrics with labels for stacked view - gradient from green-turquoise to blue
+const HTTP_METRICS = [
+ { key: "dns_time_ms", label: "DNS", color: MONITOR_COLORS.dns }, // Green
+ { key: "tcp_time_ms", label: "Connection", color: MONITOR_COLORS.connection }, // Turquoise
+ { key: "tls_time_ms", label: "TLS Handshake", color: MONITOR_COLORS.tls }, // Light Blue
+ { key: "transfer_time_ms", label: "Data Transfer", color: MONITOR_COLORS.transfer }, // Blue
+] as const;
+
+const formatTooltipValue = (value: number) => {
+ return `${Math.round(value)}ms`;
+};
+
+export function MonitorResponseTimeChart({
+ monitor,
+ monitorId,
+ isLoading: isLoadingMonitor,
+}: {
+ monitor?: UptimeMonitor;
+ monitorId: number;
+ isLoading: boolean;
+}) {
+ const monitorType = monitor?.monitorType;
+
+ const { timeRange, bucket, setBucket, selectedRegion } = useUptimeStore();
+
+ const [visibleMetrics, setVisibleMetrics] = useState<Set<string>>(new Set());
+
+ useEffect(() => {
+ if (monitorType === "http") {
+ setVisibleMetrics(new Set(HTTP_METRICS.map((m) => m.key)));
+ } else {
+ setVisibleMetrics(new Set(["response_time_ms"]));
+ }
+ }, [monitorType]);
+
+ const { data: statsData, isLoading } = useMonitorStats(monitorId, {
+ hours: getHoursFromTimeRange(timeRange),
+ bucket,
+ region: selectedRegion,
+ });
+
+ const toggleMetric = (metricKey: string) => {
+ setVisibleMetrics((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(metricKey)) {
+ newSet.delete(metricKey);
+ } else {
+ newSet.add(metricKey);
+ }
+ return newSet;
+ });
+ };
+
+ // Process data for the chart
+ const processedData =
+ statsData?.distribution
+ ?.map((item: any) => {
+ if (!item.hour) return null;
+
+ const timestamp = DateTime.fromSQL(item.hour, { zone: "utc" }).toLocal();
+ if (!timestamp.isValid) return null;
+
+ const dataPoint: any = {
+ time: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ timestamp: timestamp.toISO(), // Store ISO timestamp for proper timezone handling
+ response_time_ms: item.avg_response_time,
+ check_count: item.check_count || 0,
+ success_count: item.success_count || 0,
+ failure_count: item.failure_count || 0,
+ timeout_count: item.timeout_count || 0,
+ };
+
+ // Calculate failure percentage
+ dataPoint.failure_percentage =
+ dataPoint.check_count > 0
+ ? ((dataPoint.failure_count + dataPoint.timeout_count) / dataPoint.check_count) * 100
+ : 0;
+
+ // For HTTP monitors, include additional timing data
+ if (monitorType === "http") {
+ dataPoint.dns_time_ms = item.avg_dns_time || 0;
+ dataPoint.tcp_time_ms = item.avg_tcp_time || 0;
+ dataPoint.tls_time_ms = item.avg_tls_time || 0;
+ dataPoint.ttfb_ms = item.avg_ttfb || 0;
+ dataPoint.transfer_time_ms = item.avg_transfer_time || 0;
+ }
+
+ return dataPoint;
+ })
+ .filter((e: any) => e !== null)
+ .reverse() ?? []; // Reverse to get chronological order (oldest first)
+
+ // Create data series based on monitor type
+ const createDataSeries = () => {
+ if (monitorType === "tcp") {
+ return [
+ {
+ id: "Response Time",
+ color: "hsl(180, 70%, 45%)",
+ data: processedData
+ .map((item: any) => ({
+ x: item.time,
+ y: item.response_time_ms,
+ }))
+ .filter((point: any) => point.y !== null && point.y > 0),
+ },
+ ];
+ }
+
+ // For HTTP, show stacked timing metrics
+ // Order matters for stacking - DNS first, then connection, TLS, and finally transfer
+ return HTTP_METRICS.filter((metric) => visibleMetrics.has(metric.key)).map((metric) => ({
+ id: metric.label,
+ color: metric.color,
+ data: processedData
+ .map((item: any) => ({
+ x: item.time,
+ y: item[metric.key] || 0,
+ }))
+ .filter((point: any) => point.y !== null),
+ }));
+ };
+
+ const data = createDataSeries();
+
+ // Define gradients for stacked areas with lower opacity - gradient from green-turquoise to blue
+ const defs =
+ monitorType === "http"
+ ? [
+ {
+ id: "gradientDNS",
+ type: "linearGradient" as const,
+ colors: [{ offset: 0, color: MONITOR_COLORS.dns, opacity: 0.1 }],
+ },
+ {
+ id: "gradientConnection",
+ type: "linearGradient" as const,
+ colors: [{ offset: 0, color: MONITOR_COLORS.connection, opacity: 0.1 }],
+ },
+ {
+ id: "gradientTLS",
+ type: "linearGradient" as const,
+ colors: [{ offset: 0, color: MONITOR_COLORS.tls, opacity: 0.1 }],
+ },
+ {
+ id: "gradientTransfer",
+ type: "linearGradient" as const,
+ colors: [{ offset: 0, color: MONITOR_COLORS.transfer, opacity: 0.1 }],
+ },
+ ]
+ : [];
+
+ const fill =
+ monitorType === "http"
+ ? [
+ { match: { id: "DNS" }, id: "gradientDNS" },
+ { match: { id: "Connection" }, id: "gradientConnection" },
+ { match: { id: "TLS Handshake" }, id: "gradientTLS" },
+ { match: { id: "Data Transfer" }, id: "gradientTransfer" },
+ ]
+ : [];
+
+ const formatXAxisValue = (value: Date) => {
+ const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+
+ // Format based on bucket size
+ switch (bucket) {
+ case "minute":
+ case "five_minutes":
+ case "ten_minutes":
+ case "fifteen_minutes":
+ return dt.toFormat(hour12 ? "h:mma" : "HH:mm");
+ case "hour":
+ if (timeRange === "24h") {
+ return dt.toFormat(hour12 ? "ha" : "HH:mm");
+ }
+ return dt.toFormat(hour12 ? "MMM d, ha" : "dd MMM, HH:mm");
+ case "day":
+ return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
+ case "week":
+ return dt.toFormat("MMM d");
+ case "month":
+ return dt.toFormat("MMM yyyy");
+ default:
+ return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
+ }
+ };
+
+ return (
+ <Card className="overflow-visible">
+ <CardContent className="p-4 overflow-visible">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-base font-medium">Response Time</h3>
+
+ <div className="flex items-center gap-4">
+ {/* Metric toggles for HTTP monitors */}
+ {monitorType === "http" && (
+ <div className="flex items-center gap-2">
+ {HTTP_METRICS.map((metric) => {
+ const isVisible = visibleMetrics.has(metric.key);
+ return (
+ <button
+ key={metric.key}
+ onClick={() => toggleMetric(metric.key)}
+ className={cn(
+ "flex items-center space-x-1.5 px-2 py-1 rounded text-xs font-medium transition-all",
+ isVisible
+ ? "bg-neutral-800 text-white"
+ : "bg-neutral-900 text-neutral-500 hover:text-neutral-400"
+ )}
+ >
+ <div
+ className={cn(
+ "w-3 h-3 rounded-sm transition-opacity",
+ isVisible ? "opacity-100" : "opacity-30"
+ )}
+ style={{ backgroundColor: metric.color }}
+ />
+ <span>{metric.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Time range and bucket selectors */}
+ <div className="flex items-center gap-2">
+ <UptimeBucketSelection timeRange={timeRange} bucket={bucket} onBucketChange={setBucket} />
+ </div>
+ </div>
+ </div>
+
+ {isLoadingMonitor || isLoading ? (
+ <Skeleton className="w-full h-[400px] rounded-md" />
+ ) : data.length === 0 || data.every((series) => series.data.length === 0) ? (
+ <div className="h-[400px] w-full flex items-center justify-center">
+ <div className="text-center text-neutral-500">
+ <p className="text-lg font-medium">No data available</p>
+ <p className="text-sm">Try adjusting your time range</p>
+ </div>
+ </div>
+ ) : (
+ <div className="h-[400px] w-full relative" style={{ overflow: "visible", zIndex: 10 }}>
+ <ResponsiveLine
+ data={data}
+ theme={{ ...nivoTheme }}
+ margin={{ top: 10, right: 20, bottom: 25, left: 50 }}
+ defs={defs}
+ fill={fill}
+ xScale={{
+ type: "time",
+ precision: "second",
+ format: "%Y-%m-%d %H:%M:%S",
+ useUTC: false,
+ }}
+ yScale={{
+ type: "linear",
+ min: 0,
+ stacked: monitorType === "http",
+ reverse: false,
+ }}
+ enableGridX={false}
+ enableGridY={true}
+ gridYValues={5}
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ format: formatXAxisValue,
+ }}
+ axisLeft={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: 5,
+ format: (value) => `${value}ms`,
+ }}
+ colors={(d) => d.color}
+ lineWidth={1}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices="x"
+ enableArea={monitorType === "http"}
+ areaOpacity={0.7}
+ layers={[
+ "grid",
+ "axes",
+ "areas",
+ // Custom layer for failure indicators - render AFTER areas and lines
+ ({ innerHeight, xScale }) => (
+ <>
+ {processedData.map((point: any, index: number) => {
+ if (point.failure_percentage === 0) return null;
+
+ // Use the jsDate for proper timezone handling
+ const x = xScale(point.jsDate);
+
+ // Calculate width based on next point or use a default
+ let width = 20; // Default width
+ if (index < processedData.length - 1) {
+ const nextPoint = processedData[index + 1];
+ width = Math.abs(xScale(nextPoint.jsDate) - x);
+ } else if (index > 0) {
+ // For the last point, use the width from the previous interval
+ const prevPoint = processedData[index - 1];
+ width = Math.abs(x - xScale(prevPoint.jsDate));
+ }
+
+ // Determine color based on failure percentage
+ let color = "hsla(48, 95%, 53%, 0.4)"; // Yellow for < 50%
+ if (point.failure_percentage >= 50) {
+ color = `hsla(0, 84%, 60%, 0.4)`; // Red for >= 50%
+ }
+
+ return (
+ <rect
+ key={`failure-${index}`}
+ x={x}
+ y={0}
+ width={Math.max(1, Math.abs(width))}
+ height={innerHeight}
+ fill={color}
+ />
+ );
+ })}
+ </>
+ ),
+ "crosshair",
+ "lines",
+ "slices",
+ "points",
+ "mesh",
+ "legends",
+ ]}
+ sliceTooltip={({ slice }: any) => {
+ const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x));
+
+ // Find the corresponding data point to get failure info
+ const dataPoint = processedData.find(
+ (p: any) => DateTime.fromISO(p.timestamp).toMillis() === currentTime.toMillis()
+ );
+
+ // For stacked HTTP charts, show cumulative total
+ const total =
+ monitorType === "http"
+ ? slice.points.reduce((sum: number, point: any) => sum + Number(point.data.yFormatted), 0)
+ : 0;
+
+ return (
+ <div className="text-sm bg-neutral-850 p-3 rounded-md min-w-[200px] border border-neutral-750 text-neutral-200">
+ {formatChartDateTime(currentTime, bucket)}
+
+ {/* Show failure status if any failures */}
+ {dataPoint && dataPoint.failure_percentage > 0 && (
+ <div
+ className={cn(
+ "text-xs px-2 py-1 rounded mt-2 mb-2",
+ dataPoint.failure_percentage >= 50
+ ? "bg-red-500/20 text-red-400"
+ : "bg-yellow-500/20 text-yellow-400"
+ )}
+ >
+ {dataPoint.failure_count + dataPoint.timeout_count} of {dataPoint.check_count} checks failed (
+ {dataPoint.failure_percentage.toFixed(1)}%)
+ </div>
+ )}
+
+ <div className="space-y-1.5 mt-2 text-xs">
+ {slice.points.map((point: any) => (
+ <div key={point.seriesId} className="flex justify-between items-center">
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-sm" style={{ backgroundColor: point.seriesColor }} />
+ <span className="text-neutral-300">{point.seriesId}</span>
+ </div>
+ <span className="text-neutral-200">{formatTooltipValue(Number(point.data.yFormatted))}</span>
+ </div>
+ ))}
+ {monitorType === "http" && (
+ <div className="flex justify-between items-center pt-1.5 border-t border-neutral-700">
+ <span className="text-neutral-300">Total</span>
+ <span className="text-white font-medium">{formatTooltipValue(total)}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }}
+ />
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/MonitorTableRow.tsx b/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
new file mode 100644
index 000000000..1a8b0b864
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
@@ -0,0 +1,104 @@
+import React from "react";
+import { DateTime } from "luxon";
+import { TableCell, TableRow } from "@/components/ui/table";
+import { StatusOrb } from "./StatusOrb";
+import { UptimeBar } from "./UptimeBar";
+import { UptimeMonitor, useMonitorUptime } from "@/api/uptime/monitors";
+import { cn } from "@/lib/utils";
+import { Skeleton } from "@/components/ui/skeleton";
+
+interface MonitorTableRowProps {
+ monitor: UptimeMonitor;
+ onClick?: () => void;
+}
+
+const formatResponseTime = (value?: number) => {
+ if (value === undefined || value === null) return "-";
+ return `${Math.round(value)}ms`;
+};
+
+const formatPercentage = (value?: number) => {
+ if (value === undefined || value === null) return "-";
+ return `${value.toFixed(1)}%`;
+};
+
+const formatLastPing = (lastCheckedAt?: string) => {
+ if (!lastCheckedAt) return "-";
+
+ const lastPing = DateTime.fromSQL(lastCheckedAt, {
+ zone: "utc",
+ }).toLocal();
+
+ const now = DateTime.now();
+ const diffMs = now.toMillis() - lastPing.toMillis();
+
+ const seconds = Math.floor(diffMs / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ago`;
+ if (hours > 0) return `${hours}h ago`;
+ if (minutes > 0) return `${minutes}m ago`;
+ if (seconds > 0) return `${seconds}s ago`;
+ return "just now";
+};
+
+const formatUptime = (seconds: number): string => {
+ const days = Math.floor(seconds / 86400);
+ const hours = Math.floor((seconds % 86400) / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+
+ if (days > 0) {
+ return `${days}d ${hours}h`;
+ }
+ if (hours > 0) {
+ return `${hours}h ${minutes}m`;
+ }
+ return `${minutes}m`;
+};
+
+export function MonitorTableRow({ monitor, onClick }: MonitorTableRowProps) {
+ const stats = monitor.status;
+ const { data: uptimeData, isLoading: isLoadingUptime } = useMonitorUptime(monitor.id);
+
+ return (
+ <TableRow className="cursor-pointer hover:bg-neutral-900/50" onClick={onClick}>
+ <TableCell className="text-center">
+ <StatusOrb status={stats?.currentStatus || "unknown"} />
+ </TableCell>
+ <TableCell className="font-medium">
+ <div>{monitor.name}</div>
+ <div className="text-xs text-neutral-500">
+ {monitor.monitorType === "http"
+ ? monitor.httpConfig?.url
+ : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`}
+ </div>
+ </TableCell>
+ <TableCell>
+ <span
+ className={cn(
+ "inline-flex items-center px-2 py-1 text-xs font-medium rounded-full",
+ monitor.monitorType === "http" ? "bg-blue-500/20 text-blue-400" : "bg-purple-500/20 text-purple-400"
+ )}
+ >
+ {monitor.monitorType.toUpperCase()}
+ </span>
+ </TableCell>
+ <TableCell>
+ <UptimeBar monitorId={monitor.id} />
+ </TableCell>
+ <TableCell>{formatLastPing(stats?.lastCheckedAt)}</TableCell>
+ <TableCell className="text-right">{formatPercentage(stats?.uptimePercentage7d)}</TableCell>
+ <TableCell className="text-right">
+ {isLoadingUptime ? (
+ <Skeleton className="h-4 w-16 inline-block" />
+ ) : uptimeData ? (
+ formatUptime(uptimeData.currentUptimeSeconds)
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ </TableRow>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/MonitorsTable.tsx b/client/src/app/uptime/monitors/components/MonitorsTable.tsx
new file mode 100644
index 000000000..52936eaea
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/MonitorsTable.tsx
@@ -0,0 +1,300 @@
+import React, { useState, useMemo } from "react";
+import {
+ createColumnHelper,
+ flexRender,
+ getCoreRowModel,
+ getFilteredRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ SortingState,
+ useReactTable,
+ ColumnDef,
+ FilterFn,
+} from "@tanstack/react-table";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { UptimeMonitor, useMonitors } from "@/api/uptime/monitors";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Radio, ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
+import { StatusOrb } from "./StatusOrb";
+import { UptimeBar } from "./UptimeBar";
+import { Input } from "../../../../components/ui/input";
+import { Button } from "../../../../components/ui/button";
+import { Pagination } from "../../../../components/pagination";
+import { cn } from "@/lib/utils";
+import { DateTime } from "luxon";
+
+interface MonitorsTableProps {
+ onMonitorClick?: (monitor: UptimeMonitor) => void;
+}
+
+// Define the fuzzy filter function
+const fuzzyFilter: FilterFn<UptimeMonitor> = (row, columnId, value, addMeta) => {
+ const search = value.toLowerCase();
+ const monitor = row.original;
+
+ // Search in name (if it exists)
+ if (monitor.name && monitor.name.toLowerCase().includes(search)) return true;
+
+ // Search in URL/host
+ if (monitor.monitorType === "http" && monitor.httpConfig?.url?.toLowerCase().includes(search)) return true;
+ if (monitor.monitorType === "tcp" && monitor.tcpConfig?.host?.toLowerCase().includes(search)) return true;
+
+ // Search in type
+ if (monitor.monitorType.toLowerCase().includes(search)) return true;
+
+ return false;
+};
+
+const formatLastPing = (lastCheckedAt?: string) => {
+ if (!lastCheckedAt) return "-";
+
+ const lastPing = DateTime.fromSQL(lastCheckedAt, {
+ zone: "utc",
+ }).toLocal();
+
+ const now = DateTime.now();
+ const diffMs = now.toMillis() - lastPing.toMillis();
+
+ const seconds = Math.floor(diffMs / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ago`;
+ if (hours > 0) return `${hours}h ago`;
+ if (minutes > 0) return `${minutes}m ago`;
+ if (seconds > 0) return `${seconds}s ago`;
+ return "just now";
+};
+
+const formatPercentage = (value?: number) => {
+ if (value === undefined || value === null) return "-";
+ return `${value.toFixed(1)}%`;
+};
+
+// Create column helper
+const columnHelper = createColumnHelper<UptimeMonitor>();
+
+// Sort header component
+const SortHeader = ({ column, children }: any) => {
+ const isSorted = column.getIsSorted();
+
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}
+ className="p-0 hover:bg-transparent"
+ >
+ {children}
+ {isSorted ? (
+ isSorted === "asc" ? (
+ <ArrowUp className="ml-2 h-4 w-4" />
+ ) : (
+ <ArrowDown className="ml-2 h-4 w-4" />
+ )
+ ) : (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+};
+
+export function MonitorsTable({ onMonitorClick }: MonitorsTableProps) {
+ const { data: monitors = [], isLoading } = useMonitors();
+ const [globalFilter, setGlobalFilter] = useState("");
+ const [sorting, setSorting] = useState<SortingState>([]);
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ // Define columns
+ const columns = useMemo(
+ () => [
+ columnHelper.display({
+ id: "status",
+ header: () => <Radio className="ml-2 w-4 h-4" />,
+ cell: ({ row }) => (
+ <div className="text-center">
+ <StatusOrb status={row.original.status?.currentStatus || "unknown"} />
+ </div>
+ ),
+ size: 48,
+ }),
+ columnHelper.accessor("name", {
+ header: ({ column }) => <SortHeader column={column}>Monitor</SortHeader>,
+ cell: ({ row }) => {
+ const displayName =
+ row.original.name ||
+ (row.original.monitorType === "http"
+ ? row.original.httpConfig?.url
+ : `${row.original.tcpConfig?.host}:${row.original.tcpConfig?.port}`);
+ const subtext = row.original.name
+ ? row.original.monitorType === "http"
+ ? row.original.httpConfig?.url
+ : `${row.original.tcpConfig?.host}:${row.original.tcpConfig?.port}`
+ : null;
+
+ return (
+ <div>
+ <div className="font-medium">{displayName}</div>
+ {subtext && <div className="text-xs text-neutral-500">{subtext}</div>}
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("monitorType", {
+ header: ({ column }) => <SortHeader column={column}>Type</SortHeader>,
+ cell: ({ getValue }) => {
+ const type = getValue();
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center px-2 py-1 text-xs font-medium rounded-full",
+ type === "http" ? "bg-blue-500/20 text-blue-400" : "bg-purple-500/20 text-purple-400"
+ )}
+ >
+ {type.toUpperCase()}
+ </span>
+ );
+ },
+ size: 96,
+ }),
+ columnHelper.display({
+ id: "uptime-bar",
+ header: "Last 7 Days",
+ cell: ({ row }) => <UptimeBar monitorId={row.original.id} />,
+ size: 192,
+ }),
+ columnHelper.accessor((row) => row.status?.lastCheckedAt, {
+ id: "lastPing",
+ header: ({ column }) => <SortHeader column={column}>Last Ping</SortHeader>,
+ cell: ({ getValue }) => <span className="text-neutral-300">{formatLastPing(getValue())}</span>,
+ size: 112,
+ }),
+ columnHelper.accessor((row) => row.status?.uptimePercentage7d, {
+ id: "uptimePercentage",
+ header: ({ column }) => (
+ <SortHeader column={column}>
+ <span className="whitespace-nowrap">Uptime %</span>
+ </SortHeader>
+ ),
+ cell: ({ getValue }) => <div className="text-right text-neutral-300">{formatPercentage(getValue())}</div>,
+ size: 80,
+ }),
+ ],
+ []
+ );
+
+ // Create table instance
+ const table = useReactTable({
+ data: monitors,
+ columns,
+ state: {
+ globalFilter,
+ sorting,
+ pagination,
+ },
+ onGlobalFilterChange: setGlobalFilter,
+ onSortingChange: setSorting,
+ onPaginationChange: setPagination,
+ getCoreRowModel: getCoreRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ globalFilterFn: fuzzyFilter,
+ });
+
+ return (
+ <div className="space-y-4">
+ <Input
+ placeholder="Search monitors by name, URL, or type..."
+ value={globalFilter}
+ onChange={(e) => setGlobalFilter(e.target.value)}
+ className="max-w-sm bg-neutral-900"
+ />
+ <div className="rounded-lg border border-neutral-800">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead
+ key={header.id}
+ style={{
+ width: header.getSize() === 150 ? undefined : header.getSize(),
+ }}
+ >
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ Array.from({ length: 5 }).map((_, i) => (
+ <TableRow key={`skeleton-${i}`}>
+ <TableCell>
+ <Skeleton className="h-4 w-4 rounded-full mx-auto" />
+ </TableCell>
+ <TableCell>
+ <div className="space-y-1">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-3 w-48" />
+ </div>
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-6 w-12" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-12 ml-auto" />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : table.getRowModel().rows.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="text-center text-neutral-500 py-8">
+ {globalFilter ? "No monitors match your search" : "No monitors configured"}
+ </TableCell>
+ </TableRow>
+ ) : (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ className="cursor-pointer hover:bg-neutral-900/50"
+ onClick={() => onMonitorClick?.(row.original)}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
+ ))}
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+
+ {/* Pagination */}
+ {!isLoading && monitors.length > 0 && (
+ <Pagination
+ table={table}
+ data={{
+ items: table.getFilteredRowModel().rows.map((row) => row.original),
+ total: table.getFilteredRowModel().rows.length,
+ }}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="monitors"
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx b/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx
new file mode 100644
index 000000000..ba7efee24
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { Sidebar } from "./Sidebar";
+
+import { Menu } from "lucide-react";
+import { VisuallyHidden } from "radix-ui";
+import { AppSidebar } from "../../../../../components/AppSidebar";
+import { Button } from "../../../../../components/ui/button";
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "../../../../../components/ui/sheet";
+
+export function MobileSidebar() {
+ return (
+ <div className="md:hidden flex items-center gap-2">
+ <Sheet>
+ <SheetTrigger asChild>
+ <Button size="icon" variant="outline">
+ <Menu />
+ </Button>
+ </SheetTrigger>
+ <VisuallyHidden.Root>
+ <SheetHeader>
+ <SheetTitle>Rybbit Sidebar</SheetTitle>
+ </SheetHeader>
+ </VisuallyHidden.Root>
+ <SheetContent side="left" className="p-0 w-[240px] flex gap-0" showClose={false}>
+ <AppSidebar />
+ <Sidebar />
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/Sidebar/Sidebar.tsx b/client/src/app/uptime/monitors/components/Sidebar/Sidebar.tsx
new file mode 100644
index 000000000..82d4410ee
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/Sidebar/Sidebar.tsx
@@ -0,0 +1,70 @@
+"use client";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { cn } from "../../../../../lib/utils";
+import { Activity, AlertCircle, Plug2, Globe } from "lucide-react";
+
+export function Sidebar() {
+ const pathname = usePathname();
+
+ return (
+ <div className="w-56 bg-neutral-900 border-r border-neutral-800 flex flex-col justify-between">
+ <div className="flex flex-col p-3">
+ <div className="text-base text-neutral-100 mt-2 mb-4 mx-1 font-medium">Uptime</div>
+ <SidebarLink
+ label="Monitors"
+ active={pathname.startsWith("/uptime/monitors")}
+ href={"/uptime/monitors"}
+ icon={<Activity className="w-4 h-4" />}
+ />
+ <SidebarLink
+ label="Incidents"
+ active={pathname.startsWith("/uptime/incidents")}
+ href={"/uptime/incidents"}
+ icon={<AlertCircle className="w-4 h-4" />}
+ />
+ <SidebarLink
+ label="Notifications"
+ active={pathname.startsWith("/uptime/notifications")}
+ href={"/uptime/notifications"}
+ icon={<Plug2 className="w-4 h-4" />}
+ />
+ <SidebarLink
+ label="Status Page"
+ active={pathname.startsWith("/uptime/status-page")}
+ href={"/uptime/status-page"}
+ icon={<Globe className="w-4 h-4" />}
+ />
+ </div>
+ </div>
+ );
+}
+
+// Sidebar Link component
+function SidebarLink({
+ label,
+ active = false,
+ href,
+ icon,
+}: {
+ label: string;
+ active?: boolean;
+ href: string;
+ icon?: React.ReactNode;
+}) {
+ return (
+ <Link href={href} className="focus:outline-none">
+ <div
+ className={cn(
+ "px-3 py-2 rounded-lg transition-colors w-full",
+ active ? "bg-neutral-800 text-white" : "text-neutral-200 hover:text-white hover:bg-neutral-800/50"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {icon}
+ <span className="text-sm">{label}</span>
+ </div>
+ </div>
+ </Link>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/StatusOrb.tsx b/client/src/app/uptime/monitors/components/StatusOrb.tsx
new file mode 100644
index 000000000..f666fe6e9
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/StatusOrb.tsx
@@ -0,0 +1,52 @@
+import React from "react";
+import { cn } from "@/lib/utils";
+
+interface StatusOrbProps {
+ status: "up" | "down" | "unknown";
+ className?: string;
+ size?: "sm" | "md" | "lg";
+ animated?: boolean;
+}
+
+export function StatusOrb({ status, className, size = "md", animated = true }: StatusOrbProps) {
+ const sizeClasses = {
+ sm: "w-2 h-2",
+ md: "w-3 h-3",
+ lg: "w-4 h-4",
+ };
+
+ const statusClasses = {
+ up: "bg-green-400",
+ down: "bg-red-500",
+ unknown: "bg-gray-400 dark:bg-gray-600",
+ };
+
+ const pulseClasses = {
+ up: "animate-pulse",
+ down: "animate-pulse",
+ unknown: "",
+ };
+
+ return (
+ <div className={cn("relative inline-flex", className)}>
+ <div
+ className={cn(
+ "rounded-full",
+ sizeClasses[size],
+ statusClasses[status],
+ animated && status !== "unknown" && pulseClasses[status]
+ )}
+ />
+ {animated && status !== "unknown" && (
+ <div
+ className={cn(
+ "absolute inset-0 rounded-full opacity-75",
+ sizeClasses[size],
+ statusClasses[status],
+ "animate-ping"
+ )}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/UptimeBar.tsx b/client/src/app/uptime/monitors/components/UptimeBar.tsx
new file mode 100644
index 000000000..a1aa46303
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/UptimeBar.tsx
@@ -0,0 +1,104 @@
+import React from "react";
+import { cn } from "@/lib/utils";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { DateTime } from "luxon";
+import { useMonitorUptimeBuckets } from "@/api/uptime/monitors";
+
+interface UptimeBarProps {
+ monitorId: number;
+ className?: string;
+}
+
+export function UptimeBar({ monitorId, className }: UptimeBarProps) {
+ const { data, isLoading } = useMonitorUptimeBuckets(monitorId, {
+ bucket: "day",
+ days: 7,
+ });
+
+ if (isLoading) {
+ return (
+ <div className={cn("flex gap-1 h-6", className)}>
+ {Array.from({ length: 7 }).map((_, i) => (
+ <div key={i} className="w-[10px] rounded-md bg-neutral-300 dark:bg-neutral-600 animate-pulse" />
+ ))}
+ </div>
+ );
+ }
+
+ if (!data?.buckets) {
+ return null;
+ }
+ // Process bucket data
+ const days = data.buckets.map((bucket) => {
+ const date = DateTime.fromSQL(bucket.bucket_time).toLocal();
+ return {
+ date: bucket.bucket_formatted,
+ dateFormatted: date.toFormat("MMM dd"),
+ dayOfWeek: date.toFormat("ccc"),
+ totalChecks: bucket.total_checks,
+ successCount: bucket.successful_checks,
+ failureCount: bucket.failed_checks,
+ timeoutCount: bucket.timeout_checks,
+ uptimePercentage: bucket.uptime_percentage,
+ };
+ });
+
+ return (
+ <TooltipProvider>
+ <div className={cn("flex gap-1 h-6", className)}>
+ {days.map((day) => {
+ const totalChecks = day.totalChecks;
+ const hasIssues = day.failureCount > 0 || day.timeoutCount > 0;
+ const uptimePercentage = day.uptimePercentage.toFixed(1);
+
+ let barColor = "bg-green-500";
+ if (totalChecks === 0) {
+ barColor = "bg-neutral-300 dark:bg-neutral-600";
+ } else if (day.failureCount > 0 || day.timeoutCount > 0) {
+ const issuePercentage = (day.failureCount + day.timeoutCount) / totalChecks;
+ if (issuePercentage >= 0.5) barColor = "bg-red-500";
+ else if (issuePercentage >= 0.1) barColor = "bg-orange-500";
+ else barColor = "bg-yellow-500";
+ }
+ if (totalChecks === 0) {
+ return (
+ <div
+ key={day.date}
+ className={cn("w-[10px] rounded-md cursor-pointer transition-opacity hover:opacity-80", barColor)}
+ />
+ );
+ }
+
+ return (
+ <Tooltip key={day.date}>
+ <TooltipTrigger asChild>
+ <div
+ className={cn("w-[10px] rounded-md cursor-pointer transition-opacity hover:opacity-80", barColor)}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="text-sm space-y-1">
+ <div className="flex items-center gap-4">
+ <div className="font-medium">{uptimePercentage}%</div>
+ <div className="text-neutral-300">{day.dateFormatted}</div>
+ </div>
+ {totalChecks > 0 ? (
+ <>
+ <div className="text-xs text-neutral-300">
+ <span className="text-green-400">{day.successCount}</span> /{" "}
+ <span className="text-red-400">{day.failureCount}</span> /{" "}
+ <span className="text-orange-400">{day.timeoutCount}</span>
+ </div>
+ </>
+ ) : (
+ <div className="text-xs text-neutral-300 mt-1">No data</div>
+ )}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ </TooltipProvider>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx b/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx
new file mode 100644
index 000000000..2df88bf6b
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import React from "react";
+import { SelectItem, Select, SelectContent, SelectTrigger, SelectValue } from "@/components/ui/select";
+
+export type TimeBucket =
+ | "minute"
+ | "five_minutes"
+ | "ten_minutes"
+ | "fifteen_minutes"
+ | "hour"
+ | "day"
+ | "week"
+ | "month"
+ | "year";
+
+interface UptimeBucketSelectionProps {
+ timeRange: string;
+ bucket: TimeBucket;
+ onBucketChange: (bucket: TimeBucket) => void;
+}
+
+const getBucketOptions = (timeRange: string): TimeBucket[] => {
+ switch (timeRange) {
+ case "1h":
+ return ["minute", "five_minutes", "fifteen_minutes", "hour"];
+ case "6h":
+ return ["minute", "five_minutes", "fifteen_minutes", "hour"];
+ case "12h":
+ return ["minute", "five_minutes", "fifteen_minutes", "hour"];
+ case "24h":
+ return ["minute", "five_minutes", "fifteen_minutes", "hour"];
+ case "3d":
+ return ["five_minutes", "fifteen_minutes", "hour"];
+ case "7d":
+ return ["fifteen_minutes", "hour", "day"];
+ case "30d":
+ return ["hour", "day", "week"];
+ case "90d":
+ return ["hour", "day", "week", "month"];
+ case "180d":
+ return ["hour", "day", "week", "month", "year"];
+ case "365d":
+ return ["hour", "day", "week", "month", "year"];
+ case "all":
+ return ["day", "week", "month", "year"];
+ default:
+ return ["hour"];
+ }
+};
+
+const bucketLabels: Record<TimeBucket, string> = {
+ minute: "Minute",
+ five_minutes: "5 Minutes",
+ ten_minutes: "10 Minutes",
+ fifteen_minutes: "15 Minutes",
+ hour: "Hour",
+ day: "Day",
+ week: "Week",
+ month: "Month",
+ year: "Year",
+};
+
+export function UptimeBucketSelection({ timeRange, bucket, onBucketChange }: UptimeBucketSelectionProps) {
+ const availableBuckets = getBucketOptions(timeRange);
+
+ // If current bucket is not available for the time range, select the first available one
+ React.useEffect(() => {
+ if (!availableBuckets.includes(bucket)) {
+ onBucketChange(availableBuckets[0]);
+ }
+ }, [timeRange, bucket, availableBuckets, onBucketChange]);
+
+ return (
+ <Select value={bucket} onValueChange={(value) => onBucketChange(value as TimeBucket)}>
+ <SelectTrigger className="w-[120px]" size="sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {availableBuckets.map((bucketOption) => (
+ <SelectItem key={bucketOption} value={bucketOption} size="sm">
+ {bucketLabels[bucketOption]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx b/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx
new file mode 100644
index 000000000..247d6b8b5
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx
@@ -0,0 +1,212 @@
+import React from "react";
+import { UseFormReturn } from "react-hook-form";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Button } from "@/components/ui/button";
+import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
+import { Plus, X } from "lucide-react";
+import { Textarea } from "@/components/ui/textarea";
+import { CreateMonitorFormData, UpdateMonitorFormData } from "../monitorSchemas";
+
+interface AdvancedTabProps {
+ form: UseFormReturn<CreateMonitorFormData | UpdateMonitorFormData>;
+ monitorType: "http" | "tcp";
+}
+
+export function AdvancedTab({ form, monitorType }: AdvancedTabProps) {
+ return (
+ <div className="space-y-4">
+ {/* Monitor Name */}
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Monitor Name</FormLabel>
+ <FormControl>
+ <Input placeholder="My API Endpoint" {...field} value={field.value || ""} />
+ </FormControl>
+ <FormDescription>
+ A friendly name for this monitor. If not specified, the URL or host will be used.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {monitorType === "tcp" ? (
+ <div className="text-sm text-neutral-500 mt-4">No additional advanced options available for TCP monitors.</div>
+ ) : (
+ <>
+ <FormField
+ control={form.control}
+ name="httpConfig.userAgent"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>User Agent</FormLabel>
+ <FormControl>
+ <Input placeholder="Custom User Agent" {...field} value={field.value || ""} />
+ </FormControl>
+ <FormDescription>Override the default user agent string</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="httpConfig.headers"
+ render={({ field }) => {
+ // Use local state to manage headers array
+ const [localHeaders, setLocalHeaders] = React.useState<Array<{ key: string; value: string; id: string }>>(
+ () => {
+ if (!field.value) return [];
+ return Object.entries(field.value).map(([key, value], index) => ({
+ key,
+ value: value as string,
+ id: `header_${index}_${Date.now()}`,
+ }));
+ }
+ );
+
+ // Sync local state changes back to form field
+ React.useEffect(() => {
+ const headersObject = localHeaders
+ .filter((h) => h.key !== "") // Only include headers with keys
+ .reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {});
+
+ field.onChange(Object.keys(headersObject).length > 0 ? headersObject : undefined);
+ }, [localHeaders, field]);
+
+ const updateHeader = (id: string, type: "key" | "value", newValue: string) => {
+ setLocalHeaders((prev) =>
+ prev.map((header) => (header.id === id ? { ...header, [type]: newValue } : header))
+ );
+ };
+
+ const removeHeader = (id: string) => {
+ setLocalHeaders((prev) => prev.filter((header) => header.id !== id));
+ };
+
+ const addHeader = () => {
+ setLocalHeaders((prev) => [
+ ...prev,
+ {
+ key: "",
+ value: "",
+ id: `header_${Date.now()}`,
+ },
+ ]);
+ };
+
+ return (
+ <FormItem>
+ <div className="flex items-center justify-between mb-2">
+ <FormLabel>Custom Headers</FormLabel>
+ <Button type="button" variant="outline" size="sm" onClick={addHeader} className="h-8">
+ <Plus className="h-4 w-4 mr-1" />
+ Add header
+ </Button>
+ </div>
+ <div className="space-y-2">
+ {localHeaders.map((header) => (
+ <div key={header.id} className="flex gap-2 items-center">
+ <Input
+ placeholder="Header name"
+ value={header.key}
+ onChange={(e) => updateHeader(header.id, "key", e.target.value)}
+ className="flex-1"
+ />
+ <Input
+ placeholder="Header value"
+ value={header.value}
+ onChange={(e) => updateHeader(header.id, "value", e.target.value)}
+ className="flex-1"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeHeader(header.id)}
+ className="px-2"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ {localHeaders.length === 0 && (
+ <div className="text-sm text-neutral-500">No custom headers added</div>
+ )}
+ </div>
+ <FormDescription>Additional headers to send with requests</FormDescription>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+
+ <FormField
+ control={form.control}
+ name="httpConfig.body"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Request Body</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder='{"key": "value"}'
+ {...field}
+ value={field.value || ""}
+ className="font-mono min-h-[100px]"
+ style={{ fontSize: "12px" }}
+ />
+ </FormControl>
+ <FormDescription>Request body for POST, PUT, PATCH methods. Usually JSON or form data.</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="httpConfig.followRedirects"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <div className="space-y-0.5">
+ <FormLabel>Follow Redirects</FormLabel>
+ <FormDescription>Automatically follow HTTP redirects</FormDescription>
+ </div>
+ <FormControl>
+ <Switch checked={field.value} onCheckedChange={field.onChange} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="httpConfig.ipVersion"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>IP Version</FormLabel>
+ <Select onValueChange={field.onChange} value={field.value} defaultValue={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="any">Any</SelectItem>
+ <SelectItem value="ipv4">IPv4 Only</SelectItem>
+ <SelectItem value="ipv6">IPv6 Only</SelectItem>
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx b/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx
new file mode 100644
index 000000000..f755c3ce1
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx
@@ -0,0 +1,219 @@
+import React from "react";
+import { UseFormReturn } from "react-hook-form";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
+import { UptimeMonitor } from "@/api/uptime/monitors";
+import { CreateMonitorFormData, UpdateMonitorFormData } from "../monitorSchemas";
+
+interface GeneralTabProps {
+ form: UseFormReturn<CreateMonitorFormData | UpdateMonitorFormData>;
+ monitor?: UptimeMonitor;
+ isEdit: boolean;
+ monitorType: "http" | "tcp";
+}
+
+export const INTERVAL_OPTIONS = [
+ { value: 30, label: "30 seconds" },
+ { value: 60, label: "1 minute" },
+ { value: 120, label: "2 minutes" },
+ { value: 180, label: "3 minutes" },
+ { value: 300, label: "5 minutes" },
+ { value: 600, label: "10 minutes" },
+ { value: 1800, label: "30 minutes" },
+];
+
+const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"] as const;
+
+export function GeneralTab({ form, monitor, isEdit, monitorType }: GeneralTabProps) {
+ return (
+ <div className="space-y-4">
+ {/* Monitor Type */}
+ {!isEdit ? (
+ <FormField
+ control={form.control}
+ name="monitorType"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Monitor Type</FormLabel>
+ <Select onValueChange={field.onChange} defaultValue={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="http">HTTP/HTTPS</SelectItem>
+ <SelectItem value="tcp">TCP Port</SelectItem>
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : (
+ <div className="space-y-1">
+ <FormLabel>Monitor Type</FormLabel>
+ <div className="px-3 py-2 border border-neutral-800 rounded-md bg-neutral-900 text-neutral-400">
+ {monitor?.monitorType === "http" ? "HTTP/HTTPS" : "TCP Port"}
+ </div>
+ </div>
+ )}
+
+ {/* HTTP Configuration */}
+ {monitorType === "http" && (
+ <>
+ <FormField
+ control={form.control}
+ name="httpConfig.url"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>URL</FormLabel>
+ <FormControl>
+ <Input type="url" placeholder="https://api.example.com/health" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="grid grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="httpConfig.method"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>HTTP Method</FormLabel>
+ <Select onValueChange={field.onChange} value={field.value} defaultValue={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {HTTP_METHODS.map((method) => (
+ <SelectItem key={method} value={method}>
+ {method}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="httpConfig.timeoutMs"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Timeout (ms)</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ {...field}
+ value={field.value || ""}
+ onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </>
+ )}
+
+ {/* TCP Configuration */}
+ {monitorType === "tcp" && (
+ <div className="grid grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="tcpConfig.host"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Host</FormLabel>
+ <FormControl>
+ <Input placeholder="example.com" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="tcpConfig.port"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Port</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ {...field}
+ value={field.value || ""}
+ onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ )}
+
+ {/* Check Interval */}
+ <FormField
+ control={form.control}
+ name="intervalSeconds"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Check Interval</FormLabel>
+ <Select
+ onValueChange={(value) => field.onChange(parseInt(value))}
+ value={field.value?.toString()}
+ defaultValue={field.value?.toString()}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {INTERVAL_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value.toString()}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Enabled Switch */}
+ <FormField
+ control={form.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <div className="space-y-0.5">
+ <FormLabel>Enable Monitor</FormLabel>
+ <FormDescription>
+ {isEdit
+ ? "Monitor will run at the configured interval when enabled"
+ : "Start monitoring immediately after creation"}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch checked={field.value} onCheckedChange={field.onChange} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx b/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx
new file mode 100644
index 000000000..6bf33475e
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx
@@ -0,0 +1,278 @@
+import React, { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { useCreateMonitor, useUpdateMonitor, UptimeMonitor } from "@/api/uptime/monitors";
+import { toast } from "sonner";
+import { Loader2 } from "lucide-react";
+import { createMonitorSchema, updateMonitorSchema } from "../monitorSchemas";
+import { Form } from "@/components/ui/form";
+import { authClient } from "../../../../../lib/auth";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/basic-tabs";
+import { GeneralTab } from "./GeneralTab";
+import { AdvancedTab } from "./AdvancedTab";
+import { RegionsTab } from "./RegionsTab";
+import { NotificationsTab } from "./NotificationsTab";
+import { IS_CLOUD } from "@/lib/const";
+import { useQuery } from "@tanstack/react-query";
+import { authedFetch } from "../../../../../api/utils";
+
+interface MonitorDialogProps {
+ monitor?: UptimeMonitor;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function MonitorDialog({ monitor, open, onOpenChange }: MonitorDialogProps) {
+ const { data: activeOrganization, isPending } = authClient.useActiveOrganization();
+ const createMonitor = useCreateMonitor();
+ const updateMonitor = useUpdateMonitor();
+ const isEdit = !!monitor;
+
+ // Fetch available regions
+ const { data: regionsData } = useQuery({
+ queryKey: ["uptime-regions"],
+ queryFn: async () => {
+ const response = await authedFetch<{ regions: Array<{ code: string; name: string; isHealthy: boolean; isLocal: boolean }> }>("/uptime/regions");
+ return response.regions;
+ },
+ enabled: open && IS_CLOUD,
+ });
+
+ const form = useForm<any>({
+ resolver: zodResolver(isEdit ? updateMonitorSchema : createMonitorSchema),
+ defaultValues: isEdit
+ ? {
+ name: monitor.name,
+ intervalSeconds: monitor.intervalSeconds,
+ enabled: monitor.enabled,
+ httpConfig: monitor.httpConfig
+ ? {
+ url: monitor.httpConfig.url,
+ method: monitor.httpConfig.method as any,
+ headers: monitor.httpConfig.headers,
+ body: monitor.httpConfig.body,
+ auth: monitor.httpConfig.auth,
+ followRedirects: monitor.httpConfig.followRedirects ?? true,
+ timeoutMs: monitor.httpConfig.timeoutMs ?? 30000,
+ ipVersion: monitor.httpConfig.ipVersion ?? "any",
+ userAgent: monitor.httpConfig.userAgent,
+ }
+ : undefined,
+ tcpConfig: monitor.tcpConfig
+ ? {
+ host: monitor.tcpConfig.host,
+ port: monitor.tcpConfig.port,
+ timeoutMs: monitor.tcpConfig.timeoutMs ?? 30000,
+ }
+ : undefined,
+ validationRules: monitor.validationRules || [],
+ monitoringType: monitor.monitoringType || "local",
+ selectedRegions: monitor.selectedRegions || ["local"],
+ }
+ : {
+ organizationId: activeOrganization?.id || "",
+ name: "", // Optional - will be empty by default
+ monitorType: "http" as const,
+ intervalSeconds: 180,
+ enabled: true,
+ httpConfig: {
+ url: "",
+ method: "GET" as const,
+ followRedirects: true,
+ timeoutMs: 30000,
+ ipVersion: "any" as const,
+ },
+ validationRules: [],
+ monitoringType: IS_CLOUD ? "global" : "local",
+ selectedRegions: IS_CLOUD ? [] : ["local"], // Empty array for cloud, will be populated in RegionsTab
+ },
+ });
+
+ const monitorType = isEdit ? monitor.monitorType : form.watch("monitorType");
+
+ const onSubmit = async (data: any) => {
+ try {
+ if (isEdit) {
+ await updateMonitor.mutateAsync({
+ monitorId: monitor.id,
+ data,
+ });
+ toast.success("Monitor updated successfully");
+ } else {
+ await createMonitor.mutateAsync(data);
+ toast.success("Monitor created successfully");
+ }
+ onOpenChange(false);
+ form.reset();
+ } catch (error: any) {
+ console.error("Submit error:", error);
+ toast.error(error.response?.data?.error || `Failed to ${isEdit ? "update" : "create"} monitor`);
+ }
+ };
+
+ // Set organization ID when active organization changes (create mode only)
+ useEffect(() => {
+ if (!isEdit && activeOrganization?.id) {
+ form.setValue("organizationId", activeOrganization.id);
+ }
+ }, [activeOrganization, form, isEdit]);
+
+ // Initialize regions for new monitors in cloud mode
+ useEffect(() => {
+ if (open && !isEdit && IS_CLOUD && regionsData) {
+ const globalRegions = regionsData.filter(r => !r.isLocal && r.isHealthy);
+ if (globalRegions.length > 0) {
+ const currentRegions = form.getValues("selectedRegions");
+ // Only set if empty or has default "local" value
+ if (!currentRegions || currentRegions.length === 0 || (currentRegions.length === 1 && currentRegions[0] === "local")) {
+ form.setValue("selectedRegions", globalRegions.map(r => r.code));
+ }
+ }
+ }
+ }, [open, isEdit, IS_CLOUD, regionsData, form]);
+
+ // Reset form when dialog closes or monitor changes
+ useEffect(() => {
+ if (!open) {
+ form.reset();
+ } else if (isEdit && monitor) {
+ form.reset({
+ name: monitor.name,
+ intervalSeconds: monitor.intervalSeconds,
+ enabled: monitor.enabled,
+ httpConfig: monitor.httpConfig
+ ? {
+ url: monitor.httpConfig.url,
+ method: monitor.httpConfig.method as any,
+ headers: monitor.httpConfig.headers,
+ body: monitor.httpConfig.body,
+ auth: monitor.httpConfig.auth,
+ followRedirects: monitor.httpConfig.followRedirects ?? true,
+ timeoutMs: monitor.httpConfig.timeoutMs ?? 30000,
+ ipVersion: monitor.httpConfig.ipVersion ?? "any",
+ userAgent: monitor.httpConfig.userAgent,
+ }
+ : undefined,
+ tcpConfig: monitor.tcpConfig
+ ? {
+ host: monitor.tcpConfig.host,
+ port: monitor.tcpConfig.port,
+ timeoutMs: monitor.tcpConfig.timeoutMs ?? 30000,
+ }
+ : undefined,
+ validationRules: monitor.validationRules || [],
+ monitoringType: monitor.monitoringType || "local",
+ selectedRegions: monitor.selectedRegions || ["local"],
+ });
+ }
+ }, [monitor, open, form, isEdit]);
+
+ // Update form when monitor type changes (create mode only)
+ useEffect(() => {
+ if (!isEdit && form.watch) {
+ const subscription = form.watch((value, { name }) => {
+ if (name === "monitorType") {
+ if (value.monitorType === "tcp") {
+ form.setValue("httpConfig", undefined as any);
+ form.setValue("tcpConfig", {
+ host: "",
+ port: 80,
+ timeoutMs: 30000,
+ });
+ } else {
+ form.setValue("tcpConfig", undefined as any);
+ form.setValue("httpConfig", {
+ url: "",
+ method: "GET" as const,
+ followRedirects: true,
+ timeoutMs: 30000,
+ ipVersion: "any" as const,
+ });
+ }
+ }
+ });
+ return () => subscription.unsubscribe();
+ }
+ }, [form, isEdit]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit, (errors) => {
+ console.log("Form validation errors:", errors);
+ })}
+ >
+ <DialogHeader>
+ <DialogTitle>{isEdit ? "Edit" : "Create New"} Monitor</DialogTitle>
+ <DialogDescription>
+ {isEdit
+ ? "Update the configuration for this monitor."
+ : "Set up a new uptime monitor to track the availability of your endpoints."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <Tabs defaultValue="general" className="mt-4">
+ <TabsList className="">
+ <TabsTrigger value="general">General</TabsTrigger>
+ <TabsTrigger value="advanced">Advanced</TabsTrigger>
+ <TabsTrigger value="regions">Regions</TabsTrigger>
+ <TabsTrigger value="notifications">Notifications</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="general" className="space-y-4 mt-4">
+ <GeneralTab form={form} monitor={monitor} isEdit={isEdit} monitorType={monitorType} />
+ </TabsContent>
+
+ <TabsContent value="advanced" className="space-y-4 mt-4">
+ <AdvancedTab form={form} monitorType={monitorType} />
+ </TabsContent>
+
+ <TabsContent value="regions" className="space-y-4 mt-4">
+ <RegionsTab />
+ </TabsContent>
+
+ <TabsContent value="notifications" className="space-y-4 mt-4">
+ <NotificationsTab />
+ </TabsContent>
+ </Tabs>
+
+ <DialogFooter className="mt-6">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={createMonitor.isPending || updateMonitor.isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="success"
+ disabled={
+ (isEdit ? updateMonitor.isPending : createMonitor.isPending) ||
+ (!isEdit && (isPending || !activeOrganization))
+ }
+ >
+ {(createMonitor.isPending || updateMonitor.isPending) && (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ )}
+ {isEdit ? "Update" : "Create"} Monitor
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx b/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx
new file mode 100644
index 000000000..e345931bd
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx
@@ -0,0 +1,9 @@
+import React from "react";
+
+export function NotificationsTab() {
+ return (
+ <div className="text-neutral-500 text-sm">
+ Notification settings will be available in a future update.
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx b/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx
new file mode 100644
index 000000000..356f6d62f
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx
@@ -0,0 +1,187 @@
+import React, { useEffect } from "react";
+import { useFormContext } from "react-hook-form";
+import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Globe, Server, Info, Crown } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { authedFetch } from "../../../../../api/utils";
+import { Skeleton } from "@/components/ui/skeleton";
+import { CountryFlag } from "@/app/[site]/components/shared/icons/CountryFlag";
+import { IS_CLOUD } from "@/lib/const";
+import { cn } from "@/lib/utils";
+import { Checkbox } from "@/components/ui/checkbox";
+
+interface Region {
+ code: string;
+ name: string;
+ isHealthy: boolean;
+ lastHealthCheck: string | null;
+ isLocal: boolean;
+}
+
+export function RegionsTab() {
+ const form = useFormContext();
+ const monitoringType = IS_CLOUD ? "global" : "local";
+ const selectedRegions = form.watch("selectedRegions") || [];
+
+ const { data: regionsData, isLoading } = useQuery({
+ queryKey: ["uptime-regions"],
+ queryFn: async () => {
+ const response = await authedFetch<{ regions: Region[] }>("/uptime/regions");
+ return response.regions;
+ },
+ });
+
+ const regions = regionsData || [];
+ const globalRegions = regions.filter((r: Region) => !r.isLocal);
+
+ // Set monitoring type on mount
+ useEffect(() => {
+ form.setValue("monitoringType", monitoringType);
+
+ // For local monitoring, ensure "local" is selected
+ if (!IS_CLOUD) {
+ form.setValue("selectedRegions", ["local"]);
+ }
+ }, [monitoringType, form, IS_CLOUD]);
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ );
+ }
+
+ // Map region codes to country codes for flags
+ const regionToCountry: Record<string, string> = {
+ "us-east": "US",
+ "us-west": "US",
+ eu: "EU",
+ asia: "SG",
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h3 className="text-sm font-medium flex items-center gap-2">
+ {IS_CLOUD ? (
+ <>
+ <Globe className="h-4 w-4" /> Global Monitoring
+ </>
+ ) : (
+ <>
+ <Server className="h-4 w-4" /> Local Monitoring
+ </>
+ )}
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {IS_CLOUD ? "Monitor from multiple regions worldwide" : "Monitor from your main server location only"}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {IS_CLOUD ? (
+ <>
+ <FormField
+ control={form.control}
+ name="selectedRegions"
+ render={() => (
+ <FormItem>
+ {/* <FormLabel>Select Regions</FormLabel>
+ <FormDescription>
+ Choose which regions to monitor from. More regions provide better coverage.
+ </FormDescription> */}
+ <div className="space-y-4 mt-4">
+ {globalRegions.map((region: Region) => (
+ <FormField
+ key={region.code}
+ control={form.control}
+ name="selectedRegions"
+ render={({ field }) => {
+ const isSelected = field.value?.includes(region.code);
+ const isDisabled = !region.isHealthy;
+
+ return (
+ <FormItem>
+ <div className="flex items-center space-x-3">
+ <FormControl>
+ <Checkbox
+ checked={isSelected}
+ onCheckedChange={(checked) => {
+ if (!isDisabled) {
+ let newValue: string[];
+ if (checked) {
+ newValue = [...(field.value || []), region.code];
+ } else {
+ newValue = field.value?.filter((value: string) => value !== region.code) || [];
+ // Ensure at least one region is selected
+ if (newValue.length === 0) {
+ return; // Don't allow unchecking the last region
+ }
+ }
+ field.onChange(newValue);
+ }
+ }}
+ disabled={isDisabled}
+ className="data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500 dark:data-[state=checked]:bg-emerald-500"
+ />
+ </FormControl>
+ <div className="flex items-center gap-2 flex-1">
+ {regionToCountry[region.code] && (
+ <CountryFlag country={regionToCountry[region.code]} className="w-5 h-3.5" />
+ )}
+ <label
+ htmlFor={region.code}
+ className={cn(
+ "text-sm font-medium cursor-pointer",
+ isDisabled && "opacity-50 cursor-not-allowed"
+ )}
+ >
+ {region.name}
+ </label>
+ {!region.isHealthy && <span className="ml-auto text-xs text-red-500">Offline</span>}
+ </div>
+ </div>
+ </FormItem>
+ );
+ }}
+ />
+ ))}
+ </div>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {selectedRegions.length === 0 && (
+ <Alert variant="destructive">
+ <Info className="h-4 w-4" />
+ <AlertDescription>Please select at least one region for global monitoring.</AlertDescription>
+ </Alert>
+ )}
+
+ {selectedRegions.length === 1 && (
+ <Alert>
+ <Info className="h-4 w-4" />
+ <AlertDescription>At least one region must remain selected.</AlertDescription>
+ </Alert>
+ )}
+ </>
+ ) : (
+ <Alert>
+ <Crown className="h-4 w-4" />
+ <AlertDescription>
+ Upgrade to Cloud or Enterprise tier to enable multi-region monitoring and get better uptime insights from
+ multiple geographic locations.
+ </AlertDescription>
+ </Alert>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/uptime/monitors/components/dialog/index.ts b/client/src/app/uptime/monitors/components/dialog/index.ts
new file mode 100644
index 000000000..6105009d8
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/dialog/index.ts
@@ -0,0 +1 @@
+export { MonitorDialog } from "./MonitorDialog";
\ No newline at end of file
diff --git a/client/src/app/uptime/monitors/components/monitorSchemas.ts b/client/src/app/uptime/monitors/components/monitorSchemas.ts
new file mode 100644
index 000000000..22d9f9798
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/monitorSchemas.ts
@@ -0,0 +1,120 @@
+import { z } from "zod";
+
+// HTTP method enum
+const httpMethodSchema = z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]);
+
+// Auth type enum
+const authTypeSchema = z.enum(["none", "basic", "bearer", "api_key", "custom_header"]);
+
+// IP version enum
+const ipVersionSchema = z.enum(["any", "ipv4", "ipv6"]);
+
+// Auth credentials schema
+const authCredentialsSchema = z.object({
+ username: z.string().optional(),
+ password: z.string().optional(),
+ token: z.string().optional(),
+ headerName: z.string().optional(),
+ headerValue: z.string().optional(),
+});
+
+// Auth schema
+const authSchema = z.object({
+ type: authTypeSchema,
+ credentials: authCredentialsSchema.optional(),
+});
+
+// HTTP config schema
+const httpConfigSchema = z.object({
+ url: z.string().url("Please enter a valid URL"),
+ method: httpMethodSchema,
+ headers: z.record(z.string()).optional(),
+ body: z.string().optional(),
+ auth: authSchema.optional(),
+ followRedirects: z.boolean(),
+ timeoutMs: z.number().int().min(1000).max(300000),
+ ipVersion: ipVersionSchema,
+ userAgent: z.string().max(256).optional(),
+});
+
+// TCP config schema
+const tcpConfigSchema = z.object({
+ host: z.string().min(1, "Host is required"),
+ port: z.number().int().min(1, "Invalid port").max(65535, "Port must be between 1 and 65535"),
+ timeoutMs: z.number().int().min(1000).max(300000),
+});
+
+// Partial schemas for updates
+const partialHttpConfigSchema = z.object({
+ url: z.string().url("Please enter a valid URL").optional(),
+ method: httpMethodSchema.optional(),
+ headers: z.record(z.string()).optional(),
+ body: z.string().optional(),
+ auth: authSchema.optional(),
+ followRedirects: z.boolean().optional(),
+ timeoutMs: z.number().int().min(1000).max(300000).optional(),
+ ipVersion: ipVersionSchema.optional(),
+ userAgent: z.string().max(256).optional(),
+});
+
+const partialTcpConfigSchema = z.object({
+ host: z.string().min(1, "Host is required").optional(),
+ port: z.number().int().min(1, "Invalid port").max(65535, "Port must be between 1 and 65535").optional(),
+ timeoutMs: z.number().int().min(1000).max(300000).optional(),
+});
+
+// Create monitor schema
+export const createMonitorSchema = z
+ .object({
+ organizationId: z.string().min(1, "Organization is required"),
+ name: z.string().max(256).optional(), // Made optional
+ monitorType: z.enum(["http", "tcp"]),
+ intervalSeconds: z.number().int().min(30).max(86400),
+ enabled: z.boolean(),
+ httpConfig: httpConfigSchema.optional(),
+ tcpConfig: tcpConfigSchema.optional(),
+ validationRules: z.array(z.any()).optional(),
+ monitoringType: z.enum(["local", "global"]).optional(),
+ selectedRegions: z.array(z.string()).optional(),
+ })
+ .refine(
+ (data) => {
+ if (data.monitorType === "http") {
+ return data.httpConfig !== undefined && data.httpConfig.url !== "";
+ }
+ if (data.monitorType === "tcp") {
+ return data.tcpConfig !== undefined && data.tcpConfig.host !== "";
+ }
+ return false;
+ },
+ {
+ message: "Monitor type specific configuration is required",
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.monitoringType === "global") {
+ return data.selectedRegions && data.selectedRegions.length > 0;
+ }
+ return true;
+ },
+ {
+ message: "At least one region must be selected for global monitoring",
+ }
+ );
+
+// Update monitor schema (all fields optional except what's being updated)
+export const updateMonitorSchema = z.object({
+ name: z.string().max(256).optional(), // Allow empty string for removing name
+ intervalSeconds: z.number().int().min(30).max(86400).optional(),
+ enabled: z.boolean().optional(),
+ httpConfig: partialHttpConfigSchema.optional(),
+ tcpConfig: partialTcpConfigSchema.optional(),
+ validationRules: z.array(z.any()).optional(),
+ monitoringType: z.enum(["local", "global"]).optional(),
+ selectedRegions: z.array(z.string()).optional(),
+});
+
+// Type exports
+export type CreateMonitorFormData = z.infer<typeof createMonitorSchema>;
+export type UpdateMonitorFormData = z.infer<typeof updateMonitorSchema>;
\ No newline at end of file
diff --git a/client/src/app/uptime/monitors/components/uptimeStore.ts b/client/src/app/uptime/monitors/components/uptimeStore.ts
new file mode 100644
index 000000000..6e3ce6cfe
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/uptimeStore.ts
@@ -0,0 +1,36 @@
+import { create } from "zustand";
+import { TimeBucket } from "./UptimeBucketSelection";
+
+export const TIME_RANGES = [
+ { value: "1h", label: "1H" },
+ { value: "6h", label: "6H" },
+ { value: "12h", label: "12H" },
+ { value: "24h", label: "24H" },
+ { value: "3d", label: "3D" },
+ { value: "7d", label: "7D" },
+ { value: "14d", label: "14D" },
+ { value: "30d", label: "30D" },
+ { value: "60d", label: "60D" },
+ { value: "90d", label: "90D" },
+ { value: "180d", label: "180D" },
+ { value: "365d", label: "365D" },
+ // { value: "all", label: "All Time" },
+] as const;
+
+export type TimeRange = (typeof TIME_RANGES)[number]["value"];
+
+export const useUptimeStore = create<{
+ timeRange: TimeRange;
+ setTimeRange: (timeRange: (typeof TIME_RANGES)[number]["value"]) => void;
+ bucket: TimeBucket;
+ setBucket: (bucket: TimeBucket) => void;
+ selectedRegion?: string;
+ setSelectedRegion: (region?: string) => void;
+}>((set) => ({
+ timeRange: "24h",
+ setTimeRange: (timeRange) => set({ timeRange }),
+ bucket: "minute",
+ setBucket: (bucket) => set({ bucket }),
+ selectedRegion: undefined,
+ setSelectedRegion: (region) => set({ selectedRegion: region }),
+}));
diff --git a/client/src/app/uptime/monitors/components/utils.ts b/client/src/app/uptime/monitors/components/utils.ts
new file mode 100644
index 000000000..8de627916
--- /dev/null
+++ b/client/src/app/uptime/monitors/components/utils.ts
@@ -0,0 +1,32 @@
+import { TimeRange } from "./uptimeStore";
+
+export const getHoursFromTimeRange = (timeRange: TimeRange) => {
+ switch (timeRange) {
+ case "1h":
+ return 1;
+ case "6h":
+ return 6;
+ case "12h":
+ return 12;
+ case "24h":
+ return 24;
+ case "3d":
+ return 72;
+ case "7d":
+ return 168;
+ case "14d":
+ return 336;
+ case "30d":
+ return 720;
+ case "60d":
+ return 1440;
+ case "90d":
+ return 2160;
+ case "180d":
+ return 4320;
+ case "365d":
+ return 8760;
+ default:
+ return 24;
+ }
+};
diff --git a/client/src/app/uptime/monitors/const.ts b/client/src/app/uptime/monitors/const.ts
new file mode 100644
index 000000000..e4e6bdc5c
--- /dev/null
+++ b/client/src/app/uptime/monitors/const.ts
@@ -0,0 +1,7 @@
+export const REGIONS = [
+ { code: "all", name: "All Regions", countryCode: null },
+ { code: "us-east", name: "US East", countryCode: "US" },
+ { code: "us-west", name: "US West", countryCode: "US" },
+ { code: "eu", name: "Europe", countryCode: "EU" },
+ { code: "asia", name: "Asia", countryCode: "SG" }, // Singapore flag for Asia
+];
diff --git a/client/src/app/uptime/monitors/page.tsx b/client/src/app/uptime/monitors/page.tsx
new file mode 100644
index 000000000..448c66612
--- /dev/null
+++ b/client/src/app/uptime/monitors/page.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Plus } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { MonitorDialog } from "./components/dialog";
+import { MonitorsTable } from "./components/MonitorsTable";
+
+export default function UptimePage() {
+ const router = useRouter();
+ const [showCreateDialog, setShowCreateDialog] = useState(false);
+
+ const handleMonitorClick = (monitor: any) => {
+ router.push(`/uptime/monitors/${monitor.id}`);
+ };
+
+ return (
+ <>
+ <div className="flex items-center justify-between mb-6">
+ <div>
+ <h1 className="text-2xl font-semibold">Uptime Monitoring</h1>
+ <p className="text-sm text-neutral-500 mt-1">Monitor the availability and performance of your endpoints</p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button size="sm" className="flex items-center gap-2" onClick={() => setShowCreateDialog(true)}>
+ <Plus className="h-4 w-4" />
+ Add Monitor
+ </Button>
+ </div>
+ </div>
+
+ <MonitorsTable onMonitorClick={handleMonitorClick} />
+
+ <MonitorDialog open={showCreateDialog} onOpenChange={setShowCreateDialog} />
+ </>
+ );
+}
diff --git a/client/src/app/uptime/notifications/components/NotificationDialog.tsx b/client/src/app/uptime/notifications/components/NotificationDialog.tsx
new file mode 100644
index 000000000..c2514006f
--- /dev/null
+++ b/client/src/app/uptime/notifications/components/NotificationDialog.tsx
@@ -0,0 +1,297 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { toast } from "sonner";
+import { useNotificationsStore } from "../notificationsStore";
+import { NotificationChannel, useCreateChannel, useUpdateChannel } from "@/api/uptime/notifications";
+import { CHANNEL_CONFIG } from "../constants";
+import { useForm } from "react-hook-form";
+import { useEffect, useState } from "react";
+import * as React from "react";
+import { useMonitors } from "@/api/uptime/monitors";
+import { MultiSelect } from "@/components/ui/multi-select";
+
+type FormData = {
+ name: string;
+ email?: string;
+ webhookUrl?: string;
+ slackWebhookUrl?: string;
+ slackChannel?: string;
+ phoneNumber?: string;
+};
+
+export function NotificationDialog() {
+ const createChannel = useCreateChannel();
+ const updateChannel = useUpdateChannel();
+ const {
+ isDialogOpen,
+ selectedType,
+ editingChannel,
+ closeDialog,
+ resetForm: resetStoreForm,
+ } = useNotificationsStore();
+ const { data: monitorsData, isLoading: monitorsLoading } = useMonitors({ enabled: true });
+ const [selectedMonitorIds, setSelectedMonitorIds] = useState<string[]>([]);
+
+ const {
+ register,
+ handleSubmit,
+ formState: { errors, isValid },
+ reset,
+ watch,
+ } = useForm<FormData>({
+ mode: "onChange",
+ defaultValues: {
+ name: "",
+ email: "",
+ webhookUrl: "",
+ slackWebhookUrl: "",
+ slackChannel: "",
+ phoneNumber: "",
+ },
+ });
+
+ // Reset form when dialog closes or populate with editing data
+ useEffect(() => {
+ if (!isDialogOpen) {
+ reset();
+ setSelectedMonitorIds([]);
+ } else if (editingChannel) {
+ // Populate form with existing channel data
+ reset({
+ name: editingChannel.name,
+ email: editingChannel.config?.email || "",
+ webhookUrl: editingChannel.config?.webhookUrl || "",
+ slackWebhookUrl: editingChannel.config?.slackWebhookUrl || "",
+ slackChannel: editingChannel.config?.slackChannel || "",
+ phoneNumber: editingChannel.config?.phoneNumber || "",
+ });
+ setSelectedMonitorIds(editingChannel.monitorIds?.map((id) => id.toString()) || []);
+ }
+ }, [isDialogOpen, editingChannel, reset]);
+
+ const monitorOptions = React.useMemo(() => {
+ if (!monitorsData) return [];
+ return monitorsData.map((monitor) => ({
+ value: monitor.id.toString(),
+ label:
+ monitor.name ||
+ (monitor.monitorType === "http"
+ ? monitor.httpConfig?.url || "HTTP Monitor"
+ : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}` || "TCP Monitor"),
+ }));
+ }, [monitorsData]);
+
+ const onSubmit = async (data: FormData) => {
+ if (!selectedType) return;
+ const config: Partial<NotificationChannel["config"]> = {};
+ if (selectedType === "email" && data.email) config.email = data.email;
+ if (selectedType === "discord" && data.webhookUrl) config.webhookUrl = data.webhookUrl;
+ if (selectedType === "slack") {
+ if (data.slackWebhookUrl) config.slackWebhookUrl = data.slackWebhookUrl;
+ if (data.slackChannel) config.slackChannel = data.slackChannel;
+ }
+ if (selectedType === "sms" && data.phoneNumber) config.phoneNumber = data.phoneNumber;
+
+ try {
+ const monitorIds = selectedMonitorIds.length > 0 ? selectedMonitorIds.map((id) => parseInt(id, 10)) : null;
+
+ if (editingChannel) {
+ await updateChannel.mutateAsync({
+ id: editingChannel.id,
+ data: {
+ name: data.name,
+ config,
+ monitorIds,
+ },
+ });
+ toast.success("Notification channel updated");
+ } else {
+ await createChannel.mutateAsync({
+ type: selectedType,
+ name: data.name,
+ config,
+ monitorIds,
+ });
+ toast.success("Notification channel created");
+ }
+ closeDialog();
+ resetStoreForm();
+ reset();
+ setSelectedMonitorIds([]);
+ } catch (error) {
+ toast.error(editingChannel ? "Failed to update channel" : "Failed to create channel");
+ }
+ };
+
+ // Determine if form is valid based on selected channel type
+ const isFormValid = () => {
+ const values = watch();
+ if (!values.name?.trim()) return false;
+
+ switch (selectedType) {
+ case "email":
+ return !!values.email?.trim();
+ case "discord":
+ return !!values.webhookUrl?.trim();
+ case "slack":
+ return !!values.slackWebhookUrl?.trim();
+ case "sms":
+ return !!values.phoneNumber?.trim();
+ default:
+ return false;
+ }
+ };
+
+ const selectedConfig = selectedType ? CHANNEL_CONFIG[selectedType] : null;
+ const Icon = selectedConfig ? selectedConfig.icon : null;
+
+ return (
+ <Dialog open={isDialogOpen} onOpenChange={closeDialog}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-3">
+ {Icon && <Icon />}
+ {editingChannel ? "Edit" : "Add"} {selectedConfig && selectedConfig.title} Channel
+ </DialogTitle>
+ </DialogHeader>
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
+ <div>
+ <Label htmlFor="name">Channel Name</Label>
+ <Input
+ id="name"
+ placeholder="e.g., Team Alerts"
+ {...register("name", {
+ required: "Channel name is required",
+ minLength: { value: 1, message: "Channel name is required" },
+ })}
+ />
+ {errors.name && <p className="text-sm text-red-500 mt-1">{errors.name.message}</p>}
+ </div>
+
+ {selectedType === "email" && (
+ <div>
+ <Label htmlFor="email">Email Address</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ {...register("email", {
+ required: "Email address is required",
+ pattern: {
+ value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
+ message: "Invalid email address",
+ },
+ })}
+ />
+ {errors.email && <p className="text-sm text-red-500 mt-1">{errors.email.message}</p>}
+ </div>
+ )}
+
+ {selectedType === "discord" && (
+ <div>
+ <Label htmlFor="webhookUrl">Discord Webhook URL</Label>
+ <Input
+ id="webhookUrl"
+ placeholder="https://discord.com/api/webhooks/..."
+ {...register("webhookUrl", {
+ required: "Discord webhook URL is required",
+ pattern: {
+ value: /^https:\/\/discord\.com\/api\/webhooks\/.+/,
+ message: "Invalid Discord webhook URL",
+ },
+ })}
+ />
+ <p className="text-xs text-neutral-500 mt-1">Create a webhook in your Discord server settings</p>
+ {errors.webhookUrl && <p className="text-sm text-red-500 mt-1">{errors.webhookUrl.message}</p>}
+ </div>
+ )}
+
+ {selectedType === "slack" && (
+ <>
+ <div>
+ <Label htmlFor="slackWebhookUrl">Slack Webhook URL</Label>
+ <Input
+ id="slackWebhookUrl"
+ placeholder="https://hooks.slack.com/services/..."
+ {...register("slackWebhookUrl", {
+ required: "Slack webhook URL is required",
+ pattern: {
+ value: /^https:\/\/hooks\.slack\.com\/(services|workflows)\/.+/,
+ message: "Invalid Slack webhook URL",
+ },
+ })}
+ />
+ {errors.slackWebhookUrl && (
+ <p className="text-sm text-red-500 mt-1">{errors.slackWebhookUrl.message}</p>
+ )}
+ </div>
+ <div>
+ <Label htmlFor="slackChannel">Channel (optional)</Label>
+ <Input id="slackChannel" placeholder="#alerts" {...register("slackChannel")} />
+ </div>
+ </>
+ )}
+
+ {selectedType === "sms" && (
+ <div>
+ <Label htmlFor="phoneNumber">Phone Number</Label>
+ <Input
+ id="phoneNumber"
+ placeholder="+1234567890"
+ {...register("phoneNumber", {
+ required: "Phone number is required",
+ pattern: {
+ value: /^\+[1-9]\d{1,14}$/,
+ message: "Phone number must be in E.164 format (e.g., +14155552671)",
+ },
+ })}
+ />
+ <p className="text-xs text-neutral-500 mt-1">Use international E.164 format: +[country code][number]</p>
+ {errors.phoneNumber && <p className="text-sm text-red-500 mt-1">{errors.phoneNumber.message}</p>}
+ </div>
+ )}
+
+ {/* Monitor Selection */}
+ <div className="space-y-2">
+ <Label>Monitors</Label>
+ <MultiSelect
+ options={monitorOptions}
+ value={selectedMonitorIds}
+ onValueChange={setSelectedMonitorIds}
+ placeholder="Select monitors..."
+ searchPlaceholder="Search monitors..."
+ emptyText="No monitors found."
+ disabled={monitorsLoading}
+ />
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ Leave empty to receive alerts from all monitors
+ </p>
+ </div>
+
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={closeDialog}>
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="success"
+ disabled={!isFormValid() || createChannel.isPending || updateChannel.isPending}
+ >
+ {editingChannel
+ ? updateChannel.isPending
+ ? "Updating..."
+ : "Update Channel"
+ : createChannel.isPending
+ ? "Creating..."
+ : "Create Channel"}
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/client/src/app/uptime/notifications/constants.ts b/client/src/app/uptime/notifications/constants.ts
new file mode 100644
index 000000000..a9b954b80
--- /dev/null
+++ b/client/src/app/uptime/notifications/constants.ts
@@ -0,0 +1,32 @@
+import { Mail, Smartphone } from "lucide-react";
+import { SiDiscord, SiSlack } from "@icons-pack/react-simple-icons";
+
+export interface ChannelConfigItem {
+ icon: typeof Mail;
+ title: string;
+ description: string;
+ disabled?: boolean;
+}
+
+export const CHANNEL_CONFIG: Record<string, ChannelConfigItem> = {
+ email: {
+ icon: Mail,
+ title: "Email",
+ description: "Send notifications to an email address",
+ },
+ discord: {
+ icon: SiDiscord,
+ title: "Discord",
+ description: "Send notifications to a Discord channel via webhook",
+ },
+ slack: {
+ icon: SiSlack,
+ title: "Slack",
+ description: "Send notifications to a Slack channel",
+ },
+ sms: {
+ icon: Smartphone,
+ title: "SMS",
+ description: "Send notifications via SMS",
+ },
+};
diff --git a/client/src/app/uptime/notifications/notificationsStore.ts b/client/src/app/uptime/notifications/notificationsStore.ts
new file mode 100644
index 000000000..57f54ff90
--- /dev/null
+++ b/client/src/app/uptime/notifications/notificationsStore.ts
@@ -0,0 +1,41 @@
+import { create } from "zustand";
+import { NotificationChannel } from "@/api/uptime/notifications";
+
+type ChannelType = NotificationChannel["type"];
+
+interface NotificationsStore {
+ // Dialog state
+ isDialogOpen: boolean;
+ selectedType: ChannelType | null;
+ editingChannel: NotificationChannel | null;
+
+ // Actions
+ openDialog: (type: ChannelType, channel?: NotificationChannel) => void;
+ closeDialog: () => void;
+ resetForm: () => void;
+}
+
+export const useNotificationsStore = create<NotificationsStore>((set) => ({
+ // Initial state
+ isDialogOpen: false,
+ selectedType: null,
+ editingChannel: null,
+
+ // Actions
+ openDialog: (type, channel) => set({
+ isDialogOpen: true,
+ selectedType: type,
+ editingChannel: channel || null
+ }),
+
+ closeDialog: () => set({
+ isDialogOpen: false,
+ editingChannel: null
+ }),
+
+ resetForm: () =>
+ set({
+ selectedType: null,
+ editingChannel: null
+ }),
+}));
\ No newline at end of file
diff --git a/client/src/app/uptime/notifications/page.tsx b/client/src/app/uptime/notifications/page.tsx
new file mode 100644
index 000000000..20f4541fb
--- /dev/null
+++ b/client/src/app/uptime/notifications/page.tsx
@@ -0,0 +1,258 @@
+"use client";
+
+import { ConfirmationModal } from "@/components/ConfirmationModal";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardTitle } from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { cn } from "@/lib/utils";
+import { Bell, Edit, MoreHorizontal, Power, Trash2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import {
+ NotificationChannel,
+ useDeleteChannel,
+ useNotificationChannels,
+ useTestChannel,
+ useUpdateChannel,
+} from "../../../api/uptime/notifications";
+import { StandardPage } from "../../../components/StandardPage";
+import { NotificationDialog } from "./components/NotificationDialog";
+import { CHANNEL_CONFIG } from "./constants";
+import { useNotificationsStore } from "./notificationsStore";
+
+type ChannelType = NotificationChannel["type"];
+
+export default function NotificationsPage() {
+ const { data, isLoading } = useNotificationChannels();
+ const updateChannel = useUpdateChannel();
+ const deleteChannel = useDeleteChannel();
+ const testChannel = useTestChannel();
+ const { openDialog } = useNotificationsStore();
+ const [deleteModalOpen, setDeleteModalOpen] = useState(false);
+ const [channelToDelete, setChannelToDelete] = useState<NotificationChannel | null>(null);
+
+ const handleToggleChannel = async (channel: NotificationChannel) => {
+ try {
+ await updateChannel.mutateAsync({
+ id: channel.id,
+ data: { enabled: !channel.enabled },
+ });
+ toast.success(channel.enabled ? "Channel disabled" : "Channel enabled");
+ } catch (error) {
+ toast.error("Failed to update channel");
+ }
+ };
+
+ const handleDeleteChannel = async () => {
+ if (!channelToDelete) return;
+
+ try {
+ await deleteChannel.mutateAsync(channelToDelete.id);
+ toast.success("Channel deleted");
+ setChannelToDelete(null);
+ } catch (error) {
+ toast.error("Failed to delete channel");
+ throw error; // Re-throw to show error in modal
+ }
+ };
+
+ const openDeleteModal = (channel: NotificationChannel) => {
+ setChannelToDelete(channel);
+ setDeleteModalOpen(true);
+ };
+
+ const handleTestChannel = async (channel: NotificationChannel) => {
+ try {
+ await testChannel.mutateAsync(channel.id);
+ toast.success("Test notification sent");
+ } catch (error) {
+ toast.error("Failed to send test notification");
+ }
+ };
+
+ const openCreateDialog = (type: ChannelType) => {
+ if (CHANNEL_CONFIG[type].disabled) {
+ toast.info("This channel type is coming soon");
+ return;
+ }
+ openDialog(type);
+ };
+
+ const openEditDialog = (channel: NotificationChannel) => {
+ openDialog(channel.type, channel);
+ };
+
+ return (
+ <>
+ <div className="mb-6">
+ <h1 className="text-2xl font-semibold">Notifications</h1>
+ <p className="text-sm text-neutral-500 mt-1">Configure how you want to be notified about monitor incidents</p>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
+ {Object.entries(CHANNEL_CONFIG).map(([type, config]) => {
+ const Icon = config.icon;
+ return (
+ <div
+ key={type}
+ className={cn(
+ "bg-neutral-900 border border-neutral-800 rounded-lg p-4 flex items-center justify-between"
+ )}
+ onClick={() => openCreateDialog(type as ChannelType)}
+ >
+ <div className="flex flex-col gap-2">
+ <CardTitle className="flex items-center gap-2">
+ <Icon className={cn("w-4 h-4")} />
+ <span className="text-base">{config.title}</span>
+ </CardTitle>
+ <CardDescription>
+ {config.description}
+ {config.disabled && " - Coming soon"}
+ </CardDescription>
+ </div>
+ <Button variant="success" disabled={config.disabled}>
+ Create
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ <div className="space-y-4">
+ <h2 className="text-lg font-medium">Active Channels</h2>
+ {data?.channels?.length === 0 && !isLoading ? (
+ <Card>
+ <CardContent className="p-8 text-center text-neutral-500">
+ No notification channels configured yet
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Channel</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead>Details</TableHead>
+ <TableHead className="text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isLoading
+ ? Array.from({ length: 3 }).map((_, i) => (
+ <TableRow key={`skeleton-${i}`}>
+ <TableCell>
+ <div className="space-y-1">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-3 w-16" />
+ </div>
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-40" />
+ </TableCell>
+ <TableCell className="text-right">
+ <Skeleton className="h-8 w-8 ml-auto" />
+ </TableCell>
+ </TableRow>
+ ))
+ : data?.channels?.map((channel) => {
+ const config = CHANNEL_CONFIG[channel.type];
+ const Icon = config.icon;
+ return (
+ <TableRow key={channel.id}>
+ <TableCell className="font-medium">
+ <div className="flex items-center gap-2">
+ {channel.name}
+ {!channel.enabled && (
+ <span className="text-xs bg-neutral-800 text-neutral-400 px-2 py-0.5 rounded">
+ Disabled
+ </span>
+ )}
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <Icon className="w-4 h-4" />
+ <span className="capitalize">{channel.type}</span>
+ </div>
+ </TableCell>
+ <TableCell className="text-sm text-neutral-500">
+ {channel.type === "email" && channel.config?.email}
+ {channel.type === "discord" && "Discord webhook"}
+ {channel.type === "slack" && `Slack ${channel.config?.slackChannel || "webhook"}`}
+ {channel.type === "sms" && channel.config?.phoneNumber}
+ </TableCell>
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
+ <MoreHorizontal className="h-4 w-4" />
+ <span className="sr-only">Open menu</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => handleToggleChannel(channel)}>
+ <Power className="mr-2 h-4 w-4" />
+ {channel.enabled ? "Disable" : "Enable"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => handleTestChannel(channel)}
+ disabled={!channel.enabled}
+ >
+ <Bell className="mr-2 h-4 w-4" />
+ Test
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => openEditDialog(channel)}>
+ <Edit className="mr-2 h-4 w-4" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => openDeleteModal(channel)} className="text-red-600">
+ <Trash2 className="mr-2 h-4 w-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </Card>
+ )}
+ </div>
+ <NotificationDialog />
+ <ConfirmationModal
+ isOpen={deleteModalOpen}
+ setIsOpen={setDeleteModalOpen}
+ onConfirm={handleDeleteChannel}
+ title="Delete Notification Channel"
+ description={
+ channelToDelete ? (
+ <>
+ Are you sure you want to delete the notification channel <strong>{channelToDelete.name}</strong>? This
+ action cannot be undone.
+ </>
+ ) : (
+ "Are you sure you want to delete this notification channel?"
+ )
+ }
+ primaryAction={{
+ children: "Delete Channel",
+ variant: "destructive",
+ }}
+ />
+ </>
+ );
+}
diff --git a/client/src/app/uptime/page.tsx b/client/src/app/uptime/page.tsx
new file mode 100644
index 000000000..80f97d9c3
--- /dev/null
+++ b/client/src/app/uptime/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useEffect } from "react";
+
+export default function UptimePage() {
+ const router = useRouter();
+
+ useEffect(() => {
+ router.replace("/uptime/monitors");
+ }, [router]);
+
+ return null;
+}
diff --git a/client/src/app/uptime/status-page/page.tsx b/client/src/app/uptime/status-page/page.tsx
new file mode 100644
index 000000000..612c5b7c4
--- /dev/null
+++ b/client/src/app/uptime/status-page/page.tsx
@@ -0,0 +1,10 @@
+export default function StatusPage() {
+ return (
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-2xl font-semibold">Uptime Monitoring</h1>
+ <p className="text-sm text-neutral-500 mt-1">Monitor the availability and performance of your endpoints</p>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/AppSidebar.tsx b/client/src/components/AppSidebar.tsx
new file mode 100644
index 000000000..2597ca49f
--- /dev/null
+++ b/client/src/components/AppSidebar.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { BarChart, SquareActivity, User } from "lucide-react";
+import Image from "next/image";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { useState } from "react";
+import { IS_CLOUD } from "../lib/const";
+import { cn } from "../lib/utils";
+
+export function AppSidebar() {
+ const pathname = usePathname();
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ return (
+ <div
+ className={cn(
+ "flex flex-col items-start justify-between h-screen p-2 py-3 bg-neutral-900 border-r border-neutral-800 gap-3 transition-all duration-1s00",
+ isExpanded ? "w-44" : "w-[45px]"
+ )}
+ onMouseEnter={() => setIsExpanded(true)}
+ onMouseLeave={() => setIsExpanded(false)}
+ >
+ <div className="flex flex-col items-start gap-2">
+ <Link href="/" className="mb-3 mt-1 ml-0.5 flex items-center justify-center">
+ <Image src="/rybbit.svg" alt="Rybbit" width={24} height={18} />
+ </Link>
+ <SidebarLink
+ href="/"
+ icon={<BarChart className="w-5 h-5" />}
+ label="Analytics"
+ active={pathname === "/" || !isNaN(Number(pathname.split("/")[1]))}
+ expanded={isExpanded}
+ />
+ <SidebarLink
+ href="/uptime/monitors"
+ icon={<SquareActivity className="w-5 h-5" />}
+ label="Uptime"
+ active={pathname.startsWith("/uptime")}
+ expanded={isExpanded}
+ />
+ </div>
+ <SidebarLink
+ href="/settings/account"
+ icon={<User className="w-5 h-5" />}
+ label="Account"
+ active={pathname.startsWith("/settings/account")}
+ expanded={isExpanded}
+ />
+ </div>
+ );
+}
+
+function SidebarLink({
+ active = false,
+ href,
+ icon,
+ label,
+ expanded = false,
+}: {
+ active?: boolean;
+ href: string;
+ icon?: React.ReactNode;
+ label?: string;
+ expanded?: boolean;
+}) {
+ return (
+ <Link href={href} className="focus:outline-none">
+ <div
+ className={cn(
+ "p-1 rounded-md transition-all duration-200 flex items-center gap-2",
+ active ? "bg-neutral-800 text-white" : "text-neutral-400 hover:text-white hover:bg-neutral-800/80"
+ // expanded ? "w-40" : "w-12"
+ )}
+ >
+ <div className="flex items-center justify-center w-5 h-5 flex-shrink-0">{icon}</div>
+ {expanded && label && (
+ <span className="text-sm font-medium whitespace-nowrap overflow-hidden w-[120px]">{label}</span>
+ )}
+ </div>
+ </Link>
+ );
+}
diff --git a/client/src/components/StandardPage.tsx b/client/src/components/StandardPage.tsx
index 409d09710..2d60a6b31 100644
--- a/client/src/components/StandardPage.tsx
+++ b/client/src/components/StandardPage.tsx
@@ -1,10 +1,10 @@
-import { TopBar } from "./TopBar";
+import { AppSidebar } from "./AppSidebar";
-export function StandardPage({ children }: { children: React.ReactNode }) {
+export function StandardPage({ children, showSidebar = true }: { children: React.ReactNode; showSidebar?: boolean }) {
return (
- <div className="min-h-full">
- <TopBar />
- <main className="flex flex-col items-center p-4">
+ <div className="h-full flex w-full">
+ {showSidebar && <AppSidebar />}
+ <main className="flex flex-col items-center px-4 py-4 w-full h-screen overflow-y-auto">
<div className="w-full max-w-6xl">{children}</div>
</main>
</div>
diff --git a/client/src/components/ui/badge.tsx b/client/src/components/ui/badge.tsx
index a09964691..4f0887312 100644
--- a/client/src/components/ui/badge.tsx
+++ b/client/src/components/ui/badge.tsx
@@ -4,23 +4,33 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
- "inline-flex items-center rounded-md border border-neutral-200 px-1 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 dark:border-neutral-800 dark:focus:ring-neutral-300",
+ "inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 dark:focus:ring-neutral-300",
{
variants: {
variant: {
default:
- "border-transparent bg-neutral-900 text-neutral-50 shadow hover:bg-neutral-900/80 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/80",
+ "border-neutral-200 bg-neutral-100 text-neutral-900 hover:bg-neutral-200/80 dark:border-neutral-800 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700",
secondary:
- "border-transparent bg-neutral-100 text-neutral-900 hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",
+ "border-neutral-200/50 bg-neutral-50 text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-300 dark:hover:bg-neutral-800",
destructive:
- "border-transparent bg-red-500 text-neutral-50 shadow hover:bg-red-500/80 dark:bg-red-900 dark:text-neutral-50 dark:hover:bg-red-900/80",
+ "border-transparent bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:bg-red-500/20 dark:text-red-400 dark:hover:bg-red-500/30",
warning:
- "border-transparent bg-yellow-500 text-neutral-50 shadow hover:bg-yellow-500/80 dark:bg-yellow-800 dark:text-neutral-50 dark:hover:bg-yellow-800/80",
- outline: "text-neutral-950 dark:text-neutral-50",
+ "border-transparent bg-yellow-500/10 text-yellow-700 hover:bg-yellow-500/20 dark:bg-yellow-500/20 dark:text-yellow-400 dark:hover:bg-yellow-500/30",
+ success:
+ "border-transparent bg-green-500/10 text-green-700 hover:bg-green-500/20 dark:bg-green-500/20 dark:text-green-400 dark:hover:bg-green-500/30",
+ info:
+ "border-transparent bg-blue-500/10 text-blue-700 hover:bg-blue-500/20 dark:bg-blue-500/20 dark:text-blue-400 dark:hover:bg-blue-500/30",
+ outline:
+ "border-neutral-300 bg-transparent text-neutral-700 hover:bg-neutral-50 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800",
+ ghost:
+ "border-transparent bg-transparent text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",
+ // Legacy variants for backwards compatibility
green:
- "border-transparent bg-green-500 text-green-200 shadow hover:bg-green-500/80 dark:bg-green-900 dark:text-green-300 dark:hover:bg-green-900/80",
- red: "border-transparent bg-red-500 text-red-200 shadow hover:bg-red-500/80 dark:bg-red-900 dark:text-red-300 dark:hover:bg-red-900/80",
- minimal: "border-transparent bg-neutral-700 text-neutral-200",
+ "border-transparent bg-green-500/10 text-green-700 hover:bg-green-500/20 dark:bg-green-500/20 dark:text-green-400 dark:hover:bg-green-500/30",
+ red:
+ "border-transparent bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:bg-red-500/20 dark:text-red-400 dark:hover:bg-red-500/30",
+ minimal:
+ "border-transparent bg-neutral-200/50 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400",
},
},
defaultVariants: {
diff --git a/client/src/components/ui/checkbox.tsx b/client/src/components/ui/checkbox.tsx
new file mode 100644
index 000000000..f3870a27d
--- /dev/null
+++ b/client/src/components/ui/checkbox.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import * as React from "react";
+import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
+import { CheckIcon } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
+ return (
+ <CheckboxPrimitive.Root
+ data-slot="checkbox"
+ className={cn(
+ "peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator
+ data-slot="checkbox-indicator"
+ className="flex items-center justify-center text-current transition-none"
+ >
+ <CheckIcon className="size-3.5" />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+ );
+}
+
+export { Checkbox };
diff --git a/client/src/components/ui/command.tsx b/client/src/components/ui/command.tsx
new file mode 100644
index 000000000..17169047a
--- /dev/null
+++ b/client/src/components/ui/command.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import * as React from "react";
+import { Command as CommandPrimitive } from "cmdk";
+import { SearchIcon } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+
+function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
+ return (
+ <CommandPrimitive
+ data-slot="command"
+ className={cn(
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-neutral-950 dark:bg-neutral-900 dark:text-neutral-50",
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandDialog({
+ title = "Command Palette",
+ description = "Search for a command to run...",
+ children,
+ className,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof Dialog> & {
+ title?: string;
+ description?: string;
+ className?: string;
+ showCloseButton?: boolean;
+}) {
+ return (
+ <Dialog {...props}>
+ <DialogHeader className="sr-only">
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <DialogContent className={cn("overflow-hidden p-0", className)}>
+ {/* <DialogContent className={cn("overflow-hidden p-0", className)} showCloseButton={showCloseButton}> */}
+ <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
+ {children}
+ </Command>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function CommandInput({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) {
+ return (
+ <div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b border-neutral-200 px-3 dark:border-neutral-800">
+ <SearchIcon className="h-4 w-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ data-slot="command-input"
+ className={cn(
+ "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-neutral-500 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-neutral-400",
+ className
+ )}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
+ return (
+ <CommandPrimitive.List
+ data-slot="command-list"
+ className={cn("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto p-1", className)}
+ {...props}
+ />
+ );
+}
+
+function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
+ return <CommandPrimitive.Empty data-slot="command-empty" className="py-6 text-center text-sm text-neutral-500 dark:text-neutral-400" {...props} />;
+}
+
+function CommandGroup({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Group>) {
+ return (
+ <CommandPrimitive.Group
+ data-slot="command-group"
+ className={cn(
+ "overflow-hidden text-neutral-950 dark:text-neutral-50 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-neutral-500 dark:[&_[cmdk-group-heading]]:text-neutral-400",
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandSeparator({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Separator>) {
+ return (
+ <CommandPrimitive.Separator
+ data-slot="command-separator"
+ className={cn("-mx-1 my-1 h-px bg-neutral-100 dark:bg-neutral-800", className)}
+ {...props}
+ />
+ );
+}
+
+function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {
+ return (
+ <CommandPrimitive.Item
+ data-slot="command-item"
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-neutral-100 data-[selected=true]:text-neutral-900 data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 dark:data-[selected=true]:bg-neutral-800 dark:data-[selected=true]:text-neutral-50",
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandShortcut({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="command-shortcut"
+ className={cn("ml-auto text-xs tracking-widest text-neutral-500 dark:text-neutral-400", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Command,
+ CommandDialog,
+ CommandInput,
+ CommandList,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandShortcut,
+ CommandSeparator,
+};
diff --git a/client/src/components/ui/form.tsx b/client/src/components/ui/form.tsx
index 0fbc12c5b..561d75458 100644
--- a/client/src/components/ui/form.tsx
+++ b/client/src/components/ui/form.tsx
@@ -80,7 +80,7 @@ const FormItem = React.forwardRef<
return (
<FormItemContext.Provider value={{ id }}>
- <div ref={ref} className={cn("space-y-2", className)} {...props} />
+ <div ref={ref} className={cn("space-y-1", className)} {...props} />
</FormItemContext.Provider>
)
})
diff --git a/client/src/components/ui/label.tsx b/client/src/components/ui/label.tsx
index 0df6941a1..892294421 100644
--- a/client/src/components/ui/label.tsx
+++ b/client/src/components/ui/label.tsx
@@ -12,14 +12,9 @@ const labelVariants = cva(
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
- VariantProps<typeof labelVariants>
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
- <LabelPrimitive.Root
- ref={ref}
- className={cn(labelVariants(), className)}
- {...props}
- />
+ <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
));
Label.displayName = LabelPrimitive.Root.displayName;
diff --git a/client/src/components/ui/multi-select.tsx b/client/src/components/ui/multi-select.tsx
new file mode 100644
index 000000000..cdda5e136
--- /dev/null
+++ b/client/src/components/ui/multi-select.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import * as React from "react";
+import { Check, X, ChevronsUpDown } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
+
+export interface MultiSelectOption {
+ value: string;
+ label: string;
+ disabled?: boolean;
+}
+
+interface MultiSelectProps {
+ options: MultiSelectOption[];
+ value?: string[];
+ onValueChange?: (value: string[]) => void;
+ placeholder?: string;
+ searchPlaceholder?: string;
+ emptyText?: string;
+ disabled?: boolean;
+ className?: string;
+ badgeClassName?: string;
+}
+
+export function MultiSelect({
+ options,
+ value = [],
+ onValueChange,
+ placeholder = "Select items...",
+ searchPlaceholder = "Search...",
+ emptyText = "No items found.",
+ disabled = false,
+ className,
+ badgeClassName,
+}: MultiSelectProps) {
+ const [open, setOpen] = React.useState(false);
+ const [search, setSearch] = React.useState("");
+
+ const selected = React.useMemo(() => options.filter((option) => value.includes(option.value)), [options, value]);
+
+ const handleSelect = (option: MultiSelectOption) => {
+ const newValue = value.includes(option.value) ? value.filter((v) => v !== option.value) : [...value, option.value];
+ onValueChange?.(newValue);
+ };
+
+ const handleRemove = (option: MultiSelectOption) => {
+ onValueChange?.(value.filter((v) => v !== option.value));
+ };
+
+ const filteredOptions = React.useMemo(() => {
+ if (!search) return options;
+ const searchLower = search.toLowerCase();
+ return options.filter((option) => option.label.toLowerCase().includes(searchLower));
+ }, [options, search]);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ disabled={disabled}
+ className={cn("w-full justify-between min-h-10 h-auto", selected.length > 0 && "px-3 py-2", className)}
+ >
+ <div className="flex gap-1 flex-wrap">
+ {selected.length > 0 ? (
+ selected.map((option) => (
+ <Badge key={option.value} variant="secondary" className={cn("mr-1", badgeClassName)}>
+ {option.label}
+ <button
+ className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ e.stopPropagation();
+ handleRemove(option);
+ }
+ }}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleRemove(option);
+ }}
+ >
+ <X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
+ </button>
+ </Badge>
+ ))
+ ) : (
+ <span className="text-muted-foreground">{placeholder}</span>
+ )}
+ </div>
+ <ChevronsUpDown className="h-4 w-4 shrink-0 opacity-50 ml-2" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0" align="start">
+ <Command>
+ <CommandInput placeholder={searchPlaceholder} value={search} onValueChange={setSearch} />
+ <CommandList>
+ <CommandEmpty>{emptyText}</CommandEmpty>
+ <CommandGroup>
+ {filteredOptions.map((option) => {
+ const isSelected = value.includes(option.value);
+ return (
+ <CommandItem
+ key={option.value}
+ disabled={option.disabled}
+ onSelect={() => handleSelect(option)}
+ className="cursor-pointer"
+ >
+ <Check className={cn("mr-2 h-4 w-4", isSelected ? "opacity-100" : "opacity-0")} />
+ {option.label}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/client/src/components/ui/table.tsx b/client/src/components/ui/table.tsx
index f0d7ceff5..1f62975d1 100644
--- a/client/src/components/ui/table.tsx
+++ b/client/src/components/ui/table.tsx
@@ -2,126 +2,84 @@ import * as React from "react";
import { cn } from "@/lib/utils";
-const Table = React.forwardRef<
- HTMLTableElement,
- React.HTMLAttributes<HTMLTableElement>
->(({ className, ...props }, ref) => (
- <div className="relative w-full overflow-auto">
- <table
- ref={ref}
- className={cn("w-full caption-bottom text-sm", className)}
- {...props}
- />
- </div>
-));
+const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
+ ({ className, ...props }, ref) => (
+ <div className="relative w-full overflow-auto">
+ <table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
+ </div>
+ )
+);
Table.displayName = "Table";
-const TableHeader = React.forwardRef<
- HTMLTableSectionElement,
- React.HTMLAttributes<HTMLTableSectionElement>
->(({ className, ...props }, ref) => (
- <thead
- ref={ref}
- className={cn("[&_tr]:border-b-neutral-600", className)}
- {...props}
- />
-));
+const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
+ ({ className, ...props }, ref) => (
+ <thead ref={ref} className={cn("[&_tr]:border-b-neutral-700 bg-neutral-850", className)} {...props} />
+ )
+);
TableHeader.displayName = "TableHeader";
-const TableBody = React.forwardRef<
- HTMLTableSectionElement,
- React.HTMLAttributes<HTMLTableSectionElement>
->(({ className, ...props }, ref) => (
- <tbody
- ref={ref}
- className={cn("[&_tr:last-child]:border-0", className)}
- {...props}
- />
-));
+const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
+ ({ className, ...props }, ref) => (
+ <tbody ref={ref} className={cn("[&_tr:last-child]:border-0 bg-neutral-900", className)} {...props} />
+ )
+);
TableBody.displayName = "TableBody";
-const TableFooter = React.forwardRef<
- HTMLTableSectionElement,
- React.HTMLAttributes<HTMLTableSectionElement>
->(({ className, ...props }, ref) => (
- <tfoot
- ref={ref}
- className={cn(
- "border-t bg-neutral-100/50 font-medium [&>tr]:last:border-b-0 dark:bg-neutral-800/50",
- className
- )}
- {...props}
- />
-));
+const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
+ ({ className, ...props }, ref) => (
+ <tfoot
+ ref={ref}
+ className={cn("border-t bg-neutral-100/50 font-medium [&>tr]:last:border-b-0 dark:bg-neutral-800/50", className)}
+ {...props}
+ />
+ )
+);
TableFooter.displayName = "TableFooter";
-const TableRow = React.forwardRef<
- HTMLTableRowElement,
- React.HTMLAttributes<HTMLTableRowElement>
->(({ className, ...props }, ref) => (
- <tr
- ref={ref}
- className={cn(
- "border-b border-b-neutral-700 transition-colors hover:bg-neutral-100/50 data-[state=selected]:bg-neutral-100 dark:hover:bg-neutral-800/50 dark:data-[state=selected]:bg-neutral-800",
- className
- )}
- {...props}
- />
-));
+const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
+ ({ className, ...props }, ref) => (
+ <tr
+ ref={ref}
+ className={cn(
+ "border-b border-b-neutral-700 transition-colors hover:bg-neutral-100/50 data-[state=selected]:bg-neutral-100 dark:hover:bg-neutral-800/50 dark:data-[state=selected]:bg-neutral-800",
+ className
+ )}
+ {...props}
+ />
+ )
+);
TableRow.displayName = "TableRow";
-const TableHead = React.forwardRef<
- HTMLTableCellElement,
- React.ThHTMLAttributes<HTMLTableCellElement>
->(({ className, ...props }, ref) => (
- <th
- ref={ref}
- className={cn(
- "h-10 px-2 text-left align-middle font-medium text-neutral-500 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] dark:text-neutral-400",
- className
- )}
- {...props}
- />
-));
+const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
+ ({ className, ...props }, ref) => (
+ <th
+ ref={ref}
+ className={cn(
+ "h-10 px-2 text-left align-middle font-medium text-neutral-500 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] dark:text-neutral-400",
+ className
+ )}
+ {...props}
+ />
+ )
+);
TableHead.displayName = "TableHead";
-const TableCell = React.forwardRef<
- HTMLTableCellElement,
- React.TdHTMLAttributes<HTMLTableCellElement>
->(({ className, ...props }, ref) => (
- <td
- ref={ref}
- className={cn(
- "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
- className
- )}
- {...props}
- />
-));
+const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
+ ({ className, ...props }, ref) => (
+ <td
+ ref={ref}
+ className={cn("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className)}
+ {...props}
+ />
+ )
+);
TableCell.displayName = "TableCell";
-const TableCaption = React.forwardRef<
- HTMLTableCaptionElement,
- React.HTMLAttributes<HTMLTableCaptionElement>
->(({ className, ...props }, ref) => (
- <caption
- ref={ref}
- className={cn(
- "mt-4 text-sm text-neutral-500 dark:text-neutral-400",
- className
- )}
- {...props}
- />
-));
+const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
+ ({ className, ...props }, ref) => (
+ <caption ref={ref} className={cn("mt-4 text-sm text-neutral-500 dark:text-neutral-400", className)} {...props} />
+ )
+);
TableCaption.displayName = "TableCaption";
-export {
- Table,
- TableHeader,
- TableBody,
- TableFooter,
- TableHead,
- TableRow,
- TableCell,
- TableCaption,
-};
+export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
diff --git a/client/src/middleware.ts b/client/src/middleware.ts
index 98688db80..700811dec 100644
--- a/client/src/middleware.ts
+++ b/client/src/middleware.ts
@@ -11,14 +11,8 @@ export async function middleware(request: NextRequest) {
}
// Handle GitHub OAuth callback redirect
- if (
- path.includes("/auth/callback/github") ||
- path.includes("/auth/callback/google")
- ) {
- const redirectUrl = new URL(
- `/api${path}${request.nextUrl.search}`,
- request.url
- );
+ if (path.includes("/auth/callback/github") || path.includes("/auth/callback/google")) {
+ const redirectUrl = new URL(`/api${path}${request.nextUrl.search}`, request.url);
const response = NextResponse.redirect(redirectUrl);
response.headers.set("Cache-Control", "no-store, max-age=0");
return response;
@@ -43,6 +37,8 @@ export async function middleware(request: NextRequest) {
"admin",
"organization",
"account",
+ "uptime",
+ "settings",
"_next",
"api",
];
@@ -51,9 +47,7 @@ export async function middleware(request: NextRequest) {
}
// Add cache control headers to make sure the redirect isn't cached
- const response = NextResponse.redirect(
- new URL(`/${siteId}/main`, request.url)
- );
+ const response = NextResponse.redirect(new URL(`/${siteId}/main`, request.url));
response.headers.set("Cache-Control", "no-store, max-age=0");
return response;
}
diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml
index 37270e556..72f4a64c3 100644
--- a/docker-compose.cloud.yml
+++ b/docker-compose.cloud.yml
@@ -33,15 +33,7 @@ services:
- CLICKHOUSE_USER=${CLICKHOUSE_USER:-default}
- CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-frog}
healthcheck:
- test:
- [
- "CMD",
- "wget",
- "--no-verbose",
- "--tries=1",
- "--spider",
- "http://localhost:8123/ping",
- ]
+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8123/ping"]
interval: 3s
timeout: 5s
retries: 5
@@ -61,6 +53,16 @@ services:
ports:
- "5432:5432"
+ redis:
+ image: redis:7-alpine
+ container_name: redis
+ ports:
+ - "6379:6379" # Exposed to internet for remote connections
+ volumes:
+ - redis-data:/data
+ restart: unless-stopped
+ command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:-changeme}", "--appendonly", "yes"]
+
backend:
container_name: backend
build:
@@ -88,16 +90,26 @@ services:
- GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
- GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET}
- RESEND_API_KEY=${RESEND_API_KEY}
+ # Twilio SMS configuration (cloud only)
+ - TWILIO_ACCOUNT_SID=${TWILIO_ACCOUNT_SID}
+ - TWILIO_AUTH_TOKEN=${TWILIO_AUTH_TOKEN}
+ - TWILIO_PHONE_NUMBER=${TWILIO_PHONE_NUMBER}
# R2 storage for session replay (cloud only)
- R2_ACCOUNT_ID=${R2_ACCOUNT_ID}
- R2_ACCESS_KEY_ID=${R2_ACCESS_KEY_ID}
- R2_SECRET_ACCESS_KEY=${R2_SECRET_ACCESS_KEY}
- R2_BUCKET_NAME=${R2_BUCKET_NAME:-rybbit}
+ # Redis configuration
+ - REDIS_HOST=redis
+ - REDIS_PORT=6379
+ - REDIS_PASSWORD=${REDIS_PASSWORD:-changeme}
depends_on:
clickhouse:
condition: service_healthy
postgres:
condition: service_started
+ redis:
+ condition: service_started
restart: unless-stopped
ports:
- "3001:3001"
@@ -125,5 +137,6 @@ services:
volumes:
clickhouse-data:
postgres-data:
+ redis-data:
caddy_data: # Persistent volume for Caddy's certificates and state
caddy_config: # Persistent volume for Caddy's configuration cache (optional but good practice)
diff --git a/docker-compose.yml b/docker-compose.yml
index 25238e834..39106f547 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -33,15 +33,7 @@ services:
- CLICKHOUSE_USER=${CLICKHOUSE_USER:-default}
- CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-frog}
healthcheck:
- test:
- [
- "CMD",
- "wget",
- "--no-verbose",
- "--tries=1",
- "--spider",
- "http://localhost:8123/ping",
- ]
+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8123/ping"]
interval: 3s
timeout: 5s
retries: 5
@@ -65,6 +57,16 @@ services:
start_period: 10s
restart: unless-stopped
+ redis:
+ image: redis:7-alpine
+ container_name: redis
+ ports:
+ - "127.0.0.1:6379:6379" # Only accessible locally
+ volumes:
+ - redis-data:/data
+ restart: unless-stopped
+ command: ["redis-server", "--appendonly", "yes"]
+
backend:
image: ghcr.io/rybbit-io/rybbit-backend:${IMAGE_TAG:-latest}
container_name: backend
@@ -87,11 +89,16 @@ services:
- BASE_URL=${BASE_URL}
- DISABLE_SIGNUP=${DISABLE_SIGNUP}
- DISABLE_TELEMETRY=${DISABLE_TELEMETRY}
+ # Redis configuration
+ - REDIS_HOST=redis
+ - REDIS_PORT=6379
depends_on:
clickhouse:
condition: service_healthy
postgres:
condition: service_started
+ redis:
+ condition: service_started
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:3001/api/health"]
interval: 3s
@@ -122,5 +129,6 @@ services:
volumes:
clickhouse-data:
postgres-data:
+ redis-data:
caddy_data: # Persistent volume for Caddy's certificates and state
caddy_config: # Persistent volume for Caddy's configuration cache (optional but good practice)
diff --git a/monitor-agent/.dockerignore b/monitor-agent/.dockerignore
new file mode 100644
index 000000000..64885306e
--- /dev/null
+++ b/monitor-agent/.dockerignore
@@ -0,0 +1,19 @@
+node_modules
+npm-debug.log
+.env
+.env.local
+.env.*.local
+dist
+.git
+.gitignore
+README.md
+.vscode
+.idea
+*.log
+.DS_Store
+coverage
+.nyc_output
+docker-compose*.yml
+Dockerfile*
+nginx.conf
+certs/
\ No newline at end of file
diff --git a/monitor-agent/.env.example b/monitor-agent/.env.example
new file mode 100644
index 000000000..5ce040d67
--- /dev/null
+++ b/monitor-agent/.env.example
@@ -0,0 +1,39 @@
+# Rybbit Monitor Agent Environment Configuration
+# Copy this file to .env and update with your values
+
+# Server Configuration
+PORT=3003
+HOST=0.0.0.0
+
+# Region Configuration
+# Use region codes like: us-east, us-west, eu-west, asia-pacific
+REGION=us-east
+
+# Security Configuration
+# Set ENABLE_IP_WHITELIST=true to enable IP whitelisting (optional)
+# If enabled, only IPs in ALLOWED_IPS can connect
+ENABLE_IP_WHITELIST=false
+
+# Space-separated list of IP addresses allowed to connect to this agent
+# Only used if ENABLE_IP_WHITELIST=true
+# These should be the IP addresses of your main Rybbit server
+# Example: ALLOWED_IPS="1.2.3.4 5.6.7.8"
+ALLOWED_IPS=
+
+# Domain Configuration (for Caddy SSL)
+# The domain name pointing to this monitor agent
+# Example: DOMAIN_NAME=us-east.monitor.yourdomain.com
+DOMAIN_NAME=
+
+# Timeout Configuration
+DEFAULT_TIMEOUT_MS=30000
+MAX_TIMEOUT_MS=60000
+
+# Logging
+# Options: error, warn, info, debug
+LOG_LEVEL=info
+
+# Docker Image Configuration (for docker-compose)
+# DOCKER_REGISTRY=ghcr.io
+# DOCKER_IMAGE=your-org/rybbit-monitor-agent
+# IMAGE_TAG=latest
\ No newline at end of file
diff --git a/monitor-agent/Caddyfile b/monitor-agent/Caddyfile
new file mode 100644
index 000000000..dd0577ca4
--- /dev/null
+++ b/monitor-agent/Caddyfile
@@ -0,0 +1,11 @@
+# Caddyfile for Rybbit Monitor Agent
+{$DOMAIN_NAME} {
+ # Enable compression
+ encode zstd gzip
+
+ # Set max request body size
+ request_body max_size 10MB
+
+ # Reverse proxy to monitor agent
+ reverse_proxy monitor-agent:3003
+}
\ No newline at end of file
diff --git a/monitor-agent/Caddyfile.whitelist b/monitor-agent/Caddyfile.whitelist
new file mode 100644
index 000000000..c331091ef
--- /dev/null
+++ b/monitor-agent/Caddyfile.whitelist
@@ -0,0 +1,24 @@
+# Caddyfile for Rybbit Monitor Agent with IP Whitelisting
+{$DOMAIN_NAME} {
+ # Enable compression
+ encode zstd gzip
+
+ # Set max request body size
+ request_body max_size 10MB
+
+ # Handle requests based on IP whitelist
+ @allowed {
+ # The ALLOWED_IPS env var should contain space-separated IPs
+ remote_ip {$ALLOWED_IPS}
+ }
+
+ # Proxy allowed requests to the monitor agent service
+ handle @allowed {
+ reverse_proxy monitor-agent:3003
+ }
+
+ # Block all non-whitelisted IPs
+ handle {
+ respond "Forbidden" 403
+ }
+}
\ No newline at end of file
diff --git a/monitor-agent/DEPLOYMENT.md b/monitor-agent/DEPLOYMENT.md
new file mode 100644
index 000000000..56ece3404
--- /dev/null
+++ b/monitor-agent/DEPLOYMENT.md
@@ -0,0 +1,218 @@
+# Rybbit Monitor Agent Deployment Guide
+
+This guide covers deploying the Rybbit Monitor Agent to VPS instances in different regions.
+
+## Prerequisites
+
+- VPS instances in desired regions (us-east, us-west, europe, asia)
+- Docker installed on each VPS
+- SSL certificates (or use Let's Encrypt)
+- Main Rybbit server IP address for whitelisting
+
+## Deployment Methods
+
+### Method 1: Docker Deployment (Recommended)
+
+#### 1. Initial Setup on VPS
+
+```bash
+# SSH into your VPS
+ssh user@your-vps-ip
+
+# Create directory for the agent
+sudo mkdir -p /opt/rybbit-monitor-agent
+cd /opt/rybbit-monitor-agent
+
+# Create environment file
+sudo nano .env
+```
+
+Add the following to `.env`:
+```env
+PORT=3003
+HOST=0.0.0.0
+REGION=us-east # Change based on region
+ALLOWED_IPS=1.2.3.4,5.6.7.8 # IP addresses of your main server
+DOMAIN_NAME=your-monitor-domain.com # Domain for this monitor agent
+LOG_LEVEL=info
+```
+
+#### 2. Deploy Using Docker Compose
+
+```bash
+# Download docker-compose files
+wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/docker-compose.yml
+wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/docker-compose.prod.yml
+wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/Caddyfile
+
+# Start the services
+REGION=us-east docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+
+# Check status
+docker compose ps
+docker compose logs -f
+```
+
+#### 3. SSL Setup with Caddy
+
+Caddy automatically handles SSL certificates via Let's Encrypt. Simply ensure:
+1. Your domain points to the VPS
+2. Ports 80 and 443 are open
+3. The DOMAIN_NAME environment variable is set correctly
+
+```bash
+# SSL certificates will be automatically obtained when Caddy starts
+docker compose restart caddy
+```
+
+### Method 2: Automated Deployment Script
+
+Use the provided `deploy.sh` script from your local machine:
+
+```bash
+# Deploy to a specific region
+./deploy.sh us-east deploy
+
+# Deploy to all regions
+./deploy.sh all deploy
+
+# Check status of a region
+./deploy.sh us-east status
+
+# View logs from a region
+./deploy.sh us-east logs
+```
+
+Before using the script, update the server addresses in `deploy.sh`:
+```bash
+REGIONS["us-east"]="[email protected]"
+REGIONS["us-west"]="[email protected]"
+REGIONS["europe"]="[email protected]"
+REGIONS["asia"]="[email protected]"
+```
+
+### Method 3: Systemd Service (Alternative)
+
+For non-Docker deployments:
+
+```bash
+# Copy the systemd files to your VPS
+scp -r systemd/ user@your-vps:/tmp/
+
+# SSH into the VPS
+ssh user@your-vps
+
+# Run the setup script
+cd /tmp/systemd
+sudo ./setup.sh
+
+# Configure the environment
+sudo nano /opt/rybbit-monitor-agent/.env
+
+# Restart the service
+sudo systemctl restart rybbit-monitor-agent
+```
+
+## Post-Deployment Configuration
+
+### 1. Update Main Server Database
+
+Add the agent regions to your main Rybbit server database:
+
+```sql
+UPDATE agent_regions
+SET endpoint_url = 'https://us-east-monitor.example.com',
+ enabled = true
+WHERE code = 'us-east';
+
+UPDATE agent_regions
+SET endpoint_url = 'https://us-west-monitor.example.com',
+ enabled = true
+WHERE code = 'us-west';
+
+UPDATE agent_regions
+SET endpoint_url = 'https://europe-monitor.example.com',
+ enabled = true
+WHERE code = 'europe';
+
+UPDATE agent_regions
+SET endpoint_url = 'https://asia-monitor.example.com',
+ enabled = true
+WHERE code = 'asia';
+```
+
+### 2. Configure Firewall
+
+```bash
+# Allow HTTPS traffic
+sudo ufw allow 443/tcp
+
+# Allow HTTP traffic (for Let's Encrypt)
+sudo ufw allow 80/tcp
+
+# If not using Caddy proxy, allow agent port
+sudo ufw allow 3003/tcp
+```
+
+### 3. Setup Monitoring
+
+Monitor your agents using:
+
+1. **Health Endpoint**: `https://your-monitor-domain.com/health`
+2. **Metrics Endpoint**: `https://your-monitor-domain.com/metrics`
+3. **Main Server**: Check region health in the Rybbit UI
+
+## Security Considerations
+
+1. **IP Whitelisting**: Always configure `ALLOWED_IPS` in production
+2. **SSL/TLS**: Use HTTPS for all agent endpoints
+3. **Firewall**: Restrict access to only necessary ports
+4. **Updates**: Keep Docker images and dependencies updated
+5. **Monitoring**: Set up alerts for agent downtime
+
+## Troubleshooting
+
+### Check Agent Status
+```bash
+# Docker deployment
+docker compose logs monitor-agent
+curl http://localhost:3003/health
+
+# Systemd deployment
+sudo journalctl -u rybbit-monitor-agent -f
+sudo systemctl status rybbit-monitor-agent
+```
+
+### Common Issues
+
+1. **Connection refused**: Check firewall and ALLOWED_IPS configuration
+2. **SSL errors**: Verify certificates are properly installed
+3. **High memory usage**: Adjust Docker resource limits
+4. **Agent not responding**: Check logs and restart the service
+
+### Debug Mode
+
+Enable debug logging by setting `LOG_LEVEL=debug` in the `.env` file.
+
+## Maintenance
+
+### Update Agent
+```bash
+# Docker
+docker compose pull
+docker compose up -d
+
+# Systemd
+# Copy new files and restart
+sudo systemctl restart rybbit-monitor-agent
+```
+
+### Backup Configuration
+```bash
+# Backup environment file
+cp /opt/rybbit-monitor-agent/.env /opt/rybbit-monitor-agent/.env.backup
+```
+
+### Log Rotation
+
+Logs are automatically rotated with Docker. For systemd deployments, logrotate is configured during setup.
\ No newline at end of file
diff --git a/monitor-agent/Dockerfile b/monitor-agent/Dockerfile
new file mode 100644
index 000000000..932cc3b2e
--- /dev/null
+++ b/monitor-agent/Dockerfile
@@ -0,0 +1,35 @@
+FROM node:20-alpine
+
+# Install required system packages
+RUN apk add --no-cache \
+ curl \
+ bind-tools \
+ iputils-ping
+
+WORKDIR /app
+
+# Copy package files
+COPY package*.json ./
+COPY tsconfig.json ./
+
+# Install all dependencies (including dev dependencies for build)
+RUN npm ci
+
+# Copy source code
+COPY src ./src
+
+# Build TypeScript
+RUN npm run build
+
+# Remove dev dependencies
+RUN npm prune --production
+
+# Expose port
+EXPOSE 3003
+
+# Health check
+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
+ CMD curl -f http://localhost:3003/health || exit 1
+
+# Run the application
+CMD ["node", "dist/index.js"]
\ No newline at end of file
diff --git a/monitor-agent/Dockerfile.dev b/monitor-agent/Dockerfile.dev
new file mode 100644
index 000000000..585341826
--- /dev/null
+++ b/monitor-agent/Dockerfile.dev
@@ -0,0 +1,24 @@
+FROM node:20-alpine
+
+# Install required system packages
+RUN apk add --no-cache \
+ curl \
+ bind-tools \
+ iputils-ping
+
+WORKDIR /app
+
+# Copy package files
+COPY package*.json ./
+
+# Install all dependencies (including dev)
+RUN npm ci
+
+# Copy source code
+COPY . .
+
+# Expose port
+EXPOSE 3003
+
+# Run in development mode with hot reloading
+CMD ["npm", "run", "dev"]
\ No newline at end of file
diff --git a/monitor-agent/Makefile b/monitor-agent/Makefile
new file mode 100644
index 000000000..b01e7fa1d
--- /dev/null
+++ b/monitor-agent/Makefile
@@ -0,0 +1,67 @@
+# Makefile for Rybbit Monitor Agent
+
+.PHONY: help build dev prod test clean deploy-all status-all
+
+# Default region
+REGION ?= us-east
+
+help: ## Show this help message
+ @echo 'Usage: make [target] [REGION=region]'
+ @echo ''
+ @echo 'Targets:'
+ @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
+ @echo ''
+ @echo 'Regions: us-east, us-west, europe, asia'
+
+build: ## Build the Docker image
+ docker-compose build
+
+dev: ## Run in development mode with hot reloading
+ docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
+
+prod: ## Run in production mode
+ REGION=$(REGION) docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+
+test: ## Run tests
+ npm test
+
+lint: ## Run linter
+ npm run lint
+
+clean: ## Clean up containers and images
+ docker-compose down -v
+ docker rmi rybbit-monitor-agent:latest || true
+
+logs: ## Show logs
+ docker-compose logs -f monitor-agent
+
+shell: ## Open shell in container
+ docker-compose exec monitor-agent sh
+
+deploy: ## Deploy to a specific region
+ ./deploy.sh $(REGION) deploy
+
+deploy-all: ## Deploy to all regions
+ @for region in us-east us-west europe asia; do \
+ echo "Deploying to $$region..."; \
+ ./deploy.sh $$region deploy; \
+ done
+
+status: ## Check status of a specific region
+ ./deploy.sh $(REGION) status
+
+status-all: ## Check status of all regions
+ @for region in us-east us-west europe asia; do \
+ echo "=== Status for $$region ==="; \
+ ./deploy.sh $$region status; \
+ echo ""; \
+ done
+
+install: ## Install dependencies
+ npm install
+
+build-ts: ## Build TypeScript
+ npm run build
+
+start: ## Start the agent locally
+ npm start
\ No newline at end of file
diff --git a/monitor-agent/README.md b/monitor-agent/README.md
new file mode 100644
index 000000000..23a28267d
--- /dev/null
+++ b/monitor-agent/README.md
@@ -0,0 +1,172 @@
+# Rybbit Monitor Agent
+
+Regional monitoring agent for Rybbit uptime monitoring system. This lightweight service runs on VPS instances in different regions to execute monitoring checks.
+
+## Features
+
+- HTTP/HTTPS monitoring with detailed timing information
+- TCP port monitoring
+- DNS monitoring (coming soon)
+- SMTP monitoring (coming soon)
+- PING monitoring (coming soon)
+- Authentication via API key
+- Health check endpoint
+- Prometheus metrics (coming soon)
+
+## Deployment
+
+### 1. Environment Configuration
+
+Copy `.env.example` to `.env` and configure:
+
+```bash
+cp .env.example .env
+```
+
+Key configuration:
+- `REGION`: Unique identifier for this region (e.g., 'us-east', 'europe')
+- `API_KEY`: Shared secret with main server
+- `ALLOWED_IPS`: Optional IP whitelist for main server
+
+### 2. Docker Deployment
+
+Build and run with Docker:
+
+```bash
+# Build
+docker build -t monitor-agent .
+
+# Run
+docker run -d \
+ --name monitor-agent \
+ -p 3003:3003 \
+ --env-file .env \
+ --restart always \
+ monitor-agent
+```
+
+### 3. Docker Compose
+
+```yaml
+version: '3.8'
+services:
+ monitor-agent:
+ build: .
+ ports:
+ - "3003:3003"
+ env_file:
+ - .env
+ restart: always
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:3003/health"]
+ interval: 30s
+ timeout: 10s
+ retries: 3
+```
+
+### 4. Direct Node.js
+
+```bash
+# Install dependencies
+npm install
+
+# Build
+npm run build
+
+# Run
+npm start
+```
+
+## API Endpoints
+
+### POST /execute
+Execute a monitoring check.
+
+Request:
+```json
+{
+ "jobId": "unique-job-id",
+ "monitorId": 123,
+ "monitorType": "http",
+ "config": {
+ "url": "https://example.com",
+ "method": "GET",
+ "timeoutMs": 30000
+ },
+ "validationRules": []
+}
+```
+
+Response:
+```json
+{
+ "jobId": "unique-job-id",
+ "region": "us-east",
+ "status": "success",
+ "responseTimeMs": 234,
+ "statusCode": 200,
+ "headers": {},
+ "timing": {
+ "dnsMs": 12,
+ "tcpMs": 45,
+ "tlsMs": 67,
+ "ttfbMs": 123,
+ "transferMs": 111
+ }
+}
+```
+
+### GET /health
+Health check endpoint.
+
+### GET /metrics
+Prometheus metrics endpoint (coming soon).
+
+## Regional Deployment
+
+### Recommended VPS Providers
+
+1. **US-East**: DigitalOcean NYC, Vultr New Jersey
+2. **US-West**: Vultr Los Angeles, Linode Fremont
+3. **Europe**: Hetzner Frankfurt, DigitalOcean Amsterdam
+4. **Asia**: Vultr Singapore, Linode Tokyo
+
+### Deployment Script
+
+```bash
+#!/bin/bash
+REGION=$1
+DOCKER_IMAGE="your-registry.com/monitor-agent:$REGION"
+
+# Build and push
+docker build -t $DOCKER_IMAGE .
+docker push $DOCKER_IMAGE
+
+# Deploy to VPS
+ssh $REGION_HOST << EOF
+ docker pull $DOCKER_IMAGE
+ docker stop monitor-agent || true
+ docker rm monitor-agent || true
+ docker run -d \
+ --name monitor-agent \
+ -p 443:3003 \
+ --env-file /etc/monitor-agent/.env \
+ --restart always \
+ $DOCKER_IMAGE
+EOF
+```
+
+## Security Considerations
+
+1. Always use HTTPS in production (reverse proxy with Caddy)
+2. Keep API keys secure and rotate regularly
+3. Use IP whitelisting when possible
+4. Monitor agent logs for suspicious activity
+5. Keep the agent updated with security patches
+
+## Monitoring the Monitor
+
+The main server should health check each agent:
+- Check `/health` endpoint every 30 seconds
+- Alert if agent is down
+- Automatic failover to other regions if needed
\ No newline at end of file
diff --git a/monitor-agent/deploy.sh b/monitor-agent/deploy.sh
new file mode 100755
index 000000000..576c2c4a7
--- /dev/null
+++ b/monitor-agent/deploy.sh
@@ -0,0 +1,157 @@
+#!/bin/bash
+
+# Deploy script for monitor agents
+# Usage: ./deploy.sh [region] [action]
+# Example: ./deploy.sh us-east deploy
+
+set -e
+
+REGION=${1:-us-east}
+ACTION=${2:-deploy}
+DOCKER_REGISTRY=${DOCKER_REGISTRY:-docker.io}
+DOCKER_IMAGE=${DOCKER_IMAGE:-rybbit/monitor-agent}
+VERSION=${VERSION:-latest}
+
+# Region configurations
+declare -A REGIONS
+REGIONS["us-east"]="[email protected]"
+REGIONS["us-west"]="[email protected]"
+REGIONS["europe"]="[email protected]"
+REGIONS["asia"]="[email protected]"
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# Functions
+log_info() {
+ echo -e "${GREEN}[INFO]${NC} $1"
+}
+
+log_warn() {
+ echo -e "${YELLOW}[WARN]${NC} $1"
+}
+
+log_error() {
+ echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Check if region exists
+if [[ ! ${REGIONS[$REGION]} ]]; then
+ log_error "Unknown region: $REGION"
+ echo "Available regions: ${!REGIONS[@]}"
+ exit 1
+fi
+
+SERVER=${REGIONS[$REGION]}
+
+case $ACTION in
+ build)
+ log_info "Building Docker image for $REGION..."
+ docker build -t $DOCKER_IMAGE:$REGION .
+ docker tag $DOCKER_IMAGE:$REGION $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
+ docker tag $DOCKER_IMAGE:$REGION $DOCKER_REGISTRY/$DOCKER_IMAGE:$VERSION
+ ;;
+
+ push)
+ log_info "Pushing Docker image for $REGION..."
+ docker push $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
+ docker push $DOCKER_REGISTRY/$DOCKER_IMAGE:$VERSION
+ ;;
+
+ deploy)
+ log_info "Deploying to $REGION ($SERVER)..."
+
+ # Build and push first
+ $0 $REGION build
+ $0 $REGION push
+
+ # Deploy to server
+ ssh $SERVER << EOF
+ set -e
+
+ # Create directories
+ mkdir -p /opt/rybbit-monitor-agent
+ cd /opt/rybbit-monitor-agent
+
+ # Create .env file if it doesn't exist
+ if [ ! -f .env ]; then
+ echo "Creating .env file..."
+ cat > .env << 'ENVFILE'
+PORT=3003
+HOST=0.0.0.0
+REGION=$REGION
+ALLOWED_IPS=\${ALLOWED_IPS:-}
+LOG_LEVEL=info
+ENVFILE
+ echo "Please edit /opt/rybbit-monitor-agent/.env with correct values"
+ fi
+
+ # Pull latest image
+ docker pull $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
+
+ # Stop existing container
+ docker stop rybbit-monitor-agent 2>/dev/null || true
+ docker rm rybbit-monitor-agent 2>/dev/null || true
+
+ # Start new container
+ docker run -d \
+ --name rybbit-monitor-agent \
+ --restart always \
+ -p 3003:3003 \
+ --env-file .env \
+ -e REGION=$REGION \
+ $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
+
+ # Check if container is running
+ sleep 5
+ if docker ps | grep -q rybbit-monitor-agent; then
+ echo "Container started successfully"
+ docker logs --tail 20 rybbit-monitor-agent
+ else
+ echo "Container failed to start"
+ docker logs rybbit-monitor-agent
+ exit 1
+ fi
+EOF
+ log_info "Deployment to $REGION completed!"
+ ;;
+
+ status)
+ log_info "Checking status of $REGION ($SERVER)..."
+ ssh $SERVER << EOF
+ echo "=== Container Status ==="
+ docker ps -a | grep rybbit-monitor-agent || echo "No container found"
+ echo ""
+ echo "=== Recent Logs ==="
+ docker logs --tail 20 rybbit-monitor-agent 2>&1 || echo "No logs available"
+ echo ""
+ echo "=== Health Check ==="
+ curl -s http://localhost:3003/health | jq . || echo "Health check failed"
+EOF
+ ;;
+
+ logs)
+ log_info "Fetching logs from $REGION ($SERVER)..."
+ ssh $SERVER "docker logs --tail 100 -f rybbit-monitor-agent"
+ ;;
+
+ restart)
+ log_info "Restarting $REGION ($SERVER)..."
+ ssh $SERVER "docker restart rybbit-monitor-agent"
+ ;;
+
+ stop)
+ log_info "Stopping $REGION ($SERVER)..."
+ ssh $SERVER "docker stop rybbit-monitor-agent"
+ ;;
+
+ *)
+ echo "Usage: $0 [region] [action]"
+ echo "Regions: ${!REGIONS[@]}"
+ echo "Actions: build, push, deploy, status, logs, restart, stop"
+ exit 1
+ ;;
+esac
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.dev.yml b/monitor-agent/docker-compose.dev.yml
new file mode 100644
index 000000000..8dc48d4b9
--- /dev/null
+++ b/monitor-agent/docker-compose.dev.yml
@@ -0,0 +1,18 @@
+# Development-specific configuration
+services:
+ monitor-agent:
+ build:
+ context: .
+ dockerfile: Dockerfile.dev
+ volumes:
+ # Mount source code for hot reloading
+ - ./src:/app/src:ro
+ - ./package.json:/app/package.json:ro
+ - ./tsconfig.json:/app/tsconfig.json:ro
+ # Exclude node_modules
+ - /app/node_modules
+ environment:
+ # Development overrides
+ - LOG_LEVEL=debug
+ - NODE_ENV=development
+ command: npm run dev
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.prod.yml b/monitor-agent/docker-compose.prod.yml
new file mode 100644
index 000000000..9af53410b
--- /dev/null
+++ b/monitor-agent/docker-compose.prod.yml
@@ -0,0 +1,65 @@
+# Production deployment with multiple regions
+# Usage: REGION=us-east docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+
+services:
+ monitor-agent:
+ image: ${DOCKER_REGISTRY:-docker.io}/${DOCKER_IMAGE:-rybbit/monitor-agent}:${REGION:-latest}
+ restart: always
+
+ # Production logging
+ logging:
+ driver: "json-file"
+ options:
+ max-size: "50m"
+ max-file: "10"
+ labels: "region,service"
+
+ # Health monitoring
+ labels:
+ - "prometheus.io/scrape=true"
+ - "prometheus.io/port=3003"
+ - "prometheus.io/path=/metrics"
+ - "region=${REGION}"
+ - "service=monitor-agent"
+
+ # Production resource limits
+ deploy:
+ resources:
+ limits:
+ cpus: '1'
+ memory: 1G
+ reservations:
+ cpus: '0.5'
+ memory: 512M
+
+ # Restart policy
+ restart_policy:
+ condition: any
+ delay: 5s
+ max_attempts: 3
+ window: 120s
+
+ # Caddy with automatic SSL
+ caddy:
+ image: caddy:2.10.0
+ container_name: rybbit-monitor-caddy-${REGION}
+ ports:
+ - "443:443"
+ - "80:80"
+ - "443:443/udp" # Needed for HTTP/3
+ volumes:
+ - ./Caddyfile:/etc/caddy/Caddyfile
+ - caddy_data:/data
+ - caddy_config:/config
+ environment:
+ - DOMAIN_NAME=${DOMAIN_NAME}
+ - ALLOWED_IPS=${ALLOWED_IPS}
+ depends_on:
+ - monitor-agent
+ restart: always
+ networks:
+ - monitor-network
+
+volumes:
+ caddy_data:
+ caddy_config:
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.yml b/monitor-agent/docker-compose.yml
new file mode 100644
index 000000000..db99c4982
--- /dev/null
+++ b/monitor-agent/docker-compose.yml
@@ -0,0 +1,92 @@
+services:
+ monitor-agent:
+ build:
+ context: .
+ dockerfile: Dockerfile
+ container_name: rybbit-monitor-agent
+ ports:
+ - "${PORT:-3003}:3003"
+ environment:
+ # Server Configuration
+ - PORT=${PORT:-3003}
+ - HOST=${HOST:-0.0.0.0}
+
+ # Region Configuration
+ - REGION=${REGION:-us-east}
+
+ # Security
+ - ALLOWED_IPS=${ALLOWED_IPS:-}
+
+ # Monitoring Defaults
+ - DEFAULT_TIMEOUT_MS=${DEFAULT_TIMEOUT_MS:-30000}
+ - MAX_TIMEOUT_MS=${MAX_TIMEOUT_MS:-60000}
+
+ # Logging
+ - LOG_LEVEL=${LOG_LEVEL:-info}
+
+ # Use .env file if it exists
+ env_file:
+ - .env
+
+ restart: unless-stopped
+
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:3003/health"]
+ interval: 30s
+ timeout: 10s
+ start_period: 40s
+ retries: 3
+
+ # Resource limits
+ deploy:
+ resources:
+ limits:
+ cpus: "0.5"
+ memory: 512M
+ reservations:
+ cpus: "0.25"
+ memory: 256M
+
+ # Logging configuration
+ logging:
+ driver: "json-file"
+ options:
+ max-size: "10m"
+ max-file: "3"
+
+ # Network configuration
+ networks:
+ - monitor-network
+
+ # Caddy reverse proxy for HTTPS
+ caddy:
+ image: caddy:2.10.0
+ container_name: rybbit-monitor-caddy
+ ports:
+ - "443:443"
+ - "80:80"
+ - "443:443/udp" # Needed for HTTP/3
+ volumes:
+ - ./Caddyfile${ENABLE_IP_WHITELIST:+.whitelist}:/etc/caddy/Caddyfile
+ - caddy_data:/data
+ - caddy_config:/config
+ environment:
+ - DOMAIN_NAME=${DOMAIN_NAME}
+ - ALLOWED_IPS=${ALLOWED_IPS}
+ depends_on:
+ - monitor-agent
+ restart: unless-stopped
+ networks:
+ - monitor-network
+ profiles:
+ - with-ssl
+
+networks:
+ monitor-network:
+ driver: bridge
+
+# Volumes for persistent data
+volumes:
+ monitor-data:
+ caddy_data:
+ caddy_config:
diff --git a/monitor-agent/package-lock.json b/monitor-agent/package-lock.json
new file mode 100644
index 000000000..df6b45755
--- /dev/null
+++ b/monitor-agent/package-lock.json
@@ -0,0 +1,1566 @@
+{
+ "name": "rybbit-monitor-agent",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "rybbit-monitor-agent",
+ "version": "1.0.0",
+ "dependencies": {
+ "@fastify/cors": "^8.5.0",
+ "@fastify/rate-limit": "^9.1.0",
+ "dns-packet": "^5.6.1",
+ "dotenv": "^16.3.1",
+ "fastify": "^4.25.0",
+ "nodemailer": "^6.9.8",
+ "ping": "^0.4.4",
+ "pino": "^8.17.0",
+ "pino-pretty": "^10.3.0",
+ "undici": "^6.2.0",
+ "zod": "^3.22.4"
+ },
+ "devDependencies": {
+ "@types/node": "^20.10.0",
+ "@types/nodemailer": "^6.4.14",
+ "@types/ping": "^0.4.4",
+ "tsx": "^4.6.0",
+ "typescript": "^5.3.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.8.tgz",
+ "integrity": "sha512-urAvrUedIqEiFR3FYSLTWQgLu5tb+m0qZw0NBEasUeo6wuqatkMDaRT+1uABiGXEu5vqgPd7FGE1BhsAIy9QVA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.8.tgz",
+ "integrity": "sha512-RONsAvGCz5oWyePVnLdZY/HHwA++nxYWIX1atInlaW6SEkwq6XkP3+cb825EUcRs5Vss/lGh/2YxAb5xqc07Uw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.8.tgz",
+ "integrity": "sha512-OD3p7LYzWpLhZEyATcTSJ67qB5D+20vbtr6vHlHWSQYhKtzUYrETuWThmzFpZtFsBIxRvhO07+UgVA9m0i/O1w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.8.tgz",
+ "integrity": "sha512-yJAVPklM5+4+9dTeKwHOaA+LQkmrKFX96BM0A/2zQrbS6ENCmxc4OVoBs5dPkCCak2roAD+jKCdnmOqKszPkjA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.8.tgz",
+ "integrity": "sha512-Jw0mxgIaYX6R8ODrdkLLPwBqHTtYHJSmzzd+QeytSugzQ0Vg4c5rDky5VgkoowbZQahCbsv1rT1KW72MPIkevw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.8.tgz",
+ "integrity": "sha512-Vh2gLxxHnuoQ+GjPNvDSDRpoBCUzY4Pu0kBqMBDlK4fuWbKgGtmDIeEC081xi26PPjn+1tct+Bh8FjyLlw1Zlg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.8.tgz",
+ "integrity": "sha512-YPJ7hDQ9DnNe5vxOm6jaie9QsTwcKedPvizTVlqWG9GBSq+BuyWEDazlGaDTC5NGU4QJd666V0yqCBL2oWKPfA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.8.tgz",
+ "integrity": "sha512-MmaEXxQRdXNFsRN/KcIimLnSJrk2r5H8v+WVafRWz5xdSVmWLoITZQXcgehI2ZE6gioE6HirAEToM/RvFBeuhw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.8.tgz",
+ "integrity": "sha512-FuzEP9BixzZohl1kLf76KEVOsxtIBFwCaLupVuk4eFVnOZfU+Wsn+x5Ryam7nILV2pkq2TqQM9EZPsOBuMC+kg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.8.tgz",
+ "integrity": "sha512-WIgg00ARWv/uYLU7lsuDK00d/hHSfES5BzdWAdAig1ioV5kaFNrtK8EqGcUBJhYqotlUByUKz5Qo6u8tt7iD/w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.8.tgz",
+ "integrity": "sha512-A1D9YzRX1i+1AJZuFFUMP1E9fMaYY+GnSQil9Tlw05utlE86EKTUA7RjwHDkEitmLYiFsRd9HwKBPEftNdBfjg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.8.tgz",
+ "integrity": "sha512-O7k1J/dwHkY1RMVvglFHl1HzutGEFFZ3kNiDMSOyUrB7WcoHGf96Sh+64nTRT26l3GMbCW01Ekh/ThKM5iI7hQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.8.tgz",
+ "integrity": "sha512-uv+dqfRazte3BzfMp8PAQXmdGHQt2oC/y2ovwpTteqrMx2lwaksiFZ/bdkXJC19ttTvNXBuWH53zy/aTj1FgGw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.8.tgz",
+ "integrity": "sha512-GyG0KcMi1GBavP5JgAkkstMGyMholMDybAf8wF5A70CALlDM2p/f7YFE7H92eDeH/VBtFJA5MT4nRPDGg4JuzQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.8.tgz",
+ "integrity": "sha512-rAqDYFv3yzMrq7GIcen3XP7TUEG/4LK86LUPMIz6RT8A6pRIDn0sDcvjudVZBiiTcZCY9y2SgYX2lgK3AF+1eg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.8.tgz",
+ "integrity": "sha512-Xutvh6VjlbcHpsIIbwY8GVRbwoviWT19tFhgdA7DlenLGC/mbc3lBoVb7jxj9Z+eyGqvcnSyIltYUrkKzWqSvg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.8.tgz",
+ "integrity": "sha512-ASFQhgY4ElXh3nDcOMTkQero4b1lgubskNlhIfJrsH5OKZXDpUAKBlNS0Kx81jwOBp+HCeZqmoJuihTv57/jvQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.8.tgz",
+ "integrity": "sha512-d1KfruIeohqAi6SA+gENMuObDbEjn22olAR7egqnkCD9DGBG0wsEARotkLgXDu6c4ncgWTZJtN5vcgxzWRMzcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.8.tgz",
+ "integrity": "sha512-nVDCkrvx2ua+XQNyfrujIG38+YGyuy2Ru9kKVNyh5jAys6n+l44tTtToqHjino2My8VAY6Lw9H7RI73XFi66Cg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.8.tgz",
+ "integrity": "sha512-j8HgrDuSJFAujkivSMSfPQSAa5Fxbvk4rgNAS5i3K+r8s1X0p1uOO2Hl2xNsGFppOeHOLAVgYwDVlmxhq5h+SQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.8.tgz",
+ "integrity": "sha512-1h8MUAwa0VhNCDp6Af0HToI2TJFAn1uqT9Al6DJVzdIBAd21m/G0Yfc77KDM3uF3T/YaOgQq3qTJHPbTOInaIQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.8.tgz",
+ "integrity": "sha512-r2nVa5SIK9tSWd0kJd9HCffnDHKchTGikb//9c7HX+r+wHYCpQrSgxhlY6KWV1nFo1l4KFbsMlHk+L6fekLsUg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.8.tgz",
+ "integrity": "sha512-zUlaP2S12YhQ2UzUfcCuMDHQFJyKABkAjvO5YSndMiIkMimPmxA+BYSBikWgsRpvyxuRnow4nS5NPnf9fpv41w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.8.tgz",
+ "integrity": "sha512-YEGFFWESlPva8hGL+zvj2z/SaK+pH0SwOM0Nc/d+rVnW7GSTFlLBGzZkuSU9kFIGIo8q9X3ucpZhu8PDN5A2sQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.8.tgz",
+ "integrity": "sha512-hiGgGC6KZ5LZz58OL/+qVVoZiuZlUYlYHNAmczOm7bs2oE1XriPFi5ZHHrS8ACpV5EjySrnoCKmcbQMN+ojnHg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.8.tgz",
+ "integrity": "sha512-cn3Yr7+OaaZq1c+2pe+8yxC8E144SReCQjN6/2ynubzYjvyqZjTXfQJpAcQpsdJq3My7XADANiYGHoFC69pLQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@fastify/ajv-compiler": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-3.6.0.tgz",
+ "integrity": "sha512-LwdXQJjmMD+GwLOkP7TVC68qa+pSSogeWWmznRJ/coyTcfe9qA05AHFSe1eZFwK6q+xVRpChnvFUkf1iYaSZsQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.11.0",
+ "ajv-formats": "^2.1.1",
+ "fast-uri": "^2.0.0"
+ }
+ },
+ "node_modules/@fastify/cors": {
+ "version": "8.5.0",
+ "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-8.5.0.tgz",
+ "integrity": "sha512-/oZ1QSb02XjP0IK1U0IXktEsw/dUBTxJOW7IpIeO8c/tNalw/KjoNSJv1Sf6eqoBPO+TDGkifq6ynFK3v68HFQ==",
+ "license": "MIT",
+ "dependencies": {
+ "fastify-plugin": "^4.0.0",
+ "mnemonist": "0.39.6"
+ }
+ },
+ "node_modules/@fastify/error": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/@fastify/error/-/error-3.4.1.tgz",
+ "integrity": "sha512-wWSvph+29GR783IhmvdwWnN4bUxTD01Vm5Xad4i7i1VuAOItLvbPAb69sb0IQ2N57yprvhNIwAP5B6xfKTmjmQ==",
+ "license": "MIT"
+ },
+ "node_modules/@fastify/fast-json-stringify-compiler": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-4.3.0.tgz",
+ "integrity": "sha512-aZAXGYo6m22Fk1zZzEUKBvut/CIIQe/BapEORnxiD5Qr0kPHqqI69NtEMCme74h+at72sPhbkb4ZrLd1W3KRLA==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-json-stringify": "^5.7.0"
+ }
+ },
+ "node_modules/@fastify/merge-json-schemas": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.1.1.tgz",
+ "integrity": "sha512-fERDVz7topgNjtXsJTTW1JKLy0rhuLRcquYqNR9rF7OcVpCa2OVW49ZPDIhaRRCaUuvVxI+N416xUoF76HNSXA==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3"
+ }
+ },
+ "node_modules/@fastify/rate-limit": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-9.1.0.tgz",
+ "integrity": "sha512-h5dZWCkuZXN0PxwqaFQLxeln8/LNwQwH9popywmDCFdKfgpi4b/HoMH1lluy6P+30CG9yzzpSpwTCIPNB9T1JA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lukeed/ms": "^2.0.1",
+ "fastify-plugin": "^4.0.0",
+ "toad-cache": "^3.3.1"
+ }
+ },
+ "node_modules/@leichtgewicht/ip-codec": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
+ "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
+ "license": "MIT"
+ },
+ "node_modules/@lukeed/ms": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
+ "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.9",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.9.tgz",
+ "integrity": "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/nodemailer": {
+ "version": "6.4.17",
+ "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.17.tgz",
+ "integrity": "sha512-I9CCaIp6DTldEg7vyUTZi8+9Vo0hi1/T8gv3C89yk1rSAAzoKQ8H8ki/jBYJSFoH/BisgLP8tkZMlQ91CIquww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/ping": {
+ "version": "0.4.4",
+ "resolved": "https://registry.npmjs.org/@types/ping/-/ping-0.4.4.tgz",
+ "integrity": "sha512-ifvo6w2f5eJYlXm+HiVx67iJe8WZp87sfa683nlqED5Vnt9Z93onkokNoWqOG21EaE8fMxyKPobE+mkPEyxsdw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/abort-controller": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
+ "license": "MIT",
+ "dependencies": {
+ "event-target-shim": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=6.5"
+ }
+ },
+ "node_modules/abstract-logging": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
+ "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
+ "license": "MIT"
+ },
+ "node_modules/ajv": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ajv-formats": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
+ "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ajv/node_modules/fast-uri": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz",
+ "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/atomic-sleep": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/avvio": {
+ "version": "8.4.0",
+ "resolved": "https://registry.npmjs.org/avvio/-/avvio-8.4.0.tgz",
+ "integrity": "sha512-CDSwaxINFy59iNwhYnkvALBwZiTydGkOecZyPkqBpABYR1KqGEsET0VOOYDwtleZSUIdeY36DC2bSZ24CO1igA==",
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/error": "^3.3.0",
+ "fastq": "^1.17.1"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/colorette": {
+ "version": "2.0.20",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
+ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "license": "MIT"
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/dateformat": {
+ "version": "4.6.3",
+ "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
+ "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/dns-packet": {
+ "version": "5.6.1",
+ "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
+ "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@leichtgewicht/ip-codec": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/dotenv": {
+ "version": "16.6.1",
+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
+ }
+ },
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.8",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.8.tgz",
+ "integrity": "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.8",
+ "@esbuild/android-arm": "0.25.8",
+ "@esbuild/android-arm64": "0.25.8",
+ "@esbuild/android-x64": "0.25.8",
+ "@esbuild/darwin-arm64": "0.25.8",
+ "@esbuild/darwin-x64": "0.25.8",
+ "@esbuild/freebsd-arm64": "0.25.8",
+ "@esbuild/freebsd-x64": "0.25.8",
+ "@esbuild/linux-arm": "0.25.8",
+ "@esbuild/linux-arm64": "0.25.8",
+ "@esbuild/linux-ia32": "0.25.8",
+ "@esbuild/linux-loong64": "0.25.8",
+ "@esbuild/linux-mips64el": "0.25.8",
+ "@esbuild/linux-ppc64": "0.25.8",
+ "@esbuild/linux-riscv64": "0.25.8",
+ "@esbuild/linux-s390x": "0.25.8",
+ "@esbuild/linux-x64": "0.25.8",
+ "@esbuild/netbsd-arm64": "0.25.8",
+ "@esbuild/netbsd-x64": "0.25.8",
+ "@esbuild/openbsd-arm64": "0.25.8",
+ "@esbuild/openbsd-x64": "0.25.8",
+ "@esbuild/openharmony-arm64": "0.25.8",
+ "@esbuild/sunos-x64": "0.25.8",
+ "@esbuild/win32-arm64": "0.25.8",
+ "@esbuild/win32-ia32": "0.25.8",
+ "@esbuild/win32-x64": "0.25.8"
+ }
+ },
+ "node_modules/event-target-shim": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
+ "node_modules/fast-content-type-parse": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-1.1.0.tgz",
+ "integrity": "sha512-fBHHqSTFLVnR61C+gltJuE5GkVQMV0S2nqUO8TJ+5Z3qAKG8vAx4FKai1s5jq/inV1+sREynIWSuQ6HgoSXpDQ==",
+ "license": "MIT"
+ },
+ "node_modules/fast-copy": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz",
+ "integrity": "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==",
+ "license": "MIT"
+ },
+ "node_modules/fast-decode-uri-component": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
+ "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",
+ "license": "MIT"
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-json-stringify": {
+ "version": "5.16.1",
+ "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-5.16.1.tgz",
+ "integrity": "sha512-KAdnLvy1yu/XrRtP+LJnxbBGrhN+xXu+gt3EUvZhYGKCr3lFHq/7UFJHHFgmJKoqlh6B40bZLEv7w46B0mqn1g==",
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/merge-json-schemas": "^0.1.0",
+ "ajv": "^8.10.0",
+ "ajv-formats": "^3.0.1",
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^2.1.0",
+ "json-schema-ref-resolver": "^1.0.1",
+ "rfdc": "^1.2.0"
+ }
+ },
+ "node_modules/fast-json-stringify/node_modules/ajv-formats": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fast-querystring": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",
+ "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-decode-uri-component": "^1.0.1"
+ }
+ },
+ "node_modules/fast-redact": {
+ "version": "3.5.0",
+ "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz",
+ "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/fast-safe-stringify": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
+ "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
+ "license": "MIT"
+ },
+ "node_modules/fast-uri": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.0.tgz",
+ "integrity": "sha512-ypuAmmMKInk5q7XcepxlnUWDLWv4GFtaJqAzWKqn62IpQ3pejtr5dTVbt3vwqVaMKmkNR55sTT+CqUKIaT21BA==",
+ "license": "MIT"
+ },
+ "node_modules/fastify": {
+ "version": "4.29.1",
+ "resolved": "https://registry.npmjs.org/fastify/-/fastify-4.29.1.tgz",
+ "integrity": "sha512-m2kMNHIG92tSNWv+Z3UeTR9AWLLuo7KctC7mlFPtMEVrfjIhmQhkQnT9v15qA/BfVq3vvj134Y0jl9SBje3jXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/ajv-compiler": "^3.5.0",
+ "@fastify/error": "^3.4.0",
+ "@fastify/fast-json-stringify-compiler": "^4.3.0",
+ "abstract-logging": "^2.0.1",
+ "avvio": "^8.3.0",
+ "fast-content-type-parse": "^1.1.0",
+ "fast-json-stringify": "^5.8.0",
+ "find-my-way": "^8.0.0",
+ "light-my-request": "^5.11.0",
+ "pino": "^9.0.0",
+ "process-warning": "^3.0.0",
+ "proxy-addr": "^2.0.7",
+ "rfdc": "^1.3.0",
+ "secure-json-parse": "^2.7.0",
+ "semver": "^7.5.4",
+ "toad-cache": "^3.3.0"
+ }
+ },
+ "node_modules/fastify-plugin": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz",
+ "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==",
+ "license": "MIT"
+ },
+ "node_modules/fastify/node_modules/pino": {
+ "version": "9.7.0",
+ "resolved": "https://registry.npmjs.org/pino/-/pino-9.7.0.tgz",
+ "integrity": "sha512-vnMCM6xZTb1WDmLvtG2lE/2p+t9hDEIvTWJsu6FejkE62vB7gDhvzrpFR4Cw2to+9JNQxVnkAKVPA1KPB98vWg==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0",
+ "fast-redact": "^3.1.1",
+ "on-exit-leak-free": "^2.1.0",
+ "pino-abstract-transport": "^2.0.0",
+ "pino-std-serializers": "^7.0.0",
+ "process-warning": "^5.0.0",
+ "quick-format-unescaped": "^4.0.3",
+ "real-require": "^0.2.0",
+ "safe-stable-stringify": "^2.3.1",
+ "sonic-boom": "^4.0.1",
+ "thread-stream": "^3.0.0"
+ },
+ "bin": {
+ "pino": "bin.js"
+ }
+ },
+ "node_modules/fastify/node_modules/pino-abstract-transport": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz",
+ "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==",
+ "license": "MIT",
+ "dependencies": {
+ "split2": "^4.0.0"
+ }
+ },
+ "node_modules/fastify/node_modules/pino-std-serializers": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz",
+ "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==",
+ "license": "MIT"
+ },
+ "node_modules/fastify/node_modules/pino/node_modules/process-warning": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
+ "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/fastify/node_modules/sonic-boom": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz",
+ "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0"
+ }
+ },
+ "node_modules/fastify/node_modules/thread-stream": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+ "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==",
+ "license": "MIT",
+ "dependencies": {
+ "real-require": "^0.2.0"
+ }
+ },
+ "node_modules/fastq": {
+ "version": "1.19.1",
+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
+ "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
+ "license": "ISC",
+ "dependencies": {
+ "reusify": "^1.0.4"
+ }
+ },
+ "node_modules/find-my-way": {
+ "version": "8.2.2",
+ "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-8.2.2.tgz",
+ "integrity": "sha512-Dobi7gcTEq8yszimcfp/R7+owiT4WncAJ7VTTgFH1jYJ5GaG1FbhjwDG820hptN0QDFvzVY3RfCzdInvGPGzjA==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-querystring": "^1.0.0",
+ "safe-regex2": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/get-tsconfig": {
+ "version": "4.10.1",
+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.10.1.tgz",
+ "integrity": "sha512-auHyJ4AgMz7vgS8Hp3N6HXSmlMdUyhSUrfBF16w153rxtLIEOE+HGqaBppczZvnHLqQJfiHotCYpNhl0lUROFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "resolve-pkg-maps": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
+ }
+ },
+ "node_modules/help-me": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
+ "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
+ "license": "MIT"
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/joycon": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
+ "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/json-schema-ref-resolver": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz",
+ "integrity": "sha512-EJAj1pgHc1hxF6vo2Z3s69fMjO1INq6eGHXZ8Z6wCQeldCuwxGK9Sxf4/cScGn3FZubCVUehfWtcDM/PLteCQw==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/light-my-request": {
+ "version": "5.14.0",
+ "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-5.14.0.tgz",
+ "integrity": "sha512-aORPWntbpH5esaYpGOOmri0OHDOe3wC5M2MQxZ9dvMLZm6DnaAn0kJlcbU9hwsQgLzmZyReKwFwwPkR+nHu5kA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "cookie": "^0.7.0",
+ "process-warning": "^3.0.0",
+ "set-cookie-parser": "^2.4.1"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mnemonist": {
+ "version": "0.39.6",
+ "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.6.tgz",
+ "integrity": "sha512-A/0v5Z59y63US00cRSLiloEIw3t5G+MiKz4BhX21FI+YBJXBOGW0ohFxTxO08dsOYlzxo87T7vGfZKYp2bcAWA==",
+ "license": "MIT",
+ "dependencies": {
+ "obliterator": "^2.0.1"
+ }
+ },
+ "node_modules/nodemailer": {
+ "version": "6.10.1",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.10.1.tgz",
+ "integrity": "sha512-Z+iLaBGVaSjbIzQ4pX6XV41HrooLsQ10ZWPUehGmuantvzWoDVBnmsdUcOIDM1t+yPor5pDhVlDESgOMEGxhHA==",
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/obliterator": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
+ "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==",
+ "license": "MIT"
+ },
+ "node_modules/on-exit-leak-free": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/ping": {
+ "version": "0.4.4",
+ "resolved": "https://registry.npmjs.org/ping/-/ping-0.4.4.tgz",
+ "integrity": "sha512-56ZMC0j7SCsMMLdOoUg12VZCfj/+ZO+yfOSjaNCRrmZZr6GLbN2X/Ui56T15dI8NhiHckaw5X2pvyfAomanwqQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/pino": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/pino/-/pino-8.21.0.tgz",
+ "integrity": "sha512-ip4qdzjkAyDDZklUaZkcRFb2iA118H9SgRh8yzTkSQK8HilsOJF7rSY8HoW5+I0M46AZgX/pxbprf2vvzQCE0Q==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0",
+ "fast-redact": "^3.1.1",
+ "on-exit-leak-free": "^2.1.0",
+ "pino-abstract-transport": "^1.2.0",
+ "pino-std-serializers": "^6.0.0",
+ "process-warning": "^3.0.0",
+ "quick-format-unescaped": "^4.0.3",
+ "real-require": "^0.2.0",
+ "safe-stable-stringify": "^2.3.1",
+ "sonic-boom": "^3.7.0",
+ "thread-stream": "^2.6.0"
+ },
+ "bin": {
+ "pino": "bin.js"
+ }
+ },
+ "node_modules/pino-abstract-transport": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.2.0.tgz",
+ "integrity": "sha512-Guhh8EZfPCfH+PMXAb6rKOjGQEoy0xlAIn+irODG5kgfYV+BQ0rGYYWTIel3P5mmyXqkYkPmdIkywsn6QKUR1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "readable-stream": "^4.0.0",
+ "split2": "^4.0.0"
+ }
+ },
+ "node_modules/pino-pretty": {
+ "version": "10.3.1",
+ "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.3.1.tgz",
+ "integrity": "sha512-az8JbIYeN/1iLj2t0jR9DV48/LQ3RC6hZPpapKPkb84Q+yTidMCpgWxIT3N0flnBDilyBQ1luWNpOeJptjdp/g==",
+ "license": "MIT",
+ "dependencies": {
+ "colorette": "^2.0.7",
+ "dateformat": "^4.6.3",
+ "fast-copy": "^3.0.0",
+ "fast-safe-stringify": "^2.1.1",
+ "help-me": "^5.0.0",
+ "joycon": "^3.1.1",
+ "minimist": "^1.2.6",
+ "on-exit-leak-free": "^2.1.0",
+ "pino-abstract-transport": "^1.0.0",
+ "pump": "^3.0.0",
+ "readable-stream": "^4.0.0",
+ "secure-json-parse": "^2.4.0",
+ "sonic-boom": "^3.0.0",
+ "strip-json-comments": "^3.1.1"
+ },
+ "bin": {
+ "pino-pretty": "bin.js"
+ }
+ },
+ "node_modules/pino-std-serializers": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-6.2.2.tgz",
+ "integrity": "sha512-cHjPPsE+vhj/tnhCy/wiMh3M3z3h/j15zHQX+S9GkTBgqJuTuJzYJ4gUyACLhDaJ7kk9ba9iRDmbH2tJU03OiA==",
+ "license": "MIT"
+ },
+ "node_modules/process": {
+ "version": "0.11.10",
+ "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
+ "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
+ "node_modules/process-warning": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
+ "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",
+ "license": "MIT"
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/pump": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",
+ "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "node_modules/quick-format-unescaped": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
+ "license": "MIT"
+ },
+ "node_modules/readable-stream": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
+ "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
+ "license": "MIT",
+ "dependencies": {
+ "abort-controller": "^3.0.0",
+ "buffer": "^6.0.3",
+ "events": "^3.3.0",
+ "process": "^0.11.10",
+ "string_decoder": "^1.3.0"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ }
+ },
+ "node_modules/real-require": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/resolve-pkg-maps": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
+ }
+ },
+ "node_modules/ret": {
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.4.3.tgz",
+ "integrity": "sha512-0f4Memo5QP7WQyUEAYUO3esD/XjOc3Zjjg5CPsAq1p8sIu0XPeMbHJemKA0BO7tV0X7+A0FoEpbmHXWxPyD3wQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/reusify": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
+ "license": "MIT",
+ "engines": {
+ "iojs": ">=1.0.0",
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rfdc": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+ "license": "MIT"
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/safe-regex2": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-3.1.0.tgz",
+ "integrity": "sha512-RAAZAGbap2kBfbVhvmnTFv73NWLMvDGOITFYTZBAaY8eR+Ir4ef7Up/e7amo+y1+AH+3PtLkrt9mvcTsG9LXug==",
+ "license": "MIT",
+ "dependencies": {
+ "ret": "~0.4.0"
+ }
+ },
+ "node_modules/safe-stable-stringify": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/secure-json-parse": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",
+ "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/semver": {
+ "version": "7.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
+ "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/set-cookie-parser": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
+ "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
+ "license": "MIT"
+ },
+ "node_modules/sonic-boom": {
+ "version": "3.8.1",
+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.8.1.tgz",
+ "integrity": "sha512-y4Z8LCDBuum+PBP3lSV7RHrXscqksve/bi0as7mhwVnBW+/wUqKT/2Kb7um8yqcFy0duYbbPxzt89Zy2nOCaxg==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0"
+ }
+ },
+ "node_modules/split2": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">= 10.x"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/strip-json-comments": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/thread-stream": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-2.7.0.tgz",
+ "integrity": "sha512-qQiRWsU/wvNolI6tbbCKd9iKaTnCXsTwVxhhKM6nctPdujTyztjlbUkUTUymidWcMnZ5pWR0ej4a0tjsW021vw==",
+ "license": "MIT",
+ "dependencies": {
+ "real-require": "^0.2.0"
+ }
+ },
+ "node_modules/toad-cache": {
+ "version": "3.7.0",
+ "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz",
+ "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/tsx": {
+ "version": "4.20.3",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.3.tgz",
+ "integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.25.0",
+ "get-tsconfig": "^4.7.5"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.8.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
+ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici": {
+ "version": "6.21.3",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
+ "integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/zod": {
+ "version": "3.25.76",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/monitor-agent/package.json b/monitor-agent/package.json
new file mode 100644
index 000000000..5aaceb106
--- /dev/null
+++ b/monitor-agent/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "rybbit-monitor-agent",
+ "version": "1.0.0",
+ "description": "Regional monitoring agent for Rybbit uptime monitoring",
+ "main": "dist/index.js",
+ "type": "module",
+ "scripts": {
+ "dev": "tsx watch src/index.ts",
+ "build": "tsc",
+ "start": "node dist/index.js",
+ "docker:build": "docker build -t monitor-agent .",
+ "docker:run": "docker run -p 3000:3000 --env-file .env monitor-agent"
+ },
+ "dependencies": {
+ "fastify": "^4.25.0",
+ "@fastify/cors": "^8.5.0",
+ "undici": "^6.2.0",
+ "dns-packet": "^5.6.1",
+ "ping": "^0.4.4",
+ "nodemailer": "^6.9.8",
+ "pino": "^8.17.0",
+ "pino-pretty": "^10.3.0",
+ "dotenv": "^16.3.1",
+ "zod": "^3.22.4"
+ },
+ "devDependencies": {
+ "@types/node": "^20.10.0",
+ "@types/nodemailer": "^6.4.14",
+ "@types/ping": "^0.4.4",
+ "tsx": "^4.6.0",
+ "typescript": "^5.3.0"
+ }
+}
\ No newline at end of file
diff --git a/monitor-agent/src/api/auth.ts b/monitor-agent/src/api/auth.ts
new file mode 100644
index 000000000..8f94ee75e
--- /dev/null
+++ b/monitor-agent/src/api/auth.ts
@@ -0,0 +1,38 @@
+import { FastifyRequest, FastifyReply } from 'fastify';
+import { CONFIG } from '../config.js';
+import { logger } from '../utils/logger.js';
+
+export async function authenticateRequest(
+ request: FastifyRequest,
+ reply: FastifyReply
+): Promise<void> {
+ const clientIp = request.ip;
+
+ logger.debug({
+ clientIp,
+ allowedIPs: CONFIG.ALLOWED_IPS,
+ allowedIPsLength: CONFIG.ALLOWED_IPS.length,
+ rawEnv: process.env.ALLOWED_IPS
+ }, 'Checking IP whitelist');
+
+ // If no IPs are whitelisted, allow all (with warning)
+ if (CONFIG.ALLOWED_IPS.length === 0) {
+ logger.debug({ ip: clientIp }, 'No IP whitelist configured, allowing request');
+ return;
+ }
+
+ // Check IP whitelist
+ if (!CONFIG.ALLOWED_IPS.includes(clientIp)) {
+ logger.warn({
+ ip: clientIp,
+ allowedIps: CONFIG.ALLOWED_IPS
+ }, 'Request from non-whitelisted IP');
+
+ return reply.code(403).send({
+ error: 'Forbidden',
+ message: 'Your IP address is not authorized to access this service'
+ });
+ }
+
+ logger.debug({ ip: clientIp }, 'Request from whitelisted IP');
+}
\ No newline at end of file
diff --git a/monitor-agent/src/api/server.ts b/monitor-agent/src/api/server.ts
new file mode 100644
index 000000000..07f4fa224
--- /dev/null
+++ b/monitor-agent/src/api/server.ts
@@ -0,0 +1,149 @@
+import Fastify from 'fastify';
+import cors from '@fastify/cors';
+import { CONFIG } from '../config.js';
+import { logger } from '../utils/logger.js';
+import { authenticateRequest } from './auth.js';
+import { ExecuteRequest, ExecuteResponse, HttpCheckResult, TcpCheckResult } from '../types.js';
+import { performHttpCheck } from '../monitors/http.js';
+import { performTcpCheck } from '../monitors/tcp.js';
+import { applyValidationRules } from '../utils/validation.js';
+
+export async function createServer() {
+ const fastify = Fastify({
+ logger: false, // We use our own logger
+ trustProxy: true,
+ });
+
+ // Register plugins
+ await fastify.register(cors, {
+ origin: false, // Accept requests from any origin
+ });
+
+ // Health check endpoint (no auth required)
+ fastify.get('/health', async () => {
+ return {
+ status: 'ok',
+ region: CONFIG.REGION,
+ timestamp: new Date().toISOString(),
+ };
+ });
+
+ // Metrics endpoint (no auth required)
+ fastify.get('/metrics', async (_request, reply) => {
+ // TODO: Implement Prometheus metrics
+ reply.type('text/plain');
+ return '# Metrics endpoint not yet implemented';
+ });
+
+ // Execute monitoring check
+ fastify.post<{ Body: ExecuteRequest }>(
+ '/execute',
+ {
+ preHandler: authenticateRequest,
+ schema: {
+ body: {
+ type: 'object',
+ required: ['jobId', 'monitorId', 'monitorType', 'config'],
+ properties: {
+ jobId: { type: 'string' },
+ monitorId: { type: 'number' },
+ monitorType: { type: 'string', enum: ['http', 'tcp', 'dns', 'smtp', 'ping'] },
+ config: { type: 'object' },
+ validationRules: { type: 'array', default: [] },
+ },
+ },
+ },
+ },
+ async (request, reply) => {
+ const { jobId, monitorId, monitorType, config, validationRules } = request.body;
+
+ logger.info({ jobId, monitorId, monitorType }, 'Executing monitor check');
+
+ try {
+ let result;
+
+ switch (monitorType) {
+ case 'http':
+ result = await performHttpCheck(config);
+ break;
+ case 'tcp':
+ result = await performTcpCheck(config);
+ break;
+ case 'dns':
+ // TODO: Implement DNS check
+ return reply.code(501).send({ error: 'DNS monitoring not yet implemented' });
+ case 'smtp':
+ // TODO: Implement SMTP check
+ return reply.code(501).send({ error: 'SMTP monitoring not yet implemented' });
+ case 'ping':
+ // TODO: Implement PING check
+ return reply.code(501).send({ error: 'PING monitoring not yet implemented' });
+ default:
+ return reply.code(400).send({ error: `Unknown monitor type: ${monitorType}` });
+ }
+
+ // Apply validation rules (only for HTTP checks)
+ if (result.status === 'success' && validationRules.length > 0 && monitorType === 'http') {
+ const httpResult = result as HttpCheckResult;
+ const validationErrors = applyValidationRules(httpResult, validationRules);
+ if (validationErrors.length > 0) {
+ httpResult.validationErrors = validationErrors;
+ httpResult.status = 'failure';
+ }
+ }
+
+ const response: ExecuteResponse = {
+ jobId,
+ region: CONFIG.REGION,
+ status: result.status,
+ responseTimeMs: result.responseTimeMs,
+ error: result.error,
+ };
+
+ // Add HTTP-specific fields
+ if (monitorType === 'http' && result && 'statusCode' in result) {
+ const httpResult = result as HttpCheckResult;
+ response.statusCode = httpResult.statusCode;
+ response.headers = httpResult.headers;
+ response.timing = httpResult.timing;
+ response.bodySizeBytes = httpResult.bodySizeBytes;
+ response.validationErrors = httpResult.validationErrors;
+ }
+
+ // Add validation errors for TCP if any
+ if (monitorType === 'tcp' && result && 'validationErrors' in result) {
+ const tcpResult = result as TcpCheckResult;
+ response.validationErrors = tcpResult.validationErrors;
+ }
+
+ logger.info(
+ {
+ jobId,
+ monitorId,
+ status: result.status,
+ responseTimeMs: result.responseTimeMs
+ },
+ 'Monitor check completed'
+ );
+
+ return response;
+
+ } catch (error) {
+ logger.error({ error, jobId, monitorId }, 'Monitor check failed with unexpected error');
+
+ return {
+ jobId,
+ region: CONFIG.REGION,
+ status: 'failure',
+ responseTimeMs: 0,
+ error: {
+ message: error instanceof Error ? error.message : 'Unknown error',
+ type: 'internal_error',
+ },
+ } as ExecuteResponse;
+ }
+ }
+ );
+
+ return fastify;
+}
\ No newline at end of file
diff --git a/monitor-agent/src/config.ts b/monitor-agent/src/config.ts
new file mode 100644
index 000000000..1cab647c3
--- /dev/null
+++ b/monitor-agent/src/config.ts
@@ -0,0 +1,40 @@
+import { config } from "dotenv";
+
+// Load environment variables
+config();
+
+export const CONFIG = {
+ // Server configuration
+ PORT: parseInt(process.env.PORT || "3003", 10),
+ HOST: process.env.HOST || "0.0.0.0",
+
+ // Region identifier (e.g., "us-east", "europe", "asia")
+ REGION: process.env.REGION || "unknown",
+
+ // Security - IP whitelist for main server
+ ALLOWED_IPS: process.env.ALLOWED_IPS && process.env.ALLOWED_IPS.trim()
+ ? process.env.ALLOWED_IPS.split(",").map((ip) => ip.trim()).filter((ip) => ip.length > 0)
+ : [],
+
+ // Monitoring defaults
+ DEFAULT_TIMEOUT_MS: parseInt(process.env.DEFAULT_TIMEOUT_MS || "30000", 10),
+ MAX_TIMEOUT_MS: parseInt(process.env.MAX_TIMEOUT_MS || "60000", 10),
+
+ // Logging
+ LOG_LEVEL: process.env.LOG_LEVEL || "info",
+};
+
+// Validate required configuration
+export function validateConfig(): void {
+ const required = ["REGION"];
+ const missing = required.filter((key) => !CONFIG[key as keyof typeof CONFIG]);
+
+ if (missing.length > 0) {
+ throw new Error(`Missing required environment variables: ${missing.join(", ")}`);
+ }
+
+ // Warn if no IP whitelist is configured
+ if (CONFIG.ALLOWED_IPS.length === 0) {
+ console.warn("WARNING: No IP whitelist configured. Agent will accept requests from any IP address.");
+ }
+}
diff --git a/monitor-agent/src/index.ts b/monitor-agent/src/index.ts
new file mode 100644
index 000000000..86e782952
--- /dev/null
+++ b/monitor-agent/src/index.ts
@@ -0,0 +1,58 @@
+import { CONFIG, validateConfig } from './config.js';
+import { logger } from './utils/logger.js';
+import { createServer } from './api/server.js';
+
+async function start() {
+ try {
+ // Validate configuration
+ validateConfig();
+
+ logger.info(
+ {
+ region: CONFIG.REGION,
+ port: CONFIG.PORT,
+ },
+ 'Starting monitor agent'
+ );
+
+ // Create and start server
+ const server = await createServer();
+
+ await server.listen({
+ port: CONFIG.PORT,
+ host: CONFIG.HOST,
+ });
+
+ logger.info(
+ {
+ region: CONFIG.REGION,
+ url: `http://${CONFIG.HOST}:${CONFIG.PORT}`,
+ },
+ 'Monitor agent started successfully'
+ );
+
+ // Graceful shutdown
+ const shutdown = async (signal: string) => {
+ logger.info({ signal }, 'Shutting down monitor agent');
+
+ try {
+ await server.close();
+ logger.info('Monitor agent stopped');
+ process.exit(0);
+ } catch (error) {
+ logger.error({ error }, 'Error during shutdown');
+ process.exit(1);
+ }
+ };
+
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('SIGINT', () => shutdown('SIGINT'));
+
+ } catch (error) {
+ logger.fatal({ error }, 'Failed to start monitor agent');
+ process.exit(1);
+ }
+}
+
+// Start the application
+start();
\ No newline at end of file
diff --git a/monitor-agent/src/monitors/http.ts b/monitor-agent/src/monitors/http.ts
new file mode 100644
index 000000000..f90eaa945
--- /dev/null
+++ b/monitor-agent/src/monitors/http.ts
@@ -0,0 +1,150 @@
+import { request } from 'undici';
+import { performance } from 'perf_hooks';
+import dns from 'dns/promises';
+import { MonitorConfig, HttpCheckResult, TimingInfo } from '../types.js';
+import { CONFIG } from '../config.js';
+import { logger } from '../utils/logger.js';
+
+export async function performHttpCheck(config: MonitorConfig): Promise<HttpCheckResult> {
+ const startTime = performance.now();
+ const timing: TimingInfo = {};
+
+ try {
+ if (!config.url) {
+ throw new Error('URL is required for HTTP monitoring');
+ }
+
+ const url = new URL(config.url);
+
+ // DNS lookup timing
+ const dnsStart = performance.now();
+ try {
+ const dnsOptions: any = {};
+ if (config.ipVersion === 'ipv4') dnsOptions.family = 4;
+ if (config.ipVersion === 'ipv6') dnsOptions.family = 6;
+
+ await dns.lookup(url.hostname, dnsOptions);
+ timing.dnsMs = Math.round(performance.now() - dnsStart);
+ } catch (dnsError) {
+ logger.error({ error: dnsError, hostname: url.hostname }, 'DNS lookup failed');
+ throw new Error(`DNS lookup failed: ${dnsError}`);
+ }
+
+ // Build headers
+ const headers: Record<string, string> = {
+ 'User-Agent': config.userAgent || 'Rybbit-Monitor/1.0',
+ ...config.headers,
+ };
+
+ // Add authentication
+ if (config.auth) {
+ switch (config.auth.type) {
+ case 'basic':
+ if (config.auth.credentials?.username && config.auth.credentials?.password) {
+ const basicAuth = Buffer.from(
+ `${config.auth.credentials.username}:${config.auth.credentials.password}`
+ ).toString('base64');
+ headers['Authorization'] = `Basic ${basicAuth}`;
+ }
+ break;
+ case 'bearer':
+ if (config.auth.credentials?.token) {
+ headers['Authorization'] = `Bearer ${config.auth.credentials.token}`;
+ }
+ break;
+ case 'api_key':
+ case 'custom_header':
+ if (config.auth.credentials?.headerName && config.auth.credentials?.headerValue) {
+ headers[config.auth.credentials.headerName] = config.auth.credentials.headerValue;
+ }
+ break;
+ }
+ }
+
+ // Perform request
+ const requestStart = performance.now();
+ const response = await request(config.url, {
+ method: (config.method || 'GET') as any,
+ headers,
+ body: config.body,
+ bodyTimeout: Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS),
+ headersTimeout: Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS),
+ maxRedirections: config.followRedirects !== false ? 5 : 0,
+ });
+
+ // Calculate timings
+ timing.ttfbMs = Math.round(performance.now() - requestStart);
+
+ // Get response body and size
+ const transferStart = performance.now();
+ const bodyBuffer = await response.body.arrayBuffer();
+ const bodySizeBytes = bodyBuffer.byteLength;
+
+ timing.transferMs = Math.round(performance.now() - transferStart);
+
+ // Estimate TCP and TLS times (approximations)
+ timing.tcpMs = Math.round((timing.ttfbMs - timing.dnsMs) * 0.3);
+ if (url.protocol === 'https:') {
+ timing.tlsMs = Math.round((timing.ttfbMs - timing.dnsMs - timing.tcpMs) * 0.5);
+ }
+
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ // Convert headers to simple object
+ const responseHeaders: Record<string, string> = {};
+ for (const [key, value] of Object.entries(response.headers)) {
+ responseHeaders[key] = Array.isArray(value) ? value.join(', ') : String(value);
+ }
+
+ return {
+ status: 'success',
+ statusCode: response.statusCode,
+ responseTimeMs,
+ timing,
+ headers: responseHeaders,
+ bodySizeBytes,
+ validationErrors: [],
+ };
+
+ } catch (error: any) {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ // Handle different error types
+ let errorType = 'unknown_error';
+ let errorMessage = error.message || 'Unknown error occurred';
+
+ if (error.code === 'UND_ERR_CONNECT_TIMEOUT') {
+ errorType = 'connection_timeout';
+ errorMessage = 'Connection timed out';
+ } else if (error.code === 'UND_ERR_HEADERS_TIMEOUT') {
+ errorType = 'headers_timeout';
+ errorMessage = 'Headers timeout';
+ } else if (error.code === 'UND_ERR_BODY_TIMEOUT') {
+ errorType = 'body_timeout';
+ errorMessage = 'Body timeout';
+ } else if (error.code === 'ENOTFOUND') {
+ errorType = 'dns_failure';
+ errorMessage = 'DNS lookup failed';
+ } else if (error.code === 'ECONNREFUSED') {
+ errorType = 'connection_refused';
+ errorMessage = 'Connection refused';
+ } else if (error.message?.includes('SSL') || error.message?.includes('TLS')) {
+ errorType = 'ssl_error';
+ }
+
+ logger.error({ error, url: config.url }, 'HTTP check failed');
+
+ return {
+ status: errorType.includes('timeout') ? 'timeout' : 'failure',
+ responseTimeMs,
+ timing,
+ headers: {},
+ bodySizeBytes: 0,
+ validationErrors: [],
+ error: {
+ message: errorMessage,
+ type: errorType,
+ },
+ };
+ }
+}
\ No newline at end of file
diff --git a/monitor-agent/src/monitors/tcp.ts b/monitor-agent/src/monitors/tcp.ts
new file mode 100644
index 000000000..09de5caf0
--- /dev/null
+++ b/monitor-agent/src/monitors/tcp.ts
@@ -0,0 +1,91 @@
+import net from 'net';
+import { performance } from 'perf_hooks';
+import { MonitorConfig, TcpCheckResult } from '../types.js';
+import { CONFIG } from '../config.js';
+import { logger } from '../utils/logger.js';
+
+export async function performTcpCheck(config: MonitorConfig): Promise<TcpCheckResult> {
+ const startTime = performance.now();
+
+ return new Promise((resolve) => {
+ if (!config.host || !config.port) {
+ resolve({
+ status: 'failure',
+ responseTimeMs: 0,
+ error: {
+ message: 'Host and port are required for TCP monitoring',
+ type: 'configuration_error',
+ },
+ });
+ return;
+ }
+
+ const timeout = Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS);
+ const socket = new net.Socket();
+
+ // Set timeout
+ const timeoutHandle = setTimeout(() => {
+ socket.destroy();
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ logger.warn({ host: config.host, port: config.port, responseTimeMs }, 'TCP connection timeout');
+
+ resolve({
+ status: 'timeout',
+ responseTimeMs,
+ error: {
+ message: 'Connection timeout',
+ type: 'timeout',
+ },
+ });
+ }, timeout);
+
+ // Handle connection success
+ socket.on('connect', () => {
+ clearTimeout(timeoutHandle);
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ logger.info({ host: config.host, port: config.port, responseTimeMs }, 'TCP connection successful');
+
+ socket.destroy();
+ resolve({
+ status: 'success',
+ responseTimeMs,
+ });
+ });
+
+ // Handle errors
+ socket.on('error', (error: any) => {
+ clearTimeout(timeoutHandle);
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ let errorType = 'connection_error';
+ let errorMessage = error.message;
+
+ if (error.code === 'ECONNREFUSED') {
+ errorType = 'connection_refused';
+ errorMessage = 'Connection refused';
+ } else if (error.code === 'EHOSTUNREACH') {
+ errorType = 'host_unreachable';
+ errorMessage = 'Host unreachable';
+ } else if (error.code === 'ENOTFOUND') {
+ errorType = 'dns_failure';
+ errorMessage = 'Host not found';
+ }
+
+ logger.error({ error, host: config.host, port: config.port }, 'TCP check failed');
+
+ resolve({
+ status: 'failure',
+ responseTimeMs,
+ error: {
+ message: errorMessage,
+ type: errorType,
+ },
+ });
+ });
+
+ // Initiate connection
+ socket.connect(config.port, config.host);
+ });
+}
\ No newline at end of file
diff --git a/monitor-agent/src/types.ts b/monitor-agent/src/types.ts
new file mode 100644
index 000000000..3006764cb
--- /dev/null
+++ b/monitor-agent/src/types.ts
@@ -0,0 +1,112 @@
+export interface MonitorConfig {
+ // HTTP config
+ url?: string;
+ method?: string;
+ 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 config
+ host?: string;
+ port?: number;
+
+ // DNS config
+ hostname?: string;
+ recordType?: "A" | "AAAA" | "CNAME" | "MX" | "TXT" | "NS" | "SOA";
+ expectedValue?: string;
+
+ // SMTP config
+ smtpHost?: string;
+ smtpPort?: number;
+ smtpSecure?: boolean;
+ smtpAuth?: {
+ user?: string;
+ pass?: string;
+ };
+}
+
+export interface ValidationRule {
+ type: string;
+ operator?: string;
+ value?: any;
+ header?: string;
+ caseSensitive?: boolean;
+}
+
+export interface ExecuteRequest {
+ jobId: string;
+ monitorId: number;
+ monitorType: "http" | "tcp" | "dns" | "smtp" | "ping";
+ config: MonitorConfig;
+ validationRules: ValidationRule[];
+}
+
+export interface TimingInfo {
+ dnsMs?: number;
+ tcpMs?: number;
+ tlsMs?: number;
+ ttfbMs?: number;
+ transferMs?: number;
+}
+
+export interface ErrorInfo {
+ message: string;
+ type: string;
+}
+
+export interface ExecuteResponse {
+ jobId: string;
+ region: string;
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ statusCode?: number;
+ headers?: Record<string, string>;
+ timing?: TimingInfo;
+ error?: ErrorInfo;
+ validationErrors?: string[];
+ bodySizeBytes?: number;
+}
+
+export interface HttpCheckResult {
+ status: "success" | "failure" | "timeout";
+ statusCode?: number;
+ responseTimeMs: number;
+ timing: TimingInfo;
+ headers: Record<string, string>;
+ bodySizeBytes: number;
+ validationErrors: string[];
+ error?: ErrorInfo;
+}
+
+export interface TcpCheckResult {
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ validationErrors?: string[];
+ error?: ErrorInfo;
+}
+
+export interface DnsCheckResult {
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ answers?: any[];
+ error?: ErrorInfo;
+}
+
+export interface SmtpCheckResult {
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ error?: ErrorInfo;
+}
\ No newline at end of file
diff --git a/monitor-agent/src/utils/logger.ts b/monitor-agent/src/utils/logger.ts
new file mode 100644
index 000000000..c40acccc1
--- /dev/null
+++ b/monitor-agent/src/utils/logger.ts
@@ -0,0 +1,17 @@
+import pino from 'pino';
+import { CONFIG } from '../config.js';
+
+export const logger = pino({
+ level: CONFIG.LOG_LEVEL,
+ transport: {
+ target: 'pino-pretty',
+ options: {
+ colorize: true,
+ ignore: 'pid,hostname',
+ translateTime: 'HH:MM:ss Z',
+ },
+ },
+ base: {
+ region: CONFIG.REGION,
+ },
+});
\ No newline at end of file
diff --git a/monitor-agent/src/utils/validation.ts b/monitor-agent/src/utils/validation.ts
new file mode 100644
index 000000000..8c35627cb
--- /dev/null
+++ b/monitor-agent/src/utils/validation.ts
@@ -0,0 +1,108 @@
+import { HttpCheckResult, ValidationRule } from '../types.js';
+
+export function applyValidationRules(
+ result: HttpCheckResult,
+ rules: ValidationRule[]
+): string[] {
+ const errors: string[] = [];
+
+ for (const rule of rules) {
+ switch (rule.type) {
+ case 'status_code':
+ if (!validateStatusCode(result.statusCode, rule)) {
+ errors.push(
+ `Status code validation failed: expected ${rule.operator} ${rule.value}, got ${result.statusCode}`
+ );
+ }
+ break;
+
+ case 'response_time':
+ if (!validateResponseTime(result.responseTimeMs, rule)) {
+ errors.push(
+ `Response time validation failed: expected ${rule.operator} ${rule.value}ms, got ${result.responseTimeMs}ms`
+ );
+ }
+ break;
+
+ case 'header_exists':
+ if (!result.headers[rule.header!]) {
+ errors.push(`Required header missing: ${rule.header}`);
+ }
+ break;
+
+ case 'header_value':
+ const headerValue = result.headers[rule.header!];
+ if (!validateHeaderValue(headerValue, rule)) {
+ errors.push(
+ `Header ${rule.header} validation failed: expected ${rule.operator} "${rule.value}", got "${headerValue}"`
+ );
+ }
+ break;
+
+ case 'response_size':
+ if (!validateSize(result.bodySizeBytes, rule)) {
+ errors.push(
+ `Response size validation failed: expected ${rule.operator} ${rule.value} bytes, got ${result.bodySizeBytes} bytes`
+ );
+ }
+ break;
+
+ // Note: response_body_contains validation would require storing the body
+ // which we're avoiding for performance reasons
+ }
+ }
+
+ return errors;
+}
+
+function validateStatusCode(statusCode: number | undefined, rule: ValidationRule): boolean {
+ if (statusCode === undefined) return false;
+
+ switch (rule.operator) {
+ case 'equals':
+ return statusCode === rule.value;
+ case 'not_equals':
+ return statusCode !== rule.value;
+ case 'in':
+ return Array.isArray(rule.value) && rule.value.includes(statusCode);
+ case 'not_in':
+ return Array.isArray(rule.value) && !rule.value.includes(statusCode);
+ default:
+ return true;
+ }
+}
+
+function validateResponseTime(responseTime: number, rule: ValidationRule): boolean {
+ switch (rule.operator) {
+ case 'less_than':
+ return responseTime < rule.value;
+ case 'greater_than':
+ return responseTime > rule.value;
+ default:
+ return true;
+ }
+}
+
+function validateHeaderValue(headerValue: string | undefined, rule: ValidationRule): boolean {
+ if (!headerValue) return false;
+
+ switch (rule.operator) {
+ case 'equals':
+ return headerValue === rule.value;
+ case 'contains':
+ return headerValue.includes(rule.value);
+ default:
+ return true;
+ }
+}
+
+function validateSize(size: number, rule: ValidationRule): boolean {
+ switch (rule.operator) {
+ case 'less_than':
+ return size < rule.value;
+ case 'greater_than':
+ return size > rule.value;
+ default:
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/monitor-agent/systemd/rybbit-monitor-agent.service b/monitor-agent/systemd/rybbit-monitor-agent.service
new file mode 100644
index 000000000..85041134e
--- /dev/null
+++ b/monitor-agent/systemd/rybbit-monitor-agent.service
@@ -0,0 +1,37 @@
+[Unit]
+Description=Rybbit Monitor Agent
+Documentation=https://github.com/rybbit/monitor-agent
+After=network.target
+
+[Service]
+Type=simple
+User=rybbit
+Group=rybbit
+WorkingDirectory=/opt/rybbit-monitor-agent
+ExecStart=/usr/bin/node /opt/rybbit-monitor-agent/dist/index.js
+Restart=always
+RestartSec=10
+
+# Environment
+Environment="NODE_ENV=production"
+EnvironmentFile=/opt/rybbit-monitor-agent/.env
+
+# Security
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectSystem=strict
+ProtectHome=true
+ReadWritePaths=/opt/rybbit-monitor-agent/logs
+
+# Resource limits
+LimitNOFILE=65536
+MemoryLimit=1G
+CPUQuota=100%
+
+# Logging
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=rybbit-monitor-agent
+
+[Install]
+WantedBy=multi-user.target
\ No newline at end of file
diff --git a/monitor-agent/systemd/setup.sh b/monitor-agent/systemd/setup.sh
new file mode 100755
index 000000000..ebbf20948
--- /dev/null
+++ b/monitor-agent/systemd/setup.sh
@@ -0,0 +1,171 @@
+#!/bin/bash
+
+# Setup script for Rybbit Monitor Agent with systemd
+# Run with sudo: sudo ./setup.sh
+
+set -e
+
+# Colors
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m'
+
+# Configuration
+INSTALL_DIR="/opt/rybbit-monitor-agent"
+SERVICE_USER="rybbit"
+SERVICE_NAME="rybbit-monitor-agent"
+NODE_VERSION="20"
+
+# Functions
+log_info() {
+ echo -e "${GREEN}[INFO]${NC} $1"
+}
+
+log_warn() {
+ echo -e "${YELLOW}[WARN]${NC} $1"
+}
+
+log_error() {
+ echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Check if running as root
+if [[ $EUID -ne 0 ]]; then
+ log_error "This script must be run as root"
+ exit 1
+fi
+
+# Create service user
+if ! id "$SERVICE_USER" &>/dev/null; then
+ log_info "Creating service user: $SERVICE_USER"
+ useradd --system --shell /bin/false --home-dir "$INSTALL_DIR" "$SERVICE_USER"
+else
+ log_info "Service user already exists: $SERVICE_USER"
+fi
+
+# Create installation directory
+log_info "Creating installation directory: $INSTALL_DIR"
+mkdir -p "$INSTALL_DIR"/{logs,dist}
+
+# Check Node.js installation
+if ! command -v node &> /dev/null; then
+ log_error "Node.js is not installed. Please install Node.js $NODE_VERSION or later"
+ exit 1
+fi
+
+NODE_MAJOR_VERSION=$(node -v | cut -d. -f1 | sed 's/v//')
+if [[ $NODE_MAJOR_VERSION -lt $NODE_VERSION ]]; then
+ log_error "Node.js version $NODE_VERSION or later is required. Current version: $(node -v)"
+ exit 1
+fi
+
+# Copy application files
+log_info "Copying application files..."
+cp -r ../dist/* "$INSTALL_DIR/dist/"
+cp ../package.json "$INSTALL_DIR/"
+
+# Install production dependencies
+log_info "Installing production dependencies..."
+cd "$INSTALL_DIR"
+npm ci --production
+
+# Create environment file if it doesn't exist
+if [[ ! -f "$INSTALL_DIR/.env" ]]; then
+ log_info "Creating environment file..."
+ cat > "$INSTALL_DIR/.env" << EOF
+# Rybbit Monitor Agent Configuration
+NODE_ENV=production
+PORT=3000
+HOST=0.0.0.0
+
+# Region Configuration
+REGION=${REGION:-us-east}
+REGION_NAME=${REGION_NAME:-US East}
+
+# Main Server
+MAIN_SERVER_URL=https://your-rybbit-server.com
+
+# Security - IP Whitelist (comma-separated)
+# Leave empty to allow all IPs (not recommended for production)
+ALLOWED_IPS=
+
+# Monitoring Settings
+DEFAULT_TIMEOUT_MS=30000
+MAX_TIMEOUT_MS=60000
+
+# Logging
+LOG_LEVEL=info
+
+# Health Check
+HEALTH_CHECK_INTERVAL_MS=30000
+EOF
+ log_warn "Please edit $INSTALL_DIR/.env with your configuration"
+fi
+
+# Set proper permissions
+log_info "Setting permissions..."
+chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"
+chmod 600 "$INSTALL_DIR/.env"
+
+# Install systemd service
+log_info "Installing systemd service..."
+cp rybbit-monitor-agent.service /etc/systemd/system/
+systemctl daemon-reload
+
+# Enable and start service
+log_info "Enabling service..."
+systemctl enable "$SERVICE_NAME"
+
+log_info "Starting service..."
+systemctl start "$SERVICE_NAME"
+
+# Check service status
+sleep 2
+if systemctl is-active --quiet "$SERVICE_NAME"; then
+ log_info "Service started successfully!"
+ systemctl status "$SERVICE_NAME" --no-pager
+else
+ log_error "Service failed to start"
+ journalctl -u "$SERVICE_NAME" -n 50 --no-pager
+ exit 1
+fi
+
+# Setup log rotation
+log_info "Setting up log rotation..."
+cat > /etc/logrotate.d/rybbit-monitor-agent << EOF
+$INSTALL_DIR/logs/*.log {
+ daily
+ rotate 14
+ compress
+ delaycompress
+ missingok
+ notifempty
+ create 0640 $SERVICE_USER $SERVICE_USER
+ sharedscripts
+ postrotate
+ systemctl reload $SERVICE_NAME > /dev/null 2>&1 || true
+ endscript
+}
+EOF
+
+# Setup firewall (if ufw is installed)
+if command -v ufw &> /dev/null; then
+ log_info "Configuring firewall..."
+ ufw allow 3000/tcp comment "Rybbit Monitor Agent"
+fi
+
+log_info "Installation complete!"
+log_info ""
+log_info "Next steps:"
+log_info "1. Edit the configuration file: $INSTALL_DIR/.env"
+log_info "2. Add IP whitelist for your main server"
+log_info "3. Restart the service: systemctl restart $SERVICE_NAME"
+log_info "4. Check logs: journalctl -u $SERVICE_NAME -f"
+log_info ""
+log_info "Service management commands:"
+log_info " Start: systemctl start $SERVICE_NAME"
+log_info " Stop: systemctl stop $SERVICE_NAME"
+log_info " Restart: systemctl restart $SERVICE_NAME"
+log_info " Status: systemctl status $SERVICE_NAME"
+log_info " Logs: journalctl -u $SERVICE_NAME -f"
\ No newline at end of file
diff --git a/monitor-agent/tsconfig.json b/monitor-agent/tsconfig.json
new file mode 100644
index 000000000..9dbc68b9b
--- /dev/null
+++ b/monitor-agent/tsconfig.json
@@ -0,0 +1,29 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "lib": ["ES2022"],
+ "moduleResolution": "node",
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "allowJs": true,
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedIndexedAccess": true,
+ "allowSyntheticDefaultImports": true,
+ "typeRoots": ["./node_modules/@types"]
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist"]
+}
\ No newline at end of file
diff --git a/projectBrief.md b/projectBrief.md
deleted file mode 100644
index 0ed50c94f..000000000
--- a/projectBrief.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Rybbit Analytics
-
-Rybbit is an open source web analytics platform that is meant to be a more intuitive but still extremely powerful alternative to Google Analytics. It launched in May 2025 and has 6k Github stars.
-
-See README.md for a general overview and docs/src/content for more info
-
-- docker-compose.yml is the docker setup for Rybbit
-- frontend lives in /client and uses Next.js, Tailwind, Shadcn, Nivo.rocks, Tanstack Query, Tanstack Table, Zustand and Luxon
-- backend lives in /server and uses Fastify, Luxon, Drizzle, and Stripe
-- documentation and landing page live in /docs and uses Nextra
-- we use Postgres for all relational data and Clickhouse for events data
diff --git a/server/.env.example b/server/.env.example
new file mode 100644
index 000000000..35a89bb85
--- /dev/null
+++ b/server/.env.example
@@ -0,0 +1,35 @@
+NODE_ENV=development
+
+# ClickHouse configuration
+CLICKHOUSE_HOST=http://localhost:8123
+CLICKHOUSE_DB=analytics
+CLICKHOUSE_USER=default
+CLICKHOUSE_PASSWORD=
+CLICKHOUSE_READONLY_USER=readonly
+CLICKHOUSE_READONLY_PASSWORD=
+
+# PostgreSQL configuration
+POSTGRES_HOST=localhost
+POSTGRES_PORT=5432
+POSTGRES_DB=analytics
+POSTGRES_USER=postgres
+POSTGRES_PASSWORD=
+
+# Redis configuration (for BullMQ)
+REDIS_HOST=localhost
+REDIS_PORT=6379
+REDIS_PASSWORD=your-secure-password-here
+
+# Authentication
+BETTER_AUTH_SECRET=your-secret-key-here
+
+# Stripe (optional)
+STRIPE_SECRET_KEY=
+STRIPE_WEBHOOK_SECRET=
+
+# R2 Storage (optional)
+R2_ACCOUNT_ID=
+R2_ACCESS_KEY_ID=
+R2_SECRET_ACCESS_KEY=
+R2_BUCKET_NAME=
+R2_PUBLIC_URL=
\ No newline at end of file
diff --git a/server/package-lock.json b/server/package-lock.json
index 1df2a9d2e..520672e2e 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -18,6 +18,7 @@
"@mongodb-js/zstd": "^2.0.1",
"@rybbit/shared": "file:../shared",
"better-auth": "1.3.1",
+ "bullmq": "^5.56.5",
"dotenv": "16.5.0",
"drizzle-orm": "0.43.1",
"fastify": "5.3.3",
@@ -33,8 +34,9 @@
"rrweb": "^2.0.0-alpha.11",
"sqlstring": "2.3.3",
"stripe": "18.1.0",
+ "twilio": "^5.8.0",
"ua-parser-js": "2.0.3",
- "undici": "7.9.0",
+ "undici": "^7.9.0",
"web-vitals": "^5.0.3",
"zod": "3.24.4"
},
@@ -42,7 +44,7 @@
"@types/jsdom": "^21.1.7",
"@types/luxon": "3.6.2",
"@types/node": "^20.14.8",
- "@types/pg": "8.15.1",
+ "@types/pg": "^8.15.1",
"@types/psl": "^1.1.3",
"@types/sqlstring": "2.3.2",
"drizzle-kit": "0.31.1",
@@ -2175,6 +2177,12 @@
"integrity": "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==",
"license": "MIT"
},
+ "node_modules/@ioredis/commands": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.2.0.tgz",
+ "integrity": "sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg==",
+ "license": "MIT"
+ },
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@@ -2305,6 +2313,84 @@
"node": ">= 16.20.1"
}
},
+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.3.tgz",
+ "integrity": "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.3.tgz",
+ "integrity": "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.3.tgz",
+ "integrity": "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.3.tgz",
+ "integrity": "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.3.tgz",
+ "integrity": "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.3.tgz",
+ "integrity": "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.11.tgz",
@@ -4007,6 +4093,17 @@
"fastq": "^1.17.1"
}
},
+ "node_modules/axios": {
+ "version": "1.11.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
+ "integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
+ "license": "MIT",
+ "dependencies": {
+ "follow-redirects": "^1.15.6",
+ "form-data": "^4.0.4",
+ "proxy-from-env": "^1.1.0"
+ }
+ },
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -4156,6 +4253,12 @@
"ieee754": "^1.1.13"
}
},
+ "node_modules/buffer-equal-constant-time": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -4163,6 +4266,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/bullmq": {
+ "version": "5.56.5",
+ "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.56.5.tgz",
+ "integrity": "sha512-nhcVxoE9Y0YUuNYtvaD+N0Bk2kqcU+rXzJwdQIr8i8qC/fxoghwUYb9a+CidTv24pi1eqstLnBoa8xkR/P7Mdw==",
+ "license": "MIT",
+ "dependencies": {
+ "cron-parser": "^4.9.0",
+ "ioredis": "^5.4.1",
+ "msgpackr": "^1.11.2",
+ "node-abort-controller": "^3.1.1",
+ "semver": "^7.5.4",
+ "tslib": "^2.0.0",
+ "uuid": "^9.0.0"
+ }
+ },
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -4240,6 +4358,15 @@
"node": ">=0.8"
}
},
+ "node_modules/cluster-key-slot": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
+ "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -4304,6 +4431,18 @@
"node": ">=18"
}
},
+ "node_modules/cron-parser": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz",
+ "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "luxon": "^3.2.1"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -4387,11 +4526,16 @@
"node": "*"
}
},
+ "node_modules/dayjs": {
+ "version": "1.11.13",
+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz",
+ "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==",
+ "license": "MIT"
+ },
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
"integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -4467,6 +4611,15 @@
"node": ">=0.4.0"
}
},
+ "node_modules/denque": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
+ "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -4734,6 +4887,15 @@
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"license": "MIT"
},
+ "node_modules/ecdsa-sig-formatter": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
@@ -5122,6 +5284,26 @@
"node": ">=20"
}
},
+ "node_modules/follow-redirects": {
+ "version": "1.15.9",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
+ "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
@@ -5139,14 +5321,15 @@
}
},
"node_modules/form-data": {
- "version": "4.0.2",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
- "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@@ -5477,6 +5660,30 @@
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
},
+ "node_modules/ioredis": {
+ "version": "5.6.1",
+ "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.6.1.tgz",
+ "integrity": "sha512-UxC0Yv1Y4WRJiGQxQkP0hfdL0/5/6YvdfOOClRgJ0qppSarkhneSa6UvkMkms0AkdGimSH3Ikqm+6mkMmX7vGA==",
+ "license": "MIT",
+ "dependencies": {
+ "@ioredis/commands": "^1.1.1",
+ "cluster-key-slot": "^1.1.0",
+ "debug": "^4.3.4",
+ "denque": "^2.1.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.isarguments": "^3.1.0",
+ "redis-errors": "^1.2.0",
+ "redis-parser": "^3.0.0",
+ "standard-as-callback": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=12.22.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ioredis"
+ }
+ },
"node_modules/ipaddr.js": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz",
@@ -5717,6 +5924,49 @@
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
+ "node_modules/jsonwebtoken": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
+ "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",
+ "license": "MIT",
+ "dependencies": {
+ "jws": "^3.2.2",
+ "lodash.includes": "^4.3.0",
+ "lodash.isboolean": "^3.0.3",
+ "lodash.isinteger": "^4.0.4",
+ "lodash.isnumber": "^3.0.3",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.isstring": "^4.0.1",
+ "lodash.once": "^4.0.0",
+ "ms": "^2.1.1",
+ "semver": "^7.5.4"
+ },
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ }
+ },
+ "node_modules/jwa": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz",
+ "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-equal-constant-time": "^1.0.1",
+ "ecdsa-sig-formatter": "1.0.11",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jws": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
+ "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
+ "license": "MIT",
+ "dependencies": {
+ "jwa": "^1.4.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/knip": {
"version": "5.60.2",
"resolved": "https://registry.npmjs.org/knip/-/knip-5.60.2.tgz",
@@ -5829,6 +6079,60 @@
],
"license": "MIT"
},
+ "node_modules/lodash.defaults": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
+ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.includes": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isarguments": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz",
+ "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isboolean": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isinteger": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isnumber": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isplainobject": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isstring": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.once": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
+ "license": "MIT"
+ },
"node_modules/loupe": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.3.tgz",
@@ -6023,9 +6327,39 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
+ "node_modules/msgpackr": {
+ "version": "1.11.5",
+ "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.11.5.tgz",
+ "integrity": "sha512-UjkUHN0yqp9RWKy0Lplhh+wlpdt9oQBYgULZOiFhV3VclSF1JnSQWZ5r9gORQlNYaUKQoR8itv7g7z1xDDuACA==",
+ "license": "MIT",
+ "optionalDependencies": {
+ "msgpackr-extract": "^3.0.2"
+ }
+ },
+ "node_modules/msgpackr-extract": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.3.tgz",
+ "integrity": "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-gyp-build-optional-packages": "5.2.2"
+ },
+ "bin": {
+ "download-msgpackr-prebuilds": "bin/download-prebuilds.js"
+ },
+ "optionalDependencies": {
+ "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3",
+ "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3",
+ "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3",
+ "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3",
+ "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3",
+ "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"
+ }
+ },
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
@@ -6076,6 +6410,12 @@
"node": ">=10"
}
},
+ "node_modules/node-abort-controller": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz",
+ "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
+ "license": "MIT"
+ },
"node_modules/node-addon-api": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
@@ -6121,6 +6461,21 @@
}
}
},
+ "node_modules/node-gyp-build-optional-packages": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
+ "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "detect-libc": "^2.0.1"
+ },
+ "bin": {
+ "node-gyp-build-optional-packages": "bin.js",
+ "node-gyp-build-optional-packages-optional": "optional.js",
+ "node-gyp-build-optional-packages-test": "build-test.js"
+ }
+ },
"node_modules/nwsapi": {
"version": "2.2.20",
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
@@ -6681,6 +7036,12 @@
],
"license": "MIT"
},
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
+ "license": "MIT"
+ },
"node_modules/psl": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
@@ -6850,6 +7211,27 @@
"node": ">= 12.13.0"
}
},
+ "node_modules/redis-errors": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz",
+ "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/redis-parser": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz",
+ "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==",
+ "license": "MIT",
+ "dependencies": {
+ "redis-errors": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -7091,6 +7473,12 @@
"integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==",
"peer": true
},
+ "node_modules/scmp": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/scmp/-/scmp-2.1.0.tgz",
+ "integrity": "sha512-o/mRQGk9Rcer/jEEw/yw4mwo3EU/NvYvp577/Btqrym9Qy5/MdWGBqipbALgd2lrdWTJ5/gqDusxfnQBxOxT2Q==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/secure-json-parse": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.0.0.tgz",
@@ -7372,6 +7760,12 @@
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
"dev": true
},
+ "node_modules/standard-as-callback": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz",
+ "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==",
+ "license": "MIT"
+ },
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -7782,6 +8176,49 @@
"node": "*"
}
},
+ "node_modules/twilio": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/twilio/-/twilio-5.8.0.tgz",
+ "integrity": "sha512-aJLBvI7ODLmFHI7ZYLBiMZKIdHuF9PrPeRM/GBMDg/AAzGXs4V8gEnNPHyTVThK0/8J48YHSqXMlQ+WJR5nxoQ==",
+ "license": "MIT",
+ "dependencies": {
+ "axios": "^1.11.0",
+ "dayjs": "^1.11.9",
+ "https-proxy-agent": "^5.0.0",
+ "jsonwebtoken": "^9.0.2",
+ "qs": "^6.9.4",
+ "scmp": "^2.1.0",
+ "xmlbuilder": "^13.0.2"
+ },
+ "engines": {
+ "node": ">=14.0"
+ }
+ },
+ "node_modules/twilio/node_modules/agent-base": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6.0.0"
+ }
+ },
+ "node_modules/twilio/node_modules/https-proxy-agent": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "6",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -8290,6 +8727,15 @@
"node": ">=18"
}
},
+ "node_modules/xmlbuilder": {
+ "version": "13.0.2",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-13.0.2.tgz",
+ "integrity": "sha512-Eux0i2QdDYKbdbA6AM6xE4m6ZTZr4G4xF9kahI2ukSEMCzwce2eX9WlTI5J3s+NU7hpasFsr8hWIONae7LluAQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0"
+ }
+ },
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
diff --git a/server/package.json b/server/package.json
index 92d466949..20fc5a79c 100644
--- a/server/package.json
+++ b/server/package.json
@@ -31,6 +31,7 @@
"@mongodb-js/zstd": "^2.0.1",
"@rybbit/shared": "file:../shared",
"better-auth": "1.3.1",
+ "bullmq": "^5.56.5",
"dotenv": "16.5.0",
"drizzle-orm": "0.43.1",
"fastify": "5.3.3",
@@ -46,8 +47,9 @@
"rrweb": "^2.0.0-alpha.11",
"sqlstring": "2.3.3",
"stripe": "18.1.0",
+ "twilio": "^5.8.0",
"ua-parser-js": "2.0.3",
- "undici": "7.9.0",
+ "undici": "^7.9.0",
"web-vitals": "^5.0.3",
"zod": "3.24.4"
},
@@ -55,7 +57,7 @@
"@types/jsdom": "^21.1.7",
"@types/luxon": "3.6.2",
"@types/node": "^20.14.8",
- "@types/pg": "8.15.1",
+ "@types/pg": "^8.15.1",
"@types/psl": "^1.1.3",
"@types/sqlstring": "2.3.2",
"drizzle-kit": "0.31.1",
diff --git a/server/src/api/uptime/createMonitor.ts b/server/src/api/uptime/createMonitor.ts
new file mode 100644
index 000000000..0293721bf
--- /dev/null
+++ b/server/src/api/uptime/createMonitor.ts
@@ -0,0 +1,90 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { uptimeService } from "../../services/uptime/uptimeService.js";
+import { createMonitorSchema, type CreateMonitorInput } from "./schemas.js";
+
+interface CreateMonitorBody {
+ Body: CreateMonitorInput;
+}
+
+export async function createMonitor(request: FastifyRequest<CreateMonitorBody>, reply: FastifyReply) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Validate request body with Zod
+ const validatedBody = createMonitorSchema.parse(request.body);
+
+ const {
+ organizationId,
+ name,
+ monitorType,
+ intervalSeconds,
+ enabled,
+ httpConfig,
+ tcpConfig,
+ validationRules,
+ monitoringType,
+ selectedRegions,
+ } = validatedBody;
+
+ // Check if user has access to the organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied to organization" });
+ }
+
+ // Create the monitor
+ const [newMonitor] = await db
+ .insert(uptimeMonitors)
+ .values({
+ organizationId,
+ name,
+ monitorType,
+ intervalSeconds,
+ enabled,
+ httpConfig: monitorType === "http" ? httpConfig : null,
+ tcpConfig: monitorType === "tcp" ? tcpConfig : null,
+ validationRules,
+ monitoringType: monitoringType || "local",
+ selectedRegions: selectedRegions || ["local"],
+ createdBy: userId,
+ })
+ .returning();
+
+ // Initialize monitor status
+ await db.insert(uptimeMonitorStatus).values({
+ monitorId: newMonitor.id,
+ currentStatus: "unknown",
+ consecutiveFailures: 0,
+ consecutiveSuccesses: 0,
+ });
+
+ // Schedule the monitor if enabled
+ if (enabled) {
+ await uptimeService.onMonitorCreated(newMonitor.id, intervalSeconds);
+ }
+
+ return reply.status(201).send(newMonitor);
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors,
+ });
+ }
+ console.error("Error creating monitor:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/uptime/deleteMonitor.ts b/server/src/api/uptime/deleteMonitor.ts
new file mode 100644
index 000000000..62c8108f8
--- /dev/null
+++ b/server/src/api/uptime/deleteMonitor.ts
@@ -0,0 +1,59 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { uptimeService } from "../../services/uptime/uptimeService.js";
+
+interface DeleteMonitorParams {
+ Params: {
+ monitorId: string;
+ };
+}
+
+export async function deleteMonitor(request: FastifyRequest<DeleteMonitorParams>, reply: FastifyReply) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // First get the monitor to check if it exists and user has access
+ const existingMonitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!existingMonitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, existingMonitor.organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Remove the monitor from the scheduler first
+ await uptimeService.onMonitorDeleted(Number(monitorId));
+
+ // Delete monitor and related records in a transaction
+ await db.transaction(async (tx) => {
+ // Delete monitor status first
+ await tx.delete(uptimeMonitorStatus).where(eq(uptimeMonitorStatus.monitorId, Number(monitorId)));
+
+ // Delete the monitor
+ await tx.delete(uptimeMonitors).where(eq(uptimeMonitors.id, Number(monitorId)));
+ });
+
+ return reply.status(204).send();
+ } catch (error) {
+ console.error("Error deleting monitor:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/uptime/getMonitor.ts b/server/src/api/uptime/getMonitor.ts
new file mode 100644
index 000000000..4a4214d1a
--- /dev/null
+++ b/server/src/api/uptime/getMonitor.ts
@@ -0,0 +1,68 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+
+interface GetMonitorParams {
+ Params: {
+ monitorId: string;
+ };
+}
+
+export async function getMonitor(
+ request: FastifyRequest<GetMonitorParams>,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // First get the monitor
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(
+ eq(member.userId, userId),
+ eq(member.organizationId, monitor.organizationId)
+ ),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Get monitor with status
+ const result = await db
+ .select({
+ monitor: uptimeMonitors,
+ status: uptimeMonitorStatus,
+ })
+ .from(uptimeMonitors)
+ .leftJoin(uptimeMonitorStatus, eq(uptimeMonitors.id, uptimeMonitorStatus.monitorId))
+ .where(eq(uptimeMonitors.id, Number(monitorId)))
+ .limit(1);
+
+ const monitorWithStatus = {
+ ...result[0].monitor,
+ status: result[0].status,
+ };
+
+ return reply.status(200).send(monitorWithStatus);
+ } catch (error) {
+ console.error("Error retrieving monitor:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/getMonitorEvents.ts b/server/src/api/uptime/getMonitorEvents.ts
new file mode 100644
index 000000000..136c72366
--- /dev/null
+++ b/server/src/api/uptime/getMonitorEvents.ts
@@ -0,0 +1,148 @@
+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 { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+import { getMonitorEventsQuerySchema, type GetMonitorEventsQuery } from "./schemas.js";
+
+interface GetMonitorEventsRequest {
+ Params: {
+ monitorId: string;
+ };
+ Querystring: GetMonitorEventsQuery;
+}
+
+export async function getMonitorEvents(request: FastifyRequest<GetMonitorEventsRequest>, reply: FastifyReply) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Validate query parameters with Zod
+ const query = getMonitorEventsQuerySchema.parse(request.query);
+ const { status, region, limit, offset } = query;
+ // First check if monitor exists and user has access
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Build query for ClickHouse
+ let queryStr = `
+ SELECT
+ monitor_id,
+ organization_id,
+ timestamp,
+ monitor_type,
+ monitor_url,
+ monitor_name,
+ region,
+ status,
+ status_code,
+ response_time_ms,
+ dns_time_ms,
+ tcp_time_ms,
+ tls_time_ms,
+ ttfb_ms,
+ transfer_time_ms,
+ validation_errors,
+ response_headers,
+ response_size_bytes,
+ port,
+ error_message,
+ error_type
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ `;
+
+ const queryParams: any = { monitorId: Number(monitorId) };
+
+ if (status) {
+ queryStr += ` AND status = {status: String}`;
+ queryParams.status = status;
+ }
+
+ if (region) {
+ queryStr += ` AND region = {region: String}`;
+ queryParams.region = region;
+ }
+
+ queryStr += ` ORDER BY timestamp DESC`;
+ queryStr += ` LIMIT {limit: UInt32} OFFSET {offset: UInt32}`;
+ queryParams.limit = limit;
+ queryParams.offset = offset;
+
+ const result = await clickhouse.query({
+ query: queryStr,
+ query_params: queryParams,
+ format: "JSONEachRow",
+ });
+
+ const events = await processResults(result);
+
+ // Get total count
+ let countQuery = `
+ SELECT count() as total
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ `;
+
+ const countParams: any = { monitorId: Number(monitorId) };
+
+ if (status) {
+ countQuery += ` AND status = {status: String}`;
+ countParams.status = status;
+ }
+
+ if (region) {
+ countQuery += ` AND region = {region: String}`;
+ countParams.region = region;
+ }
+
+ const countResult = await clickhouse.query({
+ query: countQuery,
+ query_params: countParams,
+ format: "JSONEachRow",
+ });
+
+ const countData = await processResults<{ total: number }>(countResult);
+ const total = countData[0]?.total || 0;
+
+ return reply.status(200).send({
+ events,
+ pagination: {
+ total: Number(total),
+ limit: limit,
+ offset: offset,
+ },
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors,
+ });
+ }
+ console.error("Error retrieving monitor events:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/uptime/getMonitorStats.ts b/server/src/api/uptime/getMonitorStats.ts
new file mode 100644
index 000000000..ad9dff6a5
--- /dev/null
+++ b/server/src/api/uptime/getMonitorStats.ts
@@ -0,0 +1,217 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults, TimeBucketToFn } from "../analytics/utils.js";
+import { getMonitorStatsQuerySchema, type GetMonitorStatsQuery } from "./schemas.js";
+import { DateTime } from "luxon";
+
+interface GetMonitorStatsRequest {
+ Params: {
+ monitorId: string;
+ };
+ Querystring: GetMonitorStatsQuery;
+}
+
+export async function getMonitorStats(request: FastifyRequest<GetMonitorStatsRequest>, reply: FastifyReply) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Validate query parameters with Zod
+ const query = getMonitorStatsQuerySchema.parse(request.query);
+ const { region, hours } = query;
+ // First check if monitor exists and user has access
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Get aggregated stats from ClickHouse
+ let statsQuery = `
+ SELECT
+ count() as total_checks,
+ countIf(status = 'success') as successful_checks,
+ countIf(status = 'failure') as failed_checks,
+ countIf(status = 'timeout') as timeout_checks,
+ avg(response_time_ms) as avg_response_time,
+ min(response_time_ms) as min_response_time,
+ max(response_time_ms) as max_response_time,
+ quantile(0.5)(response_time_ms) as p50_response_time,
+ quantile(0.75)(response_time_ms) as p75_response_time,
+ quantile(0.90)(response_time_ms) as p90_response_time,
+ quantile(0.95)(response_time_ms) as p95_response_time,
+ quantile(0.99)(response_time_ms) as p99_response_time,
+ 100 * countIf(status = 'success') / count() as uptime_percentage
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ AND timestamp >= now() - INTERVAL {hours: UInt32} HOUR
+ `;
+
+ const queryParams: any = {
+ monitorId: Number(monitorId),
+ hours: hours || 24,
+ };
+
+ if (region) {
+ statsQuery += ` AND region = {region: String}`;
+ queryParams.region = region;
+ }
+
+ const statsResult = await clickhouse.query({
+ query: statsQuery,
+ query_params: queryParams,
+ format: "JSONEachRow",
+ });
+
+ const statsData = await processResults<{
+ total_checks: number;
+ successful_checks: number;
+ failed_checks: number;
+ timeout_checks: number;
+ avg_response_time: number;
+ min_response_time: number;
+ max_response_time: number;
+ p50_response_time: number;
+ p75_response_time: number;
+ p90_response_time: number;
+ p95_response_time: number;
+ p99_response_time: number;
+ uptime_percentage: number;
+ }>(statsResult);
+ const stats = statsData[0] || {
+ total_checks: 0,
+ successful_checks: 0,
+ failed_checks: 0,
+ timeout_checks: 0,
+ avg_response_time: 0,
+ min_response_time: 0,
+ max_response_time: 0,
+ p50_response_time: 0,
+ p75_response_time: 0,
+ p90_response_time: 0,
+ p95_response_time: 0,
+ p99_response_time: 0,
+ uptime_percentage: 0,
+ };
+
+ // Determine time bucket based on time range and interval
+ const hoursBack = hours || 24;
+ const days = hoursBack / 24;
+
+ let bucket = query.bucket || "hour"; // Default to hour if not specified
+ if (!query.bucket) {
+ // Auto-select bucket based on time range
+ if (days <= 1) {
+ bucket = "minute";
+ } else if (days <= 3) {
+ bucket = "five_minutes";
+ } else if (days <= 7) {
+ bucket = "ten_minutes";
+ } else if (days <= 60) {
+ bucket = "hour";
+ } else {
+ bucket = "day";
+ }
+ }
+
+ // Validate bucket is in TimeBucketToFn
+ const bucketFn = TimeBucketToFn[bucket as keyof typeof TimeBucketToFn] || TimeBucketToFn.hour;
+
+ // Get response time distribution
+ let distributionQuery = `
+ SELECT
+ ${bucketFn}(timestamp) as time_bucket,
+ avg(response_time_ms) as avg_response_time,
+ avg(dns_time_ms) as avg_dns_time,
+ avg(tcp_time_ms) as avg_tcp_time,
+ avg(tls_time_ms) as avg_tls_time,
+ avg(ttfb_ms) as avg_ttfb,
+ avg(transfer_time_ms) as avg_transfer_time,
+ count() as check_count,
+ countIf(status = 'success') as success_count,
+ countIf(status = 'failure') as failure_count,
+ countIf(status = 'timeout') as timeout_count
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ AND timestamp >= now() - INTERVAL {hours: UInt32} HOUR
+ `;
+
+ if (region) {
+ distributionQuery += ` AND region = {region: String}`;
+ }
+
+ distributionQuery += `
+ GROUP BY time_bucket
+ ORDER BY time_bucket ASC
+ `;
+
+ const distributionResult = await clickhouse.query({
+ query: distributionQuery,
+ query_params: queryParams,
+ format: "JSONEachRow",
+ });
+
+ const distribution = await processResults(distributionResult);
+
+ // Rename time_bucket back to hour for backward compatibility with frontend
+ const formattedDistribution = distribution.map((item: any) => ({
+ ...item,
+ hour: item.time_bucket,
+ }));
+
+ return reply.status(200).send({
+ hours: hours || 24, // Return the hours used
+ region,
+ stats: {
+ totalChecks: Number(stats.total_checks),
+ successfulChecks: Number(stats.successful_checks),
+ failedChecks: Number(stats.failed_checks),
+ timeoutChecks: Number(stats.timeout_checks),
+ uptimePercentage: Number(stats.uptime_percentage),
+ responseTime: {
+ avg: Number(stats.avg_response_time),
+ min: Number(stats.min_response_time),
+ max: Number(stats.max_response_time),
+ p50: Number(stats.p50_response_time),
+ p75: Number(stats.p75_response_time),
+ p90: Number(stats.p90_response_time),
+ p95: Number(stats.p95_response_time),
+ p99: Number(stats.p99_response_time),
+ },
+ },
+ distribution: formattedDistribution,
+ monitorType: monitor.monitorType,
+ bucket,
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors,
+ });
+ }
+ console.error("Error retrieving monitor stats:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/uptime/getMonitorStatus.ts b/server/src/api/uptime/getMonitorStatus.ts
new file mode 100644
index 000000000..a994ec8ac
--- /dev/null
+++ b/server/src/api/uptime/getMonitorStatus.ts
@@ -0,0 +1,141 @@
+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 { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+
+interface GetMonitorStatusRequest {
+ Params: {
+ monitorId: string;
+ };
+}
+
+export async function getMonitorStatus(
+ request: FastifyRequest<GetMonitorStatusRequest>,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // First check if monitor exists and user has access
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(
+ eq(member.userId, userId),
+ eq(member.organizationId, monitor.organizationId)
+ ),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Get current status from PostgreSQL
+ const currentStatus = await db.query.uptimeMonitorStatus.findFirst({
+ where: eq(uptimeMonitorStatus.monitorId, Number(monitorId)),
+ });
+
+ // Get recent incidents from ClickHouse
+ const incidentsQuery = `
+ WITH incidents AS (
+ SELECT
+ timestamp,
+ status,
+ error_message,
+ error_type,
+ response_time_ms,
+ status_code,
+ LAG(status) OVER (ORDER BY timestamp) as prev_status,
+ LEAD(status) OVER (ORDER BY timestamp) as next_status
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ AND timestamp >= now() - INTERVAL 7 DAY
+ ORDER BY timestamp DESC
+ )
+ SELECT
+ timestamp as incident_start,
+ status,
+ error_message,
+ error_type,
+ response_time_ms,
+ status_code,
+ CASE
+ WHEN next_status = 'success' THEN
+ LEAD(timestamp) OVER (ORDER BY timestamp)
+ ELSE NULL
+ END as incident_end
+ FROM incidents
+ WHERE status != 'success'
+ AND (prev_status = 'success' OR prev_status IS NULL)
+ ORDER BY timestamp DESC
+ LIMIT 10
+ `;
+
+ const incidentsResult = await clickhouse.query({
+ query: incidentsQuery,
+ query_params: {
+ monitorId: Number(monitorId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const recentIncidents = await processResults(incidentsResult);
+
+ // Get last 5 checks
+ const recentChecksQuery = `
+ SELECT
+ timestamp,
+ status,
+ response_time_ms,
+ status_code,
+ error_message,
+ validation_errors
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ ORDER BY timestamp DESC
+ LIMIT 5
+ `;
+
+ const recentChecksResult = await clickhouse.query({
+ query: recentChecksQuery,
+ query_params: {
+ monitorId: Number(monitorId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const recentChecks = await processResults(recentChecksResult);
+
+ return reply.status(200).send({
+ monitorId: Number(monitorId),
+ currentStatus: currentStatus || {
+ currentStatus: "unknown",
+ lastCheckedAt: null,
+ nextCheckAt: null,
+ consecutiveFailures: 0,
+ consecutiveSuccesses: 0,
+ },
+ recentIncidents,
+ recentChecks,
+ });
+ } catch (error) {
+ console.error("Error retrieving monitor status:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/getMonitorUptime.ts b/server/src/api/uptime/getMonitorUptime.ts
new file mode 100644
index 000000000..1fd9cdec2
--- /dev/null
+++ b/server/src/api/uptime/getMonitorUptime.ts
@@ -0,0 +1,190 @@
+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 { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+
+interface GetMonitorUptimeRequest {
+ Params: {
+ monitorId: string;
+ };
+}
+
+export async function getMonitorUptime(
+ request: FastifyRequest<GetMonitorUptimeRequest>,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // First check if monitor exists and user has access
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(
+ eq(member.userId, userId),
+ eq(member.organizationId, monitor.organizationId)
+ ),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Get the first check event to determine when monitoring started
+ const firstCheckQuery = `
+ SELECT
+ min(timestamp) as first_check,
+ max(timestamp) as last_check
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ `;
+
+ const firstCheckResult = await clickhouse.query({
+ query: firstCheckQuery,
+ query_params: {
+ monitorId: Number(monitorId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const firstCheckData = await processResults<{
+ first_check: string;
+ last_check: string;
+ }>(firstCheckResult);
+
+ if (!firstCheckData[0]?.first_check) {
+ return reply.status(200).send({
+ monitorId: Number(monitorId),
+ totalUptimeSeconds: 0,
+ currentUptimeSeconds: 0,
+ lastDowntime: null,
+ monitoringSince: null,
+ lastCheck: null,
+ });
+ }
+
+ const { first_check, last_check } = firstCheckData[0];
+
+ // Get the most recent downtime event
+ const lastDowntimeQuery = `
+ SELECT
+ timestamp as downtime_start,
+ error_message,
+ error_type,
+ status
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ AND status != 'success'
+ ORDER BY timestamp DESC
+ LIMIT 1
+ `;
+
+ const lastDowntimeResult = await clickhouse.query({
+ query: lastDowntimeQuery,
+ query_params: {
+ monitorId: Number(monitorId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const lastDowntimeData = await processResults<{
+ downtime_start: string;
+ error_message?: string;
+ error_type?: string;
+ status: string;
+ }>(lastDowntimeResult);
+
+ const lastDowntime = lastDowntimeData[0] || null;
+
+ // Calculate total monitoring duration
+ const monitoringStartMs = new Date(first_check).getTime();
+ const lastCheckMs = new Date(last_check).getTime();
+ const totalMonitoringSeconds = Math.floor((lastCheckMs - monitoringStartMs) / 1000);
+
+ // Calculate current uptime (time since last downtime or since monitoring started)
+ let currentUptimeSeconds = totalMonitoringSeconds;
+ if (lastDowntime) {
+ const lastDowntimeMs = new Date(lastDowntime.downtime_start).getTime();
+ // Only count as current uptime if the downtime was after monitoring started
+ if (lastDowntimeMs > monitoringStartMs) {
+ currentUptimeSeconds = Math.floor((lastCheckMs - lastDowntimeMs) / 1000);
+ }
+ }
+
+ // Get total downtime duration for accurate total uptime calculation
+ const downtimeStatsQuery = `
+ SELECT
+ countIf(status != 'success') as total_downtime_checks,
+ countIf(status = 'success') as total_uptime_checks,
+ count() as total_checks,
+ avg(if(status = 'success', 0, 1)) * 100 as downtime_percentage
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ `;
+
+ const downtimeStatsResult = await clickhouse.query({
+ query: downtimeStatsQuery,
+ query_params: {
+ monitorId: Number(monitorId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const downtimeStats = await processResults<{
+ total_downtime_checks: number;
+ total_uptime_checks: number;
+ total_checks: number;
+ downtime_percentage: number;
+ }>(downtimeStatsResult);
+
+ const stats = downtimeStats[0] || {
+ total_downtime_checks: 0,
+ total_uptime_checks: 0,
+ total_checks: 0,
+ downtime_percentage: 0,
+ };
+
+ // Calculate estimated total uptime based on check intervals
+ // This is an approximation since we don't store exact downtime durations
+ const avgCheckInterval = monitor.intervalSeconds;
+ const estimatedTotalDowntimeSeconds = stats.total_downtime_checks * avgCheckInterval;
+ const estimatedTotalUptimeSeconds = Math.max(0, totalMonitoringSeconds - estimatedTotalDowntimeSeconds);
+
+ return reply.status(200).send({
+ monitorId: Number(monitorId),
+ totalUptimeSeconds: estimatedTotalUptimeSeconds,
+ currentUptimeSeconds,
+ totalMonitoringSeconds,
+ lastDowntime: lastDowntime ? {
+ timestamp: lastDowntime.downtime_start,
+ error: lastDowntime.error_message,
+ errorType: lastDowntime.error_type,
+ status: lastDowntime.status,
+ } : null,
+ monitoringSince: first_check,
+ lastCheck: last_check,
+ uptimePercentage: 100 - stats.downtime_percentage,
+ totalChecks: stats.total_checks,
+ failedChecks: stats.total_downtime_checks,
+ });
+ } catch (error) {
+ console.error("Error retrieving monitor uptime:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/getMonitorUptimeBuckets.ts b/server/src/api/uptime/getMonitorUptimeBuckets.ts
new file mode 100644
index 000000000..c53556bf0
--- /dev/null
+++ b/server/src/api/uptime/getMonitorUptimeBuckets.ts
@@ -0,0 +1,214 @@
+import { and, eq } from "drizzle-orm";
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+
+// Query params schema
+const getMonitorUptimeBucketsQuerySchema = z.object({
+ bucket: z.enum(["hour", "day", "week"]).default("day"),
+ days: z.string().transform(Number).pipe(z.number().int().positive().max(90)).default("7"),
+ timeZone: z.string().optional(),
+});
+
+interface GetMonitorUptimeBucketsRequest {
+ Params: {
+ monitorId: string;
+ };
+ Querystring: z.infer<typeof getMonitorUptimeBucketsQuerySchema>;
+}
+
+export async function getMonitorUptimeBuckets(
+ request: FastifyRequest<GetMonitorUptimeBucketsRequest>,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Validate query parameters
+ const query = getMonitorUptimeBucketsQuerySchema.parse(request.query);
+ const { bucket, days, timeZone = "UTC" } = query;
+
+ // First check if monitor exists and user has access
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!monitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Determine the time bucket function based on the bucket parameter
+ let timeBucketFn: string;
+ let dateFormat: string;
+ switch (bucket) {
+ case "hour":
+ timeBucketFn = `toStartOfHour(toTimeZone(timestamp, '${timeZone}'))`;
+ dateFormat = "%Y-%m-%d %H:00:00";
+ break;
+ case "week":
+ timeBucketFn = `toStartOfWeek(toTimeZone(timestamp, '${timeZone}'))`;
+ dateFormat = "%Y-%m-%d";
+ break;
+ case "day":
+ default:
+ timeBucketFn = `toStartOfDay(toTimeZone(timestamp, '${timeZone}'))`;
+ dateFormat = "%Y-%m-%d";
+ break;
+ }
+
+ // Query to get bucketed uptime data
+ const query_str = `
+ SELECT
+ toTimeZone(bucket_time_tz, 'UTC') as bucket_time,
+ formatDateTime(bucket_time_tz, '${dateFormat}', '${timeZone}') as bucket_formatted,
+ count() as total_checks,
+ countIf(status = 'success') as successful_checks,
+ countIf(status = 'failure') as failed_checks,
+ countIf(status = 'timeout') as timeout_checks,
+ if(count() > 0,
+ round(100.0 * countIf(status = 'success') / count(), 2),
+ 100.0) as uptime_percentage
+ FROM (
+ SELECT
+ *,
+ ${timeBucketFn} as bucket_time_tz
+ FROM monitor_events
+ WHERE monitor_id = {monitorId: UInt32}
+ AND timestamp >= now() - INTERVAL {days: UInt32} DAY
+ )
+ GROUP BY bucket_time_tz
+ ORDER BY bucket_time_tz DESC
+ `;
+
+ const result = await clickhouse.query({
+ query: query_str,
+ query_params: {
+ monitorId: Number(monitorId),
+ days: days,
+ },
+ format: "JSONEachRow",
+ });
+
+ const buckets = await processResults(result);
+
+ // Generate all expected buckets for the time range
+ // Use timezone-aware date generation
+ const nowInTz = new Date(new Date().toLocaleString("en-US", { timeZone }));
+ const allBuckets: Array<{
+ bucket_time: string;
+ bucket_formatted: string;
+ total_checks: number;
+ successful_checks: number;
+ failed_checks: number;
+ timeout_checks: number;
+ uptime_percentage: number;
+ }> = [];
+
+ for (let i = 0; i < days; i++) {
+ const date = new Date(nowInTz);
+
+ if (bucket === "hour") {
+ // For hourly buckets, generate 24 buckets per day
+ for (let h = 0; h < 24; h++) {
+ date.setDate(date.getDate() - i);
+ date.setHours(23 - h, 0, 0, 0);
+ if (date <= nowInTz) {
+ allBuckets.push({
+ bucket_time: date.toISOString(),
+ bucket_formatted: date.toISOString().slice(0, 13) + ':00:00',
+ total_checks: 0,
+ successful_checks: 0,
+ failed_checks: 0,
+ timeout_checks: 0,
+ uptime_percentage: 100.0,
+ });
+ }
+ }
+ } else if (bucket === "week") {
+ // For weekly buckets, calculate start of week
+ date.setDate(date.getDate() - i * 7);
+ const dayOfWeek = date.getDay();
+ const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // Monday as start
+ date.setDate(diff);
+ date.setHours(0, 0, 0, 0);
+
+ if (allBuckets.length === 0 ||
+ !allBuckets.some(b => b.bucket_formatted === date.toISOString().slice(0, 10))) {
+ allBuckets.push({
+ bucket_time: date.toISOString(),
+ bucket_formatted: date.toISOString().slice(0, 10),
+ total_checks: 0,
+ successful_checks: 0,
+ failed_checks: 0,
+ timeout_checks: 0,
+ uptime_percentage: 100.0,
+ });
+ }
+ } else {
+ // Daily buckets
+ date.setDate(date.getDate() - i);
+ date.setHours(0, 0, 0, 0);
+ allBuckets.push({
+ bucket_time: date.toISOString(),
+ bucket_formatted: date.toISOString().slice(0, 10),
+ total_checks: 0,
+ successful_checks: 0,
+ failed_checks: 0,
+ timeout_checks: 0,
+ uptime_percentage: 100.0,
+ });
+ }
+ }
+
+ // Merge actual data with empty buckets
+ const bucketsMap = new Map(
+ buckets.map((b: any) => [b.bucket_formatted, b])
+ );
+
+ const mergedBuckets = allBuckets.map(emptyBucket => {
+ const actualData = bucketsMap.get(emptyBucket.bucket_formatted);
+ return actualData || emptyBucket;
+ });
+
+ // Sort by bucket_time ascending (oldest first) for frontend display
+ mergedBuckets.sort((a, b) =>
+ new Date(a.bucket_time).getTime() - new Date(b.bucket_time).getTime()
+ );
+
+ return reply.status(200).send({
+ buckets: mergedBuckets,
+ bucket,
+ days,
+ monitorId: Number(monitorId),
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors,
+ });
+ }
+ console.error("Error retrieving monitor uptime buckets:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/getMonitors.ts b/server/src/api/uptime/getMonitors.ts
new file mode 100644
index 000000000..ba1924681
--- /dev/null
+++ b/server/src/api/uptime/getMonitors.ts
@@ -0,0 +1,174 @@
+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 { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+import { getMonitorsQuerySchema, type GetMonitorsQuery } from "./schemas.js";
+
+interface GetMonitorsRequest {
+ Querystring: GetMonitorsQuery;
+}
+
+export async function getMonitors(
+ request: FastifyRequest<GetMonitorsRequest>,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Get user's organizations
+ const userOrgs = await db
+ .select({ organizationId: member.organizationId })
+ .from(member)
+ .where(eq(member.userId, userId));
+
+ if (userOrgs.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ try {
+ // Validate query parameters with Zod
+ const query = getMonitorsQuerySchema.parse(request.query);
+ const { enabled, monitorType, organizationId, limit, offset } = query;
+
+ // Build where conditions
+ const orgIds = userOrgs.map(org => org.organizationId);
+ const conditions = [];
+
+ // Filter by specific organization if provided, otherwise all user's organizations
+ if (organizationId) {
+ // Check if user has access to the specified organization
+ if (!orgIds.includes(organizationId)) {
+ return reply.status(403).send({ error: "Access denied to organization" });
+ }
+ conditions.push(eq(uptimeMonitors.organizationId, organizationId));
+ } else {
+ // Use inArray for multiple orgs
+ conditions.push(inArray(uptimeMonitors.organizationId, orgIds));
+ }
+
+ if (enabled !== undefined) {
+ conditions.push(eq(uptimeMonitors.enabled, enabled));
+ }
+
+ if (monitorType) {
+ conditions.push(eq(uptimeMonitors.monitorType, monitorType));
+ }
+
+ // Get monitors with their status
+ const monitors = await db
+ .select({
+ monitor: uptimeMonitors,
+ status: uptimeMonitorStatus,
+ })
+ .from(uptimeMonitors)
+ .leftJoin(uptimeMonitorStatus, eq(uptimeMonitors.id, uptimeMonitorStatus.monitorId))
+ .where(and(...conditions))
+ .orderBy(desc(uptimeMonitors.createdAt))
+ .limit(limit)
+ .offset(offset);
+
+ // Get monitor IDs for uptime calculations
+ const monitorIds = monitors.map(m => m.monitor.id);
+
+ // Calculate uptime percentages from ClickHouse if we have monitors
+ let uptimeData: Record<number, { percentage24h: number; percentage7d: number; percentage30d: number }> = {};
+
+ if (monitorIds.length > 0) {
+ try {
+ const now = DateTime.now();
+ const periods = [
+ { key: '24h', startTime: now.minus({ hours: 24 }).toFormat("yyyy-MM-dd HH:mm:ss") },
+ { key: '7d', startTime: now.minus({ days: 7 }).toFormat("yyyy-MM-dd HH:mm:ss") },
+ { key: '30d', startTime: now.minus({ days: 30 }).toFormat("yyyy-MM-dd HH:mm:ss") }
+ ];
+
+ // Run queries for each period
+ const uptimeResults = await Promise.all(
+ periods.map(async ({ key, startTime }) => {
+ const query = `
+ SELECT
+ monitor_id,
+ countIf(status = 'success') as successful_checks,
+ count() as total_checks
+ FROM monitor_events
+ WHERE monitor_id IN {monitorIds:Array(UInt32)}
+ AND timestamp >= {startTime:String}
+ GROUP BY monitor_id
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ query_params: {
+ monitorIds,
+ startTime
+ },
+ format: 'JSONEachRow'
+ });
+
+ const data = await processResults<{
+ monitor_id: number;
+ successful_checks: number;
+ total_checks: number;
+ }>(result);
+
+ return { key, data };
+ })
+ );
+
+ // Organize results by monitor ID
+ monitorIds.forEach(monitorId => {
+ uptimeData[monitorId] = {
+ percentage24h: 0,
+ percentage7d: 0,
+ percentage30d: 0
+ };
+ });
+
+ uptimeResults.forEach(({ key, data }) => {
+ data.forEach(row => {
+ const percentage = row.total_checks > 0
+ ? (row.successful_checks / row.total_checks) * 100
+ : 0;
+
+ if (key === '24h') uptimeData[row.monitor_id].percentage24h = percentage;
+ else if (key === '7d') uptimeData[row.monitor_id].percentage7d = percentage;
+ else if (key === '30d') uptimeData[row.monitor_id].percentage30d = percentage;
+ });
+ });
+ } catch (error) {
+ console.error("Error calculating uptime percentages:", error);
+ // Continue without uptime data rather than failing the entire request
+ }
+ }
+
+ const result = monitors.map((row) => ({
+ ...row.monitor,
+ status: row.status ? {
+ ...row.status,
+ uptimePercentage24h: uptimeData[row.monitor.id]?.percentage24h || null,
+ uptimePercentage7d: uptimeData[row.monitor.id]?.percentage7d || null,
+ uptimePercentage30d: uptimeData[row.monitor.id]?.percentage30d || null,
+ } : null,
+ }));
+
+ return reply.status(200).send(result);
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors
+ });
+ }
+ console.error("Error retrieving monitors:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/getRegions.ts b/server/src/api/uptime/getRegions.ts
new file mode 100644
index 000000000..d4a8b42b1
--- /dev/null
+++ b/server/src/api/uptime/getRegions.ts
@@ -0,0 +1,48 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+
+export async function getRegions(
+ request: FastifyRequest,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Get all enabled regions
+ const regions = await db
+ .select({
+ code: agentRegions.code,
+ name: agentRegions.name,
+ enabled: agentRegions.enabled,
+ isHealthy: agentRegions.isHealthy,
+ lastHealthCheck: agentRegions.lastHealthCheck,
+ })
+ .from(agentRegions)
+ .where(eq(agentRegions.enabled, true))
+ .orderBy(agentRegions.code);
+
+ // Format response
+ const formattedRegions = regions.map(region => ({
+ code: region.code,
+ name: region.name,
+ isHealthy: region.isHealthy ?? true,
+ lastHealthCheck: region.lastHealthCheck,
+ isLocal: region.code === 'local',
+ }));
+
+ return reply.send({
+ regions: formattedRegions,
+ });
+ } catch (error) {
+ console.error("Error fetching regions:", error);
+ return reply.status(500).send({ error: "Failed to fetch regions" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/api/uptime/incidents.ts b/server/src/api/uptime/incidents.ts
new file mode 100644
index 000000000..f3b7ca940
--- /dev/null
+++ b/server/src/api/uptime/incidents.ts
@@ -0,0 +1,281 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { getUserOrganizations } from "./utils.js";
+
+// Schemas
+const incidentStatusSchema = z.enum(["active", "acknowledged", "resolved", "all"]);
+
+const getIncidentsQuerySchema = z.object({
+ status: incidentStatusSchema.default("all"),
+ limit: z.coerce.number().int().min(1).max(100).default(50),
+ offset: z.coerce.number().int().min(0).default(0),
+});
+
+const incidentIdParamsSchema = z.object({
+ id: z.coerce.number().int(),
+});
+
+const incidentSchema = z.object({
+ id: z.number(),
+ organizationId: z.string(),
+ monitorId: z.number(),
+ monitorName: z.string(),
+ region: z.string().nullable(),
+ startTime: z.string(),
+ endTime: z.string().nullable(),
+ status: z.string(),
+ acknowledgedBy: z.string().nullable(),
+ acknowledgedAt: z.string().nullable(),
+ resolvedBy: z.string().nullable(),
+ resolvedAt: z.string().nullable(),
+ lastError: z.string().nullable(),
+ lastErrorType: z.string().nullable(),
+ failureCount: z.number(),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+});
+
+export const incidentsRoutes = async (server: FastifyInstance) => {
+ // Get incidents
+ server.route({
+ method: "GET",
+ url: "/api/uptime/incidents",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Get user's organizations
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ const query = getIncidentsQuerySchema.parse(request.query);
+ const { status, limit, offset } = query;
+
+ // Build where conditions
+ const conditions = [inArray(uptimeIncidents.organizationId, organizationIds)];
+
+ if (status !== "all") {
+ conditions.push(eq(uptimeIncidents.status, status));
+ }
+
+ // Use SQL to group incidents by monitor and aggregate regions
+ const groupedIncidents = await db
+ .select({
+ id: sql<number>`MIN(${uptimeIncidents.id})`,
+ organizationId: sql<string>`MIN(${uptimeIncidents.organizationId})`,
+ monitorId: uptimeIncidents.monitorId,
+ monitorName: sql<string>`
+ CASE
+ WHEN ${uptimeMonitors.name} IS NOT NULL AND ${uptimeMonitors.name} != '' THEN ${uptimeMonitors.name}
+ WHEN ${uptimeMonitors.monitorType} = 'http' THEN COALESCE(${uptimeMonitors.httpConfig}->>'url', 'HTTP Monitor')
+ WHEN ${uptimeMonitors.monitorType} = 'tcp' THEN CONCAT(${uptimeMonitors.tcpConfig}->>'host', ':', ${uptimeMonitors.tcpConfig}->>'port')
+ ELSE 'Unknown Monitor'
+ END
+ `,
+ affectedRegions: sql<string[]>`ARRAY_REMOVE(ARRAY_AGG(DISTINCT ${uptimeIncidents.region} ORDER BY ${uptimeIncidents.region}), NULL)`,
+ startTime: sql<string>`MIN(${uptimeIncidents.startTime})`,
+ endTime: sql<string>`MAX(${uptimeIncidents.endTime})`,
+ status: uptimeIncidents.status,
+ acknowledgedBy: sql<string>`MAX(${uptimeIncidents.acknowledgedBy})`,
+ acknowledgedAt: sql<string>`MAX(${uptimeIncidents.acknowledgedAt})`,
+ resolvedBy: sql<string>`MAX(${uptimeIncidents.resolvedBy})`,
+ resolvedAt: sql<string>`MAX(${uptimeIncidents.resolvedAt})`,
+ lastError: sql<string>`(ARRAY_AGG(${uptimeIncidents.lastError} ORDER BY ${uptimeIncidents.updatedAt} DESC))[1]`,
+ lastErrorType: sql<string>`(ARRAY_AGG(${uptimeIncidents.lastErrorType} ORDER BY ${uptimeIncidents.updatedAt} DESC))[1]`,
+ failureCount: sql<number>`SUM(${uptimeIncidents.failureCount})`,
+ createdAt: sql<string>`MIN(${uptimeIncidents.createdAt})`,
+ updatedAt: sql<string>`MAX(${uptimeIncidents.updatedAt})`,
+ })
+ .from(uptimeIncidents)
+ .leftJoin(uptimeMonitors, eq(uptimeIncidents.monitorId, uptimeMonitors.id))
+ .where(and(...conditions))
+ .groupBy(
+ uptimeIncidents.monitorId,
+ uptimeIncidents.status,
+ sql`CASE
+ WHEN ${uptimeIncidents.status} = 'resolved' THEN
+ DATE_TRUNC('hour', ${uptimeIncidents.endTime})
+ ELSE
+ NULL
+ END`,
+ uptimeMonitors.name,
+ uptimeMonitors.monitorType,
+ uptimeMonitors.httpConfig,
+ uptimeMonitors.tcpConfig
+ )
+ .orderBy(desc(sql`MIN(${uptimeIncidents.startTime})`))
+ .limit(limit)
+ .offset(offset);
+
+ // Get total count for pagination
+ const totalCountResult = await db
+ .select({
+ count: sql<number>`COUNT(DISTINCT
+ CONCAT(
+ ${uptimeIncidents.monitorId},
+ '-',
+ ${uptimeIncidents.status},
+ '-',
+ CASE
+ WHEN ${uptimeIncidents.status} = 'resolved' THEN
+ DATE_TRUNC('hour', ${uptimeIncidents.endTime})::text
+ ELSE
+ ''
+ END
+ )
+ )`,
+ })
+ .from(uptimeIncidents)
+ .where(and(...conditions));
+
+ const total = Number(totalCountResult[0]?.count || 0);
+
+ return reply.send({
+ incidents: groupedIncidents,
+ pagination: {
+ total,
+ limit,
+ offset,
+ },
+ });
+ },
+ });
+
+ // Acknowledge incident
+ server.route({
+ method: "PATCH",
+ url: "/api/uptime/incidents/:id/acknowledge",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const params = incidentIdParamsSchema.parse(request.params);
+ const { id } = params;
+
+ // Get user's organizations
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ // Verify incident belongs to user's organization
+ const incident = await db
+ .select()
+ .from(uptimeIncidents)
+ .where(and(eq(uptimeIncidents.id, id), inArray(uptimeIncidents.organizationId, organizationIds)))
+ .limit(1);
+
+ if (!incident[0]) {
+ return reply.code(404).send({ error: "Incident not found" });
+ }
+
+ if (incident[0].status === "resolved") {
+ return reply.code(400).send({ error: "Cannot acknowledge resolved incident" });
+ }
+
+ // Update incident
+ const now = new Date().toISOString();
+ const [updated] = await db
+ .update(uptimeIncidents)
+ .set({
+ status: "acknowledged",
+ acknowledgedBy: userId,
+ acknowledgedAt: now,
+ updatedAt: now,
+ })
+ .where(eq(uptimeIncidents.id, id))
+ .returning({
+ id: uptimeIncidents.id,
+ status: uptimeIncidents.status,
+ acknowledgedBy: uptimeIncidents.acknowledgedBy,
+ acknowledgedAt: uptimeIncidents.acknowledgedAt,
+ });
+
+ return reply.send({
+ success: true,
+ incident: updated,
+ });
+ },
+ });
+
+ // Resolve incident
+ server.route({
+ method: "PATCH",
+ url: "/api/uptime/incidents/:id/resolve",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const params = incidentIdParamsSchema.parse(request.params);
+ const { id } = params;
+
+ // Get user's organizations
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ // Verify incident belongs to user's organization
+ const incident = await db
+ .select()
+ .from(uptimeIncidents)
+ .where(and(eq(uptimeIncidents.id, id), inArray(uptimeIncidents.organizationId, organizationIds)))
+ .limit(1);
+
+ if (!incident[0]) {
+ return reply.code(404).send({ error: "Incident not found" });
+ }
+
+ if (incident[0].status === "resolved") {
+ return reply.code(400).send({ error: "Incident already resolved" });
+ }
+
+ // Update incident
+ const now = new Date().toISOString();
+ const [updated] = await db
+ .update(uptimeIncidents)
+ .set({
+ status: "resolved",
+ resolvedBy: userId,
+ resolvedAt: now,
+ endTime: now,
+ updatedAt: now,
+ })
+ .where(eq(uptimeIncidents.id, id))
+ .returning({
+ id: uptimeIncidents.id,
+ status: uptimeIncidents.status,
+ resolvedBy: uptimeIncidents.resolvedBy,
+ resolvedAt: uptimeIncidents.resolvedAt,
+ endTime: uptimeIncidents.endTime,
+ });
+
+ return reply.send({
+ success: true,
+ incident: updated,
+ });
+ },
+ });
+};
+
diff --git a/server/src/api/uptime/notifications.ts b/server/src/api/uptime/notifications.ts
new file mode 100644
index 000000000..bff870465
--- /dev/null
+++ b/server/src/api/uptime/notifications.ts
@@ -0,0 +1,289 @@
+import { and, eq, inArray } from "drizzle-orm";
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { NotificationService } from "../../services/uptime/notificationService.js";
+import { getUserOrganizations } from "./utils.js";
+
+// Schemas
+const channelTypeSchema = z.enum(["email", "discord", "slack", "sms"]);
+
+const channelConfigSchema = z.object({
+ email: z.string().email().optional(),
+ webhookUrl: z.string().url().optional(),
+ slackWebhookUrl: z.string().url().optional(),
+ slackChannel: z.string().optional(),
+ phoneNumber: z.string().optional(),
+ provider: z.string().optional(),
+});
+
+const createChannelSchema = z.object({
+ type: channelTypeSchema,
+ name: z.string().min(1).max(100),
+ config: channelConfigSchema,
+ monitorIds: z.array(z.number()).nullable().optional(),
+ triggerEvents: z.array(z.string()).default(["down", "recovery"]).optional(),
+ cooldownMinutes: z.number().int().min(0).max(1440).default(5).optional(),
+});
+
+const updateChannelSchema = z.object({
+ name: z.string().min(1).max(100).optional(),
+ enabled: z.boolean().optional(),
+ config: channelConfigSchema.optional(),
+ monitorIds: z.array(z.number()).nullable().optional(),
+ triggerEvents: z.array(z.string()).optional(),
+ cooldownMinutes: z.number().int().min(0).max(1440).optional(),
+});
+
+const channelIdParamsSchema = z.object({
+ id: z.coerce.number().int(),
+});
+
+export const notificationRoutes = async (server: FastifyInstance) => {
+ // Get all notification channels
+ server.route({
+ method: "GET",
+ url: "/api/uptime/notification-channels",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ const channels = await db
+ .select()
+ .from(notificationChannels)
+ .where(inArray(notificationChannels.organizationId, organizationIds));
+
+ return reply.send({ channels });
+ },
+ });
+
+ // Create notification channel
+ server.route({
+ method: "POST",
+ url: "/api/uptime/notification-channels",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ // For creation, use the first organization (assuming user can only create in their primary org)
+ const organizationId = organizationIds[0];
+
+ const body = createChannelSchema.parse(request.body);
+ const { type, name, config, monitorIds, triggerEvents, cooldownMinutes } = body;
+
+ // Validate config based on type
+ if (type === "email" && !config.email) {
+ return reply.code(400).send({ error: "Email address is required for email channel" });
+ }
+ if (type === "discord" && !config.webhookUrl) {
+ return reply.code(400).send({ error: "Webhook URL is required for Discord channel" });
+ }
+ if (type === "slack" && !config.slackWebhookUrl) {
+ return reply.code(400).send({ error: "Webhook URL is required for Slack channel" });
+ }
+ if (type === "sms" && !config.phoneNumber) {
+ return reply.code(400).send({ error: "Phone number is required for SMS channel" });
+ }
+
+ const [channel] = await db
+ .insert(notificationChannels)
+ .values({
+ organizationId,
+ type,
+ name,
+ config,
+ monitorIds: monitorIds || null,
+ triggerEvents: triggerEvents || ["down", "recovery"],
+ cooldownMinutes: cooldownMinutes || 5,
+ createdBy: userId,
+ })
+ .returning();
+
+ return reply.send(channel);
+ },
+ });
+
+ // Update notification channel
+ server.route({
+ method: "PUT",
+ url: "/api/uptime/notification-channels/:id",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ const params = channelIdParamsSchema.parse(request.params);
+ const { id } = params;
+ const updates = updateChannelSchema.parse(request.body);
+
+ // Verify channel belongs to user's organization
+ const [channel] = await db
+ .select()
+ .from(notificationChannels)
+ .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
+ .limit(1);
+
+ if (!channel) {
+ return reply.code(404).send({ error: "Channel not found" });
+ }
+
+ const [updated] = await db
+ .update(notificationChannels)
+ .set({
+ ...updates,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(eq(notificationChannels.id, id))
+ .returning();
+
+ return reply.send(updated);
+ },
+ });
+
+ // Delete notification channel
+ server.route({
+ method: "DELETE",
+ url: "/api/uptime/notification-channels/:id",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ const params = channelIdParamsSchema.parse(request.params);
+ const { id } = params;
+
+ // Verify channel belongs to user's organization
+ const [channel] = await db
+ .select()
+ .from(notificationChannels)
+ .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
+ .limit(1);
+
+ if (!channel) {
+ return reply.code(404).send({ error: "Channel not found" });
+ }
+
+ // Delete the channel
+ await db.delete(notificationChannels).where(eq(notificationChannels.id, id));
+
+ return reply.send({ success: true });
+ },
+ });
+
+ // Test notification channel
+ server.route({
+ method: "POST",
+ url: "/api/uptime/notification-channels/:id/test",
+ handler: async (request: FastifyRequest, reply: FastifyReply) => {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const organizationIds = await getUserOrganizations(userId);
+
+ if (organizationIds.length === 0) {
+ return reply.status(403).send({ error: "No organization access" });
+ }
+
+ const params = channelIdParamsSchema.parse(request.params);
+ const { id } = params;
+
+ // Verify channel belongs to user's organization
+ const [channel] = await db
+ .select()
+ .from(notificationChannels)
+ .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
+ .limit(1);
+
+ if (!channel) {
+ return reply.code(404).send({ error: "Channel not found" });
+ }
+
+ // Create a test monitor and incident for the notification
+ const testMonitor = {
+ id: 0,
+ organizationId: channel.organizationId,
+ name: "Test Monitor",
+ monitorType: "http",
+ httpConfig: {
+ url: "https://example.com",
+ },
+ tcpConfig: null,
+ };
+
+ const testIncident = {
+ id: 0,
+ region: "test",
+ startTime: DateTime.now().toSQL()!,
+ endTime: null,
+ lastError: "This is a test notification",
+ lastErrorType: "test",
+ status: "active",
+ };
+
+ // Send test notification
+ const notificationService = new NotificationService();
+
+ try {
+ // Send the test notification to only this specific channel
+ await notificationService.sendTestNotification(channel, testMonitor, testIncident, "down");
+
+ return reply.send({
+ success: true,
+ message: `Test notification sent to ${channel.type} channel: ${channel.name}`,
+ });
+ } catch (error) {
+ console.error("Failed to send test notification:", error);
+ return reply.code(500).send({
+ success: false,
+ message: "Failed to send test notification",
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ },
+ });
+};
diff --git a/server/src/api/uptime/schemas.ts b/server/src/api/uptime/schemas.ts
new file mode 100644
index 000000000..d080827c5
--- /dev/null
+++ b/server/src/api/uptime/schemas.ts
@@ -0,0 +1,166 @@
+import { z } from "zod";
+
+// HTTP method enum
+const httpMethodSchema = z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]);
+
+// Auth type enum
+const authTypeSchema = z.enum(["none", "basic", "bearer", "api_key", "custom_header"]);
+
+// IP version enum
+const ipVersionSchema = z.enum(["any", "ipv4", "ipv6"]);
+
+// Auth credentials schema
+const authCredentialsSchema = z.object({
+ username: z.string().optional(),
+ password: z.string().optional(),
+ token: z.string().optional(),
+ headerName: z.string().optional(),
+ headerValue: z.string().optional(),
+});
+
+// Auth schema
+const authSchema = z.object({
+ type: authTypeSchema,
+ credentials: authCredentialsSchema.optional(),
+});
+
+// HTTP config schema
+const httpConfigSchema = z.object({
+ url: z.string().url("Invalid URL format"),
+ method: httpMethodSchema.default("GET"),
+ headers: z.record(z.string()).optional(),
+ body: z.string().optional(),
+ auth: authSchema.optional(),
+ followRedirects: z.boolean().default(true),
+ timeoutMs: z.number().int().positive().max(300000).optional(), // Max 5 minutes
+ ipVersion: ipVersionSchema.optional(),
+ userAgent: z.string().max(256).optional(),
+});
+
+// TCP config schema
+const tcpConfigSchema = z.object({
+ host: z.string().min(1, "Host is required"),
+ port: z.number().int().min(1).max(65535, "Port must be between 1 and 65535"),
+ timeoutMs: z.number().int().positive().max(300000).optional(), // Max 5 minutes
+});
+
+// Validation rule schemas
+const statusCodeRuleSchema = z.object({
+ type: z.literal("status_code"),
+ operator: z.enum(["equals", "not_equals", "in", "not_in"]),
+ value: z.union([z.number(), z.array(z.number())]),
+});
+
+const responseTimeRuleSchema = z.object({
+ type: z.literal("response_time"),
+ operator: z.enum(["less_than", "greater_than"]),
+ value: z.number().positive(),
+});
+
+const bodyContainsRuleSchema = z.object({
+ type: z.enum(["response_body_contains", "response_body_not_contains"]),
+ value: z.string(),
+ caseSensitive: z.boolean().optional(),
+});
+
+const headerExistsRuleSchema = z.object({
+ type: z.literal("header_exists"),
+ header: z.string(),
+});
+
+const headerValueRuleSchema = z.object({
+ type: z.literal("header_value"),
+ header: z.string(),
+ operator: z.enum(["equals", "contains"]),
+ value: z.string(),
+});
+
+const responseSizeRuleSchema = z.object({
+ type: z.literal("response_size"),
+ operator: z.enum(["less_than", "greater_than"]),
+ value: z.number().positive(),
+});
+
+const validationRuleSchema = z.discriminatedUnion("type", [
+ statusCodeRuleSchema,
+ responseTimeRuleSchema,
+ bodyContainsRuleSchema,
+ headerExistsRuleSchema,
+ headerValueRuleSchema,
+ responseSizeRuleSchema,
+]);
+
+// Create monitor schema
+export const createMonitorSchema = z
+ .object({
+ organizationId: z.string().min(1, "Organization ID is required"),
+ name: z.string().max(256).optional(), // Made optional
+ monitorType: z.enum(["http", "tcp"]),
+ intervalSeconds: z.number().int().min(30).max(86400, "Interval must be between 60 and 86400 seconds"),
+ enabled: z.boolean().default(true),
+ httpConfig: httpConfigSchema.optional(),
+ tcpConfig: tcpConfigSchema.optional(),
+ validationRules: z.array(validationRuleSchema).default([]),
+ monitoringType: z.enum(["local", "global"]).default("local"),
+ selectedRegions: z.array(z.string()).default([]),
+ })
+ .refine(
+ (data) => {
+ if (data.monitorType === "http") {
+ return data.httpConfig !== undefined;
+ }
+ if (data.monitorType === "tcp") {
+ return data.tcpConfig !== undefined;
+ }
+ return false;
+ },
+ {
+ message: "Monitor type specific configuration is required",
+ },
+ );
+
+// Update monitor schema (similar to create but with optional fields)
+export const updateMonitorSchema = z.object({
+ name: z.string().max(256).optional(), // Allow empty string to remove name
+ intervalSeconds: z.number().int().min(30).max(86400).optional(),
+ enabled: z.boolean().optional(),
+ httpConfig: httpConfigSchema.optional(),
+ tcpConfig: tcpConfigSchema.optional(),
+ validationRules: z.array(validationRuleSchema).optional(),
+ monitoringType: z.enum(["local", "global"]).optional(),
+ selectedRegions: z.array(z.string()).optional(),
+});
+
+// Query params schemas
+export const getMonitorsQuerySchema = z.object({
+ organizationId: z.string().optional(),
+ enabled: z
+ .enum(["true", "false"])
+ .transform((val) => val === "true")
+ .optional(),
+ monitorType: z.enum(["http", "tcp"]).optional(),
+ limit: z.string().transform(Number).pipe(z.number().int().positive().max(100)).default("50"),
+ offset: z.string().transform(Number).pipe(z.number().int().nonnegative()).default("0"),
+});
+
+export const getMonitorEventsQuerySchema = z.object({
+ status: z.enum(["success", "failure", "timeout"]).optional(),
+ region: z.string().optional(),
+ limit: z.string().transform(Number).pipe(z.number().int().positive().max(100)).default("20"),
+ offset: z.string().transform(Number).pipe(z.number().int().nonnegative()).default("0"),
+});
+
+export const getMonitorStatsQuerySchema = z.object({
+ hours: z.string().transform(Number).pipe(z.number().int().positive().max(8760)).optional(), // Max 1 year in hours
+ region: z.string().optional(),
+ bucket: z
+ .enum(["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour", "day", "week", "month", "year"])
+ .optional(),
+});
+
+// Type exports
+export type CreateMonitorInput = z.infer<typeof createMonitorSchema>;
+export type UpdateMonitorInput = z.infer<typeof updateMonitorSchema>;
+export type GetMonitorsQuery = z.infer<typeof getMonitorsQuerySchema>;
+export type GetMonitorEventsQuery = z.infer<typeof getMonitorEventsQuerySchema>;
+export type GetMonitorStatsQuery = z.infer<typeof getMonitorStatsQuerySchema>;
diff --git a/server/src/api/uptime/updateMonitor.ts b/server/src/api/uptime/updateMonitor.ts
new file mode 100644
index 000000000..8b6495b13
--- /dev/null
+++ b/server/src/api/uptime/updateMonitor.ts
@@ -0,0 +1,93 @@
+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 { getSessionFromReq } from "../../lib/auth-utils.js";
+import { uptimeService } from "../../services/uptime/uptimeService.js";
+import { updateMonitorSchema, type UpdateMonitorInput } from "./schemas.js";
+
+interface UpdateMonitorRequest {
+ Params: {
+ monitorId: string;
+ };
+ Body: UpdateMonitorInput;
+}
+
+export async function updateMonitor(request: FastifyRequest<UpdateMonitorRequest>, reply: FastifyReply) {
+ const session = await getSessionFromReq(request);
+ const userId = session?.user?.id;
+ const { monitorId } = request.params;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // First get the monitor to check if it exists and user has access
+ const existingMonitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, Number(monitorId)),
+ });
+
+ if (!existingMonitor) {
+ return reply.status(404).send({ error: "Monitor not found" });
+ }
+
+ // Check if user has access to the monitor's organization
+ const userHasAccess = await db.query.member.findFirst({
+ where: and(eq(member.userId, userId), eq(member.organizationId, existingMonitor.organizationId)),
+ });
+
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Access denied" });
+ }
+
+ // Validate request body with Zod
+ const updateData = updateMonitorSchema.parse(request.body);
+
+ // Additional validation for monitor type specific config if changing config
+ if (existingMonitor.monitorType === "http" && updateData.httpConfig) {
+ if (!updateData.httpConfig.url) {
+ return reply.status(400).send({ error: "HTTP monitor requires URL" });
+ }
+ }
+ if (existingMonitor.monitorType === "tcp" && updateData.tcpConfig) {
+ if (!updateData.tcpConfig.host || !updateData.tcpConfig.port) {
+ return reply.status(400).send({ error: "TCP monitor requires host and port" });
+ }
+ }
+
+ // Update the monitor
+ const [updatedMonitor] = await db
+ .update(uptimeMonitors)
+ .set({
+ ...updateData,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(eq(uptimeMonitors.id, Number(monitorId)))
+ .returning();
+
+ // Update the monitor schedule if interval or enabled status changed
+ const intervalChanged =
+ updateData.intervalSeconds !== undefined && updateData.intervalSeconds !== existingMonitor.intervalSeconds;
+ const enabledChanged = updateData.enabled !== undefined && updateData.enabled !== existingMonitor.enabled;
+
+ if (intervalChanged || enabledChanged) {
+ const enabled = updateData.enabled !== undefined ? updateData.enabled : existingMonitor.enabled!;
+ const intervalSeconds = updateData.intervalSeconds || existingMonitor.intervalSeconds;
+
+ await uptimeService.onMonitorUpdated(Number(monitorId), intervalSeconds, enabled);
+ }
+
+ return reply.status(200).send(updatedMonitor);
+ } catch (error) {
+ if (error instanceof Error && error.name === "ZodError") {
+ const zodError = error as any;
+ return reply.status(400).send({
+ error: "Validation error",
+ details: zodError.errors,
+ });
+ }
+ console.error("Error updating monitor:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/uptime/utils.ts b/server/src/api/uptime/utils.ts
new file mode 100644
index 000000000..6588efe61
--- /dev/null
+++ b/server/src/api/uptime/utils.ts
@@ -0,0 +1,12 @@
+import { eq } from "drizzle-orm";
+import { db } from "../../db/postgres/postgres.js";
+import { member } from "../../db/postgres/schema.js";
+
+export async function getUserOrganizations(userId: string) {
+ const userOrgs = await db
+ .select({ organizationId: member.organizationId })
+ .from(member)
+ .where(eq(member.userId, userId));
+
+ return userOrgs.map((org) => org.organizationId);
+}
diff --git a/server/src/db/clickhouse/clickhouse.ts b/server/src/db/clickhouse/clickhouse.ts
index 89b1cf37a..41390a3c1 100644
--- a/server/src/db/clickhouse/clickhouse.ts
+++ b/server/src/db/clickhouse/clickhouse.ts
@@ -129,6 +129,53 @@ export const initializeClickhouse = async () => {
`,
});
+ // Create uptime monitor events table
+ await clickhouse.exec({
+ query: `
+ CREATE TABLE IF NOT EXISTS monitor_events (
+ monitor_id UInt32,
+ organization_id String,
+ timestamp DateTime,
+
+ -- Monitor metadata
+ monitor_type LowCardinality(String), -- 'http', 'tcp'
+ monitor_url String,
+ monitor_name String,
+ region LowCardinality(String) DEFAULT 'local',
+
+ -- Response data
+ status LowCardinality(String), -- 'success', 'failure', 'timeout'
+ status_code Nullable(UInt16), -- HTTP status code
+ response_time_ms UInt32,
+
+ -- HTTP timing breakdown (all in milliseconds)
+ dns_time_ms Nullable(UInt32),
+ tcp_time_ms Nullable(UInt32),
+ tls_time_ms Nullable(UInt32),
+ ttfb_ms Nullable(UInt32), -- Time to first byte
+ transfer_time_ms Nullable(UInt32),
+
+ -- Validation results
+ validation_errors Array(String), -- Array of failed validation rules
+
+ -- Response metadata (for HTTP)
+ response_headers Map(String, String),
+ response_size_bytes Nullable(UInt32),
+
+ -- TCP specific
+ port Nullable(UInt16),
+
+ -- Error information
+ error_message Nullable(String),
+ error_type Nullable(String) -- 'dns_failure', 'connection_timeout', 'ssl_error', etc.
+ )
+ ENGINE = MergeTree()
+ PARTITION BY toYYYYMM(timestamp)
+ ORDER BY (organization_id, monitor_id, timestamp)
+ SETTINGS ttl_only_drop_parts = 1
+ `,
+ });
+
if (IS_CLOUD) {
await clickhouse.exec({
query: `
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 8aeae61be..c5939d09d 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -9,7 +9,10 @@ import {
foreignKey,
unique,
real,
+ check,
+ index,
} from "drizzle-orm/pg-core";
+import { sql } from "drizzle-orm";
// User table
export const user = pgTable(
@@ -260,3 +263,321 @@ 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/index.ts b/server/src/index.ts
index a2da04148..f0d62139e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -62,6 +62,19 @@ import { handleWebhook } from "./api/stripe/webhook.js";
import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
import { getUserOrganizations } from "./api/user/getUserOrganizations.js";
import { listOrganizationMembers } from "./api/user/listOrganizationMembers.js";
+import { getMonitors } from "./api/uptime/getMonitors.js";
+import { getMonitor } from "./api/uptime/getMonitor.js";
+import { createMonitor } from "./api/uptime/createMonitor.js";
+import { updateMonitor } from "./api/uptime/updateMonitor.js";
+import { deleteMonitor } from "./api/uptime/deleteMonitor.js";
+import { getMonitorEvents } from "./api/uptime/getMonitorEvents.js";
+import { getMonitorStats } from "./api/uptime/getMonitorStats.js";
+import { getMonitorUptimeBuckets } from "./api/uptime/getMonitorUptimeBuckets.js";
+import { getMonitorStatus } from "./api/uptime/getMonitorStatus.js";
+import { getMonitorUptime } from "./api/uptime/getMonitorUptime.js";
+import { getRegions } from "./api/uptime/getRegions.js";
+import { incidentsRoutes } from "./api/uptime/incidents.js";
+import { notificationRoutes } from "./api/uptime/notifications.js";
import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
import { initPostgres } from "./db/postgres/initPostgres.js";
import { loadAllowedDomains } from "./lib/allowedDomains.js";
@@ -72,6 +85,7 @@ import { siteConfig } from "./lib/siteConfig.js";
import { trackEvent } from "./services/tracker/trackEvent.js";
// need to import telemetry service here to start it
import { telemetryService } from "./services/telemetryService.js";
+import { uptimeService } from "./services/uptime/uptimeService.js";
import { extractSiteId, isSitePublic } from "./utils.js";
const __filename = fileURLToPath(import.meta.url);
@@ -230,7 +244,7 @@ server.get("/api/script.js", async (_, reply) => reply.sendFile("script.js"));
server.get("/api/replay.js", async (_, reply) => reply.sendFile("rrweb.min.js"));
server.get("/api/metrics.js", async (_, reply) => reply.sendFile("web-vitals.iife.js"));
-// Analytics
+// WEB & PRODUCT ANALYTICS
// This endpoint gets called a lot so we don't want to log it
server.get("/api/live-user-count/:site", { logLevel: "silent" }, getLiveUsercount);
@@ -291,6 +305,27 @@ server.get("/api/list-organization-members/:organizationId", listOrganizationMem
server.get("/api/user/organizations", getUserOrganizations);
server.post("/api/add-user-to-organization", addUserToOrganization);
+// UPTIME MONITORING
+server.get("/api/uptime/monitors", getMonitors);
+server.get("/api/uptime/monitors/:monitorId", getMonitor);
+server.post("/api/uptime/monitors", createMonitor);
+server.put("/api/uptime/monitors/:monitorId", updateMonitor);
+server.delete("/api/uptime/monitors/:monitorId", deleteMonitor);
+server.get("/api/uptime/monitors/:monitorId/events", getMonitorEvents);
+server.get("/api/uptime/monitors/:monitorId/stats", getMonitorStats);
+server.get("/api/uptime/monitors/:monitorId/status", getMonitorStatus);
+server.get("/api/uptime/monitors/:monitorId/uptime", getMonitorUptime);
+server.get("/api/uptime/monitors/:monitorId/buckets", getMonitorUptimeBuckets);
+server.get("/api/uptime/regions", getRegions);
+
+// Register incidents routes
+server.register(incidentsRoutes);
+
+// Register notification routes
+server.register(notificationRoutes);
+
+// STRIPE & ADMIN
+
if (IS_CLOUD) {
// Stripe Routes
server.post("/api/stripe/create-checkout-session", createCheckoutSession);
@@ -316,8 +351,20 @@ const start = async () => {
telemetryService.startTelemetryCron();
- // Start the server
+ // Start the server first
await server.listen({ port: 3001, host: "0.0.0.0" });
+ console.info("Server is listening on http://0.0.0.0:3001");
+
+ // Initialize uptime monitoring service in the background (non-blocking)
+ uptimeService
+ .initialize()
+ .then(() => {
+ console.info("Uptime monitoring service initialized successfully");
+ })
+ .catch((error) => {
+ console.error("Failed to initialize uptime service:", error);
+ // Continue running without uptime monitoring
+ });
} catch (err) {
server.log.error(err);
process.exit(1);
@@ -326,6 +373,47 @@ const start = async () => {
start();
+// Graceful shutdown
+let isShuttingDown = false;
+
+const shutdown = async (signal: string) => {
+ if (isShuttingDown) {
+ console.log(`${signal} received during shutdown, forcing exit...`);
+ process.exit(1);
+ }
+
+ isShuttingDown = true;
+ console.log(`${signal} received, shutting down gracefully...`);
+
+ // Set a timeout to force exit if shutdown takes too long
+ const forceExitTimeout = setTimeout(() => {
+ console.error("Shutdown timeout exceeded, forcing exit...");
+ process.exit(1);
+ }, 10000); // 10 second timeout
+
+ try {
+ // Stop accepting new connections
+ await server.close();
+ console.log("Server closed");
+
+ // Shutdown uptime service
+ await uptimeService.shutdown();
+ console.log("Uptime service shut down");
+
+ // Clear the timeout since we're done
+ clearTimeout(forceExitTimeout);
+
+ process.exit(0);
+ } catch (error) {
+ console.error("Error during shutdown:", error);
+ clearTimeout(forceExitTimeout);
+ process.exit(1);
+ }
+};
+
+process.on("SIGTERM", () => shutdown("SIGTERM"));
+process.on("SIGINT", () => shutdown("SIGINT"));
+
declare module "fastify" {
interface FastifyRequest {
user?: any; // Or define a more specific user type
diff --git a/server/src/lib/twilio.ts b/server/src/lib/twilio.ts
new file mode 100644
index 000000000..4dc078551
--- /dev/null
+++ b/server/src/lib/twilio.ts
@@ -0,0 +1,50 @@
+import twilio from "twilio";
+import { IS_CLOUD } from "./const.js";
+
+let twilioClient: ReturnType<typeof twilio> | undefined;
+
+// Initialize Twilio client only if we have the necessary credentials
+if (IS_CLOUD && process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
+ twilioClient = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
+}
+
+export const sendSMS = async (
+ phoneNumber: string,
+ message: string
+): Promise<{ success: boolean; error?: string }> => {
+ if (!twilioClient) {
+ console.log("[SMS] Twilio client not initialized - skipping SMS notification");
+ return { success: false, error: "SMS not configured" };
+ }
+
+ if (!process.env.TWILIO_PHONE_NUMBER) {
+ console.error("[SMS] TWILIO_PHONE_NUMBER not configured");
+ return { success: false, error: "SMS sender not configured" };
+ }
+
+ try {
+ const result = await twilioClient.messages.create({
+ body: message,
+ from: process.env.TWILIO_PHONE_NUMBER,
+ to: phoneNumber,
+ });
+
+ console.log(`[SMS] Successfully sent SMS to ${phoneNumber}, SID: ${result.sid}`);
+ return { success: true };
+ } catch (error) {
+ console.error("[SMS] Failed to send SMS:", error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Failed to send SMS"
+ };
+ }
+};
+
+export const isSMSConfigured = (): boolean => {
+ return !!(
+ twilioClient &&
+ process.env.TWILIO_PHONE_NUMBER &&
+ process.env.TWILIO_ACCOUNT_SID &&
+ process.env.TWILIO_AUTH_TOKEN
+ );
+};
\ No newline at end of file
diff --git a/server/src/services/uptime/checks/httpCheck.ts b/server/src/services/uptime/checks/httpCheck.ts
new file mode 100644
index 000000000..b84b26dd6
--- /dev/null
+++ b/server/src/services/uptime/checks/httpCheck.ts
@@ -0,0 +1,174 @@
+import { request } from "undici";
+import { performance } from "perf_hooks";
+import dns from "dns/promises";
+import { HttpCheckResult } from "../types.js";
+
+interface HttpCheckOptions {
+ 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;
+}
+
+export async function performHttpCheck(options: HttpCheckOptions): Promise<HttpCheckResult> {
+ const startTime = performance.now();
+ const timing = {
+ dnsMs: 0,
+ tcpMs: 0,
+ tlsMs: 0,
+ ttfbMs: 0,
+ transferMs: 0,
+ };
+
+ try {
+ // Parse URL
+ const url = new URL(options.url);
+
+ // DNS lookup timing
+ const dnsStart = performance.now();
+ try {
+ const dnsOptions: any = {};
+ if (options.ipVersion === "ipv4") dnsOptions.family = 4;
+ if (options.ipVersion === "ipv6") dnsOptions.family = 6;
+
+ await dns.lookup(url.hostname, dnsOptions);
+ timing.dnsMs = Math.round(performance.now() - dnsStart);
+ } catch (error) {
+ throw {
+ message: `DNS lookup failed: ${error instanceof Error ? error.message : "Unknown error"}`,
+ type: "dns_failure",
+ };
+ }
+
+ // Prepare headers
+ const headers: Record<string, string> = {
+ "User-Agent": options.userAgent || "Rybbit-Uptime-Monitor/1.0",
+ ...options.headers,
+ };
+
+ // Add authentication
+ if (options.auth && options.auth.type !== "none") {
+ switch (options.auth.type) {
+ case "basic":
+ if (options.auth.credentials?.username && options.auth.credentials?.password) {
+ const encoded = Buffer.from(
+ `${options.auth.credentials.username}:${options.auth.credentials.password}`,
+ ).toString("base64");
+ headers["Authorization"] = `Basic ${encoded}`;
+ }
+ break;
+ case "bearer":
+ if (options.auth.credentials?.token) {
+ headers["Authorization"] = `Bearer ${options.auth.credentials.token}`;
+ }
+ break;
+ case "api_key":
+ case "custom_header":
+ if (options.auth.credentials?.headerName && options.auth.credentials?.headerValue) {
+ headers[options.auth.credentials.headerName] = options.auth.credentials.headerValue;
+ }
+ break;
+ }
+ }
+
+ // Perform request
+ const requestStart = performance.now();
+ const response = await request(options.url, {
+ method: options.method,
+ headers,
+ body: options.body,
+ bodyTimeout: options.timeoutMs || 30000,
+ headersTimeout: options.timeoutMs || 30000,
+ maxRedirections: options.followRedirects !== false ? 5 : 0,
+ });
+
+ // Calculate timings
+ timing.ttfbMs = Math.round(performance.now() - requestStart);
+
+ // Get response body and size
+ const transferStart = performance.now();
+ const bodyBuffer = await response.body.arrayBuffer();
+ const bodySizeBytes = bodyBuffer.byteLength;
+
+ timing.transferMs = Math.round(performance.now() - transferStart);
+
+ // Estimate TCP and TLS times (these are approximations)
+ timing.tcpMs = Math.round((timing.ttfbMs - timing.dnsMs) * 0.3);
+ if (url.protocol === "https:") {
+ timing.tlsMs = Math.round((timing.ttfbMs - timing.dnsMs - timing.tcpMs) * 0.5);
+ }
+
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ // Convert headers to simple object
+ const responseHeaders: Record<string, string> = {};
+ for (const [key, value] of Object.entries(response.headers)) {
+ responseHeaders[key] = Array.isArray(value) ? value.join(", ") : String(value);
+ }
+
+ return {
+ status: "success",
+ statusCode: response.statusCode,
+ responseTimeMs,
+ timing,
+ headers: responseHeaders,
+ bodySizeBytes,
+ validationErrors: [],
+ };
+ } catch (error: any) {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ // Handle different error types
+ let errorType = "unknown_error";
+ let errorMessage = error.message || "Unknown error occurred";
+
+ if (error.code === "UND_ERR_CONNECT_TIMEOUT") {
+ errorType = "connection_timeout";
+ errorMessage = "Connection timed out";
+ } else if (error.code === "UND_ERR_HEADERS_TIMEOUT") {
+ errorType = "headers_timeout";
+ errorMessage = "Headers timeout";
+ } else if (error.code === "UND_ERR_BODY_TIMEOUT") {
+ errorType = "body_timeout";
+ errorMessage = "Body timeout";
+ } else if (error.code === "ENOTFOUND") {
+ errorType = "dns_failure";
+ errorMessage = "DNS lookup failed";
+ } else if (error.code === "ECONNREFUSED") {
+ errorType = "connection_refused";
+ errorMessage = "Connection refused";
+ } else if (error.message?.includes("SSL") || error.message?.includes("TLS")) {
+ errorType = "ssl_error";
+ } else if (error.type) {
+ errorType = error.type;
+ errorMessage = error.message;
+ }
+
+ return {
+ status: errorType.includes("timeout") ? "timeout" : "failure",
+ responseTimeMs,
+ timing,
+ headers: {},
+ bodySizeBytes: 0,
+ validationErrors: [],
+ error: {
+ message: errorMessage,
+ type: errorType,
+ },
+ };
+ }
+}
diff --git a/server/src/services/uptime/checks/tcpCheck.ts b/server/src/services/uptime/checks/tcpCheck.ts
new file mode 100644
index 000000000..b84eedd47
--- /dev/null
+++ b/server/src/services/uptime/checks/tcpCheck.ts
@@ -0,0 +1,99 @@
+import net from 'net';
+import { performance } from 'perf_hooks';
+import { TcpCheckResult } from '../types.js';
+
+interface TcpCheckOptions {
+ host: string;
+ port: number;
+ timeoutMs?: number;
+}
+
+export async function performTcpCheck(options: TcpCheckOptions): Promise<TcpCheckResult> {
+ const startTime = performance.now();
+
+ return new Promise<TcpCheckResult>((resolve) => {
+ const socket = new net.Socket();
+ const timeout = options.timeoutMs || 30000;
+
+ // Set timeout
+ socket.setTimeout(timeout);
+
+ // Handle successful connection
+ socket.on('connect', () => {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+ socket.destroy();
+
+ resolve({
+ status: 'success',
+ responseTimeMs,
+ validationErrors: [],
+ });
+ });
+
+ // Handle errors
+ socket.on('error', (error: any) => {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+ socket.destroy();
+
+ let errorType = 'connection_error';
+ let errorMessage = error.message || 'Connection failed';
+
+ if (error.code === 'ECONNREFUSED') {
+ errorType = 'connection_refused';
+ errorMessage = `Connection refused to ${options.host}:${options.port}`;
+ } else if (error.code === 'ENOTFOUND') {
+ errorType = 'dns_failure';
+ errorMessage = `Host ${options.host} not found`;
+ } else if (error.code === 'ETIMEDOUT') {
+ errorType = 'connection_timeout';
+ errorMessage = 'Connection timed out';
+ } else if (error.code === 'EHOSTUNREACH') {
+ errorType = 'host_unreachable';
+ errorMessage = `Host ${options.host} is unreachable`;
+ }
+
+ resolve({
+ status: errorType === 'connection_timeout' ? 'timeout' : 'failure',
+ responseTimeMs,
+ validationErrors: [],
+ error: {
+ message: errorMessage,
+ type: errorType,
+ },
+ });
+ });
+
+ // Handle timeout
+ socket.on('timeout', () => {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+ socket.destroy();
+
+ resolve({
+ status: 'timeout',
+ responseTimeMs,
+ validationErrors: [],
+ error: {
+ message: `Connection timeout after ${timeout}ms`,
+ type: 'connection_timeout',
+ },
+ });
+ });
+
+ // Attempt connection
+ try {
+ socket.connect(options.port, options.host);
+ } catch (error: any) {
+ const responseTimeMs = Math.round(performance.now() - startTime);
+
+ resolve({
+ status: 'failure',
+ responseTimeMs,
+ validationErrors: [],
+ error: {
+ message: error.message || 'Failed to initiate connection',
+ type: 'connection_error',
+ },
+ });
+ }
+ });
+}
\ No newline at end of file
diff --git a/server/src/services/uptime/monitorExecutor.ts b/server/src/services/uptime/monitorExecutor.ts
new file mode 100644
index 000000000..e1dd9abeb
--- /dev/null
+++ b/server/src/services/uptime/monitorExecutor.ts
@@ -0,0 +1,697 @@
+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 { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { MonitorCheckJob, HttpCheckResult, TcpCheckResult, MonitorEvent } from "./types.js";
+import { performHttpCheck } from "./checks/httpCheck.js";
+import { performTcpCheck } from "./checks/tcpCheck.js";
+import { applyValidationRules } from "./validationEngine.js";
+import { NotificationService } from "./notificationService.js";
+
+interface AgentExecuteRequest {
+ jobId: string;
+ monitorId: number;
+ monitorType: string;
+ config: any;
+ validationRules: any[];
+}
+
+interface AgentExecuteResponse {
+ jobId: string;
+ region: string;
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ statusCode?: number;
+ headers?: Record<string, string>;
+ timing?: {
+ dnsMs?: number;
+ tcpMs?: number;
+ tlsMs?: number;
+ ttfbMs?: number;
+ transferMs?: number;
+ };
+ error?: {
+ message: string;
+ type: string;
+ };
+ validationErrors?: string[];
+ bodySizeBytes?: number;
+}
+
+export class MonitorExecutor {
+ private worker: Worker | null = null;
+ private concurrency: number;
+ private isShuttingDown = false;
+ private connection: { host: string; port: number; password?: string };
+ private notificationService: NotificationService;
+
+ // Confirmation thresholds - require multiple consecutive checks before triggering incidents
+ private static readonly FAILURE_THRESHOLD = 2; // Consecutive failures before creating incident
+ private static readonly SUCCESS_THRESHOLD = 2; // Consecutive successes before resolving incident
+
+ constructor(concurrency: number = 10) {
+ this.concurrency = concurrency;
+ this.connection = {
+ host: process.env.REDIS_HOST || "localhost",
+ port: parseInt(process.env.REDIS_PORT || "6379", 10),
+ ...(process.env.REDIS_PASSWORD && { password: process.env.REDIS_PASSWORD }),
+ };
+ this.notificationService = new NotificationService();
+ }
+
+ async start(): Promise<void> {
+ console.log(`[Uptime] Starting BullMQ monitor executor with concurrency: ${this.concurrency}`);
+
+ // Create worker to process jobs
+ this.worker = new Worker(
+ "monitor-checks",
+ async (job: Job<MonitorCheckJob>) => {
+ await this.processMonitorCheck(job.data);
+ },
+ {
+ connection: this.connection,
+ concurrency: this.concurrency,
+ autorun: true,
+ removeOnComplete: {
+ count: 100,
+ },
+ removeOnFail: {
+ count: 100,
+ },
+ },
+ );
+
+ // Set up event listeners
+ // this.worker.on("completed", (job) => {
+ // console.log(`[Uptime] Job ${job.id} completed successfully`);
+ // });
+
+ this.worker.on("failed", (job, err) => {
+ console.error(`Job ${job?.id} failed:`, err);
+ });
+
+ this.worker.on("error", (err) => {
+ console.error("Worker error:", err);
+ });
+
+ this.worker.on("ready", () => {
+ console.log("[Uptime] BullMQ worker is ready and listening for jobs");
+ });
+
+ // this.worker.on("active", (job) => {
+ // console.log(`[Uptime] Job ${job.id} is now active`);
+ // });
+
+ // Wait for worker to be ready
+ await new Promise<void>((resolve) => {
+ if (this.worker) {
+ this.worker.once("ready", () => {
+ resolve();
+ });
+ }
+ });
+
+ console.log("[Uptime] BullMQ monitor executor started successfully");
+ }
+
+ private async processMonitorCheck(jobData: MonitorCheckJob): Promise<void> {
+ const { monitorId } = jobData;
+
+ try {
+ console.log(`[Uptime] πŸ” Starting to process monitor check for monitor ID: ${monitorId}`);
+
+ // Fetch monitor configuration
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, monitorId),
+ });
+
+ if (!monitor || !monitor.enabled) {
+ console.log(`[Uptime] Monitor ${monitorId} not found or disabled`);
+ return;
+ }
+
+ // Check if this is a global monitor
+ if (monitor.monitoringType === "global" && monitor.selectedRegions && monitor.selectedRegions.length > 0) {
+ await this.processGlobalMonitorCheck(monitor);
+ return;
+ }
+
+ // For local monitoring, proceed with the original logic
+ let result: HttpCheckResult | TcpCheckResult;
+ let responseBody: string | undefined;
+
+ if (monitor.monitorType === "http" && monitor.httpConfig) {
+ const httpResult = await performHttpCheck({
+ url: monitor.httpConfig.url,
+ method: monitor.httpConfig.method || "GET",
+ headers: monitor.httpConfig.headers,
+ body: monitor.httpConfig.body,
+ auth: monitor.httpConfig.auth,
+ followRedirects: monitor.httpConfig.followRedirects !== false,
+ timeoutMs: monitor.httpConfig.timeoutMs,
+ ipVersion: monitor.httpConfig.ipVersion,
+ userAgent: monitor.httpConfig.userAgent,
+ });
+
+ result = httpResult;
+
+ // For HTTP checks, we might need the response body for validation
+ // Note: In production, you might want to limit body size or make this optional
+ if (httpResult.status === "success" && monitor.validationRules.length > 0) {
+ // For now, we'll skip body validation to avoid memory issues
+ // In a real implementation, you'd stream the body or limit size
+ responseBody = undefined;
+ }
+ } else if (monitor.monitorType === "tcp" && monitor.tcpConfig) {
+ result = await performTcpCheck({
+ host: monitor.tcpConfig.host,
+ port: monitor.tcpConfig.port,
+ timeoutMs: monitor.tcpConfig.timeoutMs,
+ });
+ } else {
+ throw new Error(`Invalid monitor configuration for monitor ${monitorId}`);
+ }
+
+ // Apply validation rules for successful checks
+ if (result.status === "success" && monitor.validationRules.length > 0) {
+ const validationErrors = applyValidationRules(result as HttpCheckResult, monitor.validationRules, responseBody);
+
+ if (validationErrors.length > 0) {
+ result.validationErrors = validationErrors;
+ // Change status to failure if validation fails
+ result.status = "failure";
+ }
+ }
+
+ // Store result in ClickHouse
+ await this.storeMonitorEvent(monitor, result);
+
+ // Update monitor status in PostgreSQL
+ await this.updateMonitorStatus(monitor.id, result);
+
+ console.log(`[Uptime] βœ… Monitor check completed: ${monitorId} - ${result.status} (${result.responseTimeMs}ms)`);
+ } catch (error) {
+ console.error(`Error processing monitor check ${monitorId}:`, error);
+
+ // Try to store the error event
+ try {
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, monitorId),
+ });
+
+ if (monitor) {
+ const errorResult: HttpCheckResult = {
+ status: "failure",
+ responseTimeMs: 0,
+ timing: {},
+ headers: {},
+ bodySizeBytes: 0,
+ validationErrors: [],
+ error: {
+ message: error instanceof Error ? error.message : "Internal error during monitor check",
+ type: "internal_error",
+ },
+ };
+
+ await this.storeMonitorEvent(monitor, errorResult);
+ await this.updateMonitorStatus(monitor.id, errorResult);
+ }
+ } catch (innerError) {
+ console.error("Failed to store error event:", innerError);
+ }
+ }
+ }
+
+ private async processGlobalMonitorCheck(monitor: any): Promise<void> {
+ try {
+ // Filter to only include non-local regions
+ const globalRegions = monitor.selectedRegions.filter((r: string) => r !== "local");
+
+ if (globalRegions.length === 0) {
+ console.log(`[Uptime] Monitor ${monitor.id} has no global regions selected`);
+ return;
+ }
+
+ // Fetch agent regions information
+ const regions = await db.query.agentRegions.findMany({
+ where: and(
+ inArray(agentRegions.code, globalRegions),
+ eq(agentRegions.enabled, true),
+ eq(agentRegions.isHealthy, true),
+ ),
+ });
+
+ if (regions.length === 0) {
+ console.log(`[Uptime] No healthy regions found for monitor ${monitor.id}`);
+ return;
+ }
+
+ // Execute checks in parallel across all regions
+ const regionPromises = regions.map((region) =>
+ this.executeAgentCheck(monitor, region).catch((error) => {
+ console.error(`Error executing check in region ${region.code}:`, error);
+ return {
+ region: region.code,
+ result: {
+ status: "failure" as const,
+ responseTimeMs: 0,
+ timing: {},
+ headers: {},
+ bodySizeBytes: 0,
+ validationErrors: [],
+ error: {
+ message: error instanceof Error ? error.message : "Agent communication error",
+ type: "agent_error",
+ },
+ } as HttpCheckResult,
+ };
+ }),
+ );
+
+ const regionResults = await Promise.all(regionPromises);
+
+ // Store results for each region
+ for (const { region, result } of regionResults) {
+ await this.storeMonitorEvent(monitor, result, region);
+ }
+
+ // Handle incidents per region with thresholds
+ for (const { region, result } of regionResults) {
+ await this.handleRegionalIncident(monitor, region, result);
+ }
+
+ // Update monitor status based on the majority of regions
+ const successCount = regionResults.filter((r) => r.result.status === "success").length;
+ const overallStatus = successCount > regionResults.length / 2 ? "success" : "failure";
+
+ // Use the average response time from successful checks
+ const successfulResults = regionResults.filter((r) => r.result.status === "success");
+ const avgResponseTime =
+ successfulResults.length > 0
+ ? successfulResults.reduce((sum, r) => sum + r.result.responseTimeMs, 0) / successfulResults.length
+ : 0;
+
+ const aggregatedResult: HttpCheckResult = {
+ status: overallStatus === "success" ? "success" : "failure",
+ responseTimeMs: avgResponseTime,
+ timing: {},
+ headers: {},
+ bodySizeBytes: 0,
+ validationErrors: [],
+ };
+
+ await this.updateMonitorStatus(monitor.id, aggregatedResult);
+
+ console.log(
+ `[Uptime] βœ… Global monitor check completed: ${monitor.id} - ${overallStatus} (${regionResults.length} regions)`,
+ );
+ } catch (error) {
+ console.error(`Error processing global monitor check ${monitor.id}:`, error);
+ }
+ }
+
+ private async executeAgentCheck(
+ monitor: any,
+ region: any,
+ ): Promise<{ region: string; result: HttpCheckResult | TcpCheckResult }> {
+ const jobId = `${monitor.id}-${Date.now()}-${region.code}`;
+
+ const request: AgentExecuteRequest = {
+ jobId,
+ monitorId: monitor.id,
+ monitorType: monitor.monitorType,
+ config: monitor.monitorType === "http" ? monitor.httpConfig : monitor.tcpConfig,
+ validationRules: monitor.validationRules || [],
+ };
+
+ try {
+ const response = await fetch(`${region.endpointUrl}/execute`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(request),
+ signal: AbortSignal.timeout(60000), // 60 second timeout
+ });
+
+ if (!response.ok) {
+ throw new Error(`Agent returned status ${response.status}`);
+ }
+
+ const agentResponse: AgentExecuteResponse = await response.json();
+
+ // Convert agent response to our internal format
+ const result: HttpCheckResult | TcpCheckResult =
+ monitor.monitorType === "http"
+ ? {
+ status: agentResponse.status,
+ statusCode: agentResponse.statusCode,
+ responseTimeMs: agentResponse.responseTimeMs,
+ timing: agentResponse.timing || {},
+ headers: agentResponse.headers || {},
+ bodySizeBytes: agentResponse.bodySizeBytes || 0,
+ validationErrors: agentResponse.validationErrors || [],
+ error: agentResponse.error,
+ }
+ : {
+ status: agentResponse.status,
+ responseTimeMs: agentResponse.responseTimeMs,
+ validationErrors: [],
+ error: agentResponse.error,
+ };
+
+ return { region: region.code, result };
+ } catch (error) {
+ console.error(`Failed to execute check via agent ${region.code}:`, error);
+ throw error;
+ }
+ }
+
+ private async storeMonitorEvent(
+ monitor: any,
+ result: HttpCheckResult | TcpCheckResult,
+ regionCode: string = "local",
+ ): Promise<void> {
+ // Helper to ensure timing values are non-negative or undefined
+ const sanitizeTiming = (value: number | undefined): number | undefined => {
+ if (value === undefined || value === null) return undefined;
+ return value >= 0 ? Math.round(value) : undefined;
+ };
+
+ const event: MonitorEvent = {
+ monitor_id: monitor.id,
+ organization_id: monitor.organizationId,
+ timestamp: DateTime.now().toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
+ monitor_type: monitor.monitorType,
+ monitor_url: monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`,
+ monitor_name: monitor.name,
+ region: regionCode,
+ status: result.status,
+ status_code: (result as HttpCheckResult).statusCode,
+ response_time_ms: Math.max(0, Math.round(result.responseTimeMs)),
+ dns_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.dnsMs),
+ tcp_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.tcpMs),
+ tls_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.tlsMs),
+ ttfb_ms: sanitizeTiming((result as HttpCheckResult).timing?.ttfbMs),
+ transfer_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.transferMs),
+ validation_errors: result.validationErrors,
+ response_headers: (result as HttpCheckResult).headers || {},
+ response_size_bytes: (result as HttpCheckResult).bodySizeBytes,
+ port: monitor.tcpConfig?.port,
+ error_message: result.error?.message,
+ error_type: result.error?.type,
+ };
+
+ try {
+ await clickhouse.insert({
+ table: "monitor_events",
+ values: [event],
+ format: "JSONEachRow",
+ });
+ } catch (error) {
+ console.error("Failed to store monitor event in ClickHouse:", error);
+ }
+ }
+
+ private async updateMonitorStatus(monitorId: number, result: HttpCheckResult | TcpCheckResult): Promise<void> {
+ try {
+ const now = new Date();
+ const currentStatus = result.status === "success" ? "up" : "down";
+
+ // Get current status to update consecutive counts
+ const existingStatus = await db.query.uptimeMonitorStatus.findFirst({
+ where: eq(uptimeMonitorStatus.monitorId, monitorId),
+ });
+
+ let consecutiveFailures = existingStatus?.consecutiveFailures || 0;
+ let consecutiveSuccesses = existingStatus?.consecutiveSuccesses || 0;
+ const previousStatus = existingStatus?.currentStatus;
+
+ if (currentStatus === "up") {
+ consecutiveSuccesses++;
+ consecutiveFailures = 0;
+ } else {
+ consecutiveFailures++;
+ consecutiveSuccesses = 0;
+ }
+
+ // Update or insert status
+ if (existingStatus) {
+ await db
+ .update(uptimeMonitorStatus)
+ .set({
+ lastCheckedAt: now.toISOString(),
+ currentStatus,
+ consecutiveFailures,
+ consecutiveSuccesses,
+ updatedAt: now.toISOString(),
+ })
+ .where(eq(uptimeMonitorStatus.monitorId, monitorId));
+ } else {
+ await db.insert(uptimeMonitorStatus).values({
+ monitorId,
+ lastCheckedAt: now.toISOString(),
+ currentStatus,
+ consecutiveFailures,
+ consecutiveSuccesses,
+ updatedAt: now.toISOString(),
+ });
+ }
+
+ // Handle incident creation/resolution based on consecutive failures/successes
+ await this.handleIncidentManagement(
+ monitorId,
+ previousStatus || undefined,
+ currentStatus,
+ result,
+ consecutiveFailures,
+ consecutiveSuccesses
+ );
+ } catch (error) {
+ console.error("Failed to update monitor status:", error);
+ }
+ }
+
+ private async handleIncidentManagement(
+ monitorId: number,
+ previousStatus: string | undefined,
+ currentStatus: string,
+ result: HttpCheckResult | TcpCheckResult,
+ consecutiveFailures: number,
+ consecutiveSuccesses: number,
+ ): Promise<void> {
+ try {
+ // Get monitor details for incident creation
+ const monitor = await db.query.uptimeMonitors.findFirst({
+ where: eq(uptimeMonitors.id, monitorId),
+ });
+
+ if (!monitor) {
+ console.error(`Monitor ${monitorId} not found for incident management`);
+ return;
+ }
+
+ // Check for active incidents
+ const activeIncident = await db.query.uptimeIncidents.findFirst({
+ where: and(
+ eq(uptimeIncidents.monitorId, monitorId),
+ eq(uptimeIncidents.status, "active"),
+ eq(uptimeIncidents.region, "local"),
+ ),
+ });
+
+ // Create incident when failures reach threshold
+ if (currentStatus === "down" && consecutiveFailures === MonitorExecutor.FAILURE_THRESHOLD && !activeIncident) {
+ const [newIncident] = await db
+ .insert(uptimeIncidents)
+ .values({
+ organizationId: monitor.organizationId as string,
+ monitorId: monitorId,
+ region: "local",
+ startTime: new Date().toISOString(),
+ status: "active",
+ lastError: result.error?.message || null,
+ lastErrorType: result.error?.type || null,
+ failureCount: 1,
+ })
+ .returning();
+ console.log(`[Uptime] Created new incident for monitor ${monitorId} (${monitor.name})`);
+
+ // Send notifications for new incident
+ await this.notificationService.sendIncidentNotifications(monitor, newIncident, "down");
+ }
+ // Resolve incident when successes reach threshold after being down
+ else if (currentStatus === "up" && consecutiveSuccesses === MonitorExecutor.SUCCESS_THRESHOLD && activeIncident) {
+ const now = new Date().toISOString();
+ await db
+ .update(uptimeIncidents)
+ .set({
+ status: "resolved",
+ endTime: now,
+ resolvedAt: now,
+ })
+ .where(eq(uptimeIncidents.id, activeIncident.id));
+ console.log(`[Uptime] Resolved incident ${activeIncident.id} for monitor ${monitorId} (${monitor.name})`);
+
+ // Send recovery notifications
+ await this.notificationService.sendIncidentNotifications(
+ monitor,
+ { ...activeIncident, status: "resolved", endTime: now },
+ "recovery",
+ );
+ }
+ // Status remains DOWN (Update failure count)
+ else if (currentStatus === "down" && activeIncident) {
+ await db
+ .update(uptimeIncidents)
+ .set({
+ failureCount: (activeIncident.failureCount || 0) + 1,
+ lastError: result.error?.message || activeIncident.lastError,
+ lastErrorType: result.error?.type || activeIncident.lastErrorType,
+ })
+ .where(eq(uptimeIncidents.id, activeIncident.id));
+ }
+ } catch (error) {
+ console.error("Failed to manage incident:", error);
+ }
+ }
+
+ private async handleRegionalIncident(
+ monitor: any,
+ region: string,
+ result: HttpCheckResult | TcpCheckResult,
+ ): Promise<void> {
+ try {
+ const currentStatus = result.status === "success" ? "up" : "down";
+
+ // Get recent events from ClickHouse to determine consecutive counts
+ const recentEvents = await clickhouse.query({
+ query: `
+ SELECT status, timestamp
+ FROM monitor_events
+ WHERE monitor_id = {monitorId:Int32}
+ AND region = {region:String}
+ ORDER BY timestamp DESC
+ LIMIT {limit:Int32}
+ `,
+ query_params: {
+ monitorId: monitor.id,
+ region: region,
+ limit: MonitorExecutor.FAILURE_THRESHOLD + 1 // Get enough events to check threshold
+ }
+ });
+
+ const events = await recentEvents.json<{ status: string; timestamp: string }>();
+
+ // Count consecutive failures/successes from most recent events
+ let consecutiveFailures = 0;
+ let consecutiveSuccesses = 0;
+
+ // Start with current result
+ if (currentStatus === "down") {
+ consecutiveFailures = 1;
+ } else {
+ consecutiveSuccesses = 1;
+ }
+
+ // Check previous events
+ for (const event of events.data) {
+ if (currentStatus === "down" && event.status === "failure") {
+ consecutiveFailures++;
+ } else if (currentStatus === "up" && event.status === "success") {
+ consecutiveSuccesses++;
+ } else {
+ break; // Different status, not consecutive
+ }
+ }
+
+ // Check for active incidents in this region
+ const activeIncident = await db.query.uptimeIncidents.findFirst({
+ where: and(
+ eq(uptimeIncidents.monitorId, monitor.id),
+ eq(uptimeIncidents.status, "active"),
+ eq(uptimeIncidents.region, region),
+ ),
+ });
+
+ // Create incident when failures reach threshold
+ if (currentStatus === "down" && consecutiveFailures === MonitorExecutor.FAILURE_THRESHOLD && !activeIncident) {
+ const [newIncident] = await db
+ .insert(uptimeIncidents)
+ .values({
+ organizationId: monitor.organizationId as string,
+ monitorId: monitor.id,
+ region: region,
+ startTime: new Date().toISOString(),
+ status: "active",
+ lastError: result.error?.message || null,
+ lastErrorType: result.error?.type || null,
+ failureCount: 1,
+ })
+ .returning();
+ console.log(`[Uptime] Created new incident for monitor ${monitor.id} (${monitor.name}) in region ${region}`);
+
+ // Send notifications for new regional incident
+ await this.notificationService.sendIncidentNotifications(monitor, newIncident, "down");
+ }
+ // Resolve incident when successes reach threshold
+ else if (currentStatus === "up" && consecutiveSuccesses === MonitorExecutor.SUCCESS_THRESHOLD && activeIncident) {
+ const now = new Date().toISOString();
+ await db
+ .update(uptimeIncidents)
+ .set({
+ status: "resolved",
+ endTime: now,
+ resolvedAt: now,
+ updatedAt: now,
+ })
+ .where(eq(uptimeIncidents.id, activeIncident.id));
+ console.log(
+ `[Uptime] Resolved incident ${activeIncident.id} for monitor ${monitor.id} (${monitor.name}) in region ${region}`,
+ );
+
+ // Send recovery notifications for regional incident
+ await this.notificationService.sendIncidentNotifications(
+ monitor,
+ { ...activeIncident, status: "resolved", endTime: now },
+ "recovery",
+ );
+ }
+ // If check failed and there's already an active incident, update it
+ else if (currentStatus === "down" && activeIncident) {
+ await db
+ .update(uptimeIncidents)
+ .set({
+ failureCount: (activeIncident.failureCount || 0) + 1,
+ lastError: result.error?.message || activeIncident.lastError,
+ lastErrorType: result.error?.type || activeIncident.lastErrorType,
+ })
+ .where(eq(uptimeIncidents.id, activeIncident.id));
+ }
+ } catch (error) {
+ console.error(`Failed to manage regional incident for region ${region}:`, error);
+ }
+ }
+
+ async shutdown(): Promise<void> {
+ console.log("[Uptime] Shutting down BullMQ monitor executor...");
+ this.isShuttingDown = true;
+
+ if (this.worker) {
+ try {
+ // Close the worker with a timeout
+ await Promise.race([
+ this.worker.close(),
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Worker close timeout")), 5000)),
+ ]);
+ console.log("[Uptime] BullMQ monitor executor shut down successfully");
+ } catch (error) {
+ console.error("Error closing worker:", error);
+ // Force close if needed
+ this.worker = null;
+ }
+ }
+ }
+}
diff --git a/server/src/services/uptime/monitorScheduler.ts b/server/src/services/uptime/monitorScheduler.ts
new file mode 100644
index 000000000..639668f59
--- /dev/null
+++ b/server/src/services/uptime/monitorScheduler.ts
@@ -0,0 +1,227 @@
+import { Queue, QueueEvents, JobsOptions } from "bullmq";
+import { eq } from "drizzle-orm";
+import { db } from "../../db/postgres/postgres.js";
+import { uptimeMonitors } from "../../db/postgres/schema.js";
+import { MonitorCheckJob } from "./types.js";
+
+export class MonitorScheduler {
+ private queue: Queue;
+ private queueEvents: QueueEvents;
+ private isShuttingDown = false;
+ private connection: { host: string; port: number; password?: string };
+
+ constructor() {
+ // Get Redis connection from environment
+ this.connection = {
+ host: process.env.REDIS_HOST || "localhost",
+ port: parseInt(process.env.REDIS_PORT || "6379", 10),
+ ...(process.env.REDIS_PASSWORD && { password: process.env.REDIS_PASSWORD }),
+ };
+
+ console.log(`[Uptime] BullMQ connecting to Redis at ${this.connection.host}:${this.connection.port}`);
+
+ this.queue = new Queue("monitor-checks", {
+ connection: this.connection,
+ defaultJobOptions: {
+ removeOnComplete: {
+ count: 100, // Keep last 100 completed jobs
+ age: 3600, // Keep for 1 hour
+ },
+ removeOnFail: {
+ count: 100, // Keep last 100 failed jobs
+ age: 86400, // Keep for 24 hours
+ },
+ },
+ });
+
+ this.queueEvents = new QueueEvents("monitor-checks", {
+ connection: this.connection,
+ });
+ }
+
+ async initialize(): Promise<void> {
+ console.log("[Uptime] Initializing BullMQ monitor scheduler...");
+
+ // Wait for queue to be ready
+ await this.queue.waitUntilReady();
+ await this.queueEvents.waitUntilReady();
+
+ console.log("[Uptime] BullMQ queue ready");
+
+ // Clear any stale jobs from previous runs
+ await this.clearStaleJobs();
+
+ // Load and schedule all active monitors
+ await this.loadAndScheduleMonitors();
+
+ console.log("[Uptime] BullMQ monitor scheduler initialized");
+ }
+
+ private async clearStaleJobs(): Promise<void> {
+ try {
+ // For Dragonfly compatibility, we'll clear jobs more carefully
+ // First, try to get counts to see if there are any jobs
+ const counts = await this.queue.getJobCounts();
+ console.log("[Uptime] Current job counts:", counts);
+
+ // Only try to clear if there are actually jobs
+ if (counts.delayed > 0 || counts.waiting > 0 || counts.active > 0) {
+ try {
+ // Try to clean specific job types one by one
+ const waitingJobs = await this.queue.getJobs(["waiting"]);
+ const activeJobs = await this.queue.getJobs(["active"]);
+
+ console.log(`[Uptime] Found ${waitingJobs.length} waiting and ${activeJobs.length} active jobs`);
+
+ // Remove jobs individually
+ for (const job of [...waitingJobs, ...activeJobs]) {
+ try {
+ await job.remove();
+ } catch (err) {
+ console.warn(`Failed to remove job ${job.id}:`, err);
+ }
+ }
+
+ console.log("[Uptime] Cleared stale jobs");
+ } catch (err) {
+ console.warn("Could not clear all job types:", err);
+ }
+ } else {
+ console.log("[Uptime] No stale jobs to clear");
+ }
+ } catch (error) {
+ console.error("Error clearing stale jobs:", error);
+ // Continue anyway - this is not critical for startup
+ }
+ }
+
+ private async loadAndScheduleMonitors(): Promise<void> {
+ try {
+ // Load all enabled monitors
+ const monitors = await db.select().from(uptimeMonitors).where(eq(uptimeMonitors.enabled, true));
+
+ console.log(`[Uptime] Found ${monitors.length} enabled monitors`);
+
+ // Schedule each monitor
+ for (const monitor of monitors) {
+ await this.scheduleMonitor(monitor.id, monitor.intervalSeconds);
+ }
+ } catch (error) {
+ console.error("Error loading monitors:", error);
+ }
+ }
+
+ async scheduleMonitor(monitorId: number, intervalSeconds: number): Promise<void> {
+ if (this.isShuttingDown) return;
+
+ try {
+ // Remove existing jobs for this monitor
+ await this.removeMonitorSchedule(monitorId);
+
+ const jobName = `monitor-${monitorId}`;
+ const jobData: MonitorCheckJob = {
+ monitorId,
+ intervalSeconds,
+ };
+
+ // Add recurring job using repeat option
+ const job = await this.queue.add(jobName, jobData, {
+ repeat: {
+ every: intervalSeconds * 1000, // Convert to milliseconds
+ },
+ jobId: jobName, // Use monitor ID as job ID to prevent duplicates
+ });
+
+ console.log(`[Uptime] Scheduled monitor ${monitorId} to run every ${intervalSeconds} seconds (job: ${job.id})`);
+ } catch (error) {
+ console.error(`Error scheduling monitor ${monitorId}:`, error);
+ }
+ }
+
+ async removeMonitorSchedule(monitorId: number): Promise<void> {
+ try {
+ const jobName = `monitor-${monitorId}`;
+
+ // First, remove repeatable job configuration
+ const repeatableJobs = await this.queue.getRepeatableJobs();
+ const monitorRepeatableJobs = repeatableJobs.filter((job) => job.name === jobName || job.id === jobName);
+
+ await Promise.all(monitorRepeatableJobs.map((job) => this.queue.removeRepeatableByKey(job.key)));
+
+ // Then remove any non-repeat jobs (only remove jobs that don't belong to scheduler)
+ const jobs = await this.queue.getJobs(["waiting", "active", "completed", "failed"]);
+ const monitorJobs = jobs.filter((job) => {
+ // Only remove jobs that match our monitor and aren't repeat jobs
+ return (job.name === jobName || job.id === jobName) && !job.repeatJobKey;
+ });
+
+ await Promise.all(
+ monitorJobs.map(async (job) => {
+ try {
+ await job.remove();
+ } catch (err) {
+ // Ignore errors for jobs that can't be removed (e.g., repeat jobs)
+ console.warn(`Could not remove job ${job.id}:`, err);
+ }
+ }),
+ );
+
+ console.log(`[Uptime] Removed schedule for monitor ${monitorId}`);
+ } catch (error) {
+ console.error(`Error removing monitor schedule ${monitorId}:`, error);
+ }
+ }
+
+ async updateMonitorSchedule(monitorId: number, intervalSeconds: number): Promise<void> {
+ await this.scheduleMonitor(monitorId, intervalSeconds);
+ }
+
+ async triggerImmediateCheck(monitorId: number): Promise<void> {
+ try {
+ const jobName = `monitor-${monitorId}-immediate`;
+ const jobData: MonitorCheckJob = {
+ monitorId,
+ intervalSeconds: 0, // Not used for immediate checks
+ };
+
+ // Add a one-time job for immediate execution
+ const job = await this.queue.add(jobName, jobData, {
+ delay: 0, // No delay
+ priority: 1, // Higher priority than regular checks
+ removeOnComplete: true,
+ removeOnFail: false,
+ });
+
+ console.log(`[Uptime] Triggered immediate check for monitor ${monitorId} (job: ${job.id})`);
+ } catch (error) {
+ console.error(`Error triggering immediate check for monitor ${monitorId}:`, error);
+ }
+ }
+
+ async shutdown(): Promise<void> {
+ console.log("[Uptime] Shutting down BullMQ monitor scheduler...");
+ this.isShuttingDown = true;
+
+ try {
+ // Close queue events and queue with timeouts
+ await Promise.all([
+ Promise.race([
+ this.queueEvents.close(),
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Queue events close timeout")), 3000)),
+ ]).catch((err) => console.error("Queue events close error:", err)),
+ Promise.race([
+ this.queue.close(),
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Queue close timeout")), 3000)),
+ ]).catch((err) => console.error("Queue close error:", err)),
+ ]);
+
+ console.log("[Uptime] BullMQ monitor scheduler shut down successfully");
+ } catch (error) {
+ console.error("Error during scheduler shutdown:", error);
+ }
+ }
+
+ getQueue(): Queue {
+ return this.queue;
+ }
+}
diff --git a/server/src/services/uptime/notificationService.ts b/server/src/services/uptime/notificationService.ts
new file mode 100644
index 000000000..19b70deae
--- /dev/null
+++ b/server/src/services/uptime/notificationService.ts
@@ -0,0 +1,403 @@
+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 { sendEmail } from "../../lib/resend.js";
+import { sendSMS } from "../../lib/twilio.js";
+
+// Type inferred from Drizzle schema
+type NotificationChannel = InferSelectModel<typeof notificationChannels>;
+
+interface Monitor {
+ id: number;
+ organizationId: string;
+ name?: string | null;
+ monitorType: string;
+ httpConfig?: {
+ url: string;
+ } | null;
+ tcpConfig?: {
+ host: string;
+ port: number;
+ } | null;
+}
+
+interface Incident {
+ id: number;
+ region?: string | null;
+ startTime: string;
+ endTime?: string | null;
+ lastError?: string | null;
+ lastErrorType?: string | null;
+ status: string;
+}
+
+export class NotificationService {
+ async sendTestNotification(channel: NotificationChannel, monitor: Monitor, incident: Incident, eventType: "down" | "recovery"): Promise<void> {
+ try {
+ if (channel.type === "email" && channel.config.email) {
+ await this.sendEmailNotification(channel.config.email, monitor, incident, eventType);
+ } else if (channel.type === "discord" && channel.config.webhookUrl) {
+ await this.sendDiscordNotification(channel.config.webhookUrl, monitor, incident, eventType);
+ } else if (channel.type === "slack" && channel.config.slackWebhookUrl) {
+ await this.sendSlackNotification(
+ channel.config.slackWebhookUrl,
+ channel.config.slackChannel,
+ monitor,
+ incident,
+ eventType,
+ );
+ } else if (channel.type === "sms" && channel.config.phoneNumber) {
+ await this.sendSMSNotification(channel.config.phoneNumber, monitor, incident, eventType);
+ }
+ } catch (error) {
+ console.error(`Failed to send test ${channel.type} notification:`, error);
+ throw error;
+ }
+ }
+
+ async sendIncidentNotifications(monitor: Monitor, incident: Incident, eventType: "down" | "recovery"): Promise<void> {
+ try {
+ // Get all enabled notification channels for this organization
+ const channels = await db.query.notificationChannels.findMany({
+ where: and(
+ eq(notificationChannels.organizationId, monitor.organizationId),
+ eq(notificationChannels.enabled, true),
+ ),
+ });
+
+ // Filter channels that should receive notifications for this monitor
+ const relevantChannels = channels.filter((channel) => {
+ // Check if channel triggers for this event type
+ if (!channel.triggerEvents?.includes(eventType)) {
+ return false;
+ }
+
+ // Check if channel monitors this specific monitor or all monitors
+ if (channel.monitorIds === null) {
+ // null means all monitors
+ return true;
+ }
+
+ return channel.monitorIds.includes(monitor.id);
+ });
+
+ // Check cooldown for each channel
+ const now = new Date();
+ const channelsToNotify = relevantChannels.filter((channel) => {
+ if (!channel.lastNotifiedAt) return true;
+
+ const lastNotified = new Date(channel.lastNotifiedAt);
+ const cooldownMs = (channel.cooldownMinutes || 5) * 60 * 1000;
+ return now.getTime() - lastNotified.getTime() > cooldownMs;
+ });
+
+ // Send notifications for each channel
+ for (const channel of channelsToNotify) {
+ try {
+ if (channel.type === "email" && channel.config.email) {
+ await this.sendEmailNotification(channel.config.email, monitor, incident, eventType);
+ } else if (channel.type === "discord" && channel.config.webhookUrl) {
+ await this.sendDiscordNotification(channel.config.webhookUrl, monitor, incident, eventType);
+ } else if (channel.type === "slack" && channel.config.slackWebhookUrl) {
+ await this.sendSlackNotification(
+ channel.config.slackWebhookUrl,
+ channel.config.slackChannel,
+ monitor,
+ incident,
+ eventType,
+ );
+ } else if (channel.type === "sms" && channel.config.phoneNumber) {
+ await this.sendSMSNotification(channel.config.phoneNumber, monitor, incident, eventType);
+ }
+
+ // Update last notified time for successful notifications
+ await db
+ .update(notificationChannels)
+ .set({ lastNotifiedAt: now.toISOString() })
+ .where(eq(notificationChannels.id, channel.id));
+ } catch (error) {
+ console.error(`Failed to send ${channel.type} notification for channel ${channel.id}:`, error);
+ }
+ }
+ } catch (error) {
+ console.error("Failed to send incident notifications:", error);
+ }
+ }
+
+ private async sendEmailNotification(
+ email: string,
+ monitor: Monitor,
+ incident: Incident,
+ eventType: "down" | "recovery",
+ ): Promise<void> {
+ const monitorName =
+ monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
+ const region = incident.region || "local";
+ const incidentTime = DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL);
+
+ let subject: string;
+ let html: string;
+
+ if (eventType === "down") {
+ subject = `πŸ”΄ Monitor Alert: ${monitorName} is DOWN`;
+ html = `
+ <h2>Monitor Alert: ${monitorName} is DOWN</h2>
+ <p>Your monitor has stopped responding.</p>
+ <ul>
+ <li><strong>Monitor:</strong> ${monitorName}</li>
+ <li><strong>Type:</strong> ${monitor.monitorType.toUpperCase()}</li>
+ <li><strong>Region:</strong> ${region}</li>
+ <li><strong>Time:</strong> ${incidentTime}</li>
+ ${incident.lastError ? `<li><strong>Error:</strong> ${incident.lastError}</li>` : ""}
+ </ul>
+ <p>We'll continue monitoring and notify you when the service recovers.</p>
+ `;
+ } else {
+ const duration = incident.endTime
+ ? DateTime.fromSQL(incident.endTime)
+ .diff(DateTime.fromSQL(incident.startTime))
+ .toFormat("hh 'hours' mm 'minutes'")
+ : "Unknown";
+
+ subject = `βœ… Monitor Recovery: ${monitorName} is UP`;
+ html = `
+ <h2>Monitor Recovery: ${monitorName} is UP</h2>
+ <p>Your monitor has recovered and is responding normally.</p>
+ <ul>
+ <li><strong>Monitor:</strong> ${monitorName}</li>
+ <li><strong>Type:</strong> ${monitor.monitorType.toUpperCase()}</li>
+ <li><strong>Region:</strong> ${region}</li>
+ <li><strong>Downtime Duration:</strong> ${duration}</li>
+ <li><strong>Recovery Time:</strong> ${DateTime.now().toLocaleString(DateTime.DATETIME_FULL)}</li>
+ </ul>
+ `;
+ }
+
+ await sendEmail(email, subject, html);
+ console.log(`[Uptime] Sent ${eventType} email notification to ${email} for monitor ${monitor.id}`);
+ }
+
+ private async sendDiscordNotification(
+ webhookUrl: string,
+ monitor: Monitor,
+ incident: Incident,
+ eventType: "down" | "recovery",
+ ): Promise<void> {
+ const monitorName =
+ monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
+ const region = incident.region || "local";
+
+ const embed = {
+ title:
+ eventType === "down" ? `πŸ”΄ Monitor Alert: ${monitorName} is DOWN` : `βœ… Monitor Recovery: ${monitorName} is UP`,
+ color: eventType === "down" ? 0xff0000 : 0x00ff00,
+ fields: [
+ {
+ name: "Monitor",
+ value: monitorName,
+ inline: true,
+ },
+ {
+ name: "Type",
+ value: monitor.monitorType.toUpperCase(),
+ inline: true,
+ },
+ {
+ name: "Region",
+ value: region,
+ inline: true,
+ },
+ ...(eventType === "down"
+ ? [
+ {
+ name: "Time",
+ value: DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL),
+ inline: false,
+ },
+ ...(incident.lastError
+ ? [
+ {
+ name: "Error",
+ value: incident.lastError,
+ inline: false,
+ },
+ ]
+ : []),
+ ]
+ : [
+ {
+ name: "Downtime Duration",
+ value: incident.endTime
+ ? DateTime.fromSQL(incident.endTime)
+ .diff(DateTime.fromSQL(incident.startTime))
+ .toFormat("hh 'hours' mm 'minutes'")
+ : "Unknown",
+ inline: true,
+ },
+ {
+ name: "Recovery Time",
+ value: DateTime.now().toLocaleString(DateTime.DATETIME_FULL),
+ inline: true,
+ },
+ ]),
+ ],
+ timestamp: new Date().toISOString(),
+ };
+
+ const response = await fetch(webhookUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ embeds: [embed],
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Discord webhook failed: ${response.status} ${response.statusText}`);
+ }
+
+ console.log(`[Uptime] Sent ${eventType} Discord notification for monitor ${monitor.id}`);
+ }
+
+ private async sendSlackNotification(
+ webhookUrl: string,
+ slackChannel: string | undefined,
+ monitor: Monitor,
+ incident: Incident,
+ eventType: "down" | "recovery",
+ ): Promise<void> {
+ const monitorName =
+ monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
+ const region = incident.region || "local";
+ const emoji = eventType === "down" ? ":red_circle:" : ":white_check_mark:";
+
+ const blocks: any[] = [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text:
+ eventType === "down"
+ ? `${emoji} Monitor Alert: ${monitorName} is DOWN`
+ : `${emoji} Monitor Recovery: ${monitorName} is UP`,
+ emoji: true,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Monitor:*\n${monitorName}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Type:*\n${monitor.monitorType.toUpperCase()}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Region:*\n${region}`,
+ },
+ ...(eventType === "down"
+ ? [
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL)}`,
+ },
+ ]
+ : [
+ {
+ type: "mrkdwn",
+ text: `*Duration:*\n${
+ incident.endTime
+ ? DateTime.fromSQL(incident.endTime)
+ .diff(DateTime.fromSQL(incident.startTime))
+ .toFormat("hh 'hours' mm 'minutes'")
+ : "Unknown"
+ }`,
+ },
+ ]),
+ ],
+ },
+ ];
+
+ if (eventType === "down" && incident.lastError) {
+ blocks.push({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Error:* ${incident.lastError}`,
+ },
+ });
+ }
+
+ const payload: any = {
+ blocks,
+ text: eventType === "down" ? `Monitor Alert: ${monitorName} is DOWN` : `Monitor Recovery: ${monitorName} is UP`,
+ };
+
+ if (slackChannel) {
+ payload.channel = slackChannel;
+ }
+
+ const response = await fetch(webhookUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Slack webhook failed: ${response.status} ${response.statusText}`);
+ }
+
+ console.log(`[Uptime] Sent ${eventType} Slack notification for monitor ${monitor.id}`);
+ }
+
+ private async sendSMSNotification(
+ phoneNumber: string,
+ monitor: Monitor,
+ incident: Incident,
+ eventType: "down" | "recovery",
+ ): Promise<void> {
+ const monitorName =
+ monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
+ const region = incident.region || "local";
+
+ let message: string;
+ if (eventType === "down") {
+ message = `πŸ”΄ ALERT: ${monitorName} is DOWN in ${region}`;
+ if (incident.lastError) {
+ // Truncate error to fit SMS limits
+ const truncatedError = incident.lastError.length > 50
+ ? incident.lastError.substring(0, 47) + "..."
+ : incident.lastError;
+ message += ` - ${truncatedError}`;
+ }
+ } else {
+ const duration = incident.endTime
+ ? DateTime.fromSQL(incident.endTime)
+ .diff(DateTime.fromSQL(incident.startTime))
+ .toFormat("h'h' m'm'")
+ : "Unknown";
+ message = `βœ… RECOVERY: ${monitorName} is UP in ${region} after ${duration} downtime`;
+ }
+
+ // SMS messages should be concise - limit to 160 chars for single SMS
+ if (message.length > 160) {
+ message = message.substring(0, 157) + "...";
+ }
+
+ const result = await sendSMS(phoneNumber, message);
+
+ if (!result.success) {
+ throw new Error(result.error || "Failed to send SMS");
+ }
+
+ console.log(`[Uptime] Sent ${eventType} SMS notification to ${phoneNumber} for monitor ${monitor.id}`);
+ }
+}
diff --git a/server/src/services/uptime/regionHealthChecker.ts b/server/src/services/uptime/regionHealthChecker.ts
new file mode 100644
index 000000000..025a81fe3
--- /dev/null
+++ b/server/src/services/uptime/regionHealthChecker.ts
@@ -0,0 +1,98 @@
+import { eq } from "drizzle-orm";
+import { db } from "../../db/postgres/postgres.js";
+import { agentRegions } from "../../db/postgres/schema.js";
+
+export class RegionHealthChecker {
+ private intervalMs: number;
+ private intervalId: NodeJS.Timeout | null = null;
+
+ constructor(intervalMs: number = 60000) {
+ // Default: 1 minute
+ this.intervalMs = intervalMs;
+ }
+
+ async start(): Promise<void> {
+ console.log(`[Uptime] Starting region health checker with interval: ${this.intervalMs}ms`);
+
+ // Run initial check
+ await this.checkAllRegions();
+
+ // Schedule periodic checks
+ this.intervalId = setInterval(async () => {
+ await this.checkAllRegions();
+ }, this.intervalMs);
+ }
+
+ async stop(): Promise<void> {
+ if (this.intervalId) {
+ clearInterval(this.intervalId);
+ this.intervalId = null;
+ console.log("[Uptime] Region health checker stopped");
+ }
+ }
+
+ private async checkAllRegions(): Promise<void> {
+ try {
+ const regions = await db.query.agentRegions.findMany({
+ where: eq(agentRegions.enabled, true),
+ });
+
+ // Filter out local region
+ const remoteRegions = regions.filter((r) => r.code !== "local");
+
+ console.log(`[Uptime] Checking health of ${remoteRegions.length} remote regions`);
+
+ const healthPromises = remoteRegions.map((region) =>
+ this.checkRegionHealth(region).catch((error) => {
+ console.error(`Error checking health of region ${region.code}:`, error);
+ return { region, isHealthy: false };
+ }),
+ );
+
+ const results = await Promise.all(healthPromises);
+
+ // Update health status in database
+ for (const { region, isHealthy } of results) {
+ await db
+ .update(agentRegions)
+ .set({
+ isHealthy,
+ lastHealthCheck: new Date().toISOString(),
+ })
+ .where(eq(agentRegions.code, region.code));
+ }
+
+ const healthyCount = results.filter((r) => r.isHealthy).length;
+ console.log(`[Uptime] Region health check complete: ${healthyCount}/${remoteRegions.length} regions healthy`);
+ } catch (error) {
+ console.error("Error in region health check:", error);
+ }
+ }
+
+ private async checkRegionHealth(region: any): Promise<{ region: any; isHealthy: boolean }> {
+ try {
+ const response = await fetch(`${region.endpointUrl}/health`, {
+ method: "GET",
+ signal: AbortSignal.timeout(10000), // 10 second timeout
+ });
+
+ if (!response.ok) {
+ console.warn(`Region ${region.code} returned status ${response.status}`);
+ return { region, isHealthy: false };
+ }
+
+ const data = await response.json();
+
+ // Verify the response contains expected fields
+ if (data.status === "ok" && data.region === region.code) {
+ return { region, isHealthy: true };
+ }
+
+ console.warn(`Region ${region.code} returned unexpected response:`, data);
+ return { region, isHealthy: false };
+ } catch (error) {
+ console.error(`Health check failed for region ${region.code}:`, error);
+ return { region, isHealthy: false };
+ }
+ }
+}
diff --git a/server/src/services/uptime/types.ts b/server/src/services/uptime/types.ts
new file mode 100644
index 000000000..0429712df
--- /dev/null
+++ b/server/src/services/uptime/types.ts
@@ -0,0 +1,75 @@
+export interface MonitorCheckJob {
+ monitorId: number;
+ intervalSeconds: number;
+}
+
+export interface HttpCheckResult {
+ status: "success" | "failure" | "timeout";
+ statusCode?: number;
+ responseTimeMs: number;
+ timing: {
+ dnsMs?: number;
+ tcpMs?: number;
+ tlsMs?: number;
+ ttfbMs?: number;
+ transferMs?: number;
+ };
+ headers: Record<string, string>;
+ bodySizeBytes: number;
+ validationErrors: string[];
+ error?: {
+ message: string;
+ type: string;
+ };
+}
+
+export interface TcpCheckResult {
+ status: "success" | "failure" | "timeout";
+ responseTimeMs: number;
+ validationErrors: string[];
+ error?: {
+ message: string;
+ type: string;
+ };
+}
+
+export type CheckResult = HttpCheckResult | TcpCheckResult;
+
+export interface ValidationRule {
+ type:
+ | "status_code"
+ | "response_time"
+ | "response_body_contains"
+ | "response_body_not_contains"
+ | "header_exists"
+ | "header_value"
+ | "response_size";
+ operator?: "equals" | "not_equals" | "in" | "not_in" | "less_than" | "greater_than" | "contains";
+ value?: number | number[] | string;
+ header?: string;
+ caseSensitive?: boolean;
+}
+
+export interface MonitorEvent {
+ monitor_id: number;
+ organization_id: string;
+ timestamp: string; // ClickHouse DateTime format: YYYY-MM-DD HH:MM:SS
+ monitor_type: string;
+ monitor_url: string;
+ monitor_name: string;
+ region: string;
+ status: string;
+ status_code?: number;
+ response_time_ms: number;
+ dns_time_ms?: number;
+ tcp_time_ms?: number;
+ tls_time_ms?: number;
+ ttfb_ms?: number;
+ transfer_time_ms?: number;
+ validation_errors: string[];
+ response_headers: Record<string, string>;
+ response_size_bytes?: number;
+ port?: number;
+ error_message?: string;
+ error_type?: string;
+}
diff --git a/server/src/services/uptime/uptimeService.ts b/server/src/services/uptime/uptimeService.ts
new file mode 100644
index 000000000..c4f7aef64
--- /dev/null
+++ b/server/src/services/uptime/uptimeService.ts
@@ -0,0 +1,131 @@
+import { MonitorScheduler } from "./monitorScheduler.js";
+import { MonitorExecutor } from "./monitorExecutor.js";
+import { RegionHealthChecker } from "./regionHealthChecker.js";
+
+export class UptimeService {
+ private scheduler: MonitorScheduler;
+ private executor: MonitorExecutor;
+ private regionHealthChecker: RegionHealthChecker;
+ private initialized = false;
+ private initializationPromise: Promise<void> | null = null;
+
+ constructor() {
+ this.scheduler = new MonitorScheduler();
+ this.executor = new MonitorExecutor(10); // 10 concurrent workers
+ this.regionHealthChecker = new RegionHealthChecker(60000); // Check every minute
+ }
+
+ async initialize(): Promise<void> {
+ if (this.initialized) {
+ console.log("Uptime service already initialized");
+ return;
+ }
+
+ // If already initializing, return the existing promise
+ if (this.initializationPromise) {
+ return this.initializationPromise;
+ }
+
+ // Create and store the initialization promise
+ this.initializationPromise = this.performInitialization();
+ return this.initializationPromise;
+ }
+
+ private async performInitialization(): Promise<void> {
+ try {
+ console.log("Initializing BullMQ uptime monitoring service...");
+
+ // Initialize scheduler (creates queue, loads and schedules all monitors)
+ await this.scheduler.initialize();
+
+ // Start executor (begins processing jobs)
+ await this.executor.start();
+
+ // Start region health checker
+ await this.regionHealthChecker.start();
+
+ this.initialized = true;
+ console.log("BullMQ uptime monitoring service initialized successfully");
+ } catch (error) {
+ console.error("Failed to initialize uptime service:", error);
+ this.initializationPromise = null; // Reset on failure
+ throw error;
+ }
+ }
+
+ async shutdown(): Promise<void> {
+ console.log("Shutting down BullMQ uptime monitoring service...");
+
+ try {
+ // Stop region health checker
+ await this.regionHealthChecker.stop();
+
+ // Shutdown executor first (stops processing new jobs)
+ await this.executor.shutdown();
+
+ // Then shutdown scheduler (closes queue)
+ await this.scheduler.shutdown();
+
+ this.initialized = false;
+ console.log("BullMQ uptime monitoring service shut down successfully");
+ } catch (error) {
+ console.error("Error during uptime service shutdown:", error);
+ }
+ }
+
+ // Methods for managing monitors after CRUD operations
+ async onMonitorCreated(monitorId: number, intervalSeconds: number): Promise<void> {
+ // Wait for initialization if it's in progress
+ if (!this.initialized && this.initializationPromise) {
+ await this.initializationPromise;
+ }
+
+ if (!this.initialized) {
+ console.warn("Uptime service not initialized, cannot schedule monitor");
+ return;
+ }
+
+ // Schedule the monitor for recurring checks
+ await this.scheduler.scheduleMonitor(monitorId, intervalSeconds);
+
+ // Trigger an immediate check
+ await this.scheduler.triggerImmediateCheck(monitorId);
+ }
+
+ async onMonitorUpdated(monitorId: number, intervalSeconds: number, enabled: boolean): Promise<void> {
+ // Wait for initialization if it's in progress
+ if (!this.initialized && this.initializationPromise) {
+ await this.initializationPromise;
+ }
+
+ if (!this.initialized) {
+ console.warn("Uptime service not initialized, cannot update monitor");
+ return;
+ }
+
+ if (enabled) {
+ await this.scheduler.updateMonitorSchedule(monitorId, intervalSeconds);
+ // Trigger immediate check when monitor is re-enabled
+ await this.scheduler.triggerImmediateCheck(monitorId);
+ } else {
+ await this.scheduler.removeMonitorSchedule(monitorId);
+ }
+ }
+
+ async onMonitorDeleted(monitorId: number): Promise<void> {
+ // Wait for initialization if it's in progress
+ if (!this.initialized && this.initializationPromise) {
+ await this.initializationPromise;
+ }
+
+ if (!this.initialized) {
+ console.warn("Uptime service not initialized, cannot delete monitor");
+ return;
+ }
+
+ await this.scheduler.removeMonitorSchedule(monitorId);
+ }
+}
+
+// Export singleton instance
+export const uptimeService = new UptimeService();
diff --git a/server/src/services/uptime/validationEngine.ts b/server/src/services/uptime/validationEngine.ts
new file mode 100644
index 000000000..e3db53e78
--- /dev/null
+++ b/server/src/services/uptime/validationEngine.ts
@@ -0,0 +1,205 @@
+import { HttpCheckResult, ValidationRule } from './types.js';
+
+export function applyValidationRules(
+ result: HttpCheckResult,
+ rules: ValidationRule[],
+ responseBody?: string
+): string[] {
+ const errors: string[] = [];
+
+ for (const rule of rules) {
+ try {
+ const error = validateRule(result, rule, responseBody);
+ if (error) {
+ errors.push(error);
+ }
+ } catch (e) {
+ errors.push(`Validation rule error: ${e instanceof Error ? e.message : 'Unknown error'}`);
+ }
+ }
+
+ return errors;
+}
+
+function validateRule(
+ result: HttpCheckResult,
+ rule: ValidationRule,
+ responseBody?: string
+): string | null {
+ switch (rule.type) {
+ case 'status_code':
+ if (!result.statusCode) return null;
+ return validateStatusCode(result.statusCode, rule);
+
+ case 'response_time':
+ return validateResponseTime(result.responseTimeMs, rule);
+
+ case 'response_body_contains':
+ if (!responseBody) return 'Response body is empty';
+ return validateBodyContains(responseBody, rule, true);
+
+ case 'response_body_not_contains':
+ if (!responseBody) return null;
+ return validateBodyContains(responseBody, rule, false);
+
+ case 'header_exists':
+ return validateHeaderExists(result.headers, rule);
+
+ case 'header_value':
+ return validateHeaderValue(result.headers, rule);
+
+ case 'response_size':
+ return validateResponseSize(result.bodySizeBytes, rule);
+
+ default:
+ return `Unknown validation rule type: ${rule.type}`;
+ }
+}
+
+function validateStatusCode(statusCode: number, rule: ValidationRule): string | null {
+ const value = rule.value;
+
+ switch (rule.operator) {
+ case 'equals':
+ if (statusCode !== value) {
+ return `Status code ${statusCode} does not equal ${value}`;
+ }
+ break;
+
+ case 'not_equals':
+ if (statusCode === value) {
+ return `Status code ${statusCode} equals ${value}`;
+ }
+ break;
+
+ case 'in':
+ if (Array.isArray(value) && !value.includes(statusCode)) {
+ return `Status code ${statusCode} is not in [${value.join(', ')}]`;
+ }
+ break;
+
+ case 'not_in':
+ if (Array.isArray(value) && value.includes(statusCode)) {
+ return `Status code ${statusCode} is in [${value.join(', ')}]`;
+ }
+ break;
+ }
+
+ return null;
+}
+
+function validateResponseTime(responseTimeMs: number, rule: ValidationRule): string | null {
+ const value = rule.value as number;
+
+ switch (rule.operator) {
+ case 'less_than':
+ if (responseTimeMs >= value) {
+ return `Response time ${responseTimeMs}ms is not less than ${value}ms`;
+ }
+ break;
+
+ case 'greater_than':
+ if (responseTimeMs <= value) {
+ return `Response time ${responseTimeMs}ms is not greater than ${value}ms`;
+ }
+ break;
+ }
+
+ return null;
+}
+
+function validateBodyContains(
+ body: string,
+ rule: ValidationRule,
+ shouldContain: boolean
+): string | null {
+ const searchValue = String(rule.value);
+ const caseSensitive = rule.caseSensitive !== false;
+
+ const bodyToSearch = caseSensitive ? body : body.toLowerCase();
+ const valueToSearch = caseSensitive ? searchValue : searchValue.toLowerCase();
+
+ const contains = bodyToSearch.includes(valueToSearch);
+
+ if (shouldContain && !contains) {
+ return `Response body does not contain "${searchValue}"`;
+ } else if (!shouldContain && contains) {
+ return `Response body contains "${searchValue}"`;
+ }
+
+ return null;
+}
+
+function validateHeaderExists(
+ headers: Record<string, string>,
+ rule: ValidationRule
+): string | null {
+ if (!rule.header) return 'Header name not specified';
+
+ const headerKey = Object.keys(headers).find(
+ key => key.toLowerCase() === rule.header!.toLowerCase()
+ );
+
+ if (!headerKey) {
+ return `Header "${rule.header}" does not exist`;
+ }
+
+ return null;
+}
+
+function validateHeaderValue(
+ headers: Record<string, string>,
+ rule: ValidationRule
+): string | null {
+ if (!rule.header) return 'Header name not specified';
+
+ const headerKey = Object.keys(headers).find(
+ key => key.toLowerCase() === rule.header!.toLowerCase()
+ );
+
+ if (!headerKey) {
+ return `Header "${rule.header}" does not exist`;
+ }
+
+ const headerValue = headers[headerKey];
+ const expectedValue = String(rule.value);
+
+ switch (rule.operator) {
+ case 'equals':
+ if (headerValue !== expectedValue) {
+ return `Header "${rule.header}" value "${headerValue}" does not equal "${expectedValue}"`;
+ }
+ break;
+
+ case 'contains':
+ if (!headerValue.includes(expectedValue)) {
+ return `Header "${rule.header}" value "${headerValue}" does not contain "${expectedValue}"`;
+ }
+ break;
+ }
+
+ return null;
+}
+
+function validateResponseSize(
+ sizeBytes: number,
+ rule: ValidationRule
+): string | null {
+ const value = rule.value as number;
+
+ switch (rule.operator) {
+ case 'less_than':
+ if (sizeBytes >= value) {
+ return `Response size ${sizeBytes} bytes is not less than ${value} bytes`;
+ }
+ break;
+
+ case 'greater_than':
+ if (sizeBytes <= value) {
+ return `Response size ${sizeBytes} bytes is not greater than ${value} bytes`;
+ }
+ break;
+ }
+
+ return null;
+}
\ No newline at end of file