|
5 | 5 | namespace Sloop\Database; |
6 | 6 |
|
7 | 7 | use Sloop\Database\Config\ConnectionConfigResolver; |
| 8 | +use Sloop\Database\Config\PoolConfig; |
| 9 | +use Sloop\Database\Config\ValidatedConfig; |
8 | 10 | use Sloop\Database\Exception\DatabaseConnectionException; |
| 11 | +use Sloop\Database\Exception\DatabaseException; |
9 | 12 | use Sloop\Database\Exception\InvalidConfigException; |
10 | 13 | use Sloop\Database\Factory\ConnectionFactory; |
| 14 | +use Sloop\Database\Replica\DeadReplicaCache; |
| 15 | +use Sloop\Database\Replica\ReplicaSelector; |
11 | 16 |
|
12 | 17 | /** |
13 | 18 | * Lazily creates and caches database connections from pool configurations. |
|
18 | 23 | * the injected ConnectionFactory the first time they are requested and |
19 | 24 | * cached so a single request reuses one PDO instance per pool name. |
20 | 25 | * |
21 | | - * connection() currently returns the pool's primary; replica selection and |
22 | | - * the writable parameter are not yet implemented. |
| 26 | + * connection() routing: |
| 27 | + * - $writable === true → primary |
| 28 | + * - $writable === false → replica (dead-cache filter → ReplicaSelector → ping |
| 29 | + * → record on failure → next → primary fallback |
| 30 | + * → throw on max_connection_attempts exhaustion) |
| 31 | + * - $writable === null → primary (Builder layer detects SELECT, not the manager) |
| 32 | + * |
| 33 | + * Empty `read` list collapses replica routing to the primary so single-pool |
| 34 | + * setups keep working without reconfiguration. |
23 | 35 | */ |
24 | 36 | final class ConnectionManager |
25 | 37 | { |
26 | 38 | /** |
27 | | - * Cached Connection instances keyed by pool name. |
| 39 | + * Cached primary Connection instances keyed by pool name. |
28 | 40 | * |
29 | 41 | * @var array<string, Connection> |
30 | 42 | */ |
31 | | - private array $connections = []; |
| 43 | + private array $primaryConnections = []; |
| 44 | + |
| 45 | + /** |
| 46 | + * Cached replica Connection instances keyed by pool name. |
| 47 | + * |
| 48 | + * Replica selection runs at most once per pool per request: once a healthy |
| 49 | + * replica is found, subsequent connection(writable: false) calls reuse it. |
| 50 | + * |
| 51 | + * @var array<string, Connection> |
| 52 | + */ |
| 53 | + private array $replicaConnections = []; |
32 | 54 |
|
33 | 55 | /** |
34 | 56 | * Construct a new ConnectionManager. |
35 | 57 | * |
36 | | - * @param string $defaultName Pool name to return from connection() |
37 | | - * @param array<string, array<string, mixed>> $configs Pool configurations indexed by pool name |
38 | | - * @param ConnectionFactory $factory Builds Connection instances from validated configs |
| 58 | + * @param string $defaultName Pool name to return from connection() |
| 59 | + * @param array<string, array<string, mixed>> $configs Pool configurations indexed by pool name |
| 60 | + * @param ConnectionFactory $factory Builds Connection instances from validated configs |
| 61 | + * @param ReplicaSelector $replicaSelector Strategy for picking one replica from surviving candidates |
| 62 | + * @param DeadReplicaCache $deadCache Negative cache for replicas that recently failed to connect |
39 | 63 | */ |
40 | 64 | public function __construct( |
41 | 65 | private readonly string $defaultName, |
42 | 66 | private readonly array $configs, |
43 | 67 | private readonly ConnectionFactory $factory, |
| 68 | + private readonly ReplicaSelector $replicaSelector, |
| 69 | + private readonly DeadReplicaCache $deadCache, |
44 | 70 | ) { |
45 | 71 | } |
46 | 72 |
|
47 | 73 | /** |
48 | | - * Return the default pool's primary connection, creating and caching it on first call. |
| 74 | + * Return the default pool's connection, routing to primary or replica based on $writable. |
49 | 75 | * |
50 | | - * @return Connection Lazy-created, cached Connection to the default pool's primary |
| 76 | + * @param bool|null $writable true → primary; false → replica with primary fallback; |
| 77 | + * null → primary (Builder layer is responsible for SELECT detection) |
| 78 | + * @return Connection Lazy-created, cached Connection |
51 | 79 | * @throws InvalidConfigException When the default pool name is not defined or its config is malformed |
52 | | - * @throws DatabaseConnectionException When the underlying PDO connection cannot be established |
| 80 | + * @throws DatabaseConnectionException When max_connection_attempts is exhausted on the replica path |
53 | 81 | */ |
54 | | - public function connection(): Connection |
| 82 | + public function connection(?bool $writable = null): Connection |
55 | 83 | { |
56 | | - if (!isset($this->connections[$this->defaultName])) { |
57 | | - $this->connections[$this->defaultName] = $this->makeConnection($this->defaultName); |
| 84 | + if ($writable === false) { |
| 85 | + return $this->getReplicaConnection($this->defaultName); |
58 | 86 | } |
59 | 87 |
|
60 | | - return $this->connections[$this->defaultName]; |
| 88 | + return $this->getPrimaryConnection($this->defaultName); |
61 | 89 | } |
62 | 90 |
|
63 | 91 | /** |
64 | | - * Build a new Connection to the named pool's primary via the injected factory. |
| 92 | + * Return the cached primary Connection or build it on first access. |
65 | 93 | * |
66 | 94 | * @param string $name Pool name |
67 | 95 | * @return Connection |
68 | | - * @throws InvalidConfigException When the name is undefined or the config is malformed |
69 | | - * @throws DatabaseConnectionException When the underlying PDO connection cannot be established |
| 96 | + * @throws InvalidConfigException When the name is undefined or config is malformed |
| 97 | + * @throws DatabaseConnectionException When the underlying PDO connection fails |
70 | 98 | */ |
71 | | - private function makeConnection(string $name): Connection |
| 99 | + private function getPrimaryConnection(string $name): Connection |
| 100 | + { |
| 101 | + if (!isset($this->primaryConnections[$name])) { |
| 102 | + $pool = $this->resolvePool($name); |
| 103 | + |
| 104 | + $this->primaryConnections[$name] = $this->factory->make($pool->primary, $name); |
| 105 | + } |
| 106 | + |
| 107 | + return $this->primaryConnections[$name]; |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Return the cached replica Connection, or run the selection loop on first access. |
| 112 | + * |
| 113 | + * Selection flow: |
| 114 | + * 1. Filter out replicas marked dead in the cache |
| 115 | + * 2. ReplicaSelector picks one of the survivors |
| 116 | + * 3. Connect via ConnectionFactory; if health_check is on, verify with Connection::ping() |
| 117 | + * 4. On failure: record dead (auth → markPoolDead, otherwise markServerDead) |
| 118 | + * and remove the candidate; loop until success, candidates exhausted, |
| 119 | + * or max_connection_attempts reached |
| 120 | + * 5. When all replicas fail and attempts remain, fall back to primary |
| 121 | + * 6. If no healthy connection is found, throw DatabaseConnectionException |
| 122 | + * with cumulative per-attempt error details |
| 123 | + * |
| 124 | + * @param string $name Pool name |
| 125 | + * @return Connection |
| 126 | + * @throws InvalidConfigException When the name is undefined or config is malformed |
| 127 | + * @throws DatabaseConnectionException When all attempts (replica + fallback) fail |
| 128 | + */ |
| 129 | + private function getReplicaConnection(string $name): Connection |
| 130 | + { |
| 131 | + if (isset($this->replicaConnections[$name])) { |
| 132 | + return $this->replicaConnections[$name]; |
| 133 | + } |
| 134 | + |
| 135 | + $pool = $this->resolvePool($name); |
| 136 | + |
| 137 | + if ($pool->replicas === []) { |
| 138 | + // No replicas configured → primary doubles as the read endpoint. |
| 139 | + return $this->getPrimaryConnection($name); |
| 140 | + } |
| 141 | + |
| 142 | + [$candidates, $errors] = $this->partitionByDeadCache($pool); |
| 143 | + $attempts = 0; |
| 144 | + |
| 145 | + while ($candidates !== [] && $attempts < $pool->maxConnectionAttempts) { |
| 146 | + $index = $this->replicaSelector->pick($candidates); |
| 147 | + $picked = $candidates[$index]; |
| 148 | + $attempts++; |
| 149 | + |
| 150 | + try { |
| 151 | + $connection = $this->factory->make($picked, $name); |
| 152 | + |
| 153 | + if ($pool->healthCheck) { |
| 154 | + $connection->ping(); |
| 155 | + } |
| 156 | + |
| 157 | + $this->replicaConnections[$name] = $connection; |
| 158 | + |
| 159 | + return $connection; |
| 160 | + } catch (DatabaseException $e) { |
| 161 | + $errors[] = $this->formatAttemptError($picked, $e); |
| 162 | + $this->recordReplicaFailure($pool, $picked, $e); |
| 163 | + array_splice($candidates, $index, 1); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + if ($attempts < $pool->maxConnectionAttempts) { |
| 168 | + try { |
| 169 | + return $this->getPrimaryConnection($name); |
| 170 | + } catch (DatabaseException $e) { |
| 171 | + $errors[] = $this->formatAttemptError($pool->primary, $e); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + throw new DatabaseConnectionException( |
| 176 | + 'Failed to obtain a read connection for pool [' . $name . '] (replica + primary fallback exhausted): ' . implode(' | ', $errors), |
| 177 | + $name, |
| 178 | + ); |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Resolve and validate the pool config for the given name. |
| 183 | + * |
| 184 | + * @param string $name Pool name |
| 185 | + * @return PoolConfig |
| 186 | + * @throws InvalidConfigException When the name is undefined or config is malformed |
| 187 | + */ |
| 188 | + private function resolvePool(string $name): PoolConfig |
72 | 189 | { |
73 | 190 | if (!\array_key_exists($name, $this->configs)) { |
74 | 191 | throw new InvalidConfigException( |
75 | 192 | 'Database connection [' . $name . '] is not defined.', |
76 | 193 | ); |
77 | 194 | } |
78 | 195 |
|
79 | | - $pool = ConnectionConfigResolver::validatePool($name, $this->configs[$name]); |
| 196 | + return ConnectionConfigResolver::validatePool($name, $this->configs[$name]); |
| 197 | + } |
| 198 | + |
| 199 | + /** |
| 200 | + * Partition replicas into alive candidates and dead-cache skip messages. |
| 201 | + * |
| 202 | + * Skipped entries are recorded as preformatted error strings so they can be |
| 203 | + * appended to the cumulative diagnostic message that surfaces when every |
| 204 | + * connection attempt (replica + primary fallback) fails. |
| 205 | + * |
| 206 | + * @param PoolConfig $pool Pool config (provides replica list and pool name) |
| 207 | + * @return array{0: list<ValidatedConfig>, 1: list<string>} [alive in declaration order, skip messages] |
| 208 | + */ |
| 209 | + private function partitionByDeadCache(PoolConfig $pool): array |
| 210 | + { |
| 211 | + $alive = []; |
| 212 | + $skipped = []; |
| 213 | + foreach ($pool->replicas as $replica) { |
| 214 | + if ($this->deadCache->isDead($replica->host, $replica->port ?? 0, $pool->name)) { |
| 215 | + $skipped[] = $replica->host . ':' . ($replica->port ?? '?') . ' → skipped (dead-cache)'; |
| 216 | + |
| 217 | + continue; |
| 218 | + } |
| 219 | + $alive[] = $replica; |
| 220 | + } |
| 221 | + |
| 222 | + return [$alive, $skipped]; |
| 223 | + } |
| 224 | + |
| 225 | + /** |
| 226 | + * Mark a failed replica dead in the negative cache. |
| 227 | + * |
| 228 | + * Auth failures (SQLSTATE 28000) are pool-specific: the credential is wrong |
| 229 | + * only for this pool, so the per-pool key is used. Everything else (TCP |
| 230 | + * refused, server unreachable, DO 1 failure) implies the host itself is |
| 231 | + * unhealthy and goes to the shared key. |
| 232 | + * |
| 233 | + * @param PoolConfig $pool Pool config (provides pool name and TTL) |
| 234 | + * @param ValidatedConfig $replica The replica that just failed |
| 235 | + * @param DatabaseException $e Failure thrown by the factory or ping() |
| 236 | + * @return void |
| 237 | + */ |
| 238 | + private function recordReplicaFailure(PoolConfig $pool, ValidatedConfig $replica, DatabaseException $e): void |
| 239 | + { |
| 240 | + $port = $replica->port ?? 0; |
| 241 | + |
| 242 | + if ($e instanceof DatabaseConnectionException && $e->sqlState === '28000') { |
| 243 | + $this->deadCache->markPoolDead($replica->host, $port, $pool->name, $pool->deadCacheTtlSeconds); |
80 | 244 |
|
81 | | - return $this->factory->make($pool->primary, $name); |
| 245 | + return; |
| 246 | + } |
| 247 | + |
| 248 | + $this->deadCache->markServerDead($replica->host, $port, $pool->deadCacheTtlSeconds); |
| 249 | + } |
| 250 | + |
| 251 | + /** |
| 252 | + * Format one failed attempt for the cumulative error message. |
| 253 | + * |
| 254 | + * @param ValidatedConfig $config Target host/port |
| 255 | + * @param DatabaseException $e Failure |
| 256 | + * @return string |
| 257 | + */ |
| 258 | + private function formatAttemptError(ValidatedConfig $config, DatabaseException $e): string |
| 259 | + { |
| 260 | + return $config->host . ':' . ($config->port ?? '?') . ' → ' . $e->getMessage(); |
82 | 261 | } |
83 | 262 | } |
0 commit comments