Реализовать асинхронную обработку вложений
This commit is contained in:
@@ -25,7 +25,11 @@ async def cleanup(apply: bool, grace_seconds: int) -> int:
|
||||
try:
|
||||
sessions = create_session_factory(engine)
|
||||
async with sessions() as session:
|
||||
known = set(await session.scalars(select(AttachmentRow.object_key)))
|
||||
known = set(
|
||||
key
|
||||
for key in await session.scalars(select(AttachmentRow.original_key))
|
||||
if key is not None
|
||||
)
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
|
||||
removed = 0
|
||||
for item in await storage.list('originals/'):
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..config import load_settings
|
||||
from ..db import create_engine, create_session_factory
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..storage import S3Storage
|
||||
|
||||
|
||||
async def cleanup(apply: bool, retention_seconds: int) -> int:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
sessions = create_session_factory(engine)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=retention_seconds)
|
||||
try:
|
||||
async with sessions() as session:
|
||||
active = set(
|
||||
key
|
||||
for key in await session.scalars(
|
||||
select(AttachmentRow.staging_key).where(
|
||||
AttachmentRow.staging_key.is_not(None),
|
||||
AttachmentRow.status.in_(('queued', 'processing')),
|
||||
)
|
||||
)
|
||||
if key is not None
|
||||
)
|
||||
removed = 0
|
||||
for item in await storage.list('staging/'):
|
||||
if item.key in active or item.last_modified > cutoff:
|
||||
continue
|
||||
print(f'{"DELETE" if apply else "WOULD_DELETE"} key={item.key}')
|
||||
if apply:
|
||||
await storage.remove(item.key)
|
||||
removed += 1
|
||||
print(f'summary active={len(active)} removed={removed} mode={"apply" if apply else "dry-run"}')
|
||||
return 0
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description='Clean inactive durable staging objects')
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument('--dry-run', action='store_true')
|
||||
mode.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--retention-seconds', type=int)
|
||||
args = parser.parse_args()
|
||||
settings = load_settings()
|
||||
retention = args.retention_seconds or settings.staging_retention_seconds
|
||||
if retention < 60:
|
||||
parser.error('retention must be at least 60 seconds')
|
||||
raise SystemExit(asyncio.run(cleanup(args.apply, retention)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -74,7 +74,7 @@ async def _load_attachments(
|
||||
await session.execute(
|
||||
select(
|
||||
AttachmentRow.id,
|
||||
AttachmentRow.object_key,
|
||||
AttachmentRow.original_key,
|
||||
AttachmentRow.status,
|
||||
AttachmentRow.updated_at,
|
||||
)
|
||||
@@ -88,7 +88,7 @@ async def _metadata_key_exists(
|
||||
) -> bool:
|
||||
async with sessions() as session:
|
||||
attachment_id = await session.scalar(
|
||||
select(AttachmentRow.id).where(AttachmentRow.object_key == object_key).limit(1)
|
||||
select(AttachmentRow.id).where(AttachmentRow.original_key == object_key).limit(1)
|
||||
)
|
||||
return attachment_id is not None
|
||||
|
||||
@@ -165,7 +165,7 @@ async def reconcile(
|
||||
update(AttachmentRow)
|
||||
.where(
|
||||
AttachmentRow.id == attachment.id,
|
||||
AttachmentRow.object_key == attachment.object_key,
|
||||
AttachmentRow.original_key == attachment.object_key,
|
||||
AttachmentRow.status == 'ready',
|
||||
AttachmentRow.updated_at == attachment.updated_at,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from ..config import load_settings
|
||||
from ..db import create_engine, create_session_factory
|
||||
from ..repositories import JobRepository
|
||||
|
||||
|
||||
async def replay(job_id: UUID | None, attachment_id: UUID | None, dry_run: bool) -> int:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
try:
|
||||
repository = JobRepository(create_session_factory(engine))
|
||||
if job_id is None:
|
||||
assert attachment_id is not None
|
||||
job_id = await repository.id_for_attachment(attachment_id)
|
||||
if job_id is None:
|
||||
print(f'REJECTED attachment_id={attachment_id} reason=job_not_found')
|
||||
return 2
|
||||
accepted = await repository.replay(job_id, datetime.now(timezone.utc), dry_run)
|
||||
if not accepted:
|
||||
print(f'REJECTED job_id={job_id} reason=not_failed_or_staging_missing')
|
||||
return 2
|
||||
print(f'{"WOULD_REPLAY" if dry_run else "REPLAYED"} job_id={job_id}')
|
||||
return 0
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description='Safely replay one failed attachment job')
|
||||
target = parser.add_mutually_exclusive_group(required=True)
|
||||
target.add_argument('--job-id', type=UUID)
|
||||
target.add_argument('--attachment-id', type=UUID)
|
||||
parser.add_argument('--dry-run', action='store_true')
|
||||
args = parser.parse_args()
|
||||
raise SystemExit(asyncio.run(replay(args.job_id, args.attachment_id, args.dry_run)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -50,7 +50,9 @@ async def prepare(size: int) -> None:
|
||||
'chat_id': CHAT_ID,
|
||||
'owner_id': USER_ID,
|
||||
'filename': f'benchmark-{index}.png',
|
||||
'object_key': f'{OBJECT_PREFIX}{index}',
|
||||
'original_key': f'{OBJECT_PREFIX}{index}',
|
||||
'staging_key': None,
|
||||
'pipeline_version': 1,
|
||||
'content_type': 'image/png',
|
||||
'size_bytes': 1,
|
||||
'sha256': '0' * 64,
|
||||
@@ -80,7 +82,7 @@ async def prepare(size: int) -> None:
|
||||
for offset in range(0, size, 500):
|
||||
await session.execute(insert(AttachmentRow), rows[offset : offset + 500])
|
||||
|
||||
await _put_objects(storage, [row['object_key'] for row in rows])
|
||||
await _put_objects(storage, [row['original_key'] for row in rows])
|
||||
print(f'prepared metadata={size} objects={size}')
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
Reference in New Issue
Block a user