|
|
@@ -1,10 +1,9 @@
|
|
|
import os
|
|
|
-import shutil
|
|
|
-import hashlib
|
|
|
from sqlalchemy.orm import Session
|
|
|
from app.models import Project, DataVersion, DataFile
|
|
|
from app.config import settings
|
|
|
from app.services.gogs_client import GogsClient
|
|
|
+from app.services.oss_client import oss_client
|
|
|
import logging
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
@@ -13,7 +12,6 @@ class StorageService:
|
|
|
def __init__(self, db: Session, gogs_client: GogsClient):
|
|
|
self.db = db
|
|
|
self.gogs = gogs_client
|
|
|
- self.storage_root = settings.STORAGE_ROOT
|
|
|
|
|
|
def get_or_create_project(self, project_name: str, description: str = None) -> Project:
|
|
|
project = self.db.query(Project).filter(Project.project_name == project_name).first()
|
|
|
@@ -40,7 +38,6 @@ class StorageService:
|
|
|
async def process_file_with_sha(self, version: DataVersion, relative_path: str, file_sha: str, owner: str, repo: str):
|
|
|
"""只处理变化的文件,未变化的文件不记录。"""
|
|
|
# 查询同一项目 + 同一 stage + 同一文件路径的最新一条记录
|
|
|
- # 通过 version 关联查询
|
|
|
last_file = (
|
|
|
self.db.query(DataFile)
|
|
|
.join(DataVersion)
|
|
|
@@ -54,34 +51,27 @@ class StorageService:
|
|
|
)
|
|
|
|
|
|
if last_file and last_file.file_sha == file_sha:
|
|
|
- # 文件未变化,跳过不记录
|
|
|
logger.info(f"File {relative_path} (SHA: {file_sha}) unchanged. Skipping.")
|
|
|
return
|
|
|
|
|
|
- # 文件是新的或有变化,下载并记录
|
|
|
+ # 文件是新的或有变化,下载并上传到 OSS
|
|
|
logger.info(f"File {relative_path} (SHA: {file_sha}) changed. Downloading.")
|
|
|
content = await self.gogs.get_file_content(owner, repo, version.commit_id, relative_path)
|
|
|
file_size = len(content)
|
|
|
|
|
|
project_name = version.project.project_name
|
|
|
- safe_path = os.path.join(
|
|
|
- self.storage_root,
|
|
|
- project_name,
|
|
|
- version.stage,
|
|
|
- version.commit_id,
|
|
|
- relative_path.replace("/", os.sep)
|
|
|
- )
|
|
|
|
|
|
- os.makedirs(os.path.dirname(safe_path), exist_ok=True)
|
|
|
+ # 构建 OSS key
|
|
|
+ oss_key = oss_client._build_key(project_name, version.stage, version.commit_id, relative_path)
|
|
|
|
|
|
- with open(safe_path, "wb") as f:
|
|
|
- f.write(content)
|
|
|
+ # 上传到 OSS
|
|
|
+ oss_client.upload(oss_key, content)
|
|
|
|
|
|
- # 创建记录
|
|
|
+ # 创建记录(storage_path 存 OSS key)
|
|
|
new_file = DataFile(
|
|
|
version_id=version.id,
|
|
|
relative_path=relative_path,
|
|
|
- storage_path=safe_path,
|
|
|
+ storage_path=oss_key,
|
|
|
file_size=file_size,
|
|
|
file_type=os.path.splitext(relative_path)[1],
|
|
|
file_sha=file_sha
|