typing
This commit is contained in:
1 parent
ed80837810
commit
0f764ca084
12 files changed
+431
-116
No files matched your search
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user