tech-trans-rag / infrastructure /object_storage.py
phaethon-order's picture
feat: integrate Neon Object Storage for document uploads and retrieval
0cfdea5
Raw History Blame Contribute Delete
4.84 kB
"""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)