|
| 1 | +import os |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from datetime import datetime, timezone |
| 5 | +from typing import Any, Dict, List |
| 6 | + |
| 7 | +import boto3 |
| 8 | +from botocore.config import Config |
| 9 | +from botocore.exceptions import ClientError |
| 10 | +from llama_index.core import Document |
| 11 | + |
| 12 | + |
| 13 | +class S3Client: |
| 14 | + def __init__(self): |
| 15 | + # Get AWS S3 environment variables |
| 16 | + self.endpoint_url = os.getenv("AWS_ENDPOINT_URL") |
| 17 | + self.access_key = os.getenv("AWS_ACCESS_KEY_ID") |
| 18 | + self.secret_key = os.getenv("AWS_SECRET_ACCESS_KEY") |
| 19 | + self.bucket_name = os.getenv("AWS_S3_BUCKET") |
| 20 | + self.region = os.getenv("AWS_REGION") |
| 21 | + self.secure = os.getenv("AWS_SECURE", "true").lower() == "true" |
| 22 | + |
| 23 | + # Check each required variable and log if missing |
| 24 | + missing_vars = [] |
| 25 | + if not self.endpoint_url: |
| 26 | + missing_vars.append("AWS_ENDPOINT_URL") |
| 27 | + if not self.access_key: |
| 28 | + missing_vars.append("AWS_ACCESS_KEY_ID") |
| 29 | + if not self.secret_key: |
| 30 | + missing_vars.append("AWS_SECRET_ACCESS_KEY") |
| 31 | + if not self.bucket_name: |
| 32 | + missing_vars.append("AWS_S3_BUCKET") |
| 33 | + if not self.region: |
| 34 | + missing_vars.append("AWS_REGION") |
| 35 | + |
| 36 | + if missing_vars: |
| 37 | + error_msg = ( |
| 38 | + f"Missing required environment variables: {', '.join(missing_vars)}" |
| 39 | + ) |
| 40 | + logging.error(error_msg) |
| 41 | + raise ValueError(error_msg) |
| 42 | + |
| 43 | + logging.info( |
| 44 | + f"Initializing S3 client with endpoint: {self.endpoint_url}, " |
| 45 | + f"bucket: {self.bucket_name}, region: {self.region}, secure: {self.secure}" |
| 46 | + ) |
| 47 | + |
| 48 | + # Configure S3 client |
| 49 | + config = Config( |
| 50 | + signature_version="s3v4", |
| 51 | + region_name=self.region, |
| 52 | + ) |
| 53 | + |
| 54 | + self.s3_client = boto3.client( |
| 55 | + "s3", |
| 56 | + endpoint_url=self.endpoint_url, |
| 57 | + aws_access_key_id=self.access_key, |
| 58 | + aws_secret_access_key=self.secret_key, |
| 59 | + config=config, |
| 60 | + verify=self.secure, |
| 61 | + ) |
| 62 | + |
| 63 | + # Ensure bucket exists |
| 64 | + try: |
| 65 | + self.s3_client.head_bucket(Bucket=self.bucket_name) |
| 66 | + logging.info(f"Successfully connected to bucket: {self.bucket_name}") |
| 67 | + except ClientError as e: |
| 68 | + if e.response["Error"]["Code"] == "404": |
| 69 | + logging.info(f"Creating bucket: {self.bucket_name}") |
| 70 | + self.s3_client.create_bucket( |
| 71 | + Bucket=self.bucket_name, |
| 72 | + CreateBucketConfiguration={"LocationConstraint": self.region}, |
| 73 | + ) |
| 74 | + logging.info(f"Successfully created bucket: {self.bucket_name}") |
| 75 | + else: |
| 76 | + logging.error(f"Error accessing bucket {self.bucket_name}: {str(e)}") |
| 77 | + raise |
| 78 | + |
| 79 | + def _get_key(self, community_id: str, activity_type: str, timestamp: str) -> str: |
| 80 | + """Generate a unique S3 key for the data.""" |
| 81 | + return f"{community_id}/{activity_type}/{timestamp}.json" |
| 82 | + |
| 83 | + def store_extracted_data(self, community_id: str, data: Dict[str, Any]) -> str: |
| 84 | + """Store extracted data in S3.""" |
| 85 | + timestamp = datetime.now(tz=timezone.utc).isoformat() |
| 86 | + key = self._get_key(community_id, "extracted", timestamp) |
| 87 | + |
| 88 | + self.s3_client.put_object( |
| 89 | + Bucket=self.bucket_name, |
| 90 | + Key=key, |
| 91 | + Body=json.dumps(data), |
| 92 | + ContentType="application/json", |
| 93 | + ) |
| 94 | + return key |
| 95 | + |
| 96 | + def store_transformed_data( |
| 97 | + self, community_id: str, documents: List[Document] |
| 98 | + ) -> str: |
| 99 | + """Store transformed documents in S3.""" |
| 100 | + timestamp = datetime.now(tz=timezone.utc).isoformat() |
| 101 | + key = self._get_key(community_id, "transformed", timestamp) |
| 102 | + |
| 103 | + # Convert Documents to dict for JSON serialization |
| 104 | + docs_data = [doc.to_dict() for doc in documents] |
| 105 | + |
| 106 | + self.s3_client.put_object( |
| 107 | + Bucket=self.bucket_name, |
| 108 | + Key=key, |
| 109 | + Body=json.dumps(docs_data), |
| 110 | + ContentType="application/json", |
| 111 | + ) |
| 112 | + return key |
| 113 | + |
| 114 | + def get_data_by_key(self, key: str) -> Dict[str, Any]: |
| 115 | + """Get data from S3 using a specific key.""" |
| 116 | + try: |
| 117 | + obj = self.s3_client.get_object(Bucket=self.bucket_name, Key=key) |
| 118 | + return json.loads(obj["Body"].read().decode("utf-8")) |
| 119 | + except ClientError as e: |
| 120 | + if e.response["Error"]["Code"] == "NoSuchKey": |
| 121 | + logging.error(f"No data found for key: {key}") |
| 122 | + raise ValueError(f"No data found for key: {key}") |
| 123 | + logging.error(f"Error retrieving data for key {key}: {str(e)}") |
| 124 | + raise |
0 commit comments