Spaces:
Runtime error
Runtime error
Download app/services/storage.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/storage.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/services/storage.py
-
curl -L -o storage.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/storage.py
17.3 kB
| # Copyright (C) 2026 Mattia Zatelli | |
| # | |
| # This program is free software: you can redistribute it and/or modify | |
| # it under the terms of the GNU Affero General Public License as published by | |
| # the Free Software Foundation, either version 3 of the License, or | |
| # (at your option) any later version. | |
| # | |
| # This program is distributed in the hope that it will be useful, | |
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
| # GNU Affero General Public License for more details. | |
| # | |
| # You should have received a copy of the GNU Affero General Public License | |
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | |
| """ | |
| Service for storage management and file management | |
| This service coordinates all storage operations: | |
| - IFC file upload to S3/MinIO with validation | |
| - Versioning management and automatic backup | |
| - Intelligent compression for space optimization | |
| - Presigned URLs for secure downloads | |
| - Automatic cleanup of temporary files | |
| - Storage metrics and cost optimization | |
| - Encryption at rest and in transit | |
| Supports multiple storage tiers for cost optimization | |
| with automatic lifecycle policies. | |
| """ | |
| import logging | |
| import gzip | |
| import zstandard as zstd | |
| import hashlib | |
| import io | |
| from typing import Dict, Any, Optional, Union, Tuple, List, BinaryIO | |
| from datetime import datetime | |
| import aioboto3 | |
| from botocore.exceptions import ClientError | |
| from app.core.config import get_settings | |
| logger = logging.getLogger(__name__) | |
| settings = get_settings() | |
| class StorageError(Exception): | |
| """Custom exception for storage operations""" | |
| pass | |
| class CompressionType: | |
| """Supported compression types""" | |
| GZIP = "gzip" | |
| ZSTD = "zstd" | |
| NONE = "none" | |
| class StorageService: | |
| """Enhanced storage service with compression support""" | |
| def __init__(self): | |
| self.settings = get_settings() | |
| self._s3_client = None | |
| async def get_s3_client(self): | |
| """Get or create S3 client""" | |
| if not self._s3_client: | |
| session = aioboto3.Session() | |
| self._s3_client = await session.client( | |
| 's3', | |
| endpoint_url=self.settings.S3_ENDPOINT, | |
| aws_access_key_id=self.settings.S3_ACCESS_KEY, | |
| aws_secret_access_key=self.settings.S3_SECRET_KEY, | |
| region_name=self.settings.S3_REGION, | |
| use_ssl=self.settings.S3_SECURE | |
| ).__aenter__() | |
| return self._s3_client | |
| async def compress_and_store_ifc( | |
| self, | |
| stream: BinaryIO, | |
| s3_key: str, | |
| bucket: str = None, | |
| codec: str = None, | |
| level: int = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Compress stream and store in S3 | |
| Args: | |
| stream: Input stream to compress and store | |
| s3_key: S3 key for storage | |
| bucket: S3 bucket (uses default if None) | |
| codec: Compression codec (gzip, zstd, or none) | |
| level: Compression level | |
| Returns: | |
| Dict with storage metadata | |
| """ | |
| bucket = bucket or self.settings.S3_BUCKET | |
| codec = codec or self.settings.IFC_COMPRESSION | |
| level = level or self.settings.IFC_COMPRESSION_LEVEL | |
| logger.info(f"Compressing and storing file with {codec} level {level} to s3://{bucket}/{s3_key}") | |
| try: | |
| # Read and track original data | |
| original_data = stream.read() | |
| original_size = len(original_data) | |
| original_hash = hashlib.sha256(original_data).hexdigest() | |
| # Compress data | |
| compressed_data, compression_info = await self._compress_data( | |
| original_data, codec, level | |
| ) | |
| compressed_size = len(compressed_data) | |
| compressed_hash = hashlib.sha256(compressed_data).hexdigest() | |
| # Upload to S3 | |
| s3_client = await self.get_s3_client() | |
| # Determine content type and encoding | |
| content_type = "application/octet-stream" | |
| content_encoding = None | |
| if codec == CompressionType.GZIP: | |
| content_encoding = "gzip" | |
| elif codec == CompressionType.ZSTD: | |
| content_type = "application/zstd" | |
| # Upload with metadata | |
| extra_args = { | |
| 'ContentType': content_type, | |
| 'Metadata': { | |
| 'original-size': str(original_size), | |
| 'original-hash': original_hash, | |
| 'compression-type': codec, | |
| 'compression-level': str(level), | |
| 'compressed-hash': compressed_hash, | |
| 'compression-ratio': str(round(compressed_size / original_size, 3)) if original_size > 0 else '1.0', | |
| 'uploaded-at': datetime.now().isoformat() | |
| } | |
| } | |
| if content_encoding: | |
| extra_args['ContentEncoding'] = content_encoding | |
| await s3_client.put_object( | |
| Bucket=bucket, | |
| Key=s3_key, | |
| Body=compressed_data, | |
| **extra_args | |
| ) | |
| storage_metadata = { | |
| 'bucket': bucket, | |
| 's3_key': s3_key, | |
| 'original_size': original_size, | |
| 'compressed_size': compressed_size, | |
| 'compression_type': codec, | |
| 'compression_level': level, | |
| 'compression_ratio': round(compressed_size / original_size, 3) if original_size > 0 else 1.0, | |
| 'original_hash': original_hash, | |
| 'compressed_hash': compressed_hash, | |
| 'space_saved': original_size - compressed_size, | |
| 'space_saved_percent': round((1 - compressed_size / original_size) * 100, 1) if original_size > 0 else 0, | |
| **compression_info | |
| } | |
| logger.info( | |
| f"Successfully stored compressed file: {original_size} -> {compressed_size} bytes " | |
| f"({storage_metadata['space_saved_percent']}% saved)" | |
| ) | |
| return storage_metadata | |
| except Exception as e: | |
| logger.error(f"Failed to compress and store file: {e}") | |
| raise StorageError(f"Storage operation failed: {str(e)}") | |
| async def _compress_data(self, data: bytes, codec: str, level: int) -> Tuple[bytes, Dict[str, Any]]: | |
| """Compress data using specified codec""" | |
| start_time = datetime.now() | |
| if codec == CompressionType.GZIP: | |
| compressed_data = gzip.compress(data, compresslevel=level) | |
| compression_info = { | |
| 'algorithm': 'gzip', | |
| 'parameters': {'level': level} | |
| } | |
| elif codec == CompressionType.ZSTD: | |
| compressor = zstd.ZstdCompressor(level=level) | |
| compressed_data = compressor.compress(data) | |
| compression_info = { | |
| 'algorithm': 'zstandard', | |
| 'parameters': {'level': level} | |
| } | |
| elif codec == CompressionType.NONE: | |
| compressed_data = data | |
| compression_info = { | |
| 'algorithm': 'none', | |
| 'parameters': {} | |
| } | |
| else: | |
| raise StorageError(f"Unsupported compression codec: {codec}") | |
| compression_time_ms = int((datetime.now() - start_time).total_seconds() * 1000) | |
| compression_info['compression_time_ms'] = compression_time_ms | |
| return compressed_data, compression_info | |
| async def decompress_and_retrieve( | |
| self, | |
| s3_key: str, | |
| bucket: str = None, | |
| expected_codec: str = None | |
| ) -> Tuple[bytes, Dict[str, Any]]: | |
| """ | |
| Retrieve and decompress file from S3 | |
| Args: | |
| s3_key: S3 key | |
| bucket: S3 bucket | |
| expected_codec: Expected compression type for validation | |
| Returns: | |
| Tuple of (decompressed_data, metadata) | |
| """ | |
| bucket = bucket or self.settings.S3_BUCKET | |
| logger.info(f"Retrieving and decompressing s3://{bucket}/{s3_key}") | |
| try: | |
| s3_client = await self.get_s3_client() | |
| # Get object and metadata | |
| response = await s3_client.get_object(Bucket=bucket, Key=s3_key) | |
| compressed_data = await response['Body'].read() | |
| metadata = response.get('Metadata', {}) | |
| # Extract compression info from metadata | |
| compression_type = metadata.get('compression-type', CompressionType.NONE) | |
| original_size = int(metadata.get('original-size', 0)) | |
| original_hash = metadata.get('original-hash') | |
| # Validate expected codec if provided | |
| if expected_codec and compression_type != expected_codec: | |
| raise StorageError(f"Expected {expected_codec} but found {compression_type}") | |
| # Decompress | |
| decompressed_data, decompression_info = await self._decompress_data( | |
| compressed_data, compression_type | |
| ) | |
| # Validate integrity if hash available | |
| if original_hash: | |
| actual_hash = hashlib.sha256(decompressed_data).hexdigest() | |
| if actual_hash != original_hash: | |
| raise StorageError("Data integrity check failed - hash mismatch") | |
| # Validate size if available | |
| if original_size > 0 and len(decompressed_data) != original_size: | |
| raise StorageError("Data integrity check failed - size mismatch") | |
| retrieval_metadata = { | |
| 'bucket': bucket, | |
| 's3_key': s3_key, | |
| 'compressed_size': len(compressed_data), | |
| 'decompressed_size': len(decompressed_data), | |
| 'compression_type': compression_type, | |
| 'original_hash': original_hash, | |
| 'verified': True, | |
| **decompression_info | |
| } | |
| logger.info(f"Successfully retrieved and decompressed file: {len(compressed_data)} -> {len(decompressed_data)} bytes") | |
| return decompressed_data, retrieval_metadata | |
| except Exception as e: | |
| logger.error(f"Failed to retrieve and decompress file: {e}") | |
| raise StorageError(f"Retrieval operation failed: {str(e)}") | |
| async def _decompress_data(self, compressed_data: bytes, codec: str) -> Tuple[bytes, Dict[str, Any]]: | |
| """Decompress data using specified codec""" | |
| start_time = datetime.now() | |
| if codec == CompressionType.GZIP: | |
| decompressed_data = gzip.decompress(compressed_data) | |
| decompression_info = {'algorithm': 'gzip'} | |
| elif codec == CompressionType.ZSTD: | |
| decompressor = zstd.ZstdDecompressor() | |
| decompressed_data = decompressor.decompress(compressed_data) | |
| decompression_info = {'algorithm': 'zstandard'} | |
| elif codec == CompressionType.NONE: | |
| decompressed_data = compressed_data | |
| decompression_info = {'algorithm': 'none'} | |
| else: | |
| raise StorageError(f"Unsupported decompression codec: {codec}") | |
| decompression_time_ms = int((datetime.now() - start_time).total_seconds() * 1000) | |
| decompression_info['decompression_time_ms'] = decompression_time_ms | |
| return decompressed_data, decompression_info | |
| async def store_json_compressed( | |
| self, | |
| data: Union[Dict, List], | |
| s3_key: str, | |
| bucket: str = None, | |
| codec: str = None, | |
| level: int = None | |
| ) -> Dict[str, Any]: | |
| """Store JSON data with compression""" | |
| import json | |
| # Serialize to JSON | |
| json_data = json.dumps(data, indent=None, separators=(',', ':')).encode('utf-8') | |
| # Create stream | |
| stream = io.BytesIO(json_data) | |
| return await self.compress_and_store_ifc(stream, s3_key, bucket, codec, level) | |
| async def retrieve_json_decompressed( | |
| self, | |
| s3_key: str, | |
| bucket: str = None, | |
| expected_codec: str = None | |
| ) -> Tuple[Union[Dict, List], Dict[str, Any]]: | |
| """Retrieve and decompress JSON data""" | |
| import json | |
| decompressed_data, metadata = await self.decompress_and_retrieve(s3_key, bucket, expected_codec) | |
| # Parse JSON | |
| try: | |
| json_data = json.loads(decompressed_data.decode('utf-8')) | |
| except (json.JSONDecodeError, UnicodeDecodeError) as e: | |
| raise StorageError(f"Failed to parse JSON data: {str(e)}") | |
| return json_data, metadata | |
| async def copy_to_compressed( | |
| self, | |
| source_s3_key: str, | |
| dest_s3_key: str, | |
| bucket: str = None, | |
| codec: str = None, | |
| level: int = None | |
| ) -> Dict[str, Any]: | |
| """Copy existing file to compressed version""" | |
| bucket = bucket or self.settings.S3_BUCKET | |
| try: | |
| s3_client = await self.get_s3_client() | |
| # Download original | |
| response = await s3_client.get_object(Bucket=bucket, Key=source_s3_key) | |
| original_data = await response['Body'].read() | |
| # Compress and store | |
| stream = io.BytesIO(original_data) | |
| return await self.compress_and_store_ifc(stream, dest_s3_key, bucket, codec, level) | |
| except Exception as e: | |
| logger.error(f"Failed to copy to compressed: {e}") | |
| raise StorageError(f"Copy operation failed: {str(e)}") | |
| async def get_object_info(self, s3_key: str, bucket: str = None) -> Dict[str, Any]: | |
| """Get object information without downloading""" | |
| bucket = bucket or self.settings.S3_BUCKET | |
| try: | |
| s3_client = await self.get_s3_client() | |
| response = await s3_client.head_object(Bucket=bucket, Key=s3_key) | |
| return { | |
| 'bucket': bucket, | |
| 's3_key': s3_key, | |
| 'size': response['ContentLength'], | |
| 'content_type': response.get('ContentType'), | |
| 'content_encoding': response.get('ContentEncoding'), | |
| 'metadata': response.get('Metadata', {}), | |
| 'last_modified': response['LastModified'], | |
| 'etag': response['ETag'].strip('"') | |
| } | |
| except ClientError as e: | |
| if e.response['Error']['Code'] == '404': | |
| raise StorageError(f"Object not found: s3://{bucket}/{s3_key}") | |
| raise StorageError(f"Failed to get object info: {str(e)}") | |
| async def delete_object(self, s3_key: str, bucket: str = None) -> bool: | |
| """Delete object from S3""" | |
| bucket = bucket or self.settings.S3_BUCKET | |
| try: | |
| s3_client = await self.get_s3_client() | |
| await s3_client.delete_object(Bucket=bucket, Key=s3_key) | |
| logger.info(f"Deleted s3://{bucket}/{s3_key}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to delete s3://{bucket}/{s3_key}: {e}") | |
| return False | |
| async def estimate_compression_savings( | |
| self, | |
| s3_key: str, | |
| bucket: str = None, | |
| codec: str = None, | |
| level: int = None, | |
| sample_size: int = 1024 * 1024 # 1MB sample | |
| ) -> Dict[str, Any]: | |
| """Estimate compression savings by compressing a sample""" | |
| bucket = bucket or self.settings.S3_BUCKET | |
| codec = codec or self.settings.IFC_COMPRESSION | |
| level = level or self.settings.IFC_COMPRESSION_LEVEL | |
| try: | |
| s3_client = await self.get_s3_client() | |
| # Get object info | |
| info = await self.get_object_info(s3_key, bucket) | |
| total_size = info['size'] | |
| # Download sample | |
| range_header = f"bytes=0-{min(sample_size - 1, total_size - 1)}" | |
| response = await s3_client.get_object( | |
| Bucket=bucket, | |
| Key=s3_key, | |
| Range=range_header | |
| ) | |
| sample_data = await response['Body'].read() | |
| # Compress sample | |
| compressed_sample, compression_info = await self._compress_data( | |
| sample_data, codec, level | |
| ) | |
| # Calculate estimates | |
| sample_ratio = len(compressed_sample) / len(sample_data) if len(sample_data) > 0 else 1.0 | |
| estimated_compressed_size = int(total_size * sample_ratio) | |
| estimated_savings = total_size - estimated_compressed_size | |
| estimated_savings_percent = (1 - sample_ratio) * 100 | |
| return { | |
| 'current_size': total_size, | |
| 'sample_size': len(sample_data), | |
| 'sample_compressed_size': len(compressed_sample), | |
| 'sample_ratio': round(sample_ratio, 3), | |
| 'estimated_compressed_size': estimated_compressed_size, | |
| 'estimated_savings': estimated_savings, | |
| 'estimated_savings_percent': round(estimated_savings_percent, 1), | |
| 'compression_type': codec, | |
| 'compression_level': level, | |
| **compression_info | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to estimate compression savings: {e}") | |
| raise StorageError(f"Estimation failed: {str(e)}") | |
| # Global storage service instance | |
| storage_service = StorageService() |