195 lines
6.0 KiB
Python
195 lines
6.0 KiB
Python
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import resource
|
|
import sys
|
|
from uuid import UUID
|
|
|
|
|
|
def execute(job_id: UUID, lease_token: UUID) -> str:
|
|
from app.image_pipeline import InvalidImage, render_variants
|
|
from app.faults import trip_fault
|
|
from app.job_db import connect_db
|
|
from app.storage import _get, _put, bucket_name, get_client
|
|
|
|
with connect_db() as db:
|
|
row = db.execute(
|
|
"""
|
|
SELECT j.attachment_id, j.pipeline_version,
|
|
a.staging_key, a.object_key,
|
|
a.content_type, a.size_bytes, a.sha256
|
|
FROM attachment_jobs AS j
|
|
JOIN attachments AS a ON a.id = j.attachment_id
|
|
WHERE j.id = %s
|
|
AND j.status = 'processing'
|
|
AND j.lease_token = %s
|
|
AND j.lease_until > clock_timestamp()
|
|
AND a.pipeline_version = j.pipeline_version
|
|
AND a.status = 'processing'
|
|
""",
|
|
(job_id, lease_token),
|
|
).fetchone()
|
|
|
|
if row is None:
|
|
return "stale"
|
|
|
|
data = _get(row["staging_key"])
|
|
if (
|
|
len(data) != row["size_bytes"]
|
|
or hashlib.sha256(data).hexdigest() != row["sha256"]
|
|
):
|
|
raise InvalidImage("original_integrity_error")
|
|
|
|
variants = render_variants(data)
|
|
|
|
_put(row["object_key"], data, row["content_type"])
|
|
|
|
for variant in variants:
|
|
variant["object_key"] = (
|
|
f"variants/{row['attachment_id']}/"
|
|
f"v{row['pipeline_version']}/{variant['name']}"
|
|
)
|
|
_put(
|
|
variant["object_key"],
|
|
variant["data"],
|
|
variant["content_type"],
|
|
)
|
|
|
|
trip_fault(job_id, "after_objects")
|
|
|
|
with connect_db() as db:
|
|
with db.transaction():
|
|
job = db.execute(
|
|
"""
|
|
SELECT id
|
|
FROM attachment_jobs
|
|
WHERE id = %s
|
|
AND status = 'processing'
|
|
AND lease_token = %s
|
|
AND lease_until > clock_timestamp()
|
|
FOR UPDATE
|
|
""",
|
|
(job_id, lease_token),
|
|
).fetchone()
|
|
|
|
if job is None:
|
|
return "stale"
|
|
|
|
attachment = db.execute(
|
|
"""
|
|
SELECT id
|
|
FROM attachments
|
|
WHERE id = %s
|
|
AND pipeline_version = %s
|
|
AND status = 'processing'
|
|
FOR UPDATE
|
|
""",
|
|
(row["attachment_id"], row["pipeline_version"]),
|
|
).fetchone()
|
|
|
|
if attachment is None:
|
|
return "stale"
|
|
|
|
for variant in variants:
|
|
db.execute(
|
|
"""
|
|
INSERT INTO attachment_variants (
|
|
attachment_id, pipeline_version,
|
|
name, object_key, content_type,
|
|
size_bytes, width, height, sha256
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
ON CONFLICT (attachment_id, pipeline_version, name)
|
|
DO UPDATE SET
|
|
object_key = EXCLUDED.object_key,
|
|
content_type = EXCLUDED.content_type,
|
|
size_bytes = EXCLUDED.size_bytes,
|
|
width = EXCLUDED.width,
|
|
height = EXCLUDED.height,
|
|
sha256 = EXCLUDED.sha256
|
|
""",
|
|
(
|
|
row["attachment_id"], row["pipeline_version"],
|
|
variant["name"], variant["object_key"],
|
|
variant["content_type"], variant["size_bytes"],
|
|
variant["width"], variant["height"],
|
|
variant["sha256"],
|
|
),
|
|
)
|
|
|
|
db.execute(
|
|
"""
|
|
UPDATE attachments
|
|
SET status = 'ready',
|
|
error_code = NULL,
|
|
updated_at = clock_timestamp()
|
|
WHERE id = %s
|
|
""",
|
|
(row["attachment_id"],),
|
|
)
|
|
|
|
db.execute(
|
|
"""
|
|
UPDATE attachment_jobs
|
|
SET status = 'ready',
|
|
lease_token = NULL,
|
|
lease_until = NULL,
|
|
error_code = NULL,
|
|
updated_at = clock_timestamp()
|
|
WHERE id = %s
|
|
""",
|
|
(job_id,),
|
|
)
|
|
|
|
# Результат уже зафиксирован. Ошибка очистки не отменяет ready.
|
|
try:
|
|
get_client().delete_object(
|
|
Bucket=bucket_name(),
|
|
Key=row["staging_key"],
|
|
)
|
|
with connect_db() as db:
|
|
db.execute(
|
|
"""
|
|
UPDATE attachments
|
|
SET staging_key = NULL
|
|
WHERE id = %s
|
|
AND staging_key = %s
|
|
AND status = 'ready'
|
|
""",
|
|
(row["attachment_id"], row["staging_key"]),
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
return "ready"
|
|
|
|
|
|
def main():
|
|
memory_bytes = int(os.getenv("JOB_MEMORY_MB", "512")) * 1024 * 1024
|
|
cpu_seconds = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
|
|
resource.setrlimit(resource.RLIMIT_AS, (memory_bytes, memory_bytes))
|
|
resource.setrlimit(
|
|
resource.RLIMIT_CPU,
|
|
(cpu_seconds, cpu_seconds + 1),
|
|
)
|
|
|
|
from app.image_pipeline import InvalidImage
|
|
|
|
try:
|
|
outcome = execute(UUID(sys.argv[1]), UUID(sys.argv[2]))
|
|
result = {"outcome": outcome}
|
|
except InvalidImage:
|
|
result = {"outcome": "failed", "error_code": "invalid_image"}
|
|
except MemoryError:
|
|
result = {"outcome": "failed", "error_code": "resource_limit"}
|
|
except Exception:
|
|
result = {"outcome": "retry", "error_code": "processing_failed"}
|
|
|
|
print(json.dumps(result), flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|