private void verifySize() { if (count > maxMessageSize) { throw Status.RESOURCE_EXHAUSTED.withDescription(String.format( "%s: Compressed frame exceeds maximum frame size: %d. Bytes read: %d. ", debugString, maxMessageSize, count)).asRuntimeException(); } } }
@Override public void onCompleted() { if (cancelled) { throw Status.CANCELLED.asRuntimeException(); } else { call.close(Status.OK, new Metadata()); } }
@Override public void onNext(RespT response) { if (cancelled) { throw Status.CANCELLED.asRuntimeException(); } if (!sentHeaders) { call.sendHeaders(new Metadata()); sentHeaders = true; } //TODO send header from here.. call.sendMessage(response); }
@Override public StreamObserver<SimpleRequest> streamThrowsErrorInStub( StreamObserver<SimpleResponse> responseObserver) { throw Status.ABORTED.withDescription("bad streaming stub").asRuntimeException(); }
@Override public void unaryThrowsError(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) { throw Status.ABORTED.withDescription("call aborted").asRuntimeException(); }
@Override public void onNext(SimpleRequest value) { throw Status.ABORTED.withDescription("bad streaming message").asRuntimeException(); }
@Override public void invoke(String req, StreamObserver<String> observer) { try { long delay = builder.segments.get(0).latency(); semaphore.acquire(); TimeUnit.MILLISECONDS.sleep(delay); observer.onNext("response"); observer.onCompleted(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); observer.onError(Status.UNKNOWN.asRuntimeException()); } finally { semaphore.release(); } } });
@Override public void unaryCall(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) { IllegalStateException e1 = new IllegalStateException("Exception 1"); IllegalArgumentException e2 = new IllegalArgumentException(); AssertionError e3 = new AssertionError("Exception 3"); Exceptions.clearTrace(e3); RuntimeException e4 = new RuntimeException("Exception 4"); e1.initCause(e2); e2.initCause(e3); e3.initCause(e4); Status status = Status.ABORTED.withCause(e1); responseObserver.onError(status.asRuntimeException()); } }
private ByteBufOrStream getCompressedBody(ByteBuf buf) { if (decompressor == Codec.Identity.NONE) { buf.release(); throw Status.INTERNAL.withDescription( DEBUG_STRING + ": Can't decode compressed frame as compression not configured.") .asRuntimeException(); } try { // Enforce the maxMessageSizeBytes limit on the returned stream. final InputStream unlimitedStream = decompressor.decompress(new ByteBufInputStream(buf, true)); return new ByteBufOrStream( new SizeEnforcingInputStream(unlimitedStream, maxMessageSizeBytes, DEBUG_STRING)); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public void batchPoll(TaskServicePb.BatchPollRequest req, StreamObserver<TaskPb.Task> response) { final int count = GRPC_HELPER.optionalOr(req.getCount(), 1); final int timeout = GRPC_HELPER.optionalOr(req.getTimeout(), POLL_TIMEOUT_MS); if (timeout > MAX_POLL_TIMEOUT_MS) { response.onError(Status.INVALID_ARGUMENT .withDescription("longpoll timeout cannot be longer than " + MAX_POLL_TIMEOUT_MS + "ms") .asRuntimeException() ); return; } try { List<Task> polledTasks = taskService.batchPoll(req.getTaskType(), req.getWorkerId(), GRPC_HELPER.optional(req.getDomain()), count, timeout); LOGGER.info("polled tasks: "+polledTasks); polledTasks.stream().map(PROTO_MAPPER::toProto).forEach(response::onNext); response.onCompleted(); } catch (Exception e) { GRPC_HELPER.onError(response, e); } }
/** Convert an entry's status from a protobuf to an {@link ApiException}. */ private ApiException createEntryError(com.google.rpc.Status protoStatus) { io.grpc.Status grpcStatus = io.grpc.Status.fromCodeValue(protoStatus.getCode()) .withDescription(protoStatus.getMessage()); StatusCode gaxStatusCode = GrpcStatusCode.of(grpcStatus.getCode()); return ApiExceptionFactory.createException( grpcStatus.asRuntimeException(), gaxStatusCode, retryableCodes.contains(gaxStatusCode.getCode())); }
@Override public void getTask(MetadataServicePb.GetTaskRequest req, StreamObserver<MetadataServicePb.GetTaskResponse> response) { TaskDef def = service.getTaskDef(req.getTaskType()); if (def != null) { TaskDefPb.TaskDef task = PROTO_MAPPER.toProto(def); response.onNext(MetadataServicePb.GetTaskResponse.newBuilder() .setTask(task) .build() ); response.onCompleted(); } else { response.onError(Status.NOT_FOUND .withDescription("No such TaskDef found by taskType=" + req.getTaskType()) .asRuntimeException() ); } }
@Test public void onMessage_deframeError_errorListenerThrows() { doThrow(Status.INTERNAL.asRuntimeException()) .when(deframer).deframe(isA(HttpData.class), anyBoolean()); doThrow(new IllegalStateException()) .when(transportStatusListener).transportReportStatus(isA(Status.class)); reader.onSubscribe(subscription); assertThatThrownBy(() -> reader.onNext(DATA)).isInstanceOf(IllegalStateException.class); verify(deframer).close(); }
/** * Checks expected error during receive. */ @Test public void receiveError() throws Exception { mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage(containsString(TEST_MESSAGE)); mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); mStream.receive(TIMEOUT); }
@Test public void onMessage_deframeError() { doThrow(Status.INTERNAL.asRuntimeException()) .when(deframer).deframe(isA(HttpData.class), anyBoolean()); reader.onSubscribe(subscription); reader.onNext(DATA); verify(deframer).deframe(DATA, false); verify(transportStatusListener).transportReportStatus(Status.INTERNAL); verify(deframer).close(); }
@Override public void getWorkflow(MetadataServicePb.GetWorkflowRequest req, StreamObserver<MetadataServicePb.GetWorkflowResponse > response) { try { WorkflowDef workflowDef = service.getWorkflowDef(req.getName(), GRPC_HELPER.optional(req.getVersion())); WorkflowDefPb.WorkflowDef workflow = PROTO_MAPPER.toProto(workflowDef); response.onNext(MetadataServicePb.GetWorkflowResponse.newBuilder() .setWorkflow(workflow) .build() ); response.onCompleted(); } catch (ApplicationException e) { // TODO replace this with gRPC exception interceptor. response.onError(Status.NOT_FOUND .withDescription("No such workflow found by name=" + req.getName()) .asRuntimeException() ); } }
/** * Checks expected error during send. */ @Test public void sendError() throws Exception { mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage(containsString(TEST_MESSAGE)); mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); mStream.send(WriteRequest.newBuilder().build(), TIMEOUT); }
/** * Checks receive fails immediately upon error even if buffer is full. */ @Test public void receiveErrorWhenBufferFull() throws Exception { mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage(containsString(TEST_MESSAGE)); WriteResponse[] responses = Stream.generate(() -> WriteResponse.newBuilder().build()) .limit(BUFFER_SIZE).toArray(WriteResponse[]::new); for (WriteResponse response : responses) { mResponseObserver.onNext(response); } mResponseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); for (WriteResponse response : responses) { WriteResponse actualResponse = mStream.receive(TIMEOUT); Assert.assertEquals(response, actualResponse); } }
@Test public void releaseOnError() { // Setup server final Server server = startServer((req, observer) -> { observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); }); // Make Client call final Channel channel = NettyChannelBuilder.forAddress("localhost", server.getPort()) .usePlaintext(true) .build(); try { ClientCalls.blockingUnaryCall(channel, METHOD_DESCRIPTOR, CallOptions.DEFAULT, "foo"); Assert.fail("Should have failed with UNKNOWN error"); } catch (StatusRuntimeException e) { // Verify Assert.assertEquals(Status.Code.INVALID_ARGUMENT, e.getStatus().getCode()); Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class)); Mockito.verify(listener, Mockito.times(1)).onIgnore(); } }
@Override public void onNext(StreamingOutputCallRequest request) { if (request.hasResponseStatus()) { dispatcher.cancel(); responseObserver.onError(Status.fromCodeValue(request.getResponseStatus().getCode()) .withDescription( request.getResponseStatus().getMessage()) .asRuntimeException()); return; } dispatcher.enqueue(toChunkQueue(request)); }