repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/RunCompleter.java | cli/src/main/java/io/hyperfoil/cli/commands/RunCompleter.java | package io.hyperfoil.cli.commands;
import java.util.Comparator;
public class RunCompleter extends ServerOptionCompleter {
public RunCompleter() {
super(client -> client.runs(false).stream().map(r -> r.id).sorted(Comparator.reverseOrder()));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BaseEditCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BaseEditCommand.java | package io.hyperfoil.cli.commands;
import java.util.List;
import org.aesh.command.CommandException;
import org.aesh.command.option.OptionList;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
public abstract class BaseEditCommand extends BenchmarkCommand {
@OptionList(name = "extra-files", shortName = 'f', description = "Extra files for upload (comma-separated) in case this benchmark is a template and files won't be auto-detected. Example: --extra-files foo.txt,bar.txt")
protected List<String> extraFiles;
protected ConflictResolution askForConflictResolution(HyperfoilCommandInvocation invocation) {
invocation.println("Conflict: the benchmark was modified while being edited.");
try {
for (;;) {
invocation.print("Options: [C]ancel edit, [r]etry edits, [o]verwrite: ");
switch (invocation.inputLine().trim().toLowerCase()) {
case "":
case "c":
invocation.println("Edit cancelled.");
return ConflictResolution.CANCEL;
case "r":
return ConflictResolution.RETRY;
case "o":
return ConflictResolution.OVERWRITE;
}
}
} catch (InterruptedException ie) {
invocation.println("Edit cancelled by interrupt.");
return ConflictResolution.CANCEL;
}
}
protected Client.BenchmarkSource ensureSource(HyperfoilCommandInvocation invocation, Client.BenchmarkRef benchmarkRef)
throws CommandException {
Client.BenchmarkSource source;
try {
source = benchmarkRef.source();
if (source == null) {
throw new CommandException("No source available for benchmark '" + benchmarkRef.name() + "', cannot edit.");
}
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Cannot get benchmark " + benchmarkRef.name());
}
if (source.version == null) {
invocation.warn("Server did not send benchmark source version, modification conflicts won't be prevented.");
}
return source;
}
protected enum ConflictResolution {
CANCEL,
RETRY,
OVERWRITE,
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BaseUploadCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BaseUploadCommand.java | package io.hyperfoil.cli.commands;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.aesh.command.CommandException;
import org.aesh.command.option.Option;
import org.aesh.command.option.OptionList;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.config.BenchmarkData;
import io.hyperfoil.api.config.BenchmarkDefinitionException;
import io.hyperfoil.api.config.BenchmarkSource;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.core.impl.ProvidedBenchmarkData;
import io.hyperfoil.core.parser.BenchmarkParser;
import io.hyperfoil.core.parser.ParserException;
import io.hyperfoil.impl.Util;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
public abstract class BaseUploadCommand extends ServerCommand {
@Option(name = "print-stack-trace", hasValue = false)
public boolean printStackTrace;
@OptionList(name = "extra-files", shortName = 'f', description = "Extra files for upload (comma-separated) in case this benchmark is a template and files won't be auto-detected. Example: --extra-files foo.txt,bar.txt")
protected List<String> extraFiles;
protected BenchmarkSource loadBenchmarkSource(HyperfoilCommandInvocation invocation, String benchmarkYaml,
BenchmarkData data) throws CommandException {
BenchmarkSource source;
try {
source = BenchmarkParser.instance().createSource(benchmarkYaml, data);
if (source.isTemplate()) {
invocation.println("Loaded benchmark template " + source.name + " with these parameters (with defaults): ");
printTemplateParams(invocation, source.paramsWithDefaults);
invocation.println("Uploading...");
} else {
Benchmark benchmark = BenchmarkParser.instance().buildBenchmark(source, Collections.emptyMap());
// Note: we are loading and serializing the benchmark here just to fail fast - actual upload
// will be done in text+binary form to avoid the pain with syncing client and server
try {
Util.serialize(benchmark);
} catch (IOException e) {
logError(invocation, e);
throw new CommandException("Failed to serialize the benchmark.", e);
}
invocation.println("Loaded benchmark " + benchmark.name() + ", uploading...");
}
} catch (ParserException | BenchmarkDefinitionException e) {
logError(invocation, e);
throw new CommandException("Failed to parse the benchmark.", e);
}
return source;
}
protected void logError(HyperfoilCommandInvocation invocation, Exception e) {
invocation.error(e);
if (printStackTrace) {
invocation.printStackTrace(e);
} else {
invocation.println("Use --print-stack-trace to display the whole stack trace of this error.");
}
}
protected BenchmarkSource loadFromUrl(HyperfoilCommandInvocation invocation, String benchmarkPath,
Map<String, byte[]> extraData) throws CommandException {
WebClientOptions options = new WebClientOptions().setFollowRedirects(false);
if (benchmarkPath.startsWith("https://")) {
options.setSsl(true).setUseAlpn(true);
}
HyperfoilCliContext ctx = invocation.context();
WebClient client = WebClient.create(ctx.vertx(), options);
try {
HttpResponse<Buffer> response = client.getAbs(benchmarkPath).send().toCompletionStage().toCompletableFuture().get(15,
TimeUnit.SECONDS);
String benchmarkYaml = response.bodyAsString();
ProvidedBenchmarkData data = new ProvidedBenchmarkData();
data.files().putAll(extraData);
URL url = new URL(benchmarkPath);
String path = url.getPath();
if (path != null && path.contains("/")) {
path = path.substring(0, path.lastIndexOf('/') + 1);
} else {
path = "/";
}
URL dirUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
for (;;) {
try {
return loadBenchmarkSource(invocation, benchmarkYaml, data);
} catch (BenchmarkData.MissingFileException e) {
try {
HttpResponse<Buffer> fileResponse = client.getAbs(dirUrl + e.file).send().toCompletionStage()
.toCompletableFuture().get(15, TimeUnit.SECONDS);
byte[] bytes = fileResponse.bodyAsBuffer().getBytes();
data.files.put(e.file, bytes);
} catch (ExecutionException e2) {
invocation.error("Download of " + e.file + " failed", e2);
return null;
} catch (TimeoutException e2) {
invocation.error("Download of " + e.file + " timed out after 15 seconds", null);
return null;
}
}
}
} catch (InterruptedException e) {
invocation.println("Benchmark download cancelled.");
} catch (ExecutionException e) {
invocation.error("Benchmark download failed", e);
} catch (TimeoutException e) {
invocation.error("Benchmark download timed out after 15 seconds");
} catch (MalformedURLException e) {
invocation.error("Cannot parse URL " + benchmarkPath);
} finally {
client.close();
}
return null;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/ServerOptionCompleter.java | cli/src/main/java/io/hyperfoil/cli/commands/ServerOptionCompleter.java | package io.hyperfoil.cli.commands;
import java.util.function.Function;
import java.util.stream.Stream;
import io.hyperfoil.client.RestClient;
public class ServerOptionCompleter extends HyperfoilOptionCompleter {
public ServerOptionCompleter(Function<RestClient, Stream<String>> provider) {
super(context -> context.client() == null ? Stream.empty() : provider.apply(context.client()));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Connect.java | cli/src/main/java/io/hyperfoil/cli/commands/Connect.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Option;
import org.aesh.readline.Prompt;
import org.aesh.readline.terminal.formatting.Color;
import org.aesh.readline.terminal.formatting.TerminalColor;
import org.aesh.readline.terminal.formatting.TerminalString;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
@CommandDefinition(name = "connect", description = "Connects CLI to Hyperfoil Controller server")
public class Connect extends ServerCommand {
private static final int DEFAULT_PORT = 8090;
@Argument(description = "Hyperfoil host", completer = HostCompleter.class)
String host;
@Option(shortName = 'p', description = "Hyperfoil port")
Integer port;
@Option(shortName = 't', description = "Use secure (HTTPS/TLS) connections.", hasValue = false)
boolean tls;
@Option(name = "no-tls", description = "Do not use (HTTPS/TLS) connections.", hasValue = false)
boolean noTls;
@Option(shortName = 'k', description = "Do not verify certificate validity.", hasValue = false)
boolean insecure;
@Option(description = "Password used for server access (will be queried if necessary).")
String password;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
HyperfoilCliContext ctx = invocation.context();
if (host != null && host.startsWith("http://")) {
int end = host.indexOf('/', 7);
host = host.substring(7, end < 0 ? host.length() : end);
if (port == null) {
port = 80;
}
} else if (host != null && host.startsWith("https://")) {
int end = host.indexOf('/', 8);
host = host.substring(8, end < 0 ? host.length() : end);
if (port == null) {
port = 443;
}
if (!noTls) {
tls = true;
}
}
if (host != null) {
int colonIndex = host.indexOf(':');
if (colonIndex >= 0) {
String portStr = host.substring(colonIndex + 1);
try {
port = Integer.parseInt(portStr);
host = host.substring(0, colonIndex);
} catch (NumberFormatException e) {
invocation.error("Cannot parse port '" + portStr + "'");
return CommandResult.FAILURE;
}
}
}
if (port != null && port % 1000 == 443 && !noTls) {
tls = true;
}
if (ctx.client() != null) {
if (ctx.client().host().equals(host)
&& (ctx.client().port() == DEFAULT_PORT && port == null || port != null && ctx.client().port() == port)) {
invocation
.println("Already connected to " + ctx.client().host() + ":" + ctx.client().port() + ", not reconnecting.");
return CommandResult.SUCCESS;
} else {
invocation.println("Closing connection to " + ctx.client());
ctx.client().close();
ctx.setClient(null);
ctx.setServerRun(null);
ctx.setServerBenchmark(null);
ctx.setOnline(false);
invocation.setPrompt(new Prompt(new TerminalString("[hyperfoil]$ ",
new TerminalColor(Color.GREEN, Color.DEFAULT, Color.Intensity.BRIGHT))));
}
}
if (host == null && port == null && invocation.context().localControllerPort() > 0) {
host = invocation.context().localControllerHost();
port = invocation.context().localControllerPort();
} else if (host == null) {
host = "localhost";
}
if (port == null) {
port = DEFAULT_PORT;
}
connect(invocation, false, host, port, tls, insecure, password);
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Compare.java | cli/src/main/java/io/hyperfoil/cli/commands/Compare.java | package io.hyperfoil.cli.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.api.statistics.StatisticsSummary;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.RequestStatisticsResponse;
import io.hyperfoil.controller.model.RequestStats;
@CommandDefinition(name = "compare", description = "Compare results from two runs")
public class Compare extends ServerCommand {
private final Table<Comparison> TABLE = new Table<Comparison>()
.column("PHASE", c -> c.phase)
.column("METRIC", c -> c.metric)
.column("REQUESTS", c -> compare(c, ss -> ss.requestCount), Table.Align.RIGHT)
.column("MEAN", c -> compareNanos(c, ss -> ss.meanResponseTime), Table.Align.RIGHT)
.column("p50", c -> compareNanos(c, ss -> ss.percentileResponseTime.get(50d)), Table.Align.RIGHT)
.column("p90", c -> compareNanos(c, ss -> ss.percentileResponseTime.get(90d)), Table.Align.RIGHT)
.column("p99", c -> compareNanos(c, ss -> ss.percentileResponseTime.get(99d)), Table.Align.RIGHT)
.column("p99.9", c -> compareNanos(c, ss -> ss.percentileResponseTime.get(99.9)), Table.Align.RIGHT)
.column("p99.99", c -> compareNanos(c, ss -> ss.percentileResponseTime.get(99.99)), Table.Align.RIGHT);
@Arguments(required = true, description = "Runs that should be compared.", completer = RunCompleter.class)
private List<String> runIds;
@Option(name = "threshold", shortName = '\t', description = "Difference threshold for coloring.", defaultValue = "0.05")
private double threshold;
@Option(shortName = 'w', description = "Include statistics from warm-up phases.", hasValue = false)
private boolean warmup;
private String compare(Comparison c, ToIntFunction<StatisticsSummary> f) {
if (c.first == null || c.second == null) {
return "N/A";
}
int first = f.applyAsInt(c.first);
int second = f.applyAsInt(c.second);
StringBuilder sb = new StringBuilder();
double diff = (double) (second - first) / Math.min(first, second);
if (diff > threshold || diff < -threshold) {
sb.append(ANSI.YELLOW_TEXT);
}
sb.append(String.format("%+d(%+.2f%%)", second - first, diff * 100));
sb.append(ANSI.RESET);
return sb.toString();
}
private String compareNanos(Comparison c, ToLongFunction<StatisticsSummary> f) {
if (c.first == null || c.second == null) {
return "N/A";
}
long first = f.applyAsLong(c.first);
long second = f.applyAsLong(c.second);
StringBuilder sb = new StringBuilder();
double diff = (double) (second - first) / Math.min(first, second);
if (diff > threshold) {
sb.append(ANSI.RED_TEXT);
} else if (diff < -threshold) {
sb.append(ANSI.GREEN_TEXT);
}
sb.append(prettyPrintNanosDiff(second - first));
sb.append(String.format("(%+.2f%%)", diff * 100));
sb.append(ANSI.RESET);
return sb.toString();
}
public static String prettyPrintNanosDiff(long meanResponseTime) {
if (meanResponseTime < 1000 && meanResponseTime > -1000) {
return String.format("%+6d ns", meanResponseTime);
} else if (meanResponseTime < 1000_000 && meanResponseTime > -1000_000) {
return String.format("%+6.2f μs", meanResponseTime / 1000d);
} else if (meanResponseTime < 1000_000_000 && meanResponseTime > -1000_000_000) {
return String.format("%+6.2f ms", meanResponseTime / 1000_000d);
} else {
return String.format("%+6.2f s ", meanResponseTime / 1000_000_000d);
}
}
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
ensureConnection(invocation);
if (runIds.size() < 2) {
invocation.println("Two run IDs required for comparison.");
return CommandResult.FAILURE;
} else if (runIds.size() > 2) {
invocation.println("This command can compare only two run IDs; ignoring others.");
}
Client.RunRef firstRun = ensureComplete(invocation, runIds.get(0));
Client.RunRef secondRun = ensureComplete(invocation, runIds.get(1));
RequestStatisticsResponse firstStats = firstRun.statsTotal();
RequestStatisticsResponse secondStats = secondRun.statsTotal();
invocation.println("Comparing runs " + firstRun.id() + " and " + secondRun.id());
List<Comparison> comparisons = new ArrayList<>();
for (RequestStats stats : firstStats.statistics) {
if (stats.isWarmup && !warmup)
continue;
comparisons.add(new Comparison(stats.phase, stats.metric).first(stats.summary));
}
for (RequestStats stats : secondStats.statistics) {
if (stats.isWarmup && !warmup)
continue;
Optional<Comparison> maybeComparison = comparisons.stream()
.filter(c -> c.phase.equals(stats.phase) && c.metric.equals(stats.metric)).findAny();
if (maybeComparison.isPresent()) {
maybeComparison.get().second = stats.summary;
} else {
comparisons.add(new Comparison(stats.phase, stats.metric).second(stats.summary));
}
}
TABLE.print(invocation, comparisons.stream());
return CommandResult.SUCCESS;
}
private Client.RunRef ensureComplete(HyperfoilCommandInvocation invocation, String runId) throws CommandException {
Client.RunRef firstRun = invocation.context().client().run(runId);
if (firstRun.get().terminated == null) {
throw new CommandException("Run " + firstRun.id() + " did not complete yet.");
}
return firstRun;
}
private static class Comparison {
final String phase;
final String metric;
StatisticsSummary first;
StatisticsSummary second;
Comparison(String phase, String metric) {
this.phase = phase;
this.metric = metric;
}
public Comparison first(StatisticsSummary first) {
this.first = first;
return this;
}
public Comparison second(StatisticsSummary second) {
this.second = second;
return this;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/HyperfoilOptionCompleter.java | cli/src/main/java/io/hyperfoil/cli/commands/HyperfoilOptionCompleter.java | package io.hyperfoil.cli.commands;
import java.util.function.Function;
import java.util.stream.Stream;
import org.aesh.command.completer.OptionCompleter;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCompleterData;
import io.hyperfoil.client.RestClientException;
public class HyperfoilOptionCompleter implements OptionCompleter<HyperfoilCompleterData> {
private final Function<HyperfoilCliContext, Stream<String>> provider;
public HyperfoilOptionCompleter(Function<HyperfoilCliContext, Stream<String>> provider) {
this.provider = provider;
}
@Override
public void complete(HyperfoilCompleterData completerInvocation) {
HyperfoilCliContext context = completerInvocation.getContext();
Stream<String> options;
try {
options = provider.apply(context);
} catch (RestClientException e) {
return;
}
String prefix = completerInvocation.getGivenCompleteValue();
if (prefix != null) {
options = options.filter(b -> b.startsWith(prefix));
}
options.forEach(completerInvocation::addCompleterValue);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Runs.java | cli/src/main/java/io/hyperfoil/cli/commands/Runs.java | package io.hyperfoil.cli.commands;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.List;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
@CommandDefinition(name = "runs", description = "Print info about past runs.")
public class Runs extends ServerCommand {
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private static final Table<io.hyperfoil.controller.model.Run> RUN_TABLE = new Table<io.hyperfoil.controller.model.Run>()
.idColumns(2)
.column("", run -> runIcon(run))
.column("RUN_ID", run -> run.id)
.column("BENCHMARK", run -> run.benchmark)
.column("STARTED", run -> run.started == null ? "" : DATE_FORMATTER.format(run.started))
.column("TERMINATED", run -> run.terminated == null ? "" : DATE_FORMATTER.format(run.terminated))
.column("DESCRIPTION", run -> run.description);
private static String runIcon(io.hyperfoil.controller.model.Run run) {
if (run.cancelled) {
return ANSI.RED_TEXT + "×" + ANSI.RESET;
} else if (run.errors != null && !run.errors.isEmpty()) {
return ANSI.RED_TEXT + (run.terminated == null ? ANSI.BLINK : "") + "!" + ANSI.RESET;
} else if (run.started == null) {
return ANSI.YELLOW_TEXT + "?" + ANSI.RESET;
} else if (run.terminated == null) {
return ANSI.YELLOW_TEXT + ANSI.BLINK + "?" + ANSI.RESET;
} else {
return ANSI.GREEN_TEXT + "+" + ANSI.RESET;
}
}
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
List<io.hyperfoil.controller.model.Run> runs = invocation.context().client().runs(true);
RUN_TABLE.print(invocation, runs.stream().sorted(Comparator.comparing(run -> run.id)));
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BaseStandaloneCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BaseStandaloneCommand.java | package io.hyperfoil.cli.commands;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.aesh.command.AeshCommandRuntimeBuilder;
import org.aesh.command.Command;
import org.aesh.command.CommandNotFoundException;
import org.aesh.command.CommandResult;
import org.aesh.command.CommandRuntime;
import org.aesh.command.impl.registry.AeshCommandRegistryBuilder;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.cli.context.HyperfoilCommandInvocationProvider;
import io.hyperfoil.internal.Properties;
public abstract class BaseStandaloneCommand {
//ignore logging when running in the console below severe
static {
Handler[] handlers = Logger.getLogger("").getHandlers();
for (Handler handler : handlers) {
handler.setLevel(Level.SEVERE);
}
}
protected abstract Class<? extends Command<HyperfoilCommandInvocation>> getCommand();
protected List<Class<? extends Command<HyperfoilCommandInvocation>>> getDependencyCommands() {
return List.of();
}
protected abstract String getCommandName();
public int exec(String[] args) {
CommandRuntime<HyperfoilCommandInvocation> cr = null;
CommandResult result = null;
try {
AeshCommandRuntimeBuilder<HyperfoilCommandInvocation> runtime = AeshCommandRuntimeBuilder.builder();
runtime.commandInvocationProvider(new HyperfoilCommandInvocationProvider(new HyperfoilCliContext()));
@SuppressWarnings("unchecked")
AeshCommandRegistryBuilder<HyperfoilCommandInvocation> registry = AeshCommandRegistryBuilder
.<HyperfoilCommandInvocation> builder()
// add default commands
.commands(StartLocal.class, getCommand(), Exit.class);
for (Class<? extends Command<HyperfoilCommandInvocation>> command : getDependencyCommands()) {
registry.command(command);
}
runtime.commandRegistry(registry.create());
cr = runtime.build();
try {
// start the local in-vm controller server
cr.executeCommand("start-local --quiet");
// As -H option could contain a whitespace we have to either escape the space or quote the argument.
// However, quoting would not work well if the argument contains a quote.
String optionsCollected = Stream.of(args).map(arg -> arg.replaceAll(" ", "\\\\ ")).collect(Collectors.joining(" "));
result = cr.executeCommand(getCommandName() + " " + optionsCollected);
} finally {
// exit from the CLI
cr.executeCommand("exit");
}
} catch (Exception e) {
System.out.println("Failed to execute command: " + e.getMessage());
if (Boolean.getBoolean(Properties.HYPERFOIL_STACKTRACE)) {
e.printStackTrace();
}
if (cr != null) {
try {
System.out.println(
cr.getCommandRegistry().getCommand(getCommandName(), getCommandName()).printHelp(getCommandName()));
} catch (CommandNotFoundException ex) {
throw new IllegalStateException(ex);
}
}
}
return result == null ? CommandResult.FAILURE.getResultValue() : result.getResultValue();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Upload.java | cli/src/main/java/io/hyperfoil/cli/commands/Upload.java | package io.hyperfoil.cli.commands;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.stream.Collectors;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.impl.completer.FileOptionCompleter;
import org.aesh.command.option.Argument;
import io.hyperfoil.api.config.BenchmarkSource;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.core.impl.LocalBenchmarkData;
@CommandDefinition(name = "upload", description = "Uploads benchmark definition to Hyperfoil Controller server")
public class Upload extends BaseUploadCommand {
@Argument(description = "YAML benchmark definition file", required = true, completer = FileOptionCompleter.class)
String benchmarkPath;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
if (benchmarkPath != null && (benchmarkPath.startsWith("http://") || benchmarkPath.startsWith("https://"))) {
LocalBenchmarkData extraData = loadExtras(invocation, null);
if (extraData == null) {
return CommandResult.FAILURE;
}
BenchmarkSource source = loadFromUrl(invocation, benchmarkPath, extraData.files());
if (source == null) {
return CommandResult.FAILURE;
}
Client.BenchmarkRef benchmarkRef = invocation.context().client().register(source.yaml, source.data.files(), null,
null);
invocation.context().setServerBenchmark(benchmarkRef);
invocation.println("... done.");
return CommandResult.SUCCESS;
} else {
return uploadFromFile(invocation);
}
}
private LocalBenchmarkData loadExtras(HyperfoilCommandInvocation invocation, Path o) {
LocalBenchmarkData extraData = new LocalBenchmarkData(o);
if (extraFiles != null) {
for (String extraFile : extraFiles) {
try (InputStream ignored = extraData.readFile(extraFile)) {
// intentionally empty
} catch (IOException e) {
invocation.error("Cannot read file " + extraFile, e);
return null;
}
}
}
return extraData;
}
private CommandResult uploadFromFile(HyperfoilCommandInvocation invocation) throws CommandException {
String sanitizedPathStr = CliUtil.sanitize(benchmarkPath);
Path sanitizedPath = Paths.get(sanitizedPathStr);
String benchmarkYaml;
try {
benchmarkYaml = Files.readString(sanitizedPath);
} catch (IOException e) {
logError(invocation, e);
throw new CommandException("Failed to load the benchmark", e);
}
LocalBenchmarkData data = loadExtras(invocation, sanitizedPath.toAbsolutePath());
if (data == null) {
return CommandResult.FAILURE;
}
try {
BenchmarkSource source = loadBenchmarkSource(invocation, benchmarkYaml, data);
Path benchmarkDir = sanitizedPath.toAbsolutePath().getParent();
Map<String, Path> extraFiles = source.data.files().keySet().stream()
.collect(Collectors.toMap(file -> file, file -> {
Path path = Paths.get(file);
return path.isAbsolute() ? path : benchmarkDir.resolve(file);
}));
HyperfoilCliContext ctx = invocation.context();
Client.BenchmarkRef benchmarkRef = ctx.client().register(
sanitizedPath.toAbsolutePath(), extraFiles, null, null);
ctx.setServerBenchmark(benchmarkRef);
invocation.println("... done.");
return CommandResult.SUCCESS;
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Failed to upload the benchmark.", e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
logError(invocation, e);
throw new CommandException("Unknown error.", e);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BenchmarkCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BenchmarkCommand.java | package io.hyperfoil.cli.commands;
import java.util.Collections;
import org.aesh.command.CommandException;
import org.aesh.command.option.Argument;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
public abstract class BenchmarkCommand extends ServerCommand {
@Argument(description = "Name of the benchmark.", completer = BenchmarkCompleter.class)
public String benchmark;
protected Client.BenchmarkRef ensureBenchmark(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
HyperfoilCliContext ctx = invocation.context();
Client.BenchmarkRef benchmarkRef;
if (benchmark == null || benchmark.isEmpty()) {
benchmarkRef = ctx.serverBenchmark();
if (benchmarkRef == null) {
invocation.println("No benchmark was set. Available benchmarks: ");
printList(invocation, invocation.context().client().benchmarks(), 15);
throw new CommandException("Use " + getClass().getSimpleName().toLowerCase() + " <benchmark>");
}
} else {
benchmarkRef = ctx.client().benchmark(benchmark);
if (benchmarkRef == null) {
invocation.println("Available benchmarks: ");
printList(invocation, invocation.context().client().benchmarks(), 15);
throw new CommandException("No such benchmark: '" + benchmark + "'");
}
if (ctx.serverBenchmark() != null && !ctx.serverBenchmark().name().equals(benchmark)) {
ctx.setCurrentParams(Collections.emptyMap());
}
}
ctx.setServerBenchmark(benchmarkRef);
return benchmarkRef;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/ServerCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/ServerCommand.java | package io.hyperfoil.cli.commands;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.net.ssl.SSLHandshakeException;
import org.aesh.command.Command;
import org.aesh.command.CommandException;
import org.aesh.readline.Prompt;
import org.aesh.readline.action.KeyAction;
import org.aesh.readline.terminal.formatting.Color;
import org.aesh.readline.terminal.formatting.TerminalColor;
import org.aesh.readline.terminal.formatting.TerminalString;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClient;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.model.Run;
import io.hyperfoil.impl.Util;
public abstract class ServerCommand implements Command<HyperfoilCommandInvocation> {
protected static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
protected static final String MOVE_LINE_UP = new String(new byte[] { 27, 91, 49, 65 }, StandardCharsets.US_ASCII);
protected static final String ERASE_WHOLE_LINE = new String(new byte[] { 27, 91, 50, 75 }, StandardCharsets.US_ASCII);
protected static final String EDITOR;
static {
String editor = System.getenv("VISUAL");
if (editor == null || editor.isEmpty()) {
editor = System.getenv("EDITOR");
}
if (editor == null || editor.isEmpty()) {
editor = CliUtil.fromCommand("update-alternatives", "--display", "editor");
}
if (editor == null || editor.isEmpty()) {
editor = CliUtil.fromCommand("git", "var", "GIT_EDITOR");
}
if (editor == null || editor.isEmpty()) {
editor = "vi";
}
EDITOR = editor;
}
protected void openInBrowser(String url) throws CommandException {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
throw new CommandException("Cannot open '" + url + "' in browser: " + Util.explainCauses(e), e);
}
} else {
try {
Runtime.getRuntime().exec("xdg-open " + url);
} catch (IOException e) {
throw new CommandException("Cannot open '" + url + "' in browser: " + Util.explainCauses(e), e);
}
}
}
protected void ensureConnection(HyperfoilCommandInvocation invocation) throws CommandException {
HyperfoilCliContext ctx = invocation.context();
if (ctx.client() != null) {
return;
}
invocation.println("Not connected, trying to connect to localhost:8090...");
connect(invocation, false, "localhost", 8090, false, false, null);
}
protected void connect(HyperfoilCommandInvocation invocation, boolean quiet, String host, int port, boolean ssl,
boolean insecure, String password) throws CommandException {
HyperfoilCliContext ctx = invocation.context();
ctx.setClient(new RestClient(ctx.vertx(), host, port, ssl, insecure, password));
if (ssl && insecure) {
invocation.warn("Hyperfoil TLS certificate validity is not checked. Your credentials might get compromised.");
}
try {
long preMillis, postMillis;
io.hyperfoil.controller.model.Version version;
for (;;) {
try {
preMillis = System.currentTimeMillis();
version = ctx.client().version();
postMillis = System.currentTimeMillis();
break;
} catch (RestClient.Unauthorized e) {
if (!updatePassword(invocation, ctx)) {
return;
}
} catch (RestClient.Forbidden e) {
invocation.println("Provided password is incorrect, please type again:");
if (!updatePassword(invocation, ctx)) {
return;
}
} catch (RestClient.RedirectToHost e) {
ctx.client().close();
ctx.setClient(null);
invocation.println("CLI is redirected to " + e.host);
Connect connect = new Connect();
connect.host = e.host;
connect.password = password;
connect.insecure = insecure;
connect.execute(invocation);
return;
}
}
if (!quiet) {
invocation.println("Connected to " + host + ":" + port + "!");
}
ctx.setOnline(true);
if (!quiet && version.serverTime != null
&& (version.serverTime.getTime() < preMillis || version.serverTime.getTime() > postMillis)) {
invocation.warn("Controller time seems to be off by "
+ (postMillis + preMillis - 2 * version.serverTime.getTime()) / 2 + " ms");
}
if (!quiet && !Objects.equals(version.commitId, io.hyperfoil.api.Version.COMMIT_ID)) {
invocation.warn(
"Controller version is different from CLI version. Benchmark upload may fail due to binary incompatibility.");
}
String shortHost = host;
if (host.equals(invocation.context().localControllerHost()) && port == invocation.context().localControllerPort()) {
shortHost = "in-vm";
} else if (host.contains(".")) {
shortHost = host.substring(0, host.indexOf('.'));
}
invocation.setPrompt(new Prompt(new TerminalString("[hyperfoil@" + shortHost + "]$ ",
new TerminalColor(Color.GREEN, Color.DEFAULT, Color.Intensity.BRIGHT))));
ctx.setControllerId(null);
ctx.setControllerPollTask(ctx.executor().scheduleAtFixedRate(() -> {
try {
String currentId = ctx.client().version().deploymentId;
if (!ctx.online()) {
invocation.print("\n" + ANSI.GREEN_TEXT + "INFO: Controller is back online." + ANSI.RESET + "\n");
ctx.setOnline(true);
}
if (ctx.controllerId() == null) {
ctx.setControllerId(currentId);
} else if (!ctx.controllerId().equals(currentId)) {
invocation.print("\n" + ANSI.RED_TEXT + ANSI.BOLD + "WARNING: controller was restarted." + ANSI.RESET + "\n");
ctx.setControllerId(currentId);
}
} catch (RestClientException e) {
if (ctx.online()) {
invocation
.print("\n" + ANSI.YELLOW_TEXT + ANSI.BOLD + "WARNING: controller seems offline." + ANSI.RESET + "\n");
ctx.setOnline(false);
}
}
}, 0, 15, TimeUnit.SECONDS));
} catch (RestClientException e) {
ctx.client().close();
ctx.setClient(null);
invocation.error(e);
if (Objects.equals(e.getCause().getMessage(), "Connection was closed")) {
invocation.println("Hint: Server might be secured; use --tls.");
}
if (e.getCause() instanceof SSLHandshakeException) {
invocation.println("Hint: TLS certificate verification might have failed. Use --insecure to disable validation.");
}
throw new CommandException("Failed connecting to " + host + ":" + port, e);
}
}
private boolean updatePassword(HyperfoilCommandInvocation invocation, HyperfoilCliContext ctx) {
try {
String password = invocation.inputLine(new Prompt("password: ", '*'));
if (password == null || password.isEmpty()) {
invocation.println("Empty password, not connecting.");
ctx.client().close();
ctx.setClient(null);
return false;
}
ctx.client().setPassword(password);
return true;
} catch (InterruptedException ie) {
ctx.client().close();
ctx.setClient(null);
invocation.println("Not connected.");
return false;
}
}
protected void printList(HyperfoilCommandInvocation invocation, Collection<String> items, int limit) {
int counter = 0;
for (String name : items) {
invocation.print(name);
invocation.print(" ");
if (counter++ > limit) {
invocation.print("... (" + (items.size() - 15) + " more)");
break;
}
}
invocation.println("");
}
protected void clearLines(HyperfoilCommandInvocation invocation, int numLines) {
invocation.print(ERASE_WHOLE_LINE);
for (int i = 0; i < numLines; ++i) {
invocation.print(MOVE_LINE_UP);
invocation.print(ERASE_WHOLE_LINE);
}
}
protected boolean interruptibleDelay(HyperfoilCommandInvocation invocation) {
invocation
.println("Press [" + bold("s") + "] for status, [" + bold("t") + "] for stats, [" + bold("e") + "] for sessions, ["
+ bold("c") + "] for connections or " + invocation.context().interruptKey() + " to stop watching...");
try {
KeyAction action = invocation.input(1, TimeUnit.SECONDS);
if (action != null) {
String command = null;
switch (action.name()) {
case "s":
command = "status";
break;
case "t":
command = "stats";
break;
case "e":
command = "sessions";
break;
case "c":
command = "connections";
break;
}
if (command == null) {
return false;
}
clearLines(invocation, 1);
invocation.println("");
for (int i = invocation.getShell().size().getWidth(); i > 0; --i) {
invocation.print("—");
}
invocation.println("");
if (invocation.context().isSwitchable()) {
throw new SwitchCommandException(command);
} else {
invocation.executeSwitchable(command);
return true;
}
}
} catch (InterruptedException | CommandException e) {
clearLines(invocation, 1);
invocation.println("");
return true;
}
return false;
}
private String bold(String bold) {
return ANSI.BOLD + bold + ANSI.RESET;
}
protected void failMissingRunId(HyperfoilCommandInvocation invocation) throws CommandException {
invocation
.println("Command '" + getClass().getSimpleName().toLowerCase() + "' requires run ID as argument! Available runs:");
List<Run> runs = invocation.context().client().runs(false);
printList(invocation, runs.stream().map(r -> r.id).sorted(Comparator.reverseOrder()).collect(Collectors.toList()), 15);
throw new CommandException("Cannot run command without run ID.");
}
protected void printTemplateParams(HyperfoilCommandInvocation invocation, Map<String, String> params) {
Table<ParamRow> table = new Table<>();
table.column("NAME", row -> row.name).column("DEFAULT", row -> row.defaultValue).column("CURRENT (CONTEXT)",
row -> row.currentValue);
Map<String, String> current = invocation.context().currentParams();
table.print(invocation, params.entrySet().stream()
.map(entry -> {
String defaultValue = entry.getValue();
String currentValue = current.get(entry.getKey());
return new ParamRow(entry.getKey(),
defaultValue == null ? "(no default value)" : defaultValue,
currentValue == null ? "(not set)" : currentValue);
}));
}
protected boolean readYes(HyperfoilCommandInvocation invocation) throws InterruptedException {
switch (invocation.getShell().readLine().trim().toLowerCase()) {
case "y":
case "yes":
return true;
default:
return false;
}
}
private static class ParamRow {
String name;
String defaultValue;
String currentValue;
ParamRow(String name, String defaultValue, String currentValue) {
this.name = name;
this.defaultValue = defaultValue;
this.currentValue = currentValue;
}
}
public static class SwitchCommandException extends RuntimeException {
public final String newCommand;
public SwitchCommandException(String newCommand) {
super("Switch to " + newCommand, null, false, false);
this.newCommand = newCommand;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Sessions.java | cli/src/main/java/io/hyperfoil/cli/commands/Sessions.java | package io.hyperfoil.cli.commands;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "sessions", description = "Show sessions statistics")
public class Sessions extends BaseRunIdCommand {
Table<Map.Entry<String, Client.MinMax>> SESSION_STATS = new Table<Map.Entry<String, Client.MinMax>>()
.column("AGENT", Map.Entry::getKey)
.column("MIN", e -> String.valueOf(e.getValue().min), Table.Align.RIGHT)
.column("MAX", e -> String.valueOf(e.getValue().max), Table.Align.RIGHT);
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
Client.RunRef runRef = getRunRef(invocation);
Map<String, Map<String, Client.MinMax>> sessionStats = null;
for (;;) {
try {
int numLines = sessionStats == null ? 0 : sessionStats.values().stream().mapToInt(Map::size).sum() + 2;
sessionStats = runRef.sessionStatsRecent();
clearLines(invocation, numLines);
if (sessionStats == null || sessionStats.isEmpty()) {
io.hyperfoil.controller.model.Run run = runRef.get();
if (run.terminated != null) {
invocation.println("Run " + run.id + " has terminated.");
SESSION_STATS.print(invocation, "PHASE", CliUtil.toMapOfStreams(runRef.sessionStatsTotal()));
return CommandResult.SUCCESS;
}
}
if (sessionStats != null) {
SESSION_STATS.print(invocation, "PHASE", CliUtil.toMapOfStreams(sessionStats));
}
if (interruptibleDelay(invocation)) {
return CommandResult.SUCCESS;
}
} catch (RestClientException e) {
if (e.getCause() instanceof InterruptedException) {
clearLines(invocation, 1);
invocation.println("");
return CommandResult.SUCCESS;
}
invocation.error(e);
throw new CommandException("Cannot display session stats.", e);
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Exit.java | cli/src/main/java/io/hyperfoil/cli/commands/Exit.java | package io.hyperfoil.cli.commands;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandResult;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
@CommandDefinition(name = "exit", description = "exit the program", aliases = { "quit" })
public class Exit implements Command<HyperfoilCommandInvocation> {
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) {
invocation.stop();
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Edit.java | cli/src/main/java/io/hyperfoil/cli/commands/Edit.java | package io.hyperfoil.cli.commands;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.config.BenchmarkData;
import io.hyperfoil.api.config.BenchmarkDefinitionException;
import io.hyperfoil.api.config.BenchmarkSource;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.core.impl.ProvidedBenchmarkData;
import io.hyperfoil.core.parser.BenchmarkParser;
import io.hyperfoil.core.parser.ParserException;
import io.hyperfoil.impl.Util;
@CommandDefinition(name = "edit", description = "Edit benchmark definition.")
public class Edit extends BaseEditCommand {
@Option(name = "editor", shortName = 'e', description = "Editor used.")
private String editor;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
Client.BenchmarkRef benchmarkRef = ensureBenchmark(invocation);
Client.BenchmarkSource source = ensureSource(invocation, benchmarkRef);
File sourceFile;
try {
sourceFile = File.createTempFile(benchmarkRef.name() + "-", ".yaml");
Files.write(sourceFile.toPath(), source.source.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new CommandException("Cannot create temporary file for edits.", e);
}
long modifiedTimestamp = sourceFile.lastModified();
Map<String, byte[]> extraData = new HashMap<>();
if (extraFiles != null) {
for (String extraFile : extraFiles) {
try {
extraData.put(extraFile, Files.readAllBytes(Path.of(extraFile)));
} catch (IOException e) {
invocation.error(
"Cannot read file " + extraFile + " (current directory is " + new File("").getAbsolutePath() + ")", e);
}
}
}
ProvidedBenchmarkData data = new ProvidedBenchmarkData(extraData);
BenchmarkSource newSource;
for (;;) {
try {
CliUtil.execProcess(invocation, true, this.editor == null ? EDITOR : this.editor, sourceFile.getAbsolutePath());
} catch (IOException e) {
sourceFile.delete();
throw new CommandException("Failed to invoke the editor.", e);
}
if (sourceFile.lastModified() == modifiedTimestamp) {
invocation.println("No changes, not uploading.");
sourceFile.delete();
return CommandResult.SUCCESS;
}
try {
byte[] updatedSource = Files.readAllBytes(sourceFile.toPath());
newSource = BenchmarkParser.instance().createSource(new String(updatedSource, StandardCharsets.UTF_8), data);
if (!newSource.isTemplate()) {
Benchmark benchmark;
for (;;) {
try {
benchmark = BenchmarkParser.instance().buildBenchmark(newSource, Collections.emptyMap());
break;
} catch (BenchmarkData.MissingFileException e) {
Path path = Path.of("<none>");
try {
path = CliUtil.getLocalFileForUpload(invocation, e.file);
if (path != null) {
data.files().put(e.file, Files.readAllBytes(path));
} else {
data.ignoredFiles.add(e.file);
}
} catch (InterruptedException e2) {
invocation.println("Edits cancelled.");
sourceFile.delete();
return CommandResult.FAILURE;
} catch (IOException e2) {
invocation.error("Cannot read file " + path, e2);
}
}
}
try {
Util.serialize(benchmark);
} catch (IOException e) {
invocation.error("Benchmark is not serializable.", e);
sourceFile.delete();
// This is a bug in Hyperfoil; there isn't anything the user could do about that (no need to retry).
return CommandResult.FAILURE;
}
}
break;
} catch (ParserException | BenchmarkDefinitionException e) {
invocation.error(e);
invocation.print("Retry edits? [Y/n] ");
try {
switch (invocation.inputLine().trim().toLowerCase()) {
case "n":
case "no":
return CommandResult.FAILURE;
}
} catch (InterruptedException ie) {
invocation.println("Edits cancelled.");
sourceFile.delete();
return CommandResult.FAILURE;
}
data = new ProvidedBenchmarkData(extraData);
} catch (IOException e) {
invocation.error(e);
throw new CommandException("Failed to load the benchmark.", e);
}
}
try {
String prevVersion = source.version;
if (!newSource.name.equals(benchmarkRef.name())) {
invocation.println("NOTE: Renamed benchmark " + benchmarkRef.name() + " to " + newSource.name
+ "; old benchmark won't be deleted.");
prevVersion = null;
}
invocation.println("Uploading benchmark " + newSource.name + "...");
invocation.context().client().register(newSource.yaml, data.files(), prevVersion, benchmarkRef.name());
sourceFile.delete();
} catch (RestClientException e) {
if (e.getCause() instanceof Client.EditConflictException) {
switch (askForConflictResolution(invocation)) {
case CANCEL:
invocation.println("You can find your edits in " + sourceFile);
return CommandResult.SUCCESS;
case RETRY:
try {
invocation.executeCommand("edit " + this.benchmark + (editor == null ? "" : " -e " + editor));
} catch (Exception ex) {
// who cares
}
return CommandResult.SUCCESS;
case OVERWRITE:
invocation.context().client().register(newSource.yaml, data.files(), null, benchmarkRef.name());
}
} else {
invocation.println(Util.explainCauses(e));
invocation.println("You can find your edits in " + sourceFile);
throw new CommandException("Failed to upload the benchmark", e);
}
}
invocation.println("Benchmark " + newSource.name + " updated.");
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Status.java | cli/src/main/java/io/hyperfoil/cli/commands/Status.java | package io.hyperfoil.cli.commands;
import java.text.SimpleDateFormat;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.Phase;
@CommandDefinition(name = "status", description = "Prints information about executing or completed run.")
public class Status extends BaseRunIdCommand {
private static final int MAX_ERRORS = 15;
private static final SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("HH:mm:ss.SSS");
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private static final Table<Phase> PHASE_TABLE = new Table<Phase>()
.column("NAME", p -> p.name)
.column("STATUS", p -> p.status)
.column("STARTED", p -> p.started == null ? null : TIME_FORMATTER.format(p.started))
.column("REMAINING", p -> p.remaining, Table.Align.RIGHT)
.column("COMPLETED", p -> p.completed == null ? null : TIME_FORMATTER.format(p.completed))
.column("TOTAL DURATION", p -> p.totalDuration)
.column("DESCRIPTION", p -> p.description);
@Option(name = "all", shortName = 'a', description = "Show all phases", hasValue = false)
boolean all;
@Option(name = "no-errors", shortName = 'E', description = "Do not list errors", hasValue = false)
boolean noErrors;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
Client.RunRef runRef = getRunRef(invocation);
io.hyperfoil.controller.model.Run run = getRun(invocation, runRef);
invocation.println("Run " + run.id + ", benchmark " + run.benchmark);
if (run.description != null) {
invocation.println(run.description);
}
for (;;) {
int lines = 0;
if (run.agents != null && !run.agents.isEmpty()) {
invocation.print("Agents: ");
invocation.println(
String.join(", ", run.agents.stream().map(a -> a.name + "[" + a.status + "]").toArray(String[]::new)));
++lines;
}
if (run.started != null) {
invocation.print("Started: " + DATE_FORMATTER.format(run.started) + " ");
}
if (run.terminated != null) {
invocation.println("Terminated: " + DATE_FORMATTER.format(run.terminated));
} else {
invocation.println("");
}
++lines;
io.hyperfoil.controller.model.Run r = run;
lines += PHASE_TABLE.print(invocation, run.phases.stream().filter(p -> showPhase(r, p)));
long cancelled = run.phases.stream().filter(p -> "CANCELLED".equals(p.status)).count();
if (cancelled > 0) {
invocation.println(cancelled + " phases were cancelled.");
lines++;
}
if (!run.errors.isEmpty() && !noErrors) {
invocation.println(ANSI.RED_TEXT + ANSI.BOLD + "Errors:" + ANSI.RESET);
++lines;
for (int i = 0; i < run.errors.size() && (all || i < MAX_ERRORS); ++i) {
invocation.println(run.errors.get(run.errors.size() - 1 - i));
++lines;
}
if (run.errors.size() > MAX_ERRORS && !all) {
invocation.println("... " + (run.errors.size() - MAX_ERRORS) + " more errors ...");
++lines;
}
}
if (run.terminated != null) {
invocation.context().notifyRunCompleted(run);
return CommandResult.SUCCESS;
}
if (interruptibleDelay(invocation)) {
return CommandResult.SUCCESS;
}
++lines;
try {
run = runRef.get();
} catch (RestClientException e) {
if (e.getCause() instanceof InterruptedException) {
clearLines(invocation, 1);
invocation.println("");
return CommandResult.SUCCESS;
}
invocation.error(e);
throw new CommandException("Cannot fetch status for run " + runRef.id(), e);
}
clearLines(invocation, lines);
}
}
private boolean showPhase(io.hyperfoil.controller.model.Run run, Phase phase) {
return ((all || run.terminated != null) && !"CANCELLED".equals(phase.status))
|| "RUNNING".equals(phase.status) || "FINISHED".equals(phase.status);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/LoadAndRun.java | cli/src/main/java/io/hyperfoil/cli/commands/LoadAndRun.java | package io.hyperfoil.cli.commands;
import java.util.List;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
public class LoadAndRun extends BaseStandaloneCommand {
private static final String CMD = "run";
public static void main(String[] args) {
LoadAndRun lr = new LoadAndRun();
lr.exec(args);
}
@Override
protected Class<? extends Command<HyperfoilCommandInvocation>> getCommand() {
return LoadAndRunCommand.class;
}
@Override
protected List<Class<? extends Command<HyperfoilCommandInvocation>>> getDependencyCommands() {
return List.of(Upload.class, Wait.class, Report.class);
}
@Override
protected String getCommandName() {
return CMD;
}
@CommandDefinition(name = "run", description = "Load and start a benchmark on Hyperfoil controller server, the argument can be the benchmark definition directly.")
public static class LoadAndRunCommand extends io.hyperfoil.cli.commands.Run {
@Option(name = "output", shortName = 'o', description = "Output destination path for the HTML report")
private String output;
@Option(name = "print-stack-trace", hasValue = false)
public boolean printStackTrace;
@Override
protected void setup(HyperfoilCommandInvocation invocation) throws CommandException {
// if benchmarkFile is provided load the benchmark as first step and fail fast if something went wrong
if (benchmark != null && !benchmark.isBlank()) {
invocation.executeSwitchable("upload " + (printStackTrace ? "--print-stack-trace " : "") + benchmark);
// once used, reset it as it needs to be populated by the actual benchmark name
benchmark = null;
} else {
throw new CommandException("No benchmark file specified");
}
}
@Override
protected void monitor(HyperfoilCommandInvocation invocation) throws CommandException {
invocation.executeSwitchable("wait");
if (output != null && !output.isBlank()) {
invocation.executeSwitchable("report --silent -y --destination " + output);
} else {
invocation.println("Skipping report generation, consider providing --output to generate it.");
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Cpu.java | cli/src/main/java/io/hyperfoil/cli/commands/Cpu.java | package io.hyperfoil.cli.commands;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "cpu", description = "Show agent CPU usage")
public class Cpu extends BaseRunIdCommand {
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
Client.RunRef runRef = getRunRef(invocation);
Map<String, Map<String, String>> cpu = runRef.agentCpu();
if (cpu == null || cpu.isEmpty()) {
invocation.println("No agent CPU data available from run " + runRef.id() + " (maybe not completed yet).");
return CommandResult.FAILURE;
}
Table<Map.Entry<String, Map<String, String>>> table = new Table<>();
table.column("PHASE", Map.Entry::getKey);
String[] agents = cpu.values().stream().flatMap(e -> e.keySet().stream()).sorted().distinct().toArray(String[]::new);
for (String agent : agents) {
table.column(agent, e -> e.getValue().get(agent));
}
table.print(invocation, cpu.entrySet().stream());
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/StartLocal.java | cli/src/main/java/io/hyperfoil/cli/commands/StartLocal.java | package io.hyperfoil.cli.commands;
import java.io.IOException;
import java.io.InputStream;
import java.util.ServiceLoader;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Option;
import org.aesh.io.FileResource;
import org.aesh.io.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.internal.Controller;
import io.hyperfoil.internal.Properties;
@CommandDefinition(name = "start-local", description = "Start non-clustered controller within the CLI process.")
public class StartLocal extends ServerCommand {
@Option(shortName = 'l', description = "Default log level for controller log.", defaultValue = "")
private String logLevel;
@Option(shortName = 'q', description = "Do not print anything on output in this command.", hasValue = false)
private boolean quiet;
@Argument(description = "Root directory used for the controller.")
private Resource rootDir;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
HyperfoilCliContext ctx = invocation.context();
if (ctx.localControllerHost() != null || ctx.localControllerPort() > 0) {
if (!quiet) {
invocation.warn("Local controller is already running, not starting.");
}
} else {
Controller.Factory factory = null;
for (Controller.Factory f : ServiceLoader.load(Controller.Factory.class)) {
factory = f;
break;
}
if (factory == null) {
throw new CommandException("Controller is not on the classpath, cannot start.");
}
rootDir = CliUtil.sanitize(rootDir);
if (rootDir != null && rootDir.exists() && !(rootDir.isDirectory() && rootDir instanceof FileResource)) {
if (!quiet) {
invocation.println("You are trying to start Hyperfoil controller with root dir " + rootDir);
}
throw new CommandException(rootDir + " exists but it is not a directory");
}
if (!quiet) {
invocation.println("Starting controller in "
+ (rootDir == null ? "default directory (/tmp/hyperfoil)" : rootDir.getAbsolutePath()));
}
// disable logs from controller
if (!logLevel.isEmpty()) {
System.setProperty(Properties.CONTROLLER_LOG_LEVEL, logLevel);
}
reconfigureLogging(invocation);
Controller controller = factory.start(rootDir == null ? null : ((FileResource) rootDir).getFile().toPath());
ctx.setLocalControllerHost(controller.host());
ctx.setLocalControllerPort(controller.port());
if (!quiet) {
invocation.println("Controller started, listening on " + controller.host() + ":" + controller.port());
}
ctx.addCleanup(controller::stop);
}
if (!quiet) {
invocation.println("Connecting to the controller...");
}
if (ctx.client() != null) {
ctx.client().close();
}
connect(invocation, quiet, ctx.localControllerHost(), ctx.localControllerPort(), false, false, null);
return CommandResult.SUCCESS;
}
private void reconfigureLogging(HyperfoilCommandInvocation invocation) {
try {
LoggerContext context = ((Logger) LogManager.getLogger(getClass())).getContext();
InputStream configStream = getClass().getClassLoader().getResourceAsStream("log4j2-local-controller.xml");
context.setConfiguration(new XmlConfiguration(context, new ConfigurationSource(configStream)));
} catch (IOException e) {
invocation.error("Failed to set logger configuration");
invocation.error(e);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/WrkAbstract.java | cli/src/main/java/io/hyperfoil/cli/commands/WrkAbstract.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.commands;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.HdrHistogram.AbstractHistogram;
import org.HdrHistogram.HistogramIterationValue;
import org.aesh.command.Command;
import org.aesh.command.CommandResult;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Option;
import org.aesh.command.option.OptionGroup;
import org.aesh.command.option.OptionList;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.api.config.BenchmarkBuilder;
import io.hyperfoil.api.config.PhaseBuilder;
import io.hyperfoil.api.statistics.StatisticsSummary;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClient;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.HistogramConverter;
import io.hyperfoil.controller.model.RequestStatisticsResponse;
import io.hyperfoil.controller.model.RequestStats;
import io.hyperfoil.core.handlers.TransferSizeRecorder;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.statistics.HttpStats;
import io.hyperfoil.impl.Util;
public abstract class WrkAbstract extends BaseStandaloneCommand {
// @CommandDefinition(name = "wrk", description = "Runs a workload simulation against one endpoint using the same vm")
public abstract class AbstractWrkCommand implements Command<HyperfoilCommandInvocation> {
@Option(shortName = 'c', description = "Total number of HTTP connections to keep open", defaultValue = "10")
int connections;
@Option(shortName = 'd', description = "Duration of the test, e.g. 2s, 2m, 2h", defaultValue = "10s")
String duration;
@Option(shortName = 't', description = "Total number of threads to use.", defaultValue = "2")
int threads;
@Option(shortName = 's', description = "!!!NOT SUPPORTED: LuaJIT script")
String script;
@Option(shortName = 'h', hasValue = false, overrideRequired = true)
boolean help;
@OptionList(shortName = 'H', name = "header", description = "HTTP header to add to request, e.g. \"User-Agent: wrk\"")
List<String> headers;
@Option(description = "Print detailed latency statistics", hasValue = false)
boolean latency;
@Option(description = "Record a timeout if a response is not received within this amount of time.", defaultValue = "60s")
String timeout;
@OptionGroup(shortName = 'A', description = "Inline definition of agent executing the test. By default assuming non-clustered mode.")
Map<String, String> agent;
@Option(name = "enable-http2", description = "HTTP2 is not supported in wrk/wrk2: you can enable that for Hyperfoil.", defaultValue = "false")
boolean enableHttp2;
@Option(name = "use-http-cache", description = "By default the HTTP cache is disabled, providing this option you can enable it.", hasValue = false)
boolean useHttpCache;
@Argument(description = "URL that should be accessed", required = true)
String url;
String path;
String[][] parsedHeaders;
boolean started = false;
boolean initialized = false;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) {
if (help) {
invocation.println(invocation.getHelpInfo(getCommandName()));
return CommandResult.SUCCESS;
}
if (script != null) {
invocation.println("Scripting is not supported at this moment.");
}
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
invocation.println("Failed to parse URL: " + e.getMessage());
return CommandResult.FAILURE;
}
path = uri.getPath();
if (path == null || path.isEmpty()) {
path = "/";
}
if (uri.getQuery() != null) {
path = path + "?" + uri.getQuery();
}
if (uri.getFragment() != null) {
path = path + "#" + uri.getFragment();
}
if (headers != null) {
parsedHeaders = new String[headers.size()][];
for (int i = 0; i < headers.size(); i++) {
String h = headers.get(i);
int colonIndex = h.indexOf(':');
if (colonIndex < 0) {
invocation.println(String.format("Cannot parse header '%s', ignoring.", h));
continue;
}
String header = h.substring(0, colonIndex).trim();
String value = h.substring(colonIndex + 1).trim();
parsedHeaders[i] = new String[] { header, value };
}
} else {
parsedHeaders = null;
}
Protocol protocol = Protocol.fromScheme(uri.getScheme());
// @formatter:off
BenchmarkBuilder builder = BenchmarkBuilder.builder()
.name(getCommandName())
.addPlugin(HttpPluginBuilder::new)
.ergonomics()
.repeatCookies(false)
.userAgentFromSession(false)
.endErgonomics()
.http()
.protocol(protocol).host(uri.getHost()).port(protocol.portOrDefault(uri.getPort()))
.allowHttp2(enableHttp2)
.sharedConnections(connections)
.useHttpCache(useHttpCache)
.endHttp()
.endPlugin()
.threads(this.threads);
// @formatter:on
if (agent != null) {
for (Map.Entry<String, String> agent : agent.entrySet()) {
Map<String, String> properties = Stream.of(agent.getValue().split(","))
.map(property -> {
String[] pair = property.split("=", 2);
if (pair.length != 2) {
throw new IllegalArgumentException("Cannot parse " + property
+ " as a property: Agent should be formatted as -AagentName=key1=value1,key2=value2...");
}
return pair;
})
.collect(Collectors.toMap(keyValue -> keyValue[0], keyValue -> keyValue[1]));
builder.addAgent(agent.getKey(), null, properties);
}
}
addPhase(builder, PhaseType.calibration, "6s");
// We can start only after calibration has full completed because otherwise some sessions
// would not have connection available from the beginning.
addPhase(builder, PhaseType.test, duration)
.startAfterStrict(PhaseType.calibration.name())
.maxDuration(Util.parseToMillis(duration));
RestClient client = invocation.context().client();
if (client == null) {
invocation.println("You're not connected to a controller; either " + ANSI.BOLD + "connect" + ANSI.BOLD_OFF
+ " to running instance or use " + ANSI.BOLD + "start-local" + ANSI.BOLD_OFF
+ " to start a controller in this VM");
return CommandResult.FAILURE;
}
Client.BenchmarkRef benchmark = client.register(builder.build(), null);
invocation.context().setServerBenchmark(benchmark);
Client.RunRef run = benchmark.start(null, Collections.emptyMap());
invocation.context().setServerRun(run);
boolean result = awaitBenchmarkResult(run, invocation);
if (result) {
if (!started && !run.get().errors.isEmpty()) {
// here the benchmark simulation did not start, it failed during initialization
// print the error that is returned by the controller, e.g., cannot connect
invocation.println("ERROR: " + String.join(", ", run.get().errors));
return CommandResult.FAILURE;
}
RequestStatisticsResponse total = run.statsTotal();
RequestStats testStats = total.statistics.stream().filter(rs -> PhaseType.test.name().equals(rs.phase))
.findFirst().orElseThrow(() -> new IllegalStateException("Error running command: Missing Statistics"));
AbstractHistogram histogram = HistogramConverter
.convert(run.histogram(testStats.phase, testStats.stepId, testStats.metric));
List<StatisticsSummary> series = run.series(testStats.phase, testStats.stepId, testStats.metric);
printStats(testStats.summary, histogram, series, invocation);
return CommandResult.SUCCESS;
} else {
return CommandResult.FAILURE;
}
}
private boolean awaitBenchmarkResult(Client.RunRef run, HyperfoilCommandInvocation invocation) {
while (true) {
RequestStatisticsResponse recent = run.statsRecent();
if ("TERMINATED".equals(recent.status)) {
break;
} else if ("INITIALIZING".equals(recent.status) && !initialized) {
initialized = true;
} else if ("RUNNING".equals(recent.status) && !started) {
// here the benchmark simulation started, so we can print wrk/wrk2 messages
invocation.println("Running " + duration + " test @ " + url);
invocation.println(" " + threads + " threads and " + connections + " connections");
started = true;
// if started, it is also initialized
// this ensure initialized is set to true if for some reason we did not catch the "INITIALIZING" status
initialized = true;
}
invocation.getShell().write(ANSI.CURSOR_START);
invocation.getShell().write(ANSI.ERASE_WHOLE_LINE);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
invocation.println("Interrupt received, trying to abort run...");
run.kill();
return false;
}
}
return true;
}
protected abstract PhaseBuilder<?> phaseConfig(PhaseBuilder.Catalog catalog, PhaseType phaseType, long durationMs);
public enum PhaseType {
calibration,
test
}
private PhaseBuilder<?> addPhase(BenchmarkBuilder benchmarkBuilder, PhaseType phaseType, String durationStr) {
// prevent capturing WrkCommand in closure
String[][] parsedHeaders = this.parsedHeaders;
long duration = Util.parseToMillis(durationStr);
// @formatter:off
var scenarioBuilder = phaseConfig(benchmarkBuilder.addPhase(phaseType.name()), phaseType, duration)
.duration(duration)
.maxDuration(duration + Util.parseToMillis(timeout))
.scenario();
// even with pipelining or HTTP 2 multiplexing
// each session lifecycle requires to fully complete (with response)
// before being reused, hence the number of requests which can use is just 1
scenarioBuilder.maxRequests(1);
// same reasoning here: given that the default concurrency of sequence is 0 for initialSequences
// and there's a single sequence too, there's no point to have more than 1 per session
scenarioBuilder.maxSequences(1);
return scenarioBuilder
.initialSequence("request")
.step(SC).httpRequest(HttpMethod.GET)
.path(path)
.headerAppender((session, request) -> {
if (parsedHeaders != null) {
for (String[] header : parsedHeaders) {
request.putHeader(header[0], header[1]);
}
}
})
.timeout(timeout)
.handler()
.rawBytes(new TransferSizeRecorder("transfer"))
.endHandler()
.endStep()
.endSequence()
.endScenario();
// @formatter:on
}
private void printStats(StatisticsSummary stats, AbstractHistogram histogram, List<StatisticsSummary> series,
CommandInvocation invocation) {
TransferSizeRecorder.Stats transferStats = (TransferSizeRecorder.Stats) stats.extensions.get("transfer");
HttpStats httpStats = HttpStats.get(stats);
double durationSeconds = (stats.endTime - stats.startTime) / 1000d;
invocation.println(String.format(" Thread Stats%6s%11s%8s%12s", "Avg", "Stdev", "Max", "+/- Stdev"));
invocation.println(" Latency " +
Util.prettyPrintNanos(stats.meanResponseTime, "6", false) +
Util.prettyPrintNanos((long) histogram.getStdDeviation(), "8", false) +
Util.prettyPrintNanos(stats.maxResponseTime, "7", false) +
String.format("%8.2f%%", statsWithinStdev(stats, histogram)));
// Note: wrk samples #requests every 100 ms, Hyperfoil every 1s
DoubleSummaryStatistics requestsStats = series.stream().mapToDouble(s -> s.requestCount).summaryStatistics();
double requestsStdDev = !series.isEmpty() ? Math.sqrt(
series.stream().mapToDouble(s -> Math.pow(s.requestCount - requestsStats.getAverage(), 2)).sum() / series.size())
: 0;
invocation.println(" Req/Sec " +
String.format("%6.2f ", requestsStats.getAverage()) +
String.format("%8.2f ", requestsStdDev) +
String.format("%7.2f ", requestsStats.getMax()) +
String.format("%8.2f", statsWithinStdev(requestsStats, requestsStdDev,
series.stream().mapToInt(s -> s.requestCount), series.size())));
if (latency) {
invocation.println(" Latency Distribution");
for (double percentile : Arrays.asList(50.0, 75.0, 90.0, 99.0, 99.9, 99.99, 99.999, 100.0)) {
invocation.println(String.format(" %7.3f%%", percentile) + " "
+ Util.prettyPrintNanos(histogram.getValueAtPercentile(percentile), "9", false));
}
invocation.println("");
invocation.println(" Detailed Percentile Spectrum");
histogram.outputPercentileDistribution(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
invocation.print(String.valueOf((char) b));
}
}), 5, 1000_000.0);
invocation.println("----------------------------------------------------------");
}
invocation.println(" " + stats.requestCount + " requests in " + durationSeconds + "s, "
+ Util.prettyPrintData(transferStats.sent + transferStats.received) + " read");
invocation.println("Requests/sec: " + String.format("%.02f", stats.requestCount / durationSeconds));
invocation.println(
"Transfer/sec: " + Util.prettyPrintData((transferStats.sent + transferStats.received) / durationSeconds));
if (stats.connectionErrors + stats.requestTimeouts + stats.internalErrors > 0) {
invocation.println(
"Socket errors: connectionErrors " + stats.connectionErrors + ", requestTimeouts " + stats.requestTimeouts);
}
if (httpStats.status_4xx + httpStats.status_5xx + httpStats.status_other > 0) {
invocation.println(
"Non-2xx or 3xx responses: " + (httpStats.status_4xx + httpStats.status_5xx + httpStats.status_other));
}
}
private double statsWithinStdev(DoubleSummaryStatistics stats, double stdDev, IntStream stream, int count) {
double lower = stats.getAverage() - stdDev;
double upper = stats.getAverage() + stdDev;
return 100d * stream.filter(reqs -> reqs >= lower && reqs <= upper).count() / count;
}
private double statsWithinStdev(StatisticsSummary stats, AbstractHistogram histogram) {
double stdDev = histogram.getStdDeviation();
double lower = stats.meanResponseTime - stdDev;
double upper = stats.meanResponseTime + stdDev;
long sum = 0;
for (var it = histogram.allValues().iterator(); it.hasNext();) {
HistogramIterationValue value = it.next();
if (value.getValueIteratedFrom() >= lower && value.getValueIteratedTo() <= upper) {
sum += value.getCountAddedInThisIterationStep();
}
}
return 100d * sum / stats.requestCount;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/HostCompleter.java | cli/src/main/java/io/hyperfoil/cli/commands/HostCompleter.java | package io.hyperfoil.cli.commands;
public class HostCompleter extends HyperfoilOptionCompleter {
public HostCompleter() {
super(context -> context.suggestedControllerHosts().stream());
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Wrk.java | cli/src/main/java/io/hyperfoil/cli/commands/Wrk.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.commands;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import io.hyperfoil.api.config.PhaseBuilder;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
public class Wrk extends WrkAbstract {
private static final String CMD = "wrk";
public static void main(String[] args) {
Wrk wrk = new Wrk();
wrk.exec(args);
}
@Override
protected String getCommandName() {
return CMD;
}
@Override
protected Class<? extends Command<HyperfoilCommandInvocation>> getCommand() {
return WrkCommand.class;
}
@CommandDefinition(name = CMD, description = "Runs a workload simulation against one endpoint using the same vm")
public class WrkCommand extends WrkAbstract.AbstractWrkCommand {
@Override
protected PhaseBuilder<?> phaseConfig(PhaseBuilder.Catalog catalog, PhaseType phaseType, long durationMs) {
// there's no need of sessions != connections
return catalog.always(connections);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Version.java | cli/src/main/java/io/hyperfoil/cli/commands/Version.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
@CommandDefinition(name = "version", description = "Provides server/client information.")
public class Version extends ServerCommand {
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
ensureConnection(invocation);
try {
io.hyperfoil.controller.model.Version serverVersion = invocation.context().client().version();
invocation.println("Server: " + serverVersion.version + ", " + serverVersion.commitId);
} catch (RestClientException e) {
invocation.println("Server: unknown");
}
invocation.println("Client: " + io.hyperfoil.api.Version.VERSION + ", " + io.hyperfoil.api.Version.COMMIT_ID);
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BaseRunIdCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BaseRunIdCommand.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandException;
import org.aesh.command.option.Argument;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
public abstract class BaseRunIdCommand extends ServerCommand {
@Argument(description = "ID of the run", completer = RunCompleter.class)
private String runId;
protected Client.RunRef getRunRef(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
Client.RunRef runRef;
if (runId == null || runId.isEmpty()) {
runRef = invocation.context().serverRun();
if (runRef == null) {
failMissingRunId(invocation);
}
} else {
runRef = invocation.context().client().run(runId);
invocation.context().setServerRun(runRef);
}
return runRef;
}
protected io.hyperfoil.controller.model.Run getRun(HyperfoilCommandInvocation invocation, Client.RunRef runRef)
throws CommandException {
io.hyperfoil.controller.model.Run run;
try {
return runRef.get();
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Cannot fetch run " + runRef.id(), e);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Export.java | cli/src/main/java/io/hyperfoil/cli/commands/Export.java | package io.hyperfoil.cli.commands;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import org.aesh.io.Resource;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "export", description = "Export run statistics.")
public class Export extends BaseExportCommand {
@Option(shortName = 'd', description = "Target file/directory for the output", required = true, askIfNotSet = true)
public Resource destination;
@Option(shortName = 'y', description = "Assume yes for all interactive questions.", hasValue = false)
public boolean assumeYes;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
ensureConnection(invocation);
Client.RunRef runRef = getRunRef(invocation);
String acceptFormat = getAcceptFormat();
String defaultFilename = getDefaultFilename(runRef);
destination = CliUtil.sanitize(destination);
String destinationFile = destination.toString();
if (destination.isDirectory()) {
destinationFile = destination + File.separator + defaultFilename;
}
if (destination.exists() && !assumeYes) {
invocation.print("File " + destinationFile + " already exists, override? [y/N]: ");
if (!readYes(invocation)) {
invocation.println("Export cancelled.");
return CommandResult.SUCCESS;
}
}
byte[] bytes = runRef.statsAll(acceptFormat);
try {
Files.write(Paths.get(destinationFile), bytes);
} catch (IOException e) {
invocation.error("Failed to write stats into " + destinationFile);
}
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Stats.java | cli/src/main/java/io/hyperfoil/cli/commands/Stats.java | package io.hyperfoil.cli.commands;
import java.util.Map;
import java.util.stream.Stream;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.api.statistics.StatsExtension;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.RequestStatisticsResponse;
import io.hyperfoil.controller.model.RequestStats;
import io.hyperfoil.http.statistics.HttpStats;
@CommandDefinition(name = "stats", description = "Show run statistics")
public class Stats extends BaseRunIdCommand {
private static final Table<RequestStats> REQUEST_STATS_TABLE = new Table<RequestStats>()
.idColumns(2)
.rowPrefix(r -> r.failedSLAs.isEmpty() ? null : ANSI.RED_TEXT)
.rowSuffix(r -> ANSI.RESET)
.column("PHASE", r -> r.phase)
.column("METRIC", r -> r.metric)
.column("THROUGHPUT", Stats::throughput, Table.Align.RIGHT)
.columnInt("REQUESTS", r -> r.summary.requestCount)
.columnNanos("MEAN", r -> r.summary.meanResponseTime)
.columnNanos("STD_DEV", r -> r.summary.stdDevResponseTime)
.columnNanos("MAX", r -> r.summary.maxResponseTime)
.columnNanos("p50", r -> r.summary.percentileResponseTime.get(50d))
.columnNanos("p90", r -> r.summary.percentileResponseTime.get(90d))
.columnNanos("p99", r -> r.summary.percentileResponseTime.get(99d))
.columnNanos("p99.9", r -> r.summary.percentileResponseTime.get(99.9))
.columnNanos("p99.99", r -> r.summary.percentileResponseTime.get(99.99))
.columnInt("TIMEOUTS", r -> r.summary.requestTimeouts)
.columnInt("ERRORS", r -> r.summary.connectionErrors + r.summary.internalErrors)
.columnNanos("BLOCKED", r -> r.summary.blockedTime);
private static final String[] DIRECT_EXTENSIONS = { HttpStats.HTTP };
@Option(shortName = 't', description = "Show total stats instead of recent.", hasValue = false)
private boolean total;
@Option(shortName = 'e', description = "Show extensions for given key. Use 'all' or '*' to show all extensions not shown by default, or comma-separated list.", completer = ExtensionsCompleter.class)
private String extensions;
@Option(shortName = 'w', description = "Include statistics from warmup phases.", hasValue = false)
private boolean warmup;
private static String throughput(RequestStats r) {
if (r.summary.endTime <= r.summary.startTime) {
return "<none>";
} else {
double rate = 1000d * r.summary.responseCount / (r.summary.endTime - r.summary.startTime);
if (rate < 10_000) {
return String.format("%.2f req/s", rate);
} else if (rate < 10_000_000) {
return String.format("%.2fk req/s", rate / 1000);
} else {
return String.format("%.2fM req/s", rate / 1000_000);
}
}
}
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
Client.RunRef runRef = getRunRef(invocation);
boolean terminated = false;
int prevLines = -2;
for (;;) {
RequestStatisticsResponse stats;
try {
stats = total ? runRef.statsTotal() : runRef.statsRecent();
} catch (RestClientException e) {
if (e.getCause() instanceof InterruptedException) {
clearLines(invocation, 1);
invocation.println("");
break;
}
invocation.error(e);
throw new CommandException("Cannot fetch stats for run " + runRef.id(), e);
}
if ("TERMINATED".equals(stats.status)) {
// There are no (recent) stats, the run has probably terminated
stats = runRef.statsTotal();
terminated = true;
}
clearLines(invocation, prevLines + 2);
if (total || terminated) {
invocation.println("Total stats from run " + runRef.id());
} else {
invocation.println("Recent stats from run " + runRef.id());
}
if (extensions == null || extensions.isEmpty()) {
prevLines = showGeneralStats(invocation, stats);
} else {
prevLines = showExtensions(invocation, stats);
}
if (terminated || interruptibleDelay(invocation)) {
break;
}
}
return CommandResult.SUCCESS;
}
private int showGeneralStats(HyperfoilCommandInvocation invocation, RequestStatisticsResponse stats) {
int prevLines = 0;
String[] extensions = extensions(stats).toArray(String[]::new);
if (extensions.length > 0) {
invocation.print("Extensions (use -e to show): ");
invocation.println(String.join(", ", extensions));
prevLines++;
}
Table<RequestStats> table = new Table<>(REQUEST_STATS_TABLE);
addDirectExtensions(stats, table);
prevLines += table.print(invocation, stream(stats));
for (RequestStats rs : stats.statistics) {
if (rs.isWarmup && !warmup)
continue;
for (String msg : rs.failedSLAs) {
invocation.println(String.format("%s/%s: %s", rs.phase, rs.metric == null ? "*" : rs.metric, msg));
prevLines++;
}
}
return prevLines;
}
private Stream<RequestStats> stream(RequestStatisticsResponse stats) {
Stream<RequestStats> stream = stats.statistics.stream();
if (!warmup) {
stream = stream.filter(rs -> !rs.isWarmup);
}
return stream;
}
private int showExtensions(HyperfoilCommandInvocation invocation, RequestStatisticsResponse stats) {
Table<RequestStats> table = new Table<RequestStats>().idColumns(2);
table.column("PHASE", r -> r.phase).column("METRIC", r -> r.metric);
if (extensions.equalsIgnoreCase("all") || extensions.equals("*")) {
extensions(stats).flatMap(ext -> stream(stats).flatMap(rs -> {
StatsExtension extension = rs.summary.extensions.get(ext);
return extension == null ? Stream.empty() : Stream.of(extension.headers()).map(h -> Map.entry(ext, h));
})).distinct().forEach(extHeader -> table.column(extHeader.getKey() + "." + extHeader.getValue(),
rs -> rs.summary.extensions.get(extHeader.getKey()).byHeader(extHeader.getValue()), Table.Align.RIGHT));
} else if (!extensions.contains(",")) {
stream(stats).flatMap(rs -> {
StatsExtension extension = rs.summary.extensions.get(extensions);
return extension == null ? Stream.empty() : Stream.of(extension.headers());
}).distinct().forEach(
header -> table.column(header, rs -> rs.summary.extensions.get(extensions).byHeader(header), Table.Align.RIGHT));
} else {
String[] exts = extensions.split(",");
stream(stats).flatMap(rs -> Stream.of(exts).flatMap(ext -> {
StatsExtension extension = rs.summary.extensions.get(ext);
return extension == null ? Stream.empty() : Stream.of(extension.headers()).map(h -> Map.entry(ext, h));
})).distinct().forEach(extHeader -> table.column(extHeader.getKey() + "." + extHeader.getValue(),
rs -> rs.summary.extensions.get(extHeader.getKey()).byHeader(extHeader.getValue()), Table.Align.RIGHT));
}
return table.print(invocation, stream(stats));
}
private static Stream<String> extensions(RequestStatisticsResponse stats) {
return stats.statistics.stream().flatMap(rs -> rs.summary.extensions.keySet().stream())
.sorted().distinct().filter(ext -> Stream.of(DIRECT_EXTENSIONS).noneMatch(de -> de.equals(ext)));
}
private void addDirectExtensions(RequestStatisticsResponse stats, Table<RequestStats> table) {
boolean hasHttp = stream(stats).anyMatch(rs -> rs.summary.extensions.containsKey(HttpStats.HTTP));
if (hasHttp) {
table.columnInt("2xx", r -> HttpStats.get(r.summary).status_2xx)
.columnInt("3xx", r -> HttpStats.get(r.summary).status_3xx)
.columnInt("4xx", r -> HttpStats.get(r.summary).status_4xx)
.columnInt("5xx", r -> HttpStats.get(r.summary).status_5xx)
.columnInt("CACHE", r -> HttpStats.get(r.summary).cacheHits);
}
}
public static class ExtensionsCompleter extends HyperfoilOptionCompleter {
public ExtensionsCompleter() {
super(context -> {
if (context.serverRun() == null) {
return Stream.empty();
}
return Stream.concat(extensions(context.serverRun().statsTotal()), Stream.of("all"));
});
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BaseExportCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/BaseExportCommand.java | package io.hyperfoil.cli.commands;
import java.util.stream.Stream;
import org.aesh.command.CommandException;
import org.aesh.command.completer.CompleterInvocation;
import org.aesh.command.completer.OptionCompleter;
import org.aesh.command.option.Option;
import io.hyperfoil.controller.Client;
public abstract class BaseExportCommand extends BaseRunIdCommand {
@Option(shortName = 'f', description = "Format in which should the statistics exported. Options are JSON (default) and CSV.", defaultValue = "JSON", completer = FormatCompleter.class)
public String format;
protected String getDefaultFilename(Client.RunRef runRef) throws CommandException {
switch (format.toUpperCase()) {
case "JSON":
return runRef.id() + ".json";
case "CSV":
return runRef.id() + ".zip";
default:
throw new CommandException("Unknown format '" + format + "', please use JSON or CSV");
}
}
protected String getAcceptFormat() throws CommandException {
switch (format.toUpperCase()) {
case "JSON":
return "application/json";
case "CSV":
return "application/zip";
default:
throw new CommandException("Unknown format '" + format + "', please use JSON or CSV");
}
}
public static class FormatCompleter implements OptionCompleter<CompleterInvocation> {
@Override
public void complete(CompleterInvocation completerInvocation) {
Stream<String> formats = Stream.of("JSON", "CSV");
String prefix = completerInvocation.getGivenCompleteValue();
if (prefix != null) {
formats = formats.filter(b -> b.startsWith(prefix));
}
formats.forEach(completerInvocation::addCompleterValue);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Forget.java | cli/src/main/java/io/hyperfoil/cli/commands/Forget.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "forget", description = "Removes benchmark from controller.")
public class Forget extends BenchmarkCommand {
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
Client.BenchmarkRef benchmarkRef = ensureBenchmark(invocation);
try {
if (benchmarkRef.forget()) {
invocation.println("Benchmark " + benchmarkRef.name() + " was deleted.");
return CommandResult.SUCCESS;
} else {
invocation.error("Cannot find benchmark " + benchmarkRef.name());
return CommandResult.FAILURE;
}
} catch (RestClientException e) {
invocation.error(e);
return CommandResult.FAILURE;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Shutdown.java | cli/src/main/java/io/hyperfoil/cli/commands/Shutdown.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
@CommandDefinition(name = "shutdown", description = "Terminate the controller")
public class Shutdown extends ServerCommand {
@Option(description = "If true, terminate even if a run is in progress.")
public boolean force;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
invocation.context().client().shutdown(force);
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/BenchmarkCompleter.java | cli/src/main/java/io/hyperfoil/cli/commands/BenchmarkCompleter.java | package io.hyperfoil.cli.commands;
import java.util.stream.Stream;
public class BenchmarkCompleter extends ServerOptionCompleter {
public BenchmarkCompleter() {
super(client -> Stream.concat(client.benchmarks().stream(), client.templates().stream()));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Run.java | cli/src/main/java/io/hyperfoil/cli/commands/Run.java | package io.hyperfoil.cli.commands;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.api.config.BenchmarkData;
import io.hyperfoil.api.config.BenchmarkDefinitionException;
import io.hyperfoil.api.config.BenchmarkSource;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.core.impl.ProvidedBenchmarkData;
import io.hyperfoil.core.parser.BenchmarkParser;
import io.hyperfoil.core.parser.ParserException;
@CommandDefinition(name = "run", description = "Starts benchmark on Hyperfoil Controller server")
public class Run extends ParamsCommand {
@Option(shortName = 'd', description = "Run description")
String description;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
// the implementation, by default, is empty as the benchmark should be loaded using upload cmd
setup(invocation);
Client.BenchmarkRef benchmarkRef = ensureBenchmark(invocation);
Map<String, String> currentParams = getParams(invocation);
try {
Client.BenchmarkSource benchmarkSource = benchmarkRef.source();
String yaml = benchmarkSource != null ? benchmarkSource.source : null;
if (yaml != null) {
ProvidedBenchmarkData data = new ProvidedBenchmarkData();
data.ignoredFiles.addAll(benchmarkSource.files);
BenchmarkSource source = BenchmarkParser.instance().createSource(yaml, data);
List<String> missingParams = getMissingParams(source.paramsWithDefaults, currentParams);
if (!readParams(invocation, missingParams, currentParams)) {
return CommandResult.FAILURE;
}
if (source.isTemplate()) {
boolean firstMissing = true;
for (;;) {
try {
BenchmarkParser.instance().buildBenchmark(source, currentParams);
if (!data.files().isEmpty()) {
invocation.context().client().register(yaml, data.files(), benchmarkSource.version,
benchmarkRef.name());
}
break;
} catch (BenchmarkData.MissingFileException e) {
if (firstMissing) {
firstMissing = false;
invocation.println("This benchmark template is missing some files.");
}
if (!onMissingFile(invocation, e.file, data)) {
return CommandResult.FAILURE;
}
}
}
}
}
} catch (RestClientException e) {
invocation.error("Failed to retrieve source for benchmark " + benchmarkRef.name(), e);
} catch (ParserException | BenchmarkDefinitionException e) {
invocation.error("Failed to parse retrieved source for benchmark " + benchmarkRef.name(), e);
return CommandResult.FAILURE;
}
invocation.context().setCurrentParams(currentParams);
try {
invocation.context().setServerRun(benchmarkRef.start(description, currentParams));
invocation.println("Started run " + invocation.context().serverRun().id());
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Failed to start benchmark " + benchmarkRef.name(), e);
}
monitor(invocation);
return CommandResult.SUCCESS;
}
protected void setup(HyperfoilCommandInvocation invocation) throws CommandException {
// nothing to do as the benchmark should be already loaded when running
// Run command in CLI mode
}
protected void monitor(HyperfoilCommandInvocation invocation) throws CommandException {
invocation.executeSwitchable("status");
}
protected boolean onMissingFile(HyperfoilCommandInvocation invocation, String file, ProvidedBenchmarkData data) {
try {
Path path = CliUtil.getLocalFileForUpload(invocation, file);
// if user does not provide uploaded file we will still run it and let the server fail
if (path != null) {
data.files.put(file, Files.readAllBytes(path));
} else {
data.ignoredFiles.add(file);
}
return true;
} catch (InterruptedException interruptedException) {
invocation.warn("Cancelled, not running anything.");
return false;
} catch (IOException ioException) {
invocation.error("Cannot load " + file, ioException);
return false;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Wait.java | cli/src/main/java/io/hyperfoil/cli/commands/Wait.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.RequestStatisticsResponse;
@CommandDefinition(name = "wait", description = "Wait for a specific run termination.")
public class Wait extends BaseRunIdCommand {
private boolean started = false;
private boolean terminated = false;
private boolean persisted = false;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
Client.RunRef runRef = getRunRef(invocation);
io.hyperfoil.controller.model.Run run = getRun(invocation, runRef);
invocation.println("Monitoring run " + runRef.id() + ", benchmark " + runRef.benchmark().name());
if (run.description != null) {
invocation.println(run.description);
}
for (;;) {
RequestStatisticsResponse recent = runRef.statsRecent();
// check if started
if (!started && "RUNNING".equals(recent.status)) {
started = true;
run = runRef.get();
invocation.println("Started: " + DATE_FORMATTER.format(run.started));
}
// check if terminated
if (!terminated && "TERMINATED".equals(recent.status)) {
terminated = true;
run = runRef.get();
invocation.println("Terminated: " + DATE_FORMATTER.format(run.terminated));
if (!run.errors.isEmpty()) {
invocation.println(ANSI.RED_TEXT + ANSI.BOLD + "Errors:" + ANSI.RESET);
for (String error : run.errors) {
invocation.println(error);
}
}
invocation.context().notifyRunCompleted(run);
}
// right now if for some reason the run.persisted is not set to true, the process will wait forever.
// TODO: we could implement a timeout to be safe
if (terminated && !persisted) {
run = runRef.get();
// this monitoring will guarantee that if we try to run the report, the all.json is already persisted
if (run.persisted) {
persisted = true;
invocation.println("Run statistics persisted in the local filesystem");
return CommandResult.SUCCESS;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
invocation.error(e);
throw new CommandException("Cannot monitor run " + runRef.id(), e);
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/ParamsCommand.java | cli/src/main/java/io/hyperfoil/cli/commands/ParamsCommand.java | package io.hyperfoil.cli.commands;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.aesh.command.option.Option;
import org.aesh.command.option.OptionGroup;
import org.aesh.command.option.OptionList;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
public abstract class ParamsCommand extends BenchmarkCommand {
// TODO: empty and null params don't work with current version of Aesh but the fix is on the way...
@OptionGroup(name = "param", shortName = 'P', description = "Parameters in case the benchmark is a template. " +
"Can be set multiple times. Use `-PFOO=` to set the parameter to empty value and `-PFOO` to remove it " +
"and use default if available.")
Map<String, String> params;
@OptionList(name = "empty-params", shortName = 'E', description = "Template parameters that should be set to empty string.")
List<String> emptyParams;
@Option(name = "reset-params", shortName = 'r', description = "Reset all parameters in context.", hasValue = false)
boolean resetParams;
protected Map<String, String> getParams(HyperfoilCommandInvocation invocation) {
Map<String, String> currentParams = resetParams ? new HashMap<>() : new HashMap<>(invocation.context().currentParams());
if (resetParams) {
invocation.context().setCurrentParams(Collections.emptyMap());
}
if (params != null) {
params.forEach((key, value) -> {
if (value == null) {
currentParams.remove(key);
} else {
currentParams.put(key, value);
}
});
}
if (emptyParams != null) {
emptyParams.forEach(param -> currentParams.put(param, ""));
}
return currentParams;
}
protected boolean readParams(HyperfoilCommandInvocation invocation, List<String> missingParams,
Map<String, String> currentParams) {
if (!missingParams.isEmpty()) {
invocation.println("This benchmark is a template with these mandatory parameters that haven't been set:");
}
for (String param : missingParams) {
invocation.print(param + ": ");
try {
currentParams.put(param, invocation.getShell().readLine());
} catch (InterruptedException e) {
return false;
}
}
return true;
}
protected List<String> getMissingParams(Map<String, String> paramsWithDefaults, Map<String, String> currentParams) {
return paramsWithDefaults.entrySet().stream()
.filter(entry -> entry.getValue() == null)
.map(Map.Entry::getKey)
.filter(p -> !currentParams.containsKey(p))
.collect(Collectors.toList());
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Report.java | cli/src/main/java/io/hyperfoil/cli/commands/Report.java | package io.hyperfoil.cli.commands;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "report", description = "Generate HTML report")
public class Report extends BaseRunIdCommand {
@Option(shortName = 's', description = "Other file (in given run) to use as report input.")
protected String source;
@Option(shortName = 'd', description = "Destination path to the HTML report", required = true, askIfNotSet = true)
private String destination;
@Option(shortName = 'y', description = "Assume yes for all interactive questions.", hasValue = false)
public boolean assumeYes;
@Option(description = "Do not open the HTML report automatically", hasValue = false)
public boolean silent;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
Client.RunRef runRef = getRunRef(invocation);
File destination = new File(this.destination);
if (destination.exists()) {
if (destination.isFile()) {
if (!askForOverwrite(invocation, destination)) {
invocation.println("Cancelled. You can change destination file with '-d /path/to/report.html'");
return CommandResult.SUCCESS;
}
} else if (destination.isDirectory()) {
destination = destination.toPath().resolve(runRef.id() + ".html").toFile();
if (destination.exists()) {
if (destination.isFile()) {
if (!askForOverwrite(invocation, destination)) {
invocation.println("Cancelled. You can change destination file with '-d /path/to/report.html'");
return CommandResult.SUCCESS;
}
} else if (destination.isDirectory()) {
invocation.println(
"Both " + this.destination + " and " + destination + " are directories. Please use another path.");
return CommandResult.SUCCESS;
}
}
}
}
try {
byte[] report = runRef.report(source);
Files.write(destination.toPath(), report);
} catch (RestClientException e) {
invocation.error("Cannot fetch report for run " + runRef.id(), e);
return CommandResult.FAILURE;
} catch (IOException e) {
invocation.error("Cannot write to '" + destination + "': ", e);
return CommandResult.FAILURE;
}
invocation.println("Report written to " + destination);
if (!"true".equalsIgnoreCase(System.getenv("HYPERFOIL_CONTAINER")) && !silent) {
openInBrowser("file://" + destination);
}
return CommandResult.SUCCESS;
}
private boolean askForOverwrite(HyperfoilCommandInvocation invocation, File destination) {
if (assumeYes) {
return true;
}
invocation.print("File " + destination + " already exists, overwrite? [y/N]: ");
boolean overwrite = false;
try {
if (readYes(invocation)) {
overwrite = true;
}
} catch (InterruptedException e) {
// ignore
}
return overwrite;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Inspect.java | cli/src/main/java/io/hyperfoil/cli/commands/Inspect.java | package io.hyperfoil.cli.commands;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "inspect", description = "Show detailed structure of the benchmark.")
public class Inspect extends ParamsCommand {
@Option(name = "pager", shortName = 'p', description = "Pager used.")
private String pager;
@Option(name = "max-collection-size", shortName = 'm', description = "Maximum printed size for collections and arrays.")
private Integer maxCollectionSize;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
ensureConnection(invocation);
Client.BenchmarkRef benchmarkRef;
Client.BenchmarkStructure structure;
try {
benchmarkRef = ensureBenchmark(invocation);
structure = benchmarkRef.structure(maxCollectionSize, Collections.emptyMap());
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Cannot get benchmark " + benchmark);
}
if (structure.params != null && !structure.params.isEmpty()) {
invocation.println("Benchmark template '" + benchmarkRef.name() + "' has these parameters and default values:\n");
printTemplateParams(invocation, structure.params);
invocation.print("Do you want to display structure with a resolved template? [y/N]: ");
if (readYes(invocation)) {
Map<String, String> currentParams = getParams(invocation);
List<String> missingParams = getMissingParams(structure.params, currentParams);
if (!readParams(invocation, missingParams, currentParams)) {
return CommandResult.FAILURE;
}
try {
structure = benchmarkRef.structure(maxCollectionSize, currentParams);
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Cannot get benchmark " + benchmark);
}
invocation.context().setCurrentParams(currentParams);
}
}
if (structure.content != null) {
invocation.context().createPager(pager).open(invocation, structure.content, benchmark + "-structure-", ".yaml");
}
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Wrk2.java | cli/src/main/java/io/hyperfoil/cli/commands/Wrk2.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.commands;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.option.Option;
import io.hyperfoil.api.config.PhaseBuilder;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
public class Wrk2 extends WrkAbstract {
private static final String CMD = "wrk2";
public static void main(String[] args) {
Wrk2 wrk = new Wrk2();
wrk.exec(args);
}
@Override
protected String getCommandName() {
return CMD;
}
@Override
protected Class<? extends Command<HyperfoilCommandInvocation>> getCommand() {
return Wrk2Command.class;
}
@CommandDefinition(name = CMD, description = "Runs a workload simulation against one endpoint using the same vm")
public class Wrk2Command extends WrkAbstract.AbstractWrkCommand {
@Option(shortName = 'R', description = "Work rate (throughput)", required = true)
int rate;
@Override
protected PhaseBuilder<?> phaseConfig(PhaseBuilder.Catalog catalog, PhaseType phaseType, long durationMs) {
int durationSeconds = (int) Math.ceil(durationMs / 1000);
int maxSessions = switch (phaseType) {
// given that the duration of this phase is 6s seconds
// there's no point to have more than 6 * rate sessions
case calibration -> rate * durationSeconds;
case test -> rate * 15;
};
return catalog.constantRate(rate)
.variance(false)
.maxSessions(maxSessions);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/New.java | cli/src/main/java/io/hyperfoil/cli/commands/New.java | package io.hyperfoil.cli.commands;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.completer.CompleterInvocation;
import org.aesh.command.completer.OptionCompleter;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.controller.Client;
import io.hyperfoil.impl.Util;
@CommandDefinition(name = "new", description = "Creates a new benchmark")
public class New extends ServerCommand {
// Reading resource list from folder is too complicated, let's enumerate them here
private static final String[] TEMPLATES = new String[] { "constant", "throughput", "empty" };
@Option(shortName = 't', description = "Template used to set up the benchmark.", completer = TemplateCompleter.class)
public String template;
@Argument(description = "Name of the benchmark.", completer = BenchmarkCompleter.class)
public String benchmark;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
ensureConnection(invocation);
if (template == null) {
invocation.println("No template was specified, available templates: ");
invocation.println(" " + String.join(", ", TEMPLATES));
invocation.print("Please select a template or keep empty for 'empty' benchmark: ");
try {
template = invocation.inputLine();
if (template.isBlank()) {
template = "empty";
}
} catch (InterruptedException e) {
invocation.println("Cancelled, not creating any benchmark.");
return CommandResult.FAILURE;
}
}
if (!Arrays.asList(TEMPLATES).contains(template)) {
invocation.println("Template '" + template + "' is not available, please choose one of: ");
invocation.println(" " + String.join(", ", TEMPLATES));
return CommandResult.FAILURE;
}
HyperfoilCliContext ctx = invocation.context();
if (benchmark == null || benchmark.isEmpty()) {
invocation.println("Must specify benchmark name.");
invocation.println(invocation.getHelpInfo());
return CommandResult.FAILURE;
}
if (ctx.client().benchmark(benchmark).exists()) {
invocation.println("Benchmark " + benchmark + " already exists.");
return CommandResult.FAILURE;
}
ctx.setCurrentParams(Collections.emptyMap());
InputStream resourceStream = getClass().getResourceAsStream("/benchmark-templates/" + template + ".yaml");
if (resourceStream == null) {
invocation.error("Template " + template + " was not found");
return CommandResult.FAILURE;
}
try {
String yaml = Util.toString(resourceStream).replace("!param NAME", benchmark);
Client.BenchmarkRef benchmarkRef = ctx.client().register(yaml, Collections.emptyMap(), null, null);
ctx.setServerBenchmark(benchmarkRef);
} catch (IOException e) {
invocation.error(e);
return CommandResult.FAILURE;
}
try {
invocation.executeCommand("edit " + benchmark);
return CommandResult.SUCCESS;
} catch (Exception e) {
invocation.error("Cannot execute 'edit'", e);
return CommandResult.FAILURE;
}
}
public static class TemplateCompleter implements OptionCompleter<CompleterInvocation> {
@Override
public void complete(CompleterInvocation completerInvocation) {
String prefix = completerInvocation.getGivenCompleteValue();
for (String template : TEMPLATES) {
if (template.startsWith(prefix)) {
completerInvocation.addCompleterValue(template);
}
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Load.java | cli/src/main/java/io/hyperfoil/cli/commands/Load.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Argument;
import io.hyperfoil.cli.context.HyperfoilCliContext;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "load", description = "Registers a benchmark definition from a local path on the Hyperfoil Controller server")
public class Load extends ServerCommand {
@Argument(description = "YAML benchmark definition file URI", required = true)
String benchmarkResource;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException {
ensureConnection(invocation);
HyperfoilCliContext ctx = invocation.context();
try {
Client.BenchmarkRef benchmarkRef = ctx.client().registerLocal(benchmarkResource, null, null);
ctx.setServerBenchmark(benchmarkRef);
invocation.println("... done.");
return CommandResult.SUCCESS;
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Failed to load the benchmark.", e);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Kill.java | cli/src/main/java/io/hyperfoil/cli/commands/Kill.java | package io.hyperfoil.cli.commands;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.Phase;
@CommandDefinition(name = "kill", description = "Terminate run.")
public class Kill extends BaseRunIdCommand {
@Option(shortName = 'y', description = "Assume yes for all interactive questions.", hasValue = false)
public boolean assumeYes;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
Client.RunRef runRef = getRunRef(invocation);
io.hyperfoil.controller.model.Run run = runRef.get();
if (!assumeYes) {
invocation.print("Kill run " + run.id + ", benchmark " + run.benchmark);
int terminated = 0, finished = 0, running = 0;
for (Phase phase : run.phases) {
if ("TERMINATED".equals(phase.status)) {
terminated++;
} else if ("FINISHED".equals(phase.status)) {
finished++;
} else if ("RUNNING".equals(phase.status)) {
running++;
}
}
invocation
.print("(phases: " + running + " running, " + finished + " finished, " + terminated + " terminated) [y/N]: ");
if (!readYes(invocation)) {
invocation.println("Kill cancelled.");
return CommandResult.SUCCESS;
}
}
try {
runRef.kill();
} catch (RestClientException e) {
invocation.error(e);
throw new CommandException("Failed to kill run " + run.id, e);
}
invocation.println("Killed.");
return CommandResult.SUCCESS;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Help.java | cli/src/main/java/io/hyperfoil/cli/commands/Help.java | package io.hyperfoil.cli.commands;
import java.util.Comparator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandNotFoundException;
import org.aesh.command.CommandResult;
import org.aesh.command.completer.OptionCompleter;
import org.aesh.command.impl.internal.ProcessedCommand;
import org.aesh.command.option.Argument;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.cli.context.HyperfoilCompleterData;
@CommandDefinition(name = "help", description = "Provides help for other CLI commands.")
public class Help implements Command<HyperfoilCommandInvocation> {
private static final Table<ProcessedCommand<?, ?>> ALL_COMMANDS = new Table<ProcessedCommand<?, ?>>()
.column("COMMAND", ProcessedCommand::name)
.column("DESCRIPTION", ProcessedCommand::description);
@Argument(description = "Command for which you need help.", completer = CommandCompleter.class)
String command;
private Comparator<ProcessedCommand<?, ?>> COMMAND_COMPARATOR = Comparator.comparing(ProcessedCommand::name);
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) {
if (command == null || command.isEmpty()) {
invocation.println("Hyperfoil CLI, version " + io.hyperfoil.api.Version.VERSION);
invocation.println("\nAvailable commands:\n");
Function<String, ProcessedCommand<?, ?>> toProcessedCommand = c -> {
try {
return invocation.context().commandRegistry().getCommand(c, c).getParser().getProcessedCommand();
} catch (CommandNotFoundException e) {
throw new IllegalStateException(e);
}
};
ALL_COMMANDS.print(invocation, invocation.context().commandRegistry().getAllCommandNames().stream()
.map(toProcessedCommand).sorted(COMMAND_COMPARATOR));
return CommandResult.SUCCESS;
}
String help = invocation.getHelpInfo(command);
if (help == null || help.isEmpty()) {
invocation.println("No help info available for command '" + command + "'. Available commands: ");
invocation.println(
invocation.context().commandRegistry().getAllCommandNames().stream().sorted().collect(Collectors.joining(", ")));
} else {
invocation.print(help);
}
return CommandResult.SUCCESS;
}
private class CommandCompleter implements OptionCompleter<HyperfoilCompleterData> {
@Override
public void complete(HyperfoilCompleterData completerInvocation) {
Stream<String> commands = completerInvocation.getContext().commandRegistry().getAllCommandNames().stream().sorted();
String prefix = completerInvocation.getGivenCompleteValue();
if (prefix != null) {
commands = commands.filter(b -> b.startsWith(prefix));
}
commands.forEach(completerInvocation::addCompleterValue);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/commands/Connections.java | cli/src/main/java/io/hyperfoil/cli/commands/Connections.java | package io.hyperfoil.cli.commands;
import java.util.Map;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.option.Option;
import io.hyperfoil.cli.CliUtil;
import io.hyperfoil.cli.Table;
import io.hyperfoil.cli.context.HyperfoilCommandInvocation;
import io.hyperfoil.client.RestClientException;
import io.hyperfoil.controller.Client;
@CommandDefinition(name = "connections", aliases = "conns", description = "Shows number and type of connections.")
public class Connections extends BaseRunIdCommand {
Table<Map.Entry<String, Client.MinMax>> CONNECTION_STATS = new Table<Map.Entry<String, Client.MinMax>>()
.column("TYPE", Map.Entry::getKey)
.column("MIN", e -> String.valueOf(e.getValue().min), Table.Align.RIGHT)
.column("MAX", e -> String.valueOf(e.getValue().max), Table.Align.RIGHT);
@Option(description = "Show overall stats for the run.")
boolean total;
@Override
public CommandResult execute(HyperfoilCommandInvocation invocation) throws CommandException, InterruptedException {
Client.RunRef runRef = getRunRef(invocation);
Map<String, Map<String, Client.MinMax>> connectionStats = null;
for (;;) {
try {
if (!total) {
int numLines = connectionStats == null ? 0 : connectionStats.values().stream().mapToInt(Map::size).sum() + 2;
connectionStats = runRef.connectionStatsRecent();
clearLines(invocation, numLines);
}
if (connectionStats == null || connectionStats.isEmpty()) {
var run = runRef.get();
if (total || run.terminated != null) {
invocation.println("Run " + run.id + " has terminated.");
CONNECTION_STATS.print(invocation, "TARGET", CliUtil.toMapOfStreams(runRef.connectionStatsTotal()));
return CommandResult.SUCCESS;
}
}
if (connectionStats != null) {
CONNECTION_STATS.print(invocation, "TARGET", CliUtil.toMapOfStreams(connectionStats));
}
if (interruptibleDelay(invocation)) {
return CommandResult.SUCCESS;
}
} catch (RestClientException e) {
if (e.getCause() instanceof InterruptedException) {
clearLines(invocation, 1);
invocation.println("");
return CommandResult.SUCCESS;
}
invocation.error(e);
throw new CommandException("Cannot display connection stats.", e);
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCompleterData.java | cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCompleterData.java | package io.hyperfoil.cli.context;
import java.util.Collection;
import java.util.List;
import org.aesh.command.Command;
import org.aesh.command.completer.CompleterInvocation;
import org.aesh.readline.AeshContext;
import org.aesh.readline.terminal.formatting.TerminalString;
public class HyperfoilCompleterData implements CompleterInvocation {
private final CompleterInvocation delegate;
private final HyperfoilCliContext context;
public HyperfoilCompleterData(CompleterInvocation completerInvocation, HyperfoilCliContext context) {
this.delegate = completerInvocation;
this.context = context;
}
@Override
public String getGivenCompleteValue() {
return delegate.getGivenCompleteValue();
}
@Override
public Command getCommand() {
return delegate.getCommand();
}
@Override
public List<TerminalString> getCompleterValues() {
return delegate.getCompleterValues();
}
@Override
public void setCompleterValues(Collection<String> completerValues) {
delegate.setCompleterValues(completerValues);
}
@Override
public void setCompleterValuesTerminalString(List<TerminalString> completerValues) {
delegate.setCompleterValuesTerminalString(completerValues);
}
@Override
public void clearCompleterValues() {
delegate.clearCompleterValues();
}
@Override
public void addAllCompleterValues(Collection<String> completerValues) {
delegate.addAllCompleterValues(completerValues);
}
@Override
public void addCompleterValue(String value) {
delegate.addCompleterValue(value);
}
@Override
public void addCompleterValueTerminalString(TerminalString value) {
delegate.addCompleterValueTerminalString(value);
}
@Override
public boolean isAppendSpace() {
return delegate.isAppendSpace();
}
@Override
public void setAppendSpace(boolean appendSpace) {
delegate.setAppendSpace(appendSpace);
}
@Override
public void setIgnoreOffset(boolean ignoreOffset) {
delegate.setIgnoreOffset(ignoreOffset);
}
@Override
public boolean doIgnoreOffset() {
return delegate.doIgnoreOffset();
}
@Override
public void setOffset(int offset) {
delegate.setOffset(offset);
}
@Override
public int getOffset() {
return delegate.getOffset();
}
@Override
public void setIgnoreStartsWith(boolean ignoreStartsWith) {
delegate.setIgnoreStartsWith(ignoreStartsWith);
}
@Override
public boolean isIgnoreStartsWith() {
return delegate.isIgnoreStartsWith();
}
@Override
public AeshContext getAeshContext() {
return delegate.getAeshContext();
}
public HyperfoilCliContext getContext() {
return context;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCommandInvocation.java | cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCommandInvocation.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.context;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.aesh.command.CommandException;
import org.aesh.command.CommandNotFoundException;
import org.aesh.command.Executor;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.invocation.CommandInvocationConfiguration;
import org.aesh.command.parser.CommandLineParserException;
import org.aesh.command.shell.Shell;
import org.aesh.command.validator.CommandValidatorException;
import org.aesh.command.validator.OptionValidatorException;
import org.aesh.readline.Prompt;
import org.aesh.readline.action.KeyAction;
import org.aesh.terminal.utils.ANSI;
import io.hyperfoil.cli.HyperfoilCli;
import io.hyperfoil.cli.commands.ServerCommand;
import io.hyperfoil.impl.Util;
public class HyperfoilCommandInvocation implements CommandInvocation {
private final CommandInvocation commandInvocation;
private final HyperfoilCliContext context;
protected HyperfoilCommandInvocation(HyperfoilCliContext context, CommandInvocation commandInvocation) {
this.context = context;
this.commandInvocation = commandInvocation;
}
public HyperfoilCliContext context() {
return context;
}
@Override
public Shell getShell() {
return commandInvocation.getShell();
}
@Override
public void setPrompt(Prompt prompt) {
if (System.getenv(HyperfoilCli.CLI_PROMPT) == null) {
commandInvocation.setPrompt(prompt);
}
}
@Override
public Prompt getPrompt() {
return commandInvocation.getPrompt();
}
@Override
public String getHelpInfo(String commandName) {
return commandInvocation.getHelpInfo(commandName);
}
@Override
public String getHelpInfo() {
return commandInvocation.getHelpInfo();
}
@Override
public void stop() {
context.stop();
commandInvocation.stop();
}
@Override
public KeyAction input() throws InterruptedException {
return commandInvocation.input();
}
@Override
public KeyAction input(long timeout, TimeUnit unit) throws InterruptedException {
return commandInvocation.input(timeout, unit);
}
@Override
public String inputLine() throws InterruptedException {
return commandInvocation.inputLine();
}
@Override
public String inputLine(Prompt prompt) throws InterruptedException {
return commandInvocation.inputLine(prompt);
}
@Override
public void executeCommand(String input) throws CommandNotFoundException,
CommandLineParserException, OptionValidatorException,
CommandValidatorException, CommandException, InterruptedException, IOException {
commandInvocation.executeCommand(input);
}
@Override
public void print(String msg, boolean paging) {
commandInvocation.print(msg, paging);
}
@Override
public void println(String msg, boolean paging) {
commandInvocation.println(msg, paging);
}
@Override
public Executor<? extends CommandInvocation> buildExecutor(String line) throws CommandNotFoundException,
CommandLineParserException, OptionValidatorException, CommandValidatorException, IOException {
return commandInvocation.buildExecutor(line);
}
@Override
public CommandInvocationConfiguration getConfiguration() {
return commandInvocation.getConfiguration();
}
public void warn(String message) {
println(ANSI.YELLOW_TEXT + "WARNING: " + message + ANSI.RESET);
}
public void error(String message) {
println(ANSI.RED_TEXT + "ERROR: " + message + ANSI.RESET);
}
public void error(Throwable t) {
error(Util.explainCauses(t));
}
public void error(String message, Throwable t) {
error(message + ": " + Util.explainCauses(t));
}
public void printStackTrace(Throwable t) {
print(ANSI.RED_TEXT);
printStackTrace(t, new HashSet<>());
print(ANSI.RESET);
}
private void printStackTrace(Throwable t, HashSet<Throwable> set) {
if (!set.add(t)) {
println("[CIRCULAR REFERENCE]");
return;
}
for (StackTraceElement traceElement : t.getStackTrace()) {
println("\tat " + traceElement);
}
for (Throwable se : t.getSuppressed()) {
println("SUPPRESSED: " + se.getMessage());
printStackTrace(se, set);
}
Throwable cause = t.getCause();
if (cause != null) {
println("CAUSED BY: " + cause.getMessage());
printStackTrace(cause, set);
}
}
public void executeSwitchable(String input) throws CommandException {
context.setSwitchable(true);
try {
while (true) {
try {
executeCommand(input);
break;
} catch (RuntimeException e) {
Throwable cause = e.getCause();
while (cause instanceof RuntimeException && cause != cause.getCause()
&& !(cause instanceof ServerCommand.SwitchCommandException)) {
cause = cause.getCause();
}
if (cause instanceof ServerCommand.SwitchCommandException) {
input = ((ServerCommand.SwitchCommandException) cause).newCommand;
} else {
error(e);
throw new CommandException(e);
}
} catch (Exception e) {
error(e);
throw new CommandException(e);
}
}
} finally {
context.setSwitchable(false);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCommandInvocationProvider.java | cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCommandInvocationProvider.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.context;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.invocation.CommandInvocationProvider;
/**
* @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a>
*/
public class HyperfoilCommandInvocationProvider implements CommandInvocationProvider<HyperfoilCommandInvocation> {
private final HyperfoilCliContext context;
public HyperfoilCommandInvocationProvider(HyperfoilCliContext context) {
this.context = context;
}
@Override
public HyperfoilCommandInvocation enhanceCommandInvocation(CommandInvocation commandInvocation) {
return new HyperfoilCommandInvocation(context, commandInvocation);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCliContext.java | cli/src/main/java/io/hyperfoil/cli/context/HyperfoilCliContext.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.hyperfoil.cli.context;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.aesh.command.CommandException;
import org.aesh.command.registry.CommandRegistry;
import io.hyperfoil.cli.Pager;
import io.hyperfoil.cli.ProcessPager;
import io.hyperfoil.client.RestClient;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.Run;
import io.vertx.core.Vertx;
/**
* @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a>
*/
public class HyperfoilCliContext {
private final Vertx vertx;
private final boolean providedVertx;
private RestClient client;
private Client.BenchmarkRef serverBenchmark;
private Map<String, String> currentParams = Collections.emptyMap();
private Client.RunRef serverRun;
private Map<String, File> logFiles = new HashMap<>();
private Map<String, String> logIds = new HashMap<>();
private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "CLI-scheduled-executor");
thread.setDaemon(true);
return thread;
});
private String controllerId;
private ScheduledFuture<?> controllerPollTask;
private String localControllerHost = null;
private int localControllerPort = -1;
private List<Runnable> cleanup = new ArrayList<>();
// We'll start with online set to true to not say 'we're back online' when connecting the first time
private boolean online = true;
private CommandRegistry<? extends HyperfoilCommandInvocation> commandRegistry;
private List<String> suggestedControllerHosts = Collections.emptyList();
private boolean switchable;
public HyperfoilCliContext() {
this(Vertx.vertx(), false);
}
protected HyperfoilCliContext(Vertx vertx, boolean providedVertx) {
this.vertx = vertx;
this.providedVertx = providedVertx;
}
public RestClient client() {
return client;
}
public void setClient(RestClient client) {
this.client = client;
}
public void setServerBenchmark(Client.BenchmarkRef ref) {
this.serverBenchmark = ref;
}
public Client.BenchmarkRef serverBenchmark() {
return serverBenchmark;
}
public void setCurrentParams(Map<String, String> currentParams) {
this.currentParams = currentParams;
}
public Map<String, String> currentParams() {
return currentParams;
}
public void setServerRun(Client.RunRef ref) {
serverRun = ref;
}
public Client.RunRef serverRun() {
return serverRun;
}
public File getLogFile(String node) {
return logFiles.get(node);
}
public String getLogId(String node) {
return logIds.get(node);
}
public void addLog(String node, File file, String id) throws CommandException {
if (logFiles.containsKey(node) || logIds.containsKey(node)) {
throw new CommandException("Log file for " + node + " already present");
}
logFiles.put(node, file);
logIds.put(node, id);
}
public void updateLogId(String node, String logId) {
logIds.put(node, logId);
}
public ScheduledExecutorService executor() {
return executor;
}
public String controllerId() {
return controllerId;
}
public void setControllerId(String id) {
controllerId = id;
}
public void setControllerPollTask(ScheduledFuture<?> future) {
if (controllerPollTask != null) {
controllerPollTask.cancel(false);
}
controllerPollTask = future;
}
public String localControllerHost() {
return localControllerHost;
}
public void setLocalControllerHost(String localControllerHost) {
this.localControllerHost = localControllerHost;
}
public int localControllerPort() {
return localControllerPort;
}
public void setLocalControllerPort(int localControllerPort) {
this.localControllerPort = localControllerPort;
}
public void addCleanup(Runnable runnable) {
cleanup.add(runnable);
}
public void stop() {
executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (client != null) {
client.close();
client = null;
}
for (Runnable c : cleanup) {
c.run();
}
if (!providedVertx) {
vertx.close();
}
}
public void setOnline(boolean online) {
this.online = online;
}
public boolean online() {
return online;
}
public void commandRegistry(CommandRegistry<? extends HyperfoilCommandInvocation> commandRegistry) {
this.commandRegistry = commandRegistry;
}
public CommandRegistry<? extends HyperfoilCommandInvocation> commandRegistry() {
return commandRegistry;
}
public Vertx vertx() {
return vertx;
}
public synchronized List<String> suggestedControllerHosts() {
return suggestedControllerHosts;
}
public synchronized void setSuggestedControllerHosts(List<String> suggestedControllerHosts) {
this.suggestedControllerHosts = suggestedControllerHosts;
}
public String interruptKey() {
return "Ctrl+C";
}
public Pager createPager(String pager) {
return new ProcessPager(pager);
}
public synchronized void notifyRunCompleted(Run run) {
// not implemented in regular CLI
}
public void setSwitchable(boolean switchable) {
this.switchable = switchable;
}
public boolean isSwitchable() {
return this.switchable;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/client/RunRefImpl.java | cli/src/main/java/io/hyperfoil/client/RunRefImpl.java | package io.hyperfoil.client;
import static io.hyperfoil.client.RestClient.unexpected;
import static io.hyperfoil.client.RestClient.waitFor;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import com.fasterxml.jackson.core.type.TypeReference;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.statistics.StatisticsSummary;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.Histogram;
import io.hyperfoil.controller.model.RequestStatisticsResponse;
import io.hyperfoil.controller.model.Run;
import io.hyperfoil.impl.Util;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.Json;
import io.vertx.core.json.jackson.JacksonCodec;
import io.vertx.ext.web.client.HttpResponse;
public class RunRefImpl implements Client.RunRef {
private final RestClient client;
private final String id;
public RunRefImpl(RestClient client, String id) {
this.client = client;
// Accepting URL as id
int lastSlash = id.lastIndexOf('/');
this.id = lastSlash >= 0 ? id.substring(lastSlash + 1) : id;
}
@Override
public String id() {
return id;
}
@Override
public Run get() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id).send(handler), 200,
response -> Json.decodeValue(response.body(), Run.class));
}
@Override
public Client.RunRef kill() {
client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/kill").send(handler), 202,
response -> null);
return this;
}
@Override
public Benchmark benchmark() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/benchmark")
.putHeader(HttpHeaders.ACCEPT.toString(), "application/java-serialized-object")
.send(handler),
200,
response -> {
try {
return Util.deserialize(response.bodyAsBuffer().getBytes());
} catch (IOException | ClassNotFoundException e) {
throw new CompletionException(e);
}
});
}
@Override
public Map<String, Map<String, Client.MinMax>> sessionStatsRecent() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/sessions/recent").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<Map<String, Map<String, Client.MinMax>>>() {
}));
}
@Override
public Map<String, Map<String, Client.MinMax>> sessionStatsTotal() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/sessions/total").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<Map<String, Map<String, Client.MinMax>>>() {
}));
}
@Override
public Collection<String> sessions() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/sessions").send(handler), 200,
response -> Arrays.asList(response.bodyAsString().split("\n")));
}
@Override
public Collection<String> connections() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/connections").send(handler), 200,
response -> Arrays.asList(response.bodyAsString().split("\n")));
}
@Override
public Map<String, Map<String, Client.MinMax>> connectionStatsRecent() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/connections/recent").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<Map<String, Map<String, Client.MinMax>>>() {
}));
}
@Override
public Map<String, Map<String, Client.MinMax>> connectionStatsTotal() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/connections/total").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<Map<String, Map<String, Client.MinMax>>>() {
}));
}
@Override
public RequestStatisticsResponse statsRecent() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/stats/recent")
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json").send(handler),
200,
response -> Json.decodeValue(response.body(), RequestStatisticsResponse.class));
}
@Override
public RequestStatisticsResponse statsTotal() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/stats/total")
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json").send(handler),
200,
response -> Json.decodeValue(response.body(), RequestStatisticsResponse.class));
}
@Override
public byte[] statsAll(String format) {
CompletableFuture<byte[]> future = new CompletableFuture<>();
client.vertx.runOnContext(ctx -> client.request(HttpMethod.GET, "/run/" + id + "/stats/all")
.putHeader(HttpHeaders.ACCEPT.toString(), format)
.send(rsp -> {
if (rsp.failed()) {
future.completeExceptionally(rsp.cause());
return;
}
HttpResponse<Buffer> response = rsp.result();
if (response.statusCode() != 200) {
future.completeExceptionally(unexpected(response));
return;
}
try {
future.complete(response.body().getBytes());
} catch (Throwable t) {
future.completeExceptionally(t);
}
}));
return waitFor(future);
}
@Override
public Histogram histogram(String phase, int stepId, String metric) {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/stats/histogram")
.addQueryParam("phase", phase)
.addQueryParam("stepId", String.valueOf(stepId))
.addQueryParam("metric", metric)
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json").send(handler),
200,
response -> Json.decodeValue(response.body(), Histogram.class));
}
@Override
public List<StatisticsSummary> series(String phase, int stepId, String metric) {
return client.sync(handler -> client.request(HttpMethod.GET, "/run/" + id + "/stats/series")
.addQueryParam("phase", phase)
.addQueryParam("stepId", String.valueOf(stepId))
.addQueryParam("metric", metric)
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<>() {
}));
}
@Override
public byte[] file(String filename) {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/file").addQueryParam("file", filename).send(handler),
200,
response -> response.body().getBytes());
}
@Override
public byte[] report(String source) {
String path = "/run/" + id + "/report" + (source != null && !source.isEmpty() ? "?source=" + source : "");
return client.sync(
handler -> client.request(HttpMethod.GET, path).send(handler), 200,
response -> response.body().getBytes());
}
@Override
public Map<String, Map<String, String>> agentCpu() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/run/" + id + "/agentCpu").send(handler), 200,
response -> JacksonCodec.decodeValue(response.body(), new TypeReference<Map<String, Map<String, String>>>() {
}));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/client/BenchmarkRefImpl.java | cli/src/main/java/io/hyperfoil/client/BenchmarkRefImpl.java | package io.hyperfoil.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.controller.Client;
import io.hyperfoil.impl.Util;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.Json;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
class BenchmarkRefImpl implements Client.BenchmarkRef {
protected static final String YAML = "text/vnd.yaml";
protected static final String SERIALIZED = "application/java-serialized-object";
protected static final String JSON = "application/json";
protected static final String MULTIPART_FORM_DATA = "multipart/form-data";
private final RestClient client;
private final String name;
BenchmarkRefImpl(RestClient client, String name) {
this.client = client;
this.name = name;
}
@Override
public String name() {
return name;
}
@Override
public Client.BenchmarkSource source() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/benchmark/" + encode(name))
.putHeader(HttpHeaders.ACCEPT.toString(), YAML)
.send(handler),
0,
response -> {
if (response.statusCode() == 200) {
return new Client.BenchmarkSource(response.bodyAsString(), response.getHeader(HttpHeaders.ETAG.toString()),
response.headers().getAll("x-file"));
} else if (response.statusCode() == 406) {
return null;
} else {
throw RestClient.unexpected(response);
}
});
}
@Override
public Benchmark get() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/benchmark/" + encode(name))
.putHeader(HttpHeaders.ACCEPT.toString(), SERIALIZED)
.send(handler),
200,
response -> {
try {
return Util.deserialize(response.bodyAsBuffer().getBytes());
} catch (IOException | ClassNotFoundException e) {
throw new CompletionException(e);
}
});
}
@Override
public Client.RunRef start(String description, Map<String, String> templateParams) {
return this.start(description, templateParams, Boolean.FALSE);
}
public Client.RunRef start(String description, Map<String, String> templateParams, Boolean validate) {
CompletableFuture<Client.RunRef> future = new CompletableFuture<>();
client.vertx.runOnContext(ctx -> {
HttpRequest<Buffer> request = client.request(HttpMethod.GET, "/benchmark/" + encode(name) + "/start");
if (description != null) {
request.addQueryParam("desc", description);
}
for (var param : templateParams.entrySet()) {
request.addQueryParam("templateParam", param.getKey() + "=" + param.getValue());
}
request.addQueryParam("validate", validate.toString());
request.send(rsp -> {
if (rsp.succeeded()) {
HttpResponse<Buffer> response = rsp.result();
String location = response.getHeader(HttpHeaders.LOCATION.toString());
if (response.statusCode() == 202) {
if (location == null) {
future.completeExceptionally(new RestClientException("Server did not respond with run location!"));
} else {
future.complete(new RunRefImpl(client, location));
}
} else if (response.statusCode() == 301) {
if (location == null) {
future.completeExceptionally(new RestClientException("Server did not respond with run location!"));
return;
}
URL url;
try {
url = new URL(location);
} catch (MalformedURLException e) {
future.completeExceptionally(
new RestClientException("Cannot parse URL " + location, new RestClientException(e)));
return;
}
String runId = response.getHeader("x-run-id");
client.request(HttpMethod.GET, "https".equalsIgnoreCase(url.getProtocol()), url.getHost(), url.getPort(),
url.getFile()).send(rsp2 -> {
if (rsp2.succeeded()) {
HttpResponse<Buffer> response2 = rsp2.result();
if (response2.statusCode() >= 200 && response2.statusCode() < 300) {
future.complete(new RunRefImpl(client, runId == null ? "last" : runId));
} else {
future.completeExceptionally(new RestClientException("Failed to indirectly trigger job on "
+ location + ", status is " + response2.statusCode()));
}
} else {
future.completeExceptionally(
new RestClientException("Failed to indirectly trigger job on " + location, rsp2.cause()));
}
});
} else {
future.completeExceptionally(RestClient.unexpected(response));
}
} else {
future.completeExceptionally(rsp.cause());
}
});
});
return RestClient.waitFor(future);
}
@Override
public Client.BenchmarkStructure structure(Integer maxCollectionSize, Map<String, String> templateParams) {
return client.sync(
handler -> {
HttpRequest<Buffer> request = client.request(HttpMethod.GET, "/benchmark/" + encode(name) + "/structure");
if (maxCollectionSize != null) {
request.addQueryParam("maxCollectionSize", maxCollectionSize.toString());
}
for (var param : templateParams.entrySet()) {
request.addQueryParam("templateParam", param.getKey() + "=" + param.getValue());
}
request
.putHeader(HttpHeaders.ACCEPT.toString(), JSON)
.send(handler);
}, 200,
response -> Json.decodeValue(response.body(), Client.BenchmarkStructure.class));
}
@Override
public Map<String, byte[]> files() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/benchmark/" + encode(name) + "/files")
.putHeader(HttpHeaders.ACCEPT.toString(), MULTIPART_FORM_DATA)
.send(handler),
200,
response -> {
String contentType = response.getHeader(HttpHeaders.CONTENT_TYPE.toString());
if (contentType == null) {
throw new RestClientException("Missing response content-type.");
}
String[] parts = contentType.split(";");
if (!MULTIPART_FORM_DATA.equals(parts[0].trim()) || parts.length < 2 ||
!parts[1].trim().startsWith("boundary=\"") || !parts[1].trim().endsWith("\"")) {
throw new RestClientException("Unexpected content-type: " + contentType);
}
String param = parts[1].trim();
String boundary = param.substring(10, param.length() - 1);
Map<String, byte[]> files = new HashMap<>();
try (ByteArrayInputStream stream = new ByteArrayInputStream(response.bodyAsBuffer().getBytes())) {
int length = -1;
String filename = null;
byte[] buffer = new byte[2048];
for (;;) {
int b, pos = 0;
while (pos < buffer.length && (b = stream.read()) >= 0 && b != '\n') {
buffer[pos++] = (byte) b;
}
if (pos == buffer.length) {
throw new RestClientException("Too long line; probably protocol error.");
}
String line = new String(buffer, 0, pos, StandardCharsets.US_ASCII);
String lower = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("--" + boundary)) {
if (line.endsWith("--")) {
break;
}
} else if (lower.startsWith("content-type: ")) {
// ignore
} else if (lower.startsWith("content-length: ")) {
try {
length = Integer.parseInt(lower.substring("content-length: ".length()).trim());
} catch (NumberFormatException e) {
throw new RestClientException("Cannot parse content-length: " + line);
}
} else if (lower.startsWith("content-disposition: ")) {
String[] disposition = line.substring("content-disposition: ".length()).split(";");
for (int i = 0; i < disposition.length; ++i) {
String d = disposition[i].trim();
if (d.startsWith("filename=\"") && d.endsWith("\"")) {
filename = d.substring(10, d.length() - 1);
}
}
} else if (line.isEmpty()) {
if (length < 0) {
throw new RestClientException("Missing content-length!");
} else {
byte[] bytes = new byte[length];
if (stream.readNBytes(bytes, 0, length) != length) {
throw new RestClientException("Cannot read all bytes for file " + filename);
}
if (filename == null) {
throw new RestClientException("No filename in content-disposition");
}
files.put(filename, bytes);
if (stream.read() != '\n') {
throw new RestClientException("Expected newline after file " + filename);
}
filename = null;
length = -1;
}
}
}
} catch (IOException e) {
throw new RestClientException(e);
}
return files;
});
}
@Override
public boolean exists() {
return client.sync(
handler -> client.request(HttpMethod.GET, "/benchmark/" + encode(name))
.putHeader(HttpHeaders.ACCEPT.toString(), YAML)
.send(handler),
0,
response -> {
if (response.statusCode() == 200) {
return true;
} else if (response.statusCode() == 404) {
return false;
} else {
throw new RestClientException(response.bodyAsString());
}
});
}
@Override
public boolean forget() {
return client.sync(
handler -> client.request(HttpMethod.DELETE, "/benchmark/" + encode(name))
.send(handler),
0, response -> {
if (response.statusCode() == 204) {
return true;
} else if (response.statusCode() == 404) {
return false;
} else {
throw new RestClientException(response.bodyAsString());
}
});
}
private String encode(String name) {
try {
return URLEncoder.encode(name, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return name;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/client/RestClient.java | cli/src/main/java/io/hyperfoil/client/RestClient.java | package io.hyperfoil.client;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.statistics.StatsExtension;
import io.hyperfoil.controller.Client;
import io.hyperfoil.controller.model.Version;
import io.hyperfoil.impl.Util;
import io.hyperfoil.internal.Properties;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.Json;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.multipart.MultipartForm;
public class RestClient implements Client, Closeable {
private static final long REQUEST_TIMEOUT = Properties.getLong(Properties.CLI_REQUEST_TIMEOUT, 30000);
protected static final byte[] EMPTY_LOG_FILE = "<empty log file>".getBytes(StandardCharsets.UTF_8);
final Vertx vertx;
final WebClientOptions options;
private final WebClient client;
private String authorization;
static {
StatsExtension.registerSubtypes();
}
public RestClient(Vertx vertx, String host, int port, boolean ssl, boolean insecure, String password) {
this.vertx = vertx;
// Actually there's little point in using async client, but let's stay in Vert.x libs
options = new WebClientOptions().setDefaultHost(host).setDefaultPort(port);
if (ssl) {
options.setSsl(true).setUseAlpn(true);
}
if (insecure) {
options.setTrustAll(true).setVerifyHost(false);
}
client = WebClient.create(this.vertx, options.setFollowRedirects(false));
setPassword(password);
}
public void setPassword(String password) {
if (password != null) {
// server ignores username
authorization = "Basic "
+ Base64.getEncoder().encodeToString(("hyperfoil:" + password).getBytes(StandardCharsets.UTF_8));
} else {
authorization = null;
}
}
public void setToken(String token) {
if (token != null) {
authorization = "Bearer " + token;
} else {
authorization = null;
}
}
static RestClientException unexpected(HttpResponse<Buffer> response) {
StringBuilder sb = new StringBuilder("Server responded with unexpected code: ");
sb.append(response.statusCode()).append(", ").append(response.statusMessage());
String body = response.bodyAsString();
if (body != null && !body.isEmpty()) {
sb.append(":\n").append(body);
}
return new RestClientException(sb.toString());
}
public String host() {
return options.getDefaultHost();
}
public int port() {
return options.getDefaultPort();
}
HttpRequest<Buffer> request(HttpMethod method, String path) {
HttpRequest<Buffer> request = client.request(method, path);
if (authorization != null) {
request.putHeader(HttpHeaders.AUTHORIZATION.toString(), authorization);
}
return request;
}
HttpRequest<Buffer> request(HttpMethod method, boolean ssl, String host, int port, String path) {
return client.request(method, new RequestOptions().setSsl(ssl).setHost(host).setPort(port).setURI(path));
}
@Override
public BenchmarkRef register(Benchmark benchmark, String prevVersion) {
byte[] bytes;
try {
bytes = Util.serialize(benchmark);
} catch (IOException e) {
throw new RuntimeException(e);
}
return sync(
handler -> {
HttpRequest<Buffer> request = request(HttpMethod.POST, "/benchmark");
if (prevVersion != null) {
request.putHeader(HttpHeaders.IF_MATCH.toString(), prevVersion);
}
request.putHeader(HttpHeaders.CONTENT_TYPE.toString(), "application/java-serialized-object")
.sendBuffer(Buffer.buffer(bytes), handler);
}, 0,
response -> {
if (response.statusCode() == 204) {
return new BenchmarkRefImpl(this, benchmark.name());
} else if (response.statusCode() == 409) {
throw new EditConflictException();
} else {
throw unexpected(response);
}
});
}
@Override
public BenchmarkRef register(String yaml, Map<String, byte[]> otherFiles, String prevVersion, String storedFilesBenchmark) {
MultipartForm multipart = MultipartForm.create();
multipart.textFileUpload("benchmark", "benchmark.yaml", Buffer.buffer(yaml), "text/vnd.yaml");
for (var entry : otherFiles.entrySet()) {
multipart.binaryFileUpload(entry.getKey(), entry.getKey(), Buffer.buffer(entry.getValue()),
"application/octet-stream");
}
return multipartUpload(prevVersion, storedFilesBenchmark, multipart);
}
@Override
public BenchmarkRef register(Path benchmarkFile, Map<String, Path> otherFiles, String prevVersion,
String storedFilesBenchmark) {
MultipartForm multipart = MultipartForm.create();
multipart.textFileUpload("benchmark", "benchmark.yaml", benchmarkFile.toString(), "text/vnd.yaml");
for (Map.Entry<String, Path> entry : otherFiles.entrySet()) {
multipart.binaryFileUpload(entry.getKey(), entry.getKey(), entry.getValue().toString(), "application/octet-stream");
}
return multipartUpload(prevVersion, storedFilesBenchmark, multipart);
}
private BenchmarkRef multipartUpload(String prevVersion, String storedFilesBenchmark, MultipartForm multipart) {
return sync(
handler -> {
HttpRequest<Buffer> request = request(HttpMethod.POST, "/benchmark");
if (storedFilesBenchmark != null) {
request.addQueryParam("storedFilesBenchmark", storedFilesBenchmark);
}
if (prevVersion != null) {
request.putHeader(HttpHeaders.IF_MATCH.toString(), prevVersion);
}
request.sendMultipartForm(multipart, handler);
}, 0,
this::processRegisterResponse);
}
@Override
public BenchmarkRef registerLocal(String benchmarkUri, String prevVersion, String storedFilesBenchmark) {
return sync(
handler -> {
HttpRequest<Buffer> request = request(HttpMethod.POST, "/benchmark");
if (prevVersion != null) {
request.putHeader(HttpHeaders.IF_MATCH.toString(), prevVersion);
}
request.putHeader(HttpHeaders.CONTENT_TYPE.toString(), "text/uri-list")
.sendBuffer(Buffer.buffer(benchmarkUri), handler);
}, 0,
this::processRegisterResponse);
}
private BenchmarkRefImpl processRegisterResponse(HttpResponse<Buffer> response) {
if (response.statusCode() == 204) {
String location = response.getHeader(HttpHeaders.LOCATION.toString());
if (location == null) {
throw new RestClientException("Expected location header.");
}
int lastSlash = location.lastIndexOf('/');
return new BenchmarkRefImpl(this, location.substring(lastSlash + 1));
} else if (response.statusCode() == 409) {
throw new EditConflictException();
} else {
throw unexpected(response);
}
}
@Override
public List<String> benchmarks() {
return sync(
handler -> request(HttpMethod.GET, "/benchmark").send(handler), 200,
response -> Arrays.asList(Json.decodeValue(response.body(), String[].class)));
}
@Override
public List<String> templates() {
return sync(
handler -> request(HttpMethod.GET, "/template").send(handler), 200,
response -> Arrays.asList(Json.decodeValue(response.body(), String[].class)));
}
@Override
public BenchmarkRef benchmark(String name) {
return new BenchmarkRefImpl(this, name);
}
@Override
public List<io.hyperfoil.controller.model.Run> runs(boolean details) {
return sync(
handler -> request(HttpMethod.GET, "/run?details=" + details).send(handler), 200,
response -> Arrays.asList(Json.decodeValue(response.body(), io.hyperfoil.controller.model.Run[].class)));
}
@Override
public RunRef run(String id) {
return new RunRefImpl(this, id);
}
@Override
public long ping() {
return sync(handler -> request(HttpMethod.GET, "/").send(handler), 200, response -> {
try {
String header = response.getHeader("x-epoch-millis");
return header != null ? Long.parseLong(header) : 0L;
} catch (NumberFormatException e) {
return 0L;
}
});
}
@Override
public Version version() {
return sync(handler -> request(HttpMethod.GET, "/version").send(handler), 0,
response -> {
if (response.statusCode() == 401) {
throw new Unauthorized();
} else if (response.statusCode() == 403) {
throw new Forbidden();
} else if (response.statusCode() >= 300 && response.statusCode() <= 399) {
String location = response.getHeader(HttpHeaders.LOCATION.toString());
if (location == null) {
throw new RestClientException("Servers suggests redirection but does not include the Location header");
}
int pathIndex = location.indexOf('/', 8); // 8 should work for both http and https
if (pathIndex >= 0) {
location = location.substring(0, pathIndex);
}
throw new RedirectToHost(location);
} else if (response.statusCode() != 200) {
throw unexpected(response);
}
return Json.decodeValue(response.body(), Version.class);
});
}
@Override
public Collection<String> agents() {
return sync(handler -> request(HttpMethod.GET, "/agents").send(handler), 200,
response -> Arrays.asList(Json.decodeValue(response.body(), String[].class)));
}
@Override
public String downloadLog(String node, String logId, long offset, long maxLength, File destinationFile) {
String url = "/log" + (node == null ? "" : "/" + node);
// When there's no more data, content-length won't be present and the body is null
// the etag does not match
CompletableFuture<String> future = new CompletableFuture<>();
vertx.runOnContext(ctx -> {
HttpRequest<Buffer> request = request(HttpMethod.GET, url + "?offset=" + offset + "&maxLength=" + maxLength);
if (logId != null) {
request.putHeader(HttpHeaders.IF_MATCH.toString(), logId);
}
request.send(rsp -> {
if (rsp.failed()) {
future.completeExceptionally(rsp.cause());
return;
}
HttpResponse<Buffer> response = rsp.result();
if (response.statusCode() == 412) {
downloadFullLog(destinationFile, url, future);
return;
} else if (response.statusCode() != 200) {
future.completeExceptionally(unexpected(response));
return;
}
try {
String etag = response.getHeader(HttpHeaders.ETAG.toString());
if (logId == null) {
try {
byte[] bytes;
if (response.body() == null) {
bytes = EMPTY_LOG_FILE;
} else {
bytes = response.body().getBytes();
}
Files.write(destinationFile.toPath(), bytes);
} catch (IOException e) {
throw new RestClientException(e);
}
future.complete(etag);
} else if (etag != null && etag.equals(logId)) {
if (response.body() != null) {
// When there's no more data, content-length won't be present and the body is null
try (RandomAccessFile rw = new RandomAccessFile(destinationFile, "rw")) {
rw.seek(offset);
rw.write(response.body().getBytes());
} catch (IOException e) {
throw new RestClientException(e);
}
}
future.complete(etag);
} else {
downloadFullLog(destinationFile, url, future);
}
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
});
return waitFor(future);
}
@Override
public void shutdown(boolean force) {
sync(handler -> request(HttpMethod.GET, "/shutdown?force=" + force).send(handler), 200, response -> null);
}
private void downloadFullLog(File destinationFile, String url, CompletableFuture<String> future) {
// the etag does not match
request(HttpMethod.GET, url).send(rsp -> {
if (rsp.failed()) {
future.completeExceptionally(rsp.cause());
return;
}
HttpResponse<Buffer> response = rsp.result();
if (response.statusCode() != 200) {
future.completeExceptionally(unexpected(response));
return;
}
try {
Buffer body = response.body();
Files.write(destinationFile.toPath(), body != null ? body.getBytes() : EMPTY_LOG_FILE);
future.complete(response.getHeader(HttpHeaders.ETAG.toString()));
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
}
static <T> T waitFor(CompletableFuture<T> future) {
try {
return future.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RestClientException(e);
} catch (ExecutionException e) {
if (e.getCause() instanceof RestClientException) {
throw (RestClientException) e.getCause();
}
throw new RestClientException(e.getCause() == null ? e : e.getCause());
} catch (TimeoutException e) {
throw new RestClientException("Request did not complete within " + REQUEST_TIMEOUT + " ms");
}
}
<T> T sync(Consumer<Handler<AsyncResult<HttpResponse<Buffer>>>> invoker, int statusCode,
Function<HttpResponse<Buffer>, T> f) {
CompletableFuture<T> future = new CompletableFuture<>();
vertx.runOnContext(ctx -> {
try {
invoker.accept(rsp -> {
if (rsp.succeeded()) {
HttpResponse<Buffer> response = rsp.result();
if (statusCode != 0 && response.statusCode() != statusCode) {
future.completeExceptionally(unexpected(response));
return;
}
try {
future.complete(f.apply(response));
} catch (Throwable t) {
future.completeExceptionally(t);
}
} else {
future.completeExceptionally(rsp.cause());
}
});
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
return waitFor(future);
}
@Override
public void close() {
client.close();
}
public String toString() {
return options.getDefaultHost() + ":" + options.getDefaultPort();
}
public static class Unauthorized extends RestClientException {
public Unauthorized() {
super("Unauthorized: password required");
}
}
public static class Forbidden extends RestClientException {
public Forbidden() {
super("Forbidden: password incorrect");
}
}
public static class RedirectToHost extends RestClientException {
public String host;
public RedirectToHost(String host) {
super("Required redirect");
this.host = host;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/cli/src/main/java/io/hyperfoil/client/RestClientException.java | cli/src/main/java/io/hyperfoil/client/RestClientException.java | package io.hyperfoil.client;
public class RestClientException extends RuntimeException {
public RestClientException(String message) {
super(message);
}
public RestClientException(Throwable cause) {
super(cause);
}
public RestClientException(String message, Throwable cause) {
super(message, cause);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/CompressionTest.java | http/src/test/java/io/hyperfoil/http/CompressionTest.java | package io.hyperfoil.http;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.statistics.HttpStats;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
public class CompressionTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route("/short").handler(ctx -> {
if (checkAcceptEncoding(ctx)) {
return;
}
ctx.response().end("Short message to be encoded.");
});
router.route("/long").handler(ctx -> {
if (checkAcceptEncoding(ctx)) {
return;
}
StringBuilder sb = new StringBuilder();
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 10000; ++i) {
sb.append((char) random.nextInt('A', 'Z' + 1));
}
ctx.response().end(sb.toString());
});
}
@Override
protected boolean useCompression() {
return true;
}
private boolean checkAcceptEncoding(RoutingContext ctx) {
if (!"gzip".equalsIgnoreCase(ctx.request().getHeader(HttpHeaders.ACCEPT_ENCODING))) {
ctx.response().setStatusCode(400).end("Expected accept-encoding header");
return true;
}
return false;
}
@Test
public void test() {
Benchmark benchmark = loadScenario("scenarios/CompressionTest.hf.yaml");
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
validateStats(stats.get("short"));
validateStats(stats.get("long"));
}
private void validateStats(StatisticsSnapshot snapshot) {
assertThat(snapshot.requestCount).isEqualTo(1);
assertThat(HttpStats.get(snapshot).status_2xx).isEqualTo(1);
assertThat(snapshot.invalid).isEqualTo(0);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/BaseMockConnection.java | http/src/test/java/io/hyperfoil/http/BaseMockConnection.java | package io.hyperfoil.http;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import io.hyperfoil.api.connection.Connection;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpRequestWriter;
import io.hyperfoil.http.api.HttpVersion;
import io.hyperfoil.http.config.Http;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
public class BaseMockConnection implements HttpConnection {
@Override
public void attach(HttpConnectionPool pool) {
}
@Override
public void request(HttpRequest request, BiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader,
BiFunction<Session, Connection, ByteBuf> bodyGenerator) {
}
@Override
public HttpRequest dispatchedRequest() {
return null;
}
@Override
public HttpRequest peekRequest(int streamId) {
return null;
}
@Override
public boolean removeRequest(int streamId, HttpRequest request) {
return false;
}
@Override
public void setClosed() {
}
@Override
public boolean isOpen() {
return false;
}
@Override
public boolean isClosed() {
return false;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public HttpVersion version() {
return null;
}
@Override
public Http config() {
return null;
}
@Override
public HttpConnectionPool pool() {
return null;
}
@Override
public long lastUsed() {
return 0;
}
@Override
public ChannelHandlerContext context() {
return null;
}
@Override
public void onAcquire() {
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public int inFlight() {
return 0;
}
@Override
public void close() {
}
@Override
public String host() {
return null;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/HttpCacheTest.java | http/src/test/java/io/hyperfoil/http/HttpCacheTest.java | package io.hyperfoil.http;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.core.VertxBaseTest;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.core.test.TestClock;
import io.hyperfoil.http.api.HttpCache;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpRequestWriter;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.statistics.HttpStats;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class HttpCacheTest extends VertxBaseTest {
private static final Logger log = LogManager.getLogger(HttpCacheTest.class);
private static final TestClock CLOCK = new TestClock();
private static final Consumer<HttpRequest> GET_TEST = request -> {
request.method = HttpMethod.GET;
request.path = "/test";
};
private static final Consumer<HttpRequest> POST_TEST = request -> {
request.method = HttpMethod.POST;
request.path = "/test";
};
@Test
public void testSimpleRequest(VertxTestContext ctx) {
var checkpoint = ctx.checkpoint();
Context context = new Context();
// First request
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 1);
assertCacheHits(ctx, req, 0);
});
// Second request, cached
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 1);
assertCacheHits(ctx, req, 1);
});
// POST invalidates the cache
context.requests.add(() -> doRequest(context, POST_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 2);
assertEquals(HttpCache.get(context.session).size(), 0);
assertCacheHits(ctx, req, 0);
});
// 4th request is not cached
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 3);
assertCacheHits(ctx, req, 0);
});
// 5th request, cached
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 3);
assertEquals(HttpCache.get(context.session).size(), 1);
assertTrue(context.serverQueue.isEmpty());
assertCacheHits(ctx, req, 1);
checkpoint.flag();
});
test(ctx, context, true);
}
@Test
public void testExpiration(VertxTestContext ctx) {
var checkpoint = ctx.checkpoint();
Context context = new Context();
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response()
.putHeader(HttpHeaderNames.EXPIRES, HttpUtil.formatDate(CLOCK.instant().plusSeconds(5).toEpochMilli())).end());
context.handlers.add(req -> {
assertEquals(1, context.serverRequests.get());
assertCacheHits(ctx, req, 0);
});
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.handlers.add(req -> {
assertEquals(1, context.serverRequests.get());
assertCacheHits(ctx, req, 1);
CLOCK.advance(6000);
});
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(2, context.serverRequests.get());
assertCacheHits(ctx, req, 0);
});
context.requests.add(
() -> doRequest(context, GET_TEST, (s, writer) -> writer.putHeader(HttpHeaderNames.CACHE_CONTROL, "max-stale=10")));
context.handlers.add(req -> {
assertEquals(2, context.serverRequests.get());
assertEquals(1, HttpCache.get(context.session).size());
assertTrue(context.serverQueue.isEmpty());
assertCacheHits(ctx, req, 1);
checkpoint.flag();
});
test(ctx, context, true);
}
@Test
public void testEtag(VertxTestContext ctx) {
var checkpoint = ctx.checkpoint();
Context context = new Context();
// First request
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().putHeader(HttpHeaderNames.ETAG, "\"foo\"").end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 1);
assertCacheHits(ctx, req, 0);
});
// We have 'bar' and 'foo', should get cached as 'foo' is in the cache
context.requests.add(() -> doRequest(context, GET_TEST,
(s, writer) -> writer.putHeader(HttpHeaderNames.IF_NONE_MATCH, "\"bar\", \"foo\"")));
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 1);
assertCacheHits(ctx, req, 1);
});
// We have 'bar' but this is not in the cache yet -> not cached
context.requests
.add(() -> doRequest(context, GET_TEST, (s, writer) -> writer.putHeader(HttpHeaderNames.IF_NONE_MATCH, "\"bar\"")));
context.serverQueue.add(req -> req.response().putHeader(HttpHeaderNames.ETAG, "\"bar\"").end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 2);
assertEquals(HttpCache.get(context.session).size(), 2);
assertCacheHits(ctx, req, 0);
});
// foo still cached
context.requests
.add(() -> doRequest(context, GET_TEST, (s, writer) -> writer.putHeader(HttpHeaderNames.IF_NONE_MATCH, "\"foo\"")));
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 2);
assertCacheHits(ctx, req, 1);
});
// bar still cached
context.requests
.add(() -> doRequest(context, GET_TEST, (s, writer) -> writer.putHeader(HttpHeaderNames.IF_NONE_MATCH, "\"bar\"")));
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 2);
assertCacheHits(ctx, req, 1);
checkpoint.flag();
});
test(ctx, context, true);
}
@Test
public void testWithoutCache(VertxTestContext ctx) {
// applies the same test logic of #testSimpleRequest but with cache disabled
var checkpoint = ctx.checkpoint();
Context context = new Context();
// First request
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 1);
assertCacheHits(ctx, req, 0);
});
// Second request, cached but cache is disabled, hence still 0 hits
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 2);
assertCacheHits(ctx, req, 0);
});
// POST it would have invalidated the cache, but no cache, hence still 0
context.requests.add(() -> doRequest(context, POST_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 3);
assertNull(HttpCache.get(context.session));
assertCacheHits(ctx, req, 0);
});
// 4th request is not cached as the cache is disabled
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 4);
assertCacheHits(ctx, req, 0);
});
// 5th request, it would have been cached if cache was enabled, hence still 0 hits
context.requests.add(() -> doRequest(context, GET_TEST, null));
context.serverQueue.add(req -> req.response().end());
context.handlers.add(req -> {
assertEquals(context.serverRequests.get(), 5);
assertNull(HttpCache.get(context.session));
assertTrue(context.serverQueue.isEmpty());
assertCacheHits(ctx, req, 0);
checkpoint.flag();
});
test(ctx, context, false);
}
private void assertCacheHits(VertxTestContext ctx, HttpRequest req, int hits) {
assertStats(req, snapshot -> assertEquals(HttpStats.get(snapshot).cacheHits, hits));
}
private void assertStats(HttpRequest request, Consumer<StatisticsSnapshot> consumer) {
Statistics statistics = request.statistics();
statistics.end(System.currentTimeMillis());
StatisticsSnapshot snapshot = new StatisticsSnapshot();
statistics.visitSnapshots(snapshot::add);
consumer.accept(snapshot);
}
private void test(VertxTestContext ctx, Context context, boolean cacheEnabled) {
assert !context.requests.isEmpty();
vertx.createHttpServer().requestHandler(req -> {
Consumer<HttpServerRequest> handler = context.serverQueue.poll();
if (handler == null) {
ctx.failNow("No handler for request.");
}
context.serverRequests.incrementAndGet();
assert handler != null;
handler.accept(req);
if (!req.response().ended()) {
ctx.failNow(("Response not sent"));
}
}).listen(0, "localhost", event -> {
if (event.failed()) {
ctx.failNow(event.cause());
} else {
HttpServer server = event.result();
cleanup.add(server::close);
try {
HttpBuilder builder = HttpBuilder.forTesting().host("localhost").port(server.actualPort());
HttpClientPool client = HttpClientPoolImpl.forTesting(builder.build(true), 1);
client.start(result -> {
if (result.failed()) {
ctx.failNow(result.cause());
return;
}
cleanup.add(client::shutdown);
context.session = SessionFactory.forTesting();
HttpRunData.initForTesting(context.session, CLOCK, cacheEnabled);
context.pool = client;
Objects.requireNonNull(context.requests.poll()).run();
});
} catch (Exception e) {
ctx.failNow(e);
}
}
});
}
private void doRequest(Context context, Consumer<HttpRequest> configurator,
BiConsumer<Session, HttpRequestWriter> headerAppender) {
HttpRequest request = HttpRequestPool.get(context.session).acquire();
HttpResponseHandlersImpl handlers = HttpResponseHandlersImpl.Builder.forTesting()
.onCompletion(s -> {
Consumer<HttpRequest> handler = context.handlers.poll();
if (handler != null) {
handler.accept(request);
Runnable command = context.requests.poll();
if (command == null) {
return;
}
command.run();
}
})
.build();
configurator.accept(request);
log.trace("Sending {} request to {}", request.method, request.path);
HttpConnectionPool pool = context.pool.next();
request.start(pool, handlers, new SequenceInstance(), new Statistics(System.currentTimeMillis()));
@SuppressWarnings("unchecked")
BiConsumer<Session, HttpRequestWriter>[] headerAppenders = headerAppender == null ? null
: new BiConsumer[] { headerAppender };
pool.acquire(false, connection -> request.send(connection, headerAppenders, true, null));
}
private static class Context {
Session session;
HttpClientPool pool;
Queue<Runnable> requests = new LinkedList<>();
Queue<Consumer<HttpRequest>> handlers = new LinkedList<>();
AtomicInteger serverRequests = new AtomicInteger();
Queue<Consumer<HttpServerRequest>> serverQueue = new LinkedList<>();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/BigResponseParsingTest.java | http/src/test/java/io/hyperfoil/http/BigResponseParsingTest.java | package io.hyperfoil.http;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.config.Step;
import io.hyperfoil.api.connection.Request;
import io.hyperfoil.api.processor.RawBytesHandler;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.VertxBaseTest;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.hyperfoil.http.config.Http;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.netty.buffer.ByteBuf;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class BigResponseParsingTest extends VertxBaseTest {
private HttpServer httpServer;
@BeforeEach
public void before(VertxTestContext ctx) {
httpServer = vertx.createHttpServer().requestHandler(req -> {
AtomicInteger counter = new AtomicInteger(100000);
req.response().putHeader("content-length", String.valueOf(counter.get()));
sendChunk(req, counter);
}).listen(0, "localhost", ctx.succeedingThenComplete());
cleanup.add(httpServer::close);
}
private void sendChunk(HttpServerRequest req, AtomicInteger counter) {
req.response().write(Buffer.buffer(new byte[10000]), result -> {
if (counter.addAndGet(-10000) == 0) {
req.response().end();
} else {
sendChunk(req, counter);
}
});
}
private Future<HttpClientPool> getClientPool(VertxTestContext ctx) {
Http http = HttpBuilder.forTesting().protocol(Protocol.HTTP)
.host("localhost").port(httpServer.actualPort())
.allowHttp2(false).build(true);
try {
HttpClientPool client = HttpClientPoolImpl.forTesting(http, 1);
Promise<HttpClientPool> promise = Promise.promise();
client.start(result -> {
if (result.failed()) {
ctx.failNow(result.cause());
promise.fail(result.cause());
return;
}
cleanup.add(client::shutdown);
promise.complete(client);
});
return promise.future();
} catch (SSLException e) {
return Future.failedFuture(e);
}
}
@Test
public void test(VertxTestContext ctx) {
var checkpoint = ctx.checkpoint();
AtomicInteger responseSize = new AtomicInteger();
getClientPool(ctx).onComplete(result -> {
HttpClientPool client = result.result();
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
HttpResponseHandlers handlers = HttpResponseHandlersImpl.Builder.forTesting()
.rawBytes(new RawBytesHandler() {
@Override
public void onRequest(Request request, ByteBuf buf, int offset, int length) {
}
@Override
public void onResponse(Request request, ByteBuf buf, int offset, int length, boolean isLastPart) {
responseSize.addAndGet(length);
}
})
.onCompletion(s -> {
// assertTrue(responseSize.get() > 100000, String.valueOf(responseSize.get()));
assertTrue(responseSize.get() > 100000, String.valueOf(responseSize.get()));
checkpoint.flag();
}).build();
HttpRequest newRequest = HttpRequestPool.get(session).acquire();
newRequest.method = HttpMethod.GET;
newRequest.path = "/";
SequenceInstance sequence = new SequenceInstance().reset(null, 0, new Step[0], null);
HttpConnectionPool pool = client.next();
newRequest.start(pool, handlers, sequence, new Statistics(System.currentTimeMillis()));
pool.acquire(false, c -> newRequest.send(c, null, true, null));
});
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/BaseClientTest.java | http/src/test/java/io/hyperfoil/http/BaseClientTest.java | package io.hyperfoil.http;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.VertxBaseTest;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.net.JksOptions;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxTestContext;
public class BaseClientTest extends VertxBaseTest {
protected static final List<HttpVersion> HTTP1x_ONLY = Collections.singletonList(HttpVersion.HTTP_1_1);
protected static final List<HttpVersion> HTTP2_ONLY = Collections.singletonList(HttpVersion.HTTP_2);
protected void server(boolean ssl, List<HttpVersion> serverVersions, Handler<HttpServerRequest> requestHandler,
Handler<AsyncResult<HttpServer>> listenHandler) {
HttpServer httpServer;
if (ssl) {
JksOptions keyStoreOptions = new JksOptions().setPath("keystore.jks").setPassword("test123");
HttpServerOptions httpServerOptions = new HttpServerOptions()
.setSsl(true)
.setKeyStoreOptions(keyStoreOptions)
.setUseAlpn(true)
.setAlpnVersions(serverVersions);
httpServer = vertx.createHttpServer(httpServerOptions);
httpServer.requestHandler(requestHandler).listen(0, "localhost", listenHandler);
} else {
httpServer = vertx.createHttpServer();
httpServer.requestHandler(requestHandler).listen(0, "localhost", listenHandler);
}
}
protected HttpClientPool client(int port, boolean ssl, io.hyperfoil.http.api.HttpVersion[] versions) throws Exception {
HttpBuilder builder = HttpBuilder.forTesting()
.protocol(ssl ? Protocol.HTTPS : Protocol.HTTP).host("localhost").port(port);
builder.allowHttp2(Stream.of(versions).anyMatch(v -> v == io.hyperfoil.http.api.HttpVersion.HTTP_2_0));
builder.allowHttp1x(Stream.of(versions).anyMatch(v -> v == io.hyperfoil.http.api.HttpVersion.HTTP_1_1));
return HttpClientPoolImpl.forTesting(builder.build(true), 1);
}
protected void test(VertxTestContext ctx, boolean ssl, io.hyperfoil.http.api.HttpVersion[] clientVersions,
List<HttpVersion> serverVersions, Handler<HttpServerRequest> requestHandler, ClientAction clientAction) {
var checkpoint = ctx.checkpoint();
server(ssl, serverVersions, requestHandler, event -> {
if (event.failed()) {
ctx.failNow(event.cause());
} else {
HttpServer server = event.result();
cleanup.add(server::close);
try {
HttpClientPool client = client(server.actualPort(), ssl, clientVersions);
client.start(result -> {
if (result.failed()) {
ctx.failNow(result.cause());
return;
}
cleanup.add(client::shutdown);
clientAction.run(client, checkpoint);
});
} catch (Exception e) {
ctx.failNow(e);
}
}
});
}
protected void test(VertxTestContext ctx, boolean ssl, io.hyperfoil.http.api.HttpVersion[] clientVersions,
List<HttpVersion> serverVersions, Handler<HttpServerRequest> requestHandler,
Handler<AsyncResult<Void>> clientStartHandler) {
server(ssl, serverVersions, requestHandler, event -> {
if (event.failed()) {
ctx.failNow(event.cause());
} else {
HttpServer server = event.result();
cleanup.add(server::close);
try {
HttpClientPool client = client(server.actualPort(), ssl, clientVersions);
client.start(clientStartHandler);
} catch (Exception e) {
ctx.failNow(e);
}
}
});
}
protected void sendRequestAndAssertStatus(VertxTestContext ctx, HttpClientPool client, Checkpoint checkpoint,
HttpMethod method, String path, int expectedStatus) {
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
HttpRequest request = HttpRequestPool.get(session).acquire();
AtomicBoolean statusReceived = new AtomicBoolean(false);
HttpResponseHandlers handlers = HttpResponseHandlersImpl.Builder.forTesting()
.status((r, status) -> {
if (status != expectedStatus) {
ctx.failNow("Status differs from the expected one");
} else {
statusReceived.set(true);
}
})
.onCompletion(s -> {
if (statusReceived.get()) {
checkpoint.flag();
} else {
ctx.failNow("Status was not received.");
}
}).build();
request.method = method;
request.path = path;
HttpConnectionPool pool = client.next();
request.start(pool, handlers, new SequenceInstance(), new Statistics(System.currentTimeMillis()));
pool.acquire(false, c -> request.send(c, null, true, null));
}
@FunctionalInterface
protected interface ClientAction {
void run(HttpClientPool client, Checkpoint checkpoint);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/HttpDecodeSpaceTest.java | http/src/test/java/io/hyperfoil/http/HttpDecodeSpaceTest.java | package io.hyperfoil.http;
import java.util.List;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpVersion;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.junit5.VertxTestContext;
public class HttpDecodeSpaceTest extends BaseClientTest {
@Test
public void testSimpleHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY, "/ping");
}
@Test
public void testSimpleHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY, "/ping");
}
@Test
public void testSpaceBeforeHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY, "/ping pong?rules");
}
@Test
public void testSpaceBeforeHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY, "/ping pong?rules");
}
@Test
public void testSpaceAfterHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY, "/ping?pong rules");
}
@Test
public void testSpaceAfterHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY, "/ping?pong rules");
}
@Test
public void testSpaceBeforeAfterHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY, "/ping pong?rules one");
}
@Test
public void testSpaceBeforeAfterHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY, "/ping pong?rules one");
}
@Test
public void testSpacesHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY, "/ping ping pong pong?rules one two three four");
}
@Test
public void testSpacesHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY, "/ping ping pong pong?rules one two three four");
}
@Test
public void testComplexHttp1x(VertxTestContext ctx) {
test(ctx, HTTP1x_ONLY,
"/oidc/endpoint/OP/authorize me?client_id=nc4b29d8d4myasad9a9ptn9ossihjs1y&response_type=code&scope=openid email profile&redirect_uri=https://cp-console.mosss-f6522d190538f009b13c287376c6106d-0000.us-east.containers.appdomain.cloud:443/auth/liberty/callback&state=1611152679");
}
@Test
public void testComplexHttp2(VertxTestContext ctx) {
test(ctx, HTTP2_ONLY,
"/oidc/endpoint/OP/authorize me?client_id=nc4b29d8d4myasad9a9ptn9ossihjs1y&response_type=code&scope=openid email profile&redirect_uri=https://cp-console.mosss-f6522d190538f009b13c287376c6106d-0000.us-east.containers.appdomain.cloud:443/auth/liberty/callback&state=1611152679");
}
private void test(VertxTestContext ctx, List<io.vertx.core.http.HttpVersion> serverVersions, String path) {
test(ctx, true, HttpVersion.ALL_VERSIONS, serverVersions, HttpDecodeSpaceTest::isPathCorrect,
(client, checkpoint) -> sendRequestAndAssertStatus(ctx, client, checkpoint, HttpMethod.GET, path, 200));
}
private static void isPathCorrect(HttpServerRequest req) {
int status;
String url = req.uri();
if (url.contains(" ")) {
status = 600;
} else {
int question = url.indexOf("?");
String subFirst = "";
String subSecond = "";
if (question != -1) {
subFirst = url.substring(0, question);
subSecond = url.substring(url.lastIndexOf("?") + 1);
if (subFirst.contains("+")) {
status = 601;
} else {
status = 200;
}
if (status == 200 && subSecond.contains("%20")) {
status = 602;
}
} else {
status = 200;
}
}
req.response().setStatusCode(status).end("Hello");
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/HttpVersionsTest.java | http/src/test/java/io/hyperfoil/http/HttpVersionsTest.java | package io.hyperfoil.http;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpVersion;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class HttpVersionsTest extends BaseClientTest {
@Test
public void testAlpnUpgrade(VertxTestContext ctx) {
test(ctx, true, HttpVersion.ALL_VERSIONS, HTTP2_ONLY, 200);
}
@Test
public void testAlpnKeep(VertxTestContext ctx) {
test(ctx, true, HttpVersion.ALL_VERSIONS, HTTP1x_ONLY, 500);
}
@Test
public void testAlpnForceHttp2(VertxTestContext ctx) {
test(ctx, true, new HttpVersion[] { HttpVersion.HTTP_2_0 }, HTTP2_ONLY, 200);
}
@Test
public void testAlpnForceHttp2ServerKeep(VertxTestContext ctx) {
test(ctx, true, new HttpVersion[] { HttpVersion.HTTP_2_0 }, HTTP1x_ONLY, HttpVersionsTest::requireHttp2,
ctx.failingThenComplete());
}
@Test
public void testAlpnForceHttp1x(VertxTestContext ctx) {
test(ctx, true, new HttpVersion[] { HttpVersion.HTTP_1_1 }, HTTP2_ONLY, HttpVersionsTest::requireHttp2,
ctx.failingThenComplete());
}
@Test
public void testH2cUpgrade(VertxTestContext ctx) {
test(ctx, false, new HttpVersion[] { HttpVersion.HTTP_2_0 }, HTTP2_ONLY, 200);
}
@Test
public void testCleartextDefault(VertxTestContext ctx) {
test(ctx, false, HttpVersion.ALL_VERSIONS, HTTP2_ONLY, 500);
}
@Test
public void testCleartextDefaultServer1x(VertxTestContext ctx) {
test(ctx, false, HttpVersion.ALL_VERSIONS, HTTP1x_ONLY, 500);
}
@Test
public void testCleartextForceHttp1x(VertxTestContext ctx) {
test(ctx, false, new HttpVersion[] { HttpVersion.HTTP_1_1 }, HTTP2_ONLY, 500);
}
private void test(VertxTestContext ctx, boolean ssl, HttpVersion[] clientVersions,
List<io.vertx.core.http.HttpVersion> serverVersions, int expectedStatus) {
test(ctx, ssl, clientVersions, serverVersions, HttpVersionsTest::requireHttp2,
(client, checkpoint) -> sendRequestAndAssertStatus(ctx, client, checkpoint, HttpMethod.GET, "/ping",
expectedStatus));
}
private static void requireHttp2(HttpServerRequest req) {
if (req.version() != io.vertx.core.http.HttpVersion.HTTP_2) {
req.response().setStatusCode(500).end("HTTP/2 required.");
} else {
req.response().setStatusCode(200).end("Hello");
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/HttpClientPoolHandlerTest.java | http/src/test/java/io/hyperfoil/http/HttpClientPoolHandlerTest.java | /*
* Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hyperfoil.http;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.config.Http;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class HttpClientPoolHandlerTest {
protected AtomicInteger count;
private HttpServer httpServer;
@BeforeEach
public void before(Vertx vertx, VertxTestContext ctx) {
count = new AtomicInteger(0);
httpServer = vertx.createHttpServer().requestHandler(req -> {
count.getAndIncrement();
req.response().putHeader("foo", "bar").end("hello from server");
}).listen(0, "localhost", ctx.succeedingThenComplete());
}
@Test
public void simpleHeaderRequest(VertxTestContext ctx) throws Exception {
Http http = HttpBuilder.forTesting().host("localhost").port(httpServer.actualPort()).build(true);
HttpClientPool client = HttpClientPoolImpl.forTesting(http, 1);
var checkpoint = ctx.checkpoint(5);
CountDownLatch startLatch = new CountDownLatch(1);
client.start(result -> {
if (result.failed()) {
ctx.failNow(result.cause());
} else {
startLatch.countDown();
checkpoint.flag();
}
});
assertThat(startLatch.await(10, TimeUnit.SECONDS)).isTrue();
CountDownLatch latch = new CountDownLatch(4);
HttpConnectionPool pool = client.next();
pool.executor().execute(() -> {
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
HttpRequest request = HttpRequestPool.get(session).acquire();
HttpResponseHandlersImpl handlers = HttpResponseHandlersImpl.Builder.forTesting()
.status((r, code) -> {
ctx.verify(() -> {
assertThat(code).isEqualTo(200);
checkpoint.flag();
});
latch.countDown();
})
.header((req, header, value) -> {
if ("foo".contentEquals(header)) {
ctx.verify(() -> {
assertThat(value.toString()).asString().isEqualTo("bar");
checkpoint.flag();
});
latch.countDown();
}
})
.body(f -> (s, input, offset, length, isLastPart) -> {
byte[] bytes = new byte[length];
input.getBytes(offset, bytes);
ctx.verify(() -> {
assertThat(new String(bytes)).isEqualTo("hello from server");
checkpoint.flag();
});
latch.countDown();
})
.onCompletion(s -> {
latch.countDown();
checkpoint.flag();
})
.build();
request.method = HttpMethod.GET;
request.path = "/";
request.start(pool, handlers, new SequenceInstance(), new Statistics(System.currentTimeMillis()));
pool.acquire(false, c -> request.send(c, null, true, null));
});
assertThat(latch.await(3, TimeUnit.SECONDS)).isTrue();
assertThat(count.get()).isEqualTo(1);
client.shutdown();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/MemoryUsageTest.java | http/src/test/java/io/hyperfoil/http/MemoryUsageTest.java | package io.hyperfoil.http;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.net.JksOptions;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class MemoryUsageTest {
@Test
public void testPlainHttp1x(VertxTestContext context) {
test(context, new HttpServerOptions().setSsl(false));
}
@Test
public void testEncryptHttp1x(VertxTestContext context) {
HttpServerOptions serverOptions = new HttpServerOptions().setSsl(true)
.setKeyStoreOptions(new JksOptions().setPath("keystore.jks").setPassword("test123"))
.setUseAlpn(true).setAlpnVersions(Collections.singletonList(HttpVersion.HTTP_1_1));
test(context, serverOptions);
}
@Test
public void testEncryptHttp2(VertxTestContext context) {
HttpServerOptions serverOptions = new HttpServerOptions().setSsl(true)
.setKeyStoreOptions(new JksOptions().setPath("keystore.jks").setPassword("test123"))
.setUseAlpn(true).setAlpnVersions(Collections.singletonList(HttpVersion.HTTP_2));
test(context, serverOptions);
}
protected void test(VertxTestContext context, HttpServerOptions serverOptions) {
var checkpoint = context.checkpoint(200);
AtomicLong seenMemoryUsage = new AtomicLong(-1);
Handler<HttpServer> handler = server -> {
try {
HttpClientPool client = client(serverOptions.isSsl() ? Protocol.HTTPS : Protocol.HTTP, server.actualPort());
client.start(context.succeeding(nil -> {
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
HttpConnectionPool pool = client.next();
doRequest(pool, session, context, checkpoint, seenMemoryUsage);
}));
} catch (SSLException e) {
server.close();
context.failNow(e);
}
};
Vertx.vertx().createHttpServer(serverOptions)
.requestHandler(ctx -> ctx.response()
.putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
.end(Buffer.buffer(new byte[4 * 1024 * 1024])))
.listen(0, "localhost", context.succeeding(handler));
}
private HttpClientPool client(Protocol protocol, int port) throws SSLException {
HttpBuilder builder = HttpBuilder.forTesting()
.protocol(protocol).host("localhost").port(port);
return HttpClientPoolImpl.forTesting(builder.build(true), 1);
}
private void doRequest(HttpConnectionPool pool, Session session, VertxTestContext context, Checkpoint checkpoint,
AtomicLong seenMemoryUsage) {
checkpoint.flag();
// TODO: I don't know the reason for that but I couldn't refactor using Checkpoint
// if (async.count() % 100 == 0) {
// System.gc();
// }
// if (async.count() <= 0) {
// return;
// }
HttpRequest request = HttpRequestPool.get(session).acquire();
HttpResponseHandlers handlers = HttpResponseHandlersImpl.Builder.forTesting()
.body(fragmented -> (session1, data, offset, length, isLastPart) -> {
ByteBufAllocator alloc = data.alloc();
if (!data.isDirect()) {
context.failNow("Expecting to use direct buffers");
} else if (alloc instanceof PooledByteBufAllocator) {
long usedMemory = ((PooledByteBufAllocator) alloc).metric().usedDirectMemory();
if (usedMemory < 0) {
context.failNow("Cannot fetch direct memory stats");
}
long seen = seenMemoryUsage.get();
if (seen < 0) {
seenMemoryUsage.compareAndSet(seen, usedMemory);
} else if (usedMemory >= 2 * seen) {
context.failNow("Used memory seems to be growing from " + seen + " to " + usedMemory);
}
} else {
context.failNow("Buffers are not pooled");
}
})
.onCompletion(s -> pool.executor().schedule(() -> doRequest(pool, session, context, checkpoint, seenMemoryUsage), 1,
TimeUnit.MILLISECONDS))
.build();
request.path = "/";
request.method = HttpMethod.GET;
request.handlers = handlers;
request.start(pool, handlers, new SequenceInstance(), new Statistics(System.currentTimeMillis()));
pool.acquire(false, connection -> request.send(connection, null, true, null));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/ChunkedTransferTest.java | http/src/test/java/io/hyperfoil/http/ChunkedTransferTest.java | package io.hyperfoil.http;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.BaseSequenceBuilder;
import io.hyperfoil.api.config.Locator;
import io.hyperfoil.api.connection.Request;
import io.hyperfoil.api.processor.RawBytesHandler;
import io.hyperfoil.core.data.DataFormat;
import io.hyperfoil.core.handlers.StoreProcessor;
import io.hyperfoil.core.handlers.json.JsonHandler;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.core.test.TestUtil;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpDestinationTable;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.impl.Util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.vertx.core.http.HttpServerResponse;
public class ChunkedTransferTest extends BaseHttpScenarioTest {
public static final String SHIBBOLETH = "Shibboleth";
private static final int FOO_VALUE_SIZE = 10 * 1024 * 1024;
private String fooValue;
@Override
protected void initHttp(HttpBuilder http) {
http.pipeliningLimit(2);
}
@Override
protected void initRouter() {
router.route("/test").handler(ctx -> {
HttpServerResponse response = ctx.response();
response.setChunked(true);
response.write("Foo");
response.write("Bar");
response.putTrailer("Custom", "Trailer");
response.end();
});
router.route("/test2").handler(ctx -> {
ctx.response().end(SHIBBOLETH);
});
router.route("/test3").handler(ctx -> {
HttpServerResponse response = ctx.response().setChunked(true);
ThreadLocalRandom rand = ThreadLocalRandom.current();
for (int i = 0; i < 3; ++i) {
response.write(TestUtil.randomString(rand, 100));
}
response.end();
});
router.route("/test4").handler(ctx -> {
if (fooValue == null) {
final byte[] hugeValue = new byte[FOO_VALUE_SIZE];
Arrays.fill(hugeValue, (byte) 'a');
final String hugeValueString = new String(hugeValue, 0, 0, hugeValue.length);
fooValue = hugeValueString;
}
HttpServerResponse response = ctx.response().setChunked(true);
response.write("{");
// many useless crap ones
for (int i = 0; i < 100; i++) {
response.write("\"crap" + i + "\":\"crap\",");
}
response.write("\"foo\":\"");
response.write(fooValue);
response.write("\"}");
response.end();
});
}
@Test
public void testChunkedJsonTransfer() {
var capturedValue = new AtomicReference<>();
Locator.push(TestUtil.locator());
var fooValueReadAccess = SessionFactory.readAccess("foo");
Locator.pop();
// @formatter:off
scenario().initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET).path("/test4")
.handler()
.body(new JsonHandler.Builder().query(".foo")
.processors().processor(new StoreProcessor.Builder().toVar("foo").format(DataFormat.STRING)).end())
.endHandler()
.sync(true)
.endStep()
.step(s -> {
capturedValue.set(fooValueReadAccess.getObject(s));
return true;
})
.endSequence();
// @formatter:on
runScenario();
assertNotNull(capturedValue.get());
assertNotNull(fooValue);
// we're not using equals because the string is too long and will blow the test output on failure!
assertTrue(fooValue.equals(capturedValue.get()));
}
@Test
public void testChunkedTransfer() {
AtomicBoolean rawBytesSeen = new AtomicBoolean(false);
// @formatter:off
scenario().initialSequence("test")
.step(s -> {
HttpDestinationTable.get(s).getConnectionPoolByAuthority(null).connections()
.forEach(c -> injectChannelHandler(c, new BufferingDecoder()));
return true;
})
.step(SC).httpRequest(HttpMethod.GET).path("/test")
.headers().header(HttpHeaderNames.CACHE_CONTROL, "no-cache").endHeaders()
.handler().rawBytes(new RawBytesHandler() {
@Override
public void onRequest(Request request, ByteBuf buf, int offset, int length) {
}
@Override
public void onResponse(Request request, ByteBuf byteBuf, int offset, int length, boolean isLastPart) {
log.info("Received chunk {} bytes:\n{}", length,
byteBuf.toString(offset, length, StandardCharsets.UTF_8));
if (byteBuf.toString(StandardCharsets.UTF_8).contains(SHIBBOLETH)) {
throw new IllegalStateException();
}
rawBytesSeen.set(true);
}
}).endHandler()
.sync(false)
.endStep()
.step(SC).httpRequest(HttpMethod.GET)
.path("/test2")
.sync(false)
.endStep()
.step(SC).awaitAllResponses()
.endSequence();
// @formatter:on
runScenario();
assertThat(rawBytesSeen).isTrue();
}
@Test
public void testRandomCutBuffers() {
BaseSequenceBuilder<?> sequence = scenario(64).initialSequence("test")
.step(s -> {
HttpDestinationTable.get(s).getConnectionPoolByAuthority(null).connections()
.forEach(c -> injectChannelHandler(c, new RandomLengthDecoder()));
return true;
});
AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < 16; ++i) {
sequence.step(SC).httpRequest(HttpMethod.GET).path("/test3")
.headers().header("cache-control", "no-cache").endHeaders()
.sync(false)
.handler()
.body(fragmented -> (session, data, offset, length, isLastPart) -> {
String str = Util.toString(data, offset, length);
if (str.contains("\n")) {
session.fail(new AssertionError(str));
}
})
.onCompletion(s -> counter.incrementAndGet());
}
sequence.step(SC).awaitAllResponses();
runScenario();
assertThat(counter.get()).isEqualTo(16 * 64);
}
private static void injectChannelHandler(HttpConnection c, ChannelHandler channelHandler) {
try {
Field f = c.getClass().getDeclaredField("ctx");
f.setAccessible(true);
ChannelHandlerContext ctx = (ChannelHandlerContext) f.get(c);
if (ctx.pipeline().first().getClass() != channelHandler.getClass()) {
// Do not inject multiple times
ctx.pipeline().addFirst(channelHandler);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException();
}
}
private static class BufferingDecoder extends ChannelInboundHandlerAdapter {
CompositeByteBuf composite = null;
boolean buffering = true;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (buffering && msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
if (composite == null) {
composite = new CompositeByteBuf(buf.alloc(), buf.isDirect(), 2, buf);
} else {
composite.addComponent(true, buf);
}
if (composite.toString(StandardCharsets.UTF_8).contains(SHIBBOLETH)) {
buffering = false;
super.channelRead(ctx, composite);
}
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
if (composite != null && composite.refCnt() > 0) {
composite.release();
}
}
}
private static class RandomLengthDecoder extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
ThreadLocalRandom rand = ThreadLocalRandom.current();
int curr = 0;
if (buf.readableBytes() == 0) {
ctx.fireChannelRead(buf);
return;
}
while (curr + buf.readerIndex() < buf.writerIndex()) {
int len = rand.nextInt(buf.readableBytes() + 1);
ByteBuf slice = buf.retainedSlice(buf.readerIndex() + curr,
Math.min(buf.writerIndex(), buf.readerIndex() + curr + len) - curr - buf.readerIndex());
ctx.fireChannelRead(slice);
curr += len;
}
buf.release();
} else {
super.channelRead(ctx, msg);
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/TwoServersTest.java | http/src/test/java/io/hyperfoil/http/TwoServersTest.java | package io.hyperfoil.http;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.config.BenchmarkBuilder;
import io.hyperfoil.api.config.BenchmarkDefinitionException;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.statistics.HttpStats;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class TwoServersTest extends BaseHttpScenarioTest {
HttpServer secondServer;
@Override
protected void initRouter() {
router.route("/test").handler(ctx -> ctx.response().setStatusCode(200).end());
}
@BeforeEach
public void before(Vertx vertx, VertxTestContext ctx) {
super.before(vertx, ctx);
Router secondRouter = Router.router(vertx);
secondRouter.route("/test").handler(context -> context.response().setStatusCode(300).end());
var secondServerLatch = new CountDownLatch(1);
secondServer = vertx.createHttpServer().requestHandler(secondRouter)
.listen(0, "localhost", ctx.succeeding(srv -> {
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:" + srv.actualPort()).endHttp();
ctx.completeNow();
secondServerLatch.countDown();
}));
try {
secondServerLatch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
ctx.failNow(e);
}
}
@Test
public void testTwoServers(VertxTestContext ctx) throws InterruptedException {
var checkpoint = ctx.checkpoint(2);
// @formatter:off
scenario().initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path("/test")
.sync(false)
.metric("server1")
.handler()
.onCompletion(s -> checkpoint.flag())
.endHandler()
.endStep()
.step(SC).httpRequest(HttpMethod.GET)
.authority("localhost:" + secondServer.actualPort())
.path("/test")
.sync(false)
.metric("server2")
.handler()
.onCompletion(s -> checkpoint.flag())
.endHandler()
.endStep()
.step(SC).awaitAllResponses();
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
StatisticsSnapshot s1 = stats.get("server1");
assertThat(HttpStats.get(s1).status_2xx).isEqualTo(1);
StatisticsSnapshot s2 = stats.get("server2");
assertThat(HttpStats.get(s2).status_3xx).isEqualTo(1);
}
@Test
public void testMultiHostWithoutAuthorityFail() {
// Test that a multi-host HTTP configuration is not accepted when steps does not define a host to run.
// See: https://github.com/Hyperfoil/Hyperfoil/issues/315
// Override the default builder creation by the test.
benchmarkBuilder = BenchmarkBuilder.builder();
benchmarkBuilder.threads(threads());
benchmarkBuilder.addPlugin(HttpPluginBuilder::new);
// Define hosts *without* default HTTP server.
// Note that, utilizing the YAML configuration there is no way to define the default host.
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:" + server.actualPort())
.name("host-1");
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:" + secondServer.actualPort())
.name("host-2");
// A single step is enough.
scenario().initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path("/test")
.endStep();
// Fails to build since we haven't defined the authority for which server to utilize in the step.
assertThrows(BenchmarkDefinitionException.class, () -> benchmarkBuilder.build());
}
@Test
public void testServersWithSameHostAndPortAndDifferentName() {
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name("myhost1");
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name("myhost2");
benchmarkBuilder.build();
}
@Test
public void testServersWithSameHostAndPortAndSameName() {
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name("myhost1");
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name("myhost1");
assertThrows(BenchmarkDefinitionException.class, () -> benchmarkBuilder.build());
}
@Test
public void testServersWithSameHostAndPortAndNoName() {
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name(null);
benchmarkBuilder.plugin(HttpPluginBuilder.class)
.http("http://localhost:8080")
.name(null);
assertThrows(BenchmarkDefinitionException.class, () -> benchmarkBuilder.build());
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/RawBytesHandlerTest.java | http/src/test/java/io/hyperfoil/http/RawBytesHandlerTest.java | package io.hyperfoil.http;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Step;
import io.hyperfoil.api.connection.Request;
import io.hyperfoil.api.processor.RawBytesHandler;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.VertxBaseTest;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.core.test.TestUtil;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.hyperfoil.http.config.Http;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.netty.buffer.ByteBuf;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.junit5.VertxTestContext;
public class RawBytesHandlerTest extends VertxBaseTest {
private AtomicInteger numberOfPasses;
@BeforeEach
public void init() {
numberOfPasses = new AtomicInteger(1000);
}
@Test
public void test(Vertx vertx, VertxTestContext ctx) {
var checkpoint = ctx.checkpoint(numberOfPasses.get());
HttpServer httpServer = vertx.createHttpServer();
httpServer.requestHandler(this::handler).listen(0, "localhost", event -> {
if (event.failed()) {
ctx.failNow(event.cause());
} else {
HttpServer server = event.result();
cleanup.add(server::close);
try {
Http http = HttpBuilder.forTesting().protocol(Protocol.HTTP)
.host("localhost").port(server.actualPort())
.allowHttp2(false).build(true);
HttpClientPool client = HttpClientPoolImpl.forTesting(http, 1);
client.start(result -> {
if (result.failed()) {
ctx.failNow(result.cause());
return;
}
cleanup.add(client::shutdown);
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
AtomicReference<HttpResponseHandlers> handlersRef = new AtomicReference<>();
handlersRef.set(HttpResponseHandlersImpl.Builder.forTesting()
.rawBytes(new RawBytesHandler() {
@Override
public void onRequest(Request request, ByteBuf buf, int offset, int length) {
}
@Override
public void onResponse(Request request, ByteBuf buf, int offset, int length, boolean isLastPart) {
}
})
.onCompletion(s -> {
checkpoint.flag();
if (numberOfPasses.decrementAndGet() > 0) {
// we did not reach the required/expected num of passes
HttpConnectionPool pool = client.next();
pool.executor().schedule(() -> {
doRequest(session, handlersRef, pool);
}, 1, TimeUnit.NANOSECONDS);
}
}).build());
doRequest(session, handlersRef, client.next());
});
} catch (Exception e) {
ctx.failNow(e);
}
}
});
}
private void doRequest(Session session, AtomicReference<HttpResponseHandlers> handlersRef,
HttpConnectionPool pool) {
HttpRequest newRequest = HttpRequestPool.get(session).acquire();
newRequest.method = HttpMethod.GET;
newRequest.path = "/ping";
newRequest.cacheControl.noCache = true;
SequenceInstance sequence = new SequenceInstance();
sequence.reset(null, 0, new Step[0], null);
newRequest.start(pool, handlersRef.get(), sequence, new Statistics(System.currentTimeMillis()));
pool.acquire(false, c -> newRequest.send(c, null, true, null));
}
private void handler(HttpServerRequest request) {
ThreadLocalRandom rand = ThreadLocalRandom.current();
int headers = rand.nextInt(10);
for (int i = 0; i < headers; ++i) {
request.response().putHeader("x-foobar-" + i, TestUtil.randomString(rand, 100));
}
request.response().setChunked(true);
request.response().end(TestUtil.randomString(rand, 2000));
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/BaseHttpScenarioTest.java | http/src/test/java/io/hyperfoil/http/BaseHttpScenarioTest.java | package io.hyperfoil.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.core.parser.BenchmarkParser;
import io.hyperfoil.core.parser.ParserException;
import io.hyperfoil.core.session.BaseScenarioTest;
import io.hyperfoil.core.test.TestUtil;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.impl.Util;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.net.JksOptions;
import io.vertx.ext.web.Router;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public abstract class BaseHttpScenarioTest extends BaseScenarioTest {
protected Vertx vertx;
protected Router router;
protected HttpServer server;
@BeforeEach
public void before(Vertx vertx, VertxTestContext ctx) {
super.before();
this.vertx = vertx;
router = Router.router(vertx);
initRouter();
benchmarkBuilder.addPlugin(HttpPluginBuilder::new);
var serverLatch = new CountDownLatch(1);
startServer(ctx).onComplete(ctx.succeedingThenComplete()).onComplete(event -> {
if (event.succeeded()) {
serverLatch.countDown();
}
});
try {
serverLatch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
ctx.failNow(e);
}
}
protected Future<Void> startServer(VertxTestContext ctx) {
boolean tls = useHttps();
boolean compression = useCompression();
HttpServerOptions options = new HttpServerOptions();
if (tls) {
options.setSsl(true).setUseAlpn(true)
.setKeyStoreOptions(new JksOptions().setPath("keystore.jks").setPassword("test123"));
}
if (compression) {
options.setCompressionSupported(true);
}
Promise<Void> promise = Promise.promise();
server = vertx.createHttpServer(options)
.requestHandler(router)
.listen(0, "localhost", ctx.succeeding(srv -> {
initWithServer(srv, tls);
promise.complete();
ctx.completeNow();
}));
return promise.future();
}
// override me
protected boolean useHttps() {
return false;
}
protected boolean useCompression() {
return false;
}
protected void initWithServer(HttpServer srv, boolean tls) {
HttpPluginBuilder httpPlugin = benchmarkBuilder.plugin(HttpPluginBuilder.class);
HttpBuilder http = httpPlugin.http();
http.protocol(tls ? Protocol.HTTPS : Protocol.HTTP)
.name("myhost")
.host("localhost").port(srv.actualPort());
initHttp(http);
}
protected void initHttp(HttpBuilder http) {
}
protected abstract void initRouter();
@Override
protected Benchmark loadBenchmark(InputStream config) throws IOException, ParserException {
return BenchmarkParser.instance().buildBenchmark(
config, TestUtil.benchmarkData(), Map.of("PORT", String.valueOf(server.actualPort())));
}
protected void serveResourceChunked(io.vertx.ext.web.RoutingContext ctx, String resource) {
try {
InputStream index = getClass().getClassLoader().getResourceAsStream(resource);
String html = Util.toString(index);
// We'll send the body in two chunks to make sure the code works even if the body is not delivered in one row
ctx.response().setChunked(true);
int bodyStartIndex = html.indexOf("<body>");
ctx.response().write(html.substring(0, bodyStartIndex), result -> vertx.setTimer(100, ignores -> {
ctx.response().write(html.substring(bodyStartIndex));
ctx.response().end();
}));
} catch (IOException e) {
ctx.response().setStatusCode(500).end();
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/CloseConnectionTest.java | http/src/test/java/io/hyperfoil/http/CloseConnectionTest.java | package io.hyperfoil.http;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.processor.Processor;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.handlers.CloseConnectionHandler;
import io.hyperfoil.http.api.HttpMethod;
import io.netty.buffer.ByteBuf;
public class CloseConnectionTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.get("/body").handler(ctx -> {
ctx.response().end("Hello");
});
router.get("/nobody").handler(ctx -> {
ctx.response().end();
});
}
private void test(String path) {
AtomicBoolean closed = new AtomicBoolean(false);
// @formatter:off
scenario()
.initialSequence("test")
.step(SC).httpRequest(HttpMethod.POST)
.path(path)
.handler()
.body(new CloseConnectionHandler.Builder())
.body(f -> new TestProcessor(closed))
.endHandler()
.endStep();
// @formatter:on
runScenario();
assertThat(closed.get()).isTrue();
}
@Test
public void testWithBody() {
test("/body");
}
@Test
public void testWithoutBody() {
test("/nobody");
}
private static class TestProcessor implements Processor {
private final AtomicBoolean closed;
private TestProcessor(AtomicBoolean closed) {
this.closed = closed;
}
@Override
public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) {
// ignore
}
@Override
public void after(Session session) {
closed.set(session.currentRequest().connection().isClosed());
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/FollowRedirectTest.java | http/src/test/java/io/hyperfoil/http/FollowRedirectTest.java | package io.hyperfoil.http;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.config.Model;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.api.FollowRedirect;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.statistics.HttpStats;
import io.hyperfoil.http.steps.HttpStepCatalog;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
public class FollowRedirectTest extends BaseHttpScenarioTest {
private final AtomicInteger redirects = new AtomicInteger();
private final AtomicInteger notFound = new AtomicInteger();
@BeforeEach
public void resetRedirects() {
redirects.set(0);
notFound.set(0);
}
@Override
protected void initRouter() {
router.route().handler(ctx -> {
ctx.response().putHeader(HttpHeaders.CACHE_CONTROL, "no-store");
ctx.next();
});
router.route("/redirectMeViaLocation").handler(this::redirectViaLocation);
router.route("/redirectMeViaHtml").handler(this::redirectViaHtml);
router.route("/redirectMeSomehow").handler(ctx -> {
if (ThreadLocalRandom.current().nextBoolean()) {
redirectViaLocation(ctx);
} else {
redirectViaHtml(ctx);
}
});
router.route("/somewhereElse").handler(ctx -> {
if (!ensureHeaders(ctx)) {
return;
}
ctx.response().end("this is the response");
});
router.route("/redirect/me/relatively")
.handler(ctx -> ctx.response().putHeader(HttpHeaders.LOCATION, "elsewhere").setStatusCode(302).end());
router.route("/redirect/me/elsewhere").handler(ctx -> ctx.response()
.end("<html><head><meta http-equiv=\"refresh\" content=\"0; URL=../theEnd\" /></head></html>"));
router.route("/redirect/theEnd").handler(ctx -> ctx.response().end("Final destination"));
}
private void redirectViaHtml(RoutingContext ctx) {
if (!ensureHeaders(ctx)) {
return;
}
ThreadLocalRandom random = ThreadLocalRandom.current();
if (random.nextBoolean()) {
String refreshContent = random.nextInt(2) + "; url=" + target(ctx);
ctx.response().end("<html><head><meta http-equiv=\"refresh\" content=\"" + refreshContent + "\" /></head></html>");
redirects.incrementAndGet();
} else {
if (random.nextBoolean()) {
ctx.response().end("this is the response");
} else {
notFound.incrementAndGet();
ctx.response().setStatusCode(404).end("Not Found (sort of)");
}
}
}
private void redirectViaLocation(RoutingContext ctx) {
if (!ensureHeaders(ctx)) {
return;
}
ThreadLocalRandom random = ThreadLocalRandom.current();
if (random.nextBoolean()) {
ctx.response().putHeader(HttpHeaders.LOCATION, target(ctx)).setStatusCode(303).end();
redirects.incrementAndGet();
} else {
if (random.nextBoolean()) {
ctx.response().end("this is the response");
} else {
notFound.incrementAndGet();
ctx.response().setStatusCode(404).end("Not Found (sort of)");
}
}
}
private String target(RoutingContext ctx) {
boolean allowRecursion = "yes".equals(ctx.request().getParam("allowRecurse"));
return allowRecursion && ThreadLocalRandom.current().nextBoolean() ? ctx.request().path() + "?allowRecurse=yes"
: "/somewhereElse";
}
private boolean ensureHeaders(io.vertx.ext.web.RoutingContext ctx) {
if (!ctx.request().getHeader("x-preserve").equals("repeat me with redirect")) {
log.error("Missing header x-preserve");
ctx.response().setStatusCode(500).end("Missing or incorrect x-preserve header");
return false;
}
return true;
}
@Test
public void testManual() {
Benchmark benchmark = loadScenario("scenarios/FollowRedirectTest_manual.hf.yaml");
int users = benchmark.phases().stream().filter(p -> "testPhase".equals(p.name()))
.mapToInt(p -> ((Model.AtOnce) p.model).users).findFirst().orElse(0);
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
HttpStats redirectMe = HttpStats.get(stats.get("redirectMe"));
assertThat(redirectMe.status_3xx).isEqualTo(redirects.get());
assertThat(redirectMe.status_2xx).isEqualTo(users - redirects.get() - notFound.get());
assertThat(redirectMe.status_4xx).isEqualTo(notFound.get());
HttpStats redirectMe_redirect = HttpStats.get(stats.get("redirectMe_redirect"));
assertThat(redirectMe_redirect.status_2xx).isEqualTo(redirects.get());
}
@Test
public void testLocation() {
Benchmark benchmark = loadScenario("scenarios/FollowRedirectTest_location.hf.yaml");
int users = benchmark.phases().stream().filter(p -> "testPhase".equals(p.name()))
.mapToInt(p -> ((Model.AtOnce) p.model).users).findFirst().orElse(0);
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
HttpStats redirectMe = HttpStats.get(stats.get("redirectMe"));
String redirectMetric = stats.keySet().stream().filter(m -> !m.equals("redirectMe")).findFirst().orElse(null);
if (redirectMetric == null) {
// rare case when we'd not get any redirects
assertThat(redirectMe.status_2xx).isEqualTo(users - notFound.get());
assertThat(redirectMe.status_3xx).isEqualTo(0);
assertThat(redirectMe.status_4xx).isEqualTo(notFound.get());
assertThat(redirects.get()).isEqualTo(0);
} else {
HttpStats redirectStats = HttpStats.get(stats.get(redirectMetric));
assertThat(redirectMe.status_2xx + redirectStats.status_2xx).isEqualTo(users - notFound.get());
assertThat(redirectMe.status_3xx + redirectStats.status_3xx).isEqualTo(redirects.get());
assertThat(redirectMe.status_4xx + redirectStats.status_4xx).isEqualTo(notFound.get());
}
}
@Test
public void testHtmlOnly() {
Benchmark benchmark = loadScenario("scenarios/FollowRedirectTest_html.hf.yaml");
int users = benchmark.phases().stream().filter(p -> "testPhase".equals(p.name()))
.mapToInt(p -> ((Model.AtOnce) p.model).users).findFirst().orElse(0);
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
HttpStats redirectMe = HttpStats.get(stats.get("redirectMe"));
String redirectMetric = stats.keySet().stream().filter(m -> !m.equals("redirectMe")).findFirst().orElse(null);
if (redirectMetric == null) {
// rare case when we'd not get any redirects
assertThat(redirects.get()).isEqualTo(0);
assertThat(redirectMe.status_2xx).isEqualTo(users - notFound.get());
assertThat(redirectMe.status_4xx).isEqualTo(notFound.get());
} else {
HttpStats redirectStats = HttpStats.get(stats.get(redirectMetric));
assertThat(redirectStats.status_2xx + redirectMe.status_2xx).isEqualTo(users + redirects.get() - notFound.get());
assertThat(redirectStats.status_3xx).isEqualTo(0);
assertThat(redirectStats.status_4xx + redirectMe.status_4xx).isEqualTo(notFound.get());
}
assertThat(redirectMe.status_3xx).isEqualTo(0);
}
@Test
public void testAlways() {
Benchmark benchmark = loadScenario("scenarios/FollowRedirectTest_always.hf.yaml");
int users = benchmark.phases().stream().filter(p -> "testPhase".equals(p.name()))
.mapToInt(p -> ((Model.AtOnce) p.model).users).findFirst().orElse(0);
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
HttpStats redirectMe = HttpStats.get(stats.get("redirectMe"));
String redirectMetric = stats.keySet().stream().filter(m -> !m.equals("redirectMe")).findFirst().orElse(null);
if (redirectMetric == null) {
// rare case when we'd not get any redirects
assertThat(redirectMe.status_2xx).isEqualTo(users - notFound.get());
assertThat(redirectMe.status_3xx).isEqualTo(0);
assertThat(redirectMe.status_4xx).isEqualTo(notFound.get());
assertThat(redirects.get()).isEqualTo(0);
} else {
HttpStats redirectStats = HttpStats.get(stats.get(redirectMetric));
assertThat(redirectMe.status_2xx + redirectMe.status_3xx).isLessThanOrEqualTo(users)
.isGreaterThanOrEqualTo(users - notFound.get());
assertThat(redirectStats.status_2xx + redirectStats.status_3xx).isLessThanOrEqualTo(redirects.get())
.isGreaterThanOrEqualTo(redirects.get() - notFound.get());
assertThat(redirectStats.status_4xx + redirectMe.status_4xx).isEqualTo(notFound.get());
}
}
@Test
public void testRelative() {
scenario().initialSequence("test").step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path("/redirect/me/relatively")
.handler().followRedirect(FollowRedirect.ALWAYS).endHandler();
Map<String, StatisticsSnapshot> stats = runScenario();
StatisticsSnapshot testStats = stats.get("test");
assertThat(HttpStats.get(testStats).status_3xx).isEqualTo(1);
assertThat(testStats.responseCount).isEqualTo(1);
StatisticsSnapshot otherStats = stats.entrySet().stream()
.filter(e -> !e.getKey().equals("test")).map(Map.Entry::getValue).findFirst().orElse(null);
assertThat(HttpStats.get(otherStats).status_2xx).isEqualTo(2);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/CertificatesTest.java | http/src/test/java/io/hyperfoil/http/CertificatesTest.java | package io.hyperfoil.http;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.Protocol;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.steps.HttpResponseHandlersImpl;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.ClientAuth;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.net.JksOptions;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class CertificatesTest {
@Test
public void testTrustJks(VertxTestContext context) {
test(context, false, server -> executeRequestAndStop(context, server,
builder -> builder.trustManager().storeFile("keystore.jks").password("test123")));
}
@Test
public void testTrustCert(VertxTestContext context) {
test(context, false, server -> executeRequestAndStop(context, server,
builder -> builder.trustManager().certFile("servercert.crt")));
}
@Test
public void testTrustBadCert(VertxTestContext context) {
test(context, false, server -> {
try {
HttpClientPool client = client(server.actualPort(), builder -> builder.trustManager().certFile("badcert.pem"));
client.start(context.failingThenComplete());
} catch (SSLException e) {
context.failNow(e);
}
});
}
@Test
public void testTrustBadJks(VertxTestContext context) {
test(context, false, server -> {
try {
HttpClientPool client = client(server.actualPort(), builder -> builder.trustManager().storeFile("bad.jks"));
client.start(context.failingThenComplete());
} catch (SSLException e) {
context.failNow(e);
}
});
}
@Test
public void testClientJks(VertxTestContext context) {
test(context, true, server -> executeRequestAndStop(context, server,
builder -> builder
.trustManager().storeFile("keystore.jks").password("test123").end()
.keyManager().storeFile("client.jks").password("test123")));
}
@Test
public void testClientBadJksTls12(VertxTestContext context) {
// Due to https://github.com/vert-x3/wiki/wiki/4.4.0-Deprecations-and-breaking-changes#tls-10-and-tls-11-protocols-are-disabled-by-default
// which have added TLSv1.3 to the list of enabled protocols, we need to explicitly disable it to save it be
// used over TLSv1.2.
// This is necessary to verify the expected behaviour for TLSv1.2 which expect an early handshake failure
test(context, true, server -> {
try {
HttpClientPool client = client(server.actualPort(), builder -> builder
.trustManager().storeFile("keystore.jks").password("test123").end()
.keyManager().storeFile("bad.jks").password("test123"));
client.start(context.failingThenComplete());
} catch (SSLException e) {
context.failNow(e);
}
}, Set.of("TLSv1.2"));
}
@Test
public void testClientBadJksTls13(VertxTestContext context) {
// Still related https://github.com/vert-x3/wiki/wiki/4.4.0-Deprecations-and-breaking-changes#tls-10-and-tls-11-protocols-are-disabled-by-default
// Given that TLSv1.3 should be picked over TLSv1.2, we expect the handshake to NOT fail and only a later
// failure to occur when the client tries to send a request.
test(context, true, server -> {
try {
HttpClientPool client = client(server.actualPort(), builder -> builder
.trustManager().storeFile("keystore.jks").password("test123").end()
.keyManager().storeFile("bad.jks").password("test123"));
client.start(context
.succeeding(nil -> sendPingAndFailIfReceiveAnyStatus(context, server, client, context.checkpoint())));
} catch (SSLException e) {
context.failNow(e);
}
}, Set.of("TLSv1.2", "TLSv1.3"));
}
@Test
public void testClientCertAndKey(VertxTestContext context) {
test(context, true, server -> executeRequestAndStop(context, server,
builder -> builder
.trustManager().storeFile("keystore.jks").password("test123").end()
.keyManager().certFile("clientcert.pem").keyFile("clientkey.pem").password("test123")));
}
private void test(VertxTestContext context, boolean requireClientTrust, Handler<HttpServer> handler,
Set<String> enabledSecureTransportProtocols) {
HttpServerOptions serverOptions = new HttpServerOptions().setSsl(true)
.setKeyStoreOptions(new JksOptions().setPath("keystore.jks").setPassword("test123"));
if (requireClientTrust) {
serverOptions.setClientAuth(ClientAuth.REQUIRED);
if (enabledSecureTransportProtocols != null) {
serverOptions.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols);
}
serverOptions.setTrustStoreOptions(new JksOptions().setPath("client.jks").setPassword("test123"));
}
Vertx.vertx().createHttpServer(serverOptions).requestHandler(ctx -> ctx.response().end())
.listen(0, "localhost", context.succeeding(handler));
}
private void test(VertxTestContext context, boolean requireClientTrust, Handler<HttpServer> handler) {
test(context, requireClientTrust, handler, null);
}
private void executeRequestAndStop(VertxTestContext context, HttpServer server, Consumer<HttpBuilder> configuration) {
try {
HttpClientPool client = client(server.actualPort(), configuration);
var checkpoint = context.checkpoint();
client.start(context.succeeding(nil -> sendPingAndReceiveStatus(context, server, client, checkpoint, 200)));
} catch (SSLException e) {
server.close();
context.failNow(e);
}
}
private static void sendPingAndFailIfReceiveAnyStatus(VertxTestContext context, HttpServer server, HttpClientPool client,
Checkpoint checkpoint) {
sendPingAndReceiveStatus(context, server, client, checkpoint, null);
}
private static void sendPingAndReceiveStatus(VertxTestContext context, HttpServer server, HttpClientPool client,
Checkpoint checkpoint,
Integer expectedStatus) {
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
HttpRequest request = HttpRequestPool.get(session).acquire();
AtomicBoolean statusReceived = new AtomicBoolean(false);
HttpResponseHandlers handlers = HttpResponseHandlersImpl.Builder.forTesting()
.status((r, status) -> {
if (expectedStatus == null || status != expectedStatus) {
context.failNow("Unexpected status " + status);
} else {
statusReceived.set(true);
}
})
.onCompletion(s -> {
client.shutdown();
server.close();
if (statusReceived.get() || expectedStatus == null) {
checkpoint.flag();
} else {
context.failNow("Status was not received.");
}
}).build();
request.method = HttpMethod.GET;
request.path = "/ping";
HttpConnectionPool pool = client.next();
request.start(pool, handlers, new SequenceInstance(), new Statistics(System.currentTimeMillis()));
pool.acquire(false, c -> request.send(c, null, true, null));
}
private HttpClientPool client(int port, Consumer<HttpBuilder> configuration) throws SSLException {
HttpBuilder builder = HttpBuilder.forTesting()
.protocol(Protocol.HTTPS).host("localhost").port(port);
configuration.accept(builder);
return HttpClientPoolImpl.forTesting(builder.build(true), 1);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/builder/LambdaCopyTest.java | http/src/test/java/io/hyperfoil/http/builder/LambdaCopyTest.java | package io.hyperfoil.http.builder;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.handlers.RangeStatusValidator;
import io.hyperfoil.http.steps.HttpRequestStepBuilder;
public class LambdaCopyTest {
@Test
public void test() {
HttpRequestStepBuilder builder = new HttpRequestStepBuilder()
.handler().status(new RangeStatusValidator(0, 666)).endHandler();
builder.copy(null);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/cache/HttpCacheEnablementTest.java | http/src/test/java/io/hyperfoil/http/cache/HttpCacheEnablementTest.java | package io.hyperfoil.http.cache;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import io.hyperfoil.core.impl.LocalSimulationRunner;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpCache;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.steps.HttpStepCatalog;
public class HttpCacheEnablementTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route("/ok").handler(ctx -> vertx.setTimer(5, id -> ctx.response().end()));
router.route("/error").handler(ctx -> vertx.setTimer(5, id -> ctx.response().setStatusCode(400).end()));
router.route("/close").handler(ctx -> ctx.response().reset());
}
@Test
public void testOkWithoutCacheHttp1x() {
http().useHttpCache(false)
.sharedConnections(1);
testSingle("/ok", false);
}
@Test
public void testOkWithCacheHttp1x() {
http().useHttpCache(true)
.sharedConnections(1);
testSingle("/ok", true);
}
@Test
public void testOkWithCacheByDefaultHttp1x() {
http().sharedConnections(1);
testSingle("/ok", true);
}
private void testSingle(String path, boolean isUsingCache) {
AtomicReference<HttpCache> httpCacheRef = new AtomicReference<>();
benchmarkBuilder.addPhase("test").atOnce(1).duration(10).scenario()
.initialSequence("test")
.step(session -> {
httpCacheRef.set(HttpCache.get(session));
return true;
})
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET).path(path).endStep();
TestStatistics requestStats = new TestStatistics();
LocalSimulationRunner runner = new LocalSimulationRunner(benchmarkBuilder.build(), requestStats,
null, null);
runner.run();
assertThat(httpCacheRef.get() != null).isEqualTo(isUsingCache);
}
private HttpBuilder http() {
return benchmarkBuilder.plugin(HttpPluginBuilder.class).http();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/cookie/CookieTest.java | http/src/test/java/io/hyperfoil/http/cookie/CookieTest.java | package io.hyperfoil.http.cookie;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.statistics.HttpStats;
import io.vertx.core.http.Cookie;
public class CookieTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route("/test1").handler(ctx -> {
ctx.addCookie(Cookie.cookie("foo", "bar"));
ctx.response().end("Hello!");
});
router.route("/test2").handler(ctx -> {
Cookie cookie = ctx.getCookie("foo");
int status = cookie != null && cookie.getValue().equals("bar") ? 200 : 500;
ctx.response().setStatusCode(status).end();
});
}
@Test
public void testRepeatCookie() {
// @formatter:off
scenario().initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path("/test1")
.metric("test1")
.endStep()
.step(SC).httpRequest(HttpMethod.GET)
.path("/test2")
.metric("test2")
.handler()
.status((request, status) -> {
if (status != 200) request.markInvalid();
})
.endHandler()
.endStep()
.endSequence();
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
StatisticsSnapshot test1 = stats.get("test1");
StatisticsSnapshot test2 = stats.get("test1");
HttpStats http1 = HttpStats.get(test1);
HttpStats http2 = HttpStats.get(test2);
assertThat(http1.status_5xx).isEqualTo(0);
assertThat(http1.status_2xx).isEqualTo(1);
assertThat(http2.status_5xx).isEqualTo(0);
assertThat(http2.status_2xx).isEqualTo(1);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/cookie/CookieStoreTest.java | http/src/test/java/io/hyperfoil/http/cookie/CookieStoreTest.java | package io.hyperfoil.http.cookie;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.BaseMockConnection;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpRequestWriter;
public class CookieStoreTest {
@Test
public void testSubdomainRequest() {
CookieStore store = new CookieStore();
store.setCookie("hyperfoil.io", "/", "foo=bar; domain=hyperfoil.io;");
MockWriter writer = new MockWriter("foo.hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
}
@Test
public void testNoDomainRequest() {
CookieStore store = new CookieStore();
store.setCookie("hyperfoil.io", "/", "foo=bar;");
MockWriter writer1 = new MockWriter("foo.hyperfoil.io", "/");
store.appendCookies(writer1);
assertThat(writer1.values.size()).isEqualTo(0);
MockWriter writer2 = new MockWriter("hyperfoil.io", "/");
store.appendCookies(writer2);
assertThat(writer2.values.size()).isEqualTo(1);
assertThat(writer2.values.get(0)).isEqualTo("foo=bar");
}
@Test
public void testSetSuperdomain() {
CookieStore store1 = new CookieStore();
store1.setCookie("foo.hyperfoil.io", "/", "foo=bar; domain=hyperfoil.io;");
MockWriter writer = new MockWriter("foo.hyperfoil.io", "/");
store1.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
CookieStore store2 = new CookieStore();
store2.setCookie("foo.hyperfoil.io", "/", "foo=bar; domain=bar.io;");
MockWriter writer2 = new MockWriter("foo.hyperfoil.io", "/");
store2.appendCookies(writer2);
assertThat(writer2.values.size()).isEqualTo(0);
MockWriter writer3 = new MockWriter("bar.io", "/");
store2.appendCookies(writer3);
assertThat(writer3.values.size()).isEqualTo(0);
}
@Test
public void testSubpathRequest() {
CookieStore store = new CookieStore();
store.setCookie("hyperfoil.io", "/foo/", "foo=bar; path=/foo");
MockWriter writer1 = new MockWriter("hyperfoil.io", "/foo/bar.php");
store.appendCookies(writer1);
assertThat(writer1.values.size()).isEqualTo(1);
assertThat(writer1.values.get(0)).isEqualTo("foo=bar");
MockWriter writer2 = new MockWriter("foo.hyperfoil.io", "/");
store.appendCookies(writer2);
assertThat(writer2.values.size()).isEqualTo(0);
}
@Test
public void testRootPath() {
CookieStore store = new CookieStore();
store.setCookie("hyperfoil.io", "/foo.php", "foo=bar; path=/");
MockWriter writer1 = new MockWriter("hyperfoil.io", "/foo/bar.php");
store.appendCookies(writer1);
assertThat(writer1.values.size()).isEqualTo(1);
assertThat(writer1.values.get(0)).isEqualTo("foo=bar");
}
@Test
public void testSetSuperpath() {
CookieStore store1 = new CookieStore();
store1.setCookie("hyperfoil.io", "/foo/bar.php", "foo=bar; path=/");
MockWriter writer = new MockWriter("hyperfoil.io", "/xxx/yyy");
store1.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
CookieStore store2 = new CookieStore();
store2.setCookie("hyperfoil.io", "/foo/bar.php", "foo=bar; path=/bar");
MockWriter writer2 = new MockWriter("hyperfoil.io", "/bar/goo");
store2.appendCookies(writer2);
assertThat(writer2.values.size()).isEqualTo(0);
MockWriter writer3 = new MockWriter("hyperfoil.io", "/xxx");
store2.appendCookies(writer3);
assertThat(writer3.values.size()).isEqualTo(0);
}
@Test
public void testExpiration() {
CookieStore store = new CookieStore();
store.setCookie("hyperfoil.io", "/", "foo=bar; expires=Mon, 12-Jul-2038 14:52:12 GMT");
{
MockWriter writer = new MockWriter("hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
}
store.setCookie("hyperfoil.io", "/", "foo=bar; expires=Mon, 15-Sep-2012 16:11:45 GMT");
{
MockWriter writer = new MockWriter("foo.hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(0);
}
store.setCookie("hyperfoil.io", "/", "foo=bar; expires=Mon, 22-Jul-2038 14:52:12 GMT");
{
MockWriter writer = new MockWriter("hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
}
store.setCookie("hyperfoil.io", "/", "foo=bar; Max-Age=-1");
{
MockWriter writer = new MockWriter("foo.hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(0);
}
store.setCookie("hyperfoil.io", "/", "foo=bar; max-age=86400");
{
MockWriter writer = new MockWriter("hyperfoil.io", "/");
store.appendCookies(writer);
assertThat(writer.values.size()).isEqualTo(1);
assertThat(writer.values.get(0)).isEqualTo("foo=bar");
}
}
private static class MockWriter implements HttpRequestWriter {
final String host;
final String path;
final ArrayList<CharSequence> values = new ArrayList<>();
private MockWriter(String host, String path) {
this.host = host;
this.path = path;
}
@Override
public HttpConnection connection() {
return new BaseMockConnection() {
@Override
public String host() {
return host;
}
};
}
@Override
public HttpRequest request() {
HttpRequest httpRequest = new HttpRequest(null, true);
httpRequest.path = path;
return httpRequest;
}
@Override
public void putHeader(CharSequence header, CharSequence value) {
values.add(value);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/Http2ConnectionStatsTest.java | http/src/test/java/io/hyperfoil/http/connection/Http2ConnectionStatsTest.java | package io.hyperfoil.http.connection;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.hyperfoil.core.util.LowHigh;
import io.hyperfoil.http.config.ConnectionStrategy;
public class Http2ConnectionStatsTest extends AbstractConnectionStatsTest {
private static final String HTTP_2_TLS = "TLS + HTTP 2";
private static final String BLOCKED_SESSIONS = "blocked sessions";
private static final String IN_FLIGHT_REQUESTS = "in-flight requests";
private static final String USED_CONNECTIONS = "used connections";
@Override
protected boolean useHttps() {
return true;
}
@Test
public void testSingleOkSharedHttp2() {
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/ok", true);
}
@Test
public void testSingleErrorSharedHttp2() {
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/error", true);
}
@Test
public void testSingleCloseSharedHttp2() {
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/close", false);
}
@Test
public void testSharedHttp2() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(connections);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_2_TLS).high).isEqualTo(connections);
// Too many false positives
// assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isBetween(connections + 1, 50);
assertThat(stats.get(USED_CONNECTIONS).high).isEqualTo(connections);
}
@Test
public void testSharedHttp2NoErrors() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(connections);
Map<String, LowHigh> stats = testConcurrent(false);
assertThat(stats.get(HTTP_2_TLS).high).isEqualTo(connections);
assertThat(stats.get(BLOCKED_SESSIONS).high).isEqualTo(0);
// Too many false positives
// assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isBetween(connections + 1, 50);
assertThat(stats.get(USED_CONNECTIONS).high).isEqualTo(connections);
}
@Test
public void testSessionPoolsHttp2() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(connections);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_2_TLS).high).isEqualTo(connections);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isLessThanOrEqualTo(connections);
assertThat(stats.get(USED_CONNECTIONS).high).isEqualTo(connections);
}
@Test
public void testNewHttp2() {
http().connectionStrategy(ConnectionStrategy.ALWAYS_NEW);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isEqualTo(stats.get(USED_CONNECTIONS).high);
}
@Test
public void testOnRequestHttp2() {
http().connectionStrategy(ConnectionStrategy.OPEN_ON_REQUEST);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isEqualTo(stats.get(USED_CONNECTIONS).high);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/AbstractConnectionStatsTest.java | http/src/test/java/io/hyperfoil/http/connection/AbstractConnectionStatsTest.java | package io.hyperfoil.http.connection;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.core.impl.ConnectionStatsConsumer;
import io.hyperfoil.core.impl.LocalSimulationRunner;
import io.hyperfoil.core.util.LowHigh;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpDestinationTable;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.statistics.HttpStats;
import io.hyperfoil.http.steps.HttpStepCatalog;
public abstract class AbstractConnectionStatsTest extends BaseHttpScenarioTest {
private static final String HTTP_1x = "HTTP 1.x";
private static final String IN_FLIGHT_REQUESTS = "in-flight requests";
private static final String USED_CONNECTIONS = "used connections";
@Override
protected void initRouter() {
router.route("/ok").handler(ctx -> vertx.setTimer(5, id -> ctx.response().end()));
router.route("/error").handler(ctx -> vertx.setTimer(5, id -> ctx.response().setStatusCode(400).end()));
router.route("/close").handler(ctx -> ctx.response().reset());
}
@Override
protected int threads() {
return 1;
}
protected HttpBuilder http() {
return benchmarkBuilder.plugin(HttpPluginBuilder.class).http();
}
protected void testSingle(String path, boolean response) {
AtomicReference<HttpConnectionPool> connectionPoolRef = new AtomicReference<>();
benchmarkBuilder.addPhase("test").atOnce(1).duration(10).scenario()
.initialSequence("test")
.step(session -> {
connectionPoolRef.set(HttpDestinationTable.get(session).getConnectionPoolByAuthority(null));
return true;
})
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET).path(path).endStep();
TestStatistics requestStats = new TestStatistics();
TestConnectionStats connectionStats = new TestConnectionStats();
LocalSimulationRunner runner = new LocalSimulationRunner(benchmarkBuilder.build(), requestStats, null, connectionStats);
runner.run();
try {
// Some connections might be released after all sessions stopped so we need to wait for that as well.
connectionPoolRef.get().executor().awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
ConnectionPoolStats connectionPool;
if (connectionPoolRef.get() instanceof SessionConnectionPool) {
connectionPool = (ConnectionPoolStats) connectionPoolRef.get().clientPool().next();
} else {
connectionPool = (ConnectionPoolStats) connectionPoolRef.get();
}
assertThat(connectionPool.usedConnections.current()).isEqualTo(0);
assertThat(connectionPool.inFlight.current()).isEqualTo(0);
assertThat(connectionPool.blockedSessions.current()).isEqualTo(0);
StatisticsSnapshot snapshot = requestStats.stats().get("test");
assertThat(snapshot.requestCount).isEqualTo(1);
assertThat(snapshot.responseCount).isEqualTo(response ? 1 : 0);
assertThat(snapshot.connectionErrors).isEqualTo(response ? 0 : 1);
connectionStats.stats
.forEach((tag, lowHigh) -> assertThat(lowHigh.low).describedAs(tag).isLessThanOrEqualTo(lowHigh.high));
connectionStats.stats.forEach((tag, lowHigh) -> assertThat(lowHigh.low).describedAs(tag).isGreaterThanOrEqualTo(0));
}
protected Map<String, LowHigh> testConcurrent(boolean errors) {
//@formatter:off
benchmarkBuilder.addPhase("test").constantRate(100).duration(2000).scenario()
.initialSequence("test")
.step(HttpStepCatalog.SC).randomItem()
.toVar("path")
.list()
.add("/ok", 1)
.add("/error", errors ? 1 : 0)
.add("/close", errors ? 1 : 0)
.end().endStep()
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path().fromVar("path").end().endStep();
//@formatter:on
TestStatistics requestStats = new TestStatistics();
TestConnectionStats connectionStats = new TestConnectionStats();
LocalSimulationRunner runner = new LocalSimulationRunner(benchmarkBuilder.build(), requestStats, null, connectionStats);
runner.run();
StatisticsSnapshot snapshot = requestStats.stats().get("test");
HttpStats http = HttpStats.get(snapshot);
assertThat(snapshot.requestCount).isGreaterThan(100);
// When connection cancels requests from other sessions these are recorded as resets
assertThat(snapshot.responseCount).isEqualTo(snapshot.requestCount - snapshot.connectionErrors);
assertThat(snapshot.connectionErrors).isEqualTo(snapshot.requestCount - http.status_2xx - http.status_4xx);
// Too many false positives
// assertThat(http.status_2xx).isGreaterThan(30);
if (errors) {
// assertThat(http.status_4xx).isGreaterThan(30);
} else {
assertThat(http.status_4xx).isEqualTo(0);
}
connectionStats.stats
.forEach((tag, lowHigh) -> assertThat(lowHigh.low).describedAs(tag).isLessThanOrEqualTo(lowHigh.high));
connectionStats.stats.forEach((tag, lowHigh) -> assertThat(lowHigh.low).describedAs(tag).isGreaterThanOrEqualTo(0));
return connectionStats.stats;
}
protected static class TestConnectionStats implements ConnectionStatsConsumer {
Map<String, LowHigh> stats = new HashMap<>();
@Override
public void accept(String authority, String tag, int min, int max) {
// ignoring authority (we'll use only one)
LowHigh prev = stats.putIfAbsent(tag, new LowHigh(min, max));
assert prev == null;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/SessionPoolsTest.java | http/src/test/java/io/hyperfoil/http/connection/SessionPoolsTest.java | package io.hyperfoil.http.connection;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.session.ObjectAccess;
import io.hyperfoil.api.session.ReadAccess;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.core.steps.ScheduleDelayStep;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.ConnectionStrategy;
import io.hyperfoil.http.config.HttpBuilder;
import io.netty.handler.codec.http.HttpHeaderNames;
public class SessionPoolsTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.get("/").handler(ctx -> ctx.response().end());
}
@Override
protected void initHttp(HttpBuilder http) {
super.initHttp(http);
http.connectionStrategy(ConnectionStrategy.SESSION_POOLS).sharedConnections(2);
}
@Override
protected int threads() {
return 1;
}
@Test
public void test() {
// We don't need to synchronize since we're using single executor
Set<Session> runningSessions = new HashSet<>();
// @formatter:off
benchmarkBuilder.addPhase("test").always(10).duration(2000).scenario()
.initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path("/")
.handler()
.status(() -> {
ObjectAccess connection = SessionFactory.objectAccess("connection");
return (request, status) -> {
connection.setObject(request.session, request.connection());
};
})
.endHandler()
.endStep()
.step(SC).thinkTime()
.random(ScheduleDelayStep.RandomType.LINEAR)
.min(10, TimeUnit.MILLISECONDS).max(100, TimeUnit.MILLISECONDS)
.endStep()
.step(SC).httpRequest(HttpMethod.GET)
.path("/")
.headers()
.header(HttpHeaderNames.CACHE_CONTROL, "no-cache")
.endHeaders()
.handler()
.status(() -> {
ReadAccess connection = SessionFactory.readAccess("connection");
return (request, status) -> {
assertEquals(connection.getObject(request.session), request.connection());
runningSessions.add(request.session);
};
});
// @formatter:on
runScenario();
// check that the possibly failing handler was called from all sessions
assertThat(runningSessions.size()).isEqualTo(10);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/OpenConnectionOnRequestTest.java | http/src/test/java/io/hyperfoil/http/connection/OpenConnectionOnRequestTest.java | package io.hyperfoil.http.connection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.ConnectionStrategy;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.steps.HttpStepCatalog;
import io.netty.handler.codec.http.HttpHeaderNames;
public class OpenConnectionOnRequestTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.get("/").handler(ctx -> ctx.response().end());
}
@Override
protected int threads() {
return 1;
}
@Override
protected void initHttp(HttpBuilder http) {
http.connectionStrategy(ConnectionStrategy.OPEN_ON_REQUEST);
}
@Test
public void test() {
Set<HttpConnection> connections = new HashSet<>();
//@formatter:off
benchmarkBuilder.addPhase("test").always(10).duration(1000).scenario().initialSequence("test")
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path("/")
.handler().status((request, status) -> {
assertFalse(connections.contains(request.connection()));
connections.add(request.connection());
}).endHandler()
.endStep()
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path("/")
.headers().header(HttpHeaderNames.CACHE_CONTROL, "no-cache").endHeaders()
.handler().status((request, status) -> {
assertTrue(connections.contains(request.connection()));
}).endHandler()
.endStep();
//@formatter:on
runScenario();
assertTrue(connections.size() >= 10);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/AlwaysNewConnectionTest.java | http/src/test/java/io/hyperfoil/http/connection/AlwaysNewConnectionTest.java | package io.hyperfoil.http.connection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.StatusHandler;
import io.hyperfoil.http.config.ConnectionStrategy;
import io.hyperfoil.http.config.HttpBuilder;
import io.hyperfoil.http.steps.HttpStepCatalog;
import io.netty.handler.codec.http.HttpHeaderNames;
public class AlwaysNewConnectionTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.get("/").handler(ctx -> ctx.response().end());
}
@Override
protected int threads() {
return 1;
}
@Override
protected void initHttp(HttpBuilder http) {
http.connectionStrategy(ConnectionStrategy.ALWAYS_NEW);
}
@Test
public void test() {
Set<HttpConnection> connections = new HashSet<>();
StatusHandler statusHandler = (request, status) -> {
assertFalse(connections.contains(request.connection()));
connections.add(request.connection());
};
//@formatter:off
benchmarkBuilder.addPhase("test").always(10).duration(1000).scenario().initialSequence("test")
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path("/")
.handler().status(statusHandler).endHandler()
.endStep()
.step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET)
.path("/")
.headers().header(HttpHeaderNames.CACHE_CONTROL, "no-cache").endHeaders()
.handler().status(statusHandler).endHandler()
.endStep();
//@formatter:on
runScenario();
assertTrue(connections.size() >= 10);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/connection/Http1xConnectionStatsTest.java | http/src/test/java/io/hyperfoil/http/connection/Http1xConnectionStatsTest.java | package io.hyperfoil.http.connection;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.hyperfoil.core.util.LowHigh;
import io.hyperfoil.http.config.ConnectionStrategy;
public class Http1xConnectionStatsTest extends AbstractConnectionStatsTest {
private static final String HTTP_1x = "HTTP 1.x";
private static final String IN_FLIGHT_REQUESTS = "in-flight requests";
private static final String USED_CONNECTIONS = "used connections";
@Test
public void testSingleOkSharedHttp1x() {
// startServer(ctx, false);
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/ok", true);
}
@Test
public void testSingleErrorSharedHttp1x() {
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/error", true);
}
@Test
public void testSingleCloseSharedHttp1x() {
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(1);
testSingle("/close", false);
}
@Test
public void testSingleOkSessionPoolsHttp1x() {
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(1);
testSingle("/ok", true);
}
@Test
public void testSingleErrorSessionPoolsHttp1x() {
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(1);
testSingle("/error", true);
}
@Test
public void testSingleCloseSessionPoolsHttp1x() {
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(1);
testSingle("/close", false);
}
@Test
public void testSharedHttp1x() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(connections);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_1x).high).isEqualTo(connections);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isLessThanOrEqualTo(connections);
assertThat(stats.get(USED_CONNECTIONS).high).isLessThanOrEqualTo(connections);
}
@Test
public void testSharedHttp1xPipelining() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SHARED_POOL)
.sharedConnections(connections)
.pipeliningLimit(5);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_1x).high).isEqualTo(connections);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isLessThanOrEqualTo(connections * 5);
assertThat(stats.get(USED_CONNECTIONS).high).isLessThanOrEqualTo(connections);
}
@Test
public void testSessionPoolsHttp1x() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(connections);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_1x).high).isEqualTo(connections);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isLessThanOrEqualTo(connections);
assertThat(stats.get(USED_CONNECTIONS).high).isLessThanOrEqualTo(connections);
}
@Test
public void testSessionPoolsHttp1xPipelining() {
final int connections = 3;
http().connectionStrategy(ConnectionStrategy.SESSION_POOLS)
.sharedConnections(connections)
.pipeliningLimit(5);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(HTTP_1x).high).isEqualTo(connections);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isLessThanOrEqualTo(connections);
assertThat(stats.get(USED_CONNECTIONS).high).isLessThanOrEqualTo(connections);
}
@Test
public void testNewHttp1x() {
http().connectionStrategy(ConnectionStrategy.ALWAYS_NEW);
Map<String, LowHigh> stats = testConcurrent(true);
assertThat(stats.get(IN_FLIGHT_REQUESTS).high).isEqualTo(stats.get(USED_CONNECTIONS).high);
}
@Test
public void testOnRequestHttp1x() {
http().connectionStrategy(ConnectionStrategy.OPEN_ON_REQUEST);
testConcurrent(true);
// Note: in-flight and used-connections stats can run out of sync because
// other session can be executed after releasing connection and before resetting the session
}
@Test
public void testOnRequestHttp1xPipelining() {
http().connectionStrategy(ConnectionStrategy.OPEN_ON_REQUEST)
.pipeliningLimit(5);
testConcurrent(true);
// Note: in-flight and used-connections stats can run out of sync because
// other session can be executed after releasing connection and before resetting the session
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/html/EmbeddedResourcesTest.java | http/src/test/java/io/hyperfoil/http/html/EmbeddedResourcesTest.java | package io.hyperfoil.http.html;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.statistics.HttpStats;
import io.vertx.core.http.HttpHeaders;
public class EmbeddedResourcesTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route().handler(ctx -> {
ctx.response().putHeader(HttpHeaders.CACHE_CONTROL, "no-store");
ctx.next();
});
router.route("/foobar/index.html").handler(ctx -> serveResourceChunked(ctx, "data/EmbeddedResourcesTest_index.html"));
router.route("/styles/style.css").handler(ctx -> ctx.response().end("You've got style!"));
router.route("/foobar/stuff.js").handler(ctx -> ctx.response().end("alert('Hello world!')"));
router.route("/generate.php").handler(ctx -> ctx.response().end());
}
@Test
public void test() {
Benchmark benchmark = loadScenario("scenarios/EmbeddedResourcesTest.hf.yaml");
Map<String, StatisticsSnapshot> stats = runScenario(benchmark);
assertThat(stats.size()).isEqualTo(6);
for (Map.Entry<String, StatisticsSnapshot> entry : stats.entrySet()) {
String name = entry.getKey();
int hits;
if (name.equals("automatic") || name.equals("manual") || name.equals("legacy")) {
hits = 1;
} else {
assertThat(name).matches(".*\\.(css|js|ico|php)");
hits = 3;
}
StatisticsSnapshot snapshot = entry.getValue();
assertThat(snapshot.requestCount).as(name).isEqualTo(hits);
assertThat(HttpStats.get(snapshot).status_2xx).as(name).isEqualTo(hits);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/html/TagAttributeHandlerTest.java | http/src/test/java/io/hyperfoil/http/html/TagAttributeHandlerTest.java | package io.hyperfoil.http.html;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.http.BaseHttpScenarioTest;
public class TagAttributeHandlerTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route("/foobar/index.html")
.handler(ctx -> serveResourceChunked(ctx, "data/TagAttributeHandlerTest_index.html"));
}
@Test
public void test() {
Benchmark benchmark = loadScenario("scenarios/TagAttributeHandlerTest.hf.yaml");
runScenario(benchmark);
}
} | java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/html/MetaRefreshHandlerTest.java | http/src/test/java/io/hyperfoil/http/html/MetaRefreshHandlerTest.java | package io.hyperfoil.http.html;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.session.ResourceUtilizer;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.handlers.ExpectProcessor;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.HttpRunData;
import io.hyperfoil.impl.Util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
public class MetaRefreshHandlerTest {
@Test
public void test() {
HtmlHandler.Builder html = new HtmlHandler.Builder();
ExpectProcessor expect = new ExpectProcessor();
html.handler(new MetaRefreshHandler.Builder().processor(fragmented -> expect)).prepareBuild();
HtmlHandler handler = html.build(true);
Session session = SessionFactory.forTesting();
HttpRunData.initForTesting(session);
ResourceUtilizer.reserveForTesting(session, handler);
handler.before(session);
ByteBuf content1 = buf("content1");
ByteBuf content2 = buf("content2");
ByteBuf content5 = buf("content5");
try {
expect.expect(content1);
sendChunk(handler, session, "<html><head><me");
sendChunk(handler, session, "ta Http-equiv=\"refresh");
sendChunk(handler, session, "\" content=\"");
sendChunk(handler, session, "content1\" /><META");
expect.expect(content2);
sendChunk(handler, session, " content=\"content2\" foo=\"bar\" http-equiv=");
sendChunk(handler, session, "\"Ref");
sendChunk(handler, session, "resh\"></meta>");
sendChunk(handler, session, " <meta");
sendChunk(handler, session, "META http-equiv=\"refresh\" content=\"content3\"/>");
sendChunk(handler, session, "<!-- --><mETA http-equiv=\"whatever\" content=\"content4\" />");
sendChunk(handler, session, "<mETA http-equiv=\"whatever\" content=\"content4\" />");
expect.expect(content5);
sendChunk(handler, session, "<meta content=\"content5\" http-equiv=\"refresh\" /></head></html>");
handler.process(session, ByteBufAllocator.DEFAULT.buffer(0, 0), 0, 0, true);
handler.after(session);
expect.validate();
} finally {
content1.release();
content2.release();
content5.release();
}
}
protected void sendChunk(HtmlHandler handler, Session session, String string) {
ByteBuf buf = buf(string);
handler.process(session, buf, buf.readerIndex(), buf.readableBytes(), false);
buf.release();
}
private ByteBuf buf(String string) {
return Util.string2byteBuf(string, ByteBufAllocator.DEFAULT.buffer());
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/handlers/RangeStatusValidatorTest.java | http/src/test/java/io/hyperfoil/http/handlers/RangeStatusValidatorTest.java | package io.hyperfoil.http.handlers;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class RangeStatusValidatorTest {
@Test
public void test1() {
RangeStatusValidator validator = create("200");
assertThat(validator.min).isEqualTo(200);
assertThat(validator.max).isEqualTo(200);
}
@Test
public void test2() {
RangeStatusValidator validator = create("3xx");
assertThat(validator.min).isEqualTo(300);
assertThat(validator.max).isEqualTo(399);
}
@Test
public void test3() {
RangeStatusValidator validator = create("201 - 205");
assertThat(validator.min).isEqualTo(201);
assertThat(validator.max).isEqualTo(205);
}
private RangeStatusValidator create(String inline) {
return new RangeStatusValidator.Builder().init(inline).build();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/handlers/SearchValidatorTest.java | http/src/test/java/io/hyperfoil/http/handlers/SearchValidatorTest.java | package io.hyperfoil.http.handlers;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.session.ResourceUtilizer;
import io.hyperfoil.api.session.SequenceInstance;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.handlers.SearchValidator;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.http.HttpRequestPool;
import io.hyperfoil.http.HttpRunData;
import io.hyperfoil.http.api.HttpRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class SearchValidatorTest {
@Test
public void testPositive() {
SearchValidator validator = new SearchValidator("bar", m -> m == 1);
HttpRequest request = runValidator(validator, "foobarfoo");
assertThat(request.isValid()).isTrue();
}
@Test
public void testNegative() {
SearchValidator validator = new SearchValidator("bar", m -> m == 1);
HttpRequest request = runValidator(validator, "foooo");
assertThat(request.isValid()).isFalse();
}
@Test
public void testStart() {
SearchValidator validator = new SearchValidator("bar", m -> m == 1);
HttpRequest request = runValidator(validator, "barfoo");
assertThat(request.isValid()).isTrue();
}
@Test
public void testEnd() {
SearchValidator validator = new SearchValidator("bar", m -> m == 1);
HttpRequest request = runValidator(validator, "foobar");
assertThat(request.isValid()).isTrue();
}
@Test
public void testSplit() {
SearchValidator validator = new SearchValidator("bar", m -> m == 1);
HttpRequest request = runValidator(validator, "foob", "arfoo");
assertThat(request.isValid()).isTrue();
}
@Test
public void testMany() {
SearchValidator validator = new SearchValidator("bar", m -> m == 3);
HttpRequest request = runValidator(validator, "foob", "arfoob", "a", "rfooba", "rfoo");
assertThat(request.isValid()).isTrue();
}
@Test
public void testOverlapping() {
SearchValidator validator = new SearchValidator("barbar", m -> m == 1);
HttpRequest request = runValidator(validator, "barbarbar");
assertThat(request.isValid()).isTrue();
}
private HttpRequest runValidator(SearchValidator validator, String... text) {
Session session = SessionFactory.forTesting();
ResourceUtilizer.reserveForTesting(session, validator);
HttpRunData.initForTesting(session);
HttpRequest request = HttpRequestPool.get(session).acquire();
request.start(new SequenceInstance(), null);
session.currentRequest(request);
validator.before(session);
for (String t : text) {
ByteBuf data = Unpooled.wrappedBuffer(t.getBytes(StandardCharsets.UTF_8));
validator.process(session, data, data.readerIndex(), data.readableBytes(), false);
}
validator.after(session);
return request;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/handlers/FilterHeaderHandlerTest.java | http/src/test/java/io/hyperfoil/http/handlers/FilterHeaderHandlerTest.java | package io.hyperfoil.http.handlers;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.config.Locator;
import io.hyperfoil.api.session.ObjectAccess;
import io.hyperfoil.api.session.WriteAccess;
import io.hyperfoil.core.handlers.ExpectProcessor;
import io.hyperfoil.core.session.SessionFactory;
import io.hyperfoil.core.test.TestUtil;
import io.hyperfoil.http.BaseMockConnection;
import io.hyperfoil.http.api.HttpRequest;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
public class FilterHeaderHandlerTest {
@Test
public void testValue() {
ExpectProcessor expect = new ExpectProcessor().expect(0, 6, true);
FilterHeaderHandler handler = new FilterHeaderHandler.Builder()
.processor(f -> expect)
.header().value("foo").end()
.build();
HttpRequest request = requestMock();
TestUtil.resolveAccess(request.session, handler);
handler.beforeHeaders(request);
handler.handleHeader(request, "Foo", "barxxx");
handler.handleHeader(request, "moo", "xxx");
handler.afterHeaders(request);
expect.validate();
}
@Test
public void testStartsWith() {
ExpectProcessor expect = new ExpectProcessor().expect(0, 6, true);
FilterHeaderHandler handler = new FilterHeaderHandler.Builder()
.processor(f -> expect)
.header().startsWith("foo").end()
.build();
HttpRequest request = requestMock();
TestUtil.resolveAccess(request.session, handler);
handler.beforeHeaders(request);
handler.handleHeader(request, "FooBar", "barxxx");
handler.handleHeader(request, "fo", "xxx");
handler.handleHeader(request, "moobar", "xxx");
handler.afterHeaders(request);
expect.validate();
}
@Test
public void testEndsWith() {
ExpectProcessor expect = new ExpectProcessor().expect(0, 6, true);
FilterHeaderHandler handler = new FilterHeaderHandler.Builder()
.processor(f -> expect)
.header().endsWith("bar").end()
.build();
HttpRequest request = requestMock();
TestUtil.resolveAccess(request.session, handler);
handler.beforeHeaders(request);
handler.handleHeader(request, "FooBar", "barxxx");
handler.handleHeader(request, "ar", "xxx");
handler.handleHeader(request, "moomar", "xxx");
handler.afterHeaders(request);
expect.validate();
}
@Test
public void testMatchVar() {
ExpectProcessor expect = new ExpectProcessor().expect(0, 6, true);
Locator.push(TestUtil.locator());
FilterHeaderHandler handler = new FilterHeaderHandler.Builder()
.processor(f -> expect)
.header()
.matchVar("myVar")
.end()
.build();
ObjectAccess access = SessionFactory.objectAccess("myVar");
HttpRequest request = requestMock(access);
TestUtil.resolveAccess(request.session, handler);
access.setObject(request.session, "Foo");
Locator.pop();
handler.beforeHeaders(request);
handler.handleHeader(request, "foo", "barxxx");
handler.handleHeader(request, "moo", "xxx");
handler.afterHeaders(request);
expect.validate();
}
private HttpRequest requestMock(WriteAccess... accesses) {
HttpRequest request = new HttpRequest(SessionFactory.forTesting(accesses), true);
request.attach(new BaseMockConnection() {
@Override
public ChannelHandlerContext context() {
return new EmbeddedChannel().pipeline().addFirst(new ChannelHandlerAdapter() {
}).firstContext();
}
});
return request;
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/statistics/Http2ErrorRatioTest.java | http/src/test/java/io/hyperfoil/http/statistics/Http2ErrorRatioTest.java | package io.hyperfoil.http.statistics;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.Action;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpVersion;
import io.hyperfoil.http.config.HttpBuilder;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class Http2ErrorRatioTest extends ErrorRatioTest {
@Override
protected boolean useHttps() {
return true;
}
@Override
protected void initHttp(HttpBuilder http) {
http.allowHttp1x(false);
}
@Override
protected Action validateConnection(VertxTestContext ctx) {
return session -> {
ctx.verify(() -> {
assertSame(((HttpConnection) session.currentRequest().connection()).version(), HttpVersion.HTTP_2_0);
ctx.completeNow();
});
};
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/statistics/ErrorRatioTest.java | http/src/test/java/io/hyperfoil/http/statistics/ErrorRatioTest.java | package io.hyperfoil.http.statistics;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.session.Action;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class ErrorRatioTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.get("/get200").handler(ctx -> ctx.response().setStatusCode(200).end());
router.get("/get400").handler(ctx -> ctx.response().setStatusCode(400).end());
router.get("/close").handler(ctx -> ctx.response().reset());
}
@Test
public void test400(VertxTestContext ctx) {
scenario().initialSequence("400")
.step(SC).httpRequest(HttpMethod.GET).path("/get400")
.handler().onCompletion(validateConnection(ctx)).endHandler()
.endStep();
StatisticsSnapshot stats = runScenario().get("400");
HttpStats http = HttpStats.get(stats);
assertThat(stats.requestCount).isEqualTo(1);
assertThat(stats.responseCount).isEqualTo(1);
assertThat(http.status_4xx).isEqualTo(1);
assertThat(stats.connectionErrors).isEqualTo(0);
assertThat(stats.invalid).isEqualTo(1);
assertThat(http.cacheHits).isEqualTo(0);
assertThat(stats.errors()).isEqualTo(0);
}
protected Action validateConnection(VertxTestContext ctx) {
return session -> ctx.completeNow();
}
@Test
public void testClose() {
scenario().initialSequence("close")
.step(SC).httpRequest(HttpMethod.GET).path("/close").endStep();
StatisticsSnapshot stats = runScenario().get("close");
assertThat(stats.requestCount).isEqualTo(1);
assertThat(stats.responseCount).isEqualTo(0);
assertThat(stats.connectionErrors).isEqualTo(1);
assertThat(stats.invalid).isEqualTo(1);
assertThat(HttpStats.get(stats).cacheHits).isEqualTo(0);
assertThat(stats.errors()).isEqualTo(1);
}
@Test
public void testThrowInBodyHandler() {
scenario().initialSequence("throw")
.step(SC).httpRequest(HttpMethod.GET).path("/get200")
.handler().body(fragmented -> (session, data, offset, length, isLastPart) -> {
throw new RuntimeException("Induced failure");
}).endHandler().endStep();
StatisticsSnapshot stats = runScenario().get("throw");
HttpStats http = HttpStats.get(stats);
assertThat(stats.requestCount).isEqualTo(1);
// handleEnd was not invoked and handleThrowable cannot record response
// because it does not know if the complete physical response was received.
assertThat(stats.responseCount).isEqualTo(0);
assertThat(http.status_2xx).isEqualTo(1);
assertThat(stats.invalid).isEqualTo(1);
assertThat(http.cacheHits).isEqualTo(0);
assertThat(stats.connectionErrors).isEqualTo(0);
assertThat(stats.internalErrors).isEqualTo(1);
assertThat(stats.errors()).isEqualTo(1);
}
@Test
public void testThrowInCompletionHandler() {
scenario().initialSequence("throw")
.step(SC).httpRequest(HttpMethod.GET).path("/get200")
.handler().onCompletion(() -> session -> {
throw new RuntimeException("Induced failure");
}).endHandler().endStep();
StatisticsSnapshot stats = runScenario().get("throw");
HttpStats http = HttpStats.get(stats);
assertThat(stats.requestCount).isEqualTo(1);
// contrary to testThrowInBodyHandler the response is already recorded before the completion handlers run
assertThat(stats.responseCount).isEqualTo(1);
assertThat(http.status_2xx).isEqualTo(1);
assertThat(stats.invalid).isEqualTo(1);
assertThat(http.cacheHits).isEqualTo(0);
assertThat(stats.connectionErrors).isEqualTo(0);
assertThat(stats.internalErrors).isEqualTo(1);
assertThat(stats.errors()).isEqualTo(1);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/statistics/PathMetricsTest.java | http/src/test/java/io/hyperfoil/http/statistics/PathMetricsTest.java | package io.hyperfoil.http.statistics;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.core.metric.PathMetricSelector;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
public class PathMetricsTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route("/foo.js").handler(ctx -> ctx.response().setStatusCode(200).end());
router.route("/bar.php").handler(ctx -> ctx.response().setStatusCode(200).end());
router.route("/goo.css").handler(ctx -> ctx.response().setStatusCode(200).end());
router.route("/gaa.css").handler(ctx -> ctx.response().setStatusCode(200).end());
}
@Test
public void test() {
AtomicInteger counter = new AtomicInteger(0);
PathMetricSelector selector = new PathMetricSelector();
selector.nextItem(".*\\.js");
selector.nextItem("(.*\\.php).* -> $1");
selector.nextItem("-> others");
scenario(4).initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path(s -> switch (counter.getAndIncrement()) {
case 0 -> "/foo.js";
case 1 -> "/bar.php?foo=bar";
case 2 -> "/goo.css";
case 3 -> "/gaa.css";
default -> throw new IllegalStateException();
})
.metric(selector)
.endStep();
Map<String, StatisticsSnapshot> stats = runScenario();
assertThat(stats.get("/foo.js").requestCount).isEqualTo(1);
assertThat(stats.get("/bar.php").requestCount).isEqualTo(1);
assertThat(stats.get("others").requestCount).isEqualTo(2);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/steps/HttpConcurrentRequestTest.java | http/src/test/java/io/hyperfoil/http/steps/HttpConcurrentRequestTest.java | package io.hyperfoil.http.steps;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.core.handlers.NewSequenceAction;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.handlers.RangeStatusValidator;
import io.vertx.ext.web.handler.BodyHandler;
public class HttpConcurrentRequestTest extends BaseHttpScenarioTest {
private final ArrayList<Integer> responsesReceived = new ArrayList<>();
@Override
protected void initRouter() {
router.route().handler(BodyHandler.create());
router.get("/test").handler(ctx -> {
responsesReceived.add(Integer.parseInt(ctx.request().getParam("concurrency")));
ctx.response().setStatusCode(200).end();
});
}
@Test
public void testConcurrencyZeroWithPipelining() {
testConcurrencyWithPipelining(0);
}
@Test
public void testConcurrencyOneWithPipelining() {
testConcurrencyWithPipelining(1);
}
@Test
public void testConcurrencyManyWithPipelining() {
testConcurrencyWithPipelining(16);
}
private void testConcurrencyWithPipelining(int concurrency) {
int sequenceInvocation = concurrency == 0 ? 1 : concurrency;
int pipeliningLimit = concurrency == 0 ? 1 : concurrency;
int requiredSequences = concurrency == 0 ? 2 : 1;
int maxRequests = concurrency == 0 ? 1 : concurrency;
// @formatter:off
scenario()
.maxSequences(requiredSequences)
.maxRequests(maxRequests)
.initialSequence("looper")
.step(SC).loop("counter", sequenceInvocation)
.steps()
.step(SC).action(new NewSequenceAction.Builder().sequence("expectOK"))
.endSequence()
.sequence("expectOK")
.concurrency(concurrency)
.step(SC).httpRequest(HttpMethod.GET)
.path("/test?concurrency=${counter}")
.handler()
.status(new RangeStatusValidator(200, 200))
.endHandler()
.endStep()
.endSequence()
.endScenario()
.endPhase()
.plugin(HttpPluginBuilder.class)
.http()
.sharedConnections(1)
.pipeliningLimit(pipeliningLimit);
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
StatisticsSnapshot snapshot = stats.get("expectOK");
assertThat(snapshot.invalid).isEqualTo(0);
assertThat(snapshot.connectionErrors).isEqualTo(0);
assertThat(snapshot.requestCount).isEqualTo(concurrency == 0 ? 1 : concurrency);
assertThat(responsesReceived.size()).isEqualTo(concurrency == 0 ? 1 : concurrency);
// this seems counter-intuitive, but despite the sequence is invoked multiple times, we expect
// the query parameter to be valued just with the last counter value!
assertThat(responsesReceived).containsOnly(sequenceInvocation);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/steps/HttpRequestTest.java | http/src/test/java/io/hyperfoil/http/steps/HttpRequestTest.java | package io.hyperfoil.http.steps;
import static io.hyperfoil.http.steps.HttpStepCatalog.SC;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.hyperfoil.api.statistics.StatisticsSnapshot;
import io.hyperfoil.core.steps.SetAction;
import io.hyperfoil.http.BaseHttpScenarioTest;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.StatusHandler;
import io.hyperfoil.http.config.HttpPluginBuilder;
import io.hyperfoil.http.handlers.RangeStatusValidator;
import io.hyperfoil.http.handlers.RecordHeaderTimeHandler;
import io.hyperfoil.http.statistics.HttpStats;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class HttpRequestTest extends BaseHttpScenarioTest {
@Override
protected void initRouter() {
router.route().handler(BodyHandler.create());
router.post("/test").handler(ctx -> {
String expect = ctx.request().getParam("expect");
String body = ctx.body().asString();
if (expect == null) {
ctx.response().setStatusCode(400).end();
return;
}
ctx.response().setStatusCode(expect.equals(body) ? 200 : 412).end();
});
router.get("/status").handler(ctx -> {
String s = ctx.request().getParam("s");
ctx.response().setStatusCode(Integer.parseInt(s)).end();
});
router.get("/test").handler(ctx -> {
ctx.response().putHeader("x-foo", "5");
String expectHeader = ctx.request().getParam("expectHeader");
if (expectHeader != null) {
String[] headerValue = expectHeader.split(":", 2);
String actualValue = ctx.request().getHeader(headerValue[0]);
ctx.response().setStatusCode(Objects.equals(actualValue, headerValue[1]) ? 200 : 412);
}
ctx.response().end();
});
}
private StatusHandler verifyStatus(VertxTestContext ctx) {
return (request, status) -> {
if (status != 200) {
ctx.failNow("Status is " + status);
} else {
ctx.completeNow();
}
};
}
@Test
public void testStringBody(VertxTestContext ctx) {
// @formatter:off
scenario(10)
.initialSequence("test")
.step(SC).httpRequest(HttpMethod.POST)
.path("/test?expect=bar")
.body("bar")
.handler().status(verifyStatus(ctx))
.endHandler()
.endStep();
// @formatter:on
runScenario();
}
@Test
public void testStringFromVar(VertxTestContext ctx) {
// @formatter:off
scenario()
.initialSequence("test")
.step(SC).action(new SetAction.Builder()
.var("x")
.value("bar"))
.step(SC).httpRequest(HttpMethod.POST)
.path("/test?expect=bar")
.body().fromVar("x").endBody()
.handler().status(verifyStatus(ctx))
.endHandler()
.endStep();
// @formatter:on
runScenario();
}
@Test
public void testLongChineseStringFromVar(VertxTestContext ctx) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 257; ++i) {
sb.append((char) random.nextInt(0x4E00, 0x9FA5));
}
String chineseStr = sb.toString();
// @formatter:off
scenario()
.initialSequence("test")
.step(SC).action(new SetAction.Builder()
.var("x")
.value(chineseStr))
.step(SC).httpRequest(HttpMethod.POST)
.path("/test?expect=" + URLEncoder.encode(chineseStr, StandardCharsets.UTF_8))
.body().fromVar("x").endBody()
.handler().status(verifyStatus(ctx)).endHandler()
.endStep();
// @formatter:on
runScenario();
}
@Test
public void testPattern(VertxTestContext ctx) {
// @formatter:off
scenario()
.initialSequence("test")
.step(SC).action(new SetAction.Builder()
.var("x")
.value("bar"))
.step(SC).httpRequest(HttpMethod.POST)
.path("/test?expect=${x}")
.body("bar")
.handler().status(verifyStatus(ctx))
.endHandler()
.endStep();
// @formatter:off
runScenario();
}
@Test
public void testStatusValidator() {
// @formatter:off
scenario()
.initialSequence("expectOK")
.step(SC).httpRequest(HttpMethod.GET)
.path("/status?s=205")
.handler()
.status(new RangeStatusValidator(205, 205))
.endHandler()
.endStep()
.endSequence()
.initialSequence("expectFail")
.step(SC).httpRequest(HttpMethod.GET)
.path("/status?s=406")
.handler()
.status(new RangeStatusValidator(200, 299))
.endHandler()
.endStep()
.endSequence()
.endScenario().endPhase()
.plugin(HttpPluginBuilder.class).ergonomics()
.autoRangeCheck(false)
.stopOnInvalid(false);
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
StatisticsSnapshot snapshot0 = stats.get("expectOK");
StatisticsSnapshot snapshot1 = stats.get("expectFail");
assertThat(HttpStats.get(snapshot0).status_2xx).isEqualTo(1);
assertThat(HttpStats.get(snapshot0).status_4xx).isEqualTo(0);
assertThat(HttpStats.get(snapshot1).status_2xx).isEqualTo(0);
assertThat(HttpStats.get(snapshot1).status_4xx).isEqualTo(1);
assertThat(snapshot0.invalid).isEqualTo(0);
assertThat(snapshot1.invalid).isEqualTo(1);
}
@Test
public void testRecordHeaderValueHandler() {
// @formatter:off
scenario()
.initialSequence("test")
.step(SC).httpRequest(HttpMethod.GET)
.path("/test")
.handler()
.header(new RecordHeaderTimeHandler.Builder().header("x-foo").unit("ms"))
.endHandler()
.endStep()
.endSequence();
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
assertThat(stats.get("test").requestCount).isEqualTo(1);
assertThat(stats.get("x-foo").histogram.getCountAtValue(TimeUnit.MILLISECONDS.toNanos(5))).isEqualTo(1);
}
@Test
public void testRequestHeaders() {
// @formatter:off
scenario()
.initialSequence("testFromVar")
.step(SC).action(new SetAction.Builder()
.var("foo")
.value("bar"))
.step(SC).httpRequest(HttpMethod.GET)
.path("/test?expectHeader=Authorization:bar")
.headers()
.withKey("Authorization")
.fromVar("foo")
.end()
.endHeaders()
.endStep()
.endSequence()
.initialSequence("testPattern")
.step(SC).action(new SetAction.Builder()
.var("foo")
.value("bar"))
.step(SC).httpRequest(HttpMethod.GET)
.path("/test?expectHeader=Authorization:xxxbarxxx")
.headers()
.withKey("Authorization")
.pattern("xxx${foo}xxx")
.end()
.endHeaders()
.endStep()
.endSequence();
// @formatter:on
Map<String, StatisticsSnapshot> stats = runScenario();
assertThat(HttpStats.get(stats.get("testFromVar")).status_2xx).isEqualTo(1);
assertThat(HttpStats.get(stats.get("testPattern")).status_2xx).isEqualTo(1);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/steps/HttpRequestStepUtil.java | http/src/test/java/io/hyperfoil/http/steps/HttpRequestStepUtil.java | package io.hyperfoil.http.steps;
import io.hyperfoil.http.api.StatusHandler;
public final class HttpRequestStepUtil {
public static StatusHandler[] statusHandlers(PrepareHttpRequestStep step) {
return step.handler.statusHandlers.clone();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/test/java/io/hyperfoil/http/steps/HttpUtilTest.java | http/src/test/java/io/hyperfoil/http/steps/HttpUtilTest.java | package io.hyperfoil.http.steps;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import io.hyperfoil.http.HttpUtil;
public class HttpUtilTest {
@Test
public void testAuthorityMatch() {
assertThat(HttpUtil.authorityMatch("http://example.com", "example.com", true)).isTrue();
assertThat(HttpUtil.authorityMatch("http://example.com/foobar", "example.com:80", true)).isTrue();
assertThat(HttpUtil.authorityMatch("http://example.com:80", "example.com", true)).isTrue();
assertThat(HttpUtil.authorityMatch("http://example.com:1234/foobar", "example.com:1234", true)).isTrue();
assertThat(HttpUtil.authorityMatch("http://example.com:1234/foobar", "example.com", true)).isFalse();
assertThat(HttpUtil.authorityMatch("http://example.com:1234/foobar", "example.com:8080", true)).isFalse();
assertThat(HttpUtil.authorityMatch("http://hyperfoil.io/foobar", "example.com", true)).isFalse();
assertThat(HttpUtil.authorityMatch("http://hyperfoil.io:80", "example.com:80", true)).isFalse();
assertThat(HttpUtil.authorityMatch("http://hyperfoil.io:1234", "example.com:1234", true)).isFalse();
assertThat(HttpUtil.authorityMatch("https://example.com", "example.com", false)).isTrue();
assertThat(HttpUtil.authorityMatch("https://example.com/foobar", "example.com:443", false)).isTrue();
assertThat(HttpUtil.authorityMatch("https://example.com:443", "example.com", false)).isTrue();
assertThat(HttpUtil.authorityMatch("https://example.com:1234/foobar", "example.com:1234", false)).isTrue();
assertThat(HttpUtil.authorityMatch("https://example.com:1234/foobar", "example.com", false)).isFalse();
assertThat(HttpUtil.authorityMatch("https://example.com:1234/foobar", "example.com:8443", false)).isFalse();
assertThat(HttpUtil.authorityMatch("https://hyperfoil.io/foobar", "example.com", false)).isFalse();
assertThat(HttpUtil.authorityMatch("https://hyperfoil.io:443", "example.com:443", false)).isFalse();
assertThat(HttpUtil.authorityMatch("https://hyperfoil.io:1234", "example.com:1234", false)).isFalse();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/HttpUtil.java | http/src/main/java/io/hyperfoil/http/HttpUtil.java | package io.hyperfoil.http;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.TimeZone;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.impl.Util;
import io.netty.buffer.ByteBuf;
import io.netty.util.AsciiString;
import io.netty.util.concurrent.FastThreadLocal;
public final class HttpUtil {
private static final Logger log = LogManager.getLogger(HttpUtil.class);
private static final AsciiString UTC_ASCII = new AsciiString("UTC");
private static final AsciiString GMT_ASCII = new AsciiString("GMT");
private static final TimeZone UTC = TimeZone.getTimeZone(UTC_ASCII.toString());
private static final TimeZone GMT = TimeZone.getTimeZone(GMT_ASCII.toString());
private static final FastThreadLocal<Map<AsciiString, Calendar>> CALENDARS = new FastThreadLocal<>() {
@Override
protected Map<AsciiString, Calendar> initialValue() {
return Map.of(
UTC_ASCII, Calendar.getInstance(UTC),
GMT_ASCII, Calendar.getInstance(GMT));
}
};
private static final CharSequence[] MONTHS = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov",
"dec" };
private static final byte[] BYTES_80 = "80".getBytes(StandardCharsets.UTF_8);
private static final byte[] BYTES_443 = "443".getBytes(StandardCharsets.UTF_8);
public static final String HTTP_PREFIX = "http://";
public static final String HTTPS_PREFIX = "https://";
private HttpUtil() {
}
public static int indexOf(CharSequence seq, int begin, char c) {
int length = seq.length();
for (int i = begin; i < length; ++i) {
if (seq.charAt(i) == c) {
return i;
}
}
return length;
}
public static int lastIndexOf(CharSequence seq, int end, char c) {
for (int i = end - 1; i >= 0; --i) {
if (seq.charAt(i) == c) {
return i;
}
}
return -1;
}
static long parseDate(CharSequence seq) {
return parseDate(seq, 0, seq.length());
}
public static long parseDate(CharSequence seq, int begin, int end) {
int i = begin;
for (; i < end && seq.charAt(i) != ','; ++i)
; // skip day-of-week
++i; // skip the comma
for (; i < end && seq.charAt(i) == ' '; ++i)
; // skip spaces
if (i + 2 >= end) {
log.warn("Cannot parse date {}", seq.subSequence(begin, end));
return 0;
}
int dayOfMonth;
if (seq.charAt(i + 1) == ' ') {
dayOfMonth = seq.charAt(i) - '0';
i += 2; // single digit and ' '
} else {
dayOfMonth = twoDigits(seq, i);
i += 3; // two digits and ' '
}
if (dayOfMonth < 1 || dayOfMonth > 31) {
log.warn("Cannot parse date {}", seq.subSequence(begin, end));
return 0;
}
if (i + 3 >= end) {
log.warn("Cannot parse date {}", seq.subSequence(begin, end));
return 0;
}
int month = -1;
for (int m = 0; m < MONTHS.length; ++m) {
if (Character.toLowerCase(seq.charAt(i)) == MONTHS[m].charAt(0) &&
Character.toLowerCase(seq.charAt(i + 1)) == MONTHS[m].charAt(1) &&
Character.toLowerCase(seq.charAt(i + 2)) == MONTHS[m].charAt(2)) {
month = m;
break;
}
}
if (month < 0) {
log.warn("Cannot parse month in date {}", seq.subSequence(begin, end));
return 0;
}
i += 4; // skip month and '-'
int nextSpace = indexOf(seq, i, ' ');
int year;
if (nextSpace - i == 4) {
year = (int) Util.parseLong(seq, i, nextSpace);
if (year < 1600 || year >= 3000) {
log.warn("Cannot parse year in date {}", seq.subSequence(begin, end));
return 0;
}
} else if (nextSpace - i == 2) {
year = twoDigits(seq, i);
if (year < 0 || year > 100) {
log.warn("Cannot parse year in date {}", seq.subSequence(begin, end));
return 0;
}
if (year < 70) {
year += 2000;
} else {
year += 1900;
}
} else {
log.warn("Cannot parse year in date {}", seq.subSequence(begin, end));
return 0;
}
for (i = nextSpace + 1; i < end && seq.charAt(i) == ' '; ++i)
; // skip spaces
if (i + 8 >= end || seq.charAt(i + 2) != ':' || seq.charAt(i + 5) != ':') {
log.warn("Cannot parse time in date {}", seq.subSequence(begin, end));
return 0;
}
int hour = twoDigits(seq, i);
int minute = twoDigits(seq, i + 3);
int second = twoDigits(seq, i + 6);
if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
log.warn("Cannot parse time in date {}", seq.subSequence(begin, end));
return 0;
}
for (i += 8; i < end && seq.charAt(i) == ' '; ++i)
; // skip spaces
Calendar calendar;
if (i < end) {
if (end - i >= 3 && AsciiString.regionMatches(seq, false, i, GMT_ASCII, 0, 3)) {
calendar = CALENDARS.get().get(GMT_ASCII);
} else if (end - i >= 3 && AsciiString.regionMatches(seq, false, i, UTC_ASCII, 0, 3)) {
calendar = CALENDARS.get().get(UTC_ASCII);
} else {
// allocate a new calendar only if not UTC or GMT
TimeZone timeZone = TimeZone.getTimeZone(seq.subSequence(i, end).toString());
calendar = Calendar.getInstance(timeZone);
}
} else {
calendar = CALENDARS.get().get(UTC_ASCII);
}
calendar.set(year, month, dayOfMonth, hour, minute, second);
return calendar.getTimeInMillis();
}
private static int twoDigits(CharSequence seq, int i) {
return 10 * (seq.charAt(i) - '0') + (seq.charAt(i + 1) - '0');
}
public static CharSequence formatDate(long timestamp) {
Calendar calendar = Calendar.getInstance(GMT);
calendar.setTimeInMillis(timestamp);
byte[] bytes = new byte[29];
switch (calendar.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
bytes[0] = 'S';
bytes[1] = 'u';
bytes[2] = 'n';
break;
case Calendar.MONDAY:
bytes[0] = 'M';
bytes[1] = 'o';
bytes[2] = 'n';
break;
case Calendar.TUESDAY:
bytes[0] = 'T';
bytes[1] = 'u';
bytes[2] = 'e';
break;
case Calendar.WEDNESDAY:
bytes[0] = 'W';
bytes[1] = 'e';
bytes[2] = 'd';
break;
case Calendar.THURSDAY:
bytes[0] = 'T';
bytes[1] = 'h';
bytes[2] = 'u';
break;
case Calendar.FRIDAY:
bytes[0] = 'F';
bytes[1] = 'r';
bytes[2] = 'i';
break;
case Calendar.SATURDAY:
bytes[0] = 'S';
bytes[1] = 'a';
bytes[2] = 't';
break;
}
bytes[3] = ',';
bytes[4] = ' ';
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
bytes[5] = (byte) ('0' + dayOfMonth / 10);
bytes[6] = (byte) ('0' + dayOfMonth % 10);
bytes[7] = '-';
CharSequence month = MONTHS[calendar.get(Calendar.MONTH)];
bytes[8] = (byte) month.charAt(0);
bytes[9] = (byte) month.charAt(1);
bytes[10] = (byte) month.charAt(2);
bytes[11] = '-';
int year = calendar.get(Calendar.YEAR);
bytes[12] = (byte) ('0' + year / 1000);
bytes[13] = (byte) ('0' + year / 100 % 10);
bytes[14] = (byte) ('0' + year / 10 % 10);
bytes[15] = (byte) ('0' + year % 10);
bytes[16] = ' ';
int hour = calendar.get(Calendar.HOUR_OF_DAY);
bytes[17] = (byte) ('0' + hour / 10);
bytes[18] = (byte) ('0' + hour % 10);
bytes[19] = ':';
int minute = calendar.get(Calendar.MINUTE);
bytes[20] = (byte) ('0' + minute / 10);
bytes[21] = (byte) ('0' + minute % 10);
bytes[22] = ':';
int second = calendar.get(Calendar.SECOND);
bytes[23] = (byte) ('0' + second / 10);
bytes[24] = (byte) ('0' + second % 10);
bytes[25] = ' ';
bytes[26] = 'G';
bytes[27] = 'M';
bytes[28] = 'T';
return new AsciiString(bytes, false);
}
public static boolean authorityMatch(CharSequence path, CharSequence authority, boolean isHttp) {
return isHttp ? authorityMatchHttp(path, authority) : authorityMatchHttps(path, authority);
}
public static boolean authorityMatchHttp(CharSequence path, CharSequence authority) {
return authorityMatch(path, authority, "80", HTTP_PREFIX.length());
}
public static boolean authorityMatchHttps(CharSequence path, CharSequence authority) {
return authorityMatch(path, authority, "443", HTTPS_PREFIX.length());
}
public static boolean authorityMatch(CharSequence path, CharSequence authority, String defaultPort, int prefixLength) {
int colonIndex = indexOf(authority, 0, ':');
// hostname match is case-insensitive
if (!AsciiString.regionMatches(path, true, prefixLength, authority, 0, colonIndex)) {
return false;
}
if (prefixLength + colonIndex < path.length() && path.charAt(prefixLength + colonIndex) == ':') {
// path uses explicit port
CharSequence port;
int portOffset, portLength;
if (authority.length() == colonIndex) {
port = defaultPort;
portOffset = 0;
portLength = defaultPort.length();
} else {
port = authority;
portOffset = colonIndex + 1;
portLength = authority.length() - colonIndex - 1;
}
return AsciiString.regionMatches(path, false, prefixLength + colonIndex + 1, port, portOffset, portLength);
} else {
return colonIndex == authority.length() ||
colonIndex == authority.length() - defaultPort.length() - 1 &&
AsciiString.regionMatches(authority, false, authority.length() - defaultPort.length(), defaultPort, 0,
defaultPort.length());
}
}
public static boolean authorityMatch(ByteBuf pathData, int pathOffset, int pathLength, byte[] authority, boolean isHttp) {
return isHttp ? authorityMatchHttp(pathData, pathOffset, pathLength, authority)
: authorityMatchHttps(pathData, pathOffset, pathLength, authority);
}
public static boolean authorityMatchHttp(ByteBuf pathData, int pathOffset, int pathLength, byte[] authority) {
return authorityMatch(pathData, pathOffset, pathLength, authority, BYTES_80, HTTP_PREFIX.length());
}
public static boolean authorityMatchHttps(ByteBuf pathData, int pathOffset, int pathLength, byte[] authority) {
return authorityMatch(pathData, pathOffset, pathLength, authority, BYTES_443, HTTPS_PREFIX.length());
}
public static boolean authorityMatch(ByteBuf pathData, int pathOffset, int pathLength, byte[] authority, byte[] defaultPort,
int prefixLength) {
int colonIndex = indexOf(authority, (byte) ':');
// For simplicity we won't bother with case-insensitive match
if (!regionMatches(pathData, pathOffset + prefixLength, pathLength - prefixLength, authority, 0, colonIndex)) {
return false;
}
if (pathData.getByte(prefixLength + colonIndex) == ':') {
// path uses explicit port
byte[] port;
int portOffset, portLength;
if (authority.length == colonIndex) {
port = defaultPort;
portOffset = 0;
portLength = defaultPort.length;
} else {
port = authority;
portOffset = colonIndex + 1;
portLength = authority.length - colonIndex - 1;
}
return regionMatches(pathData, pathOffset + prefixLength + colonIndex, pathLength - prefixLength - colonIndex, port,
portOffset, portLength);
} else {
return colonIndex == authority.length ||
colonIndex == authority.length - defaultPort.length - 1 &&
Arrays.equals(authority, authority.length - defaultPort.length, authority.length, defaultPort, 0,
defaultPort.length);
}
}
private static boolean regionMatches(ByteBuf data, int offset, int dataLength, byte[] bytes, int bs, int length) {
if (dataLength < length) {
return false;
}
assert bytes.length >= bs + length;
for (int i = 0; i < length; ++i) {
if (data.getByte(offset + i) != bytes[bs + i]) {
return false;
}
}
return true;
}
static int indexOf(byte[] bytes, byte b) {
for (int i = 0; i <= bytes.length; ++i) {
if (bytes[i] == b) {
return i;
}
}
return bytes.length;
}
public static int indexOf(ByteBuf data, int offset, int length, char c) {
for (int i = 0; i <= length; ++i) {
if (data.getByte(offset + i) == c) {
return i;
}
}
return length;
}
public static int prefixLength(boolean isHttp) {
return isHttp ? HTTP_PREFIX.length() : HTTPS_PREFIX.length();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/UserAgentAppender.java | http/src/main/java/io/hyperfoil/http/UserAgentAppender.java | package io.hyperfoil.http;
import java.net.InetAddress;
import java.net.UnknownHostException;
import io.hyperfoil.api.session.ResourceUtilizer;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.function.SerializableBiConsumer;
import io.hyperfoil.http.api.HttpRequestWriter;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.util.AsciiString;
public class UserAgentAppender implements SerializableBiConsumer<Session, HttpRequestWriter>, ResourceUtilizer,
Session.ResourceKey<UserAgentAppender.SessionId> {
private static final String HOSTNAME;
static {
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
hostname = "unknown";
}
HOSTNAME = hostname;
}
@Override
public void accept(Session session, HttpRequestWriter httpRequestWriter) {
httpRequestWriter.putHeader(HttpHeaderNames.USER_AGENT, session.getResource(this).id);
}
@Override
public void reserve(Session session) {
SessionId sessionId = new SessionId(new AsciiString("#" + session.uniqueId() + "@" + HOSTNAME));
session.declareResource(this, () -> sessionId);
}
public static final class SessionId implements Session.Resource {
public final AsciiString id;
public SessionId(AsciiString id) {
this.id = id;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/HttpCacheImpl.java | http/src/main/java/io/hyperfoil/http/HttpCacheImpl.java | package io.hyperfoil.http;
import java.time.Clock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.util.Trie;
import io.hyperfoil.http.api.CacheControl;
import io.hyperfoil.http.api.HttpCache;
import io.hyperfoil.http.api.HttpMethod;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpRequestWriter;
import io.hyperfoil.impl.Util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.util.AsciiString;
/**
* This represents a browser cache = private one.
*/
public class HttpCacheImpl implements HttpCache {
private static final Logger log = LogManager.getLogger(HttpCacheImpl.class);
// we're ignoring no-transform directive
private static final Trie REQUEST_CACHE_CONTROL = new Trie("max-age=", "no-cache", "no-store", "max-stale=", "min-fresh=",
"only-if-cached");
// ignoring no-transform, public, private, proxy-revalidate and s-max-age as this is a private cache
private static final Trie RESPONSE_CACHE_CONTROL = new Trie("max-age=", "no-cache", "no-store", "must-revalidate");
private static final int MAX_AGE = 0;
private static final int NO_CACHE = 1;
private static final int NO_STORE = 2;
private static final int MAX_STALE = 3;
private static final int MIN_FRESH = 4;
private static final int ONLY_IF_CACHED = 5;
private static final int MUST_REVALIDATE = 3;
private final Clock clock;
// TODO: optimize this structure
private final Map<CharSequence, Map<CharSequence, List<Record>>> records = new HashMap<>();
private final List<Record> freeRecords = new ArrayList<>();
private final List<List<Record>> freeLists = new ArrayList<>();
private final Function<CharSequence, List<Record>> newList = this::newList;
public HttpCacheImpl(Clock clock) {
this.clock = clock;
}
@Override
public void onSessionReset(Session session) {
clear();
}
@Override
public void beforeRequestHeaders(HttpRequest request) {
switch (request.method) {
case GET:
case HEAD:
break;
default:
// we never cache other queries
return;
}
Map<CharSequence, List<Record>> authorityRecords = records.get(request.authority);
if (authorityRecords == null) {
return;
}
List<Record> pathRecords = authorityRecords.get(request.path);
if (pathRecords == null || pathRecords.isEmpty()) {
return;
}
for (int i = 0; i < pathRecords.size(); ++i) {
request.cacheControl.matchingCached.add(pathRecords.get(i));
}
}
@Override
public void requestHeader(HttpRequest request, CharSequence header, CharSequence value) {
if (request.method != HttpMethod.GET && request.method != HttpMethod.HEAD) {
return;
}
if (HttpHeaderNames.CACHE_CONTROL.contentEqualsIgnoreCase(header)) {
handleRequestCacheControl(request, value);
} else if (HttpHeaderNames.PRAGMA.contentEqualsIgnoreCase(header)) {
// We should ignore Pragma if there's Cache-Control, too, but we can't see to the future...
if (AsciiString.contentEquals("no-cache", value)) {
request.cacheControl.noCache = true;
}
} else if (HttpHeaderNames.IF_MATCH.contentEqualsIgnoreCase(header)) {
handleIfMatch(request, value);
} else if (HttpHeaderNames.IF_NONE_MATCH.contentEqualsIgnoreCase(header)) {
handleIfNoneMatch(request, value);
}
// Note: theoretically we need all headers as these might influence the caching
// if the cache keeps a record with 'Vary' header; for simplicity the cache
// won't store any such records.
}
// This is the command commonly used with GET: return if server-version differs from local one.
// That means that `matchingCached` should contain entries with these tags.
private void handleIfNoneMatch(HttpRequest request, CharSequence value) {
// We'll parse the header multiple times to avoid allocating extra colleciton
RECORD_LOOP: for (Iterator<HttpCache.Record> iterator = request.cacheControl.matchingCached.iterator(); iterator
.hasNext();) {
Record record = (Record) iterator.next();
if (record.etag == null) {
iterator.remove();
continue;
}
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == ' ') {
continue;
} else if (c == '*') {
continue RECORD_LOOP;
} else if (c == 'W') {
// We'll use weak comparison so we can ignore the weakness flag
if (++i >= value.length() || value.charAt(i) != '/') {
log.warn("Invalid If-None-Match: {}", value);
return;
}
} else if (c == '"') {
int start = ++i;
for (; i < value.length() && value.charAt(i) != '"'; ++i)
;
int length = i - start;
if (length == record.etag.length() && AsciiString.regionMatches(record.etag, false, 0, value, start, length)) {
continue RECORD_LOOP;
}
while (++i < value.length() && value.charAt(i) == ' ')
;
if (i < value.length() && value.charAt(i) != ',') {
log.warn("Invalid If-None-Match: {}", value);
return;
}
} else {
log.warn("Invalid If-None-Match: {}", value);
return;
}
}
// we haven't found a match
iterator.remove();
}
}
// Usually this is used with conditional modifying requests; GET if-match would return matching
// resources from servers, so `matchingCached` should contain those records that *DONT* match.
private void handleIfMatch(HttpRequest request, CharSequence value) {
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == ' ') {
continue;
} else if (c == '*') {
request.cacheControl.matchingCached.clear();
return;
} else if (c == '"') {
int start = ++i;
for (; i < value.length() && value.charAt(i) != '"'; ++i)
;
int length = i - start;
List<HttpCache.Record> matchingCached = request.cacheControl.matchingCached;
for (Iterator<HttpCache.Record> it = matchingCached.iterator(); it.hasNext();) {
HttpCache.Record item = it.next();
Record record = (Record) item;
if (record.etag != null && !record.weakETag && length == record.etag.length() &&
AsciiString.regionMatches(record.etag, false, 0, value, start, length)) {
it.remove();
}
}
while (++i < value.length() && value.charAt(i) == ' ')
;
if (i < value.length() && value.charAt(i) != ',') {
log.warn("Invalid If-Match: {}", value);
return;
}
} else {
log.warn("Invalid If-Match: {}", value);
return;
}
}
}
private void handleRequestCacheControl(HttpRequest request, CharSequence value) {
int maxAge = 0;
int maxStale = 0;
int minFresh = 0;
Trie.State state = REQUEST_CACHE_CONTROL.newState();
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == ',') {
state.reset();
do {
++i;
if (i >= value.length()) {
break;
} else {
c = value.charAt(i);
}
} while (c == ' ');
--i;
} else {
int pos = i + 1;
switch (state.next((byte) (c & 0xFF))) {
case MAX_AGE:
i = skipNumbers(value, pos);
maxAge = parseIntSaturated(value, pos, i);
--i;
break;
case MAX_STALE:
i = skipNumbers(value, pos);
maxStale = parseIntSaturated(value, pos, i);
--i;
break;
case MIN_FRESH:
i = skipNumbers(value, pos);
minFresh = parseIntSaturated(value, pos, i);
--i;
break;
case NO_CACHE:
request.cacheControl.noCache = true;
break;
case NO_STORE:
request.cacheControl.noStore = true;
break;
case ONLY_IF_CACHED:
request.cacheControl.onlyIfCached = true;
break;
}
}
}
long now = clock.millis();
Iterator<HttpCache.Record> it = request.cacheControl.matchingCached.iterator();
while (it.hasNext()) {
Record record = (Record) it.next();
if (maxAge > 0 && now - record.date > maxAge * 1000) {
it.remove();
} else if ((record.mustRevalidate && now >= record.expires)
|| (maxStale > 0 && now - record.expires > maxStale * 1000)) {
it.remove();
} else if (minFresh > 0 && record.expires - now < minFresh * 1000) {
it.remove();
}
}
// When we did the filtering here we should not do it any later
// (because that would not consider allowed stale responses)
if (maxAge > 0 || maxStale > 0 || minFresh > 0) {
request.cacheControl.ignoreExpires = true;
}
}
@Override
public boolean isCached(HttpRequest request, HttpRequestWriter writer) {
if (!request.cacheControl.ignoreExpires) {
long now = clock.millis();
for (Iterator<HttpCache.Record> iterator = request.cacheControl.matchingCached.iterator(); iterator.hasNext();) {
Record record = (Record) iterator.next();
if (record.expires != Long.MIN_VALUE && now > record.expires) {
iterator.remove();
}
}
}
if (request.cacheControl.matchingCached.isEmpty()) {
if (request.cacheControl.onlyIfCached) {
request.enter();
try {
request.handlers().handleStatus(request, 504, "Request was cache-only.");
} finally {
request.exit();
request.session.proceed();
}
return request.cacheControl.wasCached = true;
} else {
return request.cacheControl.wasCached = false;
}
} else {
Record mostRecent = findMostRecent(request);
if (request.cacheControl.noCache || mostRecent.noCache) {
addValidationHeaders(mostRecent, writer);
return request.cacheControl.wasCached = false;
}
return request.cacheControl.wasCached = true;
}
}
private Record findMostRecent(HttpRequest request) {
Record mostRecent = null;
for (HttpCache.Record r : request.cacheControl.matchingCached) {
Record record = (Record) r;
if (mostRecent == null || record.date < mostRecent.date) {
mostRecent = record;
}
}
return mostRecent;
}
private void addValidationHeaders(Record record, HttpRequestWriter writer) {
if (record.etag != null) {
writer.putHeader(HttpHeaderNames.IF_NONE_MATCH, record.etag);
} else if (record.lastModified > Long.MIN_VALUE) {
writer.putHeader(HttpHeaderNames.IF_MODIFIED_SINCE, HttpUtil.formatDate(record.lastModified));
}
}
@Override
public void tryStore(HttpRequest request) {
CacheControl cc = request.cacheControl;
if (cc.noStore) {
return;
}
if (cc.responseDate == Long.MIN_VALUE) {
cc.responseDate = clock.millis() - cc.responseAge * 1000;
}
if (cc.responseMaxAge != 0) {
cc.responseExpires = cc.responseDate + cc.responseMaxAge * 1000;
}
if (cc.responseExpires != Long.MIN_VALUE && cc.responseExpires < cc.responseDate) {
return;
}
Map<CharSequence, List<Record>> authorityRecords = records.computeIfAbsent(request.authority, a -> new HashMap<>());
List<Record> pathRecords = authorityRecords.computeIfAbsent(request.path, newList);
if (cc.responseEtag != null) {
boolean weak = false;
if (AsciiString.regionMatches(cc.responseEtag, false, 0, "W/", 0, 2)) {
weak = true;
}
// Update existing record (with matching etag) or add new
for (Record record : pathRecords) {
if (record.etag.length() == cc.responseEtag.length() - (weak ? 4 : 2) &&
AsciiString.regionMatches(record.etag, false, 0, cc.responseEtag, weak ? 1 : 3, record.etag.length())) {
record.update(cc);
return;
}
}
pathRecords.add(newRecord().set(cc));
} else if (cc.responseLastModified != Long.MIN_VALUE) {
for (Record record : pathRecords) {
if (record.lastModified > cc.responseLastModified) {
return;
}
}
Record record = pathRecords.isEmpty() ? newRecord().set(cc) : pathRecords.get(0).update(cc);
pathRecords.clear();
pathRecords.add(record);
} else {
Record record = null;
for (Iterator<Record> iterator = pathRecords.iterator(); iterator.hasNext();) {
record = iterator.next();
if (record.lastModified == Long.MIN_VALUE && record.etag == null) {
iterator.remove();
}
}
pathRecords.add(record == null ? newRecord().set(cc) : record.update(cc));
}
}
private Record newRecord() {
return freeRecords.isEmpty() ? new Record() : freeRecords.remove(freeRecords.size() - 1);
}
private List<Record> newList(CharSequence key) {
return freeLists.isEmpty() ? new ArrayList<>() : freeLists.remove(freeLists.size() - 1);
}
@Override
public void invalidate(CharSequence authority, CharSequence path) {
if (AsciiString.regionMatches(HttpUtil.HTTP_PREFIX, false, 0, path, 0, HttpUtil.HTTP_PREFIX.length())) {
if (!HttpUtil.authorityMatchHttp(path, authority)) {
return;
}
path = path.subSequence(HttpUtil.indexOf(path, HttpUtil.HTTP_PREFIX.length(), '/'), path.length());
} else if (AsciiString.regionMatches(HttpUtil.HTTPS_PREFIX, false, 0, path, 0, HttpUtil.HTTPS_PREFIX.length())) {
if (!HttpUtil.authorityMatchHttps(path, authority)) {
return;
}
path = path.subSequence(HttpUtil.indexOf(path, HttpUtil.HTTPS_PREFIX.length(), '/'), path.length());
}
Map<CharSequence, List<Record>> authorityRecords = records.get(authority);
if (authorityRecords == null) {
return;
}
List<Record> pathRecords = authorityRecords.get(path);
if (pathRecords != null) {
pathRecords.clear();
}
}
@Override
public int size() {
return records.values().stream().flatMap(map -> map.values().stream()).mapToInt(List::size).sum();
}
private static int parseIntSaturated(CharSequence value, int begin, int end) {
return (int) Math.min(Util.parseLong(value, begin, end), Integer.MAX_VALUE);
}
private static int skipNumbers(CharSequence value, int pos) {
int i = pos;
for (; i < value.length(); ++i) {
char c = value.charAt(i);
if (c < '0' || c > '9') {
return i;
}
}
return i;
}
public void responseHeader(HttpRequest request, CharSequence header, CharSequence value) {
if (HttpHeaderNames.CACHE_CONTROL.contentEqualsIgnoreCase(header)) {
Trie.State state = RESPONSE_CACHE_CONTROL.newState();
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == ',') {
state.reset();
do {
++i;
if (i >= value.length()) {
return;
} else {
c = value.charAt(i);
}
} while (c == ' ');
--i;
} else {
int pos = i + 1;
switch (state.next((byte) (c & 0xFF))) {
case MAX_AGE:
i = skipNumbers(value, pos);
request.cacheControl.responseMaxAge = parseIntSaturated(value, pos, i);
--i;
break;
case NO_CACHE:
request.cacheControl.responseNoCache = true;
break;
case NO_STORE:
request.cacheControl.noStore = true;
break;
case MUST_REVALIDATE:
request.cacheControl.responseMustRevalidate = true;
break;
}
}
}
} else if (HttpHeaderNames.EXPIRES.contentEqualsIgnoreCase(header)) {
request.cacheControl.responseExpires = HttpUtil.parseDate(value);
} else if (HttpHeaderNames.AGE.contentEqualsIgnoreCase(header)) {
request.cacheControl.responseAge = parseIntSaturated(value, 0, value.length());
} else if (HttpHeaderNames.DATE.contentEqualsIgnoreCase(header)) {
request.cacheControl.responseDate = HttpUtil.parseDate(value);
} else if (HttpHeaderNames.LAST_MODIFIED.contentEqualsIgnoreCase(header)) {
request.cacheControl.responseLastModified = HttpUtil.parseDate(value);
} else if (HttpHeaderNames.ETAG.contentEqualsIgnoreCase(header)) {
request.cacheControl.responseEtag = value;
} else if (HttpHeaderNames.PRAGMA.contentEqualsIgnoreCase(header)) {
if (AsciiString.contentEquals("no-cache", value)) {
request.cacheControl.responseNoCache = true;
}
}
}
@Override
public void clear() {
for (Map<CharSequence, List<Record>> authorityRecords : records.values()) {
// We must clean up authority records because paths can be request-specific; we can assume
// that authority can be cached for extended periods of time
for (List<Record> pathRecords : authorityRecords.values()) {
for (Record record : pathRecords) {
record.reset();
freeRecords.add(record);
}
pathRecords.clear();
freeLists.add(pathRecords);
}
authorityRecords.clear();
}
}
private static class Record implements HttpCache.Record {
long date;
long expires;
boolean noCache;
boolean mustRevalidate;
long lastModified;
boolean weakETag;
CharSequence etag;
Record set(CacheControl cc) {
this.date = cc.responseDate;
this.expires = cc.responseExpires;
this.noCache = cc.responseNoCache;
this.mustRevalidate = cc.responseMustRevalidate;
this.lastModified = cc.responseLastModified;
this.weakETag = cc.responseEtag != null && AsciiString.regionMatches(cc.responseEtag, false, 0, "W/", 0, 2);
this.etag = cc.responseEtag == null ? null
: cc.responseEtag.subSequence(weakETag ? 3 : 1, cc.responseEtag.length() - 1);
return this;
}
void reset() {
// other values are scalar
etag = null;
}
Record update(CacheControl cc) {
date = Math.max(date, cc.responseDate);
expires = Math.max(expires, cc.responseExpires);
noCache = noCache || cc.responseNoCache;
mustRevalidate = mustRevalidate || cc.responseMustRevalidate;
lastModified = Math.max(lastModified, cc.responseLastModified);
return this;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/HttpRequestPool.java | http/src/main/java/io/hyperfoil/http/HttpRequestPool.java | package io.hyperfoil.http;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.api.collection.LimitedPool;
import io.hyperfoil.api.config.Scenario;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.data.LimitedPoolResource;
import io.hyperfoil.http.api.HttpRequest;
public class HttpRequestPool extends LimitedPoolResource<HttpRequest> {
private static final Logger log = LogManager.getLogger(HttpRequestPool.class);
private static final boolean trace = log.isTraceEnabled();
public static final Session.ResourceKey<LimitedPoolResource<HttpRequest>> KEY = new Key<>();
public HttpRequestPool(Scenario scenario, Session session, boolean httpCacheEnabled) {
super(scenario.maxRequests(), HttpRequest.class, () -> new HttpRequest(session, httpCacheEnabled));
}
public static LimitedPool<HttpRequest> get(Session session) {
return session.getResource(KEY);
}
@Override
public void onSessionReset(Session session) {
if (!isFull()) {
// We can't guarantee that requests will be back in session's requestPool when it terminates
// because if the requests did timeout (calling handlers and eventually letting the session terminate)
// it might still be held in the connection.
for (HttpRequest request : (HttpRequest[]) originalObjects) {
// We won't issue the warning for invalid requests because these are likely not in flight anymore
// and we are stopping the session exactly due to the invalid request.
if (!request.isCompleted() && request.isValid()) {
log.warn("#{} Session completed with requests in-flight!", session.uniqueId());
break;
}
}
cancelRequests();
}
super.onSessionReset(session);
}
private void cancelRequests() {
// We need to close all connections used to ongoing requests, despite these might
// carry requests from independent phases/sessions
for (HttpRequest request : (HttpRequest[]) originalObjects) {
if (!request.isCompleted()) {
// When one of the handlers calls Session.stop() it may terminate the phase completely,
// sending stats before recording the invalid request in HttpResponseHandlersImpl.handleEnd().
// That's why we record it here instead and mark the request as completed (to recording the stats twice)
if (!request.isValid()) {
request.statistics().addInvalid(request.startTimestampMillis());
}
if (trace) {
log.trace("Canceling request {} to {}", request, request.connection());
}
request.setCompleting();
if (request.connection() != null) {
request.connection().close();
}
if (!request.isCompleted()) {
// Connection.close() cancels everything in flight but if this is called
// from handleEnd() the request is not in flight anymore
log.trace("#{} Connection close did not complete the request.",
request.session != null ? request.session.uniqueId() : 0);
request.setCompleted();
request.release();
}
}
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/HttpRunData.java | http/src/main/java/io/hyperfoil/http/HttpRunData.java | package io.hyperfoil.http;
import java.time.Clock;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.net.ssl.SSLException;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.config.Scenario;
import io.hyperfoil.api.config.Sequence;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.core.api.PluginRunData;
import io.hyperfoil.core.impl.ConnectionStatsConsumer;
import io.hyperfoil.http.api.HttpCache;
import io.hyperfoil.http.api.HttpClientPool;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpConnectionPool;
import io.hyperfoil.http.api.HttpDestinationTable;
import io.hyperfoil.http.config.ConnectionStrategy;
import io.hyperfoil.http.config.Http;
import io.hyperfoil.http.config.HttpPluginConfig;
import io.hyperfoil.http.connection.HttpClientPoolImpl;
import io.hyperfoil.http.connection.HttpDestinationTableImpl;
import io.hyperfoil.http.connection.SessionConnectionPool;
import io.netty.channel.EventLoop;
import io.vertx.core.Future;
import io.vertx.core.Promise;
public class HttpRunData implements PluginRunData {
private final HttpPluginConfig plugin;
private final HttpDestinationTableImpl[] destinations;
private final Map<String, HttpClientPool> clientPools = new HashMap<>();
private final boolean hasSessionPools;
private final boolean hasHttpCacheEnabled;
public HttpRunData(Benchmark benchmark, EventLoop[] executors, int agentId) {
plugin = benchmark.plugin(HttpPluginConfig.class);
// either all http configs disable the cache or keep it enabled
hasHttpCacheEnabled = plugin.http().values().stream().anyMatch(Http::enableHttpCache);
hasSessionPools = plugin.http().values().stream()
.anyMatch(http -> http.connectionStrategy() != ConnectionStrategy.SHARED_POOL);
@SuppressWarnings("unchecked")
Map<String, HttpConnectionPool>[] connectionPools = new Map[executors.length];
destinations = new HttpDestinationTableImpl[executors.length];
for (Map.Entry<String, Http> http : plugin.http().entrySet()) {
try {
HttpClientPool httpClientPool = new HttpClientPoolImpl(http.getValue(), executors, benchmark, agentId);
clientPools.put(http.getKey(), httpClientPool);
if (http.getValue().isDefault()) {
clientPools.put(null, httpClientPool);
}
for (int executorId = 0; executorId < executors.length; ++executorId) {
HttpConnectionPool httpConnectionPool = httpClientPool.connectionPool(executors[executorId]);
Map<String, HttpConnectionPool> pools = connectionPools[executorId];
if (pools == null) {
connectionPools[executorId] = pools = new HashMap<>();
}
pools.put(http.getKey(), httpConnectionPool);
if (http.getValue().isDefault()) {
pools.put(null, httpConnectionPool);
}
}
} catch (SSLException e) {
throw new IllegalStateException(
"Failed creating connection pool to " + http.getValue().host() + ":" + http.getValue().port(), e);
}
}
for (int executorId = 0; executorId < connectionPools.length; executorId++) {
Map<String, HttpConnectionPool> pools = connectionPools[executorId];
destinations[executorId] = new HttpDestinationTableImpl(pools);
}
}
public static void initForTesting(Session session) {
initForTesting(session, Clock.systemDefaultZone(), true);
}
public static void initForTesting(Session session, Clock clock, boolean cacheEnabled) {
Scenario dummyScenario = new Scenario(new Sequence[0], new Sequence[0], 16, 16);
session.declareSingletonResource(HttpDestinationTable.KEY, new HttpDestinationTableImpl(Collections.emptyMap()));
if (cacheEnabled) {
session.declareSingletonResource(HttpCache.KEY, new HttpCacheImpl(clock));
}
session.declareSingletonResource(HttpRequestPool.KEY, new HttpRequestPool(dummyScenario, session, cacheEnabled));
}
@Override
public void initSession(Session session, int executorId, Scenario scenario, Clock clock) {
HttpDestinationTable destinations = this.destinations[executorId];
if (hasSessionPools) {
destinations = new HttpDestinationTableImpl(destinations,
pool -> {
ConnectionStrategy strategy = pool.clientPool().config().connectionStrategy();
switch (strategy) {
case SHARED_POOL:
case ALWAYS_NEW:
return pool;
case SESSION_POOLS:
case OPEN_ON_REQUEST:
return new SessionConnectionPool(pool, scenario.maxRequests());
default:
throw new IllegalStateException();
}
});
}
session.declareSingletonResource(HttpDestinationTable.KEY, destinations);
if (hasHttpCacheEnabled) {
session.declareSingletonResource(HttpCache.KEY, new HttpCacheImpl(clock));
}
session.declareSingletonResource(HttpRequestPool.KEY, new HttpRequestPool(scenario, session, hasHttpCacheEnabled));
}
@Override
public void openConnections(Function<Callable<Void>, Future<Void>> blockingHandler,
Consumer<Future<Void>> promiseCollector) {
for (Map.Entry<String, HttpClientPool> entry : clientPools.entrySet()) {
// default client pool is initialized by name
if (entry.getKey() != null) {
Promise<Void> promise = Promise.promise();
promiseCollector.accept(promise.future());
entry.getValue().start(promise);
}
}
}
@Override
public void listConnections(Consumer<String> connectionCollector) {
// Connection pools should be accessed only from the executor, but since we're only publishing stats...
for (HttpDestinationTableImpl destinations : destinations) {
for (Map.Entry<String, HttpConnectionPool> entry : destinations.iterable()) {
if (entry.getKey() == null) {
// Ignore default pool: it's there twice
continue;
}
HttpConnectionPool pool = entry.getValue();
Collection<? extends HttpConnection> connections = pool.connections();
Map<String, AtomicInteger> byType = new HashMap<>();
int available = 0;
int inFlight = 0;
for (HttpConnection conn : connections) {
if (conn.isAvailable()) {
available++;
}
inFlight += conn.inFlight();
byType.computeIfAbsent(conn.getClass().getSimpleName() + (conn.isSecure() ? "(SSL)" : ""),
k -> new AtomicInteger()).incrementAndGet();
}
connectionCollector
.accept(String.format("%s: %d/%d available, %d in-flight requests, %d waiting sessions (estimate), types: %s",
entry.getKey(), available, connections.size(), inFlight, pool.waitingSessions(), byType));
}
}
}
@Override
public void visitConnectionStats(ConnectionStatsConsumer consumer) {
for (var entry : clientPools.entrySet()) {
// default pool is in the map twice
if (entry.getKey() != null) {
entry.getValue().visitConnectionStats(consumer);
}
}
}
@Override
public void shutdown() {
for (HttpClientPool pool : clientPools.values()) {
pool.shutdown();
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/cookie/CookieStore.java | http/src/main/java/io/hyperfoil/http/cookie/CookieStore.java | package io.hyperfoil.http.cookie;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.http.HttpUtil;
import io.hyperfoil.http.api.HttpRequestWriter;
import io.hyperfoil.impl.Util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.util.AsciiString;
class CookieStore implements Session.Resource {
private static final Logger log = LogManager.getLogger(CookieRecorder.class);
// We need only single object for all cookies
public static final Session.ResourceKey<CookieStore> COOKIES = new Session.ResourceKey<CookieStore>() {
};
private static final Attribute[] ATTRIBUTES = Attribute.values();
private static final int MAX_SITES = 16;
private final Cookie[] cookies = new Cookie[MAX_SITES];
CookieStore() {
for (int i = 0; i < cookies.length; ++i) {
cookies[i] = new Cookie();
}
}
@Override
public void onSessionReset(Session session) {
for (int i = 0; i < cookies.length; ++i) {
cookies[i].clear();
}
}
public void setCookie(CharSequence requestOrigin, CharSequence requestPath, CharSequence seq) {
int nameEnd = HttpUtil.indexOf(seq, 0, '=');
if (nameEnd < 0) {
log.warn("Invalid cookie value (no name): {}", seq);
return;
}
CharSequence name = seq.subSequence(0, nameEnd);
int valueEnd = HttpUtil.indexOf(seq, nameEnd + 1, ';');
CharSequence nameValue = seq.subSequence(0, valueEnd);
CharSequence domain = null;
CharSequence path = null;
boolean secure = false;
long maxAge = Long.MAX_VALUE;
long expires = Long.MAX_VALUE;
++valueEnd;
while (valueEnd < seq.length()) {
for (; valueEnd < seq.length() && seq.charAt(valueEnd) == ' '; ++valueEnd)
;
int semIndex = HttpUtil.indexOf(seq, valueEnd, ';');
for (int a = 0; a < ATTRIBUTES.length; ++a) {
Attribute attribute = ATTRIBUTES[a];
if (matchPrefix(attribute.text, seq, valueEnd)) {
switch (attribute) {
case EXPIRES:
expires = HttpUtil.parseDate(seq, valueEnd + attribute.text.length(), semIndex);
break;
case MAX_AGE:
maxAge = Util.parseLong(seq, valueEnd + attribute.text.length(), semIndex, Long.MAX_VALUE);
break;
case DOMAIN:
// ignore leading dot
if (valueEnd < seq.length() && seq.charAt(valueEnd) == '.') {
++valueEnd;
}
domain = seq.subSequence(valueEnd + attribute.text.length(), semIndex);
break;
case PATH:
path = seq.subSequence(valueEnd + attribute.text.length(), semIndex);
break;
case SECURE:
secure = true;
break;
case HTTPONLY:
case EXTENSION:
default:
// silently ignored
break;
}
break;
}
}
valueEnd = semIndex + 1;
}
// omitted Domain attribute means that the cookie should be returned only to origin
boolean exactDomain = false;
// We can set cookie for domain or superdomain of request origin
if (domain == null) {
domain = requestOrigin;
exactDomain = true;
} else if (!isSubdomain(requestOrigin, domain)) {
log.trace("Refusing to store cookie for domain {}, origin is {}", domain, requestOrigin);
return;
}
int requestPathLastSlashIndex = HttpUtil.lastIndexOf(requestPath, requestPath.length(), '/');
if (path == null) {
path = requestPath.subSequence(0, requestPathLastSlashIndex + 1);
} else if (!isSubpath(requestPath, requestPathLastSlashIndex + 1, path, path.length())) {
log.trace("Refusing to store cookie for path {}, origin is {}", path, requestPath);
return;
}
long now = System.currentTimeMillis();
if (maxAge != Long.MAX_VALUE) {
expires = now + maxAge * 1000;
}
for (int i = 0; i < cookies.length; ++i) {
if (cookies[i].name == null || cookies[i].name.length() == 0 || (AsciiString.contentEquals(cookies[i].name, name) &&
AsciiString.contentEquals(cookies[i].domain, domain) &&
AsciiString.contentEquals(cookies[i].path, path))) {
if (nameValue.length() == valueEnd + 1 || expires <= now) {
cookies[i].name = ""; // invalidate this entry as it's expired
} else {
cookies[i].name = name;
cookies[i].nameValue = nameValue;
cookies[i].domain = domain;
cookies[i].exactDomain = exactDomain;
cookies[i].path = path;
cookies[i].secure = secure;
cookies[i].expires = expires;
}
return;
}
}
log.error("Exceeded number of cookies, dropping: {}", seq);
}
private static boolean isSubpath(CharSequence subpath, int subpathLength, CharSequence path, int pathLength) {
// example: subpath = /foo/bar, path = /foo -> true
if (pathLength > subpathLength) {
return false;
}
return AsciiString.regionMatches(subpath, false, 0, path, 0, pathLength);
}
private static boolean isSubdomain(CharSequence subdomain, CharSequence domain) {
if (subdomain.length() < domain.length()) {
return false;
}
return AsciiString.regionMatches(subdomain, false, subdomain.length() - domain.length(), domain, 0, domain.length());
}
private static boolean matchPrefix(CharSequence prefix, CharSequence seq, int begin) {
int maxLength = prefix.length();
if (maxLength > seq.length() - begin) {
return false;
}
for (int i = 0; i < maxLength; ++i) {
if (prefix.charAt(i) != Character.toLowerCase(seq.charAt(begin + i))) {
return false;
}
}
return true;
}
public void appendCookies(HttpRequestWriter requestWriter) {
CharSequence domain = requestWriter.connection().host();
CharSequence path = requestWriter.request().path;
long now = System.currentTimeMillis();
for (int i = 0; i < cookies.length; ++i) {
Cookie c = cookies[i];
if (c.name == null) {
break;
} else if (c.name.length() == 0) {
// continue
} else if (((!c.exactDomain && isSubdomain(domain, c.domain)) || AsciiString.contentEquals(domain, c.domain)) &&
isSubpath(path, path.length(), c.path, c.path.length()) &&
(!c.secure || requestWriter.connection().isSecure())) {
if (now >= c.expires) {
c.name = "";
} else {
requestWriter.putHeader(HttpHeaderNames.COOKIE, c.nameValue);
}
}
}
}
static class Cookie {
CharSequence name;
CharSequence nameValue;
CharSequence domain;
boolean exactDomain;
CharSequence path;
long expires;
boolean secure;
public void clear() {
name = null;
nameValue = null;
domain = null;
exactDomain = false;
path = null;
expires = 0;
secure = false;
}
}
private enum Attribute {
EXPIRES("expires="),
MAX_AGE("max-age="),
DOMAIN("domain="),
PATH("path="),
SECURE("secure"),
HTTPONLY("httponly"),
EXTENSION("");
final CharSequence text;
Attribute(CharSequence text) {
this.text = text;
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/cookie/CookieRecorder.java | http/src/main/java/io/hyperfoil/http/cookie/CookieRecorder.java | package io.hyperfoil.http.cookie;
import io.hyperfoil.api.session.ResourceUtilizer;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.http.api.HeaderHandler;
import io.hyperfoil.http.api.HttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
public class CookieRecorder implements HeaderHandler, ResourceUtilizer {
@Override
public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) {
if (HttpHeaderNames.SET_COOKIE.regionMatches(true, 0, header, 0,
Math.min(header.length(), HttpHeaderNames.SET_COOKIE.length()))) {
CookieStore cookies = request.session.getResource(CookieStore.COOKIES);
cookies.setCookie(request.connection().host(), request.path, value);
}
}
@Override
public void reserve(Session session) {
if (session.getResource(CookieStore.COOKIES) == null) {
session.declareResource(CookieStore.COOKIES, CookieStore::new, true);
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/cookie/CookieAppender.java | http/src/main/java/io/hyperfoil/http/cookie/CookieAppender.java | package io.hyperfoil.http.cookie;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.function.SerializableBiConsumer;
import io.hyperfoil.http.api.HttpRequestWriter;
public class CookieAppender implements SerializableBiConsumer<Session, HttpRequestWriter> {
private static final Logger log = LogManager.getLogger(CookieAppender.class);
@Override
public void accept(Session session, HttpRequestWriter writer) {
CookieStore cookies = session.getResource(CookieStore.COOKIES);
if (cookies == null) {
log.error("No cookie store in the session. Did you add CookieRecorder?");
return;
}
cookies.appendCookies(writer);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/ConnectionPoolStats.java | http/src/main/java/io/hyperfoil/http/connection/ConnectionPoolStats.java | package io.hyperfoil.http.connection;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.hyperfoil.core.impl.ConnectionStatsConsumer;
import io.hyperfoil.core.util.Watermarks;
import io.hyperfoil.http.api.HttpConnection;
class ConnectionPoolStats {
private static final Logger log = LogManager.getLogger(ConnectionPoolStats.class);
protected final String authority;
protected final Watermarks usedConnections = new Watermarks();
protected final Watermarks inFlight = new Watermarks();
protected final Watermarks blockedSessions = new Watermarks();
protected final Map<String, Watermarks> typeStats = new HashMap<>();
ConnectionPoolStats(String authority) {
this.authority = authority;
}
public void incrementInFlight() {
inFlight.incrementUsed();
}
public void decrementInFlight() {
inFlight.decrementUsed();
}
public void visitConnectionStats(ConnectionStatsConsumer consumer) {
consumer.accept(authority, "in-flight requests", inFlight.minUsed(), inFlight.maxUsed());
inFlight.resetStats();
consumer.accept(authority, "used connections", usedConnections.minUsed(), usedConnections.maxUsed());
usedConnections.resetStats();
consumer.accept(authority, "blocked sessions", blockedSessions.minUsed(), blockedSessions.maxUsed());
blockedSessions.resetStats();
for (var entry : typeStats.entrySet()) {
int min = entry.getValue().minUsed();
int max = entry.getValue().maxUsed();
entry.getValue().resetStats();
consumer.accept(authority, entry.getKey(), min, max);
}
}
protected String tagConnection(HttpConnection connection) {
switch (connection.version()) {
case HTTP_1_0:
case HTTP_1_1:
return connection.isSecure() ? "TLS + HTTP 1.x" : "HTTP 1.x";
case HTTP_2_0:
return connection.isSecure() ? "TLS + HTTP 2" : "HTTP 2";
}
return "unknown";
}
protected void incrementTypeStats(HttpConnection conn) {
typeStats.computeIfAbsent(tagConnection(conn), t -> new Watermarks()).incrementUsed();
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/HttpChannelInitializer.java | http/src/main/java/io/hyperfoil/http/connection/HttpChannelInitializer.java | package io.hyperfoil.http.connection;
import java.io.IOException;
import java.util.function.BiConsumer;
import io.hyperfoil.http.api.HttpConnection;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpClientUpgradeHandler;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.DefaultHttp2Connection;
import io.netty.handler.codec.http2.Http2ClientUpgradeCodec;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslMasterKeyHandler;
import io.netty.util.internal.SystemPropertyUtil;
class HttpChannelInitializer extends ChannelInitializer<Channel> {
private final HttpClientPoolImpl clientPool;
private final BiConsumer<HttpConnection, Throwable> handler;
private final Http2ConnectionHandlerBuilder http2ConnectionHandlerBuilder;
private final ApplicationProtocolNegotiationHandler alpnHandler = new ApplicationProtocolNegotiationHandler(
ApplicationProtocolNames.HTTP_1_1) {
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
ChannelPipeline p = ctx.pipeline();
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
io.netty.handler.codec.http2.Http2Connection connection = new DefaultHttp2Connection(false);
CustomHttp2ConnectionHandler clientHandler = http2ConnectionHandlerBuilder.build(connection);
p.addLast(clientHandler);
} else if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
initHttp1xConnection(p);
} else {
ctx.close();
throw new IllegalStateException("unknown protocol: " + protocol);
}
}
@Override
protected void handshakeFailure(ChannelHandlerContext ctx, Throwable cause) throws Exception {
handler.accept(null, new IOException("TLS handshake failure", cause));
ctx.close();
}
};
HttpChannelInitializer(HttpClientPoolImpl clientPool, BiConsumer<HttpConnection, Throwable> handler) {
this.clientPool = clientPool;
this.handler = handler;
this.http2ConnectionHandlerBuilder = new Http2ConnectionHandlerBuilder(clientPool, clientPool.sslContext == null,
handler);
}
@Override
protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (clientPool.sslContext != null) {
boolean logMasterKey = SystemPropertyUtil.getBoolean(SslMasterKeyHandler.SYSTEM_PROP_KEY, false);
SslHandler sslHandler = clientPool.sslContext.newHandler(ch.alloc(), clientPool.host, clientPool.port);
if (logMasterKey) {
// the handler works only with TLSv1.2: https://github.com/netty/netty/issues/10957
sslHandler.engine().setEnabledProtocols(new String[] { "TLSv1.2" });
}
long sslHandshakeTimeout = clientPool.config().sslHandshakeTimeout();
sslHandler.setHandshakeTimeoutMillis(sslHandshakeTimeout < 0 ? 0 : sslHandshakeTimeout);
sslHandler.handshakeFuture().addListener(future -> {
if (!future.isSuccess()) {
handler.accept(null, new IOException("SSL handshake failure", future.cause()));
}
});
pipeline.addLast(sslHandler);
pipeline.addLast(alpnHandler);
if (logMasterKey) {
pipeline.addLast(SslMasterKeyHandler.newWireSharkSslMasterKeyHandler());
}
} else if (clientPool.forceH2c) {
io.netty.handler.codec.http2.Http2Connection connection = new DefaultHttp2Connection(false);
CustomHttp2ConnectionHandler clientHandler = http2ConnectionHandlerBuilder.build(connection);
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(clientHandler);
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ChannelHandler upgradeRequestHandler = new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
DefaultFullHttpRequest upgradeRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
upgradeRequest.headers().add(HttpHeaderNames.HOST, clientPool.config().originalDestination());
ctx.writeAndFlush(upgradeRequest);
ctx.fireChannelActive();
ctx.pipeline().remove(this);
}
};
pipeline.addLast(sourceCodec,
upgradeHandler,
upgradeRequestHandler);
} else {
initHttp1xConnection(pipeline);
}
}
private void initHttp1xConnection(ChannelPipeline pipeline) {
Http1xConnection connection = new Http1xConnection(clientPool, handler);
if (clientPool.http.rawBytesHandlers()) {
pipeline.addLast(new Http1xResponseHandler(connection));
pipeline.addLast(new RawRequestHandler(connection));
}
pipeline.addLast("handler", connection);
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/ConnectionReceiver.java | http/src/main/java/io/hyperfoil/http/connection/ConnectionReceiver.java | package io.hyperfoil.http.connection;
import java.util.function.BiConsumer;
import io.hyperfoil.http.api.HttpConnection;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public interface ConnectionReceiver extends BiConsumer<HttpConnection, Throwable>, GenericFutureListener<Future<Void>> {
@Override
default void operationComplete(Future<Void> future) {
if (!future.isSuccess()) {
accept(null, future.cause());
}
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Hyperfoil/Hyperfoil | https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/BaseResponseHandler.java | http/src/main/java/io/hyperfoil/http/connection/BaseResponseHandler.java | package io.hyperfoil.http.connection;
import io.hyperfoil.http.api.HttpConnection;
import io.hyperfoil.http.api.HttpRequest;
import io.hyperfoil.http.api.HttpResponseHandlers;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public abstract class BaseResponseHandler extends ChannelInboundHandlerAdapter {
protected final HttpConnection connection;
protected int responseBytes = 0;
public BaseResponseHandler(HttpConnection connection) {
this.connection = connection;
}
protected boolean handleBuffer(ChannelHandlerContext ctx, ByteBuf buf, int streamId) throws Exception {
HttpRequest request = null;
if (isRequestStream(streamId)) {
request = connection.peekRequest(streamId);
}
if (buf.readableBytes() > responseBytes) {
ByteBuf slice = buf.readRetainedSlice(responseBytes);
onRawData(request, slice, true);
onCompletion(request);
onData(ctx, slice);
responseBytes = 0;
return true;
} else {
boolean isLastPart = buf.readableBytes() == responseBytes;
if (request != null) {
onRawData(request, buf, isLastPart);
}
responseBytes -= buf.readableBytes();
if (isLastPart && request != null) {
onCompletion(request);
}
onData(ctx, buf);
return false;
}
}
protected abstract boolean isRequestStream(int streamId);
protected void onRawData(HttpRequest request, ByteBuf data, boolean isLastPart) {
// When the request times out it is marked as completed and handlers are removed
// but the connection is not closed automatically.
if (request != null && !request.isCompleted()) {
int readerIndex = data.readerIndex();
HttpResponseHandlers handlers = request.handlers();
request.enter();
try {
handlers.handleRawResponse(request, data, data.readerIndex(), data.readableBytes(), isLastPart);
} finally {
request.exit();
}
request.session.proceed();
if (data.readerIndex() != readerIndex) {
// TODO: maybe we could just reset the reader index?
throw new IllegalStateException("Handler has changed readerIndex on the buffer!");
}
}
}
protected void onData(ChannelHandlerContext ctx, ByteBuf buf) {
ctx.fireChannelRead(buf);
}
protected void onStatus(int status) {
}
protected void onHeaderRead(ByteBuf buf, int startOfName, int endOfName, int startOfValue, int endOfValue) {
}
protected void onBodyPart(ByteBuf buf, int startOffset, int length, boolean isLastPart) {
}
protected void onCompletion(HttpRequest request) {
}
}
| java | Apache-2.0 | 70ad9cad7ba105e88d7c62e7b65892ecd288f034 | 2026-01-05T02:38:03.557103Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.