Implement durable image processing pipeline with outbox and recovery
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from app.job_db import connect_db
|
||||
from app.object_locks import object_lock_id
|
||||
from app.storage import bucket_name, get_client
|
||||
|
||||
|
||||
KEY_PATTERN = re.compile(
|
||||
r"staging/([0-9a-f-]{36})/v([1-9][0-9]*)"
|
||||
)
|
||||
|
||||
|
||||
def managed_key(key):
|
||||
match = KEY_PATTERN.fullmatch(key)
|
||||
if match is None:
|
||||
return False
|
||||
try:
|
||||
return str(UUID(match.group(1))) == match.group(1)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def sweep(*, apply, grace_seconds, attachment_id=None):
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
|
||||
counts = Counter({
|
||||
"scanned": 0,
|
||||
"ignored": 0,
|
||||
"fresh": 0,
|
||||
"busy": 0,
|
||||
"active": 0,
|
||||
"gone": 0,
|
||||
"candidates": 0,
|
||||
"deleted": 0,
|
||||
})
|
||||
|
||||
bucket = bucket_name()
|
||||
client = get_client()
|
||||
prefix = (
|
||||
f"staging/{attachment_id}/"
|
||||
if attachment_id is not None
|
||||
else "staging/"
|
||||
)
|
||||
|
||||
with connect_db() as db:
|
||||
for page in client.get_paginator("list_objects_v2").paginate(
|
||||
Bucket=bucket,
|
||||
Prefix=prefix,
|
||||
PaginationConfig={"PageSize": 200},
|
||||
):
|
||||
for item in page.get("Contents", []):
|
||||
counts["scanned"] += 1
|
||||
key = item["Key"]
|
||||
|
||||
if not managed_key(key):
|
||||
counts["ignored"] += 1
|
||||
continue
|
||||
|
||||
if item["LastModified"] >= cutoff:
|
||||
counts["fresh"] += 1
|
||||
continue
|
||||
|
||||
with db.transaction():
|
||||
db.execute(
|
||||
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
|
||||
)
|
||||
locked = db.execute(
|
||||
"SELECT pg_try_advisory_xact_lock(%s) AS locked",
|
||||
(object_lock_id(bucket, key),),
|
||||
).fetchone()["locked"]
|
||||
|
||||
if not locked:
|
||||
counts["busy"] += 1
|
||||
continue
|
||||
|
||||
row = db.execute(
|
||||
"""
|
||||
SELECT id, status, updated_at
|
||||
FROM attachments
|
||||
WHERE staging_key = %s
|
||||
FOR UPDATE
|
||||
""",
|
||||
(key,),
|
||||
).fetchone()
|
||||
|
||||
if row is not None:
|
||||
if row["status"] in ("queued", "processing"):
|
||||
counts["active"] += 1
|
||||
continue
|
||||
|
||||
if row["status"] == "failed" and row["updated_at"] >= cutoff:
|
||||
counts["fresh"] += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
current = client.head_object(Bucket=bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
status = exc.response.get(
|
||||
"ResponseMetadata", {}
|
||||
).get("HTTPStatusCode")
|
||||
if status == 404:
|
||||
counts["gone"] += 1
|
||||
continue
|
||||
raise
|
||||
|
||||
if current["LastModified"] >= cutoff:
|
||||
counts["fresh"] += 1
|
||||
continue
|
||||
|
||||
counts["candidates"] += 1
|
||||
|
||||
if apply:
|
||||
client.delete_object(Bucket=bucket, Key=key)
|
||||
|
||||
if row is not None:
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET staging_key = NULL
|
||||
WHERE id = %s
|
||||
AND staging_key = %s
|
||||
AND status IN ('ready', 'failed')
|
||||
""",
|
||||
(row["id"], key),
|
||||
)
|
||||
|
||||
counts["deleted"] += 1
|
||||
|
||||
return {
|
||||
"mode": "apply" if apply else "dry-run",
|
||||
"grace_seconds": grace_seconds,
|
||||
"attachment_id": (
|
||||
str(attachment_id) if attachment_id is not None else None
|
||||
),
|
||||
**dict(counts),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument(
|
||||
"--grace-seconds",
|
||||
type=int,
|
||||
default=int(os.getenv("STAGING_RETENTION_SECONDS", "86400")),
|
||||
)
|
||||
parser.add_argument("--attachment-id", type=UUID)
|
||||
parser.add_argument("--allow-short-grace", action="store_true")
|
||||
parser.add_argument("--interval-seconds", type=int, default=0)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.grace_seconds < 0:
|
||||
parser.error("grace must not be negative")
|
||||
|
||||
if args.grace_seconds < 3600 and (
|
||||
not args.allow_short_grace or args.attachment_id is None
|
||||
):
|
||||
parser.error(
|
||||
"short grace requires --allow-short-grace "
|
||||
"and a specific --attachment-id"
|
||||
)
|
||||
|
||||
if args.interval_seconds != 0 and args.interval_seconds < 60:
|
||||
parser.error("interval must be zero or at least 60 seconds")
|
||||
|
||||
while True:
|
||||
try:
|
||||
result = sweep(
|
||||
apply=args.apply,
|
||||
grace_seconds=args.grace_seconds,
|
||||
attachment_id=args.attachment_id,
|
||||
)
|
||||
except Exception as exc:
|
||||
print(json.dumps({
|
||||
"result": "error",
|
||||
"error_type": type(exc).__name__,
|
||||
}), flush=True)
|
||||
raise SystemExit(1)
|
||||
|
||||
print(json.dumps(result), flush=True)
|
||||
|
||||
if args.interval_seconds == 0:
|
||||
return
|
||||
time.sleep(args.interval_seconds)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user