forked from mtusi2026/mtusi2026lab5
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a58d6beb5c | ||
|
|
4ac53fe332 |
@@ -66,6 +66,18 @@ docker compose down # volumes сохраняются
|
|||||||
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Операторский replay failed-задач
|
||||||
|
|
||||||
|
Причина ошибки устранена — вернуть задачи в обработку (failed → queued + новая строка outbox, готовые не трогаются):
|
||||||
|
|
||||||
|
```
|
||||||
|
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed --all-failed
|
||||||
|
# или конкретные ID:
|
||||||
|
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed <attachment_id> [...]
|
||||||
|
```
|
||||||
|
|
||||||
|
Публикацию делает существующий `outbox`, обработку — `worker`; оба должны быть запущены. Проверка: `status=queued`, затем `ready`.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
Схема процессов и хранилищ:
|
Схема процессов и хранилищ:
|
||||||
|
|||||||
@@ -410,6 +410,56 @@ class PostgresStorage:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
return count
|
return count
|
||||||
|
|
||||||
|
def replay_failed_to_queued(self, attachment_id: UUID) -> str:
|
||||||
|
"""Операторский replay: failed → queued с новой записью в outbox.
|
||||||
|
|
||||||
|
Возвращает:
|
||||||
|
- "requeued" — статус был failed, переведён в queued и запланирован job;
|
||||||
|
- "already" — запись уже queued/processing/ready (защита готовых), ничего не меняем;
|
||||||
|
- "missing" — такого вложения нет.
|
||||||
|
|
||||||
|
Ключ эффекта (attachment_id, pipeline_version, variant) и ON CONFLICT
|
||||||
|
в finalize_ready гарантируют, что повтор не создаст дублей вариантов.
|
||||||
|
Новый job_id и строка outbox публикуются отдельным процессом outbox,
|
||||||
|
поэтому разрыв между COMMIT и publish закрыт тем же механизмом, что и при upload.
|
||||||
|
"""
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT status FROM attachments WHERE id = %s FOR UPDATE",
|
||||||
|
(attachment_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is None:
|
||||||
|
conn.rollback()
|
||||||
|
return "missing"
|
||||||
|
status = row[0]
|
||||||
|
if status != "failed":
|
||||||
|
conn.rollback()
|
||||||
|
return "already"
|
||||||
|
|
||||||
|
now = now_utc()
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='queued', error_code=NULL,"
|
||||||
|
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||||
|
(now, attachment_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
job_id = uuid4()
|
||||||
|
payload = {
|
||||||
|
"job_id": str(job_id),
|
||||||
|
"type": "attachment.process.v1",
|
||||||
|
"attachment_id": str(attachment_id),
|
||||||
|
"pipeline_version": 1,
|
||||||
|
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||||
|
(job_id, _json.dumps(payload)),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return "requeued"
|
||||||
|
|
||||||
def finalize_ready(
|
def finalize_ready(
|
||||||
self,
|
self,
|
||||||
attachment_id: UUID,
|
attachment_id: UUID,
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Операторский replay failed-задач: failed → queued + запись в outbox.
|
||||||
|
|
||||||
|
Использование:
|
||||||
|
python -m app.storage.replay_failed <attachment_id> [<attachment_id> ...]
|
||||||
|
python -m app.storage.replay_failed --all-failed
|
||||||
|
|
||||||
|
Защита:
|
||||||
|
- переводит ТОЛЬКО failed; queued/processing/ready не трогает (возвращает "already");
|
||||||
|
- новая строка outbox с новым job_id — публикация через существующий outbox-процесс;
|
||||||
|
- идемпотентность эффекта по (attachment_id, pipeline_version, variant)
|
||||||
|
не даёт создать дубли вариантов, если повторная обработка уже была выполнена.
|
||||||
|
Логи пишутся только с ID и статусом, без секретов и содержимого файлов.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from .db import init_pool, close_pool
|
||||||
|
from .postgres import storage
|
||||||
|
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
)
|
||||||
|
log = logging.getLogger("replay_failed")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_args(argv):
|
||||||
|
if not argv:
|
||||||
|
print(
|
||||||
|
"usage: python -m app.storage.replay_failed <attachment_id> [...] | --all-failed",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
if argv == ["--all-failed"]:
|
||||||
|
return "all"
|
||||||
|
ids = []
|
||||||
|
for raw in argv:
|
||||||
|
try:
|
||||||
|
ids.append(uuid.UUID(raw))
|
||||||
|
except ValueError:
|
||||||
|
print("invalid attachment_id: %r" % raw, file=sys.stderr)
|
||||||
|
return None
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _list_failed_ids() -> list:
|
||||||
|
from .db import connection
|
||||||
|
with connection() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT id FROM attachments WHERE status='failed' ORDER BY updated_at")
|
||||||
|
return [r[0] for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv) -> int:
|
||||||
|
parsed = _parse_args(argv)
|
||||||
|
if parsed is None:
|
||||||
|
return 2
|
||||||
|
init_pool()
|
||||||
|
try:
|
||||||
|
if parsed == "all":
|
||||||
|
ids = _list_failed_ids()
|
||||||
|
else:
|
||||||
|
ids = parsed
|
||||||
|
requeued = already = missing = 0
|
||||||
|
for aid in ids:
|
||||||
|
result = storage.replay_failed_to_queued(aid)
|
||||||
|
if result == "requeued":
|
||||||
|
requeued += 1
|
||||||
|
log.info("event=replay_requeued attachment_id=%s", aid)
|
||||||
|
elif result == "already":
|
||||||
|
already += 1
|
||||||
|
log.info("event=replay_skipped_not_failed attachment_id=%s", aid)
|
||||||
|
else:
|
||||||
|
missing += 1
|
||||||
|
log.info("event=replay_missing attachment_id=%s", aid)
|
||||||
|
log.info(
|
||||||
|
"event=replay_done requested=%d requeued=%d skipped=%d missing=%d",
|
||||||
|
len(ids), requeued, already, missing,
|
||||||
|
)
|
||||||
|
return 0 if missing == 0 else 1
|
||||||
|
finally:
|
||||||
|
close_pool()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv[1:]))
|
||||||
@@ -60,11 +60,21 @@ def _known_keys() -> set[str]:
|
|||||||
return keys
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _active_attachment_ids() -> set[str]:
|
||||||
|
"""ID вложений в статусах queued/processing — их staging трогать нельзя."""
|
||||||
|
with connection() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM attachments WHERE status IN ('queued', 'processing')"
|
||||||
|
)
|
||||||
|
return {str(r[0]) for r in cur.fetchall()}
|
||||||
|
|
||||||
|
|
||||||
def _run_once() -> dict:
|
def _run_once() -> dict:
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
grace_cutoff = now - timedelta(seconds=_grace())
|
grace_cutoff = now - timedelta(seconds=_grace())
|
||||||
|
|
||||||
known = _known_keys()
|
known = _known_keys()
|
||||||
|
active_ids = _active_attachment_ids()
|
||||||
orphan_deleted = 0
|
orphan_deleted = 0
|
||||||
missing = 0
|
missing = 0
|
||||||
scanned = 0
|
scanned = 0
|
||||||
@@ -93,8 +103,18 @@ def _run_once() -> dict:
|
|||||||
log.error("event=orphan_delete_failed key=%s type=%s",
|
log.error("event=orphan_delete_failed key=%s type=%s",
|
||||||
key, type(exc).__name__)
|
key, type(exc).__name__)
|
||||||
|
|
||||||
# staging/ — удаляем только старое (не in-flight).
|
# staging/ — удаляем только старое И не принадлежащее активной задаче.
|
||||||
|
# Ключ: staging/<chat_id>/<attachment_id>/original
|
||||||
for obj in s3.list_objects("staging/"):
|
for obj in s3.list_objects("staging/"):
|
||||||
|
key = obj["Key"]
|
||||||
|
parts = key.split("/")
|
||||||
|
# Ожидаем минимум 4 части: staging / chat_id / attachment_id / original
|
||||||
|
if len(parts) < 4 or parts[0] != "staging":
|
||||||
|
continue
|
||||||
|
attachment_id = parts[2]
|
||||||
|
if attachment_id in active_ids:
|
||||||
|
# Задача ещё в queued/processing — staging нужен worker'у.
|
||||||
|
continue
|
||||||
lm = obj.get("LastModified")
|
lm = obj.get("LastModified")
|
||||||
if lm is None:
|
if lm is None:
|
||||||
continue
|
continue
|
||||||
@@ -103,7 +123,7 @@ def _run_once() -> dict:
|
|||||||
if lm > grace_cutoff:
|
if lm > grace_cutoff:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
s3.delete_object(obj["Key"])
|
s3.delete_object(key)
|
||||||
staging_deleted += 1
|
staging_deleted += 1
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|||||||
Reference in New Issue
Block a user