Files
mtusi2026lab7/pipeline.py
T
amin 2fae615742
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Выполнение лабораторной работы номер 7
2026-12-04 18:15:18 +03:00

100 lines
5.2 KiB
Python

"""Durable Redis Streams + transactional PostgreSQL outbox."""
import json
import os
import random
import time
import uuid
import redis
import db
import telemetry as ot
from opentelemetry.trace import SpanKind
from opentelemetry import propagate
STREAM = 'attachment:jobs'
GROUP = 'workers'
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5'))
BROKER = redis.Redis.from_url(os.environ['BROKER_URL'],decode_responses=True,socket_timeout=3,socket_connect_timeout=2,
ssl_ca_certs='/ca/ca.crt',ssl_certfile='/identity/tls.crt',ssl_keyfile='/identity/tls.key',ssl_check_hostname=True)
def ensure_group():
try:
BROKER.xgroup_create(STREAM,GROUP,id='0',mkstream=True)
except redis.ResponseError as exc:
if 'BUSYGROUP' not in str(exc):
raise
def dispatch_once():
with db.pool.connection() as conn:
q=conn.execute("SELECT count(*) AS depth,coalesce(extract(epoch FROM now()-min(j.created_at)),0) AS age FROM attachment_jobs j JOIN attachments a ON j.id=a.id WHERE a.status IN ('queued','processing')").fetchone()
ot.state['queue_depth']=q['depth']
ot.state['oldest_seconds']=float(q['age'])
expired = conn.execute("""SELECT j.id,j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.id
WHERE a.status='processing' AND j.lease_until<now() FOR UPDATE OF j,a SKIP LOCKED""").fetchall()
for row in expired:
if row['attempt'] >= MAX_ATTEMPTS:
conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s",(row['id'],))
else:
conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",(row['id'],))
conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now() WHERE id=%s",(row['id'],))
jobs = conn.execute("""SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.id
WHERE a.status='queued' AND j.available_at<=now() AND (j.published_at IS NULL OR j.published_at<now()-interval '60 seconds')
ORDER BY j.available_at LIMIT 20 FOR UPDATE OF j SKIP LOCKED""").fetchall()
for job in jobs:
envelope = {'schema_version':1,'job_id':str(job['id']),'type':'attachment.process.v1',
'attachment_id':str(job['id']),'pipeline_version':1,'attempt':job['attempt']+1,
'created_at':job['created_at'].isoformat(),**job['trace_context']}
with ot.tracer.start_as_current_span('queue publish',context=propagate.extract(job['trace_context']),kind=SpanKind.PRODUCER):
envelope.update(ot.carrier())
BROKER.xadd(STREAM,{'job':json.dumps(envelope)})
ot.logger.info('job_published')
conn.execute('UPDATE attachment_jobs SET published_at=now() WHERE id=%s',(job['id'],))
def claim(job_id):
with db.pool.connection() as conn:
row = conn.execute("""SELECT a.status,j.attempt,j.available_at<=now() AS due FROM attachment_jobs j
JOIN attachments a ON a.id=j.id WHERE j.id=%s FOR UPDATE OF j,a""",(job_id,)).fetchone()
if not row or row['status'] != 'queued' or not row['due']:
return False
conn.execute("UPDATE attachment_jobs SET attempt=attempt+1,lease_until=now()+interval '120 seconds' WHERE id=%s",(job_id,))
conn.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",(job_id,))
return True
def fail(job_id, permanent=False):
with db.pool.connection() as conn:
row = conn.execute('SELECT attempt FROM attachment_jobs WHERE id=%s FOR UPDATE',(job_id,)).fetchone()
if permanent or row['attempt']>=MAX_ATTEMPTS:
conn.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s AND status='processing'",
('invalid_image' if permanent else 'retry_exhausted',job_id))
else:
delay = min(60,2**row['attempt'])+random.random()
conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s AND status='processing'",(job_id,))
conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now()+%s*interval '1 second' WHERE id=%s",(delay,job_id))
def replay(job_id):
with db.pool.connection() as conn:
changed=conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s AND status='failed' AND NOT staging_cleaned RETURNING id",(job_id,)).fetchone()
if not changed:
raise SystemExit('Only failed jobs may be replayed')
conn.execute("UPDATE attachment_jobs SET attempt=0,published_at=NULL,lease_until=NULL,available_at=now(),replay_count=replay_count+1 WHERE id=%s",(job_id,))
conn.execute("INSERT INTO attachment_replays(job_id) VALUES (%s)",(job_id,))
if __name__ == '__main__':
import sys
db.pool.open(wait=True,timeout=30)
if len(sys.argv)==3 and sys.argv[1]=='replay':
replay(str(uuid.UUID(sys.argv[2])))
else:
while True:
try:
ensure_group()
dispatch_once()
except Exception:
print('dispatcher will retry',flush=True)
time.sleep(1)