File size: 29,886 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
"""

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()