Skeleton contracts / contracts (pull_request) Blocked by required conditions
60 lines
2.3 KiB
Python
60 lines
2.3 KiB
Python
"""Drain committed outbox rows, deleting only after a positive broker confirm."""
|
|
import logging
|
|
import os
|
|
|
|
from .broker import channel, send
|
|
from .database import get_connection
|
|
from .faults import take
|
|
from .jobs import carrier, event
|
|
from .process import serve
|
|
from .telemetry import SpanKind, log, propagator, span
|
|
|
|
|
|
def publish_one(ch):
|
|
with get_connection() as conn:
|
|
job = conn.execute("""
|
|
SELECT j.* FROM job_outbox o JOIN image_jobs j ON j.id=o.job_id
|
|
WHERE o.publish_after <= clock_timestamp()
|
|
ORDER BY o.publish_after LIMIT 1 FOR UPDATE OF o SKIP LOCKED
|
|
""").fetchone()
|
|
if job is None:
|
|
return False
|
|
if job['state'] != 'queued':
|
|
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
|
|
return True
|
|
args = (job['attachment_id'], job['pipeline_version'])
|
|
crash_before = take(conn, *args, 'before_publish') == 'crash'
|
|
if not crash_before:
|
|
parent = propagator.extract(job['trace_context'] or {})
|
|
labels = {'messaging.system': 'rabbitmq', 'messaging.destination.name': 'attachment.process.v1',
|
|
'job.attempt': job['attempt']}
|
|
with span('attachment.process.v1 publish', context=parent,
|
|
kind=SpanKind.PRODUCER, attributes=labels):
|
|
headers = {}
|
|
propagator.inject(headers)
|
|
send(ch, carrier(job), headers)
|
|
log('broker_confirmed', attempt=job['attempt'])
|
|
crash_after = take(conn, *args, 'after_confirm') == 'crash'
|
|
if not crash_after:
|
|
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
|
|
event(conn, job, 'broker_confirmed')
|
|
if crash_before or crash_after:
|
|
point = 'before_publish' if crash_before else 'after_confirm'
|
|
log('pipeline_fault', logging.WARNING, point=point, action='crash', job_id=str(job['id']))
|
|
os._exit(86)
|
|
return True
|
|
|
|
|
|
def loop(stopping, progress):
|
|
with channel() as (connection, ch):
|
|
ch.confirm_delivery()
|
|
while not stopping.is_set():
|
|
if not publish_one(ch):
|
|
connection.process_data_events(time_limit=0.2)
|
|
stopping.wait(0.1)
|
|
progress()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
serve(loop, 'publisher')
|