-
Notifications
You must be signed in to change notification settings - Fork 12
/
DualConnection.java
730 lines (658 loc) · 23.7 KB
/
DualConnection.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
package com.atlassian.db.replica.api;
import com.atlassian.db.replica.api.reason.Reason;
import com.atlassian.db.replica.internal.ClientInfo;
import com.atlassian.db.replica.internal.ForwardCall;
import com.atlassian.db.replica.internal.logs.ConnectionProviderLogger;
import com.atlassian.db.replica.internal.logs.DelegatingLazyLogger;
import com.atlassian.db.replica.internal.NoOpDirtyConnectionCloseHook;
import com.atlassian.db.replica.internal.ReplicaCallableStatement;
import com.atlassian.db.replica.internal.ReplicaConnectionProvider;
import com.atlassian.db.replica.internal.ReplicaPreparedStatement;
import com.atlassian.db.replica.internal.ReplicaStatement;
import com.atlassian.db.replica.internal.RouteDecisionBuilder;
import com.atlassian.db.replica.internal.logs.ReplicaConsistencyLogger;
import com.atlassian.db.replica.internal.logs.TaggedLogger;
import com.atlassian.db.replica.internal.logs.LazyLogger;
import com.atlassian.db.replica.internal.logs.NoopLazyLogger;
import com.atlassian.db.replica.internal.logs.StateAwareLogger;
import com.atlassian.db.replica.internal.state.NoOpStateListener;
import com.atlassian.db.replica.internal.state.State;
import com.atlassian.db.replica.internal.state.StateListener;
import com.atlassian.db.replica.spi.ConnectionProvider;
import com.atlassian.db.replica.spi.DatabaseCall;
import com.atlassian.db.replica.spi.DirtyConnectionCloseHook;
import com.atlassian.db.replica.spi.Logger;
import com.atlassian.db.replica.spi.ReplicaConsistency;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.ClientInfoStatus;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import static java.lang.String.format;
/**
* Tries to connect to a replica if the query doesn't write to the database.
* Avoids replicas, which are inconsistent with the main database.
* Falls back to the main database if it cannot use a replica.
*/
public final class DualConnection implements Connection {
private static final String CONNECTION_CLOSED_MESSAGE = "This connection has been closed.";
private final ReplicaConnectionProvider connectionProvider;
private final ReplicaConsistency consistency;
private final DatabaseCall databaseCall;
private final Set<String> readOnlyFunctions;
private final DirtyConnectionCloseHook dirtyConnectionCloseHook;
private final boolean compatibleWithPreviousVersion;
private final LazyLogger logger;
private DualConnection(
ReplicaConnectionProvider connectionProvider,
ReplicaConsistency consistency,
DatabaseCall databaseCall,
Set<String> readOnlyFunctions,
DirtyConnectionCloseHook dirtyConnectionCloseHook,
boolean compatibleWithPreviousVersion,
LazyLogger logger
) {
this.connectionProvider = connectionProvider;
this.dirtyConnectionCloseHook = dirtyConnectionCloseHook;
this.compatibleWithPreviousVersion = compatibleWithPreviousVersion;
this.logger = logger;
this.consistency = consistency;
this.databaseCall = databaseCall;
this.readOnlyFunctions = readOnlyFunctions;
}
@Override
public Statement createStatement() throws SQLException {
checkClosed();
return ReplicaStatement.builder(
connectionProvider,
consistency,
databaseCall,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).build();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).build();
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
checkClosed();
return new ReplicaCallableStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).build();
}
@Override
public String nativeSQL(String sql) throws SQLException {
checkClosed();
final Connection readConnection = connectionProvider.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL).sql(
sql));
logger.info(() -> format("nativeSQL(sql='%s')", sql));
return readConnection
.nativeSQL(sql);
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
logger.debug(() -> format("setAutoCommit(autoCommit='%s')", autoCommit));
checkClosed();
connectionProvider.setAutoCommit(autoCommit);
}
@Override
public boolean getAutoCommit() throws SQLException {
checkClosed();
return connectionProvider.getAutoCommit();
}
@Override
public void commit() throws SQLException {
checkClosed();
connectionProvider.commit();
}
@Override
public void rollback() throws SQLException {
logger.debug(() -> "rollback()");
checkClosed();
connectionProvider.rollback();
}
@Override
public void close() throws SQLException {
if (connectionProvider.isDirty()) {
dirtyConnectionCloseHook.onClose(this);
}
logger.debug(() -> "close()");
connectionProvider.close();
}
@Override
public boolean isClosed() {
return connectionProvider.isClosed();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
checkClosed();
return connectionProvider.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL)).getMetaData();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
checkClosed();
connectionProvider.setReadOnly(readOnly);
}
@Override
public boolean isReadOnly() throws SQLException {
checkClosed();
return connectionProvider.getReadOnly();
}
@Override
public void setCatalog(String catalog) throws SQLException {
checkClosed();
connectionProvider.setCatalog(catalog);
}
@Override
public String getCatalog() throws SQLException {
checkClosed();
return connectionProvider.getCatalog();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
checkClosed();
connectionProvider.setTransactionIsolation(level);
}
@Override
public int getTransactionIsolation() throws SQLException {
checkClosed();
//noinspection MagicConstant
return connectionProvider.getTransactionIsolation();
}
@Override
public SQLWarning getWarnings() throws SQLException {
checkClosed();
return connectionProvider.getWarning();
}
@Override
public void clearWarnings() throws SQLException {
checkClosed();
connectionProvider.clearWarnings();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
checkClosed();
return ReplicaStatement
.builder(
connectionProvider,
consistency,
databaseCall,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
)
.resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.build();
}
@Override
public PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency
) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.build();
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
checkClosed();
return new ReplicaCallableStatement
.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
)
.resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.build();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
checkClosed();
return connectionProvider.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
checkClosed();
connectionProvider.setTypeMap(map);
}
@Override
public void setHoldability(int holdability) throws SQLException {
checkClosed();
connectionProvider.setHoldability(holdability);
}
@Override
public int getHoldability() throws SQLException {
checkClosed();
return connectionProvider.getHoldability();
}
@Override
public Savepoint setSavepoint() throws SQLException {
checkClosed();
return connectionProvider.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL)).setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
checkClosed();
return connectionProvider.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL)).setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
checkClosed();
connectionProvider.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL)).rollback(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkClosed();
connectionProvider.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL)).releaseSavepoint(savepoint);
}
@Override
public Statement createStatement(
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability
) throws SQLException {
checkClosed();
return ReplicaStatement.builder(
connectionProvider,
consistency,
databaseCall,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.resultSetHoldability(resultSetHoldability)
.build();
}
@Override
public PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability
) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.resultSetHoldability(resultSetHoldability)
.build();
}
@Override
public CallableStatement prepareCall(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability
) throws SQLException {
checkClosed();
return new ReplicaCallableStatement
.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
)
.resultSetType(resultSetType)
.resultSetConcurrency(resultSetConcurrency)
.resultSetHoldability(resultSetHoldability)
.build();
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).autoGeneratedKeys(autoGeneratedKeys)
.build();
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).columnIndexes(columnIndexes)
.build();
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
checkClosed();
return new ReplicaPreparedStatement.Builder(
connectionProvider,
consistency,
databaseCall,
sql,
readOnlyFunctions,
this,
compatibleWithPreviousVersion,
logger
).columnNames(columnNames)
.build();
}
@Override
public Clob createClob() throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.createClob();
}
@Override
public Blob createBlob() throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
if (isClosed()) {
return false;
}
return connectionProvider.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL)).isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
try {
checkClosed();
} catch (final SQLException cause) {
final Map<String, ClientInfoStatus> failures = new HashMap<>();
failures.put(name, ClientInfoStatus.REASON_UNKNOWN);
throw new SQLClientInfoException(CONNECTION_CLOSED_MESSAGE, failures, cause);
}
try {
connectionProvider.setClientInfo(new ClientInfo(name, value));
} catch (SQLException cause) {
final Map<String, ClientInfoStatus> failures = new HashMap<>();
failures.put(name, ClientInfoStatus.REASON_UNKNOWN);
throw new SQLClientInfoException(CONNECTION_CLOSED_MESSAGE, failures, cause);
}
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
try {
checkClosed();
} catch (final SQLException cause) {
final Map<String, ClientInfoStatus> failures = new HashMap<>();
for (Map.Entry<Object, Object> e : properties.entrySet()) {
failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN);
}
throw new SQLClientInfoException(CONNECTION_CLOSED_MESSAGE, failures, cause);
}
try {
connectionProvider.setClientInfo(new ClientInfo(properties));
} catch (SQLException cause) {
final Map<String, ClientInfoStatus> failures = new HashMap<>();
for (Map.Entry<Object, Object> e : properties.entrySet()) {
failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN);
}
throw new SQLClientInfoException(CONNECTION_CLOSED_MESSAGE, failures, cause);
}
}
@Override
public String getClientInfo(String name) throws SQLException {
checkClosed();
return connectionProvider
.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL))
.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
checkClosed();
return connectionProvider
.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL))
.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
checkClosed();
return connectionProvider
.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL))
.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException {
checkClosed();
connectionProvider.setSchema(schema);
}
@Override
public String getSchema() throws SQLException {
checkClosed();
return connectionProvider.getReadConnection(new RouteDecisionBuilder(Reason.RO_API_CALL)).getSchema();
}
@Override
public void abort(Executor executor) throws SQLException {
connectionProvider.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
checkClosed();
connectionProvider.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
checkClosed();
return connectionProvider
.getWriteConnection(new RouteDecisionBuilder(Reason.RW_API_CALL))
.getNetworkTimeout();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isAssignableFrom(getClass())) {
return iface.cast(this);
}
return connectionProvider.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
if (iface.isAssignableFrom(getClass())) {
return true;
}
return connectionProvider.isWrapperFor(iface);
}
public static Builder builder(
ConnectionProvider connectionProvider,
ReplicaConsistency consistency
) {
return new Builder(connectionProvider, consistency);
}
public static class Builder {
private final ConnectionProvider connectionProvider;
private final ReplicaConsistency consistency;
private DatabaseCall databaseCall = new ForwardCall();
private StateListener stateListener = new NoOpStateListener();
private Set<String> readOnlyFunctions = new HashSet<>();
private DirtyConnectionCloseHook dirtyConnectionCloseHook = new NoOpDirtyConnectionCloseHook();
private boolean compatibleWithPreviousVersion = false;
private Logger logger = null;
private ReplicaConnectionProvider replicaConnectionProvider;
private Builder(
ConnectionProvider connectionProvider,
ReplicaConsistency consistency
) {
this.connectionProvider = connectionProvider;
this.consistency = consistency;
}
/**
* Register SQL functions as read-only. It allows utilising replica if the function is invoked.
*
* @param functions a collection of read-only function names.
*/
public DualConnection.Builder readOnlyFunctions(Collection<String> functions) {
this.readOnlyFunctions = new HashSet<>(functions);
return this;
}
public DualConnection.Builder databaseCall(DatabaseCall databaseCall) {
this.databaseCall = databaseCall;
return this;
}
DualConnection.Builder stateListener(StateListener stateListener) {
this.stateListener = stateListener;
return this;
}
/**
* Puts this connection in compatibility mode with a previous version. Developers can use this method to
* roll out the new version of the library with a feature flag.
* <p>
* It's best-effort, and there's no guarantee the library in compatibility mode will always behave
* the same way as the previous version of the library.
*/
public DualConnection.Builder compatibleWithPreviousVersion() {
this.compatibleWithPreviousVersion = true;
return this;
}
public DualConnection.Builder logger(Logger logger) {
this.logger = logger;
return this;
}
public DualConnection.Builder dirtyConnectionCloseHook(DirtyConnectionCloseHook dirtyConnectionCloseHook) {
this.dirtyConnectionCloseHook = dirtyConnectionCloseHook;
return this;
}
public Connection build() throws SQLException {
final LazyLogger lazyLogger = logger != null ?
new TaggedLogger(
"DualConnection", UUID.randomUUID().toString(),
new StateAwareLogger(this::getState, new DelegatingLazyLogger(logger))
) :
new NoopLazyLogger();
final ReplicaConsistency replicaConsistency = logger != null ? new ReplicaConsistencyLogger(
consistency,
lazyLogger
) : consistency;
final ConnectionProvider connectionProviderLogger = logger != null ? new ConnectionProviderLogger(
connectionProvider,
lazyLogger
) : connectionProvider;
replicaConnectionProvider = new ReplicaConnectionProvider(
connectionProviderLogger,
replicaConsistency,
stateListener,
lazyLogger
);
return new DualConnection(
replicaConnectionProvider,
replicaConsistency,
databaseCall,
readOnlyFunctions,
dirtyConnectionCloseHook,
compatibleWithPreviousVersion,
lazyLogger
);
}
private State getState() {
return replicaConnectionProvider.getState();
}
}
private void checkClosed() throws SQLException {
if (isClosed()) {
throw new SQLException(CONNECTION_CLOSED_MESSAGE);
}
}
}