Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Pools/Pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,11 @@ public function pop(): Connection
$this->active[$connection->getID()] = $connection;
});
return $connection;
} catch (\Exception $e) {
} catch (\Throwable $e) {
// Catch every Throwable, not just Exception: the slot was reserved
// (connectionsCreated++) before creating, so an Error (e.g. TypeError
// from the init callback) must release it too. Otherwise the reserved
// capacity leaks and the pool permanently reports itself as empty.
$this->pool->synchronized(function (): void {
$this->connectionsCreated--;
});
Expand Down
44 changes: 44 additions & 0 deletions tests/Pools/Scopes/PoolTestScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,50 @@ public function testPopRetriesAfterConnectionCreationFailure(): void
});
}

public function testPopReleasesReservedSlotWhenCreationThrowsError(): void
{
$this->execute(function (): void {
// The init callback throws a Throwable that is NOT an Exception (e.g. a
// TypeError). pop() reserves a capacity slot (connectionsCreated++) before
// creating, so it must release that slot on ANY failure, not just Exception.
// Otherwise the reserved slots leak and the pool permanently reports itself
// as empty ("size N, active 0, idle 0") even though nothing is in use.
$pool = new Pool($this->getAdapter(), 'test-error-leak', 2, function () {
throw new \TypeError('Connection init failed');
});
$pool->setReconnectAttempts(1);
$pool->setReconnectSleep(0);
$pool->setRetryAttempts(1);
$pool->setRetrySleep(0);

// Exhaust every creation attempt; each one must fully unwind.
for ($i = 0; $i < 5; $i++) {
try {
$pool->pop();
$this->fail('Should have thrown');
} catch (Exception | \TypeError) {
// expected: creation always fails
}
}

// No connection was ever handed out, so all capacity must still be available.
$this->assertSame(2, $pool->count());
$this->assertSame(0, \count($this->readActive($pool)));
});
}

/**
* @param Pool<mixed> $pool
* @return array<string, mixed>
*/
private function readActive(Pool $pool): array
{
$reflection = new \ReflectionProperty(Pool::class, 'active');
/** @var array<string, mixed> $active */
$active = $reflection->getValue($pool);
return $active;
}

public function testPoolEmptyErrorIncludesActiveCount(): void
{
$this->execute(function (): void {
Expand Down