29 lines
1.3 KiB
Python
29 lines
1.3 KiB
Python
"""Recover abandoned upload intents older than one hour; never delete ready files."""
|
|
import time
|
|
import db
|
|
from attachments import S3, BUCKET
|
|
|
|
|
|
def sweep():
|
|
with db.pool.connection() as conn:
|
|
rows = conn.execute("""SELECT id,object_key FROM attachments WHERE status='pending'
|
|
AND created_at < now() - interval '1 hour'
|
|
FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
|
|
for row in rows:
|
|
S3.delete_object(Bucket=BUCKET, Key=row['object_key'])
|
|
conn.execute("DELETE FROM attachments WHERE id=%s", (row['id'],))
|
|
ready = conn.execute("SELECT id FROM attachments WHERE NOT staging_cleaned AND ((status='ready' AND updated_at < now()-interval '1 hour') OR (status='failed' AND updated_at < now()-interval '7 days')) LIMIT 100 FOR UPDATE SKIP LOCKED").fetchall()
|
|
for row in ready:
|
|
S3.delete_object(Bucket=BUCKET,Key=f"staging/{row['id']}")
|
|
conn.execute("UPDATE attachments SET staging_cleaned=TRUE WHERE id=%s",(row['id'],))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
db.pool.open(wait=True, timeout=30)
|
|
while True:
|
|
try:
|
|
sweep()
|
|
except Exception:
|
|
print('cleanup deferred; will retry', flush=True)
|
|
time.sleep(60)
|