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
+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 });
}
});
});