This commit is contained in:
2026-11-06 18:45:08 +03:00
parent 545d083049
commit 482e7ff477
17 changed files with 958 additions and 42 deletions
+10 -7
View File
@@ -6,7 +6,7 @@ from PIL import Image, UnidentifiedImageError
from sqlalchemy import func, select
from .errors import APIError
from .models import Attachment, ChatMember
from .models import Attachment, AttachmentJob, ChatMember
from .object_storage import BUCKET, PREFIX, s3_client
from .store import ensure_uuid, serialize, store
@@ -48,25 +48,28 @@ def lock_object(session, key):
def metadata(attachment):
result = serialize(attachment, 'id', 'chat_id', 'owner_id', 'filename',
'content_type', 'size_bytes', 'sha256', 'created_at')
return {**result, 'updated_at': result['created_at'], 'status': 'ready',
'variants': [], 'error_code': None}
'content_type', 'size_bytes', 'sha256', 'created_at',
'updated_at', 'status', 'error_code')
return {**result, 'variants': [{k: v for k, v in item.items() if k != 'object_key'}
for item in attachment.variants]}
def save_attachment(source, chat_id, actor_id, filename, content_type, size, digest):
validate_image(source, content_type)
attachment_id = str(uuid4())
key = PREFIX + attachment_id
staging_key = 'staging/' + attachment_id
with store.sessions.begin() as session:
store._chat(session, chat_id, actor_id)
lock_object(session, key)
s3_client().put_object(Bucket=BUCKET, Key=key, Body=source,
lock_object(session, staging_key)
s3_client().put_object(Bucket=BUCKET, Key=staging_key, Body=source,
ContentLength=size, ContentType=content_type)
attachment = Attachment(id=attachment_id, chat_id=chat_id, owner_id=actor_id,
object_key=key, filename=filename, content_type=content_type,
size_bytes=size, sha256=digest)
size_bytes=size, sha256=digest, staging_key=staging_key)
session.add(attachment)
session.flush()
session.add(AttachmentJob(attachment_id=attachment_id))
result = metadata(attachment)
# An uncertain COMMIT is not followed by DELETE: cleanup checks the DB later.
return result
+33 -8
View File
@@ -1,6 +1,7 @@
"""Remove old S3 objects without committed metadata. Never delete on a DB error."""
import argparse
import logging
import os
import time
from datetime import datetime, timedelta, timezone
@@ -10,23 +11,47 @@ from sqlalchemy.orm import sessionmaker
from .attachments import lock_object
from .database import create_db_engine
from .models import Attachment
from .object_storage import BUCKET, PREFIX, s3_client
from .object_storage import BUCKET, s3_client
GRACE = timedelta(hours=1)
GRACE = timedelta(seconds=max(1, int(os.getenv('STAGING_RETENTION_SECONDS', '86400'))))
def cleanup(sessions, client, now=None):
cutoff = (now or datetime.now(timezone.utc)) - GRACE
deleted = 0
for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET, Prefix=PREFIX):
for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET):
for obj in page.get('Contents', []):
if obj['LastModified'] >= cutoff:
continue
key = obj['Key']
if not key.startswith(('staging/', 'originals/', 'variants/')):
continue
with sessions.begin() as session:
lock_object(session, key)
if session.scalar(select(Attachment.id).where(Attachment.object_key == key)):
continue
if key.startswith('staging/'):
attachment = session.scalar(select(Attachment).where(
Attachment.staging_key == key).with_for_update())
if attachment:
if attachment.status in ('queued', 'processing'):
continue
if attachment.status == 'failed' and attachment.updated_at >= cutoff:
continue
client.delete_object(Bucket=BUCKET, Key=key)
attachment.staging_key = None
deleted += 1
continue
else:
# All final keys belong to a server-generated attachment UUID.
from uuid import UUID
try:
attachment_id = str(UUID(key.split('/')[1]))
except (ValueError, IndexError):
continue
attachment = session.get(Attachment, attachment_id, with_for_update=True)
if attachment:
if attachment.status != 'failed' or attachment.updated_at >= cutoff:
continue
client.delete_object(Bucket=BUCKET, Key=key)
deleted += 1
continue
# Recheck age after taking the same lock as the uploader.
if client.head_object(Bucket=BUCKET, Key=key)['LastModified'] >= cutoff:
continue
@@ -52,7 +77,7 @@ def main():
raise SystemExit(1) from None
if args.once:
break
time.sleep(3600)
time.sleep(60)
finally:
engine.dispose()
+116
View File
@@ -0,0 +1,116 @@
"""One isolated process per attempt; quality: JPEG 85, WebP 80; no EXIF/ICC."""
import hashlib
import io
import os
import sys
from PIL import Image, ImageOps, UnidentifiedImageError
from sqlalchemy.orm import sessionmaker
from .attachments import MAX_BYTES, MAX_PIXELS
from .database import create_db_engine
from .jobs import now
from .models import Attachment, AttachmentJob
from .object_storage import BUCKET, s3_client
def fit_size(size, bound):
width, height = size
if max(size) <= bound:
return size
return max(1, width * bound // max(size)), max(1, height * bound // max(size))
def variants(data):
with Image.open(io.BytesIO(data), formats=['PNG', 'JPEG']) as original:
if original.width * original.height > MAX_PIXELS:
raise ValueError('pixel limit')
original.load()
oriented = ImageOps.exif_transpose(original)
rgba = oriented.convert('RGBA')
rgb = Image.new('RGB', rgba.size, 'white')
rgb.paste(rgba, mask=rgba.getchannel('A'))
rgba.close()
oriented.close()
rgb.info.clear()
try:
for name, image, fmt, mime, quality in (
('thumbnail', rgb.resize(fit_size(rgb.size, 256), Image.Resampling.LANCZOS), 'JPEG', 'image/jpeg', 85),
('crop', ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS), 'JPEG', 'image/jpeg', 85),
('optimized', rgb.resize(fit_size(rgb.size, 1280), Image.Resampling.LANCZOS), 'WEBP', 'image/webp', 80),
):
with image, io.BytesIO() as output:
image.save(output, format=fmt, quality=quality)
blob = output.getvalue()
yield {'name': name, 'content_type': mime, 'width': image.width,
'height': image.height, 'size_bytes': len(blob),
'sha256': hashlib.sha256(blob).hexdigest()}, blob
finally:
rgb.close()
def process(sessions, job_id, token):
with sessions() as session:
job = session.get(AttachmentJob, job_id)
if job.lease_token != token:
return
attachment = session.get(Attachment, job.attachment_id)
staging_key = attachment.staging_key
client = s3_client()
response = client.get_object(Bucket=BUCKET, Key=staging_key)
with response['Body'] as body:
data = body.read(MAX_BYTES + 1)
if len(data) != attachment.size_bytes or hashlib.sha256(data).hexdigest() != attachment.sha256:
raise ValueError('staging checksum mismatch')
try:
rendered = list(variants(data))
except OSError as exc:
raise ValueError('invalid image') from exc
# Job lock fences the final writes, cleanup and publication against lease recovery.
# Work before this transaction is CPU-only. Keys are stable across retries.
with sessions.begin() as session:
job = session.get(AttachmentJob, job_id, with_for_update=True)
if job.lease_token != token or job.lease_until <= now():
return
current = session.get(Attachment, job.attachment_id, with_for_update=True)
if current.status != 'processing':
return
client.put_object(Bucket=BUCKET, Key=current.object_key, Body=data,
ContentType=current.content_type)
saved = []
for meta, blob in rendered:
key = f'variants/{current.id}/v{job.pipeline_version}/{meta["name"]}'
client.put_object(Bucket=BUCKET, Key=key, Body=blob, ContentType=meta['content_type'])
saved.append({**meta, 'object_key': key})
# Test-only crash injection; never enabled by compose.yaml.
if os.getenv('JOB_FAULT') == 'after_objects':
os._exit(91)
current.variants = saved
current.status, current.error_code = 'ready', None
current.updated_at = now()
job.lease_token = job.lease_until = None
if os.getenv('JOB_FAULT') == 'after_commit':
os._exit(92)
def main():
# Linux worker: bounded address space as well as the container memory limit.
import resource
memory = int(os.getenv('JOB_MEMORY_MB', '768')) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
engine = create_db_engine()
try:
process(sessionmaker(engine, expire_on_commit=False), sys.argv[1], sys.argv[2])
except (UnidentifiedImageError, Image.DecompressionBombError, ValueError, SyntaxError):
return 20
except MemoryError:
return 21
except Exception:
return 22 # No credentials or decoder/database internals in logs.
finally:
engine.dispose()
return 0
if __name__ == '__main__':
sys.exit(main())
+176
View File
@@ -0,0 +1,176 @@
"""Small PostgreSQL outbox + Redis Streams queue; PostgreSQL owns job state."""
import argparse
import json
import logging
import os
import random
import time
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from redis import Redis
from redis.exceptions import ResponseError
from sqlalchemy import and_, or_, select
from sqlalchemy.orm import sessionmaker
from .database import create_db_engine
from .models import Attachment, AttachmentJob
from .object_storage import BUCKET, s3_client
STREAM = 'attachment-jobs'
GROUP = 'image-workers'
MAX_ATTEMPTS = max(1, int(os.getenv('JOB_MAX_ATTEMPTS', '5')))
TIMEOUT = max(1, int(os.getenv('JOB_TIMEOUT_SECONDS', '60')))
LEASE_SECONDS = TIMEOUT + 15
def now():
return datetime.now(timezone.utc)
def broker():
return Redis.from_url(os.getenv('BROKER_URL', 'redis://broker:6379/0'),
decode_responses=True, socket_connect_timeout=2, socket_timeout=5)
def ensure_group(client):
try:
client.xgroup_create(STREAM, GROUP, id='0', mkstream=True)
except ResponseError as exc:
if not str(exc).startswith('BUSYGROUP'):
raise
def envelope(job):
return {'schema_version': 1, 'job_id': job.id, 'type': 'attachment.process.v1',
'attachment_id': job.attachment_id, 'pipeline_version': job.pipeline_version,
'attempt': job.attempt + 1,
'created_at': job.created_at.isoformat().replace('+00:00', 'Z')}
def fail(session, job, attachment, code, permanent=False):
job.failures += 1
job.last_error = code
job.lease_token = job.lease_until = job.published_at = None
attachment.updated_at = now()
if permanent or job.failures >= MAX_ATTEMPTS:
attachment.status = 'failed'
attachment.error_code = code if permanent else 'retry_exhausted'
else:
attachment.status = 'queued'
attachment.error_code = None
delay = min(60, 2 ** min(job.failures, 6)) * random.uniform(0.5, 1.5)
job.available_at = now() + timedelta(seconds=delay)
logging.info('job=%s attempt=%s result=%s code=%s', job.id, job.attempt, attachment.status, code)
def dispatch_once(sessions, client):
# A crash after XADD but before COMMIT deliberately results in redelivery.
with sessions.begin() as session:
jobs = list(session.scalars(select(AttachmentJob).join(Attachment).where(
or_(and_(Attachment.status == 'queued', AttachmentJob.published_at.is_(None)),
and_(Attachment.status == 'processing', AttachmentJob.lease_until <= now())),
AttachmentJob.available_at <= now()).order_by(AttachmentJob.available_at)
.with_for_update(skip_locked=True, of=AttachmentJob).limit(50)))
for job in jobs:
attachment = session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment.status == 'processing':
if job.lease_until <= now():
fail(session, job, attachment, 'lease_expired')
continue
if job.published_at is None:
client.xadd(STREAM, {'job': json.dumps(envelope(job))})
job.published_at = now()
def claim(sessions, message):
if (message.get('schema_version') != 1 or message.get('type') != 'attachment.process.v1'
or message.get('pipeline_version') != 1):
raise ValueError('unsupported job envelope')
job_id = str(UUID(message['job_id']))
with sessions.begin() as session:
job = session.get(AttachmentJob, job_id, with_for_update=True)
if job is None or job.attachment_id != message.get('attachment_id'):
raise ValueError('unknown job')
attachment = session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment.status != 'queued' or job.available_at > now():
return None
job.attempt += 1
job.lease_token = str(uuid4())
job.lease_until = now() + timedelta(seconds=LEASE_SECONDS)
attachment.status = 'processing'
attachment.updated_at = now()
return job.id, job.lease_token
def record_failure(sessions, job_id, token, code, permanent=False):
with sessions.begin() as session:
job = session.get(AttachmentJob, job_id, with_for_update=True)
if job.lease_token == token:
attachment = session.get(Attachment, job.attachment_id, with_for_update=True)
fail(session, job, attachment, code, permanent)
def replay(sessions, job_id, reason):
if not reason.strip() or len(reason) > 200:
raise ValueError('Give a nonempty reason of at most 200 characters')
with sessions.begin() as session:
job = session.get(AttachmentJob, str(UUID(job_id)), with_for_update=True)
if job is None:
raise ValueError('Job not found')
attachment = session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment.status != 'failed':
raise ValueError('Replay is allowed only for failed jobs')
if not attachment.staging_key:
raise ValueError('Staging retention expired; upload the file again')
s3_client().head_object(Bucket=BUCKET, Key=attachment.staging_key)
job.replay_audit = job.replay_audit + [{'at': now().isoformat(), 'reason': reason,
'after_attempt': job.attempt,
'last_error': job.last_error}]
job.failures = 0
job.available_at = now()
job.published_at = job.lease_until = job.lease_token = None
attachment.status, attachment.error_code = 'queued', None
attachment.updated_at = now()
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('dispatch')
sub.add_parser('failed')
retry = sub.add_parser('replay')
retry.add_argument('job_id')
retry.add_argument('--reason', required=True)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
engine = create_db_engine()
sessions = sessionmaker(engine, expire_on_commit=False)
try:
if args.command == 'failed':
with sessions() as session:
for job, att in session.execute(select(AttachmentJob, Attachment).join(
Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(Attachment.status == 'failed')):
print(json.dumps({'job_id': job.id, 'attachment_id': att.id,
'attempt': job.attempt, 'error_code': att.error_code,
'last_error': job.last_error,
'replay_available': bool(att.staging_key)}))
elif args.command == 'replay':
replay(sessions, args.job_id, args.reason)
print('Job queued for replay')
else:
client = broker()
while True:
try:
ensure_group(client)
dispatch_once(sessions, client)
except Exception as exc:
logging.warning('Dispatch deferred: %s', type(exc).__name__)
time.sleep(1)
finally:
engine.dispose()
if __name__ == '__main__':
main()
+23 -1
View File
@@ -3,7 +3,7 @@ from uuid import uuid4
from sqlalchemy import BigInteger, CheckConstraint, DateTime, ForeignKey, Index, Text, Uuid, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
class Base(DeclarativeBase):
@@ -74,6 +74,28 @@ class Attachment(Base):
size_bytes: Mapped[int] = mapped_column(BigInteger)
sha256: Mapped[str] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
status: Mapped[str] = mapped_column(Text, server_default='queued')
staging_key: Mapped[str | None] = mapped_column(Text)
variants: Mapped[list] = mapped_column(JSONB, server_default='[]')
error_code: Mapped[str | None] = mapped_column(Text)
class AttachmentJob(Base):
"""The job row is also the transactional outbox and failed-job registry."""
__tablename__ = 'attachment_jobs'
id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4()))
attachment_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('attachments.id'), unique=True)
pipeline_version: Mapped[int] = mapped_column(BigInteger, server_default='1')
attempt: Mapped[int] = mapped_column(BigInteger, server_default='0')
failures: Mapped[int] = mapped_column(BigInteger, server_default='0')
last_error: Mapped[str | None] = mapped_column(Text)
available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
lease_token: Mapped[str | None] = mapped_column(Uuid(as_uuid=False))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
replay_audit: Mapped[list] = mapped_column(JSONB, server_default='[]')
class IdempotencyRecord(Base):
+11 -5
View File
@@ -20,7 +20,7 @@ router = APIRouter(prefix='/api/v1', tags=['attachments'])
decode_slot = asyncio.Semaphore(1)
@router.post('/chats/{chat_id}/attachments', status_code=201)
@router.post('/chats/{chat_id}/attachments', status_code=202)
async def upload(chat_id: str, request: Request, filename: str = Query(...),
user: dict = Depends(current_user)):
chat_id = ensure_uuid(chat_id)
@@ -67,9 +67,15 @@ def attachment_info(attachment_id: str, user: dict = Depends(current_user)):
@router.get('/attachments/{attachment_id}/content')
def download(attachment_id: str, variant: str = 'original', user: dict = Depends(current_user)):
attachment = get_attachment(attachment_id, user['id'])
if attachment.status != 'ready':
raise APIError(409, 'conflict', 'Вложение ещё не готово')
key, content_type, size = attachment.object_key, attachment.content_type, attachment.size_bytes
if variant != 'original':
raise APIError(404, 'not_found', 'Вариант не найден')
body = s3_client().get_object(Bucket=BUCKET, Key=attachment.object_key)['Body']
item = next((v for v in attachment.variants if v['name'] == variant), None)
if item is None:
raise APIError(404, 'not_found', 'Вариант не найден')
key, content_type, size = item['object_key'], item['content_type'], item['size_bytes']
body = s3_client().get_object(Bucket=BUCKET, Key=key)['Body']
def chunks():
try:
@@ -77,8 +83,8 @@ def download(attachment_id: str, variant: str = 'original', user: dict = Depends
finally:
body.close()
return StreamingResponse(chunks(), media_type=attachment.content_type,
headers={'Content-Length': str(attachment.size_bytes),
return StreamingResponse(chunks(), media_type=content_type,
headers={'Content-Length': str(size),
'Content-Disposition': "attachment; filename*=UTF-8''" + quote(attachment.filename, safe=''),
'X-Content-Type-Options': 'nosniff'},
background=BackgroundTask(body.close))
+5 -2
View File
@@ -136,8 +136,9 @@ class PostgresStore:
with self.sessions.begin() as session:
self._chat(session, chat_id, actor_id)
if attachment_ids:
found = list(session.scalars(select(Attachment.id).where(
Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id)))
found = list(session.scalars(select(Attachment).where(
Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id)
.order_by(Attachment.id).with_for_update()))
if len(found) != len(attachment_ids):
raise APIError(404, 'not_found', 'Объект не найден')
if idempotency_key is not None:
@@ -150,6 +151,8 @@ class PostgresStore:
if previous.text != text or previous.attachment_ids != attachment_ids:
raise APIError(409, 'conflict', 'Ключ уже использован для другого сообщения')
return serialize(previous, *MESSAGE_FIELDS)
if attachment_ids and any(item.status == 'failed' for item in found):
raise APIError(409, 'conflict', 'Обработка вложения завершилась ошибкой')
session.execute(update(Chat).where(Chat.id == chat_id).values(
history_version=Chat.history_version + 1))
message = Message(chat_id=chat_id, sender_id=actor_id, text=text, attachment_ids=attachment_ids)
+76
View File
@@ -0,0 +1,76 @@
"""Bounded consumers, one unacknowledged message per consumer, hard process timeout."""
import json
import logging
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
from sqlalchemy.orm import sessionmaker
from .database import create_db_engine
from .jobs import GROUP, STREAM, LEASE_SECONDS, TIMEOUT, broker, claim, ensure_group, record_failure
def handle(sessions, client, message_id, fields):
try:
claimed = claim(sessions, json.loads(fields['job']))
except (ValueError, KeyError, TypeError):
logging.error('Invalid broker envelope: id=%s', message_id)
claimed = None
if claimed:
job_id, token = claimed
try:
result = subprocess.run([sys.executable, '-m', 'src.image_processor', job_id, token],
timeout=TIMEOUT, check=False)
code = result.returncode
except subprocess.TimeoutExpired:
code = 23
if code in (91, 92):
# Simulate a lost worker before ack: leave the Redis pending entry and lease.
return
if code:
record_failure(sessions, job_id, token,
{20: 'invalid_image', 21: 'resource_limit', 23: 'processing_timeout'}
.get(code, 'processing_failed'), permanent=code in (20, 21))
# Only after a durable ready/failed/retry (or an existing durable lease).
with client.pipeline(transaction=True) as pipe:
pipe.xack(STREAM, GROUP, message_id)
pipe.xdel(STREAM, message_id)
pipe.execute()
def consume(sessions):
client = broker()
consumer = str(uuid4())
cursor = '0-0'
while True:
try:
ensure_group(client)
pending = client.xautoclaim(STREAM, GROUP, consumer, LEASE_SECONDS * 1000,
start_id=cursor, count=1)
cursor, messages = pending[0], pending[1]
if not messages:
batches = client.xreadgroup(GROUP, consumer, {STREAM: '>'}, count=1, block=1000)
messages = batches[0][1] if batches else []
for message_id, fields in messages:
handle(sessions, client, message_id, fields)
except Exception as exc:
logging.warning('Worker deferred: %s', type(exc).__name__)
time.sleep(1)
def main():
logging.basicConfig(level=logging.INFO)
engine = create_db_engine()
sessions = sessionmaker(engine, expire_on_commit=False)
concurrency = min(4, max(1, int(os.getenv('WORKER_CONCURRENCY', '2'))))
with ThreadPoolExecutor(max_workers=concurrency) as pool:
for task in [pool.submit(consume, sessions) for _ in range(concurrency)]:
task.result()
if __name__ == '__main__':
main()