forked from mtusi2026/mtusi2026lab4
add level 4
This commit is contained in:
+9
-1
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from tempfile import TemporaryFile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
@@ -62,7 +63,10 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
if length > limit:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше лимита")
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
timeout = int(os.environ.get("UPLOAD_TIMEOUT_SECONDS", "30"))
|
||||
if not 1 <= timeout <= 120:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит времени загрузки")
|
||||
async with asyncio.timeout(timeout):
|
||||
async with request.app.state.upload_slot:
|
||||
# Temporary scratch space only; deleted on every exit, never used for downloads.
|
||||
with TemporaryFile() as file:
|
||||
@@ -78,6 +82,10 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default. Used only by the failure-injection test to
|
||||
# model a process crash after S3 accepts the object and before DB.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
return await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Idempotent private bucket bootstrap; executed with separate admin credentials."""
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
@@ -29,6 +30,18 @@ def main():
|
||||
except ClientError as error:
|
||||
if error.response["Error"]["Code"] != "NoSuchBucketPolicy":
|
||||
raise
|
||||
# The master health endpoint can become available before a volume accepts
|
||||
# writes after a restart. Verify the actual data path before APIs start.
|
||||
probe_key = f"_bootstrap/write-probe-{uuid4()}"
|
||||
for attempt in range(30):
|
||||
try:
|
||||
store.client.put_object(Bucket=bucket, Key=probe_key, Body=b"ready")
|
||||
store.client.delete_object(Bucket=bucket, Key=probe_key)
|
||||
break
|
||||
except (BotoCoreError, ClientError):
|
||||
if attempt == 29:
|
||||
raise RuntimeError("S3 write path startup timed out") from None
|
||||
time.sleep(1)
|
||||
print("PASS: private S3 bucket ready")
|
||||
finally:
|
||||
store.client.close()
|
||||
|
||||
@@ -19,6 +19,7 @@ _CONFIGURATION_KEYS = {
|
||||
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
|
||||
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
|
||||
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+5
-1
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -45,7 +46,10 @@ async def lifespan(application: FastAPI):
|
||||
application.state.store = store
|
||||
application.state.settings = settings
|
||||
application.state.s3 = S3Store(S3Settings.load())
|
||||
application.state.upload_slot = asyncio.Semaphore(1)
|
||||
concurrency = int(os.environ.get("UPLOAD_CONCURRENCY", "1"))
|
||||
if not 1 <= concurrency <= 8:
|
||||
raise ValueError("UPLOAD_CONCURRENCY must be 1..8")
|
||||
application.state.upload_slot = asyncio.Semaphore(concurrency)
|
||||
application.state.accepting_requests = True
|
||||
try:
|
||||
yield
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Safely reconcile attachment metadata and original S3 objects.
|
||||
|
||||
The command is dry-run by default. It only deletes unreferenced objects older
|
||||
than a configured grace period; missing objects are reported and never cause a
|
||||
metadata delete. That keeps a delayed PostgreSQL commit and active attachment
|
||||
records safe from a maintenance run.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
|
||||
async def run(args) -> dict:
|
||||
settings = load_settings()
|
||||
db = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await db.connect()
|
||||
try:
|
||||
objects, metadata = await s3.list("originals/"), await db.attachment_keys()
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
orphan = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified <= cutoff)
|
||||
fresh = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified > cutoff)
|
||||
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
|
||||
if key not in objects}.items())
|
||||
deleted = []
|
||||
if args.apply:
|
||||
for key in orphan:
|
||||
await s3.delete(key)
|
||||
deleted.append(key)
|
||||
return {
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"grace_seconds": args.grace_seconds,
|
||||
"s3_objects": len(objects),
|
||||
"metadata_rows": len(metadata),
|
||||
"orphan_candidates": orphan,
|
||||
"fresh_unreferenced": fresh,
|
||||
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
|
||||
"deleted": deleted,
|
||||
}
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
|
||||
parser.add_argument("--grace-seconds", type=int, default=3600)
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
|
||||
parser.error("--grace-seconds must be 0..604800")
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -324,3 +324,11 @@ class PostgresStore:
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
return dict(row)
|
||||
|
||||
async def attachment_keys(self) -> dict[str, UUID]:
|
||||
"""Inventory used only by the maintenance reconciler."""
|
||||
try:
|
||||
rows = await self.pool.fetch("SELECT object_key, id FROM attachments")
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
return {row["object_key"]: row["id"] for row in rows}
|
||||
|
||||
@@ -69,6 +69,24 @@ class S3Store:
|
||||
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
|
||||
Body=file, ContentLength=size, ContentType=content_type)
|
||||
|
||||
async def list(self, prefix: str) -> dict[str, object]:
|
||||
"""Return every object under a controlled prefix, handling S3 pagination."""
|
||||
result: dict[str, object] = {}
|
||||
token = None
|
||||
while True:
|
||||
args = {"Bucket": self.settings.bucket, "Prefix": prefix}
|
||||
if token:
|
||||
args["ContinuationToken"] = token
|
||||
page = await self.call("list_objects_v2", **args)
|
||||
for item in page.get("Contents", []):
|
||||
result[item["Key"]] = item["LastModified"]
|
||||
if not page.get("IsTruncated"):
|
||||
return result
|
||||
token = page["NextContinuationToken"]
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
|
||||
|
||||
async def download(self, attachment):
|
||||
response = await self.call("get_object", Bucket=self.settings.bucket,
|
||||
Key=attachment["object_key"])
|
||||
|
||||
Reference in New Issue
Block a user