129 lines
4.9 KiB
TypeScript
129 lines
4.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { cookies } from "next/headers";
|
|
import { randomUUID } from "node:crypto";
|
|
import {
|
|
CLAIM_NAME,
|
|
AUTH_USER_ID,
|
|
} from "@/shared/config";
|
|
import { SITE_ID } from "@/shared/config/env";
|
|
import { FileRegistryError } from "@/server/file-registry-attestation";
|
|
import { stripBrowserRagContext } from "@/server/rag-forward-context";
|
|
import { resolveDcServiceUrl } from "@/shared/api/dc-service-request";
|
|
import { DC_SEARCH_RELAY_PATH, dcGatewayContext } from "@/shared/api/dc-search-relay";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
export const maxDuration = 300;
|
|
|
|
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
|
|
export async function POST(request: NextRequest) {
|
|
// Correlation only; a caller ID never supplies authentication or access scope.
|
|
let requestId: string = randomUUID();
|
|
try {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(CLAIM_NAME)?.value;
|
|
const userId = cookieStore.get(AUTH_USER_ID)?.value;
|
|
|
|
const parsed: unknown = await request.json();
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
return NextResponse.json(
|
|
{ error: "질문 요청 형식이 올바르지 않습니다." },
|
|
{ status: 400, headers: { "Cache-Control": "no-store", "x-request-id": requestId } },
|
|
);
|
|
}
|
|
const body = { ...parsed } as Record<string, unknown>;
|
|
stripBrowserRagContext(body);
|
|
|
|
const headers: HeadersInit = {
|
|
...dcGatewayContext(request.headers),
|
|
"Content-Type": "application/json",
|
|
Accept: "text/event-stream",
|
|
"X-Site-Id": SITE_ID,
|
|
"x-request-id": requestId,
|
|
};
|
|
if (token) {
|
|
if (CLAIM_NAME.toLowerCase() !== "authorization") headers[CLAIM_NAME] = token;
|
|
headers.Authorization = token;
|
|
}
|
|
if (userId) headers[AUTH_USER_ID] = userId;
|
|
|
|
const controller = new AbortController();
|
|
// Keep the downstream disconnect connected after the SSE headers arrive.
|
|
if (request.signal.aborted) controller.abort();
|
|
else request.signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
const timeoutId = setTimeout(() => controller.abort(), 600000);
|
|
|
|
try {
|
|
const response = await fetch(
|
|
resolveDcServiceUrl(`${DC_SEARCH_RELAY_PATH}/ask-question`),
|
|
{
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(body),
|
|
signal: controller.signal,
|
|
redirect: "error",
|
|
cache: "no-store",
|
|
}
|
|
);
|
|
|
|
clearTimeout(timeoutId);
|
|
const upstreamRequestId = response.headers.get("x-request-id");
|
|
if (upstreamRequestId && REQUEST_ID_PATTERN.test(upstreamRequestId)) {
|
|
requestId = upstreamRequestId;
|
|
}
|
|
|
|
if (!response.ok) {
|
|
console.warn("[ask-question] upstream_http_error", { status: response.status });
|
|
return NextResponse.json(
|
|
{
|
|
error: response.status === 401 ? "로그인이 만료되었습니다. 다시 로그인해 주세요."
|
|
: response.status === 403 ? "선택한 문서에 접근할 수 없습니다."
|
|
: "문서 답변 요청을 처리하지 못했습니다.",
|
|
},
|
|
{ status: response.status, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
|
);
|
|
}
|
|
|
|
const contentType =
|
|
response.headers.get("content-type") ?? "text/event-stream";
|
|
|
|
return new Response(response.body, {
|
|
status: response.status,
|
|
headers: {
|
|
"Content-Type": contentType,
|
|
"Cache-Control": "no-store, no-transform",
|
|
Connection: "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
"x-request-id": requestId,
|
|
},
|
|
});
|
|
} catch (error: unknown) {
|
|
clearTimeout(timeoutId);
|
|
if (request.signal.aborted) {
|
|
return new Response(null, { status: 499, headers: { "x-request-id": requestId } });
|
|
}
|
|
if (error instanceof Error && error.name === "AbortError") {
|
|
console.warn("[ask-question] upstream_timeout", { status: 504 });
|
|
return NextResponse.json(
|
|
{ error: "요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요." },
|
|
{ status: 504, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
|
);
|
|
}
|
|
throw error;
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof FileRegistryError) {
|
|
return NextResponse.json(
|
|
{ error: "질문에 필요한 자료관 분류와 문서 정보를 확인하지 못했습니다.", code: error.code },
|
|
{ status: error.status, headers: { "Cache-Control": "no-store", "x-request-id": requestId } },
|
|
);
|
|
}
|
|
console.error("[ask-question] request_failed", { status: 500 });
|
|
return NextResponse.json(
|
|
{ error: "서버 오류가 발생했습니다." },
|
|
{ status: 500, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
|
);
|
|
}
|
|
}
|