refactor: clean up code formatting and improve readability across multiple files

This commit is contained in:
Nawaz Dhandala
2026-03-31 14:06:05 +01:00
parent 414f7cebc7
commit 574cac7d64
9 changed files with 95 additions and 86 deletions

View File

@@ -5,7 +5,13 @@ import MonitorAlertMetrics from "../../../Components/Monitor/MonitorAlertMetrics
import PageComponentProps from "../../PageComponentProps";
import ObjectID from "Common/Types/ObjectID";
import Navigation from "Common/UI/Utils/Navigation";
import React, { Fragment, FunctionComponent, ReactElement, useEffect, useState } from "react";
import React, {
Fragment,
FunctionComponent,
ReactElement,
useEffect,
useState,
} from "react";
import Tabs from "Common/UI/Components/Tabs/Tabs";
import { Tab } from "Common/UI/Components/Tabs/Tab";
import MonitorType from "Common/Types/Monitor/MonitorType";
@@ -21,7 +27,7 @@ const MonitorMetrics: FunctionComponent<
> = (): ReactElement => {
const modelId: ObjectID = Navigation.getLastParamAsObjectID(1);
const [_currentTab, setCurrentTab] = useState<Tab | null>(null);
const [, setCurrentTab] = useState<Tab | null>(null);
const [monitorType, setMonitorType] = useState<MonitorType | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<string>("");

View File

@@ -9,7 +9,12 @@ import CardModelDetail from "Common/UI/Components/ModelDetail/CardModelDetail";
import FieldType from "Common/UI/Components/Types/FieldType";
import Navigation from "Common/UI/Utils/Navigation";
import Workflow from "Common/Models/DatabaseModels/Workflow";
import React, { Fragment, FunctionComponent, ReactElement, useState } from "react";
import React, {
Fragment,
FunctionComponent,
ReactElement,
useState,
} from "react";
import { ButtonStyleType } from "Common/UI/Components/Button/Button";
import IconProp from "Common/Types/Icon/IconProp";
import ConfirmModal from "Common/UI/Components/Modal/ConfirmModal";
@@ -24,7 +29,6 @@ import {
NodeType,
} from "Common/Types/Workflow/Component";
import { useAsyncEffect } from "use-async-effect";
import { Node } from "reactflow";
const Settings: FunctionComponent<PageComponentProps> = (): ReactElement => {
const modelId: ObjectID = Navigation.getLastParamAsObjectID(1);
@@ -45,10 +49,7 @@ const Settings: FunctionComponent<PageComponentProps> = (): ReactElement => {
requestOptions: {},
});
if (
workflow?.graph &&
(workflow.graph as JSONObject)["nodes"]
) {
if (workflow?.graph && (workflow.graph as JSONObject)["nodes"]) {
const nodes: Array<JSONObject> = (workflow.graph as JSONObject)[
"nodes"
] as Array<JSONObject>;
@@ -66,7 +67,7 @@ const Settings: FunctionComponent<PageComponentProps> = (): ReactElement => {
}
}
}
} catch (_err) {
} catch {
// ignore - just don't show the webhook section
}
}, []);

View File

@@ -1088,9 +1088,7 @@ ${alertSeverity.name}
return globalConfig.monitorMetricRetentionInDays;
}
} catch (error) {
logger.error(
"Error fetching metric retention config, using default:",
);
logger.error("Error fetching metric retention config, using default:");
logger.error(error);
}

View File

@@ -2115,9 +2115,7 @@ ${incidentSeverity.name}
return globalConfig.monitorMetricRetentionInDays;
}
} catch (error) {
logger.error(
"Error fetching metric retention config, using default:",
);
logger.error("Error fetching metric retention config, using default:");
logger.error(error);
}

View File

@@ -724,10 +724,7 @@ ${contextBlock}
return r.metricValue > 0;
})
.sort(
(
a: KubernetesAffectedResource,
b: KubernetesAffectedResource,
) => {
(a: KubernetesAffectedResource, b: KubernetesAffectedResource) => {
return b.metricValue - a.metricValue;
},
);
@@ -742,19 +739,29 @@ ${contextBlock}
// Determine which columns are present across all resources
const hasNamespace: boolean = resourcesToShow.some(
(r: KubernetesAffectedResource) => r.namespace,
(r: KubernetesAffectedResource) => {
return r.namespace;
},
);
const hasWorkload: boolean = resourcesToShow.some(
(r: KubernetesAffectedResource) => r.workloadType && r.workloadName,
(r: KubernetesAffectedResource) => {
return r.workloadType && r.workloadName;
},
);
const hasPod: boolean = resourcesToShow.some(
(r: KubernetesAffectedResource) => r.podName,
(r: KubernetesAffectedResource) => {
return r.podName;
},
);
const hasContainer: boolean = resourcesToShow.some(
(r: KubernetesAffectedResource) => r.containerName,
(r: KubernetesAffectedResource) => {
return r.containerName;
},
);
const hasNode: boolean = resourcesToShow.some(
(r: KubernetesAffectedResource) => r.nodeName,
(r: KubernetesAffectedResource) => {
return r.nodeName;
},
);
// Build table header
@@ -778,9 +785,11 @@ ${contextBlock}
headerCells.push("Value");
const headerRow: string = `| ${headerCells.join(" | ")} |`;
const separatorRow: string = `| ${headerCells.map(() => {
return "---";
}).join(" | ")} |`;
const separatorRow: string = `| ${headerCells
.map(() => {
return "---";
})
.join(" | ")} |`;
resourceLines.push(headerRow);
resourceLines.push(separatorRow);
@@ -792,9 +801,7 @@ ${contextBlock}
cells.push(resource.namespace ? `\`${resource.namespace}\`` : "-");
}
if (hasWorkload) {
cells.push(
resource.workloadType ? `${resource.workloadType}` : "-",
);
cells.push(resource.workloadType ? `${resource.workloadType}` : "-");
cells.push(
resource.workloadName ? `\`${resource.workloadName}\`` : "-",
);
@@ -849,8 +856,7 @@ ${contextBlock}
const logAttributes: Record<string, string> = {};
if (breakdown.clusterName) {
logAttributes["resource.k8s.cluster.name"] =
breakdown.clusterName;
logAttributes["resource.k8s.cluster.name"] = breakdown.clusterName;
}
if (topResource.podName) {
@@ -868,8 +874,10 @@ ${contextBlock}
}
const now: Date = OneUptimeDate.getCurrentDate();
const fifteenMinutesAgo: Date =
OneUptimeDate.addRemoveMinutes(now, -15);
const fifteenMinutesAgo: Date = OneUptimeDate.addRemoveMinutes(
now,
-15,
);
const logs: Array<JSONObject> =
await LogAggregationService.getExportLogs({
@@ -882,9 +890,7 @@ ${contextBlock}
if (logs.length > 0) {
const logLines: Array<string> = logs.map((log: JSONObject) => {
const timestamp: string = log["time"]
? String(log["time"])
: "";
const timestamp: string = log["time"] ? String(log["time"]) : "";
const severity: string = log["severityText"]
? String(log["severityText"])
: "INFO";
@@ -897,9 +903,7 @@ ${contextBlock}
);
}
} catch (err) {
logger.error(
"Failed to fetch container logs for root cause context",
);
logger.error("Failed to fetch container logs for root cause context");
logger.error(err);
}
}

View File

@@ -1,8 +1,5 @@
import Pyroscope from "@pyroscope/nodejs";
import {
DisableTelemetry,
EnableProfiling,
} from "../EnvironmentConfig";
import { DisableTelemetry, EnableProfiling } from "../EnvironmentConfig";
import logger from "./Logger";
export default class Profiling {
@@ -54,9 +51,11 @@ export default class Profiling {
}
private static getServerAddress(): string | undefined {
// Use the OTLP endpoint base URL as the Pyroscope server address.
// The Pyroscope SDK will append /ingest to this URL.
// The Telemetry service has a Pyroscope-compatible /ingest endpoint.
/*
* Use the OTLP endpoint base URL as the Pyroscope server address.
* The Pyroscope SDK will append /ingest to this URL.
* The Telemetry service has a Pyroscope-compatible /ingest endpoint.
*/
const endpoint: string | undefined =
process.env["OPENTELEMETRY_EXPORTER_OTLP_ENDPOINT"];
@@ -77,8 +76,10 @@ export default class Profiling {
}
private static getAuthToken(): string | undefined {
// Extract the OneUptime token from OTLP headers
// Format: "x-oneuptime-token=<value>;other-header=value"
/*
* Extract the OneUptime token from OTLP headers
* Format: "x-oneuptime-token=<value>;other-header=value"
*/
const headersStr: string | undefined =
process.env["OPENTELEMETRY_EXPORTER_OTLP_HEADERS"];

View File

@@ -28,9 +28,7 @@ class AlertMetricTypeUtil {
];
}
public static getTitleByAlertMetricType(
metricType: AlertMetricType,
): string {
public static getTitleByAlertMetricType(metricType: AlertMetricType): string {
switch (metricType) {
case AlertMetricType.AlertCount:
return "Alert Count";

View File

@@ -24,8 +24,10 @@ const setProfilesProductType: RequestHandler = (
next();
};
// Map Authorization: Bearer <token> to x-oneuptime-token header
// Pyroscope SDKs use authToken which sends Authorization: Bearer
/*
* Map Authorization: Bearer <token> to x-oneuptime-token header
* Pyroscope SDKs use authToken which sends Authorization: Bearer
*/
const mapBearerTokenMiddleware: RequestHandler = (
req: ExpressRequest,
_res: ExpressResponse,

View File

@@ -87,13 +87,10 @@ export default class PyroscopeIngestService {
);
// Extract pprof data from request
const pprofBuffer: Buffer | null =
this.extractPprofFromRequest(req);
const pprofBuffer: Buffer | null = this.extractPprofFromRequest(req);
if (!pprofBuffer || pprofBuffer.length === 0) {
throw new BadRequestException(
"No profile data found in request body.",
);
throw new BadRequestException("No profile data found in request body.");
}
// Decompress if gzipped
@@ -116,17 +113,17 @@ export default class PyroscopeIngestService {
// Respond immediately and queue for async processing
Response.sendEmptySuccessResponse(req, res);
await ProfilesQueueService.addProfileIngestJob(
req as TelemetryRequest,
);
await ProfilesQueueService.addProfileIngestJob(req as TelemetryRequest);
} catch (err) {
return next(err);
}
}
private static parseAppName(name: string): string {
// Pyroscope name format: "appName.profileType{label1=value1,label2=value2}"
// Extract just the app name part (before the first '{' or '.')
/*
* Pyroscope name format: "appName.profileType{label1=value1,label2=value2}"
* Extract just the app name part (before the first '{' or '.')
*/
const braceIndex: number = name.indexOf("{");
if (braceIndex >= 0) {
name = name.substring(0, braceIndex);
@@ -166,10 +163,9 @@ export default class PyroscopeIngestService {
if (files && files.length > 0) {
// Find the 'profile' field
const profileFile: { fieldname: string; buffer: Buffer } | undefined =
files.find(
(f: { fieldname: string; buffer: Buffer }) =>
f.fieldname === "profile",
);
files.find((f: { fieldname: string; buffer: Buffer }) => {
return f.fieldname === "profile";
});
if (profileFile) {
return profileFile.buffer;
@@ -195,17 +191,17 @@ export default class PyroscopeIngestService {
// Check for gzip magic bytes (0x1f, 0x8b)
if (data.length >= 2 && data[0] === 0x1f && data[1] === 0x8b) {
return new Promise<Buffer>(
(
resolve: (value: Buffer) => void,
reject: (reason: Error) => void,
) => {
zlib.gunzip(data as unknown as Uint8Array, (err: Error | null, result: Buffer) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
(resolve: (value: Buffer) => void, reject: (reason: Error) => void) => {
zlib.gunzip(
data as unknown as Uint8Array,
(err: Error | null, result: Buffer) => {
if (err) {
reject(err);
} else {
resolve(result);
}
},
);
},
);
}
@@ -305,7 +301,9 @@ export default class PyroscopeIngestService {
// Convert values to strings
const values: Array<string> = (sample.value || []).map(
(v: number | string) => v.toString(),
(v: number | string) => {
return v.toString();
},
);
otlpSamples.push({
@@ -317,10 +315,12 @@ export default class PyroscopeIngestService {
// Build sample types
const sampleType: Array<JSONObject> = (pprofData.sampleType || []).map(
(st: PprofValueType) => ({
type: st.type,
unit: st.unit,
}),
(st: PprofValueType) => {
return {
type: st.type,
unit: st.unit,
};
},
);
// Build period type
@@ -330,8 +330,9 @@ export default class PyroscopeIngestService {
// Generate profile ID
const profileId: string = ObjectID.generate().toString();
const profileIdBase64: string =
Buffer.from(profileId, "hex").toString("base64");
const profileIdBase64: string = Buffer.from(profileId, "hex").toString(
"base64",
);
return {
resourceProfiles: [