Files
Aislo/B03_FileInput/B03_FileInput_Api_Fetch.ts
T
eomsangdonandClaude Opus 5 d935013ffa feat(B03): 같은 파일 재업로드는 전송 생략, 다른 내용이면 덮어쓰기 (E2E 결함 2)
사용자 결정(2026-08-08): 복수 파일을 허용하고 중복 기준은 파일명으로 둔다. 같은 이름으로
같은 내용이 다시 들어오면 덮어쓰지 말고 건너뛰고, 내용이 다르면 덮어쓴다.

파일 지문(부분 샘플링)
- B03_FileInput_Fingerprint.ts: 파일 크기 + 앞·중간·끝 8MB를 이어 SHA-256. 24MB만 읽어
  1~2초면 끝난다. 전체 읽기(1.7GB, 10~30초)와 견줘 실용적이고, 자리를 앞·중간·끝으로
  흩어 놓아 머리말만 같은 파일도 갈린다. 한계는 주석에 적었다.
- 화면이 업로드 세션 생성 요청에 지문을 실어 보내고, 서버가 같은 이름의 최신 입력 파일
  메타데이터에 적힌 지문과 견준다. 같으면 already_uploaded=true로 답해 **전송 자체를**
  건너뛴다(1.7GB면 3~5분 절약). 지문이 없거나 다르면 그냥 올린다 — 애매하면 올리는 쪽.
- 완료 요청에도 지문을 실어 input_files.metadata에 남긴다. upload_sessions에 컬럼을
  더하지 않으려는 선택이라 DB 스키마 변경이 없다.

옛 행 정리
- supersede_previous_input_files(): 같은 이름의 이전 행을 SUPERSEDED로 내린다. 조회는
  UPLOADED/PROCESSED만 보므로 목록·분석에서 자동으로 빠지고, 행은 이력으로 남는다.
- 직접 업로드 완료와 보관함 연결 양쪽에 적용.

검증(실서버 f45243b3)
- 같은 파일 재요청 → already_uploaded=true, 세션 미발급.
- 지문이 다르면 → 세션 발급(정상 업로드 경로).
- 옛 행이 SUPERSEDED로 내려가는 것 DB에서 확인.
- 화면 코드(B03_FileInput_Fingerprint.ts)를 그대로 실행해 만든 지문과 서버측 검증
  스크립트의 지문이 20MB 표본에서 완전히 일치(f281fd08…93e4).
typecheck·ruff·prettier 통과, 정적 번들 재빌드.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 20:11:23 +09:00

208 lines
5.8 KiB
TypeScript

/* B03 다중 파일 업로드 API 클라이언트 */
import { API_BASE_URL, API_TIMEOUT_MS } from "@config/config_frontend";
export interface UploadedFileResult {
input_file_id: number;
original_filename: string;
file_type: string;
relative_path: string;
size_bytes: number;
metadata: Record<string, unknown>;
}
export interface FileUploadResponse {
status: string;
project_id: string;
files: UploadedFileResult[];
}
export interface ChunkSessionCreateResponse {
status: string;
project_id: string;
upload_session_id: string;
original_filename: string;
file_size_bytes: number;
chunk_size_bytes: number;
total_chunks: number;
completed_chunks: number;
/** 같은 내용이 이미 올라와 있어 전송을 건너뛰어도 되는지. */
already_uploaded?: boolean;
}
export interface ChunkUploadResponse {
status: string;
upload_session_id: string;
chunk_index: number;
completed_chunks: number;
total_chunks: number;
chunk_hash: string;
}
export interface UploadStatusResponse {
status: string;
upload_session_id: string;
upload_status: string;
original_filename: string;
file_size_bytes: number;
chunk_size_bytes: number;
total_chunks: number;
completed_chunks: number;
completed_chunk_indexes: number[];
}
async function readJsonOrThrow<T>(response: Response): Promise<T> {
const payload = (await response.json()) as T & { message?: string };
if (!response.ok) {
throw new Error(payload.message ?? `HTTP ${response.status}`);
}
return payload;
}
export async function uploadProjectFiles(
projectId: string,
files: readonly File[],
): Promise<FileUploadResponse> {
const formData = new FormData();
for (const file of files) formData.append("files", file, file.name);
const controller = new AbortController();
const timeoutId = window.setTimeout(() => controller.abort(), API_TIMEOUT_MS);
try {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/files`, {
method: "POST",
credentials: "include",
body: formData,
signal: controller.signal,
});
return await readJsonOrThrow<FileUploadResponse>(response);
} finally {
window.clearTimeout(timeoutId);
}
}
export async function createUploadSession(
projectId: string,
file: File,
chunkSizeBytes: number,
fingerprint?: string | null,
): Promise<ChunkSessionCreateResponse> {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/upload-sessions`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
original_filename: file.name,
size_bytes: file.size,
chunk_size_bytes: chunkSizeBytes,
fingerprint: fingerprint ?? null,
}),
});
return await readJsonOrThrow<ChunkSessionCreateResponse>(response);
}
export async function uploadFileChunk(
projectId: string,
sessionId: string,
chunkIndex: number,
chunk: Blob,
): Promise<ChunkUploadResponse> {
const formData = new FormData();
formData.append("session_id", sessionId);
formData.append("chunk_index", String(chunkIndex));
formData.append("chunk_data", chunk, `${sessionId}-${chunkIndex}.chunk`);
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/chunks`, {
method: "POST",
credentials: "include",
body: formData,
});
return await readJsonOrThrow<ChunkUploadResponse>(response);
}
export async function finalizeUploadSession(
projectId: string,
sessionId: string,
totalChunks: number,
completeUpload: boolean,
fingerprint?: string | null,
): Promise<FileUploadResponse> {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/finalize`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
session_id: sessionId,
total_chunks: totalChunks,
complete_upload: completeUpload,
fingerprint: fingerprint ?? null,
}),
});
return await readJsonOrThrow<FileUploadResponse>(response);
}
export async function fetchUploadStatus(
projectId: string,
sessionId: string,
): Promise<UploadStatusResponse> {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/upload-status/${sessionId}`, {
method: "GET",
credentials: "include",
});
return await readJsonOrThrow<UploadStatusResponse>(response);
}
export interface UploadOverviewFile {
input_file_id: number;
file_type: string;
original_filename: string;
file_size_mb: number;
status: string;
uploaded_at: string | null;
}
export interface UploadOverviewSession {
upload_session_id: string;
original_filename: string;
file_size_bytes: number;
total_chunks: number;
completed_chunks: number;
progress_percent: number;
updated_at: string | null;
}
export interface UploadOverviewResponse {
status: string;
files: UploadOverviewFile[];
pending_sessions: UploadOverviewSession[];
required_complete: boolean;
analysis_complete: boolean;
}
/** 재접속 시 업로드 현황(정본) — 완료 파일 목록 + 중단 세션 + 완료 여부. */
export async function fetchUploadOverview(projectId: string): Promise<UploadOverviewResponse> {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/upload-overview`, {
method: "GET",
credentials: "include",
});
return await readJsonOrThrow<UploadOverviewResponse>(response);
}
export interface WF1AnalysisStatus {
project_id: string;
status: "pending" | "in_progress" | "completed" | "failed";
model_count: number;
progress_percent: number;
current_stage: string;
message: string;
error?: string;
}
export async function checkWF1AnalysisStatus(projectId: string): Promise<WF1AnalysisStatus> {
const response = await fetch(`${API_BASE_URL}/projects/${projectId}/surface/status`, {
method: "GET",
credentials: "include",
});
return await readJsonOrThrow<WF1AnalysisStatus>(response);
}