forked from mtusi2026/mtusi2026lab7
165 lines
6.7 KiB
Python
165 lines
6.7 KiB
Python
"""PostgreSQL owns execution state and the publication pointer."""
|
|
import os
|
|
import random
|
|
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from .database import get_connection
|
|
from .telemetry import propagator, span
|
|
|
|
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
|
LEASE_SECONDS = int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))
|
|
|
|
|
|
def enqueue(conn, attachment_id, version, *, accepted=False):
|
|
context = {}
|
|
propagator.inject(context)
|
|
job = conn.execute("""
|
|
INSERT INTO image_jobs(attachment_id,pipeline_version,trace_context,accepted_at)
|
|
VALUES (%s,%s,%s,CASE WHEN %s THEN clock_timestamp() END) RETURNING *
|
|
""", (attachment_id, version, Jsonb(context), accepted)).fetchone()
|
|
with span('outbox.enqueue'):
|
|
schedule(conn, job['id'])
|
|
return job
|
|
|
|
|
|
def schedule(conn, job_id, delay=0):
|
|
conn.execute('''
|
|
INSERT INTO job_outbox(job_id,publish_after)
|
|
VALUES (%s, clock_timestamp() + %s * interval '1 second')
|
|
ON CONFLICT (job_id) DO UPDATE SET publish_after=excluded.publish_after
|
|
''', (job_id, delay))
|
|
|
|
|
|
def event(conn, job, name, detail=None):
|
|
conn.execute('INSERT INTO job_events(job_id,attempt,event,detail) VALUES (%s,%s,%s,%s)',
|
|
(job['id'], job['attempt'], name, detail))
|
|
|
|
|
|
def carrier(job):
|
|
return dict(schema_version=1, type='attachment.process.v1', job_id=str(job['id']),
|
|
attachment_id=str(job['attachment_id']), pipeline_version=job['pipeline_version'],
|
|
attempt=job['attempt'], created_at=job['created_at'].isoformat().replace('+00:00', 'Z'))
|
|
|
|
|
|
def claim(message):
|
|
with get_connection() as conn:
|
|
job = conn.execute('SELECT * FROM image_jobs WHERE id=%s FOR NO KEY UPDATE',
|
|
(message['job_id'],)).fetchone()
|
|
if (job is None or job['attachment_id'] != message['attachment_id']
|
|
or job['pipeline_version'] != message['pipeline_version']
|
|
or job['attempt'] != message['attempt']):
|
|
return None
|
|
if job['state'] != 'queued':
|
|
event(conn, job, 'delivery_ignored', job['state'])
|
|
return None
|
|
attachment = lock_attachment(conn, job)
|
|
if attachment['desired_version'] != job['pipeline_version']:
|
|
supersede(conn, job)
|
|
return None
|
|
job = conn.execute('''
|
|
UPDATE image_jobs SET state='processing', fence=fence+1,
|
|
lease_until=clock_timestamp() + %s * interval '1 second'
|
|
WHERE id=%s RETURNING *
|
|
''', (LEASE_SECONDS, job['id'])).fetchone()
|
|
update_attachment(conn, job, 'processing')
|
|
event(conn, job, 'claimed', str(job['fence']))
|
|
return job, attachment
|
|
|
|
|
|
def lock_attachment(conn, job):
|
|
return conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE',
|
|
(job['attachment_id'],)).fetchone()
|
|
|
|
|
|
def update_attachment(conn, job, state, error=None):
|
|
# While building a new version, continue serving the previously published version.
|
|
conn.execute('''
|
|
UPDATE attachments SET status=%s, error_code=%s, updated_at=clock_timestamp()
|
|
WHERE id=%s AND desired_version=%s AND active_version IS NULL
|
|
''', (state, error, job['attachment_id'], job['pipeline_version']))
|
|
|
|
|
|
def supersede(conn, job):
|
|
conn.execute("UPDATE image_jobs SET state='superseded', lease_until=NULL WHERE id=%s", (job['id'],))
|
|
event(conn, job, 'superseded')
|
|
|
|
|
|
def owned(conn, job):
|
|
current = conn.execute('''
|
|
SELECT *, lease_until > clock_timestamp() AS live FROM image_jobs WHERE id=%s FOR NO KEY UPDATE
|
|
''', (job['id'],)).fetchone()
|
|
return current['state'] == 'processing' and current['fence'] == job['fence'] and current['live']
|
|
|
|
|
|
def finish(job, manifest):
|
|
with get_connection() as conn:
|
|
if not owned(conn, job):
|
|
event(conn, job, 'fence_rejected', str(job['fence']))
|
|
return 'ignored', None
|
|
attachment = lock_attachment(conn, job)
|
|
if not owned(conn, job):
|
|
event(conn, job, 'fence_rejected', str(job['fence']))
|
|
return 'ignored', None
|
|
if attachment['desired_version'] != job['pipeline_version']:
|
|
supersede(conn, job)
|
|
return 'ignored', None
|
|
ready = conn.execute("""
|
|
UPDATE image_jobs SET first_ready_at=clock_timestamp(), state='ready', manifest=%s, lease_until=NULL,error_code=NULL WHERE id=%s RETURNING first_ready_at
|
|
""", (Jsonb(manifest), job['id'])).fetchone()
|
|
conn.execute("""
|
|
UPDATE attachments SET status='ready', active_version=%s, error_code=NULL,
|
|
object_key=%s, updated_at=clock_timestamp() WHERE id=%s
|
|
""", (job['pipeline_version'], manifest['original']['key'], attachment['id']))
|
|
event(conn, job, 'published')
|
|
latency = ((ready['first_ready_at'] - job['accepted_at']).total_seconds()
|
|
if job['accepted_at'] else None)
|
|
return 'ready', latency
|
|
|
|
|
|
def fail_locked(conn, job, reason, permanent=False):
|
|
attachment = lock_attachment(conn, job)
|
|
if attachment['desired_version'] != job['pipeline_version']:
|
|
supersede(conn, job)
|
|
return 'ignored'
|
|
failures = job['failures'] + 1
|
|
if permanent or failures >= MAX_ATTEMPTS:
|
|
code = reason if permanent else 'retry_exhausted'
|
|
conn.execute("""
|
|
UPDATE image_jobs SET state='failed', error_code=%s, lease_until=NULL, failures=%s WHERE id=%s
|
|
""", (code, failures, job['id']))
|
|
conn.execute('INSERT INTO job_dead_letters(job_id,attempt,error_code) VALUES (%s,%s,%s)',
|
|
(job['id'], job['attempt'], code))
|
|
update_attachment(conn, job, 'failed', code)
|
|
event(conn, job, 'dead_letter', reason)
|
|
return 'failed'
|
|
delay = min(30, 2 ** (failures - 1)) * random.uniform(0.75, 1.25)
|
|
conn.execute("""
|
|
UPDATE image_jobs SET state='queued', attempt=attempt+1, failures=%s,
|
|
lease_until=NULL,error_code=%s WHERE id=%s
|
|
""", (failures, reason, job['id']))
|
|
schedule(conn, job['id'], delay)
|
|
update_attachment(conn, job, 'queued')
|
|
event(conn, job, 'retry_scheduled', reason)
|
|
return 'retry'
|
|
|
|
|
|
def fail(job, reason, permanent=False):
|
|
with get_connection() as conn:
|
|
if owned(conn, job):
|
|
return fail_locked(conn, job, reason, permanent)
|
|
else:
|
|
event(conn, job, 'fence_rejected', str(job['fence']))
|
|
return 'ignored'
|
|
|
|
|
|
def recover_one():
|
|
with get_connection() as conn:
|
|
job = conn.execute("""
|
|
SELECT * FROM image_jobs WHERE state='processing' AND lease_until <= clock_timestamp()
|
|
ORDER BY lease_until LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED
|
|
""").fetchone()
|
|
if job:
|
|
fail_locked(conn, job, 'lease_expired')
|
|
return job is not None
|