자료관 앱을 원앤올 공통 패키지 기준으로 최신화
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST } from "./route";
|
||||
import { attestReuploadOwner } from "@/server/file-registry-attestation";
|
||||
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("@/server/file-registry-attestation")>();
|
||||
return {
|
||||
...original,
|
||||
attestRegisteredFile: vi.fn(async () => ({
|
||||
fileSn: "file-1", projectId: "test-project", clsfSystmSn: "test-leaf",
|
||||
classificationPath: ["test-project", "test-leaf"], useYn: "Y",
|
||||
})),
|
||||
attestReuploadOwner: vi.fn(async () => undefined),
|
||||
registryAuthHeaders: vi.fn(() => new Headers({
|
||||
Authorization: `Bearer x.${Buffer.from(JSON.stringify({ sub: "test-user" })).toString("base64url")}.y`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
const requestWithParser = (parserEngine?: string) => {
|
||||
const form = new FormData();
|
||||
form.set("pdf_path", "./output_pdf/file-1.pdf");
|
||||
form.set("original_filename", "source.pdf");
|
||||
form.set("file_sn", "file-1");
|
||||
form.set("project_id", "test-project");
|
||||
form.set("clsf_systm_sn", "test-leaf");
|
||||
if (parserEngine) form.set("parser_engine", parserEngine);
|
||||
return new NextRequest("http://localhost/api/flask-service/embed-documents/jobs", {
|
||||
method: "POST", body: form,
|
||||
});
|
||||
};
|
||||
|
||||
describe("explicit parser selection", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("rejects parser selection before registry access when the canary is disabled", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "0");
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-kordoc-candidate"));
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toMatchObject({ detail: {
|
||||
code: "KORDOC_CANARY_SCOPE_FORBIDDEN", dispatchState: "NOT_SENT",
|
||||
} });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unknown parser value before any registry or RAG dispatch", async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("unverified-engine"));
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toMatchObject({ detail: {
|
||||
code: "PARSER_ENGINE_INVALID", dispatchState: "NOT_SENT",
|
||||
} });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["0", "1"])("forwards explicit Docling when KorDoc selection is %s", async enabled => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", enabled);
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-docling"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect((fetchMock.mock.calls[0]![1].body as FormData).get("parser_engine")).toBe("source-docling");
|
||||
});
|
||||
|
||||
it("preserves omitted-parser API compatibility for the server default", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "1");
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser());
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect((fetchMock.mock.calls[0]![1].body as FormData).has("parser_engine")).toBe(false);
|
||||
});
|
||||
|
||||
it("forwards the selected parser for a registered file through the configured RAG service", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "1");
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockImplementation(async (_url: URL, init: RequestInit) => {
|
||||
const body = init.body as FormData;
|
||||
expect(body.get("parser_engine")).toBe("source-kordoc-candidate");
|
||||
expect(body.get("file_sn")).toBe("file-1");
|
||||
expect(JSON.parse(String(body.get("registry_context")))).toMatchObject({
|
||||
projectId: "test-project", fileSn: "file-1",
|
||||
});
|
||||
return Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111",
|
||||
completion_attestation: "a".repeat(32),
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-kordoc-candidate"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
|
||||
"http://127.0.0.1:18081/flask-service/embed-documents/jobs",
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards reupload staging and expected Current only with the server key", async () => {
|
||||
const staging = "00000000-0000-4000-8000-000000000002";
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const form = new FormData();
|
||||
form.set("pdf_path", `./output_pdf/${staging}.pdf`);
|
||||
form.set("original_filename", "same.pdf");
|
||||
form.set("file_sn", "file-1");
|
||||
form.set("project_id", "test-project");
|
||||
form.set("clsf_systm_sn", "test-leaf");
|
||||
form.set("reupload_staging_file_sn", staging);
|
||||
form.set("reupload_expected_current_ingestion_id", "old-ingestion");
|
||||
const upstream = vi.fn(async (_url: URL, init: RequestInit) => {
|
||||
const sent = init.body as FormData;
|
||||
expect(sent.get("reupload_staging_file_sn")).toBe(staging);
|
||||
expect(sent.get("reupload_expected_current_ingestion_id")).toBe("old-ingestion");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
return Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const response = await POST(new NextRequest("http://localhost/api/flask-service/embed-documents/jobs", {
|
||||
method: "POST", body: form,
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(attestReuploadOwner).toHaveBeenCalledOnce();
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("initial embedding precondition forwarding", () => {
|
||||
it.each(["true", "false", "1"])("accepts only the explicit initial boolean true (%s)", async flag => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32) })); vi.stubGlobal("fetch", fetchMock);
|
||||
const request = requestWithParser(); const form = await request.formData(); form.set("initial_embedding_only", flag); vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
const response = await POST(request);
|
||||
expect(response.status).toBe(flag === "true" ? 200 : 400);
|
||||
if (flag === "true") expect((fetchMock.mock.calls[0]![1].body as FormData).get("initial_embedding_only")).toBe("true");
|
||||
else expect(fetchMock).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
import {
|
||||
attestReuploadOwner,
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
ragInternalHeaders,
|
||||
registryAuthHeaders,
|
||||
type RegistryDiagnostic,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
function failureResponse(
|
||||
status: number, code: string, message: string,
|
||||
dispatchState: "NOT_SENT" | "UNKNOWN" = "NOT_SENT",
|
||||
diagnostic?: RegistryDiagnostic,
|
||||
): NextResponse {
|
||||
return NextResponse.json({ detail: { code, message, dispatchState, ...(diagnostic ? { diagnostic } : {}) } }, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store", "X-Rag-Dispatch-State": dispatchState },
|
||||
});
|
||||
}
|
||||
|
||||
function formString(form: FormData, name: string): string {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest): Promise<Response> {
|
||||
const diagnostic = operationDiagnostics("embed-start");
|
||||
let diagnosticFileSn: string | undefined;
|
||||
const failure: typeof failureResponse = (...args) => diagnostic.finish(failureResponse(...args), {
|
||||
code: args[1], fileSn: diagnosticFileSn,
|
||||
});
|
||||
// Once the POST starts, a lost receipt cannot prove that RAG did not accept it.
|
||||
let ragRequestStarted = false;
|
||||
try {
|
||||
const length = Number(request.headers.get("content-length") ?? 0);
|
||||
if (length > 16_384) {
|
||||
return failure(413, "EMBED_REQUEST_TOO_LARGE", "임베딩 요청이 너무 큽니다.");
|
||||
}
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await request.formData();
|
||||
} catch {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "임베딩 요청이 올바르지 않습니다.");
|
||||
}
|
||||
const pdfPath = formString(form, "pdf_path");
|
||||
const originalFilename = formString(form, "original_filename");
|
||||
const fileSn = formString(form, "file_sn");
|
||||
diagnosticFileSn = /^[A-Za-z0-9_-]{1,128}$/.test(fileSn) ? fileSn : undefined;
|
||||
const reuploadStagingFileSn = formString(form, "reupload_staging_file_sn");
|
||||
const reuploadExpectedCurrentIngestionId = formString(form, "reupload_expected_current_ingestion_id");
|
||||
const projectId = formString(form, "project_id");
|
||||
const clsfSystmSn = formString(form, "clsf_systm_sn");
|
||||
const parserEngine = formString(form, "parser_engine");
|
||||
const initialEmbeddingOnly = formString(form, "initial_embedding_only");
|
||||
if (initialEmbeddingOnly && initialEmbeddingOnly !== "true") {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "최초 임베딩 요청이 올바르지 않습니다.");
|
||||
}
|
||||
if (initialEmbeddingOnly && reuploadStagingFileSn) {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "최초 임베딩과 재임베딩을 함께 요청할 수 없습니다.");
|
||||
}
|
||||
if (!pdfPath || !originalFilename || !fileSn || !projectId || !clsfSystmSn) {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "파일 및 분류 정보가 필요합니다.");
|
||||
}
|
||||
// For reupload, the physical upload ID is distinct from the registered
|
||||
// logical file ID. Only that upload's converted PDF may be dispatched.
|
||||
const physicalFileSn = reuploadStagingFileSn || fileSn;
|
||||
const staged = !reuploadStagingFileSn ||
|
||||
(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(reuploadStagingFileSn) &&
|
||||
reuploadStagingFileSn !== fileSn);
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(fileSn) || !staged ||
|
||||
pdfPath !== `./output_pdf/${physicalFileSn}.pdf`) {
|
||||
return failure(400, "EMBED_PDF_PATH_MISMATCH", "등록된 파일의 PDF 경로가 아닙니다.");
|
||||
}
|
||||
if ((reuploadStagingFileSn && !/^[A-Za-z0-9_-]{1,256}$/.test(reuploadExpectedCurrentIngestionId)) ||
|
||||
(!reuploadStagingFileSn && reuploadExpectedCurrentIngestionId)) {
|
||||
return failure(400, "REUPLOAD_CURRENT_REQUIRED", "기존 Current 식별자가 필요합니다.");
|
||||
}
|
||||
if (parserEngine && parserEngine !== "source-docling" && parserEngine !== "source-kordoc-candidate") {
|
||||
return failure(400, "PARSER_ENGINE_INVALID", "PDF 파서 선택값이 올바르지 않습니다.");
|
||||
}
|
||||
if (parserEngine === "source-kordoc-candidate" && process.env.KORDOC_CANARY_ENABLED !== "1") {
|
||||
return failure(403, "KORDOC_CANARY_SCOPE_FORBIDDEN", "PDF 파서 선택이 현재 비활성화되어 있습니다.");
|
||||
}
|
||||
|
||||
const registered = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn });
|
||||
if (reuploadStagingFileSn) await attestReuploadOwner(request, registered);
|
||||
const target = dcRagUrl("/embed-documents/jobs");
|
||||
const upstreamForm = new FormData();
|
||||
upstreamForm.set("pdf_path", pdfPath);
|
||||
upstreamForm.set("original_filename", originalFilename);
|
||||
upstreamForm.set("file_sn", registered.fileSn);
|
||||
if (initialEmbeddingOnly) upstreamForm.set("initial_embedding_only", "true");
|
||||
if (reuploadStagingFileSn) upstreamForm.set("reupload_staging_file_sn", reuploadStagingFileSn);
|
||||
if (reuploadStagingFileSn) upstreamForm.set("reupload_expected_current_ingestion_id", reuploadExpectedCurrentIngestionId);
|
||||
upstreamForm.set("project_id", registered.projectId);
|
||||
upstreamForm.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
if (parserEngine) upstreamForm.set("parser_engine", parserEngine);
|
||||
const headers = registryAuthHeaders(request);
|
||||
headers.set("x-request-id", diagnostic.requestId);
|
||||
if (reuploadStagingFileSn) ragInternalHeaders(headers);
|
||||
upstreamForm.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
ragRequestStarted = true;
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST", headers, body: upstreamForm, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
const responseHeaders = new Headers({ "Cache-Control": "no-store" });
|
||||
const contentType = upstream.headers.get("content-type");
|
||||
if (contentType) responseHeaders.set("Content-Type", contentType);
|
||||
const responseText = await upstream.text();
|
||||
if (!upstream.ok) {
|
||||
// Never accept an upstream body's NOT_SENT assertion as frontend proof.
|
||||
responseHeaders.set("X-Rag-Dispatch-State", "UNKNOWN");
|
||||
return diagnostic.finish(new Response(responseText, { status: upstream.status, headers: responseHeaders }), {
|
||||
upstreamRequestId: upstream.headers.get("x-request-id"), fileSn: diagnosticFileSn,
|
||||
});
|
||||
}
|
||||
let job: Record<string, unknown>;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(responseText);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid job");
|
||||
job = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return failure(502, "EMBED_JOB_START_INVALID", "임베딩 작업 접수 결과가 올바르지 않습니다.", "UNKNOWN");
|
||||
}
|
||||
const jobId = job.job_id;
|
||||
if (typeof jobId !== "string" || !/^[a-f0-9-]{36}$/i.test(jobId)) {
|
||||
return failure(502, "EMBED_JOB_START_INVALID", "임베딩 작업 식별자가 올바르지 않습니다.", "UNKNOWN");
|
||||
}
|
||||
if (typeof job.completion_attestation !== "string" ||
|
||||
!/^[A-Za-z0-9_-]{32,256}$/.test(job.completion_attestation)) {
|
||||
return failure(502, "EMBED_COMPLETION_AUTHORITY_INVALID", "임베딩 완료 권한을 확인하지 못했습니다.", "UNKNOWN");
|
||||
}
|
||||
responseHeaders.set("Content-Type", "application/json");
|
||||
return diagnostic.finish(new Response(JSON.stringify(job), {
|
||||
status: upstream.status, headers: responseHeaders,
|
||||
}), { upstreamRequestId: upstream.headers.get("x-request-id"), fileSn: diagnosticFileSn, jobId, accepted: true });
|
||||
} catch (error) {
|
||||
const dispatchState = ragRequestStarted ? "UNKNOWN" : "NOT_SENT";
|
||||
if (error instanceof FileRegistryError) {
|
||||
return failure(error.status, error.code, error.message, dispatchState, error.diagnostic);
|
||||
}
|
||||
if (request.signal.aborted) {
|
||||
return failure(499, "EMBED_CANCELLED", "임베딩 요청이 취소되었습니다.", dispatchState);
|
||||
}
|
||||
return failure(502, "EMBED_UPSTREAM_UNAVAILABLE", "임베딩 서버에 연결할 수 없습니다.", dispatchState);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user