com.linecorp.armeria.common.SessionProtocol Java Examples

The following examples show how to use com.linecorp.armeria.common.SessionProtocol. 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: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxyWithH2C() throws Exception {
    final int numRequests = 5;
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(SessionProtocol.H2C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();

    final List<CompletableFuture<AggregatedHttpResponse>> responseFutures = new ArrayList<>();
    for (int i = 0; i < numRequests; i++) {
        responseFutures.add(webClient.get(PROXY_PATH).aggregate());
    }
    await().until(() -> responseFutures.stream().allMatch(CompletableFuture::isDone));
    assertThat(responseFutures.stream().map(CompletableFuture::join))
            .allMatch(response -> response.contentUtf8().equals(SUCCESS_RESPONSE));
    assertThat(numSuccessfulProxyRequests).isGreaterThanOrEqualTo(1);
    clientFactory.close();
}
 
Example #2
Source File: ServerRuleDelegate.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link URI} for the {@link Server} of the specified {@link SessionProtocol} and
 * {@link SerializationFormat}.
 *
 * @throws IllegalStateException if the {@link Server} is not started or
 *                               it did not open the port for the specified {@link SessionProtocol}.
 */
public URI uri(SessionProtocol protocol, SerializationFormat format) {
    requireNonNull(protocol, "protocol");
    requireNonNull(format, "format");

    ensureStarted();

    final int port;
    if (!protocol.isTls() && hasHttp()) {
        port = httpPort();
    } else if (protocol.isTls() && hasHttps()) {
        port = httpsPort();
    } else {
        throw new IllegalStateException("can't find the specified port");
    }

    final String uriStr = protocol.uriText() + "://127.0.0.1:" + port;
    if (format == SerializationFormat.NONE) {
        return URI.create(uriStr);
    } else {
        return URI.create(format.uriText() + '+' + uriStr);
    }
}
 
Example #3
Source File: ArmeriaCallFactoryTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void respectsHttpClientUri_endpointGroup() throws Exception {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", server.httpPort()),
                                                 Endpoint.of("127.0.0.1", server.httpPort()));

    final Service service = ArmeriaRetrofit.builder("http", group)
                                           .addConverterFactory(converterFactory)
                                           .build()
                                           .create(Service.class);

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        final Response<Pojo> response = service.postForm("Cony", 26).get();

        final RequestLog log = ctxCaptor.get().log().whenComplete().join();
        assertThat(log.sessionProtocol()).isSameAs(SessionProtocol.H2C);
        assertThat(log.requestHeaders().authority()).isEqualTo("127.0.0.1:" + server.httpPort());

        // TODO(ide) Use the actual `host:port`. See https://github.com/line/armeria/issues/379
        final HttpUrl url = response.raw().request().url();
        assertThat(url.scheme()).isEqualTo("http");
        assertThat(url.host()).startsWith("armeria-group-");
        assertThat(url.pathSegments()).containsExactly("postForm");
    }
}
 
Example #4
Source File: AbstractArmeriaBeanPostProcessor.java    From armeria with Apache License 2.0 6 votes vote down vote up
private LocalArmeriaPortElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
    super(member, pd);
    final LocalArmeriaPort localArmeriaPort = ae.getAnnotation(LocalArmeriaPort.class);
    final SessionProtocol protocol = localArmeriaPort.value();
    Server server = getServer();
    if (server == null) {
        server = beanFactory.getBean(Server.class);
        serServer(server);
    }

    Integer port = portCache.get(protocol);
    if (port == null) {
        port = server.activeLocalPort(protocol);
        portCache.put(protocol, port);
    }
    this.port = port;
}
 
Example #5
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                             .options(clientOptions)
                                             .build(Handlers.HELLO.iface());
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman");
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #6
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testTimeServiceAsync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final TimeService.AsyncIface client =
            Clients.builder(uri(Handlers.TIME, format, protocol))
                   .options(clientOptions)
                   .build(Handlers.TIME.asyncIface());

    final BlockingQueue<Object> resQueue = new LinkedBlockingQueue<>();
    client.getServerTime(new RequestQueuingCallback(resQueue));

    final Object result = resQueue.take();
    assertThat(result).isInstanceOf(Long.class);
    assertThat((Long) result).isLessThanOrEqualTo(System.currentTimeMillis());
}
 
Example #7
Source File: ServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testActiveLocalPort() throws Exception {
    final Server server = Server.builder()
                                .http(0)
                                .https(0)
                                .tlsSelfSigned()
                                .service("/", (ctx, res) -> HttpResponse.of(""))
                                .build();

    // not started yet
    assertThatThrownBy(server::activeLocalPort)
            .isInstanceOf(IllegalStateException.class)
            .hasMessageContaining("no active local ports");

    server.start().get();

    assertThat(server.activeLocalPort()).isPositive();
    assertThat(server.activeLocalPort(SessionProtocol.HTTP)).isPositive();
    assertThat(server.activeLocalPort(SessionProtocol.HTTPS)).isPositive();
    assertThatThrownBy(() -> server.activeLocalPort(SessionProtocol.PROXY))
            .isInstanceOf(IllegalStateException.class)
            .hasMessageContaining("no active local ports for " + SessionProtocol.PROXY);
}
 
Example #8
Source File: Server.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
private ServerPort activePort0(@Nullable SessionProtocol protocol) {
    ServerPort candidate = null;
    synchronized (activePorts) {
        for (ServerPort serverPort : activePorts.values()) {
            if (protocol == null || serverPort.hasProtocol(protocol)) {
                if (!isLocalPort(serverPort)) {
                    return serverPort;
                } else if (candidate == null) {
                    candidate = serverPort;
                }
            }
        }
    }
    return candidate;
}
 
Example #9
Source File: HttpClientPipelineConfigurator.java    From armeria with Apache License 2.0 6 votes vote down vote up
HttpClientPipelineConfigurator(HttpClientFactory clientFactory,
                               SessionProtocol sessionProtocol,
                               @Nullable SslContext sslCtx) {
    this.clientFactory = clientFactory;

    if (sessionProtocol == HTTP || sessionProtocol == HTTPS) {
        httpPreference = HttpPreference.HTTP2_PREFERRED;
    } else if (sessionProtocol == H1 || sessionProtocol == H1C) {
        httpPreference = HttpPreference.HTTP1_REQUIRED;
    } else if (sessionProtocol == H2 || sessionProtocol == H2C) {
        httpPreference = HttpPreference.HTTP2_REQUIRED;
    } else {
        // Should never reach here.
        throw new Error();
    }

    if (sessionProtocol.isTls()) {
        this.sslCtx = sslCtx;
    } else {
        this.sslCtx = null;
    }
}
 
Example #10
Source File: ServerMaxConnectionAgeTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    opened = new AtomicInteger();
    closed = new AtomicInteger();
    connectionPoolListener = new ConnectionPoolListener() {
        @Override
        public void connectionOpen(SessionProtocol protocol, InetSocketAddress remoteAddr,
                                   InetSocketAddress localAddr, AttributeMap attrs) throws Exception {
            opened.incrementAndGet();
        }

        @Override
        public void connectionClosed(SessionProtocol protocol, InetSocketAddress remoteAddr,
                                     InetSocketAddress localAddr, AttributeMap attrs) throws Exception {
            closed.incrementAndGet();
        }
    };
}
 
Example #11
Source File: HttpClientMaxConcurrentStreamTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void exceededMaxStreamsForMultipleEventLoops() {
    final ClientFactory clientFactory =
            ClientFactory.builder()
                         .connectionPoolListener(connectionPoolListenerWrapper)
                         .maxNumEventLoopsPerEndpoint(2)
                         .build();
    final WebClient client = WebClient.builder(server.uri(SessionProtocol.H2C))
                                      .factory(clientFactory)
                                      .build();
    final AtomicInteger opens = new AtomicInteger();
    connectionPoolListener = newConnectionPoolListener(opens::incrementAndGet, () -> {});

    final int numExpectedConnections = MAX_NUM_CONNECTIONS;
    final int numRequests = MAX_CONCURRENT_STREAMS * numExpectedConnections;

    runInsideEventLoop(clientFactory.eventLoopGroup(), () -> {
        for (int i = 0; i < numRequests; i++) {
            client.get(PATH).aggregate();
        }
    });

    await().untilAsserted(() -> assertThat(responses).hasSize(numRequests));
    assertThat(opens).hasValue(numExpectedConnections);
}
 
Example #12
Source File: ArmeriaConfigurationUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void configureServer() throws Exception {
    final File yml = new File(resourceFilePath("armeria-settings.yaml"));
    final ArmeriaSettings armeriaSettings = configFactory.build(yml);
    armeriaSettings.setSsl(null);
    final ServerBuilder serverBuilder = Server.builder()
            .service("/foo", (ctx, req) -> HttpResponse.of(200));
    serverBuilder.tlsSelfSigned();
    ArmeriaConfigurationUtil.configureServer(serverBuilder, armeriaSettings);
    final Server server = serverBuilder.build();
    assertThat(server.defaultHostname()).isEqualTo("host.name.com");
    assertThat(server.config().maxNumConnections()).isEqualTo(5000);
    assertThat(server.config().isDateHeaderEnabled()).isFalse();
    assertThat(server.config().isServerHeaderEnabled()).isTrue();
    assertThat(server.config().defaultVirtualHost().maxRequestLength()).isEqualTo(10485761);

    assertThat(server.config().ports()).hasSize(3);
    assertThat(server.config().ports()).containsExactly(
            new ServerPort(8080, SessionProtocol.HTTP),
            new ServerPort(new InetSocketAddress("127.0.0.1", 8081), SessionProtocol.HTTPS),
            new ServerPort(8443, SessionProtocol.HTTPS, SessionProtocol.PROXY)
    );
    assertThat(server.config().http1MaxChunkSize()).isEqualTo(4000);
    assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096);
    assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096);
    assertThat(server.config().http2InitialConnectionWindowSize()).isEqualTo(1024 * 1024 * 2);
    assertThat(server.config().http2InitialStreamWindowSize()).isEqualTo(1024 * 1024 * 2);
    assertThat(server.config().http2MaxFrameSize()).isEqualTo(16385);
    assertThat(server.config().http2MaxHeaderListSize()).isEqualTo(8193);
    assertThat(server.config().proxyProtocolMaxTlvSize()).isEqualTo(65320);
}
 
Example #13
Source File: ConnectionPoolListenerWrapper.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionClosed(SessionProtocol protocol,
                             InetSocketAddress remoteAddr,
                             InetSocketAddress localAddr,
                             AttributeMap attrs) throws Exception {
    delegate().connectionClosed(protocol, remoteAddr, localAddr, attrs);
}
 
Example #14
Source File: ConnectionPoolLoggingListener.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionOpen(SessionProtocol protocol,
                           InetSocketAddress remoteAddr,
                           InetSocketAddress localAddr,
                           AttributeMap attrs) throws Exception {
    final int activeChannels = this.activeChannels.incrementAndGet();
    if (logger.isInfoEnabled()) {
        attrs.attr(OPEN_NANOS).set(ticker.read());
        logger.info("[L:{} - R:{}][{}] OPEN (active channels: {})",
                    localAddr, remoteAddr, protocol.uriText(), activeChannels);
    }
}
 
Example #15
Source File: DefaultWebClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
private HttpResponse execute(EndpointGroup endpointGroup, HttpRequest req, SessionProtocol protocol) {
    final PathAndQuery pathAndQuery = PathAndQuery.parse(req.path());
    if (pathAndQuery == null) {
        final IllegalArgumentException cause = new IllegalArgumentException("invalid path: " + req.path());
        return abortRequestAndReturnFailureResponse(req, cause);
    }
    return execute(protocol, endpointGroup, req.method(),
                   pathAndQuery.path(), pathAndQuery.query(), null, req);
}
 
Example #16
Source File: Http2ClientConnectionHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
Http2ClientConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
                             Http2Settings initialSettings, Channel channel,
                             HttpClientFactory clientFactory, SessionProtocol protocol) {

    super(decoder, encoder, initialSettings);
    this.clientFactory = clientFactory;

    if (clientFactory.idleTimeoutMillis() > 0 || clientFactory.pingIntervalMillis() > 0) {
        final Timer keepAliveTimer =
                MoreMeters.newTimer(clientFactory.meterRegistry(), "armeria.client.connections.lifespan",
                                    ImmutableList.of(Tag.of("protocol", protocol.uriText())));
        keepAliveHandler = new Http2ClientKeepAliveHandler(
                channel, encoder.frameWriter(), keepAliveTimer,
                clientFactory.idleTimeoutMillis(), clientFactory.pingIntervalMillis());
    } else {
        keepAliveHandler = null;
    }

    responseDecoder = new Http2ResponseDecoder(channel, encoder(), clientFactory, keepAliveHandler);
    connection().addListener(responseDecoder);
    decoder().frameListener(responseDecoder);

    // Setup post build options
    final long timeout = clientFactory.idleTimeoutMillis();
    if (timeout > 0) {
        gracefulShutdownTimeoutMillis(timeout);
    } else {
        // Timeout disabled
        gracefulShutdownTimeoutMillis(-1);
    }
}
 
Example #17
Source File: HealthCheckedEndpointGroup.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
HealthCheckedEndpointGroup(
        EndpointGroup delegate, SessionProtocol protocol, int port,
        Backoff retryBackoff, ClientOptions clientOptions,
        Function<? super HealthCheckerContext, ? extends AsyncCloseable> checkerFactory,
        HealthCheckStrategy healthCheckStrategy) {

    super(requireNonNull(delegate, "delegate").selectionStrategy());

    this.delegate = delegate;
    this.protocol = requireNonNull(protocol, "protocol");
    this.port = port;
    this.retryBackoff = requireNonNull(retryBackoff, "retryBackoff");
    this.clientOptions = requireNonNull(clientOptions, "clientOptions");
    this.checkerFactory = requireNonNull(checkerFactory, "checkerFactory");
    this.healthCheckStrategy = requireNonNull(healthCheckStrategy, "healthCheckStrategy");

    clientOptions.factory().whenClosed().thenRun(this::closeAsync);
    delegate.addListener(this::updateCandidates);
    updateCandidates(delegate.whenReady().join());

    // Wait until the initial health of all endpoints are determined.
    final List<DefaultHealthCheckerContext> snapshot;
    synchronized (contexts) {
        snapshot = ImmutableList.copyOf(contexts.values());
    }
    snapshot.forEach(ctx -> ctx.initialCheckFuture.join());

    // If all endpoints are unhealthy, we will not have called setEndpoints even once, meaning listeners
    // aren't notified that we've finished an initial health check. We make sure to refresh endpoints once
    // on initialization to ensure this happens, even if the endpoints are currently empty.
    refreshEndpoints();
}
 
Example #18
Source File: Http1ConnectionReuseTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void returnToThePoolAfterRequestIsComplete() {
    final CompleteInterceptableFuture<Void> future = new CompleteInterceptableFuture<>();
    final HttpRequest httpRequest = httpRequest(future);

    final WebClient webClient = WebClient.of(server.uri(SessionProtocol.H1C));
    final AggregatedHttpResponse res = webClient.execute(httpRequest).aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.OK);
    assertThat(webClient.get("/").aggregate().join().status()).isSameAs(HttpStatus.OK);
    future.completeValue(null); // This will make the first connection return to the pool.
    assertThat(webClient.get("/").aggregate().join().status()).isSameAs(HttpStatus.OK);
    assertThat(remoteAddresses.get(0)).isNotSameAs(remoteAddresses.get(1));
    assertThat(remoteAddresses.get(0)).isSameAs(remoteAddresses.get(2));
}
 
Example #19
Source File: HttpClientRequestPathTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(value = SessionProtocol.class, mode = Mode.EXCLUDE, names = "PROXY")
void default_withScheme(SessionProtocol protocol) {
    final HttpRequest request = HttpRequest.of(HttpMethod.GET, server2.uri(protocol) + "/simple-client");
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        final WebClient client = WebClient.builder().factory(ClientFactory.insecure()).build();
        final HttpResponse response = client.execute(request);
        final ClientRequestContext ctx = captor.get();
        assertThat(ctx.sessionProtocol()).isEqualTo(protocol);
        assertThat(response.aggregate().join().status()).isEqualTo(OK);
    }
}
 
Example #20
Source File: ServerMaxConnectionAgeTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@CsvSource({ "H1C", "H2C" })
@ParameterizedTest
void shouldNotDisconnect(SessionProtocol protocol) throws InterruptedException {
    final WebClient client = newWebClient(serverKeepAlive.uri(protocol));

    for (int i = 0; i < 10; i++) {
        assertThat(client.get("/").aggregate().join().status()).isEqualTo(OK);
        assertThat(opened).hasValue(1);
        assertThat(closed).hasValue(0);
        Thread.sleep(100);
    }
}
 
Example #21
Source File: HttpClientSniTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testCustomAuthority() throws Exception {
    final WebClient client = WebClient.builder(SessionProtocol.HTTPS,
                                               Endpoint.of("a.com", httpsPort)
                                                       .withIpAddr("127.0.0.1"))
                                      .factory(clientFactory)
                                      .build();

    final AggregatedHttpResponse response = client.get("/").aggregate().get();

    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.contentUtf8()).isEqualTo("a.com: CN=a.com");
}
 
Example #22
Source File: BraveClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
public BraveClientIntegrationTest(SessionProtocol sessionProtocol) {
    this.sessionProtocol = sessionProtocol;

    if (sessionProtocol == SessionProtocol.H2C) {
        protocols = ImmutableList.of(Protocol.H2_PRIOR_KNOWLEDGE);
    } else {
        protocols = ImmutableList.of(Protocol.HTTP_1_1);
    }
}
 
Example #23
Source File: Server.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static String bossThreadName(ServerPort port) {
    final InetSocketAddress localAddr = port.localAddress();
    final String localHostName =
            localAddr.getAddress().isAnyLocalAddress() ? "*" : localAddr.getHostString();

    // e.g. 'armeria-boss-http-*:8080'
    //      'armeria-boss-http-127.0.0.1:8443'
    //      'armeria-boss-proxy+http+https-127.0.0.1:8443'
    final String protocolNames = port.protocols().stream()
                                     .map(SessionProtocol::uriText)
                                     .collect(Collectors.joining("+"));
    return "armeria-boss-" + protocolNames + '-' + localHostName + ':' + localAddr.getPort();
}
 
Example #24
Source File: Exceptions.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the specified exception if it is {@linkplain #isExpected(Throwable) unexpected}.
 */
public static void logIfUnexpected(Logger logger, Channel ch, @Nullable SessionProtocol protocol,
                                   String debugData, Throwable cause) {

    if (!logger.isWarnEnabled() || isExpected(cause)) {
        return;
    }

    logger.warn("{}[{}] Unexpected exception: {}",
                ch, protocolName(protocol), debugData, cause);
}
 
Example #25
Source File: HttpClientMaxConcurrentStreamTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionClosed(SessionProtocol protocol, InetSocketAddress remoteAddr,
                             InetSocketAddress localAddr, AttributeMap attrs) throws Exception {
    final ConnectionPoolListener connectionPoolListener =
            HttpClientMaxConcurrentStreamTest.this.connectionPoolListener;
    if (connectionPoolListener != null) {
        connectionPoolListener.connectionClosed(protocol, remoteAddr, localAddr, attrs);
    }
}
 
Example #26
Source File: HttpClientMaxConcurrentStreamTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void ensureCorrectPendingAcquisitionDurationBehavior() throws Exception {
    final Queue<ClientConnectionTimings> connectionTimings = new ConcurrentLinkedQueue<>();
    final WebClient client = WebClient.builder(server.uri(SessionProtocol.H2C))
                                      .factory(clientFactory)
                                      .decorator(connectionTimingsAccumulatingDecorator(connectionTimings))
                                      .build();
    final int sleepMillis = 300;
    connectionPoolListener = newConnectionPoolListener(() -> {
        try {
            Thread.sleep(sleepMillis);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }, () -> {});

    final int numConnections = MAX_NUM_CONNECTIONS;
    final int numRequests = MAX_CONCURRENT_STREAMS * numConnections;

    runInsideEventLoop(clientFactory.eventLoopGroup(), () -> {
        for (int i = 0; i < numRequests; i++) {
            client.get(PATH).aggregate();
        }
    });

    await().untilAsserted(() -> assertThat(responses).hasSize(numRequests));
    assertThat(connectionTimings.stream().filter(
            timings -> timings.pendingAcquisitionDurationNanos() > 0))
            .hasSize(numRequests - 1);

    // There should be at least one request with at least numConnections * pendingAcquisitionsDuration
    final Long maxPendingAcquisitionDurationNanos = connectionTimings.stream().mapToLong(
            ClientConnectionTimings::pendingAcquisitionDurationNanos).max().orElse(0L);
    assertThat(maxPendingAcquisitionDurationNanos)
            .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(sleepMillis * numConnections));
}
 
Example #27
Source File: ClientRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void protocol() {
    final ClientRequestContext ctx = ClientRequestContext.builder(HttpRequest.of(HttpMethod.GET, "/"))
                                                         .sessionProtocol(SessionProtocol.H2C)
                                                         .build();
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse();
    assertThat(ClientRequestContextAdapter.protocol(ctx.log().ensureComplete())).isEqualTo("h2c");
}
 
Example #28
Source File: SessionProtocolNegotiationCache.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the specified {@link Endpoint} is known to have no support for
 * the specified {@link SessionProtocol}.
 */
public static boolean isUnsupported(Endpoint endpointWithPort, SessionProtocol protocol) {
    requireNonNull(endpointWithPort, "endpointWithPort");
    checkArgument(endpointWithPort.hasPort(), "endpointWithPort must have a port.");
    // It's okay to create the key using endpointWithPort.host():
    // - If the endpoint has an IP address without host name, the IP address is used in the key to store
    //   and retrieve the value.
    // - If the endpoint has an IP address with host name, the host name is used in the key to store
    //   and retrieve the value.
    // - If the endpoint has host name only, the host name is used in the key to store and retrieve
    //   the value.
    final String key = key(endpointWithPort.host(), endpointWithPort.port());
    return isUnsupported(key, protocol);
}
 
Example #29
Source File: PortUnificationServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(UniqueProtocolsProvider.class)
void test(SessionProtocol protocol) throws Exception {
    final WebClient client = WebClient.builder(server.uri(protocol))
                                      .factory(ClientFactory.insecure())
                                      .build();
    final AggregatedHttpResponse response = client.execute(HttpRequest.of(HttpMethod.GET, "/"))
                                                  .aggregate().join();
    assertThat(response.contentUtf8()).isEqualTo(protocol.name());
}
 
Example #30
Source File: HttpClientDelegate.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void acquireConnectionAndExecute(ClientRequestContext ctx, Endpoint endpointWithPort,
                                         String ipAddr, HttpRequest req, DecodedHttpResponse res,
                                         ClientConnectionTimingsBuilder timingsBuilder) {
    final EventLoop eventLoop = ctx.eventLoop();
    if (!eventLoop.inEventLoop()) {
        eventLoop.execute(() -> acquireConnectionAndExecute(ctx, endpointWithPort, ipAddr,
                                                            req, res, timingsBuilder));
        return;
    }

    final String host = extractHost(ctx, req, endpointWithPort);
    final int port = endpointWithPort.port();
    final SessionProtocol protocol = ctx.sessionProtocol();
    final HttpChannelPool pool = factory.pool(ctx.eventLoop());

    final PoolKey key = new PoolKey(host, ipAddr, port);
    final PooledChannel pooledChannel = pool.acquireNow(protocol, key);
    if (pooledChannel != null) {
        logSession(ctx, pooledChannel, null);
        doExecute(pooledChannel, ctx, req, res);
    } else {
        pool.acquireLater(protocol, key, timingsBuilder).handle((newPooledChannel, cause) -> {
            logSession(ctx, newPooledChannel, timingsBuilder.build());
            if (cause == null) {
                doExecute(newPooledChannel, ctx, req, res);
            } else {
                final UnprocessedRequestException wrapped = UnprocessedRequestException.of(cause);
                handleEarlyRequestException(ctx, req, wrapped);
                res.close(wrapped);
            }
            return null;
        });
    }
}