@Override public void store(StoreRequest request, StreamObserver<StoreResponse> responseObserver) { try { responseObserver.onNext(indexManger.storeDocument(request)); responseObserver.onCompleted(); } catch (Exception e) { log.error("Failed to store: <" + request.getUniqueId() + "> in index <" + request.getIndexName() + ">: " + e.getClass().getSimpleName() + ": ", e); Metadata m = new Metadata(); m.put(MetaKeys.ERROR_KEY, e.getMessage()); responseObserver.onError(new StatusRuntimeException(Status.UNKNOWN, m)); if (request.hasResultDocument()) { try { if (request.getResultDocument().hasDocument()) { BasicBSONObject document = (BasicBSONObject) BSON.decode(request.getResultDocument().getDocument().toByteArray()); log.error(document.toString()); } } catch (Exception e2) { } } } }
public MetaProto.StringListType listDatabases() { MetaProto.NoneType none = MetaProto.NoneType.newBuilder().build(); MetaProto.StringListType stringList; MetaProto.StringListType.Builder builder = MetaProto.StringListType.newBuilder(); try { stringList = metaBlockingStub.listDatabases(none); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); stringList = MetaProto.StringListType.newBuilder().build(); return stringList; } logger.info("Databases list : " + stringList); return stringList; }
public MetaProto.StringListType listTables(String dbName) { MetaProto.DbNameParam databaseName = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.StringListType stringList; try { stringList = metaBlockingStub.listTables(databaseName); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); stringList = MetaProto.StringListType.newBuilder().build(); return stringList; } logger.info("Tables list : " + stringList); return stringList; }
public MetaProto.StringListType listColumns(String dbName, String tblName) { MetaProto.DbNameParam dbNameParam = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.TblNameParam tblNameParam = MetaProto.TblNameParam.newBuilder() .setTable(tblName) .build(); MetaProto.DbTblParam dbTblParam = MetaProto.DbTblParam.newBuilder() .setDatabase(dbNameParam) .setTable(tblNameParam) .build(); MetaProto.StringListType stringList; try { stringList = metaBlockingStub.listColumns(dbTblParam); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); stringList = MetaProto.StringListType.newBuilder().build(); return stringList; } logger.info("Columns list : " + stringList); return stringList; }
public MetaProto.StringListType listColumnsDataType(String dbName, String tblName) { MetaProto.DbNameParam dbNameParam = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.TblNameParam tblNameParam = MetaProto.TblNameParam.newBuilder() .setTable(tblName) .build(); MetaProto.DbTblParam dbTblParam = MetaProto.DbTblParam.newBuilder() .setDatabase(dbNameParam) .setTable(tblNameParam) .build(); MetaProto.StringListType stringList; try { stringList = metaBlockingStub.listColumnsDataType(dbTblParam); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); stringList = MetaProto.StringListType.newBuilder().build(); return stringList; } logger.info("ColumnsDataType list : " + stringList); return stringList; }
public MetaProto.DbParam getDatabase(String dbName) { MetaProto.DbNameParam databaseName = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.DbParam database; try { database = metaBlockingStub.getDatabase(databaseName); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); database = MetaProto.DbParam.newBuilder().setIsEmpty(false).build(); return database; } logger.info("Database is : " + database); return database; }
public MetaProto.TblParam getTable(String dbName, String tblName) { MetaProto.DbNameParam databaseName = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.TblNameParam tableName = MetaProto.TblNameParam.newBuilder() .setTable(tblName) .build(); MetaProto.DbTblParam databaseTable = MetaProto.DbTblParam.newBuilder() .setDatabase(databaseName) .setTable(tableName) .build(); MetaProto.TblParam table; try { table = metaBlockingStub.getTable(databaseTable); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); table = MetaProto.TblParam.newBuilder().build(); return table; } logger.info("Table is : " + table); return table; }
public StatusProto.ResponseStatus deleteTable(String dbName, String tblName) { MetaProto.DbNameParam databaseName = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); MetaProto.TblNameParam tableName = MetaProto.TblNameParam.newBuilder() .setTable(tblName) .build(); MetaProto.DbTblParam databaseTable = MetaProto.DbTblParam.newBuilder() .setDatabase(databaseName) .setTable(tableName) .build(); StatusProto.ResponseStatus status; try { status = metaBlockingStub.deleteTable(databaseTable); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); status = StatusProto.ResponseStatus.newBuilder().build(); return status; } logger.info("Delete table status is : " + status.getStatus()); return status; }
public StatusProto.ResponseStatus deleteDatabase(String dbName) { MetaProto.DbNameParam databaseName = MetaProto.DbNameParam.newBuilder() .setDatabase(dbName) .build(); StatusProto.ResponseStatus status; try { status = metaBlockingStub.deleteDatabase(databaseName); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); status = StatusProto.ResponseStatus.newBuilder().setStatus(StatusProto.ResponseStatus.State.DELETE_DATABASE_ERROR).build(); return status; } logger.info("Delete database status is : " + status.getStatus()); return status; }
public MetaProto.StorageFormatParam getStorageFormat(String storageFormatName) { MetaProto.StorageFormatParam storageFormat; if (nameValidate(storageFormatName)) { MetaProto.GetStorageFormatParam getStorageFormatParam = MetaProto.GetStorageFormatParam.newBuilder() .setStorageFormatName(storageFormatName) .build(); try { storageFormat = metaBlockingStub.getStorageFormat(getStorageFormatParam); } catch (StatusRuntimeException e) { storageFormat = MetaProto.StorageFormatParam.newBuilder().setIsEmpty(true).build(); return storageFormat; } } else { storageFormat = MetaProto.StorageFormatParam.newBuilder().setIsEmpty(true).build(); } logger.info("Create storage format status is : " + storageFormat); return storageFormat; }
public StatusProto.ResponseStatus createFunc(String funcName, byte[] funcContent) { boolean funcNameFormat = nameValidate(funcName); boolean funcNameLen = lengthValidate(funcName); StatusProto.ResponseStatus status; if (funcNameFormat & funcNameLen) { ByteString byteString = ByteString.copyFrom(funcContent); MetaProto.FuncParam func = MetaProto.FuncParam.newBuilder() .setFuncName(funcName) .setFuncContent(byteString).build(); try { status = metaBlockingStub.createFunc(func); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); status = StatusProto.ResponseStatus.newBuilder().build(); return status; } } else { status = StatusProto.ResponseStatus.newBuilder().build(); } logger.info("Create fiber function status is : " + status.getStatus()); return status; }
public MetaProto.FuncParam getFunc(String funcName) { MetaProto.FuncParam funcParam; if (nameValidate(funcName)) { MetaProto.GetFuncParam getFuncParam = MetaProto.GetFuncParam.newBuilder() .setFuncName(funcName) .build(); try { funcParam = metaBlockingStub.getFunc(getFuncParam); } catch (StatusRuntimeException e) { funcParam = MetaProto.FuncParam.newBuilder().build(); return funcParam; } } else { funcParam = MetaProto.FuncParam.newBuilder().setIsEmpty(true).build(); } logger.info("Create storage format status is : " + funcParam); return funcParam; }
@Override public StreamObserver<Message> invoke(StreamObserver<Message> responseObserver) { try { this.remote = RpcContext.getContext().getAttachment(Constants.REMOTE_ADDRESS); Class<?> requestType = grpcMethodType.requestType(); PoJo2ProtoStreamObserver servserResponseObserver = PoJo2ProtoStreamObserver.newObserverWrap(responseObserver); Object result = method.invoke(serviceToInvoke, servserResponseObserver); return Proto2PoJoStreamObserver.newObserverWrap((StreamObserver<Object>) result, requestType); } catch (Throwable e) { String stackTrace = ThrowableUtil.stackTraceToString(e); log.error(e.getMessage(), e); StatusRuntimeException statusException = Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException(); responseObserver.onError(statusException); } finally { log.debug(String.format("Service: %s Method: %s RemoteAddress: %s", providerUrl.getServiceInterface(), method.getName(), this.remote)); } return null; }
private void streamCall(Message request, StreamObserver<Message> responseObserver) { try { Class<?> requestType = grpcMethodType.requestType(); Object reqPojo = SerializerUtil.protobuf2Pojo(request, requestType); Object[] requestParams = new Object[] {reqPojo, PoJo2ProtoStreamObserver.newObserverWrap(responseObserver)}; method.invoke(serviceToInvoke, requestParams); } catch (Throwable e) { String stackTrace = ThrowableUtil.stackTraceToString(e); log.error(e.getMessage(), e); StatusRuntimeException statusException = Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException(); responseObserver.onError(statusException); } finally { log.debug(String.format("Service: %s Method: %s RemoteAddress: %s", providerUrl.getServiceInterface(), method.getName(), this.remote)); } }
@Override public void publish(@NonNull MSG_Facts request, @NonNull StreamObserver<MSG_Empty> responseObserver) { List<Fact> facts = request.getFactList().stream().map(converter::fromProto).collect( Collectors.toList()); final int size = facts.size(); log.debug("publish {} fact{}", size, size > 1 ? "s" : ""); log.trace("publish {}", facts); try { log.trace("store publish {}", facts); store.publish(facts); log.trace("store publish done"); responseObserver.onNext(MSG_Empty.getDefaultInstance()); responseObserver.onCompleted(); } catch (Throwable e) { log.error("Problem while publishing: ", e); responseObserver.onError(new StatusRuntimeException(Status.INTERNAL.withDescription(e .getMessage()))); } }
@Test public void getAllAuthoritiesRejected() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken( DEFAULT_EMAIL, DEFAULT_PASSWORD, Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); SecurityContextHolder.getContext().setAuthentication(authentication); try { List<String> roles = new ArrayList<>(); stub.getAllAuthorities(Empty.getDefaultInstance()).forEachRemaining(role -> roles.add(role.getValue())); failBecauseExceptionWasNotThrown(StatusRuntimeException.class); } catch (StatusRuntimeException e){ assertThat(e.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); } }
/** * Blocking unary call example. Calls getFeature and prints the response. */ public void getFeature(int lat, int lon) { info("*** GetFeature: lat={0} lon={1}", lat, lon); Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); Feature feature; try { feature = blockingStub.getFeature(request); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } if (RouteGuideUtil.exists(feature)) { info("Found feature called \"{0}\" at {1}, {2}", feature.getName(), RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } else { info("Found no feature at {0}, {1}", RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } }
/** * Blocking server-streaming example. Calls listFeatures with a rectangle of interest. Prints each * response feature as it arrives. */ public void listFeatures(int lowLat, int lowLon, int hiLat, int hiLon) { info("*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", lowLat, lowLon, hiLat, hiLon); Rectangle request = Rectangle.newBuilder() .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build()) .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()).build(); Iterator<Feature> features; try { features = blockingStub.listFeatures(request); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } StringBuilder responseLog = new StringBuilder("Result: "); while (features.hasNext()) { Feature feature = features.next(); responseLog.append(feature); } info(responseLog.toString()); }
/** * Executes the given {@code task} asynchronously. * * <p>If an error happened during the {@code task} execution it may be either sent to * the {@link #errorCallback} if it is <i>supported</i> by the callback, or rethrown otherwise. * * @param task the operation to execute * @see ErrorCallback for the list of <i>supported</i> errors */ protected void execute(Runnable task) { checkNotNull(task); executor.execute(() -> { try { task.run(); } catch (StatusRuntimeException e) { if (e.getStatus() .getCode() == UNAVAILABLE && errorCallback != null) { errorCallback.onNetworkError(); } else { throw e; } } }); }
@Test public void throwsErrorOnRpcTimeout() { int serverPort = testServer.getGrpcServerPort(); ImmutableList<String> args = ImmutableList.<String>builder() .addAll(makeArgs(serverPort, TEST_UNARY_METHOD)) .add(makeArgument("output_file_path", responseFilePath.toString())) .add(makeArgument("deadline_ms", "1")) // Small enough to guarantee a timeout. .build(); setStdinContents(MessageWriter.writeJsonStream(ImmutableList.of(REQUEST))); // Run the full client. try { me.dinowernli.grpc.polyglot.Main.main(args.toArray(new String[0])); throw new RuntimeException("The rpc should have timed out and thrown"); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); assertThat(rootCause).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) rootCause).getStatus().getCode()) .isEqualTo(Status.DEADLINE_EXCEEDED.getCode()); } }
/** * Checks whether an exception indicates that a dataset has been * removed by a worker, and it may need to be reconstructed. * Returns true if the reconstruction is attempted. */ boolean checkMissingDataset(Throwable throwable) { if (!(throwable instanceof StatusRuntimeException)) return false; StatusRuntimeException sre = (StatusRuntimeException)throwable; String description = sre.getStatus().getDescription(); if (description != null && description.contains("DatasetMissing")) { RpcTarget.Id[] toDelete = this.request.getDatasetSourceIds(); for (RpcTarget.Id s: toDelete) { HillviewLogger.instance.info("Trying to fix missing remote object", "{0}", s); RpcObjectManager.instance.deleteObject(s); } // Try to re-execute this request; this will trigger rebuilding the sources. RpcServer.execute(this.request, this.context); return true; } return false; }
/** * @see AIDataService#voiceRequest(InputStream, RequestExtras, AIServiceContext) */ @Override public AIResponse voiceRequest(InputStream voiceStream, RequestExtras requestExtras, AIServiceContext serviceContext) throws AIServiceException { RecognizeResponse response; try { SpeechClient speechClient = SpeechClient.create(); RecognitionAudio recognitionAudio = createRecognitionAudio(voiceStream); response = speechClient.recognize(config.getRecognitionConfig(), recognitionAudio); } catch (IOException | StatusRuntimeException e) { throw new AIServiceException("Failed to recognize speech", e); } if ((response.getResultsCount() == 0) || (response.getResults(0).getAlternativesCount() == 0)) { throw new AIServiceException("No speech"); } String transcript = response.getResults(0).getAlternatives(0).getTranscript(); AIRequest request = new AIRequest(transcript); return request(request, requestExtras, serviceContext); }
@Override public boolean tableExists(String tableId) throws IOException { try (BigtableSession session = new BigtableSession(options)) { GetTableRequest getTable = GetTableRequest.newBuilder() .setName(options.getInstanceName().toTableNameStr(tableId)) .build(); session.getTableAdminClient().getTable(getTable); return true; } catch (StatusRuntimeException e) { if (e.getStatus().getCode() == Code.NOT_FOUND) { return false; } String message = String.format( "Error checking whether table %s (BigtableOptions %s) exists", tableId, options); LOG.error(message, e); throw new IOException(message, e); } }
@Test public void testUnimplementedMethod() { EchoGrpcRx.EchoStub stub = EchoGrpcRx.newStub(channel); TestObserver<EchoService.EchoResp> observer = new TestObserver<>(); EchoService.EchoReq request = EchoService.EchoReq.newBuilder() .setId(1) .setValue("hello") .build(); stub.unary(request) .subscribe(observer); observer.awaitDone(testWaitSeconds, TimeUnit.SECONDS); observer.assertError(t -> { if (!(t instanceof StatusRuntimeException)) return false; StatusRuntimeException e = (StatusRuntimeException)t; if (e.getStatus().getCode() != Status.UNIMPLEMENTED.getCode()) return false; if (!e.getStatus().getDescription().equals("UNIMPLEMENTED: Method io.grpc.rx.Echo/unary is unimplemented")) return false; return true; }); }
@Test public void grpcServerGetsStopped() { final DropwizardTestSupport<TestConfiguration> testSupport = new DropwizardTestSupport<>(TestApplication.class, resourceFilePath("grpc-test-config.yaml")); ManagedChannel channel = null; try { testSupport.before(); channel = createPlaintextChannel(testSupport); final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel); testSupport.after(); try { // this should fail as the server is now stopped client.getPerson(GetPersonRequest.newBuilder().setName("blah").build()); fail("Request should have failed."); } catch (final Exception e) { assertEquals(StatusRuntimeException.class, e.getClass()); assertEquals(Code.UNAVAILABLE, ((StatusRuntimeException) e).getStatus().getCode()); } } finally { testSupport.after(); shutdownChannel(channel); } }
@Test public void mockGrpcServerServesOverSSL() { final NettyChannelBuilder channelBuilder = NettyChannelBuilder.forTarget(storageProperties.getApiHost()); final TraceServiceBlockingStub plainTraceService = TraceServiceGrpc.newBlockingStub(channelBuilder.build()); final TraceServiceBlockingStub sslTraceService = TraceServiceGrpc.newBlockingStub(channelBuilder.sslContext(CLIENT_SSL_CONTEXT).build()); try { plainTraceService.patchTraces(PatchTracesRequest.getDefaultInstance()); } catch (StatusRuntimeException e) { assertThat(e.getMessage(), endsWith("Channel closed while performing protocol negotiation")); } sslTraceService.patchTraces(PatchTracesRequest.getDefaultInstance()); }
@Test(timeout = 10000) public void deadlineExceeded() { // warm up the channel and JVM blockingStub.emptyCall(Empty.getDefaultInstance()); TestServiceBlockingStub stub = Clients.newDerivedClient( blockingStub, ClientOption.DEFAULT_RESPONSE_TIMEOUT_MILLIS.newValue(10L)); StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters( ResponseParameters.newBuilder() .setIntervalUs(20000)) .build(); Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next()); assertThat(t).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) t).getStatus().getCode()) .isEqualTo(Status.DEADLINE_EXCEEDED.getCode()); }
@Ignore @Test(timeout = 10000) public void deadlineInPast() throws Exception { // Test once with idle channel and once with active channel TestServiceGrpc.TestServiceBlockingStub stub = Clients.newDerivedClient( blockingStub, ClientOption.DEFAULT_RESPONSE_TIMEOUT_MILLIS.newValue(TimeUnit.SECONDS.toMillis(-10))); stub.emptyCall(EMPTY); Throwable t = catchThrowable(() -> stub.emptyCall(EMPTY)); assertThat(t).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) t).getStatus().getCode()); // warm up the channel blockingStub.emptyCall(Empty.getDefaultInstance()); t = catchThrowable(() -> stub.emptyCall(EMPTY)); assertThat(t).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) t).getStatus().getCode()); }
@Test(timeout = 10000) public void maxInboundSize_tooBig() { StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters(ResponseParameters.newBuilder().setSize(1)) .build(); int size = blockingStub.streamingOutputCall(request).next().getSerializedSize(); TestServiceBlockingStub stub = Clients.newDerivedClient( blockingStub, GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size - 1)); Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next()); assertThat(t).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED); assertThat(Throwables.getStackTraceAsString(t)).contains("exceeds maximum"); }
@Test(timeout = 10000) public void maxOutboundSize_tooBig() { // set at least one field to ensure the size is non-zero. StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder() .addResponseParameters(ResponseParameters.newBuilder().setSize(1)) .build(); TestServiceBlockingStub stub = Clients.newDerivedClient( blockingStub, GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue( request.getSerializedSize() - 1)); Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next()); assertThat(t).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.CANCELLED); assertThat(Throwables.getStackTraceAsString(t)).contains("message too large"); }
@Test public void tooLargeRequest_uncompressed() throws Exception { SimpleRequest request = SimpleRequest.newBuilder() .setPayload( Payload.newBuilder() .setBody(ByteString.copyFrom( LARGE_PAYLOAD.toByteArray()))) .build(); StatusRuntimeException t = (StatusRuntimeException) catchThrowable( () -> blockingClient.staticUnaryCall(request)); // NB: Since gRPC does not support HTTP/1, it just resets the stream with an HTTP/2 CANCEL error code, // which clients would interpret as Code.CANCELLED. Armeria supports HTTP/1, so more generically returns // an HTTP 500. assertThat(t.getStatus().getCode()).isEqualTo(Code.UNKNOWN); }
@Test public void tooLargeRequest_compressed() throws Exception { SimpleRequest request = SimpleRequest.newBuilder() .setPayload( Payload.newBuilder() .setBody(ByteString.copyFrom( LARGE_PAYLOAD.toByteArray()))) .build(); StatusRuntimeException t = (StatusRuntimeException) catchThrowable( () -> blockingClient.withCompression("gzip").staticUnaryCall(request)); // NB: Since gRPC does not support HTTP/1, it just resets the stream with an HTTP/2 CANCEL error code, // which clients would interpret as Code.CANCELLED. Armeria supports HTTP/1, so more generically returns // an HTTP 500. assertThat(t.getStatus().getCode()).isEqualTo(Code.UNKNOWN); }
@Test public void deframe_tooLargeCompressed() throws Exception { // Simple repeated character compresses below the frame threshold but uncompresses above it. SimpleRequest request = SimpleRequest.newBuilder() .setPayload(Payload.newBuilder() .setBody(ByteString.copyFromUtf8( Strings.repeat("a", 1024)))) .build(); byte[] frame = GrpcTestUtil.compressedFrame(Unpooled.wrappedBuffer(request.toByteArray())); assertThat(frame.length).isLessThan(1024); deframer.request(1); deframer.deframe(HttpData.of(frame), false); ArgumentCaptor<ByteBufOrStream> messageCaptor = ArgumentCaptor.forClass(ByteBufOrStream.class); verify(listener).messageRead(messageCaptor.capture()); verifyNoMoreInteractions(listener); try (InputStream stream = messageCaptor.getValue().stream()) { assertThatThrownBy(() -> ByteStreams.toByteArray(stream)) .isInstanceOf(StatusRuntimeException.class); } }
/** * This method can throw {@link StatusRuntimeException}, but the RemoteCache interface does not * allow throwing such an exception. Any caller must make sure to catch the * {@link StatusRuntimeException}. Note that the retrier implicitly catches it, so if this is used * in the context of {@link RemoteRetrier#execute}, that's perfectly safe. * * <p>This method also converts any NOT_FOUND code returned from the server into a * {@link CacheNotFoundException}. TODO(olaola): this is not enough. NOT_FOUND can also be raised * by execute, in which case the server should return the missing digest in the Status.details * field. This should be part of the API. */ private void readBlob(Digest digest, OutputStream stream) throws IOException, StatusRuntimeException { String resourceName = ""; if (!options.remoteInstanceName.isEmpty()) { resourceName += options.remoteInstanceName + "/"; } resourceName += "blobs/" + digest.getHash() + "/" + digest.getSizeBytes(); try { Iterator<ReadResponse> replies = bsBlockingStub() .read(ReadRequest.newBuilder().setResourceName(resourceName).build()); while (replies.hasNext()) { replies.next().getData().writeTo(stream); } } catch (StatusRuntimeException e) { if (e.getStatus().getCode() == Status.Code.NOT_FOUND) { throw new CacheNotFoundException(digest); } throw e; } }
@Test public void testPassThroughException() throws Exception { StatusRuntimeException thrown = Status.Code.UNKNOWN.toStatus().asRuntimeException(); RemoteOptions options = Options.getDefaults(RemoteOptions.class); RemoteRetrier retrier = new RemoteRetrier(options, (e) -> true, Retrier.ALLOW_ALL_CALLS); AtomicInteger numCalls = new AtomicInteger(); try { retrier.execute(() -> { numCalls.incrementAndGet(); throw new RemoteRetrier.PassThroughException(thrown); }); fail(); } catch (RetryException expected) { assertThat(expected).hasCauseThat().isSameAs(thrown); } assertThat(numCalls.get()).isEqualTo(1); }
private Map<PiTableEntry, PiCounterCellData> readEntryCounters( PiCounterId counterId, Collection<PiTableEntry> tableEntries) { Collection<PiCounterCellData> cellDatas; try { if (readAllDirectCounters) { cellDatas = client.readAllCounterCells( singleton(counterId), pipeconf).get(); } else { Set<PiCounterCellId> cellIds = tableEntries.stream() .map(entry -> PiCounterCellId.ofDirect(counterId, entry)) .collect(Collectors.toSet()); cellDatas = client.readCounterCells(cellIds, pipeconf).get(); } return cellDatas.stream() .collect(Collectors.toMap(c -> c.cellId().tableEntry(), c -> c)); } catch (InterruptedException | ExecutionException e) { if (!(e.getCause() instanceof StatusRuntimeException)) { // gRPC errors are logged in the client. log.error("Exception while reading counter '{}' from {}: {}", counterId, deviceId, e); } return Collections.emptyMap(); } }
/** * Blocking server-streaming example. Calls listFeatures with a rectangle of interest. Prints each * response feature as it arrives. */ public void listFeatures(int lowLat, int lowLon, int hiLat, int hiLon) { info("*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", lowLat, lowLon, hiLat, hiLon); Rectangle request = Rectangle.newBuilder() .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build()) .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()).build(); Iterator<Feature> features; try { features = blockingStub.listFeatures(request); for (int i = 1; features.hasNext(); i++) { Feature feature = features.next(); info("Result #" + i + ": {0}", feature); if (testHelper != null) { testHelper.onMessage(feature); } } } catch (StatusRuntimeException e) { warning("RPC failed: {0}", e.getStatus()); if (testHelper != null) { testHelper.onRpcError(e); } } }
/** * Example for testing blocking unary call. */ @Test public void getFeature_error() { Point requestPoint = Point.newBuilder().setLatitude(-1).setLongitude(-1).build(); final AtomicReference<Point> pointDelivered = new AtomicReference<Point>(); final StatusRuntimeException fakeError = new StatusRuntimeException(Status.DATA_LOSS); // implement the fake service RouteGuideImplBase getFeatureImpl = new RouteGuideImplBase() { @Override public void getFeature(Point point, StreamObserver<Feature> responseObserver) { pointDelivered.set(point); responseObserver.onError(fakeError); } }; serviceRegistry.addService(getFeatureImpl); client.getFeature(-1, -1); assertEquals(requestPoint, pointDelivered.get()); ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class); verify(testHelper).onRpcError(errorCaptor.capture()); assertEquals(fakeError.getStatus(), Status.fromThrowable(errorCaptor.getValue())); }