개선된 pool 관리
This commit is contained in:
1 parent
8671a45d96
commit
efddee217a
6 files changed
+504
-195
No files matched your search
@@ -20,13 +20,19 @@ URL 경로 형식:
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
|
||||
# 바이트 데이터로 직접 업로드 (media 저장 없이)
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song") # .mp3 자동 추가
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video") # .mp4 자동 추가
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
success = await uploader.upload_image_bytes(image_bytes, "my_image.png")
|
||||
|
||||
print(uploader.public_url) # 마지막 업로드의 공개 URL
|
||||
|
||||
성능 최적화:
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀 재사용
|
||||
- 동시 업로드: 공유 클라이언트를 통해 동시 요청 처리가 개선됩니다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
@@ -35,6 +41,37 @@ import httpx
|
||||
from config import azure_blob_settings
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_blob_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_blob_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is None or _shared_blob_client.is_closed:
|
||||
print("[AzureBlobUploader] Creating shared HTTP client...")
|
||||
_shared_blob_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(180.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
print("[AzureBlobUploader] Shared HTTP client created - "
|
||||
"max_connections: 20, max_keepalive: 10")
|
||||
return _shared_blob_client
|
||||
|
||||
|
||||
async def close_shared_blob_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is not None and not _shared_blob_client.is_closed:
|
||||
await _shared_blob_client.aclose()
|
||||
_shared_blob_client = None
|
||||
print("[AzureBlobUploader] Shared HTTP client closed")
|
||||
|
||||
|
||||
class AzureBlobUploader:
|
||||
"""Azure Blob Storage 업로드 클래스
|
||||
|
||||
@@ -85,12 +122,75 @@ class AzureBlobUploader:
|
||||
"""업로드 URL 생성 (SAS 토큰 포함)"""
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
sas_token = self._sas_token.strip("?'\"")
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
return (
|
||||
f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
)
|
||||
|
||||
def _build_public_url(self, category: str, file_name: str) -> str:
|
||||
"""공개 URL 생성 (SAS 토큰 제외)"""
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
|
||||
|
||||
async def _upload_bytes(
|
||||
self,
|
||||
file_content: bytes,
|
||||
upload_url: str,
|
||||
headers: dict,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
) -> bool:
|
||||
"""바이트 데이터를 업로드하는 공통 내부 메서드"""
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
print(f"[{log_prefix}] Getting shared client...")
|
||||
client = await get_shared_blob_client()
|
||||
client_time = time.perf_counter()
|
||||
elapsed_ms = (client_time - start_time) * 1000
|
||||
print(f"[{log_prefix}] Client acquired in {elapsed_ms:.1f}ms")
|
||||
|
||||
size = len(file_content)
|
||||
print(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
upload_time = time.perf_counter()
|
||||
duration_ms = (upload_time - start_time) * 1000
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[{log_prefix}] SUCCESS - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[{log_prefix}] FAILED - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Response: {response.text[:500]}")
|
||||
return False
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s "
|
||||
f"(limit: {timeout}s)")
|
||||
return False
|
||||
except httpx.ConnectError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] CONNECT_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
except httpx.ReadError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] READ_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
self,
|
||||
file_path: str,
|
||||
@@ -116,26 +216,20 @@ class AzureBlobUploader:
|
||||
|
||||
upload_url = self._build_upload_url(category, file_name)
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
print(f"[{log_prefix}] Upload URL (without SAS): {self._last_public_url}")
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
file_content = await file.read()
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.put(
|
||||
upload_url, content=file_content, headers=headers, timeout=timeout
|
||||
)
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[{log_prefix}] Success - Status Code: {response.status_code}")
|
||||
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[{log_prefix}] Failed - Status Code: {response.status_code}")
|
||||
print(f"[{log_prefix}] Response: {response.text}")
|
||||
return False
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
"""음악 파일을 Azure Blob Storage에 업로드합니다.
|
||||
@@ -151,7 +245,7 @@ class AzureBlobUploader:
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/song/my_song.mp3
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
@@ -161,7 +255,9 @@ class AzureBlobUploader:
|
||||
log_prefix="upload_music",
|
||||
)
|
||||
|
||||
async def upload_music_bytes(self, file_content: bytes, file_name: str) -> bool:
|
||||
async def upload_music_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
@@ -176,7 +272,7 @@ class AzureBlobUploader:
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/song/my_song.mp3
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp3 추가
|
||||
if not Path(file_name).suffix:
|
||||
@@ -184,23 +280,18 @@ class AzureBlobUploader:
|
||||
|
||||
upload_url = self._build_upload_url("song", file_name)
|
||||
self._last_public_url = self._build_public_url("song", file_name)
|
||||
print(f"[upload_music_bytes] Upload URL (without SAS): {self._last_public_url}")
|
||||
log_prefix = "upload_music_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.put(
|
||||
upload_url, content=file_content, headers=headers, timeout=120.0
|
||||
)
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[upload_music_bytes] Success - Status Code: {response.status_code}")
|
||||
print(f"[upload_music_bytes] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[upload_music_bytes] Failed - Status Code: {response.status_code}")
|
||||
print(f"[upload_music_bytes] Response: {response.text}")
|
||||
return False
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=120.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_video(self, file_path: str) -> bool:
|
||||
"""영상 파일을 Azure Blob Storage에 업로드합니다.
|
||||
@@ -216,7 +307,7 @@ class AzureBlobUploader:
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/video/my_video.mp4
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
@@ -226,7 +317,9 @@ class AzureBlobUploader:
|
||||
log_prefix="upload_video",
|
||||
)
|
||||
|
||||
async def upload_video_bytes(self, file_content: bytes, file_name: str) -> bool:
|
||||
async def upload_video_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
@@ -241,7 +334,7 @@ class AzureBlobUploader:
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/video/my_video.mp4
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp4 추가
|
||||
if not Path(file_name).suffix:
|
||||
@@ -249,23 +342,18 @@ class AzureBlobUploader:
|
||||
|
||||
upload_url = self._build_upload_url("video", file_name)
|
||||
self._last_public_url = self._build_public_url("video", file_name)
|
||||
print(f"[upload_video_bytes] Upload URL (without SAS): {self._last_public_url}")
|
||||
log_prefix = "upload_video_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.put(
|
||||
upload_url, content=file_content, headers=headers, timeout=180.0
|
||||
)
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[upload_video_bytes] Success - Status Code: {response.status_code}")
|
||||
print(f"[upload_video_bytes] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[upload_video_bytes] Failed - Status Code: {response.status_code}")
|
||||
print(f"[upload_video_bytes] Response: {response.text}")
|
||||
return False
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=180.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_image(self, file_path: str) -> bool:
|
||||
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
|
||||
@@ -281,7 +369,7 @@ class AzureBlobUploader:
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/image/my_image.png
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_path).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
@@ -294,7 +382,9 @@ class AzureBlobUploader:
|
||||
log_prefix="upload_image",
|
||||
)
|
||||
|
||||
async def upload_image_bytes(self, file_content: bytes, file_name: str) -> bool:
|
||||
async def upload_image_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
@@ -311,30 +401,25 @@ class AzureBlobUploader:
|
||||
with open("my_image.png", "rb") as f:
|
||||
content = f.read()
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
print(uploader.public_url) # {BASE_URL}/task-123/image/my_image.png
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
print(f"[upload_image_bytes] Upload URL (without SAS): {self._last_public_url}")
|
||||
log_prefix = "upload_image_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.put(
|
||||
upload_url, content=file_content, headers=headers, timeout=60.0
|
||||
)
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[upload_image_bytes] Success - Status Code: {response.status_code}")
|
||||
print(f"[upload_image_bytes] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[upload_image_bytes] Failed - Status Code: {response.status_code}")
|
||||
print(f"[upload_image_bytes] Response: {response.text}")
|
||||
return False
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=60.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
|
||||
# 사용 예시:
|
||||
|
||||
Reference in new issue
Block a user