Files
yara724api/src/ai/ai.service.ts
T

285 lines
9.6 KiB
TypeScript

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 {
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;
}
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<AiJob>,
) {}
get enabled() {
return this.config.get<string>("AI_DAMAGE_ENABLED") === "true";
}
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<void> {
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,
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,
completedAt: job?.completedAt,
error: job?.error,
errorCode: job?.errorCode,
errorRequestId: job?.errorRequestId,
result: job?.status === "completed" ? job.result : undefined,
};
}),
};
}
async retry(claimId: string, images: AiCapture[]) {
if (this.enabled)
await this.jobs.updateMany(
{
claimId,
imageKey: { $in: images.map((image) => aiImageKey(image.path)) },
status: "failed",
},
{
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
$unset: {
error: 1,
errorCode: 1,
errorRequestId: 1,
leaseToken: 1,
leaseUntil: 1,
},
},
);
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<string>("AI_DAMAGE_URL");
if (!base) throw new Error("AI_DAMAGE_URL is required");
const url = new URL("/api/v1/assessments", base);
const form = new FormData();
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;
}
}
}