#!/bin/sh # Reconcile S3 orphans: bucket objects with no matching attachments.s3_key in PG. # # Upload path compensation: S3 PUT → PG INSERT; on INSERT failure the API # best-effort DeleteObject. This script cleans leftovers after crashes between # PUT and compensate (or a failed DeleteObject). # # Dry-run by default. Fresh objects inside GRACE_SECONDS are never deleted. # # ./tools/gc_orphans.sh # APPLY=1 GRACE_SECONDS=3600 ./tools/gc_orphans.sh set -eu ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)" COMPOSE="docker compose --env-file $ROOT/.env -f $ROOT/compose.yaml" GRACE_SECONDS="${GRACE_SECONDS:-3600}" APPLY="${APPLY:-0}" PREFIX="${ORPHAN_PREFIX:-}" S3_BUCKET=$($COMPOSE exec -T api sh -c 'printf %s "$S3_BUCKET"') [ -n "$S3_BUCKET" ] || { echo "S3_BUCKET empty" >&2; exit 1; } TMP=$(mktemp -d) trap 'rm -rf "$TMP"' EXIT echo "gc_orphans: bucket=$S3_BUCKET grace=${GRACE_SECONDS}s apply=$APPLY prefix=$PREFIX" s3_listing=$($COMPOSE run --rm --no-deps -T --entrypoint /bin/sh minio-init -c " set -eu mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null mc ls --recursive --json \"local/\$S3_BUCKET/$PREFIX\" || true ") printf '%s\n' "$s3_listing" > "$TMP/s3.json" # Keep published attachments and staging objects for active direct uploads. pg_keys=$($COMPOSE exec -T db sh -c \ 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc " SELECT s3_key FROM attachments UNION SELECT staging_key FROM direct_uploads WHERE status = '\''pending'\'' "') printf '%s\n' "$pg_keys" > "$TMP/pg.keys" python3 - "$TMP/s3.json" "$TMP/pg.keys" "$GRACE_SECONDS" "$TMP/del.keys" "$PREFIX" <<'PY' import json, sys, time from datetime import datetime s3_path, pg_path, grace_s, out_path, prefix = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], sys.argv[5] now = time.time() known = {line.strip() for line in open(pg_path) if line.strip()} orphans = [] for line in open(s3_path): line = line.strip() if not line: continue try: obj = json.loads(line) except json.JSONDecodeError: continue key = obj.get("key") or obj.get("Key") if not key: continue key = key.lstrip("/") if prefix and not key.startswith(prefix): key = prefix.rstrip("/") + "/" + key if not key.startswith(("attachments/", "staging/")): continue if key in known: continue age = None lm = obj.get("lastModified") or obj.get("last_modified") if lm: try: age = now - datetime.fromisoformat(lm.replace("Z", "+00:00")).timestamp() except Exception: age = None orphans.append((key, age, obj.get("size"))) print(f"gc_orphans: scanned orphans={len(orphans)} known_pg={len(known)}") to_delete = [] for key, age, size in orphans: age_s = f"{int(age)}s" if age is not None else "?" if age is not None and age < grace_s: print(f" SKIP (grace) key={key} age={age_s} size={size}") continue print(f" ORPHAN key={key} age={age_s} size={size}") to_delete.append(key) with open(out_path, "w") as f: f.write("\n".join(to_delete) + ("\n" if to_delete else "")) print(f"gc_orphans: candidates={len(to_delete)}") PY if [ "$APPLY" != "1" ]; then echo "gc_orphans: dry-run; set APPLY=1 to delete candidates older than grace." exit 0 fi if [ ! -s "$TMP/del.keys" ]; then echo "gc_orphans: nothing to delete" exit 0 fi while IFS= read -r key; do [ -n "$key" ] || continue echo "deleting $S3_BUCKET/$key" $COMPOSE run --rm --no-deps -T -e "GC_OBJECT_KEY=$key" \ --entrypoint /bin/sh minio-init -c ' set -eu mc alias set local "$S3_ENDPOINT" "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null mc rm --force "local/$S3_BUCKET/$GC_OBJECT_KEY" ' done < "$TMP/del.keys" echo "gc_orphans: delete done"