Files
Checkmate/server/src/service/infrastructure/networkService.ts
T

584 lines
17 KiB
TypeScript
Raw Normal View History

2026-01-15 23:45:40 +00:00
import { HTTPError, RequestError } from "got";
import type { Got, Response } from "got";
2026-03-03 18:50:10 +00:00
import type {
Monitor,
MonitorStatusResponse,
GrpcStatusPayload,
PageSpeedStatusPayload,
HttpStatusPayload,
HardwareStatusPayload,
2026-03-03 19:34:28 +00:00
PingStatusPayload,
DockerStatusPayload,
PortStatusPayload,
GameStatusPayload,
2026-03-03 18:50:10 +00:00
} from "@/types/index.js";
2026-02-24 19:36:45 +00:00
import type { AxiosStatic } from "axios";
2026-02-23 10:19:42 +05:30
import { AppError } from "@/utils/AppError.js";
import path from "path";
import { fileURLToPath } from "url";
2026-03-04 23:24:48 +00:00
import { MonitorStatusResponseOverrides } from "@/types/index.js";
2026-01-15 22:33:25 +00:00
2025-10-28 22:41:05 -07:00
import CacheableLookup from "cacheable-lookup";
2026-02-24 19:19:32 +00:00
import { ISettingsService } from "../system/settingsService.js";
import { ILogger } from "@/utils/logger.js";
2026-03-04 23:24:48 +00:00
import { IStatusProvider } from "./network/IStatusProvider.js";
2025-04-20 11:29:53 -07:00
const SERVICE_NAME = "NetworkService";
2025-08-15 16:04:43 -07:00
2026-01-15 23:45:40 +00:00
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;
2026-03-03 19:34:28 +00:00
requestStatus(
monitor: Monitor
): Promise<
MonitorStatusResponse<
| PingStatusPayload
| HttpStatusPayload
| PageSpeedStatusPayload
| HardwareStatusPayload
| DockerStatusPayload
| PortStatusPayload
| GameStatusPayload
| GrpcStatusPayload
>
>;
requestWebhook(
type: string,
url: string,
body: unknown
): Promise<{ type: string; status: boolean; code: number; message: string; payload?: unknown }>;
2026-01-15 23:45:40 +00:00
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 {
2025-04-20 11:29:53 -07:00
static SERVICE_NAME = SERVICE_NAME;
2026-01-15 22:33:25 +00:00
private TYPE_PING: string;
private TYPE_HTTP: string;
private TYPE_PAGESPEED: string;
private TYPE_HARDWARE: string;
private TYPE_DOCKER: string;
private TYPE_PORT: string;
private TYPE_GAME: string;
private TYPE_GRPC: string;
2026-01-15 22:33:25 +00:00
private SERVICE_NAME: string;
private NETWORK_ERROR: number;
private PING_ERROR: number;
2026-02-24 19:36:45 +00:00
private axios: AxiosStatic;
2026-01-15 22:33:25 +00:00
private got: Got;
2026-03-03 19:34:28 +00:00
private https: typeof import("https");
private jmespath: { search: (data: unknown, expression: string) => unknown };
private GameDig: { query: (options: { type: string; host: string; port?: number }) => Promise<{ ping?: number } & { [key: string]: unknown }> };
private ping: typeof import("ping");
2026-02-24 19:36:45 +00:00
private logger: ILogger;
2026-03-03 19:34:28 +00:00
private Docker: typeof import("dockerode");
private net: typeof import("net");
2026-02-24 19:36:45 +00:00
private settingsService: ISettingsService;
2026-03-03 19:34:28 +00:00
private grpc: typeof import("@grpc/grpc-js");
private protoLoader: typeof import("@grpc/proto-loader");
2026-01-15 22:33:25 +00:00
2026-03-04 23:24:48 +00:00
// New providers
private pingProvider;
private httpProvider;
2026-03-05 17:54:16 +00:00
private pageSpeedProvider;
private hardwareProvider;
2026-03-05 18:19:03 +00:00
private dockerProvider;
2026-03-05 18:35:19 +00:00
private portProvider;
2026-03-05 18:48:19 +00:00
private gameProvider;
2026-03-04 23:24:48 +00:00
2026-01-15 23:45:40 +00:00
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;
}
2026-03-03 19:34:28 +00:00
return { ...statusResponse, ...(overrides ?? {}) } as MonitorStatusResponse<T>;
2026-01-15 23:45:40 +00:00
}
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 ?? {}),
2026-03-03 19:34:28 +00:00
} as MonitorStatusResponse<T>;
2026-01-15 23:45:40 +00:00
};
2026-02-24 19:19:32 +00:00
constructor(
2026-02-24 19:36:45 +00:00
axios: AxiosStatic,
2026-02-24 19:19:32 +00:00
got: Got,
2026-03-03 19:34:28 +00:00
https: typeof import("https"),
jmespath: { search: (data: unknown, expression: string) => unknown },
GameDig: { query: (options: { type: string; host: string; port?: number }) => Promise<{ ping?: number } & { [key: string]: unknown }> },
ping: typeof import("ping"),
2026-02-24 19:19:32 +00:00
logger: ILogger,
2026-03-03 19:34:28 +00:00
Docker: typeof import("dockerode"),
net: typeof import("net"),
2026-02-26 17:32:11 +00:00
settingsService: ISettingsService,
2026-03-03 19:34:28 +00:00
grpc: typeof import("@grpc/grpc-js"),
2026-03-04 23:24:48 +00:00
protoLoader: typeof import("@grpc/proto-loader"),
// New providers
pingProvider: IStatusProvider<PingStatusPayload>,
2026-03-05 17:54:16 +00:00
httpProvider: IStatusProvider<HttpStatusPayload>,
pagespeedProvider: IStatusProvider<PageSpeedStatusPayload>,
2026-03-05 18:19:03 +00:00
hardwareProvider: IStatusProvider<HardwareStatusPayload>,
2026-03-05 18:35:19 +00:00
dockerProvider: IStatusProvider<DockerStatusPayload>,
2026-03-05 18:48:19 +00:00
portProvider: IStatusProvider<PortStatusPayload>,
gameProvider: IStatusProvider<GameStatusPayload>
2026-02-24 19:19:32 +00:00
) {
2025-04-20 11:29:53 -07:00
this.TYPE_PING = "ping";
this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed";
this.TYPE_HARDWARE = "hardware";
this.TYPE_DOCKER = "docker";
this.TYPE_PORT = "port";
2025-08-02 02:04:06 +03:00
this.TYPE_GAME = "game";
this.TYPE_GRPC = "grpc";
2025-04-20 11:29:53 -07:00
this.SERVICE_NAME = SERVICE_NAME;
this.NETWORK_ERROR = 5000;
this.PING_ERROR = 5001;
this.axios = axios;
2025-08-15 16:04:43 -07:00
this.https = https;
this.jmespath = jmespath;
this.GameDig = GameDig;
2025-04-20 11:29:53 -07:00
this.ping = ping;
this.logger = logger;
this.Docker = Docker;
this.net = net;
this.settingsService = settingsService;
this.grpc = grpc;
this.protoLoader = protoLoader;
2025-10-28 22:41:05 -07:00
2026-03-04 23:24:48 +00:00
// New providers
this.pingProvider = pingProvider;
this.httpProvider = httpProvider;
2026-03-05 17:54:16 +00:00
this.pageSpeedProvider = pagespeedProvider;
this.hardwareProvider = hardwareProvider;
2026-03-05 18:19:03 +00:00
this.dockerProvider = dockerProvider;
2026-03-05 18:35:19 +00:00
this.portProvider = portProvider;
2026-03-05 18:48:19 +00:00
this.gameProvider = gameProvider;
2025-10-28 22:41:05 -07:00
const cacheable = new CacheableLookup();
this.got = got.extend({
dnsCache: cacheable,
timeout: {
request: 30000,
},
retry: { limit: 1 },
});
2025-04-20 11:29:53 -07:00
}
2026-01-15 23:45:40 +00:00
get serviceName(): string {
return NetworkService.SERVICE_NAME;
}
2025-08-15 16:04:43 -07:00
// Helper functions
2026-01-15 23:45:40 +00:00
private async timeRequest<T>(operation: () => Promise<T>): Promise<{ response: T | null; responseTime: number; error: unknown }> {
2025-08-15 16:04:43 -07:00
const start = process.hrtime.bigint();
2025-04-20 11:29:53 -07:00
try {
const response = await operation();
2025-10-09 09:33:14 -07:00
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
2026-01-15 23:45:40 +00:00
return { response, responseTime: elapsedMs, error: null };
2025-04-20 11:29:53 -07:00
} catch (error) {
2025-10-09 09:33:14 -07:00
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
return { response: null, responseTime: elapsedMs, error };
2025-08-15 16:04:43 -07:00
}
}
// Main entry point
2026-03-03 19:34:28 +00:00
async requestStatus(
monitor: Monitor
): Promise<
MonitorStatusResponse<
| PingStatusPayload
| HttpStatusPayload
| PageSpeedStatusPayload
| HardwareStatusPayload
| DockerStatusPayload
| PortStatusPayload
| GameStatusPayload
| GrpcStatusPayload
>
> {
2025-08-15 16:04:43 -07:00
const type = monitor?.type || "unknown";
switch (type) {
case this.TYPE_PING:
2026-03-04 23:24:48 +00:00
return await this.pingProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_HTTP:
2026-03-04 23:24:48 +00:00
return await this.httpProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_PAGESPEED:
2026-03-05 17:54:16 +00:00
return await this.pageSpeedProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_HARDWARE:
2026-03-05 18:19:03 +00:00
return await this.hardwareProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_DOCKER:
2026-03-05 18:19:03 +00:00
return await this.dockerProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_PORT:
2026-03-05 18:35:19 +00:00
return await this.portProvider.handle(monitor);
2025-08-15 16:04:43 -07:00
case this.TYPE_GAME:
2026-03-05 18:48:19 +00:00
return await this.gameProvider.handle(monitor);
case this.TYPE_GRPC:
return await this.requestGrpc(monitor);
2025-08-15 16:04:43 -07:00
default:
2026-01-15 23:45:40 +00:00
return this.handleUnsupportedType(type);
2025-04-20 11:29:53 -07:00
}
}
2026-03-03 19:34:28 +00:00
private async requestGrpc(monitor: Monitor): Promise<MonitorStatusResponse<GrpcStatusPayload>> {
try {
const { url, port, ignoreTlsErrors } = monitor;
const grpcServiceName = monitor.grpcServiceName || "";
if (!url) {
2026-02-23 10:19:42 +05:30
throw new AppError({ message: "Monitor host is required", service: this.SERVICE_NAME, method: "requestGrpc" });
}
if (!port) {
2026-02-23 10:19:42 +05:30
throw new AppError({ message: "Monitor port is required", service: this.SERVICE_NAME, method: "requestGrpc" });
}
const target = `${url}:${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,
});
2026-03-03 19:34:28 +00:00
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);
2026-03-03 19:34:28 +00:00
const grpcResponse = this.buildStatusResponse<GrpcStatusPayload>({
monitor,
overrides: {
status: false,
code: this.NETWORK_ERROR,
message: "gRPC health check not executed",
},
});
const { response, responseTime, error } = await this.timeRequest<GrpcStatusPayload>(() => {
return new Promise<GrpcStatusPayload>((resolve, reject) => {
2026-03-03 19:34:28 +00:00
client.Check({ service: grpcServiceName }, { deadline }, (err: unknown, response: unknown) => {
client.close();
if (err) {
2026-03-03 19:34:28 +00:00
const grpcErr = err as { code?: number; details?: string; message?: string };
const payload: GrpcStatusPayload = {
2026-03-03 19:34:28 +00:00
grpcStatusCode: grpcErr.code ?? -1,
grpcStatusName: this.getGrpcStatusName(grpcErr.code ?? -1),
serviceName: grpcServiceName,
servingStatus: "UNKNOWN",
};
2026-03-03 19:34:28 +00:00
const grpcError = new AppError({
message: grpcErr.details || grpcErr.message || "gRPC error",
service: this.SERVICE_NAME,
method: "requestGrpc",
}) as AppError & { grpcPayload?: GrpcStatusPayload; grpcCode?: number };
grpcError.grpcPayload = payload;
grpcError.grpcCode = grpcErr.code;
reject(grpcError);
return;
}
2026-03-03 19:34:28 +00:00
const resp = response as { status?: string } | undefined;
const servingStatus = resp?.status ?? "UNKNOWN";
resolve({
grpcStatusCode: 0,
grpcStatusName: "OK",
serviceName: grpcServiceName,
servingStatus,
});
});
});
});
if (error) {
2026-03-03 19:34:28 +00:00
const grpcError = error as AppError & { grpcPayload?: GrpcStatusPayload; grpcCode?: number };
const payload = grpcError.grpcPayload;
grpcResponse.status = false;
grpcResponse.code = grpcError.grpcCode ?? this.NETWORK_ERROR;
2026-03-03 19:34:28 +00:00
grpcResponse.message = grpcError.message ?? "gRPC health check failed";
grpcResponse.responseTime = responseTime;
2026-03-03 19:34:28 +00:00
grpcResponse.payload = payload ?? null;
return grpcResponse;
}
const grpcPayload = response as GrpcStatusPayload;
const isServing = grpcPayload.servingStatus === "SERVING";
grpcResponse.status = isServing;
grpcResponse.code = isServing ? 200 : this.NETWORK_ERROR;
grpcResponse.message = isServing
? `gRPC service healthy (${grpcPayload.servingStatus})`
: `gRPC service unhealthy (${grpcPayload.servingStatus})`;
grpcResponse.responseTime = responseTime;
grpcResponse.payload = grpcPayload;
return grpcResponse;
2026-03-03 19:34:28 +00:00
} catch (err: unknown) {
const originalMessage = err instanceof Error ? err.message : String(err);
throw new AppError({
message: originalMessage || "Error performing gRPC health check",
service: this.SERVICE_NAME,
method: "requestGrpc",
details: { url: monitor.url, port: monitor.port, grpcServiceName: monitor.grpcServiceName },
});
}
}
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";
}
2026-01-15 23:45:40 +00:00
private async handleUnsupportedType(type: string): Promise<MonitorStatusResponse> {
return {
monitorId: "unknown",
teamId: "unknown",
type: "unknown",
status: false,
code: this.NETWORK_ERROR,
message: `Unsupported type: ${type}`,
};
2025-04-20 11:29:53 -07:00
}
2025-08-15 16:04:43 -07:00
// Other network requests unrelated to monitoring:
2026-03-03 19:34:28 +00:00
async requestWebhook(type: string, url: string, body: unknown) {
2025-04-20 11:29:53 -07:00
try {
2025-06-19 12:11:43 +08:00
const response = await this.axios.post(url, body, {
2025-04-20 11:29:53 -07:00
headers: {
"Content-Type": "application/json",
},
});
return {
type: "webhook",
status: true,
code: response.status,
2025-06-19 12:11:43 +08:00
message: `Successfully sent ${type} notification`,
2025-04-20 11:29:53 -07:00
payload: response.data,
};
2026-03-03 19:34:28 +00:00
} catch (err: unknown) {
2025-04-20 11:29:53 -07:00
this.logger.warn({
2026-03-03 19:34:28 +00:00
message: err instanceof Error ? err.message : String(err),
2025-04-20 11:29:53 -07:00
service: this.SERVICE_NAME,
method: "requestWebhook",
});
2026-03-03 19:34:28 +00:00
if (err && typeof err === "object" && "response" in err) {
const axiosError = err as { response?: { status?: number; data?: unknown } };
return {
type: "webhook",
status: false,
code: axiosError.response?.status ?? this.NETWORK_ERROR,
message: `Failed to send ${type} notification`,
payload: axiosError.response?.data,
};
}
2025-04-20 11:29:53 -07:00
return {
type: "webhook",
status: false,
2026-03-03 19:34:28 +00:00
code: this.NETWORK_ERROR,
2025-06-19 12:11:43 +08:00
message: `Failed to send ${type} notification`,
2025-04-20 11:29:53 -07:00
};
}
}
2026-01-15 22:33:25 +00:00
async requestPagerDuty({ message, routingKey, monitorUrl }: { message: string; routingKey: string; monitorUrl: string }) {
2025-06-10 13:44:15 +08:00
try {
const response = await this.axios.post(`https://events.pagerduty.com/v2/enqueue`, {
routing_key: routingKey,
event_action: "trigger",
payload: {
summary: message,
severity: "critical",
source: monitorUrl,
timestamp: new Date().toISOString(),
},
});
if (response?.data?.status !== "success") return false;
return true;
2026-03-03 19:34:28 +00:00
} catch (err: unknown) {
const originalMessage = err instanceof Error ? err.message : String(err);
throw new AppError({
message: originalMessage || "Error sending PagerDuty notification",
service: this.SERVICE_NAME,
method: "requestPagerDuty",
details: {
responseData: err && typeof err === "object" && "response" in err ? (err as { response?: { data?: unknown } }).response?.data : undefined,
},
});
2025-06-10 13:44:15 +08:00
}
}
2026-01-15 22:33:25 +00:00
async requestMatrix({
homeserverUrl,
accessToken,
roomId,
message,
}: {
homeserverUrl: string;
accessToken: string;
roomId: string;
message: string;
}) {
try {
const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message?access_token=${accessToken}`;
const body = {
msgtype: "m.text",
body: message,
format: "org.matrix.custom.html",
formatted_body: message,
};
const response = await this.axios.post(url, body, {
headers: {
"Content-Type": "application/json",
},
});
return {
status: true,
code: response.status,
message: "Successfully sent Matrix notification",
};
2026-03-03 19:34:28 +00:00
} catch (err: unknown) {
if (err instanceof Error) {
this.logger.warn({
message: err.message,
service: this.SERVICE_NAME,
method: "requestMatrix",
});
if (err && typeof err === "object" && "response" in err) {
const axiosError = err as { response?: { status?: number; data?: unknown } };
return {
status: false,
code: axiosError.response?.status || this.NETWORK_ERROR,
message: "Failed to send Matrix notification",
payload: axiosError.response?.data,
};
}
}
this.logger.warn({
2026-03-03 19:34:28 +00:00
message: String(err),
service: this.SERVICE_NAME,
method: "requestMatrix",
});
return {
status: false,
2026-03-03 19:34:28 +00:00
code: this.NETWORK_ERROR,
message: "Failed to send Matrix notification",
};
}
}
2025-04-20 11:29:53 -07:00
}
export default NetworkService;