Search in sources :

Example 91 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class SimulationTest method one_big_spike.

/**
 * This simulates an alta client, which might load up some keys and then lookup each key in order to build a big
 * response for the user. The goal is 100% client-perceived success here, because building up half the response
 * is no good.
 */
@SimulationCase
public void one_big_spike(Strategy strategy) {
    int capacity = 100;
    servers = servers(SimulationServer.builder().serverName("node1").simulation(simulation).handler(h -> h.respond200UntilCapacity(429, capacity).responseTime(Duration.ofMillis(150))).build(), SimulationServer.builder().serverName("node2").simulation(simulation).handler(h -> h.respond200UntilCapacity(429, capacity).responseTime(Duration.ofMillis(150))).build());
    st = strategy;
    result = Benchmark.builder().simulation(simulation).requestsPerSecond(// fire off a ton of requests very quickly
    30_000).numRequests(1000).client(strategy.getChannel(simulation, servers)).abortAfter(Duration.ofSeconds(10)).run();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Inherited(java.lang.annotation.Inherited) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) AfterAll(org.junit.jupiter.api.AfterAll) Duration(java.time.Duration) Map(java.util.Map) Tracers(com.palantir.tracing.Tracers) Path(java.nio.file.Path) ExecutionMode(org.junit.jupiter.api.parallel.ExecutionMode) StandardOpenOption(java.nio.file.StandardOpenOption) Channel(com.palantir.dialogue.Channel) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) TestResponse(com.palantir.dialogue.TestResponse) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Response(com.palantir.dialogue.Response) IntStream(java.util.stream.IntStream) Tracer(com.palantir.tracing.Tracer) Stopwatch(com.google.common.base.Stopwatch) EnumSource(org.junit.jupiter.params.provider.EnumSource) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Retention(java.lang.annotation.Retention) ArrayList(java.util.ArrayList) Meter(com.codahale.metrics.Meter) ScheduledRequest(com.palantir.dialogue.core.Benchmark.ScheduledRequest) Suppliers(com.google.common.base.Suppliers) Endpoint(com.palantir.dialogue.Endpoint) DEFAULT_ENDPOINT(com.palantir.dialogue.core.Benchmark.DEFAULT_ENDPOINT) Logger(org.slf4j.Logger) Files(java.nio.file.Files) XYChart(org.knowm.xchart.XYChart) Observability(com.palantir.tracing.Observability) IOException(java.io.IOException) HttpMethod(com.palantir.dialogue.HttpMethod) TimeUnit(java.util.concurrent.TimeUnit) EndpointChannel(com.palantir.dialogue.EndpointChannel) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) Comparator(java.util.Comparator) Execution(org.junit.jupiter.api.parallel.Execution) RetentionPolicy(java.lang.annotation.RetentionPolicy) Endpoint(com.palantir.dialogue.Endpoint)

Example 92 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class SimulationTest method server_side_rate_limits.

@SimulationCase
void server_side_rate_limits(Strategy strategy) {
    double totalRateLimit = .1;
    int numServers = 4;
    int numClients = 2;
    double perServerRateLimit = totalRateLimit / numServers;
    servers = servers(IntStream.range(0, numServers).mapToObj(i -> {
        Meter requestRate = new Meter(simulation.codahaleClock());
        Function<SimulationServer, Response> responseFunc = _s -> {
            if (requestRate.getOneMinuteRate() < perServerRateLimit) {
                requestRate.mark();
                return new TestResponse().code(200);
            } else {
                return new TestResponse().code(429);
            }
        };
        return SimulationServer.builder().serverName("node" + i).simulation(simulation).handler(h -> h.response(responseFunc).responseTime(Duration.ofSeconds(200))).build();
    }).toArray(SimulationServer[]::new));
    st = strategy;
    result = Benchmark.builder().simulation(simulation).requestsPerSecond(totalRateLimit).sendUntil(Duration.ofMinutes(25_000)).clients(numClients, _i -> strategy.getChannel(simulation, servers)).abortAfter(Duration.ofHours(1_000)).run();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Inherited(java.lang.annotation.Inherited) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) AfterAll(org.junit.jupiter.api.AfterAll) Duration(java.time.Duration) Map(java.util.Map) Tracers(com.palantir.tracing.Tracers) Path(java.nio.file.Path) ExecutionMode(org.junit.jupiter.api.parallel.ExecutionMode) StandardOpenOption(java.nio.file.StandardOpenOption) Channel(com.palantir.dialogue.Channel) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) TestResponse(com.palantir.dialogue.TestResponse) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Response(com.palantir.dialogue.Response) IntStream(java.util.stream.IntStream) Tracer(com.palantir.tracing.Tracer) Stopwatch(com.google.common.base.Stopwatch) EnumSource(org.junit.jupiter.params.provider.EnumSource) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Retention(java.lang.annotation.Retention) ArrayList(java.util.ArrayList) Meter(com.codahale.metrics.Meter) ScheduledRequest(com.palantir.dialogue.core.Benchmark.ScheduledRequest) Suppliers(com.google.common.base.Suppliers) Endpoint(com.palantir.dialogue.Endpoint) DEFAULT_ENDPOINT(com.palantir.dialogue.core.Benchmark.DEFAULT_ENDPOINT) Logger(org.slf4j.Logger) Files(java.nio.file.Files) XYChart(org.knowm.xchart.XYChart) Observability(com.palantir.tracing.Observability) IOException(java.io.IOException) HttpMethod(com.palantir.dialogue.HttpMethod) TimeUnit(java.util.concurrent.TimeUnit) EndpointChannel(com.palantir.dialogue.EndpointChannel) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) Comparator(java.util.Comparator) Execution(org.junit.jupiter.api.parallel.Execution) RetentionPolicy(java.lang.annotation.RetentionPolicy) Function(java.util.function.Function) Meter(com.codahale.metrics.Meter) TestResponse(com.palantir.dialogue.TestResponse) Endpoint(com.palantir.dialogue.Endpoint)

Example 93 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class Benchmark method schedule.

@SuppressWarnings({ "FutureReturnValueIgnored", "CheckReturnValue" })
public ListenableFuture<BenchmarkResult> schedule() {
    long[] requestsStarted = { 0 };
    long[] responsesReceived = { 0 };
    Map<String, Integer> statusCodes = new TreeMap<>();
    Stopwatch scheduling = Stopwatch.createStarted();
    benchmarkFinished.getFuture().addListener(simulation.metricsReporter()::report, DialogueFutures.safeDirectExecutor());
    FutureCallback<Response> accumulateStatusCodes = new FutureCallback<Response>() {

        @Override
        public void onSuccess(Response response) {
            // just being a good citizen
            response.close();
            statusCodes.compute(Integer.toString(response.code()), (_c, num) -> num == null ? 1 : num + 1);
        }

        @Override
        public void onFailure(Throwable throwable) {
            statusCodes.compute(throwable.getMessage(), (_c, num) -> num == null ? 1 : num + 1);
        }
    };
    requestStream.forEach(req -> {
        log.debug("Scheduling {}", req.number());
        simulation.scheduler().schedule(() -> {
            log.debug("time={} starting num={} {}", simulation.clock().read(), req.number(), req);
            try {
                ListenableFuture<Response> future = req.endpointChannel().execute(req.request());
                requestsStarted[0] += 1;
                Futures.addCallback(future, accumulateStatusCodes, DialogueFutures.safeDirectExecutor());
                future.addListener(() -> {
                    responsesReceived[0] += 1;
                    benchmarkFinished.update(Duration.ofNanos(simulation.clock().read()), requestsStarted[0], responsesReceived[0]);
                }, DialogueFutures.safeDirectExecutor());
            } catch (RuntimeException e) {
                log.error("Channels shouldn't throw", e);
            }
        }, req.sendTimeNanos() - simulation.clock().read(), TimeUnit.NANOSECONDS);
        simulation.runClockTo(Optional.of(Duration.ofNanos(req.sendTimeNanos())));
    });
    long ms = scheduling.elapsed(TimeUnit.MILLISECONDS);
    log.warn("Fired off all requests ({} ms, {}req/sec)", ms, (1000 * requestsStarted[0]) / ms);
    return Futures.transform(benchmarkFinished.getFuture(), _v -> {
        long numGlobalResponses = MetricNames.globalResponses(simulation.taggedMetrics()).getCount();
        long leaked = numGlobalResponses - MetricNames.responseClose(simulation.taggedMetrics()).getCount();
        Map<String, Snapshot> perEndpointHistograms = KeyedStream.of(endpointChannels).mapKeys(NamedEndpointChannel::name).map(namedEndpointChannel -> namedEndpointChannel.channel().perEndpointChannelTimer().getSnapshot()).collectToMap();
        return ImmutableBenchmarkResult.builder().clientHistogram(MetricNames.clientGlobalResponseTimer(simulation.taggedMetrics()).getSnapshot()).endTime(Duration.ofNanos(simulation.clock().read())).statusCodes(statusCodes).successPercentage(Math.round(statusCodes.getOrDefault("200", 0) * 1000d / requestsStarted[0]) / 10d).numSent(requestsStarted[0]).numReceived(responsesReceived[0]).numGlobalResponses(numGlobalResponses).responsesLeaked(leaked).perEndpointHistograms(perEndpointHistograms).build();
    }, DialogueFutures.safeDirectExecutor());
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Stopwatch(com.google.common.base.Stopwatch) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) SettableFuture(com.google.common.util.concurrent.SettableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) DialogueFutures(com.palantir.dialogue.futures.DialogueFutures) SafeArg(com.palantir.logsafe.SafeArg) Value(org.immutables.value.Value) Duration(java.time.Duration) Map(java.util.Map) DefaultConjureRuntime(com.palantir.conjure.java.dialogue.serde.DefaultConjureRuntime) Endpoint(com.palantir.dialogue.Endpoint) Request(com.palantir.dialogue.Request) IntSupplier(java.util.function.IntSupplier) IntFunction(java.util.function.IntFunction) LongStream(java.util.stream.LongStream) Logger(org.slf4j.Logger) KeyedStream(com.palantir.common.streams.KeyedStream) Clients(com.palantir.dialogue.Clients) Streams(com.google.common.collect.Streams) Channel(com.palantir.dialogue.Channel) HttpMethod(com.palantir.dialogue.HttpMethod) Collectors(java.util.stream.Collectors) Snapshot(com.codahale.metrics.Snapshot) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) EndpointChannel(com.palantir.dialogue.EndpointChannel) List(java.util.List) Stream(java.util.stream.Stream) TreeMap(java.util.TreeMap) Optional(java.util.Optional) BaseStream(java.util.stream.BaseStream) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Response(com.palantir.dialogue.Response) Preconditions(com.palantir.logsafe.Preconditions) Stopwatch(com.google.common.base.Stopwatch) TreeMap(java.util.TreeMap) Response(com.palantir.dialogue.Response) Snapshot(com.codahale.metrics.Snapshot) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Aggregations

Response (com.palantir.dialogue.Response)93 Test (org.junit.jupiter.api.Test)72 TestResponse (com.palantir.dialogue.TestResponse)56 EndpointChannel (com.palantir.dialogue.EndpointChannel)27 Channel (com.palantir.dialogue.Channel)24 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)22 Endpoint (com.palantir.dialogue.Endpoint)16 Request (com.palantir.dialogue.Request)15 ClientConfiguration (com.palantir.conjure.java.client.config.ClientConfiguration)11 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)10 TestEndpoint (com.palantir.dialogue.TestEndpoint)10 SafeRuntimeException (com.palantir.logsafe.exceptions.SafeRuntimeException)9 Duration (java.time.Duration)9 Meter (com.codahale.metrics.Meter)8 IOException (java.io.IOException)8 Optional (java.util.Optional)7 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 QosException (com.palantir.conjure.java.api.errors.QosException)5 Arrays (java.util.Arrays)5 Stream (java.util.stream.Stream)5