release method

void release(
  1. ValkeyClient client
)

Releases a connection back to the pool. Automatically discards if the client is closed or stateful (Smart Release).

final client = await pool.acquire();
try {
  await client.set('key', 'value');
} finally {
  pool.release(client);
}
  • If the client is stateful (e.g., Pub/Sub mode), it is automatically discarded.
  • If the client does not belong to this pool or was already released, this does nothing (Safe).

Implementation

void release(ValkeyClient client) {
  // 1. Ownership & State Check
  if (!_allClients.contains(client)) {
    // Already discarded or foreign client. Ignore safely.
    return;
  }

  if (!_leasedClients.contains(client)) {
    // Already released (idle) or inconsistent state. Ignore safely.
    return;
  }

  // Check if connection is dead
  if (!client.isConnected) {
    discard(client);
    return;
  }

  // 2. Smart Discard: Check if client is dirty
  if (client.isStateful) {
    // Client is in Pub/Sub or Transaction mode. Cannot reuse.
    discard(client);
    return;
  }

  // 3. Normal Release: Move from Leased to Idle
  _leasedClients.remove(client);

  // 4. Handover to waiter OR make idle
  if (_waitQueue.isNotEmpty) {
    final completer = _waitQueue.removeFirst();
    _leasedClients.add(client); // Moved back to leased for the waiter
    completer.complete(client);
  } else {
    _idleClients.add(client);
  }
}