forked from Shared/esg
Add health check and retry logic and circuit breaker
This commit is contained in:
@@ -6,6 +6,7 @@ import axios, {
|
||||
InternalAxiosRequestConfig,
|
||||
} from 'axios';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import type { Agent as HttpAgent } from 'http';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
@@ -13,6 +14,21 @@ const { SocksProxyAgent } = require('socks-proxy-agent');
|
||||
|
||||
const outboundHttpLogger = new Logger('OutboundHTTP');
|
||||
|
||||
export interface OutboundRequestTrace {
|
||||
method: string;
|
||||
url: string;
|
||||
requestHeaders: Record<string, string>;
|
||||
requestBody?: unknown;
|
||||
status?: number;
|
||||
responseBody?: unknown;
|
||||
error?: string;
|
||||
durationMs?: number;
|
||||
curl: string;
|
||||
}
|
||||
|
||||
const outboundTraceStorage = new AsyncLocalStorage<OutboundRequestTrace[]>();
|
||||
const traceInterceptorsInstalled = new WeakSet<object>();
|
||||
|
||||
let cachedSocksAgents: { httpAgent: HttpAgent; httpsAgent: HttpAgent } | undefined;
|
||||
let outboundHttpDebugInstalled = false;
|
||||
|
||||
@@ -41,6 +57,93 @@ function truncate(value: string, max = 800): string {
|
||||
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
||||
}
|
||||
|
||||
function truncateTrace(value: string, max = 12000): string {
|
||||
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
||||
}
|
||||
|
||||
function redactTraceValue(value: unknown): unknown {
|
||||
if (typeof value === 'string') {
|
||||
return truncateTrace(
|
||||
value
|
||||
.replace(/(<(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)[^>]*>)[^<]*(<\/(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)>)/gi, '$1REDACTED$2')
|
||||
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>')
|
||||
.replace(/((?:"|')?(?:password|client_secret|access_token|refresh_token|authorization)(?:"|')?\s*:\s*)("[^"]*"|'[^']*')/gi, '$1"<REDACTED>"'),
|
||||
);
|
||||
}
|
||||
if (value === undefined || value === null || typeof value !== 'object') return value;
|
||||
if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
|
||||
return truncateTrace(
|
||||
value
|
||||
.toString()
|
||||
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>'),
|
||||
);
|
||||
}
|
||||
if (Buffer.isBuffer(value)) return truncateTrace(value.toString('utf8'));
|
||||
if (Array.isArray(value)) return value.map((item) => redactTraceValue(item));
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
||||
key,
|
||||
/password|secret|authorization|token|client_secret/i.test(key)
|
||||
? '<REDACTED>'
|
||||
: redactTraceValue(item),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function toTraceString(value: unknown): string {
|
||||
if (typeof value === 'string') return truncateTrace(value);
|
||||
try {
|
||||
return truncateTrace(JSON.stringify(value));
|
||||
} catch {
|
||||
return truncateTrace(String(value));
|
||||
}
|
||||
}
|
||||
|
||||
function shellQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function toHeaderRecord(headers: unknown): Record<string, string> {
|
||||
const source =
|
||||
headers && typeof headers === 'object' && 'toJSON' in headers && typeof headers.toJSON === 'function'
|
||||
? headers.toJSON()
|
||||
: headers;
|
||||
if (!source || typeof source !== 'object') return {};
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(source as Record<string, unknown>)
|
||||
.filter(([key]) => !/^(host|content-length|user-agent|accept-encoding)$/i.test(key))
|
||||
.map(([key, value]) => [
|
||||
key,
|
||||
/authorization|password|secret|token/i.test(key) ? '<REDACTED>' : String(value),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function buildCurl(
|
||||
method: string,
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
body: unknown,
|
||||
): string {
|
||||
const parts = [`curl --request ${method}`, shellQuote(url)];
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
parts.push(`--header ${shellQuote(`${key}: ${value}`)}`);
|
||||
}
|
||||
if (body !== undefined) {
|
||||
parts.push(`--data-raw ${shellQuote(toTraceString(body))}`);
|
||||
}
|
||||
return parts.join(' \\\n ');
|
||||
}
|
||||
|
||||
export function runWithOutboundTrace<T>(
|
||||
trace: OutboundRequestTrace[],
|
||||
callback: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
return outboundTraceStorage.run(trace, callback);
|
||||
}
|
||||
|
||||
function sanitizeForLog(data: unknown): string {
|
||||
if (data === undefined || data === null) {
|
||||
return String(data);
|
||||
@@ -86,6 +189,21 @@ function resolveRequestUrl(config: InternalAxiosRequestConfig): string {
|
||||
return `${base.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
|
||||
}
|
||||
|
||||
function resolveTraceUrl(config: InternalAxiosRequestConfig): string {
|
||||
const url = resolveRequestUrl(config);
|
||||
if (!config.params || typeof config.params !== 'object') return url;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
for (const [key, value] of Object.entries(config.params as Record<string, unknown>)) {
|
||||
if (Array.isArray(value)) value.forEach((item) => parsed.searchParams.append(key, String(item)));
|
||||
else if (value !== undefined && value !== null) parsed.searchParams.set(key, String(value));
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function logOutboundRequest(config: InternalAxiosRequestConfig): void {
|
||||
const method = (config.method ?? 'GET').toUpperCase();
|
||||
const url = resolveRequestUrl(config);
|
||||
@@ -140,27 +258,65 @@ function logOutboundError(error: AxiosError): void {
|
||||
}
|
||||
|
||||
export function installOutboundHttpDebugInterceptors(): void {
|
||||
if (!isOutboundHttpDebugEnabled() || outboundHttpDebugInstalled) {
|
||||
if (outboundHttpDebugInstalled) {
|
||||
return;
|
||||
}
|
||||
|
||||
outboundHttpDebugInstalled = true;
|
||||
outboundHttpLogger.log('Outbound HTTP debug logging enabled (OUTBOUND_HTTP_DEBUG=true)');
|
||||
if (isOutboundHttpDebugEnabled()) {
|
||||
outboundHttpLogger.log('Outbound HTTP debug logging enabled (OUTBOUND_HTTP_DEBUG=true)');
|
||||
}
|
||||
|
||||
axios.interceptors.request.use((config) => {
|
||||
installOutboundHttpTraceInterceptors(axios);
|
||||
}
|
||||
|
||||
function installOutboundHttpTraceInterceptors(instance: AxiosInstance): void {
|
||||
if (traceInterceptorsInstalled.has(instance)) return;
|
||||
traceInterceptorsInstalled.add(instance);
|
||||
|
||||
instance.interceptors.request.use((config) => {
|
||||
(config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart =
|
||||
Date.now();
|
||||
logOutboundRequest(config);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundRequest(config);
|
||||
const trace = outboundTraceStorage.getStore();
|
||||
if (trace) {
|
||||
const requestHeaders = toHeaderRecord(config.headers);
|
||||
const requestBody = redactTraceValue(config.data);
|
||||
const item: OutboundRequestTrace = {
|
||||
method: (config.method ?? 'GET').toUpperCase(),
|
||||
url: resolveTraceUrl(config),
|
||||
requestHeaders,
|
||||
requestBody,
|
||||
curl: buildCurl((config.method ?? 'GET').toUpperCase(), resolveTraceUrl(config), requestHeaders, requestBody),
|
||||
};
|
||||
(config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace = item;
|
||||
trace.push(item);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
axios.interceptors.response.use(
|
||||
instance.interceptors.response.use(
|
||||
(response) => {
|
||||
logOutboundResponse(response);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundResponse(response);
|
||||
const trace = (response.config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace;
|
||||
if (trace) {
|
||||
trace.status = response.status;
|
||||
trace.responseBody = redactTraceValue(response.data);
|
||||
const start = (response.config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart;
|
||||
trace.durationMs = start ? Date.now() - start : undefined;
|
||||
}
|
||||
return response;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
logOutboundError(error);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundError(error);
|
||||
const config = error.config as (InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace; _outboundStart?: number }) | undefined;
|
||||
const trace = config?._outboundTrace;
|
||||
if (trace) {
|
||||
trace.status = error.response?.status;
|
||||
trace.responseBody = redactTraceValue(error.response?.data);
|
||||
trace.error = error.message;
|
||||
trace.durationMs = config?._outboundStart ? Date.now() - config._outboundStart : undefined;
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
@@ -213,10 +369,12 @@ export function mergeOutboundAxiosConfig(config: AxiosRequestConfig = {}): Axios
|
||||
export function createOutboundAxiosInstance(config: CreateAxiosDefaults = {}): AxiosInstance {
|
||||
const outbound = getOutboundAxiosDefaults();
|
||||
|
||||
return axios.create({
|
||||
const instance = axios.create({
|
||||
...config,
|
||||
httpAgent: config.httpAgent ?? outbound.httpAgent,
|
||||
httpsAgent: config.httpsAgent ?? outbound.httpsAgent,
|
||||
proxy: config.proxy ?? outbound.proxy,
|
||||
});
|
||||
installOutboundHttpTraceInterceptors(instance);
|
||||
return instance;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user