Files
mtusi2026lab5-fork/app/worker.py
T
2026-11-22 17:20:34 +03:00

311 lines
11 KiB
Python

"""Separate process: copy the staged original and write one thumbnail.
Ack happens only after that result is committed. A kill before ack redelivers the same
job id; the variant primary key keeps the second run from creating a second thumbnail.
Staging is left in place. Removing it is a later step, after the result is known to be safe.
"""
import asyncio
import hashlib
import logging
import signal
import uuid
from datetime import datetime, timezone
from pathlib import Path
import asyncpg
from .broker import Broker, BrokerDown
from .config import job_max_attempts, job_timeout_seconds, load_broker_url, load_object_settings, load_settings, worker_concurrency
from .db import open_pool
from .jobs import PIPELINE_VERSION, QUEUE, QUEUE_ARGUMENTS, PermanentJobError, TransientJobError, dump_job, load_job, variant_key
from .objects import MissingObject, ObjectStore, StorageError
from .thumbnail import ImageRejected, make_thumbnail
logger = logging.getLogger('messenger')
_HEARTBEAT = Path('/tmp/worker-alive')
_inflight = 0
def _lock_key(attachment_id: uuid.UUID) -> int:
return attachment_id.int & ((1 << 63) - 1)
def _prepare(
objects: ObjectStore,
attachment_id: str,
staging: str,
final: str,
size: int,
digest: str,
content_type: str,
) -> dict:
"""Copy the original unchanged and build the thumbnail. Runs off the event loop."""
try:
data = objects.get(staging)
except MissingObject:
raise TransientJobError() from None
except StorageError:
raise TransientJobError() from None
if len(data) != size or hashlib.sha256(data).hexdigest() != digest:
raise PermanentJobError('processing_failed')
if staging != final:
try:
objects.put(final, data, content_type)
except StorageError:
raise TransientJobError() from None
try:
jpeg, width, height = make_thumbnail(data)
except ImageRejected:
raise PermanentJobError('invalid_image') from None
thumb_key = variant_key(attachment_id, 'thumbnail')
try:
objects.put(thumb_key, jpeg, 'image/jpeg')
except StorageError:
raise TransientJobError() from None
return {
'object_key': thumb_key,
'size_bytes': len(jpeg),
'width': width,
'height': height,
'sha256': hashlib.sha256(jpeg).hexdigest(),
}
async def _mark_failed(conn: asyncpg.Connection, attachment_id: uuid.UUID, code: str) -> None:
now = datetime.now(timezone.utc)
async with conn.transaction():
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = $3
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
code,
now,
)
async def _schedule_retry(
conn: asyncpg.Connection,
broker: Broker,
job: dict,
attachment_id: uuid.UUID,
limit: int,
) -> None:
"""Advance attempt and publish the next message before the caller acks this one."""
nxt = job['attempt'] + 1
now = datetime.now(timezone.utc)
if nxt > limit:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
async with conn.transaction():
moved = await conn.fetchval(
'''
UPDATE attachment_jobs
SET attempt = $2, updated_at = $3
WHERE id = $1 AND attempt = $4
RETURNING attempt
''',
uuid.UUID(job['job_id']),
nxt,
now,
job['attempt'],
)
if moved is None:
return
await conn.execute(
'''
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
now,
)
await broker.publish(dump_job(job['job_id'], job['attachment_id'], nxt, job['created_at']))
async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, thumb: dict) -> None:
now = datetime.now(timezone.utc)
async with conn.transaction():
await conn.execute(
'''
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, 'thumbnail', 'image/jpeg', $3, $4, $5, $6, $7)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
''',
attachment_id,
PIPELINE_VERSION,
thumb['size_bytes'],
thumb['width'],
thumb['height'],
thumb['sha256'],
thumb['object_key'],
)
await conn.execute(
'''
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
now,
)
async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, limit: int, timeout: int) -> None:
attachment_id = uuid.UUID(job['attachment_id'])
async with pool.acquire() as conn:
await conn.execute('SELECT pg_advisory_lock($1)', _lock_key(attachment_id))
try:
row = await conn.fetchrow(
'''
SELECT a.status, a.staging_key, a.object_key, a.size_bytes, a.sha256,
a.content_type, j.attempt, j.max_attempts
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = $1
''',
uuid.UUID(job['job_id']),
)
if row is None or row['status'] in ('ready', 'failed'):
return
if job['attempt'] < row['attempt']:
# The previous attempt crashed after the counter moved and before its ack.
await broker.publish(dump_job(job['job_id'], job['attachment_id'], row['attempt'], job['created_at']))
return
if job['attempt'] > row['max_attempts']:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
now = datetime.now(timezone.utc)
await conn.execute(
'''
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
now,
)
try:
thumb = await asyncio.wait_for(
asyncio.to_thread(
_prepare,
objects,
job['attachment_id'],
row['staging_key'],
row['object_key'],
row['size_bytes'],
row['sha256'],
row['content_type'],
),
timeout=timeout,
)
except PermanentJobError as exc:
await _mark_failed(conn, attachment_id, exc.code)
return
except (TransientJobError, asyncio.TimeoutError):
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
except Exception:
logger.exception('attachment %s attempt %s failed', job['attachment_id'], job['attempt'])
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
await _finish(conn, attachment_id, thumb)
logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt'])
finally:
await conn.execute('SELECT pg_advisory_unlock($1)', _lock_key(attachment_id))
async def _handle(pool, objects, broker, body: bytes, limit: int, timeout: int) -> None:
job = load_job(body)
if job is None:
logger.warning('dropped a job message that does not match the contract')
return
await _process(pool, objects, broker, job, limit, timeout)
async def _beat(stop: asyncio.Event) -> None:
while not stop.is_set():
_HEARTBEAT.write_text('ok', encoding='ascii')
try:
await asyncio.wait_for(stop.wait(), timeout=5)
except asyncio.TimeoutError:
pass
async def _run() -> None:
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
# Library logs can include the AMQP URL. Keep them quiet.
logging.getLogger('aio_pika').setLevel(logging.ERROR)
logging.getLogger('aiormq').setLevel(logging.ERROR)
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, stop.set)
settings = load_settings()
limit = job_max_attempts()
timeout = job_timeout_seconds()
pool = await open_pool(settings.database_url)
objects = ObjectStore(load_object_settings())
broker = Broker(load_broker_url())
beat = asyncio.create_task(_beat(stop))
try:
await broker.connect()
channel = broker.channel
if channel is None:
raise RuntimeError('broker did not become reachable')
await channel.set_qos(prefetch_count=worker_concurrency())
queue = await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
async def on_message(message) -> None:
global _inflight
_inflight += 1
try:
await _handle(pool, objects, broker, message.body, limit, timeout)
except BrokerDown:
await message.nack(requeue=True)
return
except Exception:
logger.exception('job was not finished')
await message.nack(requeue=True)
return
else:
await message.ack()
finally:
_inflight -= 1
consumer = await queue.consume(on_message)
logger.info('worker consuming %s', queue.name)
await stop.wait()
logger.info('worker draining')
await queue.cancel(consumer)
for _ in range(500):
if _inflight == 0:
break
await asyncio.sleep(0.05)
finally:
beat.cancel()
await broker.close()
await pool.close()
def main() -> None:
asyncio.run(_run())
if __name__ == '__main__':
main()