This commit is contained in:
Alex Holliday committed 2026-01-15 23:45:40 +00:00
1 parent ed80837810
commit 0f764ca084
12 files changed
+431 -116

No files matched your search

@@ -1,13 +1,13 @@
const SERVICE_NAME = "JobQueueHelper";
import type { Monitor } from "@/types/monitor.js";
import { AppError } from "@/utils/AppError.js";
import { INetworkService } from "@/service/index.js";
class SuperSimpleQueueHelper {
static SERVICE_NAME = SERVICE_NAME;
private db: any;
private logger: any;
private networkService: any;
private networkService: INetworkService;
private statusService: any;
private notificationService: any;
@@ -20,7 +20,7 @@ class SuperSimpleQueueHelper {
}: {
db: any;
logger: any;
networkService: any;
networkService: INetworkService;
statusService: any;
notificationService: any;
}) {
@@ -61,14 +61,13 @@ class SuperSimpleQueueHelper {
throw new Error("No network response");
}
const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(status);
const statusChangeResult = await this.statusService.updateMonitorStatus(status);
this.notificationService
.handleNotifications({
...status,
monitor: updatedMonitor,
prevStatus,
statusChanged,
monitor: statusChangeResult.monitor,
prevStatus: statusChangeResult.prevStatus,
statusChanged: statusChangeResult.statusChanged,
})
.catch((error: any) => {
this.logger.error({
@@ -1,10 +1,38 @@
import { Got } from "got";
import type { Monitor } from "@/types/index.js";
import { HTTPError, RequestError } from "got";
import type { Got, Response } from "got";
import type { Monitor, MonitorStatusResponse } from "@/types/index.js";
import CacheableLookup from "cacheable-lookup";
const SERVICE_NAME = "NetworkService";
class NetworkService {
type MonitorStatusResponseOverrides<T> = Partial<Omit<MonitorStatusResponse<T>, "monitorId" | "teamId" | "type">>;
interface BuildStatusResponseArgs<T> {
monitor: Monitor;
response?: Response<T> | null;
error?: Error | RequestError | HTTPError | null;
payload?: T | null;
jsonPath?: string;
matchMethod?: MonitorStatusResponse["matchMethod"];
expectedValue?: string;
extracted?: unknown;
overrides?: MonitorStatusResponseOverrides<T>;
}
export interface INetworkService {
readonly serviceName: string;
requestStatus(monitor: Monitor): Promise<MonitorStatusResponse>;
requestWebhook(type: string, url: string, body: any): Promise<{ type: string; status: boolean; code: number; message: string; payload?: unknown }>;
requestPagerDuty(args: { message: string; routingKey: string; monitorUrl: string }): Promise<boolean>;
requestMatrix(args: { homeserverUrl: string; accessToken: string; roomId: string; message: string }): Promise<{
status: boolean;
code: number;
message: string;
payload?: unknown;
}>;
}
class NetworkService implements INetworkService {
static SERVICE_NAME = SERVICE_NAME;
private TYPE_PING: string;
@@ -31,6 +59,60 @@ class NetworkService {
private stringService: any;
private settingsService: any;
private buildStatusResponse = <T>({
monitor,
response,
error,
payload,
jsonPath,
matchMethod,
expectedValue,
extracted,
overrides,
}: BuildStatusResponseArgs<T>): MonitorStatusResponse<T> => {
if (error) {
const statusResponse: MonitorStatusResponse<T> = {
monitorId: monitor.id,
teamId: monitor.teamId,
type: monitor.type,
status: false,
code: this.NETWORK_ERROR,
message: error.message ?? "Network error",
responseTime: 0,
timings: undefined,
jsonPath,
matchMethod,
expectedValue,
extracted,
payload,
};
if (error instanceof HTTPError || error instanceof RequestError) {
statusResponse.code = error?.response?.statusCode ?? this.NETWORK_ERROR;
statusResponse.message = error.message;
statusResponse.responseTime = error.timings?.phases?.total ?? 0;
statusResponse.timings = error.timings;
}
return { ...statusResponse, ...(overrides ?? {}) };
}
return {
monitorId: monitor.id,
teamId: monitor.teamId,
type: monitor.type,
status: response?.ok ?? false,
code: response?.statusCode ?? this.NETWORK_ERROR,
message: response?.statusMessage ?? "",
responseTime: response?.timings?.phases?.total ?? 0,
timings: response?.timings,
payload: payload ?? response?.body,
jsonPath,
matchMethod,
expectedValue,
extracted,
...(overrides ?? {}),
};
};
constructor({
axios,
got,
@@ -91,13 +173,17 @@ class NetworkService {
});
}
get serviceName(): string {
return NetworkService.SERVICE_NAME;
}
// Helper functions
async timeRequest(operation: any) {
private async timeRequest<T>(operation: () => Promise<T>): Promise<{ response: T | null; responseTime: number; error: unknown }> {
const start = process.hrtime.bigint();
try {
const response = await operation();
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
return { response, responseTime: elapsedMs };
return { response, responseTime: elapsedMs, error: null };
} catch (error) {
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
return { response: null, responseTime: elapsedMs, error };
@@ -105,7 +191,7 @@ class NetworkService {
}
// Main entry point
async requestStatus(monitor: Monitor) {
async requestStatus(monitor: Monitor): Promise<MonitorStatusResponse> {
const type = monitor?.type || "unknown";
switch (type) {
case this.TYPE_PING:
@@ -123,11 +209,11 @@ class NetworkService {
case this.TYPE_GAME:
return await this.requestGame(monitor);
default:
return await this.handleUnsupportedType(type);
return this.handleUnsupportedType(type);
}
}
async requestPing(monitor: Monitor) {
private async requestPing(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
if (!monitor?.url) {
throw new Error("Monitor URL is required");
@@ -147,19 +233,21 @@ class NetworkService {
throw new Error("Ping failed - no result returned");
}
const pingResponse = {
monitorId: monitor.id,
type: "ping",
status: response.alive,
code: 200,
responseTime: response.time,
message: "Success",
const pingResponse = this.buildStatusResponse({
monitor,
payload: response,
};
overrides: {
status: (response as { alive?: boolean })?.alive ?? false,
code: 200,
message: "Success",
responseTime: (response as { time?: number })?.time ?? 0,
payload: response,
},
});
if (error) {
pingResponse.status = false;
pingResponse.code = 200;
pingResponse.code = this.PING_ERROR;
pingResponse.message = "Ping failed";
return pingResponse;
}
@@ -172,13 +260,16 @@ class NetworkService {
}
}
async requestHttp(monitor: Monitor) {
private async requestHttp(monitor: Monitor): Promise<MonitorStatusResponse> {
const { url, secret, id, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor;
const httpResponse: Record<string, any> = {
monitorId: id,
teamId: teamId,
type,
};
const httpResponse = this.buildStatusResponse({
monitor,
overrides: {
status: false,
code: this.NETWORK_ERROR,
message: "Request not executed",
},
});
try {
if (!url) {
@@ -211,12 +302,14 @@ class NetworkService {
payload = response.body;
}
httpResponse.code = response.statusCode;
httpResponse.status = response.ok;
httpResponse.message = response.statusMessage;
httpResponse.responseTime = response.timings.phases.total || 0;
httpResponse.payload = payload;
httpResponse.timings = response.timings || {};
Object.assign(httpResponse, {
code: response.statusCode,
status: response.ok,
message: response.statusMessage ?? "",
responseTime: response.timings.phases.total || 0,
payload,
timings: response.timings,
});
if (!expectedValue && !jsonPath) {
return httpResponse;
@@ -300,7 +393,7 @@ class NetworkService {
}
}
async requestPageSpeed(monitor: Monitor) {
private async requestPageSpeed(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
const url = monitor.url;
if (!url) {
@@ -329,7 +422,7 @@ class NetworkService {
}
}
async requestHardware(monitor: Monitor) {
private async requestHardware(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
return await this.requestHttp(monitor);
} catch (err: any) {
@@ -339,7 +432,7 @@ class NetworkService {
}
}
async requestDocker(monitor: Monitor) {
private async requestDocker(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
if (!monitor.url) {
throw new Error("Monitor URL is required");
@@ -350,10 +443,14 @@ class NetworkService {
handleError: true, // Enable error handling
});
const dockerResponse: Record<string, any> = {
monitorId: monitor.id,
type: monitor.type,
};
const dockerResponse = this.buildStatusResponse({
monitor,
overrides: {
status: false,
code: this.NETWORK_ERROR,
message: "No response",
},
});
const containers = await docker.listContainers({ all: true });
@@ -406,7 +503,6 @@ class NetworkService {
method: "requestDocker",
details: { url: monitor.url },
});
dockerResponse.status = 404;
dockerResponse.status = false;
dockerResponse.message = `Ambiguous container match for "${monitor.url}". Matched by: ${matchTypes.join(", ")}. Using ${exactIdMatch ? "exact ID" : exactNameMatch ? "exact name" : "partial ID"} match.`;
return dockerResponse;
@@ -437,7 +533,7 @@ class NetworkService {
}
}
async requestPort(monitor: Monitor) {
private async requestPort(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
const { url, port } = monitor;
const { response, responseTime, error } = await this.timeRequest(async () => {
@@ -467,14 +563,15 @@ class NetworkService {
});
});
const portResponse = {
code: 200,
status: response.success,
message: this.stringService.portSuccess,
monitorId: monitor.id,
type: monitor.type,
responseTime: responseTime,
};
const portResponse = this.buildStatusResponse({
monitor,
overrides: {
code: 200,
status: (response as { success?: boolean })?.success ?? false,
message: this.stringService.portSuccess,
responseTime,
},
});
if (error) {
portResponse.code = this.NETWORK_ERROR;
@@ -491,17 +588,18 @@ class NetworkService {
}
}
async requestGame(monitor: Monitor) {
private async requestGame(monitor: Monitor): Promise<MonitorStatusResponse> {
try {
const { url, port, gameId } = monitor;
const gameResponse: Record<string, any> = {
code: 200,
status: true,
message: "Success",
monitorId: monitor.id,
type: "game",
};
const gameResponse = this.buildStatusResponse({
monitor,
overrides: {
code: 200,
status: true,
message: "Success",
},
});
const state = await this.GameDig.query({
type: gameId,
@@ -532,11 +630,15 @@ class NetworkService {
throw error;
}
}
async handleUnsupportedType(type: string) {
const err: any = new Error(`Unsupported type: ${type}`);
err.service = this.SERVICE_NAME;
err.method = "getStatus";
throw err;
private async handleUnsupportedType(type: string): Promise<MonitorStatusResponse> {
return {
monitorId: "unknown",
teamId: "unknown",
type: "unknown",
status: false,
code: this.NETWORK_ERROR,
message: `Unsupported type: ${type}`,
};
}
// Other network requests unrelated to monitoring:
@@ -1,7 +1,8 @@
import { IMonitorsRepository } from "@/repositories/index.js";
import MonitorStats from "../../db/models/MonitorStats.js";
import { CheckModel } from "@/db/models/index.js";
import type { Monitor } from "@/types/index.js";
import type { CheckErrorInfo, Monitor, MonitorStatusResponse, StatusChangeResult } from "@/types/index.js";
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
const SERVICE_NAME = "StatusService";
class StatusService {
@@ -161,15 +162,17 @@ class StatusService {
}
};
updateStatus = async (networkResponse: any) => {
const check = this.buildCheck(networkResponse);
updateMonitorStatus = async (
statusResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>
): Promise<StatusChangeResult> => {
const check = this.buildCheck(statusResponse);
await this.insertCheck(check);
try {
const { monitorId, teamId, status, code } = networkResponse;
const { monitorId, teamId, status, code } = statusResponse;
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
// Update running stats
this.updateRunningStats({ monitor, networkResponse });
this.updateRunningStats({ monitor, networkResponse: statusResponse });
// If the status window size has changed, empty
while (monitor.statusWindow.length > monitor.statusWindowSize) {
@@ -298,7 +301,9 @@ class StatusService {
}
};
buildCheck = (networkResponse: any) => {
buildCheck = (
networkResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>
) => {
const {
monitorId,
teamId,
@@ -317,7 +322,7 @@ class StatusService {
timings,
} = networkResponse;
const check = {
const check: any = {
metadata: {
monitorId,
teamId,
@@ -337,7 +342,8 @@ class StatusService {
};
if (type === "pagespeed") {
if (typeof payload === "undefined") {
const pageSpeedPayload = payload as PageSpeedStatusPayload | undefined;
if (!pageSpeedPayload) {
this.logger.warn({
message: "Failed to build check",
service: SERVICE_NAME,
@@ -346,8 +352,8 @@ class StatusService {
});
return undefined;
}
const categories = payload?.lighthouseResult?.categories ?? {};
const audits = payload?.lighthouseResult?.audits ?? {};
const categories = pageSpeedPayload.lighthouseResult?.categories ?? {};
const audits = pageSpeedPayload.lighthouseResult?.audits ?? {};
const mapAudit = (audit: any) => {
if (!audit || typeof audit !== "object") {
return undefined;
@@ -375,14 +381,17 @@ class StatusService {
}
if (type === "hardware") {
const { cpu, memory, disk, host, net } = payload?.data ?? {};
const { errors } = payload?.errors ?? [];
const hardwarePayload = payload as HardwareStatusPayload | undefined;
const { cpu, memory, disk, host, net } = hardwarePayload?.data ?? {};
const errorsSource = Array.isArray(hardwarePayload?.errors)
? hardwarePayload?.errors
: (hardwarePayload?.errors as { errors?: CheckErrorInfo[] } | undefined)?.errors;
check.cpu = cpu ?? {};
check.memory = memory ?? {};
check.disk = disk ?? {};
check.host = host ?? {};
check.errors = errors ?? [];
check.capture = payload?.capture ?? {};
check.errors = errorsSource ?? [];
check.capture = hardwarePayload?.capture ?? {};
check.net = net ?? {};
}
return check;