diff --git a/src/Provider/Amqp/AmqpHeartbeat.php b/src/Provider/Amqp/AmqpHeartbeat.php new file mode 100644 index 0000000..72d951b --- /dev/null +++ b/src/Provider/Amqp/AmqpHeartbeat.php @@ -0,0 +1,171 @@ +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; + } + } + } + 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; + } +} diff --git a/src/Provider/Amqp/AmqpQueueProvider.php b/src/Provider/Amqp/AmqpQueueProvider.php index 00ec832..daf7d98 100644 --- a/src/Provider/Amqp/AmqpQueueProvider.php +++ b/src/Provider/Amqp/AmqpQueueProvider.php @@ -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; @@ -88,11 +86,6 @@ class AmqpQueueProvider extends AbstractQueueProvider */ private $_slowPushThreshold = 0; - /** - * @var ?PCNTLHeartbeatSender - */ - protected $_heartbeatSender; - protected function _construct() { $this->_fixedConsumerCallback = [$this, 'consumerCallback']; @@ -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; @@ -404,6 +414,10 @@ public static function create( public function ack($deliveryTag) { + if($this->_consumeHeartbeatFailed()) + { + return; + } try { $this->_getChannel(self::CONN_CONSUME) @@ -418,6 +432,10 @@ public function ack($deliveryTag) public function nack($deliveryTag, $requeueFailures = false) { + if($this->_consumeHeartbeatFailed()) + { + return; + } try { $this->_getChannel(self::CONN_CONSUME) @@ -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; } @@ -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()) ) @@ -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]; @@ -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]); try { $this->_connections[$connectionMode]->close(); diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index bd8ca42..9d5ad41 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -26,12 +26,7 @@ public function testFailHeartbeat() self::assertEquals(0, $q->getDisconnectCount()); $q->consume( function ($msg, $tag) use ($q) { - - $timeLeft = (int)$msg * 3; - while($timeLeft > 0) - { - $timeLeft = sleep($timeLeft); - } + self::_sleepFor((int)$msg * 3); $q->ack($tag); // expect one reconnect @@ -71,11 +66,7 @@ public function testHeartbeatAfterMissed() $q->push('trigger'); // sleep past the heartbeat interval to cause a missed heartbeat - $timeLeft = (int)$q->config()->getItem('heartbeat') * 3; - while($timeLeft > 0) - { - $timeLeft = sleep($timeLeft); - } + $this->_idlePastHeartbeatTimeout($q); $checksBefore = $q->getHeartbeatCheckCount(); $disconnectsBefore = $q->getDisconnectCount(); @@ -85,6 +76,247 @@ public function testHeartbeatAfterMissed() self::assertGreaterThan($disconnectsBefore, $q->getDisconnectCount()); } + public function testHeartbeatKeepsEveryConnectionOfAProviderAlive() + { + $q = $this->_getProvider('test_heartbeat_all_modes'); + $q->declareExchange() + ->declareQueue() + ->bindQueue(); + $q->push('open the push connection'); + $q->getQueueInfo(); + + $this->_idlePastHeartbeatTimeout($q); + + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_PUSH); + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_OTHER); + } + + public function testHeartbeatKeepsConnectionsOfEveryProviderAlive() + { + $first = $this->_getProvider('test_heartbeat_first_provider'); + $first->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the first provider push connection'); + $second = $this->_getProvider('test_heartbeat_second_provider'); + $second->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the second provider push connection'); + + $this->_idlePastHeartbeatTimeout($first); + + $this->_assertConnectionOpen($first, AmqpMockProvider::CONN_PUSH); + $this->_assertConnectionOpen($second, AmqpMockProvider::CONN_PUSH); + } + + public function testHeartbeatKeepsIdleConnectionAliveWhileOtherConnectionsChurn() + { + $idle = $this->_getProvider('test_heartbeat_idle_beside_churn'); + $idle->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the idle provider push connection'); + $churn = $this->_getProvider('test_heartbeat_churn'); + $churn->declareExchange() + ->declareQueue() + ->bindQueue(); + + // Open and close a connection every second, more often than the heartbeat interval. + $until = time() + (int)$idle->config()->getItem('heartbeat') * 3; + while(time() < $until) + { + $churn->push('churn'); + $churn->disconnect(); + self::_sleepFor(1); + } + + $this->_assertConnectionOpen($idle, AmqpMockProvider::CONN_PUSH); + } + + public function testPushReconnectsAfterHeartbeatFailedDuringProcessPause() + { + $q = $this->_getProvider('test_heartbeat_after_pause'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('before pause'); + + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is already missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + + $disconnectsBefore = $q->getDisconnectCount(); + $q->push('after pause'); + self::assertGreaterThan($disconnectsBefore, $q->getDisconnectCount()); + } + + public function testDisconnectingOneModeKeepsTheOtherHeartbeating() + { + $q = $this->_getProvider('test_heartbeat_disconnect_one_mode'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the push connection'); + $q->getQueueInfo(); + $q->disconnect(AmqpMockProvider::CONN_OTHER); + + $this->_idlePastHeartbeatTimeout($q); + + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_PUSH); + } + + public function testConsumerCallbackPausedPastHeartbeatLeavesMessageForRedelivery() + { + $q = $this->_getProvider('test_heartbeat_paused_callback'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('slow message'); + + $consumed = $q->consume( + function ($message, $deliveryTag) use ($q) { + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + $q->ack($deliveryTag); + } + ); + self::assertFalse($consumed, 'consume() should report the batch as not consumed.'); + + $redelivered = null; + $q->consume( + function ($message, $deliveryTag) use ($q, &$redelivered) { + $redelivered = $message; + $q->ack($deliveryTag); + } + ); + self::assertSame('slow message', $redelivered); + } + + public function testBatchDropsDeliveriesFromAConsumeConnectionLostMidBatch() + { + $q = $this->_getProvider('test_heartbeat_batch_lost_connection'); + $q->configure(new ConfigSection('', ['heartbeat' => 4, 'read_write_timeout' => 3, 'wait_time' => 2])); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('second'); + + $q->afterNextBatchMessage = function () use ($q) { + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + }; + + $batch = []; + $collect = function (array $messages) use (&$batch) { + $batch = $messages; + }; + $q->batchConsume($collect, 2); + self::assertSame([], $batch, 'The batch held a delivery from the lost connection.'); + + $q->batchConsume($collect, 2); + self::assertSame(['second'], array_values($batch), 'The lost delivery should be redelivered.'); + $q->batchAck(array_fill_keys(array_keys($batch), true)); + } + + public function testReleasedConsumerProviderIsCollected() + { + $q = $this->_getProvider('test_heartbeat_released_consumer'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('consume me'); + $q->consume( + function ($message, $deliveryTag) use ($q) { + $q->ack($deliveryTag); + } + ); + + $released = \WeakReference::create($q); + unset($q); + // The first collection runs the cycle's destructors; the second frees it. + gc_collect_cycles(); + gc_collect_cycles(); + + self::assertNull($released->get(), 'The provider is still referenced after it was released.'); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testWithoutSignalsLeavesSigalrmAlone() + { + define('AMQP_WITHOUT_SIGNALS', true); + $q = $this->_getProvider('test_heartbeat_without_signals'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open a connection'); + + self::assertSame(SIG_DFL, pcntl_signal_get_handler(SIGALRM)); + } + + /** + * Sleep with no AMQP traffic for long enough that the broker closes any connection that sent no heartbeats. + */ + private function _idlePastHeartbeatTimeout(AmqpMockProvider $q) + { + self::_sleepFor((int)$q->config()->getItem('heartbeat') * 3); + } + + /** + * Sleep for the full duration. SIGALRM from the heartbeat handler interrupts usleep(), so sleep to a deadline. + */ + private static function _sleepFor(float $seconds) + { + $deadline = microtime(true) + $seconds; + while(($left = $deadline - microtime(true)) > 0) + { + usleep((int)ceil(min($left, 1) * 1000000)); + } + } + + private function _assertConnectionOpen(AmqpMockProvider $q, string $connectionMode) + { + try + { + // Opening a channel is a round trip, so it fails if the broker has closed the connection. + $q->getOpenConnection($connectionMode)->channel()->close(); + } + catch(\Exception $e) + { + self::fail(sprintf( + 'The %s connection stopped heartbeating while idle: %s: %s', + $connectionMode, get_class($e), $e->getMessage() + )); + } + $this->addToAssertionCount(1); + } + public function testAmqp() { $q = $this->_getProvider('test', 'testexchange'); diff --git a/tests/Provider/Mock/AmqpMockProvider.php b/tests/Provider/Mock/AmqpMockProvider.php index 4259362..afc1bfa 100644 --- a/tests/Provider/Mock/AmqpMockProvider.php +++ b/tests/Provider/Mock/AmqpMockProvider.php @@ -2,6 +2,7 @@ namespace Packaged\Queue\Tests\Provider\Mock; +use Packaged\Queue\Provider\Amqp\AmqpHeartbeat; use Packaged\Queue\Provider\Amqp\AmqpQueueProvider; class AmqpMockProvider extends AmqpQueueProvider @@ -13,9 +14,9 @@ class AmqpMockProvider extends AmqpQueueProvider protected function _getConnection($connectionMode) { $conn = parent::_getConnection($connectionMode); - if($this->_unregisterHeartbeat && $this->_heartbeatSender) + if($this->_unregisterHeartbeat) { - $this->_heartbeatSender->unregister(); + AmqpHeartbeat::unregister($conn); } return $conn; } @@ -23,13 +24,42 @@ protected function _getConnection($connectionMode) public function unregisterHeartbeat() { $this->_unregisterHeartbeat = true; - if($this->_unregisterHeartbeat && $this->_heartbeatSender) + foreach($this->_connections as $conn) { - $this->_heartbeatSender->unregister(); + if($conn) + { + AmqpHeartbeat::unregister($conn); + } } return $this; } + /** + * Runs once, after the next message is added to a batch. + * + * @var callable|null + */ + public $afterNextBatchMessage; + + protected function _processBatchMessage($msg, $tag = null) + { + parent::_processBatchMessage($msg, $tag); + if($this->afterNextBatchMessage) + { + $hook = $this->afterNextBatchMessage; + $this->afterNextBatchMessage = null; + $hook(); + } + } + + /** + * The connection already open for this mode, without reconnecting. + */ + public function getOpenConnection($connectionMode) + { + return $this->_connections[$connectionMode]; + } + public function getDisconnectCount() { return $this->_disconnectCount;