Files
mtusi2026lab5/src/worker.py
T

149 lines
7.1 KiB
Python

import json
import logging
import os
import signal
import subprocess
import sys
import time
from datetime import datetime, timezone
from uuid import UUID
import psycopg
from psycopg.rows import dict_row
from .broker import QUEUE, connect, envelope, publish
from .config import secret
from .storage import serialize
def pause(connection, seconds):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
connection.process_data_events(time_limit=min(0.2, deadline - time.monotonic()))
def handle(connection, channel, tag, message):
try:
data = json.loads(message)
if not isinstance(data, dict) or set(data) - {'schema_version','job_id','type','attachment_id',
'pipeline_version','attempt','created_at','traceparent','tracestate'}:
raise ValueError()
job_id, attachment_id = UUID(data['job_id']), UUID(data['attachment_id'])
if type(data['schema_version']) is not int or type(data['pipeline_version']) is not int:
raise ValueError()
if data['schema_version'] != 1 or data['pipeline_version'] != 1 or data['type'] != QUEUE:
raise ValueError()
if type(data['attempt']) is not int or data['attempt'] < 1:
raise ValueError()
if not isinstance(data['created_at'], str) or datetime.fromisoformat(data['created_at'].replace('Z', '+00:00')).tzinfo is None:
raise ValueError()
except (ValueError, KeyError, TypeError):
channel.basic_reject(tag, requeue=False)
logging.warning('invalid job rejected')
return
with psycopg.connect(secret('DATABASE_URL_FILE'), autocommit=True, row_factory=dict_row,
connect_timeout=3, options='-c statement_timeout=5000') as db:
lock = int.from_bytes(job_id.bytes[:8], 'big', signed=True)
if not db.execute('SELECT pg_try_advisory_lock(%s) AS locked', (lock,)).fetchone()['locked']:
pause(connection, 1)
channel.basic_nack(tag, requeue=True)
return
row = db.execute('SELECT j.*,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status '
'FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id '
'WHERE j.id=%s AND j.attachment_id=%s', (job_id, attachment_id)).fetchone()
if not row or row['status'] in ('ready', 'failed'):
channel.basic_ack(tag)
return
maximum = int(os.environ.get('JOB_MAX_ATTEMPTS', '5'))
if row['attempt'] >= maximum:
db.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',"
'updated_at=clock_timestamp() WHERE id=%s', (attachment_id,))
channel.basic_ack(tag)
return
expected = row['attempt'] + 1
if data['attempt'] < expected:
publish(envelope(row, expected))
channel.basic_ack(tag)
return
if data['attempt'] > expected:
channel.basic_reject(tag, requeue=False)
return
delay = (row['next_attempt_at'] - datetime.now(timezone.utc)).total_seconds()
if delay > 0:
pause(connection, min(delay, 5))
with db.transaction():
db.execute("UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() "
'WHERE id=%s', (attachment_id,))
db.execute('UPDATE attachment_jobs SET attempt=%s WHERE id=%s', (expected, job_id))
process = subprocess.Popen([sys.executable, '-m', 'src.process_image'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
started = time.monotonic()
try:
process.stdin.write(json.dumps(serialize(row)))
process.stdin.close()
while process.poll() is None:
if time.monotonic() - started > int(os.environ.get('JOB_TIMEOUT_SECONDS', '60')):
process.kill()
process.wait()
break
connection.process_data_events(time_limit=0.2)
result = json.loads(process.stdout.read()) if process.returncode == 0 else None
finally:
if process.poll() is None:
process.kill()
process.wait()
process.stdout.close()
if result:
with db.transaction():
db.execute('INSERT INTO attachment_variants '
'(attachment_id,name,content_type,width,height,size_bytes,sha256,object_key) '
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (attachment_id,pipeline_version,name) '
'DO UPDATE SET content_type=EXCLUDED.content_type,width=EXCLUDED.width,height=EXCLUDED.height,'
'size_bytes=EXCLUDED.size_bytes,sha256=EXCLUDED.sha256,object_key=EXCLUDED.object_key',
(attachment_id, *[result[k] for k in ('name','content_type','width','height','size_bytes','sha256','object_key')]))
db.execute("UPDATE attachments SET status='ready',error_code=NULL,updated_at=clock_timestamp() "
'WHERE id=%s', (attachment_id,))
print(json.dumps({'job_id': str(job_id), 'attempt': expected, 'status': 'ready'}), flush=True)
channel.basic_ack(tag)
elif process.returncode == 43 or expected >= maximum:
code = 'invalid_image' if process.returncode == 43 else 'retry_exhausted'
db.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() "
'WHERE id=%s', (code, attachment_id))
print(json.dumps({'job_id': str(job_id), 'attempt': expected, 'status': 'failed', 'error_code': code}), flush=True)
channel.basic_ack(tag)
else:
with db.transaction():
db.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() "
'WHERE id=%s', (attachment_id,))
db.execute("UPDATE attachment_jobs SET next_attempt_at=clock_timestamp()+INTERVAL '5 seconds' "
'WHERE id=%s', (job_id,))
publish(envelope(row, expected + 1))
channel.basic_ack(tag)
def main():
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
while True:
connection = None
try:
connection = connect()
channel = connection.channel()
channel.queue_declare(queue=QUEUE, durable=True)
channel.basic_qos(prefetch_count=1)
for method, properties, message in channel.consume(QUEUE, inactivity_timeout=1, auto_ack=False):
if method:
handle(connection, channel, method.delivery_tag, message)
except Exception as error:
logging.warning('worker reconnect: %s', type(error).__name__)
finally:
if connection and connection.is_open:
try:
connection.close()
except Exception:
pass
time.sleep(2)
if __name__ == '__main__':
main()