typing
This commit is contained in:
1 parent
ed80837810
commit
0f764ca084
12 files changed
+431
-116
No files matched your search
@@ -155,7 +155,7 @@ export const initializeServices = async ({
|
||||
|
||||
// Repositories
|
||||
const monitorsRepository = new MongoMonitorsRepository();
|
||||
const checksRepository = new MongoChecksRepository();
|
||||
const checksRepository = new MongoChecksRepository(logger);
|
||||
const monitorStatsRepository = new MongoMonitorStatsRepository();
|
||||
const statusPagesRepository = new MongoStatusPagesRepository();
|
||||
|
||||
|
||||
@@ -11,8 +11,7 @@ import type {
|
||||
CheckMemoryInfo,
|
||||
CheckMetadata,
|
||||
CheckNetworkInterfaceInfo,
|
||||
CheckTimings,
|
||||
CheckTimingPhases,
|
||||
GotTimings,
|
||||
ILighthouseAudit,
|
||||
} from "@/types/check.js";
|
||||
|
||||
@@ -35,7 +34,7 @@ interface CheckDocument extends CheckDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
const timingPhasesSchema = new Schema<CheckTimingPhases>(
|
||||
const timingPhasesSchema = new Schema<GotTimings["phases"]>(
|
||||
{
|
||||
wait: { type: Number, default: 0 },
|
||||
dns: { type: Number, default: 0 },
|
||||
@@ -49,7 +48,7 @@ const timingPhasesSchema = new Schema<CheckTimingPhases>(
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const timingsSchema = new Schema<CheckTimings>(
|
||||
const timingsSchema = new Schema<GotTimings>(
|
||||
{
|
||||
start: { type: Number, default: 0 },
|
||||
socket: { type: Number, default: 0 },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Check, CheckAudits, MonitorType } from "@/types/index.js";
|
||||
import type { Check, CheckAudits, MonitorStatusResponse, MonitorType } from "@/types/index.js";
|
||||
import type { LatestChecksMap } from "@/repositories/checks/MongoChecksRepistory.js";
|
||||
|
||||
export interface PageSpeedChecksResult {
|
||||
@@ -55,6 +55,7 @@ export interface UptimeChecksResult {
|
||||
|
||||
export interface IChecksRepository {
|
||||
// create
|
||||
buildCheck(status: MonitorStatusResponse, type: MonitorType): Check;
|
||||
// single fetch
|
||||
// collection fetch
|
||||
findLatestChecksByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap>;
|
||||
|
||||
@@ -10,18 +10,29 @@ import type {
|
||||
CheckMemoryInfo,
|
||||
CheckMetadata,
|
||||
CheckNetworkInterfaceInfo,
|
||||
CheckTimings,
|
||||
GotTimings,
|
||||
MonitorStatusResponse,
|
||||
MonitorType,
|
||||
} from "@/types/index.js";
|
||||
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
|
||||
import { CheckModel, type CheckDocument } from "@/db/models/index.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
const SERVICE_NAME = "StatusService";
|
||||
|
||||
export type LatestChecksMap = Record<string, Check[]>;
|
||||
type DateRange = { start: Date; end: Date };
|
||||
type HardwareAggregateData = { latestCheck: CheckDocument | null; totalChecks: number };
|
||||
type HardwareUpChecks = { totalChecks: number };
|
||||
|
||||
class MongoChecksRepository implements IChecksRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private logger: any;
|
||||
constructor(logger: any) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
private toEntity = (doc: CheckDocument): Check => {
|
||||
const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => {
|
||||
if (!value) {
|
||||
@@ -44,7 +55,7 @@ class MongoChecksRepository implements IChecksRepository {
|
||||
return toDateString(value);
|
||||
};
|
||||
|
||||
const mapTimings = (timings?: CheckTimings): CheckTimings => {
|
||||
const mapTimings = (timings?: GotTimings): GotTimings => {
|
||||
const phases = timings?.phases ?? {
|
||||
wait: 0,
|
||||
dns: 0,
|
||||
@@ -176,6 +187,102 @@ class MongoChecksRepository implements IChecksRepository {
|
||||
};
|
||||
};
|
||||
|
||||
buildCheck = (
|
||||
statusResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>
|
||||
) => {
|
||||
const {
|
||||
monitorId,
|
||||
teamId,
|
||||
type,
|
||||
status,
|
||||
responseTime,
|
||||
code,
|
||||
message,
|
||||
payload,
|
||||
first_byte_took,
|
||||
body_read_took,
|
||||
dns_took,
|
||||
conn_took,
|
||||
connect_took,
|
||||
tls_took,
|
||||
timings,
|
||||
} = statusResponse;
|
||||
|
||||
const check: any = {
|
||||
metadata: {
|
||||
monitorId,
|
||||
teamId,
|
||||
type,
|
||||
},
|
||||
status,
|
||||
statusCode: code,
|
||||
responseTime,
|
||||
timings: timings || {},
|
||||
message,
|
||||
first_byte_took,
|
||||
body_read_took,
|
||||
dns_took,
|
||||
conn_took,
|
||||
connect_took,
|
||||
tls_took,
|
||||
};
|
||||
|
||||
if (type === "pagespeed") {
|
||||
const pageSpeedPayload = payload as PageSpeedStatusPayload | undefined;
|
||||
if (!pageSpeedPayload) {
|
||||
this.logger.warn({
|
||||
message: "Failed to build check",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildCheck",
|
||||
details: "empty payload",
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
const categories = pageSpeedPayload.lighthouseResult?.categories ?? {};
|
||||
const audits = pageSpeedPayload.lighthouseResult?.audits ?? {};
|
||||
const mapAudit = (audit: any) => {
|
||||
if (!audit || typeof audit !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
id: audit.id,
|
||||
title: audit.title,
|
||||
score: typeof audit.score === "number" ? audit.score : (audit.score ?? null),
|
||||
displayValue: audit.displayValue,
|
||||
numericValue: typeof audit.numericValue === "number" ? audit.numericValue : undefined,
|
||||
numericUnit: audit.numericUnit,
|
||||
};
|
||||
};
|
||||
check.accessibility = (categories?.accessibility?.score || 0) * 100;
|
||||
check.bestPractices = (categories?.["best-practices"]?.score || 0) * 100;
|
||||
check.seo = (categories?.seo?.score || 0) * 100;
|
||||
check.performance = (categories?.performance?.score || 0) * 100;
|
||||
check.audits = {
|
||||
cls: mapAudit(audits?.["cumulative-layout-shift"]),
|
||||
si: mapAudit(audits?.["speed-index"]),
|
||||
fcp: mapAudit(audits?.["first-contentful-paint"]),
|
||||
lcp: mapAudit(audits?.["largest-contentful-paint"]),
|
||||
tbt: mapAudit(audits?.["total-blocking-time"]),
|
||||
};
|
||||
}
|
||||
|
||||
if (type === "hardware") {
|
||||
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 = errorsSource ?? [];
|
||||
check.capture = hardwarePayload?.capture ?? {};
|
||||
check.net = net ?? {};
|
||||
}
|
||||
return check;
|
||||
};
|
||||
|
||||
findLatestChecksByMonitorIds = async (monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap> => {
|
||||
if (monitorIds.length === 0) {
|
||||
return {};
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export * from "@/service/business/monitorService.js";
|
||||
export * from "@/service/infrastructure/networkService.js";
|
||||
@@ -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;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { MonitorType } from "@/types/index.js";
|
||||
import type { Response } from "got";
|
||||
export type GotTimings = Response["timings"];
|
||||
|
||||
export interface CheckMetadata {
|
||||
monitorId: string;
|
||||
@@ -6,29 +8,6 @@ export interface CheckMetadata {
|
||||
type: MonitorType;
|
||||
}
|
||||
|
||||
export interface CheckTimingPhases {
|
||||
wait: number;
|
||||
dns: number;
|
||||
tcp: number;
|
||||
tls: number;
|
||||
request: number;
|
||||
firstByte: number;
|
||||
download: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface CheckTimings {
|
||||
start: number;
|
||||
socket: number;
|
||||
lookup: number;
|
||||
connect: number;
|
||||
secureConnect: number;
|
||||
upload: number;
|
||||
response: number;
|
||||
end: number;
|
||||
phases: CheckTimingPhases;
|
||||
}
|
||||
|
||||
export interface CheckCpuInfo {
|
||||
physical_core: number;
|
||||
logical_core: number;
|
||||
@@ -107,7 +86,7 @@ export interface Check {
|
||||
metadata: CheckMetadata;
|
||||
status: boolean;
|
||||
responseTime: number;
|
||||
timings: CheckTimings;
|
||||
timings: GotTimings;
|
||||
statusCode: number;
|
||||
message: string;
|
||||
ack: boolean;
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from "@/types/check.js";
|
||||
export * from "@/types/monitor.js";
|
||||
export * from "@/types/monitorStats.js";
|
||||
export * from "@/types/statusPage.js";
|
||||
export * from "@/types/network.js";
|
||||
@@ -0,0 +1,112 @@
|
||||
import type {
|
||||
CheckCaptureInfo,
|
||||
CheckCpuInfo,
|
||||
CheckDiskInfo,
|
||||
CheckErrorInfo,
|
||||
CheckHostInfo,
|
||||
CheckMemoryInfo,
|
||||
CheckNetworkInterfaceInfo,
|
||||
GotTimings,
|
||||
ILighthouseAudit,
|
||||
Monitor,
|
||||
MonitorMatchMethod,
|
||||
MonitorType,
|
||||
} from "@/types/index.js";
|
||||
|
||||
export interface MonitorStatusResponse<T = unknown> {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
type: MonitorType | "unknown";
|
||||
status: boolean;
|
||||
code: number;
|
||||
message: string;
|
||||
responseTime?: number;
|
||||
payload?: T | null;
|
||||
timings?: GotTimings;
|
||||
first_byte_took?: number;
|
||||
body_read_took?: number;
|
||||
dns_took?: number;
|
||||
conn_took?: number;
|
||||
connect_took?: number;
|
||||
tls_took?: number;
|
||||
jsonPath?: string;
|
||||
matchMethod?: MonitorMatchMethod;
|
||||
expectedValue?: string;
|
||||
extracted?: unknown;
|
||||
}
|
||||
|
||||
export interface PingStatusPayload {
|
||||
host: string;
|
||||
numeric_host?: string;
|
||||
alive: boolean;
|
||||
time: number;
|
||||
times?: number[];
|
||||
output?: string;
|
||||
min?: string;
|
||||
max?: string;
|
||||
avg?: string;
|
||||
stddev?: string;
|
||||
packetLoss?: string;
|
||||
}
|
||||
|
||||
export type HttpStatusPayload = unknown;
|
||||
|
||||
export interface PageSpeedCategoryScore {
|
||||
score?: number | null;
|
||||
}
|
||||
|
||||
export interface PageSpeedStatusPayload {
|
||||
lighthouseResult?: {
|
||||
categories?: {
|
||||
accessibility?: PageSpeedCategoryScore;
|
||||
"best-practices"?: PageSpeedCategoryScore;
|
||||
performance?: PageSpeedCategoryScore;
|
||||
seo?: PageSpeedCategoryScore;
|
||||
[key: string]: PageSpeedCategoryScore | undefined;
|
||||
};
|
||||
audits?: Record<string, ILighthouseAudit | undefined>;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface HardwareStatusMetrics {
|
||||
cpu?: CheckCpuInfo;
|
||||
memory?: CheckMemoryInfo;
|
||||
disk?: CheckDiskInfo[];
|
||||
host?: CheckHostInfo;
|
||||
net?: CheckNetworkInterfaceInfo[];
|
||||
}
|
||||
|
||||
export interface HardwareStatusPayload {
|
||||
data?: HardwareStatusMetrics;
|
||||
errors?: CheckErrorInfo[] | { errors?: CheckErrorInfo[] };
|
||||
capture?: CheckCaptureInfo;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type DockerStatusPayload = Record<string, unknown>;
|
||||
|
||||
export interface PortStatusPayload {
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export type GameStatusPayload = Record<string, unknown>;
|
||||
|
||||
export interface MonitorPayloadMap {
|
||||
ping: PingStatusPayload;
|
||||
http: HttpStatusPayload;
|
||||
pagespeed: PageSpeedStatusPayload;
|
||||
hardware: HardwareStatusPayload;
|
||||
docker: DockerStatusPayload;
|
||||
port: PortStatusPayload;
|
||||
game: GameStatusPayload;
|
||||
default: unknown;
|
||||
}
|
||||
|
||||
export type StatusChangeResult = {
|
||||
monitor: Monitor;
|
||||
statusChanged: boolean;
|
||||
prevStatus: boolean | undefined;
|
||||
code: number;
|
||||
timestamp: number;
|
||||
};
|
||||
@@ -8,11 +8,14 @@ const createHelper = (overrides?: Partial<ConstructorParameters<typeof SuperSimp
|
||||
const maintenanceWindowModule = {
|
||||
getMaintenanceWindowsByMonitorId: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const statusServiceMock = {
|
||||
updateMonitorStatus: jest.fn().mockResolvedValue({ monitor: { id: "m1" }, statusChanged: true, prevStatus: false }),
|
||||
};
|
||||
const helper = new SuperSimpleQueueHelper({
|
||||
db: { maintenanceWindowModule },
|
||||
logger: createLogger(),
|
||||
networkService: { requestStatus: jest.fn() },
|
||||
statusService: { updateStatus: jest.fn() },
|
||||
statusService: statusServiceMock,
|
||||
notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) },
|
||||
...overrides,
|
||||
});
|
||||
@@ -39,7 +42,9 @@ describe("SuperSimpleQueueHelper", () => {
|
||||
const { helper } = createHelper({
|
||||
networkService: { requestStatus: jest.fn().mockResolvedValue(networkResponse) },
|
||||
statusService: {
|
||||
updateStatus: jest.fn().mockResolvedValue({ monitor: updatedMonitor, statusChanged: true, prevStatus: false }),
|
||||
updateMonitorStatus: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ monitor: updatedMonitor, statusChanged: true, prevStatus: false }),
|
||||
},
|
||||
notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) },
|
||||
});
|
||||
@@ -48,7 +53,7 @@ describe("SuperSimpleQueueHelper", () => {
|
||||
const monitor = { id: "m1", teamId: "team" } as Monitor;
|
||||
await job(monitor);
|
||||
expect(helper["networkService"].requestStatus).toHaveBeenCalledWith(monitor);
|
||||
expect(helper["statusService"].updateStatus).toHaveBeenCalledWith(networkResponse);
|
||||
expect(helper["statusService"].updateMonitorStatus).toHaveBeenCalledWith(networkResponse);
|
||||
expect(helper["notificationService"].handleNotifications).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ monitor: updatedMonitor, statusChanged: true, prevStatus: false })
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user