/
RetryingConnectionImpl.java
executable file
·242 lines (219 loc) · 8.61 KB
/
RetryingConnectionImpl.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
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.internal.wire;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.api.core.AbstractApiService;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.pubsublite.ErrorCodes;
import com.google.cloud.pubsublite.internal.CheckedApiException;
import com.google.cloud.pubsublite.internal.CloseableMonitor;
import com.google.cloud.pubsublite.internal.ExtractStatus;
import com.google.common.flogger.GoogleLogger;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ScheduledFuture;
import javax.annotation.concurrent.GuardedBy;
/**
* A connection which recreates an underlying stream on retryable errors.
*
* @param <StreamRequestT> The type of request sent on the stream.
* @param <StreamResponseT> The type of response sent by the stream.
* @param <ClientResponseT> The type of response sent to the client.
* @param <ConnectionT> The type of the underlying connection that is retried.
*/
class RetryingConnectionImpl<
StreamRequestT, StreamResponseT, ClientResponseT, ConnectionT extends AutoCloseable>
extends AbstractApiService
implements RetryingConnection<StreamRequestT, ConnectionT>, ResponseObserver<ClientResponseT> {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private static final Duration INITIAL_RECONNECT_BACKOFF_TIME = Duration.ofMillis(10);
private static final Duration MAX_RECONNECT_BACKOFF_TIME = Duration.ofSeconds(10);
private final StreamFactory<StreamRequestT, StreamResponseT> streamFactory;
private final SingleConnectionFactory<
StreamRequestT, StreamResponseT, ClientResponseT, ConnectionT>
connectionFactory;
private final RetryingConnectionObserver<ClientResponseT> observer;
// connectionMonitor will not be held in any upcalls.
private final CloseableMonitor connectionMonitor = new CloseableMonitor();
@GuardedBy("connectionMonitor.monitor")
private long nextRetryBackoffDuration = INITIAL_RECONNECT_BACKOFF_TIME.toMillis();
@GuardedBy("connectionMonitor.monitor")
private StreamRequestT lastInitialRequest;
@GuardedBy("connectionMonitor.monitor")
private ConnectionT currentConnection;
@GuardedBy("connectionMonitor.monitor")
private boolean completed = false;
RetryingConnectionImpl(
StreamFactory<StreamRequestT, StreamResponseT> streamFactory,
SingleConnectionFactory<StreamRequestT, StreamResponseT, ClientResponseT, ConnectionT>
connectionFactory,
RetryingConnectionObserver<ClientResponseT> observer,
StreamRequestT initialRequest) {
this.streamFactory = streamFactory;
this.connectionFactory = connectionFactory;
this.observer = observer;
this.lastInitialRequest = initialRequest;
}
@Override
protected void doStart() {
StreamRequestT initialInitialRequest;
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
initialInitialRequest = lastInitialRequest;
}
SystemExecutors.getFuturesExecutor()
.execute(
() -> {
reinitialize(initialInitialRequest);
notifyStarted();
});
}
// Reinitialize the stream. Must be called in a downcall to prevent deadlock.
@Override
public void reinitialize(StreamRequestT initialRequest) {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (completed) return;
lastInitialRequest = initialRequest;
logger.atFiner().log("Start initializing connection for %s", streamDescription());
currentConnection = connectionFactory.New(streamFactory, this, lastInitialRequest);
logger.atFiner().log("Finished initializing connection for %s", streamDescription());
}
}
@Override
protected void doStop() {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (completed) return;
completed = true;
logger.atFine().log("Terminating connection for %s", streamDescription());
if (currentConnection != null) {
currentConnection.close();
}
} catch (Throwable t) {
logger.atInfo().withCause(t).log(
"Failed while terminating connection for %s", streamDescription());
notifyFailed(t);
return;
}
notifyStopped();
}
// Run modification on the current connection or empty if not connected.
@Override
public void modifyConnection(Modifier<ConnectionT> modifier) throws CheckedApiException {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (completed) {
modifier.modify(Optional.empty());
} else {
modifier.modify(Optional.of(currentConnection));
}
}
}
void setPermanentError(Throwable error) {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (completed) return;
completed = true;
}
logger.atInfo().withCause(error).log("Permanent error occurred for %s", streamDescription());
notifyFailed(error);
}
@Override
public void onStart(StreamController controller) {
controller.disableAutoInboundFlowControl();
controller.request(Integer.MAX_VALUE);
}
// ResponseObserver implementation
@Override
public final void onResponse(ClientResponseT value) {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (completed) return;
nextRetryBackoffDuration = INITIAL_RECONNECT_BACKOFF_TIME.toMillis();
}
try {
observer.onClientResponse(value);
} catch (Throwable t) {
setPermanentError(t);
}
}
@Override
public final void onError(Throwable t) {
// This is an error code sent from the server.
Optional<CheckedApiException> statusOr = ExtractStatus.extract(t);
if (!statusOr.isPresent()) {
setPermanentError(t);
return;
}
if (!ErrorCodes.IsRetryableForStreams(statusOr.get().code())) {
setPermanentError(statusOr.get());
return;
}
Optional<Throwable> throwable = Optional.empty();
long backoffTime = 0;
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
if (currentConnection != null) {
currentConnection.close();
}
backoffTime = nextRetryBackoffDuration;
nextRetryBackoffDuration = Math.min(backoffTime * 2, MAX_RECONNECT_BACKOFF_TIME.toMillis());
} catch (Throwable t2) {
throwable = Optional.of(t2);
}
if (throwable.isPresent()) {
setPermanentError(
new CheckedApiException(
"Failed to close preexisting stream after error.",
throwable.get(),
Code.FAILED_PRECONDITION));
return;
}
logger.atFine().withCause(t).log(
"Stream disconnected attempting retry, after %s milliseconds for %s",
backoffTime, streamDescription());
ScheduledFuture<?> unusedFuture =
SystemExecutors.getAlarmExecutor()
.schedule(() -> triggerReinitialize(statusOr.get()), backoffTime, MILLISECONDS);
}
private void triggerReinitialize(CheckedApiException streamError) {
// Reinitialize in an unbounded executor to avoid starving tasks using the bounded alarm
// executor.
SystemExecutors.getFuturesExecutor()
.execute(
() -> {
try {
observer.triggerReinitialize(streamError);
} catch (Throwable t) {
logger.atInfo().withCause(t).log("Error occurred in triggerReinitialize.");
onError(t);
}
});
}
@Override
public final void onComplete() {
logger.atFine().log("Stream completed for %s", streamDescription());
boolean expectedCompletion;
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
expectedCompletion = completed;
}
if (!expectedCompletion) {
setPermanentError(
new CheckedApiException("Server unexpectedly closed stream.", Code.FAILED_PRECONDITION));
}
}
private String streamDescription() {
try (CloseableMonitor.Hold h = connectionMonitor.enter()) {
return lastInitialRequest.getClass().getSimpleName() + ": " + lastInitialRequest.toString();
}
}
}