Lines
85.71%
72 / 84
Methods
57.14%
8 / 14
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| startInBackground | 75.00% | 3 / 4 | 0.00% | 0 / 1 | 2.06 | ||
| publishMessage | 66.66% | 6 / 9 | 0.00% | 0 / 1 | 5.93 | ||
| subscribeFilter | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 2 | ||
| unsubscribeFilter | 0.00% | 0 / 3 | 0.00% | 0 / 1 | 6 | ||
| countQueuedMessages | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| close | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | ||
| keepConnected | 100.00% | 11 / 11 | 100.00% | 1 / 1 | 4 | ||
| attemptConnection | 100.00% | 14 / 14 | 100.00% | 1 / 1 | 5 | ||
| runSession | 94.44% | 17 / 18 | 0.00% | 0 / 1 | 3.00 | ||
| publishAtLeastOnce | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 4 | ||
| sendAtLeastOnce | 60.00% | 3 / 5 | 0.00% | 0 / 1 | 2.26 | ||
| subscribeOn | 60.00% | 3 / 5 | 0.00% | 0 / 1 | 3.58 | ||
| waitBeforeReconnecting | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | ||
| 27 | final class ReconnectingMqttLink implements MqttLink | |
| 28 | { | |
| 29 | /** @var array<string, true> */ | |
| 30 | private array $activeFilters = []; | |
| 31 | ||
| 32 | private ?MqttConnection $connection = null; | |
| 33 | ||
| 34 | private bool $started = false; | |
| 35 | ||
| 36 | private readonly DeferredCancellation $stop; | |
| 37 | ||
| 38 | public function __construct( | |
| 39 | private readonly MqttConfig $config, | |
| 40 | private readonly MqttConnector $connector, | |
| 41 | private readonly OutboundMqttQueue $outbound, | |
| 42 | private readonly Deadlines $deadlines, | |
| 43 | private readonly Clock $clock, | |
| 44 | private readonly LoggerInterface $logger, | |
| 45 | private readonly MqttLinkListener $listener, | |
| 46 | ) { | |
| 47 | $this->stop = new DeferredCancellation(); | |
| 48 | } | |
| 49 | ||
| 50 | public function startInBackground(MqttMessageRouter $router): void | |
| 51 | { | |
| 52 | if ($this->started) { | |
| 53 | return; | |
| 54 | } | |
| 55 | ||
| 56 | $this->started = true; | |
| 57 | async(fn() => $this->keepConnected($router)); | |
| 58 | } | |
| 59 | ||
| 60 | public function publishMessage(MqttMessage $message): void | |
| 61 | { | |
| 62 | if ($message->qos === MqttQos::AtLeastOnce && $this->outbound->canHoldMessages()) { | |
| 63 | $this->publishAtLeastOnce($message); | |
| 64 | ||
| 65 | return; | |
| 66 | } | |
| 67 | ||
| 68 | if ($this->connection === null) { | |
| 69 | $this->listener->messageDropped(MqttDropReason::Disconnected, $message->topic); | |
| 70 | ||
| 71 | return; | |
| 72 | } | |
| 73 | ||
| 74 | try { | |
| 75 | $this->connection->publishMessage($message)->ignore(); | |
| 76 | } catch (MqttClientException) { | |
| 77 | $this->listener->messageDropped(MqttDropReason::SendFailed, $message->topic); | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | public function subscribeFilter(string $topicFilter): void | |
| 82 | { | |
| 83 | $this->activeFilters[$topicFilter] = true; | |
| 84 | ||
| 85 | if ($this->connection !== null) { | |
| 86 | $this->subscribeOn($this->connection, $topicFilter); | |
| 87 | } | |
| 88 | } | |
| 89 | ||
| 90 | public function unsubscribeFilter(string $topicFilter): void | |
| 91 | { | |
| 92 | unset($this->activeFilters[$topicFilter]); | |
| 93 | ||
| 94 | try { | |
| 95 | $this->connection?->unsubscribeFilter($topicFilter)->ignore(); | |
| 96 | } catch (MqttClientException) { | |
| 97 | // A lost connection drops every subscription with it. | |
| 98 | } | |
| 99 | } | |
| 100 | ||
| 101 | public function countQueuedMessages(): int | |
| 102 | { | |
| 103 | return $this->outbound->countPending(); | |
| 104 | } | |
| 105 | ||
| 106 | public function close(): void | |
| 107 | { | |
| 108 | $this->stop->cancel(); | |
| 109 | $this->connection?->disconnect(); | |
| 110 | } | |
| 111 | ||
| 112 | private function keepConnected(MqttMessageRouter $router): void | |
| 113 | { | |
| 114 | $failures = 0; | |
| 115 | ||
| 116 | while (!$this->stop->getCancellation()->isRequested()) { | |
| 117 | $connection = $this->attemptConnection($router, $failures + 1); | |
| 118 | ||
| 119 | if ($connection === null) { | |
| 120 | $this->waitBeforeReconnecting(++$failures); | |
| 121 | ||
| 122 | continue; | |
| 123 | } | |
| 124 | ||
| 125 | $sessionStartedAt = $this->clock->getMonotonicTime(); | |
| 126 | $this->runSession($connection); | |
| 127 | ||
| 128 | // A server that drops every session at once, over a poison message or a duplicate client_id, still backs off. | |
| 129 | $sessionLength = $this->clock->getMonotonicTime()->elapsedSince($sessionStartedAt); | |
| 130 | $failures = $this->config->keepalive->isLongerThan($sessionLength) ? $failures + 1 : 0; | |
| 131 | $this->waitBeforeReconnecting(max($failures, 1)); | |
| 132 | } | |
| 133 | } | |
| 134 | ||
| 135 | private function attemptConnection(MqttMessageRouter $router, int $attempt): ?MqttConnection | |
| 136 | { | |
| 137 | try { | |
| 138 | $connection = $this->connector->openConnection($this->config, $router->routeMqttMessage(...), $this->stop->getCancellation()); | |
| 139 | } catch (Throwable $e) { | |
| 140 | if (!$this->stop->getCancellation()->isRequested()) { | |
| 141 | $this->logger->log($attempt === 1 ? LogLevel::ERROR : LogLevel::WARNING, 'Could not reach the MQTT server', [ | |
| 142 | 'server' => (string) $this->config->serverUrl, | |
| 143 | 'attempt' => $attempt, | |
| 144 | 'exception' => $e, | |
| 145 | ]); | |
| 146 | $this->listener->connectionLost($e->getMessage()); | |
| 147 | } | |
| 148 | ||
| 149 | return null; | |
| 150 | } | |
| 151 | ||
| 152 | if ($this->stop->getCancellation()->isRequested()) { | |
| 153 | $connection->disconnect(); | |
| 154 | ||
| 155 | return null; | |
| 156 | } | |
| 157 | ||
| 158 | return $connection; | |
| 159 | } | |
| 160 | ||
| 161 | private function runSession(MqttConnection $connection): void | |
| 162 | { | |
| 163 | $this->connection = $connection; | |
| 164 | $this->listener->connected(); | |
| 165 | $this->logger->info('Connected to the MQTT server', ['server' => (string) $this->config->serverUrl, 'filters' => \count($this->activeFilters)]); | |
| 166 | ||
| 167 | foreach (array_keys($this->activeFilters) as $topicFilter) { | |
| 168 | $this->subscribeOn($connection, (string) $topicFilter); | |
| 169 | } | |
| 170 | ||
| 171 | $this->outbound->replayPendingMessages( | |
| 172 | function (int $sequence, MqttMessage $message) use ($connection): void { | |
| 173 | $this->sendAtLeastOnce($connection, $sequence, $message); | |
| 174 | }, | |
| 175 | function (MqttMessage $message): void { | |
| 176 | $this->listener->messageDropped(MqttDropReason::GaveUp, $message->topic); | |
| 177 | }, | |
| 178 | ); | |
| 179 | ||
| 180 | $lostBecause = $connection->awaitClosed(); | |
| 181 | $this->connection = null; | |
| 182 | ||
| 183 | if (!$this->stop->getCancellation()->isRequested()) { | |
| 184 | $this->logger->warning('Lost the MQTT connection', ['server' => (string) $this->config->serverUrl, 'exception' => $lostBecause]); | |
| 185 | $this->listener->connectionLost($lostBecause?->getMessage() ?? 'the server closed the connection'); | |
| 186 | } | |
| 187 | } | |
| 188 | ||
| 189 | private function publishAtLeastOnce(MqttMessage $message): void | |
| 190 | { | |
| 191 | $evicted = $this->outbound->isFull() ? $this->outbound->findOldestMessage() : null; | |
| 192 | ||
| 193 | if ($evicted !== null) { | |
| 194 | $this->listener->messageDropped(MqttDropReason::BufferFull, $evicted->topic); | |
| 195 | } | |
| 196 | ||
| 197 | $sequence = $this->outbound->enqueueMessage($message); | |
| 198 | ||
| 199 | if ($this->connection !== null) { | |
| 200 | $this->sendAtLeastOnce($this->connection, $sequence, $message); | |
| 201 | } | |
| 202 | } | |
| 203 | ||
| 204 | private function sendAtLeastOnce(MqttConnection $connection, int $sequence, MqttMessage $message): void | |
| 205 | { | |
| 206 | try { | |
| 207 | $acknowledged = $connection->publishMessage($message); | |
| 208 | } catch (MqttClientException) { | |
| 209 | // Still buffered; the next connection sends it again. | |
| 210 | return; | |
| 211 | } | |
| 212 | ||
| 213 | $this->outbound->recordSendAttempt($sequence); | |
| 214 | $acknowledged->map(fn() => $this->outbound->acknowledgeMessage($sequence))->ignore(); | |
| 215 | } | |
| 216 | ||
| 217 | private function subscribeOn(MqttConnection $connection, string $topicFilter): void | |
| 218 | { | |
| 219 | try { | |
| 220 | $connection->subscribeFilter($topicFilter)->map(function (?MqttQos $grantedQos) use ($topicFilter): void { | |
| 221 | if ($grantedQos === null) { | |
| 222 | $this->logger->error('The MQTT server refused a subscription', ['filter' => $topicFilter]); | |
| 223 | } | |
| 224 | })->ignore(); | |
| 225 | } catch (MqttClientException) { | |
| 226 | // Resubscribed on the next connection. | |
| 227 | } | |
| 228 | } | |
| 229 | ||
| 230 | private function waitBeforeReconnecting(int $attempt): void | |
| 231 | { | |
| 232 | try { | |
| 233 | $this->deadlines->delay($this->config->reconnectBackoff->delayFor($attempt), $this->stop->getCancellation()); | |
| 234 | } catch (CancelledException) { | |
| 235 | // Closing; the loop sees the stop and ends. | |
| 236 | } | |
| 237 | } | |
| 238 | } |