Lines 74.07% 60 / 81
Functions and Methods 50.00% 8 / 16
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
MqttConnection 74.07% 60 / 81 50.00% 8 / 16 63.16 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 startReading 100.00% 2 / 2 100.00% 1 / 1 1
 publishMessage 75.00% 6 / 8 0.00% 0 / 1 2.06
 subscribeFilter 100.00% 5 / 5 100.00% 1 / 1 1
 unsubscribeFilter 0.00% 0 / 5 0.00% 0 / 1 2
 disconnect 60.00% 3 / 5 0.00% 0 / 1 3.58
 awaitClosed 100.00% 1 / 1 100.00% 1 / 1 1
 readUntilClosed 100.00% 4 / 4 100.00% 1 / 1 4
 handlePacket 60.00% 3 / 5 0.00% 0 / 1 8.30
 deliverPublish 100.00% 3 / 3 100.00% 1 / 1 2
 settleSubscription 100.00% 3 / 3 100.00% 1 / 1 1
 scheduleKeepalive 84.61% 11 / 13 0.00% 0 / 1 4.06
 writePacket 28.57% 2 / 7 0.00% 0 / 1 6.28
 settleAck 33.33% 1 / 3 0.00% 0 / 1 1.30
 allocatePacketId 80.00% 4 / 5 0.00% 0 / 1 4.13
 finishClosing 100.00% 11 / 11 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Mqtt\Connection;
6
7use Amp\ByteStream\BufferedReader;
8use Amp\DeferredFuture;
9use Amp\Future;
10use Amp\Socket\Socket;
11use Closure;
12use Stewart\Contracts\Mqtt\MqttMessage;
13use Stewart\Contracts\Mqtt\MqttQos;
14use Stewart\Contracts\Time\Duration;
15use Stewart\Mqtt\Exception\MqttClientError;
16use Stewart\Mqtt\Exception\MqttClientException;
17use Stewart\Mqtt\Packet\InboundPacket;
18use Stewart\Mqtt\Packet\PacketEncoder;
19use Stewart\Mqtt\Packet\PacketReader;
20use Stewart\Mqtt\Packet\PingRespPacket;
21use Stewart\Mqtt\Packet\PubAckPacket;
22use Stewart\Mqtt\Packet\PublishPacket;
23use Stewart\Mqtt\Packet\SubAckPacket;
24use Stewart\Mqtt\Packet\UnsubAckPacket;
25use Stewart\Support\Time\TimerHandle;
26use Stewart\Support\Time\Timers;
27use Throwable;
28
29use function Amp\async;
30
31final class MqttConnection
32{
33    private const int HIGHEST_PACKET_ID = 65535;
34
35    private const MqttQos SUBSCRIPTION_QOS = MqttQos::AtLeastOnce;
36
37    /** @var array<int, DeferredFuture<null>> */
38    private array $pendingAcks = [];
39
40    /** @var array<int, DeferredFuture<MqttQos|null>> */
41    private array $pendingSubAcks = [];
42
43    private int $lastPacketId = 0;
44
45    private bool $awaitingPingResponse = false;
46
47    private ?TimerHandle $keepaliveTimer = null;
48
49    /** @var DeferredFuture<MqttClientException|null> */
50    private readonly DeferredFuture $closed;
51
52    /** @param Closure(MqttMessage): void $onMessage */
53    public function __construct(
54        private readonly Socket $socket,
55        private readonly BufferedReader $bufferedReader,
56        private readonly PacketReader $packetReader,
57        private readonly PacketEncoder $encoder,
58        private readonly Timers $timers,
59        private readonly Duration $keepalive,
60        private readonly Closure $onMessage,
61    ) {
62        $this->closed = new DeferredFuture();
63    }
64
65    public function startReading(): void
66    {
67        async($this->readUntilClosed(...));
68        $this->scheduleKeepalive();
69    }
70
71    /**
72     * @return Future<null>
73     * @throws MqttClientException
74     */
75    public function publishMessage(MqttMessage $message): Future
76    {
77        if ($message->qos === MqttQos::AtMostOnce) {
78            $this->writePacket($this->encoder->encodePublish($message));
79
80            return Future::complete();
81        }
82
83        $packetId = $this->allocatePacketId();
84        /** @var DeferredFuture<null> $pending */
85        $pending = new DeferredFuture();
86        $this->pendingAcks[$packetId] = $pending;
87        $this->writePacket($this->encoder->encodePublish($message, $packetId));
88
89        return $pending->getFuture();
90    }
91
92    /**
93     * @return Future<MqttQos|null>
94     * @throws MqttClientException
95     */
96    public function subscribeFilter(string $topicFilter): Future
97    {
98        $packetId = $this->allocatePacketId();
99        /** @var DeferredFuture<MqttQos|null> $pending */
100        $pending = new DeferredFuture();
101        $this->pendingSubAcks[$packetId] = $pending;
102        $this->writePacket($this->encoder->encodeSubscribe($packetId, $topicFilter, self::SUBSCRIPTION_QOS));
103
104        return $pending->getFuture();
105    }
106
107    /**
108     * @return Future<null>
109     * @throws MqttClientException
110     */
111    public function unsubscribeFilter(string $topicFilter): Future
112    {
113        $packetId = $this->allocatePacketId();
114        /** @var DeferredFuture<null> $pending */
115        $pending = new DeferredFuture();
116        $this->pendingAcks[$packetId] = $pending;
117        $this->writePacket($this->encoder->encodeUnsubscribe($packetId, $topicFilter));
118
119        return $pending->getFuture();
120    }
121
122    public function disconnect(): void
123    {
124        if ($this->closed->isComplete()) {
125            return;
126        }
127
128        try {
129            $this->socket->write($this->encoder->encodeDisconnect());
130        } catch (Throwable) {
131            // The socket is closing either way; the server then treats the client as gone.
132        }
133
134        $this->finishClosing(null);
135    }
136
137    public function awaitClosed(): ?MqttClientException
138    {
139        return $this->closed->getFuture()->await();
140    }
141
142    private function readUntilClosed(): void
143    {
144        try {
145            while (!$this->closed->isComplete()) {
146                $this->handlePacket($this->packetReader->readPacket($this->bufferedReader));
147            }
148        } catch (Throwable $e) {
149            $this->finishClosing($e instanceof MqttClientException ? $e : MqttClientException::createForReason(MqttClientError::ConnectionLost, $e));
150        }
151    }
152
153    /** @throws MqttClientException */
154    private function handlePacket(InboundPacket $packet): void
155    {
156        match (true) {
157            $packet instanceof PublishPacket => $this->deliverPublish($packet),
158            $packet instanceof PubAckPacket, $packet instanceof UnsubAckPacket => $this->settleAck($packet),
159            $packet instanceof SubAckPacket => $this->settleSubscription($packet),
160            $packet instanceof PingRespPacket => $this->awaitingPingResponse = false,
161            default => throw MqttClientException::packetUnexpected($packet->getPacketType()->name),
162        };
163    }
164
165    /** @throws MqttClientException */
166    private function deliverPublish(PublishPacket $packet): void
167    {
168        if ($packet->packetId !== null) {
169            $this->writePacket($this->encoder->encodePubAck($packet->packetId));
170        }
171
172        ($this->onMessage)($packet->message);
173    }
174
175    /** @throws MqttClientException */
176    private function settleSubscription(SubAckPacket $packet): void
177    {
178        $pending = $this->pendingSubAcks[$packet->packetId] ?? throw MqttClientException::packetUnexpected($packet->getPacketType()->name);
179        unset($this->pendingSubAcks[$packet->packetId]);
180        $pending->complete($packet->grantedQos);
181    }
182
183    private function scheduleKeepalive(): void
184    {
185        $this->keepaliveTimer = $this->timers->startTimer($this->keepalive, function (): void {
186            if ($this->closed->isComplete()) {
187                return;
188            }
189
190            if ($this->awaitingPingResponse) {
191                $this->finishClosing(MqttClientException::createForReason(MqttClientError::KeepaliveTimedOut, keepalive: (string) $this->keepalive));
192
193                return;
194            }
195
196            $this->awaitingPingResponse = true;
197            async(function (): void {
198                try {
199                    $this->writePacket($this->encoder->encodePingRequest());
200                } catch (MqttClientException) {
201                }
202            });
203            $this->scheduleKeepalive();
204        });
205    }
206
207    /** @throws MqttClientException */
208    private function writePacket(string $bytes): void
209    {
210        if ($this->closed->isComplete()) {
211            throw MqttClientException::createForReason(MqttClientError::ConnectionClosed);
212        }
213
214        try {
215            $this->socket->write($bytes);
216        } catch (Throwable $e) {
217            $lost = MqttClientException::createForReason(MqttClientError::ConnectionLost, $e);
218            $this->finishClosing($lost);
219
220            throw $lost;
221        }
222    }
223
224    /** @throws MqttClientException */
225    private function settleAck(PubAckPacket|UnsubAckPacket $ack): void
226    {
227        $pending = $this->pendingAcks[$ack->packetId] ?? throw MqttClientException::packetUnexpected($ack->getPacketType()->name);
228        unset($this->pendingAcks[$ack->packetId]);
229        $pending->complete();
230    }
231
232    /** @throws MqttClientException */
233    private function allocatePacketId(): int
234    {
235        for ($attempt = 0; $attempt < self::HIGHEST_PACKET_ID; ++$attempt) {
236            $this->lastPacketId = $this->lastPacketId % self::HIGHEST_PACKET_ID + 1;
237
238            if (!isset($this->pendingAcks[$this->lastPacketId]) && !isset($this->pendingSubAcks[$this->lastPacketId])) {
239                return $this->lastPacketId;
240            }
241        }
242
243        throw MqttClientException::createForReason(MqttClientError::PacketIdsExhausted);
244    }
245
246    private function finishClosing(?MqttClientException $reason): void
247    {
248        if ($this->closed->isComplete()) {
249            return;
250        }
251
252        $this->keepaliveTimer?->cancel();
253        $this->socket->close();
254        $failure = $reason ?? MqttClientException::createForReason(MqttClientError::ConnectionClosed);
255
256        foreach ([...$this->pendingAcks, ...$this->pendingSubAcks] as $pending) {
257            $pending->error($failure);
258            $pending->getFuture()->ignore();
259        }
260
261        $this->pendingAcks = [];
262        $this->pendingSubAcks = [];
263        $this->closed->complete($reason);
264    }
265}