discard method

Future<void> discard(
  1. ValkeyClient client
)

Explicitly discards a connection, removing it from the pool and closing it.

Use this if the connection is broken or no longer needed. Safe to call multiple times.

Implementation

Future<void> discard(ValkeyClient client) async {
  // 1. Ownership Check
  if (!_allClients.contains(client)) {
    return; // Already gone. Safe.
  }

  // 2. Remove from all trackers
  _allClients.remove(client);
  _leasedClients.remove(client);
  _idleClients.remove(client);

  // 3. Close the physical connection
  // We await this to ensure resources are freed, but ignore errors.
  try {
    await client.close();
  } catch (_) {
    // Ignore errors during close
  }

  // 4. Fill the void: If there are waiters, create a NEW connection
  // We freed up a slot in _allClients, so we can honor a waiter.
  if (_waitQueue.isNotEmpty) {
    final completer = _waitQueue.removeFirst();
    try {
      final newClient = await _createNewClientAndLease();
      completer.complete(newClient);
    } catch (e) {
      // If creation fails, we can't satisfy the waiter now.
      // We must error the waiter to avoid deadlock.
      completer.completeError(e);
    }
  }
}