import { NextRequest, NextResponse } from "next/server"; import { registryForwardContext } from "@/server/rag-forward-context"; import { attestRegisteredFile, dcRagUrl, FileRegistryError, registryAuthHeaders, } from "@/server/file-registry-attestation"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; export const maxDuration = 60; type JsonRecord = Record; function record(value: unknown): JsonRecord | null { return value !== null && typeof value === "object" && !Array.isArray(value) ? value as JsonRecord : null; } function text(value: unknown): string { return typeof value === "string" ? value.trim() : ""; } function failure(status: number, code: string, message: string): NextResponse { return NextResponse.json({ code, error: message }, { status, headers: { "Cache-Control": "no-store" }, }); } function dcServiceImportUrl(): URL { const base = process.env.DC_SERVICE_API_URL ?? process.env.NEXT_PUBLIC_DC_SERVICE_API_URL; if (!base) { throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정이 없습니다."); } try { const url = new URL(`${base.replace(/\/+$/, "")}/dc-service/api/v1/gnsvy/imports`); if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) { throw new Error("invalid upstream URL"); } return url; } catch { throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정을 확인해 주세요."); } } function verifiedArtifact(job: JsonRecord): { fileSn: string; payload: JsonRecord } | null { if (job.type !== "EMBED_DOCUMENTS" || job.status !== "DONE") { throw new FileRegistryError(409, "EMBED_JOB_NOT_DONE", "임베딩 작업 완료를 확인하지 못했습니다."); } const result = record(job.result); if (!result) { throw new FileRegistryError(502, "EMBED_RESULT_INVALID", "임베딩 결과를 확인할 수 없습니다."); } if (result.general_survey_import == null) return null; const payload = record(result.general_survey_import); const files = result.embedded_files; const profile = record(result.ingest_profile); const file = Array.isArray(files) && files.length === 1 ? record(files[0]) : null; const fileSn = text(file?.file_sn); const digest = text(profile?.pdf_sha256).toLowerCase(); if (!payload || payload.status !== "parsed" || !fileSn || text(payload.file_sn) !== fileSn || !/^[a-f0-9]{64}$/.test(digest) || text(payload.document_id) !== `sha256:${digest}`) { throw new FileRegistryError(502, "SURVEY_HANDOFF_INVALID", "총설 등록 근거를 확인할 수 없습니다."); } return { fileSn, payload }; } /** Finish a successful RAG embed by handing its verified survey artifact to dc-service. */ export async function POST(request: NextRequest): Promise { try { if (Number(request.headers.get("content-length") ?? 0) > 1024) { return failure(413, "COMPLETE_EMBED_REQUEST_TOO_LARGE", "작업 확인 요청이 너무 큽니다."); } let body: unknown; try { body = await request.json(); } catch { return failure(400, "COMPLETE_EMBED_REQUEST_INVALID", "작업 확인 요청이 올바르지 않습니다."); } const jobId = text(record(body)?.jobId); const completionAttestation = text(record(body)?.completionAttestation); if (!/^[a-f0-9-]{36}$/i.test(jobId)) { return failure(400, "COMPLETE_EMBED_REQUEST_INVALID", "작업 식별자가 올바르지 않습니다."); } if (!completionAttestation || completionAttestation.length > 8192) { return failure(403, "COMPLETE_EMBED_AUTHORITY_INVALID", "작업 완료 권한을 확인하지 못했습니다."); } const headers = registryAuthHeaders(request); let jobResponse: Response; try { jobResponse = await fetch(dcRagUrl(`/jobs/${jobId}`), { method: "GET", headers, cache: "no-store", signal: request.signal, }); } catch { return failure(502, "EMBED_JOB_UNAVAILABLE", "임베딩 결과를 조회할 수 없습니다."); } if (!jobResponse.ok) { return failure(502, "EMBED_JOB_UNAVAILABLE", "임베딩 결과를 조회할 수 없습니다."); } const job = record(await jobResponse.json().catch(() => null)); if (!job || job.job_id !== jobId) { return failure(502, "EMBED_JOB_INVALID", "임베딩 작업 결과가 올바르지 않습니다."); } const handoff = verifiedArtifact(job); if (!handoff) { return NextResponse.json({ imported: false }, { headers: { "Cache-Control": "no-store" } }); } // Validate the current user token with dc-service before consuming RAG's // one-time completion capability. The job artifact alone grants no write. const registered = await attestRegisteredFile(request, { fileSn: handoff.fileSn }); const verifyHeaders = registryAuthHeaders(request); verifyHeaders.set("Content-Type", "application/json"); const registryContext = registryForwardContext(registered, verifyHeaders); let verifyResponse: Response; try { verifyResponse = await fetch(dcRagUrl(`/jobs/${jobId}/verify-completion`), { method: "POST", headers: verifyHeaders, body: JSON.stringify({ completionAttestation, fileSn: registered.fileSn, registryContext, }), cache: "no-store", signal: request.signal, redirect: "error", }); } catch { return failure(502, "COMPLETE_EMBED_AUTHORITY_UNCERTAIN", "작업 완료 권한을 확인하지 못했습니다."); } if (!verifyResponse.ok) { return failure(verifyResponse.status === 403 || verifyResponse.status === 409 ? 403 : 502, "COMPLETE_EMBED_AUTHORITY_INVALID", "작업 완료 권한을 확인하지 못했습니다."); } const verified = record(await verifyResponse.json().catch(() => null)); if (verified?.verified !== true) { return failure(502, "COMPLETE_EMBED_AUTHORITY_UNCERTAIN", "작업 완료 권한을 확인하지 못했습니다."); } const dcHeaders = registryAuthHeaders(request); dcHeaders.set("Content-Type", "application/json"); const importUrl = dcServiceImportUrl(); let importResponse: Response; try { // No automatic retry: a failed connection after dispatch has an unknown outcome. importResponse = await fetch(importUrl, { method: "POST", headers: dcHeaders, body: JSON.stringify(handoff.payload), cache: "no-store", }); } catch { return failure(502, "GENERAL_SURVEY_IMPORT_UNCERTAIN", "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다."); } if (!importResponse.ok) { const uncertain = importResponse.status >= 500; return failure( uncertain ? 502 : 422, uncertain ? "GENERAL_SURVEY_IMPORT_UNCERTAIN" : "GENERAL_SURVEY_IMPORT_FAILED", uncertain ? "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다." : "총설 등록을 완료하지 못했습니다.", ); } const imported = record(await importResponse.json().catch(() => null)); if (!imported || imported.status !== "IMPORTED" || imported.saved_count !== 9) { return failure(502, "GENERAL_SURVEY_IMPORT_UNCERTAIN", "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다."); } return NextResponse.json({ imported: true }, { headers: { "Cache-Control": "no-store" } }); } catch (error) { if (error instanceof FileRegistryError) { return failure(error.status, error.code, error.message); } return failure(502, "COMPLETE_EMBED_FAILED", "임베딩 후속 등록을 완료하지 못했습니다."); } }