"""Bounded supervisor: one disposable OS process per job, hard wall-clock and RAM limits.""" import hashlib import io import multiprocessing import resource import signal import tempfile import time from pathlib import Path from uuid import uuid4 import redis from pydantic import ValidationError from messenger.attachments import image_type from messenger.broker import GROUP, STREAM, Broker, Job from messenger.domain import DomainError from messenger.faults import PermanentFailure, checkpoint from messenger.images import variants from messenger.pipeline import Pipeline, event from messenger.repository import PostgresRepository from messenger.settings import Settings from messenger.storage import ObjectStore def verify_effect(store, row): records = [row, *row["variants"]] if len(records) != 4 or {v["name"] for v in row["variants"]} != { "thumbnail", "crop", "optimized", }: raise DomainError(503, "unavailable", "Incomplete result") for item in records: head = store.head(item["object_key"]) if ( not head or head["ContentLength"] != item["size_bytes"] or head["Metadata"].get("sha256") != item["sha256"] ): raise DomainError(503, "unavailable", "Incomplete result") def handle(db, broker, store, settings, id, payload): try: job = Job.model_validate_json(payload) except ValidationError: broker.quarantine(id, "invalid_envelope") return pipeline = Pipeline(db, settings) outcome, row = pipeline.claim(job) if outcome == "busy": return # Leave pending. Watchdog recovers the DB lease and schedules a retry. if outcome == "unknown": broker.quarantine(id, "unknown_job") return if outcome == "ready": verify_effect(store, row) broker.ack(id) return if outcome != "claimed": broker.ack(id) # Failed registry / obsolete version / durable retry owns this work. return try: checkpoint(db, settings, job.job_id, "before_effect") with tempfile.TemporaryFile() as original: body = store.download({**row, "object_key": row["source_key"]}) size, digest = 0, hashlib.sha256() try: while chunk := body.read(65536): size += len(chunk) if size > settings.max_upload_bytes: raise PermanentFailure digest.update(chunk) original.write(chunk) finally: body.close() if size != row["size_bytes"] or digest.hexdigest() != row["sha256"]: raise PermanentFailure image_type(original, settings.max_image_pixels) prefix = f"objects/{row['id']}/v{row['pipeline_version']}/" original_key = prefix + "original" store.put(original_key, original, size, row["content_type"], digest.hexdigest()) checkpoint(db, settings, job.job_id, "after_effect") records = [] for name, data, (width, height), media in variants(original, row["pipeline_version"]): checksum = hashlib.sha256(data).hexdigest() key = prefix + name store.put(key, io.BytesIO(data), len(data), media, checksum) records.append( { "name": name, "content_type": media, "size_bytes": len(data), "sha256": checksum, "width": width, "height": height, "object_key": key, } ) with db.connection(write=True) as conn: event(conn, job.job_id, "objects_written", version=row["pipeline_version"]) committed = pipeline.publish(row, original_key, records) if committed: checkpoint(db, settings, job.job_id, "after_commit") broker.ack(id) except PermanentFailure: pipeline.failure(row, "invalid_image", permanent=True) broker.ack(id) except MemoryError: pipeline.failure(row, "resource_limit", permanent=True) broker.ack(id) except DomainError as exc: pipeline.failure( row, "invalid_image" if exc.status in (413, 415) else "storage_unavailable", permanent=exc.status in (413, 415), ) broker.ack(id) except redis.RedisError: # Result may already be committed; retain the pending entry for a verified no-op. raise except Exception: pipeline.failure(row, "processing_failed") broker.ack(id) def child(settings, id, payload): # Linux hard limit includes Pillow buffers and native allocations. Supervisor kills hangs. resource.setrlimit(resource.RLIMIT_AS, (768 * 1024**2, 768 * 1024**2)) db = PostgresRepository(settings.database_url, pool_size=2) db.open() broker, store = Broker(settings), ObjectStore(settings) try: handle(db, broker, store, settings, id, payload) except redis.RedisError, DomainError: pass # Do not emit secret-bearing driver tracebacks; leave pending / lease intact. finally: store.close() broker.close() db.close() def main(): settings = Settings.from_env() broker = Broker(settings) consumer, cursor = uuid4().hex, "0-0" context = multiprocessing.get_context("spawn") active, running = [], True def stop(*_): nonlocal running running = False signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) try: while running: for process, deadline in active[:]: if not process.is_alive() or time.monotonic() > deadline: if process.is_alive(): process.kill() process.join() active.remove((process, deadline)) process.close() Path("/tmp/worker-heartbeat").touch() if len(active) >= settings.worker_concurrency: time.sleep(0.05) continue try: broker.group() reclaimed = broker.client.xautoclaim( STREAM, GROUP, consumer, settings.lease_seconds * 1000, cursor, count=1 ) cursor, entries = reclaimed[0], reclaimed[1] if not entries: result = broker.client.xreadgroup( GROUP, consumer, {STREAM: ">"}, count=1, block=200 ) entries = result[0][1] if result else [] if entries: id, fields = entries[0] process = context.Process( target=child, args=(settings, id, fields.get("job", "")) ) process.start() active.append((process, time.monotonic() + settings.job_timeout)) except redis.RedisError: time.sleep(0.5) finally: for process, _ in active: if process.is_alive(): process.kill() process.join() broker.close() if __name__ == "__main__": main()