Search in sources :

Example 16 with HostAndPort

use of io.servicetalk.transport.api.HostAndPort in project servicetalk by apple.

the class DefaultSingleAddressHttpClientBuilder method setFallbackHostAndPort.

private void setFallbackHostAndPort(HttpClientConfig config, U address) {
    if (address instanceof HostAndPort) {
        HostAndPort hostAndPort = (HostAndPort) address;
        config.fallbackPeerHost(hostAndPort.hostName());
        config.fallbackPeerPort(hostAndPort.port());
    } else if (address instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
        config.fallbackPeerHost(inetSocketAddress.getHostString());
        config.fallbackPeerPort(inetSocketAddress.getPort());
    } else {
        CharSequence cs = hostToCharSequenceFunction.apply(address);
        if (cs == null) {
            config.fallbackPeerHost(null);
            config.fallbackPeerPort(-1);
        } else {
            int colon = CharSequences.indexOf(cs, ':', 0);
            if (colon < 0) {
                config.fallbackPeerHost(cs.toString());
                config.fallbackPeerPort(-1);
            } else if (cs.charAt(0) == '[') {
                colon = CharSequences.indexOf(cs, ']', 1);
                if (colon < 0) {
                    throw new IllegalArgumentException("unable to find end ']' of IPv6 address: " + cs);
                }
                config.fallbackPeerHost(cs.subSequence(1, colon).toString());
                ++colon;
                if (colon >= cs.length()) {
                    config.fallbackPeerPort(-1);
                } else if (cs.charAt(colon) != ':') {
                    throw new IllegalArgumentException("':' expected after ']' for IPv6 address: " + cs);
                } else {
                    config.fallbackPeerPort(parseInt(cs.subSequence(colon + 1, cs.length()).toString()));
                }
            } else {
                config.fallbackPeerHost(cs.subSequence(0, colon).toString());
                config.fallbackPeerPort(parseInt(cs.subSequence(colon + 1, cs.length()).toString()));
            }
        }
    }
}
Also used : HostAndPort(io.servicetalk.transport.api.HostAndPort) InetSocketAddress(java.net.InetSocketAddress)

Example 17 with HostAndPort

use of io.servicetalk.transport.api.HostAndPort in project servicetalk by apple.

the class BasicAuthStrategyInfluencerTest method setup.

private BlockingHttpClient setup(boolean noOffloadsInfluence) throws Exception {
    ioExecutor = NettyIoExecutors.createIoExecutor(IO_EXECUTOR_NAME_PREFIX);
    HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0));
    when(credentialsVerifier.apply(anyString(), anyString())).thenReturn(succeeded("success"));
    when(credentialsVerifier.closeAsync()).thenReturn(completed());
    when(credentialsVerifier.closeAsyncGracefully()).thenReturn(completed());
    when(credentialsVerifier.requiredOffloads()).thenCallRealMethod();
    CredentialsVerifier<String> verifier = credentialsVerifier;
    if (noOffloadsInfluence) {
        verifier = new InfluencingVerifier(verifier, offloadNone());
        serverBuilder.executionStrategy(offloadNone());
    }
    serverBuilder.appendServiceFilter(new BasicAuthHttpServiceFilter.Builder<>(verifier, "dummy").buildServer());
    serverBuilder.ioExecutor(ioExecutor);
    service = new OffloadCheckingService();
    serverContext = serverBuilder.listenStreamingAndAwait(service);
    SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = HttpClients.forSingleAddress(serverHostAndPort(serverContext));
    this.client = clientBuilder.buildBlocking();
    return this.client;
}
Also used : AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString)

Example 18 with HostAndPort

use of io.servicetalk.transport.api.HostAndPort in project servicetalk by apple.

the class KeepAliveTest method setUp.

private void setUp(final boolean keepAlivesFromClient, final Duration keepAliveIdleFor, final Duration idleTimeout) throws Exception {
    this.idleTimeoutMillis = idleTimeout.toMillis();
    GrpcServerBuilder serverBuilder = forAddress(localAddress(0)).initializeHttp(builder -> {
        builder.executor(SERVER_CTX.executor()).ioExecutor(SERVER_CTX.ioExecutor()).executionStrategy(defaultStrategy());
        if (!keepAlivesFromClient) {
            builder.protocols(h2Config(keepAliveIdleFor));
        } else {
            builder.socketOption(IDLE_TIMEOUT, idleTimeoutMillis).protocols(h2Config(null));
        }
    });
    ctx = serverBuilder.listenAndAwait(new ServiceFactory(new InfiniteStreamsService()));
    GrpcClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = GrpcClients.forAddress(serverHostAndPort(ctx)).initializeHttp(builder -> builder.executor(CLIENT_CTX.executor()).ioExecutor(CLIENT_CTX.ioExecutor()).executionStrategy(defaultStrategy()));
    if (keepAlivesFromClient) {
        clientBuilder.initializeHttp(builder -> builder.protocols(h2Config(keepAliveIdleFor)));
    } else {
        clientBuilder.initializeHttp(builder -> builder.socketOption(IDLE_TIMEOUT, idleTimeoutMillis).protocols(h2Config(null)));
    }
    client = clientBuilder.build(new ClientFactory());
}
Also used : GrpcServerBuilder(io.servicetalk.grpc.api.GrpcServerBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServiceFactory(io.servicetalk.grpc.netty.TesterProto.Tester.ServiceFactory) InetSocketAddress(java.net.InetSocketAddress) ClientFactory(io.servicetalk.grpc.netty.TesterProto.Tester.ClientFactory)

Example 19 with HostAndPort

use of io.servicetalk.transport.api.HostAndPort in project servicetalk by apple.

the class GrpcProvidersTest method testGrpcClientBuilderProvider.

@Test
void testGrpcClientBuilderProvider() throws Exception {
    try (ServerContext serverContext = GrpcServers.forAddress(localAddress(0)).listenAndAwait(BlockingGreeterServiceImpl.INSTANCE)) {
        HostAndPort serverAddress = serverHostAndPort(serverContext);
        TestGrpcClientBuilderProvider.MODIFY_FOR_ADDRESS.set(serverAddress);
        try (Greeter.BlockingGreeterClient client = GrpcClients.forAddress(serverAddress).buildBlocking(new ClientFactory())) {
            assertThat(TestGrpcClientBuilderProvider.BUILD_COUNTER.get(), is(1));
            HelloReply reply = client.sayHello(HelloRequest.newBuilder().setName("foo").build());
            assertThat(reply.getMessage(), is(equalTo("reply to foo")));
            assertThat(TestGrpcClientBuilderProvider.CONNECTION_COUNTER.get(), is(1));
        }
    }
}
Also used : AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) GrpcServerContext(io.servicetalk.grpc.api.GrpcServerContext) ServerContext(io.servicetalk.transport.api.ServerContext) Greeter(io.grpc.examples.helloworld.Greeter) ClientFactory(io.grpc.examples.helloworld.Greeter.ClientFactory) GrpcClientFactory(io.servicetalk.grpc.api.GrpcClientFactory) HelloReply(io.grpc.examples.helloworld.HelloReply) Test(org.junit.jupiter.api.Test)

Example 20 with HostAndPort

use of io.servicetalk.transport.api.HostAndPort in project servicetalk by apple.

the class H2ConcurrencyControllerTest method setUp.

@BeforeEach
void setUp() throws Exception {
    serverEventLoopGroup = createIoExecutor(1, "server-io").eventLoopGroup();
    for (int i = 0; i < N_ITERATIONS; i++) {
        latches[i] = new CountDownLatch(1);
    }
    AtomicBoolean secondAndMore = new AtomicBoolean();
    serverAcceptorChannel = bindH2Server(serverEventLoopGroup, new ChannelInitializer<Http2StreamChannel>() {

        @Override
        protected void initChannel(Http2StreamChannel ch) {
            // Respond only for the first request which is used to propagate MAX_CONCURRENT_STREAMS_VALUE
            if (secondAndMore.compareAndSet(false, true)) {
                ch.pipeline().addLast(new EchoHttp2Handler());
            } else {
                // Do not respond to any subsequent requests, only release the associated latch to notify the client
                // that server received the request.
                ch.pipeline().addLast(new SimpleChannelInboundHandler<Http2HeadersFrame>() {

                    @Override
                    protected void channelRead0(final ChannelHandlerContext ctx, final Http2HeadersFrame msg) {
                        String path = msg.headers().path().toString();
                        int i = parseInt(path.substring(1));
                        latches[i].countDown();
                    }
                });
            }
        }
    }, parentPipeline -> {
    }, h2Builder -> {
        h2Builder.initialSettings().maxConcurrentStreams(MAX_CONCURRENT_STREAMS_VALUE);
        return h2Builder;
    });
    final HostAndPort serverAddress = of((InetSocketAddress) serverAcceptorChannel.localAddress());
    client = forResolvedAddress(serverAddress).ioExecutor(CTX.ioExecutor()).executor(CTX.executor()).executionStrategy(defaultStrategy()).appendClientFilter(// All exceptions should be propagated
    disableAutoRetries()).appendConnectionFilter(MulticastTransportEventsStreamingHttpConnectionFilter::new).appendConnectionFilter(connection -> new StreamingHttpConnectionFilter(connection) {

        @Override
        public Single<StreamingHttpResponse> request(StreamingHttpRequest request) {
            return delegate().request(request).liftSync(subscriber -> new SingleSource.Subscriber<StreamingHttpResponse>() {

                @Override
                public void onSubscribe(final Cancellable cancellable) {
                    // Defer the cancel() signal to let the test thread start a new request
                    subscriber.onSubscribe(() -> CTX.executor().schedule(cancellable::cancel, ofMillis(100)));
                }

                @Override
                public void onSuccess(@Nullable final StreamingHttpResponse result) {
                    subscriber.onSuccess(result);
                }

                @Override
                public void onError(final Throwable t) {
                    subscriber.onError(t);
                }
            });
        }
    }).protocols(h2().enableFrameLogging("servicetalk-tests-h2-frame-logger", TRACE, () -> true).build()).build();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) StreamObserverTest.safeSync(io.servicetalk.http.netty.StreamObserverTest.safeSync) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) SingleSource(io.servicetalk.concurrent.SingleSource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(io.servicetalk.concurrent.Cancellable) MulticastTransportEventsStreamingHttpConnectionFilter(io.servicetalk.http.netty.StreamObserverTest.MulticastTransportEventsStreamingHttpConnectionFilter) MAX_CONCURRENCY(io.servicetalk.http.api.HttpEventKey.MAX_CONCURRENCY) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) HostAndPort.of(io.servicetalk.transport.api.HostAndPort.of) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) EchoHttp2Handler(io.servicetalk.http.netty.H2PriorKnowledgeFeatureParityTest.EchoHttp2Handler) HttpClient(io.servicetalk.http.api.HttpClient) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ReservedHttpConnection(io.servicetalk.http.api.ReservedHttpConnection) Nullable(javax.annotation.Nullable) HttpProtocolConfigs.h2(io.servicetalk.http.netty.HttpProtocolConfigs.h2) Matchers.empty(org.hamcrest.Matchers.empty) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) NettyIoExecutors.createIoExecutor(io.servicetalk.transport.netty.internal.NettyIoExecutors.createIoExecutor) Single(io.servicetalk.concurrent.api.Single) HttpResponse(io.servicetalk.http.api.HttpResponse) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) BlockingQueue(java.util.concurrent.BlockingQueue) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) H2PriorKnowledgeFeatureParityTest.bindH2Server(io.servicetalk.http.netty.H2PriorKnowledgeFeatureParityTest.bindH2Server) InetSocketAddress(java.net.InetSocketAddress) Integer.parseInt(java.lang.Integer.parseInt) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) Channel(io.netty.channel.Channel) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) HttpsProxyTest.safeClose(io.servicetalk.http.netty.HttpsProxyTest.safeClose) RetryingHttpRequesterFilter.disableAutoRetries(io.servicetalk.http.netty.RetryingHttpRequesterFilter.disableAutoRetries) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Matchers.is(org.hamcrest.Matchers.is) Http2StreamChannel(io.netty.handler.codec.http2.Http2StreamChannel) Duration.ofMillis(java.time.Duration.ofMillis) HostAndPort(io.servicetalk.transport.api.HostAndPort) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) SingleSource(io.servicetalk.concurrent.SingleSource) Cancellable(io.servicetalk.concurrent.Cancellable) EchoHttp2Handler(io.servicetalk.http.netty.H2PriorKnowledgeFeatureParityTest.EchoHttp2Handler) MulticastTransportEventsStreamingHttpConnectionFilter(io.servicetalk.http.netty.StreamObserverTest.MulticastTransportEventsStreamingHttpConnectionFilter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HostAndPort(io.servicetalk.transport.api.HostAndPort) MulticastTransportEventsStreamingHttpConnectionFilter(io.servicetalk.http.netty.StreamObserverTest.MulticastTransportEventsStreamingHttpConnectionFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) ChannelInitializer(io.netty.channel.ChannelInitializer) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Http2StreamChannel(io.netty.handler.codec.http2.Http2StreamChannel) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

HostAndPort (io.servicetalk.transport.api.HostAndPort)31 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)25 InetSocketAddress (java.net.InetSocketAddress)22 ServerContext (io.servicetalk.transport.api.ServerContext)13 Test (org.junit.jupiter.api.Test)12 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)9 Single (io.servicetalk.concurrent.api.Single)8 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)8 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)8 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)8 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)7 Publisher (io.servicetalk.concurrent.api.Publisher)7 StreamingHttpClientFilterFactory (io.servicetalk.http.api.StreamingHttpClientFilterFactory)7 ExecutionException (java.util.concurrent.ExecutionException)7 Publisher.from (io.servicetalk.concurrent.api.Publisher.from)6 BlockingQueue (java.util.concurrent.BlockingQueue)6 Matchers.notNullValue (org.hamcrest.Matchers.notNullValue)6 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)6 Greeter (io.grpc.examples.helloworld.Greeter)5 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)5