Repository navigation
Expand file tree
/
Copy pathConnectionPoolIT.java
More file actions
511 lines (427 loc) · 16.4 KB
/
Copy pathConnectionPoolIT.java
File metadata and controls
511 lines (427 loc) · 16.4 KB
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
package dbProcs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import testUtils.TestProperties;
public class ConnectionPoolIT {
private static final Logger log = LogManager.getLogger(ConnectionPoolIT.class);
private static boolean databaseAvailable = false;
@BeforeAll
public static void setup() throws IOException, SQLException {
TestProperties.setTestPropertiesFileDirectory(log);
TestProperties.createMysqlResource();
try {
ConnectionPool.initialize();
Connection conn = ConnectionPool.getConnection();
conn.close();
databaseAvailable = true;
log.info("Database is available - running full test suite");
} catch (Exception e) {
databaseAvailable = false;
log.warn("Database not available - skipping connection-dependent tests: " + e.getMessage());
} finally {
ConnectionPool.reset();
}
}
@AfterAll
public static void cleanup() {
ConnectionPool.shutdown();
}
@BeforeEach
public void resetBeforeEachTest() throws IOException {
TestProperties.createMysqlResource();
ConnectionPool.reset();
}
private void requireDatabase() {
assumeTrue(databaseAvailable, "Database not available");
}
@Test
public void testPoolInitializationState() {
ConnectionPool.reset();
assertFalse(ConnectionPool.isInitialized(), "Pool should not be initialized before first use");
}
@Test
public void testPoolInitialization() {
requireDatabase();
ConnectionPool.reset();
assertFalse(ConnectionPool.isInitialized(), "Pool should not be initialized before first use");
ConnectionPool.initialize();
assertTrue(ConnectionPool.isInitialized(), "Pool should be initialized after initialize()");
}
@Test
public void testConnectionAcquisition() throws SQLException {
requireDatabase();
if (!ConnectionPool.isInitialized()) {
ConnectionPool.initialize();
}
Connection conn = null;
try {
conn = ConnectionPool.getConnection();
assertNotNull(conn, "Should be able to get a connection from the pool");
assertFalse(conn.isClosed(), "Connection should not be closed");
} finally {
if (conn != null) {
conn.close();
}
}
}
@Test
public void testConnectionReturn() throws SQLException {
requireDatabase();
if (!ConnectionPool.isInitialized()) {
ConnectionPool.initialize();
}
Connection conn = ConnectionPool.getConnection();
assertNotNull(conn, "Should get a connection");
conn.close();
assertTrue(conn.isClosed(), "Connection should appear closed after close()");
Connection conn2 = ConnectionPool.getConnection();
assertNotNull(conn2, "Should be able to get another connection");
conn2.close();
}
@Test
public void testPoolShutdown() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
assertTrue(ConnectionPool.isInitialized(), "Pool should be initialized");
Connection conn = ConnectionPool.getConnection();
assertNotNull(conn);
conn.close();
ConnectionPool.shutdown();
assertFalse(ConnectionPool.isInitialized(), "Pool should not be initialized after shutdown");
}
@Test
public void testConcurrentConnections() throws InterruptedException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
final int numThreads = 10;
final int operationsPerThread = 5;
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch doneLatch = new CountDownLatch(numThreads);
final AtomicInteger successCount = new AtomicInteger(0);
final AtomicInteger errorCount = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
executor.submit(
() -> {
try {
startLatch.await();
for (int j = 0; j < operationsPerThread; j++) {
Connection conn = null;
try {
conn = ConnectionPool.getConnection();
if (conn != null && !conn.isClosed()) {
successCount.incrementAndGet();
}
Thread.sleep(10);
} catch (SQLException e) {
errorCount.incrementAndGet();
log.error("Error getting connection: " + e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error closing connection: " + e.getMessage());
}
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
doneLatch.countDown();
}
});
}
startLatch.countDown();
boolean completed = doneLatch.await(60, TimeUnit.SECONDS);
executor.shutdown();
assertTrue(completed, "All threads should complete within timeout");
assertTrue(successCount.get() > 0, "Should have successful connections");
log.info("Concurrent test: {} successful, {} errors", successCount.get(), errorCount.get());
}
@Test
public void testPoolConfiguration() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
String stats = ConnectionPool.getPoolStats();
assertNotNull(stats, "Pool stats should not be null");
assertTrue(stats.contains("Pool:"), "Stats should contain pool name");
log.info("Pool stats: " + stats);
}
@Test
public void testConnectionValidation() throws SQLException {
requireDatabase();
if (!ConnectionPool.isInitialized()) {
ConnectionPool.initialize();
}
Connection conn = ConnectionPool.getConnection();
try {
assertNotNull(conn, "Connection should not be null");
assertTrue(conn.isValid(5), "Connection should be valid");
} finally {
conn.close();
}
}
@Test
public void testLazyInitialization() throws SQLException {
requireDatabase();
ConnectionPool.reset();
assertFalse(ConnectionPool.isInitialized(), "Pool should not be initialized");
Connection conn = ConnectionPool.getConnection();
assertNotNull(conn, "Should get a connection");
assertTrue(
ConnectionPool.isInitialized(), "Pool should be initialized after getting connection");
conn.close();
}
@Test
public void testChallengeConnectionAcquiresValidConnection() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
Connection conn =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
try {
assertNotNull(conn, "Challenge connection should not be null");
assertFalse(conn.isClosed(), "Challenge connection should not be closed");
assertTrue(conn.isValid(5), "Challenge connection should be valid");
} finally {
conn.close();
}
}
@Test
public void testChallengePoolReusedForSameCredentials() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
assertEquals(0, ConnectionPool.getChallengePoolCount(), "Should start with no challenge pools");
// First call creates a pool
Connection conn1 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
conn1.close();
assertEquals(1, ConnectionPool.getChallengePoolCount(), "Should have one challenge pool");
// Second call with same credentials should reuse the pool
Connection conn2 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
conn2.close();
assertEquals(1, ConnectionPool.getChallengePoolCount(), "Should still have one pool (reused)");
}
@Test
public void testChallengePoolSeparatePerCredentials() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
// Create a pool with one set of credentials
Connection conn1 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
conn1.close();
assertEquals(1, ConnectionPool.getChallengePoolCount(), "Should have one challenge pool");
// Create a pool with different schema (simulates different challenge)
Connection conn2 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(),
"information_schema",
getTestDbOptions(),
"root",
getTestPassword());
conn2.close();
assertEquals(
2, ConnectionPool.getChallengePoolCount(), "Should have two pools for different schemas");
}
@Test
public void testChallengePoolHasCorrectSizing() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
String url = getTestConnectionUrl();
String schema = "core";
String options = getTestDbOptions();
String username = "root";
String password = getTestPassword();
Connection conn =
ConnectionPool.getChallengeConnection(url, schema, options, username, password);
conn.close();
// Build the pool key the same way ConnectionPool does
String jdbcUrl = url + schema + "?" + options;
String poolKey = jdbcUrl + ":" + username;
HikariDataSource ds = ConnectionPool.getChallengePool(poolKey);
assertNotNull(ds, "Challenge pool should exist for key");
assertEquals(3, ds.getMaximumPoolSize(), "Challenge pool maxPoolSize should be 3");
assertEquals(0, ds.getMinimumIdle(), "Challenge pool minIdle should be 0");
assertEquals(120000, ds.getIdleTimeout(), "Challenge pool idleTimeout should be 2 minutes");
}
@Test
public void testChallengePoolMaxConnectionsEnforced() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
// Acquire all 3 max connections
List<Connection> connections = new ArrayList<>();
try {
for (int i = 0; i < 3; i++) {
Connection conn =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
assertNotNull(conn, "Should get connection " + (i + 1));
connections.add(conn);
}
// The 4th connection should block and eventually timeout since pool max is 3
// We can't easily test the timeout without waiting 30s, so instead verify
// the pool reports the right active count
String url = getTestConnectionUrl();
String jdbcUrl = url + "core" + "?" + getTestDbOptions();
String poolKey = jdbcUrl + ":" + "root";
HikariDataSource ds = ConnectionPool.getChallengePool(poolKey);
assertEquals(
3, ds.getHikariPoolMXBean().getActiveConnections(), "Should have 3 active connections");
} finally {
for (Connection conn : connections) {
conn.close();
}
}
}
@Test
public void testShutdownClosesAllChallengePools() throws SQLException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
// Create two challenge pools
Connection conn1 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(), "core", getTestDbOptions(), "root", getTestPassword());
conn1.close();
Connection conn2 =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(),
"information_schema",
getTestDbOptions(),
"root",
getTestPassword());
conn2.close();
assertEquals(2, ConnectionPool.getChallengePoolCount(), "Should have two challenge pools");
ConnectionPool.shutdown();
assertEquals(
0, ConnectionPool.getChallengePoolCount(), "Shutdown should clear all challenge pools");
}
@Test
public void testConcurrentChallengeConnections() throws InterruptedException {
requireDatabase();
ConnectionPool.reset();
ConnectionPool.initialize();
final int numThreads = 6;
final int operationsPerThread = 5;
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch doneLatch = new CountDownLatch(numThreads);
final AtomicInteger successCount = new AtomicInteger(0);
final AtomicInteger errorCount = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
executor.submit(
() -> {
try {
startLatch.await();
for (int j = 0; j < operationsPerThread; j++) {
Connection conn = null;
try {
conn =
ConnectionPool.getChallengeConnection(
getTestConnectionUrl(),
"core",
getTestDbOptions(),
"root",
getTestPassword());
if (conn != null && !conn.isClosed()) {
successCount.incrementAndGet();
}
Thread.sleep(10);
} catch (SQLException e) {
errorCount.incrementAndGet();
log.error("Error getting challenge connection: " + e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error closing challenge connection: " + e.getMessage());
}
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
doneLatch.countDown();
}
});
}
startLatch.countDown();
boolean completed = doneLatch.await(60, TimeUnit.SECONDS);
executor.shutdown();
assertTrue(completed, "All threads should complete within timeout");
assertEquals(
numThreads * operationsPerThread,
successCount.get(),
"All challenge connection attempts should succeed");
assertEquals(0, errorCount.get(), "Should have no errors");
assertEquals(
1,
ConnectionPool.getChallengePoolCount(),
"Should have exactly one challenge pool (all threads used same credentials)");
}
@Test
public void testPoolShutdownWithoutInit() {
ConnectionPool.reset();
assertFalse(ConnectionPool.isInitialized(), "Pool should not be initialized");
ConnectionPool.shutdown();
assertFalse(
ConnectionPool.isInitialized(), "Pool should still not be initialized after shutdown");
}
@Test
public void testResetIsIdempotent() {
ConnectionPool.reset();
ConnectionPool.reset();
ConnectionPool.reset();
assertFalse(
ConnectionPool.isInitialized(), "Pool should not be initialized after multiple resets");
}
private static String getTestConnectionUrl() {
io.github.cdimascio.dotenv.Dotenv dotenv = io.github.cdimascio.dotenv.Dotenv.load();
String host = dotenv.get("TEST_MYSQL_HOST");
String port = dotenv.get("TEST_MYSQL_PORT");
return "jdbc:mariadb://" + host + ":" + port + "/";
}
private static String getTestPassword() {
io.github.cdimascio.dotenv.Dotenv dotenv = io.github.cdimascio.dotenv.Dotenv.load();
return dotenv.get("TEST_MYSQL_PASSWORD");
}
private static String getTestDbOptions() {
return "useUnicode=true&character_set_server=utf8mb4";
}
}