112 lines
3.9 KiB
Python
112 lines
3.9 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import os
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
class MediaStorageConfigurationError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _required(name: str, *fallback_names: str) -> str:
|
|
for candidate in (name, *fallback_names):
|
|
value = os.getenv(candidate)
|
|
if value is not None and value.strip():
|
|
return value.strip()
|
|
names = ", ".join((name, *fallback_names))
|
|
raise MediaStorageConfigurationError(
|
|
f"Missing required media storage environment variable. Expected one of: {names}"
|
|
)
|
|
|
|
|
|
def _optional(name: str, *fallback_names: str) -> str | None:
|
|
for candidate in (name, *fallback_names):
|
|
value = os.getenv(candidate)
|
|
if value is not None and value.strip():
|
|
return value.strip()
|
|
return None
|
|
|
|
|
|
def _parse_bool(value: str | None, *, default: bool) -> bool:
|
|
if value is None:
|
|
return default
|
|
normalized = value.strip().lower()
|
|
if normalized in {"1", "true", "yes", "on"}:
|
|
return True
|
|
if normalized in {"0", "false", "no", "off"}:
|
|
return False
|
|
raise MediaStorageConfigurationError(f"Invalid boolean value: {value!r}")
|
|
|
|
|
|
def _normalize_endpoint(raw: str, secure_override: bool | None) -> tuple[str, bool]:
|
|
"""
|
|
MinIO's Python client expects `host[:port]` plus a separate secure flag.
|
|
Accept either `host:port` or a full http(s) URL from environment config.
|
|
Path-prefixed reverse proxy URLs are rejected because S3 signatures depend
|
|
on the exact host/path and MinIO client endpoints do not support URL prefixes.
|
|
"""
|
|
value = raw.strip().rstrip("/")
|
|
if "://" not in value:
|
|
return value, bool(secure_override)
|
|
|
|
parsed = urlparse(value)
|
|
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
raise MediaStorageConfigurationError(f"Invalid media endpoint: {raw!r}")
|
|
if parsed.path not in {"", "/"}:
|
|
raise MediaStorageConfigurationError(
|
|
"MEDIA_PRESIGN_ENDPOINT/MINIO_ENDPOINT must not contain a path prefix"
|
|
)
|
|
secure = parsed.scheme == "https" if secure_override is None else secure_override
|
|
return parsed.netloc, secure
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class MediaStorageSettings:
|
|
endpoint: str
|
|
secure: bool
|
|
access_key: str
|
|
secret_key: str
|
|
bucket: str
|
|
region: str
|
|
url_ttl_seconds: int
|
|
|
|
@classmethod
|
|
def from_env(cls) -> "MediaStorageSettings":
|
|
# Prefer an externally reachable presign endpoint. This matters when the
|
|
# API reaches MinIO as `minio:9000` but browser/mobile clients must use a
|
|
# host such as `media.example.com`.
|
|
raw_endpoint = _required(
|
|
"MEDIA_PRESIGN_ENDPOINT",
|
|
"MEDIA_STORAGE_ENDPOINT",
|
|
"MINIO_ENDPOINT",
|
|
)
|
|
|
|
secure_raw = _optional("MEDIA_STORAGE_SECURE", "MINIO_SECURE")
|
|
secure_override = (
|
|
_parse_bool(secure_raw, default=False) if secure_raw is not None else None
|
|
)
|
|
endpoint, secure = _normalize_endpoint(raw_endpoint, secure_override)
|
|
|
|
ttl_raw = _optional("MEDIA_URL_TTL_SECONDS") or "900"
|
|
try:
|
|
ttl = int(ttl_raw)
|
|
except ValueError as exc:
|
|
raise MediaStorageConfigurationError(
|
|
"MEDIA_URL_TTL_SECONDS must be an integer"
|
|
) from exc
|
|
if not 60 <= ttl <= 86_400:
|
|
raise MediaStorageConfigurationError(
|
|
"MEDIA_URL_TTL_SECONDS must be between 60 and 86400 seconds"
|
|
)
|
|
|
|
return cls(
|
|
endpoint=endpoint,
|
|
secure=secure,
|
|
access_key=_required("MEDIA_STORAGE_ACCESS_KEY", "MINIO_ACCESS_KEY"),
|
|
secret_key=_required("MEDIA_STORAGE_SECRET_KEY", "MINIO_SECRET_KEY"),
|
|
bucket=_required("MEDIA_STORAGE_BUCKET", "MINIO_BUCKET"),
|
|
region=_optional("MEDIA_STORAGE_REGION", "MINIO_REGION") or "us-east-1",
|
|
url_ttl_seconds=ttl,
|
|
)
|