forked from mtusi2026/mtusi2026lab5
ЛР 5 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""Outbox relay and lease recovery. A lost publish response causes a safe duplicate."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from .storage import db
|
||||
from .jobs import broker, STREAM, MAX_ATTEMPTS, lock_id, payload, audit, trip, finish_failed
|
||||
|
||||
|
||||
def recover():
|
||||
with db() as conn:
|
||||
rows = conn.execute("SELECT * FROM jobs WHERE status='processing' AND lease_until<clock_timestamp() ORDER BY lease_until LIMIT 100").fetchall()
|
||||
for row in rows:
|
||||
with db() as conn:
|
||||
if not conn.execute('SELECT pg_try_advisory_xact_lock(%s) AS ok',(lock_id(row['attachment_id']),)).fetchone()['ok']:
|
||||
continue
|
||||
job = conn.execute("SELECT * FROM jobs WHERE id=%s AND status='processing' AND lease_until<clock_timestamp() FOR UPDATE",(row['id'],)).fetchone()
|
||||
if not job:
|
||||
continue
|
||||
if job['attempts'] >= MAX_ATTEMPTS:
|
||||
finish_failed(conn,job,'retry_exhausted')
|
||||
else:
|
||||
conn.execute("UPDATE jobs SET status='queued',lease_until=NULL,next_attempt_at=clock_timestamp() WHERE id=%s",(job['id'],))
|
||||
conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",(job['attachment_id'],job['pipeline_version']))
|
||||
conn.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(job['id'],))
|
||||
audit(conn,job['id'],'lease_recovered')
|
||||
|
||||
|
||||
def publish_once():
|
||||
with db() as conn:
|
||||
row = conn.execute("""SELECT j.* FROM jobs j JOIN outbox o ON o.job_id=j.id
|
||||
WHERE j.status='queued' AND j.next_attempt_at<=clock_timestamp()
|
||||
AND (o.published_at IS NULL OR o.published_at<clock_timestamp()-interval '15 seconds')
|
||||
ORDER BY j.next_attempt_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED""").fetchone()
|
||||
if not row:
|
||||
return False
|
||||
crash = trip(conn,row['id'],'before_publish')
|
||||
if crash:
|
||||
os._exit(91) # accepted DB intent exists, no publish
|
||||
with db() as conn:
|
||||
# Separate relay processes may race: notifications may duplicate, effects cannot.
|
||||
broker().xadd(STREAM,{'job':json.dumps(payload(row),separators=(',',':'))})
|
||||
if trip(conn,row['id'],'after_publish'):
|
||||
conn.commit()
|
||||
os._exit(92) # Redis has the job, outbox does not yet record confirmation
|
||||
conn.execute('UPDATE outbox SET published_at=clock_timestamp(),publish_count=publish_count+1 WHERE job_id=%s',(row['id'],))
|
||||
audit(conn,row['id'],'published',str(row['attempts']+1))
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
while True:
|
||||
try:
|
||||
recover()
|
||||
for _ in range(100):
|
||||
if not publish_once():
|
||||
break
|
||||
except Exception as exc:
|
||||
logging.warning('Relay unavailable: %s',type(exc).__name__)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user