This commit is contained in:
2026-11-06 21:15:31 +03:00
parent 276dbdad8a
commit ef7e8c389e
219 changed files with 15212 additions and 57 deletions
+8
View File
@@ -0,0 +1,8 @@
FROM python:3.12.12-slim
WORKDIR /app
COPY worker/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt && useradd --system --uid 10001 worker
COPY worker/pipeline ./pipeline
USER worker
ENV PYTHONUNBUFFERED=1
CMD ["python", "-m", "pipeline.main"]
View File
+42
View File
@@ -0,0 +1,42 @@
import json
PUBLISH = """
local previous = redis.call('HGET', KEYS[2], ARGV[1])
if previous then
local attempt, id = string.match(previous, '^(%d+)|(%d+%-%d+)$')
if attempt == ARGV[2] and #redis.call('XRANGE', KEYS[1], id, id, 'COUNT', 1) > 0 then
return {id, 0}
end
end
local id = redis.call('XADD', KEYS[1], '*', 'job', ARGV[3])
redis.call('HSET', KEYS[2], ARGV[1], ARGV[2] .. '|' .. id)
return {id, 1}
"""
ACK = """
redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
redis.call('XDEL', KEYS[1], ARGV[2])
local previous = redis.call('HGET', KEYS[2], ARGV[3])
if previous then
local attempt, id = string.match(previous, '^(%d+)|(%d+%-%d+)$')
if id == ARGV[2] then redis.call('HDEL', KEYS[2], ARGV[3]) end
end
return 1
"""
def publish(broker, settings, payload):
result = broker.eval(
PUBLISH,
2,
settings.stream,
"job-publications",
payload["job_id"],
payload["attempt"],
json.dumps(payload),
)
return bool(result[1])
def acknowledge(broker, settings, message_id, job_id=""):
broker.eval(ACK, 2, settings.stream, "job-publications", settings.group, message_id, job_id)
+64
View File
@@ -0,0 +1,64 @@
from datetime import datetime, timezone, timedelta
class Cleanup:
def __init__(self, repository, storage):
self.repository = repository
self.storage = storage
def run(self):
with self.repository.connection() as db:
row = db.execute("SELECT pg_try_advisory_xact_lock(741204) AS acquired").fetchone()
if not row["acquired"]:
return
self._clear_failed(db)
self._clear_ready(db)
self._scan(db)
def _clear_ready(self, db):
rows = db.execute(
"""SELECT id,staging_key FROM attachments WHERE status='READY'
AND staging_key IS NOT NULL LIMIT 100 FOR UPDATE SKIP LOCKED"""
).fetchall()
for row in rows:
self.storage.client.delete_object(
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
)
db.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (row["id"],))
def _clear_failed(self, db):
rows = db.execute(
"""SELECT id,staging_key,pipeline_version FROM attachments WHERE status='FAILED'
AND staging_key IS NOT NULL AND updated_at < now() - %s * interval '1 second'
LIMIT 100 FOR UPDATE SKIP LOCKED""",
(self.storage.settings.retention,),
).fetchall()
for row in rows:
self.storage.client.delete_object(
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
)
db.execute(
"UPDATE attachments SET staging_key=NULL,error_code='staging_expired' WHERE id=%s",
(row["id"],),
)
db.execute(
"UPDATE processing_jobs SET error_code='staging_expired' WHERE attachment_id=%s AND pipeline_version=%s",
(row["id"], row["pipeline_version"]),
)
def _scan(self, db):
cutoff = datetime.now(timezone.utc) - timedelta(seconds=self.storage.settings.retention)
pages = self.storage.client.get_paginator("list_objects_v2")
for page in pages.paginate(Bucket=self.storage.settings.bucket):
for item in page.get("Contents", []):
if item["LastModified"] < cutoff and not self._referenced(db, item["Key"]):
self.storage.client.delete_object(
Bucket=self.storage.settings.bucket, Key=item["Key"]
)
def _referenced(self, db, key):
return db.execute(
"""SELECT 1 FROM attachments WHERE object_key=%s OR staging_key=%s
UNION ALL SELECT 1 FROM attachment_variants WHERE object_key=%s LIMIT 1""",
(key, key, key),
).fetchone()
+24
View File
@@ -0,0 +1,24 @@
import os
from dataclasses import dataclass
from pathlib import Path
def secret(name):
return Path("/run/secrets/" + name).read_text().strip()
@dataclass(frozen=True)
class Settings:
db_host: str = os.getenv("DB_HOST", "db")
broker_host: str = os.getenv("BROKER_HOST", "broker")
bucket: str = os.getenv("S3_BUCKET", "messenger-attachments")
endpoint: str = os.getenv("S3_ENDPOINT", "http://minio:9000")
max_attempts: int = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
timeout: int = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
retention: int = int(os.getenv("STAGING_RETENTION_SECONDS", "86400"))
lease: int = int(os.getenv("JOB_LEASE_SECONDS", "75"))
faults: bool = os.getenv("FAULT_INJECTION_ENABLED", "false").lower() == "true"
max_bytes: int = 10485760
max_pixels: int = 40000000
stream: str = "attachment-jobs"
group: str = "image-workers"
+16
View File
@@ -0,0 +1,16 @@
import os
import time
def inject(repository, job, point):
action = repository.fault(job, point)
if action == "crash":
os._exit(71)
if action == "pause":
time.sleep(12)
if action == "timeout":
time.sleep(repository.settings.timeout + 5)
if action == "transient":
raise TimeoutError("injected_transient")
if action == "permanent":
raise ValueError("injected_permanent")
+63
View File
@@ -0,0 +1,63 @@
import io
import warnings
from PIL import Image, ImageOps
class ImagePipeline:
def __init__(self, settings, version=1):
self.settings = settings
self.jpeg_quality = 85 if version == 1 else 90
self.webp_quality = 80 if version == 1 else 85
Image.MAX_IMAGE_PIXELS = settings.max_pixels
warnings.simplefilter("error", Image.DecompressionBombWarning)
def render(self, data):
with Image.open(io.BytesIO(data)) as source:
self.validate(source)
source.load()
ImageOps.exif_transpose(source, in_place=True)
image = self.flatten(source)
try:
yield self.scaled(image, "thumbnail", 256, "JPEG", self.jpeg_quality)
yield self.crop(image)
yield self.scaled(image, "optimized", 1280, "WEBP", self.webp_quality)
finally:
image.close()
def validate(self, image):
if image.format not in ("PNG", "JPEG"):
raise ValueError("invalid_image")
if image.width * image.height > self.settings.max_pixels:
raise ValueError("image_too_large")
def flatten(self, image):
if "A" in image.getbands() or "transparency" in image.info:
with image.convert("RGBA") as alpha:
result = Image.new("RGB", alpha.size, "white")
result.paste(alpha, mask=alpha.getchannel("A"))
return result
return image.convert("RGB")
def scaled(self, image, name, limit, format_name, quality):
divisor = max(limit, image.width, image.height)
size = (max(1, image.width * limit // divisor), max(1, image.height * limit // divisor))
with image.resize(size, Image.Resampling.LANCZOS) as resized:
return self.encode(resized, name, format_name, quality)
def crop(self, image):
with ImageOps.fit(
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
) as cropped:
return self.encode(cropped, "crop", "JPEG", self.jpeg_quality)
def encode(self, image, name, format_name, quality):
output = io.BytesIO()
image.info.clear()
image.save(output, format=format_name, quality=quality)
return {
"name": name,
"data": output.getvalue(),
"width": image.width,
"height": image.height,
"content_type": "image/jpeg" if format_name == "JPEG" else "image/webp",
}
+124
View File
@@ -0,0 +1,124 @@
import json
import os
import subprocess
import sys
import time
import uuid
from datetime import datetime
import redis
from .config import Settings
from .repository import Repository
from .cleanup import Cleanup
from .storage import Storage
from .outbox import OutboxDispatcher
from .faults import inject
from .broker import acknowledge
def validate_message(payload):
required = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
allowed = required | {"traceparent", "tracestate"}
if not isinstance(payload, dict) or not required.issubset(payload) or set(payload) - allowed:
raise ValueError("invalid_job_fields")
if (
type(payload["schema_version"]) is not int
or payload["schema_version"] != 1
or payload["type"] != "attachment.process.v1"
):
raise ValueError("invalid_job_type")
if any(not isinstance(payload[key], str) for key in ("job_id", "attachment_id", "created_at")):
raise ValueError("invalid_job_strings")
uuid.UUID(payload["job_id"])
uuid.UUID(payload["attachment_id"])
for key in ("pipeline_version", "attempt"):
if type(payload[key]) is not int or payload[key] < 1:
raise ValueError("invalid_job_counter")
if datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")).tzinfo is None:
raise ValueError("invalid_job_time")
def handle(broker, settings, repository, item):
message_id, fields = item
try:
payload = json.loads(fields["job"])
validate_message(payload)
except (ValueError, KeyError, TypeError):
acknowledge(broker, settings, message_id)
print(json.dumps({"event": "rejected_job"}), flush=True)
return
try:
result = subprocess.run(
[sys.executable, "-m", "pipeline.process", json.dumps(payload)],
timeout=settings.timeout,
)
except subprocess.TimeoutExpired:
with repository.connection() as db:
repository.event(db, payload, "worker_timeout")
return
if result.returncode == 0:
inject(repository, payload, "before_ack")
acknowledge(broker, settings, message_id, payload["job_id"])
elif result.returncode == 75:
time.sleep(0.25)
def messages(broker, settings, consumer):
pending = broker.xreadgroup(settings.group, consumer, {settings.stream: "0"}, count=1)
if pending and pending[0][1]:
return pending[0][1]
claimed = broker.xautoclaim(
settings.stream, settings.group, consumer, settings.lease * 1000, "0-0", count=1
)
if claimed[1]:
return claimed[1]
rows = broker.xreadgroup(settings.group, consumer, {settings.stream: ">"}, count=1, block=1000)
return rows[0][1] if rows else []
def consume(broker, settings, repository, consumer):
try:
broker.xgroup_create(settings.stream, settings.group, id="0", mkstream=True)
except redis.ResponseError as error:
if "BUSYGROUP" not in str(error):
raise
for item in messages(broker, settings, consumer):
handle(broker, settings, repository, item)
def main():
settings = Settings()
repository = Repository(settings)
broker = redis.Redis(
host=settings.broker_host, decode_responses=True, socket_connect_timeout=3, socket_timeout=3
)
cleanup = Cleanup(repository, Storage(settings))
consumer = str(uuid.uuid4())
dispatcher = OutboxDispatcher(repository, broker)
cleaned = 0
while True:
try:
if os.getenv("ROLE", "worker") == "dispatcher":
dispatcher.run()
if time.monotonic() - cleaned > 60:
cleanup.run()
cleaned = time.monotonic()
time.sleep(0.5)
else:
consume(broker, settings, repository, consumer)
except Exception as error:
print(
json.dumps({"event": "loop_error", "error_type": type(error).__name__}), flush=True
)
time.sleep(1)
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
import argparse
import json
import uuid
from .config import Settings
from .repository import Repository
def enqueue(db, attachment, version, settings):
job_id = uuid.uuid4()
row = db.execute(
"""INSERT INTO processing_jobs(job_id,attachment_id,pipeline_version,attempt_limit)
VALUES (%s,%s,%s,%s) RETURNING created_at""",
(job_id, attachment, version, settings.max_attempts),
).fetchone()
payload = {
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(attachment),
"pipeline_version": version,
"attempt": 1,
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
}
db.execute(
"INSERT INTO processing_outbox(job_id,payload) VALUES (%s,%s::jsonb)",
(job_id, json.dumps(payload)),
)
return {"job_id": job_id, "attempt": 0}
def upgrade(repository, attachment, version):
with repository.connection() as db:
db.execute("SELECT pg_advisory_xact_lock_shared(741204)")
current = db.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment,)
).fetchone()
if not current or version <= current["pipeline_version"]:
raise ValueError("version_must_increase")
db.execute(
"UPDATE processing_jobs SET status='SUPERSEDED',lease_until=NULL WHERE attachment_id=%s AND status IN ('QUEUED','PROCESSING','FAILED')",
(attachment,),
)
db.execute(
"UPDATE attachments SET pipeline_version=%s,status='QUEUED',error_code=NULL,updated_at=now() WHERE id=%s",
(version, attachment),
)
job = enqueue(db, attachment, version, repository.settings)
repository.event(db, job, "operator_upgrade")
return {"event": "upgraded", "version": version}
def replay(repository, attachment):
with repository.connection() as db:
db.execute("SELECT pg_advisory_xact_lock_shared(741204)")
current = db.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment,)
).fetchone()
if not current:
raise ValueError("attachment_not_found")
job = db.execute(
"SELECT * FROM processing_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(attachment, current["pipeline_version"]),
).fetchone()
if job["status"] == "READY":
repository.event(db, job, "operator_replay_noop")
return {"event": "already_ready", "replayed": False}
if job["error_code"] == "staging_expired":
raise ValueError("staging_expired")
if job["status"] != "FAILED":
raise ValueError("only_failed_can_be_replayed")
reset(db, job, repository.settings.max_attempts)
repository.event(db, job, "operator_replay")
return {"event": "replayed", "replayed": True}
def reset(db, job, budget):
db.execute(
"""UPDATE processing_jobs SET status='QUEUED',error_code=NULL,lease_token=NULL,
lease_until=NULL,completed_at=NULL,attempt_limit=attempt+%s,next_at=now(),next_publish_at=now() WHERE job_id=%s""",
(budget, job["job_id"]),
)
db.execute(
"UPDATE attachments SET status='QUEUED',error_code=NULL,updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=["upgrade", "replay"])
parser.add_argument("attachment", type=uuid.UUID)
parser.add_argument("--version", type=int, default=2)
args = parser.parse_args()
repository = Repository(Settings())
result = (
upgrade(repository, args.attachment, args.version)
if args.action == "upgrade"
else replay(repository, args.attachment)
)
print(json.dumps(result), flush=True)
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
from .faults import inject
from .broker import publish
class OutboxDispatcher:
def __init__(self, repository, broker):
self.repository = repository
self.broker = broker
def run(self):
self.recover_expired()
with self.repository.connection() as db:
rows = db.execute(
"""SELECT j.*,o.payload,o.published_at AS previous_publish FROM processing_jobs j
JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version
JOIN processing_outbox o ON o.job_id=j.job_id
WHERE j.status='QUEUED' AND j.next_at<=now() AND j.next_publish_at<=now()
ORDER BY j.created_at LIMIT 20 FOR UPDATE OF o SKIP LOCKED"""
).fetchall()
for job in rows:
self.publish(db, job)
def publish(self, db, job):
inject(self.repository, job, "before_publish")
payload = dict(job["payload"], attempt=job["attempt"] + 1)
created = publish(self.broker, self.repository.settings, payload)
inject(self.repository, job, "after_publish")
db.execute(
"UPDATE processing_jobs SET next_publish_at=now()+interval '10 seconds' WHERE job_id=%s",
(job["job_id"],),
)
db.execute(
"UPDATE processing_outbox SET published_at=now(),publish_count=publish_count+1 WHERE job_id=%s",
(job["job_id"],),
)
if created or job["previous_publish"] is None:
self.repository.event(db, dict(job, attempt=payload["attempt"]), "published")
def recover_expired(self):
with self.repository.connection() as db:
rows = db.execute(
"""SELECT j.* FROM processing_jobs j
JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version
WHERE j.status='PROCESSING' AND j.lease_until<now()
LIMIT 20 FOR UPDATE OF a,j SKIP LOCKED"""
).fetchall()
for job in rows:
terminal = job["attempt"] >= job["attempt_limit"]
code = "retry_exhausted" if terminal else "lease_expired"
self.repository.set_failure(db, job, "FAILED" if terminal else "QUEUED", code, 1)
self.repository.event(db, job, "lease_expired")
+77
View File
@@ -0,0 +1,77 @@
import hashlib
import json
import resource
import sys
from PIL import UnidentifiedImageError, Image
from .config import Settings
from .repository import Repository
from .storage import Storage
from .images import ImagePipeline
from .faults import inject
def write_effects(storage, job, data, settings):
prefix = f"results/{job['attachment_id']}/v{job['pipeline_version']}"
original = prefix + "/original-" + job["checksum"]
storage.write_result(original, data, job["content_type"])
variants = []
for variant in ImagePipeline(settings, job["pipeline_version"]).render(data):
body = variant.pop("data")
key = prefix + "/" + variant["name"] + "-" + hashlib.sha256(body).hexdigest()
item = storage.write_result(key, body, variant["content_type"])
variants.append(
dict(item, name=variant["name"], width=variant["width"], height=variant["height"])
)
return original, variants
def process(repository, settings, job):
storage = Storage(settings)
with repository.connection() as fence:
fence.execute("SELECT pg_advisory_xact_lock_shared(741204)")
inject(repository, job, "before_effects")
data = storage.read_original(job)
original, variants = write_effects(storage, job, data, settings)
inject(repository, job, "after_effects")
published = repository.publish_result(job, original, variants)
inject(repository, job, "after_commit")
if published:
storage.remove_staging(job, repository)
print(
json.dumps(
{"event": "result", "version": job["pipeline_version"], "published": published}
),
flush=True,
)
def main():
resource.setrlimit(resource.RLIMIT_AS, (768 * 1024 * 1024, 768 * 1024 * 1024))
settings = Settings()
repository = Repository(settings)
message = json.loads(sys.argv[1])
job = repository.claim(message)
if not job:
if not repository.delivery_done(message):
sys.exit(75)
print(json.dumps({"event": "duplicate_or_stale"}), flush=True)
return
try:
process(repository, settings, job)
except (
ValueError,
UnidentifiedImageError,
Image.DecompressionBombError,
Image.DecompressionBombWarning,
MemoryError,
):
repository.fail(job, permanent=True, code="invalid_image")
except Exception as error:
repository.fail(job)
print(json.dumps({"event": "retry", "error_type": type(error).__name__}), flush=True)
if not repository.delivery_done(message):
sys.exit(75)
if __name__ == "__main__":
main()
+169
View File
@@ -0,0 +1,169 @@
import json
import random
import uuid
import psycopg
from psycopg.rows import dict_row
from .config import secret
class Repository:
def __init__(self, settings):
self.settings = settings
def connection(self):
return psycopg.connect(
host=self.settings.db_host,
dbname=secret("postgres_db"),
user=secret("postgres_user"),
password=secret("postgres_password"),
connect_timeout=3,
options="-c statement_timeout=10000",
row_factory=dict_row,
)
def event(self, db, job, name):
db.execute(
"INSERT INTO pipeline_events(job_id,event,attempt) VALUES (%s,%s,%s)",
(job["job_id"], name, job.get("attempt", 0)),
)
def claim(self, message):
with self.connection() as db:
job = self._lock_job(db, message)
if (
not job
or job["status"] != "QUEUED"
or not job["due"]
or message["attempt"] != job["attempt"] + 1
):
return None
token = uuid.uuid4()
db.execute(
"""UPDATE processing_jobs SET status='PROCESSING', attempt=attempt+1,
lease_token=%s, lease_until=now() + %s * interval '1 second' WHERE job_id=%s""",
(token, self.settings.lease, job["job_id"]),
)
db.execute(
"UPDATE attachments SET status='PROCESSING',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
job.update(lease_token=token, attempt=job["attempt"] + 1)
self.event(db, job, "claimed")
return job
def _lock_job(self, db, message):
return db.execute(
"""SELECT j.*, a.object_key, a.staging_key, a.content_type,
a.checksum, a.size_bytes, j.next_at <= now() AS due, j.lease_until > now() AS live
FROM attachments a JOIN processing_jobs j ON a.id=j.attachment_id
WHERE j.job_id=%s AND j.attachment_id=%s AND j.pipeline_version=%s
AND a.pipeline_version=j.pipeline_version
FOR UPDATE OF a,j SKIP LOCKED""",
(message["job_id"], message["attachment_id"], message["pipeline_version"]),
).fetchone()
def delivery_done(self, message):
with self.connection() as db:
row = db.execute(
"""SELECT j.status,j.attempt,a.pipeline_version FROM processing_jobs j
JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s AND j.attachment_id=%s""",
(message["job_id"], message["attachment_id"]),
).fetchone()
if not row or row["pipeline_version"] != message["pipeline_version"]:
return True
if row["status"] not in ("QUEUED", "PROCESSING"):
return True
expected = row["attempt"] + (1 if row["status"] == "QUEUED" else 0)
return message["attempt"] != expected
def publish_result(self, job, original_key, variants):
with self.connection() as db:
current = self._lock_job(db, job)
if not self._owns(current, job):
self.event(db, job, "fenced_stale_result")
return False
self._save_variants(db, job, variants)
db.execute(
"""UPDATE attachments SET object_key=%s,status='READY',error_code=NULL,
updated_at=now() WHERE id=%s AND pipeline_version=%s""",
(original_key, job["attachment_id"], job["pipeline_version"]),
)
db.execute(
"""UPDATE processing_jobs SET status='READY',completed_at=now(),
lease_until=NULL,error_code=NULL WHERE job_id=%s""",
(job["job_id"],),
)
self.event(db, job, "ready")
return True
def _owns(self, current, job):
return (
current
and current["status"] == "PROCESSING"
and current["lease_token"] == job["lease_token"]
and current["live"]
)
def _save_variants(self, db, job, variants):
for item 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 DO NOTHING""",
(
job["attachment_id"],
job["pipeline_version"],
item["name"],
item["object_key"],
item["content_type"],
item["size_bytes"],
item["width"],
item["height"],
item["sha256"],
),
)
def fail(self, job, permanent=False, code="processing_failed"):
with self.connection() as db:
current = self._lock_job(db, job)
if not self._owns(current, job):
return
terminal = permanent or job["attempt"] >= job["attempt_limit"]
status = "FAILED" if terminal else "QUEUED"
delay = min(30, 2 ** job["attempt"]) + random.uniform(0, 1)
code = code if permanent else ("retry_exhausted" if terminal else code)
self.set_failure(db, job, status, code, delay)
self.event(db, job, "failed" if terminal else "retry_scheduled")
def set_failure(self, db, job, status, code, delay):
db.execute(
"""UPDATE processing_jobs SET status=%s,error_code=%s,lease_until=NULL,
next_at=now() + %s * interval '1 second',next_publish_at=now(),
completed_at=CASE WHEN %s='FAILED' THEN now() ELSE NULL END WHERE job_id=%s""",
(status, code, delay, status, job["job_id"]),
)
db.execute(
"UPDATE attachments SET status=%s,error_code=%s,updated_at=now() WHERE id=%s",
(status, code if status == "FAILED" else None, job["attachment_id"]),
)
def clear_staging(self, job):
with self.connection() as db:
result = db.execute(
"""UPDATE attachments SET staging_key=NULL WHERE id=%s AND pipeline_version=%s
AND status='READY' AND staging_key=%s""",
(job["attachment_id"], job["pipeline_version"], job["staging_key"]),
)
return result.rowcount == 1
def fault(self, job, point):
if not self.settings.faults:
return None
with self.connection() as db:
row = db.execute(
"""UPDATE pipeline_faults SET remaining=remaining-1,hits=hits+1
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s AND remaining>0
RETURNING action""",
(job["attachment_id"], job["pipeline_version"], point),
).fetchone()
return row["action"] if row else None
+62
View File
@@ -0,0 +1,62 @@
import hashlib
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from .config import secret
class Storage:
def __init__(self, settings):
self.settings = settings
self.client = boto3.client(
"s3",
endpoint_url=settings.endpoint,
region_name="us-east-1",
aws_access_key_id=secret("s3_access_key_id"),
aws_secret_access_key=secret("s3_secret_access_key"),
config=Config(
connect_timeout=3,
read_timeout=10,
retries={"max_attempts": 1},
s3={"addressing_style": "path"},
),
)
def read_original(self, job):
key = job["staging_key"] or job["object_key"]
try:
data = self._read(key)
except ClientError as error:
if error.response["Error"]["Code"] != "NoSuchKey" or key == job["object_key"]:
raise
data = self._read(job["object_key"])
if (
len(data) > self.settings.max_bytes
or len(data) != job["size_bytes"]
or hashlib.sha256(data).hexdigest() != job["checksum"]
):
raise ValueError("invalid_staging")
return data
def _read(self, key):
response = self.client.get_object(Bucket=self.settings.bucket, Key=key)
with response["Body"] as stream:
return stream.read(self.settings.max_bytes + 1)
def write_result(self, key, data, content_type):
self.client.put_object(
Bucket=self.settings.bucket, Key=key, Body=data, ContentType=content_type
)
return {
"object_key": key,
"content_type": content_type,
"size_bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
}
def remove_staging(self, job, repository):
if not job["staging_key"]:
return
if not repository.clear_staging(job):
return
self.client.delete_object(Bucket=self.settings.bucket, Key=job["staging_key"])
+4
View File
@@ -0,0 +1,4 @@
Pillow==12.0.0
redis==6.4.0
psycopg[binary]==3.2.10
boto3==1.40.59