Added AI damage helper

This commit is contained in:
SepehrYahyaee
2026-10-03 16:38:48 +03:30
parent 18ccfa81e4
commit 2f92766689
22 changed files with 1085 additions and 442 deletions
+86
View File
@@ -0,0 +1,86 @@
import { SuperAdminController } from "src/super-admin/super-admin.controller";
import { ForbiddenException } from "@nestjs/common";
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.controller";
describe("AI analysis file access", () => {
const actor = { sub: "actor", clientKey: "tenant" };
it.each(["getAiAnalysis", "retryAiAnalysis"])(
"expert %s uses the existing file access gate before reading results or scheduling work",
async (method) => {
const service = {
getClaimDetailV2: jest.fn().mockRejectedValue(new ForbiddenException()),
};
const ai = { list: jest.fn(), retry: jest.fn() },
db = { findById: jest.fn() };
const controller = new ExpertClaimV2Controller(
service as any,
ai as any,
db as any,
{} as any,
);
await expect(controller[method]("other-tenant", actor)).rejects.toThrow(
ForbiddenException,
);
expect(db.findById).not.toHaveBeenCalled();
expect(ai.list).not.toHaveBeenCalled();
expect(ai.retry).not.toHaveBeenCalled();
},
);
it.each(["getAiAnalysis", "retryAiAnalysis"])(
"insurer %s validates its public file identifier before resolving a claim",
async (method) => {
const service = {
retrieveFileDetailsByPublicId: jest
.fn()
.mockRejectedValue(new ForbiddenException()),
};
const ai = { list: jest.fn(), retry: jest.fn() },
db = { findById: jest.fn() };
const controller = new ExpertInsurerController(
service as any,
{} as any,
ai as any,
db as any,
);
await expect(controller[method](actor, "other-tenant")).rejects.toThrow(
ForbiddenException,
);
expect(service.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
"tenant",
"other-tenant",
);
expect(db.findById).not.toHaveBeenCalled();
},
);
});
describe("admin AI tenant selection", () => {
it.each(["getAiAnalysis", "retryAiAnalysis"])(
"%s resolves the file inside the selected tenant before reading AI results",
async (method) => {
const insurer = {
retrieveFileDetailsByPublicId: jest
.fn()
.mockRejectedValue(new ForbiddenException()),
};
const ai = { list: jest.fn(), retry: jest.fn() },
db = { findById: jest.fn() };
const controller = new SuperAdminController(
{} as any,
{} as any,
insurer as any,
ai as any,
db as any,
);
await expect(
controller[method]("selected-client", "other-client-file"),
).rejects.toThrow(ForbiddenException);
expect(insurer.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
"selected-client",
"other-client-file",
);
expect(db.findById).not.toHaveBeenCalled();
},
);
});
+102
View File
@@ -0,0 +1,102 @@
import { Types } from "mongoose";
import { ForbiddenException } from "@nestjs/common";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
function setup() {
const id = new Types.ObjectId(),
userId = new Types.ObjectId().toString();
const claim = {
_id: id,
owner: { fullName: "تست" },
workflow: { currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES },
damage: {
selectedParts: [
{ id: 123, name: "Fender", side: "Left", label_fa: "گلگیر" },
],
},
media: {
damagedParts: [
{
id: 123,
name: "Fender",
path: "files/previous.jpg",
url: "/files/previous.jpg",
},
],
carAngles: {},
},
};
const service = Object.create(ClaimRequestManagementService.prototype) as any;
const db = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
};
const ai = { enqueue: jest.fn().mockResolvedValue(undefined) };
Object.assign(service, {
claimCaseDbService: db,
aiService: ai,
resolveClaimEffectiveUserId: jest.fn().mockResolvedValue(userId),
assertEffectiveUserIsDamagedPartyOnClaim: jest
.fn()
.mockResolvedValue(undefined),
autoSubmitFanavaranAttachment: jest.fn().mockResolvedValue({}),
logger: { error: jest.fn() },
});
const file = {
path: "files/current.jpg",
filename: "current.jpg",
} as Express.Multer.File;
return { id: id.toString(), userId, service, db, ai, file };
}
describe("real capture flow AI scheduling", () => {
it.each(["user", "field_expert", "file_maker", "file_reviewer"])(
"%s capture persists the exact part photo before queueing without waiting for inference",
async (role) => {
const { id, userId, service, db, ai, file } = setup();
const result = await service.capturePartV2(
id,
{ captureType: "part", captureKey: "123" },
file,
userId,
{ sub: userId, role },
);
expect(
db.findByIdAndUpdate.mock.calls[0][1]["media.damagedParts.0"],
).toMatchObject({ path: file.path, fileName: file.filename });
expect(ai.enqueue).toHaveBeenCalledWith(
id,
expect.objectContaining({ path: file.path, fileName: file.filename }),
);
expect(db.findByIdAndUpdate.mock.invocationCallOrder[0]).toBeLessThan(
ai.enqueue.mock.invocationCallOrder[0],
);
expect(result.captureKey).toBe("123");
},
);
it("does not send car angle photos to the part-analysis queue", async () => {
const { id, userId, service, ai, file } = setup();
await service.capturePartV2(
id,
{ captureType: "angle", captureKey: "front" },
file,
userId,
);
expect(ai.enqueue).not.toHaveBeenCalled();
});
it("does not enqueue an unauthorized upload", async () => {
const { id, userId, service, ai, file } = setup();
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
new ForbiddenException(),
);
await expect(
service.capturePartV2(
id,
{ captureType: "part", captureKey: "123" },
file,
userId,
),
).rejects.toThrow(ForbiddenException);
expect(ai.enqueue).not.toHaveBeenCalled();
});
});
+27
View File
@@ -0,0 +1,27 @@
import type { AiCapture } from "./ai.service";
/** Use current media only: removed parts and replaced photos belong to history. */
export function currentAiCaptures(claim: any): AiCapture[] {
const parts = claim?.media?.damagedParts;
const rows = Array.isArray(parts)
? parts
: Object.entries(parts ?? {})
.filter(
([key]) =>
!["front", "back", "left", "right"].includes(key.toLowerCase()),
)
.map(([, row]) => row);
const seen = new Set<string>();
return rows.flatMap((row: any) => {
if (typeof row?.path !== "string" || !row.path.trim() || seen.has(row.path))
return [];
seen.add(row.path);
return [
{
path: row.path,
fileName: row.fileName,
label: row.label_fa || row.name || "تصویر خسارت",
},
];
});
}
+26
View File
@@ -0,0 +1,26 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Schema as MongoSchema } from "mongoose";
import { AiResult } from "./ai-result";
@Schema({ collection: "ai-damage-jobs", timestamps: true, versionKey: false })
export class AiJob {
@Prop({ required: true }) claimId: string;
@Prop({ required: true }) imageKey: string;
@Prop({ required: true }) path: string;
@Prop() fileName?: string;
@Prop({
default: "queued",
enum: ["queued", "processing", "completed", "failed"],
})
status: string;
@Prop({ default: 0 }) attempts: number;
@Prop({ default: () => new Date() }) nextAttemptAt: Date;
@Prop() leaseUntil?: Date;
@Prop() leaseToken?: string;
@Prop() completedAt?: Date;
@Prop() error?: string;
@Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult;
}
export const AiJobSchema = SchemaFactory.createForClass(AiJob);
AiJobSchema.index({ claimId: 1, imageKey: 1 }, { unique: true });
AiJobSchema.index({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
+95
View File
@@ -0,0 +1,95 @@
import { normalizeAiResult } from "./ai-result";
import { currentAiCaptures } from "./ai-captures";
const response = () => ({
distinct_damaged_parts_report: {
parts: [
{
part_name: "Headlight",
damage_severity: "Severe",
part_bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
confidence: 0.95,
side: "Right",
car_side: "front_right",
},
{
part_name: "Headlight",
damage_severity: null,
part_bbox: null,
confidence: null,
},
],
report: "گزارش تصویر",
},
damaged_part_table: [{ name: "Headlight" }],
case_report: "گزارش کامل",
});
describe("AI response contract", () => {
it("preserves distinct repeated detections, nullable fields and Persian reports without requiring a returned image", () => {
const result = normalizeAiResult(response());
expect(result.parts).toHaveLength(2);
expect(result.parts[0]).toMatchObject({
name: "Headlight",
severity: "Severe",
confidence: 0.95,
bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
});
expect(result.parts[1]).toMatchObject({
name: "Headlight",
bbox: null,
severity: null,
confidence: null,
});
expect(result).toMatchObject({
report: "گزارش تصویر",
caseReport: "گزارش کامل",
});
});
it("does not turn corrupt or failed responses into a successful empty analysis", () => {
for (const value of [
null,
{},
{ detail: "failure" },
{ ...response(), case_report: null },
])
expect(() => normalizeAiResult(value)).toThrow();
});
it("accepts a legitimate zero-detection response", () => {
const value = response();
value.distinct_damaged_parts_report.parts = [];
expect(normalizeAiResult(value).parts).toEqual([]);
});
it("omits corrupt boxes and out-of-range confidence without discarding the part", () => {
const value = response();
value.distinct_damaged_parts_report.parts[0].part_bbox.x2 = NaN;
value.distinct_damaged_parts_report.parts[0].confidence = 1.2;
expect(normalizeAiResult(value).parts[0]).toMatchObject({
name: "Headlight",
bbox: null,
confidence: null,
});
});
it("lists current photos only, deduplicates identical files and excludes history and unphotographed additions", () => {
const images = currentAiCaptures({
media: {
damagedParts: [
{ path: "files/new.jpg", label_fa: "گلگیر" },
{ path: "files/new.jpg" },
{ name: "door" },
],
},
damage: {
partSelectionHistory: [{ removedParts: [{ path: "files/old.jpg" }] }],
},
});
expect(images).toEqual([
{ path: "files/new.jpg", fileName: undefined, label: "گلگیر" },
]);
expect(
currentAiCaptures({
media: { damagedParts: { door: { path: "files/door.jpg" } } },
}),
).toHaveLength(1);
});
});
+63
View File
@@ -0,0 +1,63 @@
export interface AiPart {
name: string;
severity: string | null;
confidence: number | null;
side: string | null;
carSide: string | null;
bbox: { x1: number; y1: number; x2: number; y2: number } | null;
}
export interface AiResult {
parts: AiPart[];
report: string;
caseReport: string;
}
const text = (v: unknown): string | null =>
typeof v === "string" ? v.trim().slice(0, 20000) : null;
/** Preserve detections independently: repeated names may describe different boxes. */
export function normalizeAiResult(value: unknown): AiResult {
const raw = value as any;
const report = raw?.distinct_damaged_parts_report;
if (
!report ||
!Array.isArray(report.parts) ||
typeof report.report !== "string" ||
typeof raw.case_report !== "string"
) {
throw new Error("Invalid AI response");
}
if (report.parts.length > 500) throw new Error("Too many AI detections");
const parts = report.parts.map((part: any): AiPart => {
const name = text(part?.part_name);
if (!name) throw new Error("Invalid AI part");
const b = part.part_bbox;
const bbox =
b &&
[b.x1, b.y1, b.x2, b.y2].every(
(v) => typeof v === "number" && Number.isFinite(v),
) &&
b.x2 > b.x1 &&
b.y2 > b.y1
? { x1: b.x1, y1: b.y1, x2: b.x2, y2: b.y2 }
: null;
return {
name,
bbox,
severity: text(part.damage_severity),
confidence:
typeof part.confidence === "number" &&
Number.isFinite(part.confidence) &&
part.confidence >= 0 &&
part.confidence <= 1
? part.confidence
: null,
side: text(part.side),
carSide: text(part.car_side),
};
});
return {
parts,
report: text(report.report) ?? "",
caseReport: text(raw.case_report) ?? "",
};
}
+5 -1
View File
@@ -1,8 +1,12 @@
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { AiService } from "./ai.service";
import { AiJob, AiJobSchema } from "./ai-job.schema";
@Module({
imports: [],
imports: [
MongooseModule.forFeature([{ name: AiJob.name, schema: AiJobSchema }]),
],
providers: [AiService],
exports: [AiService],
})
+266
View File
@@ -0,0 +1,266 @@
import { ConfigService } from "@nestjs/config";
import { AiService, aiImageKey } from "./ai.service";
import { AiJobSchema } from "./ai-job.schema";
const image = { path: "files/part.jpg", label: "گلگیر" };
const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" };
function setup(enabled = true) {
const jobs = {
updateOne: jest.fn().mockResolvedValue({}),
updateMany: jest.fn().mockResolvedValue({}),
find: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([]) }),
findOneAndUpdate: jest
.fn()
.mockReturnValue({ lean: jest.fn().mockResolvedValue(null) }),
};
const config = new ConfigService({
AI_DAMAGE_ENABLED: String(enabled),
AI_DAMAGE_URL: "http://example.test",
AI_DAMAGE_TIMEOUT_MS: 1000,
});
return { service: new AiService(config, jobs as any), jobs };
}
function claimJob(
jobs: ReturnType<typeof setup>["jobs"],
fields: Record<string, unknown> = {},
) {
jobs.findOneAndUpdate.mockImplementation((_q: any, update: any) => ({
lean: async () => ({
_id: "job1",
claimId: "claim1",
imageKey: aiImageKey(image.path),
...image,
status: "processing",
attempts: 1,
leaseToken: update.$set.leaseToken,
...fields,
}),
}));
}
describe("durable AI jobs", () => {
it("is opt-in and does not send or enqueue photos when disabled", async () => {
const { service, jobs } = setup(false);
await service.enqueue("claim1", image);
await service.work();
expect(jobs.updateOne).not.toHaveBeenCalled();
expect(jobs.findOneAndUpdate).not.toHaveBeenCalled();
});
it("uniquely queues each claim/photo and never resets a completed job on repeated uploads", async () => {
const { service, jobs } = setup();
await service.enqueue("claim1", image);
expect(AiJobSchema.indexes()).toContainEqual([
{ claimId: 1, imageKey: 1 },
{ unique: true, background: true },
]);
expect(jobs.updateOne).toHaveBeenCalledWith(
{ claimId: "claim1", imageKey: aiImageKey(image.path) },
{
$setOnInsert: expect.objectContaining({
status: "queued",
attempts: 0,
}),
},
{ upsert: true },
);
});
it("a persistence failure does not fail the photo upload", async () => {
const { service, jobs } = setup();
jobs.updateOne.mockRejectedValue(new Error("offline"));
await expect(service.enqueue("claim1", image)).resolves.toBeUndefined();
});
it("leases pending and expired jobs atomically and persists only the owning worker's result", async () => {
const { service, jobs } = setup();
claimJob(jobs);
jest.spyOn(service, "aiRequestImage").mockResolvedValue(result);
await service.work();
const [filter, update] = jobs.findOneAndUpdate.mock.calls[0];
expect(filter.$or).toEqual([
expect.objectContaining({ status: "queued" }),
expect.objectContaining({
status: "processing",
leaseUntil: expect.any(Object),
}),
]);
expect(update.$inc).toEqual({ attempts: 1 });
expect(jobs.updateOne).toHaveBeenCalledWith(
expect.objectContaining({
_id: "job1",
leaseToken: update.$set.leaseToken,
}),
expect.objectContaining({
$set: expect.objectContaining({ status: "completed", result }),
}),
);
});
it("prevents overlapping processing in one instance", async () => {
const { service, jobs } = setup();
claimJob(jobs);
let finish!: (v: typeof result) => void;
jest.spyOn(service, "aiRequestImage").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const first = service.work();
await Promise.resolve();
await Promise.resolve();
await service.work();
expect(jobs.findOneAndUpdate).toHaveBeenCalledTimes(1);
finish(result);
await first;
});
it("retries transient failures with delay, but stops after three attempts", async () => {
for (const attempts of [1, 3]) {
const { service, jobs } = setup();
claimJob(jobs, { attempts });
jest
.spyOn(service, "aiRequestImage")
.mockRejectedValue(new Error("timeout"));
await service.work();
expect(jobs.updateOne).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
$set: expect.objectContaining({
status: attempts === 1 ? "queued" : "failed",
nextAttemptAt: expect.any(Date),
}),
}),
);
}
});
it("does not retry invalid/non-car images automatically", async () => {
const { service, jobs } = setup();
claimJob(jobs);
jest
.spyOn(service, "aiRequestImage")
.mockRejectedValue({ response: { status: 400 } });
await service.work();
expect(jobs.updateOne).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
$set: expect.objectContaining({
status: "failed",
error: "خودرو در تصویر تشخیص داده نشد.",
}),
}),
);
});
it("never sends another request after recovering a repeatedly crashed job beyond its limit", async () => {
const { service, jobs } = setup();
claimJob(jobs, { attempts: 4 });
const send = jest.spyOn(service, "aiRequestImage");
await service.work();
expect(send).not.toHaveBeenCalled();
});
it("only returns current photo results and never exposes storage paths or provider payloads", async () => {
const { service, jobs } = setup();
jobs.find.mockReturnValue({
lean: jest.fn().mockResolvedValue([
{
imageKey: aiImageKey(image.path),
status: "completed",
result,
path: "private",
attempts: 1,
},
]),
});
const view = await service.list("claim1", [image]);
expect(jobs.find).toHaveBeenCalledWith({
claimId: "claim1",
imageKey: { $in: [aiImageKey(image.path)] },
});
expect(view.images[0]).toMatchObject({
label: "گلگیر",
status: "completed",
result,
});
expect(view.images[0]).not.toHaveProperty("path");
});
it("manual retry affects only failed jobs for current claim/photos", async () => {
const { service, jobs } = setup();
await service.retry("claim1", [image]);
expect(jobs.updateMany).toHaveBeenCalledWith(
{
claimId: "claim1",
imageKey: { $in: [aiImageKey(image.path)] },
status: "failed",
},
expect.objectContaining({
$set: expect.objectContaining({ status: "queued", attempts: 0 }),
}),
);
});
});
describe("AI multipart transport", () => {
it("posts real image bytes under images with every pipeline flag and no returned-image dependency", async () => {
const fs = await import("node:fs/promises");
const { resolve, join } = await import("node:path");
const axios = (await import("axios")).default;
const root = await fs.mkdtemp("/tmp/yara-ai-jest-");
const file = join(root, "test.jpg");
const bytes = Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xff, 0xd9]);
await fs.writeFile(file, bytes);
const realpath = fs.realpath;
const pathSpy = jest
.spyOn(fs, "realpath")
.mockImplementation(((path: string) =>
path === resolve("files")
? Promise.resolve(root)
: realpath(path)) as any);
const post = jest
.spyOn(axios, "post")
.mockImplementation(async (url, form: any, config) => {
const parsed = new URL(String(url));
expect(parsed.pathname).toBe("/pipeline/detect_parts_with_damages");
for (const option of [
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
expect(parsed.searchParams.get(option)).toBe("true");
expect(config?.headers?.["content-type"]).toMatch(
/^multipart\/form-data; boundary=/,
);
expect(config?.maxRedirects).toBe(0);
const chunks: Buffer[] = [];
await new Promise<void>((resolve, reject) => {
form.on("data", (chunk: string | Buffer) =>
chunks.push(Buffer.from(chunk)),
);
form.on("end", resolve);
form.on("error", reject);
form.resume();
});
const body = Buffer.concat(chunks);
expect(
body.includes(Buffer.from('name="images"; filename="test.jpg"')),
).toBe(true);
expect(body.includes(bytes)).toBe(true);
return {
data: {
distinct_damaged_parts_report: { parts: [], report: "گزارش" },
case_report: "گزارش کامل",
},
} as any;
});
try {
const { service } = setup();
await expect(
service.aiRequestImage({ path: file, fileName: "test.jpg" }),
).resolves.toMatchObject({ parts: [], report: "گزارش" });
await expect(
service.aiRequestImage({ path: "/etc/hosts" }),
).rejects.toThrow("outside upload storage");
expect(post).toHaveBeenCalledTimes(1);
} finally {
pathSpy.mockRestore();
post.mockRestore();
await fs.rm(root, { recursive: true, force: true });
}
});
});
+220 -175
View File
@@ -1,204 +1,249 @@
import { createReadStream, existsSync } from "node:fs";
import { join } from "node:path";
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 {
HttpException,
HttpStatus,
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { AxiosRequestConfig } from "axios"; // TODO: Change all axios usages to HttpModule
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 { 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 {
private apiKey: string;
private accessToken: string = null;
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>,
) {}
// These configurations are for authentication and getting the API key.
private readonly loginOptions: AxiosRequestConfig = {
method: "POST",
headers: { "Content-Type": "application/json" },
url: `${this.configService.get<string>("AI_URL_V2")}/auth/login`,
data: {
username: this.configService.get<string>("AI_USERNAME"),
password: this.configService.get<string>("AI_PASSWORD"),
},
timeout: 1000, // TODO: Make this ENV
};
constructor(private readonly configService: ConfigService) {}
private get profileOptions(): AxiosRequestConfig {
return {
method: "GET",
url: `${this.configService.get<string>("AI_URL_V2")}/auth/profile`,
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
};
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),
);
}
// This getter dynamically creates the base options for the image processing request.
private get imageProcessOptions(): AxiosRequestConfig {
return {
method: "POST",
url: `${process.env.AI_URL_V2}/services/car-damage/detector?version=ai-v7`,
headers: {
Authorization: `Bearer ${this.accessToken}`,
"gateway-api-key": `${this.apiKey}`,
},
};
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();
}
async onModuleInit() {
/** 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 {
const res = await this.login();
// if (res?.accessToken) {
// this.accessToken = res.accessToken;
// await this.getApiKey();
// }
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) {
// Don't prevent app startup if AI service is temporarily unavailable
// The service will attempt to re-authenticate when aiRequestImage is called
// Reset tokens so re-authentication will be attempted
this.accessToken = null;
this.apiKey = null;
// 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.",
);
}
}
private async login() {
// const loginResponse = await axios.request(this.loginOptions);
// return loginResponse.data;
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,
result: job?.status === "completed" ? job.result : undefined,
};
}),
};
}
private async getApiKey() {
// const profileResponse = await axios.request(this.profileOptions);
// this.apiKey = profileResponse.data.apiKey.key;
// return this.apiKey;
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, leaseToken: 1, leaseUntil: 1 },
},
);
return this.list(claimId, images);
}
public async aiRequestImage(file: {
path: string;
fileName?: string;
}): Promise<any> {
// Ensure authentication is set up
if (!this.accessToken || !this.apiKey) {
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 > 20 * 1024 * 1024)
throw new Error("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(
"pipeline/detect_parts_with_damages",
base.replace(/\/?$/, "/"),
);
for (const option of [
"side",
"segments",
"bounding_box",
"severity",
"confidence",
])
url.searchParams.set(option, "true");
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: 21 * 1024 * 1024,
maxContentLength: 2 * 1024 * 1024,
maxRedirects: 0,
});
return normalizeAiResult(data);
} 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 {
const res = await this.login();
// if (res?.accessToken) {
// this.accessToken = res.accessToken;
// await this.getApiKey();
// } else {
// throw new HttpException(
// "AI Service authentication failed",
// HttpStatus.UNAUTHORIZED,
// );
// }
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, leaseUntil: 1, leaseToken: 1 },
});
} catch (error) {
throw new HttpException(
"AI Service authentication failed",
HttpStatus.UNAUTHORIZED,
if (this.stopping) return; // Leave lease for another process after shutdown.
const status = (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 === 400
? "خودرو در تصویر تشخیص داده نشد."
: status === 422 || status === 415
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
nextAttemptAt: new Date(
Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3),
),
},
$unset: { leaseUntil: 1, leaseToken: 1 },
});
this.logger.warn(
`AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.`,
);
}
}
// Resolve relative paths to absolute paths
const filePath = file.path.startsWith("/")
? file.path
: join(process.cwd(), file.path.replace(/^\.\//, ""));
// Check if file exists
if (!existsSync(filePath)) {
throw new HttpException(
`File not found: ${file.path}`,
HttpStatus.NOT_FOUND,
);
}
// const form = new FormData();
const fileStream = createReadStream(filePath);
// Append file with filename if available
if (file.fileName) {
// form.append("images", fileStream, file.fileName);
} else {
// Extract filename from path if not provided
const pathParts = filePath.split("/");
const extractedFileName = pathParts[pathParts.length - 1];
// form.append("images", fileStream, extractedFileName);
}
try {
const requestHeaders = {
...this.imageProcessOptions.headers,
// ...form.getHeaders(),
};
const fs = require("fs");
const stats = fs.statSync(filePath);
// const response = await axios.request({
// ...this.imageProcessOptions,
// headers: requestHeaders,
// // data: form,
// maxContentLength: Infinity,
// maxBodyLength: Infinity,
// });
// Validate response structure
// if (!response.data) {
// throw new HttpException(
// "AI Service returned empty response",
// HttpStatus.BAD_GATEWAY,
// );
// }
// // Check for error in response first (AI service returns 201 with error in body)
// if (response.data.error) {
// throw new HttpException(
// `AI Service error: ${response.data.error}`,
// HttpStatus.BAD_GATEWAY,
// );
// }
// // Check for processed image (downloadLink)
// if (!response.data.downloadLink) {
// throw new HttpException(
// "AI Service did not return processed image (downloadLink missing)",
// HttpStatus.BAD_GATEWAY,
// );
// }
// return response.data;
} catch (er) {
// Determine error source
let errorSource = "UNKNOWN";
let errorMessage = er.message;
let errorDetails = "No error details available";
if (er.response) {
errorSource = "AI_SERVICE_RESPONSE";
errorMessage =
er.response?.data?.message ||
er.message ||
`HTTP ${er.response.status}`;
errorDetails = er.response?.data
? JSON.stringify(er.response.data, null, 2)
: `Status: ${er.response.status}, StatusText: ${er.response.statusText}`;
} else if (er.request) {
errorSource = "NETWORK_ERROR";
errorMessage = "Network error - AI service did not respond";
errorDetails = "Request was made but no response received";
} else {
errorSource = "REQUEST_SETUP_ERROR";
errorMessage = er.message || "Error setting up request";
}
// Re-throw with detailed error information
throw new HttpException(
`[${errorSource}] ${errorMessage}`,
er.response?.status || HttpStatus.INTERNAL_SERVER_ERROR,
} catch {
this.logger.error(
"AI worker storage unavailable; will retry on the next tick.",
);
} finally {
this.abort = undefined;
this.busy = false;
}
}
}