reorg to domain and api
This commit is contained in:
1 parent
0fb210e9e1
commit
d022f7d849
190 files changed
+643
-830
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import { Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import jmespath from "jmespath";
|
||||
type JmesPath = typeof jmespath;
|
||||
|
||||
export interface IAdvancedMatcher {
|
||||
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined };
|
||||
}
|
||||
|
||||
export class AdvancedMatcher implements IAdvancedMatcher {
|
||||
constructor(private jmespath: JmesPath) {}
|
||||
|
||||
private compare(actual: unknown, expected: string, method?: string): boolean {
|
||||
if (method === "equal") return String(actual) === expected;
|
||||
if (method === "include") return String(actual).includes(expected);
|
||||
if (method === "regex") return new RegExp(expected).test(String(actual));
|
||||
return String(actual) === expected; // Default
|
||||
}
|
||||
|
||||
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined } {
|
||||
const { useAdvancedMatching, jsonPath, matchMethod, expectedValue } = monitor;
|
||||
if (!useAdvancedMatching) return { ok: true, message: "Success" };
|
||||
|
||||
let dataToValidate = payload;
|
||||
|
||||
if (jsonPath) {
|
||||
try {
|
||||
dataToValidate = this.jmespath.search(payload, jsonPath);
|
||||
} catch {
|
||||
return { ok: false, message: "Error evaluating JSON path" };
|
||||
}
|
||||
}
|
||||
|
||||
if (expectedValue) {
|
||||
const ok = this.compare(dataToValidate, expectedValue, matchMethod);
|
||||
return {
|
||||
ok,
|
||||
message: ok ? "Success" : "Expected value did not match",
|
||||
extracted: dataToValidate,
|
||||
};
|
||||
}
|
||||
|
||||
const isFalsy = dataToValidate === false || dataToValidate === "false" || dataToValidate === undefined || dataToValidate === null;
|
||||
return {
|
||||
ok: !isFalsy,
|
||||
message: !isFalsy ? "Success" : "Extracted value is falsy",
|
||||
extracted: dataToValidate,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { DNSStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import type { Resolver } from "dns/promises";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { NETWORK_ERROR, timeRequest } from "@/service/network/utils.js";
|
||||
|
||||
const SERVICE_NAME = "DNSProvider";
|
||||
|
||||
export class DNSProvider implements IStatusProvider<DNSStatusPayload> {
|
||||
readonly type = "dns";
|
||||
constructor(private createResolver: () => Resolver) {}
|
||||
supports(type: MonitorType) {
|
||||
return type === "dns";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<DNSStatusPayload>> {
|
||||
try {
|
||||
const { url, dnsServer, dnsRecordType = "A" } = monitor;
|
||||
if (!dnsServer) {
|
||||
throw new Error("DNS server is required for DNS monitoring");
|
||||
}
|
||||
|
||||
let hostname: string;
|
||||
try {
|
||||
const withScheme = /^[a-z]+:\/\//i.test(url) ? url : `http://${url}`; // Ensure URL has a scheme for proper parsing
|
||||
hostname = new URL(withScheme).hostname;
|
||||
} catch {
|
||||
hostname = url;
|
||||
}
|
||||
|
||||
const resolver = this.createResolver();
|
||||
resolver.setServers([dnsServer]);
|
||||
|
||||
const {
|
||||
response: results,
|
||||
responseTime,
|
||||
error,
|
||||
} = await timeRequest(() => {
|
||||
switch (dnsRecordType.toUpperCase()) {
|
||||
case "A":
|
||||
return resolver.resolve4(hostname);
|
||||
case "AAAA":
|
||||
return resolver.resolve6(hostname);
|
||||
case "CNAME":
|
||||
return resolver.resolveCname(hostname);
|
||||
case "MX":
|
||||
return resolver.resolveMx(hostname);
|
||||
case "TXT":
|
||||
return resolver.resolveTxt(hostname);
|
||||
case "NS":
|
||||
return resolver.resolveNs(hostname);
|
||||
default:
|
||||
return resolver.resolve(hostname, dnsRecordType);
|
||||
}
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
responseTime,
|
||||
payload: {
|
||||
hostname,
|
||||
dnsServer,
|
||||
recordType: dnsRecordType,
|
||||
resolved: false,
|
||||
results,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: true,
|
||||
code: 200,
|
||||
message: "Success",
|
||||
responseTime,
|
||||
payload: {
|
||||
hostname,
|
||||
dnsServer,
|
||||
recordType: dnsRecordType,
|
||||
resolved: true,
|
||||
results,
|
||||
},
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
const originalMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new AppError({
|
||||
message: originalMessage || "Error performing DNS check",
|
||||
status: 500,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { DockerStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import Dockerode from "dockerode";
|
||||
import { NETWORK_ERROR, timeRequest } from "@/service/network/utils.js";
|
||||
|
||||
type DockerodeType = typeof Dockerode;
|
||||
|
||||
const SERVICE_NAME = "DockerProvider";
|
||||
|
||||
export interface DockerError extends Error {
|
||||
statusCode?: number;
|
||||
reason?: string;
|
||||
json?: { message?: string };
|
||||
}
|
||||
|
||||
export class DockerProvider implements IStatusProvider<DockerStatusPayload> {
|
||||
readonly type = "docker";
|
||||
private docker: Dockerode;
|
||||
constructor(
|
||||
private logger: ILogger,
|
||||
private DockerLib: DockerodeType
|
||||
) {
|
||||
this.docker = new this.DockerLib();
|
||||
}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "docker";
|
||||
}
|
||||
|
||||
private isDockerError(error: unknown): error is DockerError {
|
||||
return error instanceof Error && ("statusCode" in error || "reason" in error || "json" in error);
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<DockerStatusPayload>> {
|
||||
const { url: containerInput } = monitor;
|
||||
try {
|
||||
if (!containerInput) {
|
||||
throw new Error("Container name or ID is required for Docker monitor");
|
||||
}
|
||||
|
||||
const containers = await this.docker.listContainers({ all: true });
|
||||
const normalizedInput = containerInput.replace(/^\/+/, "").toLowerCase();
|
||||
|
||||
// Priority-based matching to avoid ambiguity:
|
||||
// 1. Exact full ID match (64-char)
|
||||
const exactIdMatch = containers.find((c) => c.Id.toLowerCase() === normalizedInput);
|
||||
|
||||
// 2. Exact container name match (case-insensitive)
|
||||
const exactNameMatch = containers.find((c) =>
|
||||
c.Names.some((name: string) => {
|
||||
const cleanName = name.replace(/^\/+/, "").toLowerCase();
|
||||
return cleanName === normalizedInput;
|
||||
})
|
||||
);
|
||||
|
||||
// 3. Partial ID match (fallback for backwards compatibility)
|
||||
const partialIdMatch = containers.find((c) => c.Id.toLowerCase().startsWith(normalizedInput));
|
||||
|
||||
// Select container based on priority
|
||||
const targetContainer = exactIdMatch || exactNameMatch || partialIdMatch;
|
||||
|
||||
// Handle no match
|
||||
if (!targetContainer) {
|
||||
this.logger.warn({
|
||||
message: `No container found for "${monitor.url}".`,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url },
|
||||
});
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: 404,
|
||||
message: "Docker container not found",
|
||||
responseTime: 0,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 5. Handle Ambiguity Check
|
||||
const matchTypes: string[] = [];
|
||||
if (exactIdMatch) matchTypes.push("exact ID");
|
||||
if (exactNameMatch) matchTypes.push("exact name");
|
||||
if (partialIdMatch && !exactIdMatch) matchTypes.push("partial ID");
|
||||
|
||||
if (matchTypes.length > 1) {
|
||||
const matchUsed = exactIdMatch ? "exact ID" : "exact name";
|
||||
const message = `Ambiguous container match for "${containerInput}". Matched by: ${matchTypes.join(", ")}. Using ${matchUsed} match.`;
|
||||
|
||||
this.logger.warn({
|
||||
message,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: containerInput },
|
||||
});
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message,
|
||||
responseTime: 0,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 6. Inspect Container Status
|
||||
const container = this.docker.getContainer(targetContainer.Id);
|
||||
const { response, responseTime, error } = await timeRequest(() => container.inspect());
|
||||
|
||||
if (error) {
|
||||
let message = "Failed to fetch Docker container information";
|
||||
let code = NETWORK_ERROR;
|
||||
|
||||
if (this.isDockerError(error)) {
|
||||
code = error.statusCode ?? NETWORK_ERROR;
|
||||
message = error.json?.message ?? error.reason ?? error.message;
|
||||
} else if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: code,
|
||||
message: message,
|
||||
responseTime,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: "No response from Docker container inspect",
|
||||
responseTime,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: response.State?.Status === "running",
|
||||
code: 200,
|
||||
message: "Docker container status fetched successfully",
|
||||
responseTime,
|
||||
payload: response as unknown as DockerStatusPayload,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
throw new AppError({
|
||||
message: err instanceof Error ? err.message : "Error performing Docker request",
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: containerInput },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { GameStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { GameDig } from "gamedig";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { NETWORK_ERROR } from "@/service/network/utils.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
|
||||
type GameDigType = typeof GameDig;
|
||||
|
||||
const SERVICE_NAME = "GameProvider";
|
||||
export class GameProvider implements IStatusProvider<GameStatusPayload> {
|
||||
readonly type = "game";
|
||||
constructor(
|
||||
private logger: ILogger,
|
||||
private gameDig: GameDigType
|
||||
) {}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "game";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<GameStatusPayload>> {
|
||||
const { url, port, gameId, id, teamId, type } = monitor;
|
||||
|
||||
// Clean the host in case a full URL was passed
|
||||
const host = url?.replace(/^https?:\/\//, "").split(/[/?#:]/)[0] || "";
|
||||
try {
|
||||
const state = await this.gameDig
|
||||
.query({
|
||||
type: gameId ?? "unknown",
|
||||
host: host,
|
||||
port: port ?? 0,
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
this.logger.warn({
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { host, port, gameId },
|
||||
});
|
||||
return undefined;
|
||||
});
|
||||
|
||||
if (!state) {
|
||||
return {
|
||||
monitorId: id,
|
||||
teamId: teamId,
|
||||
type: type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: "No response from game server",
|
||||
responseTime: 0,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: id,
|
||||
teamId: teamId,
|
||||
type: type,
|
||||
status: true,
|
||||
code: 200,
|
||||
message: "Success",
|
||||
responseTime: state.ping ?? 0,
|
||||
payload: state,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const originalMessage = err instanceof Error ? err.message : String(err);
|
||||
throw new AppError({
|
||||
message: originalMessage || "Error performing game server check",
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url, port: monitor.port, gameId: monitor.gameId },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { GrpcStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { timeRequest } from "@/service/network/utils.js";
|
||||
import * as grpc from "@grpc/grpc-js";
|
||||
import * as protoLoader from "@grpc/proto-loader";
|
||||
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
type GrpcType = typeof grpc;
|
||||
type ProtoLoaderType = typeof protoLoader;
|
||||
|
||||
const SERVICE_NAME = "GrpcProvider";
|
||||
|
||||
export class GrpcProvider implements IStatusProvider<GrpcStatusPayload> {
|
||||
readonly type = "grpc";
|
||||
constructor(
|
||||
private grpc: GrpcType,
|
||||
private protoLoader: ProtoLoaderType
|
||||
) {}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "grpc";
|
||||
}
|
||||
|
||||
private getGrpcStatusName(code: number): string {
|
||||
const statusNames: Record<number, string> = {
|
||||
0: "OK",
|
||||
1: "CANCELLED",
|
||||
2: "UNKNOWN",
|
||||
3: "INVALID_ARGUMENT",
|
||||
4: "DEADLINE_EXCEEDED",
|
||||
5: "NOT_FOUND",
|
||||
6: "ALREADY_EXISTS",
|
||||
7: "PERMISSION_DENIED",
|
||||
8: "RESOURCE_EXHAUSTED",
|
||||
9: "FAILED_PRECONDITION",
|
||||
10: "ABORTED",
|
||||
11: "OUT_OF_RANGE",
|
||||
12: "UNIMPLEMENTED",
|
||||
13: "INTERNAL",
|
||||
14: "UNAVAILABLE",
|
||||
15: "DATA_LOSS",
|
||||
16: "UNAUTHENTICATED",
|
||||
};
|
||||
return statusNames[code] || "UNKNOWN";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<GrpcStatusPayload>> {
|
||||
try {
|
||||
const { id, teamId, type, url, port, ignoreTlsErrors } = monitor;
|
||||
const grpcServiceName = monitor.grpcServiceName || "";
|
||||
|
||||
if (!url) {
|
||||
throw new AppError({ message: "Monitor host is required", service: SERVICE_NAME, method: "handle" });
|
||||
}
|
||||
if (!port) {
|
||||
throw new AppError({ message: "Monitor port is required", service: SERVICE_NAME, method: "handle" });
|
||||
}
|
||||
|
||||
const host = url.replace(/^https?:\/\//, "").split(/[/?#:]/)[0];
|
||||
const target = `${host}:${port}`;
|
||||
|
||||
const currentFilePath = fileURLToPath(import.meta.url);
|
||||
const protoPath = path.join(path.dirname(currentFilePath), "protos", "health.proto");
|
||||
const packageDefinition = this.protoLoader.loadSync(protoPath, {
|
||||
keepCase: true,
|
||||
longs: String,
|
||||
enums: String,
|
||||
defaults: true,
|
||||
oneofs: true,
|
||||
});
|
||||
const grpcObject = this.grpc.loadPackageDefinition(packageDefinition) as unknown as {
|
||||
grpc: {
|
||||
health: {
|
||||
v1: {
|
||||
Health: new (
|
||||
target: string,
|
||||
credentials: unknown
|
||||
) => {
|
||||
Check: (request: { service: string }, options: { deadline: Date }, callback: (err: unknown, response: unknown) => void) => void;
|
||||
close: () => void;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
const healthService = grpcObject.grpc.health.v1.Health;
|
||||
|
||||
let credentials;
|
||||
if (ignoreTlsErrors) {
|
||||
credentials = this.grpc.credentials.createSsl(null, null, null, {
|
||||
checkServerIdentity: () => undefined,
|
||||
});
|
||||
} else {
|
||||
credentials = this.grpc.credentials.createInsecure();
|
||||
}
|
||||
|
||||
const client = new healthService(target, credentials);
|
||||
|
||||
const TIMEOUT_MS = 10000;
|
||||
const deadline = new Date(Date.now() + TIMEOUT_MS);
|
||||
|
||||
const { response, responseTime, error } = await timeRequest<GrpcStatusPayload>(() => {
|
||||
return new Promise<GrpcStatusPayload>((resolve, reject) => {
|
||||
client.Check({ service: grpcServiceName }, { deadline }, (err: unknown, response: unknown) => {
|
||||
client.close();
|
||||
|
||||
if (err) {
|
||||
const grpcErr = err as { code?: number; details?: string; message?: string };
|
||||
const payload: GrpcStatusPayload = {
|
||||
grpcStatusCode: grpcErr.code ?? -1,
|
||||
grpcStatusName: this.getGrpcStatusName(grpcErr.code ?? -1),
|
||||
serviceName: grpcServiceName,
|
||||
servingStatus: "UNKNOWN",
|
||||
};
|
||||
const grpcError = new AppError({
|
||||
message: grpcErr.details || grpcErr.message || "gRPC error",
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
}) as AppError & { grpcPayload?: GrpcStatusPayload; grpcCode?: number };
|
||||
grpcError.grpcPayload = payload;
|
||||
grpcError.grpcCode = grpcErr.code;
|
||||
reject(grpcError);
|
||||
return;
|
||||
}
|
||||
|
||||
const resp = response as { status?: string } | undefined;
|
||||
const servingStatus = resp?.status ?? "UNKNOWN";
|
||||
resolve({
|
||||
grpcStatusCode: 0,
|
||||
grpcStatusName: "OK",
|
||||
serviceName: grpcServiceName,
|
||||
servingStatus,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const grpcError = error as AppError & { grpcPayload?: GrpcStatusPayload; grpcCode?: number };
|
||||
const payload = grpcError.grpcPayload;
|
||||
return {
|
||||
monitorId: id,
|
||||
teamId: teamId,
|
||||
type: type,
|
||||
status: false,
|
||||
code: grpcError.grpcCode ?? 5000,
|
||||
message: grpcError.message ?? "gRPC health check failed",
|
||||
responseTime,
|
||||
payload: payload ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
const grpcPayload = response as GrpcStatusPayload;
|
||||
const isServing = grpcPayload.servingStatus === "SERVING";
|
||||
|
||||
return {
|
||||
monitorId: id,
|
||||
teamId: teamId,
|
||||
type: type,
|
||||
status: isServing,
|
||||
code: isServing ? 200 : 5000,
|
||||
message: isServing ? `gRPC service healthy (${grpcPayload.servingStatus})` : `gRPC service unhealthy (${grpcPayload.servingStatus})`,
|
||||
responseTime,
|
||||
payload: grpcPayload,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const originalMessage = err instanceof Error ? err.message : String(err);
|
||||
throw new AppError({
|
||||
message: originalMessage || "Error performing gRPC health check",
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url, port: monitor.port, grpcServiceName: monitor.grpcServiceName },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { HardwareStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { HttpProvider } from "@/service/network/HttpProvider.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
export class HardwareProvider implements IStatusProvider<HardwareStatusPayload> {
|
||||
readonly type = "hardware";
|
||||
constructor(private httpProvider: HttpProvider) {}
|
||||
|
||||
supports(type: MonitorType) {
|
||||
return type === "hardware";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<HardwareStatusPayload>> {
|
||||
const { url } = monitor;
|
||||
try {
|
||||
if (!url) throw new Error("URL is required for Hardware monitor");
|
||||
return await this.httpProvider.handle<HardwareStatusPayload>(monitor);
|
||||
} catch (err: unknown) {
|
||||
throw new AppError({
|
||||
message: err instanceof Error ? err.message : "Error performing Hardware request",
|
||||
service: "HardwareProvider",
|
||||
method: "handle",
|
||||
details: { url: monitor.url },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { type Got, HTTPError, RequestError } from "got";
|
||||
import { IAdvancedMatcher } from "@/service/network/AdvancedMatcher.js";
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { HttpStatusPayload } from "@/types/network.js";
|
||||
import { MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Agent as HttpsAgent } from "https";
|
||||
import { Agent as HttpAgent } from "http";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { NETWORK_ERROR, isStatusUp } from "@/service/network/utils.js";
|
||||
import CacheableLookup from "cacheable-lookup";
|
||||
|
||||
export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
||||
readonly type = "http";
|
||||
|
||||
// Shared, pooled agents reused across every check
|
||||
private readonly httpAgent: HttpAgent;
|
||||
private readonly httpsAgent: HttpsAgent;
|
||||
private readonly httpsAgentInsecure: HttpsAgent;
|
||||
|
||||
constructor(
|
||||
private got: Got,
|
||||
private advancedMatcher: IAdvancedMatcher
|
||||
) {
|
||||
const cacheable = new CacheableLookup({ maxTtl: 300, errorTtl: 30 });
|
||||
this.got = got.extend({
|
||||
dnsCache: cacheable,
|
||||
timeout: {
|
||||
request: 30000,
|
||||
},
|
||||
retry: { limit: 1 },
|
||||
});
|
||||
|
||||
const agentOptions = { keepAlive: true, maxSockets: 256, maxFreeSockets: 256 };
|
||||
this.httpAgent = new HttpAgent(agentOptions);
|
||||
this.httpsAgent = new HttpsAgent({ ...agentOptions, rejectUnauthorized: true });
|
||||
this.httpsAgentInsecure = new HttpsAgent({ ...agentOptions, rejectUnauthorized: false });
|
||||
}
|
||||
|
||||
supports(type: MonitorType) {
|
||||
return type === "http";
|
||||
}
|
||||
|
||||
private buildResponse<T>(
|
||||
monitor: Monitor,
|
||||
opts: {
|
||||
body: string;
|
||||
contentType: string;
|
||||
statusCode: number;
|
||||
statusUp: boolean;
|
||||
message: string;
|
||||
responseTime: number;
|
||||
timings?: MonitorStatusResponse<T>["timings"];
|
||||
}
|
||||
): MonitorStatusResponse<T> {
|
||||
const { body, contentType, statusCode, statusUp, message, responseTime, timings } = opts;
|
||||
const isJson = contentType.includes("application/json");
|
||||
|
||||
if (monitor.jsonPath && !isJson) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: statusCode,
|
||||
message: "Response is not JSON",
|
||||
responseTime,
|
||||
timings,
|
||||
payload: body,
|
||||
};
|
||||
}
|
||||
|
||||
let payload: T | string;
|
||||
if (isJson) {
|
||||
try {
|
||||
payload = JSON.parse(body) as T;
|
||||
} catch {
|
||||
payload = body;
|
||||
}
|
||||
} else {
|
||||
payload = body;
|
||||
}
|
||||
|
||||
const matchResult = this.advancedMatcher.validate<T | string>(payload, monitor);
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: statusUp && matchResult.ok,
|
||||
code: statusCode,
|
||||
message: matchResult.ok ? message : matchResult.message,
|
||||
responseTime,
|
||||
timings,
|
||||
payload,
|
||||
extracted: matchResult.extracted,
|
||||
};
|
||||
}
|
||||
|
||||
private handleHttpError<T>(error: unknown, monitor: Monitor): MonitorStatusResponse<T> {
|
||||
if (error instanceof HTTPError || error instanceof RequestError) {
|
||||
const statusCode = error.response?.statusCode;
|
||||
const statusUp = isStatusUp(statusCode, monitor.customUpCodes);
|
||||
const responseTime = error.timings?.phases?.firstByte ?? error.timings?.phases?.total ?? 0;
|
||||
|
||||
if (!statusUp) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: statusCode ?? NETWORK_ERROR,
|
||||
message: error.message,
|
||||
responseTime,
|
||||
timings: error.timings,
|
||||
payload: null as T,
|
||||
};
|
||||
}
|
||||
|
||||
return this.buildResponse<T>(monitor, {
|
||||
body: (error.response?.body ?? "") as string,
|
||||
contentType: error.response?.headers?.["content-type"] || "",
|
||||
statusCode: statusCode ?? NETWORK_ERROR,
|
||||
statusUp,
|
||||
message: error.message,
|
||||
responseTime,
|
||||
timings: error.timings,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
responseTime: 0,
|
||||
payload: null as T,
|
||||
};
|
||||
}
|
||||
|
||||
async handle<T>(monitor: Monitor): Promise<MonitorStatusResponse<T>> {
|
||||
const { url, secret, ignoreTlsErrors } = monitor;
|
||||
|
||||
if (!url) {
|
||||
throw new Error("URL is required for HTTP monitor");
|
||||
}
|
||||
|
||||
const options: Record<string, unknown> = {
|
||||
headers: monitor.secret ? { Authorization: `Bearer ${secret}` } : undefined,
|
||||
};
|
||||
|
||||
options.agent = {
|
||||
http: this.httpAgent,
|
||||
https: ignoreTlsErrors ? this.httpsAgentInsecure : this.httpsAgent,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await this.got<string>(url, options);
|
||||
const statusUp = isStatusUp(response.statusCode, monitor.customUpCodes);
|
||||
|
||||
return this.buildResponse<T>(monitor, {
|
||||
body: response.body,
|
||||
contentType: response.headers["content-type"] || "",
|
||||
statusCode: response.statusCode,
|
||||
statusUp,
|
||||
message: response.statusMessage ?? "OK",
|
||||
responseTime: response.timings.phases.firstByte ?? 0,
|
||||
timings: response.timings,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
return this.handleHttpError(error, monitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { MonitorStatusResponse } from "@/types/network.js";
|
||||
|
||||
export interface IStatusProvider<T> {
|
||||
type: string;
|
||||
supports: (type: MonitorType) => boolean;
|
||||
handle(monitor: Monitor): Promise<MonitorStatusResponse<T>>;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { MonitorStatusResponse, PageSpeedStatusPayload } from "@/types/network.js";
|
||||
import { Monitor, MonitorType, DefaultPageSpeedStrategy } from "@/domain/monitors/monitor.types.js";
|
||||
import { HttpProvider } from "@/service/network/HttpProvider.js";
|
||||
import { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
export class PageSpeedProvider implements IStatusProvider<PageSpeedStatusPayload> {
|
||||
readonly type = "pagespeed";
|
||||
constructor(
|
||||
private httpProvider: HttpProvider,
|
||||
private settingsService: ISettingsService,
|
||||
private logger: ILogger
|
||||
) {}
|
||||
|
||||
supports(type: MonitorType) {
|
||||
return type === "pagespeed";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<PageSpeedStatusPayload>> {
|
||||
const { url, strategy } = monitor;
|
||||
try {
|
||||
if (!url) throw new Error("URL is required for PageSpeed monitor");
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
const apiKey = dbSettings?.pagespeedApiKey;
|
||||
const resolvedStrategy = strategy ?? DefaultPageSpeedStrategy;
|
||||
let pageSpeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(
|
||||
url
|
||||
)}&strategy=${encodeURIComponent(resolvedStrategy)}&category=seo&category=accessibility&category=best-practices&category=performance`;
|
||||
|
||||
if (apiKey) {
|
||||
pageSpeedUrl += `&key=${apiKey}`;
|
||||
} else {
|
||||
this.logger.warn({
|
||||
message: "PageSpeed API key not found, performance may be throttled",
|
||||
service: "PageSpeedProvider",
|
||||
method: "handle",
|
||||
details: { url },
|
||||
});
|
||||
}
|
||||
|
||||
return await this.httpProvider.handle<PageSpeedStatusPayload>({
|
||||
...monitor,
|
||||
url: pageSpeedUrl,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
throw new AppError({
|
||||
message: err instanceof Error ? err.message : "Error performing PageSpeed request",
|
||||
service: "PageSpeedProvider",
|
||||
method: "handle",
|
||||
details: { url: monitor.url },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { PingStatusPayload } from "@/types/network.js";
|
||||
import { IStatusProvider } from "./IStatusProvider.js";
|
||||
import { MonitorType, Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import { MonitorStatusResponse } from "@/types/network.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import ping from "ping";
|
||||
import { timeRequest } from "@/service/network/utils.js";
|
||||
const SERVICE_NAME = "PingProvider";
|
||||
|
||||
type Ping = typeof ping;
|
||||
|
||||
export class PingProvider implements IStatusProvider<PingStatusPayload> {
|
||||
readonly type = "ping";
|
||||
|
||||
constructor(private ping: Ping) {}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "ping";
|
||||
}
|
||||
|
||||
private sanitizeHost(url: string): string {
|
||||
return url
|
||||
.replace(/^https?:\/\//, "")
|
||||
.replace(/\/.*$/, "")
|
||||
.replace(/:.*/, "");
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<PingStatusPayload>> {
|
||||
try {
|
||||
if (!monitor.url) {
|
||||
throw new Error("URL is required for ping monitor");
|
||||
}
|
||||
|
||||
const sanitizedHost = this.sanitizeHost(monitor.url);
|
||||
const { response, error } = await timeRequest<PingStatusPayload>(() => this.ping.promise.probe(sanitizedHost));
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
throw new Error(`No response from ping for host: ${sanitizedHost}`);
|
||||
}
|
||||
|
||||
const responseTime = typeof response.time === "number" ? response.time : parseFloat(String(response.time)) || 0;
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: response.alive ?? false,
|
||||
code: response.alive ? 200 : 5000,
|
||||
message: response.alive ? "Success" : "Ping failed",
|
||||
responseTime,
|
||||
payload: response,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new AppError({
|
||||
message,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { PortStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { NETWORK_ERROR, timeRequest } from "@/service/network/utils.js";
|
||||
import * as net from "net";
|
||||
type NetType = typeof net;
|
||||
|
||||
const SERVICE_NAME = "PortProvider";
|
||||
|
||||
export class PortProvider implements IStatusProvider<PortStatusPayload> {
|
||||
readonly type = "port";
|
||||
|
||||
constructor(private net: NetType) {}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "port";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<PortStatusPayload>> {
|
||||
try {
|
||||
const { url, port } = monitor;
|
||||
if (!url || !port) {
|
||||
throw new Error("URL and port are required for port monitoring");
|
||||
}
|
||||
|
||||
const { responseTime, error } = await timeRequest(async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = this.net.createConnection(
|
||||
{
|
||||
host: url,
|
||||
port,
|
||||
},
|
||||
() => {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
resolve({ success: true });
|
||||
}
|
||||
);
|
||||
|
||||
socket.setTimeout(5000);
|
||||
socket.on("timeout", () => {
|
||||
socket.destroy();
|
||||
reject(new Error("Connection timeout"));
|
||||
});
|
||||
|
||||
socket.on("error", (err: unknown) => {
|
||||
socket.destroy();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
});
|
||||
if (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "Port check failed";
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: errorMessage,
|
||||
responseTime: responseTime,
|
||||
timings: undefined,
|
||||
payload: { success: false },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: true,
|
||||
code: 200,
|
||||
message: "Port check successful",
|
||||
responseTime: responseTime,
|
||||
timings: undefined,
|
||||
payload: { success: true },
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const originalMessage = err instanceof Error ? err.message : String(err);
|
||||
throw new AppError({
|
||||
message: originalMessage || "Error performing port check",
|
||||
status: 500,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url, port: monitor.port },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { IStatusProvider } from "@/service/network/IStatusProvider.js";
|
||||
import { WebSocketStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Monitor, MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { NETWORK_ERROR, timeRequest } from "@/service/network/utils.js";
|
||||
import type WebSocket from "ws";
|
||||
|
||||
type WebSocketConstructor = typeof WebSocket;
|
||||
|
||||
const SERVICE_NAME = "WebSocketProvider";
|
||||
const TIMEOUT_MS = 10000;
|
||||
|
||||
export class WebSocketProvider implements IStatusProvider<WebSocketStatusPayload> {
|
||||
readonly type = "websocket";
|
||||
|
||||
constructor(private WS: WebSocketConstructor) {}
|
||||
|
||||
supports(type: MonitorType): boolean {
|
||||
return type === "websocket";
|
||||
}
|
||||
|
||||
async handle(monitor: Monitor): Promise<MonitorStatusResponse<WebSocketStatusPayload>> {
|
||||
try {
|
||||
const { url } = monitor;
|
||||
if (!url) {
|
||||
throw new Error("URL is required for WebSocket monitoring");
|
||||
}
|
||||
|
||||
const { responseTime, error } = await timeRequest(async () => {
|
||||
return new Promise<{ connected: boolean }>((resolve, reject) => {
|
||||
const options: WebSocket.ClientOptions = {};
|
||||
if (monitor.ignoreTlsErrors) {
|
||||
options.rejectUnauthorized = false;
|
||||
}
|
||||
|
||||
const ws = new this.WS(url, options);
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
ws.close();
|
||||
reject(new Error("WebSocket connection timeout"));
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
ws.on("open", () => {
|
||||
clearTimeout(timeout);
|
||||
ws.close();
|
||||
resolve({ connected: true });
|
||||
});
|
||||
|
||||
ws.on("error", (err: unknown) => {
|
||||
clearTimeout(timeout);
|
||||
ws.close();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "WebSocket check failed";
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: NETWORK_ERROR,
|
||||
message: errorMessage,
|
||||
responseTime: responseTime,
|
||||
timings: undefined,
|
||||
payload: { connected: false },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: true,
|
||||
code: 200,
|
||||
message: "WebSocket check successful",
|
||||
responseTime: responseTime,
|
||||
timings: undefined,
|
||||
payload: { connected: true },
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const originalMessage = err instanceof Error ? err.message : String(err);
|
||||
throw new AppError({
|
||||
message: originalMessage || "Error performing WebSocket check",
|
||||
status: 500,
|
||||
service: SERVICE_NAME,
|
||||
method: "handle",
|
||||
details: { url: monitor.url },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { HttpStatusCode } from "@/domain/monitors/monitor.types.js";
|
||||
|
||||
export const timeRequest = async <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, error: null };
|
||||
} catch (error) {
|
||||
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
|
||||
return { response: null, responseTime: elapsedMs, error };
|
||||
}
|
||||
};
|
||||
|
||||
export const NETWORK_ERROR = 5000;
|
||||
export const PING_ERROR = 5001;
|
||||
|
||||
export const isStatusUp = (statusCode: number | undefined, customUpCodes: HttpStatusCode[] = []): boolean => {
|
||||
if (statusCode === undefined) return false;
|
||||
return (statusCode >= 200 && statusCode < 300) || customUpCodes.includes(statusCode);
|
||||
};
|
||||
Reference in new issue
Block a user