Add health check and retry logic and circuit breaker

This commit is contained in:
SepehrYahyaee
2026-09-28 17:01:53 +03:30
parent 22371f4a03
commit 03fa5e0f20
67 changed files with 3101 additions and 410 deletions
+25
View File
@@ -198,6 +198,26 @@ export const ERROR_CATALOG = {
message: 'User rate limit exceeded',
messageFa: 'تعداد درخواست‌های مجاز کاربر به پایان رسیده است',
},
IDEMPOTENCY_KEY_REUSED: {
status: HttpStatus.CONFLICT,
message: 'Idempotency key was already used with a different request body',
messageFa: 'کلید idempotency قبلا با بدنه درخواست دیگری استفاده شده است',
},
IDEMPOTENCY_REQUEST_IN_PROGRESS: {
status: HttpStatus.CONFLICT,
message: 'An identical request is already in progress',
messageFa: 'درخواست مشابهی در حال پردازش است',
},
PROVIDER_CIRCUIT_OPEN: {
status: HttpStatus.SERVICE_UNAVAILABLE,
message: 'Provider is temporarily unavailable',
messageFa: 'سرویس‌دهنده موقتا در دسترس نیست',
},
PROVIDER_BULKHEAD_FULL: {
status: HttpStatus.SERVICE_UNAVAILABLE,
message: 'Provider is currently at capacity',
messageFa: 'ظرفیت همزمان سرویس‌دهنده تکمیل است',
},
SHAHKAR_NO_MATCH: {
status: HttpStatus.OK,
message: 'No match found between the provided national code and mobile number',
@@ -218,6 +238,11 @@ export const ERROR_CATALOG = {
message: 'Request failed',
messageFa: 'درخواست ناموفق بود',
},
INQUIRY_LOG_PURGE_DISABLED: {
status: HttpStatus.FORBIDDEN,
message: 'Inquiry log purge is disabled',
messageFa: 'پاک‌سازی گزارش‌های استعلام غیرفعال است',
},
} as const satisfies Record<string, ErrorCatalogEntry>;
export type AppErrorCode = keyof typeof ERROR_CATALOG;
+3
View File
@@ -13,6 +13,9 @@ export class AttemptErrorDto {
@ApiProperty({ example: 'PROVIDER_TIMEOUT' })
code!: string;
@ApiPropertyOptional({ example: '503', description: 'Raw provider HTTP or SOAP error code, when supplied' })
providerCode?: string;
@ApiProperty({ example: 1042, description: 'Duration of this attempt in milliseconds' })
durationMs!: number;
+1
View File
@@ -7,4 +7,5 @@ export enum AuditEvent {
PASSWORD_RESET = 'PASSWORD_RESET',
USER_BLOCKED = 'USER_BLOCKED',
USER_UNBLOCKED = 'USER_UNBLOCKED',
INQUIRY_LOGS_PURGED = 'INQUIRY_LOGS_PURGED',
}
+15
View File
@@ -2,4 +2,19 @@ export enum InquiryStatus {
SUCCESS = 'SUCCESS',
FAILURE = 'FAILURE',
PARTIAL = 'PARTIAL',
/** A valid provider response with no matching business record. */
NO_MATCH = 'NO_MATCH',
}
export const NO_MATCH_ERROR_CODES = [
'INQUIRY_NO_MATCH',
'CAR_POLICY_NOT_FOUND',
'RECORD_NOT_FOUND',
'REAL_ESTATE_NOT_FOUND',
'SHAHKAR_NO_MATCH',
'SHEBA_MISMATCH',
] as const;
export function isNoMatchErrorCode(code?: string): boolean {
return Boolean(code && NO_MATCH_ERROR_CODES.includes(code as (typeof NO_MATCH_ERROR_CODES)[number]));
}
@@ -37,6 +37,9 @@ export class AllExceptionsFilter implements ExceptionFilter {
: HttpStatus.INTERNAL_SERVER_ERROR;
const normalizedError = this.extractNormalizedError(exception);
if (normalizedError.code === 'IDEMPOTENCY_REQUEST_IN_PROGRESS') {
response.setHeader('Retry-After', '1');
}
const trackingCode = request.trackingCode ?? 'UNKNOWN';
const requestId = request.requestId ?? (request.headers['x-request-id'] as string | undefined) ?? 'unknown';
+166 -8
View File
@@ -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;
}
@@ -84,7 +84,9 @@ export function createDeadlineError(label = 'Inquiry'): Error {
/**
* Transport / transient failures only.
* Does NOT retry 429 (rate limit / ban risk) or business rejects.
* Retries transient HTTP 404s because the configured legacy SOAP gateway is
* known to return 404 intermittently for requests that succeed later. Does
* NOT retry 429 (rate limit / ban risk) or business rejects.
*/
export function isTransportRetryable(error: unknown): boolean {
if (!error || typeof error !== 'object') {
@@ -101,7 +103,7 @@ export function isTransportRetryable(error: unknown): boolean {
if ('response' in error) {
const status = (error as { response?: { status?: number } }).response?.status;
if (typeof status === 'number') {
if (status === 408 || status === 499 || (status >= 500 && status < 600)) {
if (status === 404 || status === 408 || status === 499 || (status >= 500 && status < 600)) {
return true;
}
}
@@ -117,7 +119,7 @@ export function isTransportRetryable(error: unknown): boolean {
return normalized.code !== 'INQUIRY_DEADLINE_EXCEEDED';
}
const providerCode = normalized.providerCode?.trim();
if (providerCode && /^(408|499|5\d\d)$/.test(providerCode)) {
if (providerCode && /^(404|408|499|5\d\d)$/.test(providerCode)) {
return true;
}
}
@@ -149,6 +151,7 @@ export function isAuthTransportRetryable(error: unknown): boolean {
export function toAttemptErrorFields(error: unknown): {
code: string;
providerCode?: string;
message: string;
messageFa?: string;
} {
@@ -158,6 +161,7 @@ export function toAttemptErrorFields(error: unknown): {
);
return {
code: normalized.code,
providerCode: normalized.providerCode,
message: normalized.message,
messageFa: normalized.messageFa,
};
@@ -168,7 +172,7 @@ export function toAttemptErrorFields(error: unknown): {
const code =
error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED'
? 'PROVIDER_TIMEOUT'
: status && status >= 500
: status
? 'PROVIDER_ERROR'
: 'PROVIDER_NETWORK_ERROR';
const normalized = translateError(
@@ -178,6 +182,7 @@ export function toAttemptErrorFields(error: unknown): {
);
return {
code: normalized.code,
providerCode: status ? String(status) : undefined,
message: normalized.message,
messageFa: normalized.messageFa,
};
@@ -219,6 +224,7 @@ export function recordResilienceAttempt(
attempt: trail.totalAttempts,
provider,
code: fields.code,
providerCode: fields.providerCode,
durationMs: info.durationMs,
message: fields.message,
messageFa: fields.messageFa,
@@ -239,7 +245,7 @@ export interface RunWithResilienceOptions {
* Shared retry + per-attempt timeout + inquiry deadline for all inquiry providers.
*/
export async function runWithProviderResilience<T>(
fn: () => Promise<T>,
fn: (signal?: AbortSignal) => Promise<T>,
options: RunWithResilienceOptions,
): Promise<T> {
const {
@@ -262,7 +268,14 @@ export async function runWithProviderResilience<T>(
throw createDeadlineError(label);
}
const attemptTimeout = Math.min(timeoutMs, remaining);
return withTimeout(fn(), attemptTimeout, label);
return withTimeout(
(signal) => {
context.signal = signal;
return fn(signal);
},
attemptTimeout,
label,
);
},
{
maxAttempts,
+31 -4
View File
@@ -8,6 +8,16 @@ function decodeXml(value: string): string {
}
function normalizeSoapTextValue(value: string): string {
const keyValueValues = [
...value.matchAll(/<(?:[\w]+:)?Value\b[^>]*>([\s\S]*?)<\/(?:[\w]+:)?Value>/gi),
]
.map((match) => normalizeSoapTextValue(match[1]))
.filter(Boolean);
if (keyValueValues.length > 0) {
return keyValueValues.join(', ');
}
if (/i:nil\s*=\s*["']true["']/i.test(value)) {
return '';
}
@@ -22,7 +32,17 @@ function normalizeSoapTextValue(value: string): string {
return nestedStrings.join(', ');
}
return decodeXml(value.trim());
return decodeXml(value.trim()).replace(/\s+/g, ' ');
}
function isNoPolicyMessage(message: string): boolean {
const normalized = message.replace(/\s+/g, ' ').trim().toLowerCase();
return (
/موردی\s*یافت\s*نشد/.test(normalized) ||
/رکورد(?:ی)?\s*یافت\s*نشد/.test(normalized) ||
/(?:no\s+(?:matching\s+)?(?:policy|record|item)|not\s+found)/i.test(normalized)
);
}
function parseSoapFields(block: string): Record<string, string> {
@@ -60,7 +80,7 @@ export function parseFirstCarPolicy(soapXml: string): Record<string, string> {
export function getCarPolicyProviderError(
soapXml: string,
policy: Record<string, string>,
): { message: string; code: string } | null {
): { message: string; code: string; providerCode?: string } | null {
const resultMatch = soapXml.match(
/<(?:[\w]+:)?(?:CIIWSPolicyChassis|CIIWSPolicyVehicleMeli|CIIWSPolicyNationalId)Result[^>]*>([\s\S]*?)<\/(?:[\w]+:)?(?:CIIWSPolicyChassis|CIIWSPolicyVehicleMeli|CIIWSPolicyNationalId)Result>/i,
);
@@ -71,14 +91,21 @@ export function getCarPolicyProviderError(
);
if (errorMatch) {
const errorText = normalizeSoapTextValue(errorMatch[1]).trim();
const providerCode = errorMatch[1]
.match(/<(?:[\w]+:)?Key\b[^>]*>([\s\S]*?)<\/(?:[\w]+:)?Key>/i)?.[1]
?.trim();
if (errorText) {
return { message: errorText, code: 'PROVIDER_ERROR' };
return {
message: errorText,
code: isNoPolicyMessage(errorText) ? 'CAR_POLICY_NOT_FOUND' : 'PROVIDER_ERROR',
providerCode,
};
}
}
}
if (Object.keys(policy).length === 0) {
return { message: 'No policy record found', code: 'RECORD_NOT_FOUND' };
return { message: 'No policy record found', code: 'CAR_POLICY_NOT_FOUND' };
}
return null;
+10 -4
View File
@@ -1,24 +1,30 @@
/**
* Races an async operation against a timeout.
* Throws a distinguishable error for BaseProvider normalization.
* Runs an async operation with a per-attempt timeout.
*
* The operation receives an AbortSignal so HTTP clients can stop the actual
* in-flight request when the timeout wins. A timeout without cancellation
* would only stop awaiting the promise and could leave sockets/slots busy.
*/
export async function withTimeout<T>(
promise: Promise<T>,
operation: (signal: AbortSignal) => Promise<T>,
timeoutMs: number,
label = 'Operation',
): Promise<T> {
const controller = new AbortController();
let timeoutHandle: NodeJS.Timeout;
const operationPromise = Promise.resolve().then(() => operation(controller.signal));
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => {
const error = new Error(`${label} timed out after ${timeoutMs}ms`);
(error as NodeJS.ErrnoException).code = 'ETIMEDOUT';
controller.abort();
reject(error);
}, timeoutMs);
});
try {
return await Promise.race([promise, timeoutPromise]);
return await Promise.race([operationPromise, timeoutPromise]);
} finally {
clearTimeout(timeoutHandle!);
}
@@ -1,6 +1,7 @@
import { InquiryType } from '../enums/inquiry-type.enum';
import { ProviderName } from '../enums/provider-name.enum';
import { AttemptTrail } from '../helpers/provider-resilience.helper';
import type { OutboundRequestTrace } from '../helpers/http-client.helper';
/**
* Contract every external provider adapter must fulfill.
@@ -22,6 +23,10 @@ export interface ProviderExecutionContext {
trackingCode: string;
/** Absolute timestamp when the inquiry wall-clock budget expires. */
deadlineAt?: number;
/** Signal for cancelling the currently active provider attempt. */
signal?: AbortSignal;
/** Mutable trail of HTTP attempts for client summary + logs. */
attemptTrail?: AttemptTrail;
/** Sanitized outbound HTTP calls made during this inquiry, including retries. */
outboundRequests?: OutboundRequestTrace[];
}