Skip to content
Open
171 changes: 171 additions & 0 deletions src/Provider/Amqp/AmqpHeartbeat.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<?php
namespace Packaged\Queue\Provider\Amqp;

use PhpAmqpLib\Connection\AbstractConnection;

/**
* Sends heartbeats for every registered AMQP connection in the process from one SIGALRM handler.
*
* A process has a single SIGALRM handler, so one sender per connection would leave every
* connection but the last registered without heartbeats.
*
* Connections are held by weak reference, so the registry never keeps a provider alive.
*/
final class AmqpHeartbeat
{
/** @var \WeakReference[] keyed by spl_object_id */
private static $_connections = [];
/** @var bool[] connections whose heartbeat failed, keyed by spl_object_id */
private static $_failed = [];
private static $_handlerInstalled = false;
/** Unix time the pending alarm fires, or 0 when none is pending */
private static $_nextBeat = 0;

public static function isSupported(): bool
{
if(defined('AMQP_WITHOUT_SIGNALS') && AMQP_WITHOUT_SIGNALS)
{
return false;
}
return function_exists('pcntl_async_signals')
&& function_exists('pcntl_signal')
&& function_exists('pcntl_alarm')
&& PHP_OS_FAMILY !== 'Windows';
Comment thread
TomK marked this conversation as resolved.
Resolved
}

public static function register(AbstractConnection $connection): void
{
if(!self::isSupported() || $connection->getHeartbeat() < 1)
{
return;
}
$id = spl_object_id($connection);
self::$_connections[$id] = \WeakReference::create($connection);
unset(self::$_failed[$id]);
self::_schedule();
}

public static function unregister(AbstractConnection $connection): void
{
$id = spl_object_id($connection);
if(!self::_holds($id, $connection))
{
return;
}
unset(self::$_connections[$id], self::$_failed[$id]);
if(!self::$_connections)
{
self::_cancel();
}
}

/**
* Whether a heartbeat on this connection failed in the signal handler.
* The connection is unusable, so its owner should disconnect and reconnect.
*/
public static function hasFailed(AbstractConnection $connection): bool
{
$id = spl_object_id($connection);
return isset(self::$_failed[$id]) && self::_holds($id, $connection);
}

/**
* Heartbeat each idle connection. Runs inside the SIGALRM handler.
*/
public static function beat(): void
{
self::$_nextBeat = 0;
foreach(self::$_connections as $id => $reference)
{
$connection = $reference->get();
if($connection === null || !$connection->isConnected())
{
unset(self::$_connections[$id], self::$_failed[$id]);
continue;
}
// A heartbeat frame written in the middle of another frame would corrupt the stream.
if(isset(self::$_failed[$id]) || $connection->isWriting())
{
continue;
}
if(time() > $connection->getLastActivity() + self::_interval($connection))
{
try
{
$connection->checkHeartBeat();
}
catch(\Throwable $e)
{
// Throwing here would unwind whatever code the signal interrupted.
// The owning provider sees the failure on its next push or consume and reconnects.
self::$_failed[$id] = true;
Comment thread
TomK marked this conversation as resolved.
Resolved
}
}
}
self::_schedule();
}

private static function _holds(int $id, AbstractConnection $connection): bool
{
return isset(self::$_connections[$id]) && self::$_connections[$id]->get() === $connection;
}

private static function _interval(AbstractConnection $connection): int
{
return (int)ceil($connection->getHeartbeat() / 2);
}

/**
* Arm the alarm for the shortest interval among live connections.
* A pending alarm is only ever brought forward, so registry changes cannot postpone it.
*/
private static function _schedule(): void
{
$interval = 0;
foreach(self::$_connections as $id => $reference)
{
$connection = $reference->get();
if($connection === null)
{
unset(self::$_connections[$id], self::$_failed[$id]);
continue;
}
$connectionInterval = self::_interval($connection);
if($interval === 0 || $connectionInterval < $interval)
{
$interval = $connectionInterval;
}
}

if($interval === 0)
{
self::_cancel();
return;
}

if(!self::$_handlerInstalled)
{
pcntl_async_signals(true);
pcntl_signal(SIGALRM, [self::class, 'beat'], true);
self::$_handlerInstalled = true;
}

$due = time() + $interval;
if(self::$_nextBeat === 0 || $due < self::$_nextBeat)
{
pcntl_alarm($interval);
self::$_nextBeat = $due;
}
}

private static function _cancel(): void
{
if(self::$_handlerInstalled)
{
pcntl_alarm(0);
pcntl_signal(SIGALRM, SIG_IGN);
self::$_handlerInstalled = false;
}
self::$_nextBeat = 0;
}
}
67 changes: 37 additions & 30 deletions src/Provider/Amqp/AmqpQueueProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AbstractConnection;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Connection\Heartbeat\PCNTLHeartbeatSender;
use PhpAmqpLib\Exception\AMQPHeartbeatMissedException;
use PhpAmqpLib\Exception\AMQPProtocolChannelException;
use PhpAmqpLib\Exception\AMQPRuntimeException;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
Expand Down Expand Up @@ -88,11 +86,6 @@ class AmqpQueueProvider extends AbstractQueueProvider
*/
private $_slowPushThreshold = 0;

/**
* @var ?PCNTLHeartbeatSender
*/
protected $_heartbeatSender;

protected function _construct()
{
$this->_fixedConsumerCallback = [$this, 'consumerCallback'];
Expand Down Expand Up @@ -313,9 +306,26 @@ public function consume(callable $callback)
{
return false;
}
if($this->_consumeHeartbeatFailed())
{
// The broker requeues the deliveries of the lost connection.
$this->disconnect(self::CONN_CONSUME);
return false;
}
return true;
}

/**
* Whether a background heartbeat failed on the consume connection.
* Its delivery tags are void, so settling them on a new channel would ack or reject unrelated messages.
*/
private function _consumeHeartbeatFailed(): bool
{
$connection = isset($this->_connections[self::CONN_CONSUME])
? $this->_connections[self::CONN_CONSUME] : null;
return $connection instanceof AbstractConnection && AmqpHeartbeat::hasFailed($connection);
}

protected function _processBatchMessage($msg, $tag = null)
{
$this->_batchData[$tag] = $msg;
Expand Down Expand Up @@ -404,6 +414,10 @@ public static function create(

public function ack($deliveryTag)
{
if($this->_consumeHeartbeatFailed())
{
return;
}
try
{
$this->_getChannel(self::CONN_CONSUME)
Expand All @@ -418,6 +432,10 @@ public function ack($deliveryTag)

public function nack($deliveryTag, $requeueFailures = false)
{
if($this->_consumeHeartbeatFailed())
{
return;
}
try
{
$this->_getChannel(self::CONN_CONSUME)
Expand All @@ -432,7 +450,7 @@ public function nack($deliveryTag, $requeueFailures = false)

public function batchAck(array $tagResults, $requeueFailures = false)
{
if(count($tagResults) < 1)
if(count($tagResults) < 1 || $this->_consumeHeartbeatFailed())
{
return;
}
Expand Down Expand Up @@ -494,10 +512,14 @@ protected function _refreshConnection($connectionMode)

$channel = isset($this->_channels[$connectionMode])
? $this->_channels[$connectionMode] : null;
$connection = isset($this->_connections[$connectionMode])
? $this->_connections[$connectionMode] : null;

// Disconnect if the channel exists but the connection is broken,
// if a background heartbeat on the connection failed,
// or if the connection has been open for too long
if(($channel &&
if(($connection instanceof AbstractConnection && AmqpHeartbeat::hasFailed($connection))
|| ($channel &&
((!$channel->getConnection())
|| (!$channel->getConnection()->isConnected())
)
Expand Down Expand Up @@ -582,20 +604,10 @@ protected function _getConnection($connectionMode)
}
$this->_persistentDefault = ValueAs::bool($config->getItem('persistent', false));
$this->_lastConnectTimes[$connectionMode] = time();
}

try
{
if($this->_heartbeatSender)
if(!empty($this->_connections[$connectionMode]))
{
$this->_heartbeatSender->unregister();
AmqpHeartbeat::register($this->_connections[$connectionMode]);
}
$this->_heartbeatSender = new PCNTLHeartbeatSender($this->_connections[$connectionMode]);
$this->_heartbeatSender->register();
}
catch(AMQPRuntimeException $e)
{
Log::error('Unable to start heartbeat sender. ' . $e->getMessage());
}

return $this->_connections[$connectionMode];
Expand Down Expand Up @@ -709,22 +721,17 @@ private function _disconnect($connectionMode)
}
$this->_channels[$connectionMode] = null;

if($this->_heartbeatSender)
if($connectionMode === self::CONN_CONSUME)
{
try
{
$this->_heartbeatSender->unregister();
}
catch(\Throwable $e)
{
}
// Delivery tags belong to the lost channel. The broker requeues those deliveries.
$this->_batchData = [];
}
$this->_heartbeatSender = null;

if((!empty($this->_connections[$connectionMode]))
&& ($this->_connections[$connectionMode] instanceof AbstractConnection)
)
{
AmqpHeartbeat::unregister($this->_connections[$connectionMode]);
Comment thread
TomK marked this conversation as resolved.
Resolved
try
{
$this->_connections[$connectionMode]->close();
Expand Down
Loading