Buckets:

download
raw
7.38 kB
# NeuroGraph - Высокопроизводительная система пространственных вычислений на основе токенов.
# Copyright (C) 2024-2025 Chernov Denys
# 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/>.
"""
FastAPI Dependencies
Dependency injection for runtime, storage, authentication, etc.
"""
from typing import Optional
from fastapi import HTTPException, status
import logging
from .storage import (
TokenStorageInterface,
GridStorageInterface,
CDNAStorageInterface
)
from .storage.memory import (
InMemoryTokenStorage,
InMemoryGridStorage,
InMemoryCDNAStorage
)
from .storage.runtime import (
RuntimeTokenStorage,
RuntimeGridStorage,
RuntimeCDNAStorage
)
from .config import settings
logger = logging.getLogger(__name__)
# Global runtime instance (v0.51.0 - initialized on demand)
_runtime_instance: Optional[object] = None
# Global storage instances (singletons)
_token_storage: Optional[TokenStorageInterface] = None
_grid_storage: Optional[GridStorageInterface] = None
_cdna_storage: Optional[CDNAStorageInterface] = None
def get_runtime():
"""
Dependency to get the NeuroGraph runtime instance.
Returns:
Runtime instance (neurograph.Runtime v0.50.0)
Raises:
HTTPException: If runtime initialization fails
"""
global _runtime_instance
if _runtime_instance is None:
try:
from neurograph import Runtime, Config
# Initialize runtime with default config
config = Config(
grid_size=settings.NEUROGRAPH_GRID_SIZE,
dimensions=settings.NEUROGRAPH_DIMENSIONS
)
_runtime_instance = Runtime(config)
logger.info(f"Runtime initialized: grid_size={settings.NEUROGRAPH_GRID_SIZE}, "
f"dimensions={settings.NEUROGRAPH_DIMENSIONS}")
except ImportError as e:
logger.error(f"Failed to import neurograph: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="neurograph package not available. Build with: maturin develop --release --features python-bindings"
)
except Exception as e:
logger.error(f"Failed to initialize runtime: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Runtime initialization failed: {str(e)}"
)
return _runtime_instance
def set_runtime(runtime):
"""Set the global runtime instance."""
global _runtime_instance
_runtime_instance = runtime
logger.info("Runtime instance set externally")
# =============================================================================
# Storage Dependencies
# =============================================================================
#
# NOTE: Authentication is handled by src/api/auth/dependencies.py
# Use get_current_active_user() for JWT authentication
# This file only contains storage dependency injection
# =============================================================================
def get_token_storage() -> TokenStorageInterface:
"""
Get token storage instance.
Returns appropriate storage backend based on settings.
Uses singleton pattern with shared Runtime instance.
"""
global _token_storage
if _token_storage is None:
backend = settings.STORAGE_BACKEND.lower()
if backend == "memory":
_token_storage = InMemoryTokenStorage()
logger.info("Initialized InMemory token storage")
elif backend == "runtime":
# Get shared runtime instance
runtime = get_runtime()
_token_storage = RuntimeTokenStorage(runtime=runtime)
logger.info("Initialized Runtime token storage with shared Runtime")
else:
logger.warning(f"Unknown storage backend '{backend}', defaulting to memory")
_token_storage = InMemoryTokenStorage()
return _token_storage
def get_grid_storage() -> GridStorageInterface:
"""
Get grid storage instance.
Returns appropriate storage backend based on settings.
Uses singleton pattern with shared Runtime instance.
"""
global _grid_storage
if _grid_storage is None:
backend = settings.STORAGE_BACKEND.lower()
if backend == "memory":
_grid_storage = InMemoryGridStorage()
logger.info("Initialized InMemory grid storage")
elif backend == "runtime":
# Get shared runtime instance
runtime = get_runtime()
_grid_storage = RuntimeGridStorage(runtime=runtime)
logger.info("Initialized Runtime grid storage with shared Runtime")
else:
logger.warning(f"Unknown storage backend '{backend}', defaulting to memory")
_grid_storage = InMemoryGridStorage()
return _grid_storage
def get_cdna_storage() -> CDNAStorageInterface:
"""
Get CDNA storage instance.
Returns appropriate storage backend based on settings.
Uses singleton pattern with shared Runtime instance.
"""
global _cdna_storage
if _cdna_storage is None:
backend = settings.STORAGE_BACKEND.lower()
if backend == "memory":
_cdna_storage = InMemoryCDNAStorage()
logger.info("Initialized InMemory CDNA storage")
elif backend == "runtime":
# Get shared runtime instance
runtime = get_runtime()
_cdna_storage = RuntimeCDNAStorage(runtime=runtime)
logger.info("Initialized Runtime CDNA storage with shared Runtime")
else:
logger.warning(f"Unknown storage backend '{backend}', defaulting to memory")
_cdna_storage = InMemoryCDNAStorage()
return _cdna_storage
def reset_storage():
"""
Reset all storage instances.
Useful for testing or when changing storage backend at runtime.
"""
global _token_storage, _grid_storage, _cdna_storage
_token_storage = None
_grid_storage = None
_cdna_storage = None
logger.info("Storage instances reset")
# =============================================================================
# Grid Availability Check
# =============================================================================
def check_grid_available() -> bool:
"""
Check if Grid V2.0 (Rust FFI) is available.
Returns:
True if Grid is available, False otherwise
"""
try:
# Try to import Rust Grid V2.0
import neurograph_grid_v2 # noqa: F401
return True
except ImportError:
return False

Xet Storage Details

Size:
7.38 kB
·
Xet hash:
1fc0bde1e8e4a97daec047497e2ee1948214cf0e1e2640e9ea6da7eb08139a59

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.