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

nats-io / nats.java / #2017

27 Jun 2025 04:11PM UTC coverage: 95.598% (-0.07%) from 95.671%
#2017

push

github

web-flow
Merge pull request #1340 from nats-io/flapper-test-overflow-fetch

Fix flapping test: testOverflowFetch

11749 of 12290 relevant lines covered (95.6%)

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
    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)",
×
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✔
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
1✔
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
        queueOutgoing(new ProtocolMessage(bab, true));
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
        // setting this to filter on stop.
1111
        // if it's an "internal" message, it won't be filtered
1112
        // if it's a normal message, the subscription will already be registered
1113
        // and therefore will be re-subscribed after a stop anyway
1114
        ProtocolMessage subMsg = new ProtocolMessage(bab, true);
1✔
1115
        if (treatAsInternal) {
1✔
1116
            queueInternalOutgoing(subMsg);
1✔
1117
        } else {
1118
            queueOutgoing(subMsg);
1✔
1119
        }
1120
    }
1✔
1121

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

1130
    int getRespInboxLength() {
1131
        return options.getInboxPrefix().length() + 22 + 1; // 22 for nuid, 1 for .
1✔
1132
    }
1133

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

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

1149
    void cleanResponses(boolean closing) {
1150
        ArrayList<String> toRemove = new ArrayList<>();
1✔
1151
        boolean wasInterrupted = false;
1✔
1152

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

1182
            if (remove) {
1✔
1183
                toRemove.add(entry.getKey());
1✔
1184
                statistics.decrementOutstandingRequests();
1✔
1185
            }
1186
        }
1✔
1187

1188
        for (String key : toRemove) {
1✔
1189
            responsesAwaiting.remove(key);
1✔
1190
        }
1✔
1191

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

1202
            for (String token : toRemove) {
1✔
1203
                responsesRespondedTo.remove(token);
1✔
1204
            }
1✔
1205
        }
1206
    }
1✔
1207

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

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

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

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

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

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

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

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

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

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

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

1297
        if (isClosed()) {
1✔
1298
            throw new IllegalStateException("Connection is Closed");
1✔
1299
        } else if (isDraining()) {
1✔
1300
            throw new IllegalStateException("Connection is Draining");
1✔
1301
        }
1302

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

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

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

1328
        if (!oldStyle) {
1✔
1329
            responsesAwaiting.put(responseToken, future);
1✔
1330
        }
1331
        statistics.incrementOutstandingRequests();
1✔
1332

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

1346
        publishInternal(subject, responseInbox, headers, data, validateSubjectAndReplyTo, flushImmediatelyAfterPublish);
1✔
1347
        statistics.incrementRequestsSent();
1✔
1348

1349
        return future;
1✔
1350
    }
1351

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

1392
    public Dispatcher createDispatcher() {
1393
        return createDispatcher(null);
1✔
1394
    }
1395

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

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

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

1417
        NatsDispatcher nd = ((NatsDispatcher) d);
1✔
1418

1419
        if (nd.isDraining()) {
1✔
1420
            return; // No op while draining
1✔
1421
        }
1422

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

1427
        cleanupDispatcher(nd);
1✔
1428
    }
1✔
1429

1430
    void cleanupDispatcher(NatsDispatcher nd) {
1431
        nd.stop(true);
1✔
1432
        this.dispatchers.remove(nd.getId());
1✔
1433
    }
1✔
1434

1435
    Map<String, Dispatcher> getDispatchers() {
1436
        return Collections.unmodifiableMap(dispatchers);
1✔
1437
    }
1438

1439
    public void addConnectionListener(ConnectionListener connectionListener) {
1440
        connectionListeners.add(connectionListener);
1✔
1441
    }
1✔
1442

1443
    public void removeConnectionListener(ConnectionListener connectionListener) {
1444
        connectionListeners.remove(connectionListener);
1✔
1445
    }
1✔
1446

1447
    public void flush(Duration timeout) throws TimeoutException, InterruptedException {
1448

1449
        Instant start = Instant.now();
1✔
1450
        waitForConnectOrClose(timeout);
1✔
1451

1452
        if (isClosed()) {
1✔
1453
            throw new TimeoutException("Attempted to flush while closed");
1✔
1454
        }
1455

1456
        if (timeout == null) {
1✔
1457
            timeout = Duration.ZERO;
1✔
1458
        }
1459

1460
        Instant now = Instant.now();
1✔
1461
        Duration waitTime = Duration.between(start, now);
1✔
1462

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

1467
        try {
1468
            Future<Boolean> waitForIt = sendPing();
1✔
1469

1470
            if (waitForIt == null) { // error in the send ping code
1✔
1471
                return;
×
1472
            }
1473

1474
            long nanos = timeout.toNanos();
1✔
1475

1476
            if (nanos > 0) {
1✔
1477

1478
                nanos -= waitTime.toNanos();
1✔
1479

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

1484
                waitForIt.get(nanos, TimeUnit.NANOSECONDS);
1✔
1485
            } else {
1486
                waitForIt.get();
1✔
1487
            }
1488

1489
            this.statistics.incrementFlushCounter();
1✔
1490
        } catch (ExecutionException | CancellationException e) {
1✔
1491
            throw new TimeoutException(e.toString());
1✔
1492
        }
1✔
1493
    }
1✔
1494

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

1511
    CompletableFuture<Boolean> sendPing() {
1512
        return this.sendPing(true);
1✔
1513
    }
1514

1515
    CompletableFuture<Boolean> softPing() {
1516
        return this.sendPing(false);
1✔
1517
    }
1518

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

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

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

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

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

1573
        CompletableFuture<Boolean> pongFuture = new CompletableFuture<>();
1✔
1574
        pongQueue.add(pongFuture);
1✔
1575

1576
        if (treatAsInternal) {
1✔
1577
            queueInternalOutgoing(new ProtocolMessage(PING_PROTO));
1✔
1578
        } else {
1579
            queueOutgoing(new ProtocolMessage(PING_PROTO));
1✔
1580
        }
1581

1582
        this.needPing.set(true);
1✔
1583
        this.statistics.incrementPingCount();
1✔
1584
        return pongFuture;
1✔
1585
    }
1586

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

1596
    void sendPong() {
1597
        queueInternalOutgoing(new ProtocolMessage(PONG_PROTO));
1✔
1598
    }
1✔
1599

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

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

1614
        while (!gotCRLF) {
1✔
1615
            int read = this.dataPort.read(readBuffer, 0, readBuffer.length);
1✔
1616

1617
            if (read < 0) {
1✔
1618
                break;
1✔
1619
            }
1620

1621
            int i = 0;
1✔
1622
            while (i < read) {
1✔
1623
                byte b = readBuffer[i++];
1✔
1624

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

1632
                    gotCRLF = true;
1✔
1633
                    break;
1✔
1634
                }
1635

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

1647
        if (!gotCRLF) {
1✔
1648
            throw new IOException("Failed to read initial info message.");
1✔
1649
        }
1650

1651
        protocolBuffer.flip();
1✔
1652

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

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

1662
        handleInfo(infoJson);
1✔
1663
    }
1✔
1664

1665
    void handleInfo(String infoJson) {
1666
        ServerInfo serverInfo = new ServerInfo(infoJson);
1✔
1667
        this.serverInfo.set(serverInfo);
1✔
1668

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

1676
        if (serverInfo.isLameDuckMode()) {
1✔
1677
            processConnectionEvent(Events.LAME_DUCK);
1✔
1678
        }
1679
    }
1✔
1680

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

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

1697
    void deliverMessage(NatsMessage msg) {
1698
        this.needPing.set(false);
1✔
1699
        this.statistics.incrementInMsgs();
1✔
1700
        this.statistics.incrementInBytes(msg.getSizeInBytes());
1✔
1701

1702
        NatsSubscription sub = subscribers.get(msg.getSID());
1✔
1703

1704
        if (sub != null) {
1✔
1705
            msg.setSubscription(sub);
1✔
1706

1707
            NatsDispatcher d = sub.getNatsDispatcher();
1✔
1708
            NatsConsumer c = (d == null) ? sub : d;
1✔
1709
            MessageQueue q = ((d == null) ? sub.getMessageQueue() : d.getMessageQueue());
1✔
1710

1711
            if (c.hasReachedPendingLimits()) {
1✔
1712
                // Drop the message and count it
1713
                this.statistics.incrementDroppedCount();
1✔
1714
                c.incrementDroppedCount();
1✔
1715

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

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

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

1737
    void processOK() {
1738
        this.statistics.incrementOkCount();
1✔
1739
    }
1✔
1740

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

1757
    void processException(Exception exp) {
1758
        this.statistics.incrementExceptionCount();
1✔
1759

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

1775
    void processError(String errorText) {
1776
        this.statistics.incrementErrCount();
1✔
1777

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

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

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

1801
    interface ErrorListenerCaller {
1802
        void call(Connection conn, ErrorListener el);
1803
    }
1804

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

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

1833
    /**
1834
     * {@inheritDoc}
1835
     */
1836
    @Override
1837
    public ServerInfo getServerInfo() {
1838
        return getInfo();
1✔
1839
    }
1840

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

1854
    ServerInfo getInfo() {
1855
        return this.serverInfo.get();
1✔
1856
    }
1857

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

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

1874
    StatisticsCollector getNatsStatistics() {
1875
        return this.statistics;
1✔
1876
    }
1877

1878
    DataPort getDataPort() {
1879
        return this.dataPort;
1✔
1880
    }
1881

1882
    // Used for testing
1883
    int getConsumerCount() {
1884
        return this.subscribers.size() + this.dispatchers.size();
1✔
1885
    }
1886

1887
    public long getMaxPayload() {
1888
        ServerInfo info = this.serverInfo.get();
1✔
1889

1890
        if (info == null) {
1✔
1891
            return -1;
×
1892
        }
1893

1894
        return info.getMaxPayload();
1✔
1895
    }
1896

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

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

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

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

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

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

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

1968
    ExecutorService getExecutor() {
1969
        return executor;
1✔
1970
    }
1971

1972
    void updateStatus(Status newStatus) {
1973
        Status oldStatus = this.status;
1✔
1974

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

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

1997
    boolean isClosing() {
1998
        return this.closing;
1✔
1999
    }
2000

2001
    boolean isClosed() {
2002
        return this.status == Status.CLOSED;
1✔
2003
    }
2004

2005
    boolean isConnected() {
2006
        return this.status == Status.CONNECTED;
1✔
2007
    }
2008

2009
    boolean isDisconnected() {
2010
        return this.status == Status.DISCONNECTED;
×
2011
    }
2012

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

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

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

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

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

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

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

2072
    void invokeReconnectDelayHandler(long totalRounds) {
2073
        long currentWaitNanos = 0;
1✔
2074

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

2093
        this.reconnectWaiter = new CompletableFuture<>();
1✔
2094

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

2107
        this.reconnectWaiter.complete(Boolean.TRUE);
1✔
2108
    }
1✔
2109

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

2119
    // For testing
2120
    NatsConnectionReader getReader() {
2121
        return this.reader;
1✔
2122
    }
2123

2124
    // For testing
2125
    NatsConnectionWriter getWriter() {
2126
        return this.writer;
1✔
2127
    }
2128

2129
    // For testing
2130
    Future<DataPort> getDataPortFuture() {
2131
        return this.dataPortFuture;
1✔
2132
    }
2133

2134
    boolean isDraining() {
2135
        return this.draining.get() != null;
1✔
2136
    }
2137

2138
    boolean isDrained() {
2139
        CompletableFuture<Boolean> tracker = this.draining.get();
1✔
2140

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

2149
        return false;
1✔
2150
    }
2151

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

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

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

2172
        final CompletableFuture<Boolean> tracker = this.draining.get();
1✔
2173
        Instant start = Instant.now();
1✔
2174

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

2179
        final HashSet<NatsConsumer> consumers = new HashSet<>();
1✔
2180
        consumers.addAll(pureSubscribers);
1✔
2181
        consumers.addAll(this.dispatchers.values());
1✔
2182

2183
        NatsDispatcher inboxer = this.inboxDispatcher.get();
1✔
2184

2185
        if (inboxer != null) {
1✔
2186
            consumers.add(inboxer);
1✔
2187
        }
2188

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

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

2202
        consumers.forEach(NatsConsumer::markUnsubedForDrain);
1✔
2203

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

2220
                // Stop publishing
2221
                this.blockPublishForDrain.set(true);
1✔
2222

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

2252
        return tracker;
1✔
2253
    }
2254

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2424
    private void ensureNotClosing() throws IOException {
2425
        if (isClosing() || isClosed()) {
1✔
2426
            throw new IOException("A JetStream context can't be established during close.");
1✔
2427
        }
2428
    }
1✔
2429
}
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