forked from mtusi2026/mtusi2026lab7
93 lines
3.8 KiB
Python
93 lines
3.8 KiB
Python
import argparse
|
|
import json
|
|
import logging
|
|
import os
|
|
import time
|
|
|
|
from . import bao
|
|
from .errors import ApiError
|
|
from .objects import Objects
|
|
from .storage import PostgresStore
|
|
|
|
|
|
def clean_once(store, objects, grace=600):
|
|
result = {"deleted": 0, "protected": 0}
|
|
for _ in range(100):
|
|
with store.connection() as connection:
|
|
intent = connection.execute(
|
|
"SELECT id,object_key FROM upload_intents "
|
|
"WHERE created_at < clock_timestamp() - %s * INTERVAL '1 second' "
|
|
"ORDER BY created_at,id LIMIT 1 FOR UPDATE SKIP LOCKED", (grace,),
|
|
).fetchone()
|
|
if not intent:
|
|
break
|
|
ready = connection.execute(
|
|
"SELECT id FROM attachments WHERE object_key=%s", (intent["object_key"],),
|
|
).fetchone()
|
|
if ready:
|
|
result["protected"] += 1
|
|
else:
|
|
objects.delete(intent["object_key"])
|
|
result["deleted"] += 1
|
|
connection.execute("DELETE FROM upload_intents WHERE id=%s", (intent["id"],))
|
|
with store.connection() as connection:
|
|
jobs = connection.execute(
|
|
"SELECT j.id,j.attachment_id,j.staging_key,a.status,a.staging_deleted FROM attachment_jobs j "
|
|
"JOIN attachments a ON a.id=j.attachment_id WHERE NOT a.staging_deleted AND "
|
|
"(a.status='ready' OR (a.status='failed' AND a.updated_at < clock_timestamp() - "
|
|
"%s * INTERVAL '1 second') OR (a.status='queued' AND j.published_at IS NULL AND "
|
|
"j.created_at < clock_timestamp() - %s * INTERVAL '1 second')) LIMIT 100",
|
|
(int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')),)*2,
|
|
).fetchall()
|
|
for job in jobs:
|
|
lock = int.from_bytes(job['id'].bytes[:8], 'big', signed=True)
|
|
if not connection.execute('SELECT pg_try_advisory_xact_lock(%s) AS locked', (lock,)).fetchone()['locked']:
|
|
continue
|
|
current = connection.execute('SELECT status FROM attachments WHERE id=%s FOR UPDATE',
|
|
(job['attachment_id'],)).fetchone()
|
|
if current['status'] == 'processing':
|
|
continue
|
|
if current['status'] == 'queued':
|
|
connection.execute("UPDATE attachments SET status='failed',error_code='dispatch_failed',"
|
|
'updated_at=clock_timestamp() WHERE id=%s', (job['attachment_id'],))
|
|
objects.delete(job['staging_key'])
|
|
if current['status'] != 'ready':
|
|
objects.delete('originals/' + str(job['attachment_id']))
|
|
objects.delete('variants/' + str(job['attachment_id']) + '/v1/thumbnail.jpg')
|
|
connection.execute('UPDATE attachments SET staging_deleted=true WHERE id=%s', (job['attachment_id'],))
|
|
result['deleted'] += 1
|
|
return result
|
|
|
|
|
|
def main():
|
|
bao.initialize()
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--once", action="store_true")
|
|
args = parser.parse_args()
|
|
store, objects = PostgresStore(), Objects()
|
|
store.open()
|
|
try:
|
|
while True:
|
|
try:
|
|
bao.ready()
|
|
result = clean_once(store, objects, int(os.environ.get("CLEANUP_GRACE_SECONDS", "600")))
|
|
print(json.dumps(result), flush=True)
|
|
except ApiError:
|
|
if args.once:
|
|
raise
|
|
logging.warning("cleanup: storage unavailable, retry later")
|
|
if args.once:
|
|
return
|
|
time.sleep(int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "30")))
|
|
finally:
|
|
objects.close()
|
|
store.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Exception as error:
|
|
logging.error("Cleanup failed: %s", type(error).__name__)
|
|
raise SystemExit(1)
|