Package · cpool

Writing an adapter

The adapter is the only place that knows what is in the pool. Three methods, and nearly all of the difficulty sits in one of them.

The contract

php
interface ConnectionFactory
{
  public function create(): object;
  public function validate(object $connection): bool;
  public function close(object $connection): void;
}

If the connection carries session state — a transaction, a mode, a selected database — the adapter also implements an optional fourth method. It is described below.

php
interface ResettableConnectionFactory extends ConnectionFactory
{
  public function reset(object $connection): bool;
}

create()

Opens one connection and returns it. It may throw — the pool wraps any exception in PoolException::connectFailed(), so the caller sees a single type regardless of driver.

This is where the full handshake happens: connect, authenticate, select the database, set session parameters. A half-configured connection handed to the pool becomes a half-configured connection in some random borrower’s hands later.

validate() — where it usually goes wrong

It answers one question: would a query work on this connection right now?

php
public function validate(object $connection): bool
{
  try {
      $connection->query('SELECT 1');   // Redis: $connection->ping()
      return true;
  } catch (Throwable) {
      return false;
  }
}

Three rules:

Return false, do not throw. The pool treats a thrown exception as death too, so nothing breaks — but the intent blurs and the trace fills with noise.

One round trip, no more. The probe runs on most borrows, and anything expensive here is paid for by every request.

Check the connection, not the schema. SELECT 1 and PING answer “the socket is alive”. A probe that touches a table will also fail when that table is locked — and the pool will enthusiastically evict perfectly healthy connections.

A fresh connection is not probed

A just-created connection carries its creation moment as its last-used timestamp, so it falls inside the aliveBypassWindow and is handed out unprobed. Probing a socket you opened a second ago means paying for the handshake twice.

close()

Releases the resource. The pool ignores errors here: the connection is going away anyway, and an exception would only hide the reason it is being closed.

Some drivers have nothing to do — PDO closes when dereferenced, and an empty body is more honest than an invented call. Others need an explicit close().

reset() — if the connection has a session

A connection outlives its borrower, and whatever the borrower left on it goes to the next one. For a database that is an open transaction: a request began one, failed before commit(), and the connection went back to the pool mid-transaction. The next borrower writes inside someone else’s transaction — its writes are lost along with it, and its own beginTransaction() fails with “already active”. For Redis an abandoned MULTI, an unfinished pipeline() and a database switched with SELECT do the same.

validate() does not see this, and should not: SELECT 1 answers perfectly well from inside an open transaction — the connection is alive. This case has a method of its own — reset() from the ResettableConnectionFactory interface.

The pool calls it on every release(), before the connection goes back into circulation. true — the connection is clean and returns to the pool; false or a thrown exception — it could not be put right, and the pool evicts it. evict() does not call reset(): a dead connection is closed, not cleaned.

php
public function reset(object $connection): bool
{
  if (!$connection->inTransaction()) {
      return true;                     // the usual case — no trip to the server
  }
  $this->logger->error('connection returned with an open transaction — rolled back');
  $connection->rollBack();

  return true;
}

Three rules:

The clean case costs no round trip. reset() runs on every release, which means on every request. Ask the driver, which remembers the state anyway: inTransaction() on PDO, getMode() and getDbNum() on phpredis. A query to the server “just in case” is paid by every request.

Undo, never finish. Roll back, not commit(); DISCARD, not EXEC. The borrower did not finish its work, and finishing it on its behalf means publishing what it never meant to publish.

Say so in the log. A connection returned with something left on it is a bug in the code that held it: a forgotten commit(), an exception that went past finally, an early return. The pool repairs the consequences, but only the log shows the cause.

Why a separate interface

reset() is not a fourth method of ConnectionFactory but a separate interface that extends it. An adapter with nothing to reset needs no change, and the pool calls reset() only on adapters that declare it.

A full example: Redis

src/RedisFactory.php
<?php

use Flytachi\Winter\CPool\ResettableConnectionFactory;

final readonly class RedisFactory implements ResettableConnectionFactory
{
  public function __construct(
      private string $host,
      private int    $port = 6379,
      private string $password = '',
      private int    $database = 0,
  ) {}

  public function create(): object
  {
      $redis = new \Redis();
      $redis->connect($this->host, $this->port, 2.0);

      if ($this->password !== '') {
          $redis->auth($this->password);
      }
      $redis->select($this->database);

      return $redis;
  }

  public function validate(object $connection): bool
  {
      try {
          return $connection->ping() !== false;
      } catch (\Throwable) {
          return false;
      }
  }

  public function close(object $connection): void
  {
      try {
          $connection->close();
      } catch (\Throwable) {
          // already closed — nothing to do
      }
  }

  public function reset(object $connection): bool
  {
      try {
          if ($connection->getMode() !== \Redis::ATOMIC) {
              $connection->discard();          // an abandoned MULTI or pipeline()
          }
          if ($connection->getDbNum() !== $this->database) {
              $connection->select($this->database);
          }
          return true;
      } catch (\Throwable) {
          return false;                        // the pool evicts the connection
      }
  }
}

Both checks in reset() are free: phpredis keeps the mode and the database number on its side, and only the cleanup itself goes to the server — and only when there is something to clean up.

What an adapter must not do

Cache the connection. The adapter creates, the pool owns. An adapter that remembers its own result turns a pool of ten connections into one connection shared by ten — the exact bug the pool exists to prevent.

Assume it is called once. create() runs every time the pool grows and after every evicted connection. Anything one-off — reading configuration, resolving a host — belongs in the constructor.

Hold request state. The adapter outlives every borrower. A tenant id or a user context captured into it will leak into connections belonging to other requests.

Next

  • Policy — aliveBypassWindow decides how often validate() is called
  • API reference — signatures and exceptions