File size: 2,345 Bytes
2620364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""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}