• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

basis-company / nats.php / 46845869230

02 Dec 2026 08:55AM UTC coverage: 95.514%. Remained the same
46845869230

push

github

nekufa
Download composer.phar compressed

1597 of 1672 relevant lines covered (95.51%)

140.5 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.56
/src/Connection.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Basis\Nats;
6

7
use Basis\Nats\Message\Connect;
8
use Basis\Nats\Message\Factory;
9
use Basis\Nats\Message\Info;
10
use Basis\Nats\Message\Msg;
11
use Basis\Nats\Message\Ok;
12
use Basis\Nats\Message\Ping;
13
use Basis\Nats\Message\Publish;
14
use Basis\Nats\Message\Pong;
15
use Basis\Nats\Message\Prototype as Message;
16
use Basis\Nats\Message\Subscribe;
17
use LogicException;
18
use Psr\Log\LoggerInterface;
19
use Throwable;
20
use Exception;
21

22
class Connection
23
{
24
    private $socket;
25
    private $context;
26

27
    private float $activityAt = 0;
28
    private float $pingAt = 0;
29
    private float $pongAt = 0;
30
    private float $prolongateTill = 0;
31
    private int $packetSize = 1024;
32

33
    private ?Authenticator $authenticator;
34
    private Configuration $config;
35
    private Connect $connectMessage;
36
    private Info $infoMessage;
37

38
    public function __construct(
600 ✔
39
        private Client $client,
40
        public ?LoggerInterface $logger = null,
41
    ) {
42
        $this->authenticator = Authenticator::create($client->configuration);
600 ✔
43
        $this->config = $client->configuration;
600 ✔
44
    }
45

46
    public function getConnectMessage(): Connect
8 ✔
47
    {
48
        return $this->connectMessage;
8 ✔
49
    }
50

51
    public function getInfoMessage(): Info
12 ✔
52
    {
53
        return $this->infoMessage;
12 ✔
54
    }
55

56
    public function getMessage(null|int|float $timeout = 0): ?Message
592 ✔
57
    {
58
        // null means use config timeout, 0 means non-blocking check
59
        if ($timeout === null) {
592 ✔
60
            $timeout = $this->config->timeout;
×
61
        }
62

63
        $now = microtime(true);
592 ✔
64
        $max = $timeout > 0 ? $now + $timeout : PHP_FLOAT_MAX;
592 ✔
65
        $iteration = 0;
592 ✔
66

67
        while (true) {
592 ✔
68
            if (!is_resource($this->socket) || feof($this->socket)) {
592 ✔
69
                $this->processException(new LogicException('supplied resource is not a valid stream resource'));
24 ✔
70
            }
71

72
            $remainingTimeout = $max - microtime(true);
592 ✔
73
            if ($remainingTimeout <= 0) {
592 ✔
74
                break;
37 ✔
75
            }
76

77
            $read = [$this->socket];
592 ✔
78
            $write = null;
592 ✔
79
            $except = null;
592 ✔
80

81
            // Calculate timeout for stream_select
82
            if ($timeout === 0) {
592 ✔
83
                // Non-blocking check - use stream_select with 0 timeout to check if data is available
84
                $seconds = 0;
28 ✔
85
                $microseconds = 0;
28 ✔
86
            } else {
87
                $seconds = (int) floor($remainingTimeout);
592 ✔
88
                $microseconds = (int) (($remainingTimeout - $seconds) * 1_000_000);
592 ✔
89
            }
90

91
            // EINTR (сигнал посреди ожидания) — штатный исход: false ниже
92
            // ретраится; без @ PHP-warning улетает в error-handler и Sentry.
93
            $result = @stream_select($read, $write, $except, $seconds, $microseconds);
592 ✔
94

95
            if ($result === false || $result === 0) {
592 ✔
96
                // For non-blocking check (timeout=0), exit immediately
97
                if ($timeout === 0) {
63 ✔
98
                    break;
28 ✔
99
                }
100
                // For blocking calls, continue waiting
101
                continue;
35 ✔
102
            }
103

104
            $message = null;
592 ✔
105
            $line = stream_get_line($this->socket, 1024, "\r\n");
592 ✔
106
            $now = microtime(true);
592 ✔
107
            if ($line) {
592 ✔
108
                $message = Factory::create($line);
592 ✔
109
                $this->activityAt = $now;
592 ✔
110
                if ($message instanceof Msg) {
592 ✔
111
                    $payload = $this->getPayload($message->length);
592 ✔
112
                    $message->parse($payload);
592 ✔
113
                    $message->setClient($this->client);
592 ✔
114
                    $this->logger?->debug('receive ' . $line . $payload);
592 ✔
115
                    return $message;
592 ✔
116
                }
117
                $this->logger?->debug('receive ' . $line);
592 ✔
118
                if ($message instanceof Ok) {
592 ✔
119
                    continue;
592 ✔
120
                } elseif ($message instanceof Ping) {
592 ✔
121
                    $this->sendMessage(new Pong([]));
1 ✔
122
                } elseif ($message instanceof Pong) {
592 ✔
123
                    $this->pongAt = $now;
56 ✔
124
                    return $message;
56 ✔
125
                } elseif ($message instanceof Info) {
592 ✔
126
                    if (isset($message->tls_verify) && $message->tls_verify && !$this->config->tlsHandshakeFirst) {
592 ✔
127
                        $this->enableTls(true);
16 ✔
128
                    } elseif (isset($message->tls_required) && $message->tls_required && !$this->config->tlsHandshakeFirst) {
592 ✔
129
                        $this->enableTls(false);
×
130
                    }
131
                    return $message;
592 ✔
132
                }
133
            } elseif ($this->activityAt && $this->activityAt + $this->config->timeout < $now) {
160 ✔
134
                if ($this->pingAt && $this->pingAt + $this->config->pingInterval < $now) {
28 ✔
135
                    if ($this->prolongateTill && $this->prolongateTill < $now) {
×
136
                        $this->sendMessage(new Ping());
×
137
                    }
138
                }
139
            }
140
            if ($message && $now < $max) {
160 ✔
141
                $this->logger?->debug('sleep', compact('max', 'now'));
1 ✔
142
                $this->config->delay($iteration++);
1 ✔
143
            }
144
        }
145

146
        if ($this->activityAt && $this->activityAt + $this->config->timeout < $now) {
65 ✔
147
            if ($this->pongAt && $this->pongAt + $this->config->pingInterval < $now) {
4 ✔
148
                if ($this->prolongateTill && $this->prolongateTill < $now) {
×
149
                    $this->processException(new LogicException('Socket read timeout'));
×
150
                }
151
            }
152
        }
153

154
        return null;
65 ✔
155
    }
156

157
    public function ping(): bool
76 ✔
158
    {
159
        $this->sendMessage(new Ping());
76 ✔
160
        $this->getMessage($this->config->timeout);
60 ✔
161

162
        return $this->pingAt <= $this->pongAt;
56 ✔
163
    }
164

165
    public function sendMessage(Message $message): void
592 ✔
166
    {
167
        $this->init();
592 ✔
168

169
        $line = $message->render() . "\r\n";
592 ✔
170
        $length = strlen($line);
592 ✔
171
        $total = 0;
592 ✔
172

173
        $this->logger?->debug('send ' . $line);
592 ✔
174

175
        while ($total < $length) {
592 ✔
176
            try {
177
                $written = @fwrite($this->socket, substr($line, $total, $this->packetSize));
592 ✔
178
                if ($written === false) {
592 ✔
179
                    throw new LogicException('Error sending data');
×
180
                }
181
                if ($written === 0) {
592 ✔
182
                    throw new LogicException('Broken pipe or closed connection');
×
183
                }
184
                $total += $written;
592 ✔
185

186
                if ($length === $total) {
592 ✔
187
                    break;
592 ✔
188
                }
189
            } catch (Throwable $e) {
4 ✔
190
                $this->processException($e);
4 ✔
191
                $line = $message->render() . "\r\n";
4 ✔
192
                $total = 0; // reset so the full message is resent on the fresh socket
4 ✔
193
            }
194
        }
195

196
        unset($line);
592 ✔
197

198
        if ($message instanceof Publish) {
592 ✔
199
            if (strpos($message->subject, '$JS.API.CONSUMER.MSG.NEXT.') === 0) {
592 ✔
200
                $prolongate = $message->payload->expires / 1_000_000_000;
68 ✔
201
                $this->prolongateTill = microtime(true) + $prolongate;
68 ✔
202
            }
203
        }
204
        if ($message instanceof Ping) {
592 ✔
205
            $this->pingAt = microtime(true);
68 ✔
206
        }
207
    }
208

209
    public function setLogger(?LoggerInterface $logger): void
4 ✔
210
    {
211
        $this->logger = $logger;
4 ✔
212
    }
213

214
    public function setTimeout(float $value): void
592 ✔
215
    {
216
        $this->init();
592 ✔
217
        $seconds = (int) floor($value);
592 ✔
218
        $microseconds = (int) (1000000 * ($value - $seconds));
592 ✔
219

220
        stream_set_timeout($this->socket, $seconds, $microseconds);
592 ✔
221
    }
222

223
    protected function init(): void
592 ✔
224
    {
225
        if ($this->socket) {
592 ✔
226
            return;
592 ✔
227
        }
228

229
        $config = $this->config;
592 ✔
230
        $dsn = "$config->host:$config->port";
592 ✔
231
        $flags = STREAM_CLIENT_CONNECT;
592 ✔
232
        $this->context = stream_context_create();
592 ✔
233
        $this->socket = @stream_socket_client($dsn, $error, $errorMessage, $config->timeout, $flags, $this->context);
592 ✔
234

235
        if ($error || !$this->socket) {
592 ✔
236
            throw new Exception($errorMessage ?: "Connection error", $error);
4 ✔
237
        }
238

239
        $this->setTimeout($config->timeout);
592 ✔
240

241
        if ($config->tlsHandshakeFirst) {
592 ✔
242
            $this->enableTls(true);
×
243
        }
244

245
        $this->connectMessage = new Connect($config->getOptions());
592 ✔
246

247
        if ($this->client->getName()) {
592 ✔
248
            $this->connectMessage->name = $this->client->getName();
4 ✔
249
        }
250

251
        $infoMessage = $this->getMessage($config->timeout);
592 ✔
252
        if (is_null($infoMessage)) {
592 ✔
253
            throw new Exception("Timeout waiting for message from server.");
×
254
        }
255
        if (!$infoMessage instanceof Info) {
592 ✔
256
            throw new Exception("Received unexpected message type: " . $infoMessage::class);
×
257
        }
258
        $this->infoMessage = $infoMessage;
592 ✔
259

260
        if (isset($this->infoMessage->nonce) && $this->authenticator) {
592 ✔
261
            $this->connectMessage->sig = $this->authenticator->sign($this->infoMessage->nonce);
4 ✔
262
            $this->connectMessage->nkey = $this->authenticator->getPublicKey();
4 ✔
263
        }
264

265
        $this->sendMessage($this->connectMessage);
592 ✔
266
    }
267

268
    protected function enableTls(bool $requireClientCert): void
16 ✔
269
    {
270
        if ($requireClientCert) {
16 ✔
271
            if (!empty($this->config->tlsKeyFile)) {
16 ✔
272
                if (!file_exists($this->config->tlsKeyFile)) {
12 ✔
273
                    throw new Exception("tlsKeyFile file does not exist: " . $this->config->tlsKeyFile);
4 ✔
274
                }
275
                stream_context_set_option($this->context, 'ssl', 'local_pk', $this->config->tlsKeyFile);
8 ✔
276
            }
277
            if (!empty($this->config->tlsCertFile)) {
12 ✔
278
                if (!file_exists($this->config->tlsCertFile)) {
8 ✔
279
                    throw new Exception("tlsCertFile file does not exist: " . $this->config->tlsCertFile);
4 ✔
280
                }
281
                stream_context_set_option($this->context, 'ssl', 'local_cert', $this->config->tlsCertFile);
4 ✔
282
            }
283
        }
284

285
        if (!empty($this->config->tlsCaFile)) {
8 ✔
286
            if (!file_exists($this->config->tlsCaFile)) {
8 ✔
287
                throw new Exception("tlsCaFile file does not exist: " . $this->config->tlsCaFile);
4 ✔
288
            }
289
            stream_context_set_option($this->context, 'ssl', 'cafile', $this->config->tlsCaFile);
4 ✔
290
            stream_context_set_option($this->context, 'ssl', 'verify_peer', true);
4 ✔
291
            stream_context_set_option($this->context, 'ssl', 'verify_peer_name', false);
4 ✔
292
        } else {
293
            stream_context_set_option($this->context, 'ssl', 'verify_peer', false);
×
294
        }
295

296
        if (!stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)) {
4 ✔
297
            throw new Exception('Failed to connect: Error enabling TLS');
×
298
        }
299
    }
300

301
    protected function getPayload(int $length): string
592 ✔
302
    {
303
        $payload = '';
592 ✔
304
        $iteration = 0;
592 ✔
305
        while (strlen($payload) < $length) {
592 ✔
306
            $payloadLine = stream_get_line($this->socket, $length, '');
592 ✔
307
            if (!$payloadLine) {
592 ✔
308
                if ($iteration > 16) {
×
309
                    break;
×
310
                }
311
                $this->config->delay($iteration++);
×
312
                continue;
×
313
            }
314
            if (strlen($payloadLine) !== $length) {
592 ✔
315
                $this->logger?->debug(
×
316
                    'got ' . strlen($payloadLine) . '/' . $length . ': ' . $payloadLine
×
317
                );
×
318
            }
319
            $payload .= $payloadLine;
592 ✔
320
        }
321
        return $payload;
592 ✔
322
    }
323

324
    private function processException(Throwable $e): void
36 ✔
325
    {
326
        $this->logger?->error($e->getMessage(), ['exception' => $e]);
36 ✔
327

328
        if (!$this->config->reconnect) {
36 ✔
329
            throw $e;
8 ✔
330
        }
331

332
        $maxAttempts = $this->config->maxReconnectAttempts;
28 ✔
333
        $iteration = 0;
28 ✔
334

335
        while (true) {
28 ✔
336
            if ($maxAttempts >= 0 && $iteration >= $maxAttempts) {
28 ✔
337
                // reconnect attempts exhausted: rethrow the last connection error
338
                throw $e;
×
339
            }
340
            if ($iteration > 0) {
28 ✔
341
                $this->config->delay($iteration - 1);
×
342
            }
343
            try {
344
                // Explicitly close the old socket, otherwise every reconnection
345
                // leaks its file descriptor and the process eventually
346
                // crosses PHP's FD_SETSIZE limit (1024) see #139
347
                if (is_resource($this->socket)) {
28 ✔
348
                    fclose($this->socket);
4 ✔
349
                }
350
                $this->socket = null;
28 ✔
351
                $this->init();
28 ✔
352
            } catch (Throwable $e) {
×
353
                $iteration++;
×
354
                continue;
×
355
            }
356
            break;
28 ✔
357
        }
358

359
        foreach ($this->client->getSubscriptions() as $subscription) {
28 ✔
360
            $this->sendMessage(new Subscribe([
8 ✔
361
                'sid' => $subscription['sid'],
8 ✔
362
                'subject' => $subscription['name'],
8 ✔
363
                'group' => $subscription['group'] ?? null,
8 ✔
364
            ]));
8 ✔
365
        }
366

367
        if ($this->client->requestsSubscribed()) {
28 ✔
368
            $this->client->subscribeRequests(true);
4 ✔
369
        }
370
    }
371

372
    public function setPacketSize(int $size): void
8 ✔
373
    {
374
        $this->packetSize = $size;
8 ✔
375
    }
376

377
    public function close(): void
592 ✔
378
    {
379
        if ($this->socket) {
592 ✔
380
            fclose($this->socket);
592 ✔
381
            $this->socket = null;
592 ✔
382
        }
383
    }
384
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc