Files
mtusi2026lab5/src/staging.py
T

60 lines
2.1 KiB
Python

"""Очистка staging с блокировкой, общей с HTTP upload и replay."""
import logging
import signal
import threading
from datetime import datetime, timezone
import psycopg
from botocore.exceptions import BotoCoreError, ClientError
from psycopg_pool import PoolTimeout
from src.config import setting
from src.objects import BUCKET, client, object_lock
from src.storage import storage
def cleanup(s3, retention):
count = 0
now = datetime.now(timezone.utc)
pages = s3.get_paginator('list_objects_v2')
for page in pages.paginate(Bucket=BUCKET, Prefix='staging/'):
for item in page.get('Contents', []):
key = item['Key']
with storage.pool.connection() as conn:
if not object_lock(conn, key, wait=False):
continue
job = conn.execute(
'SELECT j.state,a.updated_at FROM attachment_jobs j JOIN attachments a '
'ON a.id=j.attachment_id WHERE j.staging_key=%s', (key,),
).fetchone()
retention_start = job['updated_at'] if job else item['LastModified']
age = (now - retention_start).total_seconds()
if job and job['state'] in ('queued', 'processing'):
continue
if (job and job['state'] == 'ready') or age >= retention:
s3.delete_object(Bucket=BUCKET, Key=key)
count += 1
return count
def main():
stop = threading.Event()
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, lambda *_: stop.set())
retention = max(60, int(setting('STAGING_RETENTION_SECONDS', '86400')))
storage.pool.open(wait=True)
try:
while not stop.is_set():
try:
cleanup(client(), retention)
except (BotoCoreError, ClientError, OSError, psycopg.Error, PoolTimeout) as exc:
logging.warning('staging cleanup temporarily unavailable: %s', type(exc).__name__)
stop.wait(30)
finally:
storage.pool.close()
if __name__ == '__main__':
main()