Files
mtusi2026lab5/app/jobs.py
T

91 lines
2.5 KiB
Python

from __future__ import annotations
import hashlib
import os
from uuid import UUID, uuid4
from app.db import pool
from app.object_locks import object_lock_id
from app.storage import bucket_name, put_object
PIPELINE_VERSION = 1
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
if not 1 <= JOB_MAX_ATTEMPTS <= 100:
raise ValueError("JOB_MAX_ATTEMPTS must be between 1 and 100")
async def accept_upload(
*,
chat_id: UUID,
owner_id: UUID,
filename: str,
content_type: str,
data: bytes,
) -> dict:
attachment_id = uuid4()
job_id = uuid4()
staging_key = f"staging/{attachment_id}/v{PIPELINE_VERSION}"
original_key = f"originals/{attachment_id}"
digest = hashlib.sha256(data).hexdigest()
async with pool.connection() as conn:
await conn.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(object_lock_id(bucket_name(), staging_key),),
)
await put_object(staging_key, data, content_type)
cursor = await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename,
content_type, size_bytes, sha256,
object_key, staging_key, pipeline_version, status
)
VALUES (
%s, %s, %s, %s,
%s, %s, %s,
%s, %s, %s, 'queued'
)
RETURNING id, chat_id, owner_id, filename,
content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
""",
(
attachment_id, chat_id, owner_id, filename,
content_type, len(data), digest,
original_key, staging_key, PIPELINE_VERSION,
),
)
row = await cursor.fetchone()
await conn.execute(
"""
INSERT INTO attachment_jobs (
id, attachment_id, pipeline_version, max_attempts
)
VALUES (%s, %s, %s, %s)
""",
(
job_id, attachment_id,
PIPELINE_VERSION, JOB_MAX_ATTEMPTS,
),
)
await conn.execute(
"""
INSERT INTO attachment_outbox (id, job_id, attempt)
VALUES (%s, %s, 1)
""",
(uuid4(), job_id),
)
row["variants"] = []
return row