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
+5
View File
@@ -57,6 +57,11 @@ export class InquiryLogQueryDto {
@IsString()
errorMessage?: string;
@ApiPropertyOptional({ description: 'Exact inquiry tracking code lookup' })
@IsOptional()
@IsString()
trackingCode?: string;
@ApiPropertyOptional({ minimum: 1, maximum: 500, default: 50 })
@IsOptional()
@IsInt()
+69 -5
View File
@@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { FilterQuery, Model } from 'mongoose';
import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto';
import { InquiryStatus } from '../common/enums/inquiry-status.enum';
import {
InquiryStatus,
NO_MATCH_ERROR_CODES,
} from '../common/enums/inquiry-status.enum';
import { InquiryType } from '../common/enums/inquiry-type.enum';
import { ProviderName } from '../common/enums/provider-name.enum';
import { maskPayload } from '../common/helpers/mask-payload.helper';
@@ -13,6 +16,7 @@ import {
LogTimeRangePreset,
} from './dto/inquiry-log-query.dto';
import { InquiryLog, InquiryLogDocument } from './schemas/inquiry-log.schema';
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
export interface CreateInquiryLogInput {
inquiryType: InquiryType;
@@ -25,6 +29,7 @@ export interface CreateInquiryLogInput {
trackingCode: string;
error?: Record<string, unknown>;
attemptSummary?: AttemptSummaryDto;
outboundRequests?: OutboundRequestTrace[];
}
export interface InquiryLogListItem {
@@ -38,13 +43,16 @@ export interface InquiryLogListItem {
maskedRequest: Record<string, unknown>;
responsePayload?: Record<string, unknown>;
error?: Record<string, unknown>;
outboundRequests?: Record<string, unknown>[];
createdAt?: Date;
}
export interface InquiryLogSummary {
total: number;
evaluated: number;
success: number;
failure: number;
noMatch: number;
partial: number;
successRate: number;
failureRate: number;
@@ -97,6 +105,11 @@ export class InquiryLogService {
});
}
async purgeAll(): Promise<{ deletedCount: number }> {
const result = await this.inquiryLogModel.deleteMany({}).exec();
return { deletedCount: result.deletedCount ?? 0 };
}
async findLogs(query: InquiryLogQueryDto): Promise<{
data: InquiryLogListItem[];
page: number;
@@ -114,7 +127,7 @@ export class InquiryLogService {
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error createdAt')
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error outboundRequests createdAt')
.lean()
.exec(),
this.inquiryLogModel.countDocuments(filter),
@@ -132,6 +145,7 @@ export class InquiryLogService {
maskedRequest: log.maskedRequest,
responsePayload: log.responsePayload,
error: log.error,
outboundRequests: log.outboundRequests,
createdAt: log.createdAt,
})),
page,
@@ -153,6 +167,39 @@ export class InquiryLogService {
failure: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] },
},
noMatch: {
$sum: {
$cond: [
{
$or: [
{ $eq: ['$status', InquiryStatus.NO_MATCH] },
{
$and: [
{ $eq: ['$status', InquiryStatus.FAILURE] },
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
],
},
],
},
1,
0,
],
},
},
noMatchFailure: {
$sum: {
$cond: [
{
$and: [
{ $eq: ['$status', InquiryStatus.FAILURE] },
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
],
},
1,
0,
],
},
},
partial: {
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] },
},
@@ -166,13 +213,25 @@ export class InquiryLogService {
_id: 0,
total: 1,
success: 1,
failure: 1,
failure: { $subtract: ['$failure', '$noMatchFailure'] },
evaluated: {
$add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }],
},
noMatch: 1,
partial: 1,
successRate: {
$cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$success', '$total'] }],
$cond: [
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
0,
{ $divide: ['$success', { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
],
},
failureRate: {
$cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$failure', '$total'] }],
$cond: [
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
0,
{ $divide: [{ $subtract: ['$failure', '$noMatchFailure'] }, { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
],
},
averageDuration: { $ifNull: ['$averageDuration', 0] },
minDuration: { $ifNull: ['$minDuration', 0] },
@@ -331,6 +390,9 @@ export class InquiryLogService {
if (query.errorMessage) {
filter['error.message'] = { $regex: query.errorMessage, $options: 'i' };
}
if (query.trackingCode) {
filter.trackingCode = query.trackingCode;
}
return filter;
}
@@ -379,8 +441,10 @@ export class InquiryLogService {
private emptySummary(): InquiryLogSummary {
return {
total: 0,
evaluated: 0,
success: 0,
failure: 0,
noMatch: 0,
partial: 0,
successRate: 0,
failureRate: 0,
+37 -4
View File
@@ -1,9 +1,15 @@
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { Controller, Delete, Get, Query, Req, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { AppException } from '../common/exceptions/app-exception';
import { AuditService } from '../audit/audit.service';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface';
import { Roles } from '../auth/decorators/roles.decorator';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { ADMIN_ROLES } from '../common/enums/role.enum';
import { Role } from '../common/enums/role.enum';
import { InquiryLogQueryDto, InquiryLogTimelineQueryDto } from './dto/inquiry-log-query.dto';
import { InquiryLogService } from './inquiry-log.service';
@@ -11,9 +17,36 @@ import { InquiryLogService } from './inquiry-log.service';
@ApiBearerAuth()
@Controller('inquiry-logs')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(...ADMIN_ROLES)
// Inquiry logs contain operational and potentially sensitive provider payloads.
// Keep the dashboard data restricted to the seeded/managed SUPER_ADMIN role.
@Roles(Role.SUPER_ADMIN)
export class InquiryLogsController {
constructor(private readonly inquiryLogService: InquiryLogService) {}
constructor(
private readonly inquiryLogService: InquiryLogService,
private readonly auditService: AuditService,
) {}
@Delete()
@ApiOperation({ summary: 'Delete all inquiry request logs (explicitly enabled local maintenance action)' })
async purgeAll(
@CurrentUser() user: AuthenticatedUser,
@Req() request: Request,
): Promise<{ deletedCount: number }> {
if (process.env.INQUIRY_LOG_PURGE_ENABLED !== 'true') {
throw new AppException('INQUIRY_LOG_PURGE_DISABLED');
}
const result = await this.inquiryLogService.purgeAll();
await this.auditService.log(AuditEvent.INQUIRY_LOGS_PURGED, {
userId: user.id,
username: user.username,
ip: request.ip,
userAgent: request.headers['user-agent'],
metadata: { deletedCount: result.deletedCount },
});
return result;
}
@Get()
@ApiOperation({ summary: 'Search inquiry request logs' })
@@ -44,6 +44,9 @@ export class InquiryLog {
@Prop({ type: Object })
attemptSummary?: Record<string, unknown>;
@Prop({ type: [Object] })
outboundRequests?: Record<string, unknown>[];
createdAt?: Date;
}