douyinWEB/backend/app/s3_storage.py
2026-09-13 22:10:49 -05:00

217 lines
7.0 KiB
Python

# -*- coding: utf-8 -*-
"""SeaweedFS S3-compatible object storage helper."""
from __future__ import annotations
import mimetypes
import time
from pathlib import Path
from typing import Any, Optional
from urllib.parse import quote
from .config import settings
def s3_enabled() -> bool:
return bool(settings.s3_enabled and settings.s3_endpoint and settings.s3_bucket)
def _client():
import boto3
from botocore.client import Config
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint.rstrip("/"),
aws_access_key_id=settings.s3_access_key or "any",
aws_secret_access_key=settings.s3_secret_key or "any",
region_name=settings.s3_region or "us-east-1",
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
if not s3_enabled():
return
client = _client()
bucket = settings.s3_bucket
try:
client.head_bucket(Bucket=bucket)
except Exception:
try:
client.create_bucket(Bucket=bucket)
except Exception:
# race / already exists
pass
def public_url_for_key(key: str) -> str:
base = (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/")
bucket = settings.s3_bucket.strip("/")
# path-style: http://host:8333/bucket/key
return f"{base}/{bucket}/{quote(key, safe='/')}"
def head_object(key: str) -> dict[str, Any] | None:
"""Return size / etag / last_modified for a key, or None if missing."""
if not s3_enabled():
return None
try:
client = _client()
resp = client.head_object(Bucket=settings.s3_bucket, Key=key)
lm = resp.get("LastModified")
return {
"key": key,
"size": int(resp.get("ContentLength") or 0),
"etag": str(resp.get("ETag") or "").strip('"'),
"content_type": str(resp.get("ContentType") or ""),
"last_modified": float(lm.timestamp()) if lm is not None else 0.0,
"url": public_url_for_key(key),
}
except Exception:
return None
def upload_file(local_path: str | Path, key: str, content_type: str = "") -> str:
"""Upload local file to SeaweedFS S3 API. Returns public URL."""
path = Path(local_path)
if not path.is_file():
return ""
if not s3_enabled():
return ""
ensure_bucket()
ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
client = _client()
extra = {"ContentType": ctype, "ACL": "public-read"}
try:
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs=extra)
except Exception:
# some SeaweedFS builds ignore ACL
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs={"ContentType": ctype})
return public_url_for_key(key)
def upload_bytes(data: bytes, key: str, content_type: str = "application/octet-stream") -> str:
if not data or not s3_enabled():
return ""
ensure_bucket()
client = _client()
ctype = content_type or "application/octet-stream"
try:
client.put_object(
Bucket=settings.s3_bucket,
Key=key,
Body=data,
ContentType=ctype,
ACL="public-read",
)
except Exception:
client.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=ctype)
return public_url_for_key(key)
def delete_object(key: str) -> bool:
"""Delete an object from the bucket. Returns True if delete was attempted successfully."""
k = str(key or "").strip().lstrip("/")
if not k or not s3_enabled():
return False
try:
_client().delete_object(Bucket=settings.s3_bucket, Key=k)
return True
except Exception:
return False
def purge_covers_older_than(*, keep_days: float = 2.0, max_delete: int = 5000) -> dict[str, Any]:
"""Delete session cover objects older than keep_days.
Scope: ``covers/*.jpg`` session frames only — never touches ``covers/avatars/``.
Permanent project policy: keep at most ~2 days of cover blobs in Seaweed/S3.
"""
out: dict[str, Any] = {
"ok": False,
"enabled": s3_enabled(),
"keep_days": float(keep_days),
"listed": 0,
"deleted": 0,
"skipped_avatar": 0,
"skipped_fresh": 0,
"errors": 0,
"bytes_deleted": 0,
}
if not s3_enabled():
return out
try:
days = max(0.5, min(30.0, float(keep_days)))
except Exception:
days = 2.0
out["keep_days"] = days
cutoff = time.time() - days * 86400.0
limit = max(1, min(20000, int(max_delete)))
client = _client()
bucket = settings.s3_bucket
token: str | None = None
try:
while out["deleted"] < limit:
kwargs: dict[str, Any] = {
"Bucket": bucket,
"Prefix": "covers/",
"MaxKeys": 1000,
}
if token:
kwargs["ContinuationToken"] = token
resp = client.list_objects_v2(**kwargs)
contents = resp.get("Contents") or []
if not contents and not resp.get("IsTruncated"):
break
for obj in contents:
key = str(obj.get("Key") or "")
if not key or key.endswith("/"):
continue
out["listed"] += 1
# stable room avatars — not session covers
if key.startswith("covers/avatars/"):
out["skipped_avatar"] += 1
continue
lm = obj.get("LastModified")
try:
ts = float(lm.timestamp()) if lm is not None else 0.0
except Exception:
ts = 0.0
if ts >= cutoff:
out["skipped_fresh"] += 1
continue
try:
client.delete_object(Bucket=bucket, Key=key)
out["deleted"] += 1
out["bytes_deleted"] += int(obj.get("Size") or 0)
except Exception:
out["errors"] += 1
if out["deleted"] >= limit:
break
if out["deleted"] >= limit:
break
if not resp.get("IsTruncated"):
break
token = resp.get("NextContinuationToken")
if not token:
break
out["ok"] = True
except Exception as exc:
out["error"] = str(exc)[:240]
return out
def upload_cover(session_id: str, local_path: str | Path) -> str:
key = f"covers/{session_id}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")
def upload_room_avatar(room_id: str, local_path: str | Path) -> str:
"""Stable per-room avatar object (频道头像), not session stream frame."""
rid = str(room_id or "").strip()
if not rid:
return ""
safe = "".join(ch if ch.isalnum() or ch in "-_" else "_" for ch in rid)[:80]
key = f"covers/avatars/{safe}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")