feat: compensate failed uploads and clean stale pending attachments
- upload: delete the stored object when ready fails before COMMIT or the pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it - cleaner service (python -m src.cleaner): stale pending rows older than grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP LOCKED, object before row, own S3 user with read/delete only - shared session_scope for API and cleaner; early_stop process name - partial index on pending attachments, CREATE INDEX CONCURRENTLY - s3-bootstrap: cleaner user, policy and checks; make env_setup appends missing template variables to an existing .env - failure checks: cleaner on the failure stand, id-list hook actions, five new and three updated tests; driver upload-consistency - sync upload-consistency deltas into main specs (storage-consistency) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,6 +86,16 @@
|
||||
original без filename, объект в bucket (weed shell), анонимный
|
||||
GET ключа с хоста — 403, docker diff реплик без файлов
|
||||
оригиналов; код 1 при расхождении, без LB — код 2
|
||||
upload-consistency только стенд с LB: спеки attachments «Порядок
|
||||
записи» и storage-consistency — загрузка при docker compose
|
||||
pause s3 (503, строка pending), загрузка со сбоем фиксации
|
||||
ready (триггер на уникальный filename, 503, объект удалён
|
||||
компенсацией), обе строки не видны через API (404), после
|
||||
grace 30 с — docker compose run --rm --no-deps cleaner --once,
|
||||
ни строк, ни объектов, объектов без строки под префиксом базы
|
||||
нет, готовое вложение скачивается с тем же SHA-256; триггер
|
||||
снимается в finally и в начале следующего прогона; код 1 при
|
||||
расхождении, без LB — код 2
|
||||
stop остановить свой экземпляр на порту
|
||||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||||
|
||||
@@ -114,6 +124,7 @@ import io
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import subprocess
|
||||
@@ -2433,6 +2444,323 @@ def cmd_attachment_storage(port: int) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
# upload-consistency: имена триггера и функции постоянные — остаток
|
||||
# прерванного прогона убирается в начале следующего. Отказ — SQLSTATE 08006:
|
||||
# для API это отказ БД (503), а не дефект (500)
|
||||
UC_TRIGGER = "driver_uc_fail_ready"
|
||||
UC_FAIL_READY_SQL = """\
|
||||
CREATE OR REPLACE FUNCTION {name}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.filename = TG_ARGV[0] AND OLD.status = 'pending'
|
||||
AND NEW.status = 'ready' THEN
|
||||
RAISE EXCEPTION 'driver: attachment ready failure'
|
||||
USING ERRCODE = '08006';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
DROP TRIGGER IF EXISTS {name} ON attachments;
|
||||
CREATE TRIGGER {name} BEFORE UPDATE ON attachments
|
||||
FOR EACH ROW EXECUTE FUNCTION {name}('{filename}');
|
||||
"""
|
||||
UC_CLEAR_SQL = f"""\
|
||||
DROP TRIGGER IF EXISTS {UC_TRIGGER} ON attachments;
|
||||
DROP FUNCTION IF EXISTS {UC_TRIGGER}();
|
||||
"""
|
||||
# grace разового прохода: больше границы живой загрузки (17 с)
|
||||
UC_GRACE_S = 30
|
||||
# срок клиента загрузки при замороженном S3: ответ API — через 5 с
|
||||
UC_UPLOAD_TIMEOUT_S = 30
|
||||
UC_TREE_LINE = re.compile(r"^((?:[│ ] {3})*)[├└]──\s*(.*?)\s*$")
|
||||
UC_UUID = re.compile(
|
||||
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
)
|
||||
|
||||
|
||||
def stored_attachment_ids(bucket: str, database: str) -> set[str]:
|
||||
"""`id` вложений с файлом `original` под `<база>/attachments/` bucket
|
||||
стенда — по файлам `fs.tree`, а не по каталогам: пустой каталог
|
||||
`<id>/` SeaweedFS убирает лишь через ~2 мин после DELETE."""
|
||||
tree = weed_shell(
|
||||
f"fs.tree /buckets/{bucket}/{database}/{ATTACHMENT_KEY_PREFIX}",
|
||||
)
|
||||
found: set[str] = set()
|
||||
current = ""
|
||||
for line in tree.splitlines():
|
||||
match = UC_TREE_LINE.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
depth = len(match.group(1)) // 4 + 1
|
||||
if depth == 1:
|
||||
current = match.group(2) if UC_UUID.match(match.group(2)) else ""
|
||||
elif depth == 2 and match.group(2) == ATTACHMENT_ORIGINAL and current:
|
||||
found.add(current)
|
||||
return found
|
||||
|
||||
|
||||
def attachment_statuses() -> dict[str, str]:
|
||||
"""Все вложения рабочей базы: `id` → статус."""
|
||||
rows = stand_psql("SELECT id, status FROM attachments;\n").splitlines()
|
||||
return dict(line.split("|") for line in rows if "|" in line)
|
||||
|
||||
|
||||
def pending_row(attachment_id: str) -> str:
|
||||
"""Строка вложения для вывода: статус, возраст, ключ объекта."""
|
||||
# id — UUID из ответа psql: безопасен в тексте SQL
|
||||
return stand_psql(
|
||||
"SELECT status || ' age ' || round(extract(epoch FROM now() - "
|
||||
"created_at)) || ' s key ' || object_key FROM attachments "
|
||||
f"WHERE id = '{attachment_id}';\n",
|
||||
).strip()
|
||||
|
||||
|
||||
def cmd_upload_consistency(port: int) -> int:
|
||||
"""Спеки `attachments` («Порядок записи») и `storage-consistency` на
|
||||
рабочем стенде через LB (design change `upload-consistency`, решение
|
||||
11): загрузка при замороженном S3 и при сбое фиксации `ready`, их
|
||||
строки `pending` не видны через API, компенсация удаляет объект,
|
||||
разовый проход уборщика убирает обе загрузки, готовое вложение цело.
|
||||
Триггер — только на уникальный `filename` прогона, снимается в
|
||||
`finally` и в начале следующего прогона; S3 размораживается в
|
||||
`finally`. Токенов и секретов в выводе нет."""
|
||||
if no_lb(port):
|
||||
print("upload-consistency needs the stand with the load balancer")
|
||||
return 2
|
||||
|
||||
def interrupted(signum: int, _frame: object) -> None:
|
||||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||||
|
||||
previous = {
|
||||
signum: signal.signal(signum, interrupted)
|
||||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||||
}
|
||||
try:
|
||||
return upload_consistency(port)
|
||||
finally:
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
|
||||
|
||||
def upload_consistency(port: int) -> int:
|
||||
"""Тело `cmd_upload_consistency`."""
|
||||
try:
|
||||
stand = s3_stand()
|
||||
config = json.loads(compose("config", "--format", "json"))
|
||||
database = str(
|
||||
config["services"]["api"]["environment"]["DATABASE__NAME"],
|
||||
)
|
||||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||||
print(f"FAIL: compose config of the stand: {e}")
|
||||
return 1
|
||||
bucket = stand["bucket"]
|
||||
# остаток прерванного прогона
|
||||
stand_psql(UC_CLEAR_SQL)
|
||||
people = attachment_people(port, "uc")
|
||||
if people is None:
|
||||
return 1
|
||||
_, tokens, chat_id = people
|
||||
data = FIXTURE_PNG.read_bytes()
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
rows: list[tuple[str, str, str]] = []
|
||||
|
||||
def upload(filename: str, timeout: float = 30) -> tuple[int, object]:
|
||||
query = urllib.parse.urlencode({"filename": filename})
|
||||
status, _, payload = call_bytes(
|
||||
port,
|
||||
"POST",
|
||||
f"{CHATS}/{chat_id}/attachments?{query}",
|
||||
token=tokens["alice"],
|
||||
data=data,
|
||||
content_type="image/png",
|
||||
timeout=timeout,
|
||||
)
|
||||
try:
|
||||
return status, json.loads(payload) if payload else None
|
||||
except json.JSONDecodeError:
|
||||
return status, None
|
||||
|
||||
status, payload = upload(f"uc-{tag}-ready.png")
|
||||
if status != 201 or not isinstance(payload, dict):
|
||||
print(f"FAIL: ready upload {status}")
|
||||
return 1
|
||||
ready = payload
|
||||
rows.append(("ready attachment R uploaded", "201", str(status)))
|
||||
|
||||
# 1. S3 заморожен на время PUT
|
||||
before = attachment_statuses()
|
||||
started = time.monotonic()
|
||||
compose("pause", "s3")
|
||||
try:
|
||||
status, _ = upload(f"uc-{tag}-paused.png", UC_UPLOAD_TIMEOUT_S)
|
||||
took = time.monotonic() - started
|
||||
finally:
|
||||
compose("unpause", "s3")
|
||||
print(f"upload with paused S3: {status} after {took:.1f} s")
|
||||
rows.append(("upload with paused S3", "503", str(status)))
|
||||
paused = sorted(set(attachment_statuses()) - set(before))
|
||||
rows.append(("new pending rows (paused)", "1", str(len(paused))))
|
||||
if len(paused) != 1:
|
||||
print("FAIL: no single pending row of the paused upload")
|
||||
return report_rows(rows)
|
||||
paused_id = paused[0]
|
||||
print(f"pending {paused_id}: {pending_row(paused_id)}")
|
||||
|
||||
# 2. фиксация ready падает: компенсация удаляет объект
|
||||
fail_name = f"uc-{tag}-ready-failure.png"
|
||||
before = attachment_statuses()
|
||||
try:
|
||||
stand_psql(
|
||||
UC_FAIL_READY_SQL.format(name=UC_TRIGGER, filename=fail_name),
|
||||
)
|
||||
status, _ = upload(fail_name)
|
||||
finally:
|
||||
stand_psql(UC_CLEAR_SQL)
|
||||
rows.append(("upload with ready failure", "503", str(status)))
|
||||
failed = sorted(set(attachment_statuses()) - set(before))
|
||||
rows.append(("new pending rows (ready failure)", "1", str(len(failed))))
|
||||
if len(failed) != 1:
|
||||
print("FAIL: no single pending row of the ready failure")
|
||||
return report_rows(rows)
|
||||
failed_id = failed[0]
|
||||
print(f"pending {failed_id}: {pending_row(failed_id)}")
|
||||
stored = stored_attachment_ids(bucket, database)
|
||||
rows.append(
|
||||
(
|
||||
"object after compensation",
|
||||
"absent",
|
||||
"present" if failed_id in stored else "absent",
|
||||
),
|
||||
)
|
||||
triggers = stand_psql(
|
||||
f"SELECT count(*) FROM pg_trigger WHERE tgname = '{UC_TRIGGER}';\n",
|
||||
).strip()
|
||||
rows.append(("driver trigger left", "0", triggers))
|
||||
|
||||
# pending не видны через API
|
||||
for pending_id in (paused_id, failed_id):
|
||||
for label, path in (
|
||||
("metadata", f"{ATTACHMENTS}/{pending_id}"),
|
||||
("content", f"{ATTACHMENTS}/{pending_id}/content"),
|
||||
):
|
||||
status, _, _ = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
path,
|
||||
token=tokens["alice"],
|
||||
)
|
||||
rows.append(
|
||||
(f"{label} of pending {pending_id[:8]}", "404", str(status)),
|
||||
)
|
||||
status, _, _ = call(
|
||||
port,
|
||||
"POST",
|
||||
f"{CHATS}/{chat_id}/messages",
|
||||
token=tokens["alice"],
|
||||
body={"text": "link", "attachment_ids": [pending_id]},
|
||||
extra=key_header(),
|
||||
)
|
||||
rows.append((f"message with {pending_id[:8]}", "404", str(status)))
|
||||
|
||||
# 3. разовый проход уборщика после grace прогона
|
||||
# строка сбоя ready — младшая из двух: ждём, пока и она старше grace
|
||||
wait = max(0.0, UC_GRACE_S + 1 - float(age_of(failed_id)))
|
||||
print(f"waiting {wait:.0f} s for grace {UC_GRACE_S} s")
|
||||
time.sleep(wait)
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-e",
|
||||
f"CLEANER__PENDING_GRACE_SECONDS={UC_GRACE_S}",
|
||||
"cleaner",
|
||||
"--once",
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
print(f"cleaner --once (grace {UC_GRACE_S} s): exit {proc.returncode}")
|
||||
for line in (proc.stdout + proc.stderr).splitlines():
|
||||
if line.startswith("{"):
|
||||
print(" " + line)
|
||||
rows.append(("cleaner --once exit code", "0", str(proc.returncode)))
|
||||
|
||||
# 4. ни строк, ни объектов; объектов без строки нет
|
||||
statuses = attachment_statuses()
|
||||
stored = stored_attachment_ids(bucket, database)
|
||||
for pending_id in (paused_id, failed_id):
|
||||
rows.append(
|
||||
(
|
||||
f"row of {pending_id[:8]}",
|
||||
"absent",
|
||||
"present" if pending_id in statuses else "absent",
|
||||
),
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
f"object of {pending_id[:8]}",
|
||||
"absent",
|
||||
"present" if pending_id in stored else "absent",
|
||||
),
|
||||
)
|
||||
orphans = stored - set(statuses)
|
||||
print(
|
||||
f"bucket {bucket}, prefix {database}/: {len(stored)} objects, "
|
||||
f"{len(statuses)} rows, {len(orphans)} objects without a row",
|
||||
)
|
||||
rows.append(("objects without a row", "0", str(len(orphans))))
|
||||
status, _, got = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{ready['id']}/content",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
rows.append(("R downloaded", "200", str(status)))
|
||||
rows.append(
|
||||
(
|
||||
"R sha256 = uploaded",
|
||||
"yes",
|
||||
"yes" if sha256_hex(got) == ready["sha256"] else "no",
|
||||
),
|
||||
)
|
||||
return report_rows(rows)
|
||||
|
||||
|
||||
def age_of(attachment_id: str) -> str:
|
||||
"""Возраст строки в секундах; нет строки — 0."""
|
||||
value = stand_psql(
|
||||
"SELECT coalesce(max(extract(epoch FROM now() - created_at)), 0) "
|
||||
f"FROM attachments WHERE id = '{attachment_id}';\n",
|
||||
).strip()
|
||||
return value or "0"
|
||||
|
||||
|
||||
def report_rows(rows: list[tuple[str, str, str]]) -> int:
|
||||
"""Таблица «проверка → ожидаемо → получено»; код 1 при расхождении."""
|
||||
width = max(len(check) for check, _, _ in rows)
|
||||
failed = 0
|
||||
for check, expected, got in rows:
|
||||
ok = expected == got
|
||||
failed += not ok
|
||||
print(
|
||||
f"{check:<{width}} expected {expected:<7} got {got}"
|
||||
+ ("" if ok else " FAIL"),
|
||||
)
|
||||
if failed:
|
||||
print(f"FAIL: {failed} check(s) failed")
|
||||
return 1
|
||||
print(
|
||||
"PASS: pending rows are invisible, the ready failure is compensated, "
|
||||
"the cleaner removed both uploads, no object without a row, R intact",
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
# stop-at-start: записи журнала, по которым видны этапы старта и остановки
|
||||
STARTED_SERVER = "Started server process"
|
||||
SERVER_RUNNING = "Uvicorn running on"
|
||||
@@ -2815,6 +3143,7 @@ def main() -> int:
|
||||
failover = sub.add_parser("attachment-failover")
|
||||
failover.add_argument("--mode", choices=("stop", "kill"), default="stop")
|
||||
sub.add_parser("attachment-storage")
|
||||
sub.add_parser("upload-consistency")
|
||||
stop = sub.add_parser("stop-at-start")
|
||||
stop.add_argument("--image", default="mtusi-messenger:lab4")
|
||||
stop.add_argument(
|
||||
@@ -2895,6 +3224,8 @@ def main() -> int:
|
||||
return cmd_attachment_failover(port, args.mode)
|
||||
if args.cmd == "attachment-storage":
|
||||
return cmd_attachment_storage(port)
|
||||
if args.cmd == "upload-consistency":
|
||||
return cmd_upload_consistency(port)
|
||||
if args.cmd == "stop-at-start":
|
||||
return cmd_stop_at_start(
|
||||
args.image,
|
||||
|
||||
Reference in New Issue
Block a user