io.grpc.ServerCallHandler Java Examples

The following examples show how to use io.grpc.ServerCallHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void disablingInboundAutoFlowControlSuppressesRequestsForMoreMessages() throws Exception {
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.disableAutoInboundFlowControl();
              return new ServerCalls.NoopStreamObserver<Integer>();
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  callListener.onReady();
  // Transport should not call this if nothing has been requested but forcing it here
  // to verify that message delivery does not trigger a call to request(1).
  callListener.onMessage(1);
  // Should never be called
  assertThat(serverCall.requestCalls).isEmpty();
}
 
Example #2
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Echo the request headers from a client into response headers and trailers. Useful for
 * testing end-to-end metadata propagation.
 */
private static ServerInterceptor echoRequestHeadersInterceptor(final Metadata.Key<?>... keys) {
  final Set<Metadata.Key<?>> keySet = new HashSet<>(Arrays.asList(keys));
  return new ServerInterceptor() {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        final Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
            @Override
            public void sendHeaders(Metadata responseHeaders) {
              responseHeaders.merge(requestHeaders, keySet);
              super.sendHeaders(responseHeaders);
            }

            @Override
            public void close(Status status, Metadata trailers) {
              trailers.merge(requestHeaders, keySet);
              super.close(status, trailers);
            }
          }, requestHeaders);
    }
  };
}
 
Example #3
Source File: DebugServerInterceptor.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    logMethod(REQUEST, call.getMethodDescriptor());
    logHeaders(REQUEST, headers);
    return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
            next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendHeaders(Metadata responseHeaders) {
                    logMethod(RESPONSE, call.getMethodDescriptor());
                    logHeaders(RESPONSE, responseHeaders);
                    super.sendHeaders(responseHeaders);
                }

                @Override
                public void sendMessage(RespT message) {
                    logMessage(RESPONSE, message);
                    super.sendMessage(message);
                }
            }, headers)) {
 
Example #4
Source File: AuthorizationCheckingServerInterceptor.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers,
        final ServerCallHandler<ReqT, RespT> next) {
    final MethodDescriptor<ReqT, RespT> methodDescriptor = call.getMethodDescriptor();
    final InterceptorStatusToken token;
    try {
        token = beforeInvocation(methodDescriptor);
    } catch (final AuthenticationException | AccessDeniedException e) {
        log.debug("Access denied");
        throw e;
    }
    log.debug("Access granted");
    final Listener<ReqT> result;
    try {
        result = next.startCall(call, headers);
    } finally {
        finallyInvocation(token);
    }
    // TODO: Call that here or in onHalfClose?
    return (Listener<ReqT>) afterInvocation(token, result);
}
 
Example #5
Source File: SafeMethodCachingInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call,
    final Metadata requestHeaders,
    ServerCallHandler<ReqT, RespT> next) {
  return next.startCall(
      new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void sendHeaders(Metadata headers) {
          for (String cacheControlDirective : cacheControlDirectives) {
            headers.put(CACHE_CONTROL_METADATA_KEY, cacheControlDirective);
          }
          super.sendHeaders(headers);
        }
      },
      requestHeaders);
}
 
Example #6
Source File: GrpcFitInterceptor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
    if (!fitRequestHandler.isPresent()) {
        return next.startCall(call, headers);
    }

    FitInjection fitInjection = fitRequestHandler.get();
    String injectionPoint = call.getMethodDescriptor().getFullMethodName();

    // Request failure
    try {
        fitInjection.beforeImmediate(injectionPoint);
    } catch (Exception e) {
        call.close(Status.UNAVAILABLE.withDescription("FIT server failure"), new Metadata());
        return new ServerCall.Listener<ReqT>() {
        };
    }

    // Increased latency.
    return fitInjection.findAction(FitLatencyAction.ACTION_ID)
            .map(action -> {
                int latencyMs = ExceptionExt.doTry(() -> Integer.parseInt(action.getProperties().get("latency"))).orElse(100);
                return new LatencyHandler<>(call, headers, next, latencyMs).getLatencyListener();
            })
            .orElse(next.startCall(call, headers));
}
 
Example #7
Source File: TripleServer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private ServerServiceDefinition buildSofaServiceDef(GenericServiceImpl genericService,
                                                    ProviderConfig providerConfig, Invoker instance) {
    ServerServiceDefinition templateDefinition = genericService.bindService();
    ServerCallHandler<Request, Response> templateHandler = (ServerCallHandler<Request, Response>) templateDefinition
        .getMethods().iterator().next().getServerCallHandler();
    List<MethodDescriptor<Request, Response>> methodDescriptor = getMethodDescriptor(providerConfig);
    List<ServerMethodDefinition<Request, Response>> methodDefs = getMethodDefinitions(templateHandler,
        methodDescriptor);
    ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(getServiceDescriptor(
        templateDefinition, providerConfig, methodDescriptor));
    for (ServerMethodDefinition<Request, Response> methodDef : methodDefs) {
        builder.addMethod(methodDef);

    }
    return builder.build();

}
 
Example #8
Source File: TransportCompressionTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  return NettyServerBuilder.forPort(0)
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .compressorRegistry(compressors)
      .decompressorRegistry(decompressors)
      .intercept(new ServerInterceptor() {
          @Override
          public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
              Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            Listener<ReqT> listener = next.startCall(call, headers);
            // TODO(carl-mastrangelo): check that encoding was set.
            call.setMessageCompression(true);
            return listener;
          }
        });
}
 
Example #9
Source File: BinaryLogProvider.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps a {@link ServerMethodDefinition} such that it performs binary logging if needed.
 */
@Override
public final <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(
    ServerMethodDefinition<ReqT, RespT> oMethodDef) {
  ServerInterceptor binlogInterceptor =
      getServerInterceptor(oMethodDef.getMethodDescriptor().getFullMethodName());
  if (binlogInterceptor == null) {
    return oMethodDef;
  }
  MethodDescriptor<byte[], byte[]> binMethod =
      BinaryLogProvider.toByteBufferMethod(oMethodDef.getMethodDescriptor());
  ServerMethodDefinition<byte[], byte[]> binDef =
      InternalServerInterceptors.wrapMethod(oMethodDef, binMethod);
  ServerCallHandler<byte[], byte[]> binlogHandler =
      InternalServerInterceptors.interceptCallHandlerCreate(
          binlogInterceptor, binDef.getServerCallHandler());
  return ServerMethodDefinition.create(binMethod, binlogHandler);
}
 
Example #10
Source File: LeaderServerInterceptor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                  ServerCallHandler<ReqT, RespT> next) {

    if (SupervisorServiceGrpc.getServiceDescriptor().getMethods().contains(call.getMethodDescriptor())) {
        // Supervisor API calls are not restricted to the active leader.
        return next.startCall(call, headers);
    }

    if (leaderActivator.isLeader()) {
        if (leaderActivator.isActivated()) {
            return next.startCall(call, headers);
        } else {
            call.close(Status.UNAVAILABLE.withDescription("Titus Master is initializing and not yet available."), new Metadata());
            return new ServerCall.Listener<ReqT>() {
            };
        }
    } else {
        call.close(Status.UNAVAILABLE.withDescription("Titus Master is not leader."), new Metadata());
        return new ServerCall.Listener<ReqT>() {
        };
    }
}
 
Example #11
Source File: ServerImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Never returns {@code null}. */
private <ReqT, RespT> ServerStreamListener startCall(ServerStream stream, String fullMethodName,
    ServerMethodDefinition<ReqT, RespT> methodDef, Metadata headers,
    Context.CancellableContext context, StatsTraceContext statsTraceCtx) {
  // TODO(ejona86): should we update fullMethodName to have the canonical path of the method?
  statsTraceCtx.serverCallStarted(
      new ServerCallInfoImpl<ReqT, RespT>(
          methodDef.getMethodDescriptor(), // notify with original method descriptor
          stream.getAttributes(),
          stream.getAuthority()));
  ServerCallHandler<ReqT, RespT> handler = methodDef.getServerCallHandler();
  for (ServerInterceptor interceptor : interceptors) {
    handler = InternalServerInterceptors.interceptCallHandler(interceptor, handler);
  }
  ServerMethodDefinition<ReqT, RespT> interceptedDef = methodDef.withServerCallHandler(handler);
  ServerMethodDefinition<?, ?> wMethodDef = binlog == null
      ? interceptedDef : binlog.wrapMethodDefinition(interceptedDef);
  return startWrappedCall(fullMethodName, wMethodDef, stream, headers, context);
}
 
Example #12
Source File: MonitoringInterceptor.java    From feast with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

  long startCallMillis = System.currentTimeMillis();
  String fullMethodName = call.getMethodDescriptor().getFullMethodName();
  String serviceName = MethodDescriptor.extractFullServiceName(fullMethodName);
  String methodName = fullMethodName.substring(fullMethodName.indexOf("/") + 1);

  return next.startCall(
      new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
          GrpcMetrics.requestLatency
              .labels(serviceName, methodName, status.getCode().name())
              .observe((System.currentTimeMillis() - startCallMillis) / 1000f);
          super.close(status, trailers);
        }
      },
      headers);
}
 
Example #13
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void cannotDisableAutoFlowControlAfterServiceInvocation() throws Exception {
  final AtomicReference<ServerCallStreamObserver<Integer>> callObserver =
      new AtomicReference<ServerCallStreamObserver<Integer>>();
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              callObserver.set((ServerCallStreamObserver<Integer>) responseObserver);
              return new ServerCalls.NoopStreamObserver<Integer>();
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  callListener.onMessage(1);
  try {
    callObserver.get().disableAutoInboundFlowControl();
    fail("Cannot set onCancel handler after service invocation");
  } catch (IllegalStateException expected) {
    // Expected
  }
}
 
Example #14
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void disablingInboundAutoFlowControlForUnaryHasNoEffect() throws Exception {
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncUnaryCall(
          new ServerCalls.UnaryMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.disableAutoInboundFlowControl();
            }
          });
  callHandler.startCall(serverCall, new Metadata());
  // Auto inbound flow-control always requests 2 messages for unary to detect a violation
  // of the unary semantic.
  assertThat(serverCall.requestCalls).containsExactly(2);
}
 
Example #15
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSendsOne_errorMissingRequest_unary() {
  ServerCallRecorder serverCall = new ServerCallRecorder(UNARY_METHOD);
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncUnaryCall(
          new ServerCalls.UnaryMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              fail("should not be reached");
            }
          });
  ServerCall.Listener<Integer> listener = callHandler.startCall(serverCall, new Metadata());
  listener.onHalfClose();
  assertThat(serverCall.responses).isEmpty();
  assertEquals(Status.Code.INTERNAL, serverCall.status.getCode());
  assertEquals(ServerCalls.MISSING_REQUEST, serverCall.status.getDescription());
}
 
Example #16
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSendsOne_errorMissingRequest_serverStreaming() {
  ServerCallRecorder serverCall = new ServerCallRecorder(SERVER_STREAMING_METHOD);
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncServerStreamingCall(
          new ServerCalls.ServerStreamingMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              fail("should not be reached");
            }
          });
  ServerCall.Listener<Integer> listener = callHandler.startCall(serverCall, new Metadata());
  listener.onHalfClose();
  assertThat(serverCall.responses).isEmpty();
  assertEquals(Status.Code.INTERNAL, serverCall.status.getCode());
  assertEquals(ServerCalls.MISSING_REQUEST, serverCall.status.getDescription());

}
 
Example #17
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSendsOne_errorTooManyRequests_unary() {
  ServerCallRecorder serverCall = new ServerCallRecorder(UNARY_METHOD);
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncUnaryCall(
          new ServerCalls.UnaryMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              fail("should not be reached");
            }
          });
  ServerCall.Listener<Integer> listener = callHandler.startCall(serverCall, new Metadata());
  listener.onMessage(1);
  listener.onMessage(1);
  assertThat(serverCall.responses).isEmpty();
  assertEquals(Status.Code.INTERNAL, serverCall.status.getCode());
  assertEquals(ServerCalls.TOO_MANY_REQUESTS, serverCall.status.getDescription());
  // ensure onHalfClose does not invoke
  listener.onHalfClose();
}
 
Example #18
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSendsOne_errorTooManyRequests_serverStreaming() {
  ServerCallRecorder serverCall = new ServerCallRecorder(SERVER_STREAMING_METHOD);
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncServerStreamingCall(
          new ServerCalls.ServerStreamingMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              fail("should not be reached");
            }
          });
  ServerCall.Listener<Integer> listener = callHandler.startCall(serverCall, new Metadata());
  listener.onMessage(1);
  listener.onMessage(1);
  assertThat(serverCall.responses).isEmpty();
  assertEquals(Status.Code.INTERNAL, serverCall.status.getCode());
  assertEquals(ServerCalls.TOO_MANY_REQUESTS, serverCall.status.getDescription());
  // ensure onHalfClose does not invoke
  listener.onHalfClose();
}
 
Example #19
Source File: AnonymousAuthenticationInterceptor.java    From grpc-spring-security-demo with MIT License 6 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(key,
                "anonymousUser", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));

        log.debug("Populated SecurityContextHolder with anonymous token: {}",
                SecurityContextHolder.getContext().getAuthentication());
    } else {
        log.debug("SecurityContextHolder not populated with anonymous token, as it already contained: {}",
                SecurityContextHolder.getContext().getAuthentication());
    }

    return next.startCall(call, headers);
}
 
Example #20
Source File: GrpcMonitoringInterceptor.java    From feast with Apache License 2.0 6 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

  long startCallMillis = System.currentTimeMillis();
  String fullMethodName = call.getMethodDescriptor().getFullMethodName();
  String methodName = fullMethodName.substring(fullMethodName.indexOf("/") + 1);

  return next.startCall(
      new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void close(Status status, Metadata trailers) {
          Metrics.requestLatency
              .labels(methodName)
              .observe((System.currentTimeMillis() - startCallMillis) / 1000f);
          Metrics.grpcRequestCount.labels(methodName, status.getCode().name()).inc();
          super.close(status, trailers);
        }
      },
      headers);
}
 
Example #21
Source File: DebugInterceptorTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void debugServerInterceptTest() {
    LinkedList<String> logs = new LinkedList<String>();
    Metadata requestHeaders = new Metadata();
    requestHeaders.put(Metadata.Key.of("request_header", Metadata.ASCII_STRING_MARSHALLER), "request_header_value");
    // Setup
    serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new ServerInterceptor() {
        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                ServerCallHandler<ReqT, RespT> next) {
            return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
                @Override
                public void sendHeaders(Metadata responseHeaders) {
                    responseHeaders.put(Metadata.Key.of("response_header", Metadata.ASCII_STRING_MARSHALLER),
                            "response_header_value");
                    super.sendHeaders(responseHeaders);
                }
            }, headers);
        }
    }, new DebugServerInterceptor(DebugServerInterceptor.Level.METHOD, DebugServerInterceptor.Level.MESSAGE,
            DebugServerInterceptor.Level.HEADERS) {
        @Override
        protected void log(String logmessage) {
            logs.add(logmessage);
        }
    }));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel())
            .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(requestHeaders));
    stub.sayHello(HelloRequest.newBuilder().setName("World").build());
    assertThat(logs.poll()).contains("SayHello"); // request method name
    assertThat(logs.poll()).contains("request_header_value"); // request header value
    assertThat(logs.poll()).contains("World"); // request message
    assertThat(logs.poll()).contains("SayHello"); // response method name
    assertThat(logs.poll()).contains("response_header_value"); // response header
    assertThat(logs.poll()).contains("Hello World"); // response message

}
 
Example #22
Source File: DebugInterceptorTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void debugClientInterceptTest() {
    LinkedList<String> logs = new LinkedList<String>();
    Metadata requestHeaders = new Metadata();
    requestHeaders.put(Metadata.Key.of("request_header", Metadata.ASCII_STRING_MARSHALLER), "request_header_value");
    // Setup
    serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new ServerInterceptor() {
        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                ServerCallHandler<ReqT, RespT> next) {
            return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
                @Override
                public void sendHeaders(Metadata responseHeaders) {
                    responseHeaders.put(Metadata.Key.of("response_header", Metadata.ASCII_STRING_MARSHALLER),
                            "response_header_value");
                    super.sendHeaders(responseHeaders);
                }
            }, headers);
        }
    }));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel())
            .withInterceptors(new DebugClientInterceptor(Level.STATUS, Level.HEADERS, Level.MESSAGE) {
                @Override
                protected void log(String message) {
                    logs.add(message);
                }

            }, MetadataUtils.newAttachHeadersInterceptor(requestHeaders));

    stub.sayHello(HelloRequest.newBuilder().setName("World").build());
    assertThat(logs.poll()).contains("SayHello"); // request method name
    assertThat(logs.poll()).contains(requestHeaders.toString()); // request header value
    assertThat(logs.poll()).contains("World"); // request message
    assertThat(logs.poll()).contains("response_header_value"); // response header
    assertThat(logs.poll()).contains("Hello World"); // response message
    assertThat(logs.poll()).contains("0 OK"); // response status
}
 
Example #23
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void onReadyHandlerCalledForUnaryRequest() throws Exception {
  final AtomicInteger onReadyCalled = new AtomicInteger();
  ServerCallHandler<Integer, Integer> callHandler =
      ServerCalls.asyncServerStreamingCall(
          new ServerCalls.ServerStreamingMethod<Integer, Integer>() {
            @Override
            public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
              ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.setOnReadyHandler(new Runnable() {
                @Override
                public void run() {
                  onReadyCalled.incrementAndGet();
                }
              });
            }
          });
  ServerCall.Listener<Integer> callListener =
      callHandler.startCall(serverCall, new Metadata());
  serverCall.isReady = true;
  serverCall.isCancelled = false;
  callListener.onReady();
  // On ready is not called until the unary request message is delivered
  assertEquals(0, onReadyCalled.get());
  // delivering the message doesn't trigger onReady listener either
  callListener.onMessage(1);
  assertEquals(0, onReadyCalled.get());
  // half-closing triggers the unary request delivery and onReady
  callListener.onHalfClose();
  assertEquals(1, onReadyCalled.get());
  // Next on ready event from the transport triggers listener
  callListener.onReady();
  assertEquals(2, onReadyCalled.get());
}
 
Example #24
Source File: Server.java    From africastalking-java with MIT License 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
    String clientId = headers.get(CLIENT_ID_HEADER_KEY);
    if (clientId == null || !authenticator.authenticate(clientId)) {
        call.close(Status.UNAUTHENTICATED.withDescription("Invalid or unknown client: " + clientId), headers);
        return NOOP_LISTENER;
    }
    Context context = Context.current().withValue(CLIENT_ID_CONTEXT_KEY, clientId);
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example #25
Source File: GrpcRequestScope.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    ScopedBeansContainer container = new ScopedBeansContainer();
    Context context = Context.current().withValue(GRPC_REQUEST_KEY, container);
    context.addListener(this, MoreExecutors.directExecutor());
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example #26
Source File: MetricCollectingServerInterceptor.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public <Q, A> ServerCall.Listener<Q> interceptCall(
        final ServerCall<Q, A> call,
        final Metadata requestHeaders,
        final ServerCallHandler<Q, A> next) {
    final MetricSet metrics = metricsFor(call.getMethodDescriptor());
    final ServerCall<Q, A> monitoringCall = new MetricCollectingServerCall<>(call, this.registry,
            metrics.getResponseCounter(), metrics.getTimerFunction());
    return new MetricCollectingServerCallListener<>(
            next.startCall(monitoringCall, requestHeaders), metrics.getRequestCounter());
}
 
Example #27
Source File: ConnectionInterceptor.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
                                                             final Metadata headers,
                                                             final ServerCallHandler<ReqT, RespT> next) {
    Context ctx = Context.current();
    final ServerStream stream = ServerStreamHelper.getServerStream(call);
    if (stream != null) {
        ctx = ctx.withValue(STREAM, stream);
    }
    return Contexts.interceptCall(ctx, call, headers, next);
}
 
Example #28
Source File: RemoteAddressInterceptor.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
                                                             final Metadata headers,
                                                             final ServerCallHandler<ReqT, RespT> next) {
    final Context ctx = Context.current() //
        .withValue(REMOTE_ADDRESS, call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
    return Contexts.interceptCall(ctx, call, headers, next);
}
 
Example #29
Source File: GrpcLeaderServerInterceptor.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
    MethodDescriptor<ReqT, RespT> methodDescriptor = call.getMethodDescriptor();
    if (notProtectedMethods.contains(methodDescriptor)) {
        return next.startCall(call, headers);
    }

    if (leaderActivationStatus.isActivatedLeader()) {
        return next.startCall(call, headers);
    } else {
        call.close(Status.UNAVAILABLE.withDescription("Not a leader or not ready yet."), new Metadata());
        return new ServerCall.Listener<ReqT>() {
        };
    }
}
 
Example #30
Source File: HeaderServerInterceptor.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call,
    final Metadata requestHeaders,
    ServerCallHandler<ReqT, RespT> next) {
  logger.info("header received from client:" + requestHeaders);
  return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
    @Override
    public void sendHeaders(Metadata responseHeaders) {
      responseHeaders.put(CUSTOM_HEADER_KEY, "customRespondValue");
      super.sendHeaders(responseHeaders);
    }
  }, requestHeaders);
}