/
ReframingResponseObserver.java
386 lines (343 loc) · 13.4 KB
/
ReframingResponseObserver.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
/*
* Copyright 2018 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
*
* https://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.bigtable.gaxx.reframing;
import com.google.api.core.InternalApi;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StateCheckingResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.common.base.Preconditions;
import com.google.common.math.IntMath;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* Mediates message flow between two {@link ResponseObserver}s. It is intended for situations when a
* stream needs to be transformed in such a way where the incoming responses do not map 1:1 to the
* output responses.
*
* <p>This class manages back pressure between M upstream responses and N downstream responses. It
* buffers responses when M > N and spools them when M < N. The downstream responses will be
* delivered via either the upstream thread or the downstream thread that called request(); in
* either case, the downstream methods will be invoked sequentially. Neither the downstream {@link
* ResponseObserver} nor the {@link Reframer} need to be threadsafe.
*
* <p>Expected usage:
*
* <pre>{@code
* class OuterStreamingCallable extends ServerStreamingCallable<Request, FullResponse> {
* private final ServerStreamingCallable<Request, Chunk> innerCallable;
*
* OuterStreamingCallable(ServerStreamingCallable<Request, Chunk> innerCallable) {
* this.innerCallable = innerCallable;
* }
*
* public void call(Request request, ResponseObserver<FullResponse> outerResponseObserver,
* ApiCallContext context) {
* Reframer<Chunk, FullResponse> myReframer = new Reframer<>();
* innerCallable.call(request, new ReframingResponseObserver(myReframer, outerResponseObserver),
* context);
* }
* }
* }</pre>
*/
@InternalApi
public class ReframingResponseObserver<InnerT, OuterT>
extends StateCheckingResponseObserver<InnerT> {
// Used as a nonblocking mutex for deliver().
// 0 means unlocked
// 1 means locked without contention
// > 1 means locked with contention (another thread tried to deliver concurrently)
private final AtomicInteger lock = new AtomicInteger();
private final ResponseObserver<OuterT> outerResponseObserver;
private final Reframer<OuterT, InnerT> reframer;
// Written in the initial calling thread.
private StreamController innerController;
private boolean hasStarted;
private boolean autoFlowControl = true;
// Read and written by different threads w/o lock.
private final AtomicInteger numRequested = new AtomicInteger();
// Written by an application thread and read under lock in delivery.
private final AtomicReference<Throwable> cancellation = new AtomicReference<>();
// Only written under lock
private volatile boolean awaitingInner;
// Written by multiple interleaved threads. It is the staging area for messages before they are
// fed to the Reframer. It protects the Reframer from having to worry about concurrency, by acting
// like a single item queue: a GRPC thread puts a value in, and then, after acquiring the lock,
// any thread can take the value out and feed it to the Reframer.
private final AtomicReference<InnerT> newItem = new AtomicReference<>();
// Written by a GRPC thread, and read by any thread after acquiring a lock
// Care must be to taken to read the volatile done before accessing error.
private Throwable error;
private volatile boolean done;
// Always written and read by the same thread under lock.
// Safety flag set in the delivery loop before notifying the outer observer of termination.
// It's checked by error handling in delivery() to avoid double notifying the outer observer.
private boolean finished;
public ReframingResponseObserver(
ResponseObserver<OuterT> observer, Reframer<OuterT, InnerT> reframer) {
this.outerResponseObserver = observer;
this.reframer = reframer;
}
/**
* Callback that will be notified when the inner/upstream callable starts. This will in turn
* notify the outer/downstreamObserver of stream start. Regardless of the
* outer/downstreamObserver, the upstream controller will be put into manual flow control.
*
* @param controller The controller for the upstream stream.
*/
@Override
protected void onStartImpl(StreamController controller) {
innerController = controller;
innerController.disableAutoInboundFlowControl();
outerResponseObserver.onStart(
new StreamController() {
@Override
public void disableAutoInboundFlowControl() {
Preconditions.checkState(
!hasStarted, "Can't disable automatic flow control once the stream has started");
autoFlowControl = false;
numRequested.set(0);
}
@Override
public void request(int count) {
// innerController.request(int) is indirectly invoked in deliver().
ReframingResponseObserver.this.onRequest(count);
}
@Override
public void cancel() {
ReframingResponseObserver.this.onCancel();
}
});
hasStarted = true;
if (autoFlowControl) {
numRequested.set(Integer.MAX_VALUE);
deliver();
}
}
/**
* Request n responses to be delivered to the outer/downstream {@link
* ResponseObserver#onResponse(Object)}. This method might synchronously deliver the messages if
* they have already been buffered. Or it will deliver them asynchronously if they need to be
* requested from upstream.
*
* @param count The maximum number of responses to deliver
*/
private void onRequest(int count) {
Preconditions.checkState(!autoFlowControl, "Auto flow control enabled");
Preconditions.checkArgument(count > 0, "Count must be > 0");
while (true) {
int current = numRequested.get();
if (current == Integer.MAX_VALUE) {
return;
}
int newValue = IntMath.saturatedAdd(current, count);
if (numRequested.compareAndSet(current, newValue)) {
break;
}
}
deliver();
}
/**
* Cancels the stream and notifies the downstream {@link ResponseObserver#onError(Throwable)}.
* This method can be called multiple times, but only the first time has any effect. Please note
* that there is a race condition between cancellation and the stream completing normally.
*/
private void onCancel() {
if (cancellation.compareAndSet(null, new CancellationException("User cancelled stream"))) {
innerController.cancel();
}
deliver();
}
/**
* Accept a new response from inner/upstream callable. This message will be processed by the
* {@link Reframer} in the delivery loop and the output will be delivered to the downstream {@link
* ResponseObserver}.
*
* <p>If the delivery loop is stopped, this will restart it.
*/
@Override
protected void onResponseImpl(InnerT response) {
IllegalStateException error = null;
// Guard against unsolicited notifications
if (!awaitingInner || !newItem.compareAndSet(null, response)) {
// Notify downstream if it's still open
error = new IllegalStateException("Received unsolicited response from upstream.");
cancellation.compareAndSet(null, error);
}
deliver();
// Notify upstream by throwing an exception
if (error != null) {
throw error;
}
}
/**
* Process inner/upstream callable's onError notification. This will be queued to be delivered
* after the delegate exhausts its buffers.
*
* <p>If the delivery loop is stopped, this will restart it.
*/
@Override
protected void onErrorImpl(Throwable t) {
// order of assignment matters
error = t;
done = true;
deliver();
}
/**
* Process inner/upstream callable's onComplete notification. This will be queued to be delivered
* after the delegate exhausts its buffers.
*
* <p>If the delivery loop is stopped, this will restart it.
*/
@Override
protected void onCompleteImpl() {
done = true;
deliver();
}
/** Tries to kick off the delivery loop, wrapping it in error handling. */
private void deliver() {
try {
deliverUnsafe();
} catch (Throwable t) {
// This should never happen. If does, it means we are in an inconsistent state and should
// close the stream and further processing should be prevented. This is accomplished by
// purposefully leaving the lock non-zero and notifying the outerResponseObserver of the
// error. Care must be taken to avoid calling close twice in case the first invocation threw
// an error.
try {
innerController.cancel();
} catch (Throwable cancelError) {
t.addSuppressed(
new IllegalStateException(
"Failed to cancel upstream while recovering from an unexpected error",
cancelError));
}
if (!finished) {
outerResponseObserver.onError(t);
}
}
}
/**
* Coordinates state transfer between inner/downstream callable and the outer/upstream. It
* orchestrates the flow of demand from downstream to upstream. The data flows from upstream
* through the Reframer to downstream. It is back pressure aware and will only send as many
* messages as were requested. However, it will send unsolicited onComplete & onError messages.
*
* <p>This method is thread safe and performs all state changes (including interactions with the
* Reframer) using CAS mutex.
*/
private void deliverUnsafe() {
// Try to acquire the lock
if (lock.getAndIncrement() != 0) {
return;
}
do {
// Optimization: the inner loop will eager process any accumulated state, so reset the lock
// for just this iteration. (If another event occurs during processing, it can increment the
// lock to enqueue another iteration).
lock.lazySet(1);
// Process the upstream message if one exists.
pollUpstream();
// Eagerly notify of onComplete/onError disregarding demand.
// NOTE: this will purposely leave wip set to avoid further deliveries.
if (maybeFinish()) {
return;
}
// Deliver as many messages as possible
int demandSnapshot = numRequested.get();
int delivered = 0;
while (delivered < demandSnapshot) {
// Deliver a message if we can
if (reframer.hasFullFrame()) {
delivered++;
outerResponseObserver.onResponse(reframer.pop());
} else {
// Otherwise request more from upstream (if we haven't done so already)
if (!awaitingInner) {
awaitingInner = true;
innerController.request(1);
}
break;
}
if (maybeFinish()) {
return;
}
}
// update the counter in bulk
if (delivered != 0) {
numRequested.addAndGet(-delivered);
}
} while (lock.decrementAndGet() != 0);
}
/**
* Checks if the awaited upstream response is available. If it is, then feed it to the {@link
* Reframer} and update the {@link #awaitingInner} flag. Upon exit, if awaitingInner is not set,
* then done is guaranteed to reflect the current status of the upstream.
*/
private void pollUpstream() {
if (!awaitingInner) {
return;
}
boolean localDone = this.done;
// Try to move the new item into the reframer
InnerT newUpstreamItem = newItem.getAndSet(null);
if (newUpstreamItem != null) {
reframer.push(newUpstreamItem);
// and reset the awaiting flag, if the item arrived or upstream closed
awaitingInner = false;
} else if (localDone) {
awaitingInner = false;
}
}
/**
* Completes the outer observer if appropriate.
*
* <p>Grounds for completion:
*
* <ul>
* <li>Caller cancelled the stream
* <li>Upstream has been exhausted and there is no hope of completing another frame.
* </ul>
*
* <p>Upon upstream exhaustion, the outer observer will be notified via onComplete only if all
* buffers have been consumed. Otherwise it will be notified with an IncompleteStreamException.
*
* @return true if the outer observer has been notified of completion.
*/
private boolean maybeFinish() {
// Check for cancellations
Throwable localError = this.cancellation.get();
if (localError != null) {
finished = true;
outerResponseObserver.onError(localError);
return true;
}
// Check for upstream termination and exhaustion of local buffers
if (done && !reframer.hasFullFrame() && !awaitingInner) {
finished = true;
if (error != null) {
outerResponseObserver.onError(error);
} else if (reframer.hasPartialFrame()) {
outerResponseObserver.onError(new IncompleteStreamException());
} else {
outerResponseObserver.onComplete();
}
return true;
}
// No termination conditions found, go back to business as usual
return false;
}
}