261 lines
8.5 KiB
TypeScript
261 lines
8.5 KiB
TypeScript
import * as http from 'http';
|
|
import * as https from 'https';
|
|
import { URL } from 'url';
|
|
import {
|
|
BadGatewayException,
|
|
Injectable,
|
|
Logger,
|
|
RequestTimeoutException,
|
|
} from '@nestjs/common';
|
|
|
|
export type TahesabCallOptions = {
|
|
baseUrl: string;
|
|
token: string;
|
|
dbName: string;
|
|
/** مسیر OpenAPI مثل DoNewMoshtari یا CheckHealth-SSL؛ خالی = ریشه */
|
|
path: string;
|
|
/** کلید body؛ اگر خالی باشد فقط GET بدون body */
|
|
bodyKey?: string;
|
|
args?: unknown[];
|
|
method?: 'GET' | 'POST';
|
|
allowInsecureTls?: boolean;
|
|
timeoutMs?: number;
|
|
/**
|
|
* اگر تهحساب با فیلد ERROR و متن منطبق جواب داد، بهجای ۵۰۲
|
|
* مقدار خالی ([] ) برگردان — مثل «رکوردی یافت نشد» در DoListAsnad.
|
|
*/
|
|
emptyResultOnError?: RegExp;
|
|
};
|
|
|
|
function extractTahesabError(json: unknown, text: string): string {
|
|
if (json && typeof json === 'object') {
|
|
const o = json as Record<string, unknown>;
|
|
const err = o.ERROR ?? o.Error ?? o.error ?? o.message ?? o.Message;
|
|
if (typeof err === 'string' && err.trim()) return err.trim().slice(0, 300);
|
|
if (Array.isArray(err) && err.length) return String(err[0]).slice(0, 300);
|
|
}
|
|
const trimmed = text.trim();
|
|
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()
|
|
export class TahesabHttpClient {
|
|
private readonly logger = new Logger(TahesabHttpClient.name);
|
|
|
|
async call<T = unknown>(opts: TahesabCallOptions): Promise<T> {
|
|
const base = opts.baseUrl.replace(/\/+$/, '');
|
|
const path = (opts.path ?? '').replace(/^\/+/, '');
|
|
const url = path ? new URL(`${base}/${path}`) : new URL(base);
|
|
const method = opts.method ?? (opts.bodyKey ? 'POST' : 'GET');
|
|
const timeoutMs = opts.timeoutMs ?? 30_000;
|
|
const label = `${method} ${path || '(root)'} @ ${url.host}`;
|
|
|
|
const headers: Record<string, string> = {
|
|
Authorization: `Bearer ${opts.token}`,
|
|
DBname: opts.dbName,
|
|
DBName: opts.dbName,
|
|
Accept: 'application/json',
|
|
// بعضی نسخههای وبسرویس ویندوزی keep-alive را نمیبندند و Node تا timeout میماند
|
|
Connection: 'close',
|
|
};
|
|
|
|
let body: string | undefined;
|
|
if (method === 'POST' && opts.bodyKey) {
|
|
headers['Content-Type'] = 'application/json';
|
|
body = JSON.stringify({ [opts.bodyKey]: opts.args ?? [] });
|
|
headers['Content-Length'] = Buffer.byteLength(body).toString();
|
|
}
|
|
|
|
const isHttps = url.protocol === 'https:';
|
|
const lib = isHttps ? https : http;
|
|
const agent =
|
|
isHttps && opts.allowInsecureTls
|
|
? new https.Agent({ rejectUnauthorized: false, keepAlive: false })
|
|
: isHttps
|
|
? new https.Agent({ keepAlive: false })
|
|
: new http.Agent({ keepAlive: false });
|
|
|
|
return new Promise<T>((resolve, reject) => {
|
|
let settled = false;
|
|
const finish = (fn: () => void) => {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(hardTimer);
|
|
fn();
|
|
};
|
|
|
|
const req = lib.request(
|
|
{
|
|
protocol: url.protocol,
|
|
hostname: url.hostname,
|
|
port: url.port || (isHttps ? 443 : 80),
|
|
path: `${url.pathname}${url.search}` || '/',
|
|
method,
|
|
headers,
|
|
timeout: timeoutMs,
|
|
agent,
|
|
},
|
|
(res) => {
|
|
const chunks: Buffer[] = [];
|
|
let received = 0;
|
|
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');
|
|
let json: unknown = null;
|
|
if (text) {
|
|
try {
|
|
json = JSON.parse(text);
|
|
} catch {
|
|
json = { raw: text };
|
|
}
|
|
}
|
|
const status = res.statusCode ?? 0;
|
|
const detail = extractTahesabError(json, text);
|
|
const isEmptyOk =
|
|
Boolean(detail) &&
|
|
Boolean(opts.emptyResultOnError) &&
|
|
opts.emptyResultOnError!.test(detail);
|
|
|
|
if (status < 200 || status >= 300) {
|
|
if (isEmptyOk) {
|
|
this.logger.debug(
|
|
`Tahesab ${label} ${status} empty-on-error: ${detail.slice(0, 120)}`,
|
|
);
|
|
finish(() => resolve([] as T));
|
|
return;
|
|
}
|
|
this.logger.warn(
|
|
`Tahesab ${label} → ${status}: ${text.slice(0, 400)}`,
|
|
);
|
|
finish(() =>
|
|
reject(
|
|
new BadGatewayException(
|
|
detail
|
|
? `تهحساب (${status}): ${detail}`
|
|
: `پاسخ نامعتبر تهحساب (${status}) برای ${label}`,
|
|
),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
if (json && typeof json === 'object' && 'ERROR' in (json as object)) {
|
|
if (isEmptyOk) {
|
|
this.logger.debug(
|
|
`Tahesab ${label} empty-on-error: ${detail.slice(0, 120)}`,
|
|
);
|
|
finish(() => resolve([] as T));
|
|
return;
|
|
}
|
|
finish(() =>
|
|
reject(
|
|
new BadGatewayException(
|
|
detail ? `تهحساب: ${detail}` : `خطای تهحساب برای ${label}`,
|
|
),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
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();
|
|
});
|
|
},
|
|
);
|
|
|
|
const hardTimer = setTimeout(() => {
|
|
req.destroy();
|
|
finish(() =>
|
|
reject(
|
|
new RequestTimeoutException(
|
|
`مهلت اتصال به تهحساب برای ${label} به پایان رسید.`,
|
|
),
|
|
),
|
|
);
|
|
}, timeoutMs);
|
|
|
|
req.on('timeout', () => {
|
|
req.destroy();
|
|
finish(() =>
|
|
reject(
|
|
new RequestTimeoutException(
|
|
`مهلت اتصال به تهحساب برای ${label} به پایان رسید.`,
|
|
),
|
|
),
|
|
);
|
|
});
|
|
|
|
req.on('error', (err) => {
|
|
if (settled) return;
|
|
this.logger.error(`Tahesab call failed: ${label}`, err);
|
|
const raw = err.message || String(err);
|
|
const tlsHint =
|
|
/self-signed|certificate|UNABLE_TO_VERIFY|CERT_/i.test(raw)
|
|
? ' — در تنظیمات اتصال، گزینه «پذیرش گواهی SSL خودامضا» را فعال کنید.'
|
|
: '';
|
|
finish(() =>
|
|
reject(
|
|
new BadGatewayException(
|
|
`اتصال به تهحساب ناموفق بود: ${raw}${tlsHint}`,
|
|
),
|
|
),
|
|
);
|
|
});
|
|
|
|
if (body) req.write(body);
|
|
req.end();
|
|
});
|
|
}
|
|
}
|