133 lines
4.5 KiB
Python
133 lines
4.5 KiB
Python
"""
|
|
backend/app/services/file_assets/storage.py
|
|
|
|
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
|
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
|
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import logging
|
|
from datetime import timedelta
|
|
from typing import BinaryIO
|
|
|
|
from minio import Minio
|
|
from minio.error import S3Error
|
|
|
|
from app.core.config.settings import ACTIVE_ENV_NAME, config
|
|
from app.core.errors import ServiceUnavailableError
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
_cfg = config[ACTIVE_ENV_NAME]
|
|
|
|
|
|
class FileAssetStorage:
|
|
"""私有业务文件 MinIO 存储客户端。"""
|
|
|
|
def __init__(self) -> None:
|
|
self.client = Minio(
|
|
_cfg.MINIO_ENDPOINT,
|
|
access_key=_cfg.MINIO_ACCESS_KEY,
|
|
secret_key=_cfg.MINIO_SECRET_KEY,
|
|
secure=_cfg.MINIO_SECURE,
|
|
)
|
|
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
|
|
|
def _ensure_bucket_exists(self) -> None:
|
|
"""确保私有 bucket 存在,不设置 public-read policy。"""
|
|
try:
|
|
if not self.client.bucket_exists(self.bucket_name):
|
|
self.client.make_bucket(self.bucket_name)
|
|
except Exception as exc:
|
|
_LOGGER.exception('MinIO file assets bucket unavailable')
|
|
raise ServiceUnavailableError(
|
|
code='FILE_ASSET.UPLOAD_FAILED',
|
|
message='文件存储服务暂不可用,请稍后重试',
|
|
) from exc
|
|
|
|
def upload_bytes(
|
|
self,
|
|
*,
|
|
storage_key: str,
|
|
data: bytes,
|
|
content_type: str,
|
|
) -> None:
|
|
"""
|
|
上传字节流到私有 bucket。
|
|
Raises:
|
|
ServiceUnavailableError: MinIO 不可用或上传失败。
|
|
"""
|
|
self._ensure_bucket_exists()
|
|
stream: BinaryIO = io.BytesIO(data)
|
|
try:
|
|
self.client.put_object(
|
|
bucket_name=self.bucket_name,
|
|
object_name=storage_key,
|
|
data=stream,
|
|
length=len(data),
|
|
content_type=content_type or 'application/octet-stream',
|
|
)
|
|
except Exception as exc:
|
|
_LOGGER.exception('MinIO upload failed key=%s', storage_key)
|
|
raise ServiceUnavailableError(
|
|
code='FILE_ASSET.UPLOAD_FAILED',
|
|
message='文件上传失败,请稍后重试',
|
|
) from exc
|
|
|
|
def get_bytes(self, storage_key: str) -> bytes:
|
|
"""
|
|
读取对象字节内容。
|
|
Raises:
|
|
ServiceUnavailableError: 读取失败(含网络异常与 S3Error)。
|
|
"""
|
|
try:
|
|
response = self.client.get_object(self.bucket_name, storage_key)
|
|
try:
|
|
return response.read()
|
|
finally:
|
|
response.close()
|
|
response.release_conn()
|
|
except Exception as exc:
|
|
_LOGGER.exception('MinIO read failed key=%s', storage_key)
|
|
raise ServiceUnavailableError(
|
|
code='FILE_ASSET.UPLOAD_FAILED',
|
|
message='文件存储服务暂不可用,请稍后重试',
|
|
) from exc
|
|
|
|
def delete_object(self, storage_key: str) -> None:
|
|
"""
|
|
删除 MinIO 对象;失败时抛出可重试 503,供清理任务重试。
|
|
Raises:
|
|
ServiceUnavailableError: 删除失败。
|
|
"""
|
|
try:
|
|
self.client.remove_object(self.bucket_name, storage_key)
|
|
except Exception as exc:
|
|
_LOGGER.exception('MinIO delete failed key=%s', storage_key)
|
|
raise ServiceUnavailableError(
|
|
code='FILE_ASSET.UPLOAD_FAILED',
|
|
message='文件对象删除失败,请稍后重试',
|
|
) from exc
|
|
|
|
def object_exists(self, storage_key: str) -> bool:
|
|
"""判断对象是否存在。"""
|
|
try:
|
|
self.client.stat_object(self.bucket_name, storage_key)
|
|
return True
|
|
except S3Error:
|
|
return False
|
|
|
|
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
|
"""生成短期受控下载 URL。"""
|
|
self._ensure_bucket_exists()
|
|
return self.client.presigned_get_object(
|
|
self.bucket_name,
|
|
storage_key,
|
|
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
|
)
|
|
|
|
|
|
file_asset_storage = FileAssetStorage()
|