Merge pull request #3690 from harsh-aghara/feat/accept-status-codes-backend
Add customUpCodes support for HTTP monitors (Backend)
This commit is contained in:
13 files changed
+346
-60
No files matched your search
@@ -89,7 +89,7 @@ export class GeoChecksService implements IGeoChecksService {
|
||||
}
|
||||
|
||||
// Step 2: Poll for results
|
||||
const results = await this.globalPingService.pollForResults(measurementId);
|
||||
const results = await this.globalPingService.pollForResults(measurementId, undefined, monitor.customUpCodes ?? []);
|
||||
|
||||
if (results.length === 0) {
|
||||
// No successful results (all locations timed out or failed)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { GeoContinent, GeoCheckResult, GeoCheckTimings, GeoCheckLocation } from "@/types/geoCheck.js";
|
||||
import { supportsGeoCheck } from "@/types/monitor.js";
|
||||
import { supportsGeoCheck, type HttpStatusCode } from "@/types/monitor.js";
|
||||
import { MonitorType } from "@/types/index.js";
|
||||
import type { ILogger } from "@/utils/logger.js";
|
||||
import got from "got";
|
||||
import { isStatusUp } from "@/service/infrastructure/network/utils.js";
|
||||
|
||||
const SERVICE_NAME = "GlobalPingService";
|
||||
const GLOBAL_PING_API_BASE = "https://api.globalping.io/v1";
|
||||
@@ -62,7 +63,7 @@ interface GlobalPingProbeResult {
|
||||
export interface IGlobalPingService {
|
||||
readonly serviceName: string;
|
||||
createMeasurement(monitorType: MonitorType, url: string, locations: GeoContinent[]): Promise<string | null>;
|
||||
pollForResults(measurementId: string, timeoutMs?: number): Promise<GeoCheckResult[]>;
|
||||
pollForResults(measurementId: string, timeoutMs?: number, customUpCodes?: HttpStatusCode[]): Promise<GeoCheckResult[]>;
|
||||
}
|
||||
|
||||
export class GlobalPingService implements IGlobalPingService {
|
||||
@@ -119,7 +120,11 @@ export class GlobalPingService implements IGlobalPingService {
|
||||
}
|
||||
}
|
||||
|
||||
async pollForResults(measurementId: string, timeoutMs: number = MAX_POLL_TIMEOUT_MS): Promise<GeoCheckResult[]> {
|
||||
async pollForResults(
|
||||
measurementId: string,
|
||||
timeoutMs: number = MAX_POLL_TIMEOUT_MS,
|
||||
customUpCodes: HttpStatusCode[] = []
|
||||
): Promise<GeoCheckResult[]> {
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
@@ -132,7 +137,7 @@ export class GlobalPingService implements IGlobalPingService {
|
||||
const measurement = response.body;
|
||||
|
||||
if (measurement.status === "finished") {
|
||||
const results = this.transformResults(measurement.results || []);
|
||||
const results = this.transformResults(measurement.results || [], customUpCodes);
|
||||
this.logger.debug({
|
||||
message: `GlobalPing measurement completed: ${measurementId}`,
|
||||
service: SERVICE_NAME,
|
||||
@@ -174,7 +179,7 @@ export class GlobalPingService implements IGlobalPingService {
|
||||
return [];
|
||||
}
|
||||
|
||||
private transformResults(probeResults: GlobalPingProbeResult[]): GeoCheckResult[] {
|
||||
private transformResults(probeResults: GlobalPingProbeResult[], customUpCodes: HttpStatusCode[] = []): GeoCheckResult[] {
|
||||
const successfulResults: GeoCheckResult[] = [];
|
||||
|
||||
for (const probeResult of probeResults) {
|
||||
@@ -205,7 +210,7 @@ export class GlobalPingService implements IGlobalPingService {
|
||||
|
||||
successfulResults.push({
|
||||
location,
|
||||
status: probeResult.result.statusCode >= 200 && probeResult.result.statusCode < 300,
|
||||
status: isStatusUp(probeResult.result.statusCode, customUpCodes),
|
||||
statusCode: probeResult.result.statusCode,
|
||||
timings,
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import { MonitorStatusResponse } from "@/types/network.js";
|
||||
import { Agent as HttpsAgent } from "https";
|
||||
import { Agent as HttpAgent } from "http";
|
||||
import { Monitor, MonitorType } from "@/types/monitor.js";
|
||||
import { NETWORK_ERROR } from "@/service/infrastructure/network/utils.js";
|
||||
import { NETWORK_ERROR, isStatusUp } from "@/service/infrastructure/network/utils.js";
|
||||
import CacheableLookup from "cacheable-lookup";
|
||||
|
||||
export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
||||
@@ -40,21 +40,93 @@ export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
||||
return type === "http";
|
||||
}
|
||||
|
||||
private handleHttpError<T>(error: unknown, monitor: Monitor): MonitorStatusResponse<T> {
|
||||
if (error instanceof HTTPError || error instanceof RequestError) {
|
||||
private buildResponse<T>(
|
||||
monitor: Monitor,
|
||||
opts: {
|
||||
body: string;
|
||||
contentType: string;
|
||||
statusCode: number;
|
||||
statusUp: boolean;
|
||||
message: string;
|
||||
responseTime: number;
|
||||
timings?: MonitorStatusResponse<T>["timings"];
|
||||
}
|
||||
): MonitorStatusResponse<T> {
|
||||
const { body, contentType, statusCode, statusUp, message, responseTime, timings } = opts;
|
||||
const isJson = contentType.includes("application/json");
|
||||
|
||||
if (monitor.jsonPath && !isJson) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: error.response?.statusCode ?? NETWORK_ERROR,
|
||||
message: error.message,
|
||||
responseTime: error.timings?.phases?.firstByte ?? error.timings?.phases?.total ?? 0,
|
||||
timings: error.timings,
|
||||
payload: null as T,
|
||||
code: statusCode,
|
||||
message: "Response is not JSON",
|
||||
responseTime,
|
||||
timings,
|
||||
payload: body,
|
||||
};
|
||||
}
|
||||
|
||||
let payload: T | string;
|
||||
if (isJson) {
|
||||
try {
|
||||
payload = JSON.parse(body) as T;
|
||||
} catch {
|
||||
payload = body;
|
||||
}
|
||||
} else {
|
||||
payload = body;
|
||||
}
|
||||
|
||||
const matchResult = this.advancedMatcher.validate<T | string>(payload, monitor);
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: statusUp && matchResult.ok,
|
||||
code: statusCode,
|
||||
message: matchResult.ok ? message : matchResult.message,
|
||||
responseTime,
|
||||
timings,
|
||||
payload,
|
||||
extracted: matchResult.extracted,
|
||||
};
|
||||
}
|
||||
|
||||
private handleHttpError<T>(error: unknown, monitor: Monitor): MonitorStatusResponse<T> {
|
||||
if (error instanceof HTTPError || error instanceof RequestError) {
|
||||
const statusCode = error.response?.statusCode;
|
||||
const statusUp = isStatusUp(statusCode, monitor.customUpCodes);
|
||||
const responseTime = error.timings?.phases?.firstByte ?? error.timings?.phases?.total ?? 0;
|
||||
|
||||
if (!statusUp) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: statusCode ?? NETWORK_ERROR,
|
||||
message: error.message,
|
||||
responseTime,
|
||||
timings: error.timings,
|
||||
payload: null as T,
|
||||
};
|
||||
}
|
||||
|
||||
return this.buildResponse<T>(monitor, {
|
||||
body: (error.response?.body ?? "") as string,
|
||||
contentType: error.response?.headers?.["content-type"] || "",
|
||||
statusCode: statusCode ?? NETWORK_ERROR,
|
||||
statusUp,
|
||||
message: error.message,
|
||||
responseTime,
|
||||
timings: error.timings,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
@@ -68,7 +140,7 @@ export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
||||
}
|
||||
|
||||
async handle<T>(monitor: Monitor): Promise<MonitorStatusResponse<T>> {
|
||||
const { url, secret, jsonPath, ignoreTlsErrors } = monitor;
|
||||
const { url, secret, ignoreTlsErrors } = monitor;
|
||||
|
||||
if (!url) {
|
||||
throw new Error("URL is required for HTTP monitor");
|
||||
@@ -85,47 +157,17 @@ export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
||||
|
||||
try {
|
||||
const response = await this.got<string>(url, options);
|
||||
const contentType = response.headers["content-type"] || "";
|
||||
const isJson = contentType.includes("application/json");
|
||||
const statusUp = isStatusUp(response.statusCode, monitor.customUpCodes);
|
||||
|
||||
if (jsonPath && !isJson) {
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: false,
|
||||
code: response.statusCode,
|
||||
message: "Response is not JSON",
|
||||
responseTime: response.timings.phases.firstByte ?? 0,
|
||||
timings: response.timings,
|
||||
payload: response.body as unknown as T,
|
||||
};
|
||||
}
|
||||
|
||||
let payload: T;
|
||||
if (isJson) {
|
||||
try {
|
||||
payload = JSON.parse(response.body) as T;
|
||||
} catch {
|
||||
payload = response.body as unknown as T;
|
||||
}
|
||||
} else {
|
||||
payload = response.body as unknown as T;
|
||||
}
|
||||
|
||||
const matchResult = this.advancedMatcher.validate<T>(payload, monitor);
|
||||
return {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
status: response.ok && matchResult.ok,
|
||||
code: response.statusCode,
|
||||
message: matchResult.ok ? (response.statusMessage ?? "OK") : matchResult.message,
|
||||
return this.buildResponse<T>(monitor, {
|
||||
body: response.body,
|
||||
contentType: response.headers["content-type"] || "",
|
||||
statusCode: response.statusCode,
|
||||
statusUp,
|
||||
message: response.statusMessage ?? "OK",
|
||||
responseTime: response.timings.phases.firstByte ?? 0,
|
||||
timings: response.timings,
|
||||
payload,
|
||||
extracted: matchResult.extracted,
|
||||
};
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
return this.handleHttpError(error, monitor);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { HttpStatusCode } from "@/types/monitor.js";
|
||||
|
||||
export const timeRequest = async <T>(operation: () => Promise<T>): Promise<{ response: T | null; responseTime: number; error: unknown }> => {
|
||||
const start = process.hrtime.bigint();
|
||||
try {
|
||||
@@ -12,3 +14,8 @@ export const timeRequest = async <T>(operation: () => Promise<T>): Promise<{ res
|
||||
|
||||
export const NETWORK_ERROR = 5000;
|
||||
export const PING_ERROR = 5001;
|
||||
|
||||
export const isStatusUp = (statusCode: number | undefined, customUpCodes: HttpStatusCode[] = []): boolean => {
|
||||
if (statusCode === undefined) return false;
|
||||
return (statusCode >= 200 && statusCode < 300) || customUpCodes.includes(statusCode);
|
||||
};
|
||||
@@ -186,7 +186,7 @@ export class NotificationMessageBuilder implements INotificationMessageBuilder {
|
||||
const breaches: ThresholdBreach[] = [];
|
||||
|
||||
// Check if this is a hardware monitor with threshold data
|
||||
if (monitor.type !== "hardware" || !monitorStatusResponse.payload) {
|
||||
if (monitor.type !== "hardware" || !monitorStatusResponse.payload || typeof monitorStatusResponse.payload === "string") {
|
||||
return breaches;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user