This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 119
/
HttpJsonClientCallImpl.java
493 lines (440 loc) · 19 KB
/
HttpJsonClientCallImpl.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
/*
* Copyright 2022 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.gax.httpjson;
import com.google.api.client.http.HttpTransport;
import com.google.api.gax.httpjson.ApiMethodDescriptor.MethodType;
import com.google.api.gax.httpjson.HttpRequestRunnable.ResultListener;
import com.google.api.gax.httpjson.HttpRequestRunnable.RunnableResult;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* This class serves as main implementation of {@link HttpJsonClientCall} for REST transport and is
* expected to be used for every REST call. It currently supports unary and server-streaming
* workflows. The overall behavior and surface of the class mimics as close as possible behavior of
* the corresponding ClientCall implementation in gRPC transport.
*
* <p>This class is thread-safe.
*
* @param <RequestT> call request type
* @param <ResponseT> call response type
*/
final class HttpJsonClientCallImpl<RequestT, ResponseT>
extends HttpJsonClientCall<RequestT, ResponseT> implements ResultListener {
//
// A lock to guard the state of this call (and the response stream).
//
private final Object lock = new Object();
// An active delivery loop marker.
@GuardedBy("lock")
private boolean inDelivery = false;
// A queue to keep "scheduled" calls to HttpJsonClientCall.Listener<ResponseT> in a form of tasks.
// It may seem like an overkill, but it exists to implement the following listeners contract:
// - onHeaders() must be called before any onMessage();
// - onClose() must be the last call made, no onMessage() or onHeaders() are allowed after that;
// - while methods on the same listener may be called from different threads they must never be
// called simultaneously;
// - listeners should not be called under the internal lock of the client call to reduce risk of
// deadlocking and minimize time spent under lock;
// - a specialized notifications' dispatcher thread may be used in the future to send
// notifications (not the case right now).
@GuardedBy("lock")
private final Queue<NotificationTask<ResponseT>> pendingNotifications = new ArrayDeque<>();
//
// Immutable API method-specific data.
//
private final HttpJsonCallOptions callOptions;
private final String endpoint;
private final ApiMethodDescriptor<RequestT, ResponseT> methodDescriptor;
private final HttpTransport httpTransport;
private final Executor executor;
//
// Request-specific data (provided by client code) before we get a response.
//
@GuardedBy("lock")
private HttpJsonMetadata requestHeaders;
@GuardedBy("lock")
private Listener<ResponseT> listener;
@GuardedBy("lock")
private int pendingNumMessages;
//
// Response-specific data (received from server).
//
@GuardedBy("lock")
private HttpRequestRunnable<RequestT, ResponseT> requestRunnable;
@GuardedBy("lock")
private RunnableResult runnableResult;
@GuardedBy("lock")
private ProtoMessageJsonStreamIterator responseStreamIterator;
@GuardedBy("lock")
private boolean closed;
HttpJsonClientCallImpl(
ApiMethodDescriptor<RequestT, ResponseT> methodDescriptor,
String endpoint,
HttpJsonCallOptions callOptions,
HttpTransport httpTransport,
Executor executor) {
this.methodDescriptor = methodDescriptor;
this.endpoint = endpoint;
this.callOptions = callOptions;
this.httpTransport = httpTransport;
this.executor = executor;
this.closed = false;
}
@Override
public void setResult(RunnableResult runnableResult) {
Preconditions.checkNotNull(runnableResult);
synchronized (lock) {
if (closed) {
return;
}
Preconditions.checkState(this.runnableResult == null, "The call result is already set");
this.runnableResult = runnableResult;
if (runnableResult.getResponseHeaders() != null) {
pendingNotifications.offer(
new OnHeadersNotificationTask<>(listener, runnableResult.getResponseHeaders()));
}
}
// trigger delivery loop if not already running
deliver();
}
@Override
public void start(Listener<ResponseT> responseListener, HttpJsonMetadata requestHeaders) {
Preconditions.checkNotNull(responseListener);
Preconditions.checkNotNull(requestHeaders);
synchronized (lock) {
if (closed) {
return;
}
Preconditions.checkState(this.listener == null, "The call is already started");
this.listener = responseListener;
this.requestHeaders = requestHeaders;
}
}
@Override
public void request(int numMessages) {
if (numMessages < 0) {
throw new IllegalArgumentException("numMessages must be non-negative");
}
synchronized (lock) {
if (closed) {
return;
}
pendingNumMessages += numMessages;
}
// trigger delivery loop if not already running
deliver();
}
@Override
public void cancel(@Nullable String message, @Nullable Throwable cause) {
Throwable actualCause = cause;
if (actualCause == null) {
actualCause = new CancellationException(message);
}
synchronized (lock) {
close(499, message, actualCause, true);
}
// trigger delivery loop if not already running
deliver();
}
@Override
public void sendMessage(RequestT message) {
Preconditions.checkNotNull(message);
HttpRequestRunnable<RequestT, ResponseT> localRunnable;
synchronized (lock) {
if (closed) {
return;
}
Preconditions.checkState(listener != null, "The call hasn't been started");
Preconditions.checkState(
requestRunnable == null,
"The message has already been sent. Bidirectional streaming calls are not supported");
requestRunnable =
new HttpRequestRunnable<>(
message,
methodDescriptor,
endpoint,
callOptions,
httpTransport,
requestHeaders,
this);
localRunnable = requestRunnable;
}
executor.execute(localRunnable);
}
@Override
public void halfClose() {
// no-op for now, as halfClose makes sense only for bidirectional streams.
}
private void deliver() {
// A flag stored in method stack space to detect when we enter a delivery loop (regardless if
// it is a concurrent thread or a recursive call execution of delivery() method within the same
// thread).
boolean newActiveDeliveryLoop = true;
boolean allMessagesConsumed = false;
while (true) {
// The try block around listener notification logic. We need to keep this
// block inside the loop to make sure that in case onMessage() call throws, we close the
// request properly and call onClose() method on listener once eventually (because the
// listener can be called only inside this loop).
try {
// Check if there is only one delivery loop active. Exit if a competing delivery loop
// detected (either in a concurrent thread or in a previous recursive call to this method in
// the same thread). The last-standing delivery loop will do all the job. Even if something
// in this loop throws, the code will first go through this block before exiting the loop to
// make sure that the activeDeliveryLoops counter stays correct.
//
// Note, we must enter the loop before doing the check.
synchronized (lock) {
if (inDelivery && newActiveDeliveryLoop) {
// EXIT delivery loop because another active delivery loop has been detected.
break;
}
newActiveDeliveryLoop = false;
inDelivery = true;
}
if (Thread.interrupted()) {
// The catch block below will properly cancel the call. Note Thread.interrupted() clears
// the interruption flag on this thread, so we don't throw forever.
throw new InterruptedException("Message delivery has been interrupted");
}
// All listeners must be called under delivery loop (but outside the lock) to ensure that no
// two notifications come simultaneously from two different threads and that we do not go
// indefinitely deep in the stack if delivery logic is called recursively via listeners.
notifyListeners();
// The synchronized block around message reading and cancellation notification processing
// logic
synchronized (lock) {
if (allMessagesConsumed) {
// allMessagesProcessed was set to true on previous loop iteration. We do it this
// way to make sure that notifyListeners() is called in between consuming the last
// message in a stream and closing the call.
// This is to make sure that onMessage() for the last message in a stream is called
// before closing this call, because that last onMessage() listener execution may change
// how the call has to be closed (normally or cancelled).
// Close the call normally.
// once close() is called we will never ever enter this again, because `close` flag
// will be set to true by the close() method. If the call is already closed, close()
// will have no effect.
allMessagesConsumed = false;
close(
runnableResult.getStatusCode(),
runnableResult.getTrailers().getStatusMessage(),
runnableResult.getTrailers().getException(),
false);
}
// Attempt to terminate the delivery loop if:
// `runnableResult == null` => there is no response from the server yet;
// `pendingNumMessages <= 0` => we have already delivered as much as has been asked;
// `closed` => this call has been closed already;
if (runnableResult == null || pendingNumMessages <= 0 || closed) {
// The loop terminates only when there are no pending notifications left. The check
// happens under the lock, so no other thread may add a listener notification task in
// the middle of this logic.
if (pendingNotifications.isEmpty()) {
// EXIT delivery loop because there is no more work left to do. This is expected to be
// the only active delivery loop.
inDelivery = false;
break;
} else {
// We still have some stuff in notiticationTasksQueue so continue the loop, most
// likely we will finally terminate on the next cycle.
continue;
}
}
pendingNumMessages--;
allMessagesConsumed = consumeMessageFromStream();
}
} catch (Throwable e) {
// Exceptions in message delivery result into cancellation of the call to stay consistent
// with other transport implementations.
HttpJsonStatusRuntimeException ex =
new HttpJsonStatusRuntimeException(499, "Exception in message delivery", e);
// If we are already closed the exception will be swallowed, which is the best thing we
// can do in such an unlikely situation (otherwise we would stay forever in the delivery
// loop).
synchronized (lock) {
// Close the call immediately marking it cancelled. If already closed close() will have no
// effect.
close(ex.getStatusCode(), ex.getMessage(), ex, true);
}
}
}
}
private void notifyListeners() {
while (true) {
NotificationTask<ResponseT> notification;
synchronized (lock) {
if (pendingNotifications.isEmpty()) {
return;
}
notification = pendingNotifications.poll();
}
notification.call();
}
}
@GuardedBy("lock")
private boolean consumeMessageFromStream() throws IOException {
if (runnableResult.getTrailers().getException() != null
|| runnableResult.getResponseContent() == null) {
// Server returned an error, no messages to process. This will result into closing a call with
// an error.
return true;
}
boolean allMessagesConsumed;
Reader responseReader;
if (methodDescriptor.getType() == MethodType.SERVER_STREAMING) {
// Lazily initialize responseStreamIterator in case if it is a server steraming response
if (responseStreamIterator == null) {
responseStreamIterator =
new ProtoMessageJsonStreamIterator(
new InputStreamReader(runnableResult.getResponseContent(), StandardCharsets.UTF_8));
}
if (responseStreamIterator.hasNext()) {
responseReader = responseStreamIterator.next();
} else {
return true;
}
// To make sure that the call will be closed immediately once we read the last
// message from the response (otherwise we would need to wait for another request(1)
// from the client to check if there is anything else left in the stream).
allMessagesConsumed = !responseStreamIterator.hasNext();
} else {
responseReader =
new InputStreamReader(runnableResult.getResponseContent(), StandardCharsets.UTF_8);
// Unary calls have only one message in their response, so we should be ready to close
// immediately after delivering a single response message.
allMessagesConsumed = true;
}
ResponseT message =
methodDescriptor.getResponseParser().parse(responseReader, callOptions.getTypeRegistry());
pendingNotifications.offer(new OnMessageNotificationTask<>(listener, message));
return allMessagesConsumed;
}
@GuardedBy("lock")
private void close(
int statusCode, String message, Throwable cause, boolean terminateImmediatelly) {
try {
if (closed) {
return;
}
closed = true;
// Best effort task cancellation (to not be confused with task's thread interruption).
// If the task is in blocking I/O waiting for the server response, it will keep waiting for
// the response from the server, but once response is received the task will exit silently.
// If the task has already completed, this call has no effect.
if (requestRunnable != null) {
requestRunnable.cancel();
requestRunnable = null;
}
HttpJsonMetadata.Builder meatadaBuilder = HttpJsonMetadata.newBuilder();
if (runnableResult != null && runnableResult.getTrailers() != null) {
meatadaBuilder = runnableResult.getTrailers().toBuilder();
}
meatadaBuilder.setException(cause);
meatadaBuilder.setStatusMessage(message);
if (responseStreamIterator != null) {
responseStreamIterator.close();
}
if (runnableResult != null && runnableResult.getResponseContent() != null) {
runnableResult.getResponseContent().close();
}
// onClose() suppresses all other pending notifications.
// there should be no place in the code which inserts something in this queue before checking
// the `closed` flag under the lock and refusing to insert anything if `closed == true`.
if (terminateImmediatelly) {
// This usually means we are cancelling the call before processing the response in full.
// It may happen if a user explicitly cancels the call or in response to an unexpected
// exception either from server or a call listener execution.
pendingNotifications.clear();
}
pendingNotifications.offer(
new OnCloseNotificationTask<>(listener, statusCode, meatadaBuilder.build()));
} catch (Throwable e) {
// suppress stream closing exceptions in favor of the actual call closing cause. This method
// should not throw, otherwise we may stuck in an infinite loop of exception processing.
}
}
//
// Listener notification tasks. Each class simply calls only one specific method on the Listener
// interface, and to do so it also stores tha parameters needed to make the all.
//
private abstract static class NotificationTask<ResponseT> {
private final Listener<ResponseT> listener;
NotificationTask(Listener<ResponseT> listener) {
this.listener = listener;
}
protected Listener<ResponseT> getListener() {
return listener;
}
abstract void call();
}
private static class OnHeadersNotificationTask<ResponseT> extends NotificationTask<ResponseT> {
private final HttpJsonMetadata responseHeaders;
OnHeadersNotificationTask(Listener<ResponseT> listener, HttpJsonMetadata responseHeaders) {
super(listener);
this.responseHeaders = responseHeaders;
}
public void call() {
getListener().onHeaders(responseHeaders);
}
}
private static class OnMessageNotificationTask<ResponseT> extends NotificationTask<ResponseT> {
private final ResponseT message;
OnMessageNotificationTask(Listener<ResponseT> listener, ResponseT message) {
super(listener);
this.message = message;
}
public void call() {
getListener().onMessage(message);
}
}
private static class OnCloseNotificationTask<ResponseT> extends NotificationTask<ResponseT> {
private final int statusCode;
private final HttpJsonMetadata trailers;
OnCloseNotificationTask(
Listener<ResponseT> listener, int statusCode, HttpJsonMetadata trailers) {
super(listener);
this.statusCode = statusCode;
this.trailers = trailers;
}
public void call() {
getListener().onClose(statusCode, trailers);
}
}
}