add level 3

This commit is contained in:
Матвей
2026-10-26 10:19:05 +03:00
parent 3b67201e5e
commit df15ab0967
16 changed files with 438 additions and 25 deletions
+4 -4
View File
@@ -1,17 +1,17 @@
# Отчёт — лабораторная 5
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Автор, группа: Matvey Kozyrev, BVT2301
- Целевая оценка; выбранный трек 5, если нужен: 3
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Python 3.12, PostgreSQL 17.6, SeaweedFS 4.17, RabbitMQ 4.1 и HAProxy 3.0 запускаются через Compose. Для локального синтетического стенда: `python3 scripts/init-secrets.py`, затем `docker compose up -d --build`; дождаться `docker compose ps` со статусом healthy и выполнить `make test`. Локальные секреты создаются в игнорируемом `secrets/`. Остановка без удаления данных: `docker compose down`; удаление учебных данных выполняется оператором отдельно через `docker compose down -v`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
PostgreSQL хранит метаданные и состояние, SeaweedFS — private staging/final objects, RabbitMQ — durable сообщения, worker — отдельный процесс. До HTTP 202 API полностью принимает и валидирует bytes, сохраняет staging-object и в одной DB-транзакции метаданные + job, затем ждёт RabbitMQ publisher confirm. Worker ack делает только после durable результата либо после финального failed. Обработка идемпотентна по attachment/pipeline/variant: повтор ready-job не меняет результат.
## Доказательства критериев
+61 -1
View File
@@ -4,7 +4,7 @@ x-api: &api
environment:
APP_HOST: 0.0.0.0
APP_PORT: 8080
APP_ENV: lab4
APP_ENV: lab5
DATABASE_URL_FILE: /run/secrets/database_url
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
@@ -13,6 +13,7 @@ x-api: &api
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
BROKER_URL_FILE: /run/secrets/broker_url
MAX_UPLOAD_BYTES: "10485760"
MAX_IMAGE_PIXELS: "40000000"
UPLOAD_CONCURRENCY: "1"
@@ -23,11 +24,14 @@ x-api: &api
- cursor_secret
- s3_access_key_id
- s3_secret_access_key
- broker_url
depends_on:
s3-init:
condition: service_completed_successfully
migrate:
condition: service_completed_successfully
broker:
condition: service_healthy
expose:
- "8080"
stop_grace_period: 10s
@@ -44,6 +48,27 @@ x-api: &api
memory: 512M
services:
broker:
image: rabbitmq:4.1.2-alpine
environment:
RABBITMQ_DEFAULT_USER: messenger
RABBITMQ_DEFAULT_PASS_FILE: /run/secrets/rabbitmq_password
secrets:
- rabbitmq_password
volumes:
- rabbitmq_data:/var/lib/rabbitmq
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 3s
retries: 20
start_period: 10s
deploy:
resources:
limits:
cpus: "0.50"
memory: 256M
s3:
image: chrislusf/seaweedfs:4.17@sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9
command: ["server", "-dir=/data", "-ip=s3", "-ip.bind=0.0.0.0", "-s3", "-s3.config=/run/secrets/s3_config", "-master.volumeSizeLimitMB=128", "-volume.max=64", "-s3.port.iceberg=0", "-filer.exposeDirectoryData=false"]
@@ -157,6 +182,36 @@ services:
api-b:
<<: *api
worker:
build:
context: .
command: ["/app/.venv/bin/python", "-m", "src.worker"]
environment:
APP_ENV: lab5
DATABASE_URL_FILE: /run/secrets/database_url
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
S3_ENDPOINT: http://s3:8333
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
BROKER_URL_FILE: /run/secrets/broker_url
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
secrets:
- database_url
- cursor_secret
- s3_access_key_id
- s3_secret_access_key
- broker_url
depends_on:
s3-init:
condition: service_completed_successfully
migrate:
condition: service_completed_successfully
broker:
condition: service_healthy
stop_grace_period: 30s
load_balancer:
image: haproxy:3.0.11-alpine
ports:
@@ -197,7 +252,12 @@ secrets:
file: ./secrets/database_url
cursor_secret:
file: ./secrets/cursor_secret
rabbitmq_password:
file: ./secrets/rabbitmq_password
broker_url:
file: ./secrets/broker_url
volumes:
s3_data:
postgres_data:
rabbitmq_data:
+34
View File
@@ -0,0 +1,34 @@
ALTER TABLE attachments
RENAME COLUMN object_key TO staging_key;
ALTER TABLE attachments
ADD COLUMN original_key text,
ADD COLUMN status text NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
ADD COLUMN error_code text,
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1,
ADD COLUMN processing_started_at timestamptz;
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version integer NOT NULL,
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
object_key text NOT NULL UNIQUE,
content_type text NOT NULL,
size_bytes integer NOT NULL CHECK (size_bytes > 0),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
sha256 char(64) NOT NULL,
PRIMARY KEY (attachment_id, pipeline_version, name)
);
CREATE TABLE attachment_jobs (
job_id uuid PRIMARY KEY,
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version integer NOT NULL DEFAULT 1,
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX attachment_jobs_status_idx ON attachment_jobs(status, updated_at);
+1
View File
@@ -10,5 +10,6 @@ dependencies = [
"boto3==1.43.115",
"fastapi==0.141.1",
"pillow==13.0.0",
"pika==1.3.2",
"uvicorn==0.40.0",
]
+2
View File
@@ -25,6 +25,8 @@ admin_key = write("s3_admin_key", secrets.token_hex(16))
admin_secret = write("s3_admin_secret", secrets.token_hex(32))
app_key = write("s3_access_key_id", secrets.token_hex(16))
app_secret = write("s3_secret_access_key", secrets.token_hex(32))
rabbitmq_password = write("rabbitmq_password", secrets.token_urlsafe(32))
write("broker_url", f"amqp://messenger:{rabbitmq_password}@broker:5672/%2F")
config_path = root / "s3.json"
config_path.write_text(json.dumps({"identities": [
{"name": "bootstrap", "credentials": [{"accessKey": admin_key, "secretKey": admin_secret}],
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Deliberately preserves named volumes and test data.
docker compose restart postgres s3 broker
docker compose up -d --wait postgres s3 broker
docker compose run --rm --no-deps s3-init
docker compose restart worker api-a api-b load_balancer
docker compose up -d --wait worker api-a api-b load_balancer
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
for service in api-a api-b; do
container="$(docker compose ps -q "$service")"
[ -n "$container" ] || continue
hostname="$(docker inspect --format '{{.Config.Hostname}}' "$container")"
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
docker compose stop "$service"
exit 0
fi
done
printf '%s\n' 'TARGET_INSTANCE_ID does not match a running API replica' >&2
exit 2
+29 -9
View File
@@ -1,4 +1,5 @@
import asyncio
from datetime import datetime, timezone
from hashlib import sha256
import os
from tempfile import TemporaryFile
@@ -15,6 +16,7 @@ from .errors import ApiError
from .models import Attachment
from .routes import get_current_user, get_store
from .storage.postgres import PostgresStore
from .broker import publish
router = APIRouter()
Image.MAX_IMAGE_PIXELS = 40000000
@@ -42,7 +44,7 @@ def inspect_image(file, content_type, max_pixels):
file.seek(0)
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=201)
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
await store.get_chat_for_member(chat_id, user["id"])
@@ -80,8 +82,8 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
digest.update(chunk)
await run_in_threadpool(file.write, chunk)
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
attachment_id = uuid4()
key = f"originals/{attachment_id}"
attachment_id, job_id = uuid4(), uuid4()
key = f"staging/{attachment_id}/original"
async with store.attachment_transaction() as connection:
await s3.put(key, file, size, content_type)
# Disabled by default; models a crash after PUT, before INSERT.
@@ -89,9 +91,15 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
attachment = await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key, connection=connection,
size, digest.hexdigest(), key, job_id, connection=connection,
)
return attachment # Transaction has committed before 201.
await publish({
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
})
attachment["variants"] = []
return attachment
except ClientDisconnect:
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
except TimeoutError:
@@ -109,8 +117,20 @@ async def download(attachment_id: UUID, request: Request,
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
attachment = await store.attachment_for_member(attachment_id, user["id"])
if variant != "original":
raise ApiError(404, "not_found", "Вариант не найден")
data = await request.app.state.s3.download(attachment)
return Response(data, media_type=attachment["content_type"],
if attachment["status"] != "ready":
raise ApiError(409, "conflict", "Вложение ещё не готово")
if variant == "original":
data = await request.app.state.s3.download(attachment)
content_type = attachment["content_type"]
else:
matching = [item for item in attachment["variants"] if item["name"] == variant]
if not matching:
raise ApiError(404, "not_found", "Вариант не найден")
item = matching[0]
suffix = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}[variant]
data = await request.app.state.s3.download_key(
f"variants/{attachment_id}/{suffix}", item["size_bytes"], item["sha256"]
)
content_type = item["content_type"]
return Response(data, media_type=content_type,
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
+58
View File
@@ -0,0 +1,58 @@
"""Small durable RabbitMQ adapter; broker messages contain no attachment bytes."""
import json
import os
from pathlib import Path
import pika
from starlette.concurrency import run_in_threadpool
from .errors import ApiError
QUEUE = "attachment.process.v1"
def broker_url() -> str:
path = os.environ.get("BROKER_URL_FILE")
value = Path(path).read_text(encoding="utf-8").strip() if path else os.environ.get("BROKER_URL", "")
if not value.startswith(("amqp://", "amqps://")):
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQP URL")
return value
def _connection() -> pika.BlockingConnection:
connection = pika.BlockingConnection(pika.URLParameters(broker_url()))
connection.channel().queue_declare(queue=QUEUE, durable=True)
return connection
def _publish(payload: dict) -> None:
connection = _connection()
try:
channel = connection.channel()
channel.confirm_delivery()
channel.basic_publish(
exchange="", routing_key=QUEUE,
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
mandatory=True,
)
finally:
connection.close()
async def publish(payload: dict) -> None:
try:
await run_in_threadpool(_publish, payload)
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
raise ApiError(503, "unavailable", "Брокер недоступен") from error
async def ready() -> None:
connection = None
try:
connection = await run_in_threadpool(_connection)
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
raise ApiError(503, "unavailable", "Брокер недоступен") from error
finally:
if connection is not None:
await run_in_threadpool(connection.close)
+2
View File
@@ -18,8 +18,10 @@ _CONFIGURATION_KEYS = {
"S3_ENDPOINT", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
"BROKER_URL", "BROKER_URL_FILE",
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
}
+13 -2
View File
@@ -133,8 +133,19 @@ class Attachment(BaseModel):
content_type: str
size_bytes: int
sha256: str
status: str = "ready"
variants: list = Field(default_factory=list)
status: str
variants: list["Variant"] = Field(default_factory=list)
error_code: str | None = None
created_at: datetime
updated_at: datetime
class Variant(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
+2
View File
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, Header, Query, Request, Response
from .cursor import CursorError, decode_cursor, encode_cursor
from .errors import ApiError
from .storage.postgres import PostgresStore
from .broker import ready as broker_ready
from .models import (
Chat,
ChatPageResponse,
@@ -84,6 +85,7 @@ async def readiness(request: Request, store: PostgresStore = Depends(get_store))
raise ApiError(503, "unavailable", "API завершает работу")
await store.ready()
await request.app.state.s3.ready()
await broker_ready()
return {"status": "ok"}
@router.post("/api/v1/users", response_model=User, status_code=201)
+84 -5
View File
@@ -320,12 +320,15 @@ class PostgresStore:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, digest, object_key, *, connection=None) -> dict:
content_type, size_bytes, digest, staging_key, job_id, *, connection=None) -> dict:
try:
row = await (connection or self.pool).fetchrow(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key) "
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, object_key,
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, staging_key,
)
await (connection or self.pool).execute(
"INSERT INTO attachment_jobs (job_id, attachment_id) VALUES ($1, $2)", job_id, attachment_id
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
@@ -341,12 +344,88 @@ class PostgresStore:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
raise ApiError(404, "not_found", "Вложение не найдено")
return dict(row)
return await self._attachment_with_variants(row)
async def _attachment_with_variants(self, row: asyncpg.Record | dict) -> dict:
result = dict(row)
variants = await self.pool.fetch(
"SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
"WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name",
result["id"], result["pipeline_version"],
)
result["variants"] = [dict(item) for item in variants]
return result
async def claim_attachment_job(self, attachment_id: UUID) -> dict | None:
try:
async with self.pool.acquire() as connection, connection.transaction():
row = await connection.fetchrow("SELECT * FROM attachments WHERE id = $1 FOR UPDATE", attachment_id)
if row is None or row["status"] in {"ready", "failed"}:
return None
await connection.execute(
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
attachment_id,
)
await connection.execute(
"UPDATE attachment_jobs SET status = 'processing', updated_at = now() WHERE attachment_id = $1", attachment_id
)
return dict(row)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variant: dict) -> None:
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
"VALUES ($1, 1, 'thumbnail', $2, $3, $4, $5, $6, $7) "
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
attachment_id, variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
)
await connection.execute(
"UPDATE attachments SET status = 'ready', original_key = $2, error_code = NULL, updated_at = now() WHERE id = $1",
attachment_id, original_key,
)
await connection.execute("UPDATE attachment_jobs SET status = 'ready', updated_at = now() WHERE attachment_id = $1", attachment_id)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def fail_attachment_job(self, attachment_id: UUID, code: str) -> None:
try:
await self.pool.execute(
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1", attachment_id, code
)
await self.pool.execute(
"UPDATE attachment_jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE attachment_id = $1", attachment_id, code
)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int) -> bool:
"""Return true only when a bounded at-least-once retry was recorded."""
try:
async with self.pool.acquire() as connection, connection.transaction():
job = await connection.fetchrow(
"SELECT attempt FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
)
if job is not None and job["attempt"] < max_attempts:
await connection.execute(
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', updated_at = now() WHERE attachment_id = $1",
attachment_id,
)
await connection.execute(
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
)
return True
await self.fail_attachment_job(attachment_id, "retry_exhausted")
return False
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
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")
rows = await self.pool.fetch("SELECT COALESCE(original_key, staging_key) AS 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}
+14 -4
View File
@@ -69,6 +69,13 @@ class S3Store:
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
Body=file, ContentLength=size, ContentType=content_type)
async def copy(self, source_key: str, destination_key: str, content_type: str) -> None:
await self.call(
"copy_object", Bucket=self.settings.bucket, Key=destination_key,
CopySource={"Bucket": self.settings.bucket, "Key": source_key},
ContentType=content_type, MetadataDirective="REPLACE",
)
async def list(self, prefix: str) -> dict[str, object]:
"""Return every object under a controlled prefix, handling S3 pagination."""
objects, _ = await self.list_with_pages(prefix)
@@ -95,8 +102,11 @@ class S3Store:
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"])
return await self.download_key(attachment["original_key"], attachment["size_bytes"], attachment["sha256"])
async def download_key(self, key: str, expected_size: int | None = None,
expected_sha256: str | None = None) -> bytes:
response = await self.call("get_object", Bucket=self.settings.bucket, Key=key)
body = response["Body"]
try:
data = await run_in_threadpool(body.read, self.settings.max_bytes + 1)
@@ -104,7 +114,7 @@ class S3Store:
raise ApiError(503, "unavailable", "S3 недоступно") from error
finally:
body.close()
if (len(data) != attachment["size_bytes"] or
sha256(data).hexdigest() != attachment["sha256"]):
if ((expected_size is not None and len(data) != expected_size) or
(expected_sha256 is not None and sha256(data).hexdigest() != expected_sha256)):
raise ApiError(503, "unavailable", "Оригинал недоступен")
return data
+95
View File
@@ -0,0 +1,95 @@
"""RabbitMQ consumer for the version-1 attachment pipeline."""
import asyncio
from hashlib import sha256
from io import BytesIO
import json
import logging
import os
from uuid import UUID
from PIL import Image, ImageOps
from .broker import QUEUE, _connection
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
if image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info):
background = Image.new("RGBA", image.size, "white")
background.alpha_composite(image.convert("RGBA"))
image = background.convert("RGB")
else:
image = image.convert("RGB")
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), image.width, image.height
async def process(store: PostgresStore, s3: S3Store, payload: dict) -> None:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id)
if attachment is None:
return
original_key = f"originals/{attachment_id}"
variant_key = f"variants/{attachment_id}/thumbnail.jpg"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered, width, height = await asyncio.to_thread(thumbnail, original)
await s3.put(variant_key, BytesIO(rendered), len(rendered), "image/jpeg")
await store.complete_attachment_job(attachment_id, original_key, {
"object_key": variant_key, "content_type": "image/jpeg", "size_bytes": len(rendered),
"width": width, "height": height, "sha256": sha256(rendered).hexdigest(),
})
await s3.delete(attachment["staging_key"])
def main() -> None:
settings = load_settings()
store = PostgresStore(settings.database_url)
asyncio.run(store.connect())
s3 = S3Store(S3Settings.load())
connection = _connection()
channel = connection.channel()
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_CONCURRENCY", "2"))))
def consume(ch, method, properties, body):
del properties
try:
payload = json.loads(body)
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
asyncio.run(process(store, s3, payload))
except Exception:
logging.exception("job failed")
try:
attachment_id = UUID(payload["attachment_id"])
retry = asyncio.run(store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5")))
))
except Exception:
retry = False
if retry:
ch.basic_nack(method.delivery_tag, requeue=True)
else:
ch.basic_ack(method.delivery_tag)
else:
ch.basic_ack(method.delivery_tag)
try:
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
channel.start_consuming()
finally:
connection.close()
s3.client.close()
asyncio.run(store.close())
if __name__ == "__main__":
main()
Generated
+11
View File
@@ -306,6 +306,7 @@ dependencies = [
{ name = "asyncpg" },
{ name = "boto3" },
{ name = "fastapi" },
{ name = "pika" },
{ name = "pillow" },
{ name = "uvicorn" },
]
@@ -316,10 +317,20 @@ requires-dist = [
{ name = "asyncpg", specifier = "==0.31.0" },
{ name = "boto3", specifier = "==1.43.115" },
{ name = "fastapi", specifier = "==0.141.1" },
{ name = "pika", specifier = "==1.3.2" },
{ name = "pillow", specifier = "==13.0.0" },
{ name = "uvicorn", specifier = "==0.40.0" },
]
[[package]]
name = "pika"
version = "1.3.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/db/db/d4102f356af18f316c67f2cead8ece307f731dd63140e2c71f170ddacf9b/pika-1.3.2.tar.gz", hash = "sha256:b2a327ddddf8570b4965b3576ac77091b850262d34ce8c1d8cb4e4146aa4145f", size = 145029, upload-time = "2023-05-05T14:25:43.368Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f9/f3/f412836ec714d36f0f4ab581b84c491e3f42c6b5b97a6c6ed1817f3c16d0/pika-1.3.2-py3-none-any.whl", hash = "sha256:0779a7c1fafd805672796085560d290213a465e4f6f76a6fb19e378d8041a14f", size = 155415, upload-time = "2023-05-05T14:25:41.484Z" },
]
[[package]]
name = "pillow"
version = "13.0.0"