This commit is contained in:
2026-11-22 17:59:11 +03:00
parent 7e1780be67
commit 813fc03da5
18 changed files with 1859 additions and 265 deletions
+38 -20
View File
@@ -1,10 +1,11 @@
"""Durable RabbitMQ queue. Publish waits for a broker confirm; the worker acks later."""
"""Durable RabbitMQ queues. Publish waits for a broker confirm; the worker acks later."""
import asyncio
import logging
import aio_pika
from aio_pika import DeliveryMode, Message
from .jobs import QUEUE, QUEUE_ARGUMENTS
from .jobs import DLQ, DLQ_ARGUMENTS, QUEUE, QUEUE_ARGUMENTS
logger = logging.getLogger('messenger')
@@ -18,13 +19,19 @@ class Broker:
self._url = url
self._connection: aio_pika.abc.AbstractRobustConnection | None = None
self.channel: aio_pika.abc.AbstractChannel | None = None
self._publish_lock = asyncio.Lock()
async def _declare(self, channel: aio_pika.abc.AbstractChannel) -> aio_pika.abc.AbstractQueue:
await channel.declare_queue(DLQ, durable=True, arguments=DLQ_ARGUMENTS)
return await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
async def connect(self) -> None:
try:
self._connection = await aio_pika.connect_robust(self._url, timeout=10)
# Confirms make publish wait until the broker has the message, not only the socket.
# Consume uses a second channel so acks and confirms do not share one multiplexer.
self.channel = await self._connection.channel(publisher_confirms=True, on_return_raises=True)
await self.channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
await self._declare(self.channel)
except Exception:
raise RuntimeError('broker did not become reachable') from None
@@ -37,22 +44,33 @@ class Broker:
if connection is None or connection.is_closed or connection.reconnecting:
raise BrokerDown()
async def publish(self, body: bytes) -> None:
"""Persistent message. Returns after the broker confirms it, or raises BrokerDown."""
if self.channel is None:
async def open_consumer(self, prefetch: int):
"""A channel that only consumes. prefetch caps how many jobs sit unacked."""
if self._connection is None:
raise BrokerDown()
message = Message(
body,
content_type='application/json',
delivery_mode=DeliveryMode.PERSISTENT,
)
try:
await self.channel.default_exchange.publish(
message,
routing_key=QUEUE,
mandatory=True,
timeout=10,
channel = await self._connection.channel()
await channel.set_qos(prefetch_count=prefetch)
queue = await self._declare(channel)
return channel, queue
async def publish(self, body: bytes, queue: str = QUEUE, headers: dict | None = None) -> None:
"""Persistent message. Returns after the broker confirms it, or raises BrokerDown."""
async with self._publish_lock:
if self.channel is None:
raise BrokerDown()
message = Message(
body,
content_type='application/json',
delivery_mode=DeliveryMode.PERSISTENT,
headers=headers,
)
except Exception as exc:
logger.warning('broker did not confirm a job (%s)', type(exc).__name__)
raise BrokerDown() from None
try:
await self.channel.default_exchange.publish(
message,
routing_key=queue,
mandatory=True,
timeout=10,
)
except Exception as exc:
logger.warning('broker did not confirm a job (%s)', type(exc).__name__)
raise BrokerDown() from None
+32
View File
@@ -102,6 +102,38 @@ def worker_concurrency() -> int:
return _bounded_int('WORKER_CONCURRENCY', 1, 8)
def _bounded_float(name: str, default: float, upper: float) -> float:
raw = os.getenv(name, '').strip()
try:
value = float(raw) if raw else default
except ValueError:
raise RuntimeError('%s must be a number' % name) from None
if value <= 0 or value > upper:
raise RuntimeError('%s must be greater than 0 and at most %s' % (name, upper))
return value
def retry_base_seconds() -> float:
return _bounded_float('JOB_RETRY_BASE_SECONDS', 0.5, 60)
def retry_cap_seconds() -> float:
return _bounded_float('JOB_RETRY_CAP_SECONDS', 30, 600)
def job_lease_seconds() -> int:
return _bounded_int('JOB_LEASE_SECONDS', 90, 3600)
def effective_lease_seconds() -> int:
"""A live attempt refreshes this. It stays longer than the processing timeout."""
return max(job_lease_seconds(), job_timeout_seconds() + 30)
def staging_retention_seconds() -> int:
return _bounded_int('STAGING_RETENTION_SECONDS', 86400, 86400 * 30)
def load_object_settings() -> ObjectSettings:
"""S3 credentials come from files. The values are not logged."""
endpoint = os.getenv('S3_ENDPOINT', '').strip()
+117
View File
@@ -0,0 +1,117 @@
"""Operator faults stored in Postgres so every replica sees the same switch.
Armed only from `python -m app.fault`. An empty table changes nothing.
"""
import asyncio
import logging
import sys
import asyncpg
ONE_SHOT = frozenset({
'commit-before-publish',
'exit-after-put',
'transient-once',
'permanent-once',
})
HELD = frozenset({'pause-outbox'})
NAMES = ONE_SHOT | HELD
_PAUSE = 'pause-outbox'
async def fault_armed(conn: asyncpg.Connection, name: str = _PAUSE) -> bool:
found = await conn.fetchval('SELECT 1 FROM lab_faults WHERE name = $1', name)
return found is not None
async def consume_fault(pool: asyncpg.Pool, name: str) -> bool:
"""Delete a one-shot fault. True only for the caller that won the row."""
if name not in ONE_SHOT:
raise ValueError(name)
async with pool.acquire() as conn:
row = await conn.fetchrow(
'DELETE FROM lab_faults WHERE name = $1 RETURNING name',
name,
)
return row is not None
async def _arm(pool: asyncpg.Pool, name: str) -> None:
async with pool.acquire() as conn:
await conn.execute(
'''
INSERT INTO lab_faults (name, armed_at)
VALUES ($1, clock_timestamp())
ON CONFLICT (name) DO UPDATE SET armed_at = EXCLUDED.armed_at
''',
name,
)
async def _clear(pool: asyncpg.Pool, name: str | None) -> None:
async with pool.acquire() as conn:
if name is None:
await conn.execute('DELETE FROM lab_faults')
else:
await conn.execute('DELETE FROM lab_faults WHERE name = $1', name)
async def _status(pool: asyncpg.Pool) -> list[str]:
async with pool.acquire() as conn:
rows = await conn.fetch('SELECT name FROM lab_faults ORDER BY name')
return [row['name'] for row in rows]
def _usage() -> None:
print('usage: python -m app.fault arm NAME | clear [NAME] | status', file=sys.stderr)
async def _main(argv: list[str]) -> int:
from .config import load_settings
from .db import open_pool
if not argv or argv[0] not in ('arm', 'clear', 'status'):
_usage()
return 2
name = argv[1] if len(argv) > 1 else None
if argv[0] == 'arm' and (name not in NAMES or len(argv) != 2):
_usage()
return 2
if argv[0] == 'clear' and len(argv) > 2:
_usage()
return 2
if argv[0] == 'clear' and name is not None and name not in NAMES:
_usage()
return 2
if argv[0] == 'status' and len(argv) != 1:
_usage()
return 2
pool = await open_pool(load_settings().database_url)
try:
if argv[0] == 'arm':
await _arm(pool, name)
print('armed %s' % name)
elif argv[0] == 'clear':
await _clear(pool, name)
print('cleared %s' % (name or 'all'))
else:
names = await _status(pool)
print('\n'.join(names) if names else 'none')
finally:
await pool.close()
return 0
def main() -> None:
logging.basicConfig(level=logging.WARNING, format='%(levelname)s %(message)s')
try:
code = asyncio.run(_main(sys.argv[1:]))
except Exception as exc:
print('fault command failed (%s)' % type(exc).__name__, file=sys.stderr)
raise SystemExit(1) from None
raise SystemExit(code)
if __name__ == '__main__':
main()
+35
View File
@@ -1,13 +1,19 @@
"""Job payload for the broker. Bytes and credentials never go into the message."""
import json
import random
import re
import uuid
from datetime import datetime, timezone
from typing import Optional
JOB_TYPE = 'attachment.process.v1'
PIPELINE_VERSION = 1
QUEUE = 'attachment.jobs'
DLQ = 'attachment.jobs.dlq'
# Same arguments on every declare, otherwise RabbitMQ rejects the second one.
QUEUE_ARGUMENTS = {'x-queue-type': 'classic'}
DLQ_ARGUMENTS = {'x-queue-type': 'classic'}
REQUIRED_VARIANTS = ('thumbnail', 'crop', 'optimized')
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
@@ -36,6 +42,35 @@ def variant_key(attachment_id: str, name: str) -> str:
return 'variants/' + attachment_id + '/' + name
def lock_key(attachment_id: uuid.UUID) -> int:
"""Stable bigint for a session advisory lock. One attachment, one runner."""
return attachment_id.int & ((1 << 63) - 1)
def format_timestamp(moment: datetime) -> str:
if moment.tzinfo is None:
moment = moment.replace(tzinfo=timezone.utc)
text = moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
if not text.endswith('Z') or len(text) > 40:
raise ValueError('timestamp does not fit the job contract')
return text
def backoff_seconds(attempt: int, base: float, cap: float, rng: Optional[random.Random] = None) -> float:
"""Full jitter. The ceiling is min(cap, base * 2^(attempt-1)); the draw is uniform below it."""
step = attempt - 1
if step < 0:
step = 0
if step > 20:
step = 20
ceiling = min(cap, base * float(2 ** step))
if ceiling <= 0:
return 0.0
if rng is None:
return random.uniform(0, ceiling)
return rng.uniform(0, ceiling)
def dump_job(job_id: str, attachment_id: str, attempt: int, created_at: str) -> bytes:
payload = {
'schema_version': 1,
+11 -1
View File
@@ -1,8 +1,9 @@
import asyncio
import json
import logging
import re
import uuid
from contextlib import asynccontextmanager
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from fastapi import FastAPI, Request
@@ -15,6 +16,7 @@ from .config import load_broker_url, load_object_settings, load_settings
from .db import open_pool
from .errors import ApiError
from .objects import ObjectStore
from .outbox import relay_forever
from .routes import router
from .store import Store
@@ -64,6 +66,8 @@ async def lifespan(app: FastAPI):
logging.getLogger('aiormq').setLevel(logging.ERROR)
pool = await open_pool(settings.database_url)
broker = Broker(load_broker_url())
stop_relay = asyncio.Event()
relay = None
try:
await broker.connect()
app.state.broker = broker
@@ -73,9 +77,15 @@ async def lifespan(app: FastAPI):
settings.idempotency_ttl_seconds,
objects=ObjectStore(load_object_settings()),
)
relay = asyncio.create_task(relay_forever(pool, broker, stop_relay))
logger.info('instance %s started', settings.instance_id)
yield
finally:
stop_relay.set()
if relay is not None:
relay.cancel()
with suppress(asyncio.CancelledError):
await relay
await broker.close()
await pool.close()
+165
View File
@@ -0,0 +1,165 @@
"""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)
+130
View File
@@ -0,0 +1,130 @@
"""Explicit replay of a failed attachment job.
A ready job is recorded and left alone: replay does not run the pipeline again.
Queued and processing jobs are left to the worker that already owns them.
"""
import asyncio
import logging
import sys
import uuid
from .broker import Broker, BrokerDown
from .config import load_broker_url, load_settings
from .db import open_pool
from .jobs import PIPELINE_VERSION
from .outbox import publish_job
def _parse_id(value: str) -> uuid.UUID:
try:
parsed = uuid.UUID(value)
except ValueError:
raise SystemExit(2) from None
if str(parsed) != value.lower():
raise SystemExit(2)
return parsed
async def _decide(pool, attachment_id: uuid.UUID) -> tuple[str, str | None]:
async with pool.acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
'''
SELECT a.status, j.id AS job_id
FROM attachments a
JOIN attachment_jobs j
ON j.attachment_id = a.id AND j.pipeline_version = $2
WHERE a.id = $1
FOR UPDATE
''',
attachment_id,
PIPELINE_VERSION,
)
if row is None:
return 'missing', None
job_id = row['job_id']
if row['status'] == 'ready':
outcome = 'already_ready'
elif row['status'] != 'failed':
outcome = 'not_failed'
else:
outcome = 'requeued'
await conn.execute(
'''
UPDATE attachment_jobs
SET attempt = 1,
runs = 0,
lease_until = NULL,
available_at = NULL,
published_at = NULL,
last_error = NULL,
updated_at = clock_timestamp()
WHERE id = $1
''',
job_id,
)
await conn.execute(
'''
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'failed'
''',
attachment_id,
)
await conn.execute(
'''
INSERT INTO attachment_job_replays (id, job_id, attachment_id, outcome, created_at)
VALUES ($1, $2, $3, $4, clock_timestamp())
''',
uuid.uuid4(),
job_id,
attachment_id,
outcome,
)
return outcome, str(job_id)
async def _main(attachment_id: uuid.UUID) -> int:
pool = await open_pool(load_settings().database_url)
broker = None
try:
outcome, job_id = await _decide(pool, attachment_id)
if outcome == 'missing':
print('missing')
return 1
if outcome == 'requeued' and job_id is not None:
try:
broker = Broker(load_broker_url())
await broker.connect()
await publish_job(pool, broker, job_id)
except (BrokerDown, RuntimeError):
print('requeued %s outbox' % attachment_id)
return 0
print('%s %s' % (outcome, attachment_id))
return 0
finally:
if broker is not None:
await broker.close()
await pool.close()
def main() -> None:
logging.basicConfig(level=logging.WARNING, format='%(levelname)s %(message)s')
logging.getLogger('aio_pika').setLevel(logging.ERROR)
logging.getLogger('aiormq').setLevel(logging.ERROR)
if len(sys.argv) != 2:
print('usage: python -m app.replay ATTACHMENT_ID', file=sys.stderr)
raise SystemExit(2)
try:
attachment_id = _parse_id(sys.argv[1])
code = asyncio.run(_main(attachment_id))
except SystemExit:
raise
except Exception as exc:
print('replay failed (%s)' % type(exc).__name__, file=sys.stderr)
raise SystemExit(1) from None
raise SystemExit(code)
if __name__ == '__main__':
main()
+13 -4
View File
@@ -1,5 +1,7 @@
import hashlib
import json
import logging
import os
import re
import tempfile
import uuid
@@ -12,6 +14,8 @@ from starlette.responses import Response
from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer
from .broker import BrokerDown
from .fault import consume_fault
from .outbox import publish_job
from .drain import draining
from .errors import (
conflict,
@@ -31,6 +35,8 @@ from .store import Chat, Store, User
# The original is never persisted on the API volume; the spool dies with the request.
_SPOOL_RAM = 64 * 1024
logger = logging.getLogger('messenger')
router = APIRouter()
Body = TypeVar('Body', bound=BaseModel)
@@ -293,12 +299,15 @@ async def upload_attachment(
finally:
if spool is not None:
spool.close()
# The row is committed. 202 follows only a broker confirm, so a stopped API keeps the job.
# The row is committed. A crash before the confirm leaves it for the outbox relay.
if await consume_fault(store.pool, 'commit-before-publish'):
logger.warning('fault commit-before-publish: exiting before publish of %s', queued.attachment.id)
logging.shutdown()
os._exit(75)
try:
await request.app.state.broker.publish(queued.body)
await publish_job(store.pool, request.app.state.broker, queued.job_id)
except BrokerDown:
await store.abandon_upload(queued.attachment.id)
raise unavailable('Очередь недоступна') from None
logger.warning('upload %s is committed and waits in the outbox', queued.attachment.id)
return JSONResponse(queued.attachment.to_dict(), status_code=202)
+101
View File
@@ -0,0 +1,101 @@
"""Offline checks for variant geometry and retry delay. No database and no broker."""
import io
import random
import sys
from PIL import Image
from .jobs import REQUIRED_VARIANTS, backoff_seconds
from .thumbnail import (
CROP_SIDE,
OPTIMIZED_WEBP_QUALITY,
THUMBNAIL_BOX,
ImageRejected,
render_variants,
)
def _png(width: int, height: int, mode: str = 'RGB') -> bytes:
color = (20, 40, 60, 128) if mode == 'RGBA' else (20, 40, 60)
image = Image.new(mode, (width, height), color)
buffer = io.BytesIO()
image.save(buffer, format='PNG')
image.close()
return buffer.getvalue()
def _jpeg_oriented(width: int, height: int) -> bytes:
image = Image.new('RGB', (width, height), (10, 20, 30))
exif = Image.Exif()
exif[274] = 6
buffer = io.BytesIO()
image.save(buffer, format='JPEG', quality=90, exif=exif.tobytes())
image.close()
return buffer.getvalue()
def _expect(name: str, item: dict, width: int, height: int, content_type: str) -> None:
if item['width'] != width or item['height'] != height or item['content_type'] != content_type:
raise SystemExit('%s: got %s %sx%s' % (name, item['content_type'], item['width'], item['height']))
opened = Image.open(io.BytesIO(item['data']))
try:
if opened.size != (width, height):
raise SystemExit('%s pixels %s' % (name, opened.size))
if content_type == 'image/webp' and list(opened.getexif()):
raise SystemExit('optimized still carries EXIF')
finally:
opened.close()
def _check_image(data: bytes, thumb: tuple, optimized: tuple) -> None:
rendered = render_variants(data)
if tuple(rendered) != REQUIRED_VARIANTS:
raise SystemExit('variant set %s' % (tuple(rendered),))
_expect('thumbnail', rendered['thumbnail'], thumb[0], thumb[1], 'image/jpeg')
_expect('crop', rendered['crop'], CROP_SIDE, CROP_SIDE, 'image/jpeg')
_expect('optimized', rendered['optimized'], optimized[0], optimized[1], 'image/webp')
if rendered['optimized']['data'][:4] != b'RIFF' or rendered['optimized']['data'][8:12] != b'WEBP':
raise SystemExit('optimized is not WebP')
def _check_backoff() -> None:
rng = random.Random(0)
for attempt in range(1, 8):
ceiling = min(30.0, 0.5 * float(2 ** (attempt - 1)))
delay = backoff_seconds(attempt, 0.5, 30.0, rng)
if delay < 0 or delay > ceiling:
raise SystemExit('backoff attempt %s delay %s ceiling %s' % (attempt, delay, ceiling))
if backoff_seconds(1, 0.5, 0.1, random.Random(1)) > 0.1:
raise SystemExit('backoff ignored the cap')
def main() -> None:
_check_image(_png(320, 200), (THUMBNAIL_BOX, 160), (320, 200))
_check_image(_png(64, 40), (64, 40), (64, 40))
_check_image(_png(10, 10, 'RGBA'), (10, 10), (10, 10))
_check_image(_jpeg_oriented(320, 200), (160, THUMBNAIL_BOX), (200, 320))
_check_backoff()
try:
render_variants(b'not an image')
except ImageRejected:
pass
else:
raise SystemExit('invalid image was accepted')
try:
render_variants(b'\x89PNG\r\n\x1a\n' + b'0' * (10_485_760))
except ImageRejected:
pass
else:
raise SystemExit('oversized image was accepted')
if OPTIMIZED_WEBP_QUALITY != 80:
raise SystemExit('webp quality changed')
print('PASS: thumbnail 256, crop 128, webp 1280-box, exif stripped, backoff capped')
if __name__ == '__main__':
try:
main()
except SystemExit as exc:
if exc.code not in (0, None):
print(exc, file=sys.stderr)
raise
+9 -38
View File
@@ -13,7 +13,7 @@ import asyncpg
from .config import job_max_attempts
from .errors import conflict, invalid_request, not_found, unavailable
from .jobs import PIPELINE_VERSION, dump_job, original_key, staging_key
from .jobs import PIPELINE_VERSION, original_key, staging_key
from .migrate import expected_versions
from .objects import MissingObject, ObjectStore, StorageError
from .pagination import Key
@@ -129,7 +129,7 @@ class Attachment:
@dataclass(frozen=True)
class QueuedUpload:
attachment: Attachment
body: bytes
job_id: str
@dataclass(frozen=True)
@@ -200,6 +200,10 @@ class Store:
self._last_moment: Optional[datetime] = None
self._migrations = expected_versions()
@property
def pool(self) -> asyncpg.Pool:
return self._pool
def _now(self) -> datetime:
"""Strictly increasing within one process; across replicas order relies on the shared host clock."""
with self._lock:
@@ -426,9 +430,8 @@ class Store:
owner_uuid = _as_uuid(owner_id, 'Некорректный user_id')
attachment_id = uuid.uuid4()
job_id = uuid.uuid4()
# filename is never a storage key. Bytes go to staging/ first; the worker copies them
# unchanged to originals/ and writes the thumbnail. 202 is sent only after the broker
# confirms the job, which happens in the route after this commit.
# filename is never a storage key. Bytes go to staging/ first. The job row is the
# outbox: 202 follows this commit, and a missing broker confirm is retried from the row.
staged = staging_key(str(attachment_id))
final = original_key(str(attachment_id))
created = self._now()
@@ -489,39 +492,7 @@ class Store:
stamp,
stamp,
)
return QueuedUpload(
attachment,
dump_job(str(job_id), str(attachment_id), 1, stamp),
)
async def abandon_upload(self, attachment_id: str) -> None:
"""Drop a queued upload whose job never reached the broker."""
attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id')
staged: Optional[str] = None
async with self._pool.acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
'''
SELECT staging_key
FROM attachments
WHERE id = $1 AND status = 'queued'
FOR UPDATE
''',
attachment_uuid,
)
if row is None:
return
staged = row['staging_key']
await conn.execute(
'DELETE FROM attachment_jobs WHERE attachment_id = $1',
attachment_uuid,
)
await conn.execute(
"DELETE FROM attachments WHERE id = $1 AND status = 'queued'",
attachment_uuid,
)
if staged:
await self._discard_object(staged)
return QueuedUpload(attachment, str(job_id))
async def attachment_index(self) -> List[AttachmentRef]:
"""Every attachment row. `in_use` means a message still points at it.
+108 -17
View File
@@ -1,14 +1,32 @@
"""JPEG thumbnail for pipeline v1. Crop and WebP belong to the next grade."""
"""Derivatives for pipeline v1.
thumbnail: JPEG quality 85, fit inside 256×256, never upscaled, EXIF orientation applied,
alpha composited on white. 320×200 becomes 256×160.
crop: JPEG quality 85, centered square resized to 128×128. Sources smaller than 128 px
are scaled up. Orientation and alpha match the thumbnail.
optimized: WebP quality 80, encoder method 4, fit inside 1280×1280, never upscaled.
EXIF is not written. A small source is not promised to get smaller.
Bytes are capped at 10 MiB and pixels at 40 million before decode. The worker container
memory limit is the hard cap around that.
"""
import io
from typing import Tuple
from typing import Dict, Tuple
from PIL import Image, ImageOps, UnidentifiedImageError
from .images import MAX_IMAGE_PIXELS
from .errors import ApiError
from .images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES, inspect_image
THUMBNAIL_BOX = 256
# Pillow's default 75 is fine for a preview; the contract only fixes the pixel size.
_JPEG_QUALITY = 85
THUMBNAIL_JPEG_QUALITY = 85
CROP_SIDE = 128
CROP_JPEG_QUALITY = 85
OPTIMIZED_BOX = 1280
OPTIMIZED_WEBP_QUALITY = 80
OPTIMIZED_WEBP_METHOD = 4
class ImageRejected(Exception):
@@ -36,29 +54,102 @@ def _on_white(image: Image.Image) -> Image.Image:
return background
def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]:
"""Return JPEG bytes and the size actually written. 320×200 becomes 256×160."""
def _encode(image: Image.Image, fmt: str, **options) -> bytes:
"""Save a metadata-free copy. The caller's image is left open."""
bare = Image.frombytes(image.mode, image.size, image.tobytes())
try:
buffer = io.BytesIO()
bare.save(buffer, format=fmt, **options)
return buffer.getvalue()
finally:
bare.close()
def _fitted(base: Image.Image, box: int) -> Tuple[Image.Image, int, int]:
width, height = _fit(base.width, base.height, box)
if (width, height) == base.size:
return base, width, height
return base.resize((width, height), Image.Resampling.LANCZOS), width, height
def _jpeg_box(base: Image.Image, box: int, quality: int) -> Dict[str, object]:
image, width, height = _fitted(base, box)
try:
blob = _encode(image, 'JPEG', quality=quality)
finally:
if image is not base:
image.close()
return {'content_type': 'image/jpeg', 'width': width, 'height': height, 'data': blob}
def _crop(base: Image.Image) -> Dict[str, object]:
side = min(base.width, base.height)
left = (base.width - side) // 2
top = (base.height - side) // 2
square = base if side == base.width and side == base.height else base.crop((left, top, left + side, top + side))
try:
sized = square if square.size == (CROP_SIDE, CROP_SIDE) else square.resize(
(CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS
)
try:
blob = _encode(sized, 'JPEG', quality=CROP_JPEG_QUALITY)
finally:
if sized is not square:
sized.close()
finally:
if square is not base:
square.close()
return {'content_type': 'image/jpeg', 'width': CROP_SIDE, 'height': CROP_SIDE, 'data': blob}
def _webp(base: Image.Image) -> Dict[str, object]:
image, width, height = _fitted(base, OPTIMIZED_BOX)
try:
blob = _encode(image, 'WEBP', quality=OPTIMIZED_WEBP_QUALITY, method=OPTIMIZED_WEBP_METHOD)
finally:
if image is not base:
image.close()
return {'content_type': 'image/webp', 'width': width, 'height': height, 'data': blob}
def render_variants(data: bytes) -> Dict[str, Dict[str, object]]:
"""Decode once and return thumbnail, crop and optimized. Raises ImageRejected."""
if len(data) > MAX_UPLOAD_BYTES:
raise ImageRejected()
try:
inspect_image(data)
except ApiError:
raise ImageRejected() from None
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
source = Image.open(io.BytesIO(data))
owned = [source]
try:
oriented = ImageOps.exif_transpose(source)
if oriented is not source:
source.close()
owned.append(oriented)
source = oriented
source.load()
width, height = source.size
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
raise ImageRejected()
fitted = _fit(width, height, THUMBNAIL_BOX)
if fitted != (width, height):
source = source.resize(fitted, Image.Resampling.LANCZOS)
rgb = _on_white(source)
buffer = io.BytesIO()
rgb.save(buffer, format='JPEG', quality=_JPEG_QUALITY)
return buffer.getvalue(), fitted[0], fitted[1]
base = _on_white(source)
if base is not source:
owned.append(base)
return {
'thumbnail': _jpeg_box(base, THUMBNAIL_BOX, THUMBNAIL_JPEG_QUALITY),
'crop': _crop(base),
'optimized': _webp(base),
}
except ImageRejected:
raise
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, MemoryError):
raise ImageRejected() from None
finally:
source.close()
for image in owned:
image.close()
def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]:
"""JPEG thumbnail bytes and the size actually written. 320×200 becomes 256×160."""
item = render_variants(data)['thumbnail']
return item['data'], int(item['width']), int(item['height'])
+446 -169
View File
@@ -1,46 +1,59 @@
"""Separate process: copy the staged original and write one thumbnail.
"""Separate process: publish the staged original and the level-4 variants.
Ack happens only after that result is committed. A kill before ack redelivers the same
job id; the variant primary key keeps the second run from creating a second thumbnail.
Staging is left in place. Removing it is a later step, after the result is known to be safe.
Ack happens only after the ready row is committed. A kill after the object put and
before ack redelivers the same job id; variant primary keys keep a single set.
Staging is removed only after that commit. Failed staging stays until retention so
an operator can still replay.
"""
import asyncio
import hashlib
import logging
import os
import signal
import uuid
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from pathlib import Path
import asyncpg
from .broker import Broker, BrokerDown
from .config import job_max_attempts, job_timeout_seconds, load_broker_url, load_object_settings, load_settings, worker_concurrency
from .db import open_pool
from .jobs import PIPELINE_VERSION, QUEUE, QUEUE_ARGUMENTS, PermanentJobError, TransientJobError, dump_job, load_job, variant_key
from .config import (
effective_lease_seconds,
job_max_attempts,
job_timeout_seconds,
load_broker_url,
load_object_settings,
load_settings,
retry_base_seconds,
retry_cap_seconds,
staging_retention_seconds,
worker_concurrency,
)
from .fault import consume_fault
from .jobs import (
DLQ,
PIPELINE_VERSION,
REQUIRED_VARIANTS,
PermanentJobError,
TransientJobError,
backoff_seconds,
load_job,
lock_key,
variant_key,
)
from .objects import MissingObject, ObjectStore, StorageError
from .thumbnail import ImageRejected, make_thumbnail
from .outbox import due_at, publish_pending, reclaim_expired
from .thumbnail import ImageRejected, render_variants
logger = logging.getLogger('messenger')
_HEARTBEAT = Path('/tmp/worker-alive')
_inflight = 0
_ACK_LOCK = asyncio.Lock()
def _lock_key(attachment_id: uuid.UUID) -> int:
return attachment_id.int & ((1 << 63) - 1)
def _prepare(
objects: ObjectStore,
attachment_id: str,
staging: str,
final: str,
size: int,
digest: str,
content_type: str,
) -> dict:
"""Copy the original unchanged and build the thumbnail. Runs off the event loop."""
def _prepare(objects: ObjectStore, attachment_id: str, staging: str, final: str, size: int, digest: str, content_type: str) -> list:
"""Copy the original unchanged and write every required variant. Runs off the event loop."""
try:
data = objects.get(staging)
except MissingObject:
@@ -55,119 +68,228 @@ def _prepare(
except StorageError:
raise TransientJobError() from None
try:
jpeg, width, height = make_thumbnail(data)
rendered = render_variants(data)
except ImageRejected:
raise PermanentJobError('invalid_image') from None
thumb_key = variant_key(attachment_id, 'thumbnail')
try:
objects.put(thumb_key, jpeg, 'image/jpeg')
except StorageError:
raise TransientJobError() from None
return {
'object_key': thumb_key,
'size_bytes': len(jpeg),
'width': width,
'height': height,
'sha256': hashlib.sha256(jpeg).hexdigest(),
}
except MemoryError:
raise PermanentJobError('invalid_image') from None
if set(rendered) != set(REQUIRED_VARIANTS):
raise PermanentJobError('processing_failed')
stored = []
for name in REQUIRED_VARIANTS:
item = rendered[name]
key = variant_key(attachment_id, name)
blob = item['data']
try:
objects.put(key, blob, str(item['content_type']))
except StorageError:
raise TransientJobError() from None
stored.append({
'name': name,
'content_type': item['content_type'],
'object_key': key,
'size_bytes': len(blob),
'width': int(item['width']),
'height': int(item['height']),
'sha256': hashlib.sha256(blob).hexdigest(),
})
return stored
async def _mark_failed(conn: asyncpg.Connection, attachment_id: uuid.UUID, code: str) -> None:
now = datetime.now(timezone.utc)
async def _record_failure(conn: asyncpg.Connection, job: dict, code: str, permanent: bool) -> None:
await conn.execute(
'''
INSERT INTO attachment_job_failures (job_id, attempt, error_code, permanent, created_at)
VALUES ($1, $2, $3, $4, clock_timestamp())
ON CONFLICT (job_id, attempt, error_code) DO NOTHING
''',
uuid.UUID(job['job_id']),
job['attempt'],
code,
permanent,
)
async def _fail(conn: asyncpg.Connection, broker: Broker, job: dict, attachment_id: uuid.UUID, code: str, permanent: bool) -> None:
"""Terminal state plus the failure registry. The DLQ copy is best-effort after the commit."""
async with conn.transaction():
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = $3
WHERE id = $1 AND status IN ('queued', 'processing')
''',
status = await conn.fetchval(
'SELECT status FROM attachments WHERE id = $1 FOR UPDATE',
attachment_id,
code,
now,
)
async def _schedule_retry(
conn: asyncpg.Connection,
broker: Broker,
job: dict,
attachment_id: uuid.UUID,
limit: int,
) -> None:
"""Advance attempt and publish the next message before the caller acks this one."""
nxt = job['attempt'] + 1
now = datetime.now(timezone.utc)
if nxt > limit:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
async with conn.transaction():
moved = await conn.fetchval(
'''
UPDATE attachment_jobs
SET attempt = $2, updated_at = $3
WHERE id = $1 AND attempt = $4
RETURNING attempt
''',
uuid.UUID(job['job_id']),
nxt,
now,
job['attempt'],
)
if moved is None:
if status == 'ready':
return
await conn.execute(
'''
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
SET status = 'failed', error_code = $2, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
now,
code,
)
await broker.publish(dump_job(job['job_id'], job['attachment_id'], nxt, job['created_at']))
async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, thumb: dict) -> None:
now = datetime.now(timezone.utc)
async with conn.transaction():
await _record_failure(conn, job, code, permanent)
await conn.execute(
'''
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, 'thumbnail', 'image/jpeg', $3, $4, $5, $6, $7)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
UPDATE attachment_jobs
SET lease_until = NULL, last_error = $2, updated_at = clock_timestamp()
WHERE id = $1
''',
attachment_id,
PIPELINE_VERSION,
thumb['size_bytes'],
thumb['width'],
thumb['height'],
thumb['sha256'],
thumb['object_key'],
uuid.UUID(job['job_id']),
code,
)
try:
await broker.publish(dump_current(job), DLQ, {'x-error-code': code})
except BrokerDown:
logger.warning('job %s recorded as %s; DLQ did not confirm', job['job_id'], code)
def dump_current(job: dict) -> bytes:
from .jobs import dump_job
return dump_job(job['job_id'], job['attachment_id'], job['attempt'], job['created_at'])
async def _schedule_retry(conn: asyncpg.Connection, job: dict, attachment_id: uuid.UUID, limit: int, code: str) -> None:
"""Park the next attempt in the outbox. The current delivery is acked by the caller."""
nxt = job['attempt'] + 1
if nxt > limit:
return False
delay = backoff_seconds(job['attempt'], retry_base_seconds(), retry_cap_seconds())
async with conn.transaction():
moved = await conn.fetchval(
'''
UPDATE attachment_jobs
SET attempt = $2,
runs = 0,
available_at = $3,
published_at = NULL,
lease_until = NULL,
last_error = $4,
updated_at = clock_timestamp()
WHERE id = $1 AND attempt = $5
RETURNING attempt
''',
uuid.UUID(job['job_id']),
nxt,
due_at(delay),
code,
job['attempt'],
)
if moved is None:
return True
await conn.execute(
'''
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
now,
)
logger.info('attachment %s attempt %s will retry in %.3fs (%s)', job['attachment_id'], job['attempt'], delay, code)
return True
async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, limit: int, timeout: int) -> None:
async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, job_id: uuid.UUID, variants: list) -> bool:
async with conn.transaction():
status = await conn.fetchval(
'SELECT status FROM attachments WHERE id = $1 FOR UPDATE',
attachment_id,
)
if status != 'processing':
return False
for item in variants:
await conn.execute(
'''
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
''',
attachment_id,
PIPELINE_VERSION,
item['name'],
item['content_type'],
item['size_bytes'],
item['width'],
item['height'],
item['sha256'],
item['object_key'],
)
await conn.execute(
'''
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
)
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = NULL, last_error = NULL, updated_at = clock_timestamp()
WHERE id = $1
''',
job_id,
)
return True
async def _drop_staging(conn: asyncpg.Connection, objects: ObjectStore, attachment_id: uuid.UUID, staging: str, final: str) -> None:
"""Remove staging only after ready is committed and the final object is the copy."""
if not staging or staging == final:
return
try:
await asyncio.to_thread(objects.delete, staging)
except StorageError:
logger.warning('staging left in place for %s', attachment_id)
return
await conn.execute(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'ready' AND staging_key = $2
''',
attachment_id,
staging,
)
async def _beat_lease(pool: asyncpg.Pool, job_id: uuid.UUID, stop: asyncio.Event, lease_seconds: int) -> None:
interval = max(1.0, lease_seconds / 3)
while not stop.is_set():
try:
async with pool.acquire() as conn:
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = $2
WHERE id = $1
''',
job_id,
datetime.now(timezone.utc) + timedelta(seconds=lease_seconds),
)
except Exception:
logger.warning('lease refresh failed')
try:
await asyncio.wait_for(stop.wait(), timeout=interval)
except asyncio.TimeoutError:
pass
async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, lease_seconds: int, timeout: int) -> None:
attachment_id = uuid.UUID(job['attachment_id'])
job_id = uuid.UUID(job['job_id'])
async with pool.acquire() as conn:
await conn.execute('SELECT pg_advisory_lock($1)', _lock_key(attachment_id))
await conn.execute('SELECT pg_advisory_lock($1)', lock_key(attachment_id))
try:
row = await conn.fetchrow(
'''
@@ -177,66 +299,129 @@ async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = $1
''',
uuid.UUID(job['job_id']),
job_id,
)
if row is None or row['status'] in ('ready', 'failed'):
return
if job['attempt'] < row['attempt']:
# The previous attempt crashed after the counter moved and before its ack.
await broker.publish(dump_job(job['job_id'], job['attachment_id'], row['attempt'], job['created_at']))
if job['attempt'] != row['attempt']:
# A newer attempt is already in the outbox, or this delivery is stale.
return
if job['attempt'] > row['max_attempts']:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
now = datetime.now(timezone.utc)
await conn.execute(
'''
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
now,
)
try:
thumb = await asyncio.wait_for(
asyncio.to_thread(
_prepare,
objects,
job['attachment_id'],
row['staging_key'],
row['object_key'],
row['size_bytes'],
row['sha256'],
row['content_type'],
),
timeout=timeout,
lease_until = datetime.now(timezone.utc) + timedelta(seconds=lease_seconds)
async with conn.transaction():
runs = await conn.fetchval(
'''
UPDATE attachment_jobs
SET runs = runs + 1, lease_until = $2, updated_at = clock_timestamp()
WHERE id = $1 AND attempt = $3
RETURNING runs
''',
job_id,
lease_until,
job['attempt'],
)
except PermanentJobError as exc:
await _mark_failed(conn, attachment_id, exc.code)
if runs is None:
return
if runs > row['max_attempts']:
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = 'retry_exhausted', updated_at = clock_timestamp()
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
)
await _record_failure(conn, job, 'retry_exhausted', True)
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = NULL, last_error = 'retry_exhausted', updated_at = clock_timestamp()
WHERE id = $1
''',
job_id,
)
exhausted = True
else:
await conn.execute(
'''
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
)
exhausted = False
if exhausted:
try:
await broker.publish(dump_current(job), DLQ, {'x-error-code': 'retry_exhausted'})
except BrokerDown:
logger.warning('job %s exhausted; DLQ did not confirm', job['job_id'])
return
except (TransientJobError, asyncio.TimeoutError):
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
except Exception:
logger.exception('attachment %s attempt %s failed', job['attachment_id'], job['attempt'])
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
await _finish(conn, attachment_id, thumb)
logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt'])
stop_lease = asyncio.Event()
beat = asyncio.create_task(_beat_lease(pool, job_id, stop_lease, lease_seconds))
try:
try:
if await consume_fault(pool, 'transient-once'):
raise TransientJobError()
if await consume_fault(pool, 'permanent-once'):
raise PermanentJobError('invalid_image')
variants = await asyncio.wait_for(
asyncio.to_thread(
_prepare,
objects,
job['attachment_id'],
row['staging_key'],
row['object_key'],
row['size_bytes'],
row['sha256'],
row['content_type'],
),
timeout=timeout,
)
except PermanentJobError as exc:
await _fail(conn, broker, job, attachment_id, exc.code, True)
return
except TransientJobError:
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'storage'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
except asyncio.TimeoutError:
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'timeout'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
except Exception as exc:
logger.warning(
'attachment %s attempt %s failed (%s)',
job['attachment_id'],
job['attempt'],
type(exc).__name__,
)
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'processing_failed'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
if await consume_fault(pool, 'exit-after-put'):
logger.warning('fault exit-after-put: leaving %s unacked after object put', job['attachment_id'])
logging.shutdown()
os._exit(75)
finished = await _finish(conn, attachment_id, job_id, variants)
if finished:
await _drop_staging(conn, objects, attachment_id, row['staging_key'], row['object_key'])
logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt'])
finally:
stop_lease.set()
beat.cancel()
finally:
await conn.execute('SELECT pg_advisory_unlock($1)', _lock_key(attachment_id))
await conn.execute('SELECT pg_advisory_unlock($1)', lock_key(attachment_id))
async def _handle(pool, objects, broker, body: bytes, limit: int, timeout: int) -> None:
async def _handle(pool, objects, broker, body: bytes, lease_seconds: int, timeout: int) -> None:
job = load_job(body)
if job is None:
logger.warning('dropped a job message that does not match the contract')
return
await _process(pool, objects, broker, job, limit, timeout)
await _process(pool, objects, broker, job, lease_seconds, timeout)
async def _beat(stop: asyncio.Event) -> None:
async def _alive(stop: asyncio.Event) -> None:
while not stop.is_set():
_HEARTBEAT.write_text('ok', encoding='ascii')
try:
@@ -245,9 +430,81 @@ async def _beat(stop: asyncio.Event) -> None:
pass
async def _cleanup_staging(pool: asyncpg.Pool, objects: ObjectStore, retention: int) -> None:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=retention)
async with pool.acquire() as conn:
ready = await conn.fetch(
'''
SELECT id, staging_key, object_key
FROM attachments
WHERE status = 'ready' AND staging_key <> object_key
LIMIT 20
'''
)
failed = await conn.fetch(
'''
SELECT id, staging_key
FROM attachments
WHERE status = 'failed' AND staging_key <> object_key AND updated_at <= $1
LIMIT 20
''',
cutoff,
)
for row in ready:
try:
await asyncio.to_thread(objects.delete, row['staging_key'])
except StorageError:
continue
async with pool.acquire() as conn:
await conn.execute(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'ready' AND staging_key = $2
''',
row['id'],
row['staging_key'],
)
for row in failed:
async with pool.acquire() as conn:
claimed = await conn.fetchval(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'failed' AND staging_key = $2 AND updated_at <= $3
RETURNING id
''',
row['id'],
row['staging_key'],
cutoff,
)
if claimed is None:
continue
try:
await asyncio.to_thread(objects.delete, row['staging_key'])
except StorageError:
logger.warning('failed staging %s was unlinked in metadata and is still in the bucket', row['id'])
async def _maintain(pool, broker, objects, stop: asyncio.Event, retention: int) -> None:
ticks = 0
while not stop.is_set():
try:
await publish_pending(pool, broker)
await reclaim_expired(pool)
ticks += 1
if ticks % 30 == 0:
await _cleanup_staging(pool, objects, retention)
except Exception:
logger.exception('worker maintenance failed')
try:
await asyncio.wait_for(stop.wait(), timeout=1)
except asyncio.TimeoutError:
pass
async def _run() -> None:
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
# Library logs can include the AMQP URL. Keep them quiet.
logging.getLogger('aio_pika').setLevel(logging.ERROR)
logging.getLogger('aiormq').setLevel(logging.ERROR)
stop = asyncio.Event()
@@ -255,40 +512,52 @@ async def _run() -> None:
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, stop.set)
settings = load_settings()
limit = job_max_attempts()
# Imported for the side effect of validating the pool settings the API also uses.
load_settings()
job_max_attempts()
timeout = job_timeout_seconds()
pool = await open_pool(settings.database_url)
lease_seconds = effective_lease_seconds()
retention = staging_retention_seconds()
prefetch = worker_concurrency()
pool = await open_pool_from_settings()
objects = ObjectStore(load_object_settings())
broker = Broker(load_broker_url())
beat = asyncio.create_task(_beat(stop))
alive = asyncio.create_task(_alive(stop))
maintain = None
try:
await broker.connect()
channel = broker.channel
if channel is None:
raise RuntimeError('broker did not become reachable')
await channel.set_qos(prefetch_count=worker_concurrency())
queue = await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
# consumer_channel stays referenced until this function returns, so it is not closed early.
consumer_channel, queue = await broker.open_consumer(prefetch)
maintain = asyncio.create_task(_maintain(pool, broker, objects, stop, retention))
async def on_message(message) -> None:
global _inflight
_inflight += 1
try:
await _handle(pool, objects, broker, message.body, limit, timeout)
await _handle(pool, objects, broker, message.body, lease_seconds, timeout)
except BrokerDown:
await message.nack(requeue=True)
async with _ACK_LOCK:
await message.nack(requeue=True)
return
except Exception:
logger.exception('job was not finished')
await message.nack(requeue=True)
async with _ACK_LOCK:
await message.nack(requeue=True)
return
else:
await message.ack()
async with _ACK_LOCK:
await message.ack()
finally:
_inflight -= 1
consumer = await queue.consume(on_message)
logger.info('worker consuming %s', queue.name)
logger.info(
'worker consuming %s prefetch %s lease %ss channel %s',
queue.name,
prefetch,
lease_seconds,
id(consumer_channel),
)
await stop.wait()
logger.info('worker draining')
await queue.cancel(consumer)
@@ -297,11 +566,19 @@ async def _run() -> None:
break
await asyncio.sleep(0.05)
finally:
beat.cancel()
alive.cancel()
if maintain is not None:
maintain.cancel()
await broker.close()
await pool.close()
async def open_pool_from_settings():
from .db import open_pool
return await open_pool(load_settings().database_url)
def main() -> None:
asyncio.run(_run())