forked from mtusi2026/mtusi2026lab5
lab5: схема 0005 (jobs, outbox, попытки, варианты, аудит) и модули pipeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Миграция только добавляет: статусы pending/queued/processing/ready/failed, staging-ключ, published_version, jobs с lease и токеном попытки, job_attempts с заранее известными ключами, attachment_variants (PK = ключ эффекта), outbox, job_events, view failed_jobs, post_message_v3. CHECK attachments_active_has_source: у queued/processing всегда есть источник. pipeline.py — версии 1/2/3 и геометрия по контракту; imaging.py — варианты в дочернем процессе (RLIMIT_AS, таймаут, лимит пикселей); jobs.py — все переходы заданий одной транзакцией с fencing по токену; broker.py — топология и строгая схема сообщения. Зависимости: aio-pika 9.6.2, pillow 12.3.0 (lock с хешами).
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format.
|
||||
|
||||
Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and
|
||||
scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing):
|
||||
|
||||
exchange messenger.jobs direct, durable
|
||||
queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key
|
||||
attachment.process.v1; x-delivery-limit and dead-lettering to
|
||||
exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum)
|
||||
|
||||
Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not
|
||||
silently dropped), channel in confirm mode - `publish()` returns only after the broker has
|
||||
written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack
|
||||
after the durable effect, prefetch = WORKER_CONCURRENCY.
|
||||
|
||||
The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL,
|
||||
no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
EXCHANGE = "messenger.jobs"
|
||||
QUEUE = "messenger.attachment-jobs"
|
||||
DLX = "messenger.jobs.dlx"
|
||||
DLQ = "messenger.attachment-jobs.dlq"
|
||||
ROUTING_KEY = "attachment.process.v1"
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
MAX_MESSAGE_BYTES = 4096
|
||||
|
||||
REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
|
||||
OPTIONAL = {"traceparent", "tracestate"}
|
||||
TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}")
|
||||
DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z")
|
||||
|
||||
|
||||
class BadMessage(ValueError):
|
||||
"""Not a valid job message (schema v1): dead-lettered, never processed."""
|
||||
|
||||
|
||||
def rfc3339(value: dt.datetime) -> str:
|
||||
return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime) -> bytes:
|
||||
body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id,
|
||||
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)}
|
||||
return json.dumps(body, separators=(",", ":")).encode()
|
||||
|
||||
|
||||
def decode(raw: bytes) -> dict:
|
||||
"""Strict check against contracts/jobs.schema.json (additionalProperties: false)."""
|
||||
if len(raw) > MAX_MESSAGE_BYTES:
|
||||
raise BadMessage("too large")
|
||||
try:
|
||||
body = json.loads(raw)
|
||||
except (ValueError, UnicodeError):
|
||||
raise BadMessage("not JSON") from None
|
||||
if not isinstance(body, dict):
|
||||
raise BadMessage("not an object")
|
||||
keys = set(body)
|
||||
if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL:
|
||||
raise BadMessage("wrong fields")
|
||||
if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE:
|
||||
raise BadMessage("unsupported schema/type")
|
||||
for name in ("job_id", "attachment_id"):
|
||||
if not isinstance(body[name], str):
|
||||
raise BadMessage(name)
|
||||
try:
|
||||
uuid.UUID(body[name])
|
||||
except ValueError:
|
||||
raise BadMessage(name) from None
|
||||
for name in ("pipeline_version", "attempt"):
|
||||
value = body[name]
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 1:
|
||||
raise BadMessage(name)
|
||||
if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]):
|
||||
raise BadMessage("created_at")
|
||||
if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])):
|
||||
raise BadMessage("traceparent")
|
||||
if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512):
|
||||
raise BadMessage("tracestate")
|
||||
return body
|
||||
+119
-12
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -134,7 +134,29 @@ class Settings:
|
||||
jpeg_max_memory_mb: int = 256
|
||||
pending_grace_seconds: int = 900
|
||||
janitor_interval_seconds: float = 60.0
|
||||
# Lab 5: staging bucket (API writes, worker reads) and the asynchronous pipeline (jobs_settings()).
|
||||
s3_staging_bucket: str = "messenger-staging"
|
||||
broker_url: str = ""
|
||||
pipeline_version: int = 1
|
||||
job_max_attempts: int = 5
|
||||
job_timeout_seconds: float = 60.0
|
||||
job_lease_seconds: float = 30.0
|
||||
job_retry_base_seconds: float = 2.0
|
||||
job_retry_max_seconds: float = 60.0
|
||||
worker_concurrency: int = 2
|
||||
worker_shutdown_seconds: float = 20.0
|
||||
image_max_memory_mb: int = 768
|
||||
staging_retention_seconds: int = 86400
|
||||
orphan_grace_seconds: int = 600
|
||||
cleanup_interval_seconds: float = 30.0
|
||||
relay_poll_seconds: float = 0.5
|
||||
relay_batch: int = 50
|
||||
queued_republish_seconds: float = 300.0
|
||||
fault_points: frozenset[str] = frozenset()
|
||||
fault_values: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def fault_value(self, point: str, default: int = 0) -> int:
|
||||
return self.fault_values.get(point, default)
|
||||
|
||||
@property
|
||||
def db_statement_timeout_ms(self) -> int:
|
||||
@@ -142,7 +164,8 @@ class Settings:
|
||||
return max(100, int(self.db_timeout_seconds * 1000) - 500)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "Settings":
|
||||
def from_env(cls, *, s3_credentials: bool = True) -> "Settings":
|
||||
"""s3_credentials=False: processes without S3 access (relay, jobctl)."""
|
||||
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
|
||||
if log_level not in {"debug", "info", "warning", "error"}:
|
||||
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
|
||||
@@ -185,32 +208,71 @@ class Settings:
|
||||
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
|
||||
# multi-statement transaction; both have identical semantics (A/B on one image).
|
||||
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
|
||||
**s3_settings(),
|
||||
**s3_settings(credentials_required=s3_credentials),
|
||||
**jobs_settings(broker_required=False),
|
||||
)
|
||||
|
||||
|
||||
# Contract limits (contracts/README.md): configurable DOWN for experiments, never above them.
|
||||
CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
CONTRACT_MAX_IMAGE_PIXELS = 40_000_000
|
||||
# Failure points for the level 4 experiments only (compose.faults.yaml); empty in normal runs.
|
||||
FAULT_POINTS = {"after_s3_put", "after_ready_commit"}
|
||||
# Failure points for the experiments only (FAULT_POINTS of ONE service, compose variables
|
||||
# API_/RELAY_/WORKER_FAULT_POINTS); empty in normal runs. `name` or `name=<integer>`.
|
||||
FAULT_POINTS = {
|
||||
# API, upload: between the staging PUT and the job COMMIT / after the job COMMIT, before 202.
|
||||
"after_s3_put", "after_enqueue_commit",
|
||||
# Relay: crash after the broker confirmed a publish but before outbox.published_at is
|
||||
# committed; publish every message twice; publish a batch in reverse order.
|
||||
"crash_after_publish", "duplicate_publish", "reverse_order",
|
||||
# Worker: crash after the claim (before any side effect), after the S3 writes (before the
|
||||
# result COMMIT), after the result COMMIT (before the ack); transient failure of the first N
|
||||
# attempts; permanent failure; slow processing (N s, lease kept alive) of every job or only of
|
||||
# pipeline version `slow_pipeline`; hang: stop the heartbeat and sleep N s inside processing.
|
||||
"crash_after_claim", "crash_after_s3_write", "crash_after_commit", "transient_error", "permanent_error",
|
||||
"slow", "slow_pipeline", "hang",
|
||||
# Worker cleanup: pause N s after reading the candidates, before locking/deleting them.
|
||||
"pause_cleanup",
|
||||
}
|
||||
|
||||
|
||||
def _faults() -> tuple[frozenset[str], dict[str, int]]:
|
||||
names, values = set(), {}
|
||||
for item in os.environ.get("FAULT_POINTS", "").split(","):
|
||||
name, _, raw = item.strip().partition("=")
|
||||
if not name:
|
||||
continue
|
||||
if name not in FAULT_POINTS:
|
||||
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
|
||||
if raw:
|
||||
if not raw.isdigit():
|
||||
raise ConfigError(f"FAULT_POINTS value of {name} must be an integer")
|
||||
values[name] = int(raw)
|
||||
names.add(name)
|
||||
return frozenset(names), values
|
||||
|
||||
|
||||
def _bucket(name: str, default: str) -> str:
|
||||
bucket = os.environ.get(name, default).strip() or default
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
|
||||
raise ConfigError(f"{name} is not a valid bucket name: {bucket!r}")
|
||||
return bucket
|
||||
|
||||
|
||||
def s3_settings(*, credentials_required: bool = True) -> dict:
|
||||
"""S3 part of Settings; also used by the reconciler/bootstrap CLIs with their own keys."""
|
||||
faults = frozenset(f.strip() for f in os.environ.get("FAULT_POINTS", "").split(",") if f.strip())
|
||||
if faults - FAULT_POINTS:
|
||||
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
|
||||
"""S3 part of Settings; also used by the bootstrap CLI with its own keys."""
|
||||
faults, fault_values = _faults()
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").strip() or "http://s3:8333"
|
||||
if not re.fullmatch(r"https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?/?", endpoint):
|
||||
raise ConfigError(f"S3_ENDPOINT must be http(s)://host[:port], got {endpoint!r}")
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() or "messenger-attachments"
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
|
||||
raise ConfigError(f"S3_BUCKET is not a valid bucket name: {bucket!r}")
|
||||
bucket = _bucket("S3_BUCKET", "messenger-attachments")
|
||||
staging = _bucket("S3_STAGING_BUCKET", "messenger-staging")
|
||||
if staging == bucket:
|
||||
raise ConfigError("S3_STAGING_BUCKET must differ from S3_BUCKET")
|
||||
return dict(
|
||||
s3_endpoint=endpoint,
|
||||
s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1",
|
||||
s3_bucket=bucket,
|
||||
s3_staging_bucket=staging,
|
||||
s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=credentials_required),
|
||||
s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=credentials_required),
|
||||
s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 3.0, 0.2, 30.0),
|
||||
@@ -233,4 +295,49 @@ def s3_settings(*, credentials_required: bool = True) -> dict:
|
||||
pending_grace_seconds=_int("PENDING_GRACE_SECONDS", 900, 1, 7 * 24 * 3600),
|
||||
janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0),
|
||||
fault_points=faults,
|
||||
fault_values=fault_values,
|
||||
)
|
||||
|
||||
|
||||
def jobs_settings(*, broker_required: bool) -> dict:
|
||||
"""Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md)."""
|
||||
from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here
|
||||
timeout = _float("JOB_TIMEOUT_SECONDS", 60.0, 1.0, 600.0)
|
||||
lease = _float("JOB_LEASE_SECONDS", 30.0, 2.0, 600.0)
|
||||
base = _float("JOB_RETRY_BASE_SECONDS", 2.0, 0.0, 600.0)
|
||||
cap = _float("JOB_RETRY_MAX_SECONDS", 60.0, 0.0, 3600.0)
|
||||
if base > cap:
|
||||
raise ConfigError("JOB_RETRY_BASE_SECONDS must not exceed JOB_RETRY_MAX_SECONDS")
|
||||
orphan_grace = _int("ORPHAN_GRACE_SECONDS", 600, 1, 7 * 24 * 3600)
|
||||
version = _int("PIPELINE_VERSION", 1, 1, 1000)
|
||||
if version not in PIPELINES:
|
||||
raise ConfigError(f"PIPELINE_VERSION must be one of {sorted(PIPELINES)}")
|
||||
return dict(
|
||||
broker_url=_secret("BROKER_URL", required=broker_required),
|
||||
# Pipeline version of the jobs created by new uploads (track 2: versioned pipeline).
|
||||
pipeline_version=version,
|
||||
# Managed attempts (claims) per job before failed/retry_exhausted.
|
||||
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100),
|
||||
# Hard limit of ONE attempt: the image child process is killed, the lease is no longer renewed.
|
||||
job_timeout_seconds=timeout,
|
||||
# Lease of a claimed job, renewed by the heartbeat every lease/3 while the attempt runs.
|
||||
job_lease_seconds=lease,
|
||||
# Backoff of transient failures: full jitter, uniform(0, min(max, base * 2^(attempt-1))).
|
||||
job_retry_base_seconds=base,
|
||||
job_retry_max_seconds=cap,
|
||||
# Jobs processed at once by ONE worker process = RabbitMQ prefetch (basic.qos).
|
||||
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 32),
|
||||
worker_shutdown_seconds=_float("WORKER_SHUTDOWN_SECONDS", 20.0, 0.0, 120.0),
|
||||
# Address-space limit (RLIMIT_AS) of the child process that decodes/encodes ONE image.
|
||||
image_max_memory_mb=_int("IMAGE_MAX_MEMORY_MB", 768, 128, 8192),
|
||||
# Staging copy of a FAILED attachment is kept this long for a replay, then deleted.
|
||||
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 0, 30 * 24 * 3600),
|
||||
# Objects of attempts that did not publish are deleted once the attempt ended this long ago.
|
||||
orphan_grace_seconds=orphan_grace,
|
||||
cleanup_interval_seconds=_float("CLEANUP_INTERVAL_SECONDS", 30.0, 0.0, 3600.0),
|
||||
relay_poll_seconds=_float("RELAY_POLL_SECONDS", 0.5, 0.05, 60.0),
|
||||
relay_batch=_int("RELAY_BATCH", 50, 1, 1000),
|
||||
# A queued job whose message has not led to a claim for this long is published again
|
||||
# (message lost in the broker, dead-lettered, purged): no accepted job waits forever.
|
||||
queued_republish_seconds=_float("QUEUED_REPUBLISH_SECONDS", 300.0, 5.0, 86400.0),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Variants of ONE image, built in a separate child process with hard limits (lab 5 worker).
|
||||
|
||||
parent (worker): await render(data, content_type, version, ...) -> list[Rendered]
|
||||
child: python -m messenger.imaging --type image/png --pipeline 1 ...
|
||||
stdin: original bytes; stdout: one JSON header line + variant bytes
|
||||
|
||||
Why a child process per image:
|
||||
* memory: RLIMIT_AS (IMAGE_MAX_MEMORY_MB) caps the address space of the decoder; a picture that
|
||||
needs more fails with MemoryError -> `image_too_large` (permanent), the worker keeps running;
|
||||
* time: the parent kills the child at JOB_TIMEOUT_SECONDS (C code of Pillow cannot be
|
||||
interrupted inside a thread) -> `processing_timeout` (transient, bounded by JOB_MAX_ATTEMPTS);
|
||||
* pixels: the size is read from the header and checked against MAX_IMAGE_PIXELS BEFORE the
|
||||
pixels are decoded (`Image.open` is lazy).
|
||||
A crash of the decoder (signal) is a transient `processing_killed`: the next attempt may run
|
||||
with less memory pressure; JOB_MAX_ATTEMPTS bounds it.
|
||||
|
||||
Geometry and encoder settings: pipeline.py. Alpha is handled in premultiplied form (RGBa) while
|
||||
resizing, so transparent pixels do not bleed their colour into the edges; for JPEG the result is
|
||||
then composited onto white.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .pipeline import CONTENT_TYPES, CROP_SIDE, OPTIMIZED_BOX, PIPELINES, THUMBNAIL_BOX, center_square, fit
|
||||
|
||||
EXIT_INVALID = 3 # the bytes are not a decodable PNG/JPEG
|
||||
EXIT_TOO_LARGE = 4 # pixel limit or memory limit
|
||||
HEADER_LIMIT = 4096
|
||||
|
||||
|
||||
class ProcessingError(Exception):
|
||||
"""Outcome of an attempt that did not produce variants. `permanent`: another attempt with the
|
||||
same input cannot succeed (job -> failed at once); otherwise retry with backoff."""
|
||||
|
||||
def __init__(self, code: str, permanent: bool):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
self.permanent = permanent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rendered:
|
||||
name: str
|
||||
content_type: str
|
||||
width: int
|
||||
height: int
|
||||
data: bytes
|
||||
|
||||
@property
|
||||
def sha256(self) -> bytes:
|
||||
return hashlib.sha256(self.data).digest()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ parent side
|
||||
async def render(data: bytes, content_type: str, pipeline_version: int, *, max_pixels: int, timeout: float,
|
||||
memory_mb: int) -> list[Rendered]:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "messenger.imaging", "--type", content_type, "--pipeline", str(pipeline_version),
|
||||
"--max-pixels", str(max_pixels), "--memory-mb", str(memory_mb),
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
||||
try:
|
||||
out, _ = await asyncio.wait_for(process.communicate(data), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
raise ProcessingError("processing_timeout", permanent=False) from None
|
||||
except asyncio.CancelledError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
raise
|
||||
code = process.returncode
|
||||
if code == EXIT_INVALID:
|
||||
raise ProcessingError("invalid_image", permanent=True)
|
||||
if code == EXIT_TOO_LARGE:
|
||||
raise ProcessingError("image_too_large", permanent=True)
|
||||
if code is None or code < 0:
|
||||
raise ProcessingError("processing_killed", permanent=False) # OOM killer or another signal
|
||||
if code != 0:
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
return parse_output(out)
|
||||
|
||||
|
||||
def parse_output(out: bytes) -> list[Rendered]:
|
||||
newline = out.find(b"\n", 0, HEADER_LIMIT)
|
||||
if newline < 0:
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
header = json.loads(out[:newline])
|
||||
pos = newline + 1
|
||||
result = []
|
||||
for item in header["variants"]:
|
||||
size = int(item["size"])
|
||||
result.append(Rendered(item["name"], item["content_type"], int(item["width"]), int(item["height"]),
|
||||
out[pos:pos + size]))
|
||||
pos += size
|
||||
if pos != len(out) or [r.name for r in result] != list(CONTENT_TYPES):
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
return result
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ child side
|
||||
def build(data: bytes, content_type: str, pipeline_version: int, max_pixels: int) -> list[Rendered]:
|
||||
"""Decode once, build every variant. Raises the Pillow/OS errors of a bad file."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
pipeline = PIPELINES[pipeline_version]
|
||||
warnings.simplefilter("ignore", Image.DecompressionBombWarning) # our own pixel limit below
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
expected = {"image/png": "PNG", "image/jpeg": "JPEG"}[content_type]
|
||||
img = Image.open(io.BytesIO(data), formats=[expected]) # header only: nothing decoded yet
|
||||
width, height = img.size
|
||||
if width * height > max_pixels:
|
||||
raise TooLarge()
|
||||
if expected == "JPEG":
|
||||
# DCT scaling: decode a big JPEG directly at 1/2..1/8 of its size, never below what the
|
||||
# largest variant needs (the box stays square, so EXIF rotation does not matter).
|
||||
img.draft("RGB", (OPTIMIZED_BOX, OPTIMIZED_BOX))
|
||||
img.load()
|
||||
img = ImageOps.exif_transpose(img) # orientation goes into the pixels, the tag is dropped
|
||||
img = _normalize(img)
|
||||
alpha = img.mode == "RGBA"
|
||||
base = img.convert("RGBa") if alpha else img # premultiplied alpha for resampling
|
||||
del img
|
||||
|
||||
def finish(im, *, flatten: bool):
|
||||
if alpha:
|
||||
im = im.convert("RGBA")
|
||||
if flatten:
|
||||
white = Image.new("RGB", im.size, (255, 255, 255))
|
||||
white.paste(im, mask=im.getchannel("A"))
|
||||
im = white
|
||||
im.info = {} # no EXIF/XMP/ICC/comments of the source in a variant
|
||||
return im
|
||||
|
||||
def resized(im, size):
|
||||
return im if im.size == size else im.resize(size, Image.Resampling.LANCZOS, reducing_gap=3.0)
|
||||
|
||||
thumbnail = finish(resized(base, fit(*base.size, THUMBNAIL_BOX)), flatten=True)
|
||||
crop = finish(resized(base.crop(center_square(*base.size)), (CROP_SIDE, CROP_SIDE)), flatten=True)
|
||||
optimized = finish(resized(base, fit(*base.size, OPTIMIZED_BOX)), flatten=False)
|
||||
out = []
|
||||
for name, im in (("thumbnail", thumbnail), ("crop", crop), ("optimized", optimized)):
|
||||
buf = io.BytesIO()
|
||||
if CONTENT_TYPES[name] == "image/jpeg":
|
||||
im.save(buf, "JPEG", quality=pipeline.jpeg_quality, optimize=True, subsampling=2, progressive=False)
|
||||
else:
|
||||
im.save(buf, "WEBP", quality=pipeline.webp_quality, method=pipeline.webp_method, exif=b"",
|
||||
icc_profile="", xmp=b"")
|
||||
out.append(Rendered(name, CONTENT_TYPES[name], im.width, im.height, buf.getvalue()))
|
||||
return out
|
||||
|
||||
|
||||
class TooLarge(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize(img):
|
||||
"""Any PNG/JPEG mode -> RGB, or RGBA when the image has transparency."""
|
||||
if img.mode.startswith("I;16") or img.mode == "I":
|
||||
# 16-bit grey: scale 0..65535 to 0..255 (a plain convert("L") would clip to white).
|
||||
img = img.convert("I").point(lambda v: v * (1 / 257)).convert("L")
|
||||
has_alpha = img.mode in ("RGBA", "LA", "PA", "La", "RGBa") or "transparency" in img.info
|
||||
return img.convert("RGBA" if has_alpha else "RGB") if img.mode != ("RGBA" if has_alpha else "RGB") else img
|
||||
|
||||
|
||||
def child_main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--type", required=True, choices=["image/png", "image/jpeg"])
|
||||
parser.add_argument("--pipeline", type=int, required=True, choices=sorted(PIPELINES))
|
||||
parser.add_argument("--max-pixels", type=int, required=True)
|
||||
parser.add_argument("--memory-mb", type=int, required=True)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
import resource
|
||||
limit = args.memory_mb * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
except (ImportError, ValueError, OSError):
|
||||
pass # not Linux (unit tests on Windows): the container memory limit still applies
|
||||
data = sys.stdin.buffer.read()
|
||||
try:
|
||||
variants = build(data, args.type, args.pipeline, args.max_pixels)
|
||||
except (TooLarge, MemoryError):
|
||||
return EXIT_TOO_LARGE
|
||||
except Exception as exc: # noqa: BLE001 - every decoder error of the CONTENT is "invalid image"
|
||||
from PIL import Image
|
||||
if isinstance(exc, Image.DecompressionBombError):
|
||||
return EXIT_TOO_LARGE
|
||||
if isinstance(exc, (OSError, SyntaxError, ValueError, EOFError, KeyError, IndexError, TypeError)):
|
||||
return EXIT_INVALID
|
||||
raise
|
||||
header = {"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width, "height": v.height,
|
||||
"size": len(v.data)} for v in variants]}
|
||||
sys.stdout.buffer.write(json.dumps(header).encode() + b"\n")
|
||||
for v in variants:
|
||||
sys.stdout.buffer.write(v.data)
|
||||
sys.stdout.buffer.flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(child_main())
|
||||
@@ -0,0 +1,398 @@
|
||||
"""State machine of attachment jobs in PostgreSQL (lab 5). Every transition is ONE transaction.
|
||||
|
||||
Lock order, everywhere both rows are locked: the jobs row FIRST, then the attachments row
|
||||
(claim, complete, retry, lease expiry). Replay/reprocess/cleanup lock only the attachments row
|
||||
and insert NEW job rows. So two transitions never wait on each other in opposite order.
|
||||
|
||||
Fencing: a claim gives the attempt a fresh random `lease_token`. Every later write of that attempt
|
||||
(heartbeat, result, retry) is conditional on `jobs.lease_token = <its token>` under the jobs row
|
||||
lock. When the lease expires, the reaper clears the token; from then on the old attempt - even if
|
||||
its process is still alive (paused, slow) - can neither publish nor schedule anything, and the
|
||||
objects it wrote under its own keys are garbage for the cleanup.
|
||||
|
||||
Monotonic publication: a result of pipeline version V is published only if V is greater than the
|
||||
published version of the attachment; otherwise the job ends as `superseded` and nothing visible
|
||||
changes. `ready` never goes back to queued/processing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
import psycopg
|
||||
|
||||
from .pipeline import VARIANT_NAMES
|
||||
from .storage import attempt_key
|
||||
|
||||
ACTIVE = ("queued", "processing")
|
||||
|
||||
|
||||
def backoff_delay(attempt: int, base: float, cap: float, rnd=random.random) -> float:
|
||||
"""Full jitter (AWS Architecture Blog, "Exponential Backoff And Jitter"): uniform in
|
||||
[0, min(cap, base * 2^(attempt-1))]. Spreads the retries of many jobs that failed together."""
|
||||
return rnd() * min(cap, base * (2 ** max(0, attempt - 1)))
|
||||
|
||||
|
||||
async def event(conn: psycopg.AsyncConnection, job_id, name: str, actor: str, *, attempt: int | None = None,
|
||||
error_code: str | None = None, **detail) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO job_events (job_id, event, attempt, actor, error_code, detail) VALUES (%s, %s, %s, %s, %s, %s)",
|
||||
(job_id, name, attempt, actor, error_code, json.dumps(detail, default=str)))
|
||||
|
||||
|
||||
async def create_job(conn: psycopg.AsyncConnection, attachment_id, pipeline_version: int, kind: str,
|
||||
max_attempts: int, actor: str, *, replay_of=None, **detail) -> uuid.UUID:
|
||||
"""jobs row + its first outbox row + audit, in the CALLER's transaction."""
|
||||
job_id = uuid.uuid4()
|
||||
await conn.execute(
|
||||
"INSERT INTO jobs (id, attachment_id, pipeline_version, kind, replay_of, max_attempts) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s)", (job_id, attachment_id, pipeline_version, kind, replay_of, max_attempts))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, 1)", (job_id,))
|
||||
await event(conn, job_id, "created", actor, kind=kind, pipeline_version=pipeline_version,
|
||||
replay_of=str(replay_of) if replay_of else None, **detail)
|
||||
return job_id
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ relay
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Due:
|
||||
outbox_id: int
|
||||
job_id: str
|
||||
attachment_id: str
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
created_at: dt.datetime
|
||||
job_state: str
|
||||
|
||||
|
||||
async def due_outbox(conn: psycopg.AsyncConnection, batch: int) -> list[Due]:
|
||||
"""Due, unpublished outbox rows, locked for this relay pass (SKIP LOCKED: several relays
|
||||
never publish the same row at the same time - a crash may still publish it twice)."""
|
||||
cur = await conn.execute(
|
||||
"SELECT o.id, o.job_id, j.attachment_id, j.pipeline_version, o.attempt, j.created_at, j.state "
|
||||
"FROM outbox o JOIN jobs j ON j.id = o.job_id "
|
||||
"WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() "
|
||||
"ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (batch,))
|
||||
return [Due(r[0], str(r[1]), str(r[2]), r[3], r[4], r[5], r[6]) for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def mark_published(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
|
||||
if ids:
|
||||
await conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY(%s)", (ids,))
|
||||
|
||||
|
||||
async def count_publish_failure(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
|
||||
if ids:
|
||||
await conn.execute("UPDATE outbox SET publish_failures = publish_failures + 1 WHERE id = ANY(%s)", (ids,))
|
||||
|
||||
|
||||
async def expire_leases(conn: psycopg.AsyncConnection, actor: str, limit: int = 50) -> int:
|
||||
"""Reaper: processing jobs whose lease ran out (the worker died, hung or lost its database).
|
||||
The attempt is abandoned; the job goes back to queued with a new outbox row, or to failed
|
||||
`retry_exhausted` when it used all its attempts."""
|
||||
cur = await conn.execute(
|
||||
"SELECT id, attempt, max_attempts, lease_token, attachment_id FROM jobs "
|
||||
"WHERE state = 'processing' AND lease_until < clock_timestamp() "
|
||||
"ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED", (limit,))
|
||||
rows = await cur.fetchall()
|
||||
for job_id, attempt, max_attempts, token, attachment_id in rows:
|
||||
await conn.execute(
|
||||
"UPDATE job_attempts SET outcome = 'abandoned', error_code = 'lease_expired', finished_at = clock_timestamp() "
|
||||
"WHERE token = %s AND outcome = 'running'", (token,))
|
||||
if attempt >= max_attempts:
|
||||
await _fail(conn, job_id, attachment_id, "retry_exhausted", actor, attempt, cause="lease_expired")
|
||||
else:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (job_id,))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() "
|
||||
"WHERE id = %s AND status = 'processing'", (attachment_id,))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
|
||||
await event(conn, job_id, "lease_expired", actor, attempt=attempt)
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def republish_stale(conn: psycopg.AsyncConnection, older_than: float, actor: str, limit: int = 50) -> int:
|
||||
"""Lost-message guard: a queued, due job that has had no unpublished outbox row and no
|
||||
publish for `older_than` seconds gets a new outbox row (its message was lost by the broker,
|
||||
dead-lettered after too many redeliveries, or the queue was purged)."""
|
||||
cur = await conn.execute(
|
||||
"SELECT j.id, j.attempt FROM jobs j "
|
||||
"WHERE j.state = 'queued' AND j.available_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"AND j.updated_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND (o.published_at IS NULL "
|
||||
" OR o.published_at > clock_timestamp() - make_interval(secs => %s))) "
|
||||
"ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED", (older_than, older_than, older_than, limit))
|
||||
rows = await cur.fetchall()
|
||||
for job_id, attempt in rows:
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
|
||||
await event(conn, job_id, "republished", actor, attempt=attempt)
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def purge_outbox(conn: psycopg.AsyncConnection, keep_seconds: int = 7 * 86400) -> int:
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE published_at < clock_timestamp() "
|
||||
"- make_interval(secs => %s) LIMIT 1000)", (keep_seconds,))
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ worker
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Claim:
|
||||
job_id: str
|
||||
attachment_id: str
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
max_attempts: int
|
||||
token: str
|
||||
source: str # staging | original
|
||||
source_key: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: bytes
|
||||
write_original: bool # the original is not published yet: this attempt publishes it too
|
||||
|
||||
def key(self, name: str) -> str:
|
||||
return attempt_key(self.attachment_id, self.token, name)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Noop:
|
||||
reason: str # finished | leased | not_due | superseded | unknown_job
|
||||
|
||||
|
||||
async def claim(conn: psycopg.AsyncConnection, job_id: str, worker: str, lease_seconds: float) -> Claim | Noop:
|
||||
cur = await conn.execute(
|
||||
"SELECT state, attempt, max_attempts, available_at > clock_timestamp(), attachment_id, pipeline_version "
|
||||
"FROM jobs WHERE id = %s FOR UPDATE", (job_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return Noop("unknown_job")
|
||||
state, attempt, max_attempts, not_due, attachment_id, version = row
|
||||
if state not in ACTIVE:
|
||||
return Noop("finished") # duplicate/redelivery of a finished job: ack, nothing else
|
||||
if state == "processing":
|
||||
return Noop("leased") # another attempt holds the lease; the reaper handles its death
|
||||
if not_due:
|
||||
return Noop("not_due") # backoff not over: the outbox publishes it at available_at
|
||||
cur = await conn.execute(
|
||||
"SELECT status, published_version, object_key, staging_key, staging_state, content_type, size_bytes, sha256 "
|
||||
"FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,))
|
||||
status, published, object_key, staging_key, staging_state, content_type, size, sha = await cur.fetchone()
|
||||
actor = "worker:" + worker
|
||||
if published is not None and published >= version:
|
||||
# A newer (or the same) version is already published: this job can only be stale.
|
||||
await _finish(conn, job_id, "superseded", None)
|
||||
await event(conn, job_id, "superseded", actor, attempt=attempt, published_version=published)
|
||||
return Noop("superseded")
|
||||
if object_key is not None:
|
||||
source, source_key = "original", object_key
|
||||
elif staging_state == "present":
|
||||
source, source_key = "staging", staging_key
|
||||
else:
|
||||
# Cannot happen while the CHECK attachments_active_has_source holds; fail visibly anyway.
|
||||
await _fail(conn, job_id, attachment_id, "source_missing", actor, attempt)
|
||||
return Noop("finished")
|
||||
token = uuid.uuid4().hex
|
||||
attempt += 1
|
||||
write_original = object_key is None
|
||||
names = (("original",) if write_original else ()) + VARIANT_NAMES
|
||||
planned = [attempt_key(str(attachment_id), token, n) for n in names]
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'processing', attempt = %s, lease_token = %s, lease_owner = %s, "
|
||||
"lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(attempt, token, worker, lease_seconds, job_id))
|
||||
await conn.execute(
|
||||
"INSERT INTO job_attempts (token, job_id, attempt, worker, source, planned_keys) VALUES (%s, %s, %s, %s, %s, %s)",
|
||||
(token, job_id, attempt, worker, source, planned))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = %s AND status = 'queued'",
|
||||
(attachment_id,))
|
||||
await event(conn, job_id, "claimed", actor, attempt=attempt, source=source, token=token)
|
||||
return Claim(str(job_id), str(attachment_id), version, attempt, max_attempts, token, source, source_key,
|
||||
content_type, size, bytes(sha), write_original)
|
||||
|
||||
|
||||
async def heartbeat(conn: psycopg.AsyncConnection, claim: Claim, lease_seconds: float) -> bool:
|
||||
"""Extend the lease; False = the lease was lost (expired and taken over): stop the attempt."""
|
||||
cur = await conn.execute(
|
||||
"UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => %s) "
|
||||
"WHERE id = %s AND state = 'processing' AND lease_token = %s", (lease_seconds, claim.job_id, claim.token))
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
async def _holds_lease(conn: psycopg.AsyncConnection, claim: Claim) -> bool:
|
||||
cur = await conn.execute("SELECT state = 'processing' AND lease_token = %s FROM jobs WHERE id = %s FOR UPDATE",
|
||||
(claim.token, claim.job_id))
|
||||
row = await cur.fetchone()
|
||||
return bool(row and row[0])
|
||||
|
||||
|
||||
async def complete(conn: psycopg.AsyncConnection, claim: Claim, variants, worker: str) -> str:
|
||||
"""Publish the result of an attempt atomically: variant rows + attachment ready + job succeeded.
|
||||
Returns succeeded | superseded | fenced (this attempt lost its lease: nothing written)."""
|
||||
actor = "worker:" + worker
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced"
|
||||
cur = await conn.execute("SELECT published_version FROM attachments WHERE id = %s FOR UPDATE", (claim.attachment_id,))
|
||||
(published,) = await cur.fetchone()
|
||||
if published is not None and published >= claim.pipeline_version:
|
||||
await _end_attempt(conn, claim, "superseded", None)
|
||||
await _finish(conn, claim.job_id, "superseded", None)
|
||||
await event(conn, claim.job_id, "superseded", actor, attempt=claim.attempt, published_version=published)
|
||||
return "superseded"
|
||||
for v in variants:
|
||||
await conn.execute(
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, "
|
||||
"size_bytes, width, height, sha256, attempt_token) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(claim.attachment_id, claim.pipeline_version, v.name, claim.key(v.name), v.content_type, len(v.data),
|
||||
v.width, v.height, v.sha256, claim.token))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'ready', published_version = %s, error_code = NULL, failed_at = NULL, "
|
||||
"object_key = COALESCE(object_key, %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(claim.pipeline_version, claim.key("original") if claim.write_original else None, claim.attachment_id))
|
||||
await _end_attempt(conn, claim, "succeeded", None)
|
||||
await _finish(conn, claim.job_id, "succeeded", None)
|
||||
await event(conn, claim.job_id, "succeeded", actor, attempt=claim.attempt, pipeline_version=claim.pipeline_version)
|
||||
return "succeeded"
|
||||
|
||||
|
||||
async def retry_or_fail(conn: psycopg.AsyncConnection, claim: Claim, code: str, permanent: bool, worker: str,
|
||||
base: float, cap: float) -> tuple[str, float]:
|
||||
"""After a failed attempt: permanent error or no attempts left -> failed (failed registry);
|
||||
otherwise queued again after a jittered backoff. Returns (outcome, delay seconds)."""
|
||||
actor = "worker:" + worker
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced", 0.0
|
||||
if permanent or claim.attempt >= claim.max_attempts:
|
||||
final = code if permanent else "retry_exhausted"
|
||||
await _end_attempt(conn, claim, "failed", code)
|
||||
await _fail(conn, claim.job_id, claim.attachment_id, final, actor, claim.attempt, cause=code)
|
||||
return "failed", 0.0
|
||||
delay = backoff_delay(claim.attempt, base, cap)
|
||||
await _end_attempt(conn, claim, "retry", code)
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, error_code = %s, "
|
||||
"available_at = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(code, delay, claim.job_id))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
|
||||
(claim.attachment_id,))
|
||||
await conn.execute(
|
||||
"INSERT INTO outbox (job_id, attempt, available_at) "
|
||||
"VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))", (claim.job_id, claim.attempt + 1, delay))
|
||||
await event(conn, claim.job_id, "retry_scheduled", actor, attempt=claim.attempt, error_code=code,
|
||||
delay_s=round(delay, 3))
|
||||
return "retry", delay
|
||||
|
||||
|
||||
async def release(conn: psycopg.AsyncConnection, claim: Claim, worker: str) -> str:
|
||||
"""Graceful stop of a worker with an attempt still running: give the job back at once
|
||||
(without waiting for the lease to expire). The claim already counted as an attempt."""
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced"
|
||||
await _end_attempt(conn, claim, "abandoned", "worker_shutdown")
|
||||
if claim.attempt >= claim.max_attempts:
|
||||
await _fail(conn, claim.job_id, claim.attachment_id, "retry_exhausted", "worker:" + worker, claim.attempt,
|
||||
cause="worker_shutdown")
|
||||
return "failed"
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (claim.job_id,))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
|
||||
(claim.attachment_id,))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (claim.job_id, claim.attempt + 1))
|
||||
await event(conn, claim.job_id, "released", "worker:" + worker, attempt=claim.attempt)
|
||||
return "released"
|
||||
|
||||
|
||||
async def _end_attempt(conn: psycopg.AsyncConnection, claim: Claim, outcome: str, code: str | None) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE job_attempts SET outcome = %s, error_code = %s, finished_at = clock_timestamp() "
|
||||
"WHERE token = %s AND outcome = 'running'", (outcome, code, claim.token))
|
||||
|
||||
|
||||
async def _finish(conn: psycopg.AsyncConnection, job_id, state: str, code: str | None) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = %s, error_code = %s, lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (state, code, job_id))
|
||||
|
||||
|
||||
async def _fail(conn: psycopg.AsyncConnection, job_id, attachment_id, code: str, actor: str, attempt: int,
|
||||
**detail) -> None:
|
||||
"""Job -> failed (registry). The attachment becomes failed only if it is not ready: a failed
|
||||
reprocess of a newer version leaves the published result in place."""
|
||||
await _finish(conn, job_id, "failed", code)
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = %s, failed_at = clock_timestamp(), "
|
||||
"updated_at = clock_timestamp() WHERE id = %s AND status IN ('queued', 'processing')", (code, attachment_id))
|
||||
await event(conn, job_id, "failed", actor, attempt=attempt, error_code=code, **detail)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ cleanup (worker)
|
||||
async def staging_to_delete(conn: psycopg.AsyncConnection, retention_seconds: int, limit: int = 50) -> list[str]:
|
||||
"""Candidates only (no lock): ready attachments (staging no longer needed) and failed ones
|
||||
older than the retention. The decision is re-checked under the row lock in mark_staging_deleting."""
|
||||
cur = await conn.execute(
|
||||
"SELECT id FROM attachments WHERE staging_state IN ('present', 'deleting') AND (status = 'ready' OR "
|
||||
"(status = 'failed' AND failed_at < clock_timestamp() - make_interval(secs => %s))) "
|
||||
"ORDER BY updated_at LIMIT %s", (retention_seconds, limit))
|
||||
return [str(r[0]) for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def mark_staging_deleting(conn: psycopg.AsyncConnection, attachment_id: str, retention_seconds: int) -> str | None:
|
||||
"""Under the attachment row lock, decide AGAIN from the committed state and mark the staging copy
|
||||
`deleting` BEFORE the S3 DELETE. A replay that committed in between made the row queued, so it
|
||||
no longer matches; a replay that comes later sees `deleting` and refuses. Queued/processing
|
||||
rows never match (and the CHECK attachments_active_has_source forbids it anyway)."""
|
||||
cur = await conn.execute(
|
||||
"UPDATE attachments SET staging_state = 'deleting' " # internal state: updated_at stays (public field)
|
||||
"WHERE id = %s AND staging_state IN ('present', 'deleting') AND (status = 'ready' OR (status = 'failed' "
|
||||
"AND failed_at < clock_timestamp() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM jobs j "
|
||||
"WHERE j.attachment_id = attachments.id AND j.state IN ('queued', 'processing')))) RETURNING staging_key",
|
||||
(attachment_id, retention_seconds))
|
||||
row = await cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
async def mark_staging_deleted(conn: psycopg.AsyncConnection, attachment_id: str) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET staging_state = 'deleted' WHERE id = %s AND staging_state = 'deleting'", (attachment_id,))
|
||||
|
||||
|
||||
async def attempts_to_clean(conn: psycopg.AsyncConnection, grace_seconds: int, limit: int = 50) -> list[str]:
|
||||
cur = await conn.execute(
|
||||
"SELECT token FROM job_attempts WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
|
||||
"AND objects_cleaned_at IS NULL AND finished_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"ORDER BY finished_at LIMIT %s", (grace_seconds, limit))
|
||||
return [r[0].hex for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def lock_attempt_for_cleanup(conn: psycopg.AsyncConnection, token: str) -> list[str] | None:
|
||||
"""Keys of an attempt that can never publish: it ended without success, it is not the lease
|
||||
holder of its job (tokens are never reused) and nothing published references its keys."""
|
||||
cur = await conn.execute(
|
||||
"SELECT ja.planned_keys FROM job_attempts ja JOIN jobs j ON j.id = ja.job_id "
|
||||
"WHERE ja.token = %s AND ja.objects_cleaned_at IS NULL "
|
||||
"AND ja.outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
|
||||
"AND j.lease_token IS DISTINCT FROM ja.token FOR UPDATE OF ja", (token,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
keys = list(row[0])
|
||||
cur = await conn.execute(
|
||||
"SELECT EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = ANY(%s)) "
|
||||
"OR EXISTS (SELECT 1 FROM attachments WHERE object_key = ANY(%s))", (keys, keys))
|
||||
if (await cur.fetchone())[0]:
|
||||
return None # published: never delete (would be a bug elsewhere; logged by the caller)
|
||||
return keys
|
||||
|
||||
|
||||
async def mark_attempt_cleaned(conn: psycopg.AsyncConnection, token: str) -> None:
|
||||
await conn.execute("UPDATE job_attempts SET objects_cleaned_at = clock_timestamp() WHERE token = %s", (token,))
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Versioned image pipeline (lab 5): WHAT the worker builds for one attachment. Pure definitions,
|
||||
no I/O; the pixels are produced by imaging.py in a child process.
|
||||
|
||||
Every pipeline version builds the same three variants with the geometry of the contract; versions
|
||||
differ only in encoder parameters, so the published version is visible in the bytes (sha256):
|
||||
|
||||
thumbnail JPEG, fits into 256x256, keeps the aspect ratio, never upscales, floor rounding
|
||||
(minimum 1 px), EXIF orientation applied, alpha composited onto white;
|
||||
crop JPEG, centred square 128x128 (small images ARE upscaled, the contract allows it);
|
||||
optimized WebP, fits into 1280x1280, never upscales, alpha kept.
|
||||
|
||||
Metadata: nothing of the source is copied into a variant - no EXIF (orientation is applied to
|
||||
the pixels instead), no XMP, no ICC profile, no comments (the pixels are treated as sRGB).
|
||||
The original is published byte for byte and keeps everything.
|
||||
|
||||
Track 2: the version of a job is fixed when the job is created (PIPELINE_VERSION for uploads,
|
||||
`jobctl reprocess --pipeline N` later). A result is published only if its version is greater
|
||||
than the published one, so an old job can never overwrite a newer result.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
THUMBNAIL_BOX = 256
|
||||
CROP_SIDE = 128
|
||||
OPTIMIZED_BOX = 1280
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
CONTENT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Pipeline:
|
||||
version: int
|
||||
jpeg_quality: int # thumbnail and crop: baseline JPEG, 4:2:0, optimized Huffman tables
|
||||
webp_quality: int # optimized: lossy WebP
|
||||
webp_method: int # 0 (fast) .. 6 (slow, smaller)
|
||||
|
||||
|
||||
PIPELINES = {
|
||||
1: Pipeline(1, jpeg_quality=85, webp_quality=80, webp_method=4),
|
||||
# Versions 2 and 3 exist for the track 2 experiments (reprocess, reorder, stale jobs):
|
||||
# different encoder settings -> different bytes, identical geometry.
|
||||
2: Pipeline(2, jpeg_quality=80, webp_quality=75, webp_method=4),
|
||||
3: Pipeline(3, jpeg_quality=90, webp_quality=85, webp_method=5),
|
||||
}
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
"""Size inside box x box keeping the aspect ratio, never upscaling, rounded DOWN, >= 1 px.
|
||||
Integer arithmetic: 320x200 -> 256x160 exactly, 1x1000 -> 1x256 (0.256 -> 1 px minimum)."""
|
||||
if width <= box and height <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def center_square(width: int, height: int) -> tuple[int, int, int, int]:
|
||||
"""Crop box (left, top, right, bottom) of the centred square with side min(width, height)."""
|
||||
side = min(width, height)
|
||||
left = (width - side) // 2
|
||||
top = (height - side) // 2
|
||||
return left, top, left + side, top + side
|
||||
@@ -1,437 +0,0 @@
|
||||
"""Reconciler of the two stores (lab 4, track 2): S3 objects vs attachment rows in PostgreSQL.
|
||||
|
||||
docker compose run --rm reconciler # dry-run: report only (default)
|
||||
docker compose run --rm reconciler --apply # fix what is safe to fix
|
||||
docker compose run --rm reconciler --verify-checksums # also read every object (SHA-256)
|
||||
|
||||
How it walks: both sides are read as key-ordered streams and merge-joined - ListObjectsV2
|
||||
pages (prefix o/, byte order) against keyset pages of `attachments ORDER BY object_key`
|
||||
(COLLATE "C" = the same byte order, unique index). Memory does not depend on the bucket size;
|
||||
cost is ~N/1000 S3 list requests + N/page DB pages (measured: docs/CONSISTENCY.md).
|
||||
|
||||
What it finds and what --apply does (nothing else is ever changed):
|
||||
|
||||
kind condition --apply
|
||||
orphan_object object, no row, older than --grace delete the object
|
||||
stale_intent row 'pending' older than --grace (+/- object) delete object, then row
|
||||
missing_object row 'ready', object absent, older than --grace quarantine the row
|
||||
size_mismatch row 'ready', object size != size_bytes quarantine the row
|
||||
checksum_mismatch row 'ready', SHA-256 differs (--verify-checksums) quarantine the row
|
||||
restored_object row quarantined, object present and correct again remove the quarantine
|
||||
(a checksum quarantine only with --verify-checksums)
|
||||
fresh_* the same, but younger than --grace nothing (in-flight upload)
|
||||
|
||||
Safety:
|
||||
* dry-run is read-only BY CONSTRUCTION: the PostgreSQL session runs with
|
||||
default_transaction_read_only=on and the S3 wrapper has no write methods, so even a bug in
|
||||
the planner cannot modify a store;
|
||||
* ready rows are never deleted - a used (or unused) ready attachment can only be quarantined,
|
||||
which is reversible; objects that have a row are never deleted unless the row is a stale
|
||||
intent; anything younger than --grace is never touched;
|
||||
* every action re-checks its condition right before acting, under a row lock (FOR UPDATE)
|
||||
where a row exists, so the live API racing with the reconciler cannot be hurt;
|
||||
* object first, row second: an interrupted run leaves a state the next run repairs;
|
||||
re-running is idempotent (the second run finds nothing to do);
|
||||
* safety valve: --apply refuses to delete more than --max-orphan-fraction of the scanned
|
||||
objects (pointing it at the wrong/empty database would otherwise wipe the bucket).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import psycopg
|
||||
|
||||
from .config import ConfigError, Settings, _float, _secret, s3_settings
|
||||
from .errors import Unavailable
|
||||
from .storage import OBJECT_PREFIX, ListedObject, ObjectMissing, Storage
|
||||
|
||||
KINDS = ("orphan_object", "stale_intent", "missing_object", "size_mismatch", "checksum_mismatch",
|
||||
"restored_object", "fresh_orphan_object", "fresh_intent", "fresh_missing_object")
|
||||
MIN_SAFE_GRACE = 60.0 # > the longest possible upload (queue 5 s + body 30 s + verify 10 s + S3)
|
||||
ACTION_OF = {"orphan_object": "delete_object", "stale_intent": "delete_intent", "missing_object": "quarantine",
|
||||
"size_mismatch": "quarantine", "checksum_mismatch": "quarantine", "restored_object": "unquarantine"}
|
||||
|
||||
|
||||
def log(text: str) -> None:
|
||||
print(f"reconcile: {text}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Row:
|
||||
id: str
|
||||
key: str
|
||||
status: str
|
||||
size: int
|
||||
sha256: bytes
|
||||
created_at: dt.datetime
|
||||
updated_at: dt.datetime
|
||||
lost_reason: str | None
|
||||
used: bool
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Finding:
|
||||
kind: str
|
||||
key: str
|
||||
attachment_id: str | None = None
|
||||
used: bool = False
|
||||
detail: str = ""
|
||||
result: str = "planned" # planned | applied | skipped:<why> | failed:<why>
|
||||
|
||||
|
||||
@dataclass
|
||||
class Stats:
|
||||
objects: int = 0
|
||||
rows: int = 0
|
||||
consistent: int = 0
|
||||
s3_list_requests: int = 0
|
||||
s3_head_requests: int = 0
|
||||
s3_get_bytes: int = 0
|
||||
db_pages: int = 0
|
||||
|
||||
|
||||
class ReadOnlyStorage:
|
||||
"""The dry-run view of S3: listing and reading only - there is no delete to call."""
|
||||
|
||||
def __init__(self, storage: Storage):
|
||||
self._s = storage
|
||||
|
||||
async def list_page(self, *args, **kwargs):
|
||||
return await self._s.list_page(*args, **kwargs)
|
||||
|
||||
async def head(self, key: str):
|
||||
return await self._s.head(key)
|
||||
|
||||
async def read_all(self, key: str, limit: int) -> bytes:
|
||||
return await self._s.read_all(key, limit)
|
||||
|
||||
|
||||
class Reconciler:
|
||||
def __init__(self, conn: psycopg.AsyncConnection, storage: Storage | ReadOnlyStorage, *, grace: float,
|
||||
page_size: int, verify: bool, apply: bool):
|
||||
self.conn = conn
|
||||
self.s3 = storage
|
||||
self.grace = grace
|
||||
self.page_size = page_size
|
||||
self.verify = verify
|
||||
self.apply = apply
|
||||
self.stats = Stats()
|
||||
self.findings: list[Finding] = []
|
||||
|
||||
# ---------------------------------------------------------- streams
|
||||
async def objects(self) -> AsyncIterator[ListedObject]:
|
||||
after = None
|
||||
while True:
|
||||
page, more = await self.s3.list_page(OBJECT_PREFIX, after, self.page_size)
|
||||
self.stats.s3_list_requests += 1
|
||||
for item in page:
|
||||
self.stats.objects += 1
|
||||
yield item
|
||||
if not more or not page:
|
||||
return
|
||||
after = page[-1].key
|
||||
|
||||
async def rows(self) -> AsyncIterator[Row]:
|
||||
after = ""
|
||||
while True:
|
||||
cur = await self.conn.execute(
|
||||
"SELECT a.id, a.object_key, a.status, a.size_bytes, a.sha256, a.created_at, a.updated_at, "
|
||||
"a.lost_reason, EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) "
|
||||
"FROM attachments a WHERE a.object_key > %s ORDER BY a.object_key LIMIT %s",
|
||||
(after, self.page_size))
|
||||
page = await cur.fetchall()
|
||||
self.stats.db_pages += 1
|
||||
for r in page:
|
||||
self.stats.rows += 1
|
||||
yield Row(str(r[0]), r[1], r[2], r[3], bytes(r[4]), r[5], r[6], r[7], r[8])
|
||||
if len(page) < self.page_size:
|
||||
return
|
||||
after = page[-1][1]
|
||||
|
||||
# ---------------------------------------------------------- planning (read-only)
|
||||
async def scan(self) -> None:
|
||||
cur = await self.conn.execute("SELECT clock_timestamp()")
|
||||
self.db_now = (await cur.fetchone())[0]
|
||||
self.s3_now = time.time()
|
||||
objects, rows = self.objects(), self.rows()
|
||||
obj = await anext(objects, None)
|
||||
row = await anext(rows, None)
|
||||
while obj is not None or row is not None:
|
||||
if row is None or (obj is not None and obj.key < row.key):
|
||||
self.object_only(obj)
|
||||
obj = await anext(objects, None)
|
||||
elif obj is None or row.key < obj.key:
|
||||
self.row_only(row)
|
||||
row = await anext(rows, None)
|
||||
else:
|
||||
await self.both(obj, row)
|
||||
obj = await anext(objects, None)
|
||||
row = await anext(rows, None)
|
||||
|
||||
def row_old(self, row: Row) -> bool:
|
||||
return (self.db_now - max(row.created_at, row.updated_at)).total_seconds() > self.grace
|
||||
|
||||
def object_only(self, obj: ListedObject) -> None:
|
||||
old = self.s3_now - obj.last_modified_ts > self.grace
|
||||
self.add(Finding("orphan_object" if old else "fresh_orphan_object", obj.key))
|
||||
|
||||
def row_only(self, row: Row) -> None:
|
||||
if row.status == "pending":
|
||||
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
|
||||
detail="object absent"))
|
||||
elif row.lost_reason is not None:
|
||||
self.stats.consistent += 1 # already quarantined, still missing: nothing new
|
||||
else:
|
||||
self.add(Finding("missing_object" if self.row_old(row) else "fresh_missing_object", row.key, row.id,
|
||||
used=row.used))
|
||||
|
||||
async def both(self, obj: ListedObject, row: Row) -> None:
|
||||
if row.status == "pending":
|
||||
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
|
||||
detail="object present"))
|
||||
return
|
||||
problem = await self.object_problem(row, obj.size)
|
||||
if problem:
|
||||
if row.lost_reason is None:
|
||||
self.add(Finding(problem, row.key, row.id, used=row.used))
|
||||
else:
|
||||
self.stats.consistent += 1 # quarantined and still broken
|
||||
elif row.lost_reason == "checksum_mismatch" and not self.verify:
|
||||
# Same size, but this pass does not read the bytes: it cannot prove the object is the
|
||||
# original again, so a checksum quarantine is lifted only by --verify-checksums.
|
||||
self.stats.consistent += 1
|
||||
elif row.lost_reason is not None:
|
||||
self.add(Finding("restored_object", row.key, row.id, used=row.used))
|
||||
else:
|
||||
self.stats.consistent += 1
|
||||
|
||||
async def object_problem(self, row: Row, size: int) -> str | None:
|
||||
if size != row.size:
|
||||
return "size_mismatch"
|
||||
if self.verify:
|
||||
data = await self.s3.read_all(row.key, row.size)
|
||||
self.stats.s3_get_bytes += len(data)
|
||||
if hashlib.sha256(data).digest() != row.sha256:
|
||||
return "checksum_mismatch"
|
||||
return None
|
||||
|
||||
def add(self, finding: Finding) -> None:
|
||||
if finding.kind not in ACTION_OF:
|
||||
finding.result = "not_actionable"
|
||||
self.findings.append(finding)
|
||||
|
||||
# ---------------------------------------------------------- actions (--apply only)
|
||||
async def run_actions(self, max_orphan_fraction: float) -> None:
|
||||
orphans = sum(1 for f in self.findings if f.kind == "orphan_object")
|
||||
if self.stats.objects and orphans > max_orphan_fraction * self.stats.objects:
|
||||
raise SafetyValve(f"{orphans} of {self.stats.objects} objects look orphaned "
|
||||
f"(> {max_orphan_fraction:.0%}); wrong database? nothing was changed")
|
||||
handlers = {"delete_object": self.delete_object, "delete_intent": self.delete_intent,
|
||||
"quarantine": self.quarantine, "unquarantine": self.unquarantine}
|
||||
for finding in self.findings:
|
||||
action = ACTION_OF.get(finding.kind)
|
||||
if action is None:
|
||||
continue
|
||||
try:
|
||||
finding.result = await handlers[action](finding)
|
||||
except (Unavailable, psycopg.OperationalError) as exc:
|
||||
finding.result = f"failed:{type(exc).__name__}"
|
||||
raise # a store is down: stop; the next run continues from the committed state
|
||||
|
||||
async def delete_object(self, f: Finding) -> str:
|
||||
cur = await self.conn.execute("SELECT 1 FROM attachments WHERE object_key = %s", (f.key,))
|
||||
if await cur.fetchone():
|
||||
return "skipped:row_appeared"
|
||||
try:
|
||||
head = await self.s3.head(f.key)
|
||||
self.stats.s3_head_requests += 1
|
||||
except ObjectMissing:
|
||||
return "skipped:already_gone"
|
||||
if time.time() - head.last_modified_ts <= self.grace:
|
||||
return "skipped:object_rewritten_recently"
|
||||
# No row names this key and the object is older than the grace period. Rows are always
|
||||
# written BEFORE their object and keys are random and never reused, so no upload can
|
||||
# still claim it.
|
||||
await self.s3.delete(f.key)
|
||||
return "applied"
|
||||
|
||||
async def delete_intent(self, f: Finding) -> str:
|
||||
async with self.conn.transaction():
|
||||
cur = await self.conn.execute(
|
||||
"SELECT 1 FROM attachments WHERE id = %s AND status = 'pending' "
|
||||
"AND greatest(created_at, updated_at) < clock_timestamp() - make_interval(secs => %s) FOR UPDATE",
|
||||
(f.attachment_id, self.grace))
|
||||
if await cur.fetchone() is None:
|
||||
return "skipped:no_longer_stale_intent"
|
||||
await self.s3.delete(f.key) # object first (idempotent), then the row
|
||||
await self.conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'",
|
||||
(f.attachment_id,))
|
||||
return "applied"
|
||||
|
||||
async def quarantine(self, f: Finding) -> str:
|
||||
async with self.conn.transaction():
|
||||
cur = await self.conn.execute(
|
||||
"SELECT size_bytes, sha256 FROM attachments WHERE id = %s AND status = 'ready' "
|
||||
"AND lost_at IS NULL FOR UPDATE", (f.attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return "skipped:row_changed"
|
||||
reason = await self.current_problem(f.key, row[0], bytes(row[1]))
|
||||
if reason is None:
|
||||
return "skipped:object_ok_now"
|
||||
await self.conn.execute(
|
||||
"UPDATE attachments SET lost_at = clock_timestamp(), lost_reason = %s WHERE id = %s",
|
||||
(reason, f.attachment_id))
|
||||
return "applied"
|
||||
|
||||
async def unquarantine(self, f: Finding) -> str:
|
||||
async with self.conn.transaction():
|
||||
cur = await self.conn.execute(
|
||||
"SELECT size_bytes, sha256, lost_reason FROM attachments WHERE id = %s AND lost_at IS NOT NULL FOR UPDATE",
|
||||
(f.attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return "skipped:row_changed"
|
||||
if row[2] == "checksum_mismatch" and not self.verify:
|
||||
return "skipped:needs_verify_checksums"
|
||||
if await self.current_problem(f.key, row[0], bytes(row[1])) is not None:
|
||||
return "skipped:object_still_bad"
|
||||
await self.conn.execute("UPDATE attachments SET lost_at = NULL, lost_reason = NULL WHERE id = %s",
|
||||
(f.attachment_id,))
|
||||
return "applied"
|
||||
|
||||
async def current_problem(self, key: str, size: int, sha256: bytes) -> str | None:
|
||||
"""Fresh look at the object right before changing the row (the listing may be stale)."""
|
||||
try:
|
||||
head = await self.s3.head(key)
|
||||
self.stats.s3_head_requests += 1
|
||||
except ObjectMissing:
|
||||
return "missing_object"
|
||||
if head.size != size:
|
||||
return "size_mismatch"
|
||||
if self.verify:
|
||||
data = await self.s3.read_all(key, size)
|
||||
self.stats.s3_get_bytes += len(data)
|
||||
if hashlib.sha256(data).digest() != sha256:
|
||||
return "checksum_mismatch"
|
||||
return None
|
||||
|
||||
# ---------------------------------------------------------- report
|
||||
def report(self, mode: str, seconds: float, error: str | None, sample: int) -> dict:
|
||||
kinds = Counter(f.kind for f in self.findings)
|
||||
results = Counter(f.result.split(":")[0] for f in self.findings if f.kind in ACTION_OF)
|
||||
samples = {}
|
||||
for f in self.findings:
|
||||
items = samples.setdefault(f.kind, [])
|
||||
if len(items) < sample:
|
||||
items.append({"key": f.key, "attachment_id": f.attachment_id, "used": f.used,
|
||||
"result": f.result, **({"detail": f.detail} if f.detail else {})})
|
||||
return {
|
||||
"mode": mode, "grace_seconds": self.grace, "verify_checksums": self.verify,
|
||||
"duration_seconds": round(seconds, 3), "error": error,
|
||||
"scanned": {"objects": self.stats.objects, "rows": self.stats.rows, "consistent": self.stats.consistent},
|
||||
"findings": {k: kinds.get(k, 0) for k in KINDS},
|
||||
"used_attachments_in_findings": sum(1 for f in self.findings if f.used),
|
||||
"actions": {"planned": sum(1 for f in self.findings if f.kind in ACTION_OF),
|
||||
"applied": results.get("applied", 0), "skipped": results.get("skipped", 0),
|
||||
"failed": results.get("failed", 0)},
|
||||
"cost": {"s3_list_requests": self.stats.s3_list_requests, "s3_head_requests": self.stats.s3_head_requests,
|
||||
"s3_get_bytes": self.stats.s3_get_bytes, "db_pages": self.stats.db_pages,
|
||||
"page_size": self.page_size},
|
||||
"samples": samples,
|
||||
}
|
||||
|
||||
|
||||
class SafetyValve(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def arguments(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
p = argparse.ArgumentParser(prog="python -m messenger.reconcile", description=__doc__.split("\n")[0])
|
||||
p.add_argument("--apply", action="store_true", help="fix findings (default: dry-run, read-only)")
|
||||
p.add_argument("--grace", type=float, default=3600.0,
|
||||
help="seconds; anything younger is never touched (default 3600, >= PENDING_GRACE_SECONDS)")
|
||||
p.add_argument("--allow-small-grace", action="store_true",
|
||||
help="permit --grace below 60 s (tests only: a grace shorter than an upload could remove the "
|
||||
"intent of an upload that is still running; that upload then fails with 503)")
|
||||
p.add_argument("--page-size", type=int, default=1000, help="S3 list / DB page size (1..1000)")
|
||||
p.add_argument("--verify-checksums", action="store_true", help="read every ready object and compare SHA-256")
|
||||
p.add_argument("--samples", type=int, default=20, help="keys listed per finding kind in the report")
|
||||
p.add_argument("--max-orphan-fraction", type=float, default=0.5,
|
||||
help="--apply refuses if more than this share of objects look orphaned (default 0.5)")
|
||||
args = p.parse_args(argv)
|
||||
if not 1 <= args.page_size <= 1000:
|
||||
p.error("--page-size must be 1..1000")
|
||||
if args.grace < 1 or (args.grace < MIN_SAFE_GRACE and not args.allow_small_grace):
|
||||
p.error(f"--grace must be >= {MIN_SAFE_GRACE:.0f} s (or >= 1 s with --allow-small-grace)")
|
||||
if not 0 < args.max_orphan_fraction <= 1:
|
||||
p.error("--max-orphan-fraction must be in (0, 1]")
|
||||
return args
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> int:
|
||||
url = _secret("DATABASE_URL", required=True)
|
||||
base = s3_settings()
|
||||
settings = Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024,
|
||||
database_url=url, **base)
|
||||
timeout_ms = int(_float("DB_TIMEOUT_SECONDS", 10.0, 1.0, 120.0) * 1000)
|
||||
options = f"-c statement_timeout={timeout_ms} -c lock_timeout={timeout_ms // 2}"
|
||||
if not args.apply:
|
||||
options += " -c default_transaction_read_only=on" # dry-run: PostgreSQL itself refuses writes
|
||||
mode = "apply" if args.apply else "dry-run"
|
||||
storage = Storage(settings)
|
||||
await storage.open()
|
||||
started = time.perf_counter()
|
||||
error = None
|
||||
code = 0
|
||||
try:
|
||||
conn = await psycopg.AsyncConnection.connect(url, autocommit=True, connect_timeout=5, options=options,
|
||||
application_name=f"messenger-reconcile-{mode}")
|
||||
except psycopg.OperationalError as exc:
|
||||
await storage.close()
|
||||
error = f"store_unavailable: database {type(exc).__name__}"
|
||||
print(json.dumps({"mode": mode, "error": error}, ensure_ascii=False))
|
||||
log(error)
|
||||
return 1
|
||||
rec = Reconciler(conn, storage if args.apply else ReadOnlyStorage(storage), grace=args.grace,
|
||||
page_size=args.page_size, verify=args.verify_checksums, apply=args.apply)
|
||||
try:
|
||||
log(f"{mode}: scanning bucket {settings.s3_bucket} (prefix {OBJECT_PREFIX}) against table attachments")
|
||||
await rec.scan()
|
||||
log(f"scan done: {rec.stats.objects} objects, {rec.stats.rows} rows, {len(rec.findings)} findings")
|
||||
if args.apply:
|
||||
await rec.run_actions(args.max_orphan_fraction)
|
||||
except SafetyValve as exc:
|
||||
error, code = f"safety_valve: {exc}", 3
|
||||
except (Unavailable, psycopg.OperationalError) as exc:
|
||||
error, code = f"store_unavailable: {type(exc).__name__}", 1
|
||||
finally:
|
||||
await conn.close()
|
||||
await storage.close()
|
||||
print(json.dumps(rec.report(mode, time.perf_counter() - started, error, args.samples), ensure_ascii=False,
|
||||
indent=1))
|
||||
if error:
|
||||
log(error)
|
||||
return code
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = arguments(argv)
|
||||
try:
|
||||
return asyncio.run(run(args))
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user