File size: 4,843 Bytes
0cfdea5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""Neon Object Storage access for original document uploads."""

from __future__ import annotations

import hashlib
from typing import Any

import boto3
from botocore.config import Config as BotoConfig
from botocore.exceptions import ClientError

from config import cfg

DOCUMENTS_BUCKET = "documents"

_REQUIRED_SETTINGS = (
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "AWS_ENDPOINT_URL_S3",
    "AWS_REGION",
)


class ObjectStorageConfigurationError(RuntimeError):
    """Raised when Neon Object Storage credentials are not configured."""


class DocumentObjectNotFoundError(FileNotFoundError):
    """Raised when a document object does not exist in the configured bucket."""


def _settings() -> dict[str, str]:
    """Return required Neon Object Storage settings.

    Raises:
        ObjectStorageConfigurationError: If one or more settings are missing.
    """
    values = {name: cfg(name) for name in _REQUIRED_SETTINGS}
    missing = [name for name, value in values.items() if not value]
    if missing:
        raise ObjectStorageConfigurationError(
            "Neon Object Storage configuration is missing: " + ", ".join(missing)
        )
    return {name: str(value) for name, value in values.items()}


def _client() -> Any:
    """Create a path-style S3 client for the current Neon branch."""
    settings = _settings()
    return boto3.client(
        "s3",
        region_name=settings["AWS_REGION"],
        endpoint_url=settings["AWS_ENDPOINT_URL_S3"],
        aws_access_key_id=settings["AWS_ACCESS_KEY_ID"],
        aws_secret_access_key=settings["AWS_SECRET_ACCESS_KEY"],
        config=BotoConfig(
            signature_version="s3v4",
            s3={"addressing_style": "path"},
        ),
    )


def document_object_key(doc_id: int, content: bytes) -> str:
    """Build a stable, filename-independent key for an original upload."""
    if doc_id < 1:
        raise ValueError("doc_id must be a positive integer")
    digest = hashlib.sha256(content).hexdigest()
    return f"{doc_id}/{digest}"


def put_document_object(
    doc_id: int,
    content: bytes,
    content_type: str | None,
) -> str:
    """Store original upload bytes and return their key."""
    key = document_object_key(doc_id, content)
    _client().put_object(
        Bucket=DOCUMENTS_BUCKET,
        Key=key,
        Body=content,
        ContentType=content_type or "application/octet-stream",
        Metadata={"doc-id": str(doc_id)},
    )
    return key


def get_document_object(key: str) -> bytes:
    """Download an original upload by its database-backed object key."""
    try:
        response = _client().get_object(Bucket=DOCUMENTS_BUCKET, Key=key)
    except ClientError as exc:
        error_code = str(exc.response.get("Error", {}).get("Code", ""))
        if error_code in {"404", "NoSuchKey", "NotFound"}:
            raise DocumentObjectNotFoundError(key) from exc
        raise

    body = response["Body"]
    try:
        return bytes(body.read())
    finally:
        close = getattr(body, "close", None)
        if close is not None:
            close()


def delete_document_object(key: str) -> None:
    """Delete one original upload from the documents bucket."""
    _client().delete_object(Bucket=DOCUMENTS_BUCKET, Key=key)


def delete_all_document_objects() -> int:
    """Delete every object in the documents bucket and return the count."""
    client = _client()
    continuation_token: str | None = None
    deleted_count = 0

    while True:
        request: dict[str, Any] = {"Bucket": DOCUMENTS_BUCKET, "MaxKeys": 1000}
        if continuation_token:
            request["ContinuationToken"] = continuation_token
        page = client.list_objects_v2(**request)
        keys = [
            str(item["Key"])
            for item in page.get("Contents", [])
            if item.get("Key") is not None
        ]
        if keys:
            result = client.delete_objects(
                Bucket=DOCUMENTS_BUCKET,
                Delete={
                    "Objects": [{"Key": key} for key in keys],
                    "Quiet": True,
                },
            )
            errors = result.get("Errors", [])
            if errors:
                raise RuntimeError(
                    f"Neon Object Storage failed to delete {len(errors)} object(s)"
                )
            deleted_count += len(keys)

        if not page.get("IsTruncated"):
            break
        continuation_token = page.get("NextContinuationToken")
        if not continuation_token:
            raise RuntimeError(
                "Neon Object Storage returned a truncated page without a token"
            )

    return deleted_count


def ping_document_bucket() -> None:
    """Verify that the configured credentials can access the documents bucket."""
    _client().head_bucket(Bucket=DOCUMENTS_BUCKET)