forked from mtusi2026/mtusi2026lab4
Добавить прямую загрузку по короткой подписи.
Proxy endpoint сохранён. Complete сверяет владельца, размер и checksum, а сравнение трафика API на двух размерах лежит в evidence.
This commit is contained in:
@@ -14,6 +14,7 @@ from app.errors import AppError
|
||||
|
||||
logger = logging.getLogger("messenger.s3")
|
||||
_client = None
|
||||
_signer = None
|
||||
|
||||
|
||||
def _client_or_create():
|
||||
@@ -38,6 +39,26 @@ def _client_or_create():
|
||||
return _client
|
||||
|
||||
|
||||
def _signer_or_create():
|
||||
"""Signs URLs for the host the browser/client can reach. It does not send traffic."""
|
||||
global _signer
|
||||
if _signer is None:
|
||||
if not config.S3_ACCESS_KEY_ID or not config.S3_SECRET_ACCESS_KEY:
|
||||
raise AppError(503, "service unavailable")
|
||||
_signer = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=config.S3_PUBLIC_ENDPOINT,
|
||||
aws_access_key_id=config.S3_ACCESS_KEY_ID,
|
||||
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
|
||||
region_name=config.S3_REGION,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
return _signer
|
||||
|
||||
|
||||
def _unavailable(exc: Exception) -> AppError:
|
||||
code = ""
|
||||
if isinstance(exc, ClientError):
|
||||
@@ -91,6 +112,39 @@ async def get_bytes(key: str) -> bytes:
|
||||
raise _unavailable(exc) from None
|
||||
|
||||
|
||||
def presign_put(key: str, content_type: str, size: int) -> str:
|
||||
return _signer_or_create().generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
"Bucket": config.S3_BUCKET,
|
||||
"Key": key,
|
||||
"ContentType": content_type,
|
||||
"ContentLength": size,
|
||||
},
|
||||
ExpiresIn=config.PRESIGN_TTL_SECONDS,
|
||||
HttpMethod="PUT",
|
||||
)
|
||||
|
||||
|
||||
async def head_size(key: str) -> int | None:
|
||||
def _head() -> int | None:
|
||||
try:
|
||||
response = _client_or_create().head_object(Bucket=config.S3_BUCKET, Key=key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in {"404", "NoSuchKey", "NotFound"}:
|
||||
return None
|
||||
raise
|
||||
return int(response["ContentLength"])
|
||||
|
||||
try:
|
||||
return await asyncio.to_thread(_head)
|
||||
except AppError:
|
||||
raise
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise _unavailable(exc) from None
|
||||
|
||||
|
||||
async def delete_key(key: str) -> None:
|
||||
def _delete() -> None:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user