forked from mtusi2026/mtusi2026lab5
166 lines
6.0 KiB
Python
166 lines
6.0 KiB
Python
"""Publish job rows that Postgres has committed and the broker has not confirmed yet.
|
|
|
|
published_at moves only after the confirm. A crash in between leaves the same row,
|
|
and the next pass of this relay sends it. The body is ids and timestamps only.
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import asyncpg
|
|
|
|
from .broker import Broker, BrokerDown
|
|
from .fault import fault_armed
|
|
from .jobs import QUEUE, dump_job, format_timestamp, lock_key
|
|
|
|
logger = logging.getLogger('messenger')
|
|
|
|
_PAUSE = 'pause-outbox'
|
|
|
|
|
|
def _body(row) -> bytes:
|
|
return dump_job(
|
|
str(row['id']),
|
|
str(row['attachment_id']),
|
|
int(row['attempt']),
|
|
format_timestamp(row['created_at']),
|
|
)
|
|
|
|
|
|
async def publish_job(pool: asyncpg.Pool, broker: Broker, job_id: str) -> None:
|
|
"""Confirm one committed job. BrokerDown leaves published_at null for the relay."""
|
|
async with pool.acquire() as conn:
|
|
async with conn.transaction():
|
|
if await fault_armed(conn, _PAUSE):
|
|
return
|
|
row = await conn.fetchrow(
|
|
'''
|
|
SELECT j.id, j.attachment_id, j.attempt, j.created_at
|
|
FROM attachment_jobs j
|
|
JOIN attachments a ON a.id = j.attachment_id
|
|
WHERE j.id = $1 AND j.published_at IS NULL AND a.status = 'queued'
|
|
FOR UPDATE OF j
|
|
''',
|
|
uuid.UUID(job_id),
|
|
)
|
|
if row is None:
|
|
return
|
|
await broker.publish(_body(row), QUEUE)
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachment_jobs
|
|
SET published_at = clock_timestamp(), updated_at = clock_timestamp()
|
|
WHERE id = $1
|
|
''',
|
|
row['id'],
|
|
)
|
|
|
|
|
|
async def publish_pending(pool: asyncpg.Pool, broker: Broker, batch: int = 8) -> int:
|
|
"""Send due, unpublished queued jobs. Skip-locked so replicas do not double-send."""
|
|
sent = 0
|
|
for _ in range(batch):
|
|
try:
|
|
async with pool.acquire() as conn:
|
|
async with conn.transaction():
|
|
if await fault_armed(conn, _PAUSE):
|
|
return sent
|
|
row = await conn.fetchrow(
|
|
'''
|
|
SELECT j.id, j.attachment_id, j.attempt, j.created_at
|
|
FROM attachment_jobs j
|
|
JOIN attachments a ON a.id = j.attachment_id
|
|
WHERE j.published_at IS NULL
|
|
AND a.status = 'queued'
|
|
AND (j.available_at IS NULL OR j.available_at <= clock_timestamp())
|
|
ORDER BY j.created_at
|
|
FOR UPDATE OF j SKIP LOCKED
|
|
LIMIT 1
|
|
'''
|
|
)
|
|
if row is None:
|
|
return sent
|
|
await broker.publish(_body(row), QUEUE)
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachment_jobs
|
|
SET published_at = clock_timestamp(), updated_at = clock_timestamp()
|
|
WHERE id = $1
|
|
''',
|
|
row['id'],
|
|
)
|
|
except BrokerDown:
|
|
return sent
|
|
sent += 1
|
|
logger.info('outbox published job %s', row['id'])
|
|
return sent
|
|
|
|
|
|
async def reclaim_expired(pool: asyncpg.Pool) -> int:
|
|
"""Return processing rows whose lease expired and whose worker no longer holds the lock.
|
|
|
|
The attempt number stays. The next entry increments runs, which caps a crash loop.
|
|
A worker that is still inside the advisory lock is left alone.
|
|
"""
|
|
reclaimed = 0
|
|
async with pool.acquire() as conn:
|
|
async with conn.transaction():
|
|
rows = await conn.fetch(
|
|
'''
|
|
SELECT j.id, j.attachment_id
|
|
FROM attachment_jobs j
|
|
JOIN attachments a ON a.id = j.attachment_id
|
|
WHERE a.status = 'processing'
|
|
AND j.lease_until IS NOT NULL
|
|
AND j.lease_until < clock_timestamp()
|
|
ORDER BY j.lease_until
|
|
FOR UPDATE OF j SKIP LOCKED
|
|
LIMIT 8
|
|
'''
|
|
)
|
|
for row in rows:
|
|
key = lock_key(row['attachment_id'])
|
|
if not await conn.fetchval('SELECT pg_try_advisory_lock($1)', key):
|
|
continue
|
|
try:
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachments
|
|
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
|
WHERE id = $1 AND status = 'processing'
|
|
''',
|
|
row['attachment_id'],
|
|
)
|
|
await conn.execute(
|
|
'''
|
|
UPDATE attachment_jobs
|
|
SET published_at = NULL, lease_until = NULL, available_at = NULL,
|
|
updated_at = clock_timestamp()
|
|
WHERE id = $1
|
|
''',
|
|
row['id'],
|
|
)
|
|
reclaimed += 1
|
|
finally:
|
|
await conn.execute('SELECT pg_advisory_unlock($1)', key)
|
|
if reclaimed:
|
|
logger.info('reclaimed %s expired processing lease(s)', reclaimed)
|
|
return reclaimed
|
|
|
|
|
|
async def relay_forever(pool: asyncpg.Pool, broker: Broker, stop: asyncio.Event) -> None:
|
|
while not stop.is_set():
|
|
try:
|
|
await publish_pending(pool, broker)
|
|
except Exception:
|
|
logger.exception('outbox relay failed')
|
|
try:
|
|
await asyncio.wait_for(stop.wait(), timeout=1)
|
|
except asyncio.TimeoutError:
|
|
pass
|
|
|
|
|
|
def due_at(delay_seconds: float) -> datetime:
|
|
return datetime.now(timezone.utc) + timedelta(seconds=delay_seconds)
|