import { publicAiResult } from "./ai-result"; import { createHash, randomUUID } from "node:crypto"; import { createReadStream } from "node:fs"; import { realpath, stat } from "node:fs/promises"; import { basename, resolve, sep } from "node:path"; import { BadRequestException, ConflictException, ServiceUnavailableException, Injectable, Logger, OnModuleDestroy, OnModuleInit, } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { InjectModel } from "@nestjs/mongoose"; import { Model } from "mongoose"; import axios from "axios"; import FormData = require("form-data"); import { AiJob } from "./ai-job.schema"; import { AiAssessmentError, normalizeAiResult } from "./ai-result"; import { buildFileLink } from "src/helpers/urlCreator"; export interface AiCapture { path: string; fileName?: string; label?: string; carName?: string; includePrices?: boolean; priceMinSeverity?: string; } export const aiImageKey = (path: string) => createHash("sha256").update(resolve(path)).digest("hex"); @Injectable() export class AiService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(AiService.name); private timer?: NodeJS.Timeout; private busy = false; private stopping = false; private abort?: AbortController; constructor( private readonly config: ConfigService, @InjectModel(AiJob.name) private readonly jobs: Model, ) {} get enabled() { return this.config.get("AI_DAMAGE_ENABLED") === "true"; } get priceMinSeverity(): string { const value = this.config.get("AI_DAMAGE_PRICE_MIN_SEVERITY") ?? "severe"; return value === "null" ? "minor" : value; } private get timeout() { return Math.min( 600000, Math.max(1000, Number(this.config.get("AI_DAMAGE_TIMEOUT_MS")) || 180000), ); } onModuleInit() { if (!this.enabled) return; this.timer = setInterval(() => { void this.work(); }, 5000); this.timer.unref(); void this.work(); } onModuleDestroy() { this.stopping = true; clearInterval(this.timer); this.abort?.abort(); } /** Only persist the job here; never wait for the AI in an upload request. */ async enqueue(claimId: string, image: AiCapture): Promise { if (!this.enabled || !image.path) return; try { await this.jobs.updateOne( { claimId, imageKey: aiImageKey(image.path) }, { $setOnInsert: { claimId, imageKey: aiImageKey(image.path), path: image.path, fileName: image.fileName, status: "queued", attempts: 0, nextAttemptAt: new Date(), }, }, { upsert: true }, ); } catch (error) { // Concurrent duplicate uploads are already queued. A storage outage must not fail capture. if ((error as any)?.code !== 11000) this.logger.error( "Could not persist AI job; expert review will retry scheduling.", ); } } async list(claimId: string, images: AiCapture[]) { // Older captures and jobs missed during a database outage are scheduled on review. for (const image of images) await this.enqueue(claimId, image); const keys = images.map((image) => aiImageKey(image.path)); const rows = await this.jobs .find({ claimId, imageKey: { $in: keys } }) .lean(); const byKey = new Map(rows.map((row) => [row.imageKey, row])); return { enabled: this.enabled, priceMinSeverity: this.priceMinSeverity, images: images.map((image) => { const key = aiImageKey(image.path); const job = byKey.get(key); return { imageKey: key, label: image.label ?? "تصویر خسارت", imageUrl: buildFileLink(image.path), status: job?.status ?? (this.enabled ? "queued" : "disabled"), attempts: job?.attempts ?? 0, pricingRequested: job?.includePrices === true, pricingCarName: job?.carName, pricingMinSeverity: job?.priceMinSeverity, completedAt: job?.completedAt, error: job?.error, errorCode: job?.errorCode, result: job?.status === "completed" ? publicAiResult(job.result) : undefined, }; }), }; } async retry(claimId: string, images: AiCapture[], allowPricing = true) { if (this.enabled) await this.jobs.updateMany( { claimId, imageKey: { $in: images.map((image) => aiImageKey(image.path)) }, status: "failed", ...(!allowPricing ? { includePrices: { $ne: true } } : {}), }, { $set: { status: "queued", attempts: 0, nextAttemptAt: new Date() }, $unset: { error: 1, errorCode: 1, errorRequestId: 1, leaseToken: 1, leaseUntil: 1, }, }, ); return this.list(claimId, images); } /** Explicit advisory request: never maps AI part names or writes claim valuations. */ async requestPricing( claimId: string, images: AiCapture[], input: { imageKey: string; carName: string }, ) { if (!this.enabled) throw new ServiceUnavailableException( "سرویس تحلیل هوش مصنوعی در این محیط غیرفعال است.", ); const carName = typeof input?.carName === "string" ? input.carName.trim() : ""; if ( carName.length < 2 || carName.length > 100 || !/[آ-ی]/.test(carName) || /[\r\n\x00-\x1f]/.test(carName) ) throw new BadRequestException( "نام و مدل خودروی زیان‌دیده را به فارسی و حداکثر در ۱۰۰ کاراکتر وارد کنید.", ); const image = images.find( (item) => aiImageKey(item.path) === input?.imageKey, ); if (!image) throw new BadRequestException( "تصویر انتخاب‌شده متعلق به تصاویر فعلی این پرونده نیست. صفحه را تازه کنید.", ); await this.enqueue(claimId, image); const change = await this.jobs.updateOne( { claimId, imageKey: input.imageKey, status: { $ne: "processing" }, $or: [{ status: { $ne: "queued" } }, { includePrices: { $ne: true } }], }, { $set: { status: "queued", includePrices: true, carName, priceMinSeverity: this.priceMinSeverity, attempts: 0, nextAttemptAt: new Date(), }, $unset: { result: 1, completedAt: 1, error: 1, errorCode: 1, errorRequestId: 1, leaseToken: 1, leaseUntil: 1, }, }, ); if (!change.matchedCount) throw new ConflictException( "تحلیل این تصویر در صف یا در حال اجراست. پس از پایان آن دوباره تلاش کنید.", ); return this.list(claimId, images); } async aiRequestImage(file: AiCapture, signal?: AbortSignal) { // Only local managed uploads; never fetch a supplied URL or arbitrary server file. const root = await realpath(resolve("files")); const path = await realpath(resolve(file.path)); if (!path.startsWith(root + sep)) throw new Error("Image outside upload storage"); const info = await stat(path); if (!info.isFile() || info.size <= 0) throw new AiAssessmentError(null, null, 422, "Invalid image size"); if (info.size > 15 * 1024 * 1024) throw new AiAssessmentError(null, null, 413, "Invalid image size"); const base = this.config.get("AI_DAMAGE_URL"); if (!base) throw new Error("AI_DAMAGE_URL is required"); const url = new URL("/api/v1/assessments", base); url.searchParams.set("include_polygons", "false"); url.searchParams.set( "include_prices", file.includePrices ? "true" : "false", ); if (file.includePrices) { if (!file.carName) throw new BadRequestException( "نام فارسی خودرو برای برآورد قیمت لازم است.", ); url.searchParams.set( "price_min_severity", file.priceMinSeverity || this.priceMinSeverity, ); } const form = new FormData(); if (file.includePrices) form.append("car", file.carName!); const stream = createReadStream(path); form.append("images", stream, { filename: file.fileName || basename(path), knownLength: info.size, }); try { const { data } = await axios.post(url.toString(), form, { headers: form.getHeaders(), timeout: this.timeout, signal, maxBodyLength: 16 * 1024 * 1024, maxContentLength: 2 * 1024 * 1024, maxRedirects: 0, }); return normalizeAiResult(data); } catch (error) { if (axios.isAxiosError(error) && error.response?.data?.error) { const detail = error.response.data.error; const safeText = (value: unknown) => typeof value === "string" ? value.slice(0, 500) : null; throw new AiAssessmentError( safeText(detail.code), safeText(detail.request_id), error.response.status, safeText(detail.message) ?? undefined, ); } throw error; } finally { stream.destroy(); } } /** Atomic leases make this safe across replicas and recover jobs after a restart. */ async work() { if (!this.enabled || this.busy || this.stopping) return; this.busy = true; try { const now = new Date(); const token = randomUUID(); const job = await this.jobs .findOneAndUpdate( { $or: [ { status: "queued", nextAttemptAt: { $lte: now } }, { status: "processing", leaseUntil: { $lte: now } }, ], }, { $set: { status: "processing", leaseToken: token, leaseUntil: new Date(now.getTime() + this.timeout + 60000), }, $inc: { attempts: 1 }, }, { new: true, sort: { nextAttemptAt: 1 } }, ) .lean(); if (!job) return; const owned = { _id: job._id, status: "processing", leaseToken: token }; try { if (job.attempts > 3) throw new Error("Retry limit reached"); this.abort = new AbortController(); const result = await this.aiRequestImage(job, this.abort.signal); await this.jobs.updateOne(owned, { $set: { status: "completed", result, completedAt: new Date() }, $unset: { error: 1, errorCode: 1, errorRequestId: 1, leaseUntil: 1, leaseToken: 1, }, }); } catch (error) { if (this.stopping) return; // Leave lease for another process after shutdown. const providerError = error instanceof AiAssessmentError ? error : undefined; const status = providerError?.httpStatus ?? (error as any)?.response?.status; const terminal = job.attempts >= 3 || [400, 401, 403, 404, 413, 415, 422].includes(status); await this.jobs.updateOne(owned, { $set: { status: terminal ? "failed" : "queued", error: status === 413 ? "حجم تصویر برای تحلیل باید حداکثر ۱۵ مگابایت باشد." : status === 400 ? "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت." : status === 422 || status === 415 ? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید." : "تحلیل تصویر انجام نشد. دوباره تلاش کنید.", ...(providerError?.code ? { errorCode: providerError.code } : {}), ...(providerError?.requestId ? { errorRequestId: providerError.requestId } : {}), nextAttemptAt: new Date( Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3), ), }, $unset: { leaseUntil: 1, leaseToken: 1, ...(!providerError?.code ? { errorCode: 1 } : {}), ...(!providerError?.requestId ? { errorRequestId: 1 } : {}), }, }); this.logger.warn( `AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.` + (providerError ? ` ${JSON.stringify({ code: providerError.code, requestId: providerError.requestId })}` : ""), ); } } catch { this.logger.error( "AI worker storage unavailable; will retry on the next tick.", ); } finally { this.abort = undefined; this.busy = false; } } }