forked from mtusi2026/mtusi2026lab4
lab4 трек 2: reconciler S3/PostgreSQL, тесты вложений, отказов и согласованности
- python -m messenger.reconcile: merge-join листинга S3 и attachments по object_key; dry-run read-only конструктивно (default_transaction_read_only + S3 без записи), --apply: orphan/stale intent удаляются, ready-строки только в карантин (обратимо), перепроверка под FOR UPDATE, предохранитель от массового удаления; - attachment_ids хранится в строке сообщения (история остаётся одним index range scan), message_attachments — для FK и обратного поиска; - семафор полной проверки изображений (IMAGE_VERIFY_CONCURRENCY); - тесты: вложения (56), отказ/пауза S3 и деградированный режим LB, failover загрузки, приватность bucket, FAULT_POINTS после PUT/после COMMIT, janitor, reconciler; - бенчмарки памяти загрузок и стоимости обхода reconciler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
335df4b2b2
commit
a2d867bec6
@@ -389,7 +389,7 @@ async def upload_attachment(request: Request) -> JSONResponse:
|
||||
except asyncio.TimeoutError:
|
||||
raise attachments.Busy("Слишком много одновременных загрузок, повторите позже") from None
|
||||
try:
|
||||
upload = await attachments.read_image(reader, settings, declared)
|
||||
upload = await attachments.read_image(reader, settings, declared, request.app.state.verify_slots)
|
||||
finally:
|
||||
slots.release()
|
||||
except ApiError:
|
||||
@@ -518,7 +518,8 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
|
||||
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
|
||||
"upload_concurrency": settings.upload_concurrency, "pending_grace_s": settings.pending_grace_seconds,
|
||||
"upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency,
|
||||
"pending_grace_s": settings.pending_grace_seconds,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
tasks = [asyncio.create_task(purge_loop())]
|
||||
if settings.janitor_interval_seconds > 0:
|
||||
@@ -567,5 +568,6 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
app.state.sessions = sessions
|
||||
app.state.storage = storage
|
||||
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
|
||||
app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency)
|
||||
app.state.draining = False
|
||||
return app
|
||||
|
||||
@@ -227,7 +227,7 @@ def declared_length(request: Request, limit: int) -> int | None:
|
||||
return length
|
||||
|
||||
|
||||
async def read_image(reader: BodyReader, settings: Settings, declared: str) -> Upload:
|
||||
async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore) -> Upload:
|
||||
"""Body -> verified image. Memory: at most MAX_UPLOAD_BYTES per upload (bytearray); the format
|
||||
and the pixel count are known after the first bytes, so a picture that is too big or not a
|
||||
PNG/JPEG is rejected without reading/decoding the rest."""
|
||||
@@ -260,8 +260,9 @@ async def read_image(reader: BodyReader, settings: Settings, declared: str) -> U
|
||||
data = bytes(buffer)
|
||||
del buffer
|
||||
try:
|
||||
await images.verify(data, info, timeout=settings.image_verify_timeout_seconds,
|
||||
jpeg_max_memory_mb=settings.jpeg_max_memory_mb)
|
||||
async with verify_slots:
|
||||
await images.verify(data, info, timeout=settings.image_verify_timeout_seconds,
|
||||
jpeg_max_memory_mb=settings.jpeg_max_memory_mb)
|
||||
except images.ImageError as exc:
|
||||
raise _image_error(exc) from None
|
||||
except asyncio.TimeoutError:
|
||||
|
||||
@@ -130,6 +130,7 @@ class Settings:
|
||||
upload_queue_timeout_seconds: float = 5.0
|
||||
upload_read_timeout_seconds: float = 30.0
|
||||
image_verify_timeout_seconds: float = 10.0
|
||||
image_verify_concurrency: int = 1
|
||||
jpeg_max_memory_mb: int = 256
|
||||
pending_grace_seconds: int = 900
|
||||
janitor_interval_seconds: float = 60.0
|
||||
@@ -223,6 +224,9 @@ def s3_settings(*, credentials_required: bool = True) -> dict:
|
||||
upload_queue_timeout_seconds=_float("UPLOAD_QUEUE_TIMEOUT_SECONDS", 5.0, 0.0, 60.0),
|
||||
upload_read_timeout_seconds=_float("UPLOAD_READ_TIMEOUT_SECONDS", 30.0, 1.0, 300.0),
|
||||
image_verify_timeout_seconds=_float("IMAGE_VERIFY_TIMEOUT_SECONDS", 10.0, 1.0, 120.0),
|
||||
# Full checks running at once per replica: a strict JPEG decode of a 40 Mpx progressive
|
||||
# file needs up to ~120-240 MB of coefficient buffers (capped by JPEG_MAX_MEMORY_MB).
|
||||
image_verify_concurrency=_int("IMAGE_VERIFY_CONCURRENCY", 1, 1, 16),
|
||||
jpeg_max_memory_mb=_int("JPEG_MAX_MEMORY_MB", 256, 16, 2048),
|
||||
# An intent row still `pending` after this long belongs to a failed upload: the janitor
|
||||
# deletes its object and the row. Far above the longest possible upload (~45 s).
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
"""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
|
||||
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 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 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 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())
|
||||
+11
-13
@@ -219,8 +219,9 @@ async def _insert_message(conn: psycopg.AsyncConnection, message_id: uuid.UUID,
|
||||
(chat_id,))
|
||||
(created_at,) = await cur.fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||
(message_id, chat_id, user_id, _b(text), created_at))
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s::uuid[])",
|
||||
(message_id, chat_id, user_id, _b(text), created_at, attachment_ids))
|
||||
if attachment_ids:
|
||||
await conn.execute(
|
||||
"INSERT INTO message_attachments (message_id, position, attachment_id) "
|
||||
@@ -266,9 +267,7 @@ CLAIM_KEY = (
|
||||
"WHERE idempotency_keys.created_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"RETURNING 1")
|
||||
STORED_RESULT = (
|
||||
"SELECT k.request_hash, m.id, m.text, m.created_at, "
|
||||
"ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) "
|
||||
"FROM idempotency_keys k "
|
||||
"SELECT k.request_hash, m.id, m.text, m.created_at, m.attachment_ids FROM idempotency_keys k "
|
||||
"JOIN messages m ON m.id = k.message_id "
|
||||
"WHERE k.user_id = %s AND k.chat_id = %s AND k.key = %s")
|
||||
|
||||
@@ -351,14 +350,13 @@ async def purge_idempotency_keys(db: Database, ttl_seconds: int, batch: int = 50
|
||||
|
||||
# Two statements instead of one with "(%s IS NULL OR ...)": with a generic plan the OR
|
||||
# would push the cursor into a Filter and late pages would scan the whole prefix.
|
||||
# attachment_ids: a correlated sub-select per returned row (at most limit + 1 = 101 lookups on the
|
||||
# primary key of message_attachments), so the keyset range scan itself stays unchanged.
|
||||
HISTORY_COLUMNS = ("SELECT m.id, m.sender_id, m.text, m.created_at, "
|
||||
"ARRAY(SELECT ma.attachment_id FROM message_attachments ma "
|
||||
"WHERE ma.message_id = m.id ORDER BY ma.position) FROM messages m ")
|
||||
HISTORY_FIRST = HISTORY_COLUMNS + "WHERE m.chat_id = %s ORDER BY m.created_at, m.id LIMIT %s"
|
||||
HISTORY_AFTER = (HISTORY_COLUMNS +
|
||||
"WHERE m.chat_id = %s AND (m.created_at, m.id) > (%s, %s) ORDER BY m.created_at, m.id LIMIT %s")
|
||||
# attachment_ids is a column of the message row (migration 0004): still one index range scan.
|
||||
HISTORY_FIRST = (
|
||||
"SELECT id, sender_id, text, created_at, attachment_ids FROM messages "
|
||||
"WHERE chat_id = %s ORDER BY created_at, id LIMIT %s")
|
||||
HISTORY_AFTER = (
|
||||
"SELECT id, sender_id, text, created_at, attachment_ids FROM messages "
|
||||
"WHERE chat_id = %s AND (created_at, id) > (%s, %s) ORDER BY created_at, id LIMIT %s")
|
||||
|
||||
|
||||
async def list_messages(db: Database, chat_id: str, after: SortKey | None, limit: int) -> tuple[list[Message], bool]:
|
||||
|
||||
@@ -44,6 +44,7 @@ class ObjectHead:
|
||||
size: int
|
||||
content_type: str
|
||||
metadata: dict[str, str]
|
||||
last_modified_ts: float # POSIX seconds
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -116,7 +117,7 @@ class Storage:
|
||||
async def head(self, key: str) -> ObjectHead:
|
||||
response = await self._call("head", self.client.head_object(Bucket=self.bucket, Key=key))
|
||||
return ObjectHead(int(response["ContentLength"]), response.get("ContentType", ""),
|
||||
dict(response.get("Metadata", {})))
|
||||
dict(response.get("Metadata", {})), response["LastModified"].timestamp())
|
||||
|
||||
async def open_stream(self, key: str) -> tuple[int, AsyncIterator[bytes]]:
|
||||
"""Start a GET: (Content-Length, async iterator of chunks). The headers arrive under the
|
||||
|
||||
Reference in New Issue
Block a user