-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ConnectionManagerTest.java
771 lines (684 loc) · 22.8 KB
/
ConnectionManagerTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.test.core.net;
import io.netty.channel.Channel;
import io.netty.channel.embedded.EmbeddedChannel;
import io.vertx.core.Vertx;
import io.vertx.core.http.impl.pool.*;
import io.vertx.core.impl.ContextImpl;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.net.SocketAddress;
import io.vertx.test.core.VertxTestBase;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class ConnectionManagerTest extends VertxTestBase {
private static final SocketAddress TEST_ADDRESS = SocketAddress.inetSocketAddress(8080, "localhost");
class FakeConnectionManager {
private final FakeConnectionProvider connector;
private final int queueMaxSize;
private final int maxPoolSize;
private Pool<FakeConnection> pool;
private int size;
private Set<FakeConnection> active = new HashSet<>();
private boolean closed = true;
private int seq;
FakeConnectionManager(int queueMaxSize, int maxPoolSize, FakeConnectionProvider connector) {
this.queueMaxSize = queueMaxSize;
this.maxPoolSize = maxPoolSize;
this.connector = connector;
}
synchronized int sequence() {
return seq;
}
synchronized boolean closed() {
return closed;
}
synchronized boolean contains(FakeConnection conn) {
return active.contains(conn);
}
synchronized int size() {
return size;
}
synchronized Pool<FakeConnection> pool() {
return pool;
}
void getConnection(Waiter<FakeConnection> waiter) {
synchronized (this) {
if (closed) {
seq++;
closed = false;
pool = new Pool<>(
connector,
queueMaxSize,
maxPoolSize,
v -> {
synchronized (FakeConnectionManager.this) {
closed = true;
}
}, (channel, conn) -> {
synchronized (FakeConnectionManager.this) {
active.add(conn);
size++;
}
}, (channel, conn) -> {
synchronized (FakeConnectionManager.this) {
size--;
active.remove(conn);
}
}
);
}
}
pool.getConnection(waiter);
}
}
@Test
public void testConnectSuccess() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 4, connector);
AtomicReference<Boolean> initLock = new AtomicReference<>();
AtomicReference<Boolean> handleLock = new AtomicReference<>();
FakeWaiter waiter = new FakeWaiter() {
@Override
public synchronized void initConnection(ContextInternal ctx, FakeConnection conn) {
assertNull(Vertx.currentContext());
assertSame(ctx, context);
Pool<FakeConnection> pool = mgr.pool();
initLock.set(Thread.holdsLock(pool));
super.initConnection(ctx, conn);
}
@Override
public synchronized boolean handleConnection(ContextInternal ctx, FakeConnection conn) throws Exception {
assertNull(Vertx.currentContext());
assertSame(ctx, context);
Pool<FakeConnection> pool = mgr.pool();
handleLock.set(Thread.holdsLock(pool));
return super.handleConnection(ctx, conn);
}
};
mgr.getConnection(waiter);
FakeConnection conn = connector.assertRequest();
conn.connect();
assertWaitUntil(waiter::isComplete);
assertEquals(Boolean.FALSE, handleLock.get());
assertEquals(Boolean.FALSE, initLock.get());
waiter.assertInitialized(conn);
waiter.assertSuccess(conn);
waiter.recycle();
assertEquals(0, mgr.size());
assertTrue(mgr.closed());
}
@Test
public void testConnectFailure() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 4, connector);
AtomicReference<Boolean> holdsLock = new AtomicReference<>();
FakeWaiter waiter = new FakeWaiter() {
@Override
public synchronized void handleFailure(ContextInternal ctx, Throwable failure) {
assertNull(Vertx.currentContext());
assertSame(ctx, context);
Pool<FakeConnection> pool = mgr.pool();
holdsLock.set(Thread.holdsLock(pool));
super.handleFailure(ctx, failure);
}
};
mgr.getConnection(waiter);
FakeConnection conn = connector.assertRequest();
Throwable failure = new Throwable();
conn.fail(failure);
assertWaitUntil(waiter::isComplete);
assertEquals(Boolean.FALSE, holdsLock.get());
waiter.assertNotInitialized();
waiter.assertFailure(failure);
}
@Test
public void testConnectPoolEmptyWaiterCancelledAfterConnectRequest() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 3, connector);
FakeWaiter waiter = new FakeWaiter();
mgr.getConnection(waiter);
FakeConnection conn = connector.assertRequest();
waiter.cancel();
conn.connect();
waitUntil(() -> mgr.size() == 1);
waiter.assertInitialized(conn);
assertTrue(waiter.isComplete());
assertFalse(waiter.isSuccess());
assertFalse(waiter.isFailure());
assertTrue(mgr.contains(conn));
}
@Test
public void testConnectionFailure() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 3, connector);
FakeWaiter waiter = new FakeWaiter();
mgr.getConnection(waiter);
FakeConnection conn = connector.assertRequest();
Exception expected = new Exception();
conn.fail(expected);
assertWaitUntil(waiter::isComplete);
waiter.assertFailure(expected);
assertTrue(waiter.isFailure());
}
@Test
public void testRecycleConnection() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 1, connector);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection(waiter1);
FakeConnection conn = connector.assertRequest();
conn.connect();
assertWaitUntil(waiter1::isComplete);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection(waiter2);
connector.assertRequests(0);
waiter1.recycle();
assertWaitUntil(waiter2::isComplete);
waiter2.assertSuccess(conn);
}
/*
@Test
public void testRecycleClosedConnection() {
FakeConnnectionPool pool = new FakeConnnectionPool(1);
FakeConnectionProvider provider = new FakeConnectionProvider();
ConnectionManager<FakeConnection> mgr = new ConnectionManager<>(null, provider, pool, 3);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection("localhost", false, 8080, "localhost", waiter1);
FakeConnection conn = provider.assertRequest(TEST_ADDRESS);
conn.connect();
assertWaitUntil(waiter1::isComplete);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection("localhost", false, 8080, "localhost", waiter2);
provider.assertRequests(TEST_ADDRESS, 0);
conn.close();
conn.recycle();
// assertWaitUntil(waiter2::isComplete);
// waiter2.assertSuccess(conn);
}
*/
@Test
public void testRecycleInvalidConnection() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 1, connector);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection(waiter1);
FakeConnection conn = connector.assertRequest();
conn.connect();
waitUntil(waiter1::isComplete);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection(waiter2);
conn.invalidate();
waiter1.recycle();
waitUntil(() -> connector.requests(TEST_ADDRESS) == 1);
assertFalse(mgr.closed());
FakeConnection conn2 = connector.assertRequest();
conn2.connect();
waitUntil(waiter2::isSuccess);
}
@Test
public void testWaiterThrowsException() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 1, connector);
Exception failure = new Exception();
FakeWaiter waiter = new FakeWaiter() {
@Override
public synchronized boolean handleConnection(ContextInternal ctx, FakeConnection conn) throws Exception {
throw failure;
}
};
mgr.getConnection(waiter);
FakeConnection conn = connector.assertRequest();
conn.connect();
assertEquals(0, mgr.size());
}
@Test
public void testEndpointLifecycle() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 1, connector);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection(waiter1);
FakeConnection conn = connector.assertRequest();
conn.connect();
waitUntil(waiter1::isSuccess);
conn.close();
waitUntil(mgr::closed);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection(waiter2);
assertEquals(2, mgr.sequence());
}
@Test
public void testDontCloseEndpointWithInflightRequest() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(3, 2, connector);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection(waiter1);
FakeConnection conn = connector.assertRequest();
conn.connect();
waitUntil(waiter1::isComplete);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection(waiter2);
conn.close();
waitUntil(() -> !mgr.contains(conn));
assertFalse(mgr.closed());
}
@Test
public void testInitialConcurrency() {
int n = 10;
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(-1, 1, connector);
List<FakeWaiter> waiters = new ArrayList<>();
for (int i = 0; i < n; i++) {
FakeWaiter waiter = new FakeWaiter();
mgr.getConnection(waiter);
waiters.add(waiter);
}
FakeConnection conn = connector.assertRequest();
conn.concurrency(n).connect();
waiters.forEach(waiter -> {
waitUntil(waiter::isSuccess);
});
waiters.forEach(FakeWaiter::recycle);
}
@Test
public void testInitialNoConcurrency() {
int n = 10;
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(-1, 1, connector);
List<FakeWaiter> waiters = new ArrayList<>();
for (int i = 0; i < n; i++) {
FakeWaiter waiter = new FakeWaiter();
mgr.getConnection(waiter);
waiters.add(waiter);
}
FakeConnection conn = connector.assertRequest();
conn.concurrency(0).connect().awaitConnected();
conn.concurrency(n - 1);
waitUntil(() -> waiters.stream().filter(FakeWaiter::isSuccess).count() == n - 1);
waiters.stream().filter(FakeWaiter::isSuccess).findFirst().get().recycle();
waiters.forEach(waiter -> {
waitUntil(waiter::isSuccess);
});
}
@Test
public void testRecycleWithoutDispose() {
FakeConnectionProvider connector = new FakeConnectionProvider();
FakeConnectionManager mgr = new FakeConnectionManager(-1, 1, connector);
FakeWaiter waiter1 = new FakeWaiter();
mgr.getConnection(waiter1);
FakeConnection conn = connector.assertRequest();
conn.connect();
waitUntil(waiter1::isSuccess);
conn.recycle(false);
FakeWaiter waiter2 = new FakeWaiter();
mgr.getConnection(waiter2);
waitUntil(waiter1::isSuccess);
waiter2.assertSuccess(conn);
conn.recycle(true);
assertEquals(0, mgr.size());
}
@Test
public void testStress() {
int numActors = 16;
int numConnections = 1000;
FakeConnectionProvider connector = new FakeConnectionProvider() {
@Override
public long connect(ConnectionListener<FakeConnection> listener, ContextImpl context) {
int i = ThreadLocalRandom.current().nextInt(100);
FakeConnection conn = new FakeConnection(context, listener);
if (i < 10) {
conn.fail(new Exception("Could not connect"));
} else {
conn.connect();
}
return 1;
}
};
FakeConnectionManager mgr = new FakeConnectionManager(-1, 16, connector);
Thread[] actors = new Thread[numActors];
for (int i = 0; i < numActors; i++) {
actors[i] = new Thread(() -> {
CountDownLatch latch = new CountDownLatch(numConnections);
for (int i1 = 0; i1 < numConnections; i1++) {
mgr.getConnection(new Waiter<FakeConnection>((ContextImpl) vertx.getOrCreateContext()) {
@Override
public void handleFailure(ContextInternal ctx, Throwable failure) {
latch.countDown();
}
@Override
public void initConnection(ContextInternal ctx, FakeConnection conn) {
}
@Override
public boolean handleConnection(ContextInternal ctx, FakeConnection conn) throws Exception {
int action = ThreadLocalRandom.current().nextInt(100);
if (action < -1) {
latch.countDown();
return false;
} /* else if (i < 30) {
latch.countDown();
throw new Exception();
} */ else {
vertx.setTimer(10, id -> {
latch.countDown();
if (action < 15) {
conn.close();
} else {
conn.recycle();
}
});
return true;
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
actors[i].start();
}
for (int i = 0; i < actors.length; i++) {
try {
actors[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class FakeWaiter extends Waiter<FakeConnection> {
private FakeConnection init;
private boolean cancelled;
private boolean completed;
private Object result;
FakeWaiter() {
super((ContextImpl) vertx.getOrCreateContext());
}
synchronized boolean cancel() {
if (completed) {
return false;
} else {
cancelled = true;
return true;
}
}
synchronized void assertInitialized(FakeConnection conn) {
assertSame(conn, init);
}
synchronized void assertNotInitialized() {
assertSame(null, init);
}
synchronized void assertSuccess(FakeConnection conn) {
assertSame(conn, result);
}
synchronized void assertFailure(Throwable failure) {
assertSame(failure, result);
}
synchronized boolean isComplete() {
return completed;
}
synchronized boolean isSuccess() {
return completed && result instanceof FakeConnection;
}
synchronized boolean isFailure() {
return completed && result instanceof Throwable;
}
@Override
public synchronized void handleFailure(ContextInternal ctx, Throwable failure) {
assertFalse(completed);
completed = true;
result = failure;
}
@Override
public synchronized void initConnection(ContextInternal ctx, FakeConnection conn) {
assertNull(init);
assertNotNull(conn);
init = conn;
}
@Override
public synchronized boolean handleConnection(ContextInternal ctx, FakeConnection conn) throws Exception {
assertFalse(completed);
completed = true;
if (cancelled) {
return false;
} else {
synchronized (conn) {
conn.inflight++;
}
result = conn;
return true;
}
}
long recycle() {
FakeConnection conn = (FakeConnection) result;
return conn.recycle();
}
}
/*
class FakeConnnectionPool implements ConnectionPool<FakeConnection>, Function<SocketAddress, ConnectionPool<FakeConnection>> {
private final SocketAddress address = SocketAddress.inetSocketAddress(8080, "localhost");
private final int maxSize;
private final ArrayDeque<FakeConnection> available = new ArrayDeque<>();
private final Set<FakeConnection> all = new HashSet<>();
private boolean closed = true;
private int sequence;
FakeConnnectionPool(int maxSize) {
this.maxSize = maxSize;
}
@Override
public Deque<FakeConnection> available() {
return available;
}
@Override
public Set<FakeConnection> all() {
return all;
}
synchronized int size() {
return available.size();
}
synchronized boolean contains(FakeConnection conn) {
Deque<ConnectionHolder<FakeConnection>> a = (Deque<ConnectionHolder<FakeConnection>>)(Deque) available;
for (ConnectionHolder<FakeConnection> b : a) {
if (b.connection() == conn) {
return true;
}
}
return false;
}
synchronized int sequence() {
return sequence;
}
@Override
public synchronized FakeConnnectionPool apply(SocketAddress socketAddress) {
if (!socketAddress.equals(address)) {
throw new AssertionError();
}
if (!closed) {
throw new AssertionError();
}
closed = false;
sequence++;
return this;
}
@Override
public synchronized int maxSize() {
if (closed) {
throw new AssertionError();
}
return maxSize;
}
@Override
public synchronized boolean canBorrow(int connCount) {
throw new UnsupportedOperationException();
}
@Override
public synchronized FakeConnection pollConnection() {
throw new UnsupportedOperationException();
}
@Override
public synchronized boolean canCreateConnection(int connCount) {
throw new UnsupportedOperationException();
}
@Override
public synchronized boolean initConnection(FakeConnection conn) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void recycleConnection(FakeConnection conn) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void evictConnection(FakeConnection conn) {
throw new UnsupportedOperationException();
}
@Override
public synchronized boolean isValid(FakeConnection conn) {
throw new UnsupportedOperationException();
}
@Override
public synchronized ContextImpl getContext(FakeConnection conn) {
throw new UnsupportedOperationException();
}
public synchronized void close() {
if (closed) {
throw new AssertionError();
}
closed = true;
available.clear();
all.clear();
}
synchronized boolean isClosed() {
return closed;
}
}
*/
class FakeConnection {
private static final int DISCONNECTED = 0;
private static final int CONNECTING = 1;
private static final int CONNECTED = 2;
private static final int CLOSED = 3;
private final ContextImpl context;
private final ConnectionListener<FakeConnection> listener;
private final Channel channel = new EmbeddedChannel();
private long inflight;
private long concurrency = 1;
private int status = DISCONNECTED;
private boolean valid = true;
FakeConnection(ContextImpl context, ConnectionListener<FakeConnection> listener) {
this.context = context;
this.listener = listener;
}
synchronized FakeConnection invalidate() {
valid = false;
return this;
}
synchronized void close() {
if (status != CONNECTED) {
throw new IllegalStateException();
}
status = CLOSED;
listener.onClose();
}
synchronized long recycle(boolean dispose) {
return recycle(1, dispose);
}
synchronized long recycle() {
return recycle(true);
}
synchronized long recycle(int capacity, boolean dispose) {
inflight -= capacity;
listener.onRecycle(capacity, dispose);
return inflight;
}
synchronized FakeConnection concurrency(long value) {
if (value < 0) {
throw new IllegalArgumentException("Invalid concurrency");
}
if (status == CONNECTED) {
if (concurrency != value) {
concurrency = value;
listener.onConcurrencyChange(value);
}
} else {
concurrency = value;
}
return this;
}
FakeConnection awaitConnected() {
waitUntil(() -> {
synchronized (FakeConnection.this) {
return status == CONNECTED;
}
});
return this;
}
synchronized FakeConnection connect() {
if (status != DISCONNECTED) {
throw new IllegalStateException();
}
status = CONNECTING;
context.nettyEventLoop().execute(() -> {
synchronized (FakeConnection.this) {
listener.onConnectSuccess(this, concurrency, channel, context, 1, 1);
status = CONNECTED;
}
});
return this;
}
void fail(Throwable err) {
context.nettyEventLoop().execute(() -> listener.onConnectFailure(context, err, 1));
}
synchronized boolean isValid() {
return valid;
}
}
class FakeConnectionProvider implements ConnectionProvider<FakeConnection> {
private final ArrayDeque<FakeConnection> pendingRequests = new ArrayDeque<>();
void assertRequests(int expectedSize) {
assertEquals(expectedSize, pendingRequests.size());
}
@Override
public boolean isValid(FakeConnection conn) {
return conn.isValid();
}
int requests(SocketAddress address) {
return pendingRequests.size();
}
FakeConnection assertRequest() {
assertNotNull(pendingRequests);
assertTrue(pendingRequests.size() > 0);
FakeConnection request = pendingRequests.poll();
assertNotNull(request);
return request;
}
@Override
public long connect(ConnectionListener<FakeConnection> listener, ContextImpl context) {
pendingRequests.add(new FakeConnection(context, listener));
return 1;
}
@Override
public void close(FakeConnection conn) {
conn.listener.onClose();
}
}
}