com.linecorp.armeria.common.RequestHeadersBuilder Java Examples

The following examples show how to use com.linecorp.armeria.common.RequestHeadersBuilder. 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: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private RequestHeadersBuilder headersBuilder(HttpMethod method, String path) {
    final RequestHeadersBuilder builder = RequestHeaders.builder();
    builder.method(method)
           .path(path)
           .set(HttpHeaderNames.AUTHORIZATION, authorization)
           .setObject(HttpHeaderNames.ACCEPT, MediaType.JSON);

    switch (method) {
        case POST:
        case PUT:
            builder.contentType(MediaType.JSON_UTF_8);
            break;
        case PATCH:
            builder.contentType(JSON_PATCH_UTF8);
            break;
    }

    return builder;
}
 
Example #2
Source File: EurekaEndpointGroup.java    From armeria with Apache License 2.0 6 votes vote down vote up
EurekaEndpointGroup(EndpointSelectionStrategy selectionStrategy,
                    WebClient webClient, long registryFetchIntervalSeconds, @Nullable String appName,
                    @Nullable String instanceId, @Nullable String vipAddress,
                    @Nullable String secureVipAddress, @Nullable List<String> regions) {
    super(selectionStrategy);
    this.webClient = PooledWebClient.of(webClient);
    this.registryFetchIntervalSeconds = registryFetchIntervalSeconds;

    final RequestHeadersBuilder headersBuilder = RequestHeaders.builder();
    headersBuilder.method(HttpMethod.GET);
    headersBuilder.add(HttpHeaderNames.ACCEPT, MediaTypeNames.JSON_UTF_8);
    responseConverter = responseConverter(headersBuilder, appName, instanceId,
                                          vipAddress, secureVipAddress, regions);
    requestHeaders = headersBuilder.build();

    webClient.options().factory().whenClosed().thenRun(this::closeAsync);
    fetchRegistry();
}
 
Example #3
Source File: RouteDecoratingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@CsvSource({
        "/,                       headers-decorator,  headers-decorator",
        "/,                       headers-service,    headers-service",
        "/?dest=params-decorator, ,                   params-decorator",
        "/?dest=params-service,   ,                   params-service"
})
void decoratorShouldWorkWithMatchingHeadersAndParams(String path,
                                                     @Nullable String destHeader,
                                                     String result) {
    final WebClient client = WebClient.of(headersAndParamsExpectingServer.httpUri());
    final RequestHeadersBuilder builder = RequestHeaders.builder().method(HttpMethod.GET).path(path);
    if (!Strings.isNullOrEmpty(destHeader)) {
        builder.add("dest", destHeader);
    }
    assertThat(client.execute(builder.build()).aggregate().join().contentUtf8()).isEqualTo(result);
}
 
Example #4
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri,
                                   RequestHeadersBuilder out) {
    final String value = uri.getScheme();
    if (value != null) {
        out.add(HttpHeaderNames.SCHEME, value);
        return;
    }

    // Consume the Scheme extension header if present
    final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
    if (cValue != null) {
        out.add(HttpHeaderNames.SCHEME, cValue.toString());
    } else {
        out.add(HttpHeaderNames.SCHEME, "unknown");
    }
}
 
Example #5
Source File: ArmeriaClientCall.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void prepareHeaders(Compressor compressor, Metadata metadata) {
    final RequestHeadersBuilder newHeaders = req.headers().toBuilder();
    if (compressor != Identity.NONE) {
        newHeaders.set(GrpcHeaderNames.GRPC_ENCODING, compressor.getMessageEncoding());
    }

    if (!advertisedEncodingsHeader.isEmpty()) {
        newHeaders.add(GrpcHeaderNames.GRPC_ACCEPT_ENCODING, advertisedEncodingsHeader);
    }

    newHeaders.add(GrpcHeaderNames.GRPC_TIMEOUT,
                   TimeoutHeaderUtil.toHeaderValue(
                           TimeUnit.MILLISECONDS.toNanos(ctx.responseTimeoutMillis())));

    MetadataUtil.fillHeaders(metadata, newHeaders);

    final HttpRequest newReq = req.withHeaders(newHeaders);
    ctx.updateRequest(newReq);
}
 
Example #6
Source File: DefaultClientRequestContext.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void autoFillSchemeAndAuthority() {
    final HttpRequest req = request();
    if (req == null) {
        return;
    }

    final RequestHeaders headers = req.headers();
    final String authority = endpoint != null ? endpoint.authority() : "UNKNOWN";
    if (headers.scheme() == null || !authority.equals(headers.authority())) {
        final RequestHeadersBuilder headersBuilder =
                headers.toBuilder()
                       .removeAndThen(HttpHeaderNames.HOST)
                       .authority(authority)
                       .scheme(sessionProtocol());
        unsafeUpdateRequest(req.withHeaders(headersBuilder));
    }
}
 
Example #7
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}.
 */
public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers,
                                                     boolean endOfStream, String scheme,
                                                     ServerConfig cfg) {
    final RequestHeadersBuilder builder = RequestHeaders.builder();
    toArmeria(builder, headers, endOfStream);
    // A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3
    if (!builder.contains(HttpHeaderNames.SCHEME)) {
        builder.add(HttpHeaderNames.SCHEME, scheme);
    }
    if (!builder.contains(HttpHeaderNames.AUTHORITY)) {
        final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
        final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
        builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
    }
    return builder.build();
}
 
Example #8
Source File: HttpHealthChecker.java    From armeria with Apache License 2.0 6 votes vote down vote up
private synchronized void check() {
    if (closeable.isClosing()) {
        return;
    }

    final RequestHeaders headers;
    final RequestHeadersBuilder builder =
            RequestHeaders.builder(useGet ? HttpMethod.GET : HttpMethod.HEAD, path)
                          .add(HttpHeaderNames.AUTHORITY, authority);
    if (maxLongPollingSeconds > 0) {
        headers = builder.add(HttpHeaderNames.IF_NONE_MATCH, wasHealthy ? "\"healthy\"" : "\"unhealthy\"")
                         .add(HttpHeaderNames.PREFER, "wait=" + maxLongPollingSeconds)
                         .build();
    } else {
        headers = builder.build();
    }

    try (ClientRequestContextCaptor reqCtxCaptor = Clients.newContextCaptor()) {
        lastResponse = webClient.execute(headers);
        final ClientRequestContext reqCtx = reqCtxCaptor.get();
        lastResponse.subscribeWithPooledObjects(new HealthCheckResponseSubscriber(reqCtx, lastResponse),
                                                reqCtx.eventLoop());
    }
}
 
Example #9
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private <T> CompletableFuture<T> watch(Revision lastKnownRevision, long timeoutMillis,
                                       String path, QueryType queryType,
                                       BiFunction<AggregatedHttpResponse, QueryType, T> func) {
    final RequestHeadersBuilder builder = headersBuilder(HttpMethod.GET, path);
    builder.set(HttpHeaderNames.IF_NONE_MATCH, lastKnownRevision.text())
           .set(HttpHeaderNames.PREFER, "wait=" + LongMath.saturatedAdd(timeoutMillis, 999) / 1000L);

    try (SafeCloseable ignored = Clients.withContextCustomizer(ctx -> {
        final long responseTimeoutMillis = ctx.responseTimeoutMillis();
        final long adjustmentMillis = WatchTimeout.availableTimeout(timeoutMillis, responseTimeoutMillis);
        if (responseTimeoutMillis > 0) {
            ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, adjustmentMillis);
        } else {
            ctx.setResponseTimeoutMillis(adjustmentMillis);
        }
    })) {
        return client.execute(builder.build()).aggregate()
                     .handle((res, cause) -> {
                         if (cause == null) {
                             return func.apply(res, queryType);
                         }

                         if ((cause instanceof ClosedStreamException) &&
                             client.options().factory().isClosing()) {
                             // A user closed the client factory while watching.
                             return null;
                         }

                         return Exceptions.throwUnsafely(cause);
                     });
    }
}
 
Example #10
Source File: WebClientBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void authorityHeader() {
    final String path = "/echo-path?foo=bar";
    final RequestHeadersBuilder requestHeadersBuilder =
            RequestHeaders.builder()
                          .authority("localhost:" + server.httpPort())
                          .scheme("h2c")
                          .add("param1", "val1")
                          .path(path);

    final AggregatedHttpRequest request = AggregatedHttpRequest.of(
            requestHeadersBuilder.method(HttpMethod.GET).build());
    final HttpResponse response = WebClient.of().execute(request);
    assertThat(response.aggregate().join().contentUtf8()).isEqualTo(path);
}
 
Example #11
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
 * The following headers are only used if they can not be found in the {@code HOST} header or the
 * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
 * <ul>
 * <li>{@link ExtensionHeaderNames#SCHEME}</li>
 * </ul>
 * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
 */
public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in,
                                       ServerConfig cfg) throws URISyntaxException {
    final URI requestTargetUri = toUri(in);

    final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
    final RequestHeadersBuilder out = RequestHeaders.builder();
    out.sizeHint(inHeaders.size());
    out.add(HttpHeaderNames.METHOD, in.method().name());
    out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri));

    addHttp2Scheme(inHeaders, requestTargetUri, out);

    // Add the HTTP headers which have not been consumed above
    toArmeria(inHeaders, out);
    if (!out.contains(HttpHeaderNames.HOST)) {
        // The client violates the spec that the request headers must contain a Host header.
        // But we just add Host header to allow the request.
        // https://tools.ietf.org/html/rfc7230#section-5.4
        if (isOriginForm(requestTargetUri) || isAsteriskForm(requestTargetUri)) {
            // requestTargetUri does not contain authority information.
            final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
            final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
            out.add(HttpHeaderNames.HOST, defaultHostname + ':' + port);
        } else {
            out.add(HttpHeaderNames.HOST, stripUserInfo(requestTargetUri.getAuthority()));
        }
    }
    return out.build();
}
 
Example #12
Source File: HttpHeadersUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
public static RequestHeaders mergeRequestHeaders(RequestHeaders headers,
                                                 HttpHeaders additionalHeaders) {
    if (additionalHeaders.isEmpty()) {
        return headers;
    }

    final RequestHeadersBuilder builder = headers.toBuilder();
    for (AsciiString name : additionalHeaders.names()) {
        if (!ADDITIONAL_REQUEST_HEADER_BLACKLIST.contains(name)) {
            builder.remove(name);
            additionalHeaders.forEachValue(name, value -> builder.add(name, value));
        }
    }
    return builder.build();
}
 
Example #13
Source File: EurekaEndpointGroup.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static Function<byte[], List<Endpoint>> responseConverter(
        RequestHeadersBuilder builder, @Nullable String appName, @Nullable String instanceId,
        @Nullable String vipAddress, @Nullable String secureVipAddress, @Nullable List<String> regions) {
    if (regions != null) {
        final Predicate<InstanceInfo> filter;
        final String path;
        boolean secureVip = false;
        if (vipAddress != null) {
            path = VIPS + vipAddress;
            filter = instanceInfo -> vipAddress.equals(instanceInfo.getVipAddress());
        } else if (secureVipAddress != null) {
            secureVip = true;
            path = SVIPS + secureVipAddress;
            filter = instanceInfo -> secureVipAddress.equals(instanceInfo.getSecureVipAddress());
        } else {
            // If regions is specified, we fetch all registry information and filter what we need because
            // some of the REST endpoints do not support regions query parameter.
            path = APPS;
            if (appName == null && instanceId == null) {
                filter = allInstances;
            } else if (appName != null && instanceId != null) {
                filter = instanceInfo -> appName.equals(instanceInfo.getAppName()) &&
                                         instanceId.equals(instanceInfo.getInstanceId());
            } else if (appName != null) {
                filter = instanceInfo -> appName.equals(instanceInfo.getAppName());
            } else {
                filter = instanceInfo -> instanceId.equals(instanceInfo.getInstanceId());
            }
        }
        final StringJoiner joiner = new StringJoiner(",");
        regions.forEach(joiner::add);
        final QueryParams queryParams = QueryParams.of("regions", joiner.toString());
        builder.path(path + '?' + queryParams.toQueryString());
        return new ApplicationsConverter(filter, secureVip);
    }

    if (vipAddress != null) {
        builder.path(VIPS + vipAddress);
        return new ApplicationsConverter();
    }

    if (secureVipAddress != null) {
        builder.path(SVIPS + secureVipAddress);
        return new ApplicationsConverter(allInstances, true);
    }

    if (appName == null && instanceId == null) {
        builder.path(APPS);
        return new ApplicationsConverter();
    }

    if (appName != null && instanceId != null) {
        builder.path(APPS + '/' + appName + '/' + instanceId);
        return new InstanceInfoConverter();
    }

    if (appName != null) {
        builder.path(APPS + '/' + appName);
        return new ApplicationConverter();
    }

    // instanceId is not null at this point.
    builder.path(INSTANCES + instanceId);
    return new InstanceInfoConverter();
}
 
Example #14
Source File: RetryingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
private void doExecute0(ClientRequestContext ctx, HttpRequestDuplicator rootReqDuplicator,
                        HttpRequest originalReq, HttpResponse returnedRes,
                        CompletableFuture<HttpResponse> future) {
    final int totalAttempts = getTotalAttempts(ctx);
    final boolean initialAttempt = totalAttempts <= 1;
    // The request or response has been aborted by the client before it receives a response,
    // so stop retrying.
    if (originalReq.whenComplete().isCompletedExceptionally()) {
        originalReq.whenComplete().handle((unused, cause) -> {
            handleException(ctx, rootReqDuplicator, future, cause, initialAttempt);
            return null;
        });
        return;
    }
    if (returnedRes.isComplete()) {
        returnedRes.whenComplete().handle((result, cause) -> {
            final Throwable abortCause = firstNonNull(cause, AbortedStreamException.get());
            handleException(ctx, rootReqDuplicator, future, abortCause, initialAttempt);
            return null;
        });
        return;
    }

    if (!setResponseTimeout(ctx)) {
        handleException(ctx, rootReqDuplicator, future, ResponseTimeoutException.get(), initialAttempt);
        return;
    }

    final HttpRequest duplicateReq;
    if (initialAttempt) {
        duplicateReq = rootReqDuplicator.duplicate();
    } else {
        final RequestHeadersBuilder newHeaders = originalReq.headers().toBuilder();
        newHeaders.setInt(ARMERIA_RETRY_COUNT, totalAttempts - 1);
        duplicateReq = rootReqDuplicator.duplicate(newHeaders.build());
    }

    final ClientRequestContext derivedCtx = newDerivedContext(ctx, duplicateReq, ctx.rpcRequest(),
                                                              initialAttempt);
    ctx.logBuilder().addChild(derivedCtx.log());

    final HttpResponse response = executeWithFallback(unwrap(), derivedCtx,
                                                      (context, cause) -> HttpResponse.ofFailure(cause));

    if (requiresResponseTrailers) {
        response.aggregate().handle((aggregated, cause) -> {
            handleResponse(ctx, rootReqDuplicator, originalReq, returnedRes, future, derivedCtx,
                           cause != null ? HttpResponse.ofFailure(cause) : aggregated.toHttpResponse());
            return null;
        });
    } else {
        handleResponse(ctx, rootReqDuplicator, originalReq, returnedRes, future, derivedCtx, response);
    }
}
 
Example #15
Source File: ArmeriaCallFactory.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static HttpResponse doCall(ArmeriaCallFactory callFactory, Request request) {
    final HttpUrl httpUrl = request.url();
    final WebClient webClient = callFactory.getWebClient(httpUrl);
    final String absolutePathRef;
    if (httpUrl.encodedQuery() == null) {
        absolutePathRef = httpUrl.encodedPath();
    } else {
        absolutePathRef = httpUrl.encodedPath() + '?' + httpUrl.encodedQuery();
    }

    final RequestHeadersBuilder headers = RequestHeaders.builder(HttpMethod.valueOf(request.method()),
                                                                 absolutePathRef);
    final Headers requestHeaders = request.headers();
    final int numHeaders = requestHeaders.size();
    for (int i = 0; i < numHeaders; i++) {
        headers.add(HttpHeaderNames.of(requestHeaders.name(i)),
                    requestHeaders.value(i));
    }

    final RequestBody body = request.body();
    final Invocation invocation = request.tag(Invocation.class);
    if (body == null) {
        // Without a body.
        try (SafeCloseable ignored = withContextCustomizer(
                ctx -> InvocationUtil.setInvocation(ctx, invocation))) {
            return webClient.execute(headers.build());
        }
    }

    // With a body.
    final MediaType contentType = body.contentType();
    if (contentType != null) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType.toString());
    }

    try (Buffer contentBuffer = new Buffer()) {
        body.writeTo(contentBuffer);

        try (SafeCloseable ignored = withContextCustomizer(
                ctx -> InvocationUtil.setInvocation(ctx, invocation))) {
            return webClient.execute(headers.build(), contentBuffer.readByteArray());
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(
                "Failed to convert RequestBody to HttpData. " + request.method(), e);
    }
}
 
Example #16
Source File: UnframedGrpcService.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse serve(
        PooledHttpService delegate, ServiceRequestContext ctx, PooledHttpRequest req) throws Exception {
    final RequestHeaders clientHeaders = req.headers();
    final MediaType contentType = clientHeaders.contentType();
    if (contentType == null) {
        // All gRPC requests, whether framed or non-framed, must have content-type. If it's not sent, let
        // the delegate return its usual error message.
        return delegate.serve(ctx, req);
    }

    for (SerializationFormat format : GrpcSerializationFormats.values()) {
        if (format.isAccepted(contentType)) {
            // Framed request, so just delegate.
            return delegate.serve(ctx, req);
        }
    }

    final String methodName = GrpcRequestUtil.determineMethod(ctx);
    final MethodDescriptor<?, ?> method = methodName != null ? methodsByName.get(methodName) : null;
    if (method == null) {
        // Unknown method, let the delegate return a usual error.
        return delegate.serve(ctx, req);
    }

    if (method.getType() != MethodType.UNARY) {
        return HttpResponse.of(HttpStatus.BAD_REQUEST,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "Only unary methods can be used with non-framed requests.");
    }

    final RequestHeadersBuilder grpcHeaders = clientHeaders.toBuilder();

    final MediaType framedContentType;
    if (contentType.is(MediaType.PROTOBUF)) {
        framedContentType = GrpcSerializationFormats.PROTO.mediaType();
    } else if (contentType.is(MediaType.JSON_UTF_8)) {
        framedContentType = GrpcSerializationFormats.JSON.mediaType();
    } else {
        return HttpResponse.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "Unsupported media type. Only application/protobuf is supported.");
    }
    grpcHeaders.contentType(framedContentType);

    if (grpcHeaders.get(GrpcHeaderNames.GRPC_ENCODING) != null) {
        return HttpResponse.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "gRPC encoding is not supported for non-framed requests.");
    }

    // All clients support no encoding, and we don't support gRPC encoding for non-framed requests, so just
    // clear the header if it's present.
    grpcHeaders.remove(GrpcHeaderNames.GRPC_ACCEPT_ENCODING);

    ctx.logBuilder().defer(RequestLogProperty.REQUEST_CONTENT,
                           RequestLogProperty.RESPONSE_CONTENT);

    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
    req.aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc()).handle((clientRequest, t) -> {
        if (t != null) {
            responseFuture.completeExceptionally(t);
        } else {
            frameAndServe(ctx, grpcHeaders.build(), clientRequest, responseFuture);
        }
        return null;
    });
    return HttpResponse.from(responseFuture);
}
 
Example #17
Source File: BraveClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception {
    final RequestHeadersBuilder newHeaders = req.headers().toBuilder();
    final HttpClientRequest braveReq = ClientRequestContextAdapter.asHttpClientRequest(ctx, newHeaders);
    final Span span = handler.handleSend(braveReq);
    req = req.withHeaders(newHeaders);
    ctx.updateRequest(req);

    // For no-op spans, we only need to inject into headers and don't set any other attributes.
    if (span.isNoop()) {
        try (SpanInScope ignored = tracer.withSpanInScope(span)) {
            return unwrap().execute(ctx, req);
        }
    }

    ctx.log().whenComplete().thenAccept(log -> {
        span.start(log.requestStartTimeMicros());

        final Long wireSendTimeNanos = log.requestFirstBytesTransferredTimeNanos();
        if (wireSendTimeNanos != null) {
            SpanTags.logWireSend(span, wireSendTimeNanos, log);
        } else {
            // The request might have failed even before it's sent,
            // e.g. validation failure, connection error.
        }

        final Long wireReceiveTimeNanos = log.responseFirstBytesTransferredTimeNanos();
        if (wireReceiveTimeNanos != null) {
            SpanTags.logWireReceive(span, wireReceiveTimeNanos, log);
        } else {
            // If the client timed-out the request, we will have never received any response data at all.
        }

        SpanTags.updateRemoteEndpoint(span, ctx);

        final ClientConnectionTimings timings = log.connectionTimings();
        if (timings != null) {
            logTiming(span, "connection-acquire.start", "connection-acquire.end",
                      timings.connectionAcquisitionStartTimeMicros(),
                      timings.connectionAcquisitionDurationNanos());
            if (timings.dnsResolutionDurationNanos() != -1) {
                logTiming(span, "dns-resolve.start", "dns-resolve.end",
                          timings.dnsResolutionStartTimeMicros(),
                          timings.dnsResolutionDurationNanos());
            }
            if (timings.socketConnectDurationNanos() != -1) {
                logTiming(span, "socket-connect.start", "socket-connect.end",
                          timings.socketConnectStartTimeMicros(),
                          timings.socketConnectDurationNanos());
            }
            if (timings.pendingAcquisitionDurationNanos() != -1) {
                logTiming(span, "connection-reuse.start", "connection-reuse.end",
                          timings.pendingAcquisitionStartTimeMicros(),
                          timings.pendingAcquisitionDurationNanos());
            }
        }

        final HttpClientResponse braveRes = ClientRequestContextAdapter.asHttpClientResponse(log, braveReq);
        handler.handleReceive(braveRes, span);
    });

    try (SpanInScope ignored = tracer.withSpanInScope(span)) {
        return unwrap().execute(ctx, req);
    }
}
 
Example #18
Source File: ClientRequestContextAdapter.java    From armeria with Apache License 2.0 4 votes vote down vote up
HttpClientRequest(ClientRequestContext ctx, RequestHeadersBuilder headersBuilder) {
    this.ctx = ctx;
    this.headersBuilder = headersBuilder;
}
 
Example #19
Source File: ClientRequestContextAdapter.java    From armeria with Apache License 2.0 4 votes vote down vote up
static brave.http.HttpClientRequest asHttpClientRequest(ClientRequestContext ctx,
    RequestHeadersBuilder headersBuilder) {
    return new HttpClientRequest(ctx, headersBuilder);
}
 
Example #20
Source File: AWSSignatureVersion4.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
AggregatedHttpRequest sign(ClientRequestContext ctx, AggregatedHttpRequest req) {
  AWSCredentials credentials = this.credentials.get();
  if (credentials == null) throw new NullPointerException("credentials == null");

  String timestamp = iso8601.get().format(new Date());
  String yyyyMMdd = timestamp.substring(0, 8);
  String credentialScope = credentialScope(yyyyMMdd, region);

  RequestHeadersBuilder builder = req.headers().toBuilder()
      .set(X_AMZ_DATE, timestamp);

  // TODO: Test this, it requires significant mocking since these ports can't normally be used by
  // a unit test.
  String authority = req.authority();
  int colonIndex = -1;
  if (authority != null) {
    colonIndex = authority.indexOf(':');
  }
  if (colonIndex != -1) {
    if (ctx.sessionProtocol().isTls() && authority.endsWith(":443") ||
        !ctx.sessionProtocol().isTls() && authority.endsWith(":80")) {
      // AWS requests must not include standard ports in host header.
      builder.authority(authority.substring(0, colonIndex));
    }
  }

  if (credentials.sessionToken != null) {
    builder.set(X_AMZ_SECURITY_TOKEN, credentials.sessionToken);
  }

  String signedHeaders = credentials.sessionToken == null ? HOST_DATE : HOST_DATE_TOKEN;
  ByteBuf canonicalString = ctx.alloc().heapBuffer();
  ByteBuf toSign = ctx.alloc().heapBuffer();
  try {
    writeCanonicalString(ctx, builder.build(), req.content(), canonicalString);
    writeToSign(timestamp, credentialScope, canonicalString, toSign);

    // TODO: this key is invalid when the secret key or the date change. both are very infrequent
    byte[] signatureKey = signatureKey(credentials.secretKey, yyyyMMdd);
    String signature = ByteBufUtil.hexDump(hmacSha256(signatureKey, toSign.nioBuffer()));

    String authorization = "AWS4-HMAC-SHA256 Credential="
        + credentials.accessKey
        + '/'
        + credentialScope
        + ", SignedHeaders="
        + signedHeaders
        + ", Signature="
        + signature;

    return AggregatedHttpRequest.of(
        builder.add(HttpHeaderNames.AUTHORIZATION, authorization).build(),
        req.content(),
        req.trailers());
  } finally {
    canonicalString.release();
    toSign.release();
  }
}