자료관 앱을 원앤올 공통 패키지 기준으로 최신화
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { POST } from "./route";
|
||||
|
||||
const authority = vi.hoisted(() => ({ registry: vi.fn(), owner: vi.fn() }));
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => ({
|
||||
...await importOriginal<typeof import("@/server/file-registry-attestation")>(),
|
||||
attestRegisteredFile: authority.registry, attestReuploadOwner: authority.owner,
|
||||
}));
|
||||
const jobId = "123e4567-e89b-42d3-a456-426614174000";
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const registered = { fileSn: "file-1", projectId: "project-1", clsfSystmSn: "category-1", classificationPath: ["p", "c"], useYn: "Y" };
|
||||
const body = { file_sn: "file-1", project_id: "project-1", clsf_systm_sn: "category-1" };
|
||||
const request = (data: unknown = body) => new NextRequest("https://dc.invalid/api/flask-service/conversion-failures/lookup", {
|
||||
method: "POST", headers: { "Content-Type": "application/json", Cookie: `Authorization=${jwt}` },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const call = (action: string, data?: unknown) => POST(request(data), { params: Promise.resolve({ action }) });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("FLASK_API_URL", "https://rag.invalid");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "existing-test-key");
|
||||
authority.registry.mockResolvedValue(registered);
|
||||
authority.owner.mockResolvedValue(undefined);
|
||||
});
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("conversion failure-history registry proxy", () => {
|
||||
it.each(["lookup", "record"])("attests both read scope and owner before %s; replaces browser authority", async action => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ file_sn: "file-1", status: "FAILED", failures: [] }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await call(action, { ...body, conversion_job_id: jobId,
|
||||
source_path: "/attacker", registry_context: { subjectSha256: "forged" } });
|
||||
expect(response.status).toBe(200);
|
||||
expect(authority.registry).toHaveBeenCalledOnce();
|
||||
expect(authority.owner).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchMock.mock.calls[0]!;
|
||||
expect(String(url)).toBe(`https://rag.invalid/flask-service/convert-to-pdf/failures/${action}`);
|
||||
const sent = JSON.parse(init.body);
|
||||
expect(sent.file_sn).toBe("file-1");
|
||||
expect(sent.registry_context).toMatchObject(registered);
|
||||
expect(sent.registry_context.subjectSha256).not.toBe("forged");
|
||||
expect(sent.source_path).toBeUndefined();
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("existing-test-key");
|
||||
expect(new Headers(init.headers).get("Authorization")).toBe(jwt);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each(["retry", "quarantine", "../retry", "unknown"])("does not forward an unrecognized action %s", async action => {
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call(action)).status).toBe(404);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a missing failed job for recording before dispatch", async () => {
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record")).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks unauthorized documents before failure-history access", async () => {
|
||||
const { FileRegistryError } = await import("@/server/file-registry-attestation");
|
||||
authority.owner.mockRejectedValue(new FileRegistryError(403, "REUPLOAD_OWNER_FORBIDDEN", "문서 권한이 없습니다."));
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record", { ...body, conversion_job_id: jobId })).status).toBe(403);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves an upstream conflict and never automatically repeats a lost failure-record receipt", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(Response.json({ detail: "PROCESSING" }, { status: 409 }))
|
||||
.mockRejectedValueOnce(new TypeError("lost response"));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record", { ...body, conversion_job_id: jobId })).status).toBe(409);
|
||||
const unknown = await call("record", { ...body, conversion_job_id: jobId });
|
||||
expect(unknown.status).toBe(502);
|
||||
expect((await unknown.json()).detail.dispatchState).toBe("UNKNOWN");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
import {
|
||||
attestRegisteredFile, attestReuploadOwner, dcRagUrl, FileRegistryError,
|
||||
ragInternalHeaders, registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
/** Failure recording and lookup never create a document-processing job. */
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
context: { params: Promise<{ action: string }> },
|
||||
): Promise<Response> {
|
||||
const diagnostic = operationDiagnostics("conversion-failures");
|
||||
let dispatched = false;
|
||||
let fileSn: string | undefined;
|
||||
const fail = (status: number, code: string, message: string) => diagnostic.finish(
|
||||
NextResponse.json({ detail: { code, message, dispatchState: dispatched ? "UNKNOWN" : "NOT_SENT" } }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
}), { code, fileSn },
|
||||
);
|
||||
try {
|
||||
const { action } = await context.params;
|
||||
if (!["lookup", "record"].includes(action)) {
|
||||
return fail(404, "CONVERSION_FAILURES_NOT_FOUND", "요청한 실패 이력 기능을 찾지 못했습니다.");
|
||||
}
|
||||
if (Number(request.headers.get("content-length") ?? 0) > 16_384) {
|
||||
return fail(413, "CONVERSION_FAILURES_TOO_LARGE", "실패 이력 요청 크기를 초과했습니다.");
|
||||
}
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const raw: unknown = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid body");
|
||||
body = raw as Record<string, unknown>;
|
||||
} catch {
|
||||
return fail(400, "CONVERSION_FAILURES_INVALID", "실패 이력 요청이 올바르지 않습니다.");
|
||||
}
|
||||
fileSn = typeof body.file_sn === "string" ? body.file_sn : undefined;
|
||||
const projectId = typeof body.project_id === "string" ? body.project_id : "";
|
||||
const classification = typeof body.clsf_systm_sn === "string" ? body.clsf_systm_sn : "";
|
||||
const idField = action === "record" ? "conversion_job_id" : null;
|
||||
if (!fileSn || !/^[A-Za-z0-9_-]{1,128}$/.test(fileSn) || !projectId || !classification ||
|
||||
(idField && (typeof body[idField] !== "string" || !/^[a-f0-9-]{36}$/i.test(body[idField] as string)))) {
|
||||
return fail(400, "CONVERSION_FAILURES_INVALID", "파일·분류·실패 작업 정보를 확인해 주세요.");
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn: classification });
|
||||
// Keep the same owner boundary for retained registration-failure history.
|
||||
await attestReuploadOwner(request, registered);
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
headers.set("Content-Type", "application/json");
|
||||
headers.set("x-request-id", diagnostic.requestId);
|
||||
const payload = {
|
||||
file_sn: registered.fileSn,
|
||||
registry_context: registryForwardContext(registered, headers),
|
||||
...(idField ? { [idField]: body[idField] } : {}),
|
||||
};
|
||||
dispatched = true;
|
||||
const upstream = await fetch(dcRagUrl(`/convert-to-pdf/failures/${action}`), {
|
||||
method: "POST", headers, body: JSON.stringify(payload), cache: "no-store", signal: request.signal,
|
||||
});
|
||||
const response = new Response(await upstream.text(), {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
return diagnostic.finish(response, { fileSn, upstreamRequestId: upstream.headers.get("x-request-id") });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) return fail(error.status, error.code, error.message);
|
||||
return fail(request.signal.aborted ? 499 : 502, "CONVERSION_FAILURES_UNAVAILABLE",
|
||||
"실패 이력 요청 결과를 확인하지 못했습니다.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user