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
+27
View File
@@ -0,0 +1,27 @@
import { DistributedLockService } from '../../src/providers/services/distributed-lock.service';
describe('DistributedLockService', () => {
it('runs the operation under an acquired lease and releases it', async () => {
const service = new DistributedLockService({} as never);
const lease = {
lockKey: 'provider-token:TejaratNou',
ownerId: 'owner-1',
fencingToken: 1,
};
const acquire = jest.spyOn(service, 'acquire').mockResolvedValue(lease);
const release = jest.spyOn(service, 'release').mockResolvedValue(undefined);
await expect(service.withLock(lease.lockKey, async () => 'ok')).resolves.toBe('ok');
expect(acquire).toHaveBeenCalled();
expect(release).toHaveBeenCalledWith(lease);
});
it('fails after the configured wait when the lock is held elsewhere', async () => {
const service = new DistributedLockService({} as never);
jest.spyOn(service, 'acquire').mockResolvedValue(null);
await expect(service.withLock('busy', async () => 'never', { waitMs: 2 })).rejects.toMatchObject({
code: 'ELOCKED',
});
});
});
+10
View File
@@ -0,0 +1,10 @@
import { HealthService } from '../../src/health/health.service';
describe('HealthService', () => {
it('provides safe defaults for memory and disk health checks', () => {
const service = new HealthService();
expect(service.heapThresholdBytes()).toBe(512 * 1024 * 1024);
expect(service.diskThresholdPercent()).toBe(0.9);
expect(service.diskPath()).toBe('/');
});
});
+79
View File
@@ -0,0 +1,79 @@
import { IdempotencyService } from '../../src/idempotency/idempotency.service';
import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema';
class FakeRecordModel {
private readonly records = new Map<string, any>();
findOne(filter: { scopeHash: string }) {
return { exec: async () => this.records.get(filter.scopeHash) ?? null };
}
async create(record: any) {
if (this.records.has(record.scopeHash)) {
throw Object.assign(new Error('duplicate'), { code: 11000 });
}
const saved = { ...record, _id: record.scopeHash };
this.records.set(record.scopeHash, saved);
return saved;
}
updateOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }, update: any) {
return {
exec: async () => {
const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) Object.assign(record, update.$set);
return { acknowledged: true };
},
};
}
deleteOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }) {
return {
exec: async () => {
const record = this.records.get(filter.scopeHash);
if (record?.status === filter.status) this.records.delete(filter.scopeHash);
return { acknowledged: true };
},
};
}
}
describe('IdempotencyService', () => {
it('replays completed responses and rejects body reuse', async () => {
const service = new IdempotencyService(new FakeRecordModel() as never);
const input = {
key: 'request-1',
callerId: 'user-1',
method: 'POST',
path: '/inquiry/person',
body: { birthDate: '1370-01-01', nationalCode: '0012345678' },
};
const reservation = await service.begin(input);
const response = { success: true, trackingCode: 'INQ-1' };
await service.complete(reservation.scopeHash, response, 201);
const replay = await service.begin(input);
expect(replay.replay).toMatchObject({ responseStatus: 201, responseBody: response });
await expect(service.begin({ ...input, body: { different: true } })).rejects.toMatchObject({
normalizedError: { code: 'IDEMPOTENCY_KEY_REUSED' },
});
});
it('rejects a duplicate while the original request is in progress', async () => {
const service = new IdempotencyService(new FakeRecordModel() as never);
const input = {
key: 'request-2',
callerId: 'user-1',
method: 'POST',
path: '/inquiry/person',
body: { nationalCode: '0012345678' },
};
await service.begin(input);
await expect(service.begin(input)).rejects.toMatchObject({
normalizedError: { code: 'IDEMPOTENCY_REQUEST_IN_PROGRESS' },
});
});
});
+22
View File
@@ -0,0 +1,22 @@
import { InquiryType } from '../../src/common/enums/inquiry-type.enum';
import { ParsianProvider } from '../../src/providers/implementations/parsian.provider';
describe('Parsian third-party plate routing', () => {
it('uses the one-factor car-by-plate provider path without a national-code lookup', async () => {
const inquireCarByPlate = jest.fn().mockResolvedValue({ raw: { policy: true } });
const inquireThirdPartyCar = jest.fn();
const provider = Object.create(ParsianProvider.prototype) as any;
provider.config = {};
provider.centInsurCarSupport = { inquireCarByPlate, inquireThirdPartyCar };
const result = await provider.callProvider(
InquiryType.THIRD_PARTY_CAR,
{ nationalCode: '1234567890', plk1: '16', plk2: 'ب', plk3: '498', plksrl: '60' },
{ requestId: 'req-1', trackingCode: 'trk-1' },
);
expect(result).toEqual({ raw: { policy: true } });
expect(inquireCarByPlate).toHaveBeenCalledTimes(1);
expect(inquireThirdPartyCar).not.toHaveBeenCalled();
});
});
+60
View File
@@ -0,0 +1,60 @@
import { ProviderName } from '../../src/common/enums/provider-name.enum';
import { ProviderIsolationService } from '../../src/providers/strategy/provider-isolation.service';
describe('ProviderIsolationService', () => {
const provider = ProviderName.HAMTA;
beforeEach(() => {
delete process.env.PROVIDER_CIRCUIT_FAILURE_THRESHOLD;
delete process.env.PROVIDER_CIRCUIT_OPEN_MS;
delete process.env.PROVIDER_BULKHEAD_LIMIT;
});
it('opens after repeated normalized transport failures and allows a half-open probe', async () => {
process.env.PROVIDER_CIRCUIT_FAILURE_THRESHOLD = '2';
process.env.PROVIDER_CIRCUIT_OPEN_MS = '20';
const isolation = new ProviderIsolationService();
const failure = () => {
const error = new Error('upstream timeout') as Error & {
normalizedError: { code: string };
};
error.normalizedError = { code: 'PROVIDER_TIMEOUT' };
return Promise.reject(error);
};
await expect(isolation.execute(provider, failure)).rejects.toThrow('upstream timeout');
await expect(isolation.execute(provider, failure)).rejects.toThrow('upstream timeout');
await expect(isolation.execute(provider, async () => 'blocked')).rejects.toMatchObject({
normalizedError: { code: 'PROVIDER_CIRCUIT_OPEN' },
});
await new Promise((resolve) => setTimeout(resolve, 25));
await expect(isolation.execute(provider, async () => 'recovered')).resolves.toBe('recovered');
expect(isolation.snapshot(provider)).toMatchObject({
consecutiveFailures: 0,
openUntil: 0,
});
});
it('rejects work when the provider bulkhead is full', async () => {
process.env.PROVIDER_BULKHEAD_LIMIT = '1';
const isolation = new ProviderIsolationService();
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
const first = isolation.execute(provider, async () => {
await held;
return 'done';
});
await new Promise((resolve) => setImmediate(resolve));
await expect(isolation.execute(provider, async () => 'blocked')).rejects.toMatchObject({
normalizedError: { code: 'PROVIDER_BULKHEAD_FULL' },
});
release();
await expect(first).resolves.toBe('done');
});
});
+1
View File
@@ -14,6 +14,7 @@ describe('provider resilience helpers', () => {
it('retries transport failures but not 429 or business rejects', () => {
expect(isTransportRetryable({ code: 'ETIMEDOUT' })).toBe(true);
expect(isTransportRetryable({ response: { status: 503 } })).toBe(true);
expect(isTransportRetryable({ response: { status: 404 } })).toBe(true);
expect(isTransportRetryable({ response: { status: 429 } })).toBe(false);
expect(
isTransportRetryable({
+51
View File
@@ -0,0 +1,51 @@
import {
getCarPolicyProviderError,
parseFirstCarPolicy,
} from '../../src/common/helpers/soap-car-policy.helper';
describe('Parsian car-policy SOAP responses', () => {
it('extracts the Persian message from a nested KeyValue error and classifies no-policy', () => {
const xml = `
<CIIWSPolicyNationalIdResult>
<b:Error>
<b:KeyValueOfstringstring>
<b:Key>2</b:Key>
<b:Value> موردی یافت نشد .</b:Value>
</b:KeyValueOfstringstring>
</b:Error>
</CIIWSPolicyNationalIdResult>`;
expect(getCarPolicyProviderError(xml, parseFirstCarPolicy(xml))).toEqual({
message: 'موردی یافت نشد .',
code: 'CAR_POLICY_NOT_FOUND',
providerCode: '2',
});
});
it('does not classify an unrelated provider error as a no-policy result', () => {
const xml = `
<CIIWSPolicyNationalIdResult>
<b:Error>
<b:KeyValueOfstringstring>
<b:Key>500</b:Key>
<b:Value>خطای موقت سرویس</b:Value>
</b:KeyValueOfstringstring>
</b:Error>
</CIIWSPolicyNationalIdResult>`;
expect(getCarPolicyProviderError(xml, parseFirstCarPolicy(xml))).toEqual({
message: 'خطای موقت سرویس',
code: 'PROVIDER_ERROR',
providerCode: '500',
});
});
it('uses the car-policy catalog code when the response has no policy and no explicit error', () => {
const xml = '<CIIWSPolicyNationalIdResult><b:Error i:nil="true" /></CIIWSPolicyNationalIdResult>';
expect(getCarPolicyProviderError(xml, {})).toEqual({
message: 'No policy record found',
code: 'CAR_POLICY_NOT_FOUND',
});
});
});
+28
View File
@@ -42,6 +42,34 @@ describe('timeout / deadline resilience bugs', () => {
expect(Date.now() - started).toBeLessThan(250);
});
it('aborts the active operation when the attempt timeout wins', async () => {
let aborted = false;
await expect(
runWithProviderResilience(
(signal) =>
new Promise((resolve) => {
signal?.addEventListener('abort', () => {
aborted = true;
resolve('cancelled');
});
}),
{
providerName: 'PARSIAN',
maxAttempts: 1,
timeoutMs: 150,
context: {
requestId: 'req',
trackingCode: 'trk',
},
label: 'PARSIAN request',
},
),
).rejects.toMatchObject({ code: 'ETIMEDOUT' });
expect(aborted).toBe(true);
});
it('default inquiry deadline must exceed a single slow CentInsur SOAP (~30s)', () => {
// thirdPartyCar may need two SOAP calls over a proxy; 20s was killing successful ~28s responses
expect(INQUIRY_DEADLINE_MS).toBeGreaterThanOrEqual(60_000);