Skip to content

Commit 5a1c8f7

Browse files
committed
fix: worker connection strategy
1 parent a96dbb3 commit 5a1c8f7

1 file changed

Lines changed: 18 additions & 17 deletions

File tree

app/Worker/DoctrineWorker.php

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
use Illuminate\Queue\Worker as IlluminateWorker;
2222
use Illuminate\Queue\WorkerOptions;
2323
use Illuminate\Support\Facades\Log;
24+
use LaravelDoctrine\ORM\Facades\Registry;
25+
use models\utils\SilverstripeBaseModel;
2426
use Throwable;
2527

2628
/**
@@ -42,7 +44,7 @@ public function __construct(
4244
callable $isDownForMaintenance
4345
) {
4446
$this->entityManager = $entityManager;
45-
47+
$this->manager_name = SilverstripeBaseModel::EntityManager;
4648
parent::__construct($manager, $events, $exceptions, $isDownForMaintenance);
4749
}
4850

@@ -75,11 +77,12 @@ protected function runJob($job, $connectionName, WorkerOptions $options): void
7577
*/
7678
private function assertEntityManagerIsOpen(): void
7779
{
78-
if ($this->entityManager->isOpen()) {
79-
return;
80-
}
80+
$this->entityManager = Registry::getManager($this->manager_name);
8181

82-
throw new ORMException('The entity manager is closed.');
82+
if (!$this->entityManager->isOpen()) {
83+
Log::warning("DoctrineWorker::runJob : entity manager is closed!, trying to re open...");
84+
$this->entityManager = Registry::resetManager($this->manager_name);
85+
}
8386
}
8487

8588
/**
@@ -90,21 +93,19 @@ private function assertEntityManagerIsOpen(): void
9093
*/
9194
private function ensureDatabaseConnectionIsOpen(): void
9295
{
93-
$connection = $this->entityManager->getConnection();
96+
$con = $this->entityManager->getConnection();
9497

95-
// This replicates what the deprecated ping() function used to do.
96-
try {
97-
$connection->executeQuery($connection->getDatabasePlatform()->getDummySelectSQL());
98-
$ping = true;
99-
} catch (Exception $e) {
100-
Log::warning(sprintf("DoctrineWorker::ensureDatabaseConnectionIsOpen error %s", $e->getMessage()));
101-
$ping = false;
102-
}
98+
/**
99+
* Some database systems close the connection after a period of time, in MySQL this is system variable
100+
* `wait_timeout`. Given the daemon is meant to run indefinitely we need to make sure we have an open
101+
* connection before working any job. Otherwise we would see `MySQL has gone away` type errors.
102+
*/
103103

104-
if (!$ping) {
105-
$connection->close();
106-
$connection->connect();
104+
if ($con->ping() === false) {
105+
$con->close();
106+
$con->connect();
107107
}
108+
108109
}
109110

110111
/**

0 commit comments

Comments
 (0)