ai_data_scientist / shared /connection_pool.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
29.9 kB
"""
Connection pooling and resource management for Supabase and MCP servers.
Provides efficient connection management, pooling, and resource optimization.
"""
import asyncio
import logging
import time
import weakref
from typing import Dict, List, Any, Optional, Callable, AsyncContextManager, Union
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from contextlib import asynccontextmanager
from collections import defaultdict, deque
import threading
from concurrent.futures import ThreadPoolExecutor
import json
from supabase import Client, create_client
from supabase.lib.client_options import ClientOptions
from .config import settings
from .models import UserContext
from .monitoring import monitoring_system
logger = logging.getLogger(__name__)
@dataclass
class ConnectionStats:
"""Connection pool statistics."""
pool_name: str
total_connections: int
active_connections: int
idle_connections: int
max_connections: int
connections_created: int
connections_closed: int
connection_errors: int
avg_connection_time_ms: float
peak_active_connections: int
last_activity: datetime
def to_dict(self) -> Dict[str, Any]:
return {
'pool_name': self.pool_name,
'total_connections': self.total_connections,
'active_connections': self.active_connections,
'idle_connections': self.idle_connections,
'max_connections': self.max_connections,
'connections_created': self.connections_created,
'connections_closed': self.connections_closed,
'connection_errors': self.connection_errors,
'avg_connection_time_ms': self.avg_connection_time_ms,
'peak_active_connections': self.peak_active_connections,
'last_activity': self.last_activity.isoformat(),
'utilization_percent': (self.active_connections / self.max_connections * 100) if self.max_connections > 0 else 0
}
@dataclass
class PooledConnection:
"""Represents a pooled connection."""
connection_id: str
connection: Any
created_at: datetime
last_used: datetime
use_count: int
is_active: bool = False
user_id: Optional[str] = None
connection_type: str = "generic"
def touch(self):
"""Update last used timestamp and increment use count."""
self.last_used = datetime.utcnow()
self.use_count += 1
def is_expired(self, max_idle_seconds: int = 300) -> bool:
"""Check if connection has been idle too long."""
return (datetime.utcnow() - self.last_used).total_seconds() > max_idle_seconds
def is_stale(self, max_age_seconds: int = 3600) -> bool:
"""Check if connection is too old."""
return (datetime.utcnow() - self.created_at).total_seconds() > max_age_seconds
class ConnectionPool:
"""Generic connection pool with lifecycle management."""
def __init__(
self,
name: str,
connection_factory: Callable[[], Any],
max_connections: int = 10,
min_connections: int = 2,
max_idle_seconds: int = 300,
max_age_seconds: int = 3600,
health_check_interval: int = 60
):
self.name = name
self.connection_factory = connection_factory
self.max_connections = max_connections
self.min_connections = min_connections
self.max_idle_seconds = max_idle_seconds
self.max_age_seconds = max_age_seconds
self.health_check_interval = health_check_interval
self._connections: Dict[str, PooledConnection] = {}
self._idle_connections: deque = deque()
self._active_connections: Dict[str, PooledConnection] = {}
self._lock = asyncio.Lock()
self._condition = asyncio.Condition(self._lock)
# Statistics
self._stats = {
'connections_created': 0,
'connections_closed': 0,
'connection_errors': 0,
'connection_times': deque(maxlen=100),
'peak_active': 0
}
# Background tasks
self._cleanup_task: Optional[asyncio.Task] = None
self._health_check_task: Optional[asyncio.Task] = None
self._running = False
async def start(self):
"""Start the connection pool."""
if self._running:
return
self._running = True
# Create minimum connections
await self._ensure_min_connections()
# Start background tasks
self._cleanup_task = asyncio.create_task(self._cleanup_loop())
self._health_check_task = asyncio.create_task(self._health_check_loop())
logger.info(f"Connection pool '{self.name}' started with {len(self._connections)} connections")
async def stop(self):
"""Stop the connection pool and close all connections."""
self._running = False
# Cancel background tasks
if self._cleanup_task:
self._cleanup_task.cancel()
if self._health_check_task:
self._health_check_task.cancel()
# Close all connections
async with self._lock:
for conn in list(self._connections.values()):
await self._close_connection(conn)
self._connections.clear()
self._idle_connections.clear()
self._active_connections.clear()
logger.info(f"Connection pool '{self.name}' stopped")
@asynccontextmanager
async def get_connection(self, user_id: Optional[str] = None) -> AsyncContextManager[Any]:
"""Get a connection from the pool."""
connection = None
start_time = time.time()
try:
connection = await self._acquire_connection(user_id)
# Record connection time
connection_time = (time.time() - start_time) * 1000
self._stats['connection_times'].append(connection_time)
yield connection.connection
except Exception as e:
self._stats['connection_errors'] += 1
logger.error(f"Connection error in pool '{self.name}': {e}")
raise
finally:
if connection:
await self._release_connection(connection)
async def _acquire_connection(self, user_id: Optional[str] = None) -> PooledConnection:
"""Acquire a connection from the pool."""
async with self._condition:
# Wait for available connection
while len(self._active_connections) >= self.max_connections and not self._idle_connections:
await self._condition.wait()
# Try to get idle connection
if self._idle_connections:
conn_id = self._idle_connections.popleft()
connection = self._connections[conn_id]
# Check if connection is still valid
if connection.is_expired(self.max_idle_seconds) or connection.is_stale(self.max_age_seconds):
await self._close_connection(connection)
connection = await self._create_connection(user_id)
else:
connection.touch()
else:
# Create new connection if under limit
if len(self._connections) < self.max_connections:
connection = await self._create_connection(user_id)
else:
raise Exception(f"Connection pool '{self.name}' exhausted")
# Mark as active
connection.is_active = True
connection.user_id = user_id
self._active_connections[connection.connection_id] = connection
# Update peak active connections
self._stats['peak_active'] = max(self._stats['peak_active'], len(self._active_connections))
return connection
async def _release_connection(self, connection: PooledConnection):
"""Release a connection back to the pool."""
async with self._condition:
if connection.connection_id in self._active_connections:
del self._active_connections[connection.connection_id]
connection.is_active = False
connection.user_id = None
# Add back to idle pool if still valid
if not connection.is_expired() and not connection.is_stale():
self._idle_connections.append(connection.connection_id)
else:
await self._close_connection(connection)
# Notify waiting tasks
self._condition.notify()
async def _create_connection(self, user_id: Optional[str] = None) -> PooledConnection:
"""Create a new connection."""
try:
connection_obj = await asyncio.get_event_loop().run_in_executor(
None, self.connection_factory
)
connection_id = f"{self.name}_{len(self._connections)}_{int(time.time())}"
connection = PooledConnection(
connection_id=connection_id,
connection=connection_obj,
created_at=datetime.utcnow(),
last_used=datetime.utcnow(),
use_count=0,
user_id=user_id,
connection_type=self.name
)
self._connections[connection_id] = connection
self._stats['connections_created'] += 1
logger.debug(f"Created new connection {connection_id} in pool '{self.name}'")
return connection
except Exception as e:
self._stats['connection_errors'] += 1
logger.error(f"Failed to create connection in pool '{self.name}': {e}")
raise
async def _close_connection(self, connection: PooledConnection):
"""Close a connection."""
try:
# Remove from all tracking structures
if connection.connection_id in self._connections:
del self._connections[connection.connection_id]
if connection.connection_id in self._active_connections:
del self._active_connections[connection.connection_id]
# Remove from idle queue
try:
self._idle_connections.remove(connection.connection_id)
except ValueError:
pass
# Close the actual connection
if hasattr(connection.connection, 'close'):
await asyncio.get_event_loop().run_in_executor(
None, connection.connection.close
)
self._stats['connections_closed'] += 1
logger.debug(f"Closed connection {connection.connection_id} in pool '{self.name}'")
except Exception as e:
logger.error(f"Error closing connection {connection.connection_id}: {e}")
async def _ensure_min_connections(self):
"""Ensure minimum number of connections are available."""
async with self._lock:
while len(self._connections) < self.min_connections:
try:
connection = await self._create_connection()
self._idle_connections.append(connection.connection_id)
except Exception as e:
logger.error(f"Failed to create minimum connection: {e}")
break
async def _cleanup_loop(self):
"""Background task to clean up expired connections."""
while self._running:
try:
await asyncio.sleep(60) # Run every minute
await self._cleanup_expired_connections()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Connection cleanup error in pool '{self.name}': {e}")
async def _cleanup_expired_connections(self):
"""Clean up expired and stale connections."""
async with self._lock:
expired_connections = []
# Check idle connections
for conn_id in list(self._idle_connections):
connection = self._connections.get(conn_id)
if connection and (connection.is_expired(self.max_idle_seconds) or
connection.is_stale(self.max_age_seconds)):
expired_connections.append(connection)
try:
self._idle_connections.remove(conn_id)
except ValueError:
pass
# Close expired connections
for connection in expired_connections:
await self._close_connection(connection)
# Ensure minimum connections
await self._ensure_min_connections()
if expired_connections:
logger.debug(f"Cleaned up {len(expired_connections)} expired connections in pool '{self.name}'")
async def _health_check_loop(self):
"""Background task to perform health checks."""
while self._running:
try:
await asyncio.sleep(self.health_check_interval)
await self._perform_health_checks()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Health check error in pool '{self.name}': {e}")
async def _perform_health_checks(self):
"""Perform health checks on idle connections."""
async with self._lock:
unhealthy_connections = []
for conn_id in list(self._idle_connections):
connection = self._connections.get(conn_id)
if connection:
try:
# Perform basic health check
if hasattr(connection.connection, 'ping'):
healthy = await asyncio.get_event_loop().run_in_executor(
None, connection.connection.ping
)
if not healthy:
unhealthy_connections.append(connection)
except Exception:
unhealthy_connections.append(connection)
# Remove unhealthy connections
for connection in unhealthy_connections:
try:
self._idle_connections.remove(connection.connection_id)
except ValueError:
pass
await self._close_connection(connection)
if unhealthy_connections:
logger.info(f"Removed {len(unhealthy_connections)} unhealthy connections from pool '{self.name}'")
def get_stats(self) -> ConnectionStats:
"""Get connection pool statistics."""
avg_connection_time = 0
if self._stats['connection_times']:
avg_connection_time = sum(self._stats['connection_times']) / len(self._stats['connection_times'])
return ConnectionStats(
pool_name=self.name,
total_connections=len(self._connections),
active_connections=len(self._active_connections),
idle_connections=len(self._idle_connections),
max_connections=self.max_connections,
connections_created=self._stats['connections_created'],
connections_closed=self._stats['connections_closed'],
connection_errors=self._stats['connection_errors'],
avg_connection_time_ms=avg_connection_time,
peak_active_connections=self._stats['peak_active'],
last_activity=datetime.utcnow()
)
class SupabaseConnectionPool(ConnectionPool):
"""Specialized connection pool for Supabase clients."""
def __init__(self, max_connections: int = 20, **kwargs):
def create_supabase_client():
return create_client(
settings.supabase_url,
settings.supabase_service_role_key,
options=ClientOptions(
postgrest_client_timeout=30,
storage_client_timeout=30,
schema="public",
# Performance optimizations
auto_refresh_token=False, # Disable auto refresh for service role
persist_session=False, # Don't persist sessions
)
)
super().__init__(
name="supabase",
connection_factory=create_supabase_client,
max_connections=max_connections,
min_connections=kwargs.get('min_connections', 5), # Higher minimum for Supabase
max_idle_seconds=kwargs.get('max_idle_seconds', 600), # Longer idle time
max_age_seconds=kwargs.get('max_age_seconds', 7200), # 2 hours max age
**kwargs
)
# Supabase-specific optimizations
self._prepared_statements: Dict[str, Any] = {}
self._query_cache: Dict[str, Any] = {}
async def get_authenticated_client(self, user_token: str) -> AsyncContextManager[Client]:
"""Get an authenticated Supabase client."""
@asynccontextmanager
async def authenticated_client():
async with self.get_connection() as client:
# Set user authentication
client.auth.set_session({"access_token": user_token, "refresh_token": ""})
yield client
return authenticated_client()
async def execute_optimized_query(self, query: str, params: Dict[str, Any] = None, user_id: str = None):
"""Execute query with Supabase-specific optimizations."""
# Check query cache first
cache_key = f"{query}:{str(params)}:{user_id}"
if cache_key in self._query_cache:
cached_result, cache_time = self._query_cache[cache_key]
# Cache for 5 minutes
if time.time() - cache_time < 300:
return cached_result
async with self.get_connection(user_id) as client:
start_time = time.time()
try:
# Execute query with optimizations
if params:
result = await asyncio.get_event_loop().run_in_executor(
None,
lambda: client.rpc('execute_parameterized_query', {
'query_text': query,
'query_params': params
})
)
else:
result = await asyncio.get_event_loop().run_in_executor(
None,
lambda: client.rpc('execute_query', {'query_text': query})
)
# Cache successful results
execution_time = time.time() - start_time
if execution_time < 1.0: # Only cache fast queries
self._query_cache[cache_key] = (result, time.time())
# Limit cache size
if len(self._query_cache) > 1000:
# Remove oldest entries
oldest_keys = sorted(self._query_cache.keys(),
key=lambda k: self._query_cache[k][1])[:100]
for key in oldest_keys:
del self._query_cache[key]
return result
except Exception as e:
logger.error(f"Supabase query execution failed: {e}")
raise
async def bulk_insert_optimized(self, table: str, data: List[Dict[str, Any]], batch_size: int = 1000):
"""Optimized bulk insert for Supabase."""
async with self.get_connection() as client:
results = []
# Process in batches for better performance
for i in range(0, len(data), batch_size):
batch = data[i:i + batch_size]
try:
result = await asyncio.get_event_loop().run_in_executor(
None,
lambda: client.table(table).insert(batch).execute()
)
results.append(result)
except Exception as e:
logger.error(f"Bulk insert batch failed: {e}")
# Try individual inserts for failed batch
for item in batch:
try:
individual_result = await asyncio.get_event_loop().run_in_executor(
None,
lambda: client.table(table).insert(item).execute()
)
results.append(individual_result)
except Exception as individual_error:
logger.error(f"Individual insert failed: {individual_error}")
return results
def get_supabase_stats(self) -> Dict[str, Any]:
"""Get Supabase-specific statistics."""
base_stats = self.get_stats().to_dict()
return {
**base_stats,
'query_cache_size': len(self._query_cache),
'prepared_statements': len(self._prepared_statements),
'supabase_specific': True
}
class MCPConnectionPool(ConnectionPool):
"""Specialized connection pool for MCP server connections."""
def __init__(self, server_name: str, server_url: str, max_connections: int = 5, **kwargs):
self.server_url = server_url
def create_mcp_connection():
# This would create an actual MCP client connection
# For now, we'll use a placeholder
import httpx
return httpx.AsyncClient(base_url=server_url, timeout=30.0)
super().__init__(
name=f"mcp_{server_name}",
connection_factory=create_mcp_connection,
max_connections=max_connections,
**kwargs
)
class ResourceManager:
"""Manages all connection pools and resources."""
def __init__(self):
self.pools: Dict[str, ConnectionPool] = {}
self._executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="resource_mgr")
self._monitoring_task: Optional[asyncio.Task] = None
self._running = False
async def start(self):
"""Start resource manager."""
if self._running:
return
self._running = True
# Initialize default pools
await self._initialize_default_pools()
# Start monitoring
self._monitoring_task = asyncio.create_task(self._monitoring_loop())
logger.info("Resource manager started")
async def stop(self):
"""Stop resource manager and all pools."""
self._running = False
if self._monitoring_task:
self._monitoring_task.cancel()
# Stop all pools
for pool in self.pools.values():
await pool.stop()
self._executor.shutdown(wait=True)
logger.info("Resource manager stopped")
async def _initialize_default_pools(self):
"""Initialize default connection pools."""
# Supabase pool
supabase_pool = SupabaseConnectionPool(
max_connections=20,
min_connections=3
)
await self.add_pool("supabase", supabase_pool)
# MCP server pools
mcp_servers = [
("data_cleaning", "http://localhost:3001"),
("hypothesis_testing", "http://localhost:3002"),
("preprocessing", "http://localhost:3003"),
("feature_engineering", "http://localhost:3004"),
("model_training", "http://localhost:3005"),
("action_generation", "http://localhost:3006")
]
for server_name, server_url in mcp_servers:
mcp_pool = MCPConnectionPool(
server_name=server_name,
server_url=server_url,
max_connections=5,
min_connections=1
)
await self.add_pool(f"mcp_{server_name}", mcp_pool)
async def add_pool(self, name: str, pool: ConnectionPool):
"""Add a connection pool."""
self.pools[name] = pool
await pool.start()
logger.info(f"Added connection pool: {name}")
async def remove_pool(self, name: str):
"""Remove a connection pool."""
if name in self.pools:
await self.pools[name].stop()
del self.pools[name]
logger.info(f"Removed connection pool: {name}")
def get_pool(self, name: str) -> Optional[ConnectionPool]:
"""Get a connection pool by name."""
return self.pools.get(name)
async def get_supabase_connection(self, user_id: Optional[str] = None) -> AsyncContextManager[Client]:
"""Get a Supabase connection."""
pool = self.get_pool("supabase")
if not pool:
raise RuntimeError("Supabase connection pool not available")
return pool.get_connection(user_id)
async def get_mcp_connection(self, server_name: str, user_id: Optional[str] = None) -> AsyncContextManager[Any]:
"""Get an MCP server connection."""
pool = self.get_pool(f"mcp_{server_name}")
if not pool:
raise RuntimeError(f"MCP connection pool for {server_name} not available")
return pool.get_connection(user_id)
async def _monitoring_loop(self):
"""Monitor connection pools and record metrics."""
while self._running:
try:
await asyncio.sleep(30) # Monitor every 30 seconds
await self._record_pool_metrics()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Resource monitoring error: {e}")
async def _record_pool_metrics(self):
"""Record metrics for all connection pools."""
for pool_name, pool in self.pools.items():
try:
stats = pool.get_stats()
# Record metrics
monitoring_system.metrics_collector.record_metric(
"connection_pool.active_connections",
stats.active_connections,
tags={"pool": pool_name}
)
monitoring_system.metrics_collector.record_metric(
"connection_pool.idle_connections",
stats.idle_connections,
tags={"pool": pool_name}
)
monitoring_system.metrics_collector.record_metric(
"connection_pool.utilization_percent",
stats.active_connections / stats.max_connections * 100 if stats.max_connections > 0 else 0,
tags={"pool": pool_name}
)
monitoring_system.metrics_collector.record_metric(
"connection_pool.avg_connection_time_ms",
stats.avg_connection_time_ms,
tags={"pool": pool_name}
)
except Exception as e:
logger.error(f"Failed to record metrics for pool {pool_name}: {e}")
def get_all_stats(self) -> Dict[str, Dict[str, Any]]:
"""Get statistics for all connection pools."""
return {
name: pool.get_stats().to_dict()
for name, pool in self.pools.items()
}
def get_resource_summary(self) -> Dict[str, Any]:
"""Get summary of all resources."""
total_connections = sum(pool.get_stats().total_connections for pool in self.pools.values())
total_active = sum(pool.get_stats().active_connections for pool in self.pools.values())
total_errors = sum(pool.get_stats().connection_errors for pool in self.pools.values())
return {
'timestamp': datetime.utcnow().isoformat(),
'total_pools': len(self.pools),
'total_connections': total_connections,
'total_active_connections': total_active,
'total_connection_errors': total_errors,
'pool_details': self.get_all_stats()
}
# Global resource manager instance
resource_manager = ResourceManager()