feat(home): 이미지 업로드에 크기·개수 상한과 task 직렬화 락 도입
This commit is contained in:
1 parent
8096837b13
commit
f87cd07d5e
5 files changed
+1112
-168
No files matched your search
@@ -32,12 +32,17 @@ URL 경로 형식:
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import aiofiles
|
||||
import httpx
|
||||
from fastapi import UploadFile
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import azure_blob_settings
|
||||
@@ -45,6 +50,15 @@ from config import azure_blob_settings
|
||||
# 로거 설정
|
||||
logger = get_logger("blob")
|
||||
|
||||
|
||||
class BlobUploadTooLargeError(ValueError):
|
||||
"""스트리밍 중 파일 크기 상한을 초과했을 때 발생합니다."""
|
||||
|
||||
def __init__(self, max_size_bytes: int):
|
||||
self.max_size_bytes = max_size_bytes
|
||||
super().__init__(f"업로드 파일은 {max_size_bytes} bytes를 초과할 수 없습니다.")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
@@ -100,6 +114,8 @@ class AzureBlobUploader:
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".bmp": "image/bmp",
|
||||
".heic": "image/heic",
|
||||
".heif": "image/heif",
|
||||
}
|
||||
|
||||
def __init__(self, user_uuid: str, task_id: str):
|
||||
@@ -111,7 +127,7 @@ class AzureBlobUploader:
|
||||
"""
|
||||
self._user_uuid = user_uuid
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL.rstrip("/")
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@@ -204,8 +220,12 @@ class AzureBlobUploader:
|
||||
logger.debug(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
request_headers = {
|
||||
**headers,
|
||||
"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION,
|
||||
}
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
client.put(upload_url, content=file_content, headers=request_headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
upload_time = time.perf_counter()
|
||||
@@ -246,6 +266,170 @@ class AzureBlobUploader:
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _append_query(upload_url: str, **params: str) -> str:
|
||||
"""SAS 쿼리를 유지하며 Azure REST API 쿼리를 추가합니다."""
|
||||
separator = "&" if "?" in upload_url else "?"
|
||||
return f"{upload_url}{separator}{urlencode(params)}"
|
||||
|
||||
async def _delete_upload_url(self, upload_url: str, log_prefix: str) -> bool:
|
||||
"""실패한 업로드의 커밋/미커밋 Blob을 정리합니다."""
|
||||
try:
|
||||
client = await get_shared_blob_client()
|
||||
response = await client.delete(
|
||||
upload_url,
|
||||
headers={"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION},
|
||||
)
|
||||
if response.status_code in {202, 404}:
|
||||
return True
|
||||
logger.warning(
|
||||
f"[{log_prefix}] Blob cleanup failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
f"[{log_prefix}] Blob cleanup error - {type(exc).__name__}: {exc}"
|
||||
)
|
||||
return False
|
||||
|
||||
async def _upload_stream(
|
||||
self,
|
||||
chunks: AsyncIterator[bytes],
|
||||
upload_url: str,
|
||||
content_type: str,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
*,
|
||||
max_size_bytes: int | None = None,
|
||||
expected_size_bytes: int | None = None,
|
||||
cleanup_blob_on_failure: bool = False,
|
||||
) -> bool:
|
||||
"""Azure Block Blob API로 비동기 청크 스트림을 업로드합니다.
|
||||
|
||||
각 블록만 메모리에 유지하므로 파일 전체 크기와 무관하게 메모리 사용량이
|
||||
일정합니다. 커밋 전 오류가 발생하면 업로드 대상 Blob 삭제를 시도합니다.
|
||||
"""
|
||||
block_ids: list[str] = []
|
||||
block_id_nonce = os.urandom(16)
|
||||
uploaded_size = 0
|
||||
start_time = time.perf_counter()
|
||||
|
||||
async def cleanup_failed_stream() -> None:
|
||||
# 기존 deterministic key는 미커밋 블록만 TTL 정리되게 두어 정상 Blob을 보존합니다.
|
||||
if cleanup_blob_on_failure:
|
||||
await self._delete_upload_url(upload_url, log_prefix)
|
||||
|
||||
try:
|
||||
client = await get_shared_blob_client()
|
||||
async with asyncio.timeout(timeout):
|
||||
async for chunk in chunks:
|
||||
if not chunk:
|
||||
continue
|
||||
|
||||
uploaded_size += len(chunk)
|
||||
if max_size_bytes is not None and uploaded_size > max_size_bytes:
|
||||
raise BlobUploadTooLargeError(max_size_bytes)
|
||||
|
||||
raw_block_id = block_id_nonce + len(block_ids).to_bytes(4, "big")
|
||||
block_id = base64.b64encode(raw_block_id).decode("ascii")
|
||||
block_url = self._append_query(
|
||||
upload_url,
|
||||
comp="block",
|
||||
blockid=block_id,
|
||||
)
|
||||
response = await client.put(
|
||||
block_url,
|
||||
content=chunk,
|
||||
headers={
|
||||
"Content-Type": "application/octet-stream",
|
||||
"x-ms-version": (
|
||||
azure_blob_settings.AZURE_BLOB_API_VERSION
|
||||
),
|
||||
},
|
||||
)
|
||||
if response.status_code != 201:
|
||||
logger.error(
|
||||
f"[{log_prefix}] Block upload failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
block_ids.append(block_id)
|
||||
|
||||
if uploaded_size == 0:
|
||||
logger.warning(f"[{log_prefix}] Empty upload stream")
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
if (
|
||||
expected_size_bytes is not None
|
||||
and uploaded_size != expected_size_bytes
|
||||
):
|
||||
logger.error(
|
||||
f"[{log_prefix}] Stream size changed - expected: "
|
||||
f"{expected_size_bytes}, actual: {uploaded_size}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
block_list = "".join(
|
||||
f"<Latest>{block_id}</Latest>" for block_id in block_ids
|
||||
)
|
||||
commit_body = (
|
||||
f'<?xml version="1.0" encoding="utf-8"?>'
|
||||
f"<BlockList>{block_list}</BlockList>"
|
||||
).encode("utf-8")
|
||||
commit_url = self._append_query(upload_url, comp="blocklist")
|
||||
response = await client.put(
|
||||
commit_url,
|
||||
content=commit_body,
|
||||
headers={
|
||||
"Content-Type": "application/xml; charset=utf-8",
|
||||
"x-ms-blob-content-type": content_type,
|
||||
"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION,
|
||||
},
|
||||
)
|
||||
if response.status_code not in {200, 201}:
|
||||
logger.error(
|
||||
f"[{log_prefix}] Block list commit failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
duration_ms = (time.perf_counter() - start_time) * 1000
|
||||
logger.info(
|
||||
f"[{log_prefix}] SUCCESS - blocks: {len(block_ids)}, "
|
||||
f"size: {uploaded_size} bytes, Duration: {duration_ms:.1f}ms"
|
||||
)
|
||||
return True
|
||||
|
||||
except BlobUploadTooLargeError:
|
||||
await cleanup_failed_stream()
|
||||
raise
|
||||
except asyncio.CancelledError:
|
||||
# 클라이언트 연결 종료 중에도 가능한 범위에서 staged block을 정리합니다.
|
||||
await asyncio.shield(cleanup_failed_stream())
|
||||
raise
|
||||
except TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
except httpx.HTTPError as exc:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(
|
||||
f"[{log_prefix}] HTTP_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
except Exception as exc:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(
|
||||
f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
self,
|
||||
file_path: str,
|
||||
@@ -273,17 +457,20 @@ class AzureBlobUploader:
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
async def iter_file() -> AsyncIterator[bytes]:
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
while chunk := await file.read(
|
||||
azure_blob_settings.AZURE_BLOB_UPLOAD_BLOCK_SIZE_BYTES
|
||||
):
|
||||
yield chunk
|
||||
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
file_content = await file.read()
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
return await self._upload_stream(
|
||||
chunks=iter_file(),
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
timeout=timeout,
|
||||
log_prefix=log_prefix,
|
||||
expected_size_bytes=Path(file_path).stat().st_size,
|
||||
)
|
||||
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
@@ -482,6 +669,51 @@ class AzureBlobUploader:
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_image_stream(
|
||||
self,
|
||||
file: UploadFile,
|
||||
file_name: str,
|
||||
*,
|
||||
expected_size_bytes: int | None = None,
|
||||
max_size_bytes: int | None = None,
|
||||
) -> bool:
|
||||
"""FastAPI UploadFile을 Azure Block Blob으로 청크 업로드합니다."""
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
file_name = self._sanitize_filename(file_name)
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_stream"
|
||||
chunk_size = azure_blob_settings.AZURE_BLOB_UPLOAD_BLOCK_SIZE_BYTES
|
||||
max_size = (
|
||||
max_size_bytes
|
||||
if max_size_bytes is not None
|
||||
else azure_blob_settings.IMAGE_UPLOAD_MAX_FILE_SIZE_BYTES
|
||||
)
|
||||
|
||||
async def iter_upload() -> AsyncIterator[bytes]:
|
||||
await file.seek(0)
|
||||
while chunk := await file.read(chunk_size):
|
||||
yield chunk
|
||||
|
||||
return await self._upload_stream(
|
||||
chunks=iter_upload(),
|
||||
upload_url=upload_url,
|
||||
content_type=content_type,
|
||||
timeout=60.0,
|
||||
log_prefix=log_prefix,
|
||||
max_size_bytes=max_size,
|
||||
expected_size_bytes=expected_size_bytes,
|
||||
cleanup_blob_on_failure=True,
|
||||
)
|
||||
|
||||
async def delete_image(self, file_name: str) -> bool:
|
||||
"""이미지 Blob을 삭제합니다. DB 저장 실패 보상 처리용입니다."""
|
||||
sanitized_name = self._sanitize_filename(file_name)
|
||||
upload_url = self._build_upload_url("image", sanitized_name)
|
||||
return await self._delete_upload_url(upload_url, "delete_image")
|
||||
|
||||
|
||||
# 사용 예시:
|
||||
# import asyncio
|
||||
|
||||
Reference in new issue
Block a user