getConnection method

Future<PooledConnection?> getConnection(
  1. String host
)

Get or create connection for host

Implementation

Future<PooledConnection?> getConnection(String host) async {
  final hostConnections = _connections[host] ?? [];

  // Find available connection
  for (final connection in hostConnections) {
    if (connection.isAvailable) {
      connection.markInUse();
      _lastUsed[host] = DateTime.now();
      return connection;
    }
  }

  // Create new connection if under limit
  if (hostConnections.length < _maxConnectionsPerHost) {
    try {
      final connection = await _createConnection(host);
      hostConnections.add(connection);
      _connections[host] = hostConnections;
      _lastUsed[host] = DateTime.now();

      Logger.d(
          '$_source: Created new connection to $host (${hostConnections.length}/$_maxConnectionsPerHost)');
      return connection;
    } catch (e) {
      Logger.w('$_source: Failed to create connection to $host: $e');
      return null;
    }
  }

  // Wait for available connection
  Logger.d('$_source: Waiting for available connection to $host');
  return await _waitForAvailableConnection(host);
}