Skip to content
Merged
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
42 changes: 31 additions & 11 deletions app/Checks/DatabaseConnectionCountCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,52 @@

namespace App\Checks;

use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Support\Str;
use Spatie\Health\Checks\Checks\DatabaseConnectionCountCheck as SpatieDatabaseConnectionCountCheck;
use Spatie\Health\Checks\Result;

/**
* spatie's DatabaseConnectionCountCheck with the agreed thresholds (warn
* above 50, fail above 80), reporting ok for apps without a database and
* for SQLite, which has no connection count.
* Informational only: reports the number of open connections of the app's
* own database and never warns or fails. On PostgreSQL only connections to
* the current database count, because Neon servers are shared between apps.
* Apps without a database and SQLite report ok.
*/
class DatabaseConnectionCountCheck extends SpatieDatabaseConnectionCountCheck
{
protected ?int $warningThreshold = 50;

protected int $errorThreshold = 80;

public function run(): Result
{
if (! DatabaseAvailability::isAvailable()) {
return Result::make()->shortSummary('no database')->ok();
}

$connection = $this->connectionName ?? $this->getDefaultConnectionName();

if (config("database.connections.{$connection}.driver") === 'sqlite') {
if (config("database.connections.{$this->connection()}.driver") === 'sqlite') {
return Result::make()->shortSummary('sqlite')->ok();
}

return parent::run();
$connectionCount = $this->getConnectionCount();

return Result::make()
->ok()
->meta(['connection_count' => $connectionCount])
->shortSummary($connectionCount.' '.Str::plural('connection', $connectionCount));
}

protected function getConnectionCount(): int
{
$connection = app(ConnectionResolverInterface::class)->connection($this->connection());

if ($connection->getDriverName() !== 'pgsql') {
return parent::getConnectionCount();
}

$count = $connection->scalar('select count(*) from pg_stat_activity where datname = current_database()');

return is_numeric($count) ? (int) $count : 0;
}

private function connection(): string
{
return $this->connectionName ?? $this->getDefaultConnectionName();
}
}
2 changes: 0 additions & 2 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
use Spatie\Health\Checks\Checks\CacheCheck;
use Spatie\Health\Checks\Checks\DebugModeCheck;
use Spatie\Health\Checks\Checks\EnvironmentCheck;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;
use Spatie\Health\Checks\Checks\ScheduleCheck;
use Spatie\Health\Facades\Health;
use Spatie\SecurityAdvisoriesHealthCheck\SecurityAdvisoriesCheck;
Expand Down Expand Up @@ -82,7 +81,6 @@ public function boot(): void
DatabaseCheck::new(),
DatabaseConnectionCountCheck::new(),
CacheCheck::new(),
OptimizedAppCheck::new(),
ScheduleCheck::new()->heartbeatMaxAgeInMinutes(120),
SecurityAdvisoriesCheck::new(),
NightwatchIssuesCheck::new()->if(filled(config('default.nightwatch.api_token')) && filled(config('default.nightwatch.application_id'))),
Expand Down
80 changes: 75 additions & 5 deletions tests/Unit/Checks/DatabaseConnectionCountCheckTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
declare(strict_types=1);

use App\Checks\DatabaseConnectionCountCheck;
use Illuminate\Database\Connection;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\MySqlConnection;
use Spatie\Health\Enums\Status;

function connectionCountCheckWith(int $connections): DatabaseConnectionCountCheck
Expand All @@ -23,6 +26,19 @@ protected function getConnectionCount(): int
return $check;
}

function bindConnection(string $class, string $driver, mixed $count): void
{
$connection = Mockery::mock($class);
$connection->shouldReceive('getDriverName')->andReturn($driver);
$connection->shouldReceive('scalar')->andReturn($count);
$connection->shouldReceive('selectOne')->andReturn((object) ['COUNT(*)' => $count]);

$resolver = Mockery::mock(ConnectionResolverInterface::class);
$resolver->shouldReceive('connection')->andReturn($connection);

app()->instance(ConnectionResolverInterface::class, $resolver);
}

it('reports ok with "no database" when the app has none', function () {
config(['health.uses_database' => false]);

Expand All @@ -41,10 +57,64 @@ protected function getConnectionCount(): int
->and($result->shortSummary)->toBe('sqlite');
})->group('unit', 'checks');

it('applies the agreed thresholds', function (int $connections, Status $status) {
expect(connectionCountCheckWith($connections)->run()->status->equals($status))->toBeTrue();
it('only reports the count and never warns or fails', function (int $connections, string $summary) {
$result = connectionCountCheckWith($connections)->run();

expect($result->status->equals(Status::ok()))->toBeTrue()
->and($result->shortSummary)->toBe($summary)
->and($result->meta)->toBe(['connection_count' => $connections]);
})->with([
'ok' => [10, Status::ok()],
'warning above 50' => [60, Status::warning()],
'failed above 80' => [90, Status::failed()],
'one' => [1, '1 connection'],
'many' => [500, '500 connections'],
])->group('unit', 'checks');

it('counts only the connections of the current database on postgres', function () {
config(['database.connections.health_pgsql' => ['driver' => 'pgsql']]);
bindConnection(Connection::class, 'pgsql', 7);

$check = new class extends DatabaseConnectionCountCheck
{
public function count(): int
{
return $this->getConnectionCount();
}
};

$check->connectionName('health_pgsql');

expect($check->count())->toBe(7);
})->group('unit', 'checks');

it('reports zero when postgres returns no number', function () {
config(['database.connections.health_pgsql' => ['driver' => 'pgsql']]);
bindConnection(Connection::class, 'pgsql', null);

$check = new class extends DatabaseConnectionCountCheck
{
public function count(): int
{
return $this->getConnectionCount();
}
};

$check->connectionName('health_pgsql');

expect($check->count())->toBe(0);
})->group('unit', 'checks');

it('falls back to spatie for other drivers', function () {
config(['database.connections.health_mysql' => ['driver' => 'mysql']]);
bindConnection(MySqlConnection::class, 'mysql', 4);

$check = new class extends DatabaseConnectionCountCheck
{
public function count(): int
{
return $this->getConnectionCount();
}
};

$check->connectionName('health_mysql');

expect($check->count())->toBe(4);
})->group('unit', 'checks');
Loading