"""Store scan images in private R2 and their results in Supabase.""" import json import logging import os from urllib.request import Request, urlopen from uuid import uuid4 logger = logging.getLogger(__name__) REQUIRED_SETTINGS = ( "R2_ENDPOINT_URL", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY", "R2_BUCKET_NAME", "SUPABASE_URL", "SUPABASE_SECRET_KEY", ) def r2_client(settings): import boto3 from botocore.config import Config return boto3.client( "s3", endpoint_url=settings["R2_ENDPOINT_URL"], aws_access_key_id=settings["R2_ACCESS_KEY_ID"], aws_secret_access_key=settings["R2_SECRET_ACCESS_KEY"], region_name="auto", config=Config(connect_timeout=5, read_timeout=10, retries={"max_attempts": 1}), ) def save_scan(image_bytes: bytes, result: dict) -> dict: settings = {name: os.environ.get(name, "") for name in REQUIRED_SETTINGS} if not all(settings.values()): return {"status": "not_configured"} scan_id = str(uuid4()) image_key = f"scans/{scan_id}.jpg" try: r2_client(settings).put_object( Bucket=settings["R2_BUCKET_NAME"], Key=image_key, Body=image_bytes, ContentType="image/jpeg", ) except Exception as exc: # Log only the exception type; provider messages can contain credentials. logger.error("R2 scan upload failed (%s)", type(exc).__name__) return {"status": "failed"} row = {"id": scan_id, "image_key": image_key, **result} try: request = Request( f"{settings['SUPABASE_URL'].rstrip('/')}/rest/v1/scans", data=json.dumps(row).encode("utf-8"), headers={ "apikey": settings["SUPABASE_SECRET_KEY"], "Content-Type": "application/json", "Prefer": "return=minimal", }, method="POST", ) with urlopen(request, timeout=15) as response: if response.status != 201: raise OSError("Unexpected Supabase response") except Exception as exc: logger.error("Supabase scan insert failed (%s)", type(exc).__name__) # Keep the image: a timeout can occur after the database commits the row. return {"status": "partial", "id": scan_id} return {"status": "saved", "id": scan_id}