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>
This commit is contained in:
2026-08-08 20:11:23 +09:00
co-authored by Claude Opus 5
parent b3d8371882
commit d935013ffa
7 changed files with 205 additions and 4 deletions
+60
View File
@@ -26,6 +26,7 @@ from B03_FileInput.B03_FileInput_Engine_Analyze import analyze_input_metadata
from B03_FileInput.B03_FileInput_Repository import (
create_input_file,
create_upload_session,
find_input_file_by_name,
get_project_input_readiness,
get_project_storage_relative_path,
get_upload_session,
@@ -34,6 +35,7 @@ from B03_FileInput.B03_FileInput_Repository import (
list_project_input_files,
mark_upload_session_completed,
mark_upload_session_failed,
supersede_previous_input_files,
upsert_upload_chunk,
)
from B03_FileInput.B03_FileInput_Router_Errors import lookup_error_response
@@ -103,6 +105,50 @@ def _require_complete_file_set(file_types: set[str]) -> None:
raise ValueError(f"B03 필수 입력 파일이 없습니다: {', '.join(missing)}")
def _stored_fingerprint(metadata: Any) -> str | None:
"""입력 파일 메타데이터에 적어 둔 지문을 꺼낸다."""
if isinstance(metadata, str):
try:
metadata = json.loads(metadata)
except (TypeError, ValueError):
return None
if not isinstance(metadata, dict):
return None
value = metadata.get("fingerprint")
return str(value) if value else None
async def _already_uploaded(
connection: aiomysql.Connection,
project_id: UUID,
payload: ChunkSessionCreateRequest,
) -> ChunkSessionCreateResponse | None:
"""같은 이름으로 **같은 내용**이 이미 올라와 있으면 전송을 건너뛰라는 응답을 만든다.
1.7GB를 다 받은 뒤에 비교하면 아낄 게 없으므로, 세션을 만들기 전에 화면이 보내 준
지문으로 가린다. 지문이 없거나 다르면 그냥 올린다 — 애매하면 올리는 쪽이 안전하다.
"""
if not payload.fingerprint:
return None
existing = await find_input_file_by_name(connection, project_id, payload.original_filename)
if not existing or _stored_fingerprint(existing.get("metadata")) != payload.fingerprint:
return None
logger.info(
"B03 같은 파일 재업로드 — 전송 생략: project_id=%s file=%s",
project_id,
payload.original_filename,
)
return ChunkSessionCreateResponse(
project_id=str(project_id),
upload_session_id="",
original_filename=payload.original_filename,
file_size_bytes=payload.size_bytes,
chunk_size_bytes=payload.chunk_size_bytes,
total_chunks=0,
already_uploaded=True,
)
async def _complete_file_input_if_ready(
connection: aiomysql.Connection,
project_id: UUID,
@@ -401,6 +447,9 @@ async def create_project_upload_session(
status_code=409,
content={"status": "error", "message": _ANALYSIS_RUNNING_MESSAGE},
)
skipped = await _already_uploaded(connection, project_id, payload)
if skipped is not None:
return skipped
await create_upload_session(
connection,
session_id=session_id,
@@ -540,6 +589,10 @@ async def finalize_project_upload(
payload.total_chunks,
)
metadata = await asyncio.to_thread(analyze_input_metadata, final_path)
# 다음에 같은 파일이 올라오면 전송을 건너뛸 수 있도록 지문을 함께 남긴다.
fingerprint = payload.fingerprint or None
if fingerprint:
metadata = {**metadata, "fingerprint": fingerprint}
relative_path = final_path.relative_to(project_root).as_posix()
file_type = final_path.suffix.lower().lstrip(".")
crs_epsg = metadata.get("epsg")
@@ -557,6 +610,13 @@ async def finalize_project_upload(
crs_epsg=int(crs_epsg) if crs_epsg is not None else None,
metadata=metadata,
)
# 같은 이름의 옛 행은 내려 둔다 — 목록·분석이 최신 1건만 보게 한다.
await supersede_previous_input_files(
connection,
project_id,
descriptor.original_filename,
input_file_id,
)
await mark_upload_session_completed(connection, session_id=payload.session_id)
if payload.complete_upload:
point_cloud_input_id = await _complete_file_input_if_ready(