Harden Tahesab HTTP client against keep-alive hangs and retry health on alt ports.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -252,20 +252,51 @@ export class TahesabConnectionsService {
|
|||||||
const { row, api } = await this.getApi(organizationId, id);
|
const { row, api } = await this.getApi(organizationId, id);
|
||||||
try {
|
try {
|
||||||
const result = await api.checkHealth();
|
const result = await api.checkHealth();
|
||||||
|
const patch: {
|
||||||
|
lastHealthAt: Date;
|
||||||
|
lastHealthOk: boolean;
|
||||||
|
lastError: string | null;
|
||||||
|
baseUrl?: string;
|
||||||
|
allowInsecureTls?: boolean;
|
||||||
|
} = {
|
||||||
|
lastHealthAt: new Date(),
|
||||||
|
lastHealthOk: true,
|
||||||
|
lastError: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// اگر health فقط با آدرس/پروتکل جایگزین جواب داد، همان را ذخیره کن
|
||||||
|
if (
|
||||||
|
result.usedBaseUrl &&
|
||||||
|
result.usedBaseUrl.replace(/\/+$/, '') !== row.baseUrl.replace(/\/+$/, '')
|
||||||
|
) {
|
||||||
|
patch.baseUrl = result.usedBaseUrl.replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
// اگر فقط با TLS بدون verify جواب داد، فلگ را روشن کن تا بقیهٔ متدها هم کار کنند
|
||||||
|
if (!row.allowInsecureTls && result.usedInsecureTls) {
|
||||||
|
patch.allowInsecureTls = true;
|
||||||
|
}
|
||||||
|
|
||||||
const updated = await this.prisma.accountingConnection.update({
|
const updated = await this.prisma.accountingConnection.update({
|
||||||
where: { id: row.id },
|
where: { id: row.id },
|
||||||
data: {
|
data: patch,
|
||||||
lastHealthAt: new Date(),
|
|
||||||
lastHealthOk: true,
|
|
||||||
lastError: null,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
return { ok: true, connection: this.toDto(updated), health: result };
|
return {
|
||||||
|
ok: true,
|
||||||
|
connection: this.toDto(updated),
|
||||||
|
health: result,
|
||||||
|
adjusted:
|
||||||
|
Boolean(patch.baseUrl) || Boolean(patch.allowInsecureTls)
|
||||||
|
? {
|
||||||
|
baseUrl: patch.baseUrl,
|
||||||
|
allowInsecureTls: patch.allowInsecureTls,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = (err as Error).message ?? 'خطای ناشناخته';
|
const message = (err as Error).message ?? 'خطای ناشناخته';
|
||||||
const hint =
|
const hint =
|
||||||
/مهلت اتصال|timeout/i.test(message) && !row.allowInsecureTls && /^https:/i.test(row.baseUrl)
|
/مهلت اتصال|timeout/i.test(message)
|
||||||
? ' اگر گواهی تهحساب خودامضاست، «پذیرش گواهی SSL خودامضا» را فعال کنید.'
|
? ' از سرور CRM به IP/پورت تهحساب دسترسی شبکه لازم است (فایروال). برای https خودامضا گزینه SSL را فعال کنید. پورت پیشفرض: https 8081 یا http 9550.'
|
||||||
: '';
|
: '';
|
||||||
const full = `${message}${hint}`.slice(0, 500);
|
const full = `${message}${hint}`.slice(0, 500);
|
||||||
const updated = await this.prisma.accountingConnection.update({
|
const updated = await this.prisma.accountingConnection.update({
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export type TahesabCallOptions = {
|
|||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
token: string;
|
token: string;
|
||||||
dbName: string;
|
dbName: string;
|
||||||
/** مسیر OpenAPI مثل DoNewMoshtari یا CheckHealth-SSL */
|
/** مسیر OpenAPI مثل DoNewMoshtari یا CheckHealth-SSL؛ خالی = ریشه */
|
||||||
path: string;
|
path: string;
|
||||||
/** کلید body؛ اگر خالی باشد فقط GET بدون body */
|
/** کلید body؛ اگر خالی باشد فقط GET بدون body */
|
||||||
bodyKey?: string;
|
bodyKey?: string;
|
||||||
@@ -38,6 +38,32 @@ function extractTahesabError(json: unknown, text: string): string {
|
|||||||
return trimmed ? trimmed.slice(0, 300) : '';
|
return trimmed ? trimmed.slice(0, 300) : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** نامزدهای آدرس برای تست سلامت (پورت/پروتکل پیشفرض تهحساب) */
|
||||||
|
export function tahesabHealthBaseCandidates(baseUrl: string): string[] {
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(baseUrl.trim().replace(/\/+$/, ''));
|
||||||
|
} catch {
|
||||||
|
return [baseUrl.trim().replace(/\/+$/, '')];
|
||||||
|
}
|
||||||
|
const host = u.hostname;
|
||||||
|
const out: string[] = [`${u.protocol}//${u.host}`];
|
||||||
|
if (u.protocol === 'https:') {
|
||||||
|
out.push(`http://${host}:9550`);
|
||||||
|
out.push(`http://${host}:8081`);
|
||||||
|
if (u.port && u.port !== '9550' && u.port !== '8081') {
|
||||||
|
out.push(`http://${host}:${u.port}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.push(`https://${host}:8081`);
|
||||||
|
out.push(`http://${host}:9550`);
|
||||||
|
if (u.port && u.port !== '8081' && u.port !== '9550') {
|
||||||
|
out.push(`https://${host}:${u.port}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...new Set(out.filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TahesabHttpClient {
|
export class TahesabHttpClient {
|
||||||
private readonly logger = new Logger(TahesabHttpClient.name);
|
private readonly logger = new Logger(TahesabHttpClient.name);
|
||||||
@@ -45,17 +71,18 @@ export class TahesabHttpClient {
|
|||||||
async call<T = unknown>(opts: TahesabCallOptions): Promise<T> {
|
async call<T = unknown>(opts: TahesabCallOptions): Promise<T> {
|
||||||
const base = opts.baseUrl.replace(/\/+$/, '');
|
const base = opts.baseUrl.replace(/\/+$/, '');
|
||||||
const path = (opts.path ?? '').replace(/^\/+/, '');
|
const path = (opts.path ?? '').replace(/^\/+/, '');
|
||||||
// Postman تهحساب برای health به ریشه میزند (بدون path)
|
|
||||||
const url = path ? new URL(`${base}/${path}`) : new URL(base);
|
const url = path ? new URL(`${base}/${path}`) : new URL(base);
|
||||||
const method = opts.method ?? (opts.bodyKey ? 'POST' : 'GET');
|
const method = opts.method ?? (opts.bodyKey ? 'POST' : 'GET');
|
||||||
const timeoutMs = opts.timeoutMs ?? 30_000;
|
const timeoutMs = opts.timeoutMs ?? 30_000;
|
||||||
const label = path || '(root)';
|
const label = `${method} ${path || '(root)'} @ ${url.host}`;
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
Authorization: `Bearer ${opts.token}`,
|
Authorization: `Bearer ${opts.token}`,
|
||||||
DBname: opts.dbName,
|
DBname: opts.dbName,
|
||||||
DBName: opts.dbName,
|
DBName: opts.dbName,
|
||||||
Accept: 'application/json',
|
Accept: 'application/json',
|
||||||
|
// بعضی نسخههای وبسرویس ویندوزی keep-alive را نمیبندند و Node تا timeout میماند
|
||||||
|
Connection: 'close',
|
||||||
};
|
};
|
||||||
|
|
||||||
let body: string | undefined;
|
let body: string | undefined;
|
||||||
@@ -69,8 +96,10 @@ export class TahesabHttpClient {
|
|||||||
const lib = isHttps ? https : http;
|
const lib = isHttps ? https : http;
|
||||||
const agent =
|
const agent =
|
||||||
isHttps && opts.allowInsecureTls
|
isHttps && opts.allowInsecureTls
|
||||||
? new https.Agent({ rejectUnauthorized: false })
|
? new https.Agent({ rejectUnauthorized: false, keepAlive: false })
|
||||||
: undefined;
|
: isHttps
|
||||||
|
? new https.Agent({ keepAlive: false })
|
||||||
|
: new http.Agent({ keepAlive: false });
|
||||||
|
|
||||||
return new Promise<T>((resolve, reject) => {
|
return new Promise<T>((resolve, reject) => {
|
||||||
let settled = false;
|
let settled = false;
|
||||||
@@ -94,8 +123,20 @@ export class TahesabHttpClient {
|
|||||||
},
|
},
|
||||||
(res) => {
|
(res) => {
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
res.on('data', (c) => chunks.push(c));
|
let received = 0;
|
||||||
res.on('end', () => {
|
const expectedLen = Number(res.headers['content-length']);
|
||||||
|
let bodyDone = false;
|
||||||
|
|
||||||
|
const completeBody = () => {
|
||||||
|
if (bodyDone || settled) return;
|
||||||
|
bodyDone = true;
|
||||||
|
// بعد از خواندن کامل، سوکت را قطع کن تا hang روی keep-alive نماند
|
||||||
|
try {
|
||||||
|
res.destroy();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
|
||||||
const text = Buffer.concat(chunks).toString('utf8');
|
const text = Buffer.concat(chunks).toString('utf8');
|
||||||
let json: unknown = null;
|
let json: unknown = null;
|
||||||
if (text) {
|
if (text) {
|
||||||
@@ -121,7 +162,7 @@ export class TahesabHttpClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Tahesab ${method} ${label} → ${status}: ${text.slice(0, 400)}`,
|
`Tahesab ${label} → ${status}: ${text.slice(0, 400)}`,
|
||||||
);
|
);
|
||||||
finish(() =>
|
finish(() =>
|
||||||
reject(
|
reject(
|
||||||
@@ -134,7 +175,6 @@ export class TahesabHttpClient {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// بعضی متدها با ۲۰۰ و فیلد ERROR برمیگردند
|
|
||||||
if (json && typeof json === 'object' && 'ERROR' in (json as object)) {
|
if (json && typeof json === 'object' && 'ERROR' in (json as object)) {
|
||||||
if (isEmptyOk) {
|
if (isEmptyOk) {
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
@@ -153,11 +193,27 @@ export class TahesabHttpClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
finish(() => resolve(json as T));
|
finish(() => resolve(json as T));
|
||||||
|
};
|
||||||
|
|
||||||
|
res.on('data', (c: Buffer) => {
|
||||||
|
chunks.push(c);
|
||||||
|
received += c.length;
|
||||||
|
if (
|
||||||
|
Number.isFinite(expectedLen) &&
|
||||||
|
expectedLen > 0 &&
|
||||||
|
received >= expectedLen
|
||||||
|
) {
|
||||||
|
completeBody();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res.on('end', () => completeBody());
|
||||||
|
res.on('close', () => {
|
||||||
|
// اگر بادی آمده ولی end نیامده (سرور عجیب)، با دادهٔ موجود تمام کن
|
||||||
|
if (!settled && chunks.length) completeBody();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// مهلت از لحظهٔ شروع (شامل اتصال TCP/TLS) — timeout سوکت Node فقط بعد از connect است
|
|
||||||
const hardTimer = setTimeout(() => {
|
const hardTimer = setTimeout(() => {
|
||||||
req.destroy();
|
req.destroy();
|
||||||
finish(() =>
|
finish(() =>
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import type { TahesabHttpClient, TahesabCallOptions } from './tahesab-http.client';
|
import {
|
||||||
|
tahesabHealthBaseCandidates,
|
||||||
|
type TahesabHttpClient,
|
||||||
|
type TahesabCallOptions,
|
||||||
|
} from './tahesab-http.client';
|
||||||
|
|
||||||
export type ConnCreds = {
|
export type ConnCreds = {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
@@ -178,46 +182,67 @@ export class TahesabApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* تست سلامت مطابق Postman تهحساب:
|
* تست سلامت مطابق Postman تهحساب (ریشه + CheckHealth).
|
||||||
* ابتدا ریشهٔ baseUrl، بعد /CheckHealth، در نهایت مسیر SSL یا No-SSL بر اساس پروتکل.
|
* روی تایماوت، پورت/پروتکل جایگزین (8081/9550) و در صورت نیاز TLS بدون verify را هم امتحان میکند.
|
||||||
*/
|
*/
|
||||||
async checkHealth() {
|
async checkHealth(): Promise<{
|
||||||
const isHttps = /^https:/i.test(this.creds.baseUrl.trim());
|
Status?: string;
|
||||||
const timeoutMs = 12_000;
|
Api_Status?: string;
|
||||||
|
usedBaseUrl?: string;
|
||||||
|
usedPath?: string;
|
||||||
|
usedInsecureTls?: boolean;
|
||||||
|
}> {
|
||||||
|
const timeoutMs = 8_000;
|
||||||
type Health = { Status?: string; Api_Status?: string };
|
type Health = { Status?: string; Api_Status?: string };
|
||||||
const attempts: Array<{
|
const bases = tahesabHealthBaseCandidates(this.creds.baseUrl);
|
||||||
path: string;
|
const insecureFlags = this.creds.allowInsecureTls
|
||||||
bodyKey?: string;
|
? [true]
|
||||||
method: 'GET' | 'POST';
|
: [false, true];
|
||||||
}> = [
|
|
||||||
{ path: '', method: 'GET' },
|
|
||||||
{ path: '', bodyKey: 'CheckHealth', method: 'POST' },
|
|
||||||
{ path: 'CheckHealth', method: 'GET' },
|
|
||||||
{
|
|
||||||
path: isHttps ? 'CheckHealth-SSL' : 'CheckHealth-No-SSL',
|
|
||||||
method: 'GET',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
let lastErr: unknown;
|
let lastErr: unknown;
|
||||||
for (const attempt of attempts) {
|
for (const baseUrl of bases) {
|
||||||
try {
|
const isHttps = /^https:/i.test(baseUrl);
|
||||||
return await this.call<Health>(
|
const pathAttempts: Array<{
|
||||||
attempt.path,
|
path: string;
|
||||||
attempt.bodyKey,
|
bodyKey?: string;
|
||||||
attempt.bodyKey ? [] : undefined,
|
method: 'GET' | 'POST';
|
||||||
attempt.method,
|
}> = [
|
||||||
timeoutMs,
|
{ path: '', method: 'GET' },
|
||||||
);
|
{ path: '', bodyKey: 'CheckHealth', method: 'POST' },
|
||||||
} catch (err) {
|
{ path: 'CheckHealth', method: 'GET' },
|
||||||
lastErr = err;
|
{
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
path: isHttps ? 'CheckHealth-SSL' : 'CheckHealth-No-SSL',
|
||||||
// خطای گواهی با تلاشهای بعدی روی همان https حل نمیشود
|
method: 'GET',
|
||||||
if (/certificate|UNABLE_TO_VERIFY|self-signed|CERT_/i.test(msg)) {
|
},
|
||||||
throw err;
|
];
|
||||||
|
|
||||||
|
for (const allowInsecureTls of insecureFlags) {
|
||||||
|
if (!isHttps && allowInsecureTls) continue;
|
||||||
|
for (const attempt of pathAttempts) {
|
||||||
|
try {
|
||||||
|
const health = await this.http.call<Health>({
|
||||||
|
...this.creds,
|
||||||
|
baseUrl,
|
||||||
|
allowInsecureTls,
|
||||||
|
path: attempt.path,
|
||||||
|
bodyKey: attempt.bodyKey,
|
||||||
|
args: attempt.bodyKey ? [] : undefined,
|
||||||
|
method: attempt.method,
|
||||||
|
timeoutMs,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...health,
|
||||||
|
usedBaseUrl: baseUrl,
|
||||||
|
usedPath: attempt.path || '(root)',
|
||||||
|
usedInsecureTls: allowInsecureTls,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
lastErr = err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw lastErr instanceof Error
|
throw lastErr instanceof Error
|
||||||
? lastErr
|
? lastErr
|
||||||
: new Error('تست اتصال تهحساب ناموفق بود.');
|
: new Error('تست اتصال تهحساب ناموفق بود.');
|
||||||
|
|||||||
Reference in New Issue
Block a user