@Override public void onError(final Throwable cause) { log.warn("Keep alive failed, due to {}, renew it", Status.fromThrowable(cause)); heartbeat(leaseId); } };
private void invokeOnReady() { try { listener.onReady(); } catch (Throwable t) { close(Status.fromThrowable(t), EMPTY_METADATA); } }
private void invokeOnMessage(I request) { try (SafeCloseable ignored = ctx.push()) { listener.onMessage(request); } catch (Throwable t) { close(Status.fromThrowable(t), EMPTY_METADATA); } }
private void invokeHalfClose() { try (SafeCloseable ignored = ctx.push()) { listener.onHalfClose(); } catch (Throwable t) { close(Status.fromThrowable(t), EMPTY_METADATA); } }
private void invokeOnCancel() { try (SafeCloseable ignored = ctx.push()) { listener.onCancel(); } catch (Throwable t) { if (!closeCalled) { // A custom error when dealing with client cancel or transport issues should be // returned. We have already closed the listener, so it will not receive any more // callbacks as designed. close(Status.fromThrowable(t), EMPTY_METADATA); } } }
ApiException gaxException = ApiExceptionFactory.createException( cause, GrpcStatusCode.of(Status.fromThrowable(cause).getCode()), false); logger.log(Level.SEVERE, "terminated streaming with exception", gaxException); notifyFailed(gaxException);
/** * Async client-streaming example. Sends {@code numPoints} randomly chosen points from {@code * features} with a variable delay in between. Prints the statistics when they are sent from the * server. */ public void recordRoute(List<Feature> features, int numPoints) throws InterruptedException { System.out.println("*** RecordRoute"); stub.recordRoute(exchange -> { RouteSender sender = new RouteSender(features, exchange); exchange.handler(ar -> { sender.result = ar; if (ar.succeeded()) { RouteSummary summary = ar.result(); System.out.println("Finished trip with " + summary.getPointCount() + " points. Passed " + summary.getFeatureCount() + " features.Travelled " + summary.getDistance() + " meters. It took " + summary.getElapsedTime() + " seconds."); System.out.println("Finished RecordRoute"); } else { System.out.println("RecordRoute Failed: " + Status.fromThrowable(ar.cause())); } }); // Send numPoints points randomly selected from the features list. sender.send(numPoints); }); }
private void doSendMessage(O message) { checkState(sendHeadersCalled, "sendHeaders has not been called"); checkState(!closeCalled, "call is closed"); if (firstResponse == null) { firstResponse = message; } try { res.write(messageFramer.writePayload(marshaller.serializeResponse(message))); res.onDemand(() -> { if (pendingMessagesUpdater.decrementAndGet(this) == 0) { if (useBlockingTaskExecutor) { ctx.blockingTaskExecutor().execute(this::invokeOnReady); } else { invokeOnReady(); } } }); } catch (RuntimeException e) { close(Status.fromThrowable(e), EMPTY_METADATA); throw e; } catch (Throwable t) { close(Status.fromThrowable(t), EMPTY_METADATA); throw new RuntimeException(t); } }
/** * Creates a new exception based on {@code cause}. If {@code cause} indicates cancellation, {@code * context} will be inspected to establish the type of cancellation. * * <p>Intended for internal library use; user code should use {@link * #newSpannerException(ErrorCode, String)} instead of this method. */ public static SpannerException newSpannerException(@Nullable Context context, Throwable cause) { if (cause instanceof SpannerException) { SpannerException e = (SpannerException) cause; return newSpannerExceptionPreformatted(e.getErrorCode(), e.getMessage(), e); } else if (cause instanceof CancellationException) { return newSpannerExceptionForCancellation(context, cause); } // Extract gRPC status. This will produce "UNKNOWN" for non-gRPC exceptions. Status status = Status.fromThrowable(cause); if (status.getCode() == Status.Code.CANCELLED) { return newSpannerExceptionForCancellation(context, cause); } return newSpannerException(ErrorCode.fromGrpcStatus(status), cause.getMessage(), cause); }
/** * Dispatches the current response chunk to the client. This is only called by the executor. At * any time, a given dispatch task should only be registered with the executor once. */ private synchronized void dispatchChunk() { if (cancelled) { return; } try { // Pop off the next chunk and send it to the client. Chunk chunk = chunks.remove(); if (chunk == completionChunk) { responseStream.onCompleted(); } else { responseStream.onNext(chunk.toResponse()); } } catch (Throwable e) { failure = e; if (Status.fromThrowable(e).getCode() == Status.CANCELLED.getCode()) { // Stream was cancelled by client, responseStream.onError() might be called already or // will be called soon by inbounding StreamObserver. chunks.clear(); } else { responseStream.onError(e); } } }
final Status s = Status.fromThrowable(t); if (s.getCode() != Code.UNKNOWN) { return s;
@Override public void messageRead(ByteBufOrStream message) { try { final O msg = marshaller.deserializeResponse(message); if (firstResponse == null) { firstResponse = msg; } if (unsafeWrapResponseBuffers && message.buf() != null) { GrpcUnsafeBufferUtil.storeBuffer(message.buf(), msg, ctx); } try (SafeCloseable ignored = ctx.push()) { listener.onMessage(msg); } } catch (Throwable t) { req.close(Status.fromThrowable(t).asException()); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } }
} catch (Throwable t) { call.setListener(new EmptyListener<>()); call.close(Status.fromThrowable(t), EMPTY_METADATA); logger.warn( "Exception thrown from streaming request stub method before processing any request data" +
@Test public void cancelAfterBegin() throws Exception { final StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create(); final StreamObserver<StreamingInputCallRequest> requestObserver = asyncStub.streamingInputCall(responseObserver); requestObserver.onError(new RuntimeException()); responseObserver.awaitCompletion(); assertThat(responseObserver.getValues()).isEmpty(); assertThat(Status.fromThrowable(responseObserver.getError()).getCode()).isEqualTo(Code.CANCELLED); final RequestLog log = requestLogQueue.take(); assertThat(log.availabilities()).contains(RequestLogAvailability.COMPLETE); assertThat(log.responseContent()).isInstanceOf(RpcResponse.class); final Throwable cause = ((RpcResponse) log.responseContent()).cause(); assertThat(cause).isInstanceOf(StatusException.class); assertThat(((StatusException) cause).getStatus().getCode()).isEqualTo(Code.CANCELLED); }
/** * Bi-directional example, which can only be asynchronous. Send some chat messages, and print any * chat messages that are sent from the server. */ public void routeChat() { System.out.println("*** RouteChat"); stub.routeChat(exchange -> { exchange.handler(note -> { System.out.println("Got message \"" + note.getMessage() + "\" at " + note.getLocation().getLatitude() + ", " + note.getLocation().getLongitude()); }); exchange.exceptionHandler(err -> { System.out.println("RouteChat Failed: " + Status.fromThrowable(err)); }); exchange.endHandler(v -> { System.out.println("Finished RouteChat"); }); RouteNote[] requests = {newNote("First message", 0, 0), newNote("Second message", 0, 1), newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)}; for (RouteNote request : requests) { System.out.println("Sending message \"" + request.getMessage() + "\" at " + request.getLocation() .getLatitude() + ", " + request.getLocation().getLongitude()); exchange.write(request); } exchange.end(); }); }
assertThat(Status.fromThrowable(captor.getValue()).getCode()).isEqualTo(Status.UNKNOWN.getCode()); assertThat(Status.fromThrowable(captor.getValue()).getDescription()).isEqualTo(errorMessage); verifyNoMoreInteractions(responseObserver);
@Test public void cancelAfterFirstResponse() throws Exception { final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters(ResponseParameters.newBuilder() .setSize(31415)) .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[27182]))) .build(); final StreamingOutputCallResponse goldenResponse = StreamingOutputCallResponse.newBuilder() .setPayload(Payload.newBuilder() .setType(COMPRESSABLE) .setBody(ByteString.copyFrom(new byte[31415]))) .build(); final StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create(); final StreamObserver<StreamingOutputCallRequest> requestObserver = asyncStub.fullDuplexCall(responseObserver); requestObserver.onNext(request); await().untilAsserted(() -> assertThat(responseObserver.firstValue().get()).isEqualTo(goldenResponse)); requestObserver.onError(new RuntimeException()); responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS); assertThat(responseObserver.getValues()).hasSize(1); assertThat(Status.fromThrowable(responseObserver.getError()).getCode()).isEqualTo(Code.CANCELLED); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.params()).containsExactly(request); assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED); }); }
@Override public void start(Listener<O> responseListener, Metadata unused) { requireNonNull(responseListener, "responseListener"); final Compressor compressor; if (callOptions.getCompressor() != null) { compressor = compressorRegistry.lookupCompressor(callOptions.getCompressor()); if (compressor == null) { responseListener.onClose( Status.INTERNAL.withDescription( "Unable to find compressor by name " + callOptions.getCompressor()), EMPTY_METADATA); return; } } else { compressor = Identity.NONE; } messageFramer.setCompressor(compressor); prepareHeaders(req.headers(), compressor); listener = responseListener; final HttpResponse res; try (SafeCloseable ignored = ctx.push()) { res = httpClient.execute(ctx, req); } catch (Exception e) { close(Status.fromThrowable(e)); return; } res.subscribe(responseReader, ctx.eventLoop(), true); res.completionFuture().handleAsync(responseReader, ctx.eventLoop()); }
private void doSendMessage(I message) { try { if (!ctx.log().isAvailable(RequestLogAvailability.REQUEST_CONTENT)) { ctx.logBuilder().requestContent(GrpcLogUtil.rpcRequest(method, message), null); } final ByteBuf serialized = marshaller.serializeRequest(message); req.write(messageFramer.writePayload(serialized)); req.onDemand(() -> { if (pendingMessagesUpdater.decrementAndGet(this) == 0) { try (SafeCloseable ignored = ctx.push()) { listener.onReady(); } catch (Throwable t) { close(Status.fromThrowable(t)); } } }); } catch (Throwable t) { cancel(null, t); } }
assertThat(Status.fromThrowable(recorder.getError()).getCode()) .isEqualTo(Status.DEADLINE_EXCEEDED.getCode());