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

nats-io / nats.java / #1997

20 Jun 2025 12:27PM UTC coverage: 95.66% (-0.03%) from 95.69%
#1997

push

github

web-flow
Merge pull request #1334 from nats-io/timers-move-to-nano

Nano time for elapsed timings and Nats System Clock

78 of 84 new or added lines in 14 files covered. (92.86%)

1 existing line in 1 file now uncovered.

11748 of 12281 relevant lines covered (95.66%)

0.96 hits per line

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

93.88
/src/main/java/io/nats/client/impl/NatsConnection.java
1
// Copyright 2015-2018 The NATS Authors
2
// Licensed under the Apache License, Version 2.0 (the "License");
3
// you may not use this file except in compliance with the License.
4
// You may obtain a copy of the License at:
5
//
6
// http://www.apache.org/licenses/LICENSE-2.0
7
//
8
// Unless required by applicable law or agreed to in writing, software
9
// distributed under the License is distributed on an "AS IS" BASIS,
10
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
// See the License for the specific language governing permissions and
12
// limitations under the License.
13

14
package io.nats.client.impl;
15

16
import io.nats.client.*;
17
import io.nats.client.ConnectionListener.Events;
18
import io.nats.client.api.ServerInfo;
19
import io.nats.client.support.ByteArrayBuilder;
20
import io.nats.client.support.NatsRequestCompletableFuture;
21
import io.nats.client.support.NatsUri;
22
import io.nats.client.support.Validator;
23

24
import java.io.IOException;
25
import java.net.InetAddress;
26
import java.net.URISyntaxException;
27
import java.nio.ByteBuffer;
28
import java.nio.CharBuffer;
29
import java.time.Duration;
30
import java.time.Instant;
31
import java.util.*;
32
import java.util.concurrent.*;
33
import java.util.concurrent.atomic.AtomicBoolean;
34
import java.util.concurrent.atomic.AtomicLong;
35
import java.util.concurrent.atomic.AtomicReference;
36
import java.util.concurrent.locks.Condition;
37
import java.util.concurrent.locks.ReentrantLock;
38
import java.util.function.Predicate;
39

40
import static io.nats.client.support.NatsConstants.*;
41
import static io.nats.client.support.NatsRequestCompletableFuture.CancelAction;
42
import static io.nats.client.support.Validator.*;
43
import static java.nio.charset.StandardCharsets.UTF_8;
44

45
class NatsConnection implements Connection {
46

47
    public static final double NANOS_PER_SECOND = 1_000_000_000.0;
48

49
    private final Options options;
50
    final boolean forceFlushOnRequest;
51

52
    private final StatisticsCollector statistics;
53

54
    private boolean connecting; // you can only connect in one thread
55
    private boolean disconnecting; // you can only disconnect in one thread
56
    private boolean closing; // respect a close call regardless
57
    private Exception exceptionDuringConnectChange; // exception occurred in another thread while dis/connecting
58
    private final ReentrantLock closeSocketLock;
59

60
    private Status status;
61
    private final ReentrantLock statusLock;
62
    private final Condition statusChanged;
63

64
    private CompletableFuture<DataPort> dataPortFuture;
65
    private DataPort dataPort;
66
    private NatsUri currentServer;
67
    private CompletableFuture<Boolean> reconnectWaiter;
68
    private final HashMap<NatsUri, String> serverAuthErrors;
69

70
    private NatsConnectionReader reader;
71
    private NatsConnectionWriter writer;
72

73
    private final AtomicReference<ServerInfo> serverInfo;
74

75
    private final Map<String, NatsSubscription> subscribers;
76
    private final Map<String, NatsDispatcher> dispatchers; // use a concurrent map so we get more consistent iteration behavior
77
    private final Collection<ConnectionListener> connectionListeners;
78
    private final Map<String, NatsRequestCompletableFuture> responsesAwaiting;
79
    private final Map<String, NatsRequestCompletableFuture> responsesRespondedTo;
80
    private final ConcurrentLinkedDeque<CompletableFuture<Boolean>> pongQueue;
81

82
    private final String mainInbox;
83
    private final AtomicReference<NatsDispatcher> inboxDispatcher;
84
    private final ReentrantLock inboxDispatcherLock;
85
    private Timer timer;
86

87
    private final AtomicBoolean needPing;
88

89
    private final AtomicLong nextSid;
90
    private final NUID nuid;
91

92
    private final AtomicReference<String> connectError;
93
    private final AtomicReference<String> lastError;
94
    private final AtomicReference<CompletableFuture<Boolean>> draining;
95
    private final AtomicBoolean blockPublishForDrain;
96
    private final AtomicBoolean tryingToConnect;
97

98
    private final ExecutorService callbackRunner;
99
    private final ExecutorService executor;
100
    private final ExecutorService connectExecutor;
101
    private final boolean advancedTracking;
102

103
    private final ServerPool serverPool;
104
    private final DispatcherFactory dispatcherFactory;
105
    final CancelAction cancelAction;
106

107
    private final boolean trace;
108
    private final TimeTraceLogger timeTraceLogger;
109

110
    NatsConnection(Options options) {
1✔
111
        trace = options.isTraceConnection();
1✔
112
        timeTraceLogger = options.getTimeTraceLogger();
1✔
113
        timeTraceLogger.trace("creating connection object");
1✔
114

115
        this.options = options;
1✔
116
        forceFlushOnRequest = options.forceFlushOnRequest();
1✔
117

118
        advancedTracking = options.isTrackAdvancedStats();
1✔
119
        this.statistics = options.getStatisticsCollector() == null ? new NatsStatistics() : options.getStatisticsCollector();
1✔
120
        this.statistics.setAdvancedTracking(advancedTracking);
1✔
121

122
        this.closeSocketLock = new ReentrantLock();
1✔
123

124
        this.statusLock = new ReentrantLock();
1✔
125
        this.statusChanged = this.statusLock.newCondition();
1✔
126
        this.status = Status.DISCONNECTED;
1✔
127
        this.reconnectWaiter = new CompletableFuture<>();
1✔
128
        this.reconnectWaiter.complete(Boolean.TRUE);
1✔
129

130
        this.connectionListeners = ConcurrentHashMap.newKeySet();
1✔
131
        if (options.getConnectionListener() != null) {
1✔
132
            addConnectionListener(options.getConnectionListener());
1✔
133
        }
134

135
        this.dispatchers = new ConcurrentHashMap<>();
1✔
136
        this.subscribers = new ConcurrentHashMap<>();
1✔
137
        this.responsesAwaiting = new ConcurrentHashMap<>();
1✔
138
        this.responsesRespondedTo = new ConcurrentHashMap<>();
1✔
139

140
        this.serverAuthErrors = new HashMap<>();
1✔
141

142
        this.nextSid = new AtomicLong(1);
1✔
143
        timeTraceLogger.trace("creating NUID");
1✔
144
        this.nuid = new NUID();
1✔
145
        this.mainInbox = createInbox() + ".*";
1✔
146

147
        this.lastError = new AtomicReference<>();
1✔
148
        this.connectError = new AtomicReference<>();
1✔
149

150
        this.serverInfo = new AtomicReference<>();
1✔
151
        this.inboxDispatcher = new AtomicReference<>();
1✔
152
        this.inboxDispatcherLock = new ReentrantLock();
1✔
153
        this.pongQueue = new ConcurrentLinkedDeque<>();
1✔
154
        this.draining = new AtomicReference<>();
1✔
155
        this.blockPublishForDrain = new AtomicBoolean();
1✔
156
        this.tryingToConnect = new AtomicBoolean();
1✔
157

158
        timeTraceLogger.trace("creating executors");
1✔
159
        this.executor = options.getExecutor();
1✔
160
        this.callbackRunner = options.getCallbackExecutor();
1✔
161
        this.connectExecutor = options.getConnectExecutor();
1✔
162

163
        timeTraceLogger.trace("creating reader and writer");
1✔
164
        this.reader = new NatsConnectionReader(this);
1✔
165
        this.writer = new NatsConnectionWriter(this, null);
1✔
166

167
        this.needPing = new AtomicBoolean(true);
1✔
168

169
        serverPool = options.getServerPool() == null ? new NatsServerPool() : options.getServerPool();
1✔
170
        serverPool.initialize(options);
1✔
171
        dispatcherFactory = options.getDispatcherFactory() == null ? new DispatcherFactory() : options.getDispatcherFactory();
1✔
172

173
        cancelAction = options.isReportNoResponders() ? CancelAction.REPORT : CancelAction.CANCEL;
1✔
174

175
        timeTraceLogger.trace("connection object created");
1✔
176
    }
1✔
177

178
    // Connect is only called after creation
179
    void connect(boolean reconnectOnConnect) throws InterruptedException, IOException {
180
        if (!tryingToConnect.get()) {
1✔
181
            try {
182
                tryingToConnect.set(true);
1✔
183
                connectImpl(reconnectOnConnect);
1✔
184
            }
185
            finally {
186
                tryingToConnect.set(false);
1✔
187
            }
188
        }
189
    }
1✔
190

191
    void connectImpl(boolean reconnectOnConnect) throws InterruptedException, IOException {
192
        if (options.getServers().isEmpty()) {
1✔
193
            throw new IllegalArgumentException("No servers provided in options");
×
194
        }
195

196
        boolean trace = options.isTraceConnection();
1✔
197
        long start = NatsSystemClock.nanoTime();
1✔
198

199
        this.lastError.set("");
1✔
200

201
        timeTraceLogger.trace("starting connect loop");
1✔
202

203
        Set<NatsUri> failList = new HashSet<>();
1✔
204
        boolean keepGoing = true;
1✔
205
        NatsUri first = null;
1✔
206
        NatsUri cur;
207
        while (keepGoing && (cur = serverPool.peekNextServer()) != null) {
1✔
208
            if (first == null) {
1✔
209
                first = cur;
1✔
210
            }
211
            else if (cur.equals(first)) {
1✔
212
                break;  // connect only goes through loop once
1✔
213
            }
214
            serverPool.nextServer(); // b/c we only peeked.
1✔
215

216
            // let server pool resolve hostnames, then loop through resolved
217
            List<NatsUri> resolvedList = resolveHost(cur);
1✔
218
            for (NatsUri resolved : resolvedList) {
1✔
219
                if (isClosed()) {
1✔
220
                    keepGoing = false;
1✔
221
                    break;
1✔
222
                }
223
                connectError.set(""); // new on each attempt
1✔
224

225
                timeTraceLogger.trace("setting status to connecting");
1✔
226
                updateStatus(Status.CONNECTING);
1✔
227

228
                timeTraceLogger.trace("trying to connect to %s", cur);
1✔
229
                tryToConnect(cur, resolved, NatsSystemClock.nanoTime());
1✔
230

231
                if (isConnected()) {
1✔
232
                    serverPool.connectSucceeded(cur);
1✔
233
                    keepGoing = false;
1✔
234
                    break;
1✔
235
                }
236

237
                timeTraceLogger.trace("setting status to disconnected");
1✔
238
                updateStatus(Status.DISCONNECTED);
1✔
239

240
                failList.add(cur);
1✔
241
                serverPool.connectFailed(cur);
1✔
242

243
                String err = connectError.get();
1✔
244

245
                if (this.isAuthenticationError(err)) {
1✔
246
                    this.serverAuthErrors.put(resolved, err);
1✔
247
                }
248
            }
1✔
249
        }
1✔
250

251
        if (!isConnected() && !isClosed()) {
1✔
252
            if (reconnectOnConnect) {
1✔
253
                timeTraceLogger.trace("trying to reconnect on connect");
1✔
254
                reconnectImpl(); // call the impl here otherwise the tryingToConnect guard will block the behavior
1✔
255
            }
256
            else {
257
                timeTraceLogger.trace("connection failed, closing to cleanup");
1✔
258
                close();
1✔
259

260
                String err = connectError.get();
1✔
261
                if (this.isAuthenticationError(err)) {
1✔
262
                    throw new AuthenticationException("Authentication error connecting to NATS server: " + err);
1✔
263
                }
264
                throw new IOException("Unable to connect to NATS servers: " + failList);
1✔
265
            }
266
        }
267
        else if (trace) {
1✔
268
            long end = NatsSystemClock.nanoTime();
1✔
269
            double seconds = ((double) (end - start)) / NANOS_PER_SECOND;
1✔
270
            timeTraceLogger.trace("connect complete in %.3f seconds", seconds);
1✔
271
        }
272
    }
1✔
273

274
    @Override
275
    public void forceReconnect() throws IOException, InterruptedException {
276
        forceReconnect(null);
1✔
277
    }
1✔
278

279
    @Override
280
    public void forceReconnect(ForceReconnectOptions options) throws IOException, InterruptedException {
281
        if (!tryingToConnect.get()) {
1✔
282
            try {
283
                tryingToConnect.set(true);
1✔
284
                forceReconnectImpl(options);
1✔
285
            }
286
            finally {
287
                tryingToConnect.set(false);
1✔
288
            }
289
        }
290
    }
1✔
291

292
    void forceReconnectImpl(ForceReconnectOptions options) throws InterruptedException {
293
        if (options != null && options.getFlushWait() != null) {
1✔
294
            try {
295
                flush(options.getFlushWait());
×
296
            }
297
            catch (TimeoutException e) {
×
298
                // ignore, don't care, too bad;
299
            }
×
300
        }
301

302
        closeSocketLock.lock();
1✔
303
        try {
304
            updateStatus(Status.DISCONNECTED);
1✔
305

306
            // Close and reset the current data port and future
307
            if (dataPortFuture != null) {
1✔
308
                dataPortFuture.cancel(true);
1✔
309
                dataPortFuture = null;
1✔
310
            }
311

312
            // close the data port as a task so as not to block reconnect
313
            if (dataPort != null) {
1✔
314
                final DataPort closeMe = dataPort;
1✔
315
                dataPort = null;
1✔
316
                executor.submit(() -> {
1✔
317
                    try {
318
                        if (options != null && options.isForceClose()) {
1✔
319
                            closeMe.forceClose();
×
320
                        }
321
                        else {
322
                            closeMe.close();
1✔
323
                        }
324
                    }
325
                    catch (IOException ignore) {
×
326
                    }
1✔
327
                });
1✔
328
            }
329

330
            // stop i/o
331
            try {
332
                this.reader.stop(false).get(100, TimeUnit.MILLISECONDS);
1✔
333
            }
334
            catch (Exception ex) {
×
335
                processException(ex);
×
336
            }
1✔
337
            try {
338
                this.writer.stop().get(100, TimeUnit.MILLISECONDS);
1✔
339
            }
340
            catch (Exception ex) {
×
341
                processException(ex);
×
342
            }
1✔
343

344
            // new reader/writer
345
            reader = new NatsConnectionReader(this);
1✔
346
            writer = new NatsConnectionWriter(this, writer);
1✔
347
        }
348
        finally {
349
            closeSocketLock.unlock();
1✔
350
        }
351

352
        // calling connect just starts like a new connection versus reconnect
353
        // but we have to manually resubscribe like reconnect once it is connected
354
        reconnectImpl();
1✔
355
        writer.setReconnectMode(false);
1✔
356
    }
1✔
357

358
    void reconnect() throws InterruptedException {
359
        if (!tryingToConnect.get()) {
1✔
360
            try {
361
                tryingToConnect.set(true);
1✔
362
                reconnectImpl();
1✔
363
            }
364
            finally {
365
                tryingToConnect.set(false);
1✔
366
            }
367
        }
368
    }
1✔
369

370
    // Reconnect can only be called when the connection is disconnected
371
    void reconnectImpl() throws InterruptedException {
372
        if (isClosed()) {
1✔
373
            return;
1✔
374
        }
375

376
        if (options.getMaxReconnect() == 0) {
1✔
377
            this.close();
1✔
378
            return;
1✔
379
        }
380

381
        writer.setReconnectMode(true);
1✔
382

383
        if (!isConnected() && !isClosed() && !this.isClosing()) {
1✔
384
            boolean keepGoing = true;
1✔
385
            int totalRounds = 0;
1✔
386
            NatsUri first = null;
1✔
387
            NatsUri cur;
388
            while (keepGoing && (cur = serverPool.nextServer()) != null) {
1✔
389
                if (first == null) {
1✔
390
                    first = cur;
1✔
391
                }
392
                else if (first.equals(cur)) {
1✔
393
                    // went around the pool an entire time
394
                    invokeReconnectDelayHandler(++totalRounds);
1✔
395
                }
396

397
                // let server list provider resolve hostnames
398
                // then loop through resolved
399
                List<NatsUri> resolvedList = resolveHost(cur);
1✔
400
                for (NatsUri resolved : resolvedList) {
1✔
401
                    if (isClosed()) {
1✔
402
                        keepGoing = false;
1✔
403
                        break;
1✔
404
                    }
405
                    connectError.set(""); // reset on each loop
1✔
406
                    if (isDisconnectingOrClosed() || this.isClosing()) {
1✔
407
                        keepGoing = false;
1✔
408
                        break;
1✔
409
                    }
410
                    updateStatus(Status.RECONNECTING);
1✔
411

412
                    timeTraceLogger.trace("reconnecting to server %s", cur);
1✔
413
                    tryToConnect(cur, resolved, NatsSystemClock.nanoTime());
1✔
414

415
                    if (isConnected()) {
1✔
416
                        serverPool.connectSucceeded(cur);
1✔
417
                        statistics.incrementReconnects();
1✔
418
                        keepGoing = false;
1✔
419
                        break;
1✔
420
                    }
421

422
                    serverPool.connectFailed(cur);
1✔
423
                    String err = connectError.get();
1✔
424
                    if (this.isAuthenticationError(err)) {
1✔
425
                        if (err.equals(this.serverAuthErrors.get(resolved))) {
1✔
426
                            keepGoing = false; // double auth error
1✔
427
                            break;
1✔
428
                        }
429
                        serverAuthErrors.put(resolved, err);
1✔
430
                    }
431
                }
1✔
432
            }
1✔
433
        } // end-main-loop
434

435
        if (!isConnected()) {
1✔
436
            this.close();
1✔
437
            return;
1✔
438
        }
439

440
        this.subscribers.forEach((sid, sub) -> {
1✔
441
            if (sub.getDispatcher() == null && !sub.isDraining()) {
1✔
442
                sendSubscriptionMessage(sub.getSID(), sub.getSubject(), sub.getQueueName(), true);
1✔
443
            }
444
        });
1✔
445

446
        this.dispatchers.forEach((nuid, d) -> {
1✔
447
            if (!d.isDraining()) {
1✔
448
                d.resendSubscriptions();
1✔
449
            }
450
        });
1✔
451

452
        try {
453
            this.flush(this.options.getConnectionTimeout());
1✔
454
        } catch (Exception exp) {
1✔
455
            this.processException(exp);
1✔
456
        }
1✔
457

458
        processConnectionEvent(Events.RESUBSCRIBED);
1✔
459

460
        // When the flush returns we are done sending internal messages,
461
        // so we can switch to the non-reconnect queue
462
        this.writer.setReconnectMode(false);
1✔
463
    }
1✔
464

465
    long timeCheck(long endNanos, String message) throws TimeoutException {
466
        long remaining = endNanos - NatsSystemClock.nanoTime();
1✔
467
        if (trace) {
1✔
468
            traceTimeCheck(message, remaining);
1✔
469
        }
470
        if (remaining < 0) {
1✔
471
            throw new TimeoutException("connection timed out");
1✔
472
        }
473
        return remaining;
1✔
474
    }
475

476
    void traceTimeCheck(String message, long remaining) {
477
        if (remaining < 0) {
1✔
478
            if (remaining > -1_000_000) { // less than -1 ms
1✔
479
                timeTraceLogger.trace(message + String.format(", %d (ns) beyond timeout", -remaining));
1✔
480
            }
481
            else if (remaining > -1_000_000_000) { // less than -1 second
1✔
482
                long ms = -remaining / 1_000_000;
1✔
483
                timeTraceLogger.trace(message + String.format(", %d (ms) beyond timeout", ms));
1✔
484
            }
1✔
485
            else {
486
                double seconds = ((double)-remaining) / 1_000_000_000.0;
1✔
487
                timeTraceLogger.trace(message + String.format(", %.3f (s) beyond timeout", seconds));
1✔
488
            }
1✔
489
        }
490
        else if (remaining < 1_000_000) {
1✔
491
            timeTraceLogger.trace(message + String.format(", %d (ns) remaining", remaining));
1✔
492
        }
493
        else if (remaining < 1_000_000_000) {
1✔
494
            long ms = remaining / 1_000_000;
1✔
495
            timeTraceLogger.trace(message + String.format(", %d (ms) remaining", ms));
1✔
496
        }
1✔
497
        else {
498
            double seconds = ((double) remaining) / 1_000_000_000.0;
1✔
499
            timeTraceLogger.trace(message + String.format(", %.3f (s) remaining", seconds));
1✔
500
        }
501
    }
1✔
502

503
    // is called from reconnect and connect
504
    // will wait for any previous attempt to complete, using the reader.stop and
505
    // writer.stop
506
    void tryToConnect(NatsUri cur, NatsUri resolved, long now) {
507
        currentServer = null;
1✔
508

509
        try {
510
            Duration connectTimeout = options.getConnectionTimeout();
1✔
511
            boolean trace = options.isTraceConnection();
1✔
512
            long end = now + connectTimeout.toNanos();
1✔
513
            timeCheck(end, "starting connection attempt");
1✔
514

515
            statusLock.lock();
1✔
516
            try {
517
                if (this.connecting) {
1✔
518
                    return;
×
519
                }
520
                this.connecting = true;
1✔
521
                statusChanged.signalAll();
1✔
522
            } finally {
523
                statusLock.unlock();
1✔
524
            }
525

526
            // Create a new future for the dataport, the reader/writer will use this
527
            // to wait for the connect/failure.
528
            this.dataPortFuture = new CompletableFuture<>();
1✔
529

530
            // Make sure the reader and writer are stopped
531
            long timeoutNanos = timeCheck(end, "waiting for reader");
1✔
532
            if (reader.isRunning()) {
1✔
533
                this.reader.stop().get(timeoutNanos, TimeUnit.NANOSECONDS);
×
534
            }
535
            timeoutNanos = timeCheck(end, "waiting for writer");
1✔
536
            if (writer.isRunning()) {
1✔
537
                this.writer.stop().get(timeoutNanos, TimeUnit.NANOSECONDS);
×
538
            }
539

540
            timeCheck(end, "cleaning pong queue");
1✔
541
            cleanUpPongQueue();
1✔
542

543
            timeoutNanos = timeCheck(end, "connecting data port");
1✔
544
            DataPort newDataPort = this.options.buildDataPort();
1✔
545
            newDataPort.connect(resolved.toString(), this, timeoutNanos);
1✔
546

547
            // Notify any threads waiting on the sockets
548
            this.dataPort = newDataPort;
1✔
549
            this.dataPortFuture.complete(this.dataPort);
1✔
550

551
            // Wait for the INFO message manually
552
            // all other traffic will use the reader and writer
553
            // TLS First, don't read info until after upgrade
554
            Callable<Object> connectTask = () -> {
1✔
555
                if (!options.isTlsFirst()) {
1✔
556
                    readInitialInfo();
1✔
557
                    checkVersionRequirements();
1✔
558
                }
559
                long start = NatsSystemClock.nanoTime();
1✔
560
                upgradeToSecureIfNeeded(resolved);
1✔
561
                if (trace && options.isTLSRequired()) {
1✔
562
                    // If the time appears too long it might be related to
563
                    // https://github.com/nats-io/nats.java#linux-platform-note
564
                    timeTraceLogger.trace("TLS upgrade took: %.3f (s)",
×
NEW
565
                            ((double) (NatsSystemClock.nanoTime() - start)) / NANOS_PER_SECOND);
×
566
                }
567
                if (options.isTlsFirst()) {
1✔
568
                    readInitialInfo();
1✔
569
                    checkVersionRequirements();
1✔
570
                }
571
                return null;
1✔
572
            };
573

574
            timeoutNanos = timeCheck(end, "reading info, version and upgrading to secure if necessary");
1✔
575
            Future<Object> future = this.connectExecutor.submit(connectTask);
1✔
576
            try {
577
                future.get(timeoutNanos, TimeUnit.NANOSECONDS);
1✔
578
            } finally {
579
                future.cancel(true);
1✔
580
            }
581

582
            // start the reader and writer after we secured the connection, if necessary
583
            timeCheck(end, "starting reader");
1✔
584
            this.reader.start(this.dataPortFuture);
1✔
585
            timeCheck(end, "starting writer");
1✔
586
            this.writer.start(this.dataPortFuture);
1✔
587

588
            timeCheck(end, "sending connect message");
1✔
589
            this.sendConnect(resolved);
1✔
590

591
            timeoutNanos = timeCheck(end, "sending initial ping");
1✔
592
            Future<Boolean> pongFuture = sendPing();
1✔
593

594
            if (pongFuture != null) {
1✔
595
                pongFuture.get(timeoutNanos, TimeUnit.NANOSECONDS);
1✔
596
            }
597

598
            if (this.timer == null) {
1✔
599
                timeCheck(end, "starting ping and cleanup timers");
1✔
600
                this.timer = new Timer("Nats Connection Timer");
1✔
601

602
                long pingMillis = this.options.getPingInterval().toMillis();
1✔
603

604
                if (pingMillis > 0) {
1✔
605
                    this.timer.schedule(new TimerTask() {
1✔
606
                        public void run() {
607
                            if (isConnected()) {
1✔
608
                                try {
609
                                    softPing(); // The timer always uses the standard queue
1✔
610
                                }
611
                                catch (Exception e) {
1✔
612
                                    // it's running in a thread, there is no point throwing here
613
                                }
1✔
614
                            }
615
                        }
1✔
616
                    }, pingMillis, pingMillis);
617
                }
618

619
                long cleanMillis = this.options.getRequestCleanupInterval().toMillis();
1✔
620

621
                if (cleanMillis > 0) {
1✔
622
                    this.timer.schedule(new TimerTask() {
1✔
623
                        public void run() {
624
                            cleanResponses(false);
1✔
625
                        }
1✔
626
                    }, cleanMillis, cleanMillis);
627
                }
628
            }
629

630
            // Set connected status
631
            timeCheck(end, "updating status to connected");
1✔
632
            statusLock.lock();
1✔
633
            try {
634
                this.connecting = false;
1✔
635

636
                if (this.exceptionDuringConnectChange != null) {
1✔
637
                    throw this.exceptionDuringConnectChange;
×
638
                }
639

640
                this.currentServer = cur;
1✔
641
                this.serverAuthErrors.clear(); // reset on successful connection
1✔
642
                updateStatus(Status.CONNECTED); // will signal status change, we also signal in finally
1✔
643
            } finally {
644
                statusLock.unlock();
1✔
645
            }
646
            timeTraceLogger.trace("status updated");
1✔
647
        } catch (Exception exp) {
1✔
648
            processException(exp);
1✔
649
            try {
650
                // allow force reconnect since this is pretty exceptional,
651
                // a connection failure while trying to connect
652
                this.closeSocket(false, true);
1✔
653
            } catch (InterruptedException e) {
×
654
                processException(e);
×
655
                Thread.currentThread().interrupt();
×
656
            }
1✔
657
        } finally {
658
            statusLock.lock();
1✔
659
            try {
660
                this.connecting = false;
1✔
661
                statusChanged.signalAll();
1✔
662
            } finally {
663
                statusLock.unlock();
1✔
664
            }
665
        }
666
    }
1✔
667

668
    void checkVersionRequirements() throws IOException {
669
        Options opts = getOptions();
1✔
670
        ServerInfo info = getInfo();
1✔
671

672
        if (opts.isNoEcho() && info.getProtocolVersion() < 1) {
1✔
673
            throw new IOException("Server does not support no echo.");
1✔
674
        }
675
    }
1✔
676

677
    void upgradeToSecureIfNeeded(NatsUri nuri) throws IOException {
678
        // When already communicating over "https" websocket, do NOT try to upgrade to secure.
679
        if (!nuri.isWebsocket()) {
1✔
680
            if (options.isTlsFirst()) {
1✔
681
                dataPort.upgradeToSecure();
1✔
682
            }
683
            else {
684
                // server    | client options      | result
685
                // --------- | ------------------- | --------
686
                // required  | not isTLSRequired() | mismatch
687
                // available | not isTLSRequired() | ok
688
                // neither   | not isTLSRequired() | ok
689
                // required  | isTLSRequired()     | ok
690
                // available | isTLSRequired()     | ok
691
                // neither   | isTLSRequired()     | mismatch
692
                ServerInfo serverInfo = getInfo();
1✔
693
                if (options.isTLSRequired()) {
1✔
694
                    if (!serverInfo.isTLSRequired() && !serverInfo.isTLSAvailable()) {
1✔
695
                        throw new IOException("SSL connection wanted by client.");
1✔
696
                    }
697
                    dataPort.upgradeToSecure();
1✔
698
                }
699
                else if (serverInfo.isTLSRequired()) {
1✔
700
                    throw new IOException("SSL required by server.");
1✔
701
                }
702
            }
703
        }
704
    }
1✔
705
    // Called from reader/writer thread
706
    void handleCommunicationIssue(Exception io) {
707
        // If we are connecting or disconnecting, note exception and leave
708
        statusLock.lock();
1✔
709
        try {
710
            if (this.connecting || this.disconnecting || this.status == Status.CLOSED || this.isDraining()) {
1✔
711
                this.exceptionDuringConnectChange = io;
1✔
712
                return;
1✔
713
            }
714
        } finally {
715
            statusLock.unlock();
1✔
716
        }
717

718
        processException(io);
1✔
719

720
        // Spawn a thread so we don't have timing issues with
721
        // waiting on read/write threads
722
        executor.submit(() -> {
1✔
723
            if (!tryingToConnect.get()) {
1✔
724
                try {
725
                    tryingToConnect.set(true);
1✔
726

727
                    // any issue that brings us here is pretty serious
728
                    // so we are comfortable forcing the close
729
                    this.closeSocket(true, true);
1✔
730
                } catch (InterruptedException e) {
×
731
                    processException(e);
×
732
                    Thread.currentThread().interrupt();
×
733
                } finally {
734
                    tryingToConnect.set(false);
1✔
735
                }
736
            }
737
        });
1✔
738
    }
1✔
739

740
    // Close socket is called when another connect attempt is possible
741
    // Close is called when the connection should shut down, period
742
    void closeSocket(boolean tryReconnectIfConnected, boolean forceClose) throws InterruptedException {
743
        // Ensure we close the socket exclusively within one thread.
744
        closeSocketLock.lock();
1✔
745
        try {
746
            boolean wasConnected;
747
            statusLock.lock();
1✔
748
            try {
749
                if (isDisconnectingOrClosed()) {
1✔
750
                    waitForDisconnectOrClose(this.options.getConnectionTimeout());
1✔
751
                    return;
1✔
752
                }
753
                this.disconnecting = true;
1✔
754
                this.exceptionDuringConnectChange = null;
1✔
755
                wasConnected = (this.status == Status.CONNECTED);
1✔
756
                statusChanged.signalAll();
1✔
757
            } finally {
758
                statusLock.unlock();
1✔
759
            }
760

761
            closeSocketImpl(forceClose);
1✔
762

763
            statusLock.lock();
1✔
764
            try {
765
                updateStatus(Status.DISCONNECTED);
1✔
766
                this.exceptionDuringConnectChange = null; // Ignore IOExceptions during closeSocketImpl()
1✔
767
                this.disconnecting = false;
1✔
768
                statusChanged.signalAll();
1✔
769
            } finally {
770
                statusLock.unlock();
1✔
771
            }
772

773
            if (isClosing()) { // isClosing() means we are in the close method or were asked to be
1✔
UNCOV
774
                close();
×
775
            } else if (wasConnected && tryReconnectIfConnected) {
1✔
776
                reconnectImpl(); // call the impl here otherwise the tryingToConnect guard will block the behavior
1✔
777
            }
778
        } finally {
779
            closeSocketLock.unlock();
1✔
780
        }
781
    }
1✔
782

783
    // Close socket is called when another connect attempt is possible
784
    // Close is called when the connection should shut down, period
785
    /**
786
     * {@inheritDoc}
787
     */
788
    @Override
789
    public void close() throws InterruptedException {
790
        this.close(true, false);
1✔
791
    }
1✔
792

793
    void close(boolean checkDrainStatus, boolean forceClose) throws InterruptedException {
794
        statusLock.lock();
1✔
795
        try {
796
            if (checkDrainStatus && this.isDraining()) {
1✔
797
                waitForDisconnectOrClose(this.options.getConnectionTimeout());
1✔
798
                return;
1✔
799
            }
800

801
            this.closing = true;// We were asked to close, so do it
1✔
802
            if (isDisconnectingOrClosed()) {
1✔
803
                waitForDisconnectOrClose(this.options.getConnectionTimeout());
1✔
804
                return;
1✔
805
            } else {
806
                this.disconnecting = true;
1✔
807
                this.exceptionDuringConnectChange = null;
1✔
808
                statusChanged.signalAll();
1✔
809
            }
810
        } finally {
811
            statusLock.unlock();
1✔
812
        }
813

814
        // Stop the reconnect wait timer after we stop the writer/reader (only if we are
815
        // really closing, not on errors)
816
        if (this.reconnectWaiter != null) {
1✔
817
            this.reconnectWaiter.cancel(true);
1✔
818
        }
819

820
        closeSocketImpl(forceClose);
1✔
821

822
        this.dispatchers.forEach((nuid, d) -> d.stop(false));
1✔
823

824
        this.subscribers.forEach((sid, sub) -> sub.invalidate());
1✔
825

826
        this.dispatchers.clear();
1✔
827
        this.subscribers.clear();
1✔
828

829
        if (timer != null) {
1✔
830
            timer.cancel();
1✔
831
            timer = null;
1✔
832
        }
833

834
        cleanResponses(true);
1✔
835

836
        cleanUpPongQueue();
1✔
837

838
        statusLock.lock();
1✔
839
        try {
840
            updateStatus(Status.CLOSED); // will signal, we also signal when we stop disconnecting
1✔
841

842
            /*
843
             * if (exceptionDuringConnectChange != null) {
844
             * processException(exceptionDuringConnectChange); exceptionDuringConnectChange
845
             * = null; }
846
             */
847
        } finally {
848
            statusLock.unlock();
1✔
849
        }
850

851
        // Stop the error handling and connect executors
852
        callbackRunner.shutdown();
1✔
853
        try {
854
            callbackRunner.awaitTermination(this.options.getConnectionTimeout().toNanos(), TimeUnit.NANOSECONDS);
1✔
855
        } finally {
856
            callbackRunner.shutdownNow();
1✔
857
        }
858

859
        // There's no need to wait for running tasks since we're told to close
860
        connectExecutor.shutdownNow();
1✔
861

862
        statusLock.lock();
1✔
863
        try {
864
            this.disconnecting = false;
1✔
865
            statusChanged.signalAll();
1✔
866
        } finally {
867
            statusLock.unlock();
1✔
868
        }
869
    }
1✔
870

871
    // Should only be called from closeSocket or close
872
    void closeSocketImpl(boolean forceClose) {
873
        this.currentServer = null;
1✔
874

875
        // Signal both to stop.
876
        final Future<Boolean> readStop = this.reader.stop();
1✔
877
        final Future<Boolean> writeStop = this.writer.stop();
1✔
878

879
        // Now wait until they both stop before closing the socket.
880
        try {
881
            readStop.get(1, TimeUnit.SECONDS);
1✔
882
        } catch (Exception ex) {
1✔
883
            //
884
        }
1✔
885
        try {
886
            writeStop.get(1, TimeUnit.SECONDS);
1✔
887
        } catch (Exception ex) {
×
888
            //
889
        }
1✔
890

891
        // Close and reset the current data port and future
892
        if (dataPortFuture != null) {
1✔
893
            dataPortFuture.cancel(true);
1✔
894
            dataPortFuture = null;
1✔
895
        }
896

897
        // Close the current socket and cancel anyone waiting for it
898
        try {
899
            if (dataPort != null) {
1✔
900
                if (forceClose) {
1✔
901
                    dataPort.forceClose();
1✔
902
                }
903
                else {
904
                    dataPort.close();
1✔
905
                }
906
            }
907

908
        } catch (IOException ex) {
×
909
            processException(ex);
×
910
        }
1✔
911
        cleanUpPongQueue();
1✔
912

913
        try {
914
            this.reader.stop().get(10, TimeUnit.SECONDS);
1✔
915
        } catch (Exception ex) {
×
916
            processException(ex);
×
917
        }
1✔
918
        try {
919
            this.writer.stop().get(10, TimeUnit.SECONDS);
1✔
920
        } catch (Exception ex) {
×
921
            processException(ex);
×
922
        }
1✔
923
    }
1✔
924

925
    void cleanUpPongQueue() {
926
        Future<Boolean> b;
927
        while ((b = pongQueue.poll()) != null) {
1✔
928
            b.cancel(true);
1✔
929
        }
930
    }
1✔
931

932
    /**
933
     * {@inheritDoc}
934
     */
935
    @Override
936
    public void publish(String subject, byte[] body) {
937
        publishInternal(subject, null, null, body, true, false);
1✔
938
    }
1✔
939

940
    /**
941
     * {@inheritDoc}
942
     */
943
    @Override
944
    public void publish(String subject, Headers headers, byte[] body) {
945
        publishInternal(subject, null, headers, body, true, false);
1✔
946
    }
1✔
947

948
    /**
949
     * {@inheritDoc}
950
     */
951
    @Override
952
    public void publish(String subject, String replyTo, byte[] body) {
953
        publishInternal(subject, replyTo, null, body, true, false);
1✔
954
    }
1✔
955

956
    /**
957
     * {@inheritDoc}
958
     */
959
    @Override
960
    public void publish(String subject, String replyTo, Headers headers, byte[] body) {
961
        publishInternal(subject, replyTo, headers, body, true, false);
1✔
962
    }
1✔
963

964
    /**
965
     * {@inheritDoc}
966
     */
967
    @Override
968
    public void publish(Message message) {
969
        validateNotNull(message, "Message");
1✔
970
        publishInternal(message.getSubject(), message.getReplyTo(), message.getHeaders(), message.getData(), false, false);
1✔
971
    }
1✔
972

973
    void publishInternal(String subject, String replyTo, Headers headers, byte[] data, boolean validateSubjectAndReplyTo, boolean flushImmediatelyAfterPublish) {
974
        checkPayloadSize(data);
1✔
975
        NatsPublishableMessage npm = new NatsPublishableMessage(subject, replyTo, headers, data, validateSubjectAndReplyTo, flushImmediatelyAfterPublish);
1✔
976
        if (npm.hasHeaders && !serverInfo.get().isHeadersSupported()) {
1✔
977
            throw new IllegalArgumentException("Headers are not supported by the server, version: " + serverInfo.get().getVersion());
1✔
978
        }
979

980
        if (isClosed()) {
1✔
981
            throw new IllegalStateException("Connection is Closed");
1✔
982
        } else if (blockPublishForDrain.get()) {
1✔
983
            throw new IllegalStateException("Connection is Draining"); // Ok to publish while waiting on subs
×
984
        }
985

986
        if ((status == Status.RECONNECTING || status == Status.DISCONNECTED)
1✔
987
                && !this.writer.canQueueDuringReconnect(npm)) {
1✔
988
            throw new IllegalStateException(
1✔
989
                    "Unable to queue any more messages during reconnect, max buffer is " + options.getReconnectBufferSize());
1✔
990
        }
991

992
        queueOutgoing(npm);
1✔
993
    }
1✔
994

995
    private void checkPayloadSize(byte[] body) {
996
        if (options.clientSideLimitChecks() && body != null && body.length > this.getMaxPayload() && this.getMaxPayload() > 0) {
1✔
997
            throw new IllegalArgumentException(
1✔
998
                "Message payload size exceed server configuration " + body.length + " vs " + this.getMaxPayload());
1✔
999
        }
1000
    }
1✔
1001
    /**
1002
     * {@inheritDoc}
1003
     */
1004
    @Override
1005
    public Subscription subscribe(String subject) {
1006
        validateSubject(subject, true);
1✔
1007
        return createSubscription(subject, null, null, null);
1✔
1008
    }
1009

1010
    /**
1011
     * {@inheritDoc}
1012
     */
1013
    @Override
1014
    public Subscription subscribe(String subject, String queueName) {
1015
        validateSubject(subject, true);
1✔
1016
        validateQueueName(queueName, true);
1✔
1017
        return createSubscription(subject, queueName, null, null);
1✔
1018
    }
1019

1020
    void invalidate(NatsSubscription sub) {
1021
        remove(sub);
1✔
1022
        sub.invalidate();
1✔
1023
    }
1✔
1024

1025
    void remove(NatsSubscription sub) {
1026
        CharSequence sid = sub.getSID();
1✔
1027
        subscribers.remove(sid);
1✔
1028

1029
        if (sub.getNatsDispatcher() != null) {
1✔
1030
            sub.getNatsDispatcher().remove(sub);
1✔
1031
        }
1032
    }
1✔
1033

1034
    void unsubscribe(NatsSubscription sub, int after) {
1035
        if (isClosed()) { // last chance, usually sub will catch this
1✔
1036
            throw new IllegalStateException("Connection is Closed");
×
1037
        }
1038

1039
        if (after <= 0) {
1✔
1040
            this.invalidate(sub); // Will clean it up
1✔
1041
        } else {
1042
            sub.setUnsubLimit(after);
1✔
1043

1044
            if (sub.reachedUnsubLimit()) {
1✔
1045
                sub.invalidate();
1✔
1046
            }
1047
        }
1048

1049
        if (!isConnected()) {
1✔
1050
            return; // We will set up sub on reconnect or ignore
×
1051
        }
1052

1053
        sendUnsub(sub, after);
1✔
1054
    }
1✔
1055

1056
    void sendUnsub(NatsSubscription sub, int after) {
1057
        ByteArrayBuilder bab =
1✔
1058
            new ByteArrayBuilder().append(UNSUB_SP_BYTES).append(sub.getSID());
1✔
1059
        if (after > 0) {
1✔
1060
            bab.append(SP).append(after);
1✔
1061
        }
1062
        queueInternalOutgoing(new ProtocolMessage(bab));
1✔
1063
    }
1✔
1064

1065
    // Assumes the null/empty checks were handled elsewhere
1066
    NatsSubscription createSubscription(String subject, String queueName, NatsDispatcher dispatcher, NatsSubscriptionFactory factory) {
1067
        if (isClosed()) {
1✔
1068
            throw new IllegalStateException("Connection is Closed");
1✔
1069
        } else if (isDraining() && (dispatcher == null || dispatcher != this.inboxDispatcher.get())) {
1✔
1070
            throw new IllegalStateException("Connection is Draining");
1✔
1071
        }
1072

1073
        NatsSubscription sub;
1074
        String sid = getNextSid();
1✔
1075

1076
        if (factory == null) {
1✔
1077
            sub = new NatsSubscription(sid, subject, queueName, this, dispatcher);
1✔
1078
        }
1079
        else {
1080
            sub = factory.createNatsSubscription(sid, subject, queueName, this, dispatcher);
1✔
1081
        }
1082
        subscribers.put(sid, sub);
1✔
1083

1084
        sendSubscriptionMessage(sid, subject, queueName, false);
1✔
1085
        return sub;
1✔
1086
    }
1087

1088
    String getNextSid() {
1089
        return Long.toString(nextSid.getAndIncrement());
1✔
1090
    }
1091

1092
    String reSubscribe(NatsSubscription sub, String subject, String queueName) {
1093
        String sid = getNextSid();
1✔
1094
        sendSubscriptionMessage(sid, subject, queueName, false);
1✔
1095
        subscribers.put(sid, sub);
1✔
1096
        return sid;
1✔
1097
    }
1098

1099
    void sendSubscriptionMessage(String sid, String subject, String queueName, boolean treatAsInternal) {
1100
        if (!isConnected()) {
1✔
1101
            return; // We will set up sub on reconnect or ignore
1✔
1102
        }
1103

1104
        ByteArrayBuilder bab = new ByteArrayBuilder(UTF_8).append(SUB_SP_BYTES).append(subject);
1✔
1105
        if (queueName != null) {
1✔
1106
            bab.append(SP).append(queueName);
1✔
1107
        }
1108
        bab.append(SP).append(sid);
1✔
1109

1110
        ProtocolMessage subMsg = new ProtocolMessage(bab);
1✔
1111

1112
        if (treatAsInternal) {
1✔
1113
            queueInternalOutgoing(subMsg);
1✔
1114
        } else {
1115
            queueOutgoing(subMsg);
1✔
1116
        }
1117
    }
1✔
1118

1119
    /**
1120
     * {@inheritDoc}
1121
     */
1122
    @Override
1123
    public String createInbox() {
1124
        return options.getInboxPrefix() + nuid.next();
1✔
1125
    }
1126

1127
    int getRespInboxLength() {
1128
        return options.getInboxPrefix().length() + 22 + 1; // 22 for nuid, 1 for .
1✔
1129
    }
1130

1131
    String createResponseInbox(String inbox) {
1132
        // Substring gets rid of the * [trailing]
1133
        return inbox.substring(0, getRespInboxLength()) + nuid.next();
1✔
1134
    }
1135

1136
    // If the inbox is long enough, pull out the end part, otherwise, just use the
1137
    // full thing
1138
    String getResponseToken(String responseInbox) {
1139
        int len = getRespInboxLength();
1✔
1140
        if (responseInbox.length() <= len) {
1✔
1141
            return responseInbox;
1✔
1142
        }
1143
        return responseInbox.substring(len);
1✔
1144
    }
1145

1146
    void cleanResponses(boolean closing) {
1147
        ArrayList<String> toRemove = new ArrayList<>();
1✔
1148
        boolean wasInterrupted = false;
1✔
1149

1150
        for (Map.Entry<String, NatsRequestCompletableFuture> entry : responsesAwaiting.entrySet()) {
1✔
1151
            boolean remove = false;
1✔
1152
            NatsRequestCompletableFuture future = entry.getValue();
1✔
1153
            if (future.hasExceededTimeout()) {
1✔
1154
                remove = true;
1✔
1155
                future.cancelTimedOut();
1✔
1156
            }
1157
            else if (closing) {
1✔
1158
                remove = true;
1✔
1159
                future.cancelClosing();
1✔
1160
            }
1161
            else if (future.isDone()) {
1✔
1162
                // done should have already been removed, not sure if
1163
                // this even needs checking, but it won't hurt
1164
                remove = true;
1✔
1165
                try {
1166
                    future.get();
1✔
1167
                }
1168
                catch (InterruptedException e) {
×
1169
                    Thread.currentThread().interrupt();
×
1170
                    // we might have collected some entries already, but were interrupted
1171
                    // break out so we finish as quick as possible
1172
                    // cleanResponses will be called again anyway
1173
                    wasInterrupted = true;
×
1174
                    break;
×
1175
                }
1176
                catch (Throwable ignore) {}
1✔
1177
            }
1178

1179
            if (remove) {
1✔
1180
                toRemove.add(entry.getKey());
1✔
1181
                statistics.decrementOutstandingRequests();
1✔
1182
            }
1183
        }
1✔
1184

1185
        for (String key : toRemove) {
1✔
1186
            responsesAwaiting.remove(key);
1✔
1187
        }
1✔
1188

1189
        if (advancedTracking && !wasInterrupted) {
1✔
1190
            toRemove.clear(); // just reuse this
1✔
1191
            for (Map.Entry<String, NatsRequestCompletableFuture> entry : responsesRespondedTo.entrySet()) {
1✔
1192
                NatsRequestCompletableFuture future = entry.getValue();
1✔
1193
                if (future.hasExceededTimeout()) {
1✔
1194
                    toRemove.add(entry.getKey());
1✔
1195
                    future.cancelTimedOut();
1✔
1196
                }
1197
            }
1✔
1198

1199
            for (String token : toRemove) {
1✔
1200
                responsesRespondedTo.remove(token);
1✔
1201
            }
1✔
1202
        }
1203
    }
1✔
1204

1205
    /**
1206
     * {@inheritDoc}
1207
     */
1208
    @Override
1209
    public Message request(String subject, byte[] body, Duration timeout) throws InterruptedException {
1210
        return requestInternal(subject, null, body, timeout, cancelAction, true, forceFlushOnRequest);
1✔
1211
    }
1212

1213
    /**
1214
     * {@inheritDoc}
1215
     */
1216
    @Override
1217
    public Message request(String subject, Headers headers, byte[] body, Duration timeout) throws InterruptedException {
1218
        return requestInternal(subject, headers, body, timeout, cancelAction, true, forceFlushOnRequest);
1✔
1219
    }
1220

1221
    /**
1222
     * {@inheritDoc}
1223
     */
1224
    @Override
1225
    public Message request(Message message, Duration timeout) throws InterruptedException {
1226
        validateNotNull(message, "Message");
1✔
1227
        return requestInternal(message.getSubject(), message.getHeaders(), message.getData(), timeout, cancelAction, false, forceFlushOnRequest);
1✔
1228
    }
1229

1230
    Message requestInternal(String subject, Headers headers, byte[] data, Duration timeout,
1231
                            CancelAction cancelAction, boolean validateSubjectAndReplyTo, boolean flushImmediatelyAfterPublish) throws InterruptedException {
1232
        CompletableFuture<Message> incoming = requestFutureInternal(subject, headers, data, timeout, cancelAction, validateSubjectAndReplyTo, flushImmediatelyAfterPublish);
1✔
1233
        try {
1234
            return incoming.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
1✔
1235
        } catch (TimeoutException | ExecutionException | CancellationException e) {
1✔
1236
            return null;
1✔
1237
        }
1238
    }
1239

1240
    /**
1241
     * {@inheritDoc}
1242
     */
1243
    @Override
1244
    public CompletableFuture<Message> request(String subject, byte[] body) {
1245
        return requestFutureInternal(subject, null, body, null, cancelAction, true, forceFlushOnRequest);
1✔
1246
    }
1247

1248
    /**
1249
     * {@inheritDoc}
1250
     */
1251
    @Override
1252
    public CompletableFuture<Message> request(String subject, Headers headers, byte[] body) {
1253
        return requestFutureInternal(subject, headers, body, null, cancelAction, true, forceFlushOnRequest);
1✔
1254
    }
1255

1256
    /**
1257
     * {@inheritDoc}
1258
     */
1259
    @Override
1260
    public CompletableFuture<Message> requestWithTimeout(String subject, byte[] body, Duration timeout) {
1261
        return requestFutureInternal(subject, null, body, timeout, cancelAction, true, forceFlushOnRequest);
1✔
1262
    }
1263

1264
    /**
1265
     * {@inheritDoc}
1266
     */
1267
    @Override
1268
    public CompletableFuture<Message> requestWithTimeout(String subject, Headers headers, byte[] body, Duration timeout) {
1269
        return requestFutureInternal(subject, headers, body, timeout, cancelAction, true, forceFlushOnRequest);
1✔
1270
    }
1271

1272
    /**
1273
     * {@inheritDoc}
1274
     */
1275
    @Override
1276
    public CompletableFuture<Message> requestWithTimeout(Message message, Duration timeout) {
1277
        validateNotNull(message, "Message");
1✔
1278
        return requestFutureInternal(message.getSubject(), message.getHeaders(), message.getData(), timeout, cancelAction, false, forceFlushOnRequest);
1✔
1279
    }
1280

1281
    /**
1282
     * {@inheritDoc}
1283
     */
1284
    @Override
1285
    public CompletableFuture<Message> request(Message message) {
1286
        validateNotNull(message, "Message");
1✔
1287
        return requestFutureInternal(message.getSubject(), message.getHeaders(), message.getData(), null, cancelAction, false, forceFlushOnRequest);
1✔
1288
    }
1289

1290
    CompletableFuture<Message> requestFutureInternal(String subject, Headers headers, byte[] data, Duration futureTimeout,
1291
                                                     CancelAction cancelAction, boolean validateSubjectAndReplyTo, boolean flushImmediatelyAfterPublish) {
1292
        checkPayloadSize(data);
1✔
1293

1294
        if (isClosed()) {
1✔
1295
            throw new IllegalStateException("Connection is Closed");
1✔
1296
        } else if (isDraining()) {
1✔
1297
            throw new IllegalStateException("Connection is Draining");
1✔
1298
        }
1299

1300
        if (inboxDispatcher.get() == null) {
1✔
1301
            inboxDispatcherLock.lock();
1✔
1302
            try {
1303
                if (inboxDispatcher.get() == null) {
1✔
1304
                    NatsDispatcher d = dispatcherFactory.createDispatcher(this, this::deliverReply);
1✔
1305

1306
                    // Ensure the dispatcher is started before publishing messages
1307
                    String id = this.nuid.next();
1✔
1308
                    this.dispatchers.put(id, d);
1✔
1309
                    d.start(id);
1✔
1310
                    d.subscribe(this.mainInbox);
1✔
1311
                    inboxDispatcher.set(d);
1✔
1312
                }
1313
            } finally {
1314
                inboxDispatcherLock.unlock();
1✔
1315
            }
1316
        }
1317

1318
        boolean oldStyle = options.isOldRequestStyle();
1✔
1319
        String responseInbox = oldStyle ? createInbox() : createResponseInbox(this.mainInbox);
1✔
1320
        String responseToken = getResponseToken(responseInbox);
1✔
1321
        NatsRequestCompletableFuture future =
1✔
1322
            new NatsRequestCompletableFuture(cancelAction,
1323
                futureTimeout == null ? options.getRequestCleanupInterval() : futureTimeout, options.useTimeoutException());
1✔
1324

1325
        if (!oldStyle) {
1✔
1326
            responsesAwaiting.put(responseToken, future);
1✔
1327
        }
1328
        statistics.incrementOutstandingRequests();
1✔
1329

1330
        if (oldStyle) {
1✔
1331
            NatsDispatcher dispatcher = this.inboxDispatcher.get();
1✔
1332
            NatsSubscription sub = dispatcher.subscribeReturningSubscription(responseInbox);
1✔
1333
            dispatcher.unsubscribe(responseInbox, 1);
1✔
1334
            // Unsubscribe when future is cancelled:
1335
            future.whenComplete((msg, exception) -> {
1✔
1336
                if (exception instanceof CancellationException) {
1✔
1337
                    dispatcher.unsubscribe(responseInbox);
×
1338
                }
1339
            });
1✔
1340
            responsesAwaiting.put(sub.getSID(), future);
1✔
1341
        }
1342

1343
        publishInternal(subject, responseInbox, headers, data, validateSubjectAndReplyTo, flushImmediatelyAfterPublish);
1✔
1344
        statistics.incrementRequestsSent();
1✔
1345

1346
        return future;
1✔
1347
    }
1348

1349
    void deliverReply(Message msg) {
1350
        boolean oldStyle = options.isOldRequestStyle();
1✔
1351
        String subject = msg.getSubject();
1✔
1352
        String token = getResponseToken(subject);
1✔
1353
        String key = oldStyle ? msg.getSID() : token;
1✔
1354
        NatsRequestCompletableFuture f = responsesAwaiting.remove(key);
1✔
1355
        if (f != null) {
1✔
1356
            if (advancedTracking) {
1✔
1357
                responsesRespondedTo.put(key, f);
1✔
1358
            }
1359
            statistics.decrementOutstandingRequests();
1✔
1360
            if (msg.isStatusMessage() && msg.getStatus().getCode() == 503) {
1✔
1361
                switch (f.getCancelAction()) {
1✔
1362
                    case COMPLETE:
1363
                        f.complete(msg);
1✔
1364
                        break;
1✔
1365
                    case REPORT:
1366
                        f.completeExceptionally(new JetStreamStatusException(msg.getStatus()));
1✔
1367
                        break;
1✔
1368
                    case CANCEL:
1369
                    default:
1370
                        f.cancel(true);
1✔
1371
                }
1372
            }
1373
            else {
1374
                f.complete(msg);
1✔
1375
            }
1376
            statistics.incrementRepliesReceived();
1✔
1377
        }
1378
        else if (!oldStyle && !subject.startsWith(mainInbox)) {
1✔
1379
            if (advancedTracking) {
1✔
1380
                if (responsesRespondedTo.get(key) != null) {
1✔
1381
                    statistics.incrementDuplicateRepliesReceived();
1✔
1382
                } else {
1383
                    statistics.incrementOrphanRepliesReceived();
1✔
1384
                }
1385
            }
1386
        }
1387
    }
1✔
1388

1389
    public Dispatcher createDispatcher() {
1390
        return createDispatcher(null);
1✔
1391
    }
1392

1393
    public Dispatcher createDispatcher(MessageHandler handler) {
1394
        if (isClosed()) {
1✔
1395
            throw new IllegalStateException("Connection is Closed");
1✔
1396
        } else if (isDraining()) {
1✔
1397
            throw new IllegalStateException("Connection is Draining");
1✔
1398
        }
1399

1400
        NatsDispatcher dispatcher = dispatcherFactory.createDispatcher(this, handler);
1✔
1401
        String id = this.nuid.next();
1✔
1402
        this.dispatchers.put(id, dispatcher);
1✔
1403
        dispatcher.start(id);
1✔
1404
        return dispatcher;
1✔
1405
    }
1406

1407
    public void closeDispatcher(Dispatcher d) {
1408
        if (isClosed()) {
1✔
1409
            throw new IllegalStateException("Connection is Closed");
1✔
1410
        } else if (!(d instanceof NatsDispatcher)) {
1✔
1411
            throw new IllegalArgumentException("Connection can only manage its own dispatchers");
×
1412
        }
1413

1414
        NatsDispatcher nd = ((NatsDispatcher) d);
1✔
1415

1416
        if (nd.isDraining()) {
1✔
1417
            return; // No op while draining
1✔
1418
        }
1419

1420
        if (!this.dispatchers.containsKey(nd.getId())) {
1✔
1421
            throw new IllegalArgumentException("Dispatcher is already closed.");
1✔
1422
        }
1423

1424
        cleanupDispatcher(nd);
1✔
1425
    }
1✔
1426

1427
    void cleanupDispatcher(NatsDispatcher nd) {
1428
        nd.stop(true);
1✔
1429
        this.dispatchers.remove(nd.getId());
1✔
1430
    }
1✔
1431

1432
    Map<String, Dispatcher> getDispatchers() {
1433
        return Collections.unmodifiableMap(dispatchers);
1✔
1434
    }
1435

1436
    public void addConnectionListener(ConnectionListener connectionListener) {
1437
        connectionListeners.add(connectionListener);
1✔
1438
    }
1✔
1439

1440
    public void removeConnectionListener(ConnectionListener connectionListener) {
1441
        connectionListeners.remove(connectionListener);
1✔
1442
    }
1✔
1443

1444
    public void flush(Duration timeout) throws TimeoutException, InterruptedException {
1445

1446
        Instant start = Instant.now();
1✔
1447
        waitForConnectOrClose(timeout);
1✔
1448

1449
        if (isClosed()) {
1✔
1450
            throw new TimeoutException("Attempted to flush while closed");
1✔
1451
        }
1452

1453
        if (timeout == null) {
1✔
1454
            timeout = Duration.ZERO;
1✔
1455
        }
1456

1457
        Instant now = Instant.now();
1✔
1458
        Duration waitTime = Duration.between(start, now);
1✔
1459

1460
        if (!timeout.equals(Duration.ZERO) && waitTime.compareTo(timeout) >= 0) {
1✔
1461
            throw new TimeoutException("Timeout out waiting for connection before flush.");
1✔
1462
        }
1463

1464
        try {
1465
            Future<Boolean> waitForIt = sendPing();
1✔
1466

1467
            if (waitForIt == null) { // error in the send ping code
1✔
1468
                return;
×
1469
            }
1470

1471
            long nanos = timeout.toNanos();
1✔
1472

1473
            if (nanos > 0) {
1✔
1474

1475
                nanos -= waitTime.toNanos();
1✔
1476

1477
                if (nanos <= 0) {
1✔
1478
                    nanos = 1; // let the future timeout if it isn't resolved
×
1479
                }
1480

1481
                waitForIt.get(nanos, TimeUnit.NANOSECONDS);
1✔
1482
            } else {
1483
                waitForIt.get();
1✔
1484
            }
1485

1486
            this.statistics.incrementFlushCounter();
1✔
1487
        } catch (ExecutionException | CancellationException e) {
1✔
1488
            throw new TimeoutException(e.toString());
1✔
1489
        }
1✔
1490
    }
1✔
1491

1492
    void sendConnect(NatsUri nuri) throws IOException {
1493
        try {
1494
            ServerInfo info = this.serverInfo.get();
1✔
1495
            // This is changed - we used to use info.isAuthRequired(), but are changing it to
1496
            // better match older versions of the server. It may change again in the future.
1497
            CharBuffer connectOptions = options.buildProtocolConnectOptionsString(
1✔
1498
                nuri.toString(), true, info.getNonce());
1✔
1499
            ByteArrayBuilder bab =
1✔
1500
                new ByteArrayBuilder(OP_CONNECT_SP_LEN + connectOptions.limit(), UTF_8)
1✔
1501
                    .append(CONNECT_SP_BYTES).append(connectOptions);
1✔
1502
            queueInternalOutgoing(new ProtocolMessage(bab));
1✔
1503
        } catch (Exception exp) {
1✔
1504
            throw new IOException("Error sending connect string", exp);
1✔
1505
        }
1✔
1506
    }
1✔
1507

1508
    CompletableFuture<Boolean> sendPing() {
1509
        return this.sendPing(true);
1✔
1510
    }
1511

1512
    CompletableFuture<Boolean> softPing() {
1513
        return this.sendPing(false);
1✔
1514
    }
1515

1516
    /**
1517
     * {@inheritDoc}
1518
     */
1519
    @Override
1520
    public Duration RTT() throws IOException {
1521
        if (!isConnectedOrConnecting()) {
1✔
1522
            throw new IOException("Must be connected to do RTT.");
1✔
1523
        }
1524

1525
        long timeout = options.getConnectionTimeout().toMillis();
1✔
1526
        CompletableFuture<Boolean> pongFuture = new CompletableFuture<>();
1✔
1527
        pongQueue.add(pongFuture);
1✔
1528
        try {
1529
            long time = NatsSystemClock.nanoTime();
1✔
1530
            writer.queueInternalMessage(new ProtocolMessage(OP_PING_BYTES));
1✔
1531
            pongFuture.get(timeout, TimeUnit.MILLISECONDS);
1✔
1532
            return Duration.ofNanos(NatsSystemClock.nanoTime() - time);
1✔
1533
        }
1534
        catch (ExecutionException e) {
×
1535
            throw new IOException(e.getCause());
×
1536
        }
1537
        catch (TimeoutException e) {
×
1538
            throw new IOException(e);
×
1539
        }
1540
        catch (InterruptedException e) {
×
1541
            Thread.currentThread().interrupt();
×
1542
            throw new IOException(e);
×
1543
        }
1544
    }
1545

1546
    // Send a ping request and push a pong future on the queue.
1547
    // futures are completed in order, keep this one if a thread wants to wait
1548
    // for a specific pong. Note, if no pong returns the wait will not return
1549
    // without setting a timeout.
1550
    CompletableFuture<Boolean> sendPing(boolean treatAsInternal) {
1551
        if (!isConnectedOrConnecting()) {
1✔
1552
            CompletableFuture<Boolean> retVal = new CompletableFuture<>();
1✔
1553
            retVal.complete(Boolean.FALSE);
1✔
1554
            return retVal;
1✔
1555
        }
1556

1557
        if (!treatAsInternal && !this.needPing.get()) {
1✔
1558
            CompletableFuture<Boolean> retVal = new CompletableFuture<>();
1✔
1559
            retVal.complete(Boolean.TRUE);
1✔
1560
            this.needPing.set(true);
1✔
1561
            return retVal;
1✔
1562
        }
1563

1564
        int max = options.getMaxPingsOut();
1✔
1565
        if (max > 0 && pongQueue.size() + 1 > max) {
1✔
1566
            handleCommunicationIssue(new IllegalStateException("Max outgoing Ping count exceeded."));
1✔
1567
            return null;
1✔
1568
        }
1569

1570
        CompletableFuture<Boolean> pongFuture = new CompletableFuture<>();
1✔
1571
        pongQueue.add(pongFuture);
1✔
1572

1573
        if (treatAsInternal) {
1✔
1574
            queueInternalOutgoing(new ProtocolMessage(PING_PROTO));
1✔
1575
        } else {
1576
            queueOutgoing(new ProtocolMessage(PING_PROTO));
1✔
1577
        }
1578

1579
        this.needPing.set(true);
1✔
1580
        this.statistics.incrementPingCount();
1✔
1581
        return pongFuture;
1✔
1582
    }
1583

1584
    // This is a minor speed / memory enhancement.
1585
    // We can't reuse the same instance of any NatsMessage b/c of the "NatsMessage next" state
1586
    // But it is safe to share the data bytes and the size since those fields are just being read
1587
    // This constructor "ProtocolMessage(ProtocolMessage pm)" shares the data and size
1588
    // reducing allocation of data for something that is often created and used
1589
    // These static instances are the once that are used for copying, sendPing and sendPong
1590
    private static final ProtocolMessage PING_PROTO = new ProtocolMessage(OP_PING_BYTES);
1✔
1591
    private static final ProtocolMessage PONG_PROTO = new ProtocolMessage(OP_PONG_BYTES);
1✔
1592

1593
    void sendPong() {
1594
        queueInternalOutgoing(new ProtocolMessage(PONG_PROTO));
1✔
1595
    }
1✔
1596

1597
    // Called by the reader
1598
    void handlePong() {
1599
        CompletableFuture<Boolean> pongFuture = pongQueue.pollFirst();
1✔
1600
        if (pongFuture != null) {
1✔
1601
            pongFuture.complete(Boolean.TRUE);
1✔
1602
        }
1603
    }
1✔
1604

1605
    void readInitialInfo() throws IOException {
1606
        byte[] readBuffer = new byte[options.getBufferSize()];
1✔
1607
        ByteBuffer protocolBuffer = ByteBuffer.allocate(options.getBufferSize());
1✔
1608
        boolean gotCRLF = false;
1✔
1609
        boolean gotCR = false;
1✔
1610

1611
        while (!gotCRLF) {
1✔
1612
            int read = this.dataPort.read(readBuffer, 0, readBuffer.length);
1✔
1613

1614
            if (read < 0) {
1✔
1615
                break;
1✔
1616
            }
1617

1618
            int i = 0;
1✔
1619
            while (i < read) {
1✔
1620
                byte b = readBuffer[i++];
1✔
1621

1622
                if (gotCR) {
1✔
1623
                    if (b != LF) {
1✔
1624
                        throw new IOException("Missed LF after CR waiting for INFO.");
1✔
1625
                    } else if (i < read) {
1✔
1626
                        throw new IOException("Read past initial info message.");
1✔
1627
                    }
1628

1629
                    gotCRLF = true;
1✔
1630
                    break;
1✔
1631
                }
1632

1633
                if (b == CR) {
1✔
1634
                    gotCR = true;
1✔
1635
                } else {
1636
                    if (!protocolBuffer.hasRemaining()) {
1✔
1637
                        protocolBuffer = enlargeBuffer(protocolBuffer); // just double it
1✔
1638
                    }
1639
                    protocolBuffer.put(b);
1✔
1640
                }
1641
            }
1✔
1642
        }
1✔
1643

1644
        if (!gotCRLF) {
1✔
1645
            throw new IOException("Failed to read initial info message.");
1✔
1646
        }
1647

1648
        protocolBuffer.flip();
1✔
1649

1650
        String infoJson = UTF_8.decode(protocolBuffer).toString();
1✔
1651
        infoJson = infoJson.trim();
1✔
1652
        String[] msg = infoJson.split("\\s");
1✔
1653
        String op = msg[0].toUpperCase();
1✔
1654

1655
        if (!OP_INFO.equals(op)) {
1✔
1656
            throw new IOException("Received non-info initial message.");
1✔
1657
        }
1658

1659
        handleInfo(infoJson);
1✔
1660
    }
1✔
1661

1662
    void handleInfo(String infoJson) {
1663
        ServerInfo serverInfo = new ServerInfo(infoJson);
1✔
1664
        this.serverInfo.set(serverInfo);
1✔
1665

1666
        List<String> urls = this.serverInfo.get().getConnectURLs();
1✔
1667
        if (urls != null && !urls.isEmpty()) {
1✔
1668
            if (serverPool.acceptDiscoveredUrls(urls)) {
1✔
1669
                processConnectionEvent(Events.DISCOVERED_SERVERS);
1✔
1670
            }
1671
        }
1672

1673
        if (serverInfo.isLameDuckMode()) {
1✔
1674
            processConnectionEvent(Events.LAME_DUCK);
1✔
1675
        }
1676
    }
1✔
1677

1678
    void queueOutgoing(NatsMessage msg) {
1679
        if (msg.getControlLineLength() > this.options.getMaxControlLine()) {
1✔
1680
            throw new IllegalArgumentException("Control line is too long");
1✔
1681
        }
1682
        if (!writer.queue(msg)) {
1✔
1683
            options.getErrorListener().messageDiscarded(this, msg);
1✔
1684
        }
1685
    }
1✔
1686

1687
    void queueInternalOutgoing(NatsMessage msg) {
1688
        if (msg.getControlLineLength() > this.options.getMaxControlLine()) {
1✔
1689
            throw new IllegalArgumentException("Control line is too long");
×
1690
        }
1691
        this.writer.queueInternalMessage(msg);
1✔
1692
    }
1✔
1693

1694
    void deliverMessage(NatsMessage msg) {
1695
        this.needPing.set(false);
1✔
1696
        this.statistics.incrementInMsgs();
1✔
1697
        this.statistics.incrementInBytes(msg.getSizeInBytes());
1✔
1698

1699
        NatsSubscription sub = subscribers.get(msg.getSID());
1✔
1700

1701
        if (sub != null) {
1✔
1702
            msg.setSubscription(sub);
1✔
1703

1704
            NatsDispatcher d = sub.getNatsDispatcher();
1✔
1705
            NatsConsumer c = (d == null) ? sub : d;
1✔
1706
            MessageQueue q = ((d == null) ? sub.getMessageQueue() : d.getMessageQueue());
1✔
1707

1708
            if (c.hasReachedPendingLimits()) {
1✔
1709
                // Drop the message and count it
1710
                this.statistics.incrementDroppedCount();
1✔
1711
                c.incrementDroppedCount();
1✔
1712

1713
                // Notify the first time
1714
                if (!c.isMarkedSlow()) {
1✔
1715
                    c.markSlow();
1✔
1716
                    processSlowConsumer(c);
1✔
1717
                }
1718
            } else if (q != null) {
1✔
1719
                c.markNotSlow();
1✔
1720

1721
                // beforeQueueProcessor returns true if the message is allowed to be queued
1722
                if (sub.getBeforeQueueProcessor().apply(msg)) {
1✔
1723
                    q.push(msg);
1✔
1724
                }
1725
            }
1726

1727
        }
1728
//        else {
1729
//            // Drop messages we don't have a subscriber for (could be extras on an
1730
//            // auto-unsub for example)
1731
//        }
1732
    }
1✔
1733

1734
    void processOK() {
1735
        this.statistics.incrementOkCount();
1✔
1736
    }
1✔
1737

1738
    void processSlowConsumer(Consumer consumer) {
1739
        if (!this.callbackRunner.isShutdown()) {
1✔
1740
            try {
1741
                this.callbackRunner.execute(() -> {
1✔
1742
                    try {
1743
                        options.getErrorListener().slowConsumerDetected(this, consumer);
1✔
1744
                    } catch (Exception ex) {
1✔
1745
                        this.statistics.incrementExceptionCount();
1✔
1746
                    }
1✔
1747
                });
1✔
1748
            } catch (RejectedExecutionException re) {
×
1749
                // Timing with shutdown, let it go
1750
            }
1✔
1751
        }
1752
    }
1✔
1753

1754
    void processException(Exception exp) {
1755
        this.statistics.incrementExceptionCount();
1✔
1756

1757
        if (!this.callbackRunner.isShutdown()) {
1✔
1758
            try {
1759
                this.callbackRunner.execute(() -> {
1✔
1760
                    try {
1761
                        options.getErrorListener().exceptionOccurred(this, exp);
1✔
1762
                    } catch (Exception ex) {
1✔
1763
                        this.statistics.incrementExceptionCount();
1✔
1764
                    }
1✔
1765
                });
1✔
1766
            } catch (RejectedExecutionException re) {
1✔
1767
                // Timing with shutdown, let it go
1768
            }
1✔
1769
        }
1770
    }
1✔
1771

1772
    void processError(String errorText) {
1773
        this.statistics.incrementErrCount();
1✔
1774

1775
        this.lastError.set(errorText);
1✔
1776
        this.connectError.set(errorText); // even if this isn't during connection, save it just in case
1✔
1777

1778
        // If we are connected && we get an authentication error, save it
1779
        if (this.isConnected() && this.isAuthenticationError(errorText) && currentServer != null) {
1✔
1780
            this.serverAuthErrors.put(currentServer, errorText);
1✔
1781
        }
1782

1783
        if (!this.callbackRunner.isShutdown()) {
1✔
1784
            try {
1785
                this.callbackRunner.execute(() -> {
1✔
1786
                    try {
1787
                        options.getErrorListener().errorOccurred(this, errorText);
1✔
1788
                    } catch (Exception ex) {
1✔
1789
                        this.statistics.incrementExceptionCount();
1✔
1790
                    }
1✔
1791
                });
1✔
1792
            } catch (RejectedExecutionException re) {
×
1793
                // Timing with shutdown, let it go
1794
            }
1✔
1795
        }
1796
    }
1✔
1797

1798
    interface ErrorListenerCaller {
1799
        void call(Connection conn, ErrorListener el);
1800
    }
1801

1802
    void executeCallback(ErrorListenerCaller elc) {
1803
        if (!this.callbackRunner.isShutdown()) {
1✔
1804
            try {
1805
                this.callbackRunner.execute(() -> elc.call(this, options.getErrorListener()));
1✔
1806
            } catch (RejectedExecutionException re) {
×
1807
                // Timing with shutdown, let it go
1808
            }
1✔
1809
        }
1810
    }
1✔
1811

1812
    void processConnectionEvent(Events type) {
1813
        if (!this.callbackRunner.isShutdown()) {
1✔
1814
            try {
1815
                for (ConnectionListener listener : connectionListeners) {
1✔
1816
                    this.callbackRunner.execute(() -> {
1✔
1817
                        try {
1818
                            listener.connectionEvent(this, type);
1✔
1819
                        } catch (Exception ex) {
1✔
1820
                            this.statistics.incrementExceptionCount();
1✔
1821
                        }
1✔
1822
                    });
1✔
1823
                }
1✔
1824
            } catch (RejectedExecutionException re) {
×
1825
                // Timing with shutdown, let it go
1826
            }
1✔
1827
        }
1828
    }
1✔
1829

1830
    /**
1831
     * {@inheritDoc}
1832
     */
1833
    @Override
1834
    public ServerInfo getServerInfo() {
1835
        return getInfo();
1✔
1836
    }
1837

1838
    /**
1839
     * {@inheritDoc}
1840
     */
1841
    @Override
1842
    public InetAddress getClientInetAddress() {
1843
        try {
1844
            return InetAddress.getByName(getInfo().getClientIp());
1✔
1845
        }
1846
        catch (Exception e) {
×
1847
            return null;
×
1848
        }
1849
    }
1850

1851
    ServerInfo getInfo() {
1852
        return this.serverInfo.get();
1✔
1853
    }
1854

1855
    /**
1856
     * {@inheritDoc}
1857
     */
1858
    @Override
1859
    public Options getOptions() {
1860
        return this.options;
1✔
1861
    }
1862

1863
    /**
1864
     * {@inheritDoc}
1865
     */
1866
    @Override
1867
    public Statistics getStatistics() {
1868
        return this.statistics;
1✔
1869
    }
1870

1871
    StatisticsCollector getNatsStatistics() {
1872
        return this.statistics;
1✔
1873
    }
1874

1875
    DataPort getDataPort() {
1876
        return this.dataPort;
1✔
1877
    }
1878

1879
    // Used for testing
1880
    int getConsumerCount() {
1881
        return this.subscribers.size() + this.dispatchers.size();
1✔
1882
    }
1883

1884
    public long getMaxPayload() {
1885
        ServerInfo info = this.serverInfo.get();
1✔
1886

1887
        if (info == null) {
1✔
1888
            return -1;
×
1889
        }
1890

1891
        return info.getMaxPayload();
1✔
1892
    }
1893

1894
    /**
1895
     * Return the list of known server urls, including additional servers discovered
1896
     * after a connection has been established.
1897
     * @return this connection's list of known server URLs
1898
     */
1899
    public Collection<String> getServers() {
1900
        return serverPool.getServerList();
1✔
1901
    }
1902

1903
    protected List<NatsUri> resolveHost(NatsUri nuri) {
1904
        // 1. If the nuri host is not already an ip address or the nuri is not for websocket
1905
        //    let the pool resolve it.
1906
        List<NatsUri> results = new ArrayList<>();
1✔
1907
        if (!nuri.hostIsIpAddress() && !nuri.isWebsocket()) {
1✔
1908
            List<String> ips = serverPool.resolveHostToIps(nuri.getHost());
1✔
1909
            if (ips != null) {
1✔
1910
                for (String ip : ips) {
1✔
1911
                    try {
1912
                        results.add(nuri.reHost(ip));
1✔
1913
                    }
1914
                    catch (URISyntaxException u) {
1✔
1915
                        // ??? should never happen
1916
                    }
1✔
1917
                }
1✔
1918
            }
1919
        }
1920

1921
        // 2. If there were no results,
1922
        //    - host was already an ip address or
1923
        //    - host was for websocket or
1924
        //    - pool returned nothing or
1925
        //    - resolving failed...
1926
        //    so the list just becomes the original host.
1927
        if (results.isEmpty()) {
1✔
1928
            results.add(nuri);
1✔
1929
        }
1930
        return results;
1✔
1931
    }
1932

1933
    /**
1934
     * {@inheritDoc}
1935
     */
1936
    @Override
1937
    public String getConnectedUrl() {
1938
        return currentServer == null ? null : currentServer.toString();
1✔
1939
    }
1940

1941
    /**
1942
     * {@inheritDoc}
1943
     */
1944
    @Override
1945
    public Status getStatus() {
1946
        return this.status;
1✔
1947
    }
1948

1949
    /**
1950
     * {@inheritDoc}
1951
     */
1952
    @Override
1953
    public String getLastError() {
1954
        return this.lastError.get();
1✔
1955
    }
1956

1957
    /**
1958
     * {@inheritDoc}
1959
     */
1960
    @Override
1961
    public void clearLastError() {
1962
        this.lastError.set("");
1✔
1963
    }
1✔
1964

1965
    ExecutorService getExecutor() {
1966
        return executor;
1✔
1967
    }
1968

1969
    void updateStatus(Status newStatus) {
1970
        Status oldStatus = this.status;
1✔
1971

1972
        statusLock.lock();
1✔
1973
        try {
1974
            if (oldStatus == Status.CLOSED || newStatus == oldStatus) {
1✔
1975
                return;
1✔
1976
            }
1977
            this.status = newStatus;
1✔
1978
        } finally {
1979
            statusChanged.signalAll();
1✔
1980
            statusLock.unlock();
1✔
1981
        }
1982

1983
        if (this.status == Status.DISCONNECTED) {
1✔
1984
            processConnectionEvent(Events.DISCONNECTED);
1✔
1985
        } else if (this.status == Status.CLOSED) {
1✔
1986
            processConnectionEvent(Events.CLOSED);
1✔
1987
        } else if (oldStatus == Status.RECONNECTING && this.status == Status.CONNECTED) {
1✔
1988
            processConnectionEvent(Events.RECONNECTED);
1✔
1989
        } else if (this.status == Status.CONNECTED) {
1✔
1990
            processConnectionEvent(Events.CONNECTED);
1✔
1991
        }
1992
    }
1✔
1993

1994
    boolean isClosing() {
1995
        return this.closing;
1✔
1996
    }
1997

1998
    boolean isClosed() {
1999
        return this.status == Status.CLOSED;
1✔
2000
    }
2001

2002
    boolean isConnected() {
2003
        return this.status == Status.CONNECTED;
1✔
2004
    }
2005

2006
    boolean isDisconnected() {
2007
        return this.status == Status.DISCONNECTED;
×
2008
    }
2009

2010
    boolean isConnectedOrConnecting() {
2011
        statusLock.lock();
1✔
2012
        try {
2013
            return this.status == Status.CONNECTED || this.connecting;
1✔
2014
        } finally {
2015
            statusLock.unlock();
1✔
2016
        }
2017
    }
2018

2019
    boolean isDisconnectingOrClosed() {
2020
        statusLock.lock();
1✔
2021
        try {
2022
            return this.status == Status.CLOSED || this.disconnecting;
1✔
2023
        } finally {
2024
            statusLock.unlock();
1✔
2025
        }
2026
    }
2027

2028
    boolean isDisconnecting() {
2029
        statusLock.lock();
1✔
2030
        try {
2031
            return this.disconnecting;
1✔
2032
        } finally {
2033
            statusLock.unlock();
1✔
2034
        }
2035
    }
2036

2037
    void waitForDisconnectOrClose(Duration timeout) throws InterruptedException {
2038
        waitFor(timeout, (Void) -> this.isDisconnecting() && !this.isClosed() );
1✔
2039
    }
1✔
2040

2041
    void waitForConnectOrClose(Duration timeout) throws InterruptedException {
2042
        waitFor(timeout, (Void) -> !this.isConnected() && !this.isClosed());
1✔
2043
    }
1✔
2044

2045
    void waitFor(Duration timeout, Predicate<Void> test) throws InterruptedException {
2046
        statusLock.lock();
1✔
2047
        try {
2048
            long currentWaitNanos = (timeout != null) ? timeout.toNanos() : -1;
1✔
2049
            long start = NatsSystemClock.nanoTime();
1✔
2050
            while (currentWaitNanos >= 0 && test.test(null)) {
1✔
2051
                if (currentWaitNanos > 0) {
1✔
2052
                    statusChanged.await(currentWaitNanos, TimeUnit.NANOSECONDS);
1✔
2053
                    long now = NatsSystemClock.nanoTime();
1✔
2054
                    currentWaitNanos = currentWaitNanos - (now - start);
1✔
2055
                    start = now;
1✔
2056

2057
                    if (currentWaitNanos <= 0) {
1✔
2058
                        break;
1✔
2059
                    }
2060
                } else {
1✔
2061
                    statusChanged.await();
×
2062
                }
2063
            }
2064
        } finally {
2065
            statusLock.unlock();
1✔
2066
        }
2067
    }
1✔
2068

2069
    void invokeReconnectDelayHandler(long totalRounds) {
2070
        long currentWaitNanos = 0;
1✔
2071

2072
        ReconnectDelayHandler handler = options.getReconnectDelayHandler();
1✔
2073
        if (handler == null) {
1✔
2074
            Duration dur = options.getReconnectWait();
1✔
2075
            if (dur != null) {
1✔
2076
                currentWaitNanos = dur.toNanos();
1✔
2077
                dur = serverPool.hasSecureServer() ? options.getReconnectJitterTls() : options.getReconnectJitter();
1✔
2078
                if (dur != null) {
1✔
2079
                    currentWaitNanos += ThreadLocalRandom.current().nextLong(dur.toNanos());
1✔
2080
                }
2081
            }
2082
        }
1✔
2083
        else {
2084
            Duration waitTime = handler.getWaitTime(totalRounds);
1✔
2085
            if (waitTime != null) {
1✔
2086
                currentWaitNanos = waitTime.toNanos();
1✔
2087
            }
2088
        }
2089

2090
        this.reconnectWaiter = new CompletableFuture<>();
1✔
2091

2092
        long start = NatsSystemClock.nanoTime();
1✔
2093
        while (currentWaitNanos > 0 && !isDisconnectingOrClosed() && !isConnected() && !this.reconnectWaiter.isDone()) {
1✔
2094
            try {
2095
                this.reconnectWaiter.get(currentWaitNanos, TimeUnit.NANOSECONDS);
×
2096
            } catch (Exception exp) {
1✔
2097
                // ignore, try to loop again
2098
            }
×
2099
            long now = NatsSystemClock.nanoTime();
1✔
2100
            currentWaitNanos = currentWaitNanos - (now - start);
1✔
2101
            start = now;
1✔
2102
        }
1✔
2103

2104
        this.reconnectWaiter.complete(Boolean.TRUE);
1✔
2105
    }
1✔
2106

2107
    ByteBuffer enlargeBuffer(ByteBuffer buffer) {
2108
        int current = buffer.capacity();
1✔
2109
        int newSize = current * 2;
1✔
2110
        ByteBuffer newBuffer = ByteBuffer.allocate(newSize);
1✔
2111
        buffer.flip();
1✔
2112
        newBuffer.put(buffer);
1✔
2113
        return newBuffer;
1✔
2114
    }
2115

2116
    // For testing
2117
    NatsConnectionReader getReader() {
2118
        return this.reader;
1✔
2119
    }
2120

2121
    // For testing
2122
    NatsConnectionWriter getWriter() {
2123
        return this.writer;
1✔
2124
    }
2125

2126
    // For testing
2127
    Future<DataPort> getDataPortFuture() {
2128
        return this.dataPortFuture;
1✔
2129
    }
2130

2131
    boolean isDraining() {
2132
        return this.draining.get() != null;
1✔
2133
    }
2134

2135
    boolean isDrained() {
2136
        CompletableFuture<Boolean> tracker = this.draining.get();
1✔
2137

2138
        try {
2139
            if (tracker != null && tracker.getNow(false)) {
1✔
2140
                return true;
1✔
2141
            }
2142
        } catch (Exception e) {
×
2143
            // These indicate the tracker was cancelled/timed out
2144
        }
1✔
2145

2146
        return false;
1✔
2147
    }
2148

2149
    /**
2150
     * {@inheritDoc}
2151
     */
2152
    @Override
2153
    public CompletableFuture<Boolean> drain(Duration timeout) throws TimeoutException, InterruptedException {
2154

2155
        if (isClosing() || isClosed()) {
1✔
2156
            throw new IllegalStateException("A connection can't be drained during close.");
1✔
2157
        }
2158

2159
        this.statusLock.lock();
1✔
2160
        try {
2161
            if (isDraining()) {
1✔
2162
                return this.draining.get();
1✔
2163
            }
2164
            this.draining.set(new CompletableFuture<>());
1✔
2165
        } finally {
2166
            this.statusLock.unlock();
1✔
2167
        }
2168

2169
        final CompletableFuture<Boolean> tracker = this.draining.get();
1✔
2170
        Instant start = Instant.now();
1✔
2171

2172
        // Don't include subscribers with dispatchers
2173
        HashSet<NatsSubscription> pureSubscribers = new HashSet<>(this.subscribers.values());
1✔
2174
        pureSubscribers.removeIf((s) -> s.getDispatcher() != null);
1✔
2175

2176
        final HashSet<NatsConsumer> consumers = new HashSet<>();
1✔
2177
        consumers.addAll(pureSubscribers);
1✔
2178
        consumers.addAll(this.dispatchers.values());
1✔
2179

2180
        NatsDispatcher inboxer = this.inboxDispatcher.get();
1✔
2181

2182
        if (inboxer != null) {
1✔
2183
            consumers.add(inboxer);
1✔
2184
        }
2185

2186
        // Stop the consumers NOW so that when this method returns they are blocked
2187
        consumers.forEach((cons) -> {
1✔
2188
            cons.markDraining(tracker);
1✔
2189
            cons.sendUnsubForDrain();
1✔
2190
        });
1✔
2191

2192
        try {
2193
            this.flush(timeout); // Flush and wait up to the timeout, if this fails, let the caller know
1✔
2194
        } catch (Exception e) {
1✔
2195
            this.close(false, false);
1✔
2196
            throw e;
1✔
2197
        }
1✔
2198

2199
        consumers.forEach(NatsConsumer::markUnsubedForDrain);
1✔
2200

2201
        // Wait for the timeout or the pending count to go to 0
2202
        executor.submit(() -> {
1✔
2203
            try {
2204
                long stop = (timeout == null || timeout.equals(Duration.ZERO))
1✔
2205
                    ? Long.MAX_VALUE
2206
                    : NatsSystemClock.nanoTime() + timeout.toNanos();
1✔
2207
                while (NatsSystemClock.nanoTime() < stop && !Thread.interrupted())
1✔
2208
                {
2209
                    consumers.removeIf(NatsConsumer::isDrained);
1✔
2210
                    if (consumers.isEmpty()) {
1✔
2211
                        break;
1✔
2212
                    }
2213
                    //noinspection BusyWait
2214
                    Thread.sleep(1); // Sleep 1 milli
1✔
2215
                }
2216

2217
                // Stop publishing
2218
                this.blockPublishForDrain.set(true);
1✔
2219

2220
                // One last flush
2221
                if (timeout == null || timeout.equals(Duration.ZERO)) {
1✔
2222
                    this.flush(Duration.ZERO);
1✔
2223
                } else {
2224
                    Instant now = Instant.now();
1✔
2225
                    Duration passed = Duration.between(start, now);
1✔
2226
                    Duration newTimeout = timeout.minus(passed);
1✔
2227
                    if (newTimeout.toNanos() > 0) {
1✔
2228
                        this.flush(newTimeout);
1✔
2229
                    }
2230
                }
2231
                this.close(false, false); // close the connection after the last flush
1✔
2232
                tracker.complete(consumers.isEmpty());
1✔
2233
            } catch (TimeoutException e) {
×
2234
                this.processException(e);
×
2235
            } catch (InterruptedException e) {
×
2236
                this.processException(e);
×
2237
                Thread.currentThread().interrupt();
×
2238
            } finally {
2239
                try {
2240
                    this.close(false, false);// close the connection after the last flush
1✔
2241
                } catch (InterruptedException e) {
×
2242
                    processException(e);
×
2243
                    Thread.currentThread().interrupt();
×
2244
                }
1✔
2245
                tracker.complete(false);
1✔
2246
            }
2247
        });
1✔
2248

2249
        return tracker;
1✔
2250
    }
2251

2252
    boolean isAuthenticationError(String err) {
2253
        if (err == null) {
1✔
2254
            return false;
1✔
2255
        }
2256
        err = err.toLowerCase();
1✔
2257
        return err.startsWith("user authentication")
1✔
2258
            || err.contains("authorization violation")
1✔
2259
            || err.startsWith("account authentication expired");
1✔
2260
    }
2261

2262
    /**
2263
     * {@inheritDoc}
2264
     */
2265
    @Override
2266
    public void flushBuffer() throws IOException {
2267
        if (!isConnected()) {
1✔
2268
            throw new IllegalStateException("Connection is not active.");
1✔
2269
        }
2270
        writer.flushBuffer();
1✔
2271
    }
1✔
2272

2273
    /**
2274
     * {@inheritDoc}
2275
     */
2276
    @Override
2277
    public StreamContext getStreamContext(String streamName) throws IOException, JetStreamApiException {
2278
        Validator.validateStreamName(streamName, true);
1✔
2279
        ensureNotClosing();
1✔
2280
        return new NatsStreamContext(streamName, null, this, null);
1✔
2281
    }
2282

2283
    /**
2284
     * {@inheritDoc}
2285
     */
2286
    @Override
2287
    public StreamContext getStreamContext(String streamName, JetStreamOptions options) throws IOException, JetStreamApiException {
2288
        Validator.validateStreamName(streamName, true);
1✔
2289
        ensureNotClosing();
1✔
2290
        return new NatsStreamContext(streamName, null, this, options);
1✔
2291
    }
2292

2293
    /**
2294
     * {@inheritDoc}
2295
     */
2296
    @Override
2297
    public ConsumerContext getConsumerContext(String streamName, String consumerName) throws IOException, JetStreamApiException {
2298
        return getStreamContext(streamName).getConsumerContext(consumerName);
1✔
2299
    }
2300

2301
    /**
2302
     * {@inheritDoc}
2303
     */
2304
    @Override
2305
    public ConsumerContext getConsumerContext(String streamName, String consumerName, JetStreamOptions options) throws IOException, JetStreamApiException {
2306
        return getStreamContext(streamName, options).getConsumerContext(consumerName);
1✔
2307
    }
2308

2309
    /**
2310
     * {@inheritDoc}
2311
     */
2312
    @Override
2313
    public JetStream jetStream() throws IOException {
2314
        ensureNotClosing();
1✔
2315
        return new NatsJetStream(this, null);
1✔
2316
    }
2317

2318
    /**
2319
     * {@inheritDoc}
2320
     */
2321
    @Override
2322
    public JetStream jetStream(JetStreamOptions options) throws IOException {
2323
        ensureNotClosing();
1✔
2324
        return new NatsJetStream(this, options);
1✔
2325
    }
2326

2327
    /**
2328
     * {@inheritDoc}
2329
     */
2330
    @Override
2331
    public JetStreamManagement jetStreamManagement() throws IOException {
2332
        ensureNotClosing();
1✔
2333
        return new NatsJetStreamManagement(this, null);
1✔
2334
    }
2335

2336
    /**
2337
     * {@inheritDoc}
2338
     */
2339
    @Override
2340
    public JetStreamManagement jetStreamManagement(JetStreamOptions options) throws IOException {
2341
        ensureNotClosing();
1✔
2342
        return new NatsJetStreamManagement(this, options);
1✔
2343
    }
2344

2345
    /**
2346
     * {@inheritDoc}
2347
     */
2348
    @Override
2349
    public KeyValue keyValue(String bucketName) throws IOException {
2350
        Validator.validateBucketName(bucketName, true);
1✔
2351
        ensureNotClosing();
1✔
2352
        return new NatsKeyValue(this, bucketName, null);
1✔
2353
    }
2354

2355
    /**
2356
     * {@inheritDoc}
2357
     */
2358
    @Override
2359
    public KeyValue keyValue(String bucketName, KeyValueOptions options) throws IOException {
2360
        Validator.validateBucketName(bucketName, true);
1✔
2361
        ensureNotClosing();
1✔
2362
        return new NatsKeyValue(this, bucketName, options);
1✔
2363
    }
2364

2365
    /**
2366
     * {@inheritDoc}
2367
     */
2368
    @Override
2369
    public KeyValueManagement keyValueManagement() throws IOException {
2370
        ensureNotClosing();
1✔
2371
        return new NatsKeyValueManagement(this, null);
1✔
2372
    }
2373

2374
    /**
2375
     * {@inheritDoc}
2376
     */
2377
    @Override
2378
    public KeyValueManagement keyValueManagement(KeyValueOptions options) throws IOException {
2379
        ensureNotClosing();
1✔
2380
        return new NatsKeyValueManagement(this, options);
1✔
2381
    }
2382

2383
    /**
2384
     * {@inheritDoc}
2385
     */
2386
    @Override
2387
    public ObjectStore objectStore(String bucketName) throws IOException {
2388
        Validator.validateBucketName(bucketName, true);
1✔
2389
        ensureNotClosing();
1✔
2390
        return new NatsObjectStore(this, bucketName, null);
1✔
2391
    }
2392

2393
    /**
2394
     * {@inheritDoc}
2395
     */
2396
    @Override
2397
    public ObjectStore objectStore(String bucketName, ObjectStoreOptions options) throws IOException {
2398
        Validator.validateBucketName(bucketName, true);
1✔
2399
        ensureNotClosing();
1✔
2400
        return new NatsObjectStore(this, bucketName, options);
1✔
2401
    }
2402

2403
    /**
2404
     * {@inheritDoc}
2405
     */
2406
    @Override
2407
    public ObjectStoreManagement objectStoreManagement() throws IOException {
2408
        ensureNotClosing();
1✔
2409
        return new NatsObjectStoreManagement(this, null);
1✔
2410
    }
2411

2412
    /**
2413
     * {@inheritDoc}
2414
     */
2415
    @Override
2416
    public ObjectStoreManagement objectStoreManagement(ObjectStoreOptions options) throws IOException {
2417
        ensureNotClosing();
1✔
2418
        return new NatsObjectStoreManagement(this, options);
1✔
2419
    }
2420

2421
    private void ensureNotClosing() throws IOException {
2422
        if (isClosing() || isClosed()) {
1✔
2423
            throw new IOException("A JetStream context can't be established during close.");
1✔
2424
        }
2425
    }
1✔
2426
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc