-
Notifications
You must be signed in to change notification settings - Fork 12
/
ConnectionState.java
307 lines (284 loc) · 12.3 KB
/
ConnectionState.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
package com.atlassian.db.replica.internal.state;
import com.atlassian.db.replica.api.reason.RouteDecision;
import com.atlassian.db.replica.internal.ConnectionParameters;
import com.atlassian.db.replica.internal.DecisionAwareReference;
import com.atlassian.db.replica.internal.RouteDecisionBuilder;
import com.atlassian.db.replica.internal.SqlRunnable;
import com.atlassian.db.replica.internal.Warnings;
import com.atlassian.db.replica.internal.logs.LazyLogger;
import com.atlassian.db.replica.internal.logs.TaggedLogger;
import com.atlassian.db.replica.spi.ConnectionProvider;
import com.atlassian.db.replica.spi.ReplicaConsistency;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.Optional;
import java.util.concurrent.Executor;
import static com.atlassian.db.replica.api.reason.Reason.HIGH_TRANSACTION_ISOLATION_LEVEL;
import static com.atlassian.db.replica.api.reason.Reason.MAIN_CONNECTION_REUSE;
import static com.atlassian.db.replica.api.reason.Reason.REPLICA_INCONSISTENT;
import static com.atlassian.db.replica.api.reason.Reason.RO_API_CALL;
import static com.atlassian.db.replica.api.reason.Reason.RW_API_CALL;
import static com.atlassian.db.replica.internal.state.State.CLOSED;
import static com.atlassian.db.replica.internal.state.State.COMMITED_MAIN;
import static com.atlassian.db.replica.internal.state.State.MAIN;
import static com.atlassian.db.replica.internal.state.State.NOT_INITIALISED;
import static com.atlassian.db.replica.internal.state.State.REPLICA;
import static java.lang.String.format;
public final class ConnectionState {
public static final String READ_CONNECTION = "readConnection";
public static final String WRITE_CONNECTION = "writeConnection";
private final ReplicaConsistency consistency;
private volatile Boolean isClosed = false;
private final ConnectionParameters parameters;
private final Warnings warnings;
private final StateListener stateListener;
private volatile boolean replicaConsistent = true;
private final DecisionAwareReference<Connection> readConnection;
private final DecisionAwareReference<Connection> writeConnection;
private final LazyLogger logger;
/**
* When we use a connection to write to the database, it becomes a 'dirty' connection.
* The state is cleared when we commit the transaction. Currently, we use it only
* to detect dirty connection close() and commit the transaction before closing
* the connection.
* In the future we can use this state to exit `MainConnection` state and move more traffic to replicas.
* (see <a href="https://github.com/atlassian-labs/db-replica/blob/master/docs/dual-connection-states.png">Dual connection states</a>).
*/
private volatile boolean dirty = false;
public void markDirty() {
logger.debug(() -> "markDirty");
this.dirty = true;
}
public void clearDirty() {
logger.debug(() -> "clearDirty");
this.dirty = false;
}
public boolean isDirty() {
return dirty;
}
public ConnectionState(
ConnectionProvider connectionProvider,
ReplicaConsistency consistency,
ConnectionParameters parameters,
Warnings warnings,
StateListener stateListener,
LazyLogger logger
) {
this.consistency = consistency;
this.parameters = parameters;
this.warnings = warnings;
this.stateListener = stateListener;
this.logger = logger;
this.readConnection = new DecisionAwareReference<Connection>() {
@Override
public Connection create() throws SQLException {
if (connectionProvider.isReplicaAvailable()) {
final Connection replicaConnection = connectionProvider.getReplicaConnection();
parameters.initialize(replicaConnection);
return replicaConnection;
} else {
return getWriteConnection(getFirstCause());
}
}
};
this.writeConnection = new DecisionAwareReference<Connection>() {
@Override
public Connection create() throws SQLException {
final Connection mainConnection = connectionProvider.getMainConnection();
parameters.initialize(mainConnection);
return mainConnection;
}
};
}
public State getState() {
if (isClosed != null && isClosed) {
return CLOSED;
} else {
final boolean readReady = readConnection.isInitialized();
final boolean writeReady = writeConnection.isInitialized();
if (!readReady && !writeReady) {
return NOT_INITIALISED;
} else if (!replicaConsistent && writeReady) {
return COMMITED_MAIN;
} else if (writeReady) {
return MAIN;
} else {
return REPLICA;
}
}
}
public Optional<Connection> getConnection() {
final State state = getState();
if (state.equals(REPLICA)) {
return Optional.of(this.readConnection.get(new RouteDecisionBuilder(RO_API_CALL)));
} else if (hasWriteConnection()) {
return Optional.of(this.writeConnection.get(new RouteDecisionBuilder(MAIN_CONNECTION_REUSE)));
} else {
return Optional.empty();
}
}
/**
* Provides a connection that will be used for reading operation. Will use read-replica if possible.
*/
public Connection getReadConnection(RouteDecisionBuilder decisionBuilder) throws SQLException {
final State stateBefore = getState();
final Connection connection = prepareReadConnection(decisionBuilder);
final State stateAfter = getState();
if (!stateAfter.equals(stateBefore)) {
stateListener.transition(stateBefore, stateAfter);
}
return connection;
}
/**
* Provides a connection that will be used for writing operation. It will always return a connection to the
* main database.
*/
public Connection getWriteConnection(RouteDecisionBuilder decisionBuilder) throws SQLException {
final State stateBefore = getState();
replicaConsistent = true;
final Connection connection = prepareMainConnection(decisionBuilder);
final State stateAfter = getState();
if (!stateAfter.equals(stateBefore)) {
stateListener.transition(stateBefore, stateAfter);
}
return connection;
}
private Connection prepareMainConnection(RouteDecisionBuilder decisionBuilder) throws SQLException {
final Connection mainDatabaseConnection = this.writeConnection.get(decisionBuilder);
if (readConnection.isInitialized()) {
if (readConnection.get(decisionBuilder).equals(mainDatabaseConnection)) {
readConnection.reset(); // We can release the reference. We still can close it via `writeConnection`
} else {
closeConnection(readConnection, decisionBuilder, READ_CONNECTION);
}
}
return mainDatabaseConnection;
}
public Optional<RouteDecision> getDecision() {
if (getState().equals(MAIN)) {
return Optional.of(writeConnection.getFirstCause().build());
} else {
return Optional.empty();
}
}
public boolean hasWriteConnection() {
final State state = getState();
return state.equals(MAIN) || state.equals(COMMITED_MAIN);
}
public void close() throws SQLException {
final State state = getState();
isClosed = true;
final Optional<SQLException> mainConnectionCloseException = catchException(() -> closeConnection(
writeConnection,
new RouteDecisionBuilder(RW_API_CALL),
WRITE_CONNECTION
));
final Optional<SQLException> replicaConnectionCloseException = catchException(() -> closeConnection(
readConnection,
new RouteDecisionBuilder(RO_API_CALL),
READ_CONNECTION
));
final State stateAfter = getState();
if (!stateAfter.equals(state)) {
stateListener.transition(state, stateAfter);
}
throwExceptions(mainConnectionCloseException, replicaConnectionCloseException);
}
private Optional<SQLException> catchException(SqlRunnable runnable) {
try {
runnable.run();
return Optional.empty();
} catch (SQLException e) {
return Optional.of(e);
}
}
private void throwExceptions(
Optional<SQLException> mainException,
Optional<SQLException> replicaException
) throws SQLException {
if (mainException.isPresent() && replicaException.isPresent()) {
mainException.get().addSuppressed(replicaException.get());
throw mainException.get();
} else if (mainException.isPresent()) {
throw mainException.get();
} else if (replicaException.isPresent()) {
throw replicaException.get();
}
}
public void abort(Executor executor) throws SQLException {
isClosed = true;
final Optional<Connection> connection = getConnection();
if (connection.isPresent()) {
connection.get().abort(executor);
}
}
/**
* Provides a connection that will be used for reading operation. Will use read-replica if possible.
*/
private Connection prepareReadConnection(RouteDecisionBuilder decisionBuilder) throws SQLException {
if (parameters.getTransactionIsolation() != null && parameters.getTransactionIsolation() > Connection.TRANSACTION_READ_COMMITTED) {
decisionBuilder.reason(HIGH_TRANSACTION_ISOLATION_LEVEL);
return prepareMainConnection(decisionBuilder);
}
if (getState().equals(MAIN)) {
decisionBuilder.reason(MAIN_CONNECTION_REUSE);
decisionBuilder.cause(writeConnection.getFirstCause().build());
return writeConnection.get(decisionBuilder);
}
boolean isConsistent;
try {
isConsistent = consistency.isConsistent(() -> readConnection.get(decisionBuilder));
} catch (Exception e) {
closeConnection(readConnection, decisionBuilder, READ_CONNECTION);
throw e;
}
if (isConsistent) {
if (getState().equals(COMMITED_MAIN)) {
closeConnection(writeConnection, decisionBuilder, WRITE_CONNECTION);
}
final Connection connection = readConnection.get(decisionBuilder);
replicaConsistent = true;
return connection;
} else {
replicaConsistent = false;
decisionBuilder.reason(REPLICA_INCONSISTENT);
return prepareMainConnection(decisionBuilder);
}
}
private void closeConnection(
DecisionAwareReference<Connection> connectionReference,
RouteDecisionBuilder decisionBuilder,
String context
) throws SQLException {
final TaggedLogger closeConnectionLogger = new TaggedLogger("connectionType", context, logger);
closeConnectionLogger.debug(() -> "Closing connection");
if (!connectionReference.isInitialized()) {
closeConnectionLogger.debug(() -> "Connection was not initialized");
return;
}
final Connection connection = connectionReference.get(decisionBuilder);
if (connection.isClosed()) {
closeConnectionLogger.debug(() -> "Connection was already closed");
connectionReference.reset();
return;
}
try {
try {
warnings.saveWarning(connection.getWarnings());
} catch (Exception e) {
warnings.saveWarning(new SQLWarning(e));
}
if (connection.isReadOnly()) {
closeConnectionLogger.debug(() -> format("Closing connection(%s) setAutoCommit(true)", connection));
connection.setAutoCommit(true);
closeConnectionLogger.debug(() -> format("Closing connection(%s) setReadOnly(false)", connection));
connection.setReadOnly(false);
}
} finally {
connectionReference.reset();
closeConnectionLogger.debug(() -> format("Closing connection(%s) close()", connection));
connection.close();
}
}
}