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
5 changes: 5 additions & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1714,6 +1714,11 @@
'OC\\DB\\ConnectionFactory' => $baseDir . '/lib/private/DB/ConnectionFactory.php',
'OC\\DB\\DbDataCollector' => $baseDir . '/lib/private/DB/DbDataCollector.php',
'OC\\DB\\Exceptions\\DbalException' => $baseDir . '/lib/private/DB/Exceptions/DbalException.php',
'OC\\DB\\Middleware\\ConnectionActivityConnection' => $baseDir . '/lib/private/DB/Middleware/ConnectionActivityConnection.php',
'OC\\DB\\Middleware\\ConnectionActivityDriver' => $baseDir . '/lib/private/DB/Middleware/ConnectionActivityDriver.php',
'OC\\DB\\Middleware\\ConnectionActivityMiddleware' => $baseDir . '/lib/private/DB/Middleware/ConnectionActivityMiddleware.php',
'OC\\DB\\Middleware\\ConnectionActivityNotifier' => $baseDir . '/lib/private/DB/Middleware/ConnectionActivityNotifier.php',
'OC\\DB\\Middleware\\ConnectionActivityStatement' => $baseDir . '/lib/private/DB/Middleware/ConnectionActivityStatement.php',
'OC\\DB\\Middleware\\UtcTimezoneMiddleware' => $baseDir . '/lib/private/DB/Middleware/UtcTimezoneMiddleware.php',
'OC\\DB\\Middleware\\UtcTimezoneMiddlewareDriver' => $baseDir . '/lib/private/DB/Middleware/UtcTimezoneMiddlewareDriver.php',
'OC\\DB\\MigrationException' => $baseDir . '/lib/private/DB/MigrationException.php',
Expand Down
5 changes: 5 additions & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,11 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\DB\\ConnectionFactory' => __DIR__ . '/../../..' . '/lib/private/DB/ConnectionFactory.php',
'OC\\DB\\DbDataCollector' => __DIR__ . '/../../..' . '/lib/private/DB/DbDataCollector.php',
'OC\\DB\\Exceptions\\DbalException' => __DIR__ . '/../../..' . '/lib/private/DB/Exceptions/DbalException.php',
'OC\\DB\\Middleware\\ConnectionActivityConnection' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/ConnectionActivityConnection.php',
'OC\\DB\\Middleware\\ConnectionActivityDriver' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/ConnectionActivityDriver.php',
'OC\\DB\\Middleware\\ConnectionActivityMiddleware' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/ConnectionActivityMiddleware.php',
'OC\\DB\\Middleware\\ConnectionActivityNotifier' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/ConnectionActivityNotifier.php',
'OC\\DB\\Middleware\\ConnectionActivityStatement' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/ConnectionActivityStatement.php',
'OC\\DB\\Middleware\\UtcTimezoneMiddleware' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/UtcTimezoneMiddleware.php',
'OC\\DB\\Middleware\\UtcTimezoneMiddlewareDriver' => __DIR__ . '/../../..' . '/lib/private/DB/Middleware/UtcTimezoneMiddlewareDriver.php',
'OC\\DB\\MigrationException' => __DIR__ . '/../../..' . '/lib/private/DB/MigrationException.php',
Expand Down
24 changes: 21 additions & 3 deletions lib/private/DB/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Doctrine\DBAL\Result;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Statement;
use OC\DB\Middleware\ConnectionActivityNotifier;
use OC\DB\QueryBuilder\Partitioned\PartitionedQueryBuilder;
use OC\DB\QueryBuilder\Partitioned\PartitionSplit;
use OC\DB\QueryBuilder\QueryBuilder;
Expand Down Expand Up @@ -63,6 +64,8 @@ class Connection extends PrimaryReadReplicaConnection {
protected int $queriesBuilt = 0;
protected int $queriesExecuted = 0;
protected ?DbDataCollector $dbDataCollector = null;
/** Seconds the connection may sit idle before the next use re-verifies connectivity */
private const CONNECTION_CHECK_INTERVAL = 30;
private array $lastConnectionCheck = [];

protected ?float $transactionActiveSince = null;
Expand Down Expand Up @@ -122,6 +125,10 @@ public function __construct(
parent::__construct($params, $driver, $config, $eventManager);
$this->adapter = new $params['adapter']($this);
$this->tablePrefix = $params['tablePrefix'];
$activityNotifier = $params['activity_notifier'] ?? null;
if ($activityNotifier instanceof ConnectionActivityNotifier) {
$activityNotifier->setListener($this->refreshLastConnectionCheck(...));
}
$this->isShardingEnabled = isset($this->params['sharding']) && !empty($this->params['sharding']);

if ($this->isShardingEnabled) {
Expand Down Expand Up @@ -221,7 +228,7 @@ public function connect($connectionName = null) {
$status = parent::connect();
$eventLogger->end('connect:db');

$this->lastConnectionCheck[$this->getConnectionName()] = time();
$this->refreshLastConnectionCheck();

return $status;
} catch (Exception $e) {
Expand Down Expand Up @@ -902,21 +909,32 @@ public function rollBack() {
private function reconnectIfNeeded(): void {
if (
!isset($this->lastConnectionCheck[$this->getConnectionName()])
|| time() <= $this->lastConnectionCheck[$this->getConnectionName()] + 30
|| time() <= $this->lastConnectionCheck[$this->getConnectionName()] + self::CONNECTION_CHECK_INTERVAL
|| $this->isTransactionActive()
) {
return;
}

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

/**
* A successful round trip proves the connection is alive: pushing the idle
* timer forward keeps the connectivity probe of reconnectIfNeeded() from
* firing between adjacent operations, where its query would reset the
* driver level last insert id on MySQL. Invoked for every driver level
* execution via the ConnectionActivityMiddleware.
*/
private function refreshLastConnectionCheck(): void {
$this->lastConnectionCheck[$this->getConnectionName()] = time();
}

private function getConnectionName(): string {
return $this->isConnectedToPrimary() ? 'primary' : 'replica';
}
Expand Down
4 changes: 4 additions & 0 deletions lib/private/DB/ConnectionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
use OC\DB\Middleware\ConnectionActivityMiddleware;
use OC\DB\Middleware\UtcTimezoneMiddleware;
use OC\DB\QueryBuilder\Sharded\AutoIncrementHandler;
use OC\DB\QueryBuilder\Sharded\ShardConnectionManager;
Expand Down Expand Up @@ -146,9 +147,12 @@ public function getConnection(string $type, array $additionalConnectionParams):
break;
}
$configuration = new Configuration();
$activityMiddleware = new ConnectionActivityMiddleware();
$configuration->setMiddlewares([
new UtcTimezoneMiddleware(),
$activityMiddleware,
]);
$connectionParams['activity_notifier'] = $activityMiddleware->getNotifier();
/** @var Connection $connection */
$connection = DriverManager::getConnection(
$connectionParams,
Expand Down
57 changes: 57 additions & 0 deletions lib/private/DB/Middleware/ConnectionActivityConnection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\DB\Middleware;

use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Driver\Middleware\AbstractConnectionMiddleware;
use Doctrine\DBAL\Driver\PDO\Connection as PDOConnection;
use Doctrine\DBAL\Driver\Result;
use Doctrine\DBAL\Driver\Statement;

final class ConnectionActivityConnection extends AbstractConnectionMiddleware {
public function __construct(
private Connection $inner,
private ConnectionActivityNotifier $notifier,
) {
parent::__construct($inner);
}

/**
* Kept working for consumers that reach the native PDO handle through the
* deprecated accessor, like SQLiteSessionInit: forwarding is intentionally
* preferred over migrating the callers, as those code paths get refactored
* with the DBAL 4 upgrade anyway.
*/
public function getWrappedConnection(): \PDO {
if (!$this->inner instanceof PDOConnection) {
throw new \LogicException('The wrapped connection is not a PDO based connection');
}
return $this->inner->getWrappedConnection();
}

#[\Override]
public function prepare(string $sql): Statement {
return new ConnectionActivityStatement(parent::prepare($sql), $this->notifier);
}

#[\Override]
public function query(string $sql): Result {
$result = parent::query($sql);
$this->notifier->notify();
return $result;
}

#[\Override]
public function exec(string $sql): int {
$result = parent::exec($sql);
$this->notifier->notify();
return $result;
}
}
27 changes: 27 additions & 0 deletions lib/private/DB/Middleware/ConnectionActivityDriver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\DB\Middleware;

use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Middleware\AbstractDriverMiddleware;

final class ConnectionActivityDriver extends AbstractDriverMiddleware {
public function __construct(
Driver $driver,
private ConnectionActivityNotifier $notifier,
) {
parent::__construct($driver);
}

#[\Override]
public function connect(array $params) {
return new ConnectionActivityConnection(parent::connect($params), $this->notifier);
}
}
41 changes: 41 additions & 0 deletions lib/private/DB/Middleware/ConnectionActivityMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\DB\Middleware;

use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Middleware;

/**
* Doctrine middleware reporting every query and statement execution back to
* the owning connection, so the idle timer of the connectivity check can be
* refreshed (see \OC\DB\Connection::refreshLastConnectionCheck()). Working on
* the driver level covers executions of prepared statements as well, which
* bypass the executeQuery() and executeStatement() methods of the connection.
*/
final class ConnectionActivityMiddleware implements Middleware {
private ConnectionActivityNotifier $notifier;

public function __construct() {
$this->notifier = new ConnectionActivityNotifier();
}

/**
* Hand the notifier to the connection that wants to listen, e.g. via the
* connection parameters.
*/
public function getNotifier(): ConnectionActivityNotifier {
return $this->notifier;
}

#[\Override]
public function wrap(Driver $driver): Driver {
return new ConnectionActivityDriver($driver, $this->notifier);
}
}
32 changes: 32 additions & 0 deletions lib/private/DB/Middleware/ConnectionActivityNotifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\DB\Middleware;

/**
* Relays driver level activity to a listener that can only be registered
* after the middleware was created: middlewares are configured before the
* DriverManager constructs the connection wrapper that wants to listen.
*/
final class ConnectionActivityNotifier {
private ?\Closure $listener = null;

/**
* @param \Closure():void $listener
*/
public function setListener(\Closure $listener): void {
$this->listener = $listener;
}

public function notify(): void {
if ($this->listener !== null) {
($this->listener)();
}
}
}
30 changes: 30 additions & 0 deletions lib/private/DB/Middleware/ConnectionActivityStatement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\DB\Middleware;

use Doctrine\DBAL\Driver\Middleware\AbstractStatementMiddleware;
use Doctrine\DBAL\Driver\Result;
use Doctrine\DBAL\Driver\Statement;

final class ConnectionActivityStatement extends AbstractStatementMiddleware {
public function __construct(
Statement $statement,
private ConnectionActivityNotifier $notifier,
) {
parent::__construct($statement);
}

#[\Override]
public function execute($params = null): Result {
$result = parent::execute($params);
$this->notifier->notify();
return $result;
}
}
55 changes: 55 additions & 0 deletions tests/lib/DB/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
use Doctrine\DBAL\Platforms\MySQLPlatform;
use OC\DB\Adapter;
use OC\DB\Connection;
use OC\DB\ConnectionAdapter;
use OCP\IDBConnection;
use OCP\Server;
use Test\TestCase;

#[\PHPUnit\Framework\Attributes\Group('DB')]
Expand Down Expand Up @@ -96,4 +99,56 @@ public function testClusterConnectsToPrimaryAndReplica(): void {
$connection->ensureConnectedToReplica();
}

public function testSuccessfulQueryResetsConnectivityCheckTimer(): void {
$inner = $this->getInnerConnection();

// Ensure the connection is established before touching the timer
$qb = $inner->getQueryBuilder();
$qb->select('configvalue')->from('appconfig')->setMaxResults(1);
$qb->executeQuery()->closeCursor();

$property = $this->backdateLastConnectionCheck($inner);
$before = time();

$qb->executeQuery()->closeCursor();

// A connectivity probe firing between adjacent operations would reset
// the driver level last insert id on MySQL
self::assertGreaterThanOrEqual($before, max($property->getValue($inner)));
}

public function testPreparedStatementExecutionResetsConnectivityCheckTimer(): void {
$inner = $this->getInnerConnection();

$statement = $inner->prepare('SELECT `configvalue` FROM `*PREFIX*appconfig`', 1);

$property = $this->backdateLastConnectionCheck($inner);
$before = time();

$statement->executeQuery()->free();

self::assertGreaterThanOrEqual($before, max($property->getValue($inner)));
}

private function getInnerConnection(): Connection {
$connection = Server::get(IDBConnection::class);
if (!$connection instanceof ConnectionAdapter) {
self::markTestSkipped('Test requires the real database connection');
}

return $connection->getInner();
}

/**
* Make the connectivity check timer stale, but by less than the check
* interval: the probe must not fire, so only actual query activity can
* refresh the timer.
*/
private function backdateLastConnectionCheck(Connection $connection): \ReflectionProperty {
$property = new \ReflectionProperty(Connection::class, 'lastConnectionCheck');
$property->setValue($connection, ['primary' => time() - 20, 'replica' => time() - 20]);

return $property;
}

}
Loading