Skip to content

Commit

Permalink
fix: Add reconnect check in case of timeouts on the db side
Browse files Browse the repository at this point in the history
Signed-off-by: Julius Härtl <jus@bitgrid.net>
  • Loading branch information
juliushaertl committed Jan 10, 2024
1 parent f0a4aa9 commit 44dd3cf
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/private/DB/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Exception\ConnectionLost;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
Expand Down Expand Up @@ -78,6 +79,7 @@ class Connection extends PrimaryReadReplicaConnection {

/** @var DbDataCollector|null */
protected $dbDataCollector = null;
private int $lastConnectionCheck = 0;

/**
* Initializes a new instance of the Connection class.
Expand Down Expand Up @@ -123,10 +125,13 @@ public function __construct(
public function connect($connectionName = null) {
try {
if ($this->_conn) {
$this->reconnectIfNeeded();
/** @psalm-suppress InternalMethod */
return parent::connect();
}

$this->lastConnectionCheck = time();

// Only trigger the event logger for the initial connect call
$eventLogger = \OC::$server->get(IEventLogger::class);
$eventLogger->start('connect:db', 'db connection opened');
Expand Down Expand Up @@ -618,4 +623,18 @@ protected function performConnect(?string $connectionName = null): bool {
}
return $result;
}

private function reconnectIfNeeded(): void {
if ($this->lastConnectionCheck + 30 >= time() || $this->isTransactionActive()) {
return;
}

try {
$this->_conn->query($this->getDriver()->getDatabasePlatform()->getDummySelectSQL());
$this->lastConnectionCheck = time();
} catch (ConnectionLost|\Exception $e) {
$this->logger->warning('Exception during connectivity check, closing and reconnecting', ['exception' => $e]);
$this->close();
}
}
}

0 comments on commit 44dd3cf

Please sign in to comment.