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

No files matched your search

+1 -1
View File
@@ -155,7 +155,7 @@ export const initializeServices = async ({
// Repositories // Repositories
const monitorsRepository = new MongoMonitorsRepository(); const monitorsRepository = new MongoMonitorsRepository();
const checksRepository = new MongoChecksRepository(); const checksRepository = new MongoChecksRepository(logger);
const monitorStatsRepository = new MongoMonitorStatsRepository(); const monitorStatsRepository = new MongoMonitorStatsRepository();
const statusPagesRepository = new MongoStatusPagesRepository(); const statusPagesRepository = new MongoStatusPagesRepository();
+3 -4
View File
@@ -11,8 +11,7 @@ import type {
CheckMemoryInfo, CheckMemoryInfo,
CheckMetadata, CheckMetadata,
CheckNetworkInterfaceInfo, CheckNetworkInterfaceInfo,
CheckTimings, GotTimings,
CheckTimingPhases,
ILighthouseAudit, ILighthouseAudit,
} from "@/types/check.js"; } from "@/types/check.js";
@@ -35,7 +34,7 @@ interface CheckDocument extends CheckDocumentBase {
_id: Types.ObjectId; _id: Types.ObjectId;
} }
const timingPhasesSchema = new Schema<CheckTimingPhases>( const timingPhasesSchema = new Schema<GotTimings["phases"]>(
{ {
wait: { type: Number, default: 0 }, wait: { type: Number, default: 0 },
dns: { type: Number, default: 0 }, dns: { type: Number, default: 0 },
@@ -49,7 +48,7 @@ const timingPhasesSchema = new Schema<CheckTimingPhases>(
{ _id: false } { _id: false }
); );
const timingsSchema = new Schema<CheckTimings>( const timingsSchema = new Schema<GotTimings>(
{ {
start: { type: Number, default: 0 }, start: { type: Number, default: 0 },
socket: { 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"; import type { LatestChecksMap } from "@/repositories/checks/MongoChecksRepistory.js";
export interface PageSpeedChecksResult { export interface PageSpeedChecksResult {
@@ -55,6 +55,7 @@ export interface UptimeChecksResult {
export interface IChecksRepository { export interface IChecksRepository {
// create // create
buildCheck(status: MonitorStatusResponse, type: MonitorType): Check;
// single fetch // single fetch
// collection fetch // collection fetch
findLatestChecksByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap>; findLatestChecksByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap>;
@@ -10,18 +10,29 @@ import type {
CheckMemoryInfo, CheckMemoryInfo,
CheckMetadata, CheckMetadata,
CheckNetworkInterfaceInfo, CheckNetworkInterfaceInfo,
CheckTimings, GotTimings,
MonitorStatusResponse,
MonitorType, MonitorType,
} from "@/types/index.js"; } from "@/types/index.js";
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
import { CheckModel, type CheckDocument } from "@/db/models/index.js"; import { CheckModel, type CheckDocument } from "@/db/models/index.js";
import mongoose from "mongoose"; import mongoose from "mongoose";
const SERVICE_NAME = "StatusService";
export type LatestChecksMap = Record<string, Check[]>; export type LatestChecksMap = Record<string, Check[]>;
type DateRange = { start: Date; end: Date }; type DateRange = { start: Date; end: Date };
type HardwareAggregateData = { latestCheck: CheckDocument | null; totalChecks: number }; type HardwareAggregateData = { latestCheck: CheckDocument | null; totalChecks: number };
type HardwareUpChecks = { totalChecks: number }; type HardwareUpChecks = { totalChecks: number };
class MongoChecksRepository implements IChecksRepository { class MongoChecksRepository implements IChecksRepository {
static SERVICE_NAME = SERVICE_NAME;
private logger: any;
constructor(logger: any) {
this.logger = logger;
}
private toEntity = (doc: CheckDocument): Check => { private toEntity = (doc: CheckDocument): Check => {
const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => { const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => {
if (!value) { if (!value) {
@@ -44,7 +55,7 @@ class MongoChecksRepository implements IChecksRepository {
return toDateString(value); return toDateString(value);
}; };
const mapTimings = (timings?: CheckTimings): CheckTimings => { const mapTimings = (timings?: GotTimings): GotTimings => {
const phases = timings?.phases ?? { const phases = timings?.phases ?? {
wait: 0, wait: 0,
dns: 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> => { findLatestChecksByMonitorIds = async (monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap> => {
if (monitorIds.length === 0) { if (monitorIds.length === 0) {
return {}; return {};
+1
View File
@@ -1 +1,2 @@
export * from "@/service/business/monitorService.js"; export * from "@/service/business/monitorService.js";
export * from "@/service/infrastructure/networkService.js";
@@ -1,13 +1,13 @@
const SERVICE_NAME = "JobQueueHelper"; const SERVICE_NAME = "JobQueueHelper";
import type { Monitor } from "@/types/monitor.js"; import type { Monitor } from "@/types/monitor.js";
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
import { INetworkService } from "@/service/index.js";
class SuperSimpleQueueHelper { class SuperSimpleQueueHelper {
static SERVICE_NAME = SERVICE_NAME; static SERVICE_NAME = SERVICE_NAME;
private db: any; private db: any;
private logger: any; private logger: any;
private networkService: any; private networkService: INetworkService;
private statusService: any; private statusService: any;
private notificationService: any; private notificationService: any;
@@ -20,7 +20,7 @@ class SuperSimpleQueueHelper {
}: { }: {
db: any; db: any;
logger: any; logger: any;
networkService: any; networkService: INetworkService;
statusService: any; statusService: any;
notificationService: any; notificationService: any;
}) { }) {
@@ -61,14 +61,13 @@ class SuperSimpleQueueHelper {
throw new Error("No network response"); 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 this.notificationService
.handleNotifications({ .handleNotifications({
...status, ...status,
monitor: updatedMonitor, monitor: statusChangeResult.monitor,
prevStatus, prevStatus: statusChangeResult.prevStatus,
statusChanged, statusChanged: statusChangeResult.statusChanged,
}) })
.catch((error: any) => { .catch((error: any) => {
this.logger.error({ this.logger.error({
@@ -1,10 +1,38 @@
import { Got } from "got"; import { HTTPError, RequestError } from "got";
import type { Monitor } from "@/types/index.js"; import type { Got, Response } from "got";
import type { Monitor, MonitorStatusResponse } from "@/types/index.js";
import CacheableLookup from "cacheable-lookup"; import CacheableLookup from "cacheable-lookup";
const SERVICE_NAME = "NetworkService"; 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; static SERVICE_NAME = SERVICE_NAME;
private TYPE_PING: string; private TYPE_PING: string;
@@ -31,6 +59,60 @@ class NetworkService {
private stringService: any; private stringService: any;
private settingsService: 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({ constructor({
axios, axios,
got, got,
@@ -91,13 +173,17 @@ class NetworkService {
}); });
} }
get serviceName(): string {
return NetworkService.SERVICE_NAME;
}
// Helper functions // 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(); const start = process.hrtime.bigint();
try { try {
const response = await operation(); const response = await operation();
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000); const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
return { response, responseTime: elapsedMs }; return { response, responseTime: elapsedMs, error: null };
} catch (error) { } catch (error) {
const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000); const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000);
return { response: null, responseTime: elapsedMs, error }; return { response: null, responseTime: elapsedMs, error };
@@ -105,7 +191,7 @@ class NetworkService {
} }
// Main entry point // Main entry point
async requestStatus(monitor: Monitor) { async requestStatus(monitor: Monitor): Promise<MonitorStatusResponse> {
const type = monitor?.type || "unknown"; const type = monitor?.type || "unknown";
switch (type) { switch (type) {
case this.TYPE_PING: case this.TYPE_PING:
@@ -123,11 +209,11 @@ class NetworkService {
case this.TYPE_GAME: case this.TYPE_GAME:
return await this.requestGame(monitor); return await this.requestGame(monitor);
default: default:
return await this.handleUnsupportedType(type); return this.handleUnsupportedType(type);
} }
} }
async requestPing(monitor: Monitor) { private async requestPing(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
if (!monitor?.url) { if (!monitor?.url) {
throw new Error("Monitor URL is required"); throw new Error("Monitor URL is required");
@@ -147,19 +233,21 @@ class NetworkService {
throw new Error("Ping failed - no result returned"); throw new Error("Ping failed - no result returned");
} }
const pingResponse = { const pingResponse = this.buildStatusResponse({
monitorId: monitor.id, monitor,
type: "ping",
status: response.alive,
code: 200,
responseTime: response.time,
message: "Success",
payload: response, 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) { if (error) {
pingResponse.status = false; pingResponse.status = false;
pingResponse.code = 200; pingResponse.code = this.PING_ERROR;
pingResponse.message = "Ping failed"; pingResponse.message = "Ping failed";
return pingResponse; 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 { url, secret, id, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor;
const httpResponse: Record<string, any> = { const httpResponse = this.buildStatusResponse({
monitorId: id, monitor,
teamId: teamId, overrides: {
type, status: false,
}; code: this.NETWORK_ERROR,
message: "Request not executed",
},
});
try { try {
if (!url) { if (!url) {
@@ -211,12 +302,14 @@ class NetworkService {
payload = response.body; payload = response.body;
} }
httpResponse.code = response.statusCode; Object.assign(httpResponse, {
httpResponse.status = response.ok; code: response.statusCode,
httpResponse.message = response.statusMessage; status: response.ok,
httpResponse.responseTime = response.timings.phases.total || 0; message: response.statusMessage ?? "",
httpResponse.payload = payload; responseTime: response.timings.phases.total || 0,
httpResponse.timings = response.timings || {}; payload,
timings: response.timings,
});
if (!expectedValue && !jsonPath) { if (!expectedValue && !jsonPath) {
return httpResponse; return httpResponse;
@@ -300,7 +393,7 @@ class NetworkService {
} }
} }
async requestPageSpeed(monitor: Monitor) { private async requestPageSpeed(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
const url = monitor.url; const url = monitor.url;
if (!url) { if (!url) {
@@ -329,7 +422,7 @@ class NetworkService {
} }
} }
async requestHardware(monitor: Monitor) { private async requestHardware(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
return await this.requestHttp(monitor); return await this.requestHttp(monitor);
} catch (err: any) { } catch (err: any) {
@@ -339,7 +432,7 @@ class NetworkService {
} }
} }
async requestDocker(monitor: Monitor) { private async requestDocker(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
if (!monitor.url) { if (!monitor.url) {
throw new Error("Monitor URL is required"); throw new Error("Monitor URL is required");
@@ -350,10 +443,14 @@ class NetworkService {
handleError: true, // Enable error handling handleError: true, // Enable error handling
}); });
const dockerResponse: Record<string, any> = { const dockerResponse = this.buildStatusResponse({
monitorId: monitor.id, monitor,
type: monitor.type, overrides: {
}; status: false,
code: this.NETWORK_ERROR,
message: "No response",
},
});
const containers = await docker.listContainers({ all: true }); const containers = await docker.listContainers({ all: true });
@@ -406,7 +503,6 @@ class NetworkService {
method: "requestDocker", method: "requestDocker",
details: { url: monitor.url }, details: { url: monitor.url },
}); });
dockerResponse.status = 404;
dockerResponse.status = false; 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.`; dockerResponse.message = `Ambiguous container match for "${monitor.url}". Matched by: ${matchTypes.join(", ")}. Using ${exactIdMatch ? "exact ID" : exactNameMatch ? "exact name" : "partial ID"} match.`;
return dockerResponse; return dockerResponse;
@@ -437,7 +533,7 @@ class NetworkService {
} }
} }
async requestPort(monitor: Monitor) { private async requestPort(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
const { url, port } = monitor; const { url, port } = monitor;
const { response, responseTime, error } = await this.timeRequest(async () => { const { response, responseTime, error } = await this.timeRequest(async () => {
@@ -467,14 +563,15 @@ class NetworkService {
}); });
}); });
const portResponse = { const portResponse = this.buildStatusResponse({
code: 200, monitor,
status: response.success, overrides: {
message: this.stringService.portSuccess, code: 200,
monitorId: monitor.id, status: (response as { success?: boolean })?.success ?? false,
type: monitor.type, message: this.stringService.portSuccess,
responseTime: responseTime, responseTime,
}; },
});
if (error) { if (error) {
portResponse.code = this.NETWORK_ERROR; portResponse.code = this.NETWORK_ERROR;
@@ -491,17 +588,18 @@ class NetworkService {
} }
} }
async requestGame(monitor: Monitor) { private async requestGame(monitor: Monitor): Promise<MonitorStatusResponse> {
try { try {
const { url, port, gameId } = monitor; const { url, port, gameId } = monitor;
const gameResponse: Record<string, any> = { const gameResponse = this.buildStatusResponse({
code: 200, monitor,
status: true, overrides: {
message: "Success", code: 200,
monitorId: monitor.id, status: true,
type: "game", message: "Success",
}; },
});
const state = await this.GameDig.query({ const state = await this.GameDig.query({
type: gameId, type: gameId,
@@ -532,11 +630,15 @@ class NetworkService {
throw error; throw error;
} }
} }
async handleUnsupportedType(type: string) { private async handleUnsupportedType(type: string): Promise<MonitorStatusResponse> {
const err: any = new Error(`Unsupported type: ${type}`); return {
err.service = this.SERVICE_NAME; monitorId: "unknown",
err.method = "getStatus"; teamId: "unknown",
throw err; type: "unknown",
status: false,
code: this.NETWORK_ERROR,
message: `Unsupported type: ${type}`,
};
} }
// Other network requests unrelated to monitoring: // Other network requests unrelated to monitoring:
@@ -1,7 +1,8 @@
import { IMonitorsRepository } from "@/repositories/index.js"; import { IMonitorsRepository } from "@/repositories/index.js";
import MonitorStats from "../../db/models/MonitorStats.js"; import MonitorStats from "../../db/models/MonitorStats.js";
import { CheckModel } from "@/db/models/index.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"; const SERVICE_NAME = "StatusService";
class StatusService { class StatusService {
@@ -161,15 +162,17 @@ class StatusService {
} }
}; };
updateStatus = async (networkResponse: any) => { updateMonitorStatus = async (
const check = this.buildCheck(networkResponse); statusResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>
): Promise<StatusChangeResult> => {
const check = this.buildCheck(statusResponse);
await this.insertCheck(check); await this.insertCheck(check);
try { try {
const { monitorId, teamId, status, code } = networkResponse; const { monitorId, teamId, status, code } = statusResponse;
const monitor = await this.monitorsRepository.findById(monitorId, teamId); const monitor = await this.monitorsRepository.findById(monitorId, teamId);
// Update running stats // Update running stats
this.updateRunningStats({ monitor, networkResponse }); this.updateRunningStats({ monitor, networkResponse: statusResponse });
// If the status window size has changed, empty // If the status window size has changed, empty
while (monitor.statusWindow.length > monitor.statusWindowSize) { while (monitor.statusWindow.length > monitor.statusWindowSize) {
@@ -298,7 +301,9 @@ class StatusService {
} }
}; };
buildCheck = (networkResponse: any) => { buildCheck = (
networkResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>
) => {
const { const {
monitorId, monitorId,
teamId, teamId,
@@ -317,7 +322,7 @@ class StatusService {
timings, timings,
} = networkResponse; } = networkResponse;
const check = { const check: any = {
metadata: { metadata: {
monitorId, monitorId,
teamId, teamId,
@@ -337,7 +342,8 @@ class StatusService {
}; };
if (type === "pagespeed") { if (type === "pagespeed") {
if (typeof payload === "undefined") { const pageSpeedPayload = payload as PageSpeedStatusPayload | undefined;
if (!pageSpeedPayload) {
this.logger.warn({ this.logger.warn({
message: "Failed to build check", message: "Failed to build check",
service: SERVICE_NAME, service: SERVICE_NAME,
@@ -346,8 +352,8 @@ class StatusService {
}); });
return undefined; return undefined;
} }
const categories = payload?.lighthouseResult?.categories ?? {}; const categories = pageSpeedPayload.lighthouseResult?.categories ?? {};
const audits = payload?.lighthouseResult?.audits ?? {}; const audits = pageSpeedPayload.lighthouseResult?.audits ?? {};
const mapAudit = (audit: any) => { const mapAudit = (audit: any) => {
if (!audit || typeof audit !== "object") { if (!audit || typeof audit !== "object") {
return undefined; return undefined;
@@ -375,14 +381,17 @@ class StatusService {
} }
if (type === "hardware") { if (type === "hardware") {
const { cpu, memory, disk, host, net } = payload?.data ?? {}; const hardwarePayload = payload as HardwareStatusPayload | undefined;
const { errors } = payload?.errors ?? []; 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.cpu = cpu ?? {};
check.memory = memory ?? {}; check.memory = memory ?? {};
check.disk = disk ?? {}; check.disk = disk ?? {};
check.host = host ?? {}; check.host = host ?? {};
check.errors = errors ?? []; check.errors = errorsSource ?? [];
check.capture = payload?.capture ?? {}; check.capture = hardwarePayload?.capture ?? {};
check.net = net ?? {}; check.net = net ?? {};
} }
return check; return check;
+3 -24
View File
@@ -1,4 +1,6 @@
import type { MonitorType } from "@/types/index.js"; import type { MonitorType } from "@/types/index.js";
import type { Response } from "got";
export type GotTimings = Response["timings"];
export interface CheckMetadata { export interface CheckMetadata {
monitorId: string; monitorId: string;
@@ -6,29 +8,6 @@ export interface CheckMetadata {
type: MonitorType; 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 { export interface CheckCpuInfo {
physical_core: number; physical_core: number;
logical_core: number; logical_core: number;
@@ -107,7 +86,7 @@ export interface Check {
metadata: CheckMetadata; metadata: CheckMetadata;
status: boolean; status: boolean;
responseTime: number; responseTime: number;
timings: CheckTimings; timings: GotTimings;
statusCode: number; statusCode: number;
message: string; message: string;
ack: boolean; ack: boolean;
+1
View File
@@ -2,3 +2,4 @@ export * from "@/types/check.js";
export * from "@/types/monitor.js"; export * from "@/types/monitor.js";
export * from "@/types/monitorStats.js"; export * from "@/types/monitorStats.js";
export * from "@/types/statusPage.js"; export * from "@/types/statusPage.js";
export * from "@/types/network.js";
+112
View File
@@ -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 -3
View File
@@ -8,11 +8,14 @@ const createHelper = (overrides?: Partial<ConstructorParameters<typeof SuperSimp
const maintenanceWindowModule = { const maintenanceWindowModule = {
getMaintenanceWindowsByMonitorId: jest.fn().mockResolvedValue([]), getMaintenanceWindowsByMonitorId: jest.fn().mockResolvedValue([]),
}; };
const statusServiceMock = {
updateMonitorStatus: jest.fn().mockResolvedValue({ monitor: { id: "m1" }, statusChanged: true, prevStatus: false }),
};
const helper = new SuperSimpleQueueHelper({ const helper = new SuperSimpleQueueHelper({
db: { maintenanceWindowModule }, db: { maintenanceWindowModule },
logger: createLogger(), logger: createLogger(),
networkService: { requestStatus: jest.fn() }, networkService: { requestStatus: jest.fn() },
statusService: { updateStatus: jest.fn() }, statusService: statusServiceMock,
notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) }, notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) },
...overrides, ...overrides,
}); });
@@ -39,7 +42,9 @@ describe("SuperSimpleQueueHelper", () => {
const { helper } = createHelper({ const { helper } = createHelper({
networkService: { requestStatus: jest.fn().mockResolvedValue(networkResponse) }, networkService: { requestStatus: jest.fn().mockResolvedValue(networkResponse) },
statusService: { 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) }, notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) },
}); });
@@ -48,7 +53,7 @@ describe("SuperSimpleQueueHelper", () => {
const monitor = { id: "m1", teamId: "team" } as Monitor; const monitor = { id: "m1", teamId: "team" } as Monitor;
await job(monitor); await job(monitor);
expect(helper["networkService"].requestStatus).toHaveBeenCalledWith(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(helper["notificationService"].handleNotifications).toHaveBeenCalledWith(
expect.objectContaining({ monitor: updatedMonitor, statusChanged: true, prevStatus: false }) expect.objectContaining({ monitor: updatedMonitor, statusChanged: true, prevStatus: false })
); );