|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Service\Pool; |
| 6 | + |
| 7 | +use Swoole\Coroutine\Channel; |
| 8 | +use Swoole\Coroutine\Socket; |
| 9 | +use App\Service\TargetConnector; |
| 10 | + |
| 11 | +/** |
| 12 | + * Per-Worker Connection Pool for MySQL Target Connections |
| 13 | + * |
| 14 | + * Maintains a fixed-size pool of connections to the target MySQL server. |
| 15 | + * Each Swoole Worker has its own pool instance for thread safety. |
| 16 | + */ |
| 17 | +class ConnectionPool |
| 18 | +{ |
| 19 | + private Channel $pool; |
| 20 | + private TargetConnector $connector; |
| 21 | + private int $size; |
| 22 | + private float $idleTimeout; |
| 23 | + private array $stats = [ |
| 24 | + 'created' => 0, |
| 25 | + 'borrowed' => 0, |
| 26 | + 'returned' => 0, |
| 27 | + 'failed' => 0, |
| 28 | + 'destroyed' => 0, |
| 29 | + ]; |
| 30 | + |
| 31 | + public function __construct(TargetConnector $connector, int $size = 12, float $idleTimeout = 300.0) |
| 32 | + { |
| 33 | + $this->connector = $connector; |
| 34 | + $this->size = $size; |
| 35 | + $this->idleTimeout = $idleTimeout; |
| 36 | + $this->pool = new Channel($size); |
| 37 | + |
| 38 | + // Pre-populate the pool with connections |
| 39 | + $this->initializePool(); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Initialize the connection pool by creating initial connections |
| 44 | + */ |
| 45 | + private function initializePool(): void |
| 46 | + { |
| 47 | + for ($i = 0; $i < $this->size; $i++) { |
| 48 | + try { |
| 49 | + $connection = $this->connector->connect(); |
| 50 | + if ($connection) { |
| 51 | + $this->pool->push([ |
| 52 | + 'socket' => $connection, |
| 53 | + 'created_at' => microtime(true), |
| 54 | + 'last_used' => microtime(true), |
| 55 | + ]); |
| 56 | + $this->stats['created']++; |
| 57 | + } |
| 58 | + } catch (\Exception $e) { |
| 59 | + $this->stats['failed']++; |
| 60 | + // Log the error but continue creating other connections |
| 61 | + error_log("Failed to create initial connection in pool: " . $e->getMessage()); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Borrow a connection from the pool |
| 68 | + * |
| 69 | + * @param float $timeout Timeout in seconds to wait for a connection |
| 70 | + * @return Socket|null |
| 71 | + */ |
| 72 | + public function borrow(float $timeout = 5.0): ?Socket |
| 73 | + { |
| 74 | + $startTime = microtime(true); |
| 75 | + |
| 76 | + // Try to get an existing connection from the pool |
| 77 | + $connection = $this->pool->pop($timeout); |
| 78 | + if ($connection !== false) { |
| 79 | + $this->stats['borrowed']++; |
| 80 | + |
| 81 | + // Check if connection is still healthy |
| 82 | + if ($this->isConnectionHealthy($connection['socket'])) { |
| 83 | + $connection['last_used'] = microtime(true); |
| 84 | + return $connection['socket']; |
| 85 | + } else { |
| 86 | + // Connection is unhealthy, destroy it and try to create a new one |
| 87 | + $this->destroyConnection($connection['socket']); |
| 88 | + $this->stats['destroyed']++; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + // No available connection, try to create a new one |
| 93 | + try { |
| 94 | + $socket = $this->connector->connect(); |
| 95 | + if ($socket) { |
| 96 | + $this->stats['created']++; |
| 97 | + $this->stats['borrowed']++; |
| 98 | + return $socket; |
| 99 | + } |
| 100 | + } catch (\Exception $e) { |
| 101 | + $this->stats['failed']++; |
| 102 | + error_log("Failed to create new connection in pool: " . $e->getMessage()); |
| 103 | + } |
| 104 | + |
| 105 | + return null; |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Return a connection to the pool |
| 110 | + * |
| 111 | + * @param Socket $socket |
| 112 | + */ |
| 113 | + public function release(Socket $socket): void |
| 114 | + { |
| 115 | + // Check if connection is still healthy before returning to pool |
| 116 | + if ($this->isConnectionHealthy($socket)) { |
| 117 | + $connection = [ |
| 118 | + 'socket' => $socket, |
| 119 | + 'created_at' => microtime(true), // Reset timestamps |
| 120 | + 'last_used' => microtime(true), |
| 121 | + ]; |
| 122 | + |
| 123 | + // Try to return to pool, if pool is full, close the connection |
| 124 | + if ($this->pool->push($connection, 0.1) === false) { |
| 125 | + $this->destroyConnection($socket); |
| 126 | + } else { |
| 127 | + $this->stats['returned']++; |
| 128 | + } |
| 129 | + } else { |
| 130 | + // Connection is unhealthy, destroy it |
| 131 | + $this->destroyConnection($socket); |
| 132 | + $this->stats['destroyed']++; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Check if a connection is healthy |
| 138 | + * |
| 139 | + * @param Socket $socket |
| 140 | + * @return bool |
| 141 | + */ |
| 142 | + private function isConnectionHealthy(Socket $socket): bool |
| 143 | + { |
| 144 | + // Basic health check - socket should be connected and not have errors |
| 145 | + if (!$socket->isConnected()) { |
| 146 | + return false; |
| 147 | + } |
| 148 | + |
| 149 | + // Check if connection has been idle for too long |
| 150 | + $connection = null; |
| 151 | + while ($this->pool->length() > 0) { |
| 152 | + $conn = $this->pool->pop(0.001); |
| 153 | + if ($conn !== false && $conn['socket'] === $socket) { |
| 154 | + $connection = $conn; |
| 155 | + break; |
| 156 | + } elseif ($conn !== false) { |
| 157 | + $this->pool->push($conn); // Put back other connections |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + if ($connection && (microtime(true) - $connection['last_used']) > $this->idleTimeout) { |
| 162 | + return false; |
| 163 | + } |
| 164 | + |
| 165 | + // Put connection back if we found it |
| 166 | + if ($connection) { |
| 167 | + $this->pool->push($connection); |
| 168 | + } |
| 169 | + |
| 170 | + return true; |
| 171 | + } |
| 172 | + |
| 173 | + /** |
| 174 | + * Destroy a connection |
| 175 | + * |
| 176 | + * @param Socket $socket |
| 177 | + */ |
| 178 | + private function destroyConnection(Socket $socket): void |
| 179 | + { |
| 180 | + try { |
| 181 | + if ($socket->isConnected()) { |
| 182 | + $socket->close(); |
| 183 | + } |
| 184 | + } catch (\Exception $e) { |
| 185 | + // Ignore errors when closing unhealthy connections |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + /** |
| 190 | + * Get pool statistics |
| 191 | + * |
| 192 | + * @return array |
| 193 | + */ |
| 194 | + public function getStats(): array |
| 195 | + { |
| 196 | + return array_merge($this->stats, [ |
| 197 | + 'pool_size' => $this->size, |
| 198 | + 'available' => $this->pool->length(), |
| 199 | + 'idle_timeout' => $this->idleTimeout, |
| 200 | + ]); |
| 201 | + } |
| 202 | + |
| 203 | + /** |
| 204 | + * Close all connections in the pool |
| 205 | + */ |
| 206 | + public function close(): void |
| 207 | + { |
| 208 | + while ($this->pool->length() > 0) { |
| 209 | + $connection = $this->pool->pop(0.001); |
| 210 | + if ($connection !== false) { |
| 211 | + $this->destroyConnection($connection['socket']); |
| 212 | + } |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + /** |
| 217 | + * Get the current number of available connections |
| 218 | + * |
| 219 | + * @return int |
| 220 | + */ |
| 221 | + public function getAvailableCount(): int |
| 222 | + { |
| 223 | + return $this->pool->length(); |
| 224 | + } |
| 225 | +} |
0 commit comments