io.grpc.internal.GrpcUtil Java Examples

The following examples show how to use io.grpc.internal.GrpcUtil. 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: GrpclbNameResolverTest.java    From grpc-java with Apache License 2.0 7 votes vote down vote up
@Before
public void setUp() {
  GrpclbNameResolver.setEnableTxt(true);
  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(DEFAULT_PORT)
          .setProxyDetector(GrpcUtil.NOOP_PROXY_DETECTOR)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(serviceConfigParser)
          .setChannelLogger(mock(ChannelLogger.class))
          .build();
  resolver =
      new GrpclbNameResolver(
          null, NAME, args, fakeExecutorResource, fakeClock.getStopwatchSupplier().get(),
          /* isAndroid */false);
  hostName = resolver.getHost();
  assertThat(hostName).isEqualTo(NAME);
}
 
Example #2
Source File: OkHttpClientStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("GuardedBy")
public void start_headerPlaintext() throws IOException {
  Metadata metaData = new Metadata();
  metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application");
  when(transport.isUsingPlaintext()).thenReturn(true);
  stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport,
      flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost",
      "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false);
  stream.start(new BaseClientStreamListener());
  stream.transportState().start(3);

  verify(mockedFrameWriter)
      .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
  assertThat(headersCaptor.getValue()).containsExactly(
      Headers.HTTP_SCHEME_HEADER,
      Headers.METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "localhost"),
      new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"),
      Headers.CONTENT_TYPE_HEADER,
      Headers.TE_HEADER)
      .inOrder();
}
 
Example #3
Source File: OkHttpClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void overrideDefaultUserAgent() throws Exception {
  startTransport(3, null, true, DEFAULT_MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "fakeUserAgent");
  MockStreamListener listener = new MockStreamListener();
  OkHttpClientStream stream =
      clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
  stream.start(listener);
  List<Header> expectedHeaders = Arrays.asList(SCHEME_HEADER, METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "notarealauthority:80"),
      new Header(Header.TARGET_PATH, "/" + method.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(),
          GrpcUtil.getGrpcUserAgent("okhttp", "fakeUserAgent")),
      CONTENT_TYPE_HEADER, TE_HEADER);
  verify(frameWriter, timeout(TIME_OUT_MS))
      .synStream(eq(false), eq(false), eq(3), eq(0), eq(expectedHeaders));
  getStream(3).cancel(Status.CANCELLED);
  shutdownAndVerify();
}
 
Example #4
Source File: GrpcClientHandler.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 解析应答
 *
 * @param message 消息
 * @param wrapper 返回类型
 * @return 应答
 * @throws IOException
 */
protected ResponsePayload decodePayload(final Http2ResponseMessage message, final ClassWrapper wrapper) throws IOException {
    Http2Headers headers = message.headers();
    InputStream in = new UnsafeByteArrayInputStream(message.content());
    //读压缩位标识
    int isCompression = in.read();
    //读长度共4位
    if (in.skip(4) < 4) {
        throw new IOException(String.format("request data is not full. id=%d", message.getMsgId()));
    }
    //解压处理
    if (isCompression > 0) {
        Pair<String, Compression> pair = getEncoding((String) headers.get(GrpcUtil.MESSAGE_ACCEPT_ENCODING));
        if (pair != null) {
            in = pair.getValue().decompress(in);
        }
    }
    //反序列化
    Object response = serialization.getSerializer().deserialize(in, wrapper.getClazz());
    if (wrapper.isWrapper()) {
        //性能优化
        Object[] parameters = wrapper.getConversion().getToParameter().apply(response);
        response = parameters[0];
    }
    return new ResponsePayload(response);
}
 
Example #5
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (DISCOVERY_SCHEME.equals(targetUri.getScheme())) {
        final String serviceName = targetUri.getPath();
        if (serviceName == null || serviceName.length() <= 1 || !serviceName.startsWith("/")) {
            throw new IllegalArgumentException("Incorrectly formatted target uri; "
                    + "expected: '" + DISCOVERY_SCHEME + ":[//]/<service-name>'; "
                    + "but was '" + targetUri.toString() + "'");
        }
        final AtomicReference<DiscoveryClientNameResolver> reference = new AtomicReference<>();
        final DiscoveryClientNameResolver discoveryClientNameResolver =
                new DiscoveryClientNameResolver(serviceName.substring(1), this.client, args,
                        GrpcUtil.SHARED_CHANNEL_EXECUTOR,
                        () -> this.discoveryClientNameResolvers.remove(reference.get()));
        reference.set(discoveryClientNameResolver);
        this.discoveryClientNameResolvers.add(discoveryClientNameResolver);
        return discoveryClientNameResolver;
    }
    return null;
}
 
Example #6
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private void startServer(int maxStreamsPerConnection, int maxHeaderListSize) throws IOException {
  server = new NettyServer(
      TestUtils.testServerAddress(0),
      NioServerSocketChannel.class,
      new HashMap<ChannelOption<?>, Object>(),
      group, group, negotiator,
      Collections.<ServerStreamTracer.Factory>emptyList(),
      TransportTracer.getDefaultFactory(),
      maxStreamsPerConnection,
      DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, maxHeaderListSize,
      DEFAULT_SERVER_KEEPALIVE_TIME_NANOS, DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS,
      MAX_CONNECTION_IDLE_NANOS_DISABLED,
      MAX_CONNECTION_AGE_NANOS_DISABLED, MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE, true, 0,
      channelz);
  server.start(serverListener);
  address = TestUtils.testServerAddress(server.getPort());
  authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
}
 
Example #7
Source File: UtilsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("UndefinedEquals") // AsciiString.equals
public void convertServerHeaders_sanitizes() {
  Metadata metaData = new Metadata();

  // Intentionally being explicit here rather than relying on any pre-defined lists of headers,
  // since the goal of this test is to validate the correctness of such lists in the first place.
  metaData.put(GrpcUtil.CONTENT_TYPE_KEY, "to-be-removed");
  metaData.put(GrpcUtil.TE_HEADER, "to-be-removed");
  metaData.put(GrpcUtil.USER_AGENT_KEY, "to-be-removed");
  metaData.put(userKey, userValue);

  Http2Headers output = Utils.convertServerHeaders(metaData);
  DefaultHttp2Headers headers = new DefaultHttp2Headers();
  for (Map.Entry<CharSequence, CharSequence> entry : output) {
    headers.add(entry.getKey(), entry.getValue());
  }
  // 2 reserved headers, 1 user header
  assertEquals(2 + 1, headers.size());
  assertEquals(Utils.CONTENT_TYPE_GRPC, headers.get(GrpcUtil.CONTENT_TYPE_KEY.name()));
}
 
Example #8
Source File: OkHttpChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Attributes getNameResolverParams() {
  int defaultPort;
  switch (negotiationType) {
    case PLAINTEXT:
      defaultPort = GrpcUtil.DEFAULT_PORT_PLAINTEXT;
      break;
    case TLS:
      defaultPort = GrpcUtil.DEFAULT_PORT_SSL;
      break;
    default:
      throw new AssertionError(negotiationType + " not handled");
  }
  return Attributes.newBuilder()
      .set(NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build();
}
 
Example #9
Source File: OkHttpClientTransportTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void overrideDefaultUserAgent() throws Exception {
  startTransport(3, null, true, DEFAULT_MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "fakeUserAgent");
  MockStreamListener listener = new MockStreamListener();
  OkHttpClientStream stream =
      clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
  stream.start(listener);
  List<Header> expectedHeaders = Arrays.asList(HTTP_SCHEME_HEADER, METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "notarealauthority:80"),
      new Header(Header.TARGET_PATH, "/" + method.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(),
          GrpcUtil.getGrpcUserAgent("okhttp", "fakeUserAgent")),
      CONTENT_TYPE_HEADER, TE_HEADER);
  verify(frameWriter, timeout(TIME_OUT_MS))
      .synStream(eq(false), eq(false), eq(3), eq(0), eq(expectedHeaders));
  getStream(3).cancel(Status.CANCELLED);
  shutdownAndVerify();
}
 
Example #10
Source File: OkHttpClientTransport.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
  if (errorCode == ErrorCode.ENHANCE_YOUR_CALM) {
    String data = debugData.utf8();
    log.log(Level.WARNING, String.format(
        "%s: Received GOAWAY with ENHANCE_YOUR_CALM. Debug data: %s", this, data));
    if ("too_many_pings".equals(data)) {
      tooManyPingsRunnable.run();
    }
  }
  Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
      .augmentDescription("Received Goaway");
  if (debugData.size() > 0) {
    // If a debug message was provided, use it.
    status = status.augmentDescription(debugData.utf8());
  }
  startGoAway(lastGoodStreamId, null, status);
}
 
Example #11
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void wrongHostNameFailHostnameVerification() throws Exception {
  ManagedChannel channel = createChannelBuilder()
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          BAD_HOSTNAME, getPort()))
      .build();
  TestServiceGrpc.TestServiceBlockingStub blockingStub =
      TestServiceGrpc.newBlockingStub(channel);

  Throwable actualThrown = null;
  try {
    blockingStub.emptyCall(Empty.getDefaultInstance());
  } catch (Throwable t) {
    actualThrown = t;
  }
  assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
  Throwable cause = Throwables.getRootCause(actualThrown);
  assertTrue(
      "Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
  channel.shutdown();
}
 
Example #12
Source File: UtilsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("UndefinedEquals") // AsciiString.equals
public void convertServerHeaders_sanitizes() {
  Metadata metaData = new Metadata();

  // Intentionally being explicit here rather than relying on any pre-defined lists of headers,
  // since the goal of this test is to validate the correctness of such lists in the first place.
  metaData.put(GrpcUtil.CONTENT_TYPE_KEY, "to-be-removed");
  metaData.put(GrpcUtil.TE_HEADER, "to-be-removed");
  metaData.put(GrpcUtil.USER_AGENT_KEY, "to-be-removed");
  metaData.put(userKey, userValue);

  Http2Headers output = Utils.convertServerHeaders(metaData);
  DefaultHttp2Headers headers = new DefaultHttp2Headers();
  for (Map.Entry<CharSequence, CharSequence> entry : output) {
    headers.add(entry.getKey(), entry.getValue());
  }
  // 2 reserved headers, 1 user header
  assertEquals(2 + 1, headers.size());
  assertEquals(Utils.CONTENT_TYPE_GRPC, headers.get(GrpcUtil.CONTENT_TYPE_KEY.name()));
}
 
Example #13
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (DISCOVERY_SCHEME.equals(targetUri.getScheme())) {
        final String serviceName = targetUri.getPath();
        if (serviceName == null || serviceName.length() <= 1 || !serviceName.startsWith("/")) {
            throw new IllegalArgumentException("Incorrectly formatted target uri; "
                    + "expected: '" + DISCOVERY_SCHEME + ":[//]/<service-name>'; "
                    + "but was '" + targetUri.toString() + "'");
        }
        final AtomicReference<DiscoveryClientNameResolver> reference = new AtomicReference<>();
        final DiscoveryClientNameResolver discoveryClientNameResolver =
                new DiscoveryClientNameResolver(serviceName.substring(1), this.client, args,
                        GrpcUtil.SHARED_CHANNEL_EXECUTOR,
                        () -> this.discoveryClientNameResolvers.remove(reference.get()));
        reference.set(discoveryClientNameResolver);
        this.discoveryClientNameResolvers.add(discoveryClientNameResolver);
        return discoveryClientNameResolver;
    }
    return null;
}
 
Example #14
Source File: NettyClientHandler.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Handler for an inbound HTTP/2 RST_STREAM frame, terminating a stream.
 */
private void onRstStreamRead(int streamId, long errorCode) {
  NettyClientStream.TransportState stream = clientStream(connection().stream(streamId));
  if (stream != null) {
    Status status = GrpcUtil.Http2Error.statusForCode((int) errorCode)
        .augmentDescription("Received Rst Stream");
    stream.transportReportStatus(
        status,
        errorCode == Http2Error.REFUSED_STREAM.code()
            ? RpcProgress.REFUSED : RpcProgress.PROCESSED,
        false /*stop delivery*/,
        new Metadata());
    if (keepAliveManager != null) {
      keepAliveManager.onDataReceived();
    }
  }
}
 
Example #15
Source File: NettyClientTransportTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void keepAliveEnabled_shouldSetTcpUserTimeout() throws Exception {
  assume().that(Utils.isEpollAvailable()).isTrue();

  startServer();
  EventLoopGroup epollGroup = Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP.create();
  int keepAliveTimeMillis = 12345670;
  int keepAliveTimeoutMillis = 1234567;
  try {
    NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
        GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, null /* user agent */, true /* keep alive */,
        TimeUnit.MILLISECONDS.toNanos(keepAliveTimeMillis),
        TimeUnit.MILLISECONDS.toNanos(keepAliveTimeoutMillis),
        new ReflectiveChannelFactory<>(Utils.DEFAULT_CLIENT_CHANNEL_TYPE), epollGroup);

    callMeMaybe(transport.start(clientTransportListener));

    ChannelOption<Integer> tcpUserTimeoutOption = Utils.maybeGetTcpUserTimeoutOption();
    assertThat(tcpUserTimeoutOption).isNotNull();
    // on some linux based system, the integer value may have error (usually +-1)
    assertThat((double) transport.channel().config().getOption(tcpUserTimeoutOption))
        .isWithin(5.0).of((double) keepAliveTimeoutMillis);
  } finally {
    epollGroup.shutdownGracefully();
  }
}
 
Example #16
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
public static Http2Headers convertClientHeaders(Metadata headers,
    AsciiString scheme,
    AsciiString defaultPath,
    AsciiString authority,
    AsciiString method,
    AsciiString userAgent) {
  Preconditions.checkNotNull(defaultPath, "defaultPath");
  Preconditions.checkNotNull(authority, "authority");
  Preconditions.checkNotNull(method, "method");

  // Discard any application supplied duplicates of the reserved headers
  headers.discardAll(CONTENT_TYPE_KEY);
  headers.discardAll(GrpcUtil.TE_HEADER);
  headers.discardAll(GrpcUtil.USER_AGENT_KEY);

  return GrpcHttp2OutboundHeaders.clientRequestHeaders(
      toHttp2Headers(headers),
      authority,
      defaultPath,
      method,
      scheme,
      userAgent);
}
 
Example #17
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static HostPort parseAuthority(String authority) {
  URI uri = GrpcUtil.authorityToUri(Preconditions.checkNotNull(authority, "authority"));
  String host;
  int port;
  if (uri.getHost() != null) {
    host = uri.getHost();
    port = uri.getPort();
  } else {
    /*
     * Implementation note: We pick -1 as the port here rather than deriving it from the
     * original socket address.  The SSL engine doesn't use this port number when contacting the
     * remote server, but rather it is used for other things like SSL Session caching.  When an
     * invalid authority is provided (like "bad_cert"), picking the original port and passing it
     * in would mean that the port might used under the assumption that it was correct.   By
     * using -1 here, it forces the SSL implementation to treat it as invalid.
     */
    host = authority;
    port = -1;
  }
  return new HostPort(host, port);
}
 
Example #18
Source File: OkHttpClientTransport.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
OkHttpClientTransport(InetSocketAddress address, String authority, @Nullable String userAgent,
    Executor executor, @Nullable SSLSocketFactory sslSocketFactory,
    @Nullable HostnameVerifier hostnameVerifier, ConnectionSpec connectionSpec,
    int maxMessageSize, int initialWindowSize, @Nullable ProxyParameters proxy,
    Runnable tooManyPingsRunnable, int maxInboundMetadataSize, TransportTracer transportTracer) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.defaultAuthority = authority;
  this.maxMessageSize = maxMessageSize;
  this.initialWindowSize = initialWindowSize;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  serializingExecutor = new SerializingExecutor(executor);
  // Client initiated streams are odd, server initiated ones are even. Server should not need to
  // use it. We start clients at 3 to avoid conflicting with HTTP negotiation.
  nextStreamId = 3;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.connectionSpec = Preconditions.checkNotNull(connectionSpec, "connectionSpec");
  this.stopwatchFactory = GrpcUtil.STOPWATCH_SUPPLIER;
  this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent);
  this.proxy = proxy;
  this.tooManyPingsRunnable =
      Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
  this.maxInboundMetadataSize = maxInboundMetadataSize;
  this.transportTracer = Preconditions.checkNotNull(transportTracer);
  initTransportTracer();
}
 
Example #19
Source File: NettyClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getEagAttributes_negotiatorHandler() throws Exception {
  address = TestUtils.testServerAddress(new InetSocketAddress(12345));
  authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());

  NoopProtocolNegotiator npn = new NoopProtocolNegotiator();
  eagAttributes = Attributes.newBuilder()
      .set(Attributes.Key.create("trash"), "value")
      .build();
  NettyClientTransport transport = newTransport(npn);
  callMeMaybe(transport.start(clientTransportListener));

  // EAG Attributes are available before the negotiation is complete
  assertSame(eagAttributes, npn.grpcHandler.getEagAttributes());
}
 
Example #20
Source File: OkHttpChannelBuilder.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
  if (closed) {
    return;
  }
  closed = true;

  if (usingSharedScheduler) {
    SharedResourceHolder.release(GrpcUtil.TIMER_SERVICE, timeoutService);
  }

  if (usingSharedExecutor) {
    SharedResourceHolder.release(SHARED_EXECUTOR, executor);
  }
}
 
Example #21
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
public static Http2Headers convertServerHeaders(Metadata headers) {
  // Discard any application supplied duplicates of the reserved headers
  headers.discardAll(CONTENT_TYPE_KEY);
  headers.discardAll(GrpcUtil.TE_HEADER);
  headers.discardAll(GrpcUtil.USER_AGENT_KEY);

  return GrpcHttp2OutboundHeaders.serverResponseHeaders(toHttp2Headers(headers));
}
 
Example #22
Source File: NettyChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@CheckReturnValue
private static String getAuthorityFromAddress(SocketAddress address) {
  if (address instanceof InetSocketAddress) {
    InetSocketAddress inetAddress = (InetSocketAddress) address;
    return GrpcUtil.authorityFromHostAndPort(inetAddress.getHostString(), inetAddress.getPort());
  } else {
    return address.toString();
  }
}
 
Example #23
Source File: NettyServerHandlerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void transportReadyDelayedUntilConnectionPreface() throws Exception {
  initChannel(new GrpcHttp2ServerHeadersDecoder(GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE));

  handler().handleProtocolNegotiationCompleted(Attributes.EMPTY, /*securityInfo=*/ null);
  verify(transportListener, never()).transportReady(any(Attributes.class));

  // Simulate receipt of the connection preface
  channelRead(Http2CodecUtil.connectionPrefaceBuf());
  channelRead(serializeSettings(new Http2Settings()));
  verify(transportListener).transportReady(any(Attributes.class));
}
 
Example #24
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void keepAliveEnabled() throws Exception {
  startServer();
  NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
      GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, null /* user agent */, true /* keep alive */);
  callMeMaybe(transport.start(clientTransportListener));
  Rpc rpc = new Rpc(transport).halfClose();
  rpc.waitForResponse();

  assertNotNull(transport.keepAliveManager());
}
 
Example #25
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void addDefaultUserAgent() throws Exception {
  startServer();
  NettyClientTransport transport = newTransport(newNegotiator());
  callMeMaybe(transport.start(clientTransportListener));

  // Send a single RPC and wait for the response.
  new Rpc(transport).halfClose().waitForResponse();

  // Verify that the received headers contained the User-Agent.
  assertEquals(1, serverListener.streamListeners.size());

  Metadata headers = serverListener.streamListeners.get(0).headers;
  assertEquals(GrpcUtil.getGrpcUserAgent("netty", null), headers.get(USER_AGENT_KEY));
}
 
Example #26
Source File: NettyClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void addDefaultUserAgent() throws Exception {
  startServer();
  NettyClientTransport transport = newTransport(newNegotiator());
  callMeMaybe(transport.start(clientTransportListener));

  // Send a single RPC and wait for the response.
  new Rpc(transport).halfClose().waitForResponse();

  // Verify that the received headers contained the User-Agent.
  assertEquals(1, serverListener.streamListeners.size());

  Metadata headers = serverListener.streamListeners.get(0).headers;
  assertEquals(GrpcUtil.getGrpcUserAgent("netty", null), headers.get(USER_AGENT_KEY));
}
 
Example #27
Source File: AbstractTransportTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/** This assumes the client limits metadata size to GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE. */
@Test
public void clientChecksInboundMetadataSize_header() throws Exception {
  server.start(serverListener);
  client = newClientTransport(server);
  startTransport(client, mockClientTransportListener);
  MockServerTransportListener serverTransportListener
      = serverListener.takeListenerOrFail(TIMEOUT_MS, TimeUnit.MILLISECONDS);
  serverTransport = serverTransportListener.transport;

  Metadata tooLargeMetadata = new Metadata();
  tooLargeMetadata.put(
      Metadata.Key.of("foo-bin", Metadata.BINARY_BYTE_MARSHALLER),
      new byte[GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE]);

  ClientStream clientStream =
      client.newStream(methodDescriptor, new Metadata(), callOptions);
  ClientStreamListenerBase clientStreamListener = new ClientStreamListenerBase();
  clientStream.start(clientStreamListener);

  clientStream.writeMessage(methodDescriptor.streamRequest("foo"));
  clientStream.halfClose();
  clientStream.request(1);

  StreamCreation serverStreamCreation
      = serverTransportListener.takeStreamOrFail(TIMEOUT_MS, TimeUnit.MILLISECONDS);

  serverStreamCreation.stream.request(1);
  serverStreamCreation.stream.writeHeaders(tooLargeMetadata);
  serverStreamCreation.stream.writeMessage(methodDescriptor.streamResponse("response"));
  serverStreamCreation.stream.close(Status.OK, new Metadata());

  Status status = clientStreamListener.status.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
  List<Status.Code> codeOptions = Arrays.asList(
      Status.Code.UNKNOWN, Status.Code.RESOURCE_EXHAUSTED, Status.Code.INTERNAL);
  if (!codeOptions.contains(status.getCode())) {
    fail("Status code was not expected: " + status);
  }
  assertFalse(clientStreamListener.headers.isDone());
}
 
Example #28
Source File: CronetClientTransport.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
CronetClientTransport(
    StreamBuilderFactory streamFactory,
    InetSocketAddress address,
    String authority,
    @Nullable String userAgent,
    Attributes eagAttrs,
    Executor executor,
    int maxMessageSize,
    boolean alwaysUsePut,
    TransportTracer transportTracer,
    boolean useGetForSafeMethods,
    boolean usePutForIdempotentMethods) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.logId = InternalLogId.allocate(getClass(), address.toString());
  this.authority = authority;
  this.userAgent = GrpcUtil.getGrpcUserAgent("cronet", userAgent);
  this.maxMessageSize = maxMessageSize;
  this.alwaysUsePut = alwaysUsePut;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  this.streamFactory = Preconditions.checkNotNull(streamFactory, "streamFactory");
  this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
  this.attrs = Attributes.newBuilder()
      .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
      .set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs)
      .build();
  this.useGetForSafeMethods = useGetForSafeMethods;
  this.usePutForIdempotentMethods = usePutForIdempotentMethods;
}
 
Example #29
Source File: InProcessChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private InProcessClientTransportFactory(
    String name,
    @Nullable ScheduledExecutorService scheduledExecutorService,
    int maxInboundMetadataSize) {
  this.name = name;
  useSharedTimer = scheduledExecutorService == null;
  timerService = useSharedTimer
      ? SharedResourceHolder.get(GrpcUtil.TIMER_SERVICE) : scheduledExecutorService;
  this.maxInboundMetadataSize = maxInboundMetadataSize;
}
 
Example #30
Source File: OrcaOobUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public OrcaReportingHelperWrapper newOrcaReportingHelperWrapper(
    LoadBalancer.Helper delegate,
    OrcaOobReportListener listener) {
  return newOrcaReportingHelperWrapper(
      delegate,
      listener,
      new ExponentialBackoffPolicy.Provider(),
      GrpcUtil.STOPWATCH_SUPPLIER);
}