forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DelayedClientCall.java
532 lines (490 loc) · 16.1 KB
/
DelayedClientCall.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
/*
* Copyright 2020 The gRPC Authors
*
* 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 io.grpc.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import io.grpc.Attributes;
import io.grpc.ClientCall;
import io.grpc.Context;
import io.grpc.Deadline;
import io.grpc.Metadata;
import io.grpc.Status;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* A call that queues requests before the transport is available, and delegates to a real call
* implementation when the transport is available.
*
* <p>{@code ClientCall} itself doesn't require thread-safety. However, the state of {@code
* DelayedCall} may be internally altered by different threads, thus internal synchronization is
* necessary.
*/
class DelayedClientCall<ReqT, RespT> extends ClientCall<ReqT, RespT> {
private static final Logger logger = Logger.getLogger(DelayedClientCall.class.getName());
/**
* A timer to monitor the initial deadline. The timer must be cancelled on transition to the real
* call.
*/
@Nullable
private final ScheduledFuture<?> initialDeadlineMonitor;
private final Executor callExecutor;
private final Context context;
/** {@code true} once realCall is valid and all pending calls have been drained. */
private volatile boolean passThrough;
/**
* Non-{@code null} iff start has been called. Used to assert methods are called in appropriate
* order, but also used if an error occurs before {@code realCall} is set.
*/
private Listener<RespT> listener;
// Must hold {@code this} lock when setting.
private ClientCall<ReqT, RespT> realCall;
@GuardedBy("this")
private Status error;
@GuardedBy("this")
private List<Runnable> pendingRunnables = new ArrayList<>();
@GuardedBy("this")
private DelayedListener<RespT> delayedListener;
DelayedClientCall(
Executor callExecutor, ScheduledExecutorService scheduler, @Nullable Deadline deadline) {
this.callExecutor = checkNotNull(callExecutor, "callExecutor");
checkNotNull(scheduler, "scheduler");
context = Context.current();
initialDeadlineMonitor = scheduleDeadlineIfNeeded(scheduler, deadline);
}
@Nullable
private ScheduledFuture<?> scheduleDeadlineIfNeeded(
ScheduledExecutorService scheduler, @Nullable Deadline deadline) {
Deadline contextDeadline = context.getDeadline();
if (deadline == null && contextDeadline == null) {
return null;
}
long remainingNanos = Long.MAX_VALUE;
if (deadline != null) {
remainingNanos = Math.min(remainingNanos, deadline.timeRemaining(NANOSECONDS));
}
if (contextDeadline != null && contextDeadline.timeRemaining(NANOSECONDS) < remainingNanos) {
remainingNanos = contextDeadline.timeRemaining(NANOSECONDS);
if (logger.isLoggable(Level.FINE)) {
StringBuilder builder =
new StringBuilder(
String.format(
"Call timeout set to '%d' ns, due to context deadline.", remainingNanos));
if (deadline == null) {
builder.append(" Explicit call timeout was not set.");
} else {
long callTimeout = deadline.timeRemaining(TimeUnit.NANOSECONDS);
builder.append(String.format(" Explicit call timeout was '%d' ns.", callTimeout));
}
logger.fine(builder.toString());
}
}
long seconds = Math.abs(remainingNanos) / TimeUnit.SECONDS.toNanos(1);
long nanos = Math.abs(remainingNanos) % TimeUnit.SECONDS.toNanos(1);
final StringBuilder buf = new StringBuilder();
if (remainingNanos < 0) {
buf.append("ClientCall started after deadline exceeded. Deadline exceeded after -");
} else {
buf.append("Deadline exceeded after ");
}
buf.append(seconds);
buf.append(String.format(Locale.US, ".%09d", nanos));
buf.append("s. ");
/** Cancels the call if deadline exceeded prior to the real call being set. */
class DeadlineExceededRunnable implements Runnable {
@Override
public void run() {
cancel(
Status.DEADLINE_EXCEEDED.withDescription(buf.toString()),
// We should not cancel the call if the realCall is set because there could be a
// race between cancel() and realCall.start(). The realCall will handle deadline by
// itself.
/* onlyCancelPendingCall= */ true);
}
}
return scheduler.schedule(new DeadlineExceededRunnable(), remainingNanos, NANOSECONDS);
}
/**
* Transfers all pending and future requests and mutations to the given call.
*
* <p>No-op if either this method or {@link #cancel} have already been called.
*/
// When this method returns, passThrough is guaranteed to be true
final void setCall(ClientCall<ReqT, RespT> call) {
synchronized (this) {
// If realCall != null, then either setCall() or cancel() has been called.
if (realCall != null) {
return;
}
setRealCall(checkNotNull(call, "call"));
}
drainPendingCalls();
}
@Override
public final void start(Listener<RespT> listener, final Metadata headers) {
checkState(this.listener == null, "already started");
Status savedError;
boolean savedPassThrough;
synchronized (this) {
this.listener = checkNotNull(listener, "listener");
// If error != null, then cancel() has been called and was unable to close the listener
savedError = error;
savedPassThrough = passThrough;
if (!savedPassThrough) {
listener = delayedListener = new DelayedListener<>(listener);
}
}
if (savedError != null) {
callExecutor.execute(new CloseListenerRunnable(listener, savedError));
return;
}
if (savedPassThrough) {
realCall.start(listener, headers);
} else {
final Listener<RespT> finalListener = listener;
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.start(finalListener, headers);
}
});
}
}
// When this method returns, passThrough is guaranteed to be true
@Override
public final void cancel(@Nullable final String message, @Nullable final Throwable cause) {
Status status = Status.CANCELLED;
if (message != null) {
status = status.withDescription(message);
} else {
status = status.withDescription("Call cancelled without message");
}
if (cause != null) {
status = status.withCause(cause);
}
cancel(status, false);
}
/**
* Cancels the call unless {@code realCall} is set and {@code onlyCancelPendingCall} is true.
*/
private void cancel(final Status status, boolean onlyCancelPendingCall) {
boolean delegateToRealCall = true;
Listener<RespT> listenerToClose = null;
synchronized (this) {
// If realCall != null, then either setCall() or cancel() has been called
if (realCall == null) {
@SuppressWarnings("unchecked")
ClientCall<ReqT, RespT> noopCall = (ClientCall<ReqT, RespT>) NOOP_CALL;
setRealCall(noopCall);
delegateToRealCall = false;
// If listener == null, then start() will later call listener with 'error'
listenerToClose = listener;
error = status;
} else if (onlyCancelPendingCall) {
return;
}
}
if (delegateToRealCall) {
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.cancel(status.getDescription(), status.getCause());
}
});
} else {
if (listenerToClose != null) {
callExecutor.execute(new CloseListenerRunnable(listenerToClose, status));
}
drainPendingCalls();
}
callCancelled();
}
protected void callCancelled() {
}
private void delayOrExecute(Runnable runnable) {
synchronized (this) {
if (!passThrough) {
pendingRunnables.add(runnable);
return;
}
}
runnable.run();
}
/**
* Called to transition {@code passThrough} to {@code true}. This method is not safe to be called
* multiple times; the caller must ensure it will only be called once, ever. {@code this} lock
* should not be held when calling this method.
*/
private void drainPendingCalls() {
assert realCall != null;
assert !passThrough;
List<Runnable> toRun = new ArrayList<>();
DelayedListener<RespT> delayedListener ;
while (true) {
synchronized (this) {
if (pendingRunnables.isEmpty()) {
pendingRunnables = null;
passThrough = true;
delayedListener = this.delayedListener;
break;
}
// Since there were pendingCalls, we need to process them. To maintain ordering we can't set
// passThrough=true until we run all pendingCalls, but new Runnables may be added after we
// drop the lock. So we will have to re-check pendingCalls.
List<Runnable> tmp = toRun;
toRun = pendingRunnables;
pendingRunnables = tmp;
}
for (Runnable runnable : toRun) {
// Must not call transport while lock is held to prevent deadlocks.
// TODO(ejona): exception handling
runnable.run();
}
toRun.clear();
}
if (delayedListener != null) {
final DelayedListener<RespT> listener = delayedListener;
class DrainListenerRunnable extends ContextRunnable {
DrainListenerRunnable() {
super(context);
}
@Override
public void runInContext() {
listener.drainPendingCallbacks();
}
}
callExecutor.execute(new DrainListenerRunnable());
}
}
@GuardedBy("this")
private void setRealCall(ClientCall<ReqT, RespT> realCall) {
checkState(this.realCall == null, "realCall already set to %s", this.realCall);
if (initialDeadlineMonitor != null) {
initialDeadlineMonitor.cancel(false);
}
this.realCall = realCall;
}
@VisibleForTesting
final ClientCall<ReqT, RespT> getRealCall() {
return realCall;
}
@Override
public final void sendMessage(final ReqT message) {
if (passThrough) {
realCall.sendMessage(message);
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.sendMessage(message);
}
});
}
}
@Override
public final void setMessageCompression(final boolean enable) {
if (passThrough) {
realCall.setMessageCompression(enable);
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.setMessageCompression(enable);
}
});
}
}
@Override
public final void request(final int numMessages) {
if (passThrough) {
realCall.request(numMessages);
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.request(numMessages);
}
});
}
}
@Override
public final void halfClose() {
delayOrExecute(new Runnable() {
@Override
public void run() {
realCall.halfClose();
}
});
}
@Override
public final boolean isReady() {
if (passThrough) {
return realCall.isReady();
} else {
return false;
}
}
@Override
public final Attributes getAttributes() {
ClientCall<ReqT, RespT> savedRealCall;
synchronized (this) {
savedRealCall = realCall;
}
if (savedRealCall != null) {
return savedRealCall.getAttributes();
} else {
return Attributes.EMPTY;
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("realCall", realCall)
.toString();
}
private final class CloseListenerRunnable extends ContextRunnable {
final Listener<RespT> listener;
final Status status;
CloseListenerRunnable(Listener<RespT> listener, Status status) {
super(context);
this.listener = listener;
this.status = status;
}
@Override
public void runInContext() {
listener.onClose(status, new Metadata());
}
}
private static final class DelayedListener<RespT> extends Listener<RespT> {
private final Listener<RespT> realListener;
private volatile boolean passThrough;
@GuardedBy("this")
private List<Runnable> pendingCallbacks = new ArrayList<>();
public DelayedListener(Listener<RespT> listener) {
this.realListener = listener;
}
private void delayOrExecute(Runnable runnable) {
synchronized (this) {
if (!passThrough) {
pendingCallbacks.add(runnable);
return;
}
}
runnable.run();
}
@Override
public void onHeaders(final Metadata headers) {
if (passThrough) {
realListener.onHeaders(headers);
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realListener.onHeaders(headers);
}
});
}
}
@Override
public void onMessage(final RespT message) {
if (passThrough) {
realListener.onMessage(message);
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realListener.onMessage(message);
}
});
}
}
@Override
public void onClose(final Status status, final Metadata trailers) {
delayOrExecute(new Runnable() {
@Override
public void run() {
realListener.onClose(status, trailers);
}
});
}
@Override
public void onReady() {
if (passThrough) {
realListener.onReady();
} else {
delayOrExecute(new Runnable() {
@Override
public void run() {
realListener.onReady();
}
});
}
}
void drainPendingCallbacks() {
assert !passThrough;
List<Runnable> toRun = new ArrayList<>();
while (true) {
synchronized (this) {
if (pendingCallbacks.isEmpty()) {
pendingCallbacks = null;
passThrough = true;
break;
}
// Since there were pendingCallbacks, we need to process them. To maintain ordering we
// can't set passThrough=true until we run all pendingCallbacks, but new Runnables may be
// added after we drop the lock. So we will have to re-check pendingCallbacks.
List<Runnable> tmp = toRun;
toRun = pendingCallbacks;
pendingCallbacks = tmp;
}
for (Runnable runnable : toRun) {
// Avoid calling listener while lock is held to prevent deadlocks.
// TODO(ejona): exception handling
runnable.run();
}
toRun.clear();
}
}
}
private static final ClientCall<Object, Object> NOOP_CALL = new ClientCall<Object, Object>() {
@Override
public void start(Listener<Object> responseListener, Metadata headers) {}
@Override
public void request(int numMessages) {}
@Override
public void cancel(String message, Throwable cause) {}
@Override
public void halfClose() {}
@Override
public void sendMessage(Object message) {}
// Always returns {@code false}, since this is only used when the startup of the call fails.
@Override
public boolean isReady() {
return false;
}
};
}