client.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Aliyun OSS client for uploading agent run artifacts."""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. import oss2
  5. from supply_infra.config import InfraSettings, get_infra_settings
  6. class OssClient:
  7. """Thin wrapper around oss2 Bucket."""
  8. def __init__(
  9. self,
  10. settings: InfraSettings | None = None,
  11. *,
  12. root_prefix: str | None = None,
  13. ) -> None:
  14. self.settings = settings or get_infra_settings()
  15. if not self.settings.aliyun_oss_access_key_id:
  16. raise ValueError("ALIYUN_OSS_ACCESS_KEY_ID is not configured")
  17. if not self.settings.aliyun_oss_access_key_secret:
  18. raise ValueError("ALIYUN_OSS_ACCESS_KEY_SECRET is not configured")
  19. endpoint = f"https://oss-{self.settings.aliyun_oss_region}.aliyuncs.com"
  20. auth = oss2.Auth(
  21. self.settings.aliyun_oss_access_key_id,
  22. self.settings.aliyun_oss_access_key_secret,
  23. )
  24. self._bucket = oss2.Bucket(auth, endpoint, self.settings.aliyun_oss_bucket)
  25. prefix = root_prefix if root_prefix is not None else self.settings.aliyun_oss_root_prefix
  26. self._root = prefix.strip("/")
  27. self._public_base = self.settings.aliyun_oss_public_base_url.rstrip("/")
  28. def object_key(self, *parts: str) -> str:
  29. cleaned = [self._root] if self._root else []
  30. for part in parts:
  31. p = str(part).strip("/")
  32. if p:
  33. cleaned.append(p)
  34. return "/".join(cleaned)
  35. def public_url(self, object_key: str) -> str:
  36. key = object_key.lstrip("/")
  37. return f"{self._public_base}/{key}"
  38. def upload_file(self, local_path: Path | str, object_key: str) -> str:
  39. """Upload a local file and return its public CDN URL."""
  40. path = Path(local_path)
  41. if not path.is_file():
  42. raise FileNotFoundError(f"File not found: {path}")
  43. self._bucket.put_object_from_file(object_key, str(path))
  44. return self.public_url(object_key)