下面列出了怎么用io.grpc.stub.ClientCalls的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void requestWithNoCacheOptionSkipsCache() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true),
message);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertSame(reply1, reply3);
}
@Test
public void requestWithOnlyIfCachedOption_unavailableIfNotInCache() {
try {
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(
SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
fail("Expected call to fail");
} catch (StatusRuntimeException sre) {
assertEquals(Status.UNAVAILABLE.getCode(), sre.getStatus().getCode());
assertEquals(
"Unsatisfiable Request (only-if-cached set, but value not in cache)",
sre.getStatus().getDescription());
}
}
@Test
public void requestWithNoCacheAndOnlyIfCached_fails() {
try {
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT
.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true)
.withOption(SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
fail("Expected call to fail");
} catch (StatusRuntimeException sre) {
assertEquals(Status.UNAVAILABLE.getCode(), sre.getStatus().getCode());
assertEquals(
"Unsatisfiable Request (no-cache and only-if-cached conflict)",
sre.getStatus().getDescription());
}
}
@Test
public void responseNoCacheDirective_notCached() throws Exception {
cacheControlDirectives.add("no-cache");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertNotEquals(reply1, reply2);
Truth.assertThat(cache.internalCache).isEmpty();
Truth.assertThat(cache.removedKeys).isEmpty();
}
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() throws Exception {
cacheControlDirectives.add("max-age=1");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
public <ReqT, RespT> RespT callWithRetry(
BackOffer backOffer,
MethodDescriptor<ReqT, RespT> method,
Supplier<ReqT> requestFactory,
ErrorHandler<RespT> handler) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Calling %s...", method.getFullMethodName()));
}
RetryPolicy.Builder<RespT> builder = new Builder<>(backOffer);
RespT resp =
builder
.create(handler)
.callWithRetry(
() -> {
BlockingStubT stub = getBlockingStub();
return ClientCalls.blockingUnaryCall(
stub.getChannel(), method, stub.getCallOptions(), requestFactory.get());
},
method.getFullMethodName());
if (logger.isTraceEnabled()) {
logger.trace(String.format("leaving %s...", method.getFullMethodName()));
}
return resp;
}
protected <ReqT, RespT> void callAsyncWithRetry(
BackOffer backOffer,
MethodDescriptor<ReqT, RespT> method,
Supplier<ReqT> requestFactory,
StreamObserver<RespT> responseObserver,
ErrorHandler<RespT> handler) {
logger.debug(String.format("Calling %s...", method.getFullMethodName()));
RetryPolicy.Builder<RespT> builder = new Builder<>(backOffer);
builder
.create(handler)
.callWithRetry(
() -> {
StubT stub = getAsyncStub();
ClientCalls.asyncUnaryCall(
stub.getChannel().newCall(method, stub.getCallOptions()),
requestFactory.get(),
responseObserver);
return null;
},
method.getFullMethodName());
logger.debug(String.format("leaving %s...", method.getFullMethodName()));
}
public Resp execute(Client client, Duration retryTimeout) throws HederaStatusException, HederaNetworkException, LocalValidationException {
// Run local validator just before execute
localValidate();
// N.B. only QueryBuilder used onPreExecute() so instead it should just override this
// method instead
final Backoff.FallibleProducer<Resp, HederaStatusException> tryProduce = () -> {
try {
return mapResponse(ClientCalls.blockingUnaryCall(getChannel(client).newCall(getMethod(), CallOptions.DEFAULT), toProto()));
} catch (StatusRuntimeException e) {
throw new HederaNetworkException(e);
}
};
return new Backoff(RETRY_DELAY, retryTimeout)
.tryWhile(this::shouldRetry, tryProduce);
}
/**
* Get a blocking iterator which returns messages for the given topic with consensus timestamps
* between two {@link Instant}s.
*
* @param topicId
* @param startTime the lower bound for timestamps (inclusive), may be in the past or future.
* @param endTime the upper bound for timestamps (exclusive), may also be in the past or future.
* @return
*/
public Iterator<ConsensusMessage> getMessages(ConsensusTopicId topicId, Instant startTime, Instant endTime) {
final ConsensusTopicQuery topicQuery = ConsensusTopicQuery.newBuilder()
.setTopicID(topicId.toProto())
.setConsensusStartTime(TimestampHelper.timestampFrom(startTime))
.setConsensusEndTime(TimestampHelper.timestampFrom(endTime))
.build();
final Iterator<ConsensusTopicResponse> iter = ClientCalls.blockingServerStreamingCall(
channel,
ConsensusServiceGrpc.getSubscribeTopicMethod(),
CallOptions.DEFAULT,
topicQuery);
return Iterators.transform(iter, message -> new ConsensusMessage(topicId, Objects.requireNonNull(message)));
}
@Test
public void cacheHit_doesNotResetExpiration() throws Exception {
cacheControlDirectives.add("max-age=1");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
sleepAtLeast(1001);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
assertNotEquals(reply1, reply3);
Truth.assertThat(cache.internalCache).hasSize(1);
Truth.assertThat(cache.removedKeys).hasSize(1);
}
public static <ReqT, RespT> void autoCall() throws Exception {
DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(toUrl("/home/darrenfu/IdeaProjects/pampas/pampas-grpc/df/open/grpc/hello/grpc-test-229014610914606914.jar"));
Class grpc = loader.load("df.open.grpc.hello.HelloServiceGrpc");
Class proto = loader.load("df.open.grpc.hello.HelloServiceProto");
Method getSayHelloMethod = grpc.getDeclaredMethod("getSayHelloMethod");
MethodDescriptor<ReqT, RespT> methodDescriptor = (MethodDescriptor) getSayHelloMethod.invoke(grpc);
ClientCall<ReqT, RespT> call =
new ForwardingClientCall.SimpleForwardingClientCall(channel.newCall(methodDescriptor, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {
public void start(Listener responseListener, Metadata headers) {
System.out.println("start call......");
super.start(responseListener, headers);
}
};
// ClientCalls.asyncUnaryCall(call, (ReqT) req.newInstance(), responseFuture);
Class<?> reqClz = Class.forName("df.open.grpc.hello.HelloServiceProto$HelloReq", false, loader);
Constructor<?> constructor = reqClz.getDeclaredConstructor();
constructor.setAccessible(true);
System.out.println(constructor.isAccessible());
RespT respT = ClientCalls.blockingUnaryCall(call, (ReqT) constructor.newInstance());
System.out.println(respT);
System.out.println("XXXXXXXxx");
}
@Test
public void releaseOnError() {
// Setup server
startServer((req, observer) -> {
observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
});
try {
ClientCalls.blockingUnaryCall(channel, METHOD_DESCRIPTOR, CallOptions.DEFAULT, "foo");
Assert.fail("Should have failed with UNKNOWN error");
} catch (StatusRuntimeException e) {
Assert.assertEquals(Status.Code.INVALID_ARGUMENT, e.getStatus().getCode());
}
// Verify
Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));
verifyCounts(0, 0, 1, 0);
}
@Test
public void releaseOnUncaughtException() throws IOException {
// Setup server
startServer((req, observer) -> {
throw new RuntimeException("failure");
});
try {
ClientCalls.blockingUnaryCall(channel, METHOD_DESCRIPTOR, CallOptions.DEFAULT, "foo");
Assert.fail("Should have failed with UNKNOWN error");
} catch (StatusRuntimeException e) {
Assert.assertEquals(Status.Code.UNKNOWN, e.getStatus().getCode());
}
// Verify
Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));
Mockito.verify(listener.getResult().get(), Mockito.timeout(1000).times(1)).onIgnore();
verifyCounts(0, 1, 0, 0);
}
@Test
public void releaseOnCancellation() {
// Setup server
startServer((req, observer) -> {
Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
observer.onNext("delayed_response");
observer.onCompleted();
});
ListenableFuture<String> future = ClientCalls.futureUnaryCall(channel.newCall(METHOD_DESCRIPTOR, CallOptions.DEFAULT), "foo");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
future.cancel(true);
// Verify
Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));
Mockito.verify(listener.getResult().get(), Mockito.times(0)).onIgnore();
Mockito.verify(listener.getResult().get(), Mockito.timeout(2000).times(1)).onSuccess();
verifyCounts(0, 0, 1, 0);
}
@Test
public void releaseOnDeadlineExceeded() {
// Setup server
startServer((req, observer) -> {
Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
observer.onNext("delayed_response");
observer.onCompleted();
});
try {
ClientCalls.blockingUnaryCall(channel.newCall(METHOD_DESCRIPTOR, CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.SECONDS)), "foo");
} catch (StatusRuntimeException e) {
Assert.assertEquals(Status.Code.DEADLINE_EXCEEDED, e.getStatus().getCode());
}
// Verify
Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));
Mockito.verify(listener.getResult().get(), Mockito.times(0)).onIgnore();
Mockito.verify(listener.getResult().get(), Mockito.timeout(2000).times(1)).onSuccess();
verifyCounts(0, 0, 1, 0);
}
protected <ReqT, RespT> RespT callWithRetry(MethodDescriptor<ReqT, RespT> method,
Supplier<ReqT> requestFactory,
ErrorHandler<RespT> handler) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Calling %s...", method.getFullMethodName()));
}
RetryPolicy.Builder<RespT> builder = new Builder<>(conf.getRetryTimes(), conf.getBackOffClass());
RespT resp =
builder.create(handler)
.callWithRetry(
() -> {
BlockingStubT stub = getBlockingStub();
return ClientCalls.blockingUnaryCall(
stub.getChannel(), method, stub.getCallOptions(), requestFactory.get());
},
method.getFullMethodName());
if (logger.isTraceEnabled()) {
logger.trace(String.format("leaving %s...", method.getFullMethodName()));
}
return resp;
}
protected <ReqT, RespT> void callAsyncWithRetry(
MethodDescriptor<ReqT, RespT> method,
Supplier<ReqT> requestFactory,
StreamObserver<RespT> responseObserver,
ErrorHandler<RespT> handler) {
logger.debug(String.format("Calling %s...", method.getFullMethodName()));
RetryPolicy.Builder<RespT> builder = new Builder<>(conf.getRetryTimes(), conf.getBackOffClass());
builder.create(handler)
.callWithRetry(
() -> {
StubT stub = getAsyncStub();
ClientCalls.asyncUnaryCall(
stub.getChannel().newCall(method, stub.getCallOptions()),
requestFactory.get(),
responseObserver);
return null;
},
method.getFullMethodName());
logger.debug(String.format("leaving %s...", method.getFullMethodName()));
}
@Test
public void requestWithNoCacheOptionSkipsCache() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true),
message);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertSame(reply1, reply3);
}
@Test
public void requestWithOnlyIfCachedOption_unavailableIfNotInCache() {
try {
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(
SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
fail("Expected call to fail");
} catch (StatusRuntimeException sre) {
assertEquals(Status.UNAVAILABLE.getCode(), sre.getStatus().getCode());
assertEquals(
"Unsatisfiable Request (only-if-cached set, but value not in cache)",
sre.getStatus().getDescription());
}
}
@Test
public void requestWithNoCacheAndOnlyIfCached_fails() {
try {
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT
.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true)
.withOption(SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
fail("Expected call to fail");
} catch (StatusRuntimeException sre) {
assertEquals(Status.UNAVAILABLE.getCode(), sre.getStatus().getCode());
assertEquals(
"Unsatisfiable Request (no-cache and only-if-cached conflict)",
sre.getStatus().getDescription());
}
}
@Test
public void responseNoCacheDirective_notCached() throws Exception {
cacheControlDirectives.add("no-cache");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertNotEquals(reply1, reply2);
Truth.assertThat(cache.internalCache).isEmpty();
Truth.assertThat(cache.removedKeys).isEmpty();
}
@Test
public void separateResponseCacheControlDirectives_parsesWithoutError() throws Exception {
cacheControlDirectives.add("max-age=1");
cacheControlDirectives.add("no-store , no-cache");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
Truth.assertThat(cache.internalCache).isEmpty();
Truth.assertThat(cache.removedKeys).isEmpty();
}
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() throws Exception {
cacheControlDirectives.add("max-age=1");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
@Override
public void run() {
while (true) {
maxOutstanding.acquireUninterruptibly();
if (shutdown) {
maxOutstanding.release();
return;
}
ClientCalls.asyncUnaryCall(
channel.newCall(LoadServer.GENERIC_UNARY_METHOD, CallOptions.DEFAULT),
genericRequest.slice(),
new StreamObserver<ByteBuf>() {
long now = System.nanoTime();
@Override
public void onNext(ByteBuf value) {
}
@Override
public void onError(Throwable t) {
maxOutstanding.release();
Level level = shutdown ? Level.FINE : Level.INFO;
log.log(level, "Error in Generic Async Unary call", t);
}
@Override
public void onCompleted() {
delay(System.nanoTime() - now);
maxOutstanding.release();
}
});
}
}
@Test
public void causeShouldBePropagatedWithStatus() throws Exception {
server = null;
String failingServerName = "server_foo";
String serviceFoo = "service_foo";
final Status s = Status.INTERNAL.withCause(new Throwable("failing server exception"));
ServerServiceDefinition definition = ServerServiceDefinition.builder(serviceFoo)
.addMethod(TestMethodDescriptors.voidMethod(), new ServerCallHandler<Void, Void>() {
@Override
public ServerCall.Listener<Void> startCall(
ServerCall<Void, Void> call, Metadata headers) {
call.close(s, new Metadata());
return new ServerCall.Listener<Void>() {};
}
})
.build();
Server failingServer = InProcessServerBuilder
.forName(failingServerName)
.addService(definition)
.directExecutor()
.build()
.start();
grpcCleanupRule.register(failingServer);
ManagedChannel channel = InProcessChannelBuilder
.forName(failingServerName)
.propagateCauseWithStatus(true)
.build();
grpcCleanupRule.register(channel);
try {
ClientCalls.blockingUnaryCall(channel, TestMethodDescriptors.voidMethod(),
CallOptions.DEFAULT, null);
fail("exception should have been thrown");
} catch (StatusRuntimeException e) {
// When propagateCauseWithStatus is true, the cause should be sent forward
assertEquals(s.getCause(), e.getCause());
}
}
@Test
public void differentServiceCallsAreNotConflated() {
MethodDescriptor<HelloRequest, HelloReply> anotherSafeMethod =
AnotherGreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build();
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, anotherSafeMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
}
@Test
public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
@Test
public void safeCallsAreCachedWithCopiedMethodDescriptor() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod.toBuilder().build(),
CallOptions.DEFAULT,
message);
assertSame(reply1, reply2);
}
@Test
public void requestWithOnlyIfCachedOption_usesCache() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(
SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
assertSame(reply1, reply2);
}
@Override
public void run() {
long now;
while (!shutdown) {
now = System.nanoTime();
ClientCalls.blockingUnaryCall(channel, LoadServer.GENERIC_UNARY_METHOD,
CallOptions.DEFAULT,
genericRequest.slice());
delay(System.nanoTime() - now);
}
}